спрятать кнопку в теле щита, пока таблица не будет отображена - PullRequest
0 голосов
/ 06 апреля 2019

У меня есть блестящее приложение, в которое я загружаю файл и отображается таблица. Я хочу скрыть кнопку в теле, пока таблица не будет отображена.Эта кнопка собирается сохранить фильтры в файл.Я использую shinySaveButton из shinyFiles, потому что я хочу, чтобы пользователь перемещался до папки и выбирал пользовательское имя файла

Вот пользовательский интерфейс

header <- dashboardHeader()

sidebar <- dashboardSidebar(
sidebarUserPanel("Test"),
sidebarMenu(
  id = "tabs",
  menuItem("Archivo variantes", tabName = "fileupload", icon = icon("table")),
  conditionalPanel("input.tabs == 'fileupload' ",
  shinyFilesButton("file", "Choose a file" , multiple = FALSE,
               title = "Please select a file:",
               buttonType = "default", class = NULL)#,
  )
 )
)

body <- dashboardBody(
  tags$style(type="text/css",
   ".shiny-output-error { visibility: hidden; }",
   ".shiny-output-error:before { visibility: hidden; }"),

  shinyjs::useShinyjs(),

  tabItems(
    tabItem(tabName = "fileupload",
        fluidRow(column(12,
          div(DT::dataTableOutput('tabla') %>% withSpinner(color="#0dc5c1"),  style = 'overflow-x: auto'))),
        fluidRow(column(2, offset = 0,
         shinySaveButton('save', 'Save filters', 'Save as...') )))

 )
)

ui <- dashboardPage(header, sidebar, body)

А вот сервер

## Server side
server = function(input, output, session) {
  options(shiny.maxRequestSize=100*1024^2)

  if (!exists("default_search_columns")) default_search_columns <- NULL

  volumes = getVolumes()
  volumes <- c(Home = fs::path_home(), "R Installation" = R.home(), getVolumes()())

   file_selected <- reactive({
     shinyFileChoose(input, "file", roots = volumes, session = session)
     if (is.null(input$file))
       return(NULL) 
     print(parseFilePaths(volumes, input$file)$datapath)
     return(parseFilePaths(volumes, input$file)$datapath)
   })   

   contents <- reactive({
     if (is.null(file_selected()))
      return()
     print(file_selected())
     df <- read.delim(file_selected(), header = TRUE, stringsAsFactors=FALSE, as.is=TRUE)
     return(tidyr::separate_rows(df, Gene.refGene, sep = ";"))
   })

# Reactive function creating the DT output object
 output$tabla <- DT::renderDataTable({        
   if(is.null(contents()))
     return()
   datos <- contents()

   DT::datatable(datos, 
    rownames = FALSE,
            style = 'bootstrap', 
            class = 'compact cell-border stripe hover', 
            filter = list(position = 'top', clear = FALSE), 
            escape = FALSE,
            extensions = c('Buttons', "FixedHeader", "Scroller"),
             options = list(
              stateSave = FALSE,
              autoWidth = TRUE,
              search = list(regex = TRUE, caseInsensitive = TRUE),
              initComplete = JS(
                  "function(settings, json) {",
                  "$(this.api().table().header()).css({'font-size': '12px'});",
                  "}"),
              scroller = TRUE,
              scrollX = TRUE,
              scrollY = "600px",
              deferRender=TRUE,
              buttons = list('colvis', list(
                    extend = 'collection',
                    buttons = list(list(extend='csv',
                                        filename = 'results'),
                                   list(extend='excel',
                                        filename = 'results')),
                    text = 'Download'
                    )),
              FixedHeader = TRUE
            ), 
            callback = JS('table.page(3).draw(false); "setTimeout(function() { table.draw(true); }, 300);"')) %>% formatStyle(columns = colnames(.$x$data), `font-size` = "12px")

})


filtros <- eventReactive(input$tabla_search_columns, {
  str(input$tabla_search_columns)
  return(input$tabla_search_columns)
})

observeEvent(input$save, 
{
observe(
    if(is.null(input$tabla)) {
      shinyjs::disable("save")
    } else { shinyjs::enable("save") }
  )
})

observe({ 
  volumes <- getVolumes()
  volumes <- c(Home = fs::path_home(), "R Installation" = R.home(), getVolumes()())
  shinyFileSave(input, "save", roots=volumes, session=session) 
  fileinfo <- parseSavePath(volumes, input$save) 
  if (nrow(fileinfo) > 0) { 
    write.table(filtros(), fileinfo$datapath, row.names = FALSE, col.names=FALSE, quote=TRUE, sep="\t") 
  }  
})

} Блестящее приложение (пользовательский интерфейс, сервер)

Я пытаюсь использовать shinyjs::disable и shinyjs::enable, но не могу заставить его работать, кнопка save filters отображается раньшевыбрав файл.И я хочу быть скрытым, пока таблица не будет обработана

Любая помощь будет оценена

1 Ответ

0 голосов
/ 12 июня 2019

Shiny вызывает событие JavaScript shiny:value при визуализации вывода.Таким образом, вы можете отключить кнопку при инициализации приложения, и с помощью этого события JS вы можете включить кнопку при каждом отображении таблицы.Вот минимальный пример:

library(shiny)
library(shinyFiles)

js <- paste(
  "$(document).ready(function(){",
  "  $('#save').prop('disabled', true);", # disable the 'save' button
  "});",
  "$(document).on('shiny:value', function(e){",
  "  if(e.name === 'table'){", # if 'table' is rendered
  "    $('#save').prop('disabled', false);", # then enable the 'save' button
  "  }",
  "});"
  , sep = "\n"
)

ui <- fluidPage(
  tags$head(tags$script(HTML(js))),
  shinySaveButton("save", "Save", "Save file"), 
  actionButton("go", "Render table"), 
  tableOutput("table")
)

server <- function(input, output){
  output[["table"]] <- renderTable({
    req(input[["go"]]>0)
    iris[1:4, ]
  })
}

shinyApp(ui, server)

enter image description here

...