R/254_zzz_R_specific_visualize_html.R

Defines functions .viz_render_html

#####
## DO NOT EDIT THIS FILE!! EDIT THE SOURCE INSTEAD: rsrc_tree/zzz_R_specific/visualize_html.R
#####

## R-SPECIFIC: visualize_html.R -- HTML renderer for visualize()
##
## Reads the template from inst/visualize/template.html, injects the
## JSON data model, writes a self-contained HTML file, and opens it
## in the browser (or returns the path).

# ==========================================================================
# HTML renderer
# ==========================================================================

#' @noRd
.viz_render_html <- function(model, file = NULL, open = interactive(),
                             doc_base = "https://cvxr.rbind.io/reference/",
                             dcp_overlay = NULL) {
  ## Convert model to JSON (DCP overlay injected only for non-DCP problems)
  json_str <- .viz_model_to_json(model, dcp_overlay = dcp_overlay)

  ## Read template

  template_path <- system.file("visualize", "template.html", package = "CVXR")
  if (!nzchar(template_path)) {
    cli_abort(c(
      "HTML template not found.",
      "i" = "Expected at {.path inst/visualize/template.html} in the CVXR package."
    ))
  }
  template <- paste(readLines(template_path, warn = FALSE), collapse = "\n")

  ## Inject data model and config
  html <- sub("__MODEL_JSON__", json_str, template, fixed = TRUE)
  html <- sub("__DOC_BASE__", doc_base, html, fixed = TRUE)

  ## Write to file
  if (is.null(file)) {
    file <- tempfile(pattern = "cvxr_viz_", fileext = ".html")
  }
  writeLines(html, file)

  ## Open in browser / viewer
  if (open) {
    viewer <- getOption("viewer", default = utils::browseURL)
    viewer(file)
  }

  invisible(file)
}

Try the CVXR package in your browser

Any scripts or data that you put into this service are public.

CVXR documentation built on March 6, 2026, 9:10 a.m.