diff --git a/.maestro/androidExample/enrichedMarkdownText/screenshots/android/mixed_nested_list_display.png b/.maestro/androidExample/enrichedMarkdownText/screenshots/android/mixed_nested_list_display.png index f5ff1ff70..f6a76cfd6 100644 Binary files a/.maestro/androidExample/enrichedMarkdownText/screenshots/android/mixed_nested_list_display.png and b/.maestro/androidExample/enrichedMarkdownText/screenshots/android/mixed_nested_list_display.png differ diff --git a/.maestro/enrichedMarkdownText/flows/advanced/block_elements/mixed_nested_list_markers_test.yaml b/.maestro/enrichedMarkdownText/flows/advanced/block_elements/mixed_nested_list_markers_test.yaml new file mode 100644 index 000000000..fe8051110 --- /dev/null +++ b/.maestro/enrichedMarkdownText/flows/advanced/block_elements/mixed_nested_list_markers_test.yaml @@ -0,0 +1,92 @@ +appId: swmansion.enriched.markdown.example +tags: + - block + - advanced + - list + - task_list + - text + - android-only +--- +- launchApp: + permissions: {} + +- waitForAnimationToEnd + +- runFlow: + file: '../../../../subflows/move_to_playground.yaml' + +- assertVisible: + id: playground-screen + +- runFlow: + file: '../../../subflows/set_enriched_text_value.yaml' + env: + VALUE: | + 1. Ordered parent + - Bullet child + - Second bullet child + 2. Following ordered sibling + + - Bullet parent + 1. Ordered child + 2. Second ordered child + - Following bullet sibling + +- scrollUntilVisible: + element: + id: blur-button + direction: UP + visibilityPercentage: 100 + +- tapOn: + id: blur-button + +- scroll + +- waitForAnimationToEnd + +- runFlow: + file: '../../../subflows/capture_or_assert_screenshot.yaml' + env: + SCREENSHOT_NAME: 'mixed_nested_list_markers_bullet_ordered_display' + +- scrollUntilVisible: + element: + id: set-markdown-button + direction: UP + visibilityPercentage: 100 + +- runFlow: + file: '../../../subflows/set_enriched_text_value.yaml' + env: + VALUE: | + - Bullet parent + - [ ] Unchecked task child + - [x] Checked task child + + 1. Ordered parent + - [ ] Unchecked task child + - [x] Checked task child + + - [ ] Unchecked task parent + - Bullet child + - [x] Checked task parent + - Second bullet child + +- scrollUntilVisible: + element: + id: blur-button + direction: UP + visibilityPercentage: 100 + +- tapOn: + id: blur-button + +- scroll + +- waitForAnimationToEnd + +- runFlow: + file: '../../../subflows/capture_or_assert_screenshot.yaml' + env: + SCREENSHOT_NAME: 'mixed_nested_list_markers_tasks_display' diff --git a/.maestro/enrichedMarkdownText/flows/basic/block_elements/mixed_nested_list_test.yaml b/.maestro/enrichedMarkdownText/flows/basic/block_elements/mixed_nested_list_test.yaml index c7abe1af5..df5738ffe 100644 --- a/.maestro/enrichedMarkdownText/flows/basic/block_elements/mixed_nested_list_test.yaml +++ b/.maestro/enrichedMarkdownText/flows/basic/block_elements/mixed_nested_list_test.yaml @@ -25,6 +25,13 @@ tags: 1. Django 2. FastAPI +- runFlow: + when: + platform: Android + commands: + - scroll + - waitForAnimationToEnd + - runFlow: file: '../../../subflows/capture_or_assert_screenshot.yaml' env: diff --git a/.maestro/enrichedMarkdownText/screenshots/android/list_sublist_first_combo_display.png b/.maestro/enrichedMarkdownText/screenshots/android/list_sublist_first_combo_display.png index 2e90f0cc9..993688cd8 100644 Binary files a/.maestro/enrichedMarkdownText/screenshots/android/list_sublist_first_combo_display.png and b/.maestro/enrichedMarkdownText/screenshots/android/list_sublist_first_combo_display.png differ diff --git a/.maestro/enrichedMarkdownText/screenshots/android/mixed_nested_list_display.png b/.maestro/enrichedMarkdownText/screenshots/android/mixed_nested_list_display.png index 222ad4031..395de18f1 100644 Binary files a/.maestro/enrichedMarkdownText/screenshots/android/mixed_nested_list_display.png and b/.maestro/enrichedMarkdownText/screenshots/android/mixed_nested_list_display.png differ diff --git a/.maestro/enrichedMarkdownText/screenshots/android/mixed_nested_list_markers_bullet_ordered_display.png b/.maestro/enrichedMarkdownText/screenshots/android/mixed_nested_list_markers_bullet_ordered_display.png new file mode 100644 index 000000000..5f2869828 Binary files /dev/null and b/.maestro/enrichedMarkdownText/screenshots/android/mixed_nested_list_markers_bullet_ordered_display.png differ diff --git a/.maestro/enrichedMarkdownText/screenshots/android/mixed_nested_list_markers_tasks_display.png b/.maestro/enrichedMarkdownText/screenshots/android/mixed_nested_list_markers_tasks_display.png new file mode 100644 index 000000000..d90cfec1c Binary files /dev/null and b/.maestro/enrichedMarkdownText/screenshots/android/mixed_nested_list_markers_tasks_display.png differ diff --git a/packages/enriched-markdown-android/ui/src/main/java/com/swmansion/enriched/markdown/renderer/BlockStyleContext.kt b/packages/enriched-markdown-android/ui/src/main/java/com/swmansion/enriched/markdown/renderer/BlockStyleContext.kt index 7cab2df14..401383bef 100644 --- a/packages/enriched-markdown-android/ui/src/main/java/com/swmansion/enriched/markdown/renderer/BlockStyleContext.kt +++ b/packages/enriched-markdown-android/ui/src/main/java/com/swmansion/enriched/markdown/renderer/BlockStyleContext.kt @@ -44,6 +44,7 @@ class BlockStyleContext { var listMarkerExtra = 0f var ancestorMarkerOffset = 0f var listItemMarkerExtra = 0f + var listItemMarkerWidth: Float? = null var taskItemCount = 0 private val orderedListItemNumbers = ArrayDeque() @@ -155,6 +156,7 @@ class BlockStyleContext { listMarkerExtra = 0f ancestorMarkerOffset = 0f listItemMarkerExtra = 0f + listItemMarkerWidth = null taskItemCount = 0 orderedListItemNumbers.clear() } diff --git a/packages/enriched-markdown-android/ui/src/main/java/com/swmansion/enriched/markdown/renderer/ListItemRenderer.kt b/packages/enriched-markdown-android/ui/src/main/java/com/swmansion/enriched/markdown/renderer/ListItemRenderer.kt index 5878fe6c0..f0d854472 100644 --- a/packages/enriched-markdown-android/ui/src/main/java/com/swmansion/enriched/markdown/renderer/ListItemRenderer.kt +++ b/packages/enriched-markdown-android/ui/src/main/java/com/swmansion/enriched/markdown/renderer/ListItemRenderer.kt @@ -51,6 +51,7 @@ class ListItemRenderer( isChecked = isChecked, ancestorMarkerOffset = styleContext.ancestorMarkerOffset, markerExtraWidth = styleContext.listMarkerExtra, + parentMarkerWidth = styleContext.listItemMarkerWidth, ) } else { when (listType) { @@ -61,6 +62,7 @@ class ListItemRenderer( factory.context, factory.styleCache, ancestorMarkerOffset = styleContext.ancestorMarkerOffset, + parentMarkerWidth = styleContext.listItemMarkerWidth, ) } @@ -72,6 +74,7 @@ class ListItemRenderer( factory.styleCache, markerExtraWidth = styleContext.listMarkerExtra, ancestorMarkerOffset = styleContext.ancestorMarkerOffset, + parentMarkerWidth = styleContext.listItemMarkerWidth, ).apply { setItemNumber(styleContext.listItemNumber) } @@ -79,13 +82,16 @@ class ListItemRenderer( } } - // Nested lists inside this item shift by its extra marker width. + // Nested lists inside this item shift by its extra marker width and measure their indent from its column. val previousMarkerExtra = styleContext.listItemMarkerExtra styleContext.listItemMarkerExtra = span.markerExtraWidth + val previousMarkerWidth = styleContext.listItemMarkerWidth + styleContext.listItemMarkerWidth = span.baselineMarkerWidth try { factory.renderChildren(node, builder, onLinkPress, onLinkLongPress) } finally { styleContext.listItemMarkerExtra = previousMarkerExtra + styleContext.listItemMarkerWidth = previousMarkerWidth } if (builder.length == start || builder.substring(start).isBlank()) return diff --git a/packages/enriched-markdown-android/ui/src/main/java/com/swmansion/enriched/markdown/spans/BaseListSpan.kt b/packages/enriched-markdown-android/ui/src/main/java/com/swmansion/enriched/markdown/spans/BaseListSpan.kt index cffeb499a..7e8754941 100644 --- a/packages/enriched-markdown-android/ui/src/main/java/com/swmansion/enriched/markdown/spans/BaseListSpan.kt +++ b/packages/enriched-markdown-android/ui/src/main/java/com/swmansion/enriched/markdown/spans/BaseListSpan.kt @@ -23,6 +23,7 @@ abstract class BaseListSpan( protected val marginLeft: Float, protected val gapWidth: Float, internal val ancestorMarkerOffset: Float = 0f, + internal val parentMarkerWidth: Float? = null, ) : MetricAffectingSpan(), LeadingMarginSpan { private var cachedText: CharSequence? = null @@ -41,17 +42,25 @@ abstract class BaseListSpan( /** How far an ordered list widened this item's column past the one short lists reserve. */ internal open val markerExtraWidth: Float = 0f + /** This item's marker column without [markerExtraWidth]; a nested item measures its indent against it. */ + internal open val baselineMarkerWidth: Float get() = getMarkerWidth() + override fun updateMeasureState(textPaint: TextPaint) = applyTextStyle(textPaint) override fun updateDrawState(textPaint: TextPaint) = applyTextStyle(textPaint) - override fun getLeadingMargin(first: Boolean): Int = - if (depth == 0) { - val effectiveGap = gapWidth.coerceAtLeast(DEFAULT_MIN_GAP) - (getMarkerWidth() + effectiveGap).toInt() - } else { - (marginLeft + markerExtraWidth).toInt() - } + override fun getLeadingMargin(first: Boolean): Int { + val effectiveGap = gapWidth.coerceAtLeast(DEFAULT_MIN_GAP) + if (depth == 0) return (getMarkerWidth() + effectiveGap).toInt() + + // Subtract truncated absolute indents, each measured from its own item's column, so neither mixed + // columns nor fractional margins accumulate rounding. The widenings are whole pixels and add unchanged. + val markerWidth = baselineMarkerWidth + val parentWidth = parentMarkerWidth ?: markerWidth + val indent = (depth * marginLeft + markerWidth + effectiveGap).toInt() + val parentIndent = ((depth - 1) * marginLeft + parentWidth + effectiveGap).toInt() + return indent - parentIndent + markerExtraWidth.toInt() + } override fun drawLeadingMargin( canvas: Canvas, diff --git a/packages/enriched-markdown-android/ui/src/main/java/com/swmansion/enriched/markdown/spans/OrderedListSpan.kt b/packages/enriched-markdown-android/ui/src/main/java/com/swmansion/enriched/markdown/spans/OrderedListSpan.kt index 2d1130e5d..6183204d6 100644 --- a/packages/enriched-markdown-android/ui/src/main/java/com/swmansion/enriched/markdown/spans/OrderedListSpan.kt +++ b/packages/enriched-markdown-android/ui/src/main/java/com/swmansion/enriched/markdown/spans/OrderedListSpan.kt @@ -19,6 +19,7 @@ class OrderedListSpan( styleCache: SpanStyleCache, override val markerExtraWidth: Float = 0f, ancestorMarkerOffset: Float = 0f, + parentMarkerWidth: Float? = null, ) : BaseListSpan( depth = depth, context = context, @@ -33,6 +34,7 @@ class OrderedListSpan( marginLeft = listStyle.marginLeft, gapWidth = listStyle.gapWidth, ancestorMarkerOffset = ancestorMarkerOffset, + parentMarkerWidth = parentMarkerWidth, ) { companion object { private val sharedMarkerPaint = TextPaint().apply { isAntiAlias = true } @@ -78,6 +80,8 @@ class OrderedListSpan( override fun getMarkerWidth(): Float = defaultMarkerWidth + markerExtraWidth + override val baselineMarkerWidth: Float get() = defaultMarkerWidth + var itemNumber: Int = 1 private set diff --git a/packages/enriched-markdown-android/ui/src/main/java/com/swmansion/enriched/markdown/spans/TaskListSpan.kt b/packages/enriched-markdown-android/ui/src/main/java/com/swmansion/enriched/markdown/spans/TaskListSpan.kt index 0c269f96f..edcc1d526 100644 --- a/packages/enriched-markdown-android/ui/src/main/java/com/swmansion/enriched/markdown/spans/TaskListSpan.kt +++ b/packages/enriched-markdown-android/ui/src/main/java/com/swmansion/enriched/markdown/spans/TaskListSpan.kt @@ -28,6 +28,7 @@ class TaskListSpan( var isChecked: Boolean, ancestorMarkerOffset: Float = 0f, override val markerExtraWidth: Float = 0f, + parentMarkerWidth: Float? = null, ) : BaseListSpan( depth = depth, context = context, @@ -42,6 +43,7 @@ class TaskListSpan( marginLeft = listStyle.marginLeft, gapWidth = listStyle.gapWidth, ancestorMarkerOffset = ancestorMarkerOffset, + parentMarkerWidth = parentMarkerWidth, ) { companion object { private val boxPaint = @@ -61,7 +63,8 @@ class TaskListSpan( } private val checkboxSize = taskStyle.checkboxSize - private val markerColumnWidth = listStyle.effectiveMarkerWidth(checkboxSize) + markerExtraWidth + private val checkboxColumnWidth = listStyle.effectiveMarkerWidth(checkboxSize) + private val markerColumnWidth = checkboxColumnWidth + markerExtraWidth private val cornerRadius = taskStyle.checkboxBorderRadius private val rect = RectF() private val insetRect = RectF() @@ -69,6 +72,8 @@ class TaskListSpan( override fun getMarkerWidth(): Float = markerColumnWidth + override val baselineMarkerWidth: Float get() = checkboxColumnWidth + override fun drawMarker( canvas: Canvas, paint: Paint, diff --git a/packages/enriched-markdown-android/ui/src/main/java/com/swmansion/enriched/markdown/spans/UnorderedListSpan.kt b/packages/enriched-markdown-android/ui/src/main/java/com/swmansion/enriched/markdown/spans/UnorderedListSpan.kt index a5df5b519..381e7dbc7 100644 --- a/packages/enriched-markdown-android/ui/src/main/java/com/swmansion/enriched/markdown/spans/UnorderedListSpan.kt +++ b/packages/enriched-markdown-android/ui/src/main/java/com/swmansion/enriched/markdown/spans/UnorderedListSpan.kt @@ -14,6 +14,7 @@ class UnorderedListSpan( context: Context, styleCache: SpanStyleCache, ancestorMarkerOffset: Float = 0f, + parentMarkerWidth: Float? = null, ) : BaseListSpan( depth = depth, context = context, @@ -28,6 +29,7 @@ class UnorderedListSpan( marginLeft = listStyle.marginLeft, gapWidth = listStyle.gapWidth, ancestorMarkerOffset = ancestorMarkerOffset, + parentMarkerWidth = parentMarkerWidth, ) { companion object { private val sharedBulletPaint = diff --git a/packages/enriched-markdown-android/ui/src/test/java/com/swmansion/enriched/markdown/ListRenderingTest.kt b/packages/enriched-markdown-android/ui/src/test/java/com/swmansion/enriched/markdown/ListRenderingTest.kt index 09a7eadb6..75bc5c97c 100644 --- a/packages/enriched-markdown-android/ui/src/test/java/com/swmansion/enriched/markdown/ListRenderingTest.kt +++ b/packages/enriched-markdown-android/ui/src/test/java/com/swmansion/enriched/markdown/ListRenderingTest.kt @@ -2,6 +2,7 @@ package com.swmansion.enriched.markdown import android.graphics.Typeface import android.text.SpannableString +import android.text.StaticLayout import android.text.TextPaint import androidx.test.ext.junit.runners.AndroidJUnit4 import com.swmansion.enriched.markdown.parser.MarkdownASTNode @@ -137,6 +138,146 @@ class ListRenderingTest { } } + @Test + fun mixedNestsStartTheirTextFromTheirOwnMarkerColumn() { + val style = mixedStyle() + for (parent in Kind.entries) { + for (child in Kind.entries.filter { it != parent }) { + for (checked in checkedStates(parent, child)) { + val markers = drawMarkers(style, list(parent, list(child, checked = checked), checked)) + assertEquals(listOf(0, 1), markers.map { it.depth }) + val expected = (24f + columnOf(style, child) + MIXED_GAP).toInt().toFloat() + assertEquals("$child under $parent", expected, markers.last().paragraphLeft, 0f) + assertMixedGaps(markers, "$child under $parent, checked=$checked") + } + } + } + } + + @Test + fun topLevelAndSameTypeNestsKeepTheirGeometry() { + val style = mixedStyle() + for (kind in Kind.entries) { + val column = columnOf(style, kind) + val markers = drawMarkers(style, list(kind, list(kind, list(kind)))) + assertEquals(listOf(0, 1, 2), markers.map { it.depth }) + markers.forEach { + assertEquals("text for $kind at depth ${it.depth}", (column + MIXED_GAP).toInt() + it.depth * 24f, it.paragraphLeft, 0f) + assertEquals(column + it.depth * 24f, it.marker.right, 0.01f) + } + } + } + + @Test + fun mixedColumnsUseAbsoluteIndentsWithoutFractionalDrift() { + val alternating = listOf(Kind.BULLET, Kind.ORDERED, Kind.BULLET, Kind.TASK) + val sameTypeRun = List(5) { Kind.BULLET } + Kind.TASK + for (margin in listOf(24f, 24.5f, 4f)) { + val style = mixedStyle(bulletSize = 6.5f, marginLeft = margin) + for (kinds in listOf(alternating, sameTypeRun)) { + val columns = kinds.map { columnOf(style, it) } + val tree = kinds.dropLast(1).foldRight(list(kinds.last())) { kind, child -> list(kind, child) } + val markers = drawMarkers(style, tree) + assertEquals(kinds.indices.toList(), markers.map { it.depth }) + markers.forEach { + val expected = (it.depth * margin + columns[it.depth] + MIXED_GAP).toInt().toFloat() + assertEquals("absolute indent at depth ${it.depth} of $kinds, margin $margin", expected, it.paragraphLeft, 0f) + assertEquals(it.paragraphLeft - MIXED_GAP, it.marker.right, 0.99f) + } + } + } + } + + @Test + fun mixedAncestorsAndFollowingSiblingsRestoreTheirOwnColumns() { + val style = mixedStyle() + for (parent in Kind.entries) { + val tree = list(parent).copy(children = Kind.entries.map { child -> item(parent, list(child, list(parent))) }) + assertMixedGaps(drawMarkers(style, tree, list(Kind.BULLET), list(Kind.ORDERED), list(Kind.TASK)), "under $parent") + } + } + + @Test + fun mixedNestsAroundWideNumberedListsKeepTheirMarkerGap() { + val style = mixedStyle() + val wide = numbered(101) + val wideWithTask = withChild(numbered(101), 1, list(Kind.TASK, list(Kind.BULLET))) + val shapes = + listOf( + withChild(wide, 0, list(Kind.BULLET)), + wideWithTask, + list(Kind.BULLET, wide), + list(Kind.TASK, wide), + withChild(numbered(1000), 999, withChild(wide, 0, list(Kind.BULLET))), + list(Kind.BULLET, withChild(wide, 1, list(Kind.TASK))), + orderedList(*numbered(101).children.toTypedArray(), item(Kind.TASK, list(Kind.BULLET))), + ) + for ((index, shape) in shapes.withIndex()) { + assertMixedGaps(drawMarkers(style, shape), "shape $index") + } + } + + @Test + fun wrappedLinesKeepTheChildsOwnColumn() { + val style = mixedStyle() + val wrapped = orderedList(listItem(paragraph(text("wrapped child text ".repeat(12))))) + val text = SpannableString(render(document(list(Kind.BULLET, wrapped)), style)) + val layout = StaticLayout.Builder.obtain(text, 0, text.length, TextPaint(), 180).build() + val span = text.getSpans(0, text.length, OrderedListSpan::class.java).single() + val firstLine = layout.getLineForOffset(text.getSpanStart(span)) + val lastLine = layout.getLineForOffset(text.getSpanEnd(span) - 1) + assertTrue(lastLine > firstLine) + val column = columnOf(style, Kind.ORDERED) + for (line in firstLine..lastLine) { + assertEquals((24f + column + MIXED_GAP).toInt(), layout.getParagraphLeft(line)) + } + val markers = MarkerCanvas.drawMarkers(layout) + assertEquals(2, markers.size) + assertEquals(24f + column, markers.last().right, 0.01f) + } + + @Test + fun rtlMixedNestsKeepTheirMarkerGapAtEveryDepth() { + fun rtl(node: MarkdownASTNode): MarkdownASTNode { + if (node.type == MarkdownASTNode.NodeType.Text) return node.copy(content = "\u05e4\u05e8\u05d9\u05d8") + return node.copy(children = node.children.map { rtl(it) }) + } + + val style = mixedStyle() + for (parent in Kind.entries) { + for (child in Kind.entries.filter { it != parent }) { + for (checked in checkedStates(parent, child)) { + val tree = list(parent, list(child, list(parent, checked = checked), checked), checked) + val text = SpannableString(render(document(rtl(tree)), style)) + val markers = MarkerCanvas.markerGeometry(text, MarkerCanvas.layout(text, style.listStyle.fontSize, rtl = true)) + assertEquals(listOf(0, 1, 2), markers.map { it.depth }) + markers.forEach { + assertEquals("RTL paragraph at depth ${it.depth}", -1, it.direction) + // Bullets are centered on the column edge, so their recorded right is that edge in both directions. + val kind = if (it.depth == 1) child else parent + val edge = if (kind == Kind.BULLET) it.marker.right else it.marker.left + assertEquals("$child under $parent, checked=$checked, depth ${it.depth}", it.paragraphRight + MIXED_GAP, edge, 0.01f) + } + } + } + } + } + + @Test + fun equalMinimumColumnsKeepTheirGeometryForMixedNests() { + val style = mixedStyle(markerMinWidth = 40f) + for (parent in Kind.entries) { + for (child in Kind.entries.filter { it != parent }) { + val markers = drawMarkers(style, list(parent, list(child, list(parent)))) + assertEquals(listOf(0, 1, 2), markers.map { it.depth }) + markers.forEach { + assertEquals("text for $child under $parent at depth ${it.depth}", 46f + it.depth * 24f, it.paragraphLeft, 0f) + assertEquals(40f + it.depth * 24f, it.marker.right, 0.01f) + } + } + } + } + /** The rows [wide] shares with [short], tasks and their children included, all sit [wide]'s widening further right. */ private fun assertEveryRowShiftsTogether( style: StyleConfig, @@ -160,6 +301,16 @@ class ListRenderingTest { } } + private fun assertMixedGaps( + markers: List, + shape: String, + ) { + assertTrue(markers.isNotEmpty()) + markers.forEach { + assertEquals("marker gap at depth ${it.depth}, $shape", it.paragraphLeft - MIXED_GAP, it.marker.right, 0.01f) + } + } + private fun assertNestedMarkerGapsUnchanged( style: StyleConfig, short: MarkdownASTNode, @@ -227,4 +378,60 @@ class ListRenderingTest { ), ) } + + private enum class Kind { ORDERED, BULLET, TASK } + + private fun list( + kind: Kind, + child: MarkdownASTNode? = null, + checked: Boolean = false, + ): MarkdownASTNode { + val item = item(kind, child, checked) + return if (kind == Kind.ORDERED) orderedList(item) else unorderedList(item) + } + + private fun item( + kind: Kind, + child: MarkdownASTNode? = null, + checked: Boolean = false, + ): MarkdownASTNode { + val children = listOfNotNull(paragraph(text("item")), child).toTypedArray() + return if (kind == Kind.TASK) taskListItem(checked, *children) else listItem(*children) + } + + private fun checkedStates( + parent: Kind, + child: Kind, + ) = if (parent == Kind.TASK || child == Kind.TASK) listOf(false, true) else listOf(false) + + /** The marker column [kind] reserves before any widening, read from a rendered top-level item. */ + private fun columnOf( + style: StyleConfig, + kind: Kind, + ): Float { + val text = render(document(list(kind)), style) + return text.getSpans(0, text.length, BaseListSpan::class.java).single().baselineMarkerWidth + } + + private fun mixedStyle( + markerMinWidth: Float = 0f, + bulletSize: Float = 6f, + marginLeft: Float = 24f, + ): StyleConfig { + val base = MarkdownRenderTestSupport.defaultStyle + return MarkdownRenderTestSupport.styleWithList( + base.listStyle.copy( + fontSize = 16f, + bulletSize = bulletSize, + markerMinWidth = markerMinWidth, + gapWidth = MIXED_GAP, + marginLeft = marginLeft, + ), + base.taskListStyle.copy(checkboxSize = 14f), + ) + } + + private companion object { + const val MIXED_GAP = 6f + } } diff --git a/packages/enriched-markdown-android/ui/src/test/java/com/swmansion/enriched/markdown/test/ListMarkerCanvas.kt b/packages/enriched-markdown-android/ui/src/test/java/com/swmansion/enriched/markdown/test/ListMarkerCanvas.kt index 7383db048..7d925cc12 100644 --- a/packages/enriched-markdown-android/ui/src/test/java/com/swmansion/enriched/markdown/test/ListMarkerCanvas.kt +++ b/packages/enriched-markdown-android/ui/src/test/java/com/swmansion/enriched/markdown/test/ListMarkerCanvas.kt @@ -19,11 +19,13 @@ data class DrawnMarker( val baseline: Float, ) -/** A drawn marker with the text edge and list depth of the paragraph it belongs to. */ +/** A drawn marker with the text edges, direction and list depth of the paragraph it belongs to. */ data class MarkerGeometry( val marker: DrawnMarker, val paragraphLeft: Float, val depth: Int, + val paragraphRight: Float, + val direction: Int, ) /** Records the list markers a layout draws instead of painting them. */ @@ -48,6 +50,18 @@ class MarkerCanvas : Canvas(Bitmap.createBitmap(LAYOUT_WIDTH, 1, Bitmap.Config.A super.drawCircle(cx, cy, radius, paint) } + override fun drawRect( + left: Float, + top: Float, + right: Float, + bottom: Float, + paint: Paint, + ) { + // Bullets from depth 2 on are squares, centered like the round ones. + markers += DrawnMarker(left, (left + right) / 2f, (top + bottom) / 2f) + super.drawRect(left, top, right, bottom, paint) + } + override fun drawRoundRect( rect: RectF, rx: Float, @@ -86,7 +100,7 @@ class MarkerCanvas : Canvas(Bitmap.createBitmap(LAYOUT_WIDTH, 1, Bitmap.Config.A fun drawMarkers(layout: Layout): List = MarkerCanvas().also(layout::draw).markers.sortedWith(compareBy({ it.baseline }, { it.left })) - /** Every marker [layout] draws, with the text edge and depth of its paragraph. */ + /** Every marker [layout] draws, with the text edges, direction and depth of its paragraph. */ fun markerGeometry( text: Spanned, layout: Layout, @@ -95,7 +109,13 @@ class MarkerCanvas : Canvas(Bitmap.createBitmap(LAYOUT_WIDTH, 1, Bitmap.Config.A val line = layout.getLineForVertical(marker.baseline.toInt()) val start = layout.getLineStart(line) val depth = text.getSpans(start, start + 1, BaseListSpan::class.java).maxOf { it.depth } - MarkerGeometry(marker, layout.getParagraphLeft(line).toFloat(), depth) + MarkerGeometry( + marker, + layout.getParagraphLeft(line).toFloat(), + depth, + layout.getParagraphRight(line).toFloat(), + layout.getParagraphDirection(line), + ) } } } diff --git a/packages/enriched-markdown-android/ui/src/test/java/com/swmansion/enriched/markdown/test/MarkdownRenderTestSupport.kt b/packages/enriched-markdown-android/ui/src/test/java/com/swmansion/enriched/markdown/test/MarkdownRenderTestSupport.kt index 06a22103f..c68628907 100644 --- a/packages/enriched-markdown-android/ui/src/test/java/com/swmansion/enriched/markdown/test/MarkdownRenderTestSupport.kt +++ b/packages/enriched-markdown-android/ui/src/test/java/com/swmansion/enriched/markdown/test/MarkdownRenderTestSupport.kt @@ -102,8 +102,11 @@ object MarkdownRenderTestSupport { ) } - /** [defaultStyle] with only its [ListStyle] replaced. */ - fun styleWithList(listStyle: ListStyle): StyleConfig = copyOfDefault(listStyle = listStyle) + /** [defaultStyle] with its [ListStyle] and, when given, its [TaskListStyle] replaced. */ + fun styleWithList( + listStyle: ListStyle, + taskListStyle: TaskListStyle? = null, + ): StyleConfig = copyOfDefault(listStyle = listStyle, taskListStyle = taskListStyle) /** [defaultStyle] with only its [TaskListStyle] replaced. */ fun styleWithTaskList(taskListStyle: TaskListStyle): StyleConfig = copyOfDefault(taskListStyle = taskListStyle) diff --git a/packages/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/renderer/BlockStyleContext.kt b/packages/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/renderer/BlockStyleContext.kt index 1ca6f3dd4..c908586bf 100644 --- a/packages/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/renderer/BlockStyleContext.kt +++ b/packages/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/renderer/BlockStyleContext.kt @@ -44,6 +44,7 @@ class BlockStyleContext { var listMarkerExtra = 0f var ancestorMarkerOffset = 0f var listItemMarkerExtra = 0f + var listItemMarkerWidth: Float? = null var taskItemCount = 0 var accumulatedIndent = 0 @@ -157,6 +158,7 @@ class BlockStyleContext { listMarkerExtra = 0f ancestorMarkerOffset = 0f listItemMarkerExtra = 0f + listItemMarkerWidth = null taskItemCount = 0 accumulatedIndent = 0 listItemStarts.clear() diff --git a/packages/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/renderer/ListItemRenderer.kt b/packages/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/renderer/ListItemRenderer.kt index f79309fad..87d1df2e3 100644 --- a/packages/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/renderer/ListItemRenderer.kt +++ b/packages/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/renderer/ListItemRenderer.kt @@ -52,6 +52,7 @@ class ListItemRenderer( drawsMarker = drawsMarker, ancestorMarkerOffset = styleContext.ancestorMarkerOffset, markerExtraWidth = styleContext.listMarkerExtra, + parentMarkerWidth = styleContext.listItemMarkerWidth, ) } else { when (listType) { @@ -63,6 +64,7 @@ class ListItemRenderer( factory.styleCache, drawsMarker, ancestorMarkerOffset = styleContext.ancestorMarkerOffset, + parentMarkerWidth = styleContext.listItemMarkerWidth, ) } @@ -75,6 +77,7 @@ class ListItemRenderer( drawsMarker, markerExtraWidth = styleContext.listMarkerExtra, ancestorMarkerOffset = styleContext.ancestorMarkerOffset, + parentMarkerWidth = styleContext.listItemMarkerWidth, ).apply { setItemNumber(styleContext.listItemNumber) } @@ -86,6 +89,8 @@ class ListItemRenderer( val previousMarkerExtra = styleContext.listItemMarkerExtra styleContext.listItemMarkerExtra = markerSpan.markerExtraWidth + val previousMarkerWidth = styleContext.listItemMarkerWidth + styleContext.listItemMarkerWidth = markerSpan.baselineMarkerWidth val prevIndent = styleContext.accumulatedIndent styleContext.accumulatedIndent = prevIndent + markerSpan.getLeadingMargin(false) try { @@ -93,6 +98,7 @@ class ListItemRenderer( } finally { styleContext.accumulatedIndent = prevIndent styleContext.listItemMarkerExtra = previousMarkerExtra + styleContext.listItemMarkerWidth = previousMarkerWidth } if (builder.length == start || builder.substring(start).isBlank()) return diff --git a/packages/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/spans/BaseListSpan.kt b/packages/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/spans/BaseListSpan.kt index 054931d8d..b17875b3f 100644 --- a/packages/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/spans/BaseListSpan.kt +++ b/packages/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/spans/BaseListSpan.kt @@ -24,6 +24,7 @@ abstract class BaseListSpan( protected val gapWidth: Float, internal val drawsMarker: Boolean = true, internal val ancestorMarkerOffset: Float = 0f, + internal val parentMarkerWidth: Float? = null, ) : MetricAffectingSpan(), LeadingMarginSpan { private var cachedText: CharSequence? = null @@ -42,17 +43,25 @@ abstract class BaseListSpan( /** How far an ordered list widened this item's column past the one short lists reserve. */ internal open val markerExtraWidth: Float = 0f + /** This item's marker column without [markerExtraWidth]; a nested item measures its indent against it. */ + internal open val baselineMarkerWidth: Float get() = getMarkerWidth() + override fun updateMeasureState(textPaint: TextPaint) = applyTextStyle(textPaint) override fun updateDrawState(textPaint: TextPaint) = applyTextStyle(textPaint) - override fun getLeadingMargin(first: Boolean): Int = - if (depth == 0) { - val effectiveGap = gapWidth.coerceAtLeast(DEFAULT_MIN_GAP) - (getMarkerWidth() + effectiveGap).toInt() - } else { - (marginLeft + markerExtraWidth).toInt() - } + override fun getLeadingMargin(first: Boolean): Int { + val effectiveGap = gapWidth.coerceAtLeast(DEFAULT_MIN_GAP) + if (depth == 0) return (getMarkerWidth() + effectiveGap).toInt() + + // Subtract truncated absolute indents, each measured from its own item's column, so neither mixed + // columns nor fractional margins accumulate rounding. The widenings are whole pixels and add unchanged. + val markerWidth = baselineMarkerWidth + val parentWidth = parentMarkerWidth ?: markerWidth + val indent = (depth * marginLeft + markerWidth + effectiveGap).toInt() + val parentIndent = ((depth - 1) * marginLeft + parentWidth + effectiveGap).toInt() + return indent - parentIndent + markerExtraWidth.toInt() + } override fun drawLeadingMargin( canvas: Canvas, diff --git a/packages/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/spans/OrderedListSpan.kt b/packages/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/spans/OrderedListSpan.kt index 9a2b19930..02b47cc7d 100644 --- a/packages/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/spans/OrderedListSpan.kt +++ b/packages/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/spans/OrderedListSpan.kt @@ -22,6 +22,7 @@ class OrderedListSpan( drawsMarker: Boolean = true, override val markerExtraWidth: Float = 0f, ancestorMarkerOffset: Float = 0f, + parentMarkerWidth: Float? = null, ) : BaseListSpan( depth = depth, context = context, @@ -37,6 +38,7 @@ class OrderedListSpan( gapWidth = listStyle.gapWidth, drawsMarker = drawsMarker, ancestorMarkerOffset = ancestorMarkerOffset, + parentMarkerWidth = parentMarkerWidth, ) { companion object { private val sharedMarkerPaint = TextPaint().apply { isAntiAlias = true } @@ -84,6 +86,8 @@ class OrderedListSpan( override fun getMarkerWidth(): Float = defaultMarkerWidth + markerExtraWidth + override val baselineMarkerWidth: Float get() = defaultMarkerWidth + var itemNumber: Int = 1 private set diff --git a/packages/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/spans/TaskListSpan.kt b/packages/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/spans/TaskListSpan.kt index fb0088718..24ca5d920 100644 --- a/packages/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/spans/TaskListSpan.kt +++ b/packages/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/spans/TaskListSpan.kt @@ -22,6 +22,7 @@ class TaskListSpan( drawsMarker: Boolean = true, ancestorMarkerOffset: Float = 0f, override val markerExtraWidth: Float = 0f, + parentMarkerWidth: Float? = null, ) : BaseListSpan( depth = depth, context = context, @@ -37,9 +38,11 @@ class TaskListSpan( gapWidth = listStyle.gapWidth, drawsMarker = drawsMarker, ancestorMarkerOffset = ancestorMarkerOffset, + parentMarkerWidth = parentMarkerWidth, ) { private val checkboxSize = taskStyle.checkboxSize - private val markerColumnWidth = listStyle.effectiveMarkerWidth(checkboxSize) + markerExtraWidth + private val checkboxColumnWidth = listStyle.effectiveMarkerWidth(checkboxSize) + private val markerColumnWidth = checkboxColumnWidth + markerExtraWidth private val cornerRadius = taskStyle.checkboxBorderRadius private val rect = RectF() private val checkPath = Path() @@ -63,6 +66,8 @@ class TaskListSpan( override fun getMarkerWidth(): Float = markerColumnWidth + override val baselineMarkerWidth: Float get() = checkboxColumnWidth + override fun drawMarker( canvas: Canvas, paint: Paint, diff --git a/packages/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/spans/UnorderedListSpan.kt b/packages/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/spans/UnorderedListSpan.kt index 2f50f46a0..a7597f88a 100644 --- a/packages/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/spans/UnorderedListSpan.kt +++ b/packages/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/spans/UnorderedListSpan.kt @@ -15,6 +15,7 @@ class UnorderedListSpan( styleCache: SpanStyleCache, drawsMarker: Boolean = true, ancestorMarkerOffset: Float = 0f, + parentMarkerWidth: Float? = null, ) : BaseListSpan( depth = depth, context = context, @@ -30,6 +31,7 @@ class UnorderedListSpan( gapWidth = listStyle.gapWidth, drawsMarker = drawsMarker, ancestorMarkerOffset = ancestorMarkerOffset, + parentMarkerWidth = parentMarkerWidth, ) { companion object { private val sharedBulletPaint = diff --git a/packages/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/utils/text/interaction/TaskListTapUtils.kt b/packages/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/utils/text/interaction/TaskListTapUtils.kt index a9e6e00d0..e70b24167 100644 --- a/packages/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/utils/text/interaction/TaskListTapUtils.kt +++ b/packages/react-native-enriched-markdown/android/src/main/java/com/swmansion/enriched/markdown/utils/text/interaction/TaskListTapUtils.kt @@ -133,6 +133,7 @@ object TaskListTapUtils { drawsMarker = old.drawsMarker, ancestorMarkerOffset = old.ancestorMarkerOffset, markerExtraWidth = old.markerExtraWidth, + parentMarkerWidth = old.parentMarkerWidth, ) // Layout draws leading margins in insertion order, and a re-added span moves to the end of it. diff --git a/packages/react-native-enriched-markdown/android/src/test/java/com/swmansion/enriched/markdown/ListRenderingTest.kt b/packages/react-native-enriched-markdown/android/src/test/java/com/swmansion/enriched/markdown/ListRenderingTest.kt index c10a5a307..9cc404ff5 100644 --- a/packages/react-native-enriched-markdown/android/src/test/java/com/swmansion/enriched/markdown/ListRenderingTest.kt +++ b/packages/react-native-enriched-markdown/android/src/test/java/com/swmansion/enriched/markdown/ListRenderingTest.kt @@ -2,6 +2,7 @@ package com.swmansion.enriched.markdown import android.graphics.Typeface import android.text.SpannableString +import android.text.StaticLayout import android.text.TextPaint import com.swmansion.enriched.markdown.parser.MarkdownASTNode import com.swmansion.enriched.markdown.spans.BaseListSpan @@ -124,18 +125,143 @@ class ListRenderingTest { } @Test - fun shortMixedNestsKeepTheirOriginalTextIndents() { - val style = styleConfig(list = mapOf("gapWidth" to 6.0), taskList = mapOf("checkboxSize" to 14.0)) - val ordered = numbered(1, 1) - val bullet = unorderedList(item()) - val task = orderedList(taskListItem(checked = false, paragraph(text("item")))) - val shapes = listOf(ordered to bullet, bullet to ordered, bullet to task, ordered to task, task to bullet) - val baseIndents = listOf(52f, 33f, 33f, 52f, 44f) + fun mixedNestsStartTheirTextFromTheirOwnMarkerColumn() { + val style = mixedStyle() + // Each child's text sits one marginLeft plus its own column and gap in: 24 + (3, 22 or 14) + 6. + val indents = mapOf(Kind.BULLET to 33f, Kind.ORDERED to 52f, Kind.TASK to 44f) + for (parent in Kind.entries) { + for (child in Kind.entries.filter { it != parent }) { + for (checked in checkedStates(parent, child)) { + val markers = drawMarkers(style, list(parent, list(child, checked = checked), checked)) + assertEquals(listOf(0, 1), markers.map { it.depth }) + assertEquals("$child under $parent", indents.getValue(child), markers.last().paragraphLeft, 0f) + assertMixedGaps(markers, "$child under $parent, checked=$checked") + } + } + } + } + + @Test + fun topLevelAndSameTypeNestsKeepTheirGeometry() { + val style = mixedStyle() + for (kind in Kind.entries) { + val column = columnOf(style, kind) + val markers = drawMarkers(style, list(kind, list(kind, list(kind)))) + assertEquals(listOf(0, 1, 2), markers.map { it.depth }) + markers.forEach { + assertEquals("text for $kind at depth ${it.depth}", (column + MIXED_GAP).toInt() + it.depth * 24f, it.paragraphLeft, 0f) + assertEquals(column + it.depth * 24f, it.marker.right, 0.01f) + } + } + } + + @Test + fun mixedColumnsUseAbsoluteIndentsWithoutFractionalDrift() { + val alternating = listOf(Kind.BULLET, Kind.ORDERED, Kind.BULLET, Kind.TASK) + val sameTypeRun = List(5) { Kind.BULLET } + Kind.TASK + for (margin in listOf(24.0, 24.5, 4.0)) { + val style = mixedStyle(bulletSize = 6.5, marginLeft = margin) + for (kinds in listOf(alternating, sameTypeRun)) { + val columns = kinds.map { columnOf(style, it) } + val tree = kinds.dropLast(1).foldRight(list(kinds.last())) { kind, child -> list(kind, child) } + val markers = drawMarkers(style, tree) + assertEquals(kinds.indices.toList(), markers.map { it.depth }) + markers.forEach { + val expected = (it.depth * margin + columns[it.depth] + MIXED_GAP).toInt().toFloat() + assertEquals("absolute indent at depth ${it.depth} of $kinds, margin $margin", expected, it.paragraphLeft, 0f) + assertEquals(it.paragraphLeft - MIXED_GAP, it.marker.right, 0.99f) + } + } + } + } + + @Test + fun mixedAncestorsAndFollowingSiblingsRestoreTheirOwnColumns() { + val style = mixedStyle() + for (parent in Kind.entries) { + val tree = list(parent).copy(children = Kind.entries.map { child -> item(parent, list(child, list(parent))) }) + assertMixedGaps(drawMarkers(style, tree, list(Kind.BULLET), list(Kind.ORDERED), list(Kind.TASK)), "under $parent") + } + } + + @Test + fun mixedNestsAroundWideNumberedListsKeepTheirMarkerGap() { + val style = mixedStyle() + val wide = numbered(12345, 2) + val wideWithTask = orderedList(item(), item(Kind.TASK, list(Kind.BULLET)), start = 998) + val shapes = + listOf( + withChild(wide, 0, list(Kind.BULLET)), + withChild(wide, 1, list(Kind.TASK, list(Kind.BULLET))), + list(Kind.BULLET, wide), + list(Kind.TASK, wide), + withChild(numbered(998, 4), 3, withChild(wide, 0, list(Kind.BULLET))), + list(Kind.BULLET, withChild(wide, 1, list(Kind.TASK))), + withChild(wideWithTask, 0, list(Kind.BULLET)), + ) for ((index, shape) in shapes.withIndex()) { - val (parent, child) = shape - val nested = drawMarkers(style, withChild(parent, 0, child)).single { it.depth == 1 } - assertEquals("base mixed indent for shape $index", baseIndents[index], nested.paragraphLeft, 0.01f) - assertTrue(nested.marker.left >= 0f) + assertMixedGaps(drawMarkers(style, shape), "shape $index") + } + } + + @Test + fun wrappedLinesKeepTheChildsOwnColumn() { + val style = mixedStyle() + val wrapped = orderedList(listItem(paragraph(text("wrapped child text ".repeat(12))))) + val text = SpannableString(render(style, list(Kind.BULLET, wrapped))) + val layout = StaticLayout.Builder.obtain(text, 0, text.length, TextPaint(), 180).build() + val span = text.getSpans(0, text.length, OrderedListSpan::class.java).single() + val firstLine = layout.getLineForOffset(text.getSpanStart(span)) + val lastLine = layout.getLineForOffset(text.getSpanEnd(span) - 1) + assertTrue(lastLine > firstLine) + val column = columnOf(style, Kind.ORDERED) + for (line in firstLine..lastLine) { + assertEquals((24f + column + MIXED_GAP).toInt(), layout.getParagraphLeft(line)) + } + val markers = MarkerCanvas.drawMarkers(layout) + assertEquals(2, markers.size) + assertEquals(24f + column, markers.last().right, 0.01f) + } + + @Test + fun rtlMixedNestsKeepTheirMarkerGapAtEveryDepth() { + fun rtl(node: MarkdownASTNode): MarkdownASTNode { + if (node.type == MarkdownASTNode.NodeType.Text) return node.copy(content = "\u05e4\u05e8\u05d9\u05d8") + return node.copy(children = node.children.map { rtl(it) }) + } + + val style = mixedStyle() + for (parent in Kind.entries) { + for (child in Kind.entries.filter { it != parent }) { + for (checked in checkedStates(parent, child)) { + val tree = list(parent, list(child, list(parent, checked = checked), checked), checked) + val text = SpannableString(render(style, rtl(tree))) + val markers = MarkerCanvas.markerGeometry(text, MarkerCanvas.layout(text, style.listStyle.fontSize, rtl = true)) + assertEquals(listOf(0, 1, 2), markers.map { it.depth }) + markers.forEach { + assertEquals("RTL paragraph at depth ${it.depth}", -1, it.direction) + // Bullets are centered on the column edge, so their recorded right is that edge in both directions. + val kind = if (it.depth == 1) child else parent + val edge = if (kind == Kind.BULLET) it.marker.right else it.marker.left + assertEquals("$child under $parent, checked=$checked, depth ${it.depth}", it.paragraphRight + MIXED_GAP, edge, 0.01f) + } + } + } + } + } + + @Test + fun equalMinimumColumnsKeepTheirGeometryForMixedNests() { + val style = mixedStyle(markerMinWidth = 40.0) + for (parent in Kind.entries) { + for (child in Kind.entries.filter { it != parent }) { + val markers = drawMarkers(style, list(parent, list(child, list(parent)))) + assertEquals(listOf(0, 1, 2), markers.map { it.depth }) + markers.forEach { + assertEquals("text for $child under $parent at depth ${it.depth}", 46f + it.depth * 24f, it.paragraphLeft, 0f) + assertEquals(40f + it.depth * 24f, it.marker.right, 0.01f) + } + } } } @@ -169,6 +295,16 @@ class ListRenderingTest { } } + private fun assertMixedGaps( + markers: List, + shape: String, + ) { + assertTrue(markers.isNotEmpty()) + markers.forEach { + assertEquals("marker gap at depth ${it.depth}, $shape", it.paragraphLeft - MIXED_GAP, it.marker.right, 0.01f) + } + } + private fun assertDrawnMarkerPositions( style: StyleConfig, vararg lists: MarkdownASTNode, @@ -267,4 +403,58 @@ class ListRenderingTest { private fun listStyle(minWidth: Double = 0.0): StyleConfig = styleConfig(list = mapOf("fontFamily" to "monospace", "markerMinWidth" to minWidth)) + + private enum class Kind { ORDERED, BULLET, TASK } + + private fun list( + kind: Kind, + child: MarkdownASTNode? = null, + checked: Boolean = false, + ): MarkdownASTNode { + val item = item(kind, child, checked) + return if (kind == Kind.ORDERED) orderedList(item) else unorderedList(item) + } + + private fun item( + kind: Kind, + child: MarkdownASTNode? = null, + checked: Boolean = false, + ): MarkdownASTNode { + val children = listOfNotNull(paragraph(text("item")), child).toTypedArray() + return if (kind == Kind.TASK) taskListItem(checked, *children) else listItem(*children) + } + + private fun checkedStates( + parent: Kind, + child: Kind, + ) = if (parent == Kind.TASK || child == Kind.TASK) listOf(false, true) else listOf(false) + + /** The marker column [kind] reserves before any widening, read from a rendered top-level item. */ + private fun columnOf( + style: StyleConfig, + kind: Kind, + ): Float { + val text = render(style, list(kind)) + return text.getSpans(0, text.length, BaseListSpan::class.java).single().baselineMarkerWidth + } + + private fun mixedStyle( + markerMinWidth: Double = 0.0, + bulletSize: Double = 6.0, + marginLeft: Double = 24.0, + ): StyleConfig = + styleConfig( + list = + mapOf( + "bulletSize" to bulletSize, + "markerMinWidth" to markerMinWidth, + "gapWidth" to MIXED_GAP.toDouble(), + "marginLeft" to marginLeft, + ), + taskList = mapOf("checkboxSize" to 14.0), + ) + + private companion object { + const val MIXED_GAP = 6f + } } diff --git a/packages/react-native-enriched-markdown/android/src/test/java/com/swmansion/enriched/markdown/TaskListInteractionTest.kt b/packages/react-native-enriched-markdown/android/src/test/java/com/swmansion/enriched/markdown/TaskListInteractionTest.kt index 64a70db33..4ade5adce 100644 --- a/packages/react-native-enriched-markdown/android/src/test/java/com/swmansion/enriched/markdown/TaskListInteractionTest.kt +++ b/packages/react-native-enriched-markdown/android/src/test/java/com/swmansion/enriched/markdown/TaskListInteractionTest.kt @@ -38,21 +38,38 @@ class TaskListInteractionTest { @Test fun togglingATaskUnderAWideParentKeepsEveryMarginAndMarkerPosition() { - assertTaskToggleKeepsGeometry(opensWithSublist = false) + assertTaskToggleKeepsGeometry(wideParentTree(opensWithSublist = false), anchors = 0, markers = 4) } @Test fun togglingAnAnchoredTaskUnderAWideParentKeepsEveryMarginAndMarkerPosition() { - assertTaskToggleKeepsGeometry(opensWithSublist = true) + assertTaskToggleKeepsGeometry(wideParentTree(opensWithSublist = true), anchors = 1, markers = 4) + } + + @Test + fun togglingATaskInAMixedNestKeepsEveryMarginAndMarkerPosition() { + // The task's indent depends on its parent's marker column, so the toggled copy has to keep it. + val tasks = unorderedList(taskListItem(checked = false, paragraph(text("item")), numbered(1))) + val parent = listItem(paragraph(text("item")), tasks) + for (tree in listOf(unorderedList(parent), orderedList(parent))) { + assertTaskToggleKeepsGeometry(tree, anchors = 0, markers = 3) + } + } + + private fun wideParentTree(opensWithSublist: Boolean): MarkdownASTNode { + val taskChildren = if (opensWithSublist) arrayOf(numbered(1)) else arrayOf(paragraph(text("item")), numbered(1)) + val task = taskListItem(checked = false, *taskChildren) + return orderedList(listItem(paragraph(text("item")), unorderedList(task)), item(), start = 100) } // Layout draws leading margins in span insertion order, so a toggle that re-adds only the // task's span would move its checkbox by its ancestors' margins. - private fun assertTaskToggleKeepsGeometry(opensWithSublist: Boolean) { + private fun assertTaskToggleKeepsGeometry( + tree: MarkdownASTNode, + anchors: Int, + markers: Int, + ) { val style = styleConfig(list = mapOf("fontFamily" to "monospace")) - val taskChildren = if (opensWithSublist) arrayOf(numbered(1)) else arrayOf(paragraph(text("item")), numbered(1)) - val task = taskListItem(checked = false, *taskChildren) - val tree = orderedList(listItem(paragraph(text("item")), unorderedList(task)), item(), start = 100) val textView = object : AccessibleMarkdownTextView(context) {}.apply { layoutParams = ViewGroup.LayoutParams(MarkerCanvas.LAYOUT_WIDTH, ViewGroup.LayoutParams.WRAP_CONTENT) @@ -61,10 +78,10 @@ class TaskListInteractionTest { textView.setText(render(style, tree), TextView.BufferType.SPANNABLE) val initialText = textView.text as Spanned val taskIndex = initialText.getSpans(0, initialText.length, TaskListSpan::class.java).single().taskIndex - assertEquals(if (opensWithSublist) 1 else 0, initialText.getSpans(0, initialText.length, ListMarkerAnchorSpan::class.java).size) + assertEquals(anchors, initialText.getSpans(0, initialText.length, ListMarkerAnchorSpan::class.java).size) val initialMargins = listMargins(initialText) val initialMarkers = drawTextViewMarkers(textView) - assertEquals(4, initialMarkers.size) + assertEquals(markers, initialMarkers.size) for (checked in listOf(true, false)) { assertTrue(TaskListTapUtils.updateTaskListItemCheckedState(textView, taskIndex, checked, style)) diff --git a/packages/react-native-enriched-markdown/android/src/test/java/com/swmansion/enriched/markdown/test/ListMarkerCanvas.kt b/packages/react-native-enriched-markdown/android/src/test/java/com/swmansion/enriched/markdown/test/ListMarkerCanvas.kt index 7383db048..7d925cc12 100644 --- a/packages/react-native-enriched-markdown/android/src/test/java/com/swmansion/enriched/markdown/test/ListMarkerCanvas.kt +++ b/packages/react-native-enriched-markdown/android/src/test/java/com/swmansion/enriched/markdown/test/ListMarkerCanvas.kt @@ -19,11 +19,13 @@ data class DrawnMarker( val baseline: Float, ) -/** A drawn marker with the text edge and list depth of the paragraph it belongs to. */ +/** A drawn marker with the text edges, direction and list depth of the paragraph it belongs to. */ data class MarkerGeometry( val marker: DrawnMarker, val paragraphLeft: Float, val depth: Int, + val paragraphRight: Float, + val direction: Int, ) /** Records the list markers a layout draws instead of painting them. */ @@ -48,6 +50,18 @@ class MarkerCanvas : Canvas(Bitmap.createBitmap(LAYOUT_WIDTH, 1, Bitmap.Config.A super.drawCircle(cx, cy, radius, paint) } + override fun drawRect( + left: Float, + top: Float, + right: Float, + bottom: Float, + paint: Paint, + ) { + // Bullets from depth 2 on are squares, centered like the round ones. + markers += DrawnMarker(left, (left + right) / 2f, (top + bottom) / 2f) + super.drawRect(left, top, right, bottom, paint) + } + override fun drawRoundRect( rect: RectF, rx: Float, @@ -86,7 +100,7 @@ class MarkerCanvas : Canvas(Bitmap.createBitmap(LAYOUT_WIDTH, 1, Bitmap.Config.A fun drawMarkers(layout: Layout): List = MarkerCanvas().also(layout::draw).markers.sortedWith(compareBy({ it.baseline }, { it.left })) - /** Every marker [layout] draws, with the text edge and depth of its paragraph. */ + /** Every marker [layout] draws, with the text edges, direction and depth of its paragraph. */ fun markerGeometry( text: Spanned, layout: Layout, @@ -95,7 +109,13 @@ class MarkerCanvas : Canvas(Bitmap.createBitmap(LAYOUT_WIDTH, 1, Bitmap.Config.A val line = layout.getLineForVertical(marker.baseline.toInt()) val start = layout.getLineStart(line) val depth = text.getSpans(start, start + 1, BaseListSpan::class.java).maxOf { it.depth } - MarkerGeometry(marker, layout.getParagraphLeft(line).toFloat(), depth) + MarkerGeometry( + marker, + layout.getParagraphLeft(line).toFloat(), + depth, + layout.getParagraphRight(line).toFloat(), + layout.getParagraphDirection(line), + ) } } }