Files
VCCPlusOSS/platforms/macos/App/BASICReferenceView.swift
T

264 lines
14 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// SPDX-License-Identifier: GPL-3.0-or-later
import AppKit
import SwiftUI
/// A deliberate lookup changes the selected topic. The editor never drives this
/// model continuously, so a reference stays put while the user reads and types.
@MainActor
final class BASICReferenceModel: ObservableObject {
let catalog: BASICReferenceCatalog
@Published var selectedID: String?
@Published var search = "" { didSet { reconcileSelection() } }
@Published var category: String? { didSet { reconcileSelection() } }
init(catalog: BASICReferenceCatalog) {
self.catalog = catalog
selectedID = catalog.entries.first(where: { $0.id == "PRINT" })?.id ?? catalog.entries.first?.id
}
var categories: [String] { Set(catalog.entries.map(\.category)).sorted() }
var filteredEntries: [BASICReferenceEntry] {
let terms = search.split(whereSeparator: \.isWhitespace).map(String.init)
return catalog.entries.filter { entry in
guard category == nil || category == entry.category else { return false }
let searchable = [entry.title, entry.keyword, entry.summary, entry.category, entry.dialect.displayName].joined(separator: " ")
return terms.allSatisfy { searchable.localizedCaseInsensitiveContains($0) }
}.sorted {
let comparison = $0.title.localizedStandardCompare($1.title)
return comparison == .orderedSame ? $0.id < $1.id : comparison == .orderedAscending
}
}
var selectedEntry: BASICReferenceEntry? { entry(id: selectedID) }
func entry(id: String?) -> BASICReferenceEntry? {
guard let id else { return nil }
return catalog.entries.first { $0.id == id }
}
func example(for entry: BASICReferenceEntry) -> BASICReferenceExample? {
guard let id = entry.exampleID else { return nil }
return catalog.examples.first { $0.id == id }
}
func relatedEntry(_ identifier: String) -> BASICReferenceEntry? {
entry(id: identifier) ?? catalog.entries.first { $0.keyword.caseInsensitiveCompare(identifier) == .orderedSame }
}
func select(_ entry: BASICReferenceEntry) {
search = ""; category = nil; selectedID = entry.id
}
func show(keyword: String, dialect: BASICReferenceDialect? = nil) {
let key = keyword.trimmingCharacters(in: .whitespacesAndNewlines).uppercased()
let candidates = catalog.entries.filter { $0.keyword.uppercased() == key || $0.id.uppercased() == key }
let match = candidates.first { $0.dialect == dialect }
?? candidates.first { $0.dialect == .common }
?? candidates.first { $0.dialect == .disk }
?? candidates.first
if let match { select(match) }
else { category = nil; search = key }
}
func showError(code: String) {
let key = code.trimmingCharacters(in: .whitespacesAndNewlines).uppercased()
if let match = entry(id: "ERROR." + key) { select(match) }
else { show(keyword: key) }
}
private func reconcileSelection() {
let entries = filteredEntries
if !entries.contains(where: { $0.id == selectedID }) { selectedID = entries.first?.id }
}
}
struct BASICReferenceView: View {
@ObservedObject var model: BASICReferenceModel
let activeDialect: BASICReferenceDialect?
let openManualTopic: (BASICReferenceEntry) -> Void
let openExample: (BASICReferenceExample) -> Void
@FocusState private var searchFocused: Bool
var body: some View {
VStack(spacing: 0) {
HStack(spacing: 12) {
Image(systemName: "book.closed").font(.largeTitle).foregroundStyle(.tint)
VStack(alignment: .leading, spacing: 3) {
Text("BASIC Quick Reference").font(.title2.bold())
Text("Commands, examples and help for your CoCo").font(.callout).foregroundStyle(.secondary)
}
Spacer(minLength: 12)
if let activeDialect {
Label(activeDialect.displayName, systemImage: "desktopcomputer")
.font(.caption).foregroundStyle(.secondary)
.accessibilityIdentifier("basic.reference.active-dialect")
}
}.padding(16)
Divider()
HSplitView {
navigation.frame(minWidth: 210, idealWidth: 250, maxWidth: 330)
Group {
if let entry = model.selectedEntry {
ScrollView {
entryDetail(entry).padding(22).frame(maxWidth: .infinity, alignment: .leading)
}.id(entry.id).accessibilityIdentifier("basic.reference.detail")
} else {
ContentUnavailableView {
Label(model.catalog.entries.isEmpty ? "Reference unavailable" : "No matching commands", systemImage: "magnifyingglass")
} description: {
Text(model.catalog.entries.isEmpty ? "The local reference could not be loaded." : "Try a command name or choose a different category.")
} actions: {
if !model.catalog.entries.isEmpty {
Button("Clear Filters") { model.search = ""; model.category = nil }
}
}
}
}.frame(minWidth: 460, maxWidth: .infinity, maxHeight: .infinity)
}
Divider()
HStack(spacing: 6) {
Image(systemName: "internaldrive")
Text("Available offline")
Spacer()
Text("Examples open in the editor. Run them when you’re ready.")
}.font(.caption).foregroundStyle(.secondary).padding(.horizontal, 14).padding(.vertical, 9)
}.frame(minWidth: 780, minHeight: 540)
.background {
Button("Find in BASIC Reference") { searchFocused = true }
.keyboardShortcut("f", modifiers: .command).hidden().accessibilityHidden(true)
}
}
private var navigation: some View {
VStack(alignment: .leading, spacing: 10) {
HStack(spacing: 6) {
Image(systemName: "magnifyingglass").foregroundStyle(.secondary)
TextField("Find a command", text: $model.search)
.textFieldStyle(.plain).focused($searchFocused)
.accessibilityLabel("Search BASIC reference").accessibilityIdentifier("basic.reference.search")
if !model.search.isEmpty {
Button { model.search = "" } label: { Image(systemName: "xmark.circle.fill") }
.buttonStyle(.plain).foregroundStyle(.secondary).help("Clear reference search").accessibilityLabel("Clear reference search")
}
}.padding(8).background(.quaternary.opacity(0.5), in: RoundedRectangle(cornerRadius: 7))
.padding(.horizontal, 12).padding(.top, 12)
Picker("Category", selection: $model.category) {
Text("All Topics").tag(String?.none)
ForEach(model.categories, id: \.self) { Text($0).tag(Optional($0)) }
}.padding(.horizontal, 12).accessibilityIdentifier("basic.reference.category")
List(selection: $model.selectedID) {
ForEach(model.filteredEntries) { entry in
HStack(alignment: .top, spacing: 9) {
Image(systemName: symbol(for: entry)).foregroundStyle(.secondary).frame(width: 18)
VStack(alignment: .leading, spacing: 3) {
Text(entry.title).font(.callout.weight(.medium))
Text(entry.dialect.displayName).font(.caption).foregroundStyle(.secondary)
}
}.padding(.vertical, 3).tag(entry.id)
.accessibilityIdentifier("basic.reference.topic." + entry.id)
}
}.listStyle(.sidebar).accessibilityIdentifier("basic.reference.list")
Text("\(model.filteredEntries.count) topics").font(.caption).foregroundStyle(.secondary)
.padding(.horizontal, 14).padding(.bottom, 10)
}
}
private func entryDetail(_ entry: BASICReferenceEntry) -> some View {
VStack(alignment: .leading, spacing: 20) {
VStack(alignment: .leading, spacing: 9) {
HStack(alignment: .firstTextBaseline) {
Text(entry.title).font(.system(.title, design: .monospaced).bold())
.accessibilityIdentifier("basic.reference.title")
Spacer(minLength: 8)
}
HStack(spacing: 8) {
Label(entry.category, systemImage: symbol(for: entry))
Text("·")
Text(entry.dialect.displayName)
}.font(.caption).foregroundStyle(.secondary)
Text(entry.summary).textSelection(.enabled)
Button("Read in BASIC Manual", systemImage: "book.pages") { openManualTopic(entry) }
.accessibilityIdentifier("basic.reference.manual")
}
if !entry.syntax.isEmpty {
section("Syntax") { code(entry.syntax.joined(separator: "\n")) }
}
if !entry.parameters.isEmpty {
section("Parameters") {
VStack(alignment: .leading, spacing: 8) {
ForEach(Array(entry.parameters.enumerated()), id: \.offset) { _, parameter in
Text(parameter).font(.callout).textSelection(.enabled)
}
}
}
}
if !entry.sample.isEmpty {
section("Example syntax") { code(entry.sample) }
}
if let example = model.example(for: entry) {
VStack(alignment: .leading, spacing: 10) {
Label(example.title, systemImage: "play.rectangle").font(.headline)
Text(example.summary).font(.callout).textSelection(.enabled)
if !example.expectedOutput.isEmpty {
Text("Expected result: " + example.expectedOutput).font(.callout).foregroundStyle(.secondary)
.textSelection(.enabled)
}
Button { openExample(example) } label: { Label("Open Example", systemImage: "doc.badge.plus") }
.accessibilityIdentifier("basic.reference.example")
Text("Opens a separate program; does not run it.").font(.caption).foregroundStyle(.secondary)
}.padding(14).frame(maxWidth: .infinity, alignment: .leading)
.background(Color.accentColor.opacity(0.07), in: RoundedRectangle(cornerRadius: 9))
}
if !entry.notes.isEmpty {
section("Good to know") {
VStack(alignment: .leading, spacing: 9) {
ForEach(Array(entry.notes.enumerated()), id: \.offset) { _, note in
Text(note).font(.callout).textSelection(.enabled)
}
}
}
}
let related = entry.related.compactMap(model.relatedEntry)
if !related.isEmpty {
section("Related topics") {
VStack(alignment: .leading, spacing: 8) {
ForEach(related) { relatedEntry in
Button { model.select(relatedEntry) } label: {
Label(relatedEntry.title, systemImage: "arrow.turn.down.right")
}.buttonStyle(.link).accessibilityIdentifier("basic.reference.related." + relatedEntry.id)
}
}
}
}
Divider()
DisclosureGroup {
VStack(alignment: .leading, spacing: 7) {
Text(entry.citation).textSelection(.enabled)
Text("Historical manuals preserved by Color Computer Archive. Explanations and examples written for VCC Plus.")
.foregroundStyle(.secondary)
}.font(.caption).padding(.top, 7)
} label: {
Label("Bibliographic reference", systemImage: "books.vertical").font(.callout)
}.accessibilityIdentifier("basic.reference.attribution")
}
}
private func section<Content: View>(_ title: String, @ViewBuilder content: () -> Content) -> some View {
VStack(alignment: .leading, spacing: 9) {
Text(title).font(.headline)
content()
}.frame(maxWidth: .infinity, alignment: .leading)
}
private func code(_ text: String) -> some View {
Text(text).font(.system(.body, design: .monospaced)).textSelection(.enabled)
.fixedSize(horizontal: false, vertical: true)
.padding(12).frame(maxWidth: .infinity, alignment: .leading)
.background(.quaternary.opacity(0.4), in: RoundedRectangle(cornerRadius: 7))
}
private func symbol(for entry: BASICReferenceEntry) -> String {
let category = entry.category.lowercased()
if entry.id.hasPrefix("ERROR.") || category.contains("error") { return "exclamationmark.circle" }
if category.contains("graphic") || category.contains("display") || category.contains("screen") { return "paintpalette" }
if category.contains("sound") || category.contains("music") { return "speaker.wave.2" }
if category.contains("disk") || category.contains("file") || category.contains("storage") { return "externaldrive" }
if category.contains("cassette") { return "recordingtape" }
if category.contains("string") || category.contains("text") { return "textformat" }
if category.contains("math") || category.contains("number") { return "function" }
if category.contains("flow") || category.contains("control") { return "arrow.triangle.branch" }
if category.contains("memory") { return "memorychip" }
return "terminal"
}
}