R/format.R

Defines functions .mt_str_values free_cyclical_token_values time_format_impl time_format_default format_duration_token format_token_spec mt_unit_display

# called internally by mt_glue_fmt
mt_unit_display <- function(x, units, parts, ...) {
  if (is_mt <- inherits(x, "S7_class")) {
    # Match based on class only, e.g. {year}-{month}-{day}
    xi <- which(vapply(units, S7_inherits, logical(1L), x))
    if (length(xi) == 0L) {
      # This doesn't match one of the expected units, maybe it's not a mixtime S7 class?
      is_mt <- FALSE
    } else if (length(xi) > 1L) {
      # This matches multiple expected units, more precision is needed.
      cal <- time_calendar(units[[length(units)]])
      bad_tu <- names(cal)[match(S7_class_id(x), vapply(cal, S7_class_id, character(1L)))]
      cli::cli_abort(
        c(
          "Multiple units match {.code {paste0('{', bad_tu, '}')}} in the mixtime format string.",
          i =  "Specify chronon size precisely using e.g. {.code {paste0('{', bad_tu, '(1L)}')}}"
        ),
        call = NULL
      )
    }
  } else if (is_mt <- S7_inherits(x, mt_unit)) {
    xi <- vec_match(
      data.frame(x = x@n, tu = S7_class_id(x)),
      data.frame(x = vapply(units, function(u) u@n, numeric(1L)), tu = vapply(units, S7_class_id, character(1L)))
    )
    # No matches found
    if (is.na(xi)) {
      cli::cli_abort(
        c(
          "The calendar time unit of {time_granule_label(x)} could not be found."
        ),
        call = NULL
      )
    }
  }
  if (is_mt) {
    # Return cyclical labels for cyclical parts
    if (xi > 1) return(cyclical_labels_format(units[[xi]], units[[xi-1L]], parts[[xi]], at = NULL, ...))
    # Return linear labels for coarsest part
    return(as.character(parts[[xi]]))
  } else {
    as.character(x)
  }
}

# Decodes one mt_glue_fmt() `{lin(...)}`/`{cyc(...)}`/`{dur(...)}` token with attributes
format_token_spec <- function(tok) {
  list(
    chronon = tok[[1L]],
    cycle = if (length(tok) == 2L) tok[[2L]] else NULL,
    attrs = attributes(tok)[setdiff(names(attributes(tok)), "class")] %||% list()
  )
}

# Formats duration `x` for a `{dur(...)}` token, in units of the token's granule.
format_duration_token <- function(tok, x) {
  if (!S7_inherits(x, mt_duration)) {
    cli::cli_abort(
      c(
        "{.fn dur} can only format durations.",
        i = "Use {.fn lin} or {.fn cyc} to format time points."
      ),
      call = NULL
    )
  }
  spec <- format_token_spec(tok)
  duration_check_locale(spec$attrs$locale)
  if (length(x) == 0L) return(character())
  discrete <- is.integer(vec_data(x))
  duration_label(duration(x, spec$chronon, discrete = discrete)@x[[1L]])
}

time_format_default <- function(x, attr = TRUE) {
  chronon <- base::attr(x, "chronon")

  if (S7_inherits(x, mt_duration)) {
    return(chronon_format_duration(chronon))
  }

  cycle <- base::attr(x, "cycle")
  fmt <- if (is.null(cycle)) {
    chronon_format_linear(chronon)
  } else {
    chronon_format_cyclical(chronon, cycle)
  }

  # Add fractional
  if (is.double(x)) fmt <- paste(fmt, "{frac(.time)}")

  # Add format attributes (e.g. tz or location)
  if (attr) fmt <- paste0(fmt, chronon_format_attr(chronon))

  fmt
}

time_format_impl <- function(x, format = time_format_default(x, attr = attr), ..., attr = TRUE) {
  # Obtain core time information
  chronon <- attr(x, "chronon")

  # Evaluation calendar: the chronon's own, extended with the cycle's units so
  # cyclical granules (e.g. {cyc(month, year)}) can be named.
  cycle <- attr(x, "cycle")
  calendar <- if (is.null(cycle)) time_calendar(chronon) else time_calendar(cycle)

  x_special <- is.na(x) | is.infinite(vec_data(x))

  # Create the glue evaluation environment by layering format-only helpers on top
  # of the shared lin()/cyc() component mask: the attribute helpers (tz / loc /
  # frac) and .time are added to the same calendar + lin/cyc vocabulary that
  # time_components() evaluates against.
  env <- rlang::new_environment(
    data = c(
      component_mask(calendar, chronon),
      list(
        # Attribute helper functions
        tz = tz_abbreviation,
        loc = function(x) {
          chronon <- attr(x, "chronon")
          if (!S7_inherits(mt_loc_unit)) return("")
          lat <- chronon@lat
          lon <- chronon@lon
          alt <- chronon@alt
          lat_str <- sprintf("%.2f%s", abs(lat), if (lat >= 0) "N" else "S")
          lon_str <- sprintf("%.2f%s", abs(lon), if (lon >= 0) "E" else "W")
          if (alt != 0) {
            paste0(lat_str, " ", lon_str, " ", sprintf("%.0fm", alt))
          } else {
            paste0(lat_str, " ", lon_str)
          }
        },
        frac = function(x) {
          # The fraction through each chronon (in its own context)
          x <- round_ulp(vec_data(x))
          sprintf("%.1f%%", (x - floor(x)) * 100)
        },

        # Attach .time for specialised usage (e.g. tz_abbreviation(.time))
        .time = x
      )
    ),
    parent = rlang::caller_env()
  )

  fmt <- mt_glue_fmt(format, env = env)

  # Render {dur(...)} tokens directly, since durations have no calendar parts.
  fmt_dur <- vapply(fmt, inherits, logical(1L), "mt_dur_spec")
  fmt[fmt_dur] <- lapply(fmt[fmt_dur], format_duration_token, x = x[!x_special])
  fmt_parts <- vapply(fmt, is.list, logical(1L))

  # Resolve bare S7 class tokens (e.g. from {year}, {month}, {day}) into
  # lin/cyc lists using the chronon_cardinality graph to order fine->coarse.
  s7_class_lgl <- vapply(fmt, inherits, logical(1L), "S7_class")
  if (any(s7_class_lgl)) {
    bare_units <- vapply(fmt[s7_class_lgl], S7_class_id, character(1L))
    cal <- time_calendar(x)

    tu_i <- match(
      bare_units,
      vapply(cal, S7_class_id, character(1L))
    )

    cli::cli_abort(
      c(
        "Bare time granule tokens are not currently supported in format strings.",
        i = "Use {.fn lin} for linear (coarsest) units, e.g. {.code {paste0('{lin(', names(cal)[tu_i[1]], ')}')}}}",
        i = "Use {.fn cyc} for cyclical units, e.g. {.code {paste0('{cyc(', names(cal)[tu_i[1]], ', <coarser_unit>)}')}}"
      ),
      call = NULL
    )

    # class_idx <- which(s7_class_lgl)
    # class_num <- length(class_idx)

    # # Initialise as time units of size 1L
    # fmt[class_idx] <- lapply(fmt[class_idx], function(f) f(1L))

    # # Find order of granularity from fine -> coarse
    # ordered_idx <- class_idx[S7_order_granules(fmt[class_idx])]

    # # Replace string parts such that:
    # # * finer time units are cyclical with the next coarser
    # for (i in seq_len(class_num - 1L)) {
    #   fmt[[ordered_idx[i]]] <- list(fmt[[ordered_idx[i]]], fmt[[ordered_idx[i+1L]]])
    # }
    # # * coarsest time unit is linear
    # fmt[[ordered_idx[class_num]]] <- list(fmt[[ordered_idx[class_num]]])
  }

  # Compute the numeric parts for display
  res_split <- split(fmt[fmt_parts], lengths(fmt[fmt_parts]))
  parts <- chronon_parts(
    x        = x[!x_special],
    linear   = unlist(res_split[["1"]], recursive = FALSE),
    cyclical = res_split[["2"]]
  )

  # Apply labels
  parts$linear <- .mapply(
    function(tu, x) {
      spec <- format_token_spec(tu)
      rlang::exec(linear_labels_format, spec$chronon, x, !!!spec$attrs)
    },
    dots = list(res_split[["1"]], parts$linear),
    MoreArgs = NULL
  )
  parts$cyclical <- .mapply(
    # TODO floor(x) shouldn't be necessary, fix chronon_parts()?
    function(tu, x, at) {
      spec <- format_token_spec(tu)
      rlang::exec(cyclical_labels_format, spec$chronon, spec$cycle, floor(x), at = at, !!!spec$attrs)
    },
    dots = list(res_split[["2"]], parts$cyclical, parts$cyclical_at),
    MoreArgs = NULL
  )

  # Insert time labels into format string parts
  if (any(fmt_parts)) {
    fmt[fmt_parts] <- unsplit(Filter(length, parts), lengths(fmt[fmt_parts]))
  }

  # Handle format parts which include special values (e.g. timezones)
  if (any(x_special) && any(fmt_inc_special <- lengths(fmt) == length(x))) {
    fmt[fmt_inc_special] <- lapply(fmt[fmt_inc_special], function(x) x[!x_special])
  }

  out <- character(length(x))
  out[!x_special] <- trimws(rlang::exec(paste0, !!!fmt))
  out[x_special] <- format(vec_data(x)[x_special])
  out
}

#' Format mixtime vectors
#'
#' Formats a mixtime vector as a character vector, using a glue-style format
#' string of `{lin(...)}`/`{cyc(...)}` (or, for durations, `{dur(...)}`) tokens tailored to the vector's chronon
#' and cycle. If `format` is omitted, a sensible default is derived
#' automatically. See `vignette("time-format-strings")` for the format string
#' syntax.
#'
#' @section Underspecified cyclical time:
#' Underspecified cyclical time (e.g. `month_of_year(3)`) has no position on
#' the time line, so only `{cyc(...)}` tokens can be used. Attribute tokens
#' such as `{tz(.time)}` render as empty text.
#'
#' @param x A mixtime vector.
#' @param format A glue-style format string, defaulting to one derived
#'   automatically for `x`. For time points it is passed via `...`.
#' @param ... Additional arguments for methods, including `format` for time
#'   points.
#' @param attr If `TRUE` (default), append attribute information (e.g.
#'   timezone) to the default format.
#'
#' @return A character vector the same length as `x`.
#'
#' @examples
#' format(yearmonth("2024-03"))
#' format(date("2024-03-15"), format = "{cyc(day(1L), month(1L))} {lin(year(1L))}")
#' format(month_of_year(3))
#'
#' @usage
#' \S4method{format}{mt_time}(x, ..., attr = TRUE)
#' \S4method{format}{mt_cyclical_free}(x, format = NULL, ..., attr = TRUE)
#' @aliases format,mt_time-method format,mt_cyclical_free-method format.mt_cyclical_free
#' @name format.mt_time
#' @export
S7::method(format, mt_time) <- function(x, ..., attr = TRUE) {
  time_format_impl(x, ..., attr = attr)
}

#' @rdname format.mt_time
#' @export
S7::method(format, mt_cyclical_free) <- function(x, format = NULL, ..., attr = TRUE) {
  chronon <- base::attr(x, "chronon")
  cycle <- base::attr(x, "cycle")
  v <- vec_data(x)
  special <- is.na(x) | is.infinite(v)
  n <- sum(!special)

  out <- character(length(x))
  out[special] <- base::format(v[special])

  if (n > 0L) {
    fmt_str <- format %||% paste0(
      chronon_format_cyclical(chronon, cycle),
      if (attr) chronon_format_attr(chronon)
    )
    calendar <- time_calendar(cycle)
    # Templates call package internals (e.g. chronon_glb()), so evaluate them
    # in the package namespace rather than the (possibly unattached) caller's.
    env <- rlang::new_environment(
      data = c(
        component_mask(calendar, chronon),
        list(
          lin = function(...) {
            cli::cli_abort(
              c(
                "Can't format underspecified cyclical time with {.code {{lin()}}}.",
                i = "It has no enclosing cycle to locate it on the time line, so use {.code {{cyc()}}} tokens."
              ),
              call = NULL
            )
          },
          # A free value has no time zone or location to show.
          tz = function(x) "",
          loc = function(x) "",
          frac = function(x) {
            x <- round_ulp(vec_data(x))
            sprintf("%.1f%%", (x - floor(x)) * 100)
          },
          .time = x
        )
      ),
      parent = topenv()
    )
    fmt <- mt_glue_fmt(fmt_str, env = env)
    fmt_parts <- vapply(fmt, is.list, logical(1L))
    if (!all(fmt_parts | vapply(fmt, is.character, logical(1L)))) {
      cli::cli_abort(
        c(
          "Bare time granule tokens are not supported in format strings.",
          i = "Use {.fn cyc} for cyclical units, e.g. {.code {{cyc(month, year)}}}."
        ),
        call = NULL
      )
    }
    specs <- lapply(fmt[fmt_parts], format_token_spec)
    token_values <- free_cyclical_token_values(v[!special], chronon, cycle, specs)

    # A literal fragment repeats; a {cyc(...)} token renders its decomposed value.
    ti <- 0L
    pieces <- lapply(seq_along(fmt), function(i) {
      if (!fmt_parts[[i]]) {
        piece <- fmt[[i]]
        return(if (length(piece) == length(x)) piece[!special] else rep_len(piece, n))
      }
      ti <<- ti + 1L
      spec <- specs[[ti]]
      rlang::exec(
        cyclical_labels_format,
        spec$chronon, spec$cycle %||% cycle, token_values[[ti]],
        at = NULL, !!!spec$attrs
      )
    })
    out[!special] <- trimws(rlang::exec(paste0, !!!pieces))
  }
  out
}

# Split `v` (a count of `own_chronon`s) across a template's {cyc(...)} tokens,
# coarsest-to-finest, via chronon_cardinality() only - never chronon_divmod().
# The count is first rescaled to the finest token's chronon (e.g. 47 chronons
# of 30 minutes are 1410 minutes). The coarsest token keeps the leftover.
free_cyclical_token_values <- function(v, own_chronon, own_cycle, specs) {
  n <- length(specs)
  out <- vector("list", n)
  if (n == 0L) return(out)
  scale <- chronon_cardinality(specs[[n]]$chronon, own_chronon)
  remaining <- if (scale == 1) v else floor(round_ulp(v * scale))
  for (i in rev(seq_len(n))) {
    if (i == 1L) {
      out[[i]] <- remaining
    } else {
      spec <- specs[[i]]
      card <- chronon_cardinality(spec$chronon, spec$cycle %||% own_cycle)
      out[[i]] <- remaining %% card
      remaining <- remaining %/% card
    }
  }
  out
}

#' @export
S7::method(print, mt_time) <- function(x, ...) {
  cat(paste0("<", class(x)[[1L]], "[", length(x), "]>"), "\n", sep = "")
  print(format(x), quote = FALSE)
  invisible(x)
}

# A time unit as text, e.g. "1 month" or "15 minutes". Used wherever a
# granule is displayed on its own, such as a tsibble's interval.
#' @export
S7::method(format, mt_unit) <- function(x, ...) {
  time_granule_label(x, x@n)
}

#' @export
S7::method(str, mt_linear) <- function(object, ..., vec.len = getOption("str")$vec.len %||% 4L) {
  cat("linear<", format(time_chronon(object)[1L]), "> [1:", length(object), "] ", .mt_str_values(object, vec.len), "\n", sep = "")
}

#' @export
S7::method(str, mt_cyclical) <- function(object, ..., vec.len = getOption("str")$vec.len %||% 4L) {
  cat("cyclical<", format(time_chronon(object)[1L]), "/", format(time_cycle(object)[1L]), "> [1:", length(object), "] ", .mt_str_values(object, vec.len), "\n", sep = "")
}

#' @export
S7::method(str, mt_duration) <- function(object, ..., vec.len = getOption("str")$vec.len %||% 4L) {
  cat("duration<", format(time_chronon(object)[1L]), "> [1:", length(object), "] ", .mt_str_values(object, vec.len), "\n", sep = "")
}

#' @export
S7::method(str, mt_cyclical_free) <- function(object, ..., vec.len = getOption("str")$vec.len %||% 4L) {
  cat("free_cyclical<", format(time_chronon(object)[1L]), "/", format(time_cycle(object)[1L]), "> [1:", length(object), "] ", .mt_str_values(object, vec.len), "\n", sep = "")
}

.mt_str_values <- function(x, vec_len) {
  vals <- format(x)
  if (length(vals) > vec_len) {
    paste0(paste0(vals[seq_len(vec_len)], collapse = " "), " ...")
  } else {
    paste0(vals, collapse = " ")
  }
}

Try the mixtime package in your browser

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

mixtime documentation built on Nov. 18, 2026, 5:08 p.m.