SPB Git

Repository Public

CrossReferenceSheet.swift 9.1 KB 164 lines swift

1// ORIX Docs2// File: App/Sources/Sheets/CrossReferenceSheet.swift3// Description: Inserts a cross-reference to a heading, figure, table, equation or bookmark, shown as its number, label and number,4//              page or text, with a preview of the resulting text.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import SwiftUI9import DocModel1011struct CrossReferenceSheet: View {12    private struct Target: Identifiable, Hashable {13        let id: String14        let title: String15        let level: Int16    }17    private struct Kind: Identifiable, Hashable {18        let id: String19        let title: String20        let symbol: String21        let targets: [Target]22    }2324    let session: DocumentSession25    private let kinds: [Kind]26    @State private var kind: String27    @State private var target: String?28    @State private var display: CrossRef.Display = .labelAndNumber2930    init(session: DocumentSession) {31        self.session = session32        let n = session.numbering33        func captions(_ label: String) -> [Target] {34            n.captions.filter { $0.value.label == label }.sorted { $0.value.number < $1.value.number }35                .map { Target(id: $0.key, title: $0.value.text.isEmpty ? "\(label) \($0.value.number)" : $0.value.text, level: 1) }36        }37        var list = [38            Kind(id: "heading", title: String(localized: "Headings"), symbol: "text.alignleft",39                 targets: n.outline.map { Target(id: $0.id, title: ($0.number.map { $0 + "  " } ?? "") + $0.text, level: $0.level) }),40            Kind(id: "Figure", title: String(localized: "Figures"), symbol: "photo", targets: captions("Figure")),41            Kind(id: "Table", title: String(localized: "Tables"), symbol: "tablecells", targets: captions("Table")),42            Kind(id: "Equation", title: String(localized: "Equations"), symbol: "function", targets: captions("Equation")),43        ]44        // Captions with a custom label ("Listing", "Map" …) get their own kind.45        for label in Set(n.captions.values.map(\.label)).subtracting(["Figure", "Table", "Equation"]).sorted() {46            list.append(Kind(id: label, title: label, symbol: "number", targets: captions(label)))47        }48        list.append(Kind(id: "bookmark", title: String(localized: "Bookmarks"), symbol: "bookmark",49                         targets: n.bookmarks.keys.sorted().map { Target(id: $0, title: $0, level: 1) }))50        kinds = list51        let first = list.first { !$0.targets.isEmpty } ?? list[0]52        _kind = State(initialValue: first.id)53        _target = State(initialValue: first.targets.first?.id)54    }5556    private var current: Kind { kinds.first { $0.id == kind } ?? kinds[0] }57    private func close() { session.activeSheet = nil }5859    private func text(_ target: String, _ display: CrossRef.Display) -> String {60        session.numbering.crossRefText(CrossRef(target: target, display: display)) { session.layout.pageText(ofBlock: session.numbering.bookmarks[$0] ?? $0) }61    }6263    private func commit() {64        guard let target else { return }65        let ref = CrossRef(target: target, display: display)66        session.perform(String(localized: "Insert Cross-Reference")) { $0.insertInline(.crossRef(ref)) }67        close()68    }6970    private static let displays: [(CrossRef.Display, LocalizedStringKey)] = [71        (.labelAndNumber, "Label and number"), (.number, "Number only"), (.text, "Text of the target"), (.page, "Page number"),72    ]7374    var body: some View {75        let k = current76        SheetScaffold(title: "Insert Cross-Reference", symbol: "arrow.triangle.branch",77                      subtitle: "The reference follows its target: numbers and pages update when the document changes.", width: 620,78                      primaryTitle: "Insert", primaryEnabled: target != nil, onPrimary: commit, onCancel: close) {79            HStack(alignment: .top, spacing: ORIX.Space.l) {80                VStack(alignment: .leading, spacing: 2) {81                    FieldLabel("Refer to")82                    ForEach(kinds) { item in83                        let selected = item.id == k.id84                        Button { kind = item.id; target = item.targets.first?.id } label: {85                            HStack(spacing: 6) {86                                Image(systemName: item.symbol).font(.system(size: 11)).frame(width: 16)87                                    .foregroundStyle(selected ? ORIX.Palette.accent : ORIX.Palette.textSecondary)88                                Text(verbatim: item.title).font(.system(size: 12, weight: selected ? .semibold : .regular)).foregroundStyle(ORIX.Palette.text)89                                Spacer(minLength: 4)90                                Text("\(item.targets.count)").font(ORIX.Font.caption).monospacedDigit().foregroundStyle(ORIX.Palette.textTertiary)91                            }92                            .padding(.horizontal, 8).padding(.vertical, 5)93                            .background(RoundedRectangle(cornerRadius: ORIX.Radius.s).fill(selected ? ORIX.Palette.accent.opacity(0.14) : .clear))94                            .contentShape(Rectangle())95                        }96                        .buttonStyle(.plain)97                        .accessibilityLabel(Text(verbatim: "\(item.title), \(item.targets.count)"))98                        .accessibilityAddTraits(selected ? .isSelected : [])99                        .accessibilityIdentifier("xref-kind-\(item.id)")100                    }101                }102                .frame(width: 160)103104                VStack(alignment: .leading, spacing: ORIX.Space.s) {105                    FieldLabel("Target")106                    if k.targets.isEmpty {107                        EmptyState(symbol: k.symbol, title: "Nothing to refer to yet", message: emptyMessage(k.id)).frame(height: 210).well()108                    } else {109                        ScrollView {110                            LazyVStack(alignment: .leading, spacing: 1) {111                                ForEach(k.targets) { t in112                                    let selected = t.id == target113                                    Button { target = t.id } label: {114                                        HStack(spacing: 6) {115                                            Image(systemName: selected ? "checkmark.circle.fill" : "circle").font(.system(size: 10.5))116                                                .foregroundStyle(selected ? ORIX.Palette.accent : ORIX.Palette.textTertiary)117                                            Text(verbatim: t.title).font(ORIX.Font.body).foregroundStyle(ORIX.Palette.text).lineLimit(1)118                                            Spacer(minLength: 0)119                                        }120                                        .padding(.leading, CGFloat(max(0, t.level - 1)) * 12 + 8).padding(.trailing, 8).padding(.vertical, 5)121                                        .background(RoundedRectangle(cornerRadius: ORIX.Radius.s).fill(selected ? ORIX.Palette.accent.opacity(0.14) : .clear))122                                        .contentShape(Rectangle())123                                    }124                                    .buttonStyle(.plain)125                                    .accessibilityAddTraits(selected ? .isSelected : [])126                                }127                            }128                            .padding(4)129                        }130                        .frame(height: 210).well()131                        .accessibilityIdentifier("xref-targets")132                    }133                    HStack(alignment: .bottom, spacing: ORIX.Space.m) {134                        LabeledField(label: "Show") {135                            Picker("Show", selection: $display) {136                                ForEach(CrossReferenceSheet.displays, id: \.0) { Text($0.1).tag($0.0) }137                            }138                            .labelsHidden().frame(width: 170).accessibilityIdentifier("xref-display")139                        }140                        LabeledField(label: "Result") {141                            Text(verbatim: target.map { text($0, display) } ?? "—")142                                .font(.system(size: 13, design: .serif)).foregroundStyle(ORIX.Palette.text).lineLimit(1)143                                .frame(maxWidth: .infinity, alignment: .leading).padding(.horizontal, 8).padding(.vertical, 4)144                                .background(ORIX.Palette.surfaceRaised).well(radius: ORIX.Radius.s)145                                .accessibilityIdentifier("xref-preview")146                        }147                    }148                }149            }150        }151    }152153    private func emptyMessage(_ id: String) -> LocalizedStringKey {154        switch id {155        case "heading": return "Apply a heading style to a paragraph to make it a target."156        case "Figure": return "Add a figure caption (Insert › Figure Caption) to make a figure a target."157        case "Table": return "Add a table caption (Insert › Table Caption) to make a table a target."158        case "Equation": return "Insert a numbered display equation to make it a target."159        case "bookmark": return "Insert a bookmark (Insert › Bookmark) to refer to any place."160        default: return "No caption with this label."161        }162    }163}164
Files main
Menu

Theme