-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEnrichedMarkdown.kt
More file actions
341 lines (293 loc) · 11.1 KB
/
EnrichedMarkdown.kt
File metadata and controls
341 lines (293 loc) · 11.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
package com.swmansion.enriched.markdown
import android.content.Context
import android.content.res.Configuration
import android.os.Build
import android.os.Handler
import android.os.Looper
import android.util.AttributeSet
import android.util.Log
import android.view.View
import android.widget.FrameLayout
import com.facebook.react.bridge.ReadableMap
import com.swmansion.enriched.markdown.parser.Md4cFlags
import com.swmansion.enriched.markdown.parser.Parser
import com.swmansion.enriched.markdown.spoiler.SpoilerOverlay
import com.swmansion.enriched.markdown.styles.StyleConfig
import com.swmansion.enriched.markdown.utils.common.FeatureFlags
import com.swmansion.enriched.markdown.utils.common.MarkdownSegmentRenderer
import com.swmansion.enriched.markdown.utils.common.RenderedSegment
import com.swmansion.enriched.markdown.utils.common.splitASTIntoSegments
import com.swmansion.enriched.markdown.utils.text.view.applySelectionColors
import com.swmansion.enriched.markdown.utils.text.view.emitLinkLongPressEvent
import com.swmansion.enriched.markdown.utils.text.view.emitLinkPressEvent
import com.swmansion.enriched.markdown.views.BlockSegmentView
import com.swmansion.enriched.markdown.views.TableContainerView
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
class EnrichedMarkdown
@JvmOverloads
constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0,
) : FrameLayout(context, attrs, defStyleAttr) {
private val parser = Parser.shared
private val mainHandler = Handler(Looper.getMainLooper())
private val executor: ExecutorService = Executors.newSingleThreadExecutor()
private var currentRenderId = 0L
private val segmentViews = mutableListOf<View>()
var currentMarkdown: String = ""
private set
var markdownStyle: StyleConfig? = null
private set
private var markdownStyleMap: ReadableMap? = null
private var lastKnownFontScale: Float = context.resources.configuration.fontScale
var md4cFlags: Md4cFlags = Md4cFlags.DEFAULT
private set
private var allowFontScaling: Boolean = true
private var maxFontSizeMultiplier: Float = 0f
private var allowTrailingMargin: Boolean = false
private var selectable: Boolean = true
private var selectionColor: Int? = null
private var selectionHandleColor: Int? = null
private var onLinkPressCallback: ((String) -> Unit)? = null
private var onLinkLongPressCallback: ((String) -> Unit)? = null
private var onTaskListItemPressCallback: ((Int, Boolean, String) -> Unit)? = null
private var contextMenuItemTexts: List<String> = emptyList()
var onContextMenuItemPressCallback: ((itemText: String, selectedText: String, selectionStart: Int, selectionEnd: Int) -> Unit)? = null
var spoilerOverlay: SpoilerOverlay = SpoilerOverlay.PARTICLES
set(value) {
if (field == value) return
field = value
segmentViews.filterIsInstance<EnrichedMarkdownInternalText>().forEach {
it.spoilerOverlay = value
}
}
fun setMarkdownContent(markdown: String) {
if (currentMarkdown == markdown) return
currentMarkdown = markdown
scheduleRender()
}
fun setMarkdownStyle(style: ReadableMap?) {
markdownStyleMap = style
val newConfig = style?.let { StyleConfig(it, context, allowFontScaling, maxFontSizeMultiplier) }
if (markdownStyle == newConfig) return
markdownStyle = newConfig
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
recreateStyleConfig()
scheduleRenderIfNeeded()
}
fun setMaxFontSizeMultiplier(multiplier: Float) {
if (maxFontSizeMultiplier == multiplier) return
maxFontSizeMultiplier = multiplier
recreateStyleConfig()
scheduleRenderIfNeeded()
}
fun setAllowTrailingMargin(allow: Boolean) {
if (allowTrailingMargin == allow) return
allowTrailingMargin = allow
scheduleRenderIfNeeded()
}
fun setIsSelectable(value: Boolean) {
if (selectable == value) return
selectable = value
segmentViews.filterIsInstance<EnrichedMarkdownInternalText>().forEach {
it.setIsSelectable(value)
}
}
fun setSelectionColor(color: Int?) {
selectionColor = color
applySelectionColorsToSegments()
}
fun setSelectionHandleColor(color: Int?) {
selectionHandleColor = color
applySelectionColorsToSegments()
}
private fun applySelectionColorsToSegments() {
segmentViews.filterIsInstance<EnrichedMarkdownInternalText>().forEach {
it.applySelectionColors(selectionColor, selectionHandleColor)
}
}
fun setOnLinkPressCallback(callback: (String) -> Unit) {
onLinkPressCallback = callback
}
fun setOnLinkLongPressCallback(callback: (String) -> Unit) {
onLinkLongPressCallback = callback
}
fun setOnTaskListItemPressCallback(callback: ((taskIndex: Int, checked: Boolean, itemText: String) -> Unit)?) {
onTaskListItemPressCallback = callback
}
fun setContextMenuItems(items: List<String>) {
contextMenuItemTexts = items
segmentViews.filterIsInstance<EnrichedMarkdownInternalText>().forEach {
it.setContextMenuItems(items, ::forwardContextMenuItemPress)
}
}
private fun forwardContextMenuItemPress(
itemText: String,
selectedText: String,
selectionStart: Int,
selectionEnd: Int,
) {
onContextMenuItemPressCallback?.invoke(itemText, selectedText, selectionStart, selectionEnd)
}
private fun recreateStyleConfig() {
markdownStyleMap?.let {
markdownStyle = StyleConfig(it, context, allowFontScaling, maxFontSizeMultiplier)
}
}
private fun scheduleRenderIfNeeded() {
if (currentMarkdown.isNotEmpty()) scheduleRender()
}
private fun scheduleRender() {
val style = markdownStyle ?: return
val markdown = currentMarkdown.takeIf { it.isNotEmpty() } ?: return
val renderId = ++currentRenderId
executor.execute {
try {
val ast =
parser.parseMarkdown(markdown, md4cFlags) ?: run {
postToMain(renderId) { clearSegments() }
return@execute
}
val segments = splitASTIntoSegments(ast)
val renderedSegments =
MarkdownSegmentRenderer.render(
segments,
style,
context,
onLinkPressCallback,
onLinkLongPressCallback,
)
postToMain(renderId) { applyRenderedSegments(renderedSegments, style) }
} catch (e: Exception) {
Log.e(TAG, "Render failed", e)
postToMain(renderId) { clearSegments() }
}
}
}
private fun applyRenderedSegments(
renderedSegments: List<RenderedSegment>,
style: StyleConfig,
) {
clearSegments()
renderedSegments.forEach { segment ->
val view =
when (segment) {
is RenderedSegment.Text -> createTextView(segment)
is RenderedSegment.Table -> createTableView(segment, style)
is RenderedSegment.Math -> createMathView(segment, style)
}
segmentViews.add(view)
addView(view)
}
layoutSegments()
}
private fun createTextView(segment: RenderedSegment.Text) =
EnrichedMarkdownInternalText(context).apply {
spoilerOverlay = this@EnrichedMarkdown.spoilerOverlay
setIsSelectable(selectable)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && segment.needsJustify) {
justificationMode = android.text.Layout.JUSTIFICATION_MODE_INTER_WORD
}
lastElementMarginBottom = segment.lastElementMarginBottom
applyStyledText(segment.styledText)
segment.imageSpans.forEach { it.registerTextView(this) }
onTaskListItemPressCallback = { taskIndex, checked, itemText ->
this@EnrichedMarkdown.onTaskListItemPressCallback?.invoke(taskIndex, checked, itemText)
}
if (contextMenuItemTexts.isNotEmpty()) {
setContextMenuItems(contextMenuItemTexts, ::forwardContextMenuItemPress)
}
applySelectionColors(selectionColor, selectionHandleColor)
}
private fun createTableView(
segment: RenderedSegment.Table,
style: StyleConfig,
) = TableContainerView(context, style).apply {
allowFontScaling = this@EnrichedMarkdown.allowFontScaling
maxFontSizeMultiplier = this@EnrichedMarkdown.maxFontSizeMultiplier
onLinkPress = onLinkPressCallback
onLinkLongPress = onLinkLongPressCallback
applyTableNode(segment.node)
}
private fun createMathView(
segment: RenderedSegment.Math,
style: StyleConfig,
): android.view.View {
if (!FeatureFlags.IS_MATH_ENABLED) return android.view.View(context)
return try {
val mathContainerClass = Class.forName("com.swmansion.enriched.markdown.views.MathContainerView")
val view =
mathContainerClass
.getConstructor(android.content.Context::class.java, StyleConfig::class.java)
.newInstance(context, style) as android.view.View
mathContainerClass.getMethod("applyLatex", String::class.java).invoke(view, segment.latex)
view
} catch (_: Exception) {
android.view.View(context)
}
}
private fun postToMain(
renderId: Long,
action: () -> Unit,
) {
mainHandler.post {
if (renderId == currentRenderId) action()
}
}
private fun clearSegments() {
segmentViews.forEach { removeView(it) }
segmentViews.clear()
}
override fun onLayout(
changed: Boolean,
l: Int,
t: Int,
r: Int,
b: Int,
) {
layoutSegments()
}
private fun layoutSegments() {
val containerWidth = width
if (containerWidth <= 0) return
var currentY = 0
val lastIndex = segmentViews.lastIndex
val widthSpec = MeasureSpec.makeMeasureSpec(containerWidth, MeasureSpec.EXACTLY)
val heightSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED)
segmentViews.forEachIndexed { index, view ->
val segment = view as? BlockSegmentView
val shouldAddBottomMargin = index != lastIndex || allowTrailingMargin
currentY += segment?.segmentMarginTop ?: 0
view.measure(widthSpec, heightSpec)
view.layout(0, currentY, containerWidth, currentY + view.measuredHeight)
currentY += view.measuredHeight
if (shouldAddBottomMargin) {
currentY += segment?.segmentMarginBottom ?: 0
}
}
}
companion object {
private const val TAG = "EnrichedMarkdown"
}
}