R/V8-tinycolor-context.R

#' Create a tinycolor javascript interpreting context
#'
#' Use the \code{\link[V8]{v8}} function of package \code{V8} to create the context and evaluate the code of tinycolor.js, thus making all functions available.
#'
#' @seealso \code{\link[V8]{v8}} and \url{https://github.com/bgrins/TinyColor/}
#'
#' @examples
#' ct <- v8_tinycolor_context()
#' ct$eval("tinycolor("red").toHexString()")
#' @noRd
#' @importFrom V8 v8
v8_tinycolor_context <- function() {
  # get tinycolor.js's location
  file <- system.file("tinycolor.js", package="tinycolor")

  # create the context
  ct <- V8::v8()

  ct$source(file)

  # return the context
  return(ct)
}

# Evaluate commands in a V8 context
#
# Evaluate javascript commands in a V8 context. By default, this context is tinycolor.
#
# @param command vector of strings to evaluate.
# @param context context to evaluate in.
#
# @examples
# v8_eval(c('tinycolor("red").toHexString()', 'tinycolor("blue").toHexString()'))
#' @importFrom stats na.omit
v8_eval <- function(command, context=v8_tinycolor_context()) {

  out <- unlist(lapply(na.omit(command), context$eval))
  # re-insert NAs
  out <- toupper(na_insert(out, from=command))
  return(out)
}
houyunhuang/tinycolor documentation built on June 6, 2019, 7:43 p.m.