Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Sources/Shared/Compose/RichTextEditor.swift3// Description: The composer's rich text editor — a controller that owns the text (semantic attributes, undoable edits, formatting commands,4// list / quote / heading behaviour while typing, snippet expansion, paste and copy) and the native TextKit views it drives (NSTextView on5// macOS, UITextView on iOS / iPadOS), wrapped for SwiftUI. No web view.6import SPMailCore7import SwiftUI8import UniformTypeIdentifiers9#if os(macOS)10import AppKit11typealias RichPlatformTextView = RichNSTextView12#else13import UIKit14typealias RichPlatformTextView = RichUITextView15#endif1617// MARK: - controller1819@MainActor @Observable20final class RichTextController: NSObject {21 // what the format bar and the menus show22 private(set) var activeMarks: Set<RichMark> = []23 private(set) var block: RichBlock = .body24 private(set) var hasSelection = false25 private(set) var linkAtSelection: String?26 private(set) var imageAtSelection: RichImage?27 private(set) var canUndo = false28 private(set) var canRedo = false29 private(set) var isFocused = false30 /// Height the text needs at the current width (the composer scrolls as a whole; the editor never scrolls by itself).31 var contentHeight: CGFloat = 03233 @ObservationIgnored let storage = NSTextStorage()34 @ObservationIgnored let undo = UndoManager()35 @ObservationIgnored weak var textView: RichPlatformTextView?36 @ObservationIgnored var theme = RichTheme(variant: .light)37 @ObservationIgnored var maxImageWidth: CGFloat = 56038 @ObservationIgnored private var headlessSelection = NSRange(location: 0, length: 0)39 @ObservationIgnored private var headlessTyping: [NSAttributedString.Key: Any] = [:]40 @ObservationIgnored private var trailingBlock: RichBlock = .body41 @ObservationIgnored private var pendingNative: (location: Int, length: Int, typed: String?)?42 @ObservationIgnored private var blockAfterReturn: RichBlock?43 @ObservationIgnored private var applying = false4445 // hooks set by the composer46 /// Any change of the text (typing, formatting, undo).47 @ObservationIgnored var onChange: (() -> Void)?48 @ObservationIgnored var snippets: (() -> [Snippet])?49 @ObservationIgnored var onSnippet: ((Snippet) -> Void)?50 /// Files pasted or dropped on the text (images among them are offered inline first by the composer).51 @ObservationIgnored var onFiles: (([URL]) -> Void)?52 @ObservationIgnored var onImages: (([Data]) -> Void)?53 @ObservationIgnored var imageProvider: ((String) -> PlatformImage?)?54 @ObservationIgnored var allowedCIDs: (() -> Set<String>)?55 /// Keeps the hosting controller of the keyboard accessory alive (iOS).56 @ObservationIgnored var accessoryHost: AnyObject?5758 override init() {59 super.init()60 undo.levelsOfUndo = 20061 }6263 // MARK: document6465 /// The text with its semantic attributes only — what is saved and converted to HTML.66 var document: NSAttributedString { RichText.semantic(storage) }67 var plainText: String { RichHTML.plainText(from: storage) }68 var isEmpty: Bool { storage.length == 0 }6970 /// Replaces the whole text (a draft being opened): not undoable.71 func setDocument(_ text: NSAttributedString) {72 applying = true73 storage.beginEditing()74 storage.setAttributedString(RichText.semantic(text))75 restyle(NSRange(location: 0, length: storage.length))76 storage.endEditing()77 applying = false78 undo.removeAllActions()79 trailingBlock = lastParagraphBlock()80 selection = NSRange(location: 0, length: 0)81 refresh()82 }8384 private func lastParagraphBlock() -> RichBlock {85 let s = storage.string as NSString86 guard let last = RichText.paragraphRanges(in: s).last, last.length > 0 else {87 return s.length == 0 ? .body : trailingBlock88 }89 return RichText.block(ofParagraph: last, in: storage)90 }9192 func restyle(_ range: NSRange) {93 RichStyler.restyle(storage, in: range, theme: theme, maxImageWidth: maxImageWidth) { [weak self] cid in self?.imageProvider?(cid) }94 }95 func restyleAll() {96 storage.beginEditing()97 restyle(NSRange(location: 0, length: storage.length))98 storage.endEditing()99 syncTyping()100 invalidateDisplay()101 }102 func apply(theme new: RichTheme) {103 guard new != theme else { return }104 theme = new105 (storage.layoutManagers.first as? RichLayoutManager)?.theme = new106 restyleAll()107 }108 /// An inline image finished loading: its placeholder is replaced.109 func imagesChanged() { restyleAll(); textView?.remeasure() }110111 private func invalidateDisplay() {112 guard let lm = storage.layoutManagers.first else { return }113 (lm as? RichLayoutManager)?.trailingBlock = trailingBlock114 lm.invalidateDisplay(forCharacterRange: NSRange(location: 0, length: storage.length))115 #if os(macOS)116 textView?.needsDisplay = true117 #else118 textView?.setNeedsDisplay()119 textView?.subviews.forEach { $0.setNeedsDisplay() }120 #endif121 }122123 // MARK: selection and typing attributes124125 var selection: NSRange {126 get {127 #if os(macOS)128 let r = textView?.selectedRange() ?? headlessSelection129 #else130 let r = textView?.selectedRange ?? headlessSelection131 #endif132 let location = min(max(0, r.location), storage.length)133 return NSRange(location: location, length: min(r.length, storage.length - location))134 }135 set {136 let location = min(max(0, newValue.location), storage.length)137 let r = NSRange(location: location, length: min(newValue.length, storage.length - location))138 headlessSelection = r139 #if os(macOS)140 if let textView, textView.selectedRange() != r { textView.setSelectedRange(r) }141 #else142 if let textView, textView.selectedRange != r { textView.selectedRange = r }143 #endif144 // no text view to announce the change (a composer driven by code): typing attributes follow the insertion point here145 if textView == nil { syncTyping(); refresh() }146 }147 }148149 private var typing: [NSAttributedString.Key: Any] {150 get { textView?.typingAttributes ?? headlessTyping }151 set { headlessTyping = newValue; textView?.typingAttributes = newValue }152 }153154 /// The content range of the paragraph that holds `location`, and its block.155 private func paragraph(at location: Int) -> (content: NSRange, block: RichBlock) {156 let s = storage.string as NSString157 let p = s.paragraphRange(for: NSRange(location: min(location, s.length), length: 0))158 var content = p159 if content.length > 0, s.character(at: NSMaxRange(content) - 1) == 0x0A { content.length -= 1 }160 if p.length == 0 { return (content, trailingBlock) } // the empty paragraph at the very end161 return (content, RichText.block(ofParagraph: content, in: storage))162 }163164 /// Typing continues the marks of the character before the insertion point (inside the same paragraph), never a link past its end, and165 /// always the block of the paragraph the insertion point is in.166 private func syncTyping() {167 let sel = selection168 let (content, blk) = paragraph(at: sel.location)169 var sem: [NSAttributedString.Key: Any] = [:]170 let source = sel.location > content.location ? sel.location - 1 : (content.length > 0 ? content.location : -1)171 if source >= 0, source < storage.length {172 sem = RichStyler.semantic(storage.attributes(at: source, effectiveRange: nil))173 sem[RichKey.image] = nil174 if sem[RichKey.link] != nil {175 // inside a link the address continues; right after it, it does not176 let next = sel.location < storage.length ? storage.attribute(RichKey.link, at: sel.location, effectiveRange: nil) as? String : nil177 if sel.location > content.location, next != sem[RichKey.link] as? String { sem[RichKey.link] = nil }178 }179 }180 sem[RichKey.block] = blk.rawValue181 var attrs = RichStyler.display(for: sem, theme: theme)182 for (k, v) in sem { attrs[k] = v }183 typing = attrs184 }185186 /// Recomputes what the format bar shows.187 func refresh() {188 let sel = selection189 let (_, blk) = paragraph(at: sel.location)190 var marks = Set<RichMark>(), link: String?, image: RichImage?191 if sel.length > 0 {192 marks = Set(RichMark.allCases.filter { mark in193 var all = true194 storage.enumerateAttribute(mark.key, in: sel) { v, _, stop in if v == nil { all = false; stop.pointee = true } }195 return all196 })197 link = storage.attribute(RichKey.link, at: sel.location, effectiveRange: nil) as? String198 if sel.length == 1, let raw = storage.attribute(RichKey.image, at: sel.location, effectiveRange: nil) as? String { image = RichImage(rawValue: raw) }199 } else {200 let t = typing201 marks = Set(RichMark.allCases.filter { t[$0.key] != nil })202 link = t[RichKey.link] as? String ?? (sel.location < storage.length ? storage.attribute(RichKey.link, at: sel.location, effectiveRange: nil) as? String : nil)203 }204 if marks != activeMarks { activeMarks = marks }205 if blk != block { block = blk }206 if hasSelection != (sel.length > 0) { hasSelection = sel.length > 0 }207 if link != linkAtSelection { linkAtSelection = link }208 if image != imageAtSelection { imageAtSelection = image }209 if canUndo != undo.canUndo { canUndo = undo.canUndo }210 if canRedo != undo.canRedo { canRedo = undo.canRedo }211 }212213 // MARK: the one undoable edit214215 /// Replaces `range` by `replacement` (model text): registered for undo, restyled, announced. Every command goes through here.216 func edit(_ range: NSRange, with replacement: NSAttributedString, select: NSRange? = nil, actionName: String? = nil) {217 let range = NSRange(location: min(range.location, storage.length), length: min(range.length, storage.length - min(range.location, storage.length)))218 let old = Unchecked(value: RichText.semantic(storage.attributedSubstring(from: range)))219 let newRange = NSRange(location: range.location, length: replacement.length)220 let previousSelection = selection, previousTrailing = trailingBlock221 undo.registerUndo(withTarget: self) { target in222 MainActor.assumeIsolated {223 target.trailingBlock = previousTrailing224 target.edit(newRange, with: old.value, select: previousSelection, actionName: actionName)225 }226 }227 if let actionName, !undo.isUndoing, !undo.isRedoing { undo.setActionName(actionName) }228 #if os(macOS)229 textView?.breakUndoCoalescing()230 #endif231 applying = true232 storage.beginEditing()233 storage.replaceCharacters(in: range, with: RichText.semantic(replacement))234 if newRange.length > 0 || storage.length > 0 { restyle(NSRange(location: newRange.location, length: min(newRange.length + 1, storage.length - newRange.location))) }235 storage.endEditing()236 applying = false237 if storage.length == 0 || !(storage.string.hasSuffix("\n")) { trailingBlock = lastParagraphBlock() }238 selection = select ?? NSRange(location: NSMaxRange(newRange), length: 0)239 didChange()240 }241242 /// After any change, native or not.243 private func didChange() {244 syncTyping()245 invalidateDisplay()246 refresh()247 textView?.remeasure()248 onChange?()249 }250251 func undoEdit() { if undo.canUndo { undo.undo(); refresh() } }252 func redoEdit() { if undo.canRedo { undo.redo(); refresh() } }253254 // MARK: commands — inline255256 func toggle(_ mark: RichMark) {257 let sel = selection258 guard sel.length > 0 else {259 var t = typing260 if t[mark.key] != nil { t[mark.key] = nil } else { t[mark.key] = true }261 let sem = RichStyler.semantic(t)262 var attrs = RichStyler.display(for: sem, theme: theme)263 for (k, v) in sem { attrs[k] = v }264 typing = attrs265 refresh()266 return267 }268 let piece = NSMutableAttributedString(attributedString: storage.attributedSubstring(from: sel))269 let whole = NSRange(location: 0, length: piece.length)270 if activeMarks.contains(mark) { piece.removeAttribute(mark.key, range: whole) } else {271 piece.enumerateAttribute(RichKey.image, in: whole) { v, r, _ in if v == nil { piece.addAttribute(mark.key, value: true, range: r) } }272 }273 edit(sel, with: piece, select: sel, actionName: L("Mise en forme"))274 }275276 func clearFormatting() {277 let sel = selection278 let span = sel.length > 0 ? sel : paragraph(at: sel.location).content279 if span.length > 0 {280 let piece = NSMutableAttributedString(attributedString: storage.attributedSubstring(from: span))281 let whole = NSRange(location: 0, length: piece.length)282 for mark in RichMark.allCases { piece.removeAttribute(mark.key, range: whole) }283 piece.removeAttribute(RichKey.link, range: whole)284 edit(span, with: piece, select: sel, actionName: L("Effacer la mise en forme"))285 }286 setBlocks { _ in .body }287 var t = typing288 for mark in RichMark.allCases { t[mark.key] = nil }289 t[RichKey.link] = nil290 let sem = RichStyler.semantic(t)291 var attrs = RichStyler.display(for: sem, theme: theme)292 for (k, v) in sem { attrs[k] = v }293 typing = attrs294 refresh()295 }296297 /// The range of the link around the insertion point (or under the selection).298 func linkRange() -> NSRange? {299 let sel = selection300 let at = sel.length > 0 ? sel.location : (sel.location < storage.length && storage.attribute(RichKey.link, at: sel.location, effectiveRange: nil) != nil ? sel.location : sel.location - 1)301 guard at >= 0, at < storage.length, storage.attribute(RichKey.link, at: at, effectiveRange: nil) != nil else { return nil }302 var r = NSRange()303 _ = storage.attribute(RichKey.link, at: at, longestEffectiveRange: &r, in: NSRange(location: 0, length: storage.length))304 return r305 }306 /// The text a link dialog starts with: the selected text, or the text of the link being edited.307 func linkText() -> String {308 let r = selection.length > 0 ? selection : (linkRange() ?? NSRange(location: 0, length: 0))309 return (storage.string as NSString).substring(with: r).replacingOccurrences(of: RichText.attachmentCharacter, with: "")310 }311312 /// Inserts, edits or (with `url` nil) removes a link. With no selection and no link under the insertion point, `text` is inserted.313 func setLink(_ url: String?, text: String? = nil) {314 let target = selection.length > 0 ? selection : linkRange()315 if let target {316 let piece = NSMutableAttributedString(attributedString: storage.attributedSubstring(from: target))317 if let text, !text.isEmpty, text != piece.string, !piece.string.contains(RichText.attachmentCharacter) {318 var attrs = RichStyler.semantic(piece.attributes(at: 0, effectiveRange: nil))319 attrs[RichKey.link] = nil320 piece.setAttributedString(NSAttributedString(string: text, attributes: attrs))321 }322 let whole = NSRange(location: 0, length: piece.length)323 if let url { piece.addAttribute(RichKey.link, value: url, range: whole) } else { piece.removeAttribute(RichKey.link, range: whole) }324 edit(target, with: piece, select: NSRange(location: target.location + piece.length, length: 0), actionName: L("Lien"))325 } else if let url {326 var attrs = RichStyler.semantic(typing)327 attrs[RichKey.link] = url328 let label = (text?.isEmpty == false ? text! : url.replacingOccurrences(of: "mailto:", with: ""))329 edit(selection, with: NSAttributedString(string: label, attributes: attrs), actionName: L("Lien"))330 }331 }332333 // MARK: commands — blocks334335 /// Applies `transform` to the block of every paragraph touched by the selection.336 func setBlocks(_ transform: (RichBlock) -> RichBlock) {337 let sel = selection338 let s = storage.string as NSString339 let span = RichText.paragraphSpan(of: sel, in: s)340 let atTrailing = s.length == 0 || (sel.location == s.length && s.hasSuffix("\n"))341 if span.length == 0 || (atTrailing && sel.length == 0) {342 // the empty last paragraph: nothing to rewrite, the insertion point carries the block343 let next = transform(trailingBlock)344 guard next != trailingBlock else { return }345 setTrailing(next)346 return347 }348 let piece = NSMutableAttributedString(attributedString: storage.attributedSubstring(from: span))349 var changed = false350 let ps = piece.string as NSString351 var at = 0352 while at < ps.length {353 let p = ps.paragraphRange(for: NSRange(location: at, length: 0))354 guard p.length > 0 else { break }355 let current = RichBlock(rawValue: piece.attribute(RichKey.block, at: p.location, effectiveRange: nil) as? String ?? "p")356 let next = transform(current)357 if next != current { piece.addAttribute(RichKey.block, value: next.rawValue, range: p); changed = true }358 at = NSMaxRange(p)359 }360 // a selection that ends in the empty last paragraph takes it along361 if NSMaxRange(sel) == s.length, s.hasSuffix("\n") { trailingBlock = transform(trailingBlock) }362 guard changed else { syncTyping(); invalidateDisplay(); refresh(); return }363 edit(span, with: piece, select: sel, actionName: L("Mise en forme"))364 }365 private func setTrailing(_ block: RichBlock) {366 let previous = trailingBlock367 undo.registerUndo(withTarget: self) { target in MainActor.assumeIsolated { target.setTrailing(previous) } }368 trailingBlock = block369 didChange()370 }371372 private func selectedBlocks() -> [RichBlock] {373 let s = storage.string as NSString374 let span = RichText.paragraphSpan(of: selection, in: s)375 guard span.length > 0 else { return [trailingBlock] }376 var out: [RichBlock] = [], at = span.location377 while at < NSMaxRange(span) {378 let p = s.paragraphRange(for: NSRange(location: at, length: 0))379 guard p.length > 0 else { break }380 out.append(RichBlock(rawValue: storage.attribute(RichKey.block, at: p.location, effectiveRange: nil) as? String ?? "p"))381 at = NSMaxRange(p)382 }383 return out384 }385386 func toggleList(ordered: Bool) {387 let kind: RichBlock.Kind = ordered ? .ordered : .bullet388 let allAlready = selectedBlocks().allSatisfy { $0.kind == kind }389 setBlocks { b in allAlready ? RichBlock(kind: .paragraph, quote: b.quote) : RichBlock(kind: kind, level: max(1, b.level), quote: b.quote) }390 }391 func toggleQuote() {392 let quoted = selectedBlocks().allSatisfy { $0.quote > 0 }393 setBlocks { b in RichBlock(kind: b.kind, level: b.level, quote: quoted ? 0 : max(1, b.quote)) }394 }395 /// 0 = body text, 1…3 = heading level.396 func setHeading(_ level: Int) {397 setBlocks { b in RichBlock(kind: level == 0 ? .paragraph : .heading(level), quote: b.quote) }398 }399 /// Indents (+1) or outdents (−1) list items; outdenting the first level leaves the list.400 func indent(_ delta: Int) {401 setBlocks { b in402 guard b.isList else { return b }403 let level = b.level + delta404 return level < 1 ? RichBlock(kind: .paragraph, quote: b.quote) : RichBlock(kind: b.kind, level: level, quote: b.quote)405 }406 }407408 // MARK: commands — insertion409410 /// Inserts plain text at the insertion point (or over the selection) with the typing attributes there.411 func insert(text: String, replacingSelection: Bool = true) {412 let sel = selection413 let target = replacingSelection ? sel : NSRange(location: NSMaxRange(sel), length: 0)414 edit(target, with: NSAttributedString(string: RichText.normalizedNewlines(text), attributes: RichStyler.semantic(typing)), actionName: L("Insertion"))415 }416417 /// Inserts model text (a snippet, pasted rich text, a rendered template). Its first paragraph joins the current one; body paragraphs take418 /// the block the insertion point is in.419 func insert(rich: NSAttributedString, at range: NSRange? = nil, actionName: String? = nil) {420 let target = range ?? selection421 let piece = NSMutableAttributedString(attributedString: RichText.semantic(rich))422 let here = paragraph(at: target.location).block423 if here != .body {424 piece.enumerateAttribute(RichKey.block, in: NSRange(location: 0, length: piece.length)) { v, r, _ in425 if (v as? String ?? "p") == "p" { piece.addAttribute(RichKey.block, value: here.rawValue, range: r) }426 }427 }428 edit(target, with: piece, actionName: actionName ?? L("Insertion"))429 }430431 func insert(image: RichImage) {432 var attrs: [NSAttributedString.Key: Any] = [RichKey.block: paragraph(at: selection.location).block.rawValue]433 attrs[RichKey.image] = image.rawValue434 edit(selection, with: NSAttributedString(string: RichText.attachmentCharacter, attributes: attrs), actionName: L("Image"))435 }436437 /// Changes the display width of the selected image.438 func resizeSelectedImage(to preset: RichImage.Preset) {439 let sel = selection440 guard sel.length == 1, var image = imageAtSelection else { return }441 image.width = preset.width442 let piece = NSMutableAttributedString(attributedString: storage.attributedSubstring(from: sel))443 piece.addAttribute(RichKey.image, value: image.rawValue, range: NSRange(location: 0, length: 1))444 edit(sel, with: piece, select: sel, actionName: L("Taille de l’image"))445 }446447 // MARK: pasteboard448449 func handle(_ content: PasteContent) {450 switch content {451 case .files(let urls): onFiles?(urls)452 case .images(let data): onImages?(data)453 case .rich(let text): insert(rich: text, actionName: L("Coller"))454 case .plain(let s): insert(text: s)455 }456 }457458 /// Writes the selection as plain text and as the composer's own HTML (pasting it back keeps lists, links and inline images).459 func copySelection(cut: Bool) {460 let sel = selection461 guard sel.length > 0 else { return }462 let piece = RichText.semantic(storage.attributedSubstring(from: sel))463 let plain = RichHTML.plainText(from: piece), html = RichHTML.html(from: piece)464 #if os(macOS)465 let pb = NSPasteboard.general466 pb.clearContents()467 pb.setString(plain, forType: .string)468 pb.setString(html, forType: .html)469 #else470 UIPasteboard.general.setItems([[UTType.utf8PlainText.identifier: plain, UTType.html.identifier: html]])471 #endif472 if cut { edit(sel, with: NSAttributedString(), actionName: L("Couper")) }473 }474475 func paste(plainOnly: Bool) {476 let cids = allowedCIDs?() ?? []477 #if os(macOS)478 if let c = PasteContent.read(.general, plainOnly: plainOnly, allowedCIDs: cids) { handle(c) }479 #else480 if let c = PasteContent.read(.general, plainOnly: plainOnly, allowedCIDs: cids) { handle(c) }481 #endif482 }483484 // MARK: native typing485486 /// The text view is about to change characters itself (typing, deleting, autocorrection). Returns false when the change was handled487 /// here instead: Return in an empty list item or quote leaves it, Backspace at the start of one too.488 func shouldChange(_ range: NSRange, replacement: String?) -> Bool {489 guard !applying else { return true }490 let s = storage.string as NSString491 let (content, blk) = paragraph(at: range.location)492 if replacement == "\n", range.length == 0 {493 if content.length == 0, blk.isList || blk.quote > 0 {494 // an empty item: one level out495 selection = range496 setBlocks { b in497 if b.isList { return b.level > 1 ? RichBlock(kind: b.kind, level: b.level - 1, quote: b.quote) : RichBlock(kind: .paragraph, quote: b.quote) }498 return RichBlock(kind: .paragraph, quote: max(0, b.quote - 1))499 }500 return false501 }502 // after a heading the text goes back to body; elsewhere the new paragraph continues the block503 if case .heading = blk.kind, range.location == NSMaxRange(content) { blockAfterReturn = RichBlock(kind: .paragraph, quote: blk.quote) } else { blockAfterReturn = blk }504 }505 if replacement == "", range.length == 1, range.location + 1 == selection.location, selection.length == 0 {506 // Backspace right after a line break: is the insertion point at the start of a list item or a quoted paragraph?507 let here = paragraph(at: selection.location)508 if selection.location == here.content.location, s.character(at: range.location) == 0x0A, here.block.isList || here.block.quote > 0 {509 setBlocks { b in b.isList ? RichBlock(kind: .paragraph, quote: b.quote) : RichBlock(kind: .paragraph, quote: max(0, b.quote - 1)) }510 return false511 }512 }513 if replacement == "", range.length == 0, range.location == 0, blk != .body, content.location == 0 {514 setBlocks { _ in .body }515 return false516 }517 pendingNative = (range.location, (replacement as NSString?)?.length ?? 0, replacement)518 return true519 }520521 /// The text view changed characters itself.522 func nativeDidChange(hasMarkedText: Bool) {523 guard !applying else { return }524 let edited = pendingNative525 pendingNative = nil526 // an input method is composing (Japanese, Chinese, accents): its text must not be touched until it commits527 guard !hasMarkedText else { onChange?(); return }528 if let block = blockAfterReturn {529 blockAfterReturn = nil530 if selection.location == storage.length, storage.string.hasSuffix("\n") { trailingBlock = block }531 else if let edited, edited.location + 1 <= storage.length {532 // Return in the middle of a text: the paragraph that starts after the break keeps going as `block`533 let after = (storage.string as NSString).paragraphRange(for: NSRange(location: min(edited.location + 1, storage.length), length: 0))534 if after.length > 0 { applying = true; storage.addAttribute(RichKey.block, value: block.rawValue, range: after); applying = false }535 }536 } else if storage.length == 0 || !storage.string.hasSuffix("\n") { trailingBlock = lastParagraphBlock() }537 applying = true538 let fix = edited.map { NSRange(location: min($0.location, storage.length), length: min($0.length + 1, storage.length - min($0.location, storage.length))) } ?? NSRange(location: 0, length: storage.length)539 storage.beginEditing()540 restyle(fix)541 storage.endEditing()542 applying = false543 if let edited, let typed = edited.typed, (typed as NSString).length == 1, let all = snippets?(), !all.isEmpty { expandSnippet(endingAt: edited.location + 1, among: all) }544 didChange()545 }546547 private func expandSnippet(endingAt caret: Int, among all: [Snippet]) {548 guard caret <= storage.length else { return }549 let content = paragraph(at: max(0, caret - 1)).content550 guard caret > content.location else { return }551 let prefix = (storage.string as NSString).substring(with: NSRange(location: content.location, length: caret - content.location))552 guard let hit = SnippetExpander.completed(in: prefix, snippets: all) else { return }553 let target = NSRange(location: content.location + hit.trigger.location, length: hit.trigger.length)554 let body = NSMutableAttributedString(attributedString: SnippetExpander.content(of: hit.snippet))555 // plain snippets take the marks being typed; rich ones bring their own556 if !RichText.isRich(body) {557 var attrs = RichStyler.semantic(storage.attributes(at: target.location, effectiveRange: nil))558 attrs[RichKey.block] = nil559 body.addAttributes(attrs, range: NSRange(location: 0, length: body.length))560 }561 insert(rich: body, at: target, actionName: L("Extrait"))562 selection = NSRange(location: target.location + body.length + 1, length: 0)563 onSnippet?(hit.snippet)564 }565566 func selectionChanged() {567 guard !applying else { return }568 headlessSelection = selection569 syncTyping()570 refresh()571 }572573 #if DEBUG574 /// Self-test: what the text view does when the person types `text` (one character at a time, with the typing attributes).575 func simulateTyping(_ text: String) {576 for ch in text {577 let sel = selection, attrs = typing, piece = String(ch)578 guard shouldChange(sel, replacement: piece) else { continue }579 applying = true580 storage.replaceCharacters(in: sel, with: NSAttributedString(string: piece, attributes: attrs))581 applying = false582 selection = NSRange(location: sel.location + (piece as NSString).length, length: 0)583 nativeDidChange(hasMarkedText: false)584 }585 }586 /// Self-test: Backspace.587 func simulateBackspace() {588 let sel = selection589 let range = sel.length > 0 ? sel : NSRange(location: max(0, sel.location - 1), length: sel.location > 0 ? 1 : 0)590 guard shouldChange(range, replacement: "") else { return }591 applying = true592 storage.deleteCharacters(in: range)593 applying = false594 selection = NSRange(location: range.location, length: 0)595 nativeDidChange(hasMarkedText: false)596 }597 #endif598599 func focusChanged(_ focused: Bool) { if isFocused != focused { isFocused = focused } }600 func focus() {601 #if os(macOS)602 if let textView { textView.window?.makeFirstResponder(textView) }603 #else604 textView?.becomeFirstResponder()605 #endif606 }607}608609// MARK: - AppKit610611#if os(macOS)612final class RichNSTextView: NSTextView {613 weak var controller: RichTextController?614615 override var acceptableDragTypes: [NSPasteboard.PasteboardType] { super.acceptableDragTypes + [.fileURL, .png, .tiff] }616 override func paste(_ sender: Any?) { controller?.paste(plainOnly: false) }617 override func pasteAsPlainText(_ sender: Any?) { controller?.paste(plainOnly: true) }618 override func pasteAsRichText(_ sender: Any?) { controller?.paste(plainOnly: false) }619 override func copy(_ sender: Any?) { controller?.copySelection(cut: false) }620 override func cut(_ sender: Any?) { controller?.copySelection(cut: true) }621622 override func performDragOperation(_ sender: any NSDraggingInfo) -> Bool {623 let pb = sender.draggingPasteboard624 // files and pictures dropped on the text: inline images / attachments, at the drop point625 if let urls = pb.readObjects(forClasses: [NSURL.self], options: [.urlReadingFileURLsOnly: true]) as? [URL], !urls.isEmpty {626 let point = convert(sender.draggingLocation, from: nil)627 setSelectedRange(NSRange(location: characterIndexForInsertion(at: point), length: 0))628 controller?.handle(.files(urls))629 return true630 }631 if pb.availableType(from: [.string, .rtf, .html]) == nil, let data = pb.data(forType: .png) ?? pb.data(forType: .tiff) {632 let point = convert(sender.draggingLocation, from: nil)633 setSelectedRange(NSRange(location: characterIndexForInsertion(at: point), length: 0))634 controller?.handle(.images([data]))635 return true636 }637 return super.performDragOperation(sender)638 }639640 override func becomeFirstResponder() -> Bool { let ok = super.becomeFirstResponder(); if ok { controller?.focusChanged(true) }; return ok }641 override func resignFirstResponder() -> Bool { let ok = super.resignFirstResponder(); if ok { controller?.focusChanged(false) }; return ok }642643 override func setFrameSize(_ newSize: NSSize) {644 let widthChanged = abs(newSize.width - frame.width) > 0.5645 super.setFrameSize(newSize)646 if widthChanged { remeasure() }647 }648649 /// Tells the composer how tall the text is at the current width.650 func remeasure() {651 guard let lm = layoutManager, let container = textContainer else { return }652 lm.ensureLayout(for: container)653 let height = ceil(lm.usedRect(for: container).height + textContainerInset.height * 2)654 guard let controller, abs(controller.contentHeight - height) > 0.5 else { return }655 DispatchQueue.main.async { [weak controller] in controller?.contentHeight = height }656 }657}658659extension RichTextController: NSTextViewDelegate {660 func textView(_ textView: NSTextView, shouldChangeTextIn affectedCharRange: NSRange, replacementString: String?) -> Bool {661 shouldChange(affectedCharRange, replacement: replacementString)662 }663 func textDidChange(_ notification: Notification) { nativeDidChange(hasMarkedText: textView?.hasMarkedText() ?? false) }664 func textViewDidChangeSelection(_ notification: Notification) { selectionChanged() }665 func undoManager(for view: NSTextView) -> UndoManager? { undo }666 func textView(_ textView: NSTextView, doCommandBy selector: Selector) -> Bool {667 if selector == #selector(NSResponder.insertTab(_:)), block.isList { indent(1); return true }668 if selector == #selector(NSResponder.insertBacktab(_:)), block.isList { indent(-1); return true }669 if selector == #selector(NSResponder.insertLineBreak(_:)) { textView.insertNewline(nil); return true } // one kind of line ending670 if selector == #selector(NSResponder.deleteBackward(_:)), textView.selectedRange() == NSRange(location: 0, length: 0), block != .body { setBlocks { _ in .body }; return true }671 return false672 }673}674675struct RichTextRepresentable: NSViewRepresentable {676 let controller: RichTextController677 let theme: RichTheme678679 func makeNSView(context: Context) -> RichNSTextView {680 let lm = RichLayoutManager()681 lm.theme = theme682 controller.storage.addLayoutManager(lm)683 let container = NSTextContainer(size: CGSize(width: 400, height: CGFloat.greatestFiniteMagnitude))684 container.widthTracksTextView = true685 lm.addTextContainer(container)686 let view = RichNSTextView(frame: CGRect(x: 0, y: 0, width: 400, height: 200), textContainer: container)687 view.controller = controller688 view.delegate = controller689 view.isRichText = true690 view.importsGraphics = false691 view.allowsUndo = true692 view.usesFontPanel = false693 view.usesRuler = false694 view.isAutomaticLinkDetectionEnabled = false695 view.isAutomaticDataDetectionEnabled = false696 view.drawsBackground = false697 view.textContainerInset = NSSize(width: 0, height: 4)698 view.isVerticallyResizable = true699 view.isHorizontallyResizable = false700 view.autoresizingMask = [.width]701 view.minSize = NSSize(width: 0, height: 0)702 view.maxSize = NSSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude)703 view.insertionPointColor = theme.accent704 view.selectedTextAttributes = [.backgroundColor: theme.accent.withAlphaComponent(0.28)]705 view.setAccessibilityLabel(L("Corps du message"))706 controller.textView = view707 controller.theme = theme708 controller.restyleAll()709 controller.selectionChanged()710 return view711 }712713 func updateNSView(_ view: RichNSTextView, context: Context) {714 controller.apply(theme: theme)715 view.insertionPointColor = theme.accent716 view.selectedTextAttributes = [.backgroundColor: theme.accent.withAlphaComponent(0.28)]717 view.remeasure()718 }719720 static func dismantleNSView(_ view: RichNSTextView, coordinator: ()) {721 if let lm = view.layoutManager { view.textStorage?.removeLayoutManager(lm) }722 if view.controller?.textView === view { view.controller?.textView = nil }723 }724}725#else726727// MARK: - UIKit728729final class RichUITextView: UITextView {730 weak var controller: RichTextController?731 private var measuredWidth: CGFloat = 0732733 override var undoManager: UndoManager? { controller?.undo ?? super.undoManager }734 override func paste(_ sender: Any?) { controller?.paste(plainOnly: false) }735 override func pasteAndMatchStyle(_ sender: Any?) { controller?.paste(plainOnly: true) }736 override func copy(_ sender: Any?) { controller?.copySelection(cut: false) }737 override func cut(_ sender: Any?) { controller?.copySelection(cut: true) }738 override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {739 if action == #selector(paste(_:)) || action == #selector(pasteAndMatchStyle(_:)) { return UIPasteboard.general.hasStrings || UIPasteboard.general.hasImages || UIPasteboard.general.contains(pasteboardTypes: [UTType.html.identifier, UTType.rtf.identifier]) }740 return super.canPerformAction(action, withSender: sender)741 }742 // ⌘B / ⌘I / ⌘U of a hardware keyboard and the system edit menu743 override func toggleBoldface(_ sender: Any?) { controller?.toggle(.bold) }744 override func toggleItalics(_ sender: Any?) { controller?.toggle(.italic) }745 override func toggleUnderline(_ sender: Any?) { controller?.toggle(.underline) }746747 override var keyCommands: [UIKeyCommand]? {748 guard controller?.block.isList == true else { return super.keyCommands }749 let tab = UIKeyCommand(input: "\t", modifierFlags: [], action: #selector(indentItem))750 let back = UIKeyCommand(input: "\t", modifierFlags: .shift, action: #selector(outdentItem))751 tab.wantsPriorityOverSystemBehavior = true; back.wantsPriorityOverSystemBehavior = true752 return (super.keyCommands ?? []) + [tab, back]753 }754 @objc private func indentItem() { controller?.indent(1) }755 @objc private func outdentItem() { controller?.indent(-1) }756757 override func layoutSubviews() {758 super.layoutSubviews()759 if abs(bounds.width - measuredWidth) > 0.5 { measuredWidth = bounds.width; remeasure() }760 }761762 func remeasure() {763 guard bounds.width > 1 else { return }764 let height = ceil(sizeThatFits(CGSize(width: bounds.width, height: .greatestFiniteMagnitude)).height)765 guard let controller, abs(controller.contentHeight - height) > 0.5 else { return }766 DispatchQueue.main.async { [weak controller] in controller?.contentHeight = height }767 }768769 /// Keeps the insertion point visible in the composer's scroll view (the text view itself never scrolls).770 func revealCaret() {771 guard isFirstResponder, let range = selectedTextRange else { return }772 var ancestor = superview773 while let v = ancestor, !(v is UIScrollView) { ancestor = v.superview }774 guard let scroll = ancestor as? UIScrollView else { return }775 let caret = convert(caretRect(for: range.end), to: scroll).insetBy(dx: 0, dy: -18)776 scroll.scrollRectToVisible(caret, animated: false)777 }778}779780extension RichTextController: UITextViewDelegate {781 func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool { shouldChange(range, replacement: text) }782 func textViewDidChange(_ textView: UITextView) {783 nativeDidChange(hasMarkedText: textView.markedTextRange != nil)784 (textView as? RichUITextView)?.revealCaret()785 }786 func textViewDidChangeSelection(_ textView: UITextView) {787 selectionChanged()788 (textView as? RichUITextView)?.revealCaret()789 }790 func textViewDidBeginEditing(_ textView: UITextView) { focusChanged(true) }791 func textViewDidEndEditing(_ textView: UITextView) { focusChanged(false) }792}793794struct RichTextRepresentable: UIViewRepresentable {795 let controller: RichTextController796 let theme: RichTheme797 /// The keyboard accessory (the format bar on iPhone); nil on iPad, where the bar sits above the text.798 var accessory: (() -> UIView)?799800 func makeUIView(context: Context) -> RichUITextView {801 let lm = RichLayoutManager()802 lm.theme = theme803 controller.storage.addLayoutManager(lm)804 let container = NSTextContainer(size: CGSize(width: 320, height: CGFloat.greatestFiniteMagnitude))805 container.widthTracksTextView = true806 lm.addTextContainer(container)807 let view = RichUITextView(frame: CGRect(x: 0, y: 0, width: 320, height: 200), textContainer: container)808 view.controller = controller809 view.delegate = controller810 view.isScrollEnabled = false811 view.backgroundColor = .clear812 view.textContainerInset = UIEdgeInsets(top: 6, left: 0, bottom: 6, right: 0)813 view.allowsEditingTextAttributes = false814 view.dataDetectorTypes = []815 view.adjustsFontForContentSizeCategory = false816 view.keyboardDismissMode = .interactive817 view.tintColor = theme.accent818 view.accessibilityLabel = L("Corps du message")819 view.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)820 if let accessory { view.inputAccessoryView = accessory() }821 controller.textView = view822 controller.theme = theme823 controller.restyleAll()824 controller.selectionChanged()825 return view826 }827828 func updateUIView(_ view: RichUITextView, context: Context) {829 // Dynamic Type: the base size follows the text size setting830 var theme = theme831 theme.baseSize = RichTheme.bodySize832 controller.apply(theme: theme)833 view.tintColor = theme.accent834 view.remeasure()835 }836837 static func dismantleUIView(_ view: RichUITextView, coordinator: ()) {838 view.textStorage.removeLayoutManager(view.layoutManager)839 if view.controller?.textView === view { view.controller?.textView = nil }840 }841}842#endif843844// MARK: - SwiftUI845846/// The body editor of the composer: grows with its text inside the composer's scroll view.847struct RichTextEditorView: View {848 let controller: RichTextController849 var minHeight: CGFloat = 220850 #if os(iOS)851 var accessory: (() -> UIView)?852 #endif853 @Environment(\.spVariant) private var variant854 @Environment(\.colorSchemeContrast) private var contrast855 @Environment(\.dynamicTypeSize) private var typeSize856857 var body: some View {858 let theme = RichTheme(variant: variant, increasedContrast: contrast == .increased)859 Group {860 #if os(macOS)861 RichTextRepresentable(controller: controller, theme: theme)862 #else863 RichTextRepresentable(controller: controller, theme: theme, accessory: accessory).id(typeSize)864 #endif865 }866 .frame(height: max(minHeight, controller.contentHeight))867 }868}869