-
Notifications
You must be signed in to change notification settings - Fork 66
Expand file tree
/
Copy pathParametrizedStyles.kt
More file actions
372 lines (302 loc) · 10.7 KB
/
Copy pathParametrizedStyles.kt
File metadata and controls
372 lines (302 loc) · 10.7 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
package com.swmansion.enriched.textinput.styles
import android.text.Editable
import android.text.Spannable
import android.text.SpannableStringBuilder
import android.text.Spanned
import com.swmansion.enriched.common.EnrichedConstants
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.removeZWS
class ParametrizedStyles(
private val view: EnrichedTextInputView,
) {
private var mentionStart: 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.removeZWS(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)
val (safeStart, safeEnd) = spannable.getSafeSpanBoundaries(start, spanEnd)
spannable.setSpan(span, safeStart, safeEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
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)
afterTextChangedMentions(s, startCursorPosition)
}
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) {
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 span = EnrichedInputLinkSpan(matcher.group(), view.htmlStyle)
val (safeStart, safeEnd) = spannable.getSafeSpanBoundaries(spanStart, spanEnd)
spannable.setSpan(
span,
safeStart,
safeEnd,
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE,
)
}
}
}
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 afterTextChangedMentions(
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)\\w*")
val spans = spannable.getSpans(currentWord.start, currentWord.end, EnrichedInputMentionSpan::class.java)
for (span in spans) {
spannable.removeSpan(span)
}
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) {
mentionHandler.endMention()
return
}
// Previous word is not a mention -> end mention
if (!mentionRegex.matches(previousWord.text)) {
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 ?: ""
}
// Extract text without indicator
val text = spannable.subSequence(finalStart, finalEnd).toString().replaceFirst(indicator, "")
// Means we are starting mention
if (text.isEmpty()) {
mentionStart = finalStart
}
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 ?: return
view.runAsATransaction {
spannable.replace(start, selectionEnd, 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, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
val hasSpaceAtTheEnd = spannable.length > safeEnd && spannable[safeEnd] == ' '
if (!hasSpaceAtTheEnd) {
spannable.insert(safeEnd, " ")
}
}
view.mentionHandler?.reset()
view.selection.validateStyles()
}
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,
)
}
}