kintany
kintany

Reputation: 541

shinyFiles folder selection: display the default folder

I need to display selected folder for Shiny users, and I asked here how to do this (Display selected folder path in Shiny). It works but now I can't figure out how to show the default folder (for example, current directory) before the selection was made.

library(shiny)
library(shinyFiles)

ui <- fluidPage( # Application title
  mainPanel(
    shinyDirButton("dir", "Input directory", "Upload"),
    verbatimTextOutput("dir", placeholder = TRUE)  
  ))

server <- function(input, output) {
  shinyDirChoose(
    input,
    'dir',
    roots = c(home = '~'),
    filetypes = c('', 'txt', 'bigWig', "tsv", "csv", "bw")
  )

  dir <- reactive(input$dir)
  output$dir <- renderText({  
    parseDirPath(c(home = '~'), dir())
  })
## change smth here... if output$dir is null, display getwd() but it doesn't work

  observeEvent(ignoreNULL = TRUE,
               eventExpr = {
                 input$dir
               },
               handlerExpr = {
                 home <- normalizePath("~")
                 datapath <<-
                   file.path(home, paste(unlist(dir()$path[-1]), collapse = .Platform$file.sep))
               })
}

# Run the application
shinyApp(ui = ui, server = server)

I can think only of a conditional panel displaying some text if the folder wasn't selected. But I guess there should a better way to do this. Thank you!

Upvotes: 2

Views: 6492

Answers (1)

Tonio Liebrand
Tonio Liebrand

Reputation: 17689

Concerning "beyond" displaying you could save the datapath variable in a reactiveValue and set the working directory as the default:

global <- reactiveValues(datapath = getwd())

And the app:

library(shiny)
library(shinyFiles)

ui <- fluidPage( # Application title
  mainPanel(
    shinyDirButton("dir", "Input directory", "Upload"),
    verbatimTextOutput("dir", placeholder = TRUE)  
  ))

server <- function(input, output) {
  shinyDirChoose(
    input,
    'dir',
    roots = c(home = '~'),
    filetypes = c('', 'txt', 'bigWig', "tsv", "csv", "bw")
  )

  global <- reactiveValues(datapath = getwd())

  dir <- reactive(input$dir)

  output$dir <- renderText({
      global$datapath
  })

  observeEvent(ignoreNULL = TRUE,
               eventExpr = {
                 input$dir
               },
               handlerExpr = {
                 home <- normalizePath("~")
                 global$datapath <-
                   file.path(home, paste(unlist(dir()$path[-1]), collapse = .Platform$file.sep))
               })
}

# Run the application
shinyApp(ui = ui, server = server)

Upvotes: 3

Related Questions