-
Notifications
You must be signed in to change notification settings - Fork 53
Expand file tree
/
Copy pathReactNativeRichTextEditorView.kt
More file actions
391 lines (314 loc) · 12.3 KB
/
Copy pathReactNativeRichTextEditorView.kt
File metadata and controls
391 lines (314 loc) · 12.3 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
package com.swmansion.reactnativerichtexteditor
import android.content.Context
import android.graphics.BlendMode
import android.graphics.BlendModeColorFilter
import android.graphics.Color
import android.os.Build
import android.text.Spannable
import android.text.StaticLayout
import android.text.method.LinkMovementMethod
import android.util.AttributeSet
import android.util.Log
import android.util.TypedValue
import android.view.MotionEvent
import android.view.inputmethod.InputMethodManager
import androidx.appcompat.widget.AppCompatEditText
import com.facebook.react.bridge.Arguments
import com.facebook.react.common.ReactConstants
import com.facebook.react.uimanager.PixelUtil
import com.facebook.react.uimanager.StateWrapper
import com.facebook.react.views.text.ReactTypefaceUtils.applyStyles
import com.facebook.react.views.text.ReactTypefaceUtils.parseFontStyle
import com.facebook.react.views.text.ReactTypefaceUtils.parseFontWeight
import com.swmansion.reactnativerichtexteditor.events.LinkHandler
import com.swmansion.reactnativerichtexteditor.events.MentionHandler
import com.swmansion.reactnativerichtexteditor.spans.EditorSpans
import com.swmansion.reactnativerichtexteditor.styles.InlineStyles
import com.swmansion.reactnativerichtexteditor.styles.ListStyles
import com.swmansion.reactnativerichtexteditor.styles.ParagraphStyles
import com.swmansion.reactnativerichtexteditor.styles.ParametrizedStyles
import com.swmansion.reactnativerichtexteditor.utils.EditorParser
import com.swmansion.reactnativerichtexteditor.utils.EditorSelection
import com.swmansion.reactnativerichtexteditor.utils.EditorSpanState
import com.swmansion.reactnativerichtexteditor.watchers.EditorSpanWatcher
import com.swmansion.reactnativerichtexteditor.watchers.EditorTextWatcher
import kotlin.math.ceil
class ReactNativeRichTextEditorView : AppCompatEditText {
private var stateWrapper: StateWrapper? = null
val selection: EditorSelection? = EditorSelection(this)
val spanState: EditorSpanState? = EditorSpanState(this)
val inlineStyles: InlineStyles? = InlineStyles(this)
val paragraphStyles: ParagraphStyles? = ParagraphStyles(this)
val listStyles: ListStyles? = ListStyles(this)
val parametrizedStyles: ParametrizedStyles? = ParametrizedStyles(this)
var isSettingDefaultValue: Boolean = false
var linkHandler: LinkHandler? = LinkHandler(this)
val mentionHandler: MentionHandler? = MentionHandler(this)
private var autoFocus = false
private var typefaceDirty = false
private var didAttachToWindow = false
private var detectScrollMovement = false
private var fontSize: Float? = null
private var fontFamily: String? = null
private var fontStyle: Int = ReactConstants.UNSET
private var fontWeight: Int = ReactConstants.UNSET
private var forceHeightRecalculationCounter: Int = 0
private var inputMethodManager: InputMethodManager? = null
constructor(context: Context) : super(context) {
prepareComponent()
}
constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
prepareComponent()
}
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(
context,
attrs,
defStyleAttr
) {
prepareComponent()
}
init {
inputMethodManager = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
}
private fun prepareComponent() {
isSingleLine = false
isHorizontalScrollBarEnabled = false
isVerticalScrollBarEnabled = true
gravity = android.view.Gravity.TOP or android.view.Gravity.START
inputType = android.text.InputType.TYPE_CLASS_TEXT or android.text.InputType.TYPE_TEXT_FLAG_MULTI_LINE
// required to make ClickableSpans really clickable
movementMethod = LinkMovementMethod.getInstance()
setPadding(0, 0, 0, 0)
setBackgroundColor(Color.TRANSPARENT)
addSpanWatcher(EditorSpanWatcher(this))
addTextChangedListener(EditorTextWatcher(this))
}
// https://github.com/facebook/react-native/blob/36df97f500aa0aa8031098caf7526db358b6ddc1/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/textinput/ReactEditText.kt#L295C1-L296C1
override fun onTouchEvent(ev: MotionEvent): Boolean {
when (ev.action) {
MotionEvent.ACTION_DOWN -> {
detectScrollMovement = true
// Disallow parent views to intercept touch events, until we can detect if we should be
// capturing these touches or not.
this.parent.requestDisallowInterceptTouchEvent(true)
}
MotionEvent.ACTION_MOVE ->
if (detectScrollMovement) {
if (!canScrollVertically(-1) &&
!canScrollVertically(1) &&
!canScrollHorizontally(-1) &&
!canScrollHorizontally(1)) {
// We cannot scroll, let parent views take care of these touches.
this.parent.requestDisallowInterceptTouchEvent(false)
}
detectScrollMovement = false
}
}
return super.onTouchEvent(ev)
}
override fun onSelectionChanged(selStart: Int, selEnd: Int) {
super.onSelectionChanged(selStart, selEnd)
selection?.onSelection(selStart, selEnd)
}
fun setStateWrapper(sw: StateWrapper?) {
stateWrapper = sw
}
override fun clearFocus() {
super.clearFocus()
inputMethodManager?.hideSoftInputFromWindow(windowToken, 0)
}
fun requestFocusProgrammatically() {
requestFocus()
inputMethodManager?.showSoftInput(this, 0)
setSelection(selection?.start ?: text?.length ?: 0)
}
fun setDefaultValue(value: String?) {
if (value == null) return
isSettingDefaultValue = true
val isHtml = value.startsWith("<html>") && value.endsWith("</html>")
if (isHtml) {
val parsed = EditorParser.fromHtml(value, EditorParser.FROM_HTML_MODE_COMPACT, null, null, linkHandler, mentionHandler)
setText(parsed)
} else {
setText(value)
}
// Assign SpanWatcher one more time as our previous spannable has been replaced
addSpanWatcher(EditorSpanWatcher(this))
// Scroll to the last line of text
setSelection(text?.length ?: 0)
isSettingDefaultValue = false
}
fun setAutoFocus(autoFocus: Boolean) {
this.autoFocus = autoFocus
}
fun setPlaceholder(placeholder: String?) {
if (placeholder == null) return
hint = placeholder
}
fun setPlaceholderTextColor(colorInt: Int?) {
if (colorInt == null) return
setHintTextColor(colorInt)
}
fun setSelectionColor(colorInt: Int?) {
if (colorInt == null) return
highlightColor = colorInt
}
fun setCursorColor(colorInt: Int?) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
val cursorDrawable = textCursorDrawable
if (cursorDrawable == null) return
if (colorInt != null) {
cursorDrawable.colorFilter = BlendModeColorFilter(colorInt, BlendMode.SRC_IN)
} else {
cursorDrawable.clearColorFilter()
}
textCursorDrawable = cursorDrawable
}
}
fun setColor(colorInt: Int?) {
if (colorInt == null) {
setTextColor(Color.BLACK)
return
}
setTextColor(colorInt)
}
fun setFontSize(size: Float) {
if (size == 0f) return
val sizeInt = ceil(PixelUtil.toPixelFromSP(size))
fontSize = sizeInt
setTextSize(TypedValue.COMPLEX_UNIT_PX, sizeInt)
updateYogaState()
}
fun setFontFamily(family: String?) {
if (family != fontFamily) {
fontFamily = family
typefaceDirty = true
}
}
fun setFontWeight(weight: String?) {
val fontWeight = parseFontWeight(weight)
if (fontWeight != fontStyle) {
this.fontWeight = fontWeight
typefaceDirty = true
}
}
fun setFontStyle(style: String?) {
val fontStyle = parseFontStyle(style)
if (fontStyle != this.fontStyle) {
this.fontStyle = fontStyle
typefaceDirty = true
}
}
// https://github.com/facebook/react-native/blob/36df97f500aa0aa8031098caf7526db358b6ddc1/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/textinput/ReactEditText.kt#L283C2-L284C1
// After the text changes inside an EditText, TextView checks if a layout() has been requested.
// If it has, it will not scroll the text to the end of the new text inserted, but wait for the
// next layout() to be called. However, we do not perform a layout() after a requestLayout(), so
// we need to override isLayoutRequested to force EditText to scroll to the end of the new text
// immediately.
override fun isLayoutRequested(): Boolean {
return false
}
fun measureSize(maxWidth: Float): Pair<Float, Float> {
val paint = this.paint
val spannable = text as Spannable
val spannableLength = spannable.length
val staticLayout = StaticLayout.Builder
.obtain(spannable, 0, spannableLength, paint, maxWidth.toInt())
.setIncludePad(true)
.setLineSpacing(0f, 1f)
.build()
val heightInSP = PixelUtil.toDIPFromPixel(staticLayout.height.toFloat())
val widthInSP = PixelUtil.toDIPFromPixel(maxWidth)
return Pair(widthInSP, heightInSP)
}
fun updateTypeface() {
if (!typefaceDirty) return
typefaceDirty = false
val newTypeface = applyStyles(typeface, fontStyle, fontWeight, fontFamily, context.assets)
typeface = newTypeface
paint.typeface = newTypeface
updateYogaState()
}
private fun toggleStyle(name: String) {
when (name) {
EditorSpans.BOLD -> inlineStyles?.toggleStyle(EditorSpans.BOLD)
EditorSpans.ITALIC -> inlineStyles?.toggleStyle(EditorSpans.ITALIC)
EditorSpans.UNDERLINE -> inlineStyles?.toggleStyle(EditorSpans.UNDERLINE)
EditorSpans.STRIKETHROUGH -> inlineStyles?.toggleStyle(EditorSpans.STRIKETHROUGH)
EditorSpans.INLINE_CODE -> inlineStyles?.toggleStyle(EditorSpans.INLINE_CODE)
EditorSpans.H1 -> paragraphStyles?.toggleStyle(EditorSpans.H1)
EditorSpans.H2 -> paragraphStyles?.toggleStyle(EditorSpans.H2)
EditorSpans.H3 -> paragraphStyles?.toggleStyle(EditorSpans.H3)
EditorSpans.CODE_BLOCK -> paragraphStyles?.toggleStyle(EditorSpans.CODE_BLOCK)
EditorSpans.BLOCK_QUOTE -> paragraphStyles?.toggleStyle(EditorSpans.BLOCK_QUOTE)
EditorSpans.ORDERED_LIST -> listStyles?.toggleStyle(EditorSpans.ORDERED_LIST)
EditorSpans.UNORDERED_LIST -> listStyles?.toggleStyle(EditorSpans.UNORDERED_LIST)
else -> Log.w("ReactNativeRichTextEditorView", "Unknown style: $name")
}
}
private fun verifyStyle(name: String): Boolean {
val mergingConfig = EditorSpans.mergingConfig[name] ?: return true
val conflictingStyles = mergingConfig.conflictingStyles
val blockingStyles = mergingConfig.blockingStyles
for (style in blockingStyles) {
if (spanState?.getStart(style) != null) {
spanState.setStart(name, null)
return false
}
}
for (style in conflictingStyles) {
if (spanState?.getStart(style) != null) {
toggleStyle(style)
}
}
return true
}
private fun addSpanWatcher(watcher: EditorSpanWatcher) {
val spannable = text as Spannable
spannable.setSpan(watcher, 0, spannable.length, Spannable.SPAN_INCLUSIVE_INCLUSIVE)
}
fun verifyAndToggleStyle(name: String) {
val isValid = verifyStyle(name)
if (!isValid) return
toggleStyle(name)
}
fun addLink(text: String, url: String) {
val isValid = verifyStyle(EditorSpans.LINK)
if (!isValid) return
parametrizedStyles?.setLinkSpan(text, url)
}
fun addImage(src: String) {
val isValid = verifyStyle(EditorSpans.IMAGE)
if (!isValid) return
parametrizedStyles?.setImageSpan(src)
}
fun startMention(indicator: String) {
val isValid = verifyStyle(EditorSpans.MENTION)
if (!isValid) return
parametrizedStyles?.startMention(indicator)
}
fun addMention(indicator: String, text: String, value: String) {
val isValid = verifyStyle(EditorSpans.MENTION)
if (!isValid) return
parametrizedStyles?.setMentionSpan(indicator, text, value)
}
// Update shadow node's state in order to recalculate layout
fun updateYogaState() {
val counter = forceHeightRecalculationCounter
forceHeightRecalculationCounter++
val state = Arguments.createMap()
state.putInt("forceHeightRecalculationCounter", counter)
stateWrapper?.updateState(state)
}
override fun onAttachedToWindow() {
super.onAttachedToWindow()
if (autoFocus && !didAttachToWindow) {
requestFocusProgrammatically()
}
didAttachToWindow = true
}
override fun onDetachedFromWindow() {
forceHeightRecalculationCounter = 0
super.onDetachedFromWindow()
}
}