#if os(iOS) import OrgApp import OrgCore import OrgIndex import OrgPresentation import SwiftUI import UIKit /// What to read: a file, and where in it. enum ReaderRoute: Hashable { case file(String) case offset(String, Int) /// A search result, found again if the file changed since it was indexed. case heading(HeadingLocation) } /// Editing a file, from the reader. struct EditorRoute: Hashable { let path: String let offset: Int? } /// A file to read: headings that fold and unfold with a tap, as TAB cycles them, text styled as /// in the editor, and links to follow. struct ReaderScreen: View { let route: ReaderRoute let workspace: WorkspaceModel let session: DocumentSession @State private var fold = FoldState() @State private var folded: [Range] = [] @State private var loadedPath: String? @State private var showingOutline = false @State private var message: String? @Environment(\.openURL) private var openURL @Environment(MobileModel.self) private var model private var outline: [OutlineEntry] { session.outline } var body: some View { let _ = session.editVersion // Read again when settings or the Dynamic Type size change. let _ = model.settingsVersion let theme = MobileTheme(model.theme) ScrollViewReader { proxy in ScrollView { LazyVStack(alignment: .leading, spacing: 8) { if let tree = session.document?.tree { let preambleEnd = outline.first?.start ?? (tree.text as NSString).length if preambleEnd > 0 { textView(tree, 0.. CGFloat { CGFloat(entry.level - 1) * 14 } /// Hidden under a folded ancestor. private func isShown(_ index: Int) -> Bool { var parent = outline[index].parent while let p = parent { if fold.folds.contains(outline[p].start) { return false } parent = outline[p].parent } return true } /// From after the heading line to the first child, or the section's end. private func bodyRange(_ index: Int, _ tree: OrgTree) -> Range { let entry = outline[index] let ns = tree.text as NSString let lineEnd = NSMaxRange(ns.lineRange(for: NSRange(location: entry.start, length: 0))) let firstChild = outline[(index + 1)...].first { $0.parent == index }?.start ?? entry.end return min(lineEnd, firstChild).. some View { let ns = tree.text as NSString var line = ns.lineRange(for: NSRange(location: entry.start, length: 0)) let title = min(entry.start + entry.level + 1, NSMaxRange(line)) line.length = NSMaxRange(line) - title let text = attributed(ReadingText.segments(tree, in: title..<(title + line.length)), heading: entry.level, theme) let hasContent = entry.end > NSMaxRange(ns.lineRange(for: NSRange(location: entry.start, length: 0))) let foldedMark = fold.folds.contains(entry.start) && hasContent return HStack(alignment: .firstTextBaseline, spacing: 6) { Image(systemName: foldedMark ? "chevron.right" : "chevron.down") .font(.caption.weight(.semibold)).foregroundStyle(theme.swiftColor("markup") ?? Color(uiColor: .tertiaryLabel)) .opacity(hasContent ? 1 : 0) Text(text.trimmingTrailingNewlines()).lineSpacing(CGFloat(max(0, theme.spec.lineSpacing))) .frame(maxWidth: .infinity, alignment: .leading) } .padding(.leading, indent(entry)) .padding(.top, entry.level == 1 ? 6 : 0) .contentShape(Rectangle()) .onTapGesture { fold = Presentation.cycle(entry.start, in: tree, fold) } .accessibilityAddTraits(.isButton) .accessibilityHint(foldedMark ? "Unfolds the heading" : "Folds the heading") } private func textView(_ tree: OrgTree, _ range: Range, _ theme: MobileTheme) -> some View { Text(attributed(ReadingText.segments(tree, in: range, folded: folded), heading: nil, theme).trimmingTrailingNewlines()) .lineSpacing(CGFloat(max(0, theme.spec.lineSpacing))) .textSelection(.enabled) .frame(maxWidth: .infinity, alignment: .leading) } /// Segments as styled text in the theme's font and colors, as the editor styles them; /// links get `orgstar-link:` URLs to follow. private func attributed(_ segments: [ReadingText.Segment], heading level: Int?, _ theme: MobileTheme) -> AttributedString { var result = AttributedString() for segment in segments { var part = AttributedString(segment.text) var font = level.map(theme.headingFont) ?? theme.font var color = level.flatMap { theme.color("heading-\(min(max($0, 1), 8))") } ?? theme.foreground func fg(_ key: String) { if let c = theme.color(key) { color = c } } // Outer roles first, so inner ones win. for role in segment.roles.sorted(by: { Self.depth($0) < Self.depth($1) }) { switch role { case .todo, .done: font = MobileTheme.adding(.traitBold, to: font) if let c = theme.keywordColor(segment.text, done: role == .done) { color = c } case .priority: fg("priority") case .tags: fg("tags") case .bold: font = MobileTheme.adding(.traitBold, to: font) case .italic: font = MobileTheme.adding(.traitItalic, to: font) case .underline: part.underlineStyle = .single case .strikeThrough: part.strikethroughStyle = .single case .verbatim, .code, .inlineSource: if let background = theme.color("inline-background") { part.backgroundColor = Color(uiColor: background) } fg(role == .verbatim ? "verbatim" : "code") case .markup, .linkMarkup, .leadingStars: fg("markup") case .timestamp: fg("timestamp") case .comment: fg("comment") case .keyword: fg("keyword") case .metadata: fg("metadata") case .blockDelimiter: fg("block-delimiter") case .footnote, .cookie, .target, .macro, .latex: fg("special") case .table, .rule: fg("table") case .link: part.underlineStyle = .single fg("link") case .heading, .block, .syntax: break } } if segment.link != nil { // Found again by position when followed. part.link = URL(string: "orgstar-link:\(segment.offset)") } part.font = Font(font as CTFont) part.foregroundColor = Color(uiColor: color) result += part } return result } /// How deep a role's text usually nests: elements, then objects, then their parts. private static func depth(_ role: StyleRole) -> Int { switch role { case .heading: 0 case .metadata, .keyword, .comment, .block, .table, .rule: 1 case .blockDelimiter, .link, .bold, .italic, .underline, .strikeThrough, .timestamp, .footnote, .target, .macro, .latex: 2 default: 3 } } // MARK: - Actions private func open() { switch route { case .file(let path): if session.path != path { session.open(path) } case .offset(let path, let offset): if session.path != path { session.open(path) } session.reveal(offset) case .heading(let location): session.show(location) } loadFolds() } /// The file's startup visibility, kept while the same file is open. private func loadFolds() { guard let tree = session.document?.tree else { return } folded = Presentation.startupWrappers( tree, hideDrawers: session.options.hideDrawerStartup, hideBlocks: session.options.hideBlockStartup ).map(\.hidden) guard loadedPath != session.path else { return } loadedPath = session.path fold = Presentation.applyVisibilityProperties(Presentation.startupFoldState(tree) ?? FoldState(), in: tree) } /// Unfolds the way to the heading containing `offset` and scrolls to it. private func reveal(_ offset: Int, _ proxy: ScrollViewProxy) { guard let index = outline.lastIndex(where: { $0.start <= offset }) else { return } var parent = outline[index].parent while let p = parent { fold.folds.remove(outline[p].start) parent = outline[p].parent } let start = outline[index].start DispatchQueue.main.async { withAnimation { proxy.scrollTo(start, anchor: .top) } } } private func follow(_ url: URL) -> OpenURLAction.Result { guard url.scheme == "orgstar-link", let offset = Int(url.absoluteString.dropFirst("orgstar-link:".count)), let tree = session.document?.tree, let link = Links.link(at: offset, text: tree.text, tree: tree)?.link else { return .systemAction } switch session.follow(link, workspace: workspace, isText: { _ in false }) { case .shown: message = nil case .openExternally(let target): openURL(target) case .message(let text): message = text } return .handled } private var outlineSheet: some View { NavigationStack { List(outline, id: \.start) { entry in Button { showingOutline = false session.reveal(entry.start) } label: { Text(entry.title.isEmpty ? "(untitled)" : entry.title) .padding(.leading, indent(entry)) .foregroundStyle(.primary) } } .navigationTitle("Outline") .navigationBarTitleDisplayMode(.inline) .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Done") { showingOutline = false } } } } } } private extension AttributedString { /// Without the final newline, which `Text` would show as an empty line. func trimmingTrailingNewlines() -> AttributedString { var copy = self while let last = copy.characters.last, last.isNewline { copy.characters.removeLast() } return copy } } #endif