ravenous_typst/setup/generation/csv-table.typ

137 lines
3.2 KiB
Plaintext

// Generic delimited-data → Typst table renderer.
//
// `evaluate` accepts one mode for every cell:
//
// false
// "markup"
// "code"
//
// It can also be an array with one mode per cell, in row-major order:
//
// (false, false, "markup", "code", false, ..)
#import "../core/macros.typ" as macros
#import "../theme/tables.typ" as set_tables
#let csv-table(
source,
delimiter: auto,
header: true,
columns: auto,
// false, "markup", "code", or one such value per cell.
evaluate: false,
// The same definitions are available to every evaluated cell.
scope: macros.bigscope,
// Theme function to apply afterwards
theme-function: none,
// Theme name to apply instead of a function, mutually exclusive with theme-function
theme-name: none,
text-size: none,
inset-y: none,
header-inset-y: none,
) = {
if theme-function != none and theme-name != none {
panic(
"Both a theme name and theming function cannot be supplied at the same time",
)
}
let resolved-delimiter = if delimiter == auto {
if source.ends-with(".tsv") { "\t" } else { "," }
} else { delimiter }
let data = csv(source, delimiter: resolved-delimiter)
if data.len() == 0 {
return []
}
let column-count = data.first().len()
let table-columns = if columns == auto { column-count } else { columns }
let cell-count = data.flatten().len()
if type(evaluate) == array and evaluate.len() != cell-count {
panic(
"evaluate has "
+ str(evaluate.len())
+ " entries, but the CSV has "
+ str(cell-count)
+ " cells",
)
}
let render(value, index) = {
let mode = if type(evaluate) == array {
evaluate.at(index)
} else {
evaluate
}
if mode == false {
value
} else if mode == "markup" or mode == "code" {
if value == "" {
[]
} else {
eval(value, mode: mode, scope: scope)
}
} else {
panic("Evaluate entries must be false, \"markup\", or \"code\"")
}
}
let rows = ()
let cell-index = 0
for row in data {
let rendered-row = ()
for value in row {
rendered-row.push(render(value, cell-index))
cell-index += 1
}
rows.push(rendered-row)
}
let table = if header {
table(
columns: table-columns,
table.header(..rows.first()),
..rows.slice(1).flatten(),
)
} else {
table(
columns: table-columns,
..rows.flatten(),
)
}
if theme-function != none {
theme-function[#table]
} else if theme-name != none {
set_tables.set-table-style(
table,
table-theme: theme-name,
text-size: text-size,
inset-y: inset-y,
header-inset-y: header-inset-y,
)
} else {
[#table]
}
}
// Craft tables share a denser geometry without changing generic CSV tables.
#import "../craft_config.typ": craft-config
#let craft-table(
source,
scope: macros.bigscope,
text-size: craft-config.table.text-size,
inset-y: craft-config.table.inset-y,
header-inset-y: craft-config.table.header-inset-y,
..args,
) = csv-table(
source,
scope: scope + (ddlvl: macros.ddshort),
text-size: text-size,
inset-y: inset-y,
header-inset-y: header-inset-y,
..args,
)