SPB Git

Repository Public

FileSheets.swift 28.3 KB 536 lines swift

1// ORIX Docs2// File: App/Sources/Sheets/FileSheets.swift3// Description: File sheets: export (format, what the format loses, PDF options), import notes, and document properties,4//              with the sheet frame and warning list they share.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import SwiftUI9import AppKit10import DocModel11import DocContainer12import DocLayout13import DocAutomation1415// MARK: - Shared pieces1617/// Title, scrolling content and a button row. Escape cancels, Return triggers the default button.18struct FileSheetFrame<Content: View, Footer: View>: View {19    let symbol: String20    let title: LocalizedStringKey21    let subtitle: Text?22    var width: CGFloat = 54023    @ViewBuilder var content: Content24    @ViewBuilder var footer: Footer2526    var body: some View {27        VStack(alignment: .leading, spacing: 0) {28            HStack(alignment: .top, spacing: ORIX.Space.m) {29                Image(systemName: symbol)30                    .font(.system(size: 15, weight: .medium)).foregroundStyle(.white)31                    .frame(width: 32, height: 32)32                    .background(RoundedRectangle(cornerRadius: ORIX.Radius.m).fill(ORIX.Palette.accentGradient))33                    .accessibilityHidden(true)34                VStack(alignment: .leading, spacing: 2) {35                    Text(title).font(ORIX.Font.title).foregroundStyle(ORIX.Palette.text).accessibilityAddTraits(.isHeader)36                    if let subtitle {37                        subtitle.font(ORIX.Font.label).foregroundStyle(ORIX.Palette.textSecondary).fixedSize(horizontal: false, vertical: true)38                    }39                }40                Spacer(minLength: 0)41            }42            .padding(.horizontal, ORIX.Space.xl).padding(.top, ORIX.Space.xl).padding(.bottom, ORIX.Space.l)43            Rectangle().fill(ORIX.Palette.hairline).frame(height: 1)44            content45            Rectangle().fill(ORIX.Palette.hairline).frame(height: 1)46            HStack(spacing: ORIX.Space.s) { footer }47                .padding(.horizontal, ORIX.Space.xl).padding(.vertical, ORIX.Space.m)48        }49        .frame(width: width)50        .background(ORIX.Palette.chrome)51    }52}5354extension FormatWarning.Severity {55    var sheetTitle: LocalizedStringKey {56        switch self { case .dropped: return "Not carried over"; case .approximated: return "Approximated"; case .info: return "For information" }57    }58    var reportTitle: String {59        switch self {60        case .dropped: return String(localized: "Not carried over")61        case .approximated: return String(localized: "Approximated")62        case .info: return String(localized: "For information")63        }64    }65    var sheetExplanation: LocalizedStringKey {66        switch self {67        case .dropped: return "Content or features that are left out."68        case .approximated: return "Content is kept; its appearance or behaviour may differ."69        case .info: return "Handled, in a way you may want to know about."70        }71    }72    var sheetSymbol: String {73        switch self { case .dropped: return "xmark.octagon.fill"; case .approximated: return "exclamationmark.triangle.fill"; case .info: return "info.circle.fill" }74    }75    var sheetColor: Color {76        switch self { case .dropped: return ORIX.Palette.critical; case .approximated: return ORIX.Palette.warning; case .info: return ORIX.Palette.textSecondary }77    }78    static let mostSevereFirst: [FormatWarning.Severity] = [.dropped, .approximated, .info]79}8081/// Conversion warnings grouped by severity, most severe first. Each group has a symbol, a title and a count (never colour alone).82struct FormatWarningList: View {83    let warnings: [FormatWarning]8485    var body: some View {86        VStack(alignment: .leading, spacing: ORIX.Space.l) {87            ForEach(FormatWarning.Severity.mostSevereFirst, id: \.self) { severity in88                let group = warnings.filter { $0.severity == severity }89                if !group.isEmpty {90                    VStack(alignment: .leading, spacing: ORIX.Space.s) {91                        HStack(alignment: .firstTextBaseline, spacing: 6) {92                            Image(systemName: severity.sheetSymbol).font(.system(size: 11)).foregroundStyle(severity.sheetColor)93                            Text(severity.sheetTitle).font(.system(size: 12, weight: .semibold)).foregroundStyle(ORIX.Palette.text)94                            Text("\(group.count)").font(ORIX.Font.caption.monospacedDigit()).foregroundStyle(ORIX.Palette.textTertiary)95                            Text(severity.sheetExplanation).font(ORIX.Font.caption).foregroundStyle(ORIX.Palette.textTertiary).lineLimit(1)96                            Spacer(minLength: 0)97                        }98                        .accessibilityElement(children: .combine).accessibilityAddTraits(.isHeader)99                        VStack(alignment: .leading, spacing: 0) {100                            ForEach(Array(group.enumerated()), id: \.element.id) { index, warning in101                                if index > 0 { Rectangle().fill(ORIX.Palette.hairline.opacity(0.7)).frame(height: 1) }102                                VStack(alignment: .leading, spacing: 2) {103                                    HStack(spacing: 6) {104                                        Text(warning.feature).font(.system(size: 11.5, weight: .semibold)).foregroundStyle(ORIX.Palette.text)105                                        if warning.count > 1 { Text("× \(warning.count)").font(ORIX.Font.caption.monospacedDigit()).foregroundStyle(ORIX.Palette.textTertiary) }106                                    }107                                    Text(warning.detail).font(ORIX.Font.label).foregroundStyle(ORIX.Palette.textSecondary)108                                        .fixedSize(horizontal: false, vertical: true).textSelection(.enabled)109                                }110                                .padding(.horizontal, ORIX.Space.m).padding(.vertical, ORIX.Space.s)111                                .frame(maxWidth: .infinity, alignment: .leading)112                            }113                        }114                        .background(RoundedRectangle(cornerRadius: ORIX.Radius.m).fill(ORIX.Palette.surface))115                        .overlay(RoundedRectangle(cornerRadius: ORIX.Radius.m).strokeBorder(ORIX.Palette.hairline))116                    }117                }118            }119        }120    }121122    static func report(_ warnings: [FormatWarning], heading: String) -> String {123        var out = heading + "\n"124        for severity in FormatWarning.Severity.mostSevereFirst {125            let group = warnings.filter { $0.severity == severity }126            guard !group.isEmpty else { continue }127            out += "\n\(severity.reportTitle) (\(group.count))\n"128            for w in group { out += "- \(w.feature)\(w.count > 1 ? " × \(w.count)" : ""): \(w.detail)\n" }129        }130        return out131    }132}133134extension DocFormat {135    var localizedName: String {136        switch self {137        case .orixdoc: return String(localized: "ORIX Docs")138        case .docx: return String(localized: "Word Document")139        case .rtf: return String(localized: "Rich Text")140        case .txt: return String(localized: "Plain Text")141        case .markdown: return String(localized: "Markdown")142        case .html: return String(localized: "Web Page")143        case .pdf: return String(localized: "PDF")144        }145    }146    var exportSymbol: String {147        switch self {148        case .orixdoc: return "doc.text.fill"149        case .docx: return "doc.richtext"150        case .rtf: return "textformat"151        case .txt: return "text.alignleft"152        case .markdown: return "number"153        case .html: return "globe"154        case .pdf: return "doc.viewfinder"155        }156    }157}158159// MARK: - Export160161struct ExportSheet: View {162    let session: DocumentSession163    @State private var format: DocFormat = .pdf164    @State private var warnings: [FormatWarning] = []165    @State private var includeOutline = true166    @State private var tagged = true167    @State private var cropMarks = false168    @State private var bleed: Double = 9169    @State private var limitPages = false170    @State private var firstPage = 1171    @State private var lastPage = 1172173    init(session: DocumentSession) { self.session = session }174175    var body: some View {176        let pageCount = max(1, session.layout.pageCount)177        FileSheetFrame(symbol: "square.and.arrow.up", title: "Export", subtitle: Text("Writes a copy in another format. This document stays open and unchanged."), width: 700) {178            HStack(alignment: .top, spacing: 0) {179                VStack(alignment: .leading, spacing: 2) {180                    ForEach(DocumentConverter.exportFormats, id: \.self) { f in181                        ExportFormatRow(format: f, isSelected: f == format) { format = f }182                    }183                }184                .padding(ORIX.Space.s)185                .frame(width: 264)186                Rectangle().fill(ORIX.Palette.hairline).frame(width: 1)187                ScrollView {188                    VStack(alignment: .leading, spacing: ORIX.Space.l) {189                        if format == .pdf { pdfOptions(pageCount: pageCount) }190                        VStack(alignment: .leading, spacing: ORIX.Space.s) {191                            Text("What this format changes").font(ORIX.Font.sectionTitle).textCase(.uppercase).kerning(0.6)192                                .foregroundStyle(ORIX.Palette.textTertiary).accessibilityAddTraits(.isHeader)193                            if warnings.isEmpty {194                                Label {195                                    Text(format == .orixdoc ? "Nothing is lost: the native format stores the complete document."196                                         : "Nothing in this document is lost or approximated in this format.")197                                } icon: { Image(systemName: "checkmark.circle.fill").foregroundStyle(ORIX.Palette.positive) }198                                    .font(ORIX.Font.label).foregroundStyle(ORIX.Palette.textSecondary)199                                    .accessibilityIdentifier("export-no-loss")200                            } else {201                                FormatWarningList(warnings: warnings).accessibilityIdentifier("export-warnings")202                            }203                        }204                    }205                    .padding(ORIX.Space.l)206                    .frame(maxWidth: .infinity, alignment: .leading)207                }208            }209            .frame(height: 380)210        } footer: {211            Text(summary).font(ORIX.Font.caption).foregroundStyle(ORIX.Palette.textTertiary).lineLimit(1)212            Spacer()213            Button("Cancel") { session.activeSheet = nil }214                .buttonStyle(ORIXButtonStyle(prominent: false)).keyboardShortcut(.cancelAction)215                .accessibilityIdentifier("export-cancel")216            Button("Export…") { export(pageCount: pageCount) }217                .buttonStyle(ORIXButtonStyle()).keyboardShortcut(.defaultAction)218                .accessibilityIdentifier("export-confirm")219        }220        .onAppear { lastPage = pageCount; refresh() }221        .onChange(of: format) { _, _ in refresh() }222        .accessibilityIdentifier("export-sheet")223    }224225    private var summary: String {226        let dropped = warnings.filter { $0.severity == .dropped }.count, approximated = warnings.filter { $0.severity == .approximated }.count227        if dropped == 0 && approximated == 0 { return "" }228        return String(localized: "\(dropped) not carried over · \(approximated) approximated")229    }230231    private func refresh() { warnings = DocumentConverter.preflight(session.doc, format: format) }232233    @ViewBuilder234    private func pdfOptions(pageCount: Int) -> some View {235        VStack(alignment: .leading, spacing: ORIX.Space.s) {236            Text("PDF options").font(ORIX.Font.sectionTitle).textCase(.uppercase).kerning(0.6).foregroundStyle(ORIX.Palette.textTertiary)237                .accessibilityAddTraits(.isHeader)238            VStack(alignment: .leading, spacing: ORIX.Space.s) {239                Toggle("Bookmarks from headings", isOn: $includeOutline).accessibilityIdentifier("export-pdf-outline")240                Toggle("Structure tags for assistive technologies", isOn: $tagged)241                    .help("Tags headings, paragraphs, tables and figures with their alternative text. Conformance to PDF/UA is not claimed.")242                    .accessibilityIdentifier("export-pdf-tags")243                HStack(spacing: ORIX.Space.s) {244                    Toggle("Crop marks", isOn: $cropMarks).accessibilityIdentifier("export-pdf-crop")245                    Spacer(minLength: 0)246                    Text("Bleed").foregroundStyle(cropMarks ? ORIX.Palette.textSecondary : ORIX.Palette.textTertiary)247                    NumberField(value: bleed, range: 0...72, step: 1, decimals: 1, suffix: "pt", width: 72) { bleed = $0 }248                        .disabled(!cropMarks).opacity(cropMarks ? 1 : 0.45)249                        .accessibilityLabel(Text("Bleed in points"))250                }251                HStack(spacing: ORIX.Space.s) {252                    Picker("Pages", selection: $limitPages) {253                        Text("All \(pageCount) pages").tag(false)254                        Text("Range").tag(true)255                    }256                    .pickerStyle(.segmented).labelsHidden().fixedSize()257                    .accessibilityLabel(Text("Pages")).accessibilityIdentifier("export-pdf-pages")258                    Spacer(minLength: 0)259                    if limitPages {260                        NumberField(value: Double(firstPage), range: 1...Double(pageCount), decimals: 0, width: 62) { firstPage = Int($0); lastPage = max(lastPage, firstPage) }261                            .accessibilityLabel(Text("First page"))262                        Text("to").foregroundStyle(ORIX.Palette.textSecondary)263                        NumberField(value: Double(lastPage), range: 1...Double(pageCount), decimals: 0, width: 62) { lastPage = Int($0); firstPage = min(firstPage, lastPage) }264                            .accessibilityLabel(Text("Last page"))265                    }266                }267                if limitPages && session.doc.hasTrackedChanges {268                    Text("Page numbers are those of the published PDF, where pending changes read as accepted; they can differ from the pages on screen.")269                        .font(ORIX.Font.caption).foregroundStyle(ORIX.Palette.textTertiary).fixedSize(horizontal: false, vertical: true)270                }271            }272            .font(ORIX.Font.label).toggleStyle(.checkbox).controlSize(.small)273            .padding(ORIX.Space.m)274            .frame(maxWidth: .infinity, alignment: .leading)275            .background(RoundedRectangle(cornerRadius: ORIX.Radius.m).fill(ORIX.Palette.surface))276            .overlay(RoundedRectangle(cornerRadius: ORIX.Radius.m).strokeBorder(ORIX.Palette.hairline))277        }278    }279280    private func export(pageCount: Int) {281        var options = PDFOptions()282        options.includeOutline = includeOutline283        options.tagged = tagged284        options.cropMarks = cropMarks285        options.bleed = cropMarks ? CGFloat(bleed) : 0286        if limitPages {287            let lo = min(max(1, firstPage), pageCount), hi = min(max(lo, lastPage), pageCount)288            options.pageRange = lo...hi289        }290        let chosen = format, target = session291        session.activeSheet = nil292        // The save panel is a sheet of the same window: present it once this one has left.293        DispatchQueue.main.asyncAfter(deadline: .now() + 0.45) { target.exportInteractively(format: chosen, pdfOptions: options) }294    }295}296297private struct ExportFormatRow: View {298    let format: DocFormat299    let isSelected: Bool300    let action: () -> Void301    @State private var hover = false302303    var body: some View {304        Button(action: action) {305            HStack(spacing: ORIX.Space.s) {306                Image(systemName: format.exportSymbol).font(.system(size: 12, weight: .medium)).frame(width: 18)307                    .foregroundStyle(isSelected ? ORIX.Palette.accent : ORIX.Palette.textSecondary)308                Text(format.localizedName).font(.system(size: 12, weight: isSelected ? .semibold : .regular)).foregroundStyle(ORIX.Palette.text).lineLimit(1)309                Spacer(minLength: 4)310                Text("." + format.fileExtension).font(.system(size: 10.5, design: .monospaced)).foregroundStyle(ORIX.Palette.textTertiary)311                Image(systemName: "checkmark").font(.system(size: 9, weight: .bold)).foregroundStyle(ORIX.Palette.accent).opacity(isSelected ? 1 : 0)312            }313            .padding(.horizontal, ORIX.Space.s).frame(height: 30)314            .background(RoundedRectangle(cornerRadius: ORIX.Radius.s).fill(isSelected ? ORIX.Palette.accent.opacity(0.13) : (hover ? ORIX.Palette.text.opacity(0.06) : .clear)))315            .contentShape(Rectangle())316        }317        .buttonStyle(.plain)318        .onHover { hover = $0 }319        .accessibilityLabel(Text("\(format.localizedName), .\(format.fileExtension)"))320        .accessibilityAddTraits(isSelected ? .isSelected : [])321        .accessibilityIdentifier("export-format-\(format.rawValue)")322    }323}324325// MARK: - Import notes326327struct ImportWarningsSheet: View {328    let session: DocumentSession329    @State private var copied = false330331    init(session: DocumentSession) { self.session = session }332333    var body: some View {334        let warnings = session.importWarnings335        let dropped = warnings.filter { $0.severity == .dropped }.count, approximated = warnings.filter { $0.severity == .approximated }.count336        let info = warnings.count - dropped - approximated337        FileSheetFrame(symbol: "tray.and.arrow.down", title: "Import Notes",338                       subtitle: Text("The original file was not modified. Its content opened as a new, untitled ORIX document: saving creates a separate file.")) {339            VStack(alignment: .leading, spacing: 0) {340                HStack(spacing: ORIX.Space.l) {341                    ImportCount(severity: .dropped, count: dropped)342                    ImportCount(severity: .approximated, count: approximated)343                    ImportCount(severity: .info, count: info)344                    Spacer(minLength: 0)345                }346                .padding(.horizontal, ORIX.Space.xl).padding(.vertical, ORIX.Space.m)347                Rectangle().fill(ORIX.Palette.hairline.opacity(0.7)).frame(height: 1)348                if warnings.isEmpty {349                    EmptyState(symbol: "checkmark.circle", title: "Nothing to report", message: "Everything in the file was carried over.")350                        .frame(height: 160)351                } else {352                    ScrollView {353                        FormatWarningList(warnings: warnings)354                            .padding(.horizontal, ORIX.Space.xl).padding(.vertical, ORIX.Space.l)355                    }356                    .frame(height: min(360, CGFloat(warnings.count) * 58 + 90))357                    .accessibilityIdentifier("import-warnings")358                }359            }360        } footer: {361            Button { copyReport(warnings) } label: { Label(copied ? "Copied" : "Copy Report", systemImage: copied ? "checkmark" : "doc.on.doc") }362                .buttonStyle(ORIXButtonStyle(prominent: false))363                .disabled(warnings.isEmpty).opacity(warnings.isEmpty ? 0.45 : 1)364                .accessibilityIdentifier("import-copy-report")365            Spacer()366            Button("Done") { session.activeSheet = nil }367                .buttonStyle(ORIXButtonStyle()).keyboardShortcut(.defaultAction)368                .accessibilityIdentifier("import-done")369        }370        .onExitCommand { session.activeSheet = nil }371        .accessibilityIdentifier("import-warnings-sheet")372    }373374    private func copyReport(_ warnings: [FormatWarning]) {375        let name = session.document?.displayName ?? session.doc.meta.title376        let heading = String(localized: "Import notes for “\(name)”") + "\n"377            + String(localized: "The original file was not modified; its content opened as a new ORIX document.")378        NSPasteboard.general.clearContents()379        NSPasteboard.general.setString(FormatWarningList.report(warnings, heading: heading), forType: .string)380        copied = true381        DispatchQueue.main.asyncAfter(deadline: .now() + 2) { copied = false }382    }383}384385private struct ImportCount: View {386    let severity: FormatWarning.Severity387    let count: Int388    var body: some View {389        HStack(spacing: 6) {390            Image(systemName: severity.sheetSymbol).font(.system(size: 11)).foregroundStyle(count > 0 ? severity.sheetColor : ORIX.Palette.textTertiary)391            Text("\(count)").font(.system(size: 13, weight: .semibold).monospacedDigit()).foregroundStyle(count > 0 ? ORIX.Palette.text : ORIX.Palette.textTertiary)392            Text(severity.sheetTitle).font(ORIX.Font.label).foregroundStyle(ORIX.Palette.textSecondary)393        }394        .accessibilityElement(children: .combine)395    }396}397398// MARK: - Properties399400struct PropertiesSheet: View {401    let session: DocumentSession402    @State private var title = ""403    @State private var author = ""404    @State private var subject = ""405    @State private var keywords = ""406    @State private var language = "en"407    @FocusState private var focus: Field?408409    private enum Field { case title, author, subject, keywords, language }410411    static let languages = ["en", "en-CA", "en-GB", "en-US", "fr", "fr-CA", "fr-FR", "es", "de", "it", "pt"]412413    init(session: DocumentSession) { self.session = session }414415    var body: some View {416        let meta = session.doc.meta417        let stats = session.statistics418        let languageValid = PropertiesSheet.isValidLanguage(language)419        FileSheetFrame(symbol: "info.circle", title: "Document Properties", subtitle: Text("Stored in the document and written to exported files.")) {420            VStack(alignment: .leading, spacing: ORIX.Space.l) {421                Grid(alignment: .leadingFirstTextBaseline, horizontalSpacing: ORIX.Space.m, verticalSpacing: ORIX.Space.s) {422                    row("Title") { field("Title", text: $title, .title).accessibilityIdentifier("properties-title") }423                    row("Author") { field("Author", text: $author, .author).accessibilityIdentifier("properties-author") }424                    row("Subject") { field("Subject", text: $subject, .subject).accessibilityIdentifier("properties-subject") }425                    row("Keywords") { field("Separated by commas", text: $keywords, .keywords).accessibilityIdentifier("properties-keywords") }426                    row("Language") {427                        HStack(spacing: ORIX.Space.s) {428                            TextField("en", text: $language)429                                .focused($focus, equals: .language)430                                .modifier(SidebarFieldChrome(focused: focus == .language, invalid: !languageValid))431                                .frame(width: 92)432                                .accessibilityLabel(Text("Language tag"))433                                .accessibilityIdentifier("properties-language")434                            Menu {435                                ForEach(PropertiesSheet.languages, id: \.self) { tag in436                                    Button("\(PropertiesSheet.languageName(tag)) (\(tag))") { language = tag }437                                }438                            } label: { Text(languageValid ? PropertiesSheet.languageName(language) : String(localized: "Choose…")) }439                                .menuStyle(.borderlessButton).fixedSize()440                                .accessibilityLabel(Text("Common languages"))441                            Spacer(minLength: 0)442                        }443                    }444                    if !languageValid {445                        row("") {446                            Label("Enter a language tag such as en, fr or fr-CA.", systemImage: "exclamationmark.triangle.fill")447                                .font(ORIX.Font.caption).foregroundStyle(ORIX.Palette.critical)448                        }449                    }450                    row("Created") { Text(meta.created.formatted(date: .long, time: .shortened)).font(ORIX.Font.body).foregroundStyle(ORIX.Palette.textSecondary).textSelection(.enabled) }451                    row("Modified") { Text(meta.modified.formatted(date: .long, time: .shortened)).font(ORIX.Font.body).foregroundStyle(ORIX.Palette.textSecondary).textSelection(.enabled) }452                }453                VStack(alignment: .leading, spacing: ORIX.Space.s) {454                    Text("Statistics").font(ORIX.Font.sectionTitle).textCase(.uppercase).kerning(0.6).foregroundStyle(ORIX.Palette.textTertiary)455                        .accessibilityAddTraits(.isHeader)456                    LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: ORIX.Space.s), count: 4), spacing: ORIX.Space.s) {457                        stat("Pages", session.layout.pageCount)458                        stat("Words", stats.words)459                        stat("Characters", stats.characters)460                        stat("Without spaces", stats.charactersNoSpaces)461                        stat("Paragraphs", stats.paragraphs)462                        stat("Tables", stats.tables)463                        stat("Images", stats.images)464                        stat("Equations", stats.equations)465                        stat("Notes", stats.footnotes)466                        stat("Comments", session.doc.comments.count)467                    }468                    .accessibilityIdentifier("properties-statistics")469                }470            }471            .padding(ORIX.Space.xl)472        } footer: {473            Spacer()474            Button("Cancel") { session.activeSheet = nil }475                .buttonStyle(ORIXButtonStyle(prominent: false)).keyboardShortcut(.cancelAction)476                .accessibilityIdentifier("properties-cancel")477            Button("Save") { save() }478                .buttonStyle(ORIXButtonStyle()).keyboardShortcut(.defaultAction)479                .disabled(!languageValid).opacity(languageValid ? 1 : 0.45)480                .accessibilityIdentifier("properties-save")481        }482        .onAppear {483            title = meta.title; author = meta.author; subject = meta.subject484            keywords = meta.keywords.joined(separator: ", "); language = meta.language485        }486        .accessibilityIdentifier("properties-sheet")487    }488489    private func row<C: View>(_ label: LocalizedStringKey, @ViewBuilder _ content: () -> C) -> some View {490        GridRow {491            Text(label).font(ORIX.Font.label).foregroundStyle(ORIX.Palette.textSecondary).gridColumnAlignment(.trailing)492            content()493        }494    }495496    private func field(_ prompt: LocalizedStringKey, text: Binding<String>, _ id: Field) -> some View {497        TextField(prompt, text: text).focused($focus, equals: id).modifier(SidebarFieldChrome(focused: focus == id))498    }499500    private func stat(_ label: LocalizedStringKey, _ value: Int) -> some View {501        VStack(alignment: .leading, spacing: 1) {502            Text(value.formatted()).font(.system(size: 14, weight: .semibold).monospacedDigit()).foregroundStyle(ORIX.Palette.text)503            Text(label).font(ORIX.Font.caption).foregroundStyle(ORIX.Palette.textTertiary).lineLimit(1)504        }505        .padding(.horizontal, ORIX.Space.s).padding(.vertical, 6)506        .frame(maxWidth: .infinity, alignment: .leading)507        .background(RoundedRectangle(cornerRadius: ORIX.Radius.s).fill(ORIX.Palette.surface))508        .overlay(RoundedRectangle(cornerRadius: ORIX.Radius.s).strokeBorder(ORIX.Palette.hairline))509        .accessibilityElement(children: .combine)510    }511512    /// A well-formed BCP 47 tag: a 2–3 letter language, then optional script, region or variant subtags.513    static func isValidLanguage(_ tag: String) -> Bool {514        tag.range(of: "^[A-Za-z]{2,3}(-[A-Za-z0-9]{2,8})*$", options: .regularExpression) != nil515    }516517    static func languageName(_ tag: String) -> String {518        Locale.current.localizedString(forIdentifier: tag.replacingOccurrences(of: "-", with: "_"))?.localizedCapitalized ?? tag519    }520521    private func save() {522        let clean = { (s: String) in s.trimmingCharacters(in: .whitespacesAndNewlines) }523        var meta = session.doc.meta524        meta.title = clean(title)525        meta.author = clean(author)526        meta.subject = clean(subject)527        meta.keywords = keywords.split(whereSeparator: { $0 == "," || $0 == ";" }).map { clean(String($0)) }.filter { !$0.isEmpty }528        meta.language = clean(language)529        if meta != session.doc.meta {530            let updated = meta531            session.perform(String(localized: "Document Properties")) { $0.doc.meta = updated }532        }533        session.activeSheet = nil534    }535}536
Files main
Menu

Theme