library(ggforma)
library(grid)
library(systemfonts)

options <- list(sans = c("Arial", "Liberation Sans", "DejaVu Sans"))
installed <- system_fonts()$family
fonts <- vapply(options, function(x) {
  found <- intersect(x, installed)
  if (!length(found)) stop('Choose a suitable installed local font for ', paste(x, collapse = ', '))
  found[1L]
}, character(1))

sheet <- function(title, subtitle) {
  grid.newpage()
  grid.draw(markup_grob(title, format = "plain", x = .055, y = .925, hjust = 0,
                        size = 22, family = fonts["sans"], face = "bold", colour = "#172C3C"))
  grid.draw(markup_grob(subtitle, format = "plain", x = .055, y = .810, hjust = 0,
                        size = 10, family = fonts["sans"], colour = "#465865"))
  grid.lines(x = c(.055, .945), y = c(.745, .745), gp = gpar(col = "#CED7DA", lwd = .8))
}

note <- function(text, x, y, size = 17, family = fonts["sans"], ...) {
  grid.draw(markup_grob(text, x = x, y = y, size = size, family = family,
                        colour = "#172C3C", hjust = 0, ...))
}

key <- function(text, x, y) note(text, x, y, size = 9, face = "bold", format = "plain")

math <- function() {
  sheet("Sampling uncertainty", "Three expressions drawn directly by the R graphics device.")
  equations <- c("hat(mu) == frac(sum(x[i], i == 1, n), n)",
                 "S == sqrt(frac(sum((x[i] - bar(x))^2, i == 1, n), n-1))",
                 "F*(z) == integral(phi*(t)*plain(dt), -infinity, z)")
  for (i in seq_along(equations)) {
    y <- c(.61, .385, .16)[i]
    key(c("MEAN", "STANDARD DEVIATION", "DISTRIBUTION")[i], .068, y)
    grid.draw(formula_grob(equations[i], x = .43, y = y, hjust = 0, gp = gpar(fontsize = 18)))
  }
}

math()
