SPB Git

Repository Public

DocumentInspector.swift 19.0 KB 302 lines swift

1// ORIX Docs2// File: App/Sources/Inspector/DocumentInspector.swift3// Description: The Document tab: page layout of the current section (paper, orientation, margins, columns, headers and footers, page4//              numbering, border, background, watermark, section break) and document-level language and typing options.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import SwiftUI9import DocModel1011struct DocumentInspector: View {12    @Bindable var session: DocumentSession13    @State private var applyToAll = false1415    private struct MarginPreset: Identifiable { let id: String; let title: String; let insets: Insets }16    private static var marginPresets: [MarginPreset] {17        [MarginPreset(id: "normal", title: String(localized: "Normal"), insets: Insets(all: 72)),18         MarginPreset(id: "narrow", title: String(localized: "Narrow"), insets: Insets(all: 36)),19         MarginPreset(id: "moderate", title: String(localized: "Moderate"), insets: Insets(top: 72, left: 54, bottom: 72, right: 54)),20         MarginPreset(id: "wide", title: String(localized: "Wide"), insets: Insets(top: 72, left: 108, bottom: 72, right: 108))]21    }22    private static var numberFormats: [(value: NumberFormat, title: String)] {23        [(.decimal, "1, 2, 3"), (.lowerRoman, "i, ii, iii"), (.upperRoman, "I, II, III"), (.lowerAlpha, "a, b, c"), (.upperAlpha, "A, B, C")]24    }25    private static var breakKinds: [(value: SectionBreak.Kind, title: String)] {26        [(.nextPage, String(localized: "Next page")), (.continuous, String(localized: "Continuous")), (.oddPage, String(localized: "Odd page")), (.evenPage, String(localized: "Even page"))]27    }28    private static var borderStyles: [(value: BorderLine.Style, title: String)] {29        [(.solid, String(localized: "Solid")), (.dashed, String(localized: "Dashed")), (.dotted, String(localized: "Dotted"))]30    }31    /// Paper tints for page backgrounds, plus the highlight tones.32    private static let backgrounds: [(String, UInt32)] = [("Ivory", 0xFBF8EF), ("Cream", 0xF6EFDD), ("Mist", 0xF1F4F8), ("Mint", 0xEEF7F0), ("Blush", 0xFBEFF1)] + ColorMenu.highlights3334    /// Applies a page-setup change to the current section, or to every section when "Apply to all sections" is on.35    private func update(_ name: String, key: String? = nil, _ change: (inout PageSetup) -> Void) {36        let index = session.currentSectionIndex37        let all = applyToAll38        session.perform(name, coalesce: key.map { "page-\($0)" }) { e in39            let count = e.doc.sectionSetups.count40            for i in (all ? Array(0..<count) : [min(index, count - 1)]) {41                var s = e.doc.setup(ofSection: i)42                change(&s)43                e.doc.setSetup(s, ofSection: i)44            }45        }46        session.refocusCanvas()47    }4849    private func paperDetail(_ p: PaperSize) -> String {50        let u = LengthUnit.current51        let f = NumberFormatter(); f.minimumFractionDigits = 0; f.maximumFractionDigits = 252        func n(_ v: Double) -> String { f.string(from: NSNumber(value: v / u.pointsPerUnit)) ?? "" }53        return "\(n(p.width)) × \(n(p.height)) \(u.suffix)"54    }55    private func paper(width: Double, height: Double) -> PaperSize {56        PaperSize.all.first { abs($0.width - width) < 0.6 && abs($0.height - height) < 0.6 } ?? PaperSize(name: String(localized: "Custom"), width: width, height: height)57    }5859    var body: some View {60        let _ = session.selectionRevision61        let _ = session.revision62        let doc = session.doc63        let count = doc.sectionSetups.count64        let index = min(session.currentSectionIndex, count - 1)65        let setup = doc.setup(ofSection: index)66        let known = PaperSize.all.contains { $0.name == setup.paper.name && abs($0.width - setup.paper.width) < 0.6 && abs($0.height - setup.paper.height) < 0.6 }67        let inBody = session.selection.story == .body6869        // Scope70        VStack(alignment: .leading, spacing: ORIX.Space.s) {71            HStack(spacing: ORIX.Space.s) {72                Image(systemName: "rectangle.stack").font(.system(size: 11, weight: .medium)).foregroundStyle(ORIX.Palette.accent).accessibilityHidden(true)73                Text("Section \(index + 1) of \(count)").font(.system(size: 12, weight: .semibold)).foregroundStyle(ORIX.Palette.text)74                    .accessibilityIdentifier("document-section")75                Spacer(minLength: 0)76                Text(verbatim: "\(known ? setup.paper.name : String(localized: "Custom")) · \(setup.landscape ? String(localized: "Landscape") : String(localized: "Portrait"))")77                    .font(.system(size: 10.5)).foregroundStyle(ORIX.Palette.textTertiary).lineLimit(1)78            }79            if count > 1 {80                SwitchRow("Apply to all sections", isOn: applyToAll, identifier: "document-apply-all") { applyToAll = $0 }81                InspectorNote(applyToAll ? "Page layout changes apply to the whole document (\(count) sections)."82                                         : "Page layout changes apply to this section only. Place the caret in another section to edit it.")83            } else {84                InspectorNote("The document has one section: page layout changes apply to the whole document.")85            }86        }87        .padding(.horizontal, ORIX.Space.l).padding(.vertical, ORIX.Space.m)88        .frame(maxWidth: .infinity, alignment: .leading)89        .overlay(alignment: .bottom) { Rectangle().fill(ORIX.Palette.hairline.opacity(0.7)).frame(height: 1) }9091        InspectorGroup("Paper", id: "document.paper") {92            PropertyRow("Size") {93                InspectorPopup(known ? setup.paper.name : String(localized: "Custom"), width: 168, label: "Paper size", identifier: "document-paper") {94                    ForEach(PaperSize.all, id: \.name) { p in95                        Button { update(String(localized: "Paper Size")) { $0.paper = p } } label: {96                            if known && p.name == setup.paper.name { Label("\(p.name) — \(paperDetail(p))", systemImage: "checkmark") } else { Text(verbatim: "\(p.name) — \(paperDetail(p))") }97                        }98                    }99                    if !known { Divider(); Label("Custom — \(paperDetail(setup.paper))", systemImage: "checkmark") }100                }101            }102            PropertyRow("Width") {103                LengthField(points: setup.paper.width, range: 72...3600, label: "Paper width", identifier: "document-paper-width") { w in104                    update(String(localized: "Paper Size"), key: "paper-w") { $0.paper = paper(width: w, height: $0.paper.height) }105                }106            }107            PropertyRow("Height") {108                LengthField(points: setup.paper.height, range: 72...3600, label: "Paper height", identifier: "document-paper-height") { h in109                    update(String(localized: "Paper Size"), key: "paper-h") { $0.paper = paper(width: $0.paper.width, height: h) }110                }111            }112            PropertyRow("Orientation") {113                TextSegments(items: [(false, String(localized: "Portrait")), (true, String(localized: "Landscape"))], selection: setup.landscape, identifier: "document-orientation") { l in114                    update(String(localized: "Orientation")) { $0.landscape = l }115                }116                .frame(width: 168)117            }118        }119120        InspectorGroup("Margins", id: "document.margins") {121            let limitV = max(36, setup.pageHeight / 2 - 36), limitH = max(36, setup.pageWidth / 2 - 36)122            let preset = DocumentInspector.marginPresets.first { $0.insets == setup.margins }123            PropertyRow("Preset") {124                InspectorPopup(preset?.title ?? String(localized: "Custom"), width: 168, label: "Margin preset", identifier: "document-margin-preset") {125                    ForEach(DocumentInspector.marginPresets) { p in126                        Button { update(String(localized: "Margins")) { $0.margins = p.insets } } label: {127                            if p.id == preset?.id { Label(p.title, systemImage: "checkmark") } else { Text(p.title) }128                        }129                    }130                }131            }132            Grid(alignment: .leading, horizontalSpacing: ORIX.Space.s, verticalSpacing: ORIX.Space.s) {133                GridRow {134                    marginLabel("Top")135                    LengthField(points: setup.margins.top, range: 0...limitV, width: 76, label: "Top margin", identifier: "document-margin-top") { v in update(String(localized: "Margins"), key: "m-top") { $0.margins.top = v } }136                    marginLabel("Bottom").padding(.leading, 4)137                    LengthField(points: setup.margins.bottom, range: 0...limitV, width: 76, label: "Bottom margin") { v in update(String(localized: "Margins"), key: "m-bottom") { $0.margins.bottom = v } }138                }139                GridRow {140                    marginLabel("Left")141                    LengthField(points: setup.margins.left, range: 0...limitH, width: 76, label: "Left margin") { v in update(String(localized: "Margins"), key: "m-left") { $0.margins.left = v } }142                    marginLabel("Right").padding(.leading, 4)143                    LengthField(points: setup.margins.right, range: 0...limitH, width: 76, label: "Right margin") { v in update(String(localized: "Margins"), key: "m-right") { $0.margins.right = v } }144                }145            }146        }147148        InspectorGroup("Columns", id: "document.columns") {149            PropertyRow("Columns") {150                ValueField(value: Double(setup.columns), range: 1...6, step: 1, decimals: 0, width: 58, label: "Number of columns", identifier: "document-columns") { v in151                    update(String(localized: "Columns"), key: "columns") { $0.columns = max(1, min(6, Int(v.rounded()))) }152                }153            }154            PropertyRow("Gap") {155                LengthField(points: setup.columnGap, range: 6...144, label: "Gap between columns", isEnabled: setup.columns > 1) { v in update(String(localized: "Column Gap"), key: "gap") { $0.columnGap = v } }156            }157            SwitchRow("Rule between columns", isOn: setup.columnRule, isEnabled: setup.columns > 1) { on in update(String(localized: "Column Rule")) { $0.columnRule = on } }158        }159160        InspectorGroup("Header and Footer", id: "document.headerfooter") {161            PropertyRow("Header from top") {162                LengthField(points: setup.headerDistance, range: 0...max(36, setup.pageHeight / 3), label: "Distance from the top edge to the header") { v in163                    update(String(localized: "Header Position"), key: "hdist") { $0.headerDistance = v }164                }165            }166            PropertyRow("Footer from bottom") {167                LengthField(points: setup.footerDistance, range: 0...max(36, setup.pageHeight / 3), label: "Distance from the bottom edge to the footer") { v in168                    update(String(localized: "Footer Position"), key: "fdist") { $0.footerDistance = v }169                }170            }171            SwitchRow("Different first page", isOn: setup.differentFirstPage, identifier: "document-first-page") { on in update(String(localized: "Different First Page")) { $0.differentFirstPage = on } }172            SwitchRow("Different odd and even pages", isOn: setup.differentOddEven) { on in update(String(localized: "Different Odd and Even Pages")) { $0.differentOddEven = on } }173            HStack(spacing: ORIX.Space.s) {174                InspectorButton("Edit Header", symbol: "rectangle.topthird.inset.filled", identifier: "document-edit-header") { session.run(.editHeader) }175                InspectorButton("Edit Footer", symbol: "rectangle.bottomthird.inset.filled", identifier: "document-edit-footer") { session.run(.editFooter) }176            }177            HStack(spacing: ORIX.Space.s) {178                InspectorButton("Page Number", symbol: "number", identifier: "document-insert-page-number") { session.run(.insertPageNumber); session.focusCanvas() }179                    .help("Insert the page number field at the caret")180                InspectorButton("Page Count", symbol: "sum") { session.run(.insertPageCount); session.focusCanvas() }181                    .help("Insert the total page count field at the caret")182            }183            if inBody {184                InspectorNote("Fields are inserted at the caret. To number every page, edit the header or footer first.")185            } else {186                InspectorButton("Return to Body Text", symbol: "arrow.uturn.backward", prominent: true) { session.run(.returnToBody); session.focusCanvas() }187            }188        }189190        InspectorGroup("Page Numbering", id: "document.numbering") {191            SwitchRow("Restart numbering", isOn: setup.pageNumberStart != nil, identifier: "document-restart-numbering") { on in192                update(String(localized: "Page Numbering")) { $0.pageNumberStart = on ? 1 : nil }193            }194            if let start = setup.pageNumberStart {195                PropertyRow("Start at") {196                    ValueField(value: Double(start), range: 0...99_999, step: 1, decimals: 0, width: 70, label: "First page number of the section") { v in197                        update(String(localized: "Page Numbering"), key: "pstart") { $0.pageNumberStart = Int(v.rounded()) }198                    }199                }200            }201            PropertyRow("Format") {202                ChoicePopup(selection: setup.pageNumberFormat, options: DocumentInspector.numberFormats, width: 110, label: "Page number format", identifier: "document-number-format") { f in203                    update(String(localized: "Page Number Format")) { $0.pageNumberFormat = f }204                }205            }206        }207208        InspectorGroup("Page", id: "document.page") {209            SwitchRow("Border", isOn: setup.border != nil, identifier: "document-border") { on in update(String(localized: "Page Border")) { $0.border = on ? PageBorder() : nil } }210            if let border = setup.border {211                PropertyRow("Line") {212                    ChoicePopup(selection: border.line.style == .double ? .solid : border.line.style, options: DocumentInspector.borderStyles, width: 78, label: "Border style") { s in213                        update(String(localized: "Page Border")) { $0.border?.line.style = s }214                    }215                    ValueField(value: border.line.width, range: 0.25...12, step: 0.25, decimals: 2, suffix: "pt", width: 66, label: "Border width") { v in216                        update(String(localized: "Page Border"), key: "bwidth") { $0.border?.line.width = v }217                    }218                }219                PropertyRow("Colour") {220                    SwatchMenu(help: "Border colour", current: border.line.color) { c in update(String(localized: "Page Border"), key: "bcolor") { if let c { $0.border?.line.color = c } } }221                }222                PropertyRow("From page edge") {223                    LengthField(points: border.inset, range: 0...144, label: "Distance of the border from the page edge") { v in update(String(localized: "Page Border"), key: "binset") { $0.border?.inset = v } }224                }225            }226            PropertyRow("Background") {227                SwatchMenu(help: "Page background colour", current: setup.background, allowsNone: true, palette: DocumentInspector.backgrounds, identifier: "document-background") { c in228                    update(String(localized: "Page Background"), key: "bg") { $0.background = c }229                }230            }231            PropertyRow("Watermark") {232                InspectorTextField(text: setup.watermark ?? "", placeholder: String(localized: "None"), label: "Watermark text", identifier: "document-watermark") { text in233                    let t = text.trimmingCharacters(in: .whitespacesAndNewlines)234                    update(String(localized: "Watermark")) { $0.watermark = t.isEmpty ? nil : t }235                }236                .frame(width: 150)237            }238        }239240        if index > 0, let kind = sectionBreakKind(index) {241            InspectorGroup("Section Break", id: "document.break") {242                PropertyRow("Starts on") {243                    ChoicePopup(selection: kind, options: DocumentInspector.breakKinds, width: 130, label: "Where this section starts", identifier: "document-break-kind") { k in244                        session.perform(String(localized: "Section Break")) { e in245                            var s = 0246                            for i in e.doc.body.indices {247                                if case .sectionBreak(var br) = e.doc.body[i] {248                                    s += 1249                                    if s == index { br.kind = k; e.doc.body[i] = .sectionBreak(br); return }250                                }251                            }252                        }253                        session.refocusCanvas()254                    }255                }256                InspectorNote("How section \(index + 1) begins after section \(index).")257            }258        }259260        InspectorGroup("Language and Typing", id: "document.language") {261            let lang = doc.meta.language262            PropertyRow("Language") {263                InspectorPopup(CharacterGroups.languageName(lang), width: 150, label: "Document language", identifier: "document-language") {264                    ForEach(CharacterGroups.languages, id: \.self) { tag in265                        Button {266                            // The default character language follows, so spelling and hyphenation use it wherever no other language is set.267                            session.perform(String(localized: "Document Language")) { e in e.doc.meta.language = tag; e.doc.styles.defaultChar.language = tag }268                            session.canvas?.spelling.invalidate()269                            session.refocusCanvas()270                        } label: {271                            if tag == lang { Label(CharacterGroups.languageName(tag), systemImage: "checkmark") } else { Text(CharacterGroups.languageName(tag)) }272                        }273                    }274                }275            }276            SwitchRow("Smart quotes", isOn: doc.settings.smartQuotes, identifier: "document-smart-quotes") { on in277                session.perform(String(localized: "Smart Quotes")) { $0.doc.settings.smartQuotes = on }278            }279            SwitchRow("Smart dashes", isOn: doc.settings.smartDashes) { on in280                session.perform(String(localized: "Smart Dashes")) { $0.doc.settings.smartDashes = on }281            }282            SwitchRow("Check spelling", isOn: AppSettings.shared.checkSpelling, identifier: "document-spelling") { on in283                AppSettings.shared.checkSpelling = on284                session.canvas?.needsDisplay = true285            }286            InspectorNote("Spelling is a preference of this Mac; it applies to every document.")287        }288    }289290    private func marginLabel(_ text: LocalizedStringKey) -> some View {291        Text(text).font(ORIX.Font.label).foregroundStyle(ORIX.Palette.textSecondary).lineLimit(1).fixedSize()292    }293294    private func sectionBreakKind(_ index: Int) -> SectionBreak.Kind? {295        var s = 0296        for b in session.doc.body {297            if case .sectionBreak(let br) = b { s += 1; if s == index { return br.kind } }298        }299        return nil300    }301}302
Files main
Menu

Theme