SPB Git

Repository Public

EditorToolbar+Morph.swift 10.7 KB 166 lines swift

1// SP Notes iOS2// File: Editor/EditorToolbar+Morph.swift3// Description: Signature motion #2 « Morphing Editor »: the contextual part of the formatting bar follows the block of the caret.4//              Text → marks, lists, quote, link · list / task → the same plus indentation, and due date + priority for a task ·5//              code block → language only (no marks) · callout → kind · block atom → open, copy, delete. The change is a short6//              cross-dissolve with a 4 pt rise (a plain cross-fade ≤ 120 ms under Reduce Motion) and one selection haptic.7//8// Author: Simon-Pierre Boucher9// Contact: contact@spboucher.ai10import SPNotesCore11import SPNotesDesign12import UIKit1314/// State of the morphing part of the bar.15@MainActor16final class ToolbarMorph {17    var mode: BlockMode = .text18    /// Buttons that exist only in some modes.19    var contextual: [(view: UIView, modes: Set<BlockMode>)] = []20    /// Buttons of the 1.0 bar that some modes hide.21    var restricted: [(view: UIView, modes: Set<BlockMode>)] = []22    /// Views whose visibility also depends on the selection (set by `EditorToolbar.update` before the morph is applied).23    var conditional: [UIView] = []24    var dueButton: UIButton?25    var priorityButton: UIButton?26    var languageButton: UIButton?27    var calloutButton: UIButton?28    var menuSignature = ""29    /// Number of mode changes applied (tests: the haptic and the motion happen on a change of block type only).30    var transitions = 03132    /// Duration of the morph: `base`, or the reduced cross-fade.33    static func duration(reduceMotion: Bool) -> Double { NVMotion.duration(.base, reduceMotion: reduceMotion) }34}3536extension EditorToolbar {37    static let textModes: Set<BlockMode> = [.text, .list, .task, .callout]3839    func installMorph() {40        let dividers = stack.arrangedSubviews.filter { !($0 is UIButton) }41        // 1.0 buttons: marks, lists, quote and link do not apply to a code block or to a block atom42        var restricted: [(UIView, Set<BlockMode>)] = []43        for mark in ["bold", "italic", "underline", "strikethrough", "highlight", "code"] {44            if let button = buttons[.mark(mark == "strikethrough" ? "strike" : mark)] { restricted.append((button, Self.textModes)) }45        }46        for kind in [ListKind.task, .bullet, .ordered] { if let button = buttons[.list(kind)] { restricted.append((button, Self.textModes)) } }47        if let quote = buttons[.quote] { restricted.append((quote, Self.textModes)) }48        if let link = buttons[.link] { restricted.append((link, Self.textModes)) }49        if dividers.count > 1 { restricted.append((dividers[1], Self.textModes)) }50        for button in indentButtons { restricted.append((button, [.list, .task])) }51        restricted.append((openLinkButton, Self.textModes))52        morph.restricted = restricted53        morph.conditional = indentButtons + [openLinkButton]5455        // contextual buttons, right after the leading group (Insert · Style · Assistant)56        let due = makeMenuButton("calendar", label: String(localized: "Échéance de la tâche"))57        let priority = makeMenuButton("flag", label: String(localized: "Priorité de la tâche"))58        let language = makeMenuButton("chevron.left.forwardslash.chevron.right", label: String(localized: "Langage du bloc de code"))59        let callout = makeMenuButton("lightbulb", label: String(localized: "Type d’encadré"))60        let open = makeButton("slider.horizontal.3", label: String(localized: "Ouvrir le bloc"), action: .atomOpen)61        let copy = makeButton("doc.on.doc", label: String(localized: "Copier le bloc"), action: .atomCopy)62        let delete = makeButton("trash", label: String(localized: "Supprimer le bloc"), action: .atomDelete)63        morph.dueButton = due; morph.priorityButton = priority; morph.languageButton = language; morph.calloutButton = callout64        let contextual: [(UIView, Set<BlockMode>)] = [(due, [.task]), (priority, [.task]), (language, [.code]), (callout, [.callout]), (open, [.atom]), (copy, [.atom]), (delete, [.atom])]65        let anchor = dividers.first.flatMap { stack.arrangedSubviews.firstIndex(of: $0) }.map { $0 + 1 } ?? stack.arrangedSubviews.count66        for (offset, entry) in contextual.enumerated() {67            entry.0.isHidden = true68            stack.insertArrangedSubview(entry.0, at: anchor + offset)69        }70        morph.contextual = contextual71    }7273    /// Shows what applies to the block of the caret. `animated` is false for the first state.74    func applyMorph(_ context: EditorController.Context, animated: Bool) {75        rebuildMorphMenus(context)76        let mode = context.mode77        let changed = mode != morph.mode78        let apply = { [morph] in79            for (view, modes) in morph.restricted {80                if !modes.contains(mode) { view.isHidden = true }81                else if !morph.conditional.contains(where: { $0 === view }) { view.isHidden = false }82            }83            for (view, modes) in morph.contextual { view.isHidden = !modes.contains(mode) }84        }85        guard changed else { apply(); return }86        morph.mode = mode87        morph.transitions += 188        guard animated, window != nil else { apply(); return }89        let reduce = UIAccessibility.isReduceMotionEnabled90        UIView.transition(with: stack, duration: ToolbarMorph.duration(reduceMotion: reduce), options: [.transitionCrossDissolve, .allowUserInteraction, .beginFromCurrentState], animations: apply)91        if !reduce {92            stack.transform = CGAffineTransform(translationX: 0, y: 4)93            UIView.animate(withDuration: NVMotion.duration(.base, reduceMotion: false), delay: 0, usingSpringWithDamping: NVMotion.springDamping, initialSpringVelocity: 0, options: [.allowUserInteraction, .beginFromCurrentState]) {94                self.stack.transform = .identity95            }96        }97        Haptics.selection()98    }99100    /// The mode shown, and the identifiers of the visible buttons, in order (tests).101    var morphMode: BlockMode { morph.mode }102    var visibleButtonIdentifiers: [String] {103        stack.arrangedSubviews.compactMap { view in (view as? UIButton).flatMap { $0.isHidden ? nil : $0.accessibilityIdentifier } }104    }105106    private func rebuildMorphMenus(_ context: EditorController.Context) {107        let signature = "\(context.mode.rawValue)|\(context.taskDue ?? "")|\(context.taskPriority?.rawValue ?? "")|\(context.calloutKind?.rawValue ?? "")|\(context.codeLanguage ?? "")"108        guard signature != morph.menuSignature else { return }109        morph.menuSignature = signature110        let accent = UIColor(named: "AccentColor") ?? NVUIColor.accent111        let plain = UIColor(named: "TextPrimary") ?? .label112        func tint(_ button: UIButton?, on: Bool, title: String? = nil) {113            guard let button, var configuration = button.configuration else { return }114            configuration.baseForegroundColor = on ? accent : plain115            configuration.title = title116            configuration.imagePadding = title == nil ? 0 : 5117            configuration.titleTextAttributesTransformer = UIConfigurationTextAttributesTransformer { incoming in118                var outgoing = incoming119                outgoing.font = UIFont.preferredFont(forTextStyle: .footnote)120                return outgoing121            }122            button.configuration = configuration123        }124125        // task: due date126        let today = Date()127        func day(_ offset: Int) -> String { TaskItemDetail.dayString(Calendar.current.date(byAdding: .day, value: offset, to: today) ?? today) }128        let dueLabel = context.taskDue.flatMap { TaskBadge.dueLabel($0)?.text }129        tint(morph.dueButton, on: context.taskDue != nil, title: dueLabel)130        morph.dueButton?.menu = UIMenu(title: String(localized: "Échéance"), children: [131            menuAction(String(localized: "Aujourd’hui"), "sun.max", .taskDue(day(0)), on: context.taskDue == day(0)),132            menuAction(String(localized: "Demain"), "sunrise", .taskDue(day(1)), on: context.taskDue == day(1)),133            menuAction(String(localized: "Dans une semaine"), "calendar.badge.plus", .taskDue(day(7)), on: context.taskDue == day(7)),134            menuAction(String(localized: "Choisir une date…"), "calendar", .taskDuePicker),135            UIMenu(title: "", options: .displayInline, children: context.taskDue == nil ? [] : [menuAction(String(localized: "Retirer l’échéance"), "calendar.badge.minus", .taskDue(nil))]),136        ])137        // task: priority138        tint(morph.priorityButton, on: context.taskPriority != nil, title: context.taskPriority.map(TaskBadge.marks))139        morph.priorityButton?.menu = UIMenu(title: String(localized: "Priorité"), children: [140            menuAction(String(localized: "Haute"), "exclamationmark.3", .taskPriority(.high), on: context.taskPriority == .high),141            menuAction(String(localized: "Moyenne"), "exclamationmark.2", .taskPriority(.medium), on: context.taskPriority == .medium),142            menuAction(String(localized: "Basse"), "exclamationmark", .taskPriority(.low), on: context.taskPriority == .low),143            UIMenu(title: "", options: .displayInline, children: context.taskPriority == nil ? [] : [menuAction(String(localized: "Aucune priorité"), "flag.slash", .taskPriority(nil))]),144        ])145        // code: language146        let language = context.codeLanguage ?? "plaintext"147        tint(morph.languageButton, on: false, title: language == "plaintext" ? String(localized: "Texte brut") : language)148        var languages = SyntaxHighlighter.menuLanguages149        if !languages.contains(language) { languages.insert(language, at: 0) } // a language set by another editor stays selectable150        morph.languageButton?.menu = UIMenu(title: String(localized: "Langage"), children: languages.map { name in151            UIAction(title: name == "plaintext" ? String(localized: "Texte brut") : name, state: name == language ? .on : .off) { [weak self] _ in self?.onAction?(.codeLanguage(name)) }152        })153        // callout: kind154        let kind = context.calloutKind ?? .note155        tint(morph.calloutButton, on: context.calloutKind != nil, title: context.calloutKind.map { $0.defaultIcon + " " + InsertCatalog.calloutTitle($0) })156        var kinds = CalloutKind.known157        if !kinds.contains(kind) { kinds.insert(kind, at: 0) }158        morph.calloutButton?.menu = UIMenu(title: String(localized: "Type d’encadré"), children: [159            UIMenu(title: "", options: .displayInline, children: kinds.map { candidate in160                UIAction(title: candidate.defaultIcon + "  " + InsertCatalog.calloutTitle(candidate), state: candidate == context.calloutKind ? .on : .off) { [weak self] _ in self?.onAction?(.calloutKind(candidate)) }161            }),162            menuAction(String(localized: "Retirer l’encadré"), "rectangle.slash", .removeCallout),163        ])164    }165}166
Files main
Menu

Theme