SPB Git

Repository Public

NoteTextView.swift 12.6 KB 211 lines swift

1// SP Notes iOS2// File: Editor/NoteTextView.swift3// Description: The UITextView (TextKit 2) of the editor: key handling, hardware keyboard shortcuts, paste, taps on checkboxes,4//              atoms and links. All document logic lives in EditorController.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import UIKit9import UniformTypeIdentifiers10import SPNotesCore1112@MainActor13final class NoteTextView: UITextView, UIGestureRecognizerDelegate {14    weak var controller: EditorController?15    /// Pictures pasted from the pasteboard (the owner stores them as attachments and inserts image atoms).16    var onPasteImages: (([UIImage]) -> Void)?17    /// Commands that need UI owned by the screen (link sheet).18    var onRequestLink: (() -> Void)?19    private lazy var tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleTap(_:)))20    private var lastWidth: CGFloat = 021    /// Called after each layout pass (the title header, a subview that scrolls with the text, follows the width).22    var onLayout: (() -> Void)?2324    func configure() {25        backgroundColor = .clear26        textContainerInset = UIEdgeInsets(top: 12, left: 18, bottom: 28, right: 18)27        textContainer.lineFragmentPadding = 028        alwaysBounceVertical = true29        keyboardDismissMode = .interactive30        adjustsFontForContentSizeCategory = true31        allowsEditingTextAttributes = false32        smartInsertDeleteType = .no33        dataDetectorTypes = []34        tintColor = UIColor(named: "AccentColor")35        accessibilityIdentifier = "note-editor"36        accessibilityLabel = String(localized: "Contenu de la note")37        tapRecognizer.delegate = self38        tapRecognizer.cancelsTouchesInView = true39        addGestureRecognizer(tapRecognizer)40        registerForTraitChanges([UITraitUserInterfaceStyle.self, UITraitPreferredContentSizeCategory.self]) { (view: NoteTextView, _) in41            view.controller?.relayout(force: true)42        }43    }4445    override func layoutSubviews() {46        super.layoutSubviews()47        if abs(bounds.width - lastWidth) > 0.5 { lastWidth = bounds.width; onLayout?(); controller?.relayout() }48    }4950    // MARK: keys5152    override func deleteBackward() {53        if controller?.handleDeleteBackward() == true { return }54        super.deleteBackward()55    }5657    override var keyCommands: [UIKeyCommand]? {58        func command(_ input: String, _ flags: UIKeyModifierFlags, _ action: Selector, _ title: String) -> UIKeyCommand {59            let c = UIKeyCommand(title: title, action: action, input: input, modifierFlags: flags)60            c.wantsPriorityOverSystemBehavior = true61            return c62        }63        // 2.0: while the slash menu is open, the arrows move in it and Escape closes it (Return is handled as typed text)64        var slashCommands: [UIKeyCommand] = []65        if controller?.slash.isActive == true {66            slashCommands = [67                command(UIKeyCommand.inputUpArrow, [], #selector(slashUpCommand), String(localized: "Élément précédent")),68                command(UIKeyCommand.inputDownArrow, [], #selector(slashDownCommand), String(localized: "Élément suivant")),69                command(UIKeyCommand.inputEscape, [], #selector(slashEscapeCommand), String(localized: "Fermer le menu")),70            ]71        }72        return slashCommands + [73            command("\t", [], #selector(indentCommand), String(localized: "Augmenter le retrait")),74            command("\t", .shift, #selector(outdentCommand), String(localized: "Diminuer le retrait")),75            command("b", .command, #selector(boldCommand), String(localized: "Gras")),76            command("i", .command, #selector(italicCommand), String(localized: "Italique")),77            command("u", .command, #selector(underlineCommand), String(localized: "Souligné")),78            command("x", [.command, .shift], #selector(strikeCommand), String(localized: "Barré")),79            command("e", .command, #selector(codeCommand), String(localized: "Code")),80            // ⇧⌘K since 2.0: ⌘K opens the command palette everywhere (the shell's menus)81            command("k", [.command, .shift], #selector(linkCommand), String(localized: "Lien")),82            command("1", [.command, .alternate], #selector(heading1Command), String(localized: "Titre 1")),83            command("2", [.command, .alternate], #selector(heading2Command), String(localized: "Titre 2")),84            command("3", [.command, .alternate], #selector(heading3Command), String(localized: "Titre 3")),85            command("0", [.command, .alternate], #selector(bodyCommand), String(localized: "Texte")),86            command("7", [.command, .shift], #selector(orderedCommand), String(localized: "Liste numérotée")),87            command("8", [.command, .shift], #selector(bulletCommand), String(localized: "Liste à puces")),88            command("9", [.command, .shift], #selector(taskCommand), String(localized: "Liste de tâches")),89        ]90    }9192    @objc private func slashUpCommand() { controller?.slash.move(-1) }93    @objc private func slashDownCommand() { controller?.slash.move(1) }94    @objc private func slashEscapeCommand() { controller?.slash.cancel() }95    @objc private func indentCommand() { if controller?.handleTab(shift: false) != true { insertText("\t") } }96    @objc private func outdentCommand() { _ = controller?.handleTab(shift: true) }97    @objc private func boldCommand() { controller?.toggleMark("bold") }98    @objc private func italicCommand() { controller?.toggleMark("italic") }99    @objc private func underlineCommand() { controller?.toggleMark("underline") }100    @objc private func strikeCommand() { controller?.toggleMark("strike") }101    @objc private func codeCommand() { controller?.toggleMark("code") }102    @objc private func linkCommand() { onRequestLink?() }103    @objc private func heading1Command() { controller?.setBlockType("heading", level: 1) }104    @objc private func heading2Command() { controller?.setBlockType("heading", level: 2) }105    @objc private func heading3Command() { controller?.setBlockType("heading", level: 3) }106    @objc private func bodyCommand() { controller?.setBlockType("paragraph") }107    @objc private func orderedCommand() { controller?.toggleList(.ordered) }108    @objc private func bulletCommand() { controller?.toggleList(.bullet) }109    @objc private func taskCommand() { controller?.toggleList(.task) }110111    // The system Format menu (B / I / U) drives the document marks.112    override func toggleBoldface(_ sender: Any?) { controller?.toggleMark("bold") }113    override func toggleItalics(_ sender: Any?) { controller?.toggleMark("italic") }114    override func toggleUnderline(_ sender: Any?) { controller?.toggleMark("underline") }115116    override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {117        if action == #selector(toggleBoldface(_:)) || action == #selector(toggleItalics(_:)) || action == #selector(toggleUnderline(_:)) {118            return isEditable && selectedRange.length > 0119        }120        if action == #selector(paste(_:)) { return isEditable && (UIPasteboard.general.hasStrings || UIPasteboard.general.hasImages || UIPasteboard.general.hasURLs) }121        return super.canPerformAction(action, withSender: sender)122    }123124    // MARK: paste (plain text keeps the document consistent; pictures become attachments)125126    override func paste(_ sender: Any?) {127        let pasteboard = UIPasteboard.general128        if pasteboard.hasImages, !pasteboard.hasStrings, let images = pasteboard.images, !images.isEmpty {129            onPasteImages?(images)130            return131        }132        if let string = pasteboard.string, !string.isEmpty {133            controller?.insertText(string.replacingOccurrences(of: "\r\n", with: "\n").replacingOccurrences(of: "\r", with: "\n"))134        } else if let url = pasteboard.url {135            controller?.insertText(url.absoluteString)136        }137    }138139    override func copy(_ sender: Any?) {140        super.copy(sender)141        normalizePasteboardText()142    }143144    override func cut(_ sender: Any?) {145        super.cut(sender)146        normalizePasteboardText()147    }148149    /// Soft breaks and attachment characters are an internal representation: other apps get ordinary newlines.150    private func normalizePasteboardText() {151        guard let string = UIPasteboard.general.string, string.contains(EditorCharacter.softBreak) || string.contains(EditorCharacter.attachment) else { return }152        let plain = string.replacingOccurrences(of: EditorCharacter.softBreak, with: "\n").replacingOccurrences(of: EditorCharacter.attachment, with: "")153        UIPasteboard.general.addItems([[UTType.utf8PlainText.identifier: plain]])154    }155156    // MARK: taps157158    private enum TapTarget { case checkbox(Int), atom(AtomAttachment, NSRange), link(String), disclosure(Int), taskBadge(Int) }159160    private func target(at point: CGPoint) -> TapTarget? {161        guard let controller, let layoutManager = textLayoutManager, let content = layoutManager.textContentManager else { return nil }162        let containerPoint = CGPoint(x: point.x - textContainerInset.left, y: point.y - textContainerInset.top)163        guard let fragment = layoutManager.textLayoutFragment(for: containerPoint) as? EditorLayoutFragment else { return nil }164        let start = content.offset(from: content.documentRange.location, to: fragment.rangeInElement.location)165        if let hit = fragment.checkboxHitRect(), hit.contains(containerPoint) { return .checkbox(start) }166        if let hit = fragment.disclosureHitRect(), hit.contains(containerPoint) { return .disclosure(start) }167        if isEditable, let hit = fragment.taskBadgeHitRect(), hit.contains(containerPoint) { return .taskBadge(start) }168        guard fragment.layoutFragmentFrame.insetBy(dx: -4, dy: 0).contains(containerPoint) else { return nil }169        let storage = controller.storage170        guard start < storage.length else { return nil }171        if let atom = storage.attribute(.attachment, at: start, effectiveRange: nil) as? AtomAttachment, atom.isBlock {172            // only when the tap is on the drawn atom, not in the empty space right of it173            if containerPoint.x <= LineGeometry(style: controller.style(at: start), theme: controller.styler.theme).textIndent + atom.bounds.width + 8 { return .atom(atom, NSRange(location: start, length: 1)) }174            return nil175        }176        guard let position = closestPosition(to: point) else { return nil }177        let offset = self.offset(from: beginningOfDocument, to: position)178        for index in [offset, offset - 1] where index >= 0 && index < storage.length {179            guard let range = textRange(from: self.position(from: beginningOfDocument, offset: index)!, to: self.position(from: beginningOfDocument, offset: index + 1)!) else { continue }180            let rect = firstRect(for: range)181            guard rect.insetBy(dx: -2, dy: -2).contains(point) else { continue }182            if let atom = storage.attribute(.attachment, at: index, effectiveRange: nil) as? AtomAttachment { return .atom(atom, NSRange(location: index, length: 1)) }183            // A link opens directly only while reading; while editing, a tap places the caret (the toolbar offers "open").184            if !isFirstResponder, let href = (storage.attribute(.spnMarks, at: index, effectiveRange: nil) as? MarksBox)?.link { return .link(href) }185        }186        return nil187    }188189    override func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {190        if gestureRecognizer === tapRecognizer { return target(at: gestureRecognizer.location(in: self)) != nil }191        return super.gestureRecognizerShouldBegin(gestureRecognizer)192    }193194    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith other: UIGestureRecognizer) -> Bool { false }195    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldBeRequiredToFailBy other: UIGestureRecognizer) -> Bool {196        // our tap wins over the text view's own tap handling when it has a target197        gestureRecognizer === tapRecognizer && other is UITapGestureRecognizer198    }199200    @objc private func handleTap(_ recognizer: UITapGestureRecognizer) {201        guard recognizer.state == .ended, let controller, let target = target(at: recognizer.location(in: self)) else { return }202        switch target {203        case .checkbox(let location): controller.toggleTask(at: location)204        case .atom(let atom, let range): controller.delegate?.editor(controller, didTapAtom: atom.node, at: range)205        case .link(let href): controller.delegate?.editor(controller, didTapLink: href)206        case .disclosure(let location): controller.toggleDetails(at: location)207        case .taskBadge(let location): controller.onTapTaskBadge?(location)208        }209    }210}211
Files main
Menu

Theme