build-shiny-module
关于
This skill helps developers build reusable Shiny modules with proper namespace isolation using NS(). It covers creating UI/server pairs, handling reactive return values, and enabling inter-module communication and nested composition. Use it when extracting reusable components from growing apps, encapsulating complex logic, or composing larger applications from testable units.
快速安装
Claude Code
推荐npx skills add pjt222/agent-almanac -a claude-code/plugin add https://github.com/pjt222/agent-almanacgit clone https://github.com/pjt222/agent-almanac.git ~/.claude/skills/build-shiny-module在 Claude Code 中复制并粘贴此命令以安装该技能
技能文档
Build Shiny Module
Reusable Shiny UI/server module pairs w/ proper namespace isolation, reactive comm, composability.
Use When
- Extract reusable component from growing Shiny app
- UI widget used in many places
- Encapsulate complex reactive logic behind clean interface
- Compose larger apps from smaller testable units
In
- Required: Module purpose + fn desc
- Required: In/out contract (what module receives + returns)
- Optional: Whether module nests others (default: no)
- Optional: Framework ctx (golem, rhino, vanilla)
Do
Step 1: Define Interface
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.
Step 2: Module UI Fn
#' 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:
- Fn name:
<name>UIconvention - First arg always
id ns <- NS(id)at top- Wrap every
inputId+outputIdw/ns() - Return
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().
Step 3: Module Server Fn
#' 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:
- Fn name:
<name>Serverconvention - First arg always
id - Additional args = reactive exprs or static values
- Use
moduleServer(id, function(input, output, session) { ... }) - Use
session$nsfor dynamic UI inside server - Return reactive values explicitly
→ 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().
Step 4: Wire Module into Parent
# 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.
Step 5: Nested Modules (Optional)
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).
Step 6: Test in Isolation
# 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.
Check
- UI fn accepts
idas first arg + usesNS(id) - Every in/out ID in UI wrapped w/
ns() - Server uses
moduleServer(id, function(input, output, session) { ... }) - Dynamic UI in server uses
session$nsfor IDs - Module instantiable many times w/o ID collisions
- Reactive returns accessible to parent
- Works in minimal standalone test
Traps
- Forget
ns()inrenderUI(): Dynamic UI inside server must usesession$ns— outernsnot available inmoduleServer() - Non-reactive data: Args that change over time must be reactive. Pass
reactive(data)notdata - ID mismatch:
idin UI call must exactly matchidin server call - Not returning reactives: Module computes something parent needs → must
return()reactive. Silent bug - Nested namespace: UI:
ns("inner_id"). Server: just"inner_id". Mixing → double-wrapping or missing prefixes
→
scaffold-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
GitHub 仓库
相关推荐技能
content-collections
元Content Collections 是一个 TypeScript 优先的构建工具,可将本地 Markdown/MDX 文件转换为类型安全的数据集合。它专为构建博客、文档站和内容密集型 Vite+React 应用而设计,提供基于 Zod 的自动模式验证。该工具涵盖从 Vite 插件配置、MDX 编译到生产环境部署的完整工作流。
polymarket
元这个Claude Skill为开发者提供完整的Polymarket预测市场开发支持,涵盖API调用、交易执行和市场数据分析。关键特性包括实时WebSocket数据流,可监控实时交易、订单和市场动态。开发者可用它构建预测市场应用、实施交易策略并集成实时市场预测功能。
creating-opencode-plugins
元该Skill帮助开发者创建OpenCode插件,用于接入命令、文件、LSP等25+种事件。它提供了插件结构、事件API规范和JavaScript/TypeScript实现模式,适合需要拦截操作、扩展功能或自定义事件处理的场景。开发者可通过它快速构建响应式模块来增强OpenCode AI助手的能力。
sglang
元SGLang是一个专为LLM设计的高性能推理框架,特别适用于需要结构化输出的场景。它通过RadixAttention前缀缓存技术,在处理JSON、正则表达式、工具调用等具有重复前缀的复杂工作流时,能实现极速生成。如果你正在构建智能体或多轮对话系统,并追求远超vLLM的推理性能,SGLang是理想选择。
