rstudio/bslib

Add css for pandoc syntax highlighting themes

Open

#145 opened on Oct 29, 2020

View on GitHub
 (9 comments) (0 reactions) (0 assignees)SCSS (67 forks)github user discovery
help wantedinvalid

Repository metrics

Stars
 (561 stars)
PR merge metrics
 (PR metrics pending)

Description

If your html contains code, you're likely to want to match the syntax highlighting colours with the them as a whole. So I think it makes sense for bootstraplib to provide some tools to turn pandoc themes into css. Could building from something like this:

library(jsonlite)
library(purrr)
library(dplyr)
library(farver)
library(ggplot2)

# From https://github.com/jgm/skylighting/blob/a1d02a0db6260c73aaf04aae2e6e18b569caacdc/skylighting-core/src/Skylighting/Format/HTML.hs#L117-L147
abbr <- c(
  "Keyword"        = "kw",
  "DataType"       = "dt",
  "DecVal"         = "dv",
  "BaseN"          = "bn",
  "Float"          = "fl",
  "Char"           = "ch",
  "String"         = "st",
  "Comment"        = "co",
  "Other"          = "ot",
  "Alert"          = "al",
  "Function"       = "fu",
  "RegionMarker"   = "re",
  "Error"          = "er",
  "Constant"       = "cn",
  "SpecialChar"    = "sc",
  "VerbatimString" = "vs",
  "SpecialString"  = "ss",
  "Import"         = "im",
  "Documentation"  = "do",
  "Annotation"     = "an",
  "CommentVar"     = "cv",
  "Variable"       = "va",
  "ControlFlow"    = "cf",
  "Operator"       = "op",
  "BuiltIn"        = "bu",
  "Extension"      = "ex",
  "Preprocessor"   = "pp",
  "Attribute"      = "at",
  "Information"    = "in",
  "Warning"        = "wa",
  "Normal"         = ""
)


theme <- jsonlite::read_json("https://raw.githubusercontent.com/rstudio/distill/master/inst/rmarkdown/templates/distill_article/resources/arrow.theme")

as_row <- function(x) {
  x %>%
    modify_if(is.null, ~ NA) %>%
    as_tibble()
}

styles_df <- theme$`text-styles` %>%
  purrr::map_df(as_row, .id = "name") %>%
  rename(color = `text-color`, background = `background-color`) %>%
  mutate(abbr = unname(abbr[name]))

# From https://accessible-colors.com
rel_l <- function(x) {
  scale <- function(x) {
    ifelse(x <= 0.03928, x / 12.92, ((x + 0.055) / 1.055)^2.4)
  }
  rgb <- farver::decode_colour(x) / 255
  0.2126 * scale(rgb[, 1]) + 0.7152 * scale(rgb[, 2]) + 0.0722 * scale(rgb[, 3])
}
contrast_ratio <- function(x, y) {
  x_l <- rel_l(x)
  y_l <- rel_l(y)

  (pmax(x_l, y_l) + 0.05) / (pmin(x_l, y_l) + 0.05)
}

styles_df %>% mutate(contrast = contrast_ratio(color, "#fefefe"))

Contributor guide