Repository Public
1// ORIX Docs2// File: App/Sources/Sheets/EquationSheet.swift3// Description: The equation editor: LaTeX source with a live typeset preview, the parser's error shown inline, display and numbering4// options, and a palette of symbols and structures the renderer is known to typeset.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import SwiftUI9import AppKit10import DocModel11import DocMath1213struct EquationSheet: View {14 let session: DocumentSession15 /// Position of the equation being edited; nil inserts a new one.16 let existing: Position?17 private let story: StoryID18 private let typeface: MathTypeface1920 @State private var latex: String21 @State private var display: Bool22 @State private var numbered: Bool23 @State private var category: String24 @State private var controller = LatexEditorController()2526 init(session: DocumentSession, existing: Position?) {27 self.session = session28 self.existing = existing29 self.story = session.selection.story30 self.typeface = MathTypeface.matching(textFamily: session.editor.currentCharacterFormat().fontFamily)31 var source = "", isDisplay = false, isNumbered = false32 if let existing, case .equation(let e)? = session.editor.inline(at: existing, in: session.selection.story) {33 source = e.latex; isDisplay = e.display34 } else if session.pendingDisplayEquation {35 isDisplay = true; isNumbered = true36 } else if session.editor.currentParagraph()?.isEmpty ?? false {37 isDisplay = true38 }39 _latex = State(initialValue: source)40 _display = State(initialValue: isDisplay)41 _numbered = State(initialValue: isNumbered)42 _category = State(initialValue: EquationPalette.supported.first?.id ?? "")43 }4445 private var trimmed: String { latex.trimmingCharacters(in: .whitespacesAndNewlines) }4647 /// The parser's message, nil when the source typesets (or is still empty).48 private var parseError: String? {49 guard !trimmed.isEmpty else { return nil }50 return MathRenderer.validate(trimmed) ?? MathRenderer.layout(latex: trimmed, fontSize: 20, display: display, typeface: typeface).error51 }5253 private func close() { session.activeSheet = nil }5455 private func commit() {56 let source = trimmed57 guard !source.isEmpty, parseError == nil else { return }58 if let existing {59 let isDisplay = display, where_ = story60 session.perform(String(localized: "Edit Equation")) { e in61 e.updateInline(at: existing, in: where_) { inline in62 if case .equation(var eq) = inline { eq.latex = source; eq.display = isDisplay; inline = .equation(eq) }63 }64 }65 } else {66 session.insertEquation(latex: source, display: display, numbered: display && numbered)67 }68 close()69 }7071 var body: some View {72 let error = parseError73 SheetScaffold(title: existing == nil ? "Insert Equation" : "Edit Equation", symbol: "function",74 subtitle: "Write LaTeX math. The preview is typeset exactly as it will appear in the document.", width: 680,75 primaryTitle: existing == nil ? "Insert" : "Update", primaryEnabled: !trimmed.isEmpty && error == nil,76 onPrimary: commit, onCancel: close) {77 VStack(alignment: .leading, spacing: ORIX.Space.m) {78 preview(error: error)79 VStack(alignment: .leading, spacing: 3) {80 FieldLabel("LaTeX source")81 LatexEditor(text: $latex, controller: controller)82 .frame(height: 76)83 .background(RoundedRectangle(cornerRadius: ORIX.Radius.m).fill(ORIX.Palette.surface))84 .overlay(RoundedRectangle(cornerRadius: ORIX.Radius.m).strokeBorder(error == nil ? ORIX.Palette.hairline : ORIX.Palette.critical.opacity(0.7)))85 }86 HStack(spacing: ORIX.Space.l) {87 Picker("Placement", selection: $display) {88 Text("Inline").tag(false)89 Text("Display").tag(true)90 }91 .pickerStyle(.segmented).labelsHidden().fixedSize()92 .accessibilityLabel(Text("Placement")).accessibilityIdentifier("equation-display")93 .help("Inline equations sit in the line of text; display equations take their own centred line.")94 if existing == nil {95 Toggle("Numbered", isOn: $numbered)96 .toggleStyle(.checkbox).disabled(!display)97 .accessibilityIdentifier("equation-numbered")98 .help("Adds an equation number at the right margin that cross-references can target.")99 }100 Spacer()101 Text("⌘↩ inserts").font(ORIX.Font.caption).foregroundStyle(ORIX.Palette.textTertiary)102 .accessibilityLabel(Text("Command Return inserts the equation"))103 }104 palette105 }106 }107 .background {108 // Return adds a line in the source field; Command-Return commits from anywhere.109 Button("", action: commit).keyboardShortcut(.return, modifiers: .command).opacity(0).accessibilityHidden(true)110 }111 .onAppear { if session.pendingDisplayEquation { session.pendingDisplayEquation = false } }112 }113114 @ViewBuilder115 private func preview(error: String?) -> some View {116 VStack(spacing: 0) {117 ZStack {118 if trimmed.isEmpty {119 Text("The typeset equation appears here.").font(ORIX.Font.label).foregroundStyle(ORIX.Palette.textTertiary)120 } else if error == nil {121 HStack(spacing: 0) {122 MathView(latex: trimmed, fontSize: display ? 24 : 20, display: display, typeface: typeface, padding: 10)123 .accessibilityElement()124 .accessibilityLabel(Text("Equation preview"))125 .accessibilityValue(Text(verbatim: trimmed))126 if display && numbered && existing == nil {127 Text(verbatim: "(\(nextEquationNumber))").font(.system(size: 15, design: .serif)).foregroundStyle(ORIX.Palette.textSecondary)128 .padding(.trailing, ORIX.Space.l)129 .accessibilityLabel(Text("Equation number \(nextEquationNumber)"))130 }131 }132 } else {133 Text(verbatim: trimmed).font(.system(size: 12, design: .monospaced)).foregroundStyle(ORIX.Palette.textSecondary)134 .lineLimit(3).padding(.horizontal, ORIX.Space.l)135 }136 }137 .frame(maxWidth: .infinity).frame(height: 116)138 if let error {139 Rectangle().fill(ORIX.Palette.hairline).frame(height: 1)140 HStack(alignment: .firstTextBaseline, spacing: 6) {141 Image(systemName: "exclamationmark.triangle.fill").font(.system(size: 11)).foregroundStyle(ORIX.Palette.critical).accessibilityHidden(true)142 Text(verbatim: error).font(ORIX.Font.label).foregroundStyle(ORIX.Palette.text).textSelection(.enabled)143 Spacer(minLength: 0)144 }145 .padding(.horizontal, 10).padding(.vertical, 7)146 .background(ORIX.Palette.critical.opacity(0.08))147 .accessibilityElement(children: .combine)148 .accessibilityLabel(Text("LaTeX error: \(error)"))149 .accessibilityIdentifier("equation-error")150 }151 }152 .background(ORIX.Palette.surfaceRaised)153 .well()154 }155156 /// Number the new equation would take: one more than the numbered equations before the caret.157 private var nextEquationNumber: Int {158 let block = session.selection.head.path.block159 return session.numbering.captions.values.filter { $0.label == "Equation" && $0.blockIndex <= block }.count + 1160 }161162 private var palette: some View {163 let categories = EquationPalette.supported164 let current = categories.first { $0.id == category } ?? categories.first165 return VStack(alignment: .leading, spacing: ORIX.Space.s) {166 ScrollView(.horizontal, showsIndicators: false) {167 HStack(spacing: 4) {168 ForEach(categories) { c in169 let selected = c.id == current?.id170 Button { category = c.id } label: {171 HStack(spacing: 4) {172 Image(systemName: c.symbol).font(.system(size: 10, weight: .medium))173 Text(verbatim: c.title).font(.system(size: 11, weight: selected ? .semibold : .regular))174 }175 .padding(.horizontal, 9).padding(.vertical, 4)176 .foregroundStyle(selected ? Color.white : ORIX.Palette.textSecondary)177 .background(Capsule().fill(selected ? AnyShapeStyle(ORIX.Palette.accentGradient) : AnyShapeStyle(ORIX.Palette.text.opacity(0.06))))178 .contentShape(Capsule())179 }180 .buttonStyle(.plain)181 .accessibilityAddTraits(selected ? .isSelected : [])182 .accessibilityIdentifier("palette-\(c.id)")183 }184 }185 }186 ScrollView {187 if let current {188 LazyVGrid(columns: [GridItem(.adaptive(minimum: current.keyWidth, maximum: current.keyWidth * 1.6), spacing: 4)], alignment: .leading, spacing: 4) {189 ForEach(current.snippets) { snippet in190 PaletteKey(snippet: snippet, typeface: typeface, tall: current.id == "matrices" || current.id == "sums" || current.id == "fractions") {191 controller.insert(snippet.latex)192 }193 }194 }195 .padding(6)196 }197 }198 .frame(height: 150)199 .well()200 }201 }202}203204/// One key of the palette: the snippet typeset as its own label.205private struct PaletteKey: View {206 let snippet: MathSnippet207 let typeface: MathTypeface208 let tall: Bool209 let action: () -> Void210 @State private var hover = false211212 var body: some View {213 Button(action: action) {214 MathView(latex: snippet.sample, fontSize: 14, display: false, typeface: typeface, padding: 4)215 .frame(maxWidth: .infinity).frame(height: tall ? 44 : 30)216 .background(RoundedRectangle(cornerRadius: ORIX.Radius.s).fill(hover ? ORIX.Palette.accent.opacity(0.14) : ORIX.Palette.surface))217 .overlay(RoundedRectangle(cornerRadius: ORIX.Radius.s).strokeBorder(hover ? ORIX.Palette.accent.opacity(0.6) : ORIX.Palette.hairline))218 .contentShape(Rectangle())219 }220 .buttonStyle(.plain)221 .onHover { hover = $0 }222 .help(Text(verbatim: snippet.source))223 .accessibilityLabel(Text(verbatim: snippet.source))224 .accessibilityHint(Text("Inserts this LaTeX at the insertion point"))225 }226}227