ajalt / mordant

Multiplatform text styling for Kotlin command-line applications
https://ajalt.github.io/mordant/
Apache License 2.0
935 stars 33 forks source link

Customizable table rendering #145

Open mikaelstaldal opened 7 months ago

mikaelstaldal commented 7 months ago

Related to #140, I experimented with JSON rendering of tables. I managed to do it like this (proof of concept, not production ready):

fun jsonTable(init: TableBuilder.() -> Unit): String {
    val tableBuilder = TableBuilderInstance().apply(init)
    return buildString {
        append("[\n")
        for (row in tableBuilder.bodySection.rows.withIndex()) {
            append('{')
            for (cell in row.value.cells.withIndex()) {
                append('"')
                append((tableBuilder.headerSection.rows[0].cells[cell.index].content as CellContent.TextContent).text)
                append('"')
                append(':')
                append('"')
                append((cell.value.content as CellContent.TextContent).text) // TODO escape value
                append('"')
                if (cell.index < row.value.cells.size - 1) append(',')
            }
            append('}')
            if (row.index < tableBuilder.bodySection.rows.size - 1) append(',')
            append('\n')
        }
        append("]\n")
    }
}

The problem is that it requires access to some code which is internal in Mordant, in particular TableBuilderInstance.

Maybe JSON rendering should not be part of Mordant, this code only works for simple tables and it might be hard to make it fully generic. But it would be nice to expose those classes, or some kind of similar API, to make it possible to implement this yourself like this.