@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
swift 1,423 lines 48.9 KB
Raw
1 import ExpoModulesCore
2 import UIKit
3 import UniformTypeIdentifiers
4
5 private struct ComposerTokenPayload: Decodable, Equatable {
6 let type: String
7 let source: String
8 let label: String
9 let iconUri: String?
10 let accent: String?
11 let tintsIcon: Bool?
12 let detail: String?
13 var start: Int
14 var end: Int
15
16 func rendersLike(_ other: Self) -> Bool {
17 var moved = other
18 moved.start = start
19 moved.end = end
20 // String == accepts canonically equivalent sources, but their UTF-16 lengths differ.
21 return moved == self && source.utf16.elementsEqual(other.source.utf16)
22 }
23 }
24
25 private struct ComposerSelectionPayload: Decodable, Equatable {
26 let start: Int
27 let end: Int
28 }
29
30 private struct ComposerControlledDocumentPayload: Decodable {
31 let value: String
32 let selection: ComposerSelectionPayload?
33 let tokensJson: String
34 let mostRecentEventCount: Int
35 let isNativeEcho: Bool
36 let resetGeneration: Int
37 }
38
39 private struct ComposerThemePayload: Decodable {
40 let text: String
41 let placeholder: String
42 }
43
44 private enum ComposerEnterBehavior: String {
45 case send
46 case newline
47 }
48
49 private final class ComposerTextAttachment: NSTextAttachment {
50 let token: ComposerTokenPayload
51 var source: String { token.source }
52 var label: String { token.label }
53
54 init(token: ComposerTokenPayload, image: UIImage, size: CGSize, baselineOffset: CGFloat) {
55 self.token = token
56 super.init(data: nil, ofType: nil)
57 self.image = image
58 bounds = CGRect(x: 0, y: baselineOffset, width: size.width, height: size.height)
59 }
60
61 required init?(coder: NSCoder) {
62 nil
63 }
64 }
65
66 private final class ComposerContextAccessibilityElement: UIAccessibilityElement {
67 var activate: (() -> Bool)?
68
69 override func accessibilityActivate() -> Bool {
70 activate?() ?? false
71 }
72 }
73
74 private final class ComposerTextView: UITextView {
75 private static let pastedImageDirectoryName = "t3-composer-paste"
76 private static let stalePastedImageAge: TimeInterval = 60 * 60
77 private static let readOnlyActions = Set([
78 "cut:",
79 "delete:",
80 "paste:",
81 "redo:",
82 "toggleBoldface:",
83 "toggleItalics:",
84 "toggleUnderline:",
85 "undo:",
86 ])
87
88 var onPasteImages: (([String]) -> Void)?
89 var onPasteContext: (([String: String]) -> Void)?
90 var onPasteText: ((String, NSRange) -> Void)?
91 var clipboardFragment = ""
92 var onSubmit: ((Bool) -> Void)?
93 var isReadOnly = false
94 var textPasteThresholdBytes = 0
95 var maxInputChars = Int.max
96 var enterBehavior: ComposerEnterBehavior = .send
97 /// JS supplies the actual send outcomes so the iPad Command-hold HUD names the configured actions.
98 var submitTitle = "Send Message"
99 var alternateSubmitTitle = "Send Message"
100 private var bypassTextPasteInterception = false
101
102 override var keyCommands: [UIKeyCommand]? {
103 var commands = super.keyCommands ?? []
104 guard !isReadOnly, markedTextRange == nil else { return commands }
105 if enterBehavior == .send {
106 let submitOnReturn = UIKeyCommand(
107 input: "\r",
108 modifierFlags: [],
109 action: #selector(submitMessage(_:))
110 )
111 submitOnReturn.discoverabilityTitle = submitTitle
112 submitOnReturn.wantsPriorityOverSystemBehavior = true
113 commands.append(submitOnReturn)
114
115 let submitAlternate = UIKeyCommand(
116 input: "\r",
117 modifierFlags: .command,
118 action: #selector(submitMessageAlternate(_:))
119 )
120 submitAlternate.discoverabilityTitle = alternateSubmitTitle
121 submitAlternate.wantsPriorityOverSystemBehavior = true
122 commands.append(submitAlternate)
123
124 let newline = UIKeyCommand(
125 input: "\r",
126 modifierFlags: .shift,
127 action: #selector(insertNewline(_:))
128 )
129 newline.discoverabilityTitle = "New Line"
130 newline.wantsPriorityOverSystemBehavior = true
131 commands.append(newline)
132 } else {
133 let submit = UIKeyCommand(
134 input: "\r",
135 modifierFlags: .command,
136 action: #selector(submitMessage(_:))
137 )
138 submit.discoverabilityTitle = submitTitle
139 submit.wantsPriorityOverSystemBehavior = true
140 commands.append(submit)
141
142 let submitAlternate = UIKeyCommand(
143 input: "\r",
144 modifierFlags: [.command, .shift],
145 action: #selector(submitMessageAlternate(_:))
146 )
147 submitAlternate.discoverabilityTitle = alternateSubmitTitle
148 submitAlternate.wantsPriorityOverSystemBehavior = true
149 commands.append(submitAlternate)
150 }
151 if textPasteThresholdBytes > 0 {
152 let pasteAsText = UIKeyCommand(
153 input: "v",
154 modifierFlags: [.command, .shift],
155 action: #selector(pasteInline(_:))
156 )
157 pasteAsText.discoverabilityTitle = "Paste as Text"
158 pasteAsText.wantsPriorityOverSystemBehavior = true
159 commands.append(pasteAsText)
160 }
161 return commands
162 }
163
164 @objc private func submitMessage(_ sender: UIKeyCommand) {
165 guard !isReadOnly, markedTextRange == nil else { return }
166 onSubmit?(false)
167 }
168
169 @objc private func submitMessageAlternate(_ sender: UIKeyCommand) {
170 guard !isReadOnly, markedTextRange == nil else { return }
171 onSubmit?(true)
172 }
173
174 @objc private func insertNewline(_ sender: UIKeyCommand) {
175 guard !isReadOnly, markedTextRange == nil else { return }
176 insertText("\n")
177 }
178
179 @objc private func pasteInline(_ sender: UIKeyCommand) {
180 guard !isReadOnly else {
181 return
182 }
183 bypassTextPasteInterception = true
184 defer { bypassTextPasteInterception = false }
185 paste(sender)
186 }
187
188 override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
189 if action == #selector(submitMessage(_:)) || action == #selector(insertNewline(_:)) {
190 return isEditable && !isReadOnly && markedTextRange == nil
191 }
192 if isReadOnly && Self.readOnlyActions.contains(NSStringFromSelector(action)) {
193 return false
194 }
195 if action == #selector(paste(_:)) {
196 let pasteboard = UIPasteboard.general
197 if pasteboard.hasImages ||
198 pasteboard.itemProviders.contains(where: {
199 $0.canLoadObject(ofClass: UIImage.self)
200 }) {
201 return true
202 }
203 }
204 return super.canPerformAction(action, withSender: sender)
205 }
206
207 override func canPaste(_ itemProviders: [NSItemProvider]) -> Bool {
208 guard isEditable, !isReadOnly else { return false }
209 // UIKit checks canPaste before forwarding a drag to UITextDropDelegate.
210 if !itemProviders.isEmpty,
211 itemProviders.allSatisfy({ $0.canLoadObject(ofClass: UIImage.self) }) {
212 return true
213 }
214 return super.canPaste(itemProviders)
215 }
216
217 override func paste(itemProviders: [NSItemProvider]) {
218 guard isEditable, !isReadOnly else { return }
219 if !itemProviders.isEmpty,
220 itemProviders.allSatisfy({ $0.canLoadObject(ofClass: UIImage.self) }) {
221 loadImages(from: itemProviders)
222 return
223 }
224 super.paste(itemProviders: itemProviders)
225 }
226
227 override func paste(_ sender: Any?) {
228 guard !isReadOnly else {
229 return
230 }
231 let pasteboard = UIPasteboard.general
232 let context = T3ComposerClipboard.read()
233 if !context["fragment", default: ""].isEmpty || context["html", default: ""].contains("data-t3-context-fragment=") {
234 onPasteContext?(context)
235 return
236 }
237 let imageProviders = pasteboard.itemProviders.filter {
238 $0.canLoadObject(ofClass: UIImage.self)
239 }
240 if !imageProviders.isEmpty {
241 loadImages(from: imageProviders)
242 return
243 }
244
245 let images = pasteboard.images ?? []
246 if !images.isEmpty {
247 let urls = images.compactMap(Self.writeTemporaryImage)
248 if !urls.isEmpty {
249 onPasteImages?(urls)
250 return
251 }
252 }
253 // pasteboard.string is only the first item; super.paste inserts every text item.
254 if !bypassTextPasteInterception,
255 let text = pasteboard.strings?.joined(), shouldInterceptTextPaste(text) {
256 onPasteText?(text, selectedRange)
257 return
258 }
259 // read() sees only the first item; native paste keeps every item of a longer pasteboard.
260 if !bypassTextPasteInterception, pasteboard.numberOfItems == 1,
261 T3ComposerClipboard.hasThreadLink(context["text", default: ""]) {
262 onPasteContext?(context)
263 return
264 }
265 super.paste(sender)
266 }
267
268 private func shouldInterceptTextPaste(_ text: String) -> Bool {
269 guard textPasteThresholdBytes > 0, !text.isEmpty else { return false }
270 let pastedLength = (text as NSString).length
271 if pastedLength >= textPasteThresholdBytes || text.utf8.count >= textPasteThresholdBytes {
272 return true
273 }
274 // Chips occupy one display character but expand to their source in the
275 // submitted message. Measure that source, including the replaced selection.
276 let sourceLength = sourceOffset(forDisplayOffset: attributedText.length)
277 let selectedLength = sourceOffset(forDisplayOffset: NSMaxRange(selectedRange)) -
278 sourceOffset(forDisplayOffset: selectedRange.location)
279 return sourceLength - selectedLength + pastedLength > maxInputChars
280 }
281
282 override func deleteBackward() {
283 guard !isReadOnly else {
284 return
285 }
286 guard selectedRange.length == 0, selectedRange.location > 0 else {
287 super.deleteBackward()
288 return
289 }
290
291 let previousOffset = selectedRange.location - 1
292 if textStorage.attribute(.attachment, at: previousOffset, effectiveRange: nil)
293 is ComposerTextAttachment {
294 replaceDisplayRange(NSRange(location: previousOffset, length: 1))
295 return
296 }
297
298 super.deleteBackward()
299 }
300
301 private func replaceDisplayRange(_ range: NSRange) {
302 guard let start = position(from: beginningOfDocument, offset: range.location),
303 let end = position(from: start, offset: range.length),
304 let textRange = textRange(from: start, to: end) else {
305 return
306 }
307 replace(textRange, withText: "")
308 }
309
310 func loadImages(from providers: [NSItemProvider]) {
311 let group = DispatchGroup()
312 let lock = NSLock()
313 var images = [(data: Data, fileExtension: String)?](repeating: nil, count: providers.count)
314
315 for (index, provider) in providers.enumerated() {
316 group.enter()
317 let store = { (image: (data: Data, fileExtension: String)?) in
318 lock.lock()
319 images[index] = image
320 lock.unlock()
321 group.leave()
322 }
323 let loadPNG = {
324 _ = provider.loadObject(ofClass: UIImage.self) { object, _ in
325 store((object as? UIImage)?.pngData().map { ($0, "png") })
326 }
327 }
328 // Decoding a GIF to UIImage keeps only its first frame, so pass its bytes through.
329 if provider.hasItemConformingToTypeIdentifier(UTType.gif.identifier) {
330 _ = provider.loadDataRepresentation(forTypeIdentifier: UTType.gif.identifier) { data, _ in
331 if let data { store((data, "gif")) } else { loadPNG() }
332 }
333 } else {
334 loadPNG()
335 }
336 }
337
338 group.notify(queue: .main) { [weak self] in
339 guard let self, !self.isReadOnly else {
340 return
341 }
342 let urls = images.compactMap { $0 }.compactMap {
343 Self.writeTemporaryImage($0.data, fileExtension: $0.fileExtension)
344 }
345 if !urls.isEmpty {
346 self.onPasteImages?(urls)
347 }
348 }
349 }
350
351 override func copy(_ sender: Any?) {
352 guard selectedRange.length > 0 else {
353 return super.copy(sender)
354 }
355 T3ComposerClipboard.write(text: serializedText(in: selectedRange), fragment: clipboardFragment)
356 }
357
358 override func cut(_ sender: Any?) {
359 guard !isReadOnly else {
360 return
361 }
362 guard isEditable, selectedRange.length > 0 else {
363 return super.cut(sender)
364 }
365 copy(sender)
366 replaceDisplayRange(selectedRange)
367 }
368
369 func serializedText() -> String {
370 serializedText(in: NSRange(location: 0, length: attributedText.length))
371 }
372
373 func serializedText(in range: NSRange) -> String {
374 guard range.length > 0 else {
375 return ""
376 }
377
378 let source = NSMutableString()
379 let nsString = attributedText.string as NSString
380 var cursor = range.location
381 let end = NSMaxRange(range)
382 attributedText.enumerateAttribute(.attachment, in: range) { value, attachmentRange, _ in
383 if attachmentRange.location > cursor {
384 source.append(
385 nsString.substring(
386 with: NSRange(location: cursor, length: attachmentRange.location - cursor)
387 )
388 )
389 }
390 if let attachment = value as? ComposerTextAttachment {
391 source.append(attachment.source)
392 } else {
393 source.append(nsString.substring(with: attachmentRange))
394 }
395 cursor = NSMaxRange(attachmentRange)
396 }
397 if cursor < end {
398 source.append(nsString.substring(with: NSRange(location: cursor, length: end - cursor)))
399 }
400 return source as String
401 }
402
403 func sourceOffset(forDisplayOffset displayOffset: Int) -> Int {
404 let boundedOffset = max(0, min(attributedText.length, displayOffset))
405 if boundedOffset == 0 {
406 return 0
407 }
408
409 var sourceOffset = 0
410 let range = NSRange(location: 0, length: boundedOffset)
411 attributedText.enumerateAttribute(.attachment, in: range) { value, attributeRange, _ in
412 if let attachment = value as? ComposerTextAttachment {
413 sourceOffset += (attachment.source as NSString).length
414 } else {
415 sourceOffset += attributeRange.length
416 }
417 }
418 return sourceOffset
419 }
420
421 private static func writeTemporaryImage(_ image: UIImage) -> String? {
422 image.pngData().flatMap { writeTemporaryImage($0, fileExtension: "png") }
423 }
424
425 private static func writeTemporaryImage(_ data: Data, fileExtension: String) -> String? {
426 let directory = FileManager.default.temporaryDirectory
427 .appendingPathComponent(pastedImageDirectoryName, isDirectory: true)
428 do {
429 try FileManager.default.createDirectory(
430 at: directory,
431 withIntermediateDirectories: true
432 )
433 removeStaleTemporaryImages(in: directory)
434 let url = directory.appendingPathComponent("\(UUID().uuidString).\(fileExtension)")
435 try data.write(to: url, options: .atomic)
436 return url.absoluteString
437 } catch {
438 return nil
439 }
440 }
441
442 private static func removeStaleTemporaryImages(in directory: URL) {
443 let cutoff = Date().addingTimeInterval(-stalePastedImageAge)
444 guard let urls = try? FileManager.default.contentsOfDirectory(
445 at: directory,
446 includingPropertiesForKeys: [.contentModificationDateKey, .isRegularFileKey],
447 options: [.skipsHiddenFiles]
448 ) else {
449 return
450 }
451
452 for url in urls {
453 guard
454 let values = try? url.resourceValues(
455 forKeys: [.contentModificationDateKey, .isRegularFileKey]
456 ),
457 values.isRegularFile == true,
458 let modifiedAt = values.contentModificationDate,
459 modifiedAt < cutoff
460 else {
461 continue
462 }
463 try? FileManager.default.removeItem(at: url)
464 }
465 }
466 }
467
468 public final class T3ComposerEditorView: ExpoView, UITextViewDelegate, UITextDropDelegate, UIGestureRecognizerDelegate {
469 // This view reads `layoutManager`, which otherwise swaps a live TextKit 2 view to
470 // TextKit 1 mid-edit; that swap can leave typed text laid out but never drawn.
471 private let textView = ComposerTextView(usingTextLayoutManager: false)
472 private let placeholderLabel = UILabel()
473 private var value = ""
474 private var tokensJson = "[]"
475 private var tokens: [ComposerTokenPayload] = []
476 private var requestedSelection: ComposerSelectionPayload?
477 private var theme = ComposerThemePayload(
478 text: "#262626",
479 placeholder: "#8e8e93"
480 )
481 private var fontFamily = "DMSans-Regular"
482 private var fontSize: CGFloat = 14
483 private var lineHeight: CGFloat = 20
484 private var contentInsetVertical: CGFloat = 0
485 private var shouldAutoFocus = false
486 private var didAutoFocus = false
487 private var isReadOnly = false
488 private var isApplyingControlledValue = false
489 private var nativeEventCount = 0
490 // Count of the latest intercepted paste, so a flush can tell whether JS has received it.
491 private var lastPasteEventCount = 0
492 private var hasControlledDocument = false
493 private var resetGeneration = 0
494 private var lastContentSize = CGSize.zero
495 private var iconImages: [String: UIImage] = [:]
496 private var pendingIconUris = Set<String>()
497 private var tokensNeedRebuild = false
498 private var chipsNeedMeasuredWidth = false
499 private var hasDeferredForcedRebuild = false
500 private var pendingContentOffset: CGPoint?
501 private var needsSelectionReveal = false
502 private var selectionBeforeFocusingTap: (selection: ComposerSelectionPayload, value: String)?
503
504 let onComposerChange = EventDispatcher()
505 let onComposerSelectionChange = EventDispatcher()
506 let onComposerFocus = EventDispatcher()
507 let onComposerBlur = EventDispatcher()
508 let onComposerSubmit = EventDispatcher()
509 let onComposerPasteImages = EventDispatcher()
510 let onComposerContextPress = EventDispatcher()
511 let onComposerPasteContext = EventDispatcher()
512 let onComposerPasteText = EventDispatcher()
513 let onComposerContentSizeChange = EventDispatcher()
514
515 public required init(appContext: AppContext? = nil) {
516 super.init(appContext: appContext)
517
518 clipsToBounds = true
519 textView.clipsToBounds = true
520 textView.delegate = self
521 textView.textDropDelegate = self
522 textView.backgroundColor = .clear
523 textView.textContainerInset = .zero
524 textView.textContainer.lineFragmentPadding = 0
525 textView.keyboardDismissMode = .interactive
526 textView.alwaysBounceVertical = false
527 textView.showsVerticalScrollIndicator = true
528 textView.adjustsFontForContentSizeCategory = true
529 if #available(iOS 26.0, *) {
530 // UIKit can attach a nearby bar's scroll edge effect to this text view; its backdrop
531 // then draws over the typed text while the caret stays visible.
532 let edges = [textView.topEdgeEffect, textView.leftEdgeEffect, textView.bottomEdgeEffect, textView.rightEdgeEffect]
533 for edge in edges {
534 edge.isHidden = true
535 }
536 }
537 textView.onPasteImages = { [weak self] urls in
538 self?.onComposerPasteImages(["uris": urls])
539 }
540 textView.onPasteContext = { [weak self] context in
541 guard let self else { return }
542 let selection = self.sourceSelection()
543 self.nativeEventCount += 1
544 self.lastPasteEventCount = self.nativeEventCount
545 var payload: [String: Any] = context
546 payload["value"] = self.textView.serializedText()
547 payload["eventCount"] = self.nativeEventCount
548 payload["resetGeneration"] = self.resetGeneration
549 payload["selection"] = ["start": selection.start, "end": selection.end]
550 self.onComposerPasteContext(payload)
551 }
552 textView.onPasteText = { [weak self] text, _ in
553 guard let self else { return }
554 let selection = self.sourceSelection()
555 self.nativeEventCount += 1
556 self.lastPasteEventCount = self.nativeEventCount
557 self.onComposerPasteText([
558 "value": self.textView.serializedText(),
559 "eventCount": self.nativeEventCount,
560 "resetGeneration": self.resetGeneration,
561 "text": text,
562 "selection": ["start": selection.start, "end": selection.end],
563 ])
564 }
565 textView.onSubmit = { [weak self] alternate in
566 self?.onComposerSubmit(["alternate": alternate])
567 }
568 let contextTap = UITapGestureRecognizer(target: self, action: #selector(openContext(_:)))
569 contextTap.cancelsTouchesInView = false
570 contextTap.delegate = self
571 textView.addGestureRecognizer(contextTap)
572 addSubview(textView)
573
574 placeholderLabel.numberOfLines = 0
575 placeholderLabel.adjustsFontForContentSizeCategory = true
576 addSubview(placeholderLabel)
577 applyTypography()
578 applyTheme()
579 }
580
581 @objc private func openContext(_ recognizer: UITapGestureRecognizer) {
582 guard let (index, attachment) = contextAttachment(at: recognizer.location(in: textView)) else {
583 textView.becomeFirstResponder()
584 if selectionBeforeFocusingTap != nil {
585 // UIKit places the caret from its own tap recognizer during this same touch.
586 DispatchQueue.main.async { [weak self] in
587 self?.restoreSelectionBeforeFocusingTap()
588 }
589 }
590 return
591 }
592 openContext(index: index, attachment: attachment)
593 }
594
595 private func openContext(index: Int, attachment: ComposerTextAttachment) {
596 let start = textView.sourceOffset(forDisplayOffset: index)
597 onComposerContextPress(["source": attachment.source, "start": start, "end": start + (attachment.source as NSString).length])
598 }
599
600 public override var accessibilityElements: [Any]? {
601 get {
602 var elements: [Any] = [textView]
603 let layout = textView.layoutManager
604 textView.textStorage.enumerateAttribute(.attachment, in: NSRange(location: 0, length: textView.textStorage.length)) { value, range, _ in
605 guard let attachment = value as? ComposerTextAttachment else { return }
606 let glyphRange = layout.glyphRange(forCharacterRange: range, actualCharacterRange: nil)
607 let rect = layout.boundingRect(forGlyphRange: glyphRange, in: textView.textContainer)
608 .offsetBy(dx: textView.textContainerInset.left, dy: textView.textContainerInset.top)
609 guard rect.intersects(textView.bounds) else { return }
610 let element = ComposerContextAccessibilityElement(accessibilityContainer: self)
611 element.accessibilityLabel = attachment.label
612 element.accessibilityTraits = .button
613 element.accessibilityFrameInContainerSpace = textView.convert(rect, to: self)
614 element.activate = { [weak self] in
615 guard let self, range.location < self.textView.textStorage.length,
616 self.textView.textStorage.attribute(.attachment, at: range.location, effectiveRange: nil) as? ComposerTextAttachment === attachment else { return false }
617 self.openContext(index: range.location, attachment: attachment)
618 return true
619 }
620 elements.append(element)
621 }
622 return elements
623 }
624 set { super.accessibilityElements = newValue }
625 }
626
627 public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
628 // The collapsed editor only shows the draft's first line, so a tap that expands an
629 // overflowing draft returns to the caret it was left at instead of moving it there.
630 let collapsedOverflow = !textView.isFirstResponder && !textView.isScrollEnabled && draftOverflowsBounds()
631 selectionBeforeFocusingTap = collapsedOverflow ? (sourceSelection(), value) : nil
632 return true
633 }
634
635 public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
636 true
637 }
638
639 public func textView(_ textView: UITextView, shouldInteractWith textAttachment: NSTextAttachment, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
640 // A chip is text context, not an image to save to the camera roll.
641 !(textAttachment is ComposerTextAttachment)
642 }
643
644 private func contextAttachment(at point: CGPoint) -> (Int, ComposerTextAttachment)? {
645 let containerPoint = CGPoint(x: point.x - textView.textContainerInset.left, y: point.y - textView.textContainerInset.top)
646 let layout = textView.layoutManager
647 let index = layout.characterIndex(for: containerPoint, in: textView.textContainer, fractionOfDistanceBetweenInsertionPoints: nil)
648 guard index < textView.textStorage.length,
649 let attachment = textView.textStorage.attribute(.attachment, at: index, effectiveRange: nil) as? ComposerTextAttachment else { return nil }
650 let glyphRange = layout.glyphRange(forCharacterRange: NSRange(location: index, length: 1), actualCharacterRange: nil)
651 guard layout.boundingRect(forGlyphRange: glyphRange, in: textView.textContainer).contains(containerPoint) else { return nil }
652 return (index, attachment)
653 }
654
655 public override func layoutSubviews() {
656 super.layoutSubviews()
657 let previousSize = textView.bounds.size
658 textView.frame = bounds
659 if chipsNeedMeasuredWidth, bounds.width > 0 {
660 chipsNeedMeasuredWidth = false
661 applyControlledDocument(force: true)
662 }
663 if textView.isScrollEnabled, bounds.width > 0, bounds.height > 0 {
664 textView.layoutIfNeeded()
665 if let offset = pendingContentOffset {
666 let minY = -textView.adjustedContentInset.top
667 let maxY = max(minY, textView.contentSize.height - bounds.height + textView.adjustedContentInset.bottom)
668 textView.setContentOffset(CGPoint(x: offset.x, y: min(maxY, max(minY, offset.y))), animated: false)
669 pendingContentOffset = nil
670 }
671 if needsSelectionReveal || (previousSize != bounds.size && textView.isFirstResponder) {
672 needsSelectionReveal = false
673 if let selection = textView.selectedTextRange {
674 textView.scrollRectToVisible(textView.caretRect(for: selection.end), animated: false)
675 }
676 }
677 }
678 let placeholderX = textView.textContainerInset.left + textView.textContainer.lineFragmentPadding
679 let placeholderY = textView.textContainerInset.top
680 let placeholderWidth = max(
681 0,
682 bounds.width - placeholderX - textView.textContainerInset.right -
683 textView.textContainer.lineFragmentPadding
684 )
685 placeholderLabel.frame = CGRect(
686 x: placeholderX,
687 y: placeholderY,
688 width: placeholderWidth,
689 height: max(lineHeight, placeholderLabel.font.lineHeight)
690 )
691 emitContentSizeIfNeeded()
692 }
693
694 func setClipboardFragment(_ fragment: String) {
695 textView.clipboardFragment = fragment
696 }
697
698 public override func didMoveToWindow() {
699 super.didMoveToWindow()
700 guard window != nil, shouldAutoFocus, !didAutoFocus else {
701 return
702 }
703 didAutoFocus = true
704 DispatchQueue.main.async { [weak self] in
705 self?.textView.becomeFirstResponder()
706 }
707 }
708
709 func setControlledDocumentJson(_ documentJson: String) {
710 guard let document = decode(ComposerControlledDocumentPayload.self, from: documentJson) else {
711 return
712 }
713 // A parent reset (a send clear) wins over native edits it could not see; JS drops their events
714 // by generation, so the revision restarts where the parent last acknowledged.
715 let isReset = document.resetGeneration > resetGeneration
716 guard isReset || document.mostRecentEventCount >= nativeEventCount else {
717 return
718 }
719 if isReset {
720 resetGeneration = document.resetGeneration
721 // JS drops a paste from before the reset by generation, so the flush must not wait for it.
722 lastPasteEventCount = 0
723 endComposition()
724 }
725 // iOS destroys this view under display: none and mounts a fresh one while JS keeps its
726 // revision and draft. Continue from them, or JS drops every event the new view sends.
727 nativeEventCount = document.mostRecentEventCount
728 if document.isNativeEcho && !isReset && hasControlledDocument && textView.serializedText() != document.value {
729 return
730 }
731 hasControlledDocument = true
732 if tokensJson != document.tokensJson {
733 tokensJson = document.tokensJson
734 let nextTokens = decode([ComposerTokenPayload].self, from: document.tokensJson) ?? []
735 // Rebuild only when a chip on screen would look different: typing before a chip moves its
736 // offsets, and Undo restores the chip it removed. A rebuild there makes iOS autocorrect
737 // behind the caret, and replacing the text drops UIKit's Redo.
738 tokensNeedRebuild = tokensNeedRebuild || !nextTokens.elementsEqual(renderedChipTokens(), by: { $0.rendersLike($1) })
739 tokens = nextTokens
740 }
741 let previousSelection = sourceSelection()
742 value = document.value
743 requestedSelection = document.selection
744 applyControlledDocument(force: tokensNeedRebuild)
745 applyRequestedSelection()
746 cancelFocusingTapRestoreIfSelectionMoved(from: previousSelection)
747 if tokensMatchCurrentValue() {
748 tokensNeedRebuild = false
749 }
750 }
751
752 func setThemeJson(_ themeJson: String) {
753 guard let nextTheme = decode(ComposerThemePayload.self, from: themeJson) else {
754 return
755 }
756 theme = nextTheme
757 applyTheme()
758 applyControlledDocument(force: true)
759 }
760
761 func setPlaceholder(_ placeholder: String) {
762 placeholderLabel.text = placeholder
763 textView.accessibilityLabel = placeholder
764 setNeedsLayout()
765 }
766
767 func setFontFamily(_ fontFamily: String) {
768 self.fontFamily = fontFamily
769 applyTypography()
770 applyControlledDocument(force: true)
771 }
772
773 func setFontSize(_ fontSize: CGFloat) {
774 self.fontSize = fontSize
775 applyTypography()
776 applyControlledDocument(force: true)
777 }
778
779 func setLineHeight(_ lineHeight: CGFloat) {
780 self.lineHeight = lineHeight
781 applyTypography()
782 applyControlledDocument(force: true)
783 }
784
785 func setContentInsetVertical(_ contentInsetVertical: CGFloat) {
786 self.contentInsetVertical = contentInsetVertical
787 textView.textContainerInset = UIEdgeInsets(
788 top: contentInsetVertical,
789 left: 0,
790 bottom: contentInsetVertical,
791 right: 0
792 )
793 setNeedsLayout()
794 }
795
796 func setEditable(_ editable: Bool) {
797 textView.isEditable = editable
798 }
799
800 func setReadOnly(_ readOnly: Bool) {
801 isReadOnly = readOnly
802 textView.isReadOnly = readOnly
803 }
804
805 func setScrollEnabled(_ scrollEnabled: Bool) {
806 guard textView.isScrollEnabled != scrollEnabled else { return }
807 if !scrollEnabled {
808 // Disabling scrolling discards UITextView's offset. Restore it after
809 // expansion has laid out the text, regardless of prop update order.
810 pendingContentOffset = pendingContentOffset ?? textView.contentOffset
811 }
812 textView.isScrollEnabled = scrollEnabled
813 if scrollEnabled {
814 revealSelectionAfterLayout()
815 }
816 }
817
818 func setAutoFocus(_ autoFocus: Bool) {
819 shouldAutoFocus = autoFocus
820 }
821
822 func setAutoCorrect(_ autoCorrect: Bool) {
823 textView.autocorrectionType = autoCorrect ? .yes : .no
824 }
825
826 func setSpellCheck(_ spellCheck: Bool) {
827 textView.spellCheckingType = spellCheck ? .yes : .no
828 }
829
830 func setEnterBehavior(_ behavior: String) {
831 textView.enterBehavior = ComposerEnterBehavior(rawValue: behavior) ?? .send
832 }
833
834 func setSubmitTitle(_ title: String) {
835 textView.submitTitle = title
836 }
837
838 func setAlternateSubmitTitle(_ title: String) {
839 textView.alternateSubmitTitle = title
840 }
841
842 func setTextPasteThresholdBytes(_ threshold: Int) {
843 textView.textPasteThresholdBytes = threshold
844 }
845
846 func setMaxInputChars(_ maxInputChars: Int) {
847 textView.maxInputChars = maxInputChars
848 }
849
850 func focusEditor() {
851 textView.becomeFirstResponder()
852 }
853
854 func blurEditor() {
855 textView.resignFirstResponder()
856 }
857
858 func readState() -> [String: Any] {
859 let selection = sourceSelection()
860 return [
861 "value": value,
862 "selection": ["start": selection.start, "end": selection.end],
863 "eventCount": nativeEventCount,
864 "resetGeneration": resetGeneration,
865 "pasteEventCount": lastPasteEventCount,
866 ]
867 }
868
869 func setSelection(start: Int, end: Int) {
870 let previousSelection = sourceSelection()
871 requestedSelection = ComposerSelectionPayload(start: start, end: end)
872 applyRequestedSelection()
873 cancelFocusingTapRestoreIfSelectionMoved(from: previousSelection)
874 }
875
876 public func textViewDidChange(_ textView: UITextView) {
877 emitTextChange()
878 }
879
880 public func textViewDidChangeSelection(_ textView: UITextView) {
881 guard !isApplyingControlledValue else {
882 return
883 }
884 restoreBaseTypingAttributes()
885 // UIKit moves the selection before textViewDidChange runs. Emitting here
886 // would pair the post-edit text with a pre-edit revision counter, so let
887 // the change event that follows carry both; only pure caret moves emit.
888 guard self.textView.serializedText() == value else {
889 return
890 }
891 emitSelection()
892 }
893
894 public func textView(
895 _ textView: UITextView,
896 shouldChangeTextIn range: NSRange,
897 replacementText text: String
898 ) -> Bool {
899 restoreBaseTypingAttributes()
900 return !isReadOnly
901 }
902
903 public func textDroppableView(
904 _ textDroppableView: UIView & UITextDroppable,
905 proposalForDrop drop: UITextDropRequest
906 ) -> UITextDropProposal {
907 guard !isReadOnly else {
908 return UITextDropProposal(operation: .cancel)
909 }
910 guard droppedImageProviders(in: drop) != nil else {
911 return drop.suggestedProposal
912 }
913
914 // The composer owns image drops so UIKit does not insert NSTextAttachments
915 // that the controlled plain-text value cannot represent.
916 let proposal = UITextDropProposal(operation: .copy)
917 proposal.dropAction = .insert
918 proposal.dropPerformer = .delegate
919 return proposal
920 }
921
922 public func textDroppableView(
923 _ textDroppableView: UIView & UITextDroppable,
924 willPerformDrop drop: UITextDropRequest
925 ) {
926 guard !isReadOnly else {
927 return
928 }
929 guard let imageProviders = droppedImageProviders(in: drop) else {
930 return
931 }
932 textView.loadImages(from: imageProviders)
933 }
934
935 private func droppedImageProviders(in drop: UITextDropRequest) -> [NSItemProvider]? {
936 let providers = drop.dropSession.items.map(\.itemProvider)
937 guard !providers.isEmpty,
938 providers.allSatisfy({ $0.canLoadObject(ofClass: UIImage.self) }) else {
939 return nil
940 }
941 return providers
942 }
943
944 public func textViewDidBeginEditing(_ textView: UITextView) {
945 revealSelectionAfterLayout()
946 onComposerFocus()
947 }
948
949 public func textViewDidEndEditing(_ textView: UITextView) {
950 onComposerBlur()
951 }
952
953 private func applyControlledDocument(force: Bool = false) {
954 // Rebuilding the attributed string tears down an active IME composition.
955 // Skip while marked text exists; committing the composition sends a new
956 // value from JS, and that update rebuilds, keeping any skipped force.
957 if textView.markedTextRange != nil {
958 hasDeferredForcedRebuild = hasDeferredForcedRebuild || force
959 updatePlaceholderVisibility()
960 return
961 }
962 let shouldForce = force || hasDeferredForcedRebuild
963 let currentSource = textView.serializedText()
964 guard shouldForce || currentSource != value || !documentMatchesExpectedTokens() else {
965 updatePlaceholderVisibility()
966 return
967 }
968 hasDeferredForcedRebuild = false
969
970 let previousSelection = sourceSelection()
971 if textView.isScrollEnabled {
972 pendingContentOffset = pendingContentOffset ?? textView.contentOffset
973 }
974 isApplyingControlledValue = true
975 textView.attributedText = makeAttributedDocument()
976 let targetSelection = requestedSelection ?? previousSelection
977 requestedSelection = nil
978 textView.selectedRange = displayRange(for: targetSelection)
979 restoreBaseTypingAttributes()
980 isApplyingControlledValue = false
981 if currentSource != value || previousSelection.start != targetSelection.start || previousSelection.end != targetSelection.end {
982 revealSelectionAfterLayout()
983 } else {
984 setNeedsLayout()
985 }
986 updatePlaceholderVisibility()
987 emitContentSizeIfNeeded()
988 }
989
990 private func endComposition() {
991 guard textView.markedTextRange != nil else {
992 return
993 }
994 isApplyingControlledValue = true
995 textView.unmarkText()
996 isApplyingControlledValue = false
997 }
998
999 private func makeAttributedDocument() -> NSAttributedString {
1000 let result = NSMutableAttributedString()
1001 let source = value as NSString
1002 var cursor = 0
1003 let validTokens = tokens.filter {
1004 $0.start >= cursor &&
1005 $0.end > $0.start &&
1006 $0.end <= source.length &&
1007 source.substring(with: NSRange(location: $0.start, length: $0.end - $0.start)) == $0.source
1008 }
1009
1010 for token in validTokens {
1011 if token.start < cursor {
1012 continue
1013 }
1014 if token.start > cursor {
1015 appendPlainText(
1016 source.substring(with: NSRange(location: cursor, length: token.start - cursor)),
1017 to: result
1018 )
1019 }
1020 result.append(makeAttachmentString(token))
1021 cursor = token.end
1022 }
1023 if cursor < source.length {
1024 appendPlainText(
1025 source.substring(with: NSRange(location: cursor, length: source.length - cursor)),
1026 to: result
1027 )
1028 }
1029 return result
1030 }
1031
1032 private func appendPlainText(_ text: String, to result: NSMutableAttributedString) {
1033 result.append(NSAttributedString(string: text, attributes: baseAttributes()))
1034 }
1035
1036 private func makeAttachmentString(_ token: ComposerTokenPayload) -> NSAttributedString {
1037 let color = token.accent.flatMap { UIColor(composerHex: $0) }
1038 ?? UIColor(composerHex: theme.text) ?? .label
1039 let chipFont = UIFont(name: "DMSans-Medium", size: fontSize)
1040 ?? UIFont.systemFont(ofSize: fontSize, weight: .medium)
1041 let icon = token.iconUri.flatMap(iconImage(for:)).map {
1042 token.tintsIcon == true ? Self.tinted($0, color: color) : $0
1043 }
1044 let image = renderChip(
1045 label: token.label,
1046 detail: token.detail,
1047 icon: icon,
1048 color: color,
1049 font: chipFont
1050 )
1051 let attachment = ComposerTextAttachment(
1052 token: token,
1053 image: image,
1054 size: image.size,
1055 baselineOffset: chipFont.ascender - image.size.height
1056 )
1057 let attributedAttachment = NSMutableAttributedString(attachment: attachment)
1058 attributedAttachment.addAttributes(
1059 baseAttributes(),
1060 range: NSRange(location: 0, length: attributedAttachment.length)
1061 )
1062 return attributedAttachment
1063 }
1064
1065 private func renderChip(
1066 label: String,
1067 detail: String?,
1068 icon: UIImage?,
1069 color: UIColor,
1070 font: UIFont
1071 ) -> UIImage {
1072 let paragraph = NSMutableParagraphStyle()
1073 paragraph.alignment = .left
1074 paragraph.lineBreakMode = .byTruncatingMiddle
1075 let attributedLabel = NSMutableAttributedString(
1076 string: label,
1077 attributes: [.font: font, .foregroundColor: color, .paragraphStyle: paragraph]
1078 )
1079 // The size reads as metadata, not part of the name, so it renders a step down from the
1080 // label the way the web chip does.
1081 if let detail, !detail.isEmpty {
1082 let detailFont = font.withSize(font.pointSize * 0.84)
1083 attributedLabel.append(
1084 NSAttributedString(
1085 string: " \(detail)",
1086 attributes: [.font: detailFont, .foregroundColor: color, .paragraphStyle: paragraph]
1087 )
1088 )
1089 }
1090 let iconSide = font.pointSize
1091 let iconSlot: CGFloat = icon == nil ? 0 : iconSide * 1.25
1092 let padding: CGFloat = 5
1093 let height = ceil(font.ascender - font.descender)
1094 // A long path would otherwise draw a chip wider than the composer and clip. Cap the label
1095 // to the text the editor can actually show and truncate inside it, as Android's
1096 // `maximumWidth` does, so the chip always fits the line it sits on.
1097 let availableWidth = textView.textContainer.size.width > 0
1098 ? textView.textContainer.size.width - textView.textContainer.lineFragmentPadding * 2
1099 : (textView.window?.bounds.width ?? bounds.width)
1100 if availableWidth <= 0 {
1101 chipsNeedMeasuredWidth = true
1102 }
1103 let maximumLabelWidth = max(font.pointSize * 3, availableWidth - padding * 2 - iconSlot)
1104 let labelWidth = min(attributedLabel.size().width, maximumLabelWidth)
1105 let width = ceil(padding * 2 + iconSlot + labelWidth)
1106 let format = UIGraphicsImageRendererFormat.preferred()
1107 format.opaque = false
1108 let renderer = UIGraphicsImageRenderer(size: CGSize(width: width, height: height), format: format)
1109 return renderer.image { _ in
1110 if let icon {
1111 icon.draw(
1112 in: CGRect(x: padding, y: (height - iconSide) / 2, width: iconSide, height: iconSide)
1113 )
1114 }
1115 // Exactly the measured width: a spare pixel here would let a capped label draw past
1116 // the cap instead of truncating inside it.
1117 attributedLabel.draw(
1118 in: CGRect(x: padding + iconSlot, y: 0, width: labelWidth, height: height)
1119 )
1120 }
1121 }
1122
1123 private static func tinted(_ image: UIImage, color: UIColor) -> UIImage {
1124 let format = UIGraphicsImageRendererFormat.preferred()
1125 format.scale = image.scale
1126 format.opaque = false
1127 return UIGraphicsImageRenderer(size: image.size, format: format).image { _ in
1128 color.setFill()
1129 UIRectFill(CGRect(origin: .zero, size: image.size))
1130 image.draw(at: .zero, blendMode: .destinationIn, alpha: 1)
1131 }
1132 }
1133
1134 private func iconImage(for uri: String) -> UIImage? {
1135 if let image = iconImages[uri] {
1136 return image
1137 }
1138 guard !pendingIconUris.contains(uri), let url = URL(string: uri) else {
1139 return nil
1140 }
1141
1142 if url.isFileURL, let image = UIImage(contentsOfFile: url.path) {
1143 iconImages[uri] = image
1144 return image
1145 }
1146
1147 pendingIconUris.insert(uri)
1148 URLSession.shared.dataTask(with: url) { [weak self] data, _, _ in
1149 guard let self, let data, let image = UIImage(data: data) else {
1150 DispatchQueue.main.async {
1151 self?.pendingIconUris.remove(uri)
1152 }
1153 return
1154 }
1155 DispatchQueue.main.async {
1156 self.pendingIconUris.remove(uri)
1157 self.iconImages[uri] = image
1158 self.applyControlledDocument(force: true)
1159 }
1160 }.resume()
1161 return nil
1162 }
1163
1164 private func baseAttributes() -> [NSAttributedString.Key: Any] {
1165 let font = UIFont(name: fontFamily, size: fontSize)
1166 ?? UIFont.systemFont(ofSize: fontSize)
1167 let paragraph = NSMutableParagraphStyle()
1168 paragraph.minimumLineHeight = lineHeight
1169 paragraph.maximumLineHeight = lineHeight
1170 return [
1171 .font: font,
1172 .foregroundColor: UIColor(composerHex: theme.text) ?? .label,
1173 .paragraphStyle: paragraph,
1174 ]
1175 }
1176
1177 private func applyTypography() {
1178 let font = UIFont(name: fontFamily, size: fontSize)
1179 ?? UIFont.systemFont(ofSize: fontSize)
1180 textView.font = font
1181 restoreBaseTypingAttributes()
1182 placeholderLabel.font = font
1183 setNeedsLayout()
1184 }
1185
1186 private func restoreBaseTypingAttributes() {
1187 guard textView.markedTextRange == nil else {
1188 return
1189 }
1190 textView.typingAttributes = baseAttributes()
1191 }
1192
1193 private func applyTheme() {
1194 textView.textColor = UIColor(composerHex: theme.text) ?? .label
1195 placeholderLabel.textColor = UIColor(composerHex: theme.placeholder) ?? .placeholderText
1196 tintColor = UIColor.systemBlue
1197 }
1198
1199 private func emitTextChange() {
1200 guard !isApplyingControlledValue else {
1201 return
1202 }
1203 value = textView.serializedText()
1204 revealSelectionAfterLayout()
1205 let selection = sourceSelection()
1206 nativeEventCount += 1
1207 onComposerChange([
1208 "value": value,
1209 "selection": ["start": selection.start, "end": selection.end],
1210 "eventCount": nativeEventCount,
1211 "resetGeneration": resetGeneration,
1212 ])
1213 updatePlaceholderVisibility()
1214 emitContentSizeIfNeeded()
1215 }
1216
1217 private func emitSelection() {
1218 // Caret moves advance the revision counter like text edits do: a
1219 // controlled payload computed before this move is stale and must fail the
1220 // revision guard instead of yanking the caret back mid-typing.
1221 let currentValue = textView.serializedText()
1222 let selection = sourceSelection()
1223 nativeEventCount += 1
1224 onComposerSelectionChange([
1225 "value": currentValue,
1226 "selection": ["start": selection.start, "end": selection.end],
1227 "eventCount": nativeEventCount,
1228 "resetGeneration": resetGeneration,
1229 ])
1230 }
1231
1232 private func sourceSelection() -> ComposerSelectionPayload {
1233 ComposerSelectionPayload(
1234 start: textView.sourceOffset(forDisplayOffset: textView.selectedRange.location),
1235 end: textView.sourceOffset(forDisplayOffset: NSMaxRange(textView.selectedRange))
1236 )
1237 }
1238
1239 private func displayRange(for selection: ComposerSelectionPayload) -> NSRange {
1240 let start = displayOffset(forSourceOffset: selection.start)
1241 let end = displayOffset(forSourceOffset: selection.end)
1242 return NSRange(location: start, length: max(0, end - start))
1243 }
1244
1245 private func displayOffset(forSourceOffset sourceOffset: Int) -> Int {
1246 let boundedOffset = max(0, min((value as NSString).length, sourceOffset))
1247 var collapsedLength = 0
1248 for token in tokens where token.end <= boundedOffset {
1249 collapsedLength += max(0, token.end - token.start - 1)
1250 }
1251 if let token = tokens.first(where: { $0.start < boundedOffset && boundedOffset < $0.end }) {
1252 return token.start - collapsedLength + 1
1253 }
1254 return boundedOffset - collapsedLength
1255 }
1256
1257 private func applyRequestedSelection() {
1258 guard let requestedSelection else {
1259 return
1260 }
1261 let nextRange = displayRange(for: requestedSelection)
1262 guard nextRange.location <= textView.attributedText.length,
1263 NSMaxRange(nextRange) <= textView.attributedText.length else {
1264 return
1265 }
1266 self.requestedSelection = nil
1267 // Programmatically assigning selectedRange resets the keyboard's
1268 // autocorrect and predictive-text context even when the range is
1269 // unchanged, so a no-op assignment must be skipped.
1270 guard !NSEqualRanges(nextRange, textView.selectedRange) else {
1271 return
1272 }
1273 isApplyingControlledValue = true
1274 textView.selectedRange = nextRange
1275 isApplyingControlledValue = false
1276 revealSelectionAfterLayout()
1277 }
1278
1279 private func restoreSelectionBeforeFocusingTap() {
1280 guard let snapshot = selectionBeforeFocusingTap else {
1281 return
1282 }
1283 selectionBeforeFocusingTap = nil
1284 // A draft that changed during the touch, such as a transcript landing, owns the caret now.
1285 guard textView.isFirstResponder, textView.markedTextRange == nil, value == snapshot.value else {
1286 return
1287 }
1288 let range = displayRange(for: snapshot.selection)
1289 guard !NSEqualRanges(range, textView.selectedRange) else {
1290 return
1291 }
1292 textView.selectedRange = range
1293 revealSelectionAfterLayout()
1294 }
1295
1296 private func cancelFocusingTapRestoreIfSelectionMoved(from previousSelection: ComposerSelectionPayload) {
1297 if sourceSelection() != previousSelection {
1298 selectionBeforeFocusingTap = nil
1299 }
1300 }
1301
1302 private func draftOverflowsBounds() -> Bool {
1303 let size = textView.sizeThatFits(CGSize(width: textView.bounds.width, height: .greatestFiniteMagnitude))
1304 return size.height > textView.bounds.height + 1
1305 }
1306
1307 private func revealSelectionAfterLayout() {
1308 needsSelectionReveal = true
1309 setNeedsLayout()
1310 }
1311
1312 private func updatePlaceholderVisibility() {
1313 placeholderLabel.isHidden = !value.isEmpty
1314 }
1315
1316 private func emitContentSizeIfNeeded() {
1317 guard bounds.width > 0 else { return }
1318 // Fit independently of the animated viewport: when scrolling is disabled,
1319 // its current height can clip TextKit's laid-out line fragments.
1320 let fittedHeight = textView.sizeThatFits(CGSize(width: bounds.width, height: .greatestFiniteMagnitude)).height
1321 - textView.textContainerInset.top - textView.textContainerInset.bottom
1322 let measuredHeight = min(lineHeight * 4, fittedHeight)
1323 let width = fittedHeight <= lineHeight + 0.5
1324 ? textView.layoutManager.usedRect(for: textView.textContainer).width
1325 : 0
1326 let nextSize = CGSize(width: ceil(width), height: ceil(measuredHeight))
1327 guard abs(nextSize.width - lastContentSize.width) > 0.5 ||
1328 abs(nextSize.height - lastContentSize.height) > 0.5 else {
1329 return
1330 }
1331 lastContentSize = nextSize
1332 onComposerContentSizeChange(["width": nextSize.width, "height": nextSize.height])
1333 }
1334
1335 private func decode<T: Decodable>(_ type: T.Type, from json: String) -> T? {
1336 guard let data = json.data(using: .utf8) else {
1337 return nil
1338 }
1339 return try? JSONDecoder().decode(type, from: data)
1340 }
1341
1342 private func tokensMatchCurrentValue() -> Bool {
1343 let source = value as NSString
1344 return tokens.allSatisfy {
1345 $0.start >= 0 &&
1346 $0.end > $0.start &&
1347 $0.end <= source.length &&
1348 source.substring(with: NSRange(location: $0.start, length: $0.end - $0.start)) == $0.source
1349 }
1350 }
1351
1352 private func renderedChipTokens() -> [ComposerTokenPayload] {
1353 var rendered: [ComposerTokenPayload] = []
1354 textView.textStorage.enumerateAttribute(
1355 .attachment,
1356 in: NSRange(location: 0, length: textView.textStorage.length)
1357 ) { value, _, _ in
1358 if let attachment = value as? ComposerTextAttachment {
1359 rendered.append(attachment.token)
1360 }
1361 }
1362 return rendered
1363 }
1364
1365 private func documentMatchesExpectedTokens() -> Bool {
1366 let source = value as NSString
1367 let expectedChips = tokens.compactMap { token -> (Int, String)? in
1368 guard token.start >= 0,
1369 token.end > token.start,
1370 token.end <= source.length,
1371 source.substring(
1372 with: NSRange(location: token.start, length: token.end - token.start)
1373 ) == token.source else {
1374 return nil
1375 }
1376 return (token.start, token.source)
1377 }
1378 var renderedChips: [(Int, String)] = []
1379 var sourceOffset = 0
1380 textView.attributedText.enumerateAttribute(
1381 .attachment,
1382 in: NSRange(location: 0, length: textView.attributedText.length)
1383 ) { value, range, _ in
1384 if let attachment = value as? ComposerTextAttachment {
1385 renderedChips.append((sourceOffset, attachment.source))
1386 sourceOffset += (attachment.source as NSString).length
1387 } else {
1388 sourceOffset += range.length
1389 }
1390 }
1391 return renderedChips.elementsEqual(expectedChips, by: ==)
1392 }
1393 }
1394
1395 private extension UIColor {
1396 convenience init?(composerHex hex: String?) {
1397 guard var value = hex?.trimmingCharacters(in: .whitespacesAndNewlines), !value.isEmpty else {
1398 return nil
1399 }
1400 if value.hasPrefix("#") {
1401 value.removeFirst()
1402 }
1403 guard value.count == 6 || value.count == 8,
1404 let raw = UInt64(value, radix: 16) else {
1405 return nil
1406 }
1407 if value.count == 8 {
1408 self.init(
1409 red: CGFloat((raw >> 24) & 0xff) / 255,
1410 green: CGFloat((raw >> 16) & 0xff) / 255,
1411 blue: CGFloat((raw >> 8) & 0xff) / 255,
1412 alpha: CGFloat(raw & 0xff) / 255
1413 )
1414 } else {
1415 self.init(
1416 red: CGFloat((raw >> 16) & 0xff) / 255,
1417 green: CGFloat((raw >> 8) & 0xff) / 255,
1418 blue: CGFloat(raw & 0xff) / 255,
1419 alpha: 1
1420 )
1421 }
1422 }
1423 }