@g9tm/lynxcontrols-native 2.5.7 → 2.5.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -0
- package/android/src/main/java/com/g9lynx/g9native/G9NativeImages.kt +24 -0
- package/android/src/main/java/com/g9lynx/g9native/blurhash/G9BlurhashUI.kt +76 -0
- package/android/src/main/java/com/g9lynx/g9native/blurhash/core/G9Blurhash.kt +100 -0
- package/android/src/main/java/com/g9lynx/g9native/canvas/G9CanvasModel.kt +94 -0
- package/android/src/main/java/com/g9lynx/g9native/canvas/G9CanvasPaths.kt +192 -0
- package/android/src/main/java/com/g9lynx/g9native/canvas/G9CanvasUI.kt +162 -0
- package/android/src/main/java/com/g9lynx/g9native/canvas/G9CanvasView.kt +1053 -0
- package/android/src/main/java/com/g9lynx/g9native/richtext/G9PictureSpan.kt +99 -0
- package/android/src/main/java/com/g9lynx/g9native/richtext/G9RichEditText.kt +458 -0
- package/android/src/main/java/com/g9lynx/g9native/richtext/G9RichStyle.kt +343 -0
- package/android/src/main/java/com/g9lynx/g9native/richtext/G9RichTextUI.kt +94 -0
- package/catalog/catalog.json +1 -1
- package/catalog/index.md +1 -1
- package/dist/.tsbuildinfo +1 -1
- package/ios/g9lynx-native-swift.podspec +20 -0
- package/ios/g9lynx-native.podspec +6 -2
- package/ios/src/G9LCBlurhashUI.h +14 -0
- package/ios/src/G9LCBlurhashUI.m +28 -0
- package/ios/src/G9LCCanvasUI.h +18 -0
- package/ios/src/G9LCCanvasUI.m +81 -0
- package/ios/src/G9LCRichTextUI.h +16 -0
- package/ios/src/G9LCRichTextUI.m +71 -0
- package/ios/swift/blurhash/G9LCBlurhashView.swift +165 -0
- package/ios/swift/canvas/G9LCCanvasCore.swift +848 -0
- package/ios/swift/canvas/G9LCCanvasView.swift +482 -0
- package/ios/swift/richtext/G9LCRichStyle.swift +238 -0
- package/ios/swift/richtext/G9LCRichTextView.swift +647 -0
- package/ios/swift/shared/G9LCColors.swift +78 -0
- package/ios/swift/shared/G9LCFonts.swift +38 -0
- package/ios/swift/shared/G9LCImages.swift +28 -0
- package/ios/swift/shared/G9LCJson.swift +73 -0
- package/package.json +6 -4
|
@@ -0,0 +1,647 @@
|
|
|
1
|
+
import UIKit
|
|
2
|
+
|
|
3
|
+
/// The text surface of `<g9-richtext>` (G9LCRichTextUI; 2.5.8, from G9Hub): a UITextView (TextKit 1) holding the document's flat text,
|
|
4
|
+
/// styled line by line from the app's line styles — the iOS twin of the Android host's G9RichEditText, following
|
|
5
|
+
/// client/app `features/docs/editor/element-core.ts`:
|
|
6
|
+
///
|
|
7
|
+
/// - every change of the text (typing, dictation, autocorrect, paste, deleting) is reported as one replacement
|
|
8
|
+
/// `rtedit {seq, base, from, to, text, len}` (diffed after UIKit applied it; nothing while an IME composes);
|
|
9
|
+
/// - an app message is applied only when its `ack` is the last `seq`: its replacements, the line changes (those lines
|
|
10
|
+
/// restyled), the selection, the collaborators' carets; then `rtapplied {rev}`; a message it cannot apply → `resync`;
|
|
11
|
+
/// - selection and focus changes → `rtselect`; checkbox, chip and picture taps, shortcuts → `rtaction`.
|
|
12
|
+
///
|
|
13
|
+
/// Positions are UTF-16 offsets (NSString), as in the protocol. List markers, checkboxes, quote bars and boxes are drawn
|
|
14
|
+
/// by overlay views from the laid-out lines; inline objects (U+FFFC) are text attachments.
|
|
15
|
+
@objc(G9LCRichTextView)
|
|
16
|
+
final class G9LCRichTextView: UIView, UITextViewDelegate, UIGestureRecognizerDelegate {
|
|
17
|
+
/// `(event name, detail)` → the element (G9LCRichTextUI).
|
|
18
|
+
@objc var emitter: ((String, [String: Any]) -> Void)?
|
|
19
|
+
|
|
20
|
+
private let storage: NSTextStorage
|
|
21
|
+
private let layout: NSLayoutManager
|
|
22
|
+
private let container: NSTextContainer
|
|
23
|
+
private let input: G9LCRichTextInput
|
|
24
|
+
private let backdrop = G9LCRichDecorations()
|
|
25
|
+
private let overlay = G9LCRichDecorations()
|
|
26
|
+
private let placeholderLabel = UILabel()
|
|
27
|
+
|
|
28
|
+
private var seq = 0
|
|
29
|
+
private var rev = 0
|
|
30
|
+
/// The app's lines as of `rev` (the base of the next line change).
|
|
31
|
+
private var appLines: [[String: Any]] = [["t": "p", "r": [Any]()]]
|
|
32
|
+
/// What is drawn: the app's lines, adjusted for edits the app has not answered yet.
|
|
33
|
+
private var lines: [[String: Any]] = [["t": "p", "r": [Any]()]]
|
|
34
|
+
private var lastText: NSString = ""
|
|
35
|
+
private var applying = false
|
|
36
|
+
private var editableMode = false
|
|
37
|
+
private var focusedNow = false
|
|
38
|
+
private var lastSel = NSRange(location: NSNotFound, length: 0)
|
|
39
|
+
private var waiting: [[String: Any]] = []
|
|
40
|
+
private struct Peer {
|
|
41
|
+
let a: Int
|
|
42
|
+
let h: Int
|
|
43
|
+
let color: UIColor
|
|
44
|
+
let name: String
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
private var peers: [Peer] = []
|
|
48
|
+
fileprivate var style = G9LCRichStyle()
|
|
49
|
+
private var lastWidth: CGFloat = 0
|
|
50
|
+
|
|
51
|
+
override init(frame: CGRect) {
|
|
52
|
+
let storage = NSTextStorage()
|
|
53
|
+
let layout = NSLayoutManager()
|
|
54
|
+
let container = NSTextContainer(size: CGSize(width: 0, height: CGFloat.greatestFiniteMagnitude))
|
|
55
|
+
layout.addTextContainer(container)
|
|
56
|
+
storage.addLayoutManager(layout)
|
|
57
|
+
self.storage = storage
|
|
58
|
+
self.layout = layout
|
|
59
|
+
self.container = container
|
|
60
|
+
input = G9LCRichTextInput(frame: .zero, textContainer: container)
|
|
61
|
+
super.init(frame: frame)
|
|
62
|
+
container.widthTracksTextView = true
|
|
63
|
+
input.delegate = self
|
|
64
|
+
input.backgroundColor = .clear
|
|
65
|
+
input.textContainerInset = UIEdgeInsets(top: 14, left: 12, bottom: 24, right: 12)
|
|
66
|
+
input.alwaysBounceVertical = true
|
|
67
|
+
input.keyboardDismissMode = .interactive
|
|
68
|
+
input.autocapitalizationType = .sentences
|
|
69
|
+
input.isEditable = false
|
|
70
|
+
input.isSelectable = true
|
|
71
|
+
input.dataDetectorTypes = []
|
|
72
|
+
input.font = style.font(size: 16, weight: 400)
|
|
73
|
+
input.textColor = style.text
|
|
74
|
+
input.frame = bounds
|
|
75
|
+
input.autoresizingMask = [.flexibleWidth, .flexibleHeight]
|
|
76
|
+
input.onKey = { [weak self] key in self?.key(key) }
|
|
77
|
+
input.onSoftBreak = { [weak self] in self?.softBreak() }
|
|
78
|
+
addSubview(input)
|
|
79
|
+
|
|
80
|
+
backdrop.isUserInteractionEnabled = false
|
|
81
|
+
backdrop.drawer = { [weak self] rect in self?.drawBackdrop(rect) }
|
|
82
|
+
input.insertSubview(backdrop, at: 0)
|
|
83
|
+
overlay.isUserInteractionEnabled = false
|
|
84
|
+
overlay.drawer = { [weak self] rect in self?.drawOverlay(rect) }
|
|
85
|
+
input.addSubview(overlay)
|
|
86
|
+
|
|
87
|
+
placeholderLabel.numberOfLines = 0
|
|
88
|
+
placeholderLabel.font = style.font(size: 16, weight: 400)
|
|
89
|
+
placeholderLabel.textColor = style.text3
|
|
90
|
+
input.addSubview(placeholderLabel)
|
|
91
|
+
|
|
92
|
+
let tap = UITapGestureRecognizer(target: self, action: #selector(tapped(_:)))
|
|
93
|
+
tap.cancelsTouchesInView = false
|
|
94
|
+
tap.delegate = self
|
|
95
|
+
input.addGestureRecognizer(tap)
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
required init?(coder: NSCoder) {
|
|
99
|
+
fatalError("init(coder:) is not used")
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
override func layoutSubviews() {
|
|
103
|
+
super.layoutSubviews()
|
|
104
|
+
let width = bounds.width
|
|
105
|
+
if width != lastWidth {
|
|
106
|
+
lastWidth = width
|
|
107
|
+
restyle(0, lines.count)
|
|
108
|
+
}
|
|
109
|
+
layoutDecorations()
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
// MARK: - attributes
|
|
113
|
+
|
|
114
|
+
@objc func applyEditable(_ value: Bool) {
|
|
115
|
+
editableMode = value
|
|
116
|
+
input.isEditable = value
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
@objc func applyPlaceholder(_ value: String?) {
|
|
120
|
+
placeholderLabel.text = value
|
|
121
|
+
updatePlaceholder()
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
@objc func applyPalette(_ json: String?) {
|
|
125
|
+
guard let palette = G9LCJson.object(json) else { return }
|
|
126
|
+
style.setPalette(palette)
|
|
127
|
+
input.textColor = style.text
|
|
128
|
+
input.tintColor = style.accent
|
|
129
|
+
placeholderLabel.textColor = style.text3
|
|
130
|
+
restyle(0, lines.count)
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
@objc func applyPageDir(_ value: String?) {
|
|
134
|
+
style.pageRtl = value == "rtl"
|
|
135
|
+
restyle(0, lines.count)
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
@objc func applyBottomInset(_ value: Double) {
|
|
139
|
+
let inset = value.isFinite ? CGFloat(max(0, value)) : 0
|
|
140
|
+
input.contentInset.bottom = inset
|
|
141
|
+
input.verticalScrollIndicatorInsets.bottom = inset
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
// MARK: - local edits
|
|
145
|
+
|
|
146
|
+
func textViewDidChange(_ textView: UITextView) {
|
|
147
|
+
guard !applying, input.markedTextRange == nil else { return }
|
|
148
|
+
let now = (input.text ?? "") as NSString
|
|
149
|
+
let old = lastText
|
|
150
|
+
let oldLength = old.length
|
|
151
|
+
let newLength = now.length
|
|
152
|
+
var prefix = 0
|
|
153
|
+
let shortest = min(oldLength, newLength)
|
|
154
|
+
while prefix < shortest && old.character(at: prefix) == now.character(at: prefix) { prefix += 1 }
|
|
155
|
+
var suffix = 0
|
|
156
|
+
while suffix < shortest - prefix && old.character(at: oldLength - 1 - suffix) == now.character(at: newLength - 1 - suffix) { suffix += 1 }
|
|
157
|
+
let from = prefix
|
|
158
|
+
let to = oldLength - suffix
|
|
159
|
+
let inserted = now.substring(with: NSRange(location: prefix, length: newLength - suffix - prefix))
|
|
160
|
+
lastText = now
|
|
161
|
+
if from == to && inserted.isEmpty {
|
|
162
|
+
flushWaiting()
|
|
163
|
+
return
|
|
164
|
+
}
|
|
165
|
+
seq += 1
|
|
166
|
+
let removed = G9LCRichTextView.newlines(old, from, to)
|
|
167
|
+
let added = G9LCRichTextView.newlines(inserted as NSString, 0, (inserted as NSString).length)
|
|
168
|
+
if removed > 0 || added > 0 {
|
|
169
|
+
let line = G9LCRichTextView.newlines(now, 0, from)
|
|
170
|
+
var copy: [String: Any] = line < lines.count ? lines[line] : ["t": "p"]
|
|
171
|
+
copy.removeValue(forKey: "mk")
|
|
172
|
+
copy["r"] = [Any]()
|
|
173
|
+
let drop = min(removed, max(0, lines.count - line - 1))
|
|
174
|
+
if drop > 0 { lines.removeSubrange((line + 1)..<(line + 1 + drop)) }
|
|
175
|
+
for _ in 0..<added { lines.insert(copy, at: min(line + 1, lines.count)) }
|
|
176
|
+
}
|
|
177
|
+
emit("rtedit", ["seq": seq, "base": rev, "from": from, "to": to, "text": inserted, "len": oldLength])
|
|
178
|
+
updatePlaceholder()
|
|
179
|
+
layoutDecorations()
|
|
180
|
+
flushWaiting()
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
func textViewDidChangeSelection(_ textView: UITextView) {
|
|
184
|
+
guard !applying else { return }
|
|
185
|
+
reportSelection(force: false)
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
func textViewDidBeginEditing(_ textView: UITextView) {
|
|
189
|
+
focusedNow = true
|
|
190
|
+
reportSelection(force: true)
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
func textViewDidEndEditing(_ textView: UITextView) {
|
|
194
|
+
focusedNow = false
|
|
195
|
+
reportSelection(force: true)
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
private func reportSelection(force: Bool) {
|
|
199
|
+
let range = input.selectedRange
|
|
200
|
+
if !force && NSEqualRanges(range, lastSel) { return }
|
|
201
|
+
lastSel = range
|
|
202
|
+
emit("rtselect", ["seq": seq, "base": rev, "a": range.location, "h": range.location + range.length, "focus": focusedNow])
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/// Shift+Enter: a line break inside the paragraph (U+2028 for the app; it becomes a hard break).
|
|
206
|
+
private func softBreak() {
|
|
207
|
+
guard editableMode else { return }
|
|
208
|
+
input.insertText("\u{2028}")
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
private func key(_ key: String) {
|
|
212
|
+
emit("rtaction", ["kind": "key", "key": key])
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
// MARK: - app messages
|
|
216
|
+
|
|
217
|
+
/// The app's message (`invoke('apply', {json})`).
|
|
218
|
+
@objc func applyMessage(_ json: String?) {
|
|
219
|
+
guard let message = G9LCJson.object(json) else { return }
|
|
220
|
+
// While an input method composes, the text must not move under it: messages wait for the composition's end.
|
|
221
|
+
if input.markedTextRange != nil {
|
|
222
|
+
waiting.append(message)
|
|
223
|
+
return
|
|
224
|
+
}
|
|
225
|
+
apply(message)
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
private func flushWaiting() {
|
|
229
|
+
guard input.markedTextRange == nil, !waiting.isEmpty else { return }
|
|
230
|
+
let queued = waiting
|
|
231
|
+
waiting.removeAll()
|
|
232
|
+
for message in queued { apply(message) }
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
private func apply(_ message: [String: Any]) {
|
|
236
|
+
guard G9LCJson.int(message, "ack") == seq else { return }
|
|
237
|
+
let newRev = G9LCJson.int(message, "rev") ?? rev
|
|
238
|
+
if let full = message["full"] as? [String: Any] {
|
|
239
|
+
applying = true
|
|
240
|
+
let text = G9LCJson.string(full, "text") ?? ""
|
|
241
|
+
storage.replaceCharacters(in: NSRange(location: 0, length: storage.length), with: text)
|
|
242
|
+
appLines = G9LCRichTextView.parseLines(full["lines"])
|
|
243
|
+
lines = appLines
|
|
244
|
+
lastText = storage.string as NSString
|
|
245
|
+
rev = newRev
|
|
246
|
+
restyle(0, lines.count)
|
|
247
|
+
let limit = storage.length
|
|
248
|
+
if let sel = message["sel"] as? [String: Any] {
|
|
249
|
+
select(G9LCJson.int(sel, "a") ?? 0, G9LCJson.int(sel, "h") ?? 0, limit: limit)
|
|
250
|
+
} else {
|
|
251
|
+
select(input.selectedRange.location, input.selectedRange.location + input.selectedRange.length, limit: limit)
|
|
252
|
+
}
|
|
253
|
+
applying = false
|
|
254
|
+
afterMessage(message, newRev)
|
|
255
|
+
return
|
|
256
|
+
}
|
|
257
|
+
let splice = message["lines"] as? [String: Any]
|
|
258
|
+
if let splice = splice, G9LCJson.int(splice, "of") != rev {
|
|
259
|
+
emit("rtaction", ["kind": "resync"])
|
|
260
|
+
return
|
|
261
|
+
}
|
|
262
|
+
var selA = input.selectedRange.location
|
|
263
|
+
var selH = input.selectedRange.location + input.selectedRange.length
|
|
264
|
+
var firstChanged = Int.max
|
|
265
|
+
var lastChanged = -1
|
|
266
|
+
applying = true
|
|
267
|
+
defer { applying = false }
|
|
268
|
+
for raw in (message["ops"] as? [Any]) ?? [] {
|
|
269
|
+
guard let op = raw as? [String: Any], let from = G9LCJson.int(op, "from"), let to = G9LCJson.int(op, "to") else { continue }
|
|
270
|
+
let text = G9LCJson.string(op, "text") ?? ""
|
|
271
|
+
guard from >= 0, to >= from, to <= storage.length else {
|
|
272
|
+
emit("rtaction", ["kind": "resync"])
|
|
273
|
+
return
|
|
274
|
+
}
|
|
275
|
+
storage.replaceCharacters(in: NSRange(location: from, length: to - from), with: text)
|
|
276
|
+
selA = G9LCRichTextView.mapPos(selA, from, to, (text as NSString).length)
|
|
277
|
+
selH = G9LCRichTextView.mapPos(selH, from, to, (text as NSString).length)
|
|
278
|
+
let line = G9LCRichTextView.newlines(storage.string as NSString, 0, from)
|
|
279
|
+
firstChanged = min(firstChanged, line)
|
|
280
|
+
lastChanged = max(lastChanged, line + G9LCRichTextView.newlines(text as NSString, 0, (text as NSString).length) + 1)
|
|
281
|
+
}
|
|
282
|
+
if let splice = splice {
|
|
283
|
+
let at = G9LCJson.int(splice, "at") ?? 0
|
|
284
|
+
let del = G9LCJson.int(splice, "del") ?? 0
|
|
285
|
+
let ins = G9LCRichTextView.parseLines(splice["ins"])
|
|
286
|
+
var next = appLines
|
|
287
|
+
let start = min(max(at, 0), next.count)
|
|
288
|
+
let count = min(max(del, 0), next.count - start)
|
|
289
|
+
next.replaceSubrange(start..<(start + count), with: ins)
|
|
290
|
+
appLines = next
|
|
291
|
+
firstChanged = min(firstChanged, start)
|
|
292
|
+
lastChanged = max(lastChanged, start + ins.count)
|
|
293
|
+
}
|
|
294
|
+
lines = appLines
|
|
295
|
+
lastText = storage.string as NSString
|
|
296
|
+
if lines.count != G9LCRichTextView.newlines(lastText, 0, lastText.length) + 1 {
|
|
297
|
+
emit("rtaction", ["kind": "resync"])
|
|
298
|
+
return
|
|
299
|
+
}
|
|
300
|
+
rev = newRev
|
|
301
|
+
if lastChanged >= 0 { restyle(firstChanged, min(lastChanged, lines.count)) }
|
|
302
|
+
let limit = storage.length
|
|
303
|
+
if let sel = message["sel"] as? [String: Any] {
|
|
304
|
+
select(G9LCJson.int(sel, "a") ?? 0, G9LCJson.int(sel, "h") ?? 0, limit: limit)
|
|
305
|
+
} else {
|
|
306
|
+
select(selA, selH, limit: limit)
|
|
307
|
+
}
|
|
308
|
+
afterMessage(message, newRev)
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
private func select(_ a: Int, _ h: Int, limit: Int) {
|
|
312
|
+
let start = min(max(0, min(a, h)), limit)
|
|
313
|
+
let end = min(max(0, max(a, h)), limit)
|
|
314
|
+
input.selectedRange = NSRange(location: start, length: end - start)
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
private func afterMessage(_ message: [String: Any], _ newRev: Int) {
|
|
318
|
+
if let list = message["peers"] as? [Any] {
|
|
319
|
+
peers = list.compactMap { raw -> Peer? in
|
|
320
|
+
guard let peer = raw as? [String: Any] else { return nil }
|
|
321
|
+
return Peer(a: G9LCJson.int(peer, "a") ?? 0, h: G9LCJson.int(peer, "h") ?? 0,
|
|
322
|
+
color: G9LCColors.color(G9LCJson.string(peer, "c")) ?? .systemGray, name: G9LCJson.string(peer, "n") ?? "")
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
updatePlaceholder()
|
|
326
|
+
layoutDecorations()
|
|
327
|
+
emit("rtapplied", ["rev": newRev])
|
|
328
|
+
reportSelection(force: false)
|
|
329
|
+
if G9LCJson.bool(message, "focus") == true, editableMode {
|
|
330
|
+
input.becomeFirstResponder()
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
// MARK: - styling
|
|
335
|
+
|
|
336
|
+
/// Re-applies the attributes of lines `[from, to)`.
|
|
337
|
+
private func restyle(_ from: Int, _ to: Int) {
|
|
338
|
+
let text = storage.string as NSString
|
|
339
|
+
let starts = G9LCRichTextView.lineStarts(text)
|
|
340
|
+
let width = max(40, input.bounds.width - input.textContainerInset.left - input.textContainerInset.right - 10)
|
|
341
|
+
let wasApplying = applying
|
|
342
|
+
applying = true
|
|
343
|
+
let selection = input.selectedRange
|
|
344
|
+
storage.beginEditing()
|
|
345
|
+
let lower = max(0, from)
|
|
346
|
+
let upper = min(to, lines.count)
|
|
347
|
+
for index in lower..<max(lower, upper) {
|
|
348
|
+
guard index < starts.count else { break }
|
|
349
|
+
let start = starts[index]
|
|
350
|
+
let end = index + 1 < starts.count ? starts[index + 1] - 1 : text.length
|
|
351
|
+
let paragraphEnd = end < text.length ? end + 1 : end
|
|
352
|
+
let range = NSRange(location: start, length: paragraphEnd - start)
|
|
353
|
+
if range.length > 0 {
|
|
354
|
+
let line = lines[index]
|
|
355
|
+
storage.setAttributes(style.base(line, lineText: text.substring(with: NSRange(location: start, length: end - start))), range: range)
|
|
356
|
+
style.decorate(storage, line: line, start: start, end: end, width: width) { [weak self] in
|
|
357
|
+
self?.restyle(0, self?.lines.count ?? 0)
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
storage.endEditing()
|
|
362
|
+
input.selectedRange = selection
|
|
363
|
+
applying = wasApplying
|
|
364
|
+
layoutDecorations()
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
// MARK: - decorations
|
|
368
|
+
|
|
369
|
+
private func layoutDecorations() {
|
|
370
|
+
layout.ensureLayout(for: container)
|
|
371
|
+
let size = CGSize(width: max(input.bounds.width, input.contentSize.width), height: max(input.bounds.height, input.contentSize.height))
|
|
372
|
+
backdrop.frame = CGRect(origin: .zero, size: size)
|
|
373
|
+
overlay.frame = CGRect(origin: .zero, size: size)
|
|
374
|
+
backdrop.setNeedsDisplay()
|
|
375
|
+
overlay.setNeedsDisplay()
|
|
376
|
+
input.sendSubviewToBack(backdrop)
|
|
377
|
+
input.bringSubviewToFront(overlay)
|
|
378
|
+
let inset = input.textContainerInset
|
|
379
|
+
placeholderLabel.frame = CGRect(x: inset.left + 5, y: inset.top, width: max(0, input.bounds.width - inset.left - inset.right - 10), height: 24)
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
private func updatePlaceholder() {
|
|
383
|
+
placeholderLabel.isHidden = storage.length > 0
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
/// The rect of a line's paragraph in the text view's content coordinates.
|
|
387
|
+
private func paragraphRect(start: Int, end: Int) -> CGRect {
|
|
388
|
+
let inset = input.textContainerInset
|
|
389
|
+
let characters = NSRange(location: start, length: max(end - start, 0))
|
|
390
|
+
var rect: CGRect
|
|
391
|
+
if characters.length == 0 {
|
|
392
|
+
rect = start < storage.length ? layout.lineFragmentRect(forGlyphAt: layout.glyphIndexForCharacter(at: start), effectiveRange: nil)
|
|
393
|
+
: layout.extraLineFragmentRect
|
|
394
|
+
if rect == .zero, start > 0 {
|
|
395
|
+
rect = layout.lineFragmentRect(forGlyphAt: layout.glyphIndexForCharacter(at: start - 1), effectiveRange: nil)
|
|
396
|
+
}
|
|
397
|
+
} else {
|
|
398
|
+
let glyphs = layout.glyphRange(forCharacterRange: characters, actualCharacterRange: nil)
|
|
399
|
+
rect = layout.boundingRect(forGlyphRange: glyphs, in: container)
|
|
400
|
+
let first = layout.lineFragmentRect(forGlyphAt: glyphs.location, effectiveRange: nil)
|
|
401
|
+
rect = CGRect(x: first.minX, y: first.minY, width: first.width, height: rect.maxY - first.minY)
|
|
402
|
+
}
|
|
403
|
+
return rect.offsetBy(dx: inset.left, dy: inset.top)
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
private func drawBackdrop(_ dirty: CGRect) {
|
|
407
|
+
guard let context = UIGraphicsGetCurrentContext() else { return }
|
|
408
|
+
let text = storage.string as NSString
|
|
409
|
+
let starts = G9LCRichTextView.lineStarts(text)
|
|
410
|
+
let inset = input.textContainerInset
|
|
411
|
+
let fullWidth = input.bounds.width - inset.left - inset.right
|
|
412
|
+
for (index, line) in lines.enumerated() where index < starts.count {
|
|
413
|
+
let t = G9LCJson.string(line, "t") ?? "p"
|
|
414
|
+
let tone = G9LCJson.string(line, "co")
|
|
415
|
+
let cell = line["cell"] as? [String: Any]
|
|
416
|
+
guard t == "code" || tone != nil || cell != nil else { continue }
|
|
417
|
+
let start = starts[index]
|
|
418
|
+
let end = index + 1 < starts.count ? starts[index + 1] - 1 : text.length
|
|
419
|
+
let rect = paragraphRect(start: start, end: end)
|
|
420
|
+
guard rect.intersects(dirty.insetBy(dx: 0, dy: -40)) else { continue }
|
|
421
|
+
let box = CGRect(x: inset.left + style.margin(line) - 8, y: rect.minY - 2, width: fullWidth - style.margin(line) + 8, height: rect.height + 4)
|
|
422
|
+
if t == "code" {
|
|
423
|
+
context.setFillColor(style.surface2.cgColor)
|
|
424
|
+
context.fill(box)
|
|
425
|
+
} else if let tone = tone {
|
|
426
|
+
context.setFillColor(style.tone(tone).withAlphaComponent(0.12).cgColor)
|
|
427
|
+
context.fill(box)
|
|
428
|
+
context.setFillColor(style.tone(tone).cgColor)
|
|
429
|
+
let rtl = style.isRtl(line, text.substring(with: NSRange(location: start, length: end - start)))
|
|
430
|
+
context.fill(CGRect(x: rtl ? box.maxX - 3 : box.minX, y: box.minY, width: 3, height: box.height))
|
|
431
|
+
} else if cell != nil {
|
|
432
|
+
context.setStrokeColor(style.border.cgColor)
|
|
433
|
+
context.setLineWidth(1)
|
|
434
|
+
context.stroke(box.insetBy(dx: 0.5, dy: 0.5))
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
private func drawOverlay(_ dirty: CGRect) {
|
|
440
|
+
guard let context = UIGraphicsGetCurrentContext() else { return }
|
|
441
|
+
let text = storage.string as NSString
|
|
442
|
+
let starts = G9LCRichTextView.lineStarts(text)
|
|
443
|
+
let inset = input.textContainerInset
|
|
444
|
+
let width = input.bounds.width
|
|
445
|
+
for (index, line) in lines.enumerated() where index < starts.count {
|
|
446
|
+
let q = G9LCJson.int(line, "q") ?? 0
|
|
447
|
+
let marker = line["mk"] as? [String: Any]
|
|
448
|
+
guard q > 0 || marker != nil else { continue }
|
|
449
|
+
let start = starts[index]
|
|
450
|
+
let end = index + 1 < starts.count ? starts[index + 1] - 1 : text.length
|
|
451
|
+
let rect = paragraphRect(start: start, end: end)
|
|
452
|
+
guard rect.intersects(dirty.insetBy(dx: 0, dy: -40)) else { continue }
|
|
453
|
+
let rtl = style.isRtl(line, text.substring(with: NSRange(location: start, length: end - start)))
|
|
454
|
+
func x(_ offset: CGFloat) -> CGFloat { rtl ? width - inset.right - offset : inset.left + offset }
|
|
455
|
+
if q > 0 {
|
|
456
|
+
context.setFillColor(style.border.cgColor)
|
|
457
|
+
for i in 0..<q {
|
|
458
|
+
let barX = x(CGFloat(i) * G9LCRichStyle.quoteStep + 2)
|
|
459
|
+
context.fill(CGRect(x: rtl ? barX - 3 : barX, y: rect.minY, width: 3, height: rect.height))
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
guard let marker = marker else { continue }
|
|
463
|
+
let ind = max(1, G9LCJson.int(line, "ind") ?? 0)
|
|
464
|
+
let center = x(CGFloat(q) * G9LCRichStyle.quoteStep + (CGFloat(ind) - 0.5) * G9LCRichStyle.indentStep)
|
|
465
|
+
let firstLine = paragraphRect(start: start, end: start)
|
|
466
|
+
let midY = firstLine.minY + min(firstLine.height, 24) / 2 + 1
|
|
467
|
+
switch G9LCJson.string(marker, "k") {
|
|
468
|
+
case "t":
|
|
469
|
+
let box = CGRect(x: center - 8, y: midY - 8, width: 16, height: 16)
|
|
470
|
+
let path = UIBezierPath(roundedRect: box, cornerRadius: 4)
|
|
471
|
+
if G9LCJson.bool(marker, "c") == true {
|
|
472
|
+
style.accent.setFill()
|
|
473
|
+
path.fill()
|
|
474
|
+
let tick = UIBezierPath()
|
|
475
|
+
tick.move(to: CGPoint(x: box.minX + 4, y: box.midY))
|
|
476
|
+
tick.addLine(to: CGPoint(x: box.minX + 7, y: box.maxY - 4.5))
|
|
477
|
+
tick.addLine(to: CGPoint(x: box.maxX - 3.5, y: box.minY + 4.5))
|
|
478
|
+
tick.lineWidth = 2
|
|
479
|
+
UIColor.white.setStroke()
|
|
480
|
+
tick.stroke()
|
|
481
|
+
} else {
|
|
482
|
+
style.text3.setStroke()
|
|
483
|
+
path.lineWidth = 1.5
|
|
484
|
+
path.stroke()
|
|
485
|
+
}
|
|
486
|
+
case "n":
|
|
487
|
+
let label = (G9LCJson.string(marker, "n") ?? "") as NSString
|
|
488
|
+
let attributes: [NSAttributedString.Key: Any] = [.font: style.font(size: 15, weight: 500), .foregroundColor: style.text2]
|
|
489
|
+
let size = label.size(withAttributes: attributes)
|
|
490
|
+
label.draw(at: CGPoint(x: center - size.width / 2, y: midY - size.height / 2), withAttributes: attributes)
|
|
491
|
+
default:
|
|
492
|
+
style.text2.setFill()
|
|
493
|
+
UIBezierPath(ovalIn: CGRect(x: center - 3, y: midY - 3, width: 6, height: 6)).fill()
|
|
494
|
+
}
|
|
495
|
+
}
|
|
496
|
+
// Collaborators: a caret and a name tag each.
|
|
497
|
+
for peer in peers {
|
|
498
|
+
let position = min(max(peer.h, 0), storage.length)
|
|
499
|
+
let caret = input.caretRect(for: input.position(from: input.beginningOfDocument, offset: position) ?? input.endOfDocument)
|
|
500
|
+
guard caret.intersects(dirty.insetBy(dx: -80, dy: -40)) else { continue }
|
|
501
|
+
peer.color.setFill()
|
|
502
|
+
UIBezierPath(rect: CGRect(x: caret.minX - 1, y: caret.minY, width: 2, height: caret.height)).fill()
|
|
503
|
+
let attributes: [NSAttributedString.Key: Any] = [.font: style.font(size: 11, weight: 600), .foregroundColor: UIColor.white]
|
|
504
|
+
let label = peer.name as NSString
|
|
505
|
+
let size = label.size(withAttributes: attributes)
|
|
506
|
+
let tag = CGRect(x: caret.minX - 1, y: caret.minY - size.height - 2, width: size.width + 8, height: size.height + 2)
|
|
507
|
+
UIBezierPath(roundedRect: tag, cornerRadius: 4).fill()
|
|
508
|
+
label.draw(at: CGPoint(x: tag.minX + 4, y: tag.minY + 1), withAttributes: attributes)
|
|
509
|
+
}
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
// MARK: - taps
|
|
513
|
+
|
|
514
|
+
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith other: UIGestureRecognizer) -> Bool {
|
|
515
|
+
true
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
/// A checkbox in the start margin, a chip, or a picture: an action for the app.
|
|
519
|
+
@objc private func tapped(_ gesture: UITapGestureRecognizer) {
|
|
520
|
+
guard gesture.state == .ended else { return }
|
|
521
|
+
let point = gesture.location(in: input)
|
|
522
|
+
let inset = input.textContainerInset
|
|
523
|
+
let inContainer = CGPoint(x: point.x - inset.left, y: point.y - inset.top)
|
|
524
|
+
guard storage.length > 0 else { return }
|
|
525
|
+
let glyph = layout.glyphIndex(for: inContainer, in: container)
|
|
526
|
+
let index = layout.characterIndexForGlyph(at: glyph)
|
|
527
|
+
let text = storage.string as NSString
|
|
528
|
+
let lineIndex = G9LCRichTextView.newlines(text, 0, min(index, text.length))
|
|
529
|
+
guard lineIndex < lines.count else { return }
|
|
530
|
+
let line = lines[lineIndex]
|
|
531
|
+
let starts = G9LCRichTextView.lineStarts(text)
|
|
532
|
+
let start = starts[min(lineIndex, starts.count - 1)]
|
|
533
|
+
if let marker = line["mk"] as? [String: Any], G9LCJson.string(marker, "k") == "t" {
|
|
534
|
+
let firstLine = paragraphRect(start: start, end: start)
|
|
535
|
+
let end = lineIndex + 1 < starts.count ? starts[lineIndex + 1] - 1 : text.length
|
|
536
|
+
let rtl = style.isRtl(line, text.substring(with: NSRange(location: start, length: end - start)))
|
|
537
|
+
let margin = style.margin(line)
|
|
538
|
+
let inMargin = rtl ? point.x > input.bounds.width - inset.right - margin : point.x < inset.left + margin
|
|
539
|
+
if inMargin && point.y >= firstLine.minY - 4 && point.y <= firstLine.maxY + 4 {
|
|
540
|
+
emit("rtaction", ["kind": "check", "line": lineIndex])
|
|
541
|
+
return
|
|
542
|
+
}
|
|
543
|
+
}
|
|
544
|
+
if G9LCJson.string(line, "t") == "img" {
|
|
545
|
+
emit("rtaction", ["kind": "image", "line": lineIndex])
|
|
546
|
+
return
|
|
547
|
+
}
|
|
548
|
+
for position in [index, index - 1] where position >= 0 && position < text.length {
|
|
549
|
+
if text.character(at: position) == 0xFFFC, storage.attribute(.g9Atom, at: position, effectiveRange: nil) != nil {
|
|
550
|
+
emit("rtaction", ["kind": "tap", "at": position])
|
|
551
|
+
return
|
|
552
|
+
}
|
|
553
|
+
}
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
// MARK: - helpers
|
|
557
|
+
|
|
558
|
+
private func emit(_ name: String, _ detail: [String: Any]) {
|
|
559
|
+
emitter?(name, detail)
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
static func parseLines(_ raw: Any?) -> [[String: Any]] {
|
|
563
|
+
((raw as? [Any]) ?? []).compactMap { $0 as? [String: Any] }
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
static func newlines(_ text: NSString, _ from: Int, _ to: Int) -> Int {
|
|
567
|
+
var count = 0
|
|
568
|
+
var i = max(0, from)
|
|
569
|
+
let end = min(to, text.length)
|
|
570
|
+
while i < end {
|
|
571
|
+
if text.character(at: i) == 10 { count += 1 }
|
|
572
|
+
i += 1
|
|
573
|
+
}
|
|
574
|
+
return count
|
|
575
|
+
}
|
|
576
|
+
|
|
577
|
+
static func lineStarts(_ text: NSString) -> [Int] {
|
|
578
|
+
var starts = [0]
|
|
579
|
+
for i in 0..<text.length where text.character(at: i) == 10 { starts.append(i + 1) }
|
|
580
|
+
return starts
|
|
581
|
+
}
|
|
582
|
+
|
|
583
|
+
/// A position through a replacement; a caret stays before text inserted right at it (element-core's `mapPos`).
|
|
584
|
+
static func mapPos(_ pos: Int, _ from: Int, _ to: Int, _ length: Int) -> Int {
|
|
585
|
+
if pos <= from { return pos }
|
|
586
|
+
if pos >= to { return pos + length - (to - from) }
|
|
587
|
+
return from + length
|
|
588
|
+
}
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
/// The UITextView of the element: hardware-keyboard shortcuts go to the app (undo, marks, indent), no undo of its own
|
|
592
|
+
/// (the document's undo is the app's, Yjs).
|
|
593
|
+
final class G9LCRichTextInput: UITextView {
|
|
594
|
+
var onKey: ((String) -> Void)?
|
|
595
|
+
var onSoftBreak: (() -> Void)?
|
|
596
|
+
private let noUndo: UndoManager = {
|
|
597
|
+
let manager = UndoManager()
|
|
598
|
+
manager.disableUndoRegistration()
|
|
599
|
+
return manager
|
|
600
|
+
}()
|
|
601
|
+
|
|
602
|
+
override var undoManager: UndoManager? { noUndo }
|
|
603
|
+
|
|
604
|
+
override var keyCommands: [UIKeyCommand]? {
|
|
605
|
+
let commands: [(String, UIKeyModifierFlags, String)] = [
|
|
606
|
+
("z", .command, "undo"), ("z", [.command, .shift], "redo"), ("y", .command, "redo"),
|
|
607
|
+
("b", .command, "bold"), ("i", .command, "italic"), ("u", .command, "underline"), ("e", .command, "code"),
|
|
608
|
+
("\t", [], "indent"), ("\t", .shift, "outdent"), ("\r", .shift, "softBreak"),
|
|
609
|
+
]
|
|
610
|
+
return commands.map { entry in
|
|
611
|
+
let command = UIKeyCommand(input: entry.0, modifierFlags: entry.1, action: #selector(keyPressed(_:)))
|
|
612
|
+
command.wantsPriorityOverSystemBehavior = true
|
|
613
|
+
command.title = entry.2
|
|
614
|
+
return command
|
|
615
|
+
}
|
|
616
|
+
}
|
|
617
|
+
|
|
618
|
+
@objc private func keyPressed(_ command: UIKeyCommand) {
|
|
619
|
+
guard let name = command.title.isEmpty ? nil : command.title else { return }
|
|
620
|
+
if name == "softBreak" { onSoftBreak?() } else { onKey?(name) }
|
|
621
|
+
}
|
|
622
|
+
}
|
|
623
|
+
|
|
624
|
+
/// A view that draws through a closure (the element's backdrop and overlay).
|
|
625
|
+
final class G9LCRichDecorations: UIView {
|
|
626
|
+
var drawer: ((CGRect) -> Void)?
|
|
627
|
+
|
|
628
|
+
override init(frame: CGRect) {
|
|
629
|
+
super.init(frame: frame)
|
|
630
|
+
isOpaque = false
|
|
631
|
+
backgroundColor = .clear
|
|
632
|
+
contentMode = .redraw
|
|
633
|
+
}
|
|
634
|
+
|
|
635
|
+
required init?(coder: NSCoder) {
|
|
636
|
+
fatalError("init(coder:) is not used")
|
|
637
|
+
}
|
|
638
|
+
|
|
639
|
+
override func draw(_ rect: CGRect) {
|
|
640
|
+
drawer?(rect)
|
|
641
|
+
}
|
|
642
|
+
}
|
|
643
|
+
|
|
644
|
+
extension NSAttributedString.Key {
|
|
645
|
+
/// An inline object (U+FFFC) of the text: what it stands for (mention, chip, date).
|
|
646
|
+
static let g9Atom = NSAttributedString.Key("g9Atom")
|
|
647
|
+
}
|