Repository Public
1// ORIX DJ2// File: App/Sources/Features/Docs/DocsView.swift3// Description: The Docs section: offline ORIX Script documentation with a chapter sidebar, full-text search, a native4// Markdown reader with runnable examples, and previous/next navigation.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import ORIXDJCore9import SwiftUI1011struct DocsView: View {12 @Environment(AppModel.self) private var model13 @State private var store = DocsStore()14 @AppStorage("docs.textScale") private var textScale = 1.015 @FocusState private var searchFocused: Bool16 @State private var appliedLaunchOptions = false1718 private var scale: CGFloat { CGFloat(min(1.8, max(0.8, textScale))) }19 private var searching: Bool { model.docsSearch.trimmingCharacters(in: .whitespaces).count >= 2 }2021 private var currentFile: String? {22 if let f = model.docsChapter, store.chapters[f] != nil { return f }23 return store.entries.first?.file24 }2526 var body: some View {27 HStack(spacing: 0) {28 sidebar.frame(width: 288)29 Rectangle().fill(ORIX.Palette.hairline).frame(width: 1)30 reader.frame(maxWidth: .infinity, maxHeight: .infinity)31 }32 .background(ORIX.Palette.canvas)33 .background(shortcuts)34 .environment(\.openURL, OpenURLAction { url in35 guard url.scheme == MarkdownStyle.linkScheme else { return .systemAction }36 open(file: String(url.path.dropFirst()), anchor: url.fragment)37 return .handled38 })39 .task {40 await store.load()41 applyLaunchOptions()42 }43 .modifier(SettingsLaunchOption())44 .accessibilityElement(children: .contain).accessibilityIdentifier("docs-root")45 }4647 /// Keyboard shortcuts that have no visible control of their own.48 private var shortcuts: some View {49 Group {50 Button("Find in Documentation") { searchFocused = true }.keyboardShortcut("f", modifiers: .command)51 Button("Larger Text") { zoom(0.1) }.keyboardShortcut("+", modifiers: .command)52 Button("Larger Text") { zoom(0.1) }.keyboardShortcut("=", modifiers: .command)53 Button("Smaller Text") { zoom(-0.1) }.keyboardShortcut("-", modifiers: .command)54 Button("Actual Size") { textScale = 1 }.keyboardShortcut("0", modifiers: .command)55 }56 .opacity(0).frame(width: 0, height: 0).accessibilityHidden(true)57 }5859 private func zoom(_ delta: Double) { textScale = min(1.8, max(0.8, ((textScale + delta) * 10).rounded() / 10)) }6061 private func open(file: String, anchor: String? = nil, line: Int? = nil) {62 guard store.chapters[file] != nil else { model.show(notice: String(localized: "That chapter is not part of this build of the documentation.")); return }63 model.docsChapter = file64 store.target(file: file, anchor: anchor, line: line)65 }6667 private func applyLaunchOptions() {68 guard !appliedLaunchOptions else { return }69 appliedLaunchOptions = true70 let defaults = UserDefaults.standard71 if let chapter = defaults.string(forKey: "ORIXDocsChapter") {72 let file = store.chapters[chapter] != nil ? chapter : (store.chapters.keys.first { $0.hasSuffix(chapter) || $0 == chapter + ".md" } ?? chapter)73 if store.chapters[file] != nil { open(file: file) }74 }75 if let l = defaults.string(forKey: "ORIXDocsLine").flatMap(Int.init), let file = currentFile { open(file: file, line: l) }76 if let q = defaults.string(forKey: "ORIXDocsSearch"), !q.isEmpty { model.docsSearch = q }77 if let s = defaults.string(forKey: "ORIXDocsScale"), let v = Double(s) { textScale = v }78 if defaults.bool(forKey: "ORIXDocsRunFirst"), let file = currentFile, let chapter = store.chapters[file],79 let block = chapter.document.codeBlocks.first(where: { ["orixdj", "orix", "orixscript"].contains($0.language) }) {80 ScriptRunCache.shared.run(block.text)81 store.target(file: file, node: block.topLevelID)82 }83 if let file = currentFile { store.expanded.formUnion([file, store.entry(for: file)?.parent].compactMap { $0 }) }84 }8586 // MARK: Sidebar8788 private var sidebar: some View {89 VStack(spacing: 0) {90 HStack(spacing: 6) {91 Image(systemName: "magnifyingglass").font(.system(size: 12)).foregroundStyle(ORIX.Palette.textTertiary)92 TextField("Search the documentation", text: Binding(get: { model.docsSearch }, set: { model.docsSearch = $0 }))93 .textFieldStyle(.plain).font(.system(size: 12.5))94 .focused($searchFocused)95 .onExitCommand { model.docsSearch = ""; searchFocused = false }96 .accessibilityLabel("Search the documentation")97 .accessibilityIdentifier("docs-search")98 if !model.docsSearch.isEmpty {99 Button { model.docsSearch = "" } label: { Image(systemName: "xmark.circle.fill").foregroundStyle(ORIX.Palette.textTertiary) }100 .buttonStyle(.plain).accessibilityLabel("Clear search").accessibilityIdentifier("docs-search-clear")101 }102 }103 .padding(.horizontal, 10).frame(height: 30)104 .background(ORIX.Palette.well.opacity(0.7), in: RoundedRectangle(cornerRadius: ORIX.Radius.control, style: .continuous))105 .overlay(RoundedRectangle(cornerRadius: ORIX.Radius.control, style: .continuous).strokeBorder(searchFocused ? ORIX.Palette.accent : ORIX.Palette.hairline, lineWidth: 1))106 .padding(ORIX.Space.sm)107 Rectangle().fill(ORIX.Palette.hairline).frame(height: 1)108 switch store.phase {109 case .loading: ProgressView().controlSize(.small).frame(maxWidth: .infinity, maxHeight: .infinity)110 case .unavailable: Color.clear111 case .ready: if searching { searchResults } else { chapterList }112 }113 }114 .background(ORIX.Palette.surface)115 }116117 private var chapterList: some View {118 VStack(spacing: 0) {119 ScrollViewReader { proxy in120 ScrollView {121 LazyVStack(alignment: .leading, spacing: 1) {122 SectionLabel("ORIX Script \(ORIXScriptLanguage.version)").padding(.horizontal, 10).padding(.top, 10).padding(.bottom, 4)123 ForEach(store.visibleEntries) { entry in chapterRow(entry).id(entry.file) }124 }125 .padding(.horizontal, 6).padding(.bottom, 10)126 }127 .onChange(of: currentFile) { _, file in if let file { proxy.scrollTo(file) } }128 .onAppear { if let file = currentFile { proxy.scrollTo(file, anchor: .center) } }129 }130 .accessibilityIdentifier("docs-chapters")131 if !store.missingFiles.isEmpty || !store.usedManifest {132 Rectangle().fill(ORIX.Palette.hairline).frame(height: 1)133 Group {134 if !store.usedManifest { Text("No table of contents was found: the chapters are listed by file name.") }135 else { Text("\(store.missingFiles.count) chapters of the table of contents are not in this build.") }136 }137 .font(.system(size: 10.5)).foregroundStyle(ORIX.Palette.textTertiary)138 .frame(maxWidth: .infinity, alignment: .leading).padding(10)139 .accessibilityIdentifier("docs-missing-note")140 }141 }142 }143144 private func chapterRow(_ entry: DocEntry) -> some View {145 let selected = entry.file == currentFile146 return HStack(spacing: 6) {147 if let n = entry.number {148 Text(verbatim: "\(n)").font(.system(size: 10.5, weight: .semibold).monospacedDigit())149 .foregroundStyle(selected ? ORIX.Palette.accent : ORIX.Palette.textTertiary).frame(width: 20, alignment: .trailing)150 } else {151 Image(systemName: "doc.text").font(.system(size: 9.5)).foregroundStyle(ORIX.Palette.textTertiary).frame(width: 20, alignment: .trailing).padding(.leading, 14)152 }153 Text(verbatim: entry.title).font(.system(size: 12.5, weight: selected ? .semibold : .regular))154 .foregroundStyle(selected ? ORIX.Palette.textPrimary : ORIX.Palette.textSecondary).lineLimit(1)155 Spacer(minLength: 4)156 if entry.hasChildren {157 let open = store.expanded.contains(entry.file)158 Button { if open { store.expanded.remove(entry.file) } else { store.expanded.insert(entry.file) } } label: {159 Image(systemName: open ? "chevron.down" : "chevron.right").font(.system(size: 9, weight: .bold)).foregroundStyle(ORIX.Palette.textTertiary).frame(width: 20, height: 20).contentShape(Rectangle())160 }161 .buttonStyle(.plain)162 .accessibilityLabel(open ? Text("Hide the pages of \(entry.title)") : Text("Show the pages of \(entry.title)"))163 }164 }165 .padding(.horizontal, 6).frame(height: 26)166 .background(selected ? ORIX.Palette.surfaceRaised : .clear, in: RoundedRectangle(cornerRadius: ORIX.Radius.chip, style: .continuous))167 .overlay(alignment: .leading) { if selected { RoundedRectangle(cornerRadius: 1).fill(ORIX.Palette.accent).frame(width: 2.5, height: 14) } }168 .contentShape(Rectangle())169 .onTapGesture { open(file: entry.file) }170 .accessibilityElement(children: .combine)171 .accessibilityAddTraits(selected ? [.isButton, .isSelected] : .isButton)172 .accessibilityAction { open(file: entry.file) }173 .accessibilityIdentifier("docs-chapter-\(entry.file)")174 }175176 private var searchResults: some View {177 let found = store.search(model.docsSearch)178 return VStack(spacing: 0) {179 HStack {180 Text(found.total == 0 ? "No match" : "\(found.total) matches in \(found.groups.count) pages")181 .font(ORIX.Typeface.caption).foregroundStyle(ORIX.Palette.textSecondary)182 Spacer()183 }184 .padding(.horizontal, 12).frame(height: 28)185 .accessibilityIdentifier("docs-search-count")186 Rectangle().fill(ORIX.Palette.hairline).frame(height: 1)187 ScrollView {188 LazyVStack(alignment: .leading, spacing: 2, pinnedViews: []) {189 ForEach(found.groups) { group in190 Text(verbatim: group.title).font(.system(size: 11, weight: .semibold)).foregroundStyle(ORIX.Palette.textPrimary)191 .padding(.horizontal, 8).padding(.top, 10).padding(.bottom, 2)192 .accessibilityAddTraits(.isHeader)193 ForEach(group.hits) { hit in194 Button { open(file: hit.file, line: hit.line) } label: {195 Text(emphasised(hit)).lineLimit(3).multilineTextAlignment(.leading)196 .frame(maxWidth: .infinity, alignment: .leading)197 .padding(.horizontal, 8).padding(.vertical, 5)198 .background(ORIX.Palette.surfaceRaised.opacity(0.55), in: RoundedRectangle(cornerRadius: ORIX.Radius.chip, style: .continuous))199 .contentShape(Rectangle())200 }201 .buttonStyle(.plain)202 .accessibilityLabel(Text(verbatim: "\(group.title): \(hit.text)"))203 .accessibilityIdentifier("docs-search-hit")204 }205 }206 if found.truncated {207 Text("Only the first 400 matches are listed. Type more to narrow the search.")208 .font(.system(size: 10.5)).foregroundStyle(ORIX.Palette.textTertiary).padding(8)209 }210 }211 .padding(.horizontal, 6).padding(.bottom, 10)212 }213 .accessibilityIdentifier("docs-search-results")214 }215 }216217 /// The matching line, shortened around the match, with the match in bold on a tinted background.218 private func emphasised(_ hit: DocSearchHit) -> AttributedString {219 let text = hit.text220 let before = text.distance(from: text.startIndex, to: hit.match.lowerBound)221 let start = before > 46 ? text.index(hit.match.lowerBound, offsetBy: -40) : text.startIndex222 let end = text.index(hit.match.upperBound, offsetBy: 110, limitedBy: text.endIndex) ?? text.endIndex223 func plain(_ s: Substring) -> AttributedString {224 var a = AttributedString(String(s)); a.font = .system(size: 11.5); a.foregroundColor = ORIX.Palette.textSecondary; return a225 }226 var out = plain((start > text.startIndex ? "…" : "") + text[start ..< hit.match.lowerBound])227 var match = AttributedString(String(text[hit.match]))228 match.font = .system(size: 11.5, weight: .bold); match.foregroundColor = ORIX.Palette.textPrimary229 match.backgroundColor = ORIX.Palette.accent.opacity(0.28); match.underlineStyle = .single230 out.append(match)231 out.append(plain(text[hit.match.upperBound ..< end] + (end < text.endIndex ? "…" : "")))232 return out233 }234235 // MARK: Reader236237 @ViewBuilder private var reader: some View {238 switch store.phase {239 case .loading:240 ProgressView().frame(maxWidth: .infinity, maxHeight: .infinity)241 case .unavailable:242 EmptyState(symbol: "book.closed", title: "Documentation not found", message: "The ORIX Script documentation is missing from this copy of the application. Reinstall ORIX DJ to restore it.")243 .accessibilityIdentifier("docs-unavailable")244 case .ready:245 if let file = currentFile, let chapter = store.chapters[file] {246 VStack(spacing: 0) {247 readerHeader(chapter)248 Rectangle().fill(ORIX.Palette.hairline).frame(height: 1)249 chapterBody(chapter)250 }251 }252 }253 }254255 private func readerHeader(_ chapter: DocChapter) -> some View {256 let entry = store.entry(for: chapter.file)257 let parent = store.entry(for: entry?.parent)258 let sections = chapter.document.headings.filter { $0.level == 2 }259 return HStack(spacing: ORIX.Space.xs) {260 if let parent {261 Button { open(file: parent.file) } label: { Text(verbatim: parent.title) }.buttonStyle(.link).font(.system(size: 12))262 Image(systemName: "chevron.right").font(.system(size: 9, weight: .bold)).foregroundStyle(ORIX.Palette.textTertiary)263 } else if let n = entry?.number {264 Text("Chapter \(n) of \(store.entries.compactMap(\.number).max() ?? n)").font(ORIX.Typeface.caption).foregroundStyle(ORIX.Palette.textTertiary)265 Text(verbatim: "·").foregroundStyle(ORIX.Palette.textTertiary)266 }267 Text(verbatim: entry?.title ?? chapter.title).font(.system(size: 12.5, weight: .semibold)).foregroundStyle(ORIX.Palette.textPrimary).lineLimit(1)268 Spacer(minLength: 8)269 if !sections.isEmpty {270 Menu {271 ForEach(sections, id: \.id) { h in Button { open(file: chapter.file, anchor: h.anchor) } label: { Text(verbatim: h.title) } }272 } label: { Label("On this page", systemImage: "list.bullet.indent") }273 .menuStyle(.borderlessButton).fixedSize()274 .accessibilityIdentifier("docs-sections")275 }276 HStack(spacing: 2) {277 Button { zoom(-0.1) } label: { Image(systemName: "textformat.size.smaller").frame(width: 24, height: 22) }278 .help("Smaller text (⌘−)").accessibilityLabel("Smaller text").accessibilityIdentifier("docs-text-smaller").disabled(textScale <= 0.8)279 Text(verbatim: "\(Int((scale * 100).rounded())) %").font(ORIX.Typeface.caption).foregroundStyle(ORIX.Palette.textSecondary).frame(width: 44)280 .accessibilityLabel("Text size").accessibilityValue(Text(verbatim: "\(Int((scale * 100).rounded())) %"))281 Button { zoom(0.1) } label: { Image(systemName: "textformat.size.larger").frame(width: 24, height: 22) }282 .help("Larger text (⌘+)").accessibilityLabel("Larger text").accessibilityIdentifier("docs-text-larger").disabled(textScale >= 1.8)283 }284 .buttonStyle(.borderless)285 }286 .padding(.horizontal, ORIX.Space.md).frame(height: 38)287 .background(ORIX.Palette.surface)288 }289290 private struct ScrollKey: Equatable { var file: String; var token: Int }291292 private func chapterBody(_ chapter: DocChapter) -> some View {293 let style = MarkdownStyle(file: chapter.file, scale: scale, markedNode: store.markedNode)294 return ScrollViewReader { proxy in295 ScrollView {296 LazyVStack(alignment: .leading, spacing: 12 * scale) {297 ForEach(chapter.document.nodes) { node in298 MarkdownNodeView(node: node, style: style).id(node.id)299 }300 chapterFooter(chapter)301 }302 .padding(.horizontal, ORIX.Space.xl).padding(.vertical, ORIX.Space.lg)303 .frame(maxWidth: 1080, alignment: .leading)304 .frame(maxWidth: .infinity, alignment: .leading)305 }306 .id(chapter.file)307 .task(id: ScrollKey(file: chapter.file, token: store.scrollToken)) {308 guard let node = store.scrollNode else { return }309 // Twice: the lazy stack only knows the height of far blocks once it has laid them out.310 for delay in [60, 220] as [UInt64] {311 try? await Task.sleep(nanoseconds: delay * 1_000_000)312 if Task.isCancelled { return }313 proxy.scrollTo(node, anchor: .top)314 }315 }316 .accessibilityIdentifier("docs-reader")317 }318 }319320 private func chapterFooter(_ chapter: DocChapter) -> some View {321 let previous = store.neighbour(of: chapter.file, offset: -1), next = store.neighbour(of: chapter.file, offset: 1)322 return HStack(spacing: ORIX.Space.sm) {323 if let previous {324 Button { open(file: previous.file) } label: { navigationCard(caption: "Previous", title: previous.title, symbol: "chevron.left", leading: true) }325 .buttonStyle(.plain).accessibilityIdentifier("docs-previous")326 }327 Spacer(minLength: 0)328 if let next {329 Button { open(file: next.file) } label: { navigationCard(caption: "Next", title: next.title, symbol: "chevron.right", leading: false) }330 .buttonStyle(.plain).accessibilityIdentifier("docs-next")331 }332 }333 .padding(.top, ORIX.Space.lg)334 .frame(maxWidth: 900 * scale)335 }336337 private func navigationCard(caption: LocalizedStringKey, title: String, symbol: String, leading: Bool) -> some View {338 HStack(spacing: 10) {339 if leading { Image(systemName: symbol).font(.system(size: 12, weight: .bold)).foregroundStyle(ORIX.Palette.accent) }340 VStack(alignment: leading ? .leading : .trailing, spacing: 2) {341 Text(caption).font(ORIX.Typeface.label).foregroundStyle(ORIX.Palette.textTertiary).textCase(.uppercase)342 Text(verbatim: title).font(.system(size: 13, weight: .semibold)).foregroundStyle(ORIX.Palette.textPrimary).lineLimit(1)343 }344 if !leading { Image(systemName: symbol).font(.system(size: 12, weight: .bold)).foregroundStyle(ORIX.Palette.accent) }345 }346 .padding(.horizontal, 14).padding(.vertical, 10)347 .frame(minWidth: 200, alignment: leading ? .leading : .trailing)348 .background(ORIX.Palette.surface, in: RoundedRectangle(cornerRadius: ORIX.Radius.control, style: .continuous))349 .overlay(RoundedRectangle(cornerRadius: ORIX.Radius.control, style: .continuous).strokeBorder(ORIX.Palette.hairline, lineWidth: 1))350 .contentShape(Rectangle())351 }352}353