Sync source edition with VCC Plus 3.7.0 build 63

This commit is contained in:
Brian Holman committed 2026-11-14 01:43:46 -07:00
1 parent c652a5276d
commit b2ecec4d87
86 files changed
+10519 -472

No files matched your search

+290 -5
View File
@@ -100,33 +100,157 @@ struct ManualLibraryContent {
}
}
private final class ManualContinuityBridge: NSObject, WKScriptMessageHandler {
weak var reader: ManualReader?
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
guard message.frameInfo.isMainFrame else { return }
Task { @MainActor [weak self] in self?.reader?.receivedPosition(message.body) }
}
}
@MainActor
final class ManualReader: NSObject, ObservableObject, WKNavigationDelegate {
let webView: WKWebView
let content: ManualLibraryContent?
lazy var pageFind = ManualPageFind(webView: webView)
private var searchNavigation: WKNavigation?
let continuity: LibraryContinuityStore?
private let scrollBridge = ManualContinuityBridge()
private var restorePosition: LibraryReadingPosition?
private var navigationRevision = 0
@Published private(set) var currentBookID: String?
@Published private(set) var currentBookTitle = ""
@Published private(set) var currentSectionTitle = ""
@Published private(set) var currentPosition: LibraryReadingPosition?
@Published private(set) var bookmarkMessage: String?
@Published private var changedBookmarkIDs: Set<UUID> = []
private var restoringBookmarkID: UUID?
var openExample: ((String) -> Void)?
@Published private(set) var canGoBack = false
@Published private(set) var canGoForward = false
@Published private(set) var error: String?
init(content: ManualLibraryContent? = .bundled) {
init(content: ManualLibraryContent? = .bundled, continuity: LibraryContinuityStore? = nil) {
self.content = content
self.continuity = continuity ?? (content?.root == ManualLibraryContent.bundled?.root ? .shared : nil)
let configuration = WKWebViewConfiguration()
configuration.websiteDataStore = .nonPersistent()
webView = WKWebView(frame: .zero, configuration: configuration)
super.init()
scrollBridge.reader = self
webView.configuration.userContentController.add(scrollBridge, name: "libraryPosition")
webView.configuration.userContentController.addUserScript(WKUserScript(source: Self.positionScript, injectionTime: .atDocumentEnd, forMainFrameOnly: true))
webView.navigationDelegate = self
webView.allowsBackForwardNavigationGestures = true
webView.publisher(for: \.canGoBack).receive(on: RunLoop.main).assign(to: &$canGoBack)
webView.publisher(for: \.canGoForward).receive(on: RunLoop.main).assign(to: &$canGoForward)
}
func showHome() {
loadPage(content?.home)
func showHome() { loadPage(content?.home) }
func resume() {
guard webView.url == nil else { return }
if let position = continuity?.reading(for: "manual-last"), let path = position.relativePath,
let content, content.relativePath(for: content.root.appendingPathComponent(path)) != nil {
loadPage(content.root.appendingPathComponent(path), restore: position)
} else { showHome() }
}
var hasCurrentBookmark: Bool {
guard let book = currentBookID, let position = currentPosition else { return false }
return continuity?.bookmarks.contains {
$0.bookID == book && $0.position.relativePath == position.relativePath && $0.position.anchor == position.anchor
&& (position.anchor != nil || Int($0.position.offset * 10_000) == Int(position.offset * 10_000))
} == true
}
func bookmarkCurrentLocation() {
guard continuity != nil, !webView.isLoading, let url = webView.url else { return }
let revision = navigationRevision
// The periodic scroll checkpoint deliberately runs infrequently. A
// deliberate bookmark must ask the loaded page for its location now.
Task { [weak self] in
guard let self else { return }
do {
let value = try await webView.evaluateJavaScript("window.vccLibraryCheckpoint?.()")
guard navigationRevision == revision, webView.url == url, !webView.isLoading,
let object = value as? [String: Any], object["href"] as? String == url.absoluteString else { return }
receivedPosition(object)
guard let book = currentBookID, let position = currentPosition else { return }
let existing = hasCurrentBookmark
_ = continuity?.addBookmark(bookID: book, bookTitle: currentBookTitle, sectionTitle: currentSectionTitle, position: position)
bookmarkMessage = existing ? "This location is already bookmarked." : "Bookmark saved."
} catch {
guard navigationRevision == revision, webView.url == url else { return }
bookmarkMessage = "This location could not be bookmarked. Try again after the page finishes loading."
}
}
}
func openBookmark(_ bookmark: ManualBookmark, fromBookStart: Bool = false) {
guard let content else { return }
let home = bookmark.bookID.hasPrefix("toolchain-reference:") ? "toolchain-reference/index.html" : bookmark.bookID + "/template.html"
let path = fromBookStart ? home : bookmark.position.relativePath ?? ""
let url = content.root.appendingPathComponent(path)
guard content.relativePath(for: url) != nil else {
error = "This bookmark's page is no longer in the bundled book. The bookmark has been preserved."
return
}
loadPage(url, restore: fromBookStart ? nil : bookmark.position)
restoringBookmarkID = fromBookStart ? nil : bookmark.id
}
func bookmarkAvailable(_ bookmark: ManualBookmark) -> Bool {
guard let content, let path = bookmark.position.relativePath else { return false }
return bookmark.locationChanged != true && !changedBookmarkIDs.contains(bookmark.id) && content.relativePath(for: content.root.appendingPathComponent(path)) != nil
}
func checkpoint() {
webView.evaluateJavaScript("window.vccLibraryCheckpoint?.()", completionHandler: nil)
continuity?.checkpoint()
}
fileprivate func receivedPosition(_ value: Any) {
guard let object = value as? [String: Any], let href = object["href"] as? String,
let url = URL(string: href), let path = content?.relativePath(for: url),
path == webView.url.flatMap({ content?.relativePath(for: $0) }),
url.pathExtension.lowercased() == "html" else { return }
let parts = path.split(separator: "/")
let bookID: String? = parts.count > 1 ? (parts[0] == "toolchain-reference" ? "toolchain-reference:" + String(parts[1]) : String(parts[0])) : nil
let anchor = (object["anchor"] as? String).flatMap { $0.isEmpty ? nil : $0 }
let position = LibraryReadingPosition(documentID: bookID ?? "manual-home", relativePath: path,
anchor: anchor, offset: min(1, max(0, (object["offset"] as? Double) ?? 0)), readingOrder: object["order"] as? Int)
currentBookID = bookID
currentBookTitle = object["bookTitle"] as? String ?? "Manual Library"
currentSectionTitle = object["sectionTitle"] as? String ?? currentBookTitle
currentPosition = position
continuity?.setReading(position, for: "manual-last")
continuity?.setReading(position, for: "manual-page:" + path)
if let bookID { continuity?.setReading(position, for: "manual-book:" + bookID) }
}
private static let positionScript = #"""
(() => {
let timer;
const sections = () => Array.from(document.querySelectorAll('article section[id],article h2[id],article h3[id]'));
window.vccLibraryCheckpoint = () => {
const y = window.scrollY, candidates = sections();
let target = null;
for (const item of candidates) { if (item.getBoundingClientRect().top + y <= y + 12) target = item; }
const start = target ? target.getBoundingClientRect().top + y : 0;
const index = candidates.indexOf(target);
const next = target ? candidates[index + 1] : null;
const end = next ? next.getBoundingClientRect().top + y : document.documentElement.scrollHeight;
const title = target?.querySelector('h2,h3,h4')?.textContent || target?.textContent || document.querySelector('h1')?.textContent || document.title;
const crumb = document.querySelector('.crumb a:nth-child(2)')?.textContent;
const bookTitle = location.pathname.includes('/toolchain-reference/') ? (document.querySelector('h1')?.textContent || document.title) : (crumb || document.title);
const chapters = Array.from(document.querySelectorAll('.toc ol > li > a'));
const chapter = chapters.findIndex(link => new URL(link.href).pathname === location.pathname);
const position = {href: location.href, anchor: target?.id || '', offset: Math.min(1, Math.max(0, (y-start)/Math.max(1,end-start))), bookTitle, sectionTitle:title.slice(0,1024),order:Math.max(0,chapter)*10000+Math.max(0,index)};
window.webkit.messageHandlers.libraryPosition.postMessage(position);
return position;
};
window.addEventListener('scroll', () => { if (!timer) timer=setTimeout(() => { timer=null; window.vccLibraryCheckpoint(); },1000); }, {passive:true});
window.addEventListener('pagehide', window.vccLibraryCheckpoint);
})();
"""#
func showLibrarySearch() {
pageFind.close()
if let url = webView.url, content?.relativePath(for: url) == "index.html", !webView.isLoading {
@@ -151,11 +275,16 @@ final class ManualReader: NSObject, ObservableObject, WKNavigationDelegate {
}
@discardableResult
private func loadPage(_ url: URL?) -> WKNavigation? {
private func loadPage(_ url: URL?, restore: LibraryReadingPosition? = nil) -> WKNavigation? {
guard let content, let url, content.relativePath(for: url) != nil else {
error = "This page is missing from the bundled Manual Library."
return nil
}
checkpoint()
navigationRevision += 1
restorePosition = restore
restoringBookmarkID = nil
currentPosition = nil
error = nil
return webView.loadFileURL(url, allowingReadAccessTo: content.root)
}
@@ -192,6 +321,21 @@ final class ManualReader: NSObject, ObservableObject, WKNavigationDelegate {
}
return
}
if action.navigationType == .linkActivated {
navigationRevision += 1
restorePosition = nil
if url.fragment == nil || url.fragment?.isEmpty == true {
if url.lastPathComponent == "template.html", let book = path.split(separator: "/").first,
let saved = continuity?.reading(for: "manual-book:" + String(book)),
let savedPath = saved.relativePath, savedPath != path,
let content, content.relativePath(for: content.root.appendingPathComponent(savedPath)) != nil {
decisionHandler(.cancel)
loadPage(content.root.appendingPathComponent(savedPath), restore: saved)
return
}
restorePosition = continuity?.reading(for: "manual-page:" + path)
}
}
decisionHandler(.allow)
return
}
@@ -211,6 +355,42 @@ final class ManualReader: NSObject, ObservableObject, WKNavigationDelegate {
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
error = nil
let saved = restorePosition
let restoredBookmark = restoringBookmarkID
restorePosition = nil
restoringBookmarkID = nil
let revision = navigationRevision
if let saved, saved.relativePath == webView.url.flatMap({ content?.relativePath(for: $0) }) {
let argument = ["anchor": saved.anchor ?? "", "offset": saved.offset, "href": webView.url?.absoluteString ?? ""] as [String: Any]
if let data = try? JSONSerialization.data(withJSONObject: argument), let json = String(data: data, encoding: .utf8) {
webView.evaluateJavaScript("""
(() => {
const p = \(json);
if (location.href !== p.href) return null;
const target = p.anchor ? document.getElementById(p.anchor) : null;
if (p.anchor && !target) return false;
const y = target ? target.getBoundingClientRect().top + window.scrollY : 0;
const candidates = Array.from(document.querySelectorAll('article section[id],article h2[id],article h3[id]'));
const next = target ? candidates[candidates.indexOf(target)+1] : null;
const end = next ? next.getBoundingClientRect().top + window.scrollY : document.documentElement.scrollHeight;
window.scrollTo(0,y + Math.max(0,end-y)*p.offset);
window.vccLibraryCheckpoint?.(); return true;
})();
""") { [weak self] result, _ in
guard let self, self.navigationRevision == revision else { return }
if (result as? Bool) == false {
if let restoredBookmark {
self.changedBookmarkIDs.insert(restoredBookmark)
self.continuity?.markBookmarkLocationChanged(restoredBookmark, changed: true)
}
self.error = "Location changed. This saved section is no longer available; the page and bookmark have been preserved."
} else if let restoredBookmark {
self.changedBookmarkIDs.remove(restoredBookmark)
self.continuity?.markBookmarkLocationChanged(restoredBookmark, changed: false)
}
}
}
} else { webView.evaluateJavaScript("window.vccLibraryCheckpoint?.()", completionHandler: nil) }
if let searchNavigation, navigation === searchNavigation {
self.searchNavigation = nil
focusLibrarySearch()
@@ -248,6 +428,7 @@ private struct ManualWebPage: NSViewRepresentable {
struct ManualLibraryView: View {
@Environment(\.openWindow) private var openWindow
@ObservedObject var reader: ManualReader
@State private var showsBookmarks = false
var body: some View {
VStack(spacing: 0) {
@@ -264,6 +445,23 @@ struct ManualLibraryView: View {
.focusedSceneValue(\.manualPageFind, reader.pageFind)
.toolbar {
ToolbarItemGroup(placement: .primaryAction) {
Button {
let exists = reader.hasCurrentBookmark
reader.bookmarkCurrentLocation()
if exists { showsBookmarks = true }
} label: { Image(systemName: reader.hasCurrentBookmark ? "bookmark.fill" : "bookmark") }
.disabled(reader.currentBookID == nil || reader.currentPosition == nil || reader.continuity == nil)
.help("Bookmark this location").accessibilityLabel("Bookmark this location")
.accessibilityIdentifier("manual.bookmark-location")
Button { showsBookmarks.toggle() } label: { Image(systemName: "list.bullet") }
.help("Bookmarks").accessibilityLabel("Bookmarks")
.accessibilityIdentifier("manual.bookmarks")
.popover(isPresented: $showsBookmarks) {
if let continuity = reader.continuity {
ManualBookmarksPopover(reader: reader, continuity: continuity) { showsBookmarks = false }
} else { Text("Bookmarks are unavailable in this reader.").padding() }
}
Button("Find on This Page", systemImage: "magnifyingglass") { reader.pageFind.show() }
.help("Find on this page (⌘F)").accessibilityIdentifier("manual.find")
@@ -288,7 +486,94 @@ struct ManualLibraryView: View {
}
.frame(minWidth: 420, minHeight: 340)
.onAppear {
if reader.error == nil && reader.webView.url == nil && !reader.webView.isLoading { reader.showHome() }
if reader.error == nil && reader.webView.url == nil && !reader.webView.isLoading { reader.resume() }
}
.onDisappear { reader.checkpoint() }
.onReceive(NotificationCenter.default.publisher(for: NSApplication.willTerminateNotification)) { _ in reader.checkpoint() }
}
}
private struct ManualBookmarksPopover: View {
@ObservedObject var reader: ManualReader
@ObservedObject var continuity: LibraryContinuityStore
let close: () -> Void
@State private var filter = "all"
@State private var renameID: UUID?
@State private var renameText = ""
private var entries: [ManualBookmark] {
continuity.bookmarks.filter { filter != "book" || $0.bookID == reader.currentBookID }
.sorted {
if $0.bookID != $1.bookID { return order($0.bookID) < order($1.bookID) }
if let first = $0.position.readingOrder, let second = $1.position.readingOrder, first != second { return first < second }
let first = ($0.position.relativePath ?? "") + "#" + ($0.position.anchor ?? "")
let second = ($1.position.relativePath ?? "") + "#" + ($1.position.anchor ?? "")
return first.localizedStandardCompare(second) == .orderedAscending
}
}
private func order(_ id: String) -> String {
let books = ["meet-your-color-computer", "back-at-the-coco", "software-storage-and-peripherals", "users-handbook", "programming-in-coco-basic", "your-first-6809-programs", "assembly-language-programming", "programming-in-c", "inside-the-coco-3", "working-with-os9", "nitros9-on-vcc-plus", "vibe-coding-with-chatgpt"]
if let index = books.firstIndex(of: id) { return String(format: "%02d", index) }
return "99-" + id
}
var body: some View {
VStack(alignment: .leading, spacing: 10) {
Text("Bookmarks").font(.headline)
Picker("Bookmark scope", selection: $filter) {
Text("All Books").tag("all")
Text("This Book").tag("book").disabled(reader.currentBookID == nil)
}.pickerStyle(.segmented).accessibilityIdentifier("manual.bookmark-scope")
if let error = continuity.saveError { Text(error).font(.caption).foregroundStyle(.red) }
if entries.isEmpty {
VStack(alignment: .leading, spacing: 8) {
Label("No bookmarks", systemImage: "bookmark").font(.headline)
Text("Use Bookmark This Location while reading a manual.")
.foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)
}
.frame(maxWidth: .infinity, alignment: .leading)
.padding(.top, 12)
Spacer(minLength: 0)
} else {
List {
ForEach(Array(Set(entries.map(\.bookID))).sorted(by: { order($0) < order($1) }), id: \.self) { book in
Section(entries.first { $0.bookID == book }?.bookTitle ?? book) {
ForEach(entries.filter { $0.bookID == book }) { item in
HStack {
Button {
reader.openBookmark(item); close()
} label: {
VStack(alignment: .leading) {
Text(item.displayName).lineLimit(2)
Text(reader.bookmarkAvailable(item) ? item.sectionTitle : "Location changed — page unavailable")
.font(.caption).foregroundStyle(.secondary).lineLimit(2)
}.frame(maxWidth: .infinity, alignment: .leading)
}.buttonStyle(.plain)
.accessibilityIdentifier("manual.bookmark-open-" + item.id.uuidString)
Menu {
Button("Open") { reader.openBookmark(item); close() }
Button("Open Book") { reader.openBookmark(item, fromBookStart: true); close() }
Button("Rename…") { renameText = item.label ?? item.sectionTitle; renameID = item.id }
Button("Remove Bookmark", role: .destructive) { continuity.removeBookmark(item.id) }
} label: { Image(systemName: "ellipsis.circle") }
.menuStyle(.borderlessButton).fixedSize().accessibilityLabel("Bookmark actions for " + item.displayName)
.accessibilityIdentifier("manual.bookmark-actions-" + item.id.uuidString)
}
}
}
}
}.listStyle(.inset)
}
}.padding(12).frame(width: 400, height: 420, alignment: .topLeading)
.onAppear {
filter = continuity.browse(for: "manual-bookmark-ui")?.filters["scope"] ?? (reader.currentBookID == nil ? "all" : "book")
if reader.currentBookID == nil { filter = "all" }
}
.onChange(of: filter) { _, value in var state = LibraryBrowseState(); state.filters["scope"] = value; continuity.setBrowse(state, for: "manual-bookmark-ui") }
.onChange(of: reader.currentBookID) { _, value in if value == nil { filter = "all" } }
.alert("Rename Bookmark", isPresented: Binding(get: { renameID != nil }, set: { if !$0 { renameID = nil } })) {
TextField("Bookmark name", text: $renameText)
Button("Cancel", role: .cancel) { renameID = nil }
Button("Save") { if let renameID { continuity.renameBookmark(renameID, label: renameText) }; renameID = nil }
}
}
}