-
Notifications
You must be signed in to change notification settings - Fork 56
Expand file tree
/
Copy pathParametrizedStyles.kt
More file actions
435 lines (360 loc) · 13.1 KB
/
Copy pathParametrizedStyles.kt
File metadata and controls
435 lines (360 loc) · 13.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
package com.swmansion.enriched.textinput.styles
import android.text.Editable
import android.text.Selection
import android.text.Spannable
import android.text.SpannableStringBuilder
import android.text.Spanned
import com.swmansion.enriched.common.EnrichedConstants
import com.swmansion.enriched.common.EnrichedSpanFlags
import com.swmansion.enriched.textinput.EnrichedTextInputView
import com.swmansion.enriched.textinput.spans.EnrichedInputImageSpan
import com.swmansion.enriched.textinput.spans.EnrichedInputLinkSpan
import com.swmansion.enriched.textinput.spans.EnrichedInputMentionSpan
import com.swmansion.enriched.textinput.spans.EnrichedSpans
import com.swmansion.enriched.textinput.utils.getSafeSpanBoundaries
import com.swmansion.enriched.textinput.utils.safelyRemoveZWS
class ParametrizedStyles(
private val view: EnrichedTextInputView,
) {
private var mentionStart: Int? = null
private var mentionEnd: Int? = null
private var isSettingLinkSpan = false
var mentionIndicators: Array<String> = emptyArray<String>()
fun <T> removeSpansForRange(
spannable: Spannable,
start: Int,
end: Int,
clazz: Class<T>,
): Boolean {
val ssb = spannable as SpannableStringBuilder
val spans = ssb.getSpans(start, end, clazz)
if (spans.isEmpty()) return false
ssb.safelyRemoveZWS(start, end)
for (span in spans) {
ssb.removeSpan(span)
}
return true
}
fun setLinkSpan(
start: Int,
end: Int,
text: String,
url: String,
) {
isSettingLinkSpan = true
val spannable = view.text as SpannableStringBuilder
val spans = spannable.getSpans(start, end, EnrichedInputLinkSpan::class.java)
for (span in spans) {
spannable.removeSpan(span)
}
if (start == end) {
spannable.insert(start, text)
} else {
spannable.replace(start, end, text)
}
val spanEnd = start + text.length
val span = EnrichedInputLinkSpan(url, view.htmlStyle, true)
val (safeStart, safeEnd) = spannable.getSafeSpanBoundaries(start, spanEnd)
spannable.setSpan(span, safeStart, safeEnd, EnrichedSpanFlags.forSpan(span))
view.selection?.validateStyles()
isSettingLinkSpan = false
}
fun removeLinkSpans(
start: Int,
end: Int,
) {
val spannable = view.text as SpannableStringBuilder
val textLength = spannable.length
val clampedStart = minOf(start, end).coerceIn(0, textLength)
val clampedEnd = maxOf(start, end).coerceIn(0, textLength)
val spans = spannable.getSpans(clampedStart, clampedEnd, EnrichedInputLinkSpan::class.java)
for (span in spans) {
spannable.removeSpan(span)
}
view.selection?.validateStyles()
}
fun afterTextChanged(
s: Editable,
startCursorPosition: Int,
endCursorPosition: Int,
) {
afterTextChangedLinks(startCursorPosition, endCursorPosition)
detectActiveMention(s, startCursorPosition)
}
// Re-runs in-progress mention detection on a pure caret move (no text change),
fun afterSelectionChangedMentions(
start: Int,
end: Int,
) {
val s = view.text ?: return
// A non-collapsed selection can't be editing a single mention.
if (start != end) {
view.mentionHandler?.endMention()
return
}
detectActiveMention(s, end)
}
fun onStyleToggled(
name: String,
start: Int,
end: Int,
) {
// Run afterTextChangedLinks on the range affected by the style toggle to re-detect links.
// For example, toggling a code block on and off will restore automatically detected links.
val linkConfig = EnrichedSpans.getMergingConfigForStyle(EnrichedSpans.LINK, view.htmlStyle) ?: return
if (name in linkConfig.blockingStyles || name in linkConfig.conflictingStyles) {
afterTextChangedLinks(start, end)
}
}
fun detectLinksInRange(
spannable: Spannable,
start: Int,
end: Int,
) {
val regex = view.linkRegex ?: return
val textLength = spannable.length
val safeStart = minOf(start, end).coerceIn(0, textLength)
val safeEnd = maxOf(start, end).coerceIn(0, textLength)
if (safeStart >= safeEnd) return
val contextText = spannable.subSequence(safeStart, safeEnd).toString()
val spans = spannable.getSpans(safeStart, safeEnd, EnrichedInputLinkSpan::class.java)
for (span in spans) {
if (span.getIsManual()) continue
spannable.removeSpan(span)
}
val wordsRegex = Regex("\\S+")
for (wordMatch in wordsRegex.findAll(contextText)) {
var word = wordMatch.value
var wordStart = wordMatch.range.first
// Do not include zero-width space in link detection
if (word.startsWith(EnrichedConstants.ZWS_STRING)) {
word = word.substring(1)
wordStart += 1
}
// Loop over words and detect links
val matcher = regex.matcher(word)
while (matcher.find()) {
val linkStart = matcher.start()
val linkEnd = matcher.end()
val spanStart = start + wordStart + linkStart
val spanEnd = start + wordStart + linkEnd
val (safeStart, safeEnd) = spannable.getSafeSpanBoundaries(spanStart, spanEnd)
// Do not overwrite a manual link span with an auto-detected one
val overlappingManual =
spannable
.getSpans(safeStart, safeEnd, EnrichedInputLinkSpan::class.java)
.any { it.getIsManual() }
if (overlappingManual) continue
val span = EnrichedInputLinkSpan(matcher.group(), view.htmlStyle)
spannable.setSpan(
span,
safeStart,
safeEnd,
EnrichedSpanFlags.forSpan(span),
)
}
}
}
private fun getWordAtIndex(
s: CharSequence,
index: Int,
): TextRange? {
if (index < 0) return null
var start = index
var end = index
while (start > 0 && !Character.isWhitespace(s[start - 1])) {
start--
}
while (end < s.length && !Character.isWhitespace(s[end])) {
end++
}
val result = s.subSequence(start, end).toString()
return TextRange(result, start, end)
}
// After editing text we want to automatically detect links in the affected range
// Affected range is range + previous word + next word
private fun getLinksAffectedRange(
s: CharSequence,
start: Int,
end: Int,
): IntRange {
var actualStart = start
var actualEnd = end
// Expand backward to find the start of the first affected word
while (actualStart > 0 && !Character.isWhitespace(s[actualStart - 1])) {
actualStart--
}
// Expand forward to find the end of the last affected word
while (actualEnd < s.length && !Character.isWhitespace(s[actualEnd])) {
actualEnd++
}
return actualStart..actualEnd
}
private fun canLinkBeApplied(): Boolean {
val mergingConfig = EnrichedSpans.getMergingConfigForStyle(EnrichedSpans.LINK, view.htmlStyle) ?: return true
val conflictingStyles = mergingConfig.conflictingStyles
val blockingStyles = mergingConfig.blockingStyles
for (style in blockingStyles) {
if (view.spanState?.getStart(style) != null) return false
}
for (style in conflictingStyles) {
if (view.spanState?.getStart(style) != null) return false
}
return true
}
private fun afterTextChangedLinks(
editStart: Int,
editEnd: Int,
) {
// Do not detect link if it's applied manually
if (isSettingLinkSpan || !canLinkBeApplied()) return
val spannable = view.text as? Spannable ?: return
val affectedRange = getLinksAffectedRange(spannable, editStart, editEnd)
detectLinksInRange(spannable, affectedRange.first, affectedRange.last)
}
private fun detectActiveMention(
s: CharSequence,
endCursorPosition: Int,
) {
val mentionHandler = view.mentionHandler ?: return
val currentWord = getWordAtIndex(s, endCursorPosition) ?: return
val spannable = view.text as Spannable
val indicatorsPattern = mentionIndicators.joinToString("|") { Regex.escape(it) }
val mentionIndicatorRegex = Regex("^($indicatorsPattern)")
val mentionRegex = Regex("^($indicatorsPattern)\\S*")
var indicator: String
var finalStart: Int
val finalEnd = currentWord.end
// No mention in the current word, check previous one
if (!mentionRegex.matches(currentWord.text)) {
val previousWord = getWordAtIndex(spannable, currentWord.start - 1)
// No previous word -> no mention to be detected
if (previousWord == null) {
mentionStart = null
mentionEnd = null
mentionHandler.endMention()
return
}
// Previous word is not a mention -> end mention
if (!mentionRegex.matches(previousWord.text)) {
mentionStart = null
mentionEnd = null
mentionHandler.endMention()
return
}
// Previous word is a mention -> use it
finalStart = previousWord.start
indicator = mentionIndicatorRegex.find(previousWord.text)?.value ?: ""
} else {
// Current word is a mention -> use it
finalStart = currentWord.start
indicator = mentionIndicatorRegex.find(currentWord.text)?.value ?: ""
}
mentionStart = finalStart
mentionEnd = finalEnd
// Mirror iOS conflicting-styles behaviour: check the full candidate range for
// a finalized mention span. If the span's stored text still matches what is in
// the buffer the mention is intact — block the event (covers HTML-loaded
// mentions and typing adjacent to a freshly-selected mention).
// If the span is stale (user edited inside it), remove it and record mentionStart
// so setMentionSpan can replace text correctly when the user picks a new mention.
val rangeSpans = spannable.getSpans(finalStart, finalEnd, EnrichedInputMentionSpan::class.java)
for (span in rangeSpans) {
val spanStart = spannable.getSpanStart(span)
val spanEnd = spannable.getSpanEnd(span)
val currentSpanText = spannable.subSequence(spanStart, spanEnd).toString()
if (currentSpanText == span.getText()) {
mentionStart = null
mentionEnd = null
mentionHandler.endMention()
return
}
spannable.removeSpan(span)
mentionStart = spanStart
mentionEnd = spanEnd
}
// Extract text without indicator
val text = spannable.subSequence(finalStart, finalEnd).toString().replaceFirst(indicator, "")
mentionHandler.onMention(indicator, text)
}
fun setImageSpan(
src: String,
width: Float,
height: Float,
) {
if (view.selection == null) return
val spannable = view.text as SpannableStringBuilder
val (start, originalEnd) = view.selection.getInlineSelection()
if (start == originalEnd) {
spannable.insert(start, EnrichedConstants.ORC_STRING)
} else {
val spans = spannable.getSpans(start, originalEnd, EnrichedInputImageSpan::class.java)
for (s in spans) {
spannable.removeSpan(s)
}
spannable.replace(start, originalEnd, EnrichedConstants.ORC_STRING)
}
val (imageStart, imageEnd) = spannable.getSafeSpanBoundaries(start, start + 1)
val span = EnrichedInputImageSpan.createEnrichedImageSpan(src, width.toInt(), height.toInt())
span.observeAsyncDrawableLoaded(view.text)
spannable.setSpan(span, imageStart, imageEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
}
fun startMention(indicator: String) {
val selection = view.selection ?: return
val spannable = view.text as SpannableStringBuilder
val (start, end) = selection.getInlineSelection()
if (start == end) {
spannable.insert(start, indicator)
} else {
spannable.replace(start, end, indicator)
}
}
fun setMentionSpan(
indicator: String,
text: String,
attributes: Map<String, String>,
) {
val selection = view.selection ?: return
val spannable = view.text as SpannableStringBuilder
val (selectionStart, selectionEnd) = selection.getInlineSelection()
val spans = spannable.getSpans(selectionStart, selectionEnd, EnrichedInputMentionSpan::class.java)
for (span in spans) {
spannable.removeSpan(span)
}
val start = mentionStart ?: selectionStart
val end = mentionEnd ?: selectionEnd
view.runAsATransaction {
spannable.replace(start, end, text)
val span = EnrichedInputMentionSpan(text, indicator, attributes, view.htmlStyle)
val spanEnd = start + text.length
val (safeStart, safeEnd) = spannable.getSafeSpanBoundaries(start, spanEnd)
spannable.setSpan(span, safeStart, safeEnd, EnrichedSpanFlags.forSpan(span))
val hasSpaceAtTheEnd = spannable.length > safeEnd && spannable[safeEnd] == ' '
if (!hasSpaceAtTheEnd) {
spannable.insert(safeEnd, " ")
}
Selection.setSelection(spannable, (safeEnd + 1).coerceAtMost(spannable.length))
}
view.mentionHandler?.reset()
view.selection.validateStyles()
mentionStart = null
mentionEnd = null
}
fun getStyleRange(): Pair<Int, Int> = view.selection?.getInlineSelection() ?: Pair(0, 0)
fun removeStyle(
name: String,
start: Int,
end: Int,
): Boolean {
val config = EnrichedSpans.parametrizedStyles[name] ?: return false
val spannable = view.text as Spannable
return removeSpansForRange(spannable, start, end, config.clazz)
}
companion object {
data class TextRange(
val text: String,
val start: Int,
val end: Int,
)
}
}