-
-
Notifications
You must be signed in to change notification settings - Fork 44
/
Copy pathmodules.R
508 lines (476 loc) · 18.6 KB
/
modules.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
setOldClass("teal_module")
setOldClass("teal_modules")
#' Create `teal_module` and `teal_modules` objects
#'
#' @description
#' `r lifecycle::badge("stable")`
#' Create a nested tab structure to embed modules in a `teal` application.
#'
#' @details
#' `module()` creates an instance of a `teal_module` that can be placed in a `teal` application.
#' `modules()` shapes the structure of a the application by organizing `teal_module` within the navigation panel.
#' It wraps `teal_module` and `teal_modules` objects in a `teal_modules` object,
#' which results in a nested structure corresponding to the nested tabs in the final application.
#'
#' Note that for `modules()` `label` comes after `...`, so it must be passed as a named argument,
#' otherwise it will be captured by `...`.
#'
#' The labels `"global_filters"` and `"Report previewer"` are reserved
#' because they are used by the `mapping` argument of [teal_slices()]
#' and the report previewer module [reporter_previewer_module()], respectively.
#'
#' @param label (`character(1)`) Label shown in the navigation item for the module or module group.
#' For `modules()` defaults to `"root"`. See `Details`.
#' @param server (`function`) `shiny` module with following arguments:
#' - `id` - `teal` will set proper `shiny` namespace for this module (see [shiny::moduleServer()]).
#' - `input`, `output`, `session` - (optional; not recommended) When provided, then [shiny::callModule()]
#' will be used to call a module. From `shiny` 1.5.0, the recommended way is to use
#' [shiny::moduleServer()] instead which doesn't require these arguments.
#' - `data` (optional) When provided, the module will be called with `teal_data` object (i.e. a list of
#' reactive (filtered) data specified in the `filters` argument) as the value of this argument.
#' - `datasets` (optional) When provided, the module will be called with `FilteredData` object as the
#' value of this argument. (See [`teal.slice::FilteredData`]).
#' - `reporter` (optional) When provided, the module will be called with `Reporter` object as the value
#' of this argument. (See [`teal.reporter::Reporter`]).
#' - `filter_panel_api` (optional) When provided, the module will be called with `FilterPanelAPI` object
#' as the value of this argument. (See [`teal.slice::FilterPanelAPI`]).
#' - `...` (optional) When provided, `server_args` elements will be passed to the module named argument
#' or to the `...`.
#' @param ui (`function`) `shiny` UI module function with following arguments:
#' - `id` - `teal` will set proper `shiny` namespace for this module.
#' - `...` (optional) When provided, `ui_args` elements will be passed to the module named argument
#' or to the `...`.
#' @param filters (`character`) Deprecated. Use `datanames` instead.
#' @param datanames (`character`) Names of the datasets that are relevant for the item.
#' The keyword `"all"` provides all datasets available in `data` passed to `teal` application.
#' `NULL` will hide the filter panel.
#' @param server_args (named `list`) with additional arguments passed on to the server function.
#' @param ui_args (named `list`) with additional arguments passed on to the UI function.
#' @param x (`teal_module` or `teal_modules`) Object to format/print.
#' @param indent (`integer(1)`) Indention level; each nested element is indented one level more.
#' @param transformers (`list` of `teal_data_module`) that will be applied to transform the data.
#' Each transform module UI will appear in the `teal` application, unless the `custom_ui` attribute is set on the list.
#' If so, the module developer is responsible to display the UI in the module itself. `datanames` of the `transformers`
#' will be added to the `datanames`.
#'
#' When the transformation does not have sufficient input data, the resulting data will fallback
#' to the last successful transform or, in case there are none, to the filtered data.
#' @param ...
#' - For `modules()`: (`teal_module` or `teal_modules`) Objects to wrap into a tab.
#' - For `format()` and `print()`: Arguments passed to other methods.
#'
#' @section `datanames`:
#' The module's `datanames` argument determines a subset of datasets from the `data` object, as specified in the
#' server function argument, to be presented in the module. Datasets displayed in the filter panel will be limited
#' to this subset.
#' When `datanames` is set to `"all"`, all available datasets in the `data` object are considered relevant for the
#' module. However, setting `datanames` argument to `"all"` might include datasets that are irrelevant for the module,
#' for example:
#' - Proxy variables used for modifying columns.
#' - Modified copies of datasets used to create a final dataset.
#' - Connection objects.
#' To prevent these irrelevant datasets from appearing in the module, use the [set_datanames()] function on the
#' [module] or [modules()] to change the `datanames` from `"all"` to specific dataset names. Attempting to change
#' `datanames` values that was not set to `"all"` using [set_datanames()] will be ignored with a warning.
#'
#' Additionally, datasets with names starting with `.` are ignored when `datanames` is set to `"all"`.
#'
#' @return
#' `module()` returns an object of class `teal_module`.
#'
#' `modules()` returns a `teal_modules` object which contains following fields:
#' - `label`: taken from the `label` argument.
#' - `children`: a list containing objects passed in `...`. List elements are named after
#' their `label` attribute converted to a valid `shiny` id.
#'
#' @name teal_modules
#' @aliases teal_module
#'
#' @examples
#' library(shiny)
#'
#' module_1 <- module(
#' label = "a module",
#' server = function(id, data) {
#' moduleServer(
#' id,
#' module = function(input, output, session) {
#' output$data <- renderDataTable(data()[["iris"]])
#' }
#' )
#' },
#' ui = function(id) {
#' ns <- NS(id)
#' tagList(dataTableOutput(ns("data")))
#' },
#' datanames = "all"
#' )
#'
#' module_2 <- module(
#' label = "another module",
#' server = function(id) {
#' moduleServer(
#' id,
#' module = function(input, output, session) {
#' output$text <- renderText("Another Module")
#' }
#' )
#' },
#' ui = function(id) {
#' ns <- NS(id)
#' tagList(textOutput(ns("text")))
#' },
#' datanames = NULL
#' )
#'
#' modules <- modules(
#' label = "modules",
#' modules(
#' label = "nested modules",
#' module_1
#' ),
#' module_2
#' )
#'
#' app <- init(
#' data = teal_data(iris = iris),
#' modules = modules
#' )
#'
#' if (interactive()) {
#' shinyApp(app$ui, app$server)
#' }
#' @rdname teal_modules
#' @export
#'
module <- function(label = "module",
server = function(id, data, ...) moduleServer(id, function(input, output, session) NULL),
ui = function(id, ...) tags$p(paste0("This module has no UI (id: ", id, " )")),
filters,
datanames = "all",
server_args = NULL,
ui_args = NULL,
transformers = list()) {
# argument checking (independent)
## `label`
checkmate::assert_string(label)
if (label == "global_filters") {
stop(
sprintf("module(label = \"%s\", ...\n ", label),
"Label 'global_filters' is reserved in teal. Please change to something else.",
call. = FALSE
)
}
if (label == "Report previewer") {
stop(
sprintf("module(label = \"%s\", ...\n ", label),
"Label 'Report previewer' is reserved in teal. Please change to something else.",
call. = FALSE
)
}
## server
checkmate::assert_function(server)
server_formals <- names(formals(server))
if (!(
"id" %in% server_formals ||
all(c("input", "output", "session") %in% server_formals)
)) {
stop(
"\nmodule() `server` argument requires a function with following arguments:",
"\n - id - `teal` will set proper `shiny` namespace for this module.",
"\n - input, output, session (not recommended) - then `shiny::callModule` will be used to call a module.",
"\n\nFollowing arguments can be used optionaly:",
"\n - `data` - module will receive list of reactive (filtered) data specified in the `filters` argument",
"\n - `datasets` - module will receive `FilteredData`. See `help(teal.slice::FilteredData)`",
"\n - `reporter` - module will receive `Reporter`. See `help(teal.reporter::Reporter)`",
"\n - `filter_panel_api` - module will receive `FilterPanelAPI`. (See [teal.slice::FilterPanelAPI]).",
"\n - `...` server_args elements will be passed to the module named argument or to the `...`"
)
}
if ("datasets" %in% server_formals) {
warning(
sprintf("Called from module(label = \"%s\", ...)\n ", label),
"`datasets` argument in the server is deprecated and will be removed in the next release. ",
"Please use `data` instead.",
call. = FALSE
)
}
## UI
checkmate::assert_function(ui)
ui_formals <- names(formals(ui))
if (!"id" %in% ui_formals) {
stop(
"\nmodule() `ui` argument requires a function with following arguments:",
"\n - id - `teal` will set proper `shiny` namespace for this module.",
"\n\nFollowing arguments can be used optionally:",
"\n - `...` ui_args elements will be passed to the module argument of the same name or to the `...`"
)
}
if (any(c("data", "datasets") %in% ui_formals)) {
stop(
sprintf("Called from module(label = \"%s\", ...)\n ", label),
"UI with `data` or `datasets` argument is no longer accepted.\n ",
"If some UI inputs depend on data, please move the logic to your server instead.\n ",
"Possible solutions are renderUI() or updateXyzInput() functions."
)
}
## `filters`
if (!missing(filters)) {
datanames <- filters
msg <-
"The `filters` argument is deprecated and will be removed in the next release. Please use `datanames` instead."
warning(msg)
}
## `datanames` (also including deprecated `filters`)
# please note a race condition between datanames set when filters is not missing and data arg in server function
if (!is.element("data", server_formals) && !is.null(datanames)) {
message(sprintf("module \"%s\" server function takes no data so \"datanames\" will be ignored", label))
datanames <- NULL
}
checkmate::assert_character(datanames, min.len = 1, null.ok = TRUE, any.missing = FALSE)
## `server_args`
checkmate::assert_list(server_args, null.ok = TRUE, names = "named")
srv_extra_args <- setdiff(names(server_args), server_formals)
if (length(srv_extra_args) > 0 && !"..." %in% server_formals) {
stop(
"\nFollowing `server_args` elements have no equivalent in the formals of the server:\n",
paste(paste(" -", srv_extra_args), collapse = "\n"),
"\n\nUpdate the server arguments by including above or add `...`"
)
}
## `ui_args`
checkmate::assert_list(ui_args, null.ok = TRUE, names = "named")
ui_extra_args <- setdiff(names(ui_args), ui_formals)
if (length(ui_extra_args) > 0 && !"..." %in% ui_formals) {
stop(
"\nFollowing `ui_args` elements have no equivalent in the formals of UI:\n",
paste(paste(" -", ui_extra_args), collapse = "\n"),
"\n\nUpdate the UI arguments by including above or add `...`"
)
}
## `transformers`
if (inherits(transformers, "teal_transform_module")) {
transformers <- list(transformers)
}
checkmate::assert_list(transformers, types = "teal_transform_module")
transformer_datanames <- unlist(lapply(transformers, attr, "datanames"))
combined_datanames <- if (identical(datanames, "all") || any(sapply(transformer_datanames, identical, "all"))) {
"all"
} else {
union(datanames, transformer_datanames)
}
structure(
list(
label = label,
server = server,
ui = ui,
datanames = combined_datanames,
server_args = server_args,
ui_args = ui_args,
transformers = transformers
),
class = "teal_module"
)
}
#' @rdname teal_modules
#' @export
#'
modules <- function(..., label = "root") {
checkmate::assert_string(label)
submodules <- list(...)
if (any(vapply(submodules, is.character, FUN.VALUE = logical(1)))) {
stop(
"The only character argument to modules() must be 'label' and it must be named, ",
"change modules('lab', ...) to modules(label = 'lab', ...)"
)
}
checkmate::assert_list(submodules, min.len = 1, any.missing = FALSE, types = c("teal_module", "teal_modules"))
# name them so we can more easily access the children
# beware however that the label of the submodules should not be changed as it must be kept synced
labels <- vapply(submodules, function(submodule) submodule$label, character(1))
names(submodules) <- get_unique_labels(labels)
structure(
list(
label = label,
children = submodules
),
class = "teal_modules"
)
}
# printing methods ----
#' @rdname teal_modules
#' @export
format.teal_module <- function(x, indent = 0, ...) {
paste0(paste(rep(" ", indent), collapse = ""), "+ ", x$label, "\n", collapse = "")
}
#' @rdname teal_modules
#' @export
print.teal_module <- function(x, ...) {
cat(format(x, ...))
invisible(x)
}
#' @rdname teal_modules
#' @export
format.teal_modules <- function(x, indent = 0, ...) {
paste(
c(
paste0(rep(" ", indent), "+ ", x$label, "\n"),
unlist(lapply(x$children, format, indent = indent + 1, ...))
),
collapse = ""
)
}
#' @param modules (`teal_module` or `teal_modules`)
#' @rdname teal_modules
#' @examples
#' # change the module's datanames
#' set_datanames(module(datanames = "all"), "a")
#'
#' # change modules' datanames
#' set_datanames(
#' modules(
#' module(datanames = "all"),
#' module(datanames = "a")
#' ),
#' "b"
#' )
#' @export
set_datanames <- function(modules, datanames) {
checkmate::assert_multi_class(modules, c("teal_modules", "teal_module"))
if (inherits(modules, "teal_modules")) {
modules$children <- lapply(modules$children, set_datanames, datanames)
} else {
if (identical(modules$datanames, "all")) {
modules$datanames <- datanames
} else {
warning(
"Not possible to modify datanames of the module ", modules$label,
". set_datanames() can only change datanames if it was set to \"all\".",
call. = FALSE
)
}
}
modules
}
#' @rdname teal_modules
#' @export
print.teal_modules <- print.teal_module
# utilities ----
## subset or modify modules ----
#' Append a `teal_module` to `children` of a `teal_modules` object
#' @keywords internal
#' @param modules (`teal_modules`)
#' @param module (`teal_module`) object to be appended onto the children of `modules`
#' @return A `teal_modules` object with `module` appended.
append_module <- function(modules, module) {
checkmate::assert_class(modules, "teal_modules")
checkmate::assert_class(module, "teal_module")
modules$children <- c(modules$children, list(module))
labels <- vapply(modules$children, function(submodule) submodule$label, character(1))
names(modules$children) <- get_unique_labels(labels)
modules
}
#' Extract/Remove module(s) of specific class
#'
#' Given a `teal_module` or a `teal_modules`, return the elements of the structure according to `class`.
#'
#' @param modules (`teal_modules`)
#' @param class The class name of `teal_module` to be extracted or dropped.
#' @keywords internal
#' @return
#' - For `extract_module`, a `teal_module` of class `class` or `teal_modules` containing modules of class `class`.
#' - For `drop_module`, the opposite, which is all `teal_modules` of class other than `class`.
#' @rdname module_management
extract_module <- function(modules, class) {
if (inherits(modules, class)) {
modules
} else if (inherits(modules, "teal_module")) {
NULL
} else if (inherits(modules, "teal_modules")) {
Filter(function(x) length(x) > 0L, lapply(modules$children, extract_module, class))
}
}
#' @keywords internal
#' @return `teal_modules`
#' @rdname module_management
drop_module <- function(modules, class) {
if (inherits(modules, class)) {
NULL
} else if (inherits(modules, "teal_module")) {
modules
} else if (inherits(modules, "teal_modules")) {
do.call(
"modules",
c(Filter(function(x) length(x) > 0L, lapply(modules$children, drop_module, class)), label = modules$label)
)
}
}
## read modules ----
#' Does the object make use of the `arg`
#'
#' @param modules (`teal_module` or `teal_modules`) object
#' @param arg (`character(1)`) names of the arguments to be checked against formals of `teal` modules.
#' @return `logical` whether the object makes use of `arg`.
#' @rdname is_arg_used
#' @keywords internal
is_arg_used <- function(modules, arg) {
checkmate::assert_string(arg)
if (inherits(modules, "teal_modules")) {
any(unlist(lapply(modules$children, is_arg_used, arg)))
} else if (inherits(modules, "teal_module")) {
is_arg_used(modules$server, arg) || is_arg_used(modules$ui, arg)
} else if (is.function(modules)) {
isTRUE(arg %in% names(formals(modules)))
} else {
stop("is_arg_used function not implemented for this object")
}
}
#' Get module depth
#'
#' Depth starts at 0, so a single `teal.module` has depth 0.
#' Nesting it increases overall depth by 1.
#'
#' @inheritParams init
#' @param depth optional integer determining current depth level
#'
#' @return Depth level for given module.
#' @keywords internal
modules_depth <- function(modules, depth = 0L) {
checkmate::assert_multi_class(modules, c("teal_module", "teal_modules"))
checkmate::assert_int(depth, lower = 0)
if (inherits(modules, "teal_modules")) {
max(vapply(modules$children, modules_depth, integer(1), depth = depth + 1L))
} else {
depth
}
}
#' Retrieve labels from `teal_modules`
#'
#' @param modules (`teal_modules`)
#' @return A `list` containing the labels of the modules. If the modules are nested,
#' the function returns a nested `list` of labels.
#' @keywords internal
module_labels <- function(modules) {
if (inherits(modules, "teal_modules")) {
lapply(modules$children, module_labels)
} else {
modules$label
}
}
#' Retrieve `teal_bookmarkable` attribute from `teal_modules`
#'
#' @param modules (`teal_modules` or `teal_module`) object
#' @return named list of the same structure as `modules` with `TRUE` or `FALSE` values indicating
#' whether the module is bookmarkable.
#' @keywords internal
modules_bookmarkable <- function(modules) {
checkmate::assert_multi_class(modules, c("teal_modules", "teal_module"))
if (inherits(modules, "teal_modules")) {
setNames(
lapply(modules$children, modules_bookmarkable),
vapply(modules$children, `[[`, "label", FUN.VALUE = character(1))
)
} else {
attr(modules, "teal_bookmarkable", exact = TRUE)
}
}