SPB Git

Repository Public

EditorToolbar.swift 13.4 KB 218 lines swift

1// SP Notes iOS2// File: Editor/EditorToolbar.swift3// Description: Formatting bar shown above the keyboard (input accessory view): one scrollable row of the most used actions, menus for4//              styles and insertions. It never takes the focus away from the text, so the selection stays where it was.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import UIKit9import SPNotesCore1011enum EditorAction: Hashable, Sendable {12    // 2.0 — blocks of SPEC §2 and input ergonomics (catalogue: Editor/InsertCatalog.swift; dispatch: NoteEditorModel+Blocks.swift)13    case insertMermaid, insertChart, insertQueryView, insertBlockRef, insertRunCode, insertBibliography, insertCanvasLink, insertCitation14    case insertPDF, insertAudio, insertDetails, insertFootnote15    case calloutKind(CalloutKind), removeCallout, codeLanguage(String)16    case taskDue(String?), taskDuePicker, taskPriority(ItemPriority?)17    case atomOpen, atomCopy, atomDelete18    case mark(String)19    case heading(Int), body, codeBlock20    case list(ListKind), indent, outdent, quote, callout21    case link, openLink22    case insertPhoto, insertCamera, insertScan, insertFile, insertDrawing, insertTable, insertRule, insertMath, insertInlineMath, insertNoteLink23    case assistant24    case undo, redo, dismissKeyboard25}2627@MainActor28final class EditorToolbar: UIInputView {29    var onAction: ((EditorAction) -> Void)?30    private let scroll = UIScrollView()31    let stack = UIStackView()32    var buttons: [EditorAction: UIButton] = [:]33    /// 2.0: the contextual part of the bar, which morphs with the block of the caret (Editor/EditorToolbar+Morph.swift).34    let morph = ToolbarMorph()35    private var styleButton: UIButton!36    private var insertButton: UIButton!37    var indentButtons: [UIButton] = []38    var openLinkButton: UIButton!39    private var assistantButton: UIButton!4041    init() {42        super.init(frame: CGRect(x: 0, y: 0, width: 320, height: 48), inputViewStyle: .keyboard)43        allowsSelfSizing = true44        translatesAutoresizingMaskIntoConstraints = false45        accessibilityIdentifier = "editor-toolbar"46        // An opaque bar: the text scrolling behind it must never show through the controls.47        let backdrop = UIVisualEffectView(effect: UIBlurEffect(style: .systemChromeMaterial))48        backdrop.frame = bounds49        backdrop.autoresizingMask = [.flexibleWidth, .flexibleHeight]50        backdrop.backgroundColor = (UIColor(named: "Surface") ?? .systemBackground).withAlphaComponent(0.92)51        addSubview(backdrop)52        build()53    }54    required init?(coder: NSCoder) { fatalError("not used") }5556    override var intrinsicContentSize: CGSize { CGSize(width: UIView.noIntrinsicMetric, height: 48) }5758    private func build() {59        scroll.showsHorizontalScrollIndicator = false60        scroll.alwaysBounceHorizontal = true61        scroll.translatesAutoresizingMaskIntoConstraints = false62        stack.axis = .horizontal63        stack.spacing = 264        stack.alignment = .center65        stack.translatesAutoresizingMaskIntoConstraints = false66        addSubview(scroll)67        scroll.addSubview(stack)68        let dismiss = makeButton("keyboard.chevron.compact.down", label: String(localized: "Masquer le clavier"), action: .dismissKeyboard)69        dismiss.translatesAutoresizingMaskIntoConstraints = false70        addSubview(dismiss)71        let separator = UIView(); separator.backgroundColor = .separator; separator.translatesAutoresizingMaskIntoConstraints = false72        addSubview(separator)73        NSLayoutConstraint.activate([74            scroll.leadingAnchor.constraint(equalTo: safeAreaLayoutGuide.leadingAnchor), scroll.topAnchor.constraint(equalTo: topAnchor), scroll.bottomAnchor.constraint(equalTo: bottomAnchor),75            scroll.trailingAnchor.constraint(equalTo: separator.leadingAnchor),76            separator.widthAnchor.constraint(equalToConstant: 0.5), separator.topAnchor.constraint(equalTo: topAnchor, constant: 8), separator.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -8),77            separator.trailingAnchor.constraint(equalTo: dismiss.leadingAnchor),78            dismiss.trailingAnchor.constraint(equalTo: safeAreaLayoutGuide.trailingAnchor, constant: -4), dismiss.centerYAnchor.constraint(equalTo: centerYAnchor),79            stack.leadingAnchor.constraint(equalTo: scroll.contentLayoutGuide.leadingAnchor, constant: 6), stack.trailingAnchor.constraint(equalTo: scroll.contentLayoutGuide.trailingAnchor, constant: -6),80            stack.topAnchor.constraint(equalTo: scroll.contentLayoutGuide.topAnchor), stack.bottomAnchor.constraint(equalTo: scroll.contentLayoutGuide.bottomAnchor),81            stack.heightAnchor.constraint(equalTo: scroll.frameLayoutGuide.heightAnchor),82            heightAnchor.constraint(equalToConstant: 48),83        ])8485        styleButton = makeMenuButton("textformat.size", label: String(localized: "Style de texte"))86        insertButton = makeMenuButton("plus.circle.fill", label: String(localized: "Insérer"))87        assistantButton = makeButton("sparkles", label: String(localized: "Assistant"), action: .assistant)88        let outdent = makeButton("decrease.indent", label: String(localized: "Diminuer le retrait"), action: .outdent)89        let indent = makeButton("increase.indent", label: String(localized: "Augmenter le retrait"), action: .indent)90        indentButtons = [outdent, indent]91        openLinkButton = makeButton("arrow.up.right.square", label: String(localized: "Ouvrir le lien"), action: .openLink)92        let items: [UIView] = [93            insertButton, styleButton, assistantButton, divider(),94            makeButton("bold", label: String(localized: "Gras"), action: .mark("bold")),95            makeButton("italic", label: String(localized: "Italique"), action: .mark("italic")),96            makeButton("underline", label: String(localized: "Souligné"), action: .mark("underline")),97            makeButton("strikethrough", label: String(localized: "Barré"), action: .mark("strike")),98            makeButton("highlighter", label: String(localized: "Surligné"), action: .mark("highlight")),99            makeButton("chevron.left.forwardslash.chevron.right", label: String(localized: "Code"), action: .mark("code")),100            divider(),101            makeButton("checklist", label: String(localized: "Liste de tâches"), action: .list(.task)),102            makeButton("list.bullet", label: String(localized: "Liste à puces"), action: .list(.bullet)),103            makeButton("list.number", label: String(localized: "Liste numérotée"), action: .list(.ordered)),104            outdent, indent,105            makeButton("text.quote", label: String(localized: "Citation"), action: .quote),106            makeButton("link", label: String(localized: "Lien"), action: .link),107            openLinkButton,108            divider(),109            makeButton("arrow.uturn.backward", label: String(localized: "Annuler"), action: .undo),110            makeButton("arrow.uturn.forward", label: String(localized: "Rétablir"), action: .redo),111        ]112        items.forEach(stack.addArrangedSubview)113        installMorph()114        rebuildMenus(context: EditorController.Context())115        update(EditorController.Context())116    }117118    private func divider() -> UIView {119        let v = UIView(); v.backgroundColor = .separator120        v.translatesAutoresizingMaskIntoConstraints = false121        v.widthAnchor.constraint(equalToConstant: 0.5).isActive = true122        v.heightAnchor.constraint(equalToConstant: 24).isActive = true123        let wrap = UIView(); wrap.translatesAutoresizingMaskIntoConstraints = false124        wrap.addSubview(v)125        NSLayoutConstraint.activate([wrap.widthAnchor.constraint(equalToConstant: 9), v.centerXAnchor.constraint(equalTo: wrap.centerXAnchor), v.centerYAnchor.constraint(equalTo: wrap.centerYAnchor), wrap.heightAnchor.constraint(equalToConstant: 44)])126        return wrap127    }128129    func baseConfiguration(_ symbol: String) -> UIButton.Configuration {130        var configuration = UIButton.Configuration.plain()131        configuration.image = UIImage(systemName: symbol, withConfiguration: UIImage.SymbolConfiguration(pointSize: 17, weight: .medium))132        configuration.contentInsets = NSDirectionalEdgeInsets(top: 10, leading: 10, bottom: 10, trailing: 10)133        configuration.baseForegroundColor = UIColor(named: "TextPrimary") ?? .label134        configuration.background.cornerRadius = 9135        return configuration136    }137138    func makeButton(_ symbol: String, label: String, action: EditorAction) -> UIButton {139        let button = UIButton(configuration: baseConfiguration(symbol), primaryAction: UIAction { [weak self] _ in self?.onAction?(action) })140        button.accessibilityLabel = label141        button.accessibilityIdentifier = "toolbar-\(symbol)"142        button.widthAnchor.constraint(greaterThanOrEqualToConstant: 44).isActive = true143        button.heightAnchor.constraint(equalToConstant: 44).isActive = true144        button.isPointerInteractionEnabled = true145        buttons[action] = button146        return button147    }148149    func makeMenuButton(_ symbol: String, label: String) -> UIButton {150        var configuration = baseConfiguration(symbol)151        if symbol == "plus.circle.fill" { configuration.baseForegroundColor = UIColor(named: "AccentColor") ?? .systemOrange }152        let button = UIButton(configuration: configuration)153        button.showsMenuAsPrimaryAction = true154        button.accessibilityLabel = label155        button.accessibilityIdentifier = "toolbar-\(symbol)"156        button.widthAnchor.constraint(greaterThanOrEqualToConstant: 44).isActive = true157        button.heightAnchor.constraint(equalToConstant: 44).isActive = true158        return button159    }160161    func menuAction(_ title: String, _ symbol: String, _ action: EditorAction, on: Bool = false) -> UIAction {162        UIAction(title: title, image: UIImage(systemName: symbol), state: on ? .on : .off) { [weak self] _ in self?.onAction?(action) }163    }164165    private func rebuildMenus(context: EditorController.Context) {166        styleButton.menu = UIMenu(title: "", children: [167            UIMenu(title: "", options: .displayInline, children: [168                menuAction(String(localized: "Texte"), "textformat", .body, on: context.blockType == "paragraph"),169                menuAction(String(localized: "Titre 1"), "1.square", .heading(1), on: context.headingLevel == 1),170                menuAction(String(localized: "Titre 2"), "2.square", .heading(2), on: context.headingLevel == 2),171                menuAction(String(localized: "Titre 3"), "3.square", .heading(3), on: context.headingLevel == 3),172            ]),173            UIMenu(title: "", options: .displayInline, children: [174                menuAction(String(localized: "Bloc de code"), "curlybraces", .codeBlock, on: context.isCode),175                menuAction(String(localized: "Citation"), "text.quote", .quote, on: context.inQuote),176                menuAction(String(localized: "Encadré"), "lightbulb", .callout, on: context.inCallout),177            ]),178            UIMenu(title: "", options: .displayInline, children: [179                menuAction(String(localized: "Indice"), "textformat.subscript", .mark("subscript"), on: context.marks.contains("subscript")),180                menuAction(String(localized: "Exposant"), "textformat.superscript", .mark("superscript"), on: context.marks.contains("superscript")),181            ]),182        ])183        // 2.0: the Insert menu comes from the shared catalogue (Média · Structure · Données · Références) — add entries there184        insertButton.menu = InsertCatalog.insertMenu { [weak self] action in self?.onAction?(action) }185    }186187    private var lastContext: EditorController.Context?188189    /// Reflects the state of the caret's paragraph and selection.190    func update(_ context: EditorController.Context) {191        let accent = UIColor(named: "AccentColor") ?? .systemOrange192        func set(_ action: EditorAction, on: Bool) {193            guard let button = buttons[action], var configuration = button.configuration else { return }194            configuration.baseForegroundColor = on ? accent : (UIColor(named: "TextPrimary") ?? .label)195            configuration.background.backgroundColor = on ? accent.withAlphaComponent(0.16) : .clear196            button.configuration = configuration197            button.accessibilityTraits = on ? [.button, .selected] : .button198        }199        for mark in ["bold", "italic", "underline", "strike", "highlight", "code"] { set(.mark(mark), on: context.marks.contains(mark)) }200        set(.list(.task), on: context.listType == "taskList")201        set(.list(.bullet), on: context.listType == "bulletList")202        set(.list(.ordered), on: context.listType == "orderedList")203        set(.quote, on: context.inQuote)204        set(.link, on: context.link != nil)205        buttons[.undo]?.isEnabled = context.canUndo206        buttons[.redo]?.isEnabled = context.canRedo207        indentButtons.forEach { $0.isHidden = context.listType == nil }208        openLinkButton.isHidden = context.link == nil209        for mark in ["bold", "italic", "underline", "strike", "highlight", "code"] { buttons[.mark(mark)]?.isEnabled = !context.isCode || mark == "code" }210        if lastContext?.blockType != context.blockType || lastContext?.headingLevel != context.headingLevel || lastContext?.inQuote != context.inQuote211            || lastContext?.inCallout != context.inCallout || lastContext?.isCode != context.isCode || lastContext?.marks != context.marks {212            rebuildMenus(context: context)213        }214        applyMorph(context, animated: lastContext != nil)215        lastContext = context216    }217}218
Files main
Menu

Theme