diff --git a/DESCRIPTION b/DESCRIPTION index 1eb0960cd4..2c97acceac 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -44,12 +44,14 @@ Imports: glue (>= 1.6.1), htmltools (>= 0.5.2), juicyjuice (>= 0.1.0), + jsonlite, magrittr (>= 2.0.2), rlang (>= 1.0.2), sass (>= 0.4.1), scales (>= 1.2.0), tibble (>= 3.1.6), - tidyselect (>= 1.1.1) + tidyselect (>= 1.1.1), + uuid Suggests: covr, digest (>= 0.6.29), diff --git a/R/print.R b/R/print.R index c8f9f9ce0d..0c2a99ac0c 100644 --- a/R/print.R +++ b/R/print.R @@ -38,6 +38,19 @@ knitr_is_word_output <- function() { #' @noRd knit_print.gt_tbl <- function(x, ...) { + if (check_quarto()) { + caption_text <- dt_options_get_value(data = x, option = "table_caption") + table_uuid <- random_id() + x <- dt_options_set_value(data = x, option = "table_id", value = table_uuid) + + if (!is.na(caption_text)) { + quarto_api_send( + "set_table_caption", + caption = caption_text, + table_id = paste0("table-", table_uuid)) + } + } + if (knitr_is_rtf_output()) { x <- as_rtf(x) diff --git a/R/render_as_html.R b/R/render_as_html.R index 7167733d9b..ba4b509c5b 100644 --- a/R/render_as_html.R +++ b/R/render_as_html.R @@ -40,6 +40,7 @@ render_as_html <- function(data) { finalize_html_table( class = "gt_table", style = table_defs$table_style, + id = if (check_quarto()) paste0("table-", dt_options_get_value(data, "table_id")), caption_component, table_defs$table_colgroups, heading_component, diff --git a/R/utils_quarto.R b/R/utils_quarto.R index 4c6488d98c..eaff7ed795 100644 --- a/R/utils_quarto.R +++ b/R/utils_quarto.R @@ -1,3 +1,43 @@ check_quarto <- function() { Sys.getenv("QUARTO_MESSAGES_FILE") != "" } + +check_knitr <- function() { + + if (!requireNamespace("knitr", quietly = TRUE)) { + + cli::cli_abort(c( + "Please install the knitr package.", + "*" = "Use `install.packages(\"knitr\")`." + )) + } +} + +get_uuid <- function() { + uuid::UUIDgenerate() +} + +quarto_api_send <- function(message, ...) { + + uuid <- get_uuid() + + # Ensure that the knitr package is available + check_knitr() + + # Generate a JSON-formatted line + line <- + jsonlite::toJSON( + list( + message = message, + uuid = uuid, + payload = list(...) + ), + auto_unbox = TRUE + ) + + file <- Sys.getenv("QUARTO_MESSAGES_FILE") + + write(line, file, append = TRUE) + + uuid +}