2019-11-26 12:49:03 +01:00
|
|
|
|
|
|
|
#' Format numbers (with D3)
|
|
|
|
#'
|
|
|
|
#' @param format Format for numbers, currency, percentage, e.g. \code{".0\%"} for rounded percentage.
|
|
|
|
#' See online documentation : \url{https://github.com/d3/d3-format}.
|
2019-11-27 23:17:23 +01:00
|
|
|
#' @param prefix Character string to append before formatted value.
|
|
|
|
#' @param suffix Character string to append after formatted value.
|
|
|
|
#' @param locale Localization to use, for example \code{"fr-FR"} for french,
|
2019-11-26 12:49:03 +01:00
|
|
|
#' see possible values here: \url{https://github.com/d3/d3-format/tree/master/locale}.
|
|
|
|
#'
|
|
|
|
#' @return a \code{JS} function
|
|
|
|
#' @export
|
2021-09-17 11:17:43 +02:00
|
|
|
#'
|
2019-11-26 12:49:03 +01:00
|
|
|
#' @importFrom htmlwidgets JS
|
|
|
|
#'
|
|
|
|
#' @example examples/format.R
|
2019-11-26 13:09:47 +01:00
|
|
|
format_num <- function(format, prefix = "", suffix = "", locale = "en-US") {
|
2020-03-19 10:00:35 +01:00
|
|
|
check_locale_d3(locale)
|
2021-08-20 16:53:55 +02:00
|
|
|
path <- system.file(file.path("d3-format-locale", paste0(locale, ".json")), package = "apexcharter")
|
2019-11-26 12:49:03 +01:00
|
|
|
if (path != "") {
|
|
|
|
locale <- paste(readLines(con = path, encoding = "UTF-8"), collapse = "")
|
|
|
|
}
|
|
|
|
JS(sprintf(
|
2021-09-17 11:17:43 +02:00
|
|
|
"function(value) {var locale = formatLocale(JSON.parse('%s')); return '%s' + locale.format('%s')(value) + '%s';}",
|
2019-11-26 13:09:47 +01:00
|
|
|
locale, prefix, format, suffix
|
2019-11-26 12:49:03 +01:00
|
|
|
))
|
|
|
|
}
|
|
|
|
|
|
|
|
|
2020-03-19 10:00:35 +01:00
|
|
|
check_locale_d3 <- function(x) {
|
2021-08-20 16:53:55 +02:00
|
|
|
json <- list.files(system.file("d3-format-locale", package = "apexcharter"))
|
2019-11-26 12:49:03 +01:00
|
|
|
njson <- gsub("\\.json", "", json)
|
|
|
|
if (!x %in% njson) {
|
|
|
|
stop(paste(
|
|
|
|
"Invalid D3 locale, must be one of:",
|
|
|
|
paste(njson, collapse = ", ")
|
|
|
|
), call. = FALSE)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-03-04 16:52:37 +01:00
|
|
|
|
|
|
|
|
|
|
|
|
2020-03-19 10:00:35 +01:00
|
|
|
|
2020-03-04 16:52:37 +01:00
|
|
|
#' Format date in JS
|
|
|
|
#'
|
|
|
|
#' @param x Date to use in JavaScript
|
|
|
|
#'
|
|
|
|
#' @return a JavaScript string
|
|
|
|
#' @export
|
|
|
|
#'
|
|
|
|
format_date <- function(x) {
|
|
|
|
stopifnot(length(x) == 1)
|
|
|
|
JS(sprintf("new Date('%s').getTime()", x))
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|