SPB Git

Repository Public

StylesInspector.swift 25.6 KB 485 lines swift

1// ORIX Docs2// File: App/Sources/Inspector/StylesInspector.swift3// Description: The Styles tab: document theme, heading numbering, live previews of paragraph and character styles (apply, update from4//              the selection, create, edit, delete) and the style editor sub-panel that reuses the Typography controls.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import SwiftUI9import DocModel10import DocLayout1112extension StyleSheet {13    /// Identifiers of the styles every document has; they cannot be deleted.14    static let builtInIDs: Set<String> = Set(StyleSheet.standard().styles.map(\.id))1516    /// Unresolved properties of a style of either kind: document defaults, then its chain.17    func chainProps(_ id: String, includingSelf: Bool = true) -> (para: ParaProps, char: CharProps) {18        var p = defaultPara, c = defaultChar19        let chain = chain(id)20        for s in includingSelf ? chain : Array(chain.dropLast()) { p.apply(s.para); c.apply(s.char) }21        return (p, c)22    }2324    /// True when `candidate` is `id` or inherits from it (it cannot become the parent of `id`).25    func inherits(_ candidate: String, from id: String) -> Bool { chain(candidate).contains { $0.id == id } }26}2728extension DocumentSession {29    func applyParagraphStyle(_ id: String) {30        perform(String(localized: "Apply Style")) { $0.setParagraphStyle(id) }31        refocusCanvas()32    }3334    func applyCharacterStyle(_ id: String?) {35        perform(String(localized: "Apply Character Style")) { $0.setCharacterStyle(id) }36        refocusCanvas()37    }3839    /// Deletes a custom style. Paragraphs and runs that use it fall back to its parent; styles based on it are re-parented.40    func deleteStyle(_ id: String) {41        guard !StyleSheet.builtInIDs.contains(id), let style = doc.styles.style(id) else { return }42        perform(String(localized: "Delete Style")) { e in43            let parent = style.basedOn.flatMap { e.doc.styles.style($0) != nil ? $0 : nil }44            e.doc.mutateEveryParagraph { p in45                if style.kind == .paragraph {46                    if p.style == id { p.style = parent ?? StyleID.normal }47                } else {48                    for i in p.runs.indices where p.runs[i].charStyle == id { p.runs[i].charStyle = parent }49                }50            }51            for i in e.doc.styles.styles.indices {52                if e.doc.styles.styles[i].basedOn == id { e.doc.styles.styles[i].basedOn = parent }53                if e.doc.styles.styles[i].next == id { e.doc.styles.styles[i].next = nil }54            }55            e.doc.styles.styles.removeAll { $0.id == id }56        }57    }5859    /// Creates a style from the formatting at the selection, based on the current style, and applies it. Returns its id.60    @discardableResult61    func createStyleFromSelection(name: String, kind: Style.Kind) -> String? {62        let trimmed = name.trimmingCharacters(in: .whitespacesAndNewlines)63        guard !trimmed.isEmpty, !doc.styles.styles.contains(where: { $0.name.caseInsensitiveCompare(trimmed) == .orderedSame }) else { return nil }64        var id = String(trimmed.unicodeScalars.filter { CharacterSet.alphanumerics.contains($0) && $0.isASCII }.map(Character.init))65        if id.isEmpty { id = "Style" }66        if doc.styles.style(id) != nil { id += "-" + DocID.make() }67        let parent = kind == .paragraph ? (editor.currentParagraph()?.style ?? StyleID.normal) : directCharacterProps.charStyle68        perform(String(localized: "New Style")) { e in69            e.doc.styles.upsert(Style(id: id, name: trimmed, kind: kind, basedOn: parent))70            e.updateStyleFromSelection(id)71            if kind == .paragraph {72                e.setParagraphStyle(id)73            } else if !e.selection.isCaret {74                // The direct formatting now lives in the style.75                e.formatCharacters { p in p = CharProps(link: p.link, language: p.language) }76                e.setCharacterStyle(id)77            }78        }79        return id80    }8182    func characterTarget(forStyle id: String) -> CharacterTarget? {83        guard let style = doc.styles.style(id) else { return nil }84        return CharacterTarget(resolved: ResolvedChar(doc.styles.chainProps(id).char), direct: style.char,85                               base: doc.styles.chainProps(id, includingSelf: false).char) { [weak self] name, key, change in86            self?.perform(name, coalesce: key) { e in87                guard var s = e.doc.styles.style(id) else { return }88                change(&s.char)89                e.doc.styles.upsert(s)90            }91        }92    }9394    func paragraphTarget(forStyle id: String) -> ParagraphTarget? {95        guard let style = doc.styles.style(id), style.kind == .paragraph else { return nil }96        return ParagraphTarget(resolved: ResolvedPara(doc.styles.chainProps(id).para), direct: style.para,97                               base: doc.styles.chainProps(id, includingSelf: false).para) { [weak self] name, key, change in98            self?.perform(name, coalesce: key) { e in99                guard var s = e.doc.styles.style(id) else { return }100                change(&s.para)101                e.doc.styles.upsert(s)102            }103        }104    }105}106107/// Remembers which styles the document uses, per document revision.108private final class StyleUsage {109    private var revision = -1110    private var used = Set<String>()111    func ids(_ session: DocumentSession) -> Set<String> {112        if revision == session.revision { return used }113        var out = Set<String>()114        session.doc.forEachParagraphEverywhere { p, _, _ in115            out.insert(p.style)116            for r in p.runs { if let c = r.charStyle { out.insert(c) } }117        }118        used = out; revision = session.revision119        return out120    }121}122123struct StylesInspector: View {124    @Bindable var session: DocumentSession125    @State private var editing: String?126    @State private var showAll = false127    @State private var namingKind: Style.Kind?128    @State private var newName = ""129    @State private var usage = StyleUsage()130131    private static let common: Set<String> = [StyleID.normal, StyleID.title, StyleID.subtitle, StyleID.heading(1), StyleID.heading(2), StyleID.heading(3),132                                              StyleID.quote, StyleID.caption, StyleID.code, StyleID.abstract]133134    var body: some View {135        let _ = session.selectionRevision136        let _ = session.revision137        if let id = editing, session.doc.styles.style(id) != nil {138            StyleEditor(session: session, styleID: id) { editing = nil }139        } else {140            list141        }142    }143144    @ViewBuilder private var list: some View {145        let styles = session.doc.styles146        let para = session.editor.currentParagraph()147        let currentStyle = para.flatMap { styles.style($0.style) }148        let charStyle = session.directCharacterProps.charStyle149        let used = usage.ids(session)150        let visible = styles.paragraphStyles.filter { showAll || used.contains($0.id) || StylesInspector.common.contains($0.id) || !StyleSheet.builtInIDs.contains($0.id) }151        let hidden = styles.paragraphStyles.count - visible.count152        let hasDirect = !(para?.props.isEmpty ?? true) || TypographyInspector.hasVisibleFormatting(session.directCharacterProps.props)153154        InspectorSection(title: "At the Selection") {155            HStack(spacing: ORIX.Space.s) {156                Image(systemName: "paragraphsign").font(.system(size: 10, weight: .semibold)).foregroundStyle(ORIX.Palette.accent).accessibilityHidden(true)157                Text(currentStyle?.name ?? "—").font(.system(size: 12, weight: .semibold)).foregroundStyle(ORIX.Palette.text).lineLimit(1)158                if let cs = charStyle, let name = styles.style(cs)?.name { Pill(text: name) }159                Spacer(minLength: 0)160                if hasDirect { Pill(text: String(localized: "Modified"), color: ORIX.Palette.secondary).help("The selection has direct formatting on top of its style") }161            }162            if let currentStyle {163                InspectorButton("Update “\(currentStyle.name)” to Match Selection", symbol: "arrow.triangle.2.circlepath", isEnabled: hasDirect, identifier: "style-update") {164                    session.perform(String(localized: "Update Style")) { $0.updateStyleFromSelection(currentStyle.id) }165                    session.refocusCanvas()166                }167                .help("Redefine the style from the formatting of the selection; every paragraph of that style follows")168            }169            if let kind = namingKind {170                newStyleForm(kind)171            } else {172                InspectorButton("New Style from Selection…", symbol: "plus", identifier: "style-new") { newName = ""; namingKind = .paragraph }173            }174        }175176        InspectorGroup("Theme", id: "styles.theme") {177            LazyVGrid(columns: [GridItem(.flexible(), spacing: ORIX.Space.s), GridItem(.flexible())], spacing: ORIX.Space.s) {178                ForEach(Theme.all) { theme in179                    ThemeCard(theme: theme, isCurrent: styles.themeName == theme.name) {180                        session.perform(String(localized: "Apply Theme")) { $0.doc.styles.applyTheme(theme) }181                        session.refocusCanvas()182                    }183                }184            }185            SwitchRow("Numbered headings", isOn: styles.style(StyleID.heading(1))?.numbered ?? false, identifier: "style-heading-numbering") { on in186                session.perform(String(localized: "Heading Numbering")) { e in187                    for level in 1...9 { if var s = e.doc.styles.style(StyleID.heading(level)) { s.numbered = on; e.doc.styles.upsert(s) } }188                }189                session.refocusCanvas()190            }191        }192193        InspectorGroup("Paragraph Styles", id: "styles.paragraph") {194            ForEach(visible) { style in195                StyleRow(session: session, style: style, isCurrent: para?.style == style.id, isEnabled: true,196                         onApply: { session.applyParagraphStyle(style.id) }, onEdit: { editing = style.id })197            }198            if hidden > 0 || showAll {199                InspectorButton(showAll ? "Show Used and Common Styles" : "Show All \(styles.paragraphStyles.count) Styles", fill: true) { showAll.toggle() }200            }201        }202203        InspectorGroup("Character Styles", id: "styles.character") {204            let caret = session.selection.isCaret205            ForEach(styles.characterStyles) { style in206                StyleRow(session: session, style: style, isCurrent: charStyle == style.id, isEnabled: !caret,207                         onApply: { session.applyCharacterStyle(charStyle == style.id ? nil : style.id) }, onEdit: { editing = style.id })208            }209            if caret {210                InspectorNote("Select text to apply a character style.", symbol: "character.cursor.ibeam")211            } else if charStyle != nil {212                InspectorButton("Remove Character Style", symbol: "xmark") { session.applyCharacterStyle(nil) }213            }214        }215    }216217    @ViewBuilder private func newStyleForm(_ kind: Style.Kind) -> some View {218        let trimmed = newName.trimmingCharacters(in: .whitespaces)219        let duplicate = session.doc.styles.styles.contains { $0.name.caseInsensitiveCompare(trimmed) == .orderedSame }220        let parentName = kind == .paragraph ? session.editor.currentParagraph().flatMap { session.doc.styles.style($0.style)?.name }221                                            : session.directCharacterProps.charStyle.flatMap { session.doc.styles.style($0)?.name }222        VStack(alignment: .leading, spacing: ORIX.Space.s) {223            Text("New style").font(ORIX.Font.caption).foregroundStyle(ORIX.Palette.textSecondary)224            TextField("Style name", text: $newName)225                .textFieldStyle(.roundedBorder).controlSize(.small)226                .onSubmit { create(kind) }227                .accessibilityIdentifier("style-new-name")228            TextSegments(items: [(Style.Kind.paragraph, String(localized: "Paragraph")), (Style.Kind.character, String(localized: "Character"))], selection: kind) { namingKind = $0 }229            if duplicate {230                InspectorNote("A style with this name already exists.", symbol: "exclamationmark.triangle", color: ORIX.Palette.warning)231            } else if let parentName {232                InspectorNote("Based on “\(parentName)”, with the formatting of the selection.")233            } else {234                InspectorNote("Takes the character formatting of the selection.")235            }236            HStack(spacing: ORIX.Space.s) {237                InspectorButton("Cancel") { namingKind = nil }238                InspectorButton("Create", isEnabled: !trimmed.isEmpty && !duplicate, prominent: true, identifier: "style-new-create") { create(kind) }239            }240        }241        .padding(ORIX.Space.s)242        .background(RoundedRectangle(cornerRadius: ORIX.Radius.m).fill(ORIX.Palette.text.opacity(0.04)))243    }244245    private func create(_ kind: Style.Kind) {246        if session.createStyleFromSelection(name: newName, kind: kind) != nil {247            namingKind = nil248            session.focusCanvas()249        }250    }251}252253// MARK: - Previews254255/// Text drawn with a style's resolved character formatting, on "paper" (documents are always printed on white).256struct StylePreviewText: View {257    let text: String258    let char: ResolvedChar259    var maxSize: CGFloat = 17260261    var body: some View {262        let size = min(maxSize, max(11, char.fontSize * 0.92))263        let base = Font.documentFamily(char.fontFamily, size: size, weight: Font.Weight(css: char.weight))264        Text(char.allCaps ? text.uppercased() : text)265            .font(char.smallCaps ? base.smallCaps() : base)266            .italic(char.italic)267            .underline(char.underline)268            .strikethrough(char.strikethrough)269            .tracking(char.tracking)270            .foregroundStyle(char.color.color)271            .lineLimit(1)272            .truncationMode(.tail)273    }274}275276private struct StyleRow: View {277    let session: DocumentSession278    let style: Style279    let isCurrent: Bool280    let isEnabled: Bool281    let onApply: () -> Void282    let onEdit: () -> Void283    @State private var hover = false284285    var body: some View {286        let props = session.doc.styles.chainProps(style.id)287        let char = ResolvedChar(props.char)288        let para = ResolvedPara(props.para)289        let custom = !StyleSheet.builtInIDs.contains(style.id)290        HStack(spacing: 0) {291            Button(action: onApply) {292                HStack(spacing: 6) {293                    if let b = para.borderLeft, b.width > 0, style.kind == .paragraph {294                        RoundedRectangle(cornerRadius: 1).fill(b.color.color).frame(width: 2, height: 18).accessibilityHidden(true)295                    }296                    if style.kind == .paragraph, style.numbered, para.outlineLevel > 0 {297                        Text(verbatim: (1...para.outlineLevel).map { _ in "1" }.joined(separator: ".")).font(.system(size: 9.5, weight: .medium).monospacedDigit())298                            .foregroundStyle(Color(hex: 0x8A8FA3)).accessibilityHidden(true)299                    }300                    StylePreviewText(text: style.name, char: char)301                    Spacer(minLength: 2)302                    if isCurrent {303                        Image(systemName: "checkmark").font(.system(size: 9.5, weight: .bold)).foregroundStyle(Color(hex: 0x4F46E5))304                    }305                }306                .padding(.leading, 9)307                .frame(maxWidth: .infinity, minHeight: 30, alignment: .leading)308                .contentShape(Rectangle())309            }310            .buttonStyle(.plain)311            .disabled(!isEnabled)312            .accessibilityLabel(Text(style.name))313            .accessibilityValue(isCurrent ? Text("Applied to the selection") : Text(""))314            .accessibilityAddTraits(isCurrent ? .isSelected : [])315            .accessibilityIdentifier("style-row-\(style.id)")316            Menu {317                Button("Edit Style…", action: onEdit)318                if style.kind == .paragraph {319                    Button("Update to Match Selection") {320                        session.perform(String(localized: "Update Style")) { $0.updateStyleFromSelection(style.id) }321                    }322                }323                if custom {324                    Divider()325                    Button("Delete Style", role: .destructive) { session.deleteStyle(style.id) }326                }327            } label: {328                Image(systemName: "ellipsis").font(.system(size: 11, weight: .semibold)).foregroundStyle(Color(hex: 0x5B6170))329                    .frame(width: 26, height: 30).contentShape(Rectangle())330            }331            .menuStyle(.button).buttonStyle(.plain).menuIndicator(.hidden).fixedSize()332            .help("Edit, update or delete this style")333            .accessibilityLabel(Text("Actions for \(style.name)"))334            .accessibilityIdentifier("style-menu-\(style.id)")335        }336        .background(RoundedRectangle(cornerRadius: ORIX.Radius.s).fill((para.shading.flatMap { $0.a > 0 && style.kind == .paragraph ? $0.color : nil }) ?? Color.white))337        .overlay(RoundedRectangle(cornerRadius: ORIX.Radius.s).strokeBorder(isCurrent ? ORIX.Palette.accent : (hover ? ORIX.Palette.textTertiary : ORIX.Palette.hairline), lineWidth: isCurrent ? 1.5 : 1))338        .opacity(isEnabled ? 1 : 0.55)339        .onHover { hover = $0 }340        .contextMenu {341            Button("Apply", action: onApply).disabled(!isEnabled)342            Button("Edit Style…", action: onEdit)343            if custom { Button("Delete Style", role: .destructive) { session.deleteStyle(style.id) } }344        }345    }346}347348private struct ThemeCard: View {349    let theme: Theme350    let isCurrent: Bool351    let action: () -> Void352    @State private var hover = false353354    var body: some View {355        Button(action: action) {356            VStack(alignment: .leading, spacing: 1) {357                HStack(alignment: .firstTextBaseline, spacing: 5) {358                    Text(verbatim: "Aa").font(Font.documentFamily(theme.headingFont, size: 17, weight: .bold)).foregroundStyle(theme.accent.color)359                    Text(verbatim: "Aa").font(Font.documentFamily(theme.bodyFont, size: 13)).foregroundStyle(theme.text.color)360                    Spacer(minLength: 0)361                    if isCurrent { Image(systemName: "checkmark.circle.fill").font(.system(size: 11)).foregroundStyle(Color(hex: 0x4F46E5)) }362                }363                Text(theme.name).font(.system(size: 11, weight: .semibold)).foregroundStyle(Color(hex: 0x16181D)).lineLimit(1)364                Text(verbatim: theme.headingFont == theme.bodyFont ? theme.bodyFont : "\(theme.headingFont) + \(theme.bodyFont)")365                    .font(.system(size: 9.5)).foregroundStyle(Color(hex: 0x5B6170)).lineLimit(1).truncationMode(.tail)366            }367            .padding(.horizontal, 8).padding(.vertical, 6)368            .frame(maxWidth: .infinity, alignment: .leading)369            .background(RoundedRectangle(cornerRadius: ORIX.Radius.m).fill(Color.white))370            .overlay(RoundedRectangle(cornerRadius: ORIX.Radius.m).strokeBorder(isCurrent ? ORIX.Palette.accent : (hover ? ORIX.Palette.textTertiary : ORIX.Palette.hairline), lineWidth: isCurrent ? 1.5 : 1))371            .contentShape(Rectangle())372        }373        .buttonStyle(.plain)374        .onHover { hover = $0 }375        .help("Headings in \(theme.headingFont), body text in \(theme.bodyFont) at \(TypographyInspector.number(theme.bodySize)) pt")376        .accessibilityLabel(Text("\(theme.name) theme: headings in \(theme.headingFont), body in \(theme.bodyFont)"))377        .accessibilityAddTraits(isCurrent ? .isSelected : [])378        .accessibilityIdentifier("theme-\(theme.name)")379    }380}381382// MARK: - Style editor383384/// Sub-panel that edits one style with the Typography controls.385struct StyleEditor: View {386    @Bindable var session: DocumentSession387    let styleID: String388    let onClose: () -> Void389390    private func update(_ name: String, _ change: @escaping (inout Style) -> Void) {391        session.perform(name) { e in392            guard var s = e.doc.styles.style(styleID) else { return }393            change(&s)394            e.doc.styles.upsert(s)395        }396    }397398    var body: some View {399        let styles = session.doc.styles400        if let style = styles.style(styleID) {401            let props = styles.chainProps(styleID)402            let char = ResolvedChar(props.char)403            let para = ResolvedPara(props.para)404            let custom = !StyleSheet.builtInIDs.contains(styleID)405            let sameKind = styles.styles.filter { $0.kind == style.kind && $0.id != styleID }406407            VStack(alignment: .leading, spacing: ORIX.Space.s) {408                HStack {409                    Button(action: onClose) {410                        HStack(spacing: 3) { Image(systemName: "chevron.left").font(.system(size: 10, weight: .semibold)); Text("Styles").font(.system(size: 11.5, weight: .medium)) }411                            .foregroundStyle(ORIX.Palette.accent).contentShape(Rectangle())412                    }413                    .buttonStyle(.plain).keyboardShortcut(.cancelAction).accessibilityIdentifier("style-editor-back")414                    Spacer()415                    Pill(text: style.kind == .paragraph ? String(localized: "Paragraph style") : String(localized: "Character style"))416                }417                HStack {418                    StylePreviewText(text: style.name, char: char, maxSize: 22)419                    Spacer(minLength: 0)420                }421                .padding(.horizontal, 10).frame(maxWidth: .infinity, minHeight: 44, alignment: .leading)422                .background(RoundedRectangle(cornerRadius: ORIX.Radius.m).fill((para.shading.flatMap { $0.a > 0 ? $0.color : nil }) ?? Color.white))423                .overlay(RoundedRectangle(cornerRadius: ORIX.Radius.m).strokeBorder(ORIX.Palette.hairline))424                .accessibilityHidden(true)425            }426            .padding(.horizontal, ORIX.Space.l).padding(.vertical, ORIX.Space.m)427            .frame(maxWidth: .infinity, alignment: .leading)428            .overlay(alignment: .bottom) { Rectangle().fill(ORIX.Palette.hairline.opacity(0.7)).frame(height: 1) }429430            InspectorGroup("Style", id: "style.definition") {431                PropertyRow("Name") {432                    InspectorTextField(text: style.name, label: "Style name", identifier: "style-editor-name") { name in433                        let t = name.trimmingCharacters(in: .whitespacesAndNewlines)434                        guard !t.isEmpty, !styles.styles.contains(where: { $0.id != styleID && $0.name.caseInsensitiveCompare(t) == .orderedSame }) else { return }435                        update(String(localized: "Rename Style")) { $0.name = t }436                    }437                    .frame(width: 168)438                }439                PropertyRow("Based on") {440                    InspectorPopup(style.basedOn.flatMap { styles.style($0)?.name } ?? String(localized: "No style"), width: 168, label: "Parent style", identifier: "style-editor-based-on") {441                        Button { update(String(localized: "Based On")) { $0.basedOn = nil } } label: {442                            if style.basedOn == nil { Label("No style", systemImage: "checkmark") } else { Text("No style") }443                        }444                        Divider()445                        ForEach(sameKind.filter { !styles.inherits($0.id, from: styleID) }) { s in446                            Button { update(String(localized: "Based On")) { $0.basedOn = s.id } } label: {447                                if style.basedOn == s.id { Label(s.name, systemImage: "checkmark") } else { Text(s.name) }448                            }449                        }450                    }451                }452                if style.kind == .paragraph {453                    PropertyRow("Next style") {454                        InspectorPopup(style.next.flatMap { styles.style($0)?.name } ?? String(localized: "Same style"), width: 168, label: "Style of the paragraph created by Return", identifier: "style-editor-next") {455                            Button { update(String(localized: "Next Style")) { $0.next = nil } } label: {456                                if style.next == nil { Label("Same style", systemImage: "checkmark") } else { Text("Same style") }457                            }458                            Divider()459                            ForEach(sameKind) { s in460                                Button { update(String(localized: "Next Style")) { $0.next = s.id } } label: {461                                    if style.next == s.id { Label(s.name, systemImage: "checkmark") } else { Text(s.name) }462                                }463                            }464                        }465                    }466                    if (1...9).contains(para.outlineLevel) {467                        SwitchRow("Numbered heading", isOn: style.numbered, identifier: "style-editor-numbered") { on in update(String(localized: "Heading Numbering")) { $0.numbered = on } }468                        InspectorNote("Outline level \(para.outlineLevel). Numbered headings are prefixed with their hierarchical number (2.1).")469                    }470                }471                if custom {472                    InspectorButton("Delete Style", symbol: "trash", identifier: "style-editor-delete") { session.deleteStyle(styleID); onClose() }473                        .help("Text using this style falls back to the style it is based on")474                }475            }476            if let target = session.characterTarget(forStyle: styleID) {477                CharacterGroups(target: target, scopeID: "style").environment(\.formatScope, .style)478            }479            if let target = session.paragraphTarget(forStyle: styleID) {480                ParagraphGroups(target: target, scopeID: "style", fontSize: char.fontSize).environment(\.formatScope, .style)481            }482        }483    }484}485
Files main
Menu

Theme