Skip to content

Your phone, on your command. Gotcha is world's first fully on-device AI copilot for Android that turns natural language into real device actions — safely.

Scrollable markdown tables for chat and viewer (#156)

Rishabh Bajpaif70b756f6047
diff --git a/app/src/main/java/com/gotcha/ui/CodeBox.kt b/app/src/main/java/com/gotcha/ui/CodeBox.kt
index 8b6289a..d770808 100644
--- a/app/src/main/java/com/gotcha/ui/CodeBox.kt
+++ b/app/src/main/java/com/gotcha/ui/CodeBox.kt
@@ -40,10 +40,17 @@ import com.halilibo.richtext.ui.material3.Material3RichText
@Composable
fun RichMarkdown(markdown: String, modifier: Modifier = Modifier, style: RichTextStyle? = null) {
Column(modifier = modifier, verticalArrangement = Arrangement.spacedBy(8.dp)) {
- splitFencedBlocks(markdown).forEach { segment ->
+ splitFencedBlocks(markdown).flatMap { segment ->
+ if (segment is MarkdownSegment.Prose) splitTables(segment.markdown) else listOf(segment)
+ }.forEach { segment ->
when (segment) {
is MarkdownSegment.Prose -> Material3RichText(style = style) { Markdown(segment.markdown) }
is MarkdownSegment.Code -> CodeBox(code = segment.code, language = segment.language)
+ is MarkdownSegment.Table -> MarkdownTable(
+ headers = segment.headers,
+ aligns = segment.aligns,
+ rows = segment.rows
+ )
}
}
}
diff --git a/app/src/main/java/com/gotcha/ui/MarkdownSegment.kt b/app/src/main/java/com/gotcha/ui/MarkdownSegment.kt
index a73cc79..7740184 100644
--- a/app/src/main/java/com/gotcha/ui/MarkdownSegment.kt
+++ b/app/src/main/java/com/gotcha/ui/MarkdownSegment.kt
@@ -1,12 +1,18 @@
package com.gotcha.ui
/**
- * A piece of a Markdown message: prose for the Markdown renderer, or a fenced
- * code block drawn as a [CodeBox] with its own copy button (issue #109).
+ * A piece of a Markdown message: prose for the Markdown renderer, a fenced
+ * code block drawn as a [CodeBox] with its own copy button (issue #109), or a
+ * table drawn as a sideways-scrollable [MarkdownTable].
*/
sealed interface MarkdownSegment {
data class Prose(val markdown: String) : MarkdownSegment
data class Code(val code: String, val language: String?) : MarkdownSegment
+ data class Table(
+ val headers: List<String>,
+ val aligns: List<TableAlign>,
+ val rows: List<List<String>>
+ ) : MarkdownSegment
}
private val OPENING_FENCE = Regex("^( {0,3})(`{3,}|~{3,})\\s*([^\\s`]*)[^`]*$")
diff --git a/app/src/main/java/com/gotcha/ui/MarkdownTable.kt b/app/src/main/java/com/gotcha/ui/MarkdownTable.kt
new file mode 100644
index 0000000..060ec84
--- /dev/null
+++ b/app/src/main/java/com/gotcha/ui/MarkdownTable.kt
@@ -0,0 +1,184 @@
+@file:Suppress("MatchingDeclarationName")
+
+package com.gotcha.ui
+
+import androidx.compose.foundation.horizontalScroll
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.widthIn
+import androidx.compose.foundation.rememberScrollState
+import androidx.compose.material3.HorizontalDivider
+import androidx.compose.material3.MaterialTheme
+import androidx.compose.material3.Surface
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.text.font.FontWeight
+import androidx.compose.ui.text.style.TextAlign
+import androidx.compose.ui.unit.dp
+
+/** Column alignment parsed from a GFM delimiter row (`:---`, `:--:`, `---:`). */
+enum class TableAlign { LEFT, CENTER, RIGHT }
+
+/**
+ * A GFM table: pipe header, delimiter row, pipe body rows. The bundled
+ * Markdown renderer sizes every column equally, which squeezes wide tables
+ * into unreadable slivers on a phone, so tables are drawn here instead in a
+ * sideways-scrollable grid with capped column widths.
+ */
+fun splitTables(prose: String): List<MarkdownSegment> {
+ val segments = mutableListOf<MarkdownSegment>()
+ val text = StringBuilder()
+ val lines = prose.lines()
+ var i = 0
+ fun flush() {
+ val t = text.toString().trim('\n')
+ if (t.isNotBlank()) segments += MarkdownSegment.Prose(t)
+ text.setLength(0)
+ }
+ while (i < lines.size) {
+ val header = tableLine(lines.getOrNull(i))
+ val delimiter = tableLine(lines.getOrNull(i + 1))
+ if (header != null && delimiter != null && header.contains('|') && isDelimiterRow(delimiter) &&
+ splitRow(header).size == splitRow(delimiter).size
+ ) {
+ val headers = splitRow(header)
+ val aligns = splitRow(delimiter).map(::alignOf)
+ val width = headers.size
+ val rows = mutableListOf<List<String>>()
+ var j = i + 2
+ while (j < lines.size) {
+ val row = tableLine(lines[j]) ?: break
+ if (!row.contains('|') || isDelimiterRow(row)) break
+ rows += splitRow(row).fitTo(width, "")
+ j++
+ }
+ flush()
+ segments += MarkdownSegment.Table(headers, aligns.fitTo(width, TableAlign.LEFT), rows)
+ i = j
+ } else {
+ text.appendLine(lines.getOrNull(i).orEmpty())
+ i++
+ }
+ }
+ flush()
+ return segments
+}
+
+/** Table-eligible line: up to 3 leading spaces (GFM allows 3). deeper indents are code, `>` quotes stay with the bundled renderer. */
+private fun tableLine(line: String?): String? {
+ if (line == null) return null
+ val stripped = line.trimStart()
+ if (stripped.startsWith('>')) return null
+ val indent = line.length - stripped.length
+ if (line.startsWith('\t') || indent >= 4) return null
+ return stripped
+}
+
+/** True when [line] is a GFM delimiter row: pipes of dashes with optional edge colons. */
+private fun isDelimiterRow(line: String): Boolean {
+ val cells = splitRow(line)
+ if (cells.isEmpty()) return false
+ return cells.all { it.matches(Regex(":?-{1,}:?")) }
+}
+
+/** Splits one table row on unescaped pipes; trims cells and drops the outer pair. */
+private fun splitRow(line: String): List<String> {
+ val cells = mutableListOf<String>()
+ val cur = StringBuilder()
+ var escaped = false
+ line.forEach { ch ->
+ when {
+ escaped -> {
+ cur.append(ch)
+ escaped = false
+ }
+ ch == '\\' -> escaped = true
+ ch == '|' -> {
+ cells += cur.toString()
+ cur.clear()
+ }
+ else -> cur.append(ch)
+ }
+ }
+ cells += cur.toString()
+ val trimmed = cells.map { it.trim() }
+ val inner = { list: List<String> ->
+ var result = list
+ if (result.isNotEmpty() && result.first().isEmpty()) result = result.drop(1)
+ if (result.isNotEmpty() && result.last().isEmpty()) result = result.dropLast(1)
+ result
+ }
+ return inner(trimmed)
+}
+
+private fun alignOf(cell: String): TableAlign = when {
+ cell.startsWith(':') && cell.endsWith(':') -> TableAlign.CENTER
+ cell.endsWith(':') -> TableAlign.RIGHT
+ else -> TableAlign.LEFT
+}
+
+private fun <T> List<T>.fitTo(width: Int, pad: T): List<T> {
+ val taken = take(width)
+ return if (taken.size >= width) taken else taken + List(width - taken.size) { pad }
+}
+
+private fun TableAlign.toTextAlign(): TextAlign = when (this) {
+ TableAlign.LEFT -> TextAlign.Start
+ TableAlign.CENTER -> TextAlign.Center
+ TableAlign.RIGHT -> TextAlign.End
+}
+
+/**
+ * A sideways-scrollable table: columns size to their content between a fixed
+ * min and max, so narrow columns stay compact and wide ones wrap instead of
+ * squeezing their neighbours.
+ */
+@Composable
+fun MarkdownTable(
+ headers: List<String>,
+ aligns: List<TableAlign>,
+ rows: List<List<String>>,
+ modifier: Modifier = Modifier
+) {
+ Surface(
+ modifier = modifier.fillMaxWidth(),
+ shape = MaterialTheme.shapes.small,
+ tonalElevation = 1.dp
+ ) {
+ Row(modifier = Modifier.horizontalScroll(rememberScrollState())) {
+ headers.forEachIndexed { index, header ->
+ val align = aligns.getOrElse(index) { TableAlign.LEFT }.toTextAlign()
+ val cells = rows.map { it.getOrElse(index) { "" } }
+ Column(
+ modifier = Modifier
+ .widthIn(min = 84.dp, max = 240.dp)
+ .padding(horizontal = 10.dp, vertical = 6.dp)
+ ) {
+ // No fillMaxWidth: in the scrolling row each column sizes
+ // to its content (within the caps) instead of every
+ // column stretching to the 240dp maximum.
+ Text(
+ text = header,
+ style = MaterialTheme.typography.bodySmall,
+ fontWeight = FontWeight.Bold,
+ textAlign = align
+ )
+ HorizontalDivider(modifier = Modifier.padding(vertical = 4.dp))
+ cells.forEachIndexed { rowIndex, cell ->
+ Text(
+ text = cell,
+ style = MaterialTheme.typography.bodySmall,
+ textAlign = align
+ )
+ if (rowIndex < cells.size - 1) {
+ HorizontalDivider(modifier = Modifier.padding(vertical = 4.dp))
+ }
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/app/src/test/java/com/gotcha/ui/MarkdownTableTest.kt b/app/src/test/java/com/gotcha/ui/MarkdownTableTest.kt
new file mode 100644
index 0000000..a62ffd9
--- /dev/null
+++ b/app/src/test/java/com/gotcha/ui/MarkdownTableTest.kt
@@ -0,0 +1,82 @@
+package com.gotcha.ui
+
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+/** [splitTables]: GFM table parsing for the scrollable table renderer. */
+class MarkdownTableTest {
+
+ private val table = listOf(
+ "| Time | Item | Est. | Done when |",
+ "|------|------|------|-----------|",
+ "| 08:00 | Standup | ~15m | Blockers shared |",
+ "| 09:00 | Deep work | ~2h | Draft done |",
+ ""
+ ).joinToString("\n")
+
+ @Test
+ fun `a table splits out of prose`() {
+ val segments = splitTables("Intro.\n\n$table\nOutro.")
+ assertEquals(3, segments.size)
+ assertTrue(segments[0] is MarkdownSegment.Prose)
+ val parsed = segments[1] as MarkdownSegment.Table
+ assertEquals(listOf("Time", "Item", "Est.", "Done when"), parsed.headers)
+ assertEquals(2, parsed.rows.size)
+ assertEquals(listOf("08:00", "Standup", "~15m", "Blockers shared"), parsed.rows[0])
+ assertTrue(segments[2] is MarkdownSegment.Prose)
+ }
+
+ @Test
+ fun `alignments parse from the delimiter row`() {
+ val segments = splitTables("| A | B | C |\n|:---|:--:|---:|\n| x | y | z |")
+ val parsed = segments.single() as MarkdownSegment.Table
+ assertEquals(listOf(TableAlign.LEFT, TableAlign.CENTER, TableAlign.RIGHT), parsed.aligns)
+ }
+
+ @Test
+ fun `escaped pipes stay inside cells`() {
+ val segments = splitTables("| A |\n|---|\n| x \\| y |")
+ val parsed = segments.single() as MarkdownSegment.Table
+ assertEquals(listOf(listOf("x | y")), parsed.rows)
+ }
+
+ @Test
+ fun `ragged rows fit the header width`() {
+ val segments = splitTables("| A | B |\n|---|---|\n| only |\n| one | two | three |")
+ val parsed = segments.single() as MarkdownSegment.Table
+ assertEquals(listOf(listOf("only", "")), parsed.rows.take(1))
+ assertEquals(listOf("one", "two"), parsed.rows[1])
+ }
+
+ @Test
+ fun `plain pipe text without a delimiter stays prose`() {
+ val text = "Fish \\| chips\n\nNo table here."
+ val segments = splitTables(text)
+ assertEquals(1, segments.size)
+ assertTrue(segments.single() is MarkdownSegment.Prose)
+ }
+
+ @Test
+ fun `tables without outer pipes parse`() {
+ val segments = splitTables("Time | Item\n--- | ---\n08:00 | Standup")
+ val parsed = segments.single() as MarkdownSegment.Table
+ assertEquals(listOf("Time", "Item"), parsed.headers)
+ assertEquals(listOf(listOf("08:00", "Standup")), parsed.rows)
+ }
+
+ @Test
+ fun `a header without a matching delimiter stays prose`() {
+ val segments = splitTables("Fish | chips\n---\nNot a table.")
+ assertEquals(1, segments.size)
+ assertTrue(segments.single() is MarkdownSegment.Prose)
+ }
+
+ @Test
+ fun `indented code and quotes stay with the bundled renderer`() {
+ val code = " | A |\n |---|\n | x |"
+ assertTrue(splitTables(code).single() is MarkdownSegment.Prose)
+ val quote = "> | A |\n> |---|\n> | x |"
+ assertTrue(splitTables(quote).single() is MarkdownSegment.Prose)
+ }
+}