cecilialee
2/13/2018 - 10:38 AM

Simple module in Shiny

Simple module in Shiny. #r #shiny

# UI ==========================================================================

confirmModalInput = function(id) {
  ns <- NS(id)
  
  tagList(
    actionButton(ns("show"), "Show modal dialog"),
    verbatimTextOutput(ns("print"))
  )
}


# Server ======================================================================

confirmModalServer = function(input, output, session) {
  ns <- session$ns
  
  # Create object to store reactive values
  vals <- reactiveValues(
    txt = NULL,
    error_msg = NULL,
    print = FALSE
  )
  
  # Create modal
  popupModal <- function() {
    modalDialog(
      textInput(ns("txt"), "Write something"),
      
      textOutput(ns("skip_error_msg")),
      
      footer = tagList(
        modalButton("Cancel"),
        actionButton(ns("ok"), "OK")
      )
    )
  }
  
  # Show modal when button is clicked
  observeEvent(input$show, {
    vals$error_msg <- NULL
    showModal(popupModal())
  })
  
  # Validate submission
  observeEvent(input$ok, {
    vals$txt <- input$txt
    
    if (!is.null(vals$txt) && nzchar(vals$txt)) {
      removeModal()
      vals$print <- TRUE
    } else {
      vals$error_msg <- "You did not input anything."
    }
  })
  
  # Output error message
  output$skip_error_msg <- renderText({
    vals$error_msg
  })
  
  # Output inputted text
  output$print <- renderPrint({
    if (vals$print) {
      vals$txt
    } else {
      NULL
    }
  })
}
# UI ==========================================================================

textModalInput = function(id) {
  ns <- NS(id)
  
  tagList(
    textInput(ns("txt"), "Write something")
  )
}

# Server ======================================================================

textModalServer = function(input, output, session) {
  mytext <- reactive({
    input$txt
  })
  return(mytext)
}
library(shiny)
source("modules/module_1.R")
source("modules/module_2.R")

ui = basicPage(
  # module 1
  strong("Module 1", style = "color:steelblue;"),
  textModalInput("txt_modal"),
  textOutput("txt"),
  
  # module 2
  strong("Module 2", style = "color:steelblue;"),
  br(),
  confirmModalInput("confirm_modal")
)

server = function(input, output, session) {
  # module 1
  confirm_txt <- callModule(textModalServer, "txt_modal")
  
  output$txt <- renderText({
    confirm_txt()
  })
  
  # module 2
  callModule(confirmModalServer, "confirm_modal")
}

shinyApp(ui, server)