1097 lines · 49.2 KB · SwiftRaw
// The writing surface: one UITextView over TextKit 1, styled live from the// core's blocks, spans and tables, with the bar above the keyboard and the// formatting panel.//// - Typing is the text view's own. After each change the host is handed the// whole text (`onChange`, which it saves on a pause) and the core is asked// to style it for the cursor, one question at a time; an answer for a text// or a cursor that has moved on since is dropped and asked again. A caret// moved asks again too: a mark is dim where the cursor is and hidden away.// - Only the lines whose blocks or spans changed are restyled, attributes// only, never while the system is composing text (dictation, Telugu,// Japanese).// - Return, a key on the bar or the panel, a ticked box, a table's cell and a// placed picture are asks of the core (`press`); its answer is written back// as its one replacement, so Undo takes back exactly that. Keys typed while// the core answers wait, and follow in order.#if canImport(UIKit)import UIKitimport UniformTypeIdentifiers/// The text view: the bar sits on it, the panel takes the keyboard's place,/// and a hardware keyboard's shortcuts reach the core.public final class WritingTextView: UITextView { var bar: UIView? var panel: UIView? var formatting = false var shortcuts: [(input: String, flags: UIKeyModifierFlags, key: WritingKey)] = [] var onShortcut: ((WritingKey) -> Void)? var onPasteImages: (([UIImage]) -> Void)? var onLayout: (() -> Void)? /// The widest the text column grows. var lineWidth: CGFloat = 680 static let margin: CGFloat = 24 override public var inputAccessoryView: UIView? { get { bar } set { bar = newValue } } override public var inputView: UIView? { get { formatting ? panel : nil } set { panel = newValue } } override public var keyCommands: [UIKeyCommand]? { shortcuts.map { shortcut in let command = UIKeyCommand(title: shortcut.key.label, action: #selector(shortcutPressed(_:)), input: shortcut.input, modifierFlags: shortcut.flags) command.wantsPriorityOverSystemBehavior = true return command } } @objc private func shortcutPressed(_ command: UIKeyCommand) { guard let shortcut = shortcuts.first(where: { $0.input == command.input && $0.flags == command.modifierFlags }) else { return } onShortcut?(shortcut.key) } // Formatting is the core's: the system's own bold, italic and underline // (the edit menu) would write attributes the text does not hold. override public func toggleBoldface(_ sender: Any?) { shortcut("bold") } override public func toggleItalics(_ sender: Any?) { shortcut("italic") } override public func toggleUnderline(_ sender: Any?) { shortcut("underline") } private func shortcut(_ id: String) { if let key = shortcuts.first(where: { $0.key.id == id })?.key { onShortcut?(key) } } override public func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool { if action == #selector(paste(_:)), UIPasteboard.general.hasImages { return true } return super.canPerformAction(action, withSender: sender) } override public func paste(_ sender: Any?) { let board = UIPasteboard.general if board.hasImages, !board.hasStrings, let images = board.images, !images.isEmpty { onPasteImages?(images) return } super.paste(sender) } override public func layoutSubviews() { super.layoutSubviews() let side = max(Self.margin, (bounds.width - lineWidth) / 2) if abs(textContainerInset.left - side) > 0.5 { textContainerInset = UIEdgeInsets(top: textContainerInset.top, left: side, bottom: textContainerInset.bottom, right: side) } onLayout?() }}@MainActorpublic final class WritingEditor: NSObject, UITextViewDelegate, @preconcurrency NSTextStorageDelegate, UIGestureRecognizerDelegate, UITextDropDelegate { public let textView: WritingTextView private let storage = NSTextStorage() private let layout = WritingLayoutManager() private let container = NSTextContainer(size: CGSize(width: 320, height: CGFloat.greatestFiniteMagnitude)) private let rules: any WritingRules private let media: (any WritingMedia)? public let words: WritingWords public private(set) var look: WritingLook private var styler: WritingStyler private let bar: WritingBar private var panel: WritingPanel? private let hint = UILabel() /// The whole text after every change the person or the core made. public var onChange: ((String) -> Void)? /// A picture tapped: its address. public var onOpenPicture: ((String) -> Void)? /// The panel's picture key: the host offers the library and the camera. public var onPicture: (() -> Void)? /// The picture key held: the camera at once (else the picture key's own offer). public var onCamera: (() -> Void)? /// A tag in the text tapped (FEEDBACK-4 C1): its name as the core reads it, `#` and a closing `#` off; the host /// opens the list of the notes that carry it. public var onOpenTag: ((String) -> Void)? /// The bar's Hide (and Return in a table's last cell): the host puts the /// keyboard away, as the app does it in one place (`KeyboardDismissal`). public var onPutAway: (() -> Void)? /// A refusal from the core, in its words. public var onError: ((Error) -> Void)? /// The notes a `[[` being typed may name, for the text and the cursor (the host's `notes.links`); nil when no `[[` is open. public var onLinkOffers: ((String, Int) async -> WritingLinkOffers?)? /// Where words stand in the text (the host's `notes.find`). public var onFind: ((String, String) async -> [NSRange])? /// A link opened from the bar's Open: an address, or `note:<title>` for a `[[note link]]`. public var onOpenLink: ((String) -> Void)? /// The links a single tap opens at once (through `onOpenLink`), rather than standing the caret in them: /// a surface that takes no keyboard has no bar to open them from (Words' read-only file). Any other link /// opens from the bar's row, as before. public var tapOpens: ((String) -> Bool)? /// Find's matches changed (the host's find bar counts them). public var onFound: (() -> Void)? /// A picture held: its address (the host offers its widths). public var onPictureHold: ((String) -> Void)? /// A picture line set to `width` (`small`, `medium`, `full`) by the core's `picture_width` button, the caret on its line. public func setPictureWidth(_ src: String, _ width: String) { guard let block = (drawn?.blocks ?? []).first(where: { $0.kind == "picture" && $0.src == src }) else { return } ask(WritingAction("picture_width", ["width": .text(width)]), at: NSRange(location: block.start, length: 0)) } /// The lines folded (each line's start); moved along by edits, unfolded when the caret walks in. public private(set) var folded: Set<Int> = [] /// Find: what is looked for (nil: Find is closed), each place it is found, the one standing. public private(set) var finding: String? public private(set) var found: [NSRange] = [] public private(set) var foundAt = 0 /// The core's last answer, and the text it was for: the overlay is laid over it again when a fold or Find changes. private var coreStyled: WritingStyled? private var coreText: String? private(set) var drawn: WritingStyled? private var dirty: NSRange? private var delta = 0 private var writing = false private var asking = false private var askAgain = false private var pressing = false private var waiting: [String?] = [] private var blocks: [String: any WritingBlockView] = [:] private var blocksMoved = true private var columnWidth: CGFloat = 0 /// How long each restyle took, in milliseconds, newest last (the 50,000 /// character measurement reads it). public private(set) var restyleTimes: [Double] = [] public init(rules: any WritingRules, media: (any WritingMedia)?, words: WritingWords, look: WritingLook) { self.rules = rules self.media = media self.words = words self.look = look self.styler = WritingStyler(look: look) storage.addLayoutManager(layout) layout.addTextContainer(container) container.widthTracksTextView = true textView = WritingTextView(frame: .zero, textContainer: container) bar = WritingBar(words: words, look: look) super.init() storage.delegate = self textView.delegate = self textView.textDropDelegate = self textView.backgroundColor = .clear textView.alwaysBounceVertical = true textView.keyboardDismissMode = .interactive textView.adjustsFontForContentSizeCategory = true textView.textContainerInset = UIEdgeInsets(top: 8, left: WritingTextView.margin, bottom: 160, right: WritingTextView.margin) textView.accessibilityIdentifier = "writing-body" textView.inputAccessoryView = bar textView.shortcuts = words.shortcuts.compactMap { shortcut in guard let key = words.key(shortcut.does) else { return nil } var flags: UIKeyModifierFlags = [] if shortcut.ctrl { flags.insert(.command) } if shortcut.shift { flags.insert(.shift) } if shortcut.alt { flags.insert(.alternate) } let input = switch shortcut.key { case "up": UIKeyCommand.inputUpArrow case "down": UIKeyCommand.inputDownArrow default: shortcut.key.lowercased() } return (input, flags, key) } textView.onShortcut = { [weak self] key in self?.press(key) } textView.onPasteImages = { [weak self] images in self?.place(images) } textView.onLayout = { [weak self] in self?.laidOut() } bar.onKey = { [weak self] key in self?.press(key) } bar.onOffer = { [weak self] offer in self?.take(offer) } bar.onLinkOffer = { [weak self] offer in self?.takeLink(offer) } bar.onOpen = { [weak self] url in self?.onOpenLink?(url) } let tap = UITapGestureRecognizer(target: self, action: #selector(tapped(_:))) tap.delegate = self textView.addGestureRecognizer(tap) hint.text = words.word("hint") hint.isAccessibilityElement = false textView.addSubview(hint) apply(look) NotificationCenter.default.addObserver(self, selector: #selector(sizeChanged), name: UIContentSizeCategory.didChangeNotification, object: nil) } // MARK: The look /// A theme or the typography changed: every run drawn again. public func apply(_ look: WritingLook) { var look = look look.traits = textView.traitCollection self.look = look styler.look = look layout.accent = look.theme.accent layout.onAccent = look.theme.onAccent layout.ring = look.theme.dim layout.mark = look.theme.rule layout.check = look.theme.check textView.tintColor = look.theme.accent textView.typingAttributes = look.base // The line width is in characters of the body (0: the whole screen). textView.lineWidth = look.type.width > 0 ? CGFloat(look.type.width) * look.body.pointSize * 0.52 : .greatestFiniteMagnitude textView.keyboardAppearance = look.theme.dark ? .dark : .light textView.indicatorStyle = look.theme.dark ? .white : .black bar.restyle(look) panel?.restyle(look) hint.font = look.font(.title) hint.textColor = look.theme.faint blocks.values.forEach { $0.removeFromSuperview() } blocks = [:] layout.blockHeights = [:] restyleAll() textView.setNeedsLayout() } @objc private func sizeChanged() { apply(look) } // MARK: The text public var text: String { storage.string } /// Lays `text` in, the caret at its start, the undo history fresh. public func load(_ text: String) { writing = true storage.setAttributedString(NSAttributedString(string: text, attributes: look.base)) textView.selectedRange = NSRange(location: 0, length: 0) writing = false drawn = nil dirty = nil delta = 0 textView.undoManager?.removeAllActions() showHint() askStyle() } /// The keyboard up, the caret at the end: a new page. public func beginWriting() { textView.selectedRange = NSRange(location: storage.length, length: 0) textView.becomeFirstResponder() } private func showHint() { hint.isHidden = storage.length > 0 let inset = textView.textContainerInset hint.frame = CGRect(x: inset.left + container.lineFragmentPadding, y: inset.top, width: max(0, textView.bounds.width - inset.left - inset.right), height: hint.font.lineHeight + 4) } // MARK: Style /// The cursor the core styles for: nil while the surface is not being /// written in (every mark hidden, as when reading). private var cursor: Int? { textView.isFirstResponder ? textView.selectedRange.location : nil } /// Asks the core to style the text for the cursor, one question at a time. private func askStyle() { guard !asking else { askAgain = true; return } asking = true let asked = storage.string let at = cursor let rules = rules Task { [weak self] in let answer: Result<WritingStyled, Error> do { answer = .success(try await rules.style(asked, cursor: at)) } catch { answer = .failure(error) } guard let self else { return } asking = false let current = asked == storage.string && at == cursor switch answer { case .success(let styled) where current: coreStyled = styled coreText = asked draw(overlaid(styled)) case .failure(let error): onError?(error) default: break } if askAgain || !current { askAgain = false askStyle() } } } /// Draws `styled` for the text as it stands: only the lines whose blocks /// or spans changed since the last drawn, and the lines typed in since. private func draw(_ styled: WritingStyled) { guard textView.markedTextRange == nil else { askAgain = true; return } let started = CACurrentMediaTime() styler.blockKeys = WritingBlockKey.keys(styled) let length = storage.length var range = dirty if let drawn { range = changed(drawn.spans, styled.spans, into: range) range = changed(drawn.blocks, styled.blocks, into: range) if drawn.tables != styled.tables { for table in drawn.tables + styled.tables { range = union(range, table.range) } } } else { range = NSRange(location: 0, length: length) } drawn = styled dirty = nil delta = 0 if let range, length > 0 { styler.style(storage, styled, in: NSIntersectionRange(range, NSRange(location: 0, length: length))) } syncBlocks() cleanTyping() // The core's reading came after the caret moved: what is offered follows it (a tag typed on). if textView.isFirstResponder { offerTags() } restyleTimes.append((CACurrentMediaTime() - started) * 1000) if restyleTimes.count > 400 { restyleTimes.removeFirst(restyleTimes.count - 400) } } /// `range` widened by every run that differs between `old` and `new`: /// the runs before the first edit are the same, the runs after it the same /// moved by what the edits added or took away. private func changed<T: WritingRanged & Equatable>(_ old: [T], _ new: [T], into range: NSRange?) -> NSRange? { var range = range var front = 0 while front < old.count, front < new.count, old[front] == new[front] { front += 1 } var o = old.count - 1 var n = new.count - 1 while o >= front, n >= front, old[o].start + delta == new[n].start, old[o].end + delta == new[n].end, Self.same(old[o], new[n]) { o -= 1; n -= 1 } if n >= front { for run in new[front...n] { range = union(range, NSRange(location: run.start, length: max(0, run.end - run.start))) } } if o >= front { for run in old[front...o] { range = union(range, NSRange(location: run.start, length: max(0, run.end - run.start))) } } return range } /// Two runs the same but for where they stand. private static func same<T: WritingRanged & Equatable>(_ a: T, _ b: T) -> Bool { if let a = a as? WritingSpan, let b = b as? WritingSpan { return a.style == b.style && a.look == b.look && a.level == b.level && a.glyph == b.glyph && a.url == b.url } if let a = a as? WritingBlock, let b = b as? WritingBlock { return a.kind == b.kind && a.depth == b.depth && a.level == b.level && a.checked == b.checked && a.number == b.number && a.title == b.title && a.src == b.src && a.content - a.start == b.content - b.start } return false } private func restyleAll() { guard storage.length > 0, let drawn else { return } styler.blockKeys = WritingBlockKey.keys(drawn) styler.style(storage, drawn, in: NSRange(location: 0, length: storage.length)) syncBlocks() } private func union(_ a: NSRange?, _ b: NSRange) -> NSRange { guard let a else { return b } return NSUnionRange(a, b) } public func textStorage(_ textStorage: NSTextStorage, didProcessEditing editedMask: NSTextStorage.EditActions, range editedRange: NSRange, changeInLength: Int) { guard editedMask.contains(.editedCharacters) else { return } // The run changed since the style was drawn, in today's offsets. let location = editedRange.location if let old = dirty { let start = old.location < location ? old.location : max(location, old.location + changeInLength) let end = NSMaxRange(old) <= location ? NSMaxRange(old) : max(location, NSMaxRange(old) + changeInLength) dirty = NSUnionRange(NSRange(location: start, length: max(0, end - start)), editedRange) } else { dirty = editedRange } delta += changeInLength blocksMoved = true // Folded lines after the edit move with it; one the edit took away goes. if !folded.isEmpty, changeInLength != 0 { folded = Set(folded.compactMap { $0 > location ? ($0 + changeInLength >= location ? $0 + changeInLength : nil) : $0 }) } } /// What is typed next carries no block, glyph, chip, hidden mark or ground of the run before it. private func cleanTyping() { var typing = textView.typingAttributes let stale: [NSAttributedString.Key] = [.writingBlock, .writingGlyph, .writingChip, .writingLink, .backgroundColor, .strikethroughStyle, .writingFolded, .writingFold] let clear = (typing[.foregroundColor] as? UIColor) == .clear let tiny = ((typing[.font] as? UIFont)?.pointSize ?? 17) < 1 guard clear || tiny || stale.contains(where: { typing[$0] != nil }) else { return } for key in stale { typing[key] = nil } if clear { typing[.foregroundColor] = look.theme.ink } if tiny { typing[.font] = look.body } textView.typingAttributes = typing } // MARK: Blocks private var column: CGFloat { container.size.width - container.lineFragmentPadding * 2 } private func syncBlocks() { guard let drawn else { return } let keys = styler.blockKeys var kept: Set<String> = [] var resized = false for block in drawn.blocks where block.kind == "picture" { guard let key = keys[block.start], let src = block.src else { continue } kept.insert(key) // A width the core now says (Small, Medium, Full): measured again. if let view = blocks[key] as? WritingImageBlock, view.share != block.pictureShare { view.share = block.pictureShare resized = true } if blocks[key] == nil { let view = WritingImageBlock(key: key, src: src, look: look) view.onOpen = { [weak self] src in self?.onOpenPicture?(src) } view.onHold = { [weak self] src in self?.onPictureHold?(src) } view.share = block.pictureShare view.onSized = { [weak self] in self?.measureBlocks() } blocks[key] = view textView.addSubview(view) view.load(from: media, width: max(column, 200)) } } if resized { layout.blockHeights = [:] measureBlocks() layout.invalidateLayout(forCharacterRange: NSRange(location: 0, length: storage.length), actualCharacterRange: nil) blocksMoved = true textView.setNeedsLayout() } for table in drawn.tables { guard let key = keys[table.start] else { continue } kept.insert(key) if let view = blocks[key] as? WritingTableBlock { view.update(table) } else { let view = WritingTableBlock(key: key, table: table, look: look, words: words) view.onAsk = { [weak self] action, selection in self?.ask(action, at: selection) } view.onPutAway = { [weak self] in self?.onPutAway?() } blocks[key] = view textView.addSubview(view) } } for (key, view) in blocks where !kept.contains(key) { view.removeFromSuperview() blocks[key] = nil layout.blockHeights[key] = nil } measureBlocks() } /// Each block's height at the column's width; a block whose height moved /// has its line laid out again. private func measureBlocks() { let width = column for (key, view) in blocks { let height = view.height(for: width) guard layout.blockHeights[key] != height else { continue } layout.blockHeights[key] = height var whole = NSRange() storage.enumerateAttribute(.writingBlock, in: NSRange(location: 0, length: storage.length)) { value, range, stop in if value as? String == key { whole = range; stop.pointee = true } } if whole.length > 0 { layout.invalidateLayout(forCharacterRange: whole, actualCharacterRange: nil) } } blocksMoved = true textView.setNeedsLayout() } /// The text view laid out: blocks put where their lines are, the /// column's width noted, the hint placed. private func laidOut() { if abs(column - columnWidth) > 0.5 { columnWidth = column measureBlocks() } showHint() guard blocksMoved, !blocks.isEmpty else { return } blocksMoved = false let inset = textView.textContainerInset for found in layout.blocks(in: container) { guard let view = blocks[found.key] else { continue } view.frame = found.rect.offsetBy(dx: inset.left, dy: inset.top) } } // MARK: The caret public func textViewDidChangeSelection(_ textView: UITextView) { guard !writing else { return } // The caret never stands inside a block's hidden text: it goes past it. let selected = textView.selectedRange if selected.length == 0, selected.location > 0, selected.location < storage.length { var whole = NSRange() if storage.attribute(.writingBlock, at: selected.location, longestEffectiveRange: &whole, in: NSRange(location: 0, length: storage.length)) != nil, whole.location < selected.location { textView.selectedRange = NSRange(location: NSMaxRange(whole), length: 0) return } } cleanTyping() unfoldAtCaret() offerTags() offerLinks() askStyle() } public func textViewDidBeginEditing(_ textView: UITextView) { askStyle() } public func textViewDidEndEditing(_ textView: UITextView) { askStyle() } // MARK: Typing public func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool { if writing { return true } // A picture comes in through `place`, never as an attachment character. if text.contains("\u{FFFC}") { return false } // The system is composing (dictation, Telugu): its text is its own. if textView.markedTextRange != nil { return true } if pressing { waiting.append(text.isEmpty ? nil : text) return false } // Return is the core's: it continues a list, and ends one on an empty item. if text == "\n" { ask(WritingAction("return"), at: range) return false } // Deleting into a block takes the whole block, as one change Undo brings back. if text.isEmpty, range.length > 0 { var whole = NSRange() if range.location < storage.length, storage.attribute(.writingBlock, at: range.location, longestEffectiveRange: &whole, in: NSRange(location: 0, length: storage.length)) != nil, whole != range { replace(NSUnionRange(whole, range), with: "") return false } } return true } public func textViewDidChange(_ textView: UITextView) { changed() } private func changed() { showHint() onChange?(storage.string) askStyle() } /// The core's answer written back as its one replacement. private func take(_ change: WritingChange) { if let said = change.replace { let length = storage.length let start = min(max(0, said.start), length) let end = min(max(start, said.end), length) replace(NSRange(location: start, length: end - start), with: said.with) } else if let text = change.text, text != storage.string { // No replacement said: the smallest one that makes the new text. let old = storage.string as NSString let new = text as NSString var prefix = 0 let shorter = min(old.length, new.length) while prefix < shorter, old.character(at: prefix) == new.character(at: prefix) { prefix += 1 } var suffix = 0 while suffix < shorter - prefix, old.character(at: old.length - 1 - suffix) == new.character(at: new.length - 1 - suffix) { suffix += 1 } replace(NSRange(location: prefix, length: old.length - prefix - suffix), with: new.substring(with: NSRange(location: prefix, length: new.length - prefix - suffix))) } if let selection = change.selection { let length = storage.length let range = selection.range let start = min(range.location, length) textView.selectedRange = NSRange(location: start, length: min(range.length, length - start)) textView.scrollRangeToVisible(textView.selectedRange) } } private func replace(_ range: NSRange, with text: String) { guard let start = textView.position(from: textView.beginningOfDocument, offset: range.location), let end = textView.position(from: start, offset: range.length), let span = textView.textRange(from: start, to: end) else { return } writing = true textView.replace(span, withText: text) writing = false changed() } private func replayWaiting() { let keys = waiting waiting = [] for (at, typed) in keys.enumerated() { switch typed { case "\n": ask(WritingAction("return"), at: textView.selectedRange) case let typed?: textView.insertText(typed) case nil: textView.deleteBackward() } // A Return among them asked the core again: the rest wait for it. if pressing { waiting = Array(keys[(at + 1)...]) + waiting break } } } // MARK: Keys /// A key from the bar, the panel or a hardware shortcut. public func press(_ key: WritingKey) { switch key.id { case "undo": textView.undoManager?.undo() case "redo": textView.undoManager?.redo() // FEEDBACK-4 C2: `#` is typed where the caret stands, as the keyboard's own would be, so the tags it may // begin are offered in the bar's quiet row above the keyboard (`offerTags`) and typing on continues it. case "tag": typeTagMark() case "hide", "hide_keyboard": setFormatting(false) onPutAway?() case "format": setFormatting(!textView.formatting) case "keyboard": setFormatting(false) case "delete": textView.deleteBackward() case "space": textView.insertText(" ") case "return": ask(WritingAction("return"), at: textView.selectedRange) case "picture", "image": onPicture?() case "camera": if let onCamera { onCamera() } else { onPicture?() } case "copy": textView.copy(nil) case "paste": textView.paste(nil) case "note_link": // The bar's [[: types the brackets; the notes it may name are offered as it is typed. textView.insertText("[[") case "fold": foldAtCaret() default: if let action = key.action { ask(action, at: textView.selectedRange) } } } /// Shows or hides the formatting panel in the keyboard's place (the bar's formatting key). public func showFormatting(_ on: Bool) { setFormatting(on) } private func setFormatting(_ on: Bool) { guard textView.formatting != on else { return } if on, panel == nil { let height = max(260, min(340, textView.window?.bounds.height ?? 800) * 0.36) let made = WritingPanel(words: words, look: look, height: height) made.onKey = { [weak self] key in self?.press(key) } panel = made textView.panel = made } textView.formatting = on bar.formatting = on textView.reloadInputViews() } /// Asks the core what `action` does to the text at `selection`, and writes its answer. public func ask(_ action: WritingAction, at selection: NSRange) { guard !pressing, textView.markedTextRange == nil else { return } pressing = true let asked = storage.string let key = action.name let ask = WritingAsk(action: action, text: asked, selection: selection) let rules = rules Task { [weak self] in let answer: Result<WritingChange, Error> do { answer = .success(try await rules.press(ask)) } catch { answer = .failure(error) } guard let self else { return } pressing = false switch answer { case .success(let change) where asked == storage.string: take(change) case .failure(let error): // The core could not answer: Return is still a new line. if key == "return", asked == storage.string { textView.insertText("\n") } onError?(error) default: break } replayWaiting() } } // MARK: Checkboxes and pictures tapped @objc private func tapped(_ tap: UITapGestureRecognizer) { if let url = tappedLink(at: tap.location(in: textView)) { onOpenLink?(url) return } if let tag = tappedTag(at: tap.location(in: textView)) { onOpenTag?(tag) return } if let line = foldMark(at: tap.location(in: textView)) { fold(line) UISelectionFeedbackGenerator().selectionChanged() return } guard let at = box(at: tap.location(in: textView)) else { return } let caret = textView.selectedRange guard !pressing else { return } pressing = true let asked = storage.string let rules = rules Task { [weak self] in do { let change = try await rules.press(WritingAsk(action: WritingAction("tick"), text: asked, start: at, end: at)) guard let self else { return } pressing = false guard asked == storage.string else { return } take(WritingChange(text: change.text, replace: change.replace, selection: WritingSelection(caret))) UISelectionFeedbackGenerator().selectionChanged() } catch { self?.pressing = false self?.onError?(error) } self?.replayWaiting() } } public func gestureRecognizerShouldBegin(_ gesture: UIGestureRecognizer) -> Bool { let point = gesture.location(in: textView) return tappedLink(at: point) != nil || tappedTag(at: point) != nil || foldMark(at: point) != nil || box(at: point) != nil } /// The tag drawn under `point` (its chip), when the host opens tags: its name. func tappedTag(at point: CGPoint) -> String? { guard onOpenTag != nil, storage.length > 0 else { return nil } let inset = textView.textContainerInset let inContainer = CGPoint(x: point.x - inset.left, y: point.y - inset.top) var fraction: CGFloat = 0 let index = min(layout.characterIndex(for: inContainer, in: container, fractionOfDistanceBetweenInsertionPoints: &fraction), storage.length - 1) var range = NSRange() guard storage.attribute(.writingChip, at: index, effectiveRange: &range) != nil, range.length > 1 else { return nil } let glyphs = layout.glyphRange(forCharacterRange: range, actualCharacterRange: nil) let drawn = layout.boundingRect(forGlyphRange: glyphs, in: container).insetBy(dx: -4, dy: -6) guard drawn.contains(inContainer) else { return nil } return Self.tagName((storage.string as NSString).substring(with: range)) } /// A tag as written (`#work`, `#two words#`), named: the marks off. static func tagName(_ written: String) -> String? { var name = Substring(written.trimmingCharacters(in: .whitespacesAndNewlines)) guard name.hasPrefix("#") else { return nil } name = name.dropFirst() if name.hasSuffix("#") { name = name.dropLast() } let trimmed = name.trimmingCharacters(in: .whitespaces) return trimmed.isEmpty ? nil : trimmed } /// `#` where the caret stands, a space before it when it would join the word before; the selection, if any, is /// replaced, as a typed key replaces it. private func typeTagMark() { if !textView.isFirstResponder { textView.becomeFirstResponder() } let at = textView.selectedRange.location let text = storage.string as NSString let joins = at > 0 && at <= text.length && ![0x20, 0x0A, 0x09].contains(text.character(at: at - 1)) textView.insertText(joins ? " #" : "#") } /// The link under `point` that a tap opens at once (`tapOpens`), drawn there: its address. private func tappedLink(at point: CGPoint) -> String? { guard let tapOpens, storage.length > 0 else { return nil } let inset = textView.textContainerInset let inContainer = CGPoint(x: point.x - inset.left, y: point.y - inset.top) var fraction: CGFloat = 0 let index = min(layout.characterIndex(for: inContainer, in: container, fractionOfDistanceBetweenInsertionPoints: &fraction), storage.length - 1) var range = NSRange() guard let url = storage.attribute(.writingLink, at: index, effectiveRange: &range) as? String, tapOpens(url) else { return nil } let glyphs = layout.glyphRange(forCharacterRange: range, actualCharacterRange: nil) let drawn = layout.boundingRect(forGlyphRange: glyphs, in: container).insetBy(dx: -4, dy: -6) return drawn.contains(inContainer) ? url : nil } /// The chevron of a line that folds under `point`, in the margin beside the line: the line's start. private func foldMark(at point: CGPoint) -> Int? { guard storage.length > 0 else { return nil } let inset = textView.textContainerInset guard point.x < inset.left + container.lineFragmentPadding + 4, point.x > inset.left - 40 else { return nil } let inContainer = CGPoint(x: inset.left + 2 - inset.left, y: point.y - inset.top) let glyph = layout.glyphIndex(for: inContainer, in: container) let index = layout.characterIndexForGlyph(at: glyph) let text = storage.string as NSString let line = text.paragraphRange(for: NSRange(location: min(index, max(0, text.length - 1)), length: 0)) guard line.location < storage.length, storage.attribute(.writingFold, at: line.location, effectiveRange: nil) != nil else { return nil } return line.location } /// The checkbox under `point`, as the character its mark starts at. private func box(at point: CGPoint) -> Int? { guard storage.length > 0 else { return nil } let inset = textView.textContainerInset let inContainer = CGPoint(x: point.x - inset.left, y: point.y - inset.top) var fraction: CGFloat = 0 let index = layout.characterIndex(for: inContainer, in: container, fractionOfDistanceBetweenInsertionPoints: &fraction) let text = storage.string as NSString let line = text.paragraphRange(for: NSRange(location: min(index, text.length - 1), length: 0)) var found: Int? storage.enumerateAttribute(.writingGlyph, in: line) { value, range, stop in guard let glyph = value as? String, glyph == "box" || glyph == "ticked" else { return } let glyphs = layout.glyphRange(forCharacterRange: range, actualCharacterRange: nil) let rect = layout.boundingRect(forGlyphRange: glyphs, in: container).insetBy(dx: -10, dy: -8) if rect.contains(inContainer) { found = range.location stop.pointee = true } } return found } // MARK: Tags private var offering: String? /// The tag typed before the caret, `#` and all, and where it stands; /// nil when the caret is not in one. private var typedTag: (String, NSRange)? { let selected = textView.selectedRange guard selected.length == 0, selected.location > 0, let drawn else { return nil } let text = storage.string as NSString // A tag the core already reads at the caret. if let span = drawn.spans.first(where: { $0.style == "tag" && $0.start < selected.location && $0.end >= selected.location }) { let range = NSRange(location: span.start, length: selected.location - span.start) return (text.substring(with: range), range) } // A tag being typed that the core has not read yet (FEEDBACK-4 C2: typing on continues it, its offers kept): // back from the caret over a word to a `#` that starts it, at the text's start or after a space or a line. let spaces: Set<unichar> = [0x20, 0x0A, 0x09] var start = selected.location while start > 0, !spaces.contains(text.character(at: start - 1)), text.character(at: start - 1) != 0x23 { start -= 1 } guard start > 0, text.character(at: start - 1) == 0x23 else { return nil } let mark = start - 1 guard mark == 0 || spaces.contains(text.character(at: mark - 1)) else { return nil } let range = NSRange(location: mark, length: selected.location - mark) return (text.substring(with: range), range) } private func offerTags() { guard let (typed, _) = typedTag else { if offering != nil { offering = nil; bar.offer([]) } return } guard typed != offering else { return } offering = typed let rules = rules Task { [weak self] in let offers = (try? await rules.tags(String(typed.dropFirst()))) ?? [] guard let self, offering == typed else { return } bar.offer(offers) } } /// A tag offered, picked: written in place of what was typed, as the /// core writes a tag, one change Undo takes back. private func take(_ offer: WritingTagOffer) { offering = nil bar.offer([]) guard let (_, typed) = typedTag else { return } let written = rules.written(offer.tag) + " " replace(typed, with: written) textView.selectedRange = NSRange(location: typed.location + (written as NSString).length, length: 0) } // MARK: Note links private var linkAsk = 0 /// The offers standing, and the text they were for. private var linkOffers: (offers: WritingLinkOffers, text: String)? /// The notes a `[[` being typed may name, in the bar (the core decides whether one is open); the caret in a /// link, the bar's Open. private func offerLinks() { let caret = textView.selectedRange let current = coreText == storage.string ? coreStyled : nil bar.openHere(caret.length == 0 ? WritingOverlay.linkAt(current, at: caret.location) : nil) guard caret.length == 0, typedTag == nil, let ask = onLinkOffers else { if linkOffers != nil { linkOffers = nil; bar.offerLinks([]) } return } linkAsk += 1 let n = linkAsk let text = storage.string Task { [weak self] in let offers = await ask(text, caret.location) guard let self, n == linkAsk else { return } linkOffers = offers.map { ($0, text) } bar.offerLinks(offers?.offers.map { WritingTagOffer(tag: $0.id, label: $0.title) } ?? []) } } /// A note offered for a `[[`, picked: the core's `with` written in place of what was typed, the cursor where it says. private func takeLink(_ picked: WritingTagOffer) { defer { linkOffers = nil; bar.offerLinks([]) } guard let (offers, text) = linkOffers, text == storage.string, let offer = offers.offers.first(where: { $0.id == picked.tag }), NSMaxRange(offers.replace) <= storage.length else { return } replace(offers.replace, with: offer.with) textView.selectedRange = NSRange(location: min(offer.cursor, storage.length), length: 0) } // MARK: Folds and Find /// The core's runs with the overlay laid over them, in order. private func overlaid(_ styled: WritingStyled) -> WritingStyled { let extra = WritingOverlay.spans(length: storage.length, folds: styled.folds, folded: folded, found: found, current: foundAt) guard !extra.isEmpty else { return styled } var out = styled out.spans = (styled.spans + extra).enumerated().sorted { a, b in a.element.start != b.element.start ? a.element.start < b.element.start : a.offset < b.offset }.map(\.element) return out } /// A fold or Find changed: the overlay laid again over the core's last answer, or the core asked again. private func refreshOverlay() { if let coreStyled, coreText == storage.string, textView.markedTextRange == nil { draw(overlaid(coreStyled)) } else { askStyle() } } /// Where the text folds, as the core last said for this very text. private var folds: [WritingFold] { coreText == storage.string ? coreStyled?.folds ?? [] : [] } /// Fold or unfold the line starting at `line`. public func fold(_ line: Int) { if folded.contains(line) { folded.remove(line) } else { folded.insert(line) } // The caret never stays inside what folds away: it goes to the folding line's end. if let f = folds.first(where: { $0.line == line }), folded.contains(line) { let at = textView.selectedRange.location if at >= f.start, at <= f.end { textView.selectedRange = NSRange(location: max(f.line, f.start - 1), length: 0) } } refreshOverlay() } /// Fold: the section the caret stands in (its heading, or the list item it is under). private func foldAtCaret() { let at = textView.selectedRange.location guard let f = folds.last(where: { $0.line <= at && (at <= $0.end || folded.contains($0.line)) }) else { return } fold(f.line) } /// The caret walking into a folded section unfolds it, so no words are typed unseen. private func unfoldAtCaret() { guard !folded.isEmpty else { return } let at = textView.selectedRange.location let opened = folds.filter { folded.contains($0.line) && at >= $0.start && at <= $0.end } guard !opened.isEmpty else { return } for f in opened { folded.remove(f.line) } refreshOverlay() } /// Find: what is looked for (nil closes Find); the first match shown. public func find(_ words: String?) { finding = words foundAt = 0 guard let words, !words.isEmpty, let ask = onFind else { found = [] refreshOverlay() onFound?() return } let text = storage.string Task { [weak self] in let matches = await ask(text, words) guard let self, finding == words, storage.string == text else { return } found = matches foundAt = 0 refreshOverlay() showFound() onFound?() } } /// The match before or after the one standing. public func findNext(_ by: Int) { guard !found.isEmpty else { return } foundAt = (foundAt + by + found.count) % found.count refreshOverlay() showFound() onFound?() } private func showFound() { guard foundAt < found.count else { return } let r = found[foundAt] // A match in a folded section unfolds it first. let shut = folds.filter { folded.contains($0.line) && r.location >= $0.start && r.location <= $0.end } if !shut.isEmpty { for f in shut { folded.remove(f.line) } refreshOverlay() } layout.ensureLayout(forCharacterRange: r) textView.scrollRangeToVisible(r) } /// Jump to `at` (a heading from Info's contents): the caret there, the line in view. public func show(_ at: Int) { let at = min(max(0, at), storage.length) textView.selectedRange = NSRange(location: at, length: 0) layout.ensureLayout(forCharacterRange: NSRange(location: at, length: 0)) textView.scrollRangeToVisible(NSRange(location: at, length: 0)) } /// An answer the host had from the core for this text (a tag added at /// the end, say), written back as one change Undo takes back. public func apply(_ change: WritingChange) { take(change) } // MARK: Pictures /// Keeps each picture with the document and asks the core to place it. public func place(_ images: [UIImage]) { place(images.compactMap { $0.jpegData(compressionQuality: 0.86) }, type: .jpeg) } /// Keeps each picture's bytes and places it after the caret's line, in order. public func place(_ pictures: [Data], type: UTType) { guard let media else { return } Task { [weak self] in for bytes in pictures { let file = FileManager.default.temporaryDirectory .appendingPathComponent(UUID().uuidString).appendingPathExtension(type.preferredFilenameExtension ?? "jpg") do { try bytes.write(to: file) guard let self else { return } while pressing { try? await Task.sleep(for: .milliseconds(20)) } let asked = storage.string let change = try await media.add(file, text: asked, selection: textView.selectedRange) if asked == storage.string { take(change) } } catch { self?.onError?(error) } try? FileManager.default.removeItem(at: file) } } } public func textDroppableView(_ view: UIView & UITextDroppable, proposalForDrop drop: UITextDropRequest) -> UITextDropProposal { if drop.dropSession.hasItemsConforming(toTypeIdentifiers: [UTType.image.identifier]), !drop.dropSession.hasItemsConforming(toTypeIdentifiers: [UTType.plainText.identifier]) { for provider in drop.dropSession.items.map(\.itemProvider) where provider.hasItemConformingToTypeIdentifier(UTType.image.identifier) { _ = provider.loadDataRepresentation(for: .image) { [weak self] data, _ in guard let data else { return } Task { @MainActor in self?.place([data], type: .jpeg) } } } return UITextDropProposal(operation: .cancel) } return drop.suggestedProposal }}#if canImport(SwiftUI)import SwiftUI/// The surface in a SwiftUI screen.public struct WritingEditorView: UIViewRepresentable { let editor: WritingEditor public init(editor: WritingEditor) { self.editor = editor } public func makeUIView(context: Context) -> WritingTextView { editor.textView } public func updateUIView(_ view: WritingTextView, context: Context) {}}#endif#endif