-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathEnrichedMarkdownText.kt
More file actions
335 lines (280 loc) · 10.8 KB
/
EnrichedMarkdownText.kt
File metadata and controls
335 lines (280 loc) · 10.8 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
package com.swmansion.enriched.markdown
import android.content.Context
import android.content.res.Configuration
import android.graphics.Canvas
import android.os.Build
import android.os.Handler
import android.os.Looper
import android.text.Layout
import android.util.AttributeSet
import android.util.Log
import android.view.MotionEvent
import com.facebook.react.bridge.ReadableMap
import com.swmansion.enriched.markdown.accessibility.AccessibleMarkdownTextView
import com.swmansion.enriched.markdown.parser.Md4cFlags
import com.swmansion.enriched.markdown.parser.Parser
import com.swmansion.enriched.markdown.renderer.Renderer
import com.swmansion.enriched.markdown.spoiler.SpoilerCapable
import com.swmansion.enriched.markdown.spoiler.SpoilerOverlay
import com.swmansion.enriched.markdown.spoiler.SpoilerOverlayDrawer
import com.swmansion.enriched.markdown.styles.StyleConfig
import com.swmansion.enriched.markdown.utils.text.TailFadeInAnimator
import com.swmansion.enriched.markdown.utils.text.interaction.CheckboxTouchHelper
import com.swmansion.enriched.markdown.utils.text.view.LinkLongPressMovementMethod
import com.swmansion.enriched.markdown.utils.text.view.applySelectableState
import com.swmansion.enriched.markdown.utils.text.view.applySelectionColors
import com.swmansion.enriched.markdown.utils.text.view.cancelJSTouchForCheckboxTap
import com.swmansion.enriched.markdown.utils.text.view.cancelJSTouchForLinkTap
import com.swmansion.enriched.markdown.utils.text.view.createSelectionActionModeCallback
import com.swmansion.enriched.markdown.utils.text.view.emitLinkLongPressEvent
import com.swmansion.enriched.markdown.utils.text.view.emitLinkPressEvent
import com.swmansion.enriched.markdown.utils.text.view.setupAsMarkdownTextView
import java.util.concurrent.Executors
/**
* EnrichedMarkdownText that handles Markdown parsing and rendering on a background thread.
* View starts invisible and becomes visible after render completes to avoid layout shift.
*/
class EnrichedMarkdownText
@JvmOverloads
constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0,
) : AccessibleMarkdownTextView(context, attrs, defStyleAttr),
SpoilerCapable {
private val parser = Parser.shared
private val renderer = Renderer()
private var onLinkPressCallback: ((String) -> Unit)? = null
private var onLinkLongPressCallback: ((String) -> Unit)? = null
private val checkboxTouchHelper = CheckboxTouchHelper(this)
private val mainHandler = Handler(Looper.getMainLooper())
private val executor = Executors.newSingleThreadExecutor()
private var currentRenderId = 0L
val layoutManager = EnrichedMarkdownTextLayoutManager(this)
private var contextMenuItemTexts: List<String> = emptyList()
var onContextMenuItemPressCallback: ((itemText: String, selectedText: String, selectionStart: Int, selectionEnd: Int) -> Unit)? = null
var markdownStyle: StyleConfig? = null
private set
var currentMarkdown: String = ""
private set
var md4cFlags: Md4cFlags = Md4cFlags.DEFAULT
private set
private var lastKnownFontScale: Float = context.resources.configuration.fontScale
private var markdownStyleMap: ReadableMap? = null
private var allowFontScaling: Boolean = true
private var maxFontSizeMultiplier: Float = 0f
private var allowTrailingMargin: Boolean = false
private var streamingAnimation: Boolean = false
private var previousTextLength: Int = 0
private var fadeAnimator: TailFadeInAnimator? = null
override var spoilerOverlayDrawer: SpoilerOverlayDrawer? = null
private set
var spoilerOverlay: SpoilerOverlay = SpoilerOverlay.PARTICLES
private var selectionColor: Int? = null
private var selectionHandleColor: Int? = null
init {
setupAsMarkdownTextView()
customSelectionActionModeCallback =
createSelectionActionModeCallback(
this,
getCustomItemTexts = { contextMenuItemTexts },
onCustomItemPress = { itemText, selectedText, start, end ->
onContextMenuItemPressCallback?.invoke(itemText, selectedText, start, end)
},
)
}
fun setMarkdownContent(markdown: String) {
if (currentMarkdown == markdown) return
currentMarkdown = markdown
scheduleRender()
}
fun setMarkdownStyle(style: ReadableMap?) {
markdownStyleMap = style
// Register font scaling settings when style is set (view should have ID by now)
updateMeasurementStoreFontScaling()
val newStyle = style?.let { StyleConfig(it, context, allowFontScaling, maxFontSizeMultiplier) }
if (markdownStyle == newStyle) return
markdownStyle = newStyle
updateJustificationMode(newStyle)
scheduleRender()
}
override fun onConfigurationChanged(newConfig: Configuration) {
super.onConfigurationChanged(newConfig)
if (!allowFontScaling) {
return
}
val newFontScale = newConfig.fontScale
if (newFontScale != lastKnownFontScale) {
lastKnownFontScale = newFontScale
recreateStyleConfig()
scheduleRenderIfNeeded()
}
}
fun setMd4cFlags(flags: Md4cFlags) {
if (md4cFlags == flags) return
md4cFlags = flags
scheduleRenderIfNeeded()
}
fun setAllowFontScaling(allow: Boolean) {
if (allowFontScaling == allow) return
allowFontScaling = allow
updateMeasurementStoreFontScaling()
recreateStyleConfig()
scheduleRenderIfNeeded()
}
fun setMaxFontSizeMultiplier(multiplier: Float) {
if (maxFontSizeMultiplier == multiplier) return
maxFontSizeMultiplier = multiplier
updateMeasurementStoreFontScaling()
recreateStyleConfig()
scheduleRenderIfNeeded()
}
fun setAllowTrailingMargin(allow: Boolean) {
if (allowTrailingMargin == allow) return
allowTrailingMargin = allow
scheduleRenderIfNeeded()
}
fun setStreamingAnimation(enabled: Boolean) {
if (streamingAnimation == enabled) return
streamingAnimation = enabled
if (enabled) {
previousTextLength = text?.length ?: 0
} else {
fadeAnimator?.cancelAll()
fadeAnimator = null
previousTextLength = 0
}
}
private fun updateMeasurementStoreFontScaling() {
MeasurementStore.updateFontScalingSettings(id, allowFontScaling, maxFontSizeMultiplier)
}
private fun scheduleRenderIfNeeded() {
if (currentMarkdown.isNotEmpty()) {
scheduleRender()
}
}
private fun recreateStyleConfig() {
markdownStyleMap?.let { styleMap ->
markdownStyle = StyleConfig(styleMap, context, allowFontScaling, maxFontSizeMultiplier)
updateJustificationMode(markdownStyle)
}
}
private fun updateJustificationMode(style: StyleConfig?) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
justificationMode =
if (style?.needsJustify == true) {
Layout.JUSTIFICATION_MODE_INTER_WORD
} else {
Layout.JUSTIFICATION_MODE_NONE
}
}
}
private fun scheduleRender() {
val style = markdownStyle ?: return
val markdown = currentMarkdown
if (markdown.isEmpty()) return
val renderId = ++currentRenderId
executor.execute {
try {
val ast =
parser.parseMarkdown(markdown, md4cFlags) ?: run {
mainHandler.post { if (renderId == currentRenderId) text = "" }
return@execute
}
renderer.configure(style, context)
val styledText = renderer.renderDocument(ast, onLinkPressCallback, onLinkLongPressCallback)
mainHandler.post {
if (renderId == currentRenderId) {
applyRenderedText(styledText)
}
}
} catch (e: Exception) {
Log.e(TAG, "Render failed: ${e.message}", e)
mainHandler.post { if (renderId == currentRenderId) text = "" }
}
}
}
private fun applyRenderedText(styledText: CharSequence) {
val tailStart = previousTextLength
text = styledText
if (movementMethod !is LinkLongPressMovementMethod) {
movementMethod = LinkLongPressMovementMethod.createInstance()
}
renderer.getCollectedImageSpans().forEach { span ->
span.registerTextView(this)
}
spoilerOverlayDrawer = SpoilerOverlayDrawer.setupIfNeeded(this, styledText, spoilerOverlayDrawer, spoilerOverlay)
layoutManager.invalidateLayout()
accessibilityHelper.invalidateAccessibilityItems()
if (streamingAnimation) {
if (fadeAnimator == null) {
fadeAnimator = TailFadeInAnimator(this)
}
fadeAnimator?.animate(tailStart, styledText.length)
previousTextLength = styledText.length
}
applySelectionColors(selectionColor, selectionHandleColor)
}
fun setContextMenuItems(items: List<String>) {
contextMenuItemTexts = items
}
fun setIsSelectable(selectable: Boolean) {
applySelectableState(selectable)
}
fun setSelectionColor(color: Int?) {
if (selectionColor == color) return
selectionColor = color
applySelectionColors(selectionColor, selectionHandleColor)
}
fun setSelectionHandleColor(color: Int?) {
if (selectionHandleColor == color) return
selectionHandleColor = color
applySelectionColors(selectionColor, selectionHandleColor)
}
fun emitOnLinkPress(url: String) {
emitLinkPressEvent(url)
}
fun emitOnLinkLongPress(url: String) {
emitLinkLongPressEvent(url)
}
fun setOnLinkPressCallback(callback: (String) -> Unit) {
onLinkPressCallback = callback
}
fun setOnLinkLongPressCallback(callback: (String) -> Unit) {
onLinkLongPressCallback = callback
}
fun setOnTaskListItemPressCallback(callback: ((taskIndex: Int, checked: Boolean, itemText: String) -> Unit)?) {
checkboxTouchHelper.onCheckboxTap = callback
}
fun clearActiveImageSpans() {
renderer.clearActiveImageSpans()
}
override fun onDetachedFromWindow() {
stopSpoilerAnimations()
super.onDetachedFromWindow()
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
spoilerOverlayDrawer?.draw(canvas)
}
private fun stopSpoilerAnimations() {
spoilerOverlayDrawer?.stop()
spoilerOverlayDrawer = null
}
override fun onTouchEvent(event: MotionEvent): Boolean {
if (checkboxTouchHelper.onTouchEvent(event)) {
if (event.action == MotionEvent.ACTION_DOWN) {
cancelJSTouchForCheckboxTap(event)
}
return true
}
val result = super.onTouchEvent(event)
if (event.action == MotionEvent.ACTION_DOWN) {
cancelJSTouchForLinkTap(event)
}
return result
}
companion object {
private const val TAG = "EnrichedMarkdownMeasure"
}
}