diff --git a/.github/workflows/R-CMD-check.yaml b/.github/workflows/R-CMD-check.yaml index 562fe0f..cd24f2f 100644 --- a/.github/workflows/R-CMD-check.yaml +++ b/.github/workflows/R-CMD-check.yaml @@ -34,6 +34,10 @@ jobs: - uses: r-lib/actions/setup-pandoc@v2 + # The Quarto render tests compile the Typst backend's tables; without + # the quarto command-line tool they are skipped. + - uses: quarto-dev/quarto-actions/setup@v2 + - uses: r-lib/actions/setup-r@v2 with: r-version: ${{ matrix.config.r }} diff --git a/NEWS.md b/NEWS.md index 86af132..86c0c71 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,5 +1,14 @@ # tabtibble 0.0.2.9000 +* The `"typst"` backend frames each table's data with a rule under the + column header (repeated with the header on every page) and one at the end + of the table. Attributes on a table adjust it further: + `tabtibble_header_cols` (the number of leading columns that label their + rows, separated from the rest by a vertical rule), `tabtibble_widths` + (Typst column widths, such as `"auto"`, `"3cm"`, or `"2fr"`), + `tabtibble_topic_labels` (`TRUE` shows each topic header as + ": "), and `tabtibble_typst_raw` (columns whose cells + are Typst markup, such as `$r^2$`, written without escaping). * `knit_print()` now detects whether it is rendering under Quarto or plain R Markdown/knitr (`knitr::opts_knit$get("quarto.version")`, falling back to the `QUARTO_PROJECT_ROOT`/`QUARTO_DOCUMENT_PATH` environment diff --git a/R/typst_topic_table.R b/R/typst_topic_table.R index 23b830c..45b39cf 100644 --- a/R/typst_topic_table.R +++ b/R/typst_topic_table.R @@ -60,20 +60,148 @@ resolve_typst_align <- function(x, align = NULL) { if (bold) sprintf("[*%s*]", label) else sprintf("[%s]", label) } +#' Resolve per-column Typst column widths +#' +#' @param x A data.frame (the data columns only). +#' @param widths `NULL` for Typst's automatic widths, or the +#' `"tabtibble_widths"` attribute: Typst track sizes (`"auto"`, a length +#' such as `"3cm"`, `".5in"`, or `"40%"`, or a fraction such as `"2fr"`), +#' either all named by column (each column once, no other names) or none +#' named, in column order. +#' @returns The Typst `columns:` value: the number of columns when `widths` +#' is `NULL`, otherwise a Typst array of track sizes. +#' @keywords internal +resolve_typst_widths <- function(x, widths = NULL) { + cols <- names(x) + if (is.null(widths)) { + return(as.character(length(cols))) + } + if (!is.character(widths)) { + stop("`tabtibble_widths` must be a character vector of Typst track sizes.", call. = FALSE) + } + width_names <- names(widths) + if (!is.null(width_names)) { + if (any(is.na(width_names) | !nzchar(width_names))) { + stop("`tabtibble_widths` must name every width or none of them.", call. = FALSE) + } + dup <- unique(width_names[duplicated(width_names)]) + if (length(dup) > 0) { + stop(sprintf("`tabtibble_widths` names column(s) more than once: %s", paste(sQuote(dup), collapse = ", ")), call. = FALSE) + } + unknown <- setdiff(width_names, cols) + if (length(unknown) > 0) { + stop( + sprintf("`tabtibble_widths` names column(s) that are not data columns: %s", paste(sQuote(unknown), collapse = ", ")), + call. = FALSE + ) + } + missing_cols <- setdiff(cols, width_names) + if (length(missing_cols) > 0) { + stop( + sprintf("`tabtibble_widths` is missing an entry for column(s): %s", paste(sQuote(missing_cols), collapse = ", ")), + call. = FALSE + ) + } + widths <- widths[cols] + } else if (length(widths) != length(cols)) { + stop("`tabtibble_widths` must be named, or the same length as the number of (non-topic) columns.", call. = FALSE) + } + valid <- !is.na(widths) & grepl("^(auto|([0-9]+(\\.[0-9]+)?|\\.[0-9]+)(pt|mm|cm|in|em|%|fr))$", widths) + if (!all(valid)) { + stop( + sprintf( + paste( + "`tabtibble_widths` values must be Typst track sizes (\"auto\", a length such as \"3cm\", \".5in\",", + "or \"40%%\", or a fraction such as \"2fr\"): %s" + ), + paste(sQuote(widths[!valid]), collapse = ", ") + ), + call. = FALSE + ) + } + sprintf("(%s,)", paste(unname(widths), collapse = ", ")) +} + +#' Resolve the number of leading row-header columns +#' +#' @param x A data.frame (the data columns only). +#' @param header_cols `NULL` (none), or the `"tabtibble_header_cols"` +#' attribute: the number of leading data columns that label their rows. +#' @returns A single integer, `0` when there are none. +#' @keywords internal +resolve_typst_header_cols <- function(x, header_cols = NULL) { + if (is.null(header_cols)) { + return(0L) + } + ok <- is.numeric(header_cols) && length(header_cols) == 1 && !is.na(header_cols) && + header_cols == round(header_cols) && header_cols >= 0 && header_cols < ncol(x) + if (!ok) { + if (ncol(x) == 0) { + stop("`tabtibble_header_cols` cannot be set on a table whose every column is a topic column.", call. = FALSE) + } + stop( + sprintf( + "`tabtibble_header_cols` must be a single whole number from 0 to %d (one less than the number of (non-topic) columns).", + ncol(x) - 1L + ), + call. = FALSE + ) + } + as.integer(header_cols) +} + +#' Resolve whether topic headers name their column +#' +#' @param topic_labels `NULL` (no), or the `"tabtibble_topic_labels"` +#' attribute: a single `TRUE` or `FALSE`. +#' @returns `TRUE` or `FALSE`. +#' @keywords internal +resolve_typst_topic_labels <- function(topic_labels = NULL) { + if (is.null(topic_labels)) { + return(FALSE) + } + if (!is.logical(topic_labels) || length(topic_labels) != 1 || is.na(topic_labels)) { + stop("`tabtibble_topic_labels` must be a single TRUE or FALSE.", call. = FALSE) + } + topic_labels +} + #' Render a data.frame as a raw Typst table, with optional repeating topic headers #' #' Emits a fenced `{=typst}` block (which Quarto passes through verbatim) #' containing a `#table(...)` whose column header repeats #' (`table.header(repeat: true, ...)`) on every page the table continues -#' onto. When `topic_cols` is non-empty, each distinct combination of topic -#' values is additionally emitted once, as its own repeating header row -#' (`table.header(level = 2, ...)` for the first topic column, `level = 3` -#' for the second, and so on) spanning the data columns, immediately above -#' its rows; `x` must already be sorted by `topic_cols` (`new_tab_tibble()` -#' checks this). A topic header is never left alone at the bottom of a page -#' -- Typst keeps a `table.header` row with at least the row after it, -#' verified against a render long enough to force the break. Without -#' `topic_cols`, this is an ordinary repeating-header table. +#' onto. A rule (`table.hline()`) closes the column header, so it repeats +#' with it under the header on every page, and another ends the table: the +#' rules frame the data. When `topic_cols` is non-empty, each distinct +#' combination of topic values is additionally emitted once, as its own +#' repeating header row (`table.header(level = 2, ...)` for the first topic +#' column, `level = 3` for the second, and so on) spanning the data columns, +#' immediately above its rows; `x` must already be sorted by `topic_cols` +#' (`new_tab_tibble()` checks this). A topic header is never left alone at +#' the bottom of a page -- Typst keeps a `table.header` row with at least the +#' row after it, verified against a render long enough to force the break. +#' Without `topic_cols`, this is an ordinary repeating-header table. +#' +#' Attributes of `x` adjust the table: +#' +#' * `"tabtibble_align"`: the column alignment; see `resolve_typst_align()`. +#' * `"tabtibble_widths"`: the column widths; see `resolve_typst_widths()`. +#' * `"tabtibble_header_cols"`: the number of leading data columns that +#' label their rows; a vertical rule (`table.vline()`) separates them from +#' the other columns. +#' * `"tabtibble_topic_labels"`: `TRUE` to show each topic header as +#' ": " instead of the value alone, so a topic row says +#' what it is. +#' * `"tabtibble_typst_raw"`: the names of data columns whose cells are +#' already Typst markup (for example `$r^2$`); they are written as given, +#' not escaped, so the caller escapes any literal text in them. The other +#' backends do not read these attributes, so under them (and under the +#' markdown fallback outside Quarto) a raw column is escaped like any +#' other and its markup shows literally. +#' +#' Column names, in the column header and in topic headers, are escaped like +#' cell text. #' #' @param x A data.frame. #' @param topic_cols Character vector of column names (outer to inner) to @@ -85,18 +213,38 @@ resolve_typst_align <- function(x, align = NULL) { #' rendered table with `cat()`. #' @keywords internal render_typst_table <- function(x, topic_cols = character(0), ...) { - x <- escape_typst_df(x) + raw_cols <- attr(x, "tabtibble_typst_raw", exact = TRUE) + if (is.null(raw_cols)) { + raw_cols <- character(0) + } + topic_labels <- resolve_typst_topic_labels(attr(x, "tabtibble_topic_labels", exact = TRUE)) data_cols <- setdiff(names(x), topic_cols) + bad_raw <- setdiff(raw_cols, data_cols) + if (length(bad_raw) > 0) { + stop( + sprintf("`tabtibble_typst_raw` names column(s) that are not data columns: %s", paste(sQuote(bad_raw), collapse = ", ")), + call. = FALSE + ) + } + x_raw <- x[raw_cols] + x <- escape_typst_df(x) + x[raw_cols] <- x_raw n_col <- length(data_cols) - align <- resolve_typst_align(x[data_cols], attr(x, "tabtibble_align")) + align <- resolve_typst_align(x[data_cols], attr(x, "tabtibble_align", exact = TRUE)) + columns <- resolve_typst_widths(x[data_cols], attr(x, "tabtibble_widths", exact = TRUE)) + header_cols <- resolve_typst_header_cols(x[data_cols], attr(x, "tabtibble_header_cols", exact = TRUE)) + topic_names <- escape_typst(topic_cols) cat("```{=typst}\n") cat("#table(\n") - cat(" columns: ", n_col, ",\n", sep = "") + cat(" columns: ", columns, ",\n", sep = "") cat(" align: (", paste(align, collapse = ", "), ",),\n", sep = "") + if (header_cols > 0) { + cat(" table.vline(x: ", header_cols, "),\n", sep = "") + } cat( " table.header(repeat: true, ", - paste(vapply(data_cols, .typst_header_cell, character(1)), collapse = ", "), ",),\n", + paste(vapply(escape_typst(data_cols), .typst_header_cell, character(1)), collapse = ", "), ", table.hline(),),\n", sep = "" ) @@ -109,6 +257,9 @@ render_typst_table <- function(x, topic_cols = character(0), ...) { for (lvl in seq_along(topic_cols)) { if (changes[i, lvl]) { value <- .format_typst_cell(x[[topic_cols[[lvl]]]][i]) + if (topic_labels) { + value <- paste0(topic_names[[lvl]], ": ", value) + } cat( " table.header(level: ", lvl + 1L, ", table.cell(colspan: ", n_col, ")[*", value, "*]),\n", @@ -120,6 +271,7 @@ render_typst_table <- function(x, topic_cols = character(0), ...) { cells <- vapply(data_cols, function(cn) .typst_cell(.format_typst_cell(x[[cn]][i])), character(1)) cat(" ", paste(cells, collapse = ", "), ",\n", sep = "") } + cat(" table.hline(),\n") cat(")\n```\n") invisible(NULL) } diff --git a/man/render_typst_table.Rd b/man/render_typst_table.Rd index 6d6a171..2e6b710 100644 --- a/man/render_typst_table.Rd +++ b/man/render_typst_table.Rd @@ -24,14 +24,38 @@ rendered table with \code{cat()}. Emits a fenced \verb{\{=typst\}} block (which Quarto passes through verbatim) containing a \verb{#table(...)} whose column header repeats (\verb{table.header(repeat: true, ...)}) on every page the table continues -onto. When \code{topic_cols} is non-empty, each distinct combination of topic -values is additionally emitted once, as its own repeating header row -(\code{table.header(level = 2, ...)} for the first topic column, \code{level = 3} -for the second, and so on) spanning the data columns, immediately above -its rows; \code{x} must already be sorted by \code{topic_cols} (\code{new_tab_tibble()} -checks this). A topic header is never left alone at the bottom of a page --- Typst keeps a \code{table.header} row with at least the row after it, -verified against a render long enough to force the break. Without -\code{topic_cols}, this is an ordinary repeating-header table. +onto. A rule (\code{table.hline()}) closes the column header, so it repeats +with it under the header on every page, and another ends the table: the +rules frame the data. When \code{topic_cols} is non-empty, each distinct +combination of topic values is additionally emitted once, as its own +repeating header row (\code{table.header(level = 2, ...)} for the first topic +column, \code{level = 3} for the second, and so on) spanning the data columns, +immediately above its rows; \code{x} must already be sorted by \code{topic_cols} +(\code{new_tab_tibble()} checks this). A topic header is never left alone at +the bottom of a page -- Typst keeps a \code{table.header} row with at least the +row after it, verified against a render long enough to force the break. +Without \code{topic_cols}, this is an ordinary repeating-header table. +} +\details{ +Attributes of \code{x} adjust the table: +\itemize{ +\item \code{"tabtibble_align"}: the column alignment; see \code{resolve_typst_align()}. +\item \code{"tabtibble_widths"}: the column widths; see \code{resolve_typst_widths()}. +\item \code{"tabtibble_header_cols"}: the number of leading data columns that +label their rows; a vertical rule (\code{table.vline()}) separates them from +the other columns. +\item \code{"tabtibble_topic_labels"}: \code{TRUE} to show each topic header as +"\if{html}{\out{}}: \if{html}{\out{}}" instead of the value alone, so a topic row says +what it is. +\item \code{"tabtibble_typst_raw"}: the names of data columns whose cells are +already Typst markup (for example \verb{$r^2$}); they are written as given, +not escaped, so the caller escapes any literal text in them. The other +backends do not read these attributes, so under them (and under the +markdown fallback outside Quarto) a raw column is escaped like any +other and its markup shows literally. +} + +Column names, in the column header and in topic headers, are escaped like +cell text. } \keyword{internal} diff --git a/man/resolve_typst_header_cols.Rd b/man/resolve_typst_header_cols.Rd new file mode 100644 index 0000000..dcc520f --- /dev/null +++ b/man/resolve_typst_header_cols.Rd @@ -0,0 +1,21 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/typst_topic_table.R +\name{resolve_typst_header_cols} +\alias{resolve_typst_header_cols} +\title{Resolve the number of leading row-header columns} +\usage{ +resolve_typst_header_cols(x, header_cols = NULL) +} +\arguments{ +\item{x}{A data.frame (the data columns only).} + +\item{header_cols}{\code{NULL} (none), or the \code{"tabtibble_header_cols"} +attribute: the number of leading data columns that label their rows.} +} +\value{ +A single integer, \code{0} when there are none. +} +\description{ +Resolve the number of leading row-header columns +} +\keyword{internal} diff --git a/man/resolve_typst_topic_labels.Rd b/man/resolve_typst_topic_labels.Rd new file mode 100644 index 0000000..7b2da9c --- /dev/null +++ b/man/resolve_typst_topic_labels.Rd @@ -0,0 +1,19 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/typst_topic_table.R +\name{resolve_typst_topic_labels} +\alias{resolve_typst_topic_labels} +\title{Resolve whether topic headers name their column} +\usage{ +resolve_typst_topic_labels(topic_labels = NULL) +} +\arguments{ +\item{topic_labels}{\code{NULL} (no), or the \code{"tabtibble_topic_labels"} +attribute: a single \code{TRUE} or \code{FALSE}.} +} +\value{ +\code{TRUE} or \code{FALSE}. +} +\description{ +Resolve whether topic headers name their column +} +\keyword{internal} diff --git a/man/resolve_typst_widths.Rd b/man/resolve_typst_widths.Rd new file mode 100644 index 0000000..927feb7 --- /dev/null +++ b/man/resolve_typst_widths.Rd @@ -0,0 +1,25 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/typst_topic_table.R +\name{resolve_typst_widths} +\alias{resolve_typst_widths} +\title{Resolve per-column Typst column widths} +\usage{ +resolve_typst_widths(x, widths = NULL) +} +\arguments{ +\item{x}{A data.frame (the data columns only).} + +\item{widths}{\code{NULL} for Typst's automatic widths, or the +\code{"tabtibble_widths"} attribute: Typst track sizes (\code{"auto"}, a length +such as \code{"3cm"}, \code{".5in"}, or \code{"40\%"}, or a fraction such as \code{"2fr"}), +either all named by column (each column once, no other names) or none +named, in column order.} +} +\value{ +The Typst \verb{columns:} value: the number of columns when \code{widths} +is \code{NULL}, otherwise a Typst array of track sizes. +} +\description{ +Resolve per-column Typst column widths +} +\keyword{internal} diff --git a/tests/testthat/test-quarto-render.R b/tests/testthat/test-quarto-render.R index 6f7a5e7..ea68052 100644 --- a/tests/testthat/test-quarto-render.R +++ b/tests/testthat/test-quarto-render.R @@ -166,3 +166,71 @@ test_that("multiple backends each produce a crossreferenceable, captioned table" expect_match(txt, "Table 1", fixed = TRUE) expect_match(txt, "Table 2", fixed = TRUE) }) + +test_that("a typst-backend table compiles with its rules, widths, row-header rule, topic labels, and raw cells", { + skip_quarto_tests() + + txt <- render_typst_pdf(c( + "```{r echo=FALSE}", + "options(tabtibble.backend = 'typst')", + "d <- data.frame(", + " Subject = c('S001', 'S002', 'S003'),", + " Parameter = c('r.squared', 'lambda.z', 'none'),", + " Name = c('$r^2$', '$lambda_z$', NA)", + ")", + "attr(d, 'tabtibble_header_cols') <- 1", + "attr(d, 'tabtibble_widths') <- c(Parameter = 'auto', Name = '1fr')", + "attr(d, 'tabtibble_topic_labels') <- TRUE", + "attr(d, 'tabtibble_typst_raw') <- 'Name'", + "d_tab <- new_tab_tibble(tibble::tibble(", + " table = list(d),", + " caption = 'A table with every attribute',", + " label = 'attributes',", + " topic_cols = list('Subject')", + "))", + "```", + "", + "```{r results='asis'}", + "knit_print(d_tab)", + "```" + )) + + expect_match(txt, "A table with every attribute", fixed = TRUE) + expect_match(txt, "Subject: S001", fixed = TRUE) + expect_match(txt, "Subject: S003", fixed = TRUE) + # The math is typeset: its markup is not printed, and the symbols are. + expect_no_match(txt, "$", fixed = TRUE) + expect_no_match(txt, "lambda_z", fixed = TRUE) + # Typst sets math variables in mathematical italic (U+1D45F is r, U+1D706 + # is lambda, U+1D467 is z). + expect_match(txt, "\U0001D45F2", fixed = TRUE) + expect_match(txt, "\U0001D706\U0001D467", fixed = TRUE) +}) + +test_that("a typst-backend table with rules and a row-header column repeats its header on every page", { + skip_quarto_tests() + + pages <- render_typst_pdf_pages(c( + "```{r echo=FALSE}", + "options(tabtibble.backend = 'typst')", + "d <- data.frame(Row = sprintf('R%03d', 1:150), Value = 1:150)", + "attr(d, 'tabtibble_header_cols') <- 1", + "d_tab <- new_tab_tibble(tibble::tibble(", + " table = list(d),", + " caption = 'A long table with rules',", + " label = 'longrules'", + "))", + "```", + "", + "```{r results='asis'}", + "knit_print(d_tab)", + "```" + )) + + table_pages <- pages[grepl("R[0-9]{3}", pages)] + expect_gt(length(table_pages), 1) + for (page in table_pages) { + expect_match(page, "Row\\s+Value") + } + expect_match(paste(table_pages, collapse = "\n"), "R150", fixed = TRUE) +}) diff --git a/tests/testthat/test-typst-topic-table.R b/tests/testthat/test-typst-topic-table.R index 1474205..7f2cbde 100644 --- a/tests/testthat/test-typst-topic-table.R +++ b/tests/testthat/test-typst-topic-table.R @@ -13,7 +13,7 @@ test_that("render_typst_table emits the exact expected Typst for a two-level top "#table(", " columns: 2,", " align: (right, right,),", - " table.header(repeat: true, [*time*], [*value*],),", + " table.header(repeat: true, [*time*], [*value*], table.hline(),),", " table.header(level: 2, table.cell(colspan: 2)[*S1*]),", " table.header(level: 3, table.cell(colspan: 2)[*X*]),", " [0], [1.5],", @@ -22,6 +22,7 @@ test_that("render_typst_table emits the exact expected Typst for a two-level top " table.header(level: 2, table.cell(colspan: 2)[*S2*]),", " table.header(level: 3, table.cell(colspan: 2)[*X*]),", " [0], [3.5],", + " table.hline(),", ")", "```" ) @@ -38,9 +39,10 @@ test_that("render_typst_table emits an ordinary repeating-header table without t "#table(", " columns: 2,", " align: (right, left,),", - " table.header(repeat: true, [*x*], [*y*],),", + " table.header(repeat: true, [*x*], [*y*], table.hline(),),", " [1], [a],", " [2], [b],", + " table.hline(),", ")", "```" ) @@ -127,6 +129,31 @@ test_that("markdown/tinytable/gt/flextable backends ignore topic_cols gracefully }) }) +test_that("the other backends ignore the Typst-only attributes, and escape a raw column like any other", { + d <- data.frame(Parameter = c("r.squared", "lambda.z"), Name = c("$r^2$", NA), Value = 1:2) + attr(d, "tabtibble_header_cols") <- 1 + attr(d, "tabtibble_widths") <- c("auto", "1fr", "auto") + attr(d, "tabtibble_topic_labels") <- TRUE + attr(d, "tabtibble_typst_raw") <- "Name" + with_tabtibble_render_mode("quarto", with_tabtibble_backend("markdown", { + out <- paste(capture.output(render_backend_table(d)), collapse = "\n") + expect_match(out, "\\$r^2\\$", fixed = TRUE) + expect_no_match(out, "vline", fixed = TRUE) + })) + # The typst backend falls back to markdown outside Quarto, escaping the raw + # column there too. + with_tabtibble_render_mode("rmarkdown", with_tabtibble_backend("typst", { + out <- paste(capture.output(render_backend_table(d)), collapse = "\n") + expect_match(out, "\\$r^2\\$", fixed = TRUE) + })) + for (backend in c("tinytable", "gt", "flextable")) { + skip_if_not_installed(backend) + with_tabtibble_render_mode("quarto", with_tabtibble_backend(backend, { + expect_no_error(utils::capture.output(render_backend_table(d))) + })) + } +}) + test_that("emit_typst_breakable_figure_rule emits the expected raw block", { out <- capture.output(emit_typst_breakable_figure_rule()) expect_identical( @@ -157,3 +184,164 @@ test_that("knit_print emits the breakable-figure rule before the div, only for t }) })) }) + +test_that("render_typst_table frames the data with a rule under the header and one at the end, even with no rows", { + out <- capture.output(render_typst_table(data.frame(x = numeric(0)))) + expect_identical( + out, + c( + "```{=typst}", + "#table(", + " columns: 1,", + " align: (right,),", + " table.header(repeat: true, [*x*], table.hline(),),", + " table.hline(),", + ")", + "```" + ) + ) +}) + +test_that("render_typst_table separates the row-header columns with a vertical rule", { + d <- data.frame(Option = c("a", "b"), Value = 1:2, Default = 1:2) + attr(d, "tabtibble_header_cols") <- 1 + out <- capture.output(render_typst_table(d)) + expect_identical( + out[3:6], + c( + " columns: 3,", + " align: (left, right, right,),", + " table.vline(x: 1),", + " table.header(repeat: true, [*Option*], [*Value*], [*Default*], table.hline(),)," + ) + ) + # None, the default, writes no vertical rule. + attr(d, "tabtibble_header_cols") <- 0 + expect_no_match(paste(capture.output(render_typst_table(d)), collapse = "\n"), "vline", fixed = TRUE) +}) + +test_that("render_typst_table refuses a tabtibble_header_cols that is not a count of leading data columns", { + d <- data.frame(a = 1, b = 2) + for (bad in list(2, -1, 1.5, NA_real_, c(1, 1), "1")) { + attr(d, "tabtibble_header_cols") <- bad + expect_error(render_typst_table(d), regexp = "`tabtibble_header_cols` must be a single whole number from 0 to 1") + } +}) + +test_that("render_typst_table sets column widths from tabtibble_widths, named or in order", { + d <- data.frame(Option = "a", Description = "b") + attr(d, "tabtibble_widths") <- c(Description = "1fr", Option = "auto") + expect_identical(capture.output(render_typst_table(d))[3], " columns: (auto, 1fr,),") + attr(d, "tabtibble_widths") <- c("3cm", "40%") + expect_identical(capture.output(render_typst_table(d))[3], " columns: (3cm, 40%,),") + # Widths are for the data columns; a topic column takes none. + d_topic <- data.frame(subject = "S1", Option = "a", Description = "b") + attr(d_topic, "tabtibble_widths") <- c("auto", "2.5fr") + expect_identical(capture.output(render_typst_table(d_topic, topic_cols = "subject"))[3], " columns: (auto, 2.5fr,),") +}) + +test_that("resolve_typst_widths refuses widths that are missing, the wrong length, or not Typst track sizes", { + d <- data.frame(a = 1, b = 2) + expect_error(resolve_typst_widths(d, c(a = "auto")), regexp = "missing an entry for column\\(s\\): 'b'") + expect_error(resolve_typst_widths(d, "auto"), regexp = "must be named, or the same length") + expect_error(resolve_typst_widths(d, c("auto", "wide")), regexp = "must be Typst track sizes.*'wide'") + expect_error(resolve_typst_widths(d, c("auto", NA)), regexp = "must be Typst track sizes.*NA") + expect_error(resolve_typst_widths(d, c(1, 2)), regexp = "must be a character vector") + expect_identical(resolve_typst_widths(d, NULL), "2") +}) + +test_that("resolve_typst_widths takes every name or none, each a data column once", { + d <- data.frame(a = 1, b = 2) + # A partly named vector is refused, not read by its names alone. + expect_error(resolve_typst_widths(d, c(a = "1fr", "2fr")), regexp = "`tabtibble_widths` must name every width or none") + # A name that is not a column is named in the error, even beside a + # missing column. + expect_error( + resolve_typst_widths(d, c(a = "1fr", z = "2fr")), + regexp = "`tabtibble_widths` names column\\(s\\) that are not data columns: 'z'" + ) + expect_error( + resolve_typst_widths(d, c(a = "1fr", b = "2fr", c = "auto")), + regexp = "not data columns: 'c'" + ) + expect_error( + resolve_typst_widths(d, c(a = "1fr", a = "2fr", b = "auto")), + regexp = "`tabtibble_widths` names column\\(s\\) more than once: 'a'" + ) +}) + +test_that("resolve_typst_widths accepts lengths and fractions with or without a leading zero", { + d <- data.frame(a = 1, b = 2, c = 3, d = 4) + expect_identical(resolve_typst_widths(d, c(".5cm", "0.5fr", "12.25pt", "auto")), "(.5cm, 0.5fr, 12.25pt, auto,)") + expect_error(resolve_typst_widths(d, c("5.cm", "1fr", "1fr", "1fr")), regexp = "'5.cm'") +}) + +test_that("render_typst_table refuses a tabtibble_topic_labels that is not a single TRUE or FALSE", { + d <- data.frame(subject = "S1", value = 1) + for (bad in list("yes", 1, NA, c(TRUE, TRUE), logical(0))) { + attr(d, "tabtibble_topic_labels") <- bad + expect_error( + render_typst_table(d, topic_cols = "subject"), + regexp = "`tabtibble_topic_labels` must be a single TRUE or FALSE" + ) + } + attr(d, "tabtibble_topic_labels") <- FALSE + expect_identical( + capture.output(render_typst_table(d, topic_cols = "subject"))[6], + " table.header(level: 2, table.cell(colspan: 1)[*S1*])," + ) +}) + +test_that("render_typst_table escapes column names in the column header and in topic headers", { + d <- data.frame(`Sub_ject` = "S1", `AUC*` = 1, `Cmax#1` = 2, check.names = FALSE) + attr(d, "tabtibble_topic_labels") <- TRUE + out <- capture.output(render_typst_table(d, topic_cols = "Sub_ject")) + expect_identical(out[5], " table.header(repeat: true, [*AUC\\**], [*Cmax\\#1*], table.hline(),),") + expect_identical(out[6], " table.header(level: 2, table.cell(colspan: 2)[*Sub\\_ject: S1*]),") +}) + +test_that("resolve_typst_header_cols says so when every column is a topic column", { + d <- data.frame(subject = "S1") + attr(d, "tabtibble_header_cols") <- 1 + expect_error( + render_typst_table(d, topic_cols = "subject"), + regexp = "`tabtibble_header_cols` cannot be set on a table whose every column is a topic column" + ) +}) + +test_that("render_typst_table names each topic header's column with tabtibble_topic_labels", { + d <- data.frame(Part = c("A", "A"), Subject = c("S001", "S_2"), value = 1:2) + attr(d, "tabtibble_topic_labels") <- TRUE + out <- capture.output(render_typst_table(d, topic_cols = c("Part", "Subject"))) + expect_identical( + out[6:10], + c( + " table.header(level: 2, table.cell(colspan: 1)[*Part: A*]),", + " table.header(level: 3, table.cell(colspan: 1)[*Subject: S001*]),", + " [1],", + " table.header(level: 3, table.cell(colspan: 1)[*Subject: S\\_2*]),", + " [2]," + ) + ) + # Without the attribute, a topic header is the value alone. + attr(d, "tabtibble_topic_labels") <- NULL + out_plain <- capture.output(render_typst_table(d, topic_cols = c("Part", "Subject"))) + expect_identical(out_plain[6], " table.header(level: 2, table.cell(colspan: 1)[*A*]),") +}) + +test_that("render_typst_table writes tabtibble_typst_raw columns as given and escapes the others", { + d <- data.frame(Parameter = "r_sq", Name = "$r^2$") + attr(d, "tabtibble_typst_raw") <- "Name" + out <- capture.output(render_typst_table(d)) + expect_identical(out[6], " [r\\_sq], [$r^2$],") + attr(d, "tabtibble_typst_raw") <- NULL + expect_identical(capture.output(render_typst_table(d))[6], " [r\\_sq], [\\$r^2\\$],") +}) + +test_that("render_typst_table refuses tabtibble_typst_raw columns that are not data columns", { + d <- data.frame(subject = "S1", Name = "$x$") + attr(d, "tabtibble_typst_raw") <- c("Name", "subject") + expect_error(render_typst_table(d, topic_cols = "subject"), regexp = "not data columns: 'subject'") + attr(d, "tabtibble_typst_raw") <- "missing" + expect_error(render_typst_table(d), regexp = "not data columns: 'missing'") +}) diff --git a/vignettes/example-usage.Rmd b/vignettes/example-usage.Rmd index 6276a7b..b94c3e6 100644 --- a/vignettes/example-usage.Rmd +++ b/vignettes/example-usage.Rmd @@ -152,3 +152,43 @@ d_tab_topic_aligned <- tibble::tibble(table = list(conc), caption = "Aligned columns", topic_cols = list("subject")) %>% new_tab_tibble() ``` + +The `"typst"` backend frames the data of every table with a rule under the +column header, which repeats with the header on every page, and a rule at +the end of the table. Four more attributes on the table adjust it; the +other backends ignore them. + +`tabtibble_header_cols` is the number of leading columns that label their +rows; a vertical rule separates them from the rest: + +```{r header-cols-example} +params <- tibble::tibble(Parameter = c("cmax", "tmax"), Value = c(5.2, 1.0)) +attr(params, "tabtibble_header_cols") <- 1 +``` + +`tabtibble_widths` sets the column widths as Typst track sizes: `"auto"`, a +length such as `"3cm"` or `".5in"`, or a fraction of the remaining width +such as `"2fr"`. Name every column, or give the widths in column order: + +```{r widths-example} +attr(params, "tabtibble_widths") <- c(Parameter = "auto", Value = "1fr") +``` + +`tabtibble_topic_labels = TRUE` shows each topic header as +": " (here "subject: S001") rather than the value alone, +so a topic row says what it is: + +```{r topic-labels-example} +attr(conc, "tabtibble_topic_labels") <- TRUE +``` + +`tabtibble_typst_raw` names columns whose cells are Typst markup, such as an +equation, written without escaping. Any literal text in those cells must be +escaped by the caller. Under the other backends, and under the markdown +fallback outside Quarto, the column is escaped like any other, so its markup +shows as text: + +```{r typst-raw-example} +names_tab <- tibble::tibble(Parameter = c("r.squared", "lambda.z"), Name = c("$r^2$", "$lambda_z$")) +attr(names_tab, "tabtibble_typst_raw") <- "Name" +```