Debian Codegraph @

R/input-select.R

raw
1 #' Create a select list input control
2 #'
3 #' Create a select list that can be used to choose a single or multiple items
4 #' from a list of values.
5 #'
6 #' By default, `selectInput()` and `selectizeInput()` use the JavaScript library
7 #' \pkg{selectize.js} (<https://selectize.dev/>) instead of
8 #' the basic select input element. To use the standard HTML select input
9 #' element, use `selectInput()` with `selectize=FALSE`.
10 #'
11 #' In selectize mode, if the first element in `choices` has a value of `""`, its
12 #' name will be treated as a placeholder prompt. For example:
13 #' `selectInput("letter", "Letter", c("Choose one" = "", LETTERS))`
14 #'
15 #' **Performance note:** `selectInput()` and `selectizeInput()` can slow down
16 #' significantly when thousands of choices are used; with legacy browsers like
17 #' Internet Explorer, the user interface may hang for many seconds. For large
18 #' numbers of choices, Shiny offers a "server-side selectize" option that
19 #' massively improves performance and efficiency; see
20 #' [this selectize article](https://shiny.rstudio.com/articles/selectize.html)
21 #' on the Shiny Dev Center for details.
22 #'
23 #' @inheritParams textInput
24 #' @param choices List of values to select from. If elements of the list are
25 #' named, then that name --- rather than the value --- is displayed to the
26 #' user. It's also possible to group related inputs by providing a named list
27 #' whose elements are (either named or unnamed) lists, vectors, or factors. In
28 #' this case, the outermost names will be used as the group labels (leveraging
29 #' the `<optgroup>` HTML tag) for the elements in the respective sublist. See
30 #' the example section for a small demo of this feature.
31 #' @param selected The initially selected value (or multiple values if `multiple
32 #' = TRUE`). If not specified then defaults to the first value for
33 #' single-select lists and no values for multiple select lists.
34 #' @param multiple Is selection of multiple items allowed?
35 #' @param selectize Whether to use \pkg{selectize.js} or not.
36 #' @param size Number of items to show in the selection box; a larger number
37 #' will result in a taller box. Not compatible with `selectize=TRUE`.
38 #' Normally, when `multiple=FALSE`, a select input will be a drop-down list,
39 #' but when `size` is set, it will be a box instead.
40 #' @return A select list control that can be added to a UI definition.
41 #'
42 #' @family input elements
43 #' @seealso [updateSelectInput()] [varSelectInput()]
44 #'
45 #' @examples
46 #' ## Only run examples in interactive R sessions
47 #' if (interactive()) {
48 #'
49 #' # basic example
50 #' shinyApp(
51 #' ui = fluidPage(
52 #' selectInput("variable", "Variable:",
53 #' c("Cylinders" = "cyl",
54 #' "Transmission" = "am",
55 #' "Gears" = "gear")),
56 #' tableOutput("data")
57 #' ),
58 #' server = function(input, output) {
59 #' output$data <- renderTable({
60 #' mtcars[, c("mpg", input$variable), drop = FALSE]
61 #' }, rownames = TRUE)
62 #' }
63 #' )
64 #'
65 #' # demoing group support in the `choices` arg
66 #' shinyApp(
67 #' ui = fluidPage(
68 #' selectInput("state", "Choose a state:",
69 #' list(`East Coast` = list("NY", "NJ", "CT"),
70 #' `West Coast` = list("WA", "OR", "CA"),
71 #' `Midwest` = list("MN", "WI", "IA"))
72 #' ),
73 #' textOutput("result")
74 #' ),
75 #' server = function(input, output) {
76 #' output$result <- renderText({
77 #' paste("You chose", input$state)
78 #' })
79 #' }
80 #' )
81 #' }
82 #'
83 #' @section Server value: A vector of character strings, usually of length
84 #' 1, with the value of the selected items. When `multiple=TRUE` and
85 #' nothing is selected, this value will be `NULL`.
86 #'
87 #' @export
88 selectInput <- function(inputId, label, choices, selected = NULL,
89 multiple = FALSE, selectize = TRUE, width = NULL,
90 size = NULL) {
91
92 selected <- restoreInput(id = inputId, default = selected)
93
94 # resolve names
95 choices <- choicesWithNames(choices)
96
97 # default value if it's not specified
98 if (is.null(selected)) {
99 if (!multiple) selected <- firstChoice(choices)
100 } else selected <- as.character(selected)
101
102 if (!is.null(size) && selectize) {
103 stop("'size' argument is incompatible with 'selectize=TRUE'.")
104 }
105
106 # create select tag and add options
107 selectTag <- tags$select(
108 id = inputId,
109 class = "shiny-input-select",
110 class = if (!selectize) "form-control",
111 size = size,
112 selectOptions(choices, selected, inputId, selectize)
113 )
114 if (multiple)
115 selectTag$attribs$multiple <- "multiple"
116
117 # return label and select tag
118 res <- div(
119 class = "form-group shiny-input-container",
120 style = css(width = validateCssUnit(width)),
121 shinyInputLabel(inputId, label),
122 div(selectTag)
123 )
124
125 if (!selectize) return(res)
126
127 selectizeIt(inputId, res, NULL, nonempty = !multiple && !("" %in% choices))
128 }
129
130 firstChoice <- function(choices) {
131 if (length(choices) == 0L) return()
132 choice <- choices[[1]]
133 if (is.list(choice)) firstChoice(choice) else choice
134 }
135
136 # Create tags for each of the options; use <optgroup> if necessary.
137 # This returns a HTML string instead of tags for performance reasons.
138 selectOptions <- function(choices, selected = NULL, inputId, perfWarning = FALSE) {
139 if (length(choices) >= 1000) {
140 warning("The select input \"", inputId, "\" contains a large number of ",
141 "options; consider using server-side selectize for massively improved ",
142 "performance. See the Details section of the ?selectizeInput help topic.",
143 call. = FALSE)
144 }
145
146 html <- mapply(choices, names(choices), FUN = function(choice, label) {
147 if (is.list(choice)) {
148 # If sub-list, create an optgroup and recurse into the sublist
149 sprintf(
150 '<optgroup label="%s">\n%s\n</optgroup>',
151 htmlEscape(label, TRUE),
152 selectOptions(choice, selected, inputId, perfWarning)
153 )
154
155 } else {
156 # If single item, just return option string
157 sprintf(
158 '<option value="%s"%s>%s</option>',
159 htmlEscape(choice, TRUE),
160 if (choice %in% selected) ' selected' else '',
161 htmlEscape(label)
162 )
163 }
164 })
165
166 HTML(paste(html, collapse = '\n'))
167 }
168
169 # need <optgroup> when choices contains sub-lists
170 needOptgroup <- function(choices) {
171 any(vapply(choices, is.list, logical(1)))
172 }
173
174 #' @rdname selectInput
175 #' @param ... Arguments passed to `selectInput()`.
176 #' @param options A list of options. See the documentation of \pkg{selectize.js}(<https://selectize.dev/docs/usage>)
177 #' for possible options (character option values inside [base::I()] will
178 #' be treated as literal JavaScript code; see [renderDataTable()]
179 #' for details).
180 #' @param width The width of the input, e.g. `'400px'`, or `'100%'`;
181 #' see [validateCssUnit()].
182 #' @note The selectize input created from `selectizeInput()` allows
183 #' deletion of the selected option even in a single select input, which will
184 #' return an empty string as its value. This is the default behavior of
185 #' \pkg{selectize.js}. However, the selectize input created from
186 #' `selectInput(..., selectize = TRUE)` will ignore the empty string
187 #' value when it is a single choice input and the empty string is not in the
188 #' `choices` argument. This is to keep compatibility with
189 #' `selectInput(..., selectize = FALSE)`.
190 #' @export
191 selectizeInput <- function(inputId, ..., options = NULL, width = NULL) {
192 selectizeIt(
193 inputId,
194 selectInput(inputId, ..., selectize = FALSE, width = width),
195 options
196 )
197 }
198
199 # given a select input and its id, selectize it
200 selectizeIt <- function(inputId, select, options, nonempty = FALSE) {
201 if (length(options) == 0) {
202 # For NULL and empty unnamed list, replace with an empty named list, so that
203 # it will get translated to {} in JSON later on.
204 options <- empty_named_list()
205 }
206
207 # Make sure accessibility plugin is included
208 if (!('selectize-plugin-a11y' %in% options$plugins)) {
209 options$plugins <- c(options$plugins, list('selectize-plugin-a11y'))
210 }
211
212 res <- checkAsIs(options)
213
214 deps <- list(selectizeDependency())
215
216 if ('drag_drop' %in% options$plugins) {
217 deps[[length(deps) + 1]] <- jqueryuiDependency()
218 }
219
220 # Insert script on same level as <select> tag
221 select$children[[2]] <- tagAppendChild(
222 select$children[[2]],
223 tags$script(
224 type = 'application/json',
225 `data-for` = inputId, `data-nonempty` = if (nonempty) '',
226 `data-eval` = if (length(res$eval)) HTML(toJSON(res$eval)),
227 HTML(toJSON(res$options))
228 )
229 )
230
231 attachDependencies(select, deps)
232 }
233
234
235 selectizeDependency <- function() {
236 bslib::bs_dependency_defer(selectizeDependencyFunc)
237 }
238
239 selectizeDependencyFunc <- function(theme) {
240 if (!is_bs_theme(theme)) {
241 return(selectizeStaticDependency(version_selectize))
242 }
243
244 bs_version <- bslib::theme_version(theme)
245
246 # It'd be cleaner to ship the JS in a separate, href-based,
247 # HTML dependency (which we currently do for other themable widgets),
248 # but DT, crosstalk, and maybe other pkgs include selectize JS/CSS
249 # in HTML dependency named selectize, so if we were to change that
250 # name, the JS/CSS would be loaded/included twice, which leads to
251 # strange issues, especially since we now include a 3rd party
252 # accessibility plugin https://github.com/rstudio/shiny/pull/3153
253 selectizeDir <- system_file(package = "shiny", "www/shared/selectize/")
254 script <- file.path(selectizeDir, selectizeScripts())
255
256 bslib::bs_dependency(
257 input = selectizeSass(bs_version),
258 theme = theme,
259 name = "selectize",
260 version = version_selectize,
261 cache_key_extra = get_package_version("shiny"),
262 .dep_args = list(script = script)
263 )
264 }
265
266 selectizeSass <- function(bs_version) {
267 selectizeDir <- system_file(package = "shiny", "www/shared/selectize/")
268 stylesheet <- file.path(
269 selectizeDir, "scss", paste0("selectize.bootstrap", bs_version, ".scss")
270 )
271 sass::sass_file(stylesheet)
272 }
273
274 selectizeStaticDependency <- function(version) {
275 htmlDependency(
276 "selectize",
277 version,
278 src = "www/shared/selectize",
279 package = "shiny",
280 stylesheet = "css/selectize.bootstrap3.css",
281 script = selectizeScripts()
282 )
283 }
284
285 selectizeScripts <- function() {
286 isMinified <- isTRUE(get_devmode_option("shiny.minified", TRUE))
287 paste0(
288 c(
289 "js/selectize",
290 "accessibility/js/selectize-plugin-a11y"
291 ),
292 if (isMinified) ".min.js" else ".js"
293 )
294 }
295
296
297 #' Select variables from a data frame
298 #'
299 #' Create a select list that can be used to choose a single or multiple items
300 #' from the column names of a data frame.
301 #'
302 #' By default, `varSelectInput()` and `selectizeInput()` use the
303 #' JavaScript library \pkg{selectize.js}
304 #' (<https://selectize.dev/>) to instead of the basic
305 #' select input element. To use the standard HTML select input element, use
306 #' `selectInput()` with `selectize=FALSE`.
307 #'
308 #' @inheritParams selectInput
309 #' @param data A data frame. Used to retrieve the column names as choices for a [selectInput()]
310 #' @return A variable select list control that can be added to a UI definition.
311 #'
312 #' @family input elements
313 #' @seealso [updateSelectInput()]
314 #'
315 #' @section Server value:
316 #' The resulting server `input` value will be returned as:
317 #'
318 #' * A symbol if `multiple = FALSE`. The `input` value should be
319 #' used with rlang's [rlang::!!()]. For example,
320 #' `ggplot2::aes(!!input$variable)`.
321 #' * A list of symbols if `multiple = TRUE`. The `input` value
322 #' should be used with rlang's [rlang::!!!()] to expand
323 #' the symbol list as individual arguments. For example,
324 #' `dplyr::select(mtcars, !!!input$variabls)` which is
325 #' equivalent to `dplyr::select(mtcars, !!input$variabls[[1]], !!input$variabls[[2]], ..., !!input$variabls[[length(input$variabls)]])`.
326 #'
327 #' @examples
328 #'
329 #' ## Only run examples in interactive R sessions
330 #' if (interactive()) {
331 #'
332 #' library(ggplot2)
333 #'
334 #' # single selection
335 #' shinyApp(
336 #' ui = fluidPage(
337 #' varSelectInput("variable", "Variable:", mtcars),
338 #' plotOutput("data")
339 #' ),
340 #' server = function(input, output) {
341 #' output$data <- renderPlot({
342 #' ggplot(mtcars, aes(!!input$variable)) + geom_histogram()
343 #' })
344 #' }
345 #' )
346 #'
347 #'
348 #' # multiple selections
349 #' \dontrun{
350 #' shinyApp(
351 #' ui = fluidPage(
352 #' varSelectInput("variables", "Variable:", mtcars, multiple = TRUE),
353 #' tableOutput("data")
354 #' ),
355 #' server = function(input, output) {
356 #' output$data <- renderTable({
357 #' if (length(input$variables) == 0) return(mtcars)
358 #' mtcars %>% dplyr::select(!!!input$variables)
359 #' }, rownames = TRUE)
360 #' }
361 #' )}
362 #'
363 #' }
364 #' @export
365 varSelectInput <- function(
366 inputId, label, data, selected = NULL,
367 multiple = FALSE, selectize = TRUE, width = NULL,
368 size = NULL
369 ) {
370 # no place holders
371 choices <- colnames(data)
372
373 selectInputVal <- selectInput(
374 inputId = inputId,
375 label = label,
376 choices = choices,
377 selected = selected,
378 multiple = multiple,
379 selectize = selectize,
380 width = width,
381 size = size
382 )
383
384 # set the select tag class to be "symbol"
385 selectClass <- selectInputVal$children[[2]]$children[[1]]$attribs$class
386 if (is.null(selectClass)) {
387 newClass <- "symbol"
388 } else {
389 newClass <- paste(selectClass, "symbol", sep = " ")
390 }
391 selectInputVal$children[[2]]$children[[1]]$attribs$class <- newClass
392
393 selectInputVal
394 }
395
396
397
398 #' @rdname varSelectInput
399 #' @param ... Arguments passed to `varSelectInput()`.
400 #' @param options A list of options. See the documentation of \pkg{selectize.js}(<https://selectize.dev/docs/usage>)
401 #' for possible options (character option values inside [base::I()] will
402 #' be treated as literal JavaScript code; see [renderDataTable()]
403 #' for details).
404 #' @param width The width of the input, e.g. `'400px'`, or `'100%'`;
405 #' see [validateCssUnit()].
406 #' @note The variable selectize input created from `varSelectizeInput()` allows
407 #' deletion of the selected option even in a single select input, which will
408 #' return an empty string as its value. This is the default behavior of
409 #' \pkg{selectize.js}. However, the selectize input created from
410 #' `selectInput(..., selectize = TRUE)` will ignore the empty string
411 #' value when it is a single choice input and the empty string is not in the
412 #' `choices` argument. This is to keep compatibility with
413 #' `selectInput(..., selectize = FALSE)`.
414 #' @export
415 varSelectizeInput <- function(inputId, ..., options = NULL, width = NULL) {
416 selectizeIt(
417 inputId,
418 varSelectInput(inputId, ..., selectize = FALSE, width = width),
419 options
420 )
421 }