R/standalone-fav.R

Defines functions .standalone_fav_as_href .standalone_fav_encode favawesome_icon

# ---
# repo: shinyworks/favawesome
# file: standalone-fav.R
# last-updated: 2024-10-28
# license: https://unlicense.org
# imports: [fontawesome, htmltools, jsonlite, rsvg]
# ---
#
# Provides the fav() function from {favawesome} as favawesome_icon(), with
# stand-alone code for use in packages that can't import favawesome. See
# favawesome::use_favawesome_standalone() or usethis::use_standalone() for usage
# details.
#
# ## Changelog
#
# 2024-10-28:
#
# * Initial version.

# nocov start

#' Use Font Awesome icons as favicons
#'
#' Generate the html necessary to use a Font Awesome icon as the favicon (the
#' icon that appears on browser tabs) for a shiny app or other HTML document.
#'
#' @return A `shiny.tag` (see [htmltools::tag()]) that can be used to embed a
#'   favicon in a shiny app or other HTML document.
#' @noRd
favawesome_icon <- function(name, ...) {
  fav_base64 <- .standalone_fav_encode(name, ...)
  fav_href <- .standalone_fav_as_href(fav_base64)
  htmltools::tags$head(
    htmltools::tags$link(rel = "icon", type = "image/png", href = fav_href)
  )
}

#' Load Font Awesome icon and encode
#'
#' @return A base64-encoded character vector representing the icon png.
#' @noRd
.standalone_fav_encode <- function(name, ...) {
  jsonlite::base64_enc(
    rsvg::rsvg_png(
      charToRaw(
        fontawesome::fa(name, ...)
      ),
      width = 32,
      height = 32
    )
  )
}

#' Add data URI prefix to base64-encoded icon
#'
#' @param fav_base64 A base64-encoded character vector generated by
#'   `.fav_encode()`.
#'
#' @return The base64-encoded icon with the data URI prefix.
#' @noRd
.standalone_fav_as_href <- function(fav_base64) {
  paste0("data:image/png;base64,", fav_base64)
}

# nocov end

Try the favawesome package in your browser

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

favawesome documentation built on Nov. 1, 2024, 5:07 p.m.