Package 'blockr.ui'

Title: User Interface Components for the 'blockr' Ecosystem
Description: User-interface primitives shared across the 'blockr' ecosystem, currently a paginated, sortable HTML table display for block results that plugs into the tabular display extension point of 'blockr.core'.
Authors: David Granjon [aut, cre]
Maintainer: David Granjon <[email protected]>
License: GPL (>= 3)
Version: 0.0.1
Built: 2026-11-05 11:25:34 UTC
Source: https://github.com/BristolMyersSquibb/blockr.ui

Help Index


Action menu

Description

A menu of actions opened by a button: downloads, Rename, Remove. A row does one thing and the menu closes. That is the difference from a select, which sets a value: nothing here is remembered, and there is no current pick.

Usage

action_menu(trigger, ..., align = c("end", "start"))

menu_item(x, meta = NULL, icon = NULL, danger = FALSE, disabled = NULL)

menu_section(title)

menu_divider()

Arguments

trigger

The button that opens the menu, typically a tool_button().

...

Rows: menu_item()s, menu_section() titles and menu_divider() rules, in order. NULLs are dropped, so a row can be conditional.

align

"end" lines the menu up with the trigger's right edge, for a trigger in a block's header row, where a menu opening to the right would leave the block; "start" with its left edge.

x

The row's element: a shiny::downloadLink(), an shiny::actionLink(), or any ⁠<a>⁠ or ⁠<button>⁠. Its text is the row's label.

meta

Text after the label, muted and right-aligned: the format of a download (".pptx"), a block ID, or a keyboard shortcut from shortcut().

icon

An icon before the label, as a tag or htmltools::HTML().

danger

A removal: the row turns red under the pointer or keyboard focus, and stays plain at rest.

disabled

NULL for a usable row, or the reason it is not usable: the row stays in the list, greyed, with the reason as its tooltip.

title

A group title: the rows after it, up to the next title or divider, belong under it.

Details

The rows are ordinary Shiny markup, so a shiny::downloadLink() or an shiny::actionLink() works as it is; menu_item() only dresses it as a row. Blockr.actionMenu (in blockr-ui.js, loaded by controls_dep()) opens the list on a click on the trigger, places it on the page body with Blockr.place so no panel's overflow clips it, and closes it again on a pick, Escape, Tab or a click outside.

A download row works once Shiny has bound its handler, which it does when the menu first shows, so for a moment on that first open the row is still inert. To have it ready from the start, set shiny::outputOptions(output, "<id>", suspendWhenHidden = FALSE) for its output.

menu_divider() draws a rule between groups that have no title, such as the ordinary actions and a destructive one after them.

Value

A htmltools::tag carrying controls_dep().

Examples

action_menu(
  tool_button(
    htmltools::HTML("&darr;"),
    "Download"
  ),
  menu_section("This patient"),
  menu_item(shiny::downloadLink("dl_pptx", "PowerPoint"), meta = ".pptx"),
  menu_item(shiny::downloadLink("dl_html", "Web page"), meta = ".html"),
  menu_section("This block"),
  menu_item(shiny::actionLink("remove", "Remove"), danger = TRUE)
)

Sort a data frame for the table preview

Description

Legacy whole-frame sort kept for direct callers (blockr.dm) during the transition to table_page(), which sorts via a cached order index instead. Same semantics: asc / desc put NA last, na puts NA first.

Usage

apply_table_sort(data, sort_col, sort_dir)

Arguments

data

A data frame.

sort_col

Column name to sort by.

sort_dir

"asc", "desc", "na" or "none".

Value

The sorted data frame.


Base stylesheet for a page without Bootstrap

Description

What a blockr page needs from Bootstrap when it does not load it: the reset of the browser's defaults, the body face (Open Sans, bundled), and the look of the markup Shiny's own inputs emit, which keeps Bootstrap's class names (form-group, form-control, checkbox, btn) whatever the page loads. The button rules read the ⁠--bs-btn-*⁠ properties that theme_dep() sets per kind, so a button looks the same on either kind of page.

Usage

base_dep()

Details

The base sheet is written against the theme layer, so it brings theme_dep() along, after itself: the theme restyles over it as it does over Bootstrap. Attach it once, from a page that does not load Bootstrap; a theme_dep() attached elsewhere on the page is the same dependency. On a page that does load Bootstrap it restyles what Bootstrap already styles and must be left out.

Value

An htmltools::tagList() of htmltools::htmlDependency objects: the font, the base sheet, then the tokens and the theme layer of theme_dep().

Examples

htmltools::tagList(
  base_dep(),
  shiny::textInput("name", "Name")
)

Block mark

Description

A block's mark is its glyph in its category colour on an 18% tint of that colour (design system, "The block's mark and bare mode"). It comes in four sizes: 32px in the dock header, 24px in list rows, 20px in the compact header and 16px in a tab. The glyph is half the mark plus 2px, and the corner radius a quarter of it.

Usage

block_mark(icon, category, size = 24, ...)

block_mark_svg(icon, category, size = 24, uri = FALSE)

category_color(category)

Arguments

icon

The block's glyph, as SVG markup: the icon column of blockr.core::block_metadata().

category

The block's category: the category column of blockr.core::block_metadata(). A category outside blockr.core::suggested_categories() takes the colour of "uncategorized".

size

The side of the mark in pixels. The HTML mark comes in the four sizes: 24 (a list row), 32 (the dock header), 20 (the compact header) and 16 (a tab). The SVG takes any size.

...

Further attributes of the mark, such as its tooltip.

uri

Return a ⁠data:⁠ URI of the SVG rather than the SVG itself.

Details

In HTML, block_mark() draws the mark with the .blockr-block-mark class, which colours it from the category's token, ⁠--blockr-category-<category>⁠. The mark on a Blockr.menu row is the same element at 24px. For a place that takes an image rather than markup, such as the DAG's canvas, block_mark_svg() draws the mark as a standalone SVG. An image cannot read the tokens, so the SVG carries its colour as a literal, which category_color() looks up from the tokens file. Both tints are translucent, so the mark sits at 18% on whatever surface is under it, in either scheme.

Value

A ⁠<span>⁠ htmltools::tag carrying controls_dep() from block_mark(). From block_mark_svg(), the SVG as htmltools::HTML(), or with uri = TRUE a ⁠data:⁠ URI of it, to use as an image's source. From category_color(), one hex colour per category.

Examples

meta <- blockr.core::block_metadata(blockr.core::new_dataset_block())

block_mark(meta$icon, meta$category, size = 32)
block_mark_svg(meta$icon, meta$category, size = 48, uri = TRUE)
category_color(c("input", "plot", "uncategorized"))

Build the HTML table preview for one page

Description

Pure presentation: renders an already-materialized page of data as the blockr table preview (header with column names, labels and type tags, pillar-formatted cells, NA / negative styling, footer with row range and prev / next pagination). Data access (sorting, pagination, lazy tables) is handled by table_page().

Usage

build_html_table(
  dat,
  total_rows,
  sort_state = NULL,
  ns = NULL,
  page = 1L,
  page_size = 5L,
  table_label = NULL,
  sort_input = NULL,
  page_input = NULL,
  has_more = NULL,
  cache = NULL
)

Arguments

dat

Materialized data frame holding only the rows of the current page.

total_rows

Total number of rows in the full result (drives the row-range text and pagination).

sort_state

List with elements col and dir ("asc", "desc", "na" or "none") or NULL.

ns

Optional namespace function used for the legacy default input ids when sort_input / page_input are not supplied.

page

Current page (1-based).

page_size

Rows per page.

table_label

Optional table-level label shown in the footer.

sort_input, page_input

Full (already namespaced) ids of the Shiny inputs receiving sort and page events. Supply per-instance ids when a session shows more than one preview; when NULL the legacy shared names blockr_table_sort / blockr_table_page are used.

has_more

Look-ahead flag used when total_rows is NA (remote / lazy tables that are never counted): TRUE signals that rows exist beyond the current page, which keeps the next button enabled and shows the "of many" row-range text instead of a known total.

cache

Optional environment memoizing the column widths across renders of the same result (keyed on the column names). Pass the same per-result cache used for table_page() so sorting and paging emit identical widths and the columns never reflow. When NULL, widths are recomputed from the current page on every render.

Value

A shiny::tagList() with the table preview, carrying the table_preview_dep() html dependency.


Estimate fixed-layout column widths

Description

Per-column width in px, from the header parts and the formatted cell strings, for tables rendered with table-layout: fixed (the blockr table preview and blockr.viz's html tables). Computing widths server-side keeps the layout independent of measuring the DOM - the measure-and-lock approach reads 0 whenever a render lands while a dock panel is hidden or mid-relayout, crushing the columns.

Usage

column_widths_px(
  col_names,
  col_labels = character(length(col_names)),
  col_types = character(length(col_names)),
  formatted = rep(list(character(0)), length(col_names)),
  col_na = lapply(formatted, is.na),
  wrap_names = FALSE
)

Arguments

col_names

Character vector of column header texts (plain text, strip any HTML before calling).

col_labels

Optional secondary header line per column (the preview's ADaM labels); "" for none.

col_types

Optional type-tag line per column ("<dbl>" etc.); "" for none.

formatted

List of character vectors: the display strings of each column's cells (only the rows being rendered).

col_na

List of logical vectors flagging cells rendered as the NA marker instead of their display string.

wrap_names

Measure each header by its longest word rather than its full length. A header is free to wrap (nothing pins it to one line), it simply never has to when the estimate buys it a full line - so a long title sets the column width outright and the table sprawls. Measuring the longest word instead gives the narrowest column that still never breaks a word, and the header wraps into it by itself. FALSE (the default) keeps the historical one-line estimate.

Details

Deliberately px, not font-relative units: ch tracks the width of the digit 0, which in some font stacks runs 40% narrower than average text, so ch-sized columns clip hard exactly where fonts differ. 8px/char at the 14px table font (the constant the header min-width heuristic used for years) over-estimates almost every UI font, so the estimate degrades to slightly roomy columns - or, at worst, mild ellipsis with the tooltip - never to crushed ones.

Value

Integer vector of pixel widths, one per column, including the two 16px cell paddings, clamped to [60, 320].


Shared block controls

Description

The JavaScript and CSS of the controls blockr blocks are built from: Blockr.Select (single, multi, list and menu), Blockr.Input (the code field with column and function completions), the Enter button of a field that commits on Enter, the required-empty cue, the checkbox, the segmented control, the gear tray, the tooltip (Blockr.tooltip), the menus of actions (Blockr.menu for those built in JavaScript, Blockr.actionMenu for those action_menu() builds in R), the dropdown dropdown() builds (Blockr.dropdown), the placement routine for floating panels (Blockr.place) and the small icons (Blockr.icons), all on the window.Blockr namespace, together with the rows, pills, labels, fields and buttons (.blockr-btn) they draw, and the Shiny side of the controls: the binding of the gear tray R renders (gear_tray()), and Shiny's selectize dropdowns on the dismiss stack.

Usage

controls_dep()

small_icon(name)

Arguments

name

The icon: "chevron", "remove" (a tag's x, 10px), "x" (a row's remove button, 14px), "grip" (a drag handle), "plus", "minus", "trash", "sliders", "check" (a menu's current item), "confirm" (a committed field, a picked option), "code", "gear", "eye" (a preview toggle), "dots" (a "…" menu's trigger), "info", "warning", "maximize" or "restore" (a dock group's maximise button), or "open" (a menu's tool that opens its list somewhere fuller).

Details

The small icons are not in blockr-ui.js: the dependency writes them into the page's head ahead of it, from the files small_icon() reads, so markup built in R and markup built in JavaScript draw one copy of each, and small_icon("gear") is Blockr.icons.gear. An icon draws in currentColor, so it takes the colour of the text around it, and is hidden from screen readers: the control that holds it carries the name, as tool_button() does.

Each icon is a file of its own, ⁠assets/icons/<name>.svg⁠ in the installed package, so JavaScript that runs without R, such as a package's test harness, can build Blockr.icons from the files: an icon is its file without its comment, which carries the icon's note, and without the whitespace between tags.

The stylesheets read the design tokens without fallbacks, so the dependency brings the tokens along, but not the theme layer that restyles the rest of the page: an app opts into that with theme_dep(). Attach it from a block's UI; dependencies are de-duplicated by name, so any number of blocks can.

The dependency names are the ones blockr.dplyr used while these files lived there (blockr-select-js, blockr-select-css, blockr-blocks-css, blockr-input-js, blockr-input-css), so a page carries one copy of each. Of two dependencies with one name, htmltools keeps the higher version, so while blockr.dplyr still ships its own copies, a page that has both uses blockr.dplyr's.

Value

For controls_dep(), an htmltools::tagList() of htmltools::htmlDependency objects, in load order.

For small_icon(), the icon's ⁠<svg>⁠ element, as htmltools::HTML().

Examples

shiny::fluidPage(
  controls_dep(),
  shiny::div(id = "cols"),
  shiny::tags$script(
    "Blockr.Select.multi(document.getElementById('cols'),",
    "  { options: ['mpg', 'cyl', 'disp'], selected: ['mpg'] });"
  )
)

tool_button(small_icon("gear"), "Settings")

Gear and settings tray

Description

The gear button and the tray it opens, for a block whose UI is rendered in R. The gear is the last thing in the header row, after any tools; the tray opens in flow under it, slides open and closed, and closes on the gear or Escape. Blockr.gearTray (in blockr-ui.js) does this; a Shiny input binding wires it up, so there is no inline script, and input[[id]] is TRUE while the tray is open. A tray drawn again (a renderUI()) keeps the state it had, for the session.

Usage

gear_tray(id, ..., tools = NULL, label = "Settings")

tray_section(title = NULL, ..., toggle = NULL, value = FALSE)

Arguments

id

The gear's id, an input id. The tray's is ⁠<id>_tray⁠.

...

For gear_tray(), tray_section()s, or fields for a tray of one section. For tray_section(), its fields: Shiny's inputs, or any other tag. Each goes in a cell of the tray's grid, which gives Shiny's inputs the design system's sizes: a number or a checkbox takes one column, a multi select the whole row, anything else two.

tools

Tool buttons (tool_button(), an action_menu()) that stand left of the gear in the header row.

label

The tray's accessible name.

title

The section title, or NULL. With toggle, the label of the checkbox that switches the section on.

toggle

The id of a checkbox that switches the section on, or NULL for a section that is always on.

value

Whether the toggle checkbox starts checked.

Details

The tray holds sections, each a title over a grid of fields. A tray with one section shows no title. A section switched on by a checkbox (toggle) keeps the checkbox before its title, and its fields show only while it is checked; the checkbox is an input of its own, input[[toggle]].

The fields are Shiny's own inputs, with updateOn = "blur" for shiny::textInput() and shiny::numericInput(), so their value changes on Enter or blur only. An open shiny::selectInput() closes on Escape before the tray does.

Value

gear_tray(): an htmltools::tagList() of the header row and the tray, carrying controls_dep(). tray_section(): a section, for gear_tray() only.

Examples

gear_tray(
  "gear",
  tray_section(
    "Format",
    shiny::selectInput("sep", "Separator", c(",", ";", "\t")),
    shiny::checkboxInput("header", "First row is a header", TRUE)
  ),
  tray_section(
    "Skip rows",
    shiny::numericInput("skip", "Rows", 0, updateOn = "blur"),
    toggle = "skip_on"
  )
)

Render a result as the HTML table preview

Description

html_table_render() returns a shiny::renderUI() that shows result as the paginated, sortable table preview. html_table_result() is the block-flavored wrapper that reads the page_size board option first.

Usage

html_table_render(result, session, page_size = 5L)

html_table_result(result, block, session)

html_table_display

Arguments

result

A data frame or lazy table (tbl_lazy).

session

The Shiny session.

page_size

Rows per page.

block

The block object (used to read board options).

Details

html_table_display is the blockr.core::tabular_display that wires this preview into data, parser and transform blocks. Opt in per app with options(blockr.tabular_display = blockr.ui::html_table_display); the display declares and triggers on a single board option, page_size, which the HTML table reads to paginate.

Sort and page state live in the browser and arrive via Shiny inputs whose ids are derived from the output name (via shiny::getCurrentOutputInfo()), so several previews in one module session stay independent. Sorting and pagination are resolved by table_page(): in-memory frames use a cached order index, lazy dbplyr tables are counted and paged in the database.

Value

A shiny::renderUI() object.


Strip a redundant ⁠:has(> *)⁠ guard from Shiny's recalculating fade

Description

Shiny 1.8.1 styles uiOutput() and conditionalPanel() containers display: contents once they hold children, so those children lay out as direct children of the parent (rstudio/shiny#3957). A pass-through container generates no box and can no longer carry the .recalculating fade, so Shiny pushes the opacity down to the children with a companion rule, ⁠div:where(.shiny-html-output):has(> *).recalculating > *⁠.

Usage

shiny_has_perf_dep()

Details

The companion rule is the one that costs. Its ⁠:has()⁠ sits in non-subject position with a universal subject, and Chrome answers that by restyling the whole document on every DOM insertion. On a 40-block dock board (6.4k elements, 5.5k CSS rules) that is 107ms of style recalculation for a single appended div, against 3ms once the guard is gone, and it grows linearly with element count – including the panels that are not on screen. It is paid by every block re-render, every keystroke in a picker and every streamed chat token. The display: contents rule beside it, whose ⁠:has()⁠ is in subject position, measures free and is left alone.

The guard is redundant on the companion. A selector shaped ⁠X:has(> *)... > *⁠ picks a descendant of X, so X necessarily has an element child wherever the subject exists. Removing it preserves both the pass-through layout and the fade.

Attach it once, at the page level. It is a separate dependency from theme_dep() so a host gets the fix whether or not it opts into blockr styling, and because Shiny de-duplicates dependencies by name, attaching it from more than one place is harmless.

Editing the CSSOM is the only route. The cost is bound to the selector being present in the active index, which Chrome consults before the cascade runs, so a rule stripped of every declaration, or aimed at a class present nowhere in the document, still costs full price. Shiny's documented escape hatch, overriding display on .shiny-html-output, addresses layout and leaves the cost untouched.

Value

An htmltools::htmlDependency.

Examples

shiny::fluidPage(shiny_has_perf_dep())

Skip the empty input messages Shiny sends after deferred inputs

Description

Shiny's input batcher checks whether a send is already queued but, since 1.7.5, never records that one is, so every deferred setInput queues its own send. The first carries all pending inputs and the rest send an empty update. The server runs a full input cycle for each: it walks every output of the session to update its hidden state, then flushes. Mounting a block card sets about a dozen inputs, so a dock view sends mostly empty messages while its cards mount, and the dock's own messages queue behind them.

Usage

shiny_input_batch_dep()

Details

The script wraps Shiny.shinyapp.sendInput to return early on an empty object. Nothing is lost: the inputs such a send would have carried went out with the first one. Once Shiny records the queued send itself (https://github.com/rstudio/shiny/issues/4436), an empty batch is left only where an event-priority input sent the batch while its send was queued, which is rare enough that the dependency can go.

Attach it once, at the page level, like shiny_has_perf_dep().

Value

An htmltools::htmlDependency.

Examples

shiny::fluidPage(shiny_input_batch_dep())

A keyboard shortcut hint

Description

Writes a shortcut once, for every platform: keys joined by "+", with "Mod" for Command on a Mac and Ctrl elsewhere. The hint carries both forms and blockr.ui shows the one that applies (design system, "Keyboard shortcuts"): "Mod+Shift+S" reads ⌘⇧S on a Mac and Ctrl+Shift+S elsewhere, and "Mod+Enter" reads ⌘↵ or Ctrl+↵. Put it in a menu row's meta slot (menu_item()) or after a button's label.

Usage

shortcut(keys)

Arguments

keys

The keys, such as "Mod+S". Named keys: Mod, Shift, Alt, Ctrl, Enter and Esc; any other single character is shown in upper case.

Value

A ⁠<span>⁠, with controls_dep() attached.

Examples

shortcut("Mod+Shift+S")

Fetch one page of a tabular result

Description

Resolves sorting and pagination for the table preview and returns a single materialized page. In-memory data frames are sorted via a cached order index on the sort column only (O(page) on page navigation); lazy dbplyr tables are counted and paged in the database via a ROW_NUMBER() window query, so the full table is never collected.

Usage

table_page(
  result,
  sort_state = NULL,
  page = 1L,
  page_size = 5L,
  cache = new.env(parent = emptyenv())
)

Arguments

result

A data frame or lazy table (tbl_lazy).

sort_state

List with elements col and dir ("asc", "desc", "na" or "none") or NULL for unsorted.

page

Requested page (1-based; clamped to the valid range).

page_size

Rows per page.

cache

Environment used to memoize the sort index (local) and the row count (lazy) across interactions on the same result. Callers should keep one cache per result; the default creates a fresh one.

Details

NA placement matches local dplyr::arrange() semantics on both backends (asc / desc put NA last, na puts NA first): SQL ⁠ORDER BY⁠ would put NULLs first, so the remote sort keys are normalized with an explicit is.na() key.

Value

A list with dat (materialized page as a data frame), total_rows and page (after clamping).


Table-preview assets

Description

table_preview_dep() returns the htmltools::htmlDependency carrying the table-preview CSS and JS; build_html_table() attaches it automatically. table_preview_css() returns the base CSS as an inline shiny::tags$style for hosts that layer delta CSS on top of it (e.g. blockr.viz's html table block); it reads the same file the dependency serves, so there is a single source.

Usage

table_preview_dep()

table_preview_css()

Value

An htmltools::htmlDependency or a shiny::tags$style element.


Shared blockr stylesheet

Description

The ⁠--blockr-*⁠ design tokens and the Bootstrap theme layer that the blockr packages style themselves from, as two dependencies. The tokens define the vocabulary in a ⁠:root⁠ block: the colour palette, the meaning tokens built on it (text, backgrounds, borders, status colours), type, radii, control heights and shadows. The file blockr-tokens-dark.css restates them under data-bs-theme="dark", the attribute blockr.core's dark-mode board option sets. On their own the tokens are inert: nothing is styled by defining a custom property. The theme layer, blockr-theme.css, applies them to the host app.

Usage

theme_dep()

Details

The theme layer is deliberately unscoped: it restyles Bootstrap typography, labels, form controls, selectize, buttons, tooltips, popovers and the DataTables chrome across the whole page. An app opts into it by attaching theme_dep() once, from its UI, as blockr.dock's board page does. A component brings only the tokens: with theme_dep() in the page the app gets the full look, and without it the controls of controls_dep() keep theirs and the app keeps its own.

Packages that read the tokens without attaching them write a literal fallback, as in ⁠var(--blockr-color-text-muted, #6b7280)⁠.

Value

An htmltools::tagList() of two htmltools::htmlDependency objects: the tokens, then the theme layer.

Examples

# The full look: the theme layer restyles the app's heading and field.
shiny::fluidPage(
  theme_dep(),
  controls_dep(),
  shiny::h4("Section"),
  shiny::textInput("name", "Name")
)

# The controls keep their look, and the app keeps its own.
shiny::fluidPage(
  controls_dep(),
  shiny::h4("Section"),
  shiny::textInput("name", "Name")
)

Tool button

Description

The design system's icon button: 26px, bare, the icon muted until hover. It has no text, so it carries its name as a tooltip (the light card of Blockr.tooltip) and as its accessible name.

Usage

tool_button(icon, tooltip, ...)

Arguments

icon

The icon, as a tag or htmltools::HTML().

tooltip

What the button does, in a few words ("Download").

...

Further attributes, such as id.

Value

A ⁠<button>⁠ htmltools::tag carrying controls_dep().

Examples

tool_button(htmltools::HTML("&darr;"), "Download")