MCP HubMCP Hub
스킬 목록으로 돌아가기

build-shiny-module

pjt222
업데이트됨 2 days ago
5 조회
17
2
17
GitHub에서 보기
메타reactaitestingdesign

정보

이 스킬은 개발자가 NS()를 사용하여 적절한 네임스페이스 격리를 갖춘 재사용 가능한 Shiny 모듈을 구축하도록 돕습니다. 모듈 UI/서버 쌍 생성, 반응형 반환 값 처리, 모듈 간 통신 및 중첩 구성을 다룹니다. 성장하는 앱에서 재사용 가능한 구성 요소를 추출하거나, 복잡한 로직을 캡슐화하거나, 테스트 가능한 단위들로 더 큰 애플리케이션을 구성할 때 사용하세요.

빠른 설치

Claude Code

추천
기본
npx skills add pjt222/agent-almanac -a claude-code
플러그인 명령대체
/plugin add https://github.com/pjt222/agent-almanac
Git 클론대체
git clone https://github.com/pjt222/agent-almanac.git ~/.claude/skills/build-shiny-module

Claude Code에서 이 명령을 복사하여 붙여넣어 스킬을 설치하세요

문서

Build Shiny Module

Create reusable Shiny UI/server module pairs with proper namespace isolation, reactive communication, composability.

When Use

  • Extracting reusable component from growing Shiny app
  • Building UI widget used in multiple places
  • Encapsulating complex reactive logic behind clean interface
  • Composing larger applications from smaller, testable units

Inputs

  • Required: Module purpose and functionality description
  • Required: Input/output contract (what module receives and returns)
  • Optional: Whether module nests other modules (default: no)
  • Optional: Framework context (golem, rhino, vanilla)

Steps

Step 1: Define the Module Interface

Before writing code, define what module accepts and returns:

Module: data_filter
Inputs: reactive dataset, column names to filter on
Outputs: reactive filtered dataset
UI: filter controls (selectInput, sliderInput, dateRangeInput)

Got: Clear contract specifying reactive inputs, reactive outputs, UI elements.

If fail: Interface unclear? Module probably too broad. Split into smaller modules with single responsibilities.

Step 2: Create the Module UI Function

#' 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:

  • Function name follows <name>UI convention
  • First argument is always id
  • Create ns <- NS(id) at top
  • Wrap every inputId and outputId with ns()
  • Return tagList() to allow flexible placement

Got: UI function creating namespaced input/output elements.

If fail: IDs collide when using module twice? Check every ID wrapped with ns(). Common miss: IDs inside renderUI() or uiOutput() — these need ns() too.

Step 3: Create the Module Server Function

#' 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:

  • Function name follows <name>Server convention
  • First argument is always id
  • Additional arguments are reactive expressions or static values
  • Use moduleServer(id, function(input, output, session) { ... })
  • Use session$ns for dynamic UI created inside server
  • Return reactive values explicitly

Got: Server function processing inputs and returning reactive output.

If fail: Reactive values don't update? Check inputs from dynamic UI use session$ns (not outer ns). Module returns NULL? Ensure return() is last expression inside moduleServer().

Step 4: Wire the Module into the Parent App

# 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()
  })
}

Got: Module appears in UI and its returned reactive flows into downstream outputs.

If fail: Module UI doesn't render? Verify id string matches between UI and server calls. Returned reactive is NULL? Check server function actually returns value.

Step 5: Compose Nested Modules (Optional)

For 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 rule: In UI, nest with ns("inner_id"). In server, call with just "inner_id"moduleServer handles namespace chaining.

Got: Inner module renders correctly within outer module's namespace.

If fail: Inner module's UI doesn't appear? Likely forgot ns() around inner module's ID in outer UI function. Server communication breaks? Check inner module ID matches (no ns() in server call).

Step 6: Test the Module 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())
    }
  )
}

Got: Module works correctly in minimal test app.

If fail: Module fails in isolation but works in full app (or vice versa)? Check for implicit dependencies on global variables or parent session state.

Checks

  • Module UI function accepts id as first argument, uses NS(id)
  • Every input/output ID in UI wrapped with ns()
  • Module server uses moduleServer(id, function(input, output, session) { ... })
  • Dynamic UI in server uses session$ns for IDs
  • Module can be instantiated multiple times without ID collisions
  • Reactive return values accessible to parent app
  • Module works in minimal standalone test app

Pitfalls

  • Forgetting ns() in renderUI(): Dynamic UI created inside server must use session$ns — outer ns not available inside moduleServer().
  • Passing non-reactive data: Module arguments that change over time must be reactive expressions. Pass reactive(data) not data.
  • ID mismatch: id string in UI call must exactly match id in server call.
  • Not returning reactives: Module computes something parent needs? Must return() a reactive. Forgetting this is silent bug.
  • Namespace in nested modules: In UI: ns("inner_id"). In server: just "inner_id". Mixing these up causes namespace double-wrapping or missing prefixes.

See Also

  • scaffold-shiny-app — set up app structure before adding modules
  • test-shiny-app — test modules with testServer() unit tests
  • design-shiny-ui — bslib layout and theming for module UIs
  • optimize-shiny-performance — cache and async patterns within modules

GitHub 저장소

pjt222/agent-almanac
경로: i18n/caveman/skills/build-shiny-module
0
agentsagentskillsai-assisted-developmentclaude-codeskillsteams

연관 스킬

content-collections

메타

이 스킬은 콘텐츠 콜렉션(Content Collections)을 위한 프로덕션 검증된 설정을 제공합니다. 콘텐츠 콜렉션은 Markdown/MDX 파일을 Zod 검증이 포함된 타입 안전한 데이터 콜렉션으로 변환해주는 TypeScript 최우선 도구입니다. 블로그, 문서 사이트 또는 콘텐츠 중심의 Vite + React 애플리케이션을 구축할 때 타입 안전성과 자동 콘텐츠 검증을 보장하기 위해 사용하세요. Vite 플러그인 구성과 MDX 컴파일부터 배포 최적화 및 스키마 검증에 이르기까지 모든 것을 다룹니다.

스킬 보기

polymarket

메타

이 스킬은 개발자들이 Polymarket 예측 시장 플랫폼을 활용한 애플리케이션을 구축할 수 있도록 지원하며, 거래 및 시장 데이터를 위한 API 통합 기능을 포함합니다. 또한 WebSocket을 통한 실시간 데이터 스트리밍을 제공하여 실시간 거래와 시장 활동을 모니터링할 수 있습니다. 이를 통해 거래 전략을 구현하거나 실시간 시장 업데이트를 처리하는 도구를 생성하는 데 활용할 수 있습니다.

스킬 보기

creating-opencode-plugins

메타

이 스킬은 개발자들이 명령어, 파일, LSP 작업 등 25개 이상의 이벤트 유형에 연결되는 OpenCode 플러그인을 만들 수 있도록 돕습니다. JavaScript/TypeScript 모듈을 위한 플러그인 구조, 이벤트 API 명세, 구현 패턴을 제공합니다. OpenCode AI 어시스턴트의 라이프사이클을 사용자 정의 이벤트 기반 로직으로 가로채거나, 모니터링하거나, 확장해야 할 때 사용하세요.

스킬 보기

sglang

메타

SGLang은 RadixAttention 프리픽스 캐싱을 활용하여 JSON, 정규식, 에이전트 워크플로우를 위한 고속 구조화 생성에 특화된 고성능 LLM 서빙 프레임워크입니다. 특히 반복되는 프리픽스가 있는 작업에서 상당히 빠른 추론 속도를 제공하여 복잡한 구조화 출력 및 다중 턴 대화에 이상적입니다. 제약 디코딩이 필요하거나 광범위한 프리픽스 공유가 있는 애플리케이션을 구축할 때는 vLLM과 같은 대안보다 SGLang을 선택하십시오.

스킬 보기