brainstorming
brainstorming
You MUST use this before any creative work - creating features, building components, adding functionality, modifying behavior, or planning anything new, in software or out of it (a talk, a business, a renovation).
build-shiny-moduleBuild reusable Shiny modules with proper namespace isolation using NS(). Covers module UI/server pairs, reactive return values, inter-module communication, and nested module composition. Use when extracting a reusable component from a growing Shiny app, building a UI widget used in multiple places, encapsulating complex reactive logic behind a clean interfa…
Independent GitHub snapshot · Automated classification · Original documentation governs
Reusable Shiny UI/server module pairs w/ proper namespace isolation, reactive comm, composability.
Before code, define accepts + returns:
Module: data_filter
Inputs: reactive dataset, column names to filter on
Outputs: reactive filtered dataset
UI: filter controls (selectInput, sliderInput, dateRangeInput)
→ Clear contract w/ reactive ins, reactive outs, UI elements.
If err: Interface unclear → module too broad. Split into smaller, single responsibilities.
#' Data Filter Module UI
#'
#' @param id Module namespace ID
#' @return A tagList of filter controls
#' @export
dataFilterUI <- function(id) {
ns <- NS(id)
tagList(
selectInput(
ns("column"),
"Filter column",
choices = NULL
),
uiOutput(ns("filter_control")),
actionButton(ns("apply"), "Apply Filter", class = "btn-primary")
)
}
Key rules:
<name>UI conventionidns <- NS(id) at topinputId + outputId w/ ns()tagList() for flexible placement→ UI fn creates namespaced in/out elements.
If err: IDs collide when module used twice → check every ID wrapped w/ ns(). Common miss: IDs inside renderUI() or uiOutput() — also need ns().
#' Data Filter Module Server
#'
#' @param id Module namespace ID
#' @param data Reactive expression returning a data frame
#' @param columns Character vector of filterable column names
#' @return Reactive expression returning the filtered data frame
#' @export
dataFilterServer <- function(id, data, columns) {
moduleServer(id, function(input, output, session) {
ns <- session$ns
# Update column choices when data changes
observeEvent(data(), {
available <- intersect(columns, names(data()))
updateSelectInput(session, "column", choices = available)
})
# Dynamic filter control based on selected column
output$filter_control <- renderUI({
req(input$column)
col_data <- data()[[input$column]]
if (is.numeric(col_data)) {
sliderInput(
ns("value_range"),
"Range",
min = min(col_data, na.rm = TRUE),
max = max(col_data, na.rm = TRUE),
value = range(col_data, na.rm = TRUE)
)
} else {
selectInput(
ns("value_select"),
"Values",
choices = unique(col_data),
multiple = TRUE,
selected = unique(col_data)
)
}
})
# Return filtered data as a reactive
filtered <- eventReactive(input$apply, {
req(input$column)
col <- input$column
df <- data()
if (is.numeric(df[[col]])) {
req(input$value_range)
df[df[[col]] >= input$value_range[1] &
df[[col]] <= input$value_range[2], ]
} else {
req(input$value_select)
df[df[[col]] %in% input$value_select, ]
}
}, ignoreNULL = FALSE)
return(filtered)
})
}
Key rules:
<name>Server conventionidmoduleServer(id, function(input, output, session) { ... })session$ns for dynamic UI inside server→ Server fn processes ins + returns reactive out.
If err: Reactives don't update → check ins from dynamic UI use session$ns (not outer ns). Module returns NULL → ensure return() is last expr in moduleServer().
# In app_ui.R or ui
ui <- page_sidebar(
title = "Analysis App",
sidebar = sidebar(
dataFilterUI("filter1")
),
card(
DT::dataTableOutput("table")
)
)
# In app_server.R or server
server <- function(input, output, session) {
# Raw data source
raw_data <- reactive({ mtcars })
# Call module — capture its return value
filtered_data <- dataFilterServer(
"filter1",
data = raw_data,
columns = c("cyl", "mpg", "hp", "wt")
)
# Use the module's returned reactive
output$table <- DT::renderDataTable({
filtered_data()
})
}
→ Module appears in UI, returned reactive flows into downstream outs.
If err: UI doesn't render → verify id matches between UI + server calls. Returned reactive NULL → check server fn actually returns value.
Modules containing other modules:
analysisUI <- function(id) {
ns <- NS(id)
tagList(
dataFilterUI(ns("filter")),
plotOutput(ns("plot"))
)
}
analysisServer <- function(id, data) {
moduleServer(id, function(input, output, session) {
# Call inner module with namespaced ID
filtered <- dataFilterServer("filter", data = data, columns = names(data()))
output$plot <- renderPlot({
req(filtered())
plot(filtered())
})
return(filtered)
})
}
Key: UI nests w/ ns("inner_id"). Server calls w/ just "inner_id" — moduleServer handles namespace chaining.
→ Inner module renders correctly w/in outer's namespace.
If err: Inner UI doesn't appear → likely forgot ns() around inner ID in outer UI. Server comm breaks → check inner ID matches (no ns() in server call).
# Quick test app for the module
if (interactive()) {
shiny::shinyApp(
ui = fluidPage(
dataFilterUI("test"),
DT::dataTableOutput("result")
),
server = function(input, output, session) {
data <- reactive(iris)
filtered <- dataFilterServer("test", data, names(iris))
output$result <- DT::renderDataTable(filtered())
}
)
}
→ Module works correctly in minimal test app.
If err: Fails in isolation but works in full app (or reverse) → implicit deps on global vars or parent session state.
id as first arg + uses NS(id)ns()moduleServer(id, function(input, output, session) { ... })session$ns for IDsns() in renderUI(): Dynamic UI inside server must use session$ns — outer ns not available in moduleServer()reactive(data) not dataid in UI call must exactly match id in server callreturn() reactive. Silent bugns("inner_id"). Server: just "inner_id". Mixing → double-wrapping or missing prefixesscaffold-shiny-app — set up app structure before adding modulestest-shiny-app — test modules w/ testServer() unit testsdesign-shiny-ui — bslib layout + theming for module UIsoptimize-shiny-performance — cache + async patterns w/in modules