R/turbo-stream.R

Defines functions turbo_stream

Documented in turbo_stream

#' @title Turbo Stream
#'
#' @description
#' Turbo Streams deliver page changes as fragments of HTML wrapped in
#' self-executing `<turbo-stream>` elements. Each stream element specifies an
#' action together with a target ID to declare what should happen to the HTML
#' inside it. These elements are delivered by the server over a WebSocket, SSE
#' or other transport to bring the application alive with updates made by other
#' users or processes.
#'
#' @details
#' It’s good practice to start your interaction design without Turbo Streams.
#' Make the entire application work as it would if Turbo Streams were not
#' available, then layer them on as a level-up. This means you won’t come to
#' rely on the updates for flows that need to work in native applications or
#' elsewhere without them.
#'
#' @inheritParams turbo_frame
#' @param action (str) the action to be taken for this stream element:
#'   * `append`  - inserted last inside the element
#'   * `prepend` - inserted first inside the element
#'   * `replace` - replace the whole element
#'   * `update`  - replace the element but keep handlers intact; only HTML
#'   * `remove`  - remove the element
#'   * `before`  - insert before the element
#'   * `after`   - insert after the element
#' @param multiple (flg) if multiple targets, where `target` is CSS selector
#'
#' @family Turbo
#' @export
turbo_stream <- function(action = c("append", "prepend", "replace", "update",
                                    "remove", "before", "after"),
                         target,
                         ...,
                         multiple = FALSE,
                         env = parent.frame()) {

  action <- match_arg(action)
  assert_string(action)
  assert_string(target)
  assert_flag(multiple)

  tag(
    `_tag_name` = "turbo-stream",
    varArgs = list(
      action = action,
      target = if (!multiple) target,
      targets = if (multiple) target,
      tags$template(html_tags(..., env = env))
    )
  ) %>%
    add_class("turbo_stream")

}
tjpalanca/hotwire.R documentation built on Dec. 23, 2021, 10:59 a.m.