SPB Git

Repository Public

MathEditorSheet.swift 12.2 KB 242 lines swift

1// SP Notes iOS2// File: Features/Editor/Sheets/MathEditorSheet.swift3// Description: LaTeX editor for an inline or block equation with a live native preview (SwiftMath) and a row of shortcut keys.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import SwiftMath8import SwiftUI9import UIKit1011/// Typesets LaTeX for previews.12@MainActor13enum MathPreview {14    /// The typeset equation, or nil when the source is empty or cannot be parsed.15    static func image(latex: String, display: Bool, fontSize: CGFloat, color: UIColor) -> UIImage? {16        let source = MathSource.normalize(latex)17        guard !source.isEmpty else { return nil }18        var typeset = MathImage(latex: source, fontSize: fontSize, textColor: color, labelMode: display ? .display : .text, textAlignment: .center)19        let (error, image, _) = typeset.asImage()20        guard error == nil, let image, image.size.width > 0, image.size.height > 0 else { return nil }21        return image22    }23}2425/// A shortcut key of the equation editor: inserts `text` and leaves the caret `caretOffset` characters after the insertion point.26struct MathShortcut: Identifiable, Hashable {27    var label: String28    var text: String29    var caretOffset: Int30    /// Spoken name (French).31    var name: String32    var id: String { text }3334    init(_ label: String, _ text: String, caret: Int? = nil, name: String) {35        self.label = label; self.text = text; self.caretOffset = caret ?? text.count; self.name = name36    }3738    static let all: [MathShortcut] = [39        MathShortcut("a⁄b", "\\frac{}{}", caret: 6, name: String(localized: "Fraction")),40        MathShortcut("xⁿ", "^{}", caret: 2, name: String(localized: "Exposant")),41        MathShortcut("xₙ", "_{}", caret: 2, name: String(localized: "Indice")),42        MathShortcut("√", "\\sqrt{}", caret: 6, name: String(localized: "Racine carrée")),43        MathShortcut("∑", "\\sum_{}^{}", caret: 6, name: String(localized: "Somme")),44        MathShortcut("∫", "\\int_{}^{}", caret: 6, name: String(localized: "Intégrale")),45        MathShortcut("∏", "\\prod_{}^{}", caret: 7, name: String(localized: "Produit")),46        MathShortcut("lim", "\\lim_{}", caret: 6, name: String(localized: "Limite")),47        MathShortcut("( )", "\\left(  \\right)", caret: 7, name: String(localized: "Parenthèses extensibles")),48        MathShortcut("{", "{}", caret: 1, name: String(localized: "Accolades")),49        MathShortcut("\\", "\\", name: String(localized: "Barre oblique inverse")),50        MathShortcut("α", "\\alpha ", name: "alpha"), MathShortcut("β", "\\beta ", name: "bêta"),51        MathShortcut("γ", "\\gamma ", name: "gamma"), MathShortcut("δ", "\\delta ", name: "delta"),52        MathShortcut("ε", "\\varepsilon ", name: "epsilon"), MathShortcut("θ", "\\theta ", name: "thêta"),53        MathShortcut("λ", "\\lambda ", name: "lambda"), MathShortcut("μ", "\\mu ", name: "mu"),54        MathShortcut("π", "\\pi ", name: "pi"), MathShortcut("σ", "\\sigma ", name: "sigma"),55        MathShortcut("φ", "\\varphi ", name: "phi"), MathShortcut("ω", "\\omega ", name: "oméga"),56        MathShortcut("Δ", "\\Delta ", name: String(localized: "Delta majuscule")), MathShortcut("Σ", "\\Sigma ", name: String(localized: "Sigma majuscule")),57        MathShortcut("≤", "\\leq ", name: String(localized: "Inférieur ou égal")), MathShortcut("≥", "\\geq ", name: String(localized: "Supérieur ou égal")),58        MathShortcut("≠", "\\neq ", name: String(localized: "Différent de")), MathShortcut("≈", "\\approx ", name: String(localized: "Environ égal")),59        MathShortcut("×", "\\times ", name: String(localized: "Multiplié par")), MathShortcut("·", "\\cdot ", name: String(localized: "Point médian")),60        MathShortcut("±", "\\pm ", name: String(localized: "Plus ou moins")), MathShortcut("∞", "\\infty ", name: String(localized: "Infini")),61        MathShortcut("∂", "\\partial ", name: String(localized: "Dérivée partielle")), MathShortcut("→", "\\to ", name: String(localized: "Flèche")),62        MathShortcut("∈", "\\in ", name: String(localized: "Appartient à")), MathShortcut("ℝ", "\\mathbb{R}", name: String(localized: "Ensemble des réels")),63        MathShortcut("x̂", "\\hat{}", caret: 5, name: String(localized: "Chapeau")), MathShortcut("x̄", "\\bar{}", caret: 5, name: String(localized: "Barre")),64    ]6566    /// Replaces `selection` (UTF-16 range) of `source` by the shortcut and returns the new source and caret location.67    func apply(to source: String, selection: NSRange) -> (text: String, caret: Int) {68        let ns = source as NSString69        let location = min(max(0, selection.location), ns.length)70        let clamped = NSRange(location: location, length: min(max(0, selection.length), ns.length - location))71        return (ns.replacingCharacters(in: clamped, with: text), location + (String(text.prefix(caretOffset)) as NSString).length)72    }73}7475/// Sheet editing the LaTeX of an equation. `onDone` receives the source, trimmed (empty = the caller should remove the equation).76struct MathEditorSheet: View {77    var isBlock: Bool78    var isEditing: Bool79    var onDone: (String) -> Void80    var onCancel: () -> Void8182    @State private var latex: String83    @State private var selection = NSRange(location: 0, length: 0)84    @Environment(\.colorScheme) private var colorScheme85    @ScaledMetric(relativeTo: .body) private var previewFontSize: CGFloat = 228687    init(latex: String = "", isBlock: Bool, isEditing: Bool = false, onDone: @escaping (String) -> Void, onCancel: @escaping () -> Void) {88        _latex = State(initialValue: latex)89        _selection = State(initialValue: NSRange(location: (latex as NSString).length, length: 0))90        self.isBlock = isBlock91        self.isEditing = isEditing92        self.onDone = onDone93        self.onCancel = onCancel94    }9596    private var trimmed: String { latex.trimmingCharacters(in: .whitespacesAndNewlines) }9798    var body: some View {99        NavigationStack {100            VStack(spacing: 0) {101                preview102                Divider().overlay(Color("Border"))103                LatexTextView(text: $latex, selection: $selection)104                    .frame(minHeight: 96)105                    .background(Color("Surface"))106                    .accessibilityIdentifier("math-source")107                Divider().overlay(Color("Border"))108                shortcuts109            }110            .background(Color("Background"))111            .navigationTitle(isBlock ? Text("Équation") : Text("Formule en ligne"))112            .navigationBarTitleDisplayMode(.inline)113            .toolbar {114                ToolbarItem(placement: .cancellationAction) {115                    Button { onCancel() } label: { Text("Annuler") }.accessibilityIdentifier("math-cancel")116                }117                ToolbarItem(placement: .confirmationAction) {118                    Button { onDone(trimmed) } label: { Text(isEditing ? "Terminé" : "Insérer").bold() }119                        .disabled(trimmed.isEmpty && !isEditing)120                        .accessibilityIdentifier("math-done")121                }122            }123        }124        .presentationDetents([.medium, .large])125    }126127    @ViewBuilder private var preview: some View {128        let color = UIColor(named: "TextPrimary") ?? .label129        // The typesetter draws a bitmap: resolve the colour for the current appearance (re-evaluated when colorScheme changes).130        let resolved = color.resolvedColor(with: UITraitCollection(userInterfaceStyle: colorScheme == .dark ? .dark : .light))131        Group {132            if trimmed.isEmpty {133                Text("L’aperçu de la formule apparaît ici.")134                    .font(.callout)135                    .foregroundStyle(Color("Muted"))136            } else if let image = MathPreview.image(latex: latex, display: isBlock, fontSize: previewFontSize, color: resolved) {137                ScrollView([.horizontal, .vertical]) {138                    Image(uiImage: image)139                        .padding(16)140                        .accessibilityLabel(Text("Aperçu de la formule"))141                        .accessibilityValue(Text(verbatim: trimmed))142                }143                .accessibilityIdentifier("math-preview")144            } else {145                Label { Text("LaTeX incomplet ou non reconnu") } icon: { Image(systemName: "exclamationmark.triangle") }146                    .font(.callout)147                    .foregroundStyle(Color("Warning"))148                    .accessibilityIdentifier("math-error")149            }150        }151        .frame(maxWidth: .infinity, minHeight: 110, maxHeight: 220)152        .background(Color("Background"))153    }154155    private var shortcuts: some View {156        ScrollView(.horizontal, showsIndicators: false) {157            HStack(spacing: 6) {158                ForEach(MathShortcut.all) { shortcut in159                    Button {160                        let next = shortcut.apply(to: latex, selection: selection)161                        latex = next.text162                        selection = NSRange(location: next.caret, length: 0)163                    } label: {164                        Text(verbatim: shortcut.label)165                            .font(.body.monospaced())166                            .frame(minWidth: 44, minHeight: 44)167                            .padding(.horizontal, 4)168                            .background(Color("Surface2"), in: RoundedRectangle(cornerRadius: 8))169                            .foregroundStyle(Color("TextPrimary"))170                    }171                    .buttonStyle(.plain)172                    .accessibilityLabel(Text(verbatim: shortcut.name))173                    .accessibilityIdentifier("math-key-\(shortcut.text.trimmingCharacters(in: .whitespaces))")174                }175            }176            .padding(.horizontal, 12)177            .padding(.vertical, 8)178        }179        .background(Color("Surface"))180    }181}182183/// Plain monospaced text view for LaTeX: no smart punctuation, no autocorrection, and a selection the shortcut keys can drive.184private struct LatexTextView: UIViewRepresentable {185    @Binding var text: String186    @Binding var selection: NSRange187188    func makeCoordinator() -> Coordinator { Coordinator(self) }189190    func makeUIView(context: Context) -> UITextView {191        let view = UITextView()192        view.delegate = context.coordinator193        view.font = UIFontMetrics(forTextStyle: .body).scaledFont(for: .monospacedSystemFont(ofSize: 16, weight: .regular))194        view.adjustsFontForContentSizeCategory = true195        view.textColor = UIColor(named: "TextPrimary") ?? .label196        view.tintColor = UIColor(named: "AccentColor")197        view.backgroundColor = .clear198        view.autocapitalizationType = .none199        view.autocorrectionType = .no200        view.spellCheckingType = .no201        view.smartQuotesType = .no202        view.smartDashesType = .no203        view.smartInsertDeleteType = .no204        view.keyboardType = .asciiCapable205        view.textContainerInset = UIEdgeInsets(top: 12, left: 12, bottom: 12, right: 12)206        view.accessibilityLabel = String(localized: "Source LaTeX")207        view.text = text208        view.selectedRange = clamp(selection, in: view)209        DispatchQueue.main.async { view.becomeFirstResponder() }210        return view211    }212213    func updateUIView(_ view: UITextView, context: Context) {214        context.coordinator.parent = self215        if view.text != text { view.text = text }216        let wanted = clamp(selection, in: view)217        if view.selectedRange != wanted { view.selectedRange = wanted }218    }219220    private func clamp(_ range: NSRange, in view: UITextView) -> NSRange {221        let length = (view.text as NSString).length222        let location = min(max(0, range.location), length)223        return NSRange(location: location, length: min(max(0, range.length), length - location))224    }225226    @MainActor227    final class Coordinator: NSObject, UITextViewDelegate {228        var parent: LatexTextView229        init(_ parent: LatexTextView) { self.parent = parent }230231        func textViewDidChange(_ textView: UITextView) {232            parent.text = textView.text233            parent.selection = textView.selectedRange234        }235236        func textViewDidChangeSelection(_ textView: UITextView) {237            guard parent.selection != textView.selectedRange, textView.text == parent.text else { return }238            parent.selection = textView.selectedRange239        }240    }241}242
Files main
Menu

Theme