diff --git a/coverage-report/index.html b/coverage-report/index.html index 24c30d09f..c9d9e0cb0 100644 --- a/coverage-report/index.html +++ b/coverage-report/index.html @@ -95,7 +95,7 @@ font-size: 11px; }
1 |
- #' Generate lockfile for application's environment reproducibility+ #' `teal` main module |
||
3 |
- #' @param lockfile_path (`character`) path to the lockfile.+ #' @description |
||
4 |
- #'+ #' `r lifecycle::badge("stable")` |
||
5 |
- #' @section Different ways of creating lockfile:+ #' Module to create a `teal` app. This module can be called directly instead of [init()] and |
||
6 |
- #' `teal` leverages [renv::snapshot()], which offers multiple methods for lockfile creation.+ #' included in your custom application. Please note that [init()] adds `reporter_previewer_module` |
||
7 |
- #'+ #' automatically, which is not a case when calling `ui/srv_teal` directly. |
||
8 |
- #' - **Working directory lockfile**: `teal`, by default, will create an `implicit` type lockfile that uses+ #' |
||
9 |
- #' `renv::dependencies()` to detect all R packages in the current project's working directory.+ #' @details |
||
10 |
- #' - **`DESCRIPTION`-based lockfile**: To generate a lockfile based on a `DESCRIPTION` file in your working+ #' |
||
11 |
- #' directory, set `renv::settings$snapshot.type("explicit")`. The naming convention for `type` follows+ #' Module is responsible for creating the main `shiny` app layout and initializing all the necessary |
||
12 |
- #' `renv::snapshot()`. For the `"explicit"` type, refer to `renv::settings$package.dependency.fields()` for the+ #' components. This module establishes reactive connection between the input `data` and every other |
||
13 |
- #' `DESCRIPTION` fields included in the lockfile.+ #' component in the app. Reactive change of the `data` passed as an argument, reloads the app and |
||
14 |
- #' - **Custom files-based lockfile**: To specify custom files as the basis for the lockfile, set+ #' possibly keeps all input settings the same so the user can continue where one left off. |
||
15 |
- #' `renv::settings$snapshot.type("custom")` and configure the `renv.snapshot.filter` option.+ #' |
||
16 |
- #'+ #' ## data flow in `teal` application |
||
17 |
- #' @section lockfile usage:+ #' |
||
18 |
- #' After creating the lockfile, you can restore the application's environment using `renv::restore()`.+ #' This module supports multiple data inputs but eventually, they are all converted to `reactive` |
||
19 |
- #'+ #' returning `teal_data` in this module. On this `reactive teal_data` object several actions are |
||
20 |
- #' @seealso [renv::snapshot()], [renv::restore()].+ #' performed: |
||
21 |
- #'+ #' - data loading in [`module_init_data`] |
||
22 |
- #' @return `NULL`+ #' - data filtering in [`module_filter_data`] |
||
23 |
- #'+ #' - data transformation in [`module_transform_data`] |
||
24 |
- #' @name module_teal_lockfile+ #' |
||
25 |
- #' @rdname module_teal_lockfile+ #' ## Fallback on failure |
||
27 |
- #' @keywords internal+ #' `teal` is designed in such way that app will never crash if the error is introduced in any |
||
28 |
- NULL+ #' custom `shiny` module provided by app developer (e.g. [teal_data_module()], [teal_transform_module()]). |
||
29 |
-
+ #' If any module returns a failing object, the app will halt the evaluation and display a warning message. |
||
30 |
- #' @rdname module_teal_lockfile+ #' App user should always have a chance to fix the improper input and continue without restarting the session. |
||
31 |
- ui_teal_lockfile <- function(id) {+ #' |
||
32 | -! | +
- ns <- NS(id)+ #' @rdname module_teal |
|
33 | -! | +
- shiny::tagList(+ #' @name module_teal |
|
34 | -! | +
- tags$span("", id = ns("lockFileStatus")),+ #' |
|
35 | -! | +
- shinyjs::disabled(downloadLink(ns("lockFileLink"), "Download lockfile"))+ #' @inheritParams module_init_data |
|
36 |
- )+ #' @inheritParams init |
||
37 |
- }+ #' |
||
38 |
-
+ #' @return `NULL` invisibly |
||
39 |
- #' @rdname module_teal_lockfile+ NULL |
||
40 |
- srv_teal_lockfile <- function(id) {+ |
||
41 | -88x | +
- moduleServer(id, function(input, output, session) {+ #' @rdname module_teal |
|
42 | -88x | +
- logger::log_debug("Initialize srv_teal_lockfile.")+ #' @export |
|
43 | -88x | +
- enable_lockfile_download <- function() {+ ui_teal <- function(id, |
|
44 | -! | +
- shinyjs::html("lockFileStatus", "Application lockfile ready.")+ modules, |
|
45 | -! | +
- shinyjs::hide("lockFileStatus", anim = TRUE)+ title = build_app_title(), |
|
46 | -! | +
- shinyjs::enable("lockFileLink")+ header = tags$p(), |
|
47 | -! | +
- output$lockFileLink <- shiny::downloadHandler(+ footer = tags$p()) { |
|
48 | ! |
- filename = function() {+ checkmate::assert_character(id, max.len = 1, any.missing = FALSE) |
|
49 | ! |
- "renv.lock"+ checkmate::assert( |
|
50 | -+ | ! |
- },+ .var.name = "title", |
51 | ! |
- content = function(file) {+ checkmate::check_string(title), |
|
52 | ! |
- file.copy(lockfile_path, file)+ checkmate::check_multi_class(title, c("shiny.tag", "shiny.tag.list", "html")) |
|
53 | -! | +
- file+ ) |
|
54 | -+ | ! |
- },+ checkmate::assert( |
55 | ! |
- contentType = "application/json"+ .var.name = "header", |
|
56 | -+ | ! |
- )+ checkmate::check_string(header), |
57 | -+ | ! |
- }+ checkmate::check_multi_class(header, c("shiny.tag", "shiny.tag.list", "html")) |
58 | -88x | +
- disable_lockfile_download <- function() {+ ) |
|
59 | ! |
- warning("Lockfile creation failed.", call. = FALSE)+ checkmate::assert( |
|
60 | ! |
- shinyjs::html("lockFileStatus", "Lockfile creation failed.")+ .var.name = "footer", |
|
61 | ! |
- shinyjs::hide("lockFileLink")+ checkmate::check_string(footer), |
|
62 | -+ | ! |
- }+ checkmate::check_multi_class(footer, c("shiny.tag", "shiny.tag.list", "html")) |
63 |
-
+ ) |
||
64 | -88x | +
- shiny::onStop(function() {+ |
|
65 | -88x | +! |
- if (file.exists(lockfile_path) && !shiny::isRunning()) {+ if (is.character(title)) { |
66 | -1x | +! |
- logger::log_debug("Removing lockfile after shutting down the app")+ title <- build_app_title(title) |
67 | -1x | +
- file.remove(lockfile_path)+ } else { |
|
68 | -+ | ! |
- }+ validate_app_title_tag(title) |
69 |
- })+ } |
||
71 | -88x | +! |
- lockfile_path <- "teal_app.lock"+ if (checkmate::test_string(header)) { |
72 | -88x | +! |
- mode <- getOption("teal.lockfile.mode", default = "")+ header <- tags$p(header) |
73 |
-
+ } |
||
74 | -88x | +
- if (!(mode %in% c("auto", "enabled", "disabled"))) {+ |
|
75 | ! |
- stop("'teal.lockfile.mode' option can only be one of \"auto\", \"disabled\" or \"disabled\". ")+ if (checkmate::test_string(footer)) { |
|
76 | -+ | ! |
- }+ footer <- tags$p(footer) |
77 |
-
+ } |
||
78 | -88x | +
- if (mode == "disabled") {+ |
|
79 | -1x | +! |
- logger::log_debug("'teal.lockfile.mode' option is set to 'disabled'. Hiding lockfile download button.")+ ns <- NS(id) |
80 | -1x | +
- shinyjs::hide("lockFileLink")+ |
|
81 | -1x | +
- return(NULL)+ # show busy icon when `shiny` session is busy computing stuff |
|
82 |
- }+ # based on https://stackoverflow.com/questions/17325521/r-shiny-display-loading-message-while-function-is-running/22475216#22475216 # nolint: line_length. |
||
83 | -+ | ! |
-
+ shiny_busy_message_panel <- conditionalPanel( |
84 | -87x | +! |
- if (file.exists(lockfile_path)) {+ condition = "(($('html').hasClass('shiny-busy')) && (document.getElementById('shiny-notification-panel') == null))", # nolint: line_length. |
85 | ! |
- logger::log_debug("Lockfile has already been created for this app - skipping automatic creation.")+ tags$div( |
|
86 | ! |
- enable_lockfile_download()+ icon("arrows-rotate", class = "fa-spin", prefer_type = "solid"), |
|
87 | ! |
- return(NULL)+ "Computing ...", |
|
88 |
- }+ # CSS defined in `custom.css` |
||
89 | -+ | ! |
-
+ class = "shinybusymessage" |
90 | -87x | +
- if (mode == "auto" && .is_disabled_lockfile_scenario()) {+ ) |
|
91 | -86x | +
- logger::log_debug(+ ) |
|
92 | -86x | +
- "Automatic lockfile creation disabled. Execution scenario satisfies teal:::.is_disabled_lockfile_scenario()."+ |
|
93 | -+ | ! |
- )+ fluidPage( |
94 | -86x | +! |
- shinyjs::hide("lockFileLink")+ id = id, |
95 | -86x | +! |
- return(NULL)+ title = title, |
96 | -+ | ! |
- }+ theme = get_teal_bs_theme(), |
97 | -+ | ! |
-
+ include_teal_css_js(), |
98 | -1x | +! |
- if (!.is_lockfile_deps_installed()) {+ tags$header(header), |
99 | ! |
- warning("Automatic lockfile creation disabled. `mirai` and `renv` packages must be installed.")+ tags$hr(class = "my-2"), |
|
100 | ! |
- shinyjs::hide("lockFileLink")+ shiny_busy_message_panel, |
|
101 | ! |
- return(NULL)+ tags$div( |
|
102 | -+ | ! |
- }+ id = ns("tabpanel_wrapper"), |
103 | -+ | ! |
-
+ class = "teal-body", |
104 | -+ | ! |
- # - Will be run only if the lockfile doesn't exist (see the if-s above)+ ui_teal_module(id = ns("teal_modules"), modules = modules) |
105 |
- # - We render to the tempfile because the process might last after session is closed and we don't+ ), |
||
106 | -+ | ! |
- # want to make a "teal_app.renv" then. This is why we copy only during active session.+ tags$div( |
107 | -1x | +! |
- process <- .teal_lockfile_process_invoke(lockfile_path)+ id = ns("options_buttons"), |
108 | -1x | +! |
- observeEvent(process$status(), {+ style = "position: absolute; right: 10px;", |
109 | ! |
- if (process$status() %in% c("initial", "running")) {+ ui_bookmark_panel(ns("bookmark_manager"), modules), |
|
110 | ! |
- shinyjs::html("lockFileStatus", "Creating lockfile...")+ tags$button( |
|
111 | ! |
- } else if (process$status() == "success") {+ class = "btn action-button filter_hamburger", # see sidebar.css for style filter_hamburger |
|
112 | ! |
- result <- process$result()+ href = "javascript:void(0)", |
|
113 | ! |
- if (any(grepl("Lockfile written to", result$out))) {+ onclick = sprintf("toggleFilterPanel('%s');", ns("tabpanel_wrapper")), |
|
114 | ! |
- logger::log_debug("Lockfile containing { length(result$res$Packages) } packages created.")+ title = "Toggle filter panel", |
|
115 | ! |
- if (any(grepl("(WARNING|ERROR):", result$out))) {+ icon("fas fa-bars") |
|
116 | -! | +
- warning("Lockfile created with warning(s) or error(s):", call. = FALSE)+ ), |
|
117 | ! |
- for (i in result$out) {+ ui_snapshot_manager_panel(ns("snapshot_manager_panel")), |
|
118 | ! |
- warning(i, call. = FALSE)+ ui_filter_manager_panel(ns("filter_manager_panel")) |
|
119 |
- }+ ), |
||
120 | -+ | ! |
- }+ tags$script( |
121 | ! |
- enable_lockfile_download()+ HTML( |
|
122 | -+ | ! |
- } else {+ sprintf( |
123 | -! | +
- disable_lockfile_download()+ " |
|
124 | -+ | ! |
- }+ $(document).ready(function() { |
125 | ! |
- } else if (process$status() == "error") {+ $('#%s').appendTo('#%s'); |
|
126 | -! | +
- disable_lockfile_download()+ }); |
|
127 |
- }+ ", |
||
128 | -+ | ! |
- })+ ns("options_buttons"), |
129 | -+ | ! |
-
+ ns("teal_modules-active_tab") |
130 | -1x | +
- NULL+ ) |
|
131 |
- })+ ) |
||
132 |
- }+ ), |
||
133 | -+ | ! |
-
+ tags$hr(), |
134 | -+ | ! |
- utils::globalVariables(c("opts", "sysenv", "libpaths", "wd", "lockfilepath", "run")) # needed for mirai call+ tags$footer( |
135 | -+ | ! |
- #' @rdname module_teal_lockfile+ tags$div( |
136 | -+ | ! |
- .teal_lockfile_process_invoke <- function(lockfile_path) {+ footer, |
137 | -1x | +! |
- mirai_obj <- NULL+ teal.widgets::verbatim_popup_ui(ns("sessionInfo"), "Session Info", type = "link"), |
138 | -1x | +! |
- process <- shiny::ExtendedTask$new(function() {+ br(), |
139 | -1x | +! |
- m <- mirai::mirai(+ ui_teal_lockfile(ns("lockfile")), |
140 | -+ | ! |
- {+ textOutput(ns("identifier")) |
141 | -1x | +
- options(opts)+ ) |
|
142 | -1x | +
- do.call(Sys.setenv, sysenv)+ ) |
|
143 | -1x | +
- .libPaths(libpaths)+ ) |
|
144 | -1x | +
- setwd(wd)+ } |
|
145 | -1x | +
- run(lockfile_path = lockfile_path)+ |
|
146 |
- },+ #' @rdname module_teal |
||
147 | -1x | +
- run = .renv_snapshot,+ #' @export |
|
148 | -1x | +
- lockfile_path = lockfile_path,+ srv_teal <- function(id, data, modules, filter = teal_slices()) { |
|
149 | -1x | +89x |
- opts = options(),+ checkmate::assert_character(id, max.len = 1, any.missing = FALSE) |
150 | -1x | +89x |
- libpaths = .libPaths(),+ checkmate::assert_multi_class(data, c("teal_data", "teal_data_module", "reactive")) |
151 | -1x | +88x |
- sysenv = as.list(Sys.getenv()),+ checkmate::assert_class(modules, "teal_modules") |
152 | -1x | +88x |
- wd = getwd()+ checkmate::assert_class(filter, "teal_slices") |
153 |
- )+ |
||
154 | -1x | +88x |
- mirai_obj <<- m+ moduleServer(id, function(input, output, session) { |
155 | -1x | +88x |
- m+ logger::log_debug("srv_teal initializing.") |
156 |
- })+ |
||
157 | -+ | 88x |
-
+ if (getOption("teal.show_js_log", default = FALSE)) { |
158 | -1x | +! |
- shiny::onStop(function() {+ shinyjs::showLog() |
159 | -1x | +
- if (mirai::unresolved(mirai_obj)) {+ } |
|
160 | -! | +
- logger::log_debug("Terminating a running lockfile process...")+ |
|
161 | -! | +88x |
- mirai::stop_mirai(mirai_obj) # this doesn't stop running - renv will be created even if session is closed+ srv_teal_lockfile("lockfile") |
162 |
- }+ |
||
163 | -+ | 88x |
- })+ output$identifier <- renderText( |
164 | -+ | 88x |
-
+ paste0("Pid:", Sys.getpid(), " Token:", substr(session$token, 25, 32)) |
165 | -1x | +
- suppressWarnings({ # 'package:stats' may not be available when loading+ ) |
|
166 | -1x | +
- process$invoke()+ |
|
167 | -+ | 88x |
- })+ teal.widgets::verbatim_popup_srv( |
168 | -+ | 88x |
-
+ "sessionInfo", |
169 | -1x | +88x |
- logger::log_debug("Lockfile creation started based on { getwd() }.")+ verbatim_content = utils::capture.output(utils::sessionInfo()), |
170 | -+ | 88x |
-
+ title = "SessionInfo" |
171 | -1x | +
- process+ ) |
|
172 |
- }+ |
||
173 |
-
+ # `JavaScript` code |
||
174 | -+ | 88x |
- #' @rdname module_teal_lockfile+ run_js_files(files = "init.js") |
175 |
- .renv_snapshot <- function(lockfile_path) {+ |
||
176 | -1x | +
- out <- utils::capture.output(+ # set timezone in shiny app |
|
177 | -1x | +
- res <- renv::snapshot(+ # timezone is set in the early beginning so it will be available also |
|
178 | -1x | +
- lockfile = lockfile_path,+ # for `DDL` and all shiny modules |
|
179 | -1x | +88x |
- prompt = FALSE,+ get_client_timezone(session$ns) |
180 | -1x | +88x |
- force = TRUE,+ observeEvent( |
181 | -1x | +88x |
- type = renv::settings$snapshot.type() # see the section "Different ways of creating lockfile" above here+ eventExpr = input$timezone, |
182 | -+ | 88x |
- )+ once = TRUE, |
183 | -+ | 88x |
- )+ handlerExpr = { |
184 | -+ | ! |
-
+ session$userData$timezone <- input$timezone |
185 | -1x | +! |
- list(out = out, res = res)+ logger::log_debug("srv_teal@1 Timezone set to client's timezone: { input$timezone }.") |
186 |
- }+ } |
||
187 |
-
+ ) |
||
188 |
- #' @rdname module_teal_lockfile+ |
||
189 | -+ | 88x |
- .is_lockfile_deps_installed <- function() {+ data_handled <- srv_init_data("data", data = data) |
190 | -1x | +
- requireNamespace("mirai", quietly = TRUE) && requireNamespace("renv", quietly = TRUE)+ |
|
191 | -+ | 87x |
- }+ validate_ui <- tags$div( |
192 | -+ | 87x |
-
+ id = session$ns("validate_messages"), |
193 | -+ | 87x |
- #' @rdname module_teal_lockfile+ class = "teal_validated", |
194 | -+ | 87x |
- .is_disabled_lockfile_scenario <- function() {+ ui_check_class_teal_data(session$ns("class_teal_data")), |
195 | -86x | +87x |
- identical(Sys.getenv("CALLR_IS_RUNNING"), "true") || # inside callr process+ ui_validate_error(session$ns("silent_error")), |
196 | -86x | +87x |
- identical(Sys.getenv("TESTTHAT"), "true") || # inside devtools::test+ ui_check_module_datanames(session$ns("datanames_warning")) |
197 | -86x | +
- !identical(Sys.getenv("QUARTO_PROJECT_ROOT"), "") || # inside Quarto process+ ) |
|
198 | -+ | 87x |
- (+ srv_check_class_teal_data("class_teal_data", data_handled) |
199 | -86x | +87x |
- ("CheckExEnv" %in% search()) || any(c("_R_CHECK_TIMINGS_", "_R_CHECK_LICENSE_") %in% names(Sys.getenv()))+ srv_validate_error("silent_error", data_handled, validate_shiny_silent_error = FALSE) |
200 | -86x | +87x |
- ) # inside R CMD CHECK+ srv_check_module_datanames("datanames_warning", data_handled, modules) |
201 |
- }+ |
1 | -+ | ||
202 | +87x |
- #' `teal` main module+ data_validated <- .trigger_on_success(data_handled) |
|
2 | +203 |
- #'+ |
|
3 | -+ | ||
204 | +87x |
- #' @description+ data_signatured <- reactive({ |
|
4 | -+ | ||
205 | +152x |
- #' `r lifecycle::badge("stable")`+ req(inherits(data_validated(), "teal_data")) |
|
5 | -+ | ||
206 | +75x |
- #' Module to create a `teal` app. This module can be called directly instead of [init()] and+ is_filter_ok <- check_filter_datanames(filter, names(data_validated())) |
|
6 | -+ | ||
207 | +75x |
- #' included in your custom application. Please note that [init()] adds `reporter_previewer_module`+ if (!isTRUE(is_filter_ok)) { |
|
7 | -+ | ||
208 | +2x |
- #' automatically, which is not a case when calling `ui/srv_teal` directly.+ showNotification( |
|
8 | -+ | ||
209 | +2x |
- #'+ "Some filters were not applied because of incompatibility with data. Contact app developer.", |
|
9 | -+ | ||
210 | +2x |
- #' @details+ type = "warning", |
|
10 | -+ | ||
211 | +2x |
- #'+ duration = 10 |
|
11 | +212 |
- #' Module is responsible for creating the main `shiny` app layout and initializing all the necessary+ ) |
|
12 | -+ | ||
213 | +2x |
- #' components. This module establishes reactive connection between the input `data` and every other+ warning(is_filter_ok) |
|
13 | +214 |
- #' component in the app. Reactive change of the `data` passed as an argument, reloads the app and+ } |
|
14 | -+ | ||
215 | +75x |
- #' possibly keeps all input settings the same so the user can continue where one left off.+ .add_signature_to_data(data_validated()) |
|
15 | +216 |
- #'+ }) |
|
16 | +217 |
- #' ## data flow in `teal` application+ |
|
17 | -+ | ||
218 | +87x |
- #'+ data_load_status <- reactive({ |
|
18 | -+ | ||
219 | +80x |
- #' This module supports multiple data inputs but eventually, they are all converted to `reactive`+ if (inherits(data_handled(), "teal_data")) { |
|
19 | -+ | ||
220 | +75x |
- #' returning `teal_data` in this module. On this `reactive teal_data` object several actions are+ "ok" |
|
20 | -+ | ||
221 | +5x |
- #' performed:+ } else if (inherits(data, "teal_data_module")) { |
|
21 | -+ | ||
222 | +5x |
- #' - data loading in [`module_init_data`]+ "teal_data_module failed" |
|
22 | +223 |
- #' - data filtering in [`module_filter_data`]+ } else { |
|
23 | -+ | ||
224 | +! |
- #' - data transformation in [`module_transform_data`]+ "external failed" |
|
24 | +225 |
- #'+ } |
|
25 | +226 |
- #' ## Fallback on failure+ }) |
|
26 | +227 |
- #'+ |
|
27 | -+ | ||
228 | +87x |
- #' `teal` is designed in such way that app will never crash if the error is introduced in any+ datasets_rv <- if (!isTRUE(attr(filter, "module_specific"))) { |
|
28 | -+ | ||
229 | +76x |
- #' custom `shiny` module provided by app developer (e.g. [teal_data_module()], [teal_transform_module()]).+ eventReactive(data_signatured(), { |
|
29 | -+ | ||
230 | +66x |
- #' If any module returns a failing object, the app will halt the evaluation and display a warning message.+ req(inherits(data_signatured(), "teal_data")) |
|
30 | -+ | ||
231 | +66x |
- #' App user should always have a chance to fix the improper input and continue without restarting the session.+ logger::log_debug("srv_teal@1 initializing FilteredData") |
|
31 | -+ | ||
232 | +66x |
- #'+ teal_data_to_filtered_data(data_signatured()) |
|
32 | +233 |
- #' @rdname module_teal+ }) |
|
33 | +234 |
- #' @name module_teal+ } |
|
34 | +235 |
- #'+ |
|
35 | +236 |
- #' @inheritParams module_init_data+ |
|
36 | +237 |
- #' @inheritParams init+ + |
+ |
238 | +87x | +
+ if (inherits(data, "teal_data_module")) {+ |
+ |
239 | +9x | +
+ setBookmarkExclude(c("teal_modules-active_tab"))+ |
+ |
240 | +9x | +
+ shiny::insertTab(+ |
+ |
241 | +9x | +
+ inputId = "teal_modules-active_tab",+ |
+ |
242 | +9x | +
+ position = "before",+ |
+ |
243 | +9x | +
+ select = TRUE,+ |
+ |
244 | +9x | +
+ tabPanel(+ |
+ |
245 | +9x | +
+ title = icon("fas fa-database"),+ |
+ |
246 | +9x | +
+ value = "teal_data_module",+ |
+ |
247 | +9x | +
+ tags$div(+ |
+ |
248 | +9x | +
+ ui_init_data(session$ns("data")),+ |
+ |
249 | +9x | +
+ validate_ui |
|
37 | +250 |
- #'+ ) |
|
38 | +251 |
- #' @return `NULL` invisibly+ ) |
|
39 | +252 |
- NULL+ ) |
|
40 | +253 | ||
41 | -+ | ||
254 | +9x |
- #' @rdname module_teal+ if (attr(data, "once")) { |
|
42 | -+ | ||
255 | +9x |
- #' @export+ observeEvent(data_signatured(), once = TRUE, {+ |
+ |
256 | +4x | +
+ logger::log_debug("srv_teal@2 removing data tab.") |
|
43 | +257 |
- ui_teal <- function(id,+ # when once = TRUE we pull data once and then remove data tab+ |
+ |
258 | +4x | +
+ removeTab("teal_modules-active_tab", target = "teal_data_module") |
|
44 | +259 |
- modules,+ }) |
|
45 | +260 |
- title = build_app_title(),+ } |
|
46 | +261 |
- header = tags$p(),+ } else { |
|
47 | +262 |
- footer = tags$p()) {+ # when no teal_data_module then we want to display messages above tabsetPanel (because there is no data-tab) |
|
48 | -! | +||
263 | +78x |
- checkmate::assert_character(id, max.len = 1, any.missing = FALSE)+ insertUI( |
|
49 | -! | +||
264 | +78x |
- checkmate::assert(+ selector = sprintf("#%s", session$ns("tabpanel_wrapper")), |
|
50 | -! | +||
265 | +78x |
- .var.name = "title",+ where = "beforeBegin", |
|
51 | -! | +||
266 | +78x |
- checkmate::check_string(title),+ ui = tags$div(validate_ui, tags$br()) |
|
52 | -! | +||
267 | +
- checkmate::check_multi_class(title, c("shiny.tag", "shiny.tag.list", "html"))+ ) |
||
53 | +268 |
- )+ } |
|
54 | -! | +||
269 | +
- checkmate::assert(+ |
||
55 | -! | +||
270 | +87x |
- .var.name = "header",+ module_labels <- unlist(module_labels(modules), use.names = FALSE) |
|
56 | -! | +||
271 | +87x |
- checkmate::check_string(header),+ slices_global <- methods::new(".slicesGlobal", filter, module_labels) |
|
57 | -! | +||
272 | +87x |
- checkmate::check_multi_class(header, c("shiny.tag", "shiny.tag.list", "html"))+ modules_output <- srv_teal_module( |
|
58 | -+ | ||
273 | +87x |
- )+ id = "teal_modules", |
|
59 | -! | +||
274 | +87x |
- checkmate::assert(+ data = data_signatured, |
|
60 | -! | +||
275 | +87x |
- .var.name = "footer",+ datasets = datasets_rv, |
|
61 | -! | +||
276 | +87x |
- checkmate::check_string(footer),+ modules = modules, |
|
62 | -! | +||
277 | +87x |
- checkmate::check_multi_class(footer, c("shiny.tag", "shiny.tag.list", "html"))+ slices_global = slices_global, |
|
63 | -+ | ||
278 | +87x |
- )+ data_load_status = data_load_status |
|
64 | +279 | - - | -|
65 | -! | -
- if (is.character(title)) {+ ) |
|
66 | -! | +||
280 | +87x |
- title <- build_app_title(title)+ mapping_table <- srv_filter_manager_panel("filter_manager_panel", slices_global = slices_global) |
|
67 | -+ | ||
281 | +87x |
- } else {+ snapshots <- srv_snapshot_manager_panel("snapshot_manager_panel", slices_global = slices_global) |
|
68 | -! | +||
282 | +87x |
- validate_app_title_tag(title)+ srv_bookmark_panel("bookmark_manager", modules) |
|
69 | +283 |
- }+ }) |
|
70 | +284 | ||
71 | -! | +||
285 | +87x |
- if (checkmate::test_string(header)) {+ invisible(NULL) |
|
72 | -! | +||
286 | +
- header <- tags$p(header)+ } |
73 | +1 |
- }+ #' Calls all `modules` |
||
74 | +2 |
-
+ #' |
||
75 | -! | +|||
3 | +
- if (checkmate::test_string(footer)) {+ #' On the UI side each `teal_modules` is translated to a `tabsetPanel` and each `teal_module` is a |
|||
76 | -! | +|||
4 | +
- footer <- tags$p(footer)+ #' `tabPanel`. Both, UI and server are called recursively so that each tab is a separate module and |
|||
77 | +5 |
- }+ #' reflect nested structure of `modules` argument. |
||
78 | +6 |
-
+ #' |
||
79 | -! | +|||
7 | +
- ns <- NS(id)+ #' @name module_teal_module |
|||
80 | +8 |
-
+ #' |
||
81 | +9 |
- # show busy icon when `shiny` session is busy computing stuff+ #' @inheritParams module_teal |
||
82 | +10 |
- # based on https://stackoverflow.com/questions/17325521/r-shiny-display-loading-message-while-function-is-running/22475216#22475216 # nolint: line_length.+ #' |
||
83 | -! | +|||
11 | +
- shiny_busy_message_panel <- conditionalPanel(+ #' @param data (`reactive` returning `teal_data`) |
|||
84 | -! | +|||
12 | +
- condition = "(($('html').hasClass('shiny-busy')) && (document.getElementById('shiny-notification-panel') == null))", # nolint: line_length.+ #' |
|||
85 | -! | +|||
13 | +
- tags$div(+ #' @param slices_global (`reactiveVal` returning `modules_teal_slices`) |
|||
86 | -! | +|||
14 | +
- icon("arrows-rotate", class = "fa-spin", prefer_type = "solid"),+ #' see [`module_filter_manager`] |
|||
87 | -! | +|||
15 | +
- "Computing ...",+ #' |
|||
88 | +16 |
- # CSS defined in `custom.css`+ #' @param depth (`integer(1)`) |
||
89 | -! | +|||
17 | +
- class = "shinybusymessage"+ #' number which helps to determine depth of the modules nesting. |
|||
90 | +18 |
- )+ #' |
||
91 | +19 |
- )+ #' @param datasets (`reactive` returning `FilteredData` or `NULL`) |
||
92 | +20 |
-
+ #' When `datasets` is passed from the parent module (`srv_teal`) then `dataset` is a singleton |
||
93 | -! | +|||
21 | +
- fluidPage(+ #' which implies in filter-panel to be "global". When `NULL` then filter-panel is "module-specific". |
|||
94 | -! | +|||
22 | +
- id = id,+ #' |
|||
95 | -! | +|||
23 | +
- title = title,+ #' @param data_load_status (`reactive` returning `character`) |
|||
96 | -! | +|||
24 | +
- theme = get_teal_bs_theme(),+ #' Determines action dependent on a data loading status: |
|||
97 | -! | +|||
25 | +
- include_teal_css_js(),+ #' - `"ok"` when `teal_data` is returned from the data loading. |
|||
98 | -! | +|||
26 | +
- tags$header(header),+ #' - `"teal_data_module failed"` when [teal_data_module()] didn't return `teal_data`. Disables tabs buttons. |
|||
99 | -! | +|||
27 | +
- tags$hr(class = "my-2"),+ #' - `"external failed"` when a `reactive` passed to `srv_teal(data)` didn't return `teal_data`. Hides the whole tab |
|||
100 | -! | +|||
28 | +
- shiny_busy_message_panel,+ #' panel. |
|||
101 | -! | +|||
29 | +
- tags$div(+ #' |
|||
102 | -! | +|||
30 | +
- id = ns("tabpanel_wrapper"),+ #' @return |
|||
103 | -! | +|||
31 | +
- class = "teal-body",+ #' output of currently active module. |
|||
104 | -! | +|||
32 | +
- ui_teal_module(id = ns("teal_modules"), modules = modules)+ #' - `srv_teal_module.teal_module` returns `reactiveVal` containing output of the called module. |
|||
105 | +33 |
- ),+ #' - `srv_teal_module.teal_modules` returns output of module selected by `input$active_tab`. |
||
106 | -! | +|||
34 | +
- tags$div(+ #' |
|||
107 | -! | +|||
35 | +
- id = ns("options_buttons"),+ #' @keywords internal |
|||
108 | -! | +|||
36 | +
- style = "position: absolute; right: 10px;",+ NULL |
|||
109 | -! | +|||
37 | +
- ui_bookmark_panel(ns("bookmark_manager"), modules),+ |
|||
110 | -! | +|||
38 | +
- tags$button(+ #' @rdname module_teal_module |
|||
111 | -! | +|||
39 | +
- class = "btn action-button filter_hamburger", # see sidebar.css for style filter_hamburger+ ui_teal_module <- function(id, modules, depth = 0L) { |
|||
112 | +40 | ! |
- href = "javascript:void(0)",+ checkmate::assert_multi_class(modules, c("teal_modules", "teal_module", "shiny.tag")) |
|
113 | +41 | ! |
- onclick = sprintf("toggleFilterPanel('%s');", ns("tabpanel_wrapper")),+ checkmate::assert_count(depth) |
|
114 | +42 | ! |
- title = "Toggle filter panel",+ UseMethod("ui_teal_module", modules)+ |
+ |
43 | ++ |
+ }+ |
+ ||
44 | ++ | + + | +||
45 | ++ |
+ #' @rdname module_teal_module+ |
+ ||
46 | ++ |
+ #' @export+ |
+ ||
47 | ++ |
+ ui_teal_module.default <- function(id, modules, depth = 0L) { |
||
115 | +48 | ! |
- icon("fas fa-bars")+ stop("Modules class not supported: ", paste(class(modules), collapse = " ")) |
|
116 | +49 |
- ),+ }+ |
+ ||
50 | ++ | + + | +||
51 | ++ |
+ #' @rdname module_teal_module+ |
+ ||
52 | ++ |
+ #' @export+ |
+ ||
53 | ++ |
+ ui_teal_module.teal_modules <- function(id, modules, depth = 0L) { |
||
117 | +54 | ! |
- ui_snapshot_manager_panel(ns("snapshot_manager_panel")),+ ns <- NS(id) |
|
118 | +55 | ! |
- ui_filter_manager_panel(ns("filter_manager_panel"))+ tags$div( |
|
119 | -+ | |||
56 | +! |
- ),+ id = ns("wrapper"), |
||
120 | +57 | ! |
- tags$script(+ do.call( |
|
121 | +58 | ! |
- HTML(+ tabsetPanel, |
|
122 | +59 | ! |
- sprintf(+ c( |
|
123 | +60 |
- "+ # by giving an id, we can reactively respond to tab changes |
||
124 | +61 | ! |
- $(document).ready(function() {+ list( |
|
125 | +62 | ! |
- $('#%s').appendTo('#%s');+ id = ns("active_tab"), |
|
126 | -+ | |||
63 | +! |
- });+ type = if (modules$label == "root") "pills" else "tabs" |
||
127 | +64 |
- ",+ ), |
||
128 | +65 | ! |
- ns("options_buttons"),+ lapply( |
|
129 | +66 | ! |
- ns("teal_modules-active_tab")+ names(modules$children), |
|
130 | -+ | |||
67 | +! |
- )+ function(module_id) { |
||
131 | -+ | |||
68 | +! |
- )+ module_label <- modules$children[[module_id]]$label |
||
132 | -+ | |||
69 | +! |
- ),+ if (is.null(module_label)) { |
||
133 | +70 | ! |
- tags$hr(),+ module_label <- icon("fas fa-database")+ |
+ |
71 | ++ |
+ } |
||
134 | +72 | ! |
- tags$footer(+ tabPanel( |
|
135 | +73 | ! |
- tags$div(+ title = module_label, |
|
136 | +74 | ! |
- footer,+ value = module_id, # when clicked this tab value changes input$<tabset panel id> |
|
137 | +75 | ! |
- teal.widgets::verbatim_popup_ui(ns("sessionInfo"), "Session Info", type = "link"),+ ui_teal_module( |
|
138 | +76 | ! |
- br(),+ id = ns(module_id), |
|
139 | +77 | ! |
- ui_teal_lockfile(ns("lockfile")),+ modules = modules$children[[module_id]], |
|
140 | +78 | ! |
- textOutput(ns("identifier"))+ depth = depth + 1L |
|
141 | +79 |
- )+ ) |
||
142 | +80 |
- )+ ) |
||
143 | +81 |
- )+ } |
||
144 | +82 |
- }+ ) |
||
145 | +83 |
-
+ ) |
||
146 | +84 |
- #' @rdname module_teal+ ) |
||
147 | +85 |
- #' @export+ ) |
||
148 | +86 |
- srv_teal <- function(id, data, modules, filter = teal_slices()) {- |
- ||
149 | -89x | -
- checkmate::assert_character(id, max.len = 1, any.missing = FALSE)+ } |
||
150 | -89x | +|||
87 | +
- checkmate::assert_multi_class(data, c("teal_data", "teal_data_module", "reactive"))+ |
|||
151 | -88x | +|||
88 | +
- checkmate::assert_class(modules, "teal_modules")+ #' @rdname module_teal_module |
|||
152 | -88x | +|||
89 | +
- checkmate::assert_class(filter, "teal_slices")+ #' @export |
|||
153 | +90 |
-
+ ui_teal_module.teal_module <- function(id, modules, depth = 0L) { |
||
154 | -88x | +|||
91 | +! |
- moduleServer(id, function(input, output, session) {+ ns <- NS(id) |
||
155 | -88x | +|||
92 | +! |
- logger::log_debug("srv_teal initializing.")+ args <- c(list(id = ns("module")), modules$ui_args) |
||
156 | +93 | |||
157 | -88x | +|||
94 | +! |
- if (getOption("teal.show_js_log", default = FALSE)) {+ ui_teal <- tagList( |
||
158 | +95 | ! |
- shinyjs::showLog()+ shinyjs::hidden( |
|
159 | -+ | |||
96 | +! |
- }+ tags$div( |
||
160 | -+ | |||
97 | +! |
-
+ id = ns("transform_failure_info"), |
||
161 | -88x | +|||
98 | +! |
- srv_teal_lockfile("lockfile")+ class = "teal_validated", |
||
162 | -+ | |||
99 | +! |
-
+ div( |
||
163 | -88x | +|||
100 | +! |
- output$identifier <- renderText(+ class = "teal-output-warning", |
||
164 | -88x | +|||
101 | +! |
- paste0("Pid:", Sys.getpid(), " Token:", substr(session$token, 25, 32))+ "One of transformators failed. Please check its inputs." |
||
165 | +102 |
- )+ ) |
||
166 | +103 |
-
+ ) |
||
167 | -88x | +|||
104 | +
- teal.widgets::verbatim_popup_srv(+ ), |
|||
168 | -88x | +|||
105 | +! |
- "sessionInfo",+ tags$div( |
||
169 | -88x | +|||
106 | +! |
- verbatim_content = utils::capture.output(utils::sessionInfo()),+ id = ns("teal_module_ui"), |
||
170 | -88x | +|||
107 | +! |
- title = "SessionInfo"+ tags$div( |
||
171 | -+ | |||
108 | +! |
- )+ class = "teal_validated", |
||
172 | -+ | |||
109 | +! |
-
+ ui_check_module_datanames(ns("validate_datanames")) |
||
173 | +110 |
- # `JavaScript` code+ ), |
||
174 | -88x | +|||
111 | +! |
- run_js_files(files = "init.js")+ do.call(modules$ui, args) |
||
175 | +112 |
-
+ ) |
||
176 | +113 |
- # set timezone in shiny app+ ) |
||
177 | +114 |
- # timezone is set in the early beginning so it will be available also+ |
||
178 | -+ | |||
115 | +! |
- # for `DDL` and all shiny modules+ div( |
||
179 | -88x | +|||
116 | +! |
- get_client_timezone(session$ns)+ id = id, |
||
180 | -88x | +|||
117 | +! |
- observeEvent(+ class = "teal_module", |
||
181 | -88x | +|||
118 | +! |
- eventExpr = input$timezone,+ uiOutput(ns("data_reactive"), inline = TRUE), |
||
182 | -88x | +|||
119 | +! |
- once = TRUE,+ tagList( |
||
183 | -88x | +|||
120 | +! |
- handlerExpr = {+ if (depth >= 2L) tags$div(style = "mt-6"), |
||
184 | +121 | ! |
- session$userData$timezone <- input$timezone+ if (!is.null(modules$datanames)) { |
|
185 | +122 | ! |
- logger::log_debug("srv_teal@1 Timezone set to client's timezone: { input$timezone }.")+ fluidRow(+ |
+ |
123 | +! | +
+ column(width = 9, ui_teal, class = "teal_primary_col"),+ |
+ ||
124 | +! | +
+ column(+ |
+ ||
125 | +! | +
+ width = 3,+ |
+ ||
126 | +! | +
+ ui_data_summary(ns("data_summary")),+ |
+ ||
127 | +! | +
+ ui_filter_data(ns("filter_panel")),+ |
+ ||
128 | +! | +
+ ui_transform_teal_data(ns("data_transform"), transformators = modules$transformators, class = "well"),+ |
+ ||
129 | +! | +
+ class = "teal_secondary_col" |
||
186 | +130 |
- }+ ) |
||
187 | +131 |
- )+ ) |
||
188 | +132 |
-
+ } else { |
||
189 | -88x | +|||
133 | +! |
- data_pulled <- srv_init_data("data", data = data)+ ui_teal |
||
190 | +134 |
-
+ } |
||
191 | -87x | +|||
135 | +
- validate_ui <- tags$div(+ ) |
|||
192 | -87x | +|||
136 | +
- id = session$ns("validate_messages"),+ ) |
|||
193 | -87x | +|||
137 | +
- class = "teal_validated",+ } |
|||
194 | -87x | +|||
138 | +
- ui_check_class_teal_data(session$ns("class_teal_data")),+ |
|||
195 | -87x | +|||
139 | +
- ui_validate_error(session$ns("silent_error")),+ #' @rdname module_teal_module |
|||
196 | -87x | +|||
140 | +
- ui_check_module_datanames(session$ns("datanames_warning"))+ srv_teal_module <- function(id, |
|||
197 | +141 |
- )+ data, |
||
198 | -87x | +|||
142 | +
- srv_check_class_teal_data("class_teal_data", data_pulled)+ modules, |
|||
199 | -87x | +|||
143 | +
- srv_validate_error("silent_error", data_pulled, validate_shiny_silent_error = FALSE)+ datasets = NULL, |
|||
200 | -87x | +|||
144 | +
- srv_check_module_datanames("datanames_warning", data_pulled, modules)+ slices_global, |
|||
201 | +145 |
-
+ reporter = teal.reporter::Reporter$new(), |
||
202 | -87x | +|||
146 | +
- data_validated <- .trigger_on_success(data_pulled)+ data_load_status = reactive("ok"), |
|||
203 | +147 |
-
+ is_active = reactive(TRUE)) { |
||
204 | -87x | +148 | +199x |
- data_rv <- reactive({+ checkmate::assert_string(id) |
205 | -152x | +149 | +199x |
- req(inherits(data_validated(), "teal_data"))+ assert_reactive(data) |
206 | -75x | +150 | +199x |
- is_filter_ok <- check_filter_datanames(filter, names(data_validated()))+ checkmate::assert_multi_class(modules, c("teal_modules", "teal_module")) |
207 | -75x | +151 | +199x |
- if (!isTRUE(is_filter_ok)) {+ assert_reactive(datasets, null.ok = TRUE) |
208 | -2x | +152 | +199x |
- showNotification(+ checkmate::assert_class(slices_global, ".slicesGlobal") |
209 | -2x | +153 | +199x |
- "Some filters were not applied because of incompatibility with data. Contact app developer.",+ checkmate::assert_class(reporter, "Reporter") |
210 | -2x | +154 | +199x |
- type = "warning",+ assert_reactive(data_load_status) |
211 | -2x | +155 | +199x |
- duration = 10+ UseMethod("srv_teal_module", modules) |
212 | +156 |
- )+ } |
||
213 | -2x | +|||
157 | +
- warning(is_filter_ok)+ |
|||
214 | +158 |
- }+ #' @rdname module_teal_module |
||
215 | -75x | +|||
159 | +
- .add_signature_to_data(data_validated())+ #' @export |
|||
216 | +160 |
- })+ srv_teal_module.default <- function(id, |
||
217 | +161 |
-
+ data, |
||
218 | -87x | +|||
162 | +
- data_load_status <- reactive({+ modules, |
|||
219 | -80x | +|||
163 | +
- if (inherits(data_pulled(), "teal_data")) {+ datasets = NULL, |
|||
220 | -75x | +|||
164 | +
- "ok"+ slices_global, |
|||
221 | -5x | +|||
165 | +
- } else if (inherits(data, "teal_data_module")) {+ reporter = teal.reporter::Reporter$new(), |
|||
222 | -5x | +|||
166 | +
- "teal_data_module failed"+ data_load_status = reactive("ok"), |
|||
223 | +167 |
- } else {+ is_active = reactive(TRUE)) { |
||
224 | +168 | ! |
- "external failed"+ stop("Modules class not supported: ", paste(class(modules), collapse = " ")) |
|
225 | +169 |
- }+ } |
||
226 | +170 |
- })+ |
||
227 | +171 | - - | -||
228 | -87x | -
- datasets_rv <- if (!isTRUE(attr(filter, "module_specific"))) {+ #' @rdname module_teal_module |
||
229 | -76x | +|||
172 | +
- eventReactive(data_rv(), {+ #' @export |
|||
230 | -66x | +|||
173 | +
- req(inherits(data_rv(), "teal_data"))+ srv_teal_module.teal_modules <- function(id, |
|||
231 | -66x | +|||
174 | +
- logger::log_debug("srv_teal@1 initializing FilteredData")+ data, |
|||
232 | -66x | +|||
175 | +
- teal_data_to_filtered_data(data_rv())+ modules, |
|||
233 | +176 |
- })+ datasets = NULL, |
||
234 | +177 |
- }+ slices_global, |
||
235 | +178 |
-
+ reporter = teal.reporter::Reporter$new(), |
||
236 | +179 |
-
+ data_load_status = reactive("ok"), |
||
237 | +180 |
-
+ is_active = reactive(TRUE)) { |
||
238 | +181 | 87x |
- if (inherits(data, "teal_data_module")) {+ moduleServer(id = id, module = function(input, output, session) { |
|
239 | -9x | +182 | +87x |
- setBookmarkExclude(c("teal_modules-active_tab"))+ logger::log_debug("srv_teal_module.teal_modules initializing the module { deparse1(modules$label) }.") |
240 | -9x | +|||
183 | +
- shiny::insertTab(+ |
|||
241 | -9x | +184 | +87x |
- inputId = "teal_modules-active_tab",+ observeEvent(data_load_status(), { |
242 | -9x | +185 | +80x |
- position = "before",+ tabs_selector <- sprintf("#%s li a", session$ns("active_tab")) |
243 | -9x | +186 | +80x |
- select = TRUE,+ if (identical(data_load_status(), "ok")) { |
244 | -9x | +187 | +75x |
- tabPanel(+ logger::log_debug("srv_teal_module@1 enabling modules tabs.") |
245 | -9x | +188 | +75x |
- title = icon("fas fa-database"),+ shinyjs::show("wrapper") |
246 | -9x | +189 | +75x |
- value = "teal_data_module",+ shinyjs::enable(selector = tabs_selector) |
247 | -9x | +190 | +5x |
- tags$div(+ } else if (identical(data_load_status(), "teal_data_module failed")) { |
248 | -9x | -
- ui_init_data(session$ns("data")),- |
- ||
249 | -9x | -
- validate_ui- |
- ||
250 | -- |
- )- |
- ||
251 | -- |
- )- |
- ||
252 | -- |
- )- |
- ||
253 | -- | - - | -||
254 | -9x | -
- if (attr(data, "once")) {- |
- ||
255 | -9x | +191 | +5x |
- observeEvent(data_rv(), once = TRUE, {+ logger::log_debug("srv_teal_module@1 disabling modules tabs.") |
256 | -4x | +192 | +5x |
- logger::log_debug("srv_teal@2 removing data tab.")+ shinyjs::disable(selector = tabs_selector) |
257 | -+ | |||
193 | +! |
- # when once = TRUE we pull data once and then remove data tab+ } else if (identical(data_load_status(), "external failed")) { |
||
258 | -4x | +|||
194 | +! |
- removeTab("teal_modules-active_tab", target = "teal_data_module")+ logger::log_debug("srv_teal_module@1 hiding modules tabs.") |
||
259 | -+ | |||
195 | +! |
- })+ shinyjs::hide("wrapper") |
||
260 | +196 |
} |
||
261 | +197 |
- } else {+ }) |
||
262 | +198 |
- # when no teal_data_module then we want to display messages above tabsetPanel (because there is no data-tab)+ |
||
263 | -78x | +199 | +87x |
- insertUI(+ modules_output <- sapply( |
264 | -78x | +200 | +87x |
- selector = sprintf("#%s", session$ns("tabpanel_wrapper")),+ names(modules$children), |
265 | -78x | +201 | +87x |
- where = "beforeBegin",+ function(module_id) { |
266 | -78x | -
- ui = tags$div(validate_ui, tags$br())- |
- ||
267 | -- |
- )- |
- ||
268 | -+ | 202 | +112x |
- }+ srv_teal_module( |
269 | -+ | |||
203 | +112x |
-
+ id = module_id, |
||
270 | -87x | +204 | +112x |
- module_labels <- unlist(module_labels(modules), use.names = FALSE)+ data = data, |
271 | -87x | +205 | +112x |
- slices_global <- methods::new(".slicesGlobal", filter, module_labels)+ modules = modules$children[[module_id]], |
272 | -87x | +206 | +112x |
- modules_output <- srv_teal_module(+ datasets = datasets, |
273 | -87x | +207 | +112x |
- id = "teal_modules",+ slices_global = slices_global, |
274 | -87x | +208 | +112x |
- data_rv = data_rv,+ reporter = reporter, |
275 | -87x | +209 | +112x |
- datasets = datasets_rv,+ is_active = reactive( |
276 | -87x | +210 | +112x |
- modules = modules,+ is_active() && |
277 | -87x | +211 | +112x |
- slices_global = slices_global,+ input$active_tab == module_id && |
278 | -87x | +212 | +112x |
- data_load_status = data_load_status+ identical(data_load_status(), "ok") |
279 | +213 |
- )+ ) |
||
280 | -87x | +|||
214 | +
- mapping_table <- srv_filter_manager_panel("filter_manager_panel", slices_global = slices_global)+ ) |
|||
281 | -87x | +|||
215 | +
- snapshots <- srv_snapshot_manager_panel("snapshot_manager_panel", slices_global = slices_global)+ }, |
|||
282 | +216 | 87x |
- srv_bookmark_panel("bookmark_manager", modules)+ simplify = FALSE |
|
283 | +217 |
- })+ ) |
||
284 | +218 | |||
285 | +219 | 87x |
- invisible(NULL)+ modules_output |
|
286 | +220 |
- }+ }) |
1 | +221 |
- #' Get client timezone+ } |
||
2 | +222 |
- #'+ |
||
3 | +223 |
- #' User timezone in the browser may be different to the one on the server.+ #' @rdname module_teal_module |
||
4 | +224 |
- #' This script can be run to register a `shiny` input which contains information about the timezone in the browser.+ #' @export |
||
5 | +225 |
- #'+ srv_teal_module.teal_module <- function(id, |
||
6 | +226 |
- #' @param ns (`function`) namespace function passed from the `session` object in the `shiny` server.+ data, |
||
7 | +227 |
- #' For `shiny` modules this will allow for proper name spacing of the registered input.+ modules, |
||
8 | +228 |
- #'+ datasets = NULL, |
||
9 | +229 |
- #' @return `NULL`, invisibly.+ slices_global, |
||
10 | +230 |
- #'+ reporter = teal.reporter::Reporter$new(), |
||
11 | +231 |
- #' @keywords internal+ data_load_status = reactive("ok"), |
||
12 | +232 |
- #'+ is_active = reactive(TRUE)) { |
||
13 | -+ | |||
233 | +112x |
- get_client_timezone <- function(ns) {+ logger::log_debug("srv_teal_module.teal_module initializing the module: { deparse1(modules$label) }.") |
||
14 | -88x | +234 | +112x |
- script <- sprintf(+ moduleServer(id = id, module = function(input, output, session) { |
15 | -88x | +235 | +112x |
- "Shiny.setInputValue(`%s`, Intl.DateTimeFormat().resolvedOptions().timeZone)",+ module_out <- reactiveVal()+ |
+
236 | ++ | + | ||
16 | -88x | +237 | +112x |
- ns("timezone")+ active_datanames <- reactive({+ |
+
238 | +89x | +
+ .resolve_module_datanames(data = data(), modules = modules) |
||
17 | +239 |
- )+ }) |
||
18 | -88x | +240 | +112x |
- shinyjs::runjs(script) # function does not return anything+ if (is.null(datasets)) { |
19 | -88x | +241 | +20x |
- invisible(NULL)+ datasets <- eventReactive(data(), { |
20 | -+ | |||
242 | +16x |
- }+ req(inherits(data(), "teal_data")) |
||
21 | -+ | |||
243 | +16x |
-
+ logger::log_debug("srv_teal_module@1 initializing module-specific FilteredData") |
||
22 | -+ | |||
244 | +16x |
- #' Resolve the expected bootstrap theme+ teal_data_to_filtered_data(data(), datanames = active_datanames()) |
||
23 | +245 |
- #' @noRd+ }) |
||
24 | +246 |
- #' @keywords internal+ } |
||
25 | +247 |
- get_teal_bs_theme <- function() {+ |
||
26 | -4x | +|||
248 | +
- bs_theme <- getOption("teal.bs_theme")+ # manage module filters on the module level |
|||
27 | +249 |
-
+ # important: |
||
28 | -4x | +|||
250 | +
- if (is.null(bs_theme)) {+ # filter_manager_module_srv needs to be called before filter_panel_srv |
|||
29 | -1x | +|||
251 | +
- return(NULL)+ # Because available_teal_slices is used in FilteredData$srv_available_slices (via srv_filter_panel) |
|||
30 | +252 |
- }+ # and if it is not set, then it won't be available in the srv_filter_panel+ |
+ ||
253 | +112x | +
+ srv_module_filter_manager(modules$label, module_fd = datasets, slices_global = slices_global) |
||
31 | +254 | |||
32 | -3x | +255 | +112x |
- if (!checkmate::test_class(bs_theme, "bs_theme")) {+ call_once_when(is_active(), { |
33 | -2x | +256 | +86x |
- warning(+ filtered_teal_data <- srv_filter_data( |
34 | -2x | +257 | +86x |
- "Assertion on 'teal.bs_theme' option value failed: ",+ "filter_panel", |
35 | -2x | +258 | +86x |
- checkmate::check_class(bs_theme, "bs_theme"),+ datasets = datasets, |
36 | -2x | +259 | +86x |
- ". The default Shiny Bootstrap theme will be used."+ active_datanames = active_datanames, |
37 | -+ | |||
260 | +86x |
- )+ data = data, |
||
38 | -2x | +261 | +86x |
- return(NULL)+ is_active = is_active |
39 | +262 |
- }+ ) |
||
40 | -+ | |||
263 | +86x |
-
+ is_transform_failed <- reactiveValues() |
||
41 | -1x | +264 | +86x |
- bs_theme+ transformed_teal_data <- srv_transform_teal_data( |
42 | -+ | |||
265 | +86x |
- }+ "data_transform", |
||
43 | -+ | |||
266 | +86x |
-
+ data = filtered_teal_data, |
||
44 | -+ | |||
267 | +86x |
- #' Return parentnames along with datanames.+ transformators = modules$transformators, |
||
45 | -+ | |||
268 | +86x |
- #' @noRd+ modules = modules, |
||
46 | -+ | |||
269 | +86x |
- #' @keywords internal+ is_transform_failed = is_transform_failed |
||
47 | +270 |
- .include_parent_datanames <- function(datanames, join_keys) {+ ) |
||
48 | -32x | +271 | +86x |
- ordered_datanames <- datanames+ any_transform_failed <- reactive({ |
49 | -32x | +272 | +86x |
- for (current in datanames) {+ any(unlist(reactiveValuesToList(is_transform_failed)))+ |
+
273 | ++ |
+ })+ |
+ ||
274 | ++ | + | ||
50 | -62x | +275 | +86x |
- parents <- character(0L)+ observeEvent(any_transform_failed(), { |
51 | -62x | +276 | +86x |
- while (length(current) > 0) {+ if (isTRUE(any_transform_failed())) { |
52 | -64x | +277 | +6x |
- current <- teal.data::parent(join_keys, current)+ shinyjs::hide("teal_module_ui") |
53 | -64x | +278 | +6x |
- parents <- c(current, parents)+ shinyjs::show("transform_failure_info") |
54 | +279 |
- }+ } else { |
||
55 | -62x | +280 | +80x |
- ordered_datanames <- c(parents, ordered_datanames)+ shinyjs::show("teal_module_ui")+ |
+
281 | +80x | +
+ shinyjs::hide("transform_failure_info") |
||
56 | +282 |
- }+ } |
||
57 | +283 | ++ |
+ })+ |
+ |
284 | ||||
58 | -32x | +285 | +86x |
- unique(ordered_datanames)+ module_teal_data <- reactive({ |
59 | -+ | |||
286 | +94x |
- }+ req(inherits(transformed_teal_data(), "teal_data")) |
||
60 | -+ | |||
287 | +88x |
-
+ all_teal_data <- transformed_teal_data() |
||
61 | -+ | |||
288 | +88x |
- #' Create a `FilteredData`+ module_datanames <- .resolve_module_datanames(data = all_teal_data, modules = modules) |
||
62 | -+ | |||
289 | +88x |
- #'+ all_teal_data[c(module_datanames, ".raw_data")] |
||
63 | +290 |
- #' Create a `FilteredData` object from a `teal_data` object.+ }) |
||
64 | +291 |
- #'+ |
||
65 | -+ | |||
292 | +86x |
- #' @param x (`teal_data`) object+ srv_check_module_datanames( |
||
66 | -+ | |||
293 | +86x |
- #' @param datanames (`character`) vector of data set names to include; must be subset of `names(x)`+ "validate_datanames", |
||
67 | -+ | |||
294 | +86x |
- #' @return A `FilteredData` object.+ data = module_teal_data,+ |
+ ||
295 | +86x | +
+ modules = modules |
||
68 | +296 |
- #' @keywords internal+ ) |
||
69 | +297 |
- teal_data_to_filtered_data <- function(x, datanames = names(x)) {+ |
||
70 | -83x | +298 | +86x |
- checkmate::assert_class(x, "teal_data")+ summary_table <- srv_data_summary("data_summary", module_teal_data) |
71 | -83x | +|||
299 | +
- checkmate::assert_character(datanames, min.chars = 1L, any.missing = FALSE)+ |
|||
72 | +300 |
- # Otherwise, FilteredData will be created in the modules' scope later+ # Call modules. |
||
73 | -83x | +301 | +86x |
- teal.slice::init_filtered_data(+ if (!inherits(modules, "teal_module_previewer")) { |
74 | -83x | +302 | +86x |
- x = Filter(length, sapply(datanames, function(dn) x[[dn]], simplify = FALSE)),+ obs_module <- call_once_when( |
75 | -83x | +303 | +86x |
- join_keys = teal.data::join_keys(x)+ !is.null(module_teal_data()), |
76 | -+ | |||
304 | +86x |
- )+ ignoreNULL = TRUE, |
||
77 | -+ | |||
305 | +86x |
- }+ handlerExpr = { |
||
78 | -+ | |||
306 | +80x |
-
+ module_out(.call_teal_module(modules, datasets, module_teal_data, reporter)) |
||
79 | +307 |
-
+ } |
||
80 | +308 |
- #' Template function for `TealReportCard` creation and customization+ ) |
||
81 | +309 |
- #'+ } else { |
||
82 | +310 |
- #' This function generates a report card with a title,+ # Report previewer must be initiated on app start for report cards to be included in bookmarks. |
||
83 | +311 |
- #' an optional description, and the option to append the filter state list.+ # When previewer is delayed, cards are bookmarked only if previewer has been initiated (visited). |
||
84 | -+ | |||
312 | +! |
- #'+ module_out(.call_teal_module(modules, datasets, module_teal_data, reporter)) |
||
85 | +313 |
- #' @param title (`character(1)`) title of the card (unless overwritten by label)+ } |
||
86 | +314 |
- #' @param label (`character(1)`) label provided by the user when adding the card+ }) |
||
87 | +315 |
- #' @param description (`character(1)`) optional, additional description+ |
||
88 | -+ | |||
316 | +112x |
- #' @param with_filter (`logical(1)`) flag indicating to add filter state+ module_out |
||
89 | +317 |
- #' @param filter_panel_api (`FilterPanelAPI`) object with API that allows the generation+ }) |
||
90 | +318 |
- #' of the filter state in the report+ } |
||
91 | +319 |
- #'+ |
||
92 | +320 |
- #' @return (`TealReportCard`) populated with a title, description and filter state.+ # This function calls a module server function. |
||
93 | +321 |
- #'+ .call_teal_module <- function(modules, datasets, data, reporter) { |
||
94 | -+ | |||
322 | +80x |
- #' @export+ assert_reactive(data) |
||
95 | +323 |
- report_card_template <- function(title, label, description = NULL, with_filter, filter_panel_api) {+ |
||
96 | -2x | +|||
324 | +
- checkmate::assert_string(title)+ # collect arguments to run teal_module |
|||
97 | -2x | +325 | +80x |
- checkmate::assert_string(label)+ args <- c(list(id = "module"), modules$server_args) |
98 | -2x | +326 | +80x |
- checkmate::assert_string(description, null.ok = TRUE)+ if (is_arg_used(modules$server, "reporter")) { |
99 | -2x | +327 | +1x |
- checkmate::assert_flag(with_filter)+ args <- c(args, list(reporter = reporter)) |
100 | -2x | +|||
328 | +
- checkmate::assert_class(filter_panel_api, classes = "FilterPanelAPI")+ } |
|||
101 | +329 | |||
102 | -2x | +330 | +80x |
- card <- teal::TealReportCard$new()+ if (is_arg_used(modules$server, "datasets")) { |
103 | -2x | +331 | +1x |
- title <- if (label == "") title else label+ args <- c(args, datasets = datasets()) |
104 | -2x | +332 | +1x |
- card$set_name(title)+ warning("datasets argument is not reactive and therefore it won't be updated when data is refreshed.") |
105 | -2x | +|||
333 | +
- card$append_text(title, "header2")+ } |
|||
106 | -1x | +|||
334 | +
- if (!is.null(description)) card$append_text(description, "header3")+ |
|||
107 | -1x | +335 | +80x |
- if (with_filter) card$append_fs(filter_panel_api$get_filter_state())+ if (is_arg_used(modules$server, "data")) { |
108 | -2x | +336 | +76x |
- card+ args <- c(args, data = list(data)) |
109 | +337 |
- }+ } |
||
110 | +338 | |||
111 | -+ | |||
339 | +80x |
-
+ if (is_arg_used(modules$server, "filter_panel_api")) { |
||
112 | -+ | |||
340 | +1x |
- #' Check `datanames` in modules+ args <- c(args, filter_panel_api = teal.slice::FilterPanelAPI$new(datasets())) |
||
113 | +341 |
- #'+ } |
||
114 | +342 |
- #' These functions check if specified `datanames` in modules match those in the data object,+ |
||
115 | -+ | |||
343 | +80x |
- #' returning error messages or `TRUE` for successful validation. Two functions return error message+ if (is_arg_used(modules$server, "id")) { |
||
116 | -+ | |||
344 | +80x |
- #' in different forms:+ do.call(modules$server, args) |
||
117 | +345 |
- #' - `check_modules_datanames` returns `character(1)` for basic assertion usage+ } else { |
||
118 | -+ | |||
346 | +! |
- #' - `check_modules_datanames_html` returns `shiny.tag.list` to display it in the app.+ do.call(callModule, c(args, list(module = modules$server))) |
||
119 | +347 |
- #'+ } |
||
120 | +348 |
- #' @param modules (`teal_modules`) object+ } |
||
121 | +349 |
- #' @param datanames (`character`) names of datasets available in the `data` object+ |
||
122 | +350 |
- #'+ .resolve_module_datanames <- function(data, modules) { |
||
123 | -+ | |||
351 | +177x |
- #' @return `TRUE` if validation passes, otherwise `character(1)` or `shiny.tag.list`+ stopifnot("data must be teal_data object." = inherits(data, "teal_data")) |
||
124 | -+ | |||
352 | +177x |
- #' @keywords internal+ if (is.null(modules$datanames) || identical(modules$datanames, "all")) { |
||
125 | -+ | |||
353 | +145x |
- check_modules_datanames <- function(modules, datanames) {+ names(data) |
||
126 | -11x | +|||
354 | +
- out <- check_modules_datanames_html(modules, datanames)+ } else { |
|||
127 | -11x | +355 | +32x |
- if (inherits(out, "shiny.tag.list")) {+ intersect( |
128 | -5x | +356 | +32x |
- out_with_ticks <- gsub("<code>|</code>", "`", toString(out))+ names(data), # Keep topological order from teal.data::names() |
129 | -5x | +357 | +32x |
- out_text <- gsub("<[^<>]+>", "", toString(out_with_ticks))- |
-
130 | -5x | -
- trimws(gsub("[[:space:]]+", " ", out_text))+ .include_parent_datanames(modules$datanames, teal.data::join_keys(data)) |
||
131 | +358 |
- } else {- |
- ||
132 | -6x | -
- out+ ) |
||
133 | +359 |
} |
||
134 | +360 |
} |
||
135 | +361 | |||
136 | +362 |
- #' @rdname check_modules_datanames+ #' Calls expression when condition is met |
||
137 | +363 |
- check_reserved_datanames <- function(datanames) {- |
- ||
138 | -190x | -
- reserved_datanames <- datanames[datanames %in% c("all", ".raw_data")]- |
- ||
139 | -190x | -
- if (length(reserved_datanames) == 0L) {+ #' |
||
140 | -184x | +|||
364 | +
- return(NULL)+ #' Function postpones `handlerExpr` to the moment when `eventExpr` (condition) returns `TRUE`, |
|||
141 | +365 |
- }+ #' otherwise nothing happens. |
||
142 | +366 |
-
+ #' @param eventExpr A (quoted or unquoted) logical expression that represents the event; |
||
143 | -6x | +|||
367 | +
- tags$span(+ #' this can be a simple reactive value like input$click, a call to a reactive expression |
|||
144 | -6x | +|||
368 | +
- to_html_code_list(reserved_datanames),+ #' like dataset(), or even a complex expression inside curly braces. |
|||
145 | -6x | +|||
369 | +
- sprintf(+ #' @param ... additional arguments passed to `observeEvent` with the exception of `eventExpr` that is not allowed. |
|||
146 | -6x | +|||
370 | +
- "%s reserved for internal use. Please avoid using %s as %s.",+ #' @inheritParams shiny::observeEvent |
|||
147 | -6x | +|||
371 | +
- pluralize(reserved_datanames, "is", "are"),+ #' |
|||
148 | -6x | +|||
372 | +
- pluralize(reserved_datanames, "it", "them"),+ #' @return An observer. |
|||
149 | -6x | +|||
373 | +
- pluralize(reserved_datanames, "a dataset name", "dataset names")+ #' |
|||
150 | +374 |
- )+ #' @keywords internal |
||
151 | +375 |
- )+ call_once_when <- function(eventExpr, # nolint: object_name. |
||
152 | +376 |
- }+ handlerExpr, # nolint: object_name. |
||
153 | +377 |
-
+ event.env = parent.frame(), # nolint: object_name. |
||
154 | +378 |
- #' @rdname check_modules_datanames+ handler.env = parent.frame(), # nolint: object_name. |
||
155 | +379 |
- check_modules_datanames_html <- function(modules, datanames) {+ ...) { |
||
156 | -190x | +380 | +198x |
- check_datanames <- check_modules_datanames_recursive(modules, datanames)+ event_quo <- rlang::new_quosure(substitute(eventExpr), env = event.env) |
157 | -190x | +381 | +198x |
- show_module_info <- inherits(modules, "teal_modules") # used in two contexts - module and app+ handler_quo <- rlang::new_quosure(substitute(handlerExpr), env = handler.env) |
158 | +382 | |||
159 | -190x | -
- reserved_datanames <- check_reserved_datanames(datanames)- |
- ||
160 | +383 |
-
+ # When `condExpr` is TRUE, then `handlerExpr` is evaluated once. |
||
161 | -190x | +384 | +198x |
- if (!length(check_datanames)) {+ activator <- reactive({ |
162 | -172x | +385 | +198x |
- out <- if (is.null(reserved_datanames)) {+ if (isTRUE(rlang::eval_tidy(event_quo))) { |
163 | +386 | 166x |
TRUE |
|
164 | +387 |
- } else {- |
- ||
165 | -6x | -
- shiny::tagList(reserved_datanames)+ } |
||
166 | +388 |
- }- |
- ||
167 | -172x | -
- return(out)+ }) |
||
168 | +389 |
- }+ |
||
169 | -18x | +390 | +198x |
- shiny::tagList(+ observeEvent( |
170 | -18x | +391 | +198x |
- reserved_datanames,+ eventExpr = activator(), |
171 | -18x | +392 | +198x |
- lapply(+ once = TRUE, |
172 | -18x | +393 | +198x |
- check_datanames,+ handlerExpr = rlang::eval_tidy(handler_quo), |
173 | -18x | +|||
394 | +
- function(mod) {+ ... |
|||
174 | -18x | +|||
395 | +
- tagList(+ ) |
|||
175 | -18x | +|||
396 | +
- tags$span(+ } |
|||
176 | -18x | +
1 | +
- tags$span(pluralize(mod$missing_datanames, "Dataset")),+ #' Filter state snapshot management |
|||
177 | -18x | +|||
2 | +
- to_html_code_list(mod$missing_datanames),+ #' |
|||
178 | -18x | +|||
3 | +
- tags$span(+ #' Capture and restore snapshots of the global (app) filter state. |
|||
179 | -18x | +|||
4 | +
- sprintf(+ #' |
|||
180 | -18x | +|||
5 | +
- "%s missing%s.",+ #' This module introduces snapshots: stored descriptions of the filter state of the entire application. |
|||
181 | -18x | +|||
6 | +
- pluralize(mod$missing_datanames, "is", "are"),+ #' Snapshots allow the user to save the current filter state of the application for later use in the session, |
|||
182 | -18x | +|||
7 | +
- if (show_module_info) sprintf(" for module '%s'", mod$label) else ""+ #' as well as to save it to file in order to share it with an app developer or other users, |
|||
183 | +8 |
- )+ #' who in turn can upload it to their own session. |
||
184 | +9 |
- )+ #' |
||
185 | +10 |
- ),+ #' The snapshot manager is accessed with the camera icon in the tabset bar. |
||
186 | -18x | +|||
11 | +
- if (length(datanames) >= 1) {+ #' At the beginning of a session it presents three icons: a camera, an upload, and an circular arrow. |
|||
187 | -16x | +|||
12 | +
- tagList(+ #' Clicking the camera captures a snapshot, clicking the upload adds a snapshot from a file |
|||
188 | -16x | +|||
13 | +
- tags$span(pluralize(datanames, "Dataset")),+ #' and applies the filter states therein, and clicking the arrow resets initial application state. |
|||
189 | -16x | +|||
14 | +
- tags$span("available in data:"),+ #' As snapshots are added, they will show up as rows in a table and each will have a select button and a save button. |
|||
190 | -16x | +|||
15 | +
- tagList(+ #' |
|||
191 | -16x | +|||
16 | +
- tags$span(+ #' @section Server logic: |
|||
192 | -16x | +|||
17 | +
- to_html_code_list(datanames),+ #' Snapshots are basically `teal_slices` objects, however, since each module is served by a separate instance |
|||
193 | -16x | +|||
18 | +
- tags$span(".", .noWS = "outside"),+ #' of `FilteredData` and these objects require shared state, `teal_slice` is a `reactiveVal` so `teal_slices` |
|||
194 | -16x | +|||
19 | +
- .noWS = c("outside")+ #' cannot be stored as is. Therefore, `teal_slices` are reversibly converted to a list of lists representation |
|||
195 | +20 |
- )+ #' (attributes are maintained). |
||
196 | +21 |
- )+ #' |
||
197 | +22 |
- )+ #' Snapshots are stored in a `reactiveVal` as a named list. |
||
198 | +23 |
- } else {+ #' The first snapshot is the initial state of the application and the user can add a snapshot whenever they see fit. |
||
199 | -2x | +|||
24 | +
- tags$span("No datasets are available in data.")+ #' |
|||
200 | +25 |
- },+ #' For every snapshot except the initial one, a piece of UI is generated that contains |
||
201 | -18x | +|||
26 | +
- tags$br(.noWS = "before")+ #' the snapshot name, a select button to restore that snapshot, and a save button to save it to a file. |
|||
202 | +27 |
- )+ #' The initial snapshot is restored by a separate "reset" button. |
||
203 | +28 |
- }+ #' It cannot be saved directly but a user is welcome to capture the initial state as a snapshot and save that. |
||
204 | +29 |
- )+ #' |
||
205 | +30 |
- )+ #' @section Snapshot mechanics: |
||
206 | +31 |
- }+ #' When a snapshot is captured, the user is prompted to name it. |
||
207 | +32 |
-
+ #' Names are displayed as is but since they are used to create button ids, |
||
208 | +33 |
- #' Recursively checks modules and returns list for every datanames mismatch between module and data+ #' under the hood they are converted to syntactically valid strings. |
||
209 | +34 |
- #' @noRd+ #' New snapshot names are validated so that their valid versions are unique. |
||
210 | +35 |
- check_modules_datanames_recursive <- function(modules, datanames) { # nolint: object_name_length+ #' Leading and trailing white space is trimmed. |
||
211 | -296x | +|||
36 | +
- checkmate::assert_multi_class(modules, c("teal_module", "teal_modules"))+ #' |
|||
212 | -296x | +|||
37 | +
- checkmate::assert_character(datanames)+ #' The module can read the global state of the application from `slices_global` and `mapping_matrix`. |
|||
213 | -296x | +|||
38 | +
- if (inherits(modules, "teal_modules")) {+ #' The former provides a list of all existing `teal_slice`s and the latter says which slice is active in which module. |
|||
214 | -86x | +|||
39 | +
- unlist(+ #' Once a name has been accepted, `slices_global` is converted to a list of lists - a snapshot. |
|||
215 | -86x | +|||
40 | +
- lapply(modules$children, check_modules_datanames_recursive, datanames = datanames),+ #' The snapshot contains the `mapping` attribute of the initial application state |
|||
216 | -86x | +|||
41 | +
- recursive = FALSE+ #' (or one that has been restored), which may not reflect the current one, |
|||
217 | +42 |
- )+ #' so `mapping_matrix` is transformed to obtain the current mapping, i.e. a list that, |
||
218 | +43 |
- } else {+ #' when passed to the `mapping` argument of [teal_slices()], would result in the current mapping. |
||
219 | -210x | +|||
44 | +
- missing_datanames <- setdiff(modules$datanames, c("all", datanames))+ #' This is substituted as the snapshot's `mapping` attribute and the snapshot is added to the snapshot list. |
|||
220 | -210x | +|||
45 | +
- if (length(missing_datanames)) {+ #' |
|||
221 | -18x | +|||
46 | +
- list(list(+ #' To restore app state, a snapshot is retrieved from storage and rebuilt into a `teal_slices` object. |
|||
222 | -18x | +|||
47 | +
- label = modules$label,+ #' Then state of all `FilteredData` objects (provided in `datasets`) is cleared |
|||
223 | -18x | +|||
48 | +
- missing_datanames = missing_datanames+ #' and set anew according to the `mapping` attribute of the snapshot. |
|||
224 | +49 |
- ))+ #' The snapshot is then set as the current content of `slices_global`. |
||
225 | +50 |
- }+ #' |
||
226 | +51 |
- }+ #' To save a snapshot, the snapshot is retrieved and reassembled just like for restoring, |
||
227 | +52 |
- }+ #' and then saved to file with [slices_store()]. |
||
228 | +53 |
-
+ #' |
||
229 | +54 |
- #' Convert character vector to html code separated with commas and "and"+ #' When a snapshot is uploaded, it will first be added to storage just like a newly created one, |
||
230 | +55 |
- #' @noRd+ #' and then used to restore app state much like a snapshot taken from storage. |
||
231 | +56 |
- to_html_code_list <- function(x) {+ #' Upon clicking the upload icon the user will be prompted for a file to upload |
||
232 | -40x | +|||
57 | +
- checkmate::assert_character(x)+ #' and may choose to name the new snapshot. The name defaults to the name of the file (the extension is dropped) |
|||
233 | -40x | +|||
58 | +
- do.call(+ #' and normal naming rules apply. Loading the file yields a `teal_slices` object, |
|||
234 | -40x | +|||
59 | +
- tagList,+ #' which is disassembled for storage and used directly for restoring app state. |
|||
235 | -40x | +|||
60 | +
- lapply(seq_along(x), function(.ix) {+ #' |
|||
236 | -56x | +|||
61 | +
- tagList(+ #' @section Transferring snapshots: |
|||
237 | -56x | +|||
62 | +
- tags$code(x[.ix]),+ #' Snapshots uploaded from disk should only be used in the same application they come from, |
|||
238 | -56x | +|||
63 | +
- if (.ix != length(x)) {+ #' _i.e._ an application that uses the same data and the same modules. |
|||
239 | -1x | +|||
64 | +
- if (.ix == length(x) - 1) tags$span(" and ") else tags$span(", ", .noWS = "before")+ #' To ensure this is the case, `init` stamps `teal_slices` with an app id that is stored in the `app_id` attribute of |
|||
240 | +65 |
- }+ #' a `teal_slices` object. When a snapshot is restored from file, its `app_id` is compared to that |
||
241 | +66 |
- )+ #' of the current app state and only if the match is the snapshot admitted to the session. |
||
242 | +67 |
- })+ #' |
||
243 | +68 |
- )+ #' @section Bookmarks: |
||
244 | +69 |
- }+ #' An `onBookmark` callback creates a snapshot of the current filter state. |
||
245 | +70 |
-
+ #' This is done on the app session, not the module session. |
||
246 | +71 |
-
+ #' (The snapshot will be retrieved by `module_teal` in order to set initial app state in a restored app.) |
||
247 | +72 |
- #' Check `datanames` in filters+ #' Then that snapshot, and the previous snapshot history are dumped into the `values.rds` file in `<bookmark_dir>`. |
||
248 | +73 |
#' |
||
249 | +74 |
- #' This function checks whether `datanames` in filters correspond to those in `data`,+ #' @param id (`character(1)`) `shiny` module instance id. |
||
250 | +75 |
- #' returning character vector with error messages or `TRUE` if all checks pass.+ #' @param slices_global (`reactiveVal`) that contains a `teal_slices` object |
||
251 | +76 |
- #'+ #' containing all `teal_slice`s existing in the app, both active and inactive. |
||
252 | +77 |
- #' @param filters (`teal_slices`) object+ #' |
||
253 | +78 |
- #' @param datanames (`character`) names of datasets available in the `data` object+ #' @return `list` containing the snapshot history, where each element is an unlisted `teal_slices` object. |
||
254 | +79 |
#' |
||
255 | +80 |
- #' @return A `character(1)` containing error message or TRUE if validation passes.+ #' @name module_snapshot_manager |
||
256 | +81 |
- #' @keywords internal+ #' @rdname module_snapshot_manager |
||
257 | +82 |
- check_filter_datanames <- function(filters, datanames) {+ #' |
||
258 | -86x | +|||
83 | +
- checkmate::assert_class(filters, "teal_slices")+ #' @author Aleksander Chlebowski |
|||
259 | -86x | +|||
84 | +
- checkmate::assert_character(datanames)+ #' @keywords internal |
|||
260 | +85 |
-
+ NULL |
||
261 | +86 |
- # check teal_slices against datanames+ |
||
262 | -86x | +|||
87 | +
- out <- unlist(sapply(+ #' @rdname module_snapshot_manager |
|||
263 | -86x | +|||
88 | +
- filters, function(filter) {+ ui_snapshot_manager_panel <- function(id) { |
|||
264 | -24x | +|||
89 | +! |
- dataname <- shiny::isolate(filter$dataname)+ ns <- NS(id) |
||
265 | -24x | +|||
90 | +! |
- if (!dataname %in% datanames) {+ tags$button( |
||
266 | -3x | +|||
91 | +! |
- sprintf(+ id = ns("show_snapshot_manager"), |
||
267 | -3x | +|||
92 | +! |
- "- Filter '%s' refers to dataname not available in 'data':\n %s not in (%s)",+ class = "btn action-button wunder_bar_button", |
||
268 | -3x | +|||
93 | +! |
- shiny::isolate(filter$id),+ title = "View filter mapping", |
||
269 | -3x | +|||
94 | +! |
- dQuote(dataname, q = FALSE),+ suppressMessages(icon("fas fa-camera")) |
||
270 | -3x | +|||
95 | +
- toString(dQuote(datanames, q = FALSE))+ ) |
|||
271 | +96 |
- )+ } |
||
272 | +97 |
- }+ |
||
273 | +98 |
- }+ #' @rdname module_snapshot_manager |
||
274 | +99 |
- ))+ srv_snapshot_manager_panel <- function(id, slices_global) { |
||
275 | -+ | |||
100 | +87x |
-
+ moduleServer(id, function(input, output, session) { |
||
276 | -+ | |||
101 | +87x |
-
+ logger::log_debug("srv_snapshot_manager_panel initializing") |
||
277 | -86x | +102 | +87x |
- if (length(out)) {+ setBookmarkExclude(c("show_snapshot_manager")) |
278 | -3x | +103 | +87x |
- paste(out, collapse = "\n")+ observeEvent(input$show_snapshot_manager, { |
279 | -+ | |||
104 | +! |
- } else {+ logger::log_debug("srv_snapshot_manager_panel@1 show_snapshot_manager button has been clicked.") |
||
280 | -83x | +|||
105 | +! |
- TRUE+ showModal( |
||
281 | -+ | |||
106 | +! |
- }+ modalDialog( |
||
282 | -+ | |||
107 | +! |
- }+ ui_snapshot_manager(session$ns("module")), |
||
283 | -+ | |||
108 | +! |
-
+ class = "snapshot_manager_modal", |
||
284 | -+ | |||
109 | +! |
- #' Function for validating the title parameter of `teal::init`+ size = "m", |
||
285 | -+ | |||
110 | +! |
- #'+ footer = NULL, |
||
286 | -+ | |||
111 | +! |
- #' Checks if the input of the title from `teal::init` will create a valid title and favicon tag.+ easyClose = TRUE |
||
287 | +112 |
- #' @param shiny_tag (`shiny.tag`) Object to validate for a valid title.+ ) |
||
288 | +113 |
- #' @keywords internal+ ) |
||
289 | +114 |
- validate_app_title_tag <- function(shiny_tag) {+ }) |
||
290 | -7x | +115 | +87x |
- checkmate::assert_class(shiny_tag, "shiny.tag")+ srv_snapshot_manager("module", slices_global = slices_global) |
291 | -7x | +|||
116 | +
- checkmate::assert_true(shiny_tag$name == "head")+ }) |
|||
292 | -6x | +|||
117 | +
- child_names <- vapply(shiny_tag$children, `[[`, character(1L), "name")+ } |
|||
293 | -6x | +|||
118 | +
- checkmate::assert_subset(c("title", "link"), child_names, .var.name = "child tags")+ |
|||
294 | -4x | +|||
119 | +
- rel_attr <- shiny_tag$children[[which(child_names == "link")]]$attribs$rel+ #' @rdname module_snapshot_manager |
|||
295 | -4x | +|||
120 | +
- checkmate::assert_subset(+ ui_snapshot_manager <- function(id) { |
|||
296 | -4x | +|||
121 | +! |
- rel_attr,+ ns <- NS(id) |
||
297 | -4x | +|||
122 | +! |
- c("icon", "shortcut icon"),+ tags$div( |
||
298 | -4x | +|||
123 | +! |
- .var.name = "Link tag's rel attribute",+ class = "manager_content", |
||
299 | -4x | +|||
124 | +! |
- empty.ok = FALSE+ tags$div( |
||
300 | -+ | |||
125 | +! |
- )+ class = "manager_table_row", |
||
301 | -+ | |||
126 | +! |
- }+ tags$span(tags$b("Snapshot manager")), |
||
302 | -+ | |||
127 | +! |
-
+ actionLink(ns("snapshot_add"), label = NULL, icon = icon("fas fa-camera"), title = "add snapshot"), |
||
303 | -+ | |||
128 | +! |
- #' Build app title with favicon+ actionLink(ns("snapshot_load"), label = NULL, icon = icon("fas fa-upload"), title = "upload snapshot"), |
||
304 | -+ | |||
129 | +! |
- #'+ actionLink(ns("snapshot_reset"), label = NULL, icon = icon("fas fa-undo"), title = "reset initial state"), |
||
305 | -+ | |||
130 | +! |
- #' A helper function to create the browser title along with a logo.+ NULL |
||
306 | +131 |
- #'+ ), |
||
307 | -+ | |||
132 | +! |
- #' @param title (`character`) The browser title for the `teal` app.+ uiOutput(ns("snapshot_list")) |
||
308 | +133 |
- #' @param favicon (`character`) The path for the icon for the title.+ ) |
||
309 | +134 |
- #' The image/icon path can be remote or the static path accessible by `shiny`, like the `www/`+ } |
||
310 | +135 |
- #'+ |
||
311 | +136 |
- #' @return A `shiny.tag` containing the element that adds the title and logo to the `shiny` app.+ #' @rdname module_snapshot_manager |
||
312 | +137 |
- #' @export+ srv_snapshot_manager <- function(id, slices_global) { |
||
313 | -+ | |||
138 | +87x |
- build_app_title <- function(+ checkmate::assert_character(id) |
||
314 | +139 |
- title = "teal app",+ |
||
315 | -+ | |||
140 | +87x |
- favicon = "https://raw.githubusercontent.com/insightsengineering/hex-stickers/main/PNG/nest.png") {+ moduleServer(id, function(input, output, session) { |
||
316 | -15x | +141 | +87x |
- checkmate::assert_string(title, null.ok = TRUE)+ logger::log_debug("srv_snapshot_manager initializing") |
317 | -15x | +|||
142 | +
- checkmate::assert_string(favicon, null.ok = TRUE)+ |
|||
318 | -15x | +|||
143 | +
- tags$head(+ # Set up bookmarking callbacks ---- |
|||
319 | -15x | +|||
144 | +
- tags$title(title),+ # Register bookmark exclusions (all buttons and text fields). |
|||
320 | -15x | +145 | +87x |
- tags$link(+ setBookmarkExclude(c( |
321 | -15x | +146 | +87x |
- rel = "icon",+ "snapshot_add", "snapshot_load", "snapshot_reset", |
322 | -15x | +147 | +87x |
- href = favicon,+ "snapshot_name_accept", "snaphot_file_accept", |
323 | -15x | +148 | +87x |
- sizes = "any"+ "snapshot_name", "snapshot_file" |
324 | +149 |
- )+ )) |
||
325 | +150 |
- )+ # Add snapshot history to bookmark. |
||
326 | -+ | |||
151 | +87x |
- }+ session$onBookmark(function(state) { |
||
327 | -+ | |||
152 | +! |
-
+ logger::log_debug("srv_snapshot_manager@onBookmark: storing snapshot and bookmark history") |
||
328 | -+ | |||
153 | +! |
- #' Application ID+ state$values$snapshot_history <- snapshot_history() # isolate this? |
||
329 | +154 |
- #'+ }) |
||
330 | +155 |
- #' Creates App ID used to match filter snapshots to application.+ |
||
331 | -+ | |||
156 | +87x |
- #'+ ns <- session$ns |
||
332 | +157 |
- #' Calculate app ID that will be used to stamp filter state snapshots.+ |
||
333 | +158 |
- #' App ID is a hash of the app's data and modules.+ # Track global filter states ---- |
||
334 | -+ | |||
159 | +87x |
- #' See "transferring snapshots" section in ?snapshot.+ snapshot_history <- reactiveVal({ |
||
335 | +160 |
- #'+ # Restore directly from bookmarked state, if applicable. |
||
336 | -+ | |||
161 | +87x |
- #' @param data (`teal_data` or `teal_data_module`) as accepted by `init`+ restoreValue( |
||
337 | -+ | |||
162 | +87x |
- #' @param modules (`teal_modules`) object as accepted by `init`+ ns("snapshot_history"), |
||
338 | -+ | |||
163 | +87x |
- #'+ list("Initial application state" = shiny::isolate(as.list(slices_global$all_slices(), recursive = TRUE))) |
||
339 | +164 |
- #' @return A single character string.+ ) |
||
340 | +165 |
- #'+ }) |
||
341 | +166 |
- #' @keywords internal+ |
||
342 | +167 |
- create_app_id <- function(data, modules) {- |
- ||
343 | -23x | -
- checkmate::assert_multi_class(data, c("teal_data", "teal_data_module"))- |
- ||
344 | -22x | -
- checkmate::assert_class(modules, "teal_modules")+ # Snapshot current application state ---- |
||
345 | +168 |
-
+ # Name snaphsot. |
||
346 | -21x | +169 | +87x |
- data <- if (inherits(data, "teal_data")) {+ observeEvent(input$snapshot_add, { |
347 | -19x | +|||
170 | +! |
- as.list(data)+ logger::log_debug("srv_snapshot_manager: snapshot_add button clicked") |
||
348 | -21x | +|||
171 | +! |
- } else if (inherits(data, "teal_data_module")) {+ showModal( |
||
349 | -2x | +|||
172 | +! |
- deparse1(body(data$server))+ modalDialog( |
||
350 | -+ | |||
173 | +! |
- }+ textInput(ns("snapshot_name"), "Name the snapshot", width = "100%", placeholder = "Meaningful, unique name"), |
||
351 | -21x | +|||
174 | +! |
- modules <- lapply(modules, defunction)+ footer = tagList( |
||
352 | -+ | |||
175 | +! |
-
+ actionButton(ns("snapshot_name_accept"), "Accept", icon = icon("far fa-thumbs-up")), |
||
353 | -21x | +|||
176 | +! |
- rlang::hash(list(data = data, modules = modules))+ modalButton(label = "Cancel", icon = icon("far fa-thumbs-down")) |
||
354 | +177 |
- }+ ), |
||
355 | -+ | |||
178 | +! |
-
+ size = "s" |
||
356 | +179 |
- #' Go through list and extract bodies of encountered functions as string, recursively.+ ) |
||
357 | +180 |
- #' @keywords internal+ ) |
||
358 | +181 |
- #' @noRd+ }) |
||
359 | +182 |
- defunction <- function(x) {+ # Store snaphsot. |
||
360 | -297x | +183 | +87x |
- if (is.list(x)) {+ observeEvent(input$snapshot_name_accept, { |
361 | -121x | +|||
184 | +! |
- lapply(x, defunction)+ logger::log_debug("srv_snapshot_manager: snapshot_name_accept button clicked") |
||
362 | -176x | +|||
185 | +! |
- } else if (is.function(x)) {+ snapshot_name <- trimws(input$snapshot_name) |
||
363 | -54x | +|||
186 | +! |
- deparse1(body(x))+ if (identical(snapshot_name, "")) { |
||
364 | -+ | |||
187 | +! |
- } else {+ logger::log_debug("srv_snapshot_manager: snapshot name rejected") |
||
365 | -122x | +|||
188 | +! |
- x+ showNotification( |
||
366 | -+ | |||
189 | +! |
- }+ "Please name the snapshot.", |
||
367 | -+ | |||
190 | +! |
- }+ type = "message" |
||
368 | +191 |
-
+ ) |
||
369 | -+ | |||
192 | +! |
- #' Get unique labels+ updateTextInput(inputId = "snapshot_name", value = "", placeholder = "Meaningful, unique name") |
||
370 | -+ | |||
193 | +! |
- #'+ } else if (is.element(make.names(snapshot_name), make.names(names(snapshot_history())))) { |
||
371 | -+ | |||
194 | +! |
- #' Get unique labels for the modules to avoid namespace conflicts.+ logger::log_debug("srv_snapshot_manager: snapshot name rejected") |
||
372 | -+ | |||
195 | +! |
- #'+ showNotification( |
||
373 | -+ | |||
196 | +! |
- #' @param labels (`character`) vector of labels+ "This name is in conflict with other snapshot names. Please choose a different one.", |
||
374 | -+ | |||
197 | +! |
- #'+ type = "message" |
||
375 | +198 |
- #' @return (`character`) vector of unique labels+ ) |
||
376 | -+ | |||
199 | +! |
- #'+ updateTextInput(inputId = "snapshot_name", value = "", placeholder = "Meaningful, unique name") |
||
377 | +200 |
- #' @keywords internal+ } else { |
||
378 | -+ | |||
201 | +! |
- get_unique_labels <- function(labels) {+ logger::log_debug("srv_snapshot_manager: snapshot name accepted, adding snapshot") |
||
379 | -141x | -
- make.unique(gsub("[^[:alnum:]]", "_", tolower(labels)), sep = "_")- |
- ||
380 | -- |
- }- |
- ||
381 | -- | - - | -||
382 | -- |
- #' Remove ANSI escape sequences from a string- |
- ||
383 | -- |
- #' @noRd- |
- ||
384 | -+ | |||
202 | +! |
- strip_style <- function(string) {+ snapshot <- as.list(slices_global$all_slices(), recursive = TRUE) |
||
385 | -2x | +|||
203 | +! |
- checkmate::assert_string(string)+ snapshot_update <- c(snapshot_history(), list(snapshot)) |
||
386 | -+ | |||
204 | +! |
-
+ names(snapshot_update)[length(snapshot_update)] <- snapshot_name |
||
387 | -2x | +|||
205 | +! |
- gsub(+ snapshot_history(snapshot_update) |
||
388 | -2x | +|||
206 | +! |
- "(?:(?:\\x{001b}\\[)|\\x{009b})(?:(?:[0-9]{1,3})?(?:(?:;[0-9]{0,3})*)?[A-M|f-m])|\\x{001b}[A-M]",+ removeModal() |
||
389 | +207 |
- "",- |
- ||
390 | -2x | -
- string,- |
- ||
391 | -2x | -
- perl = TRUE,+ # Reopen filter manager modal by clicking button in the main application. |
||
392 | -2x | +|||
208 | +! |
- useBytes = TRUE+ shinyjs::click(id = "teal-wunder_bar-show_snapshot_manager", asis = TRUE) |
||
393 | +209 |
- )+ } |
||
394 | +210 |
- }+ }) |
||
395 | +211 | |||
396 | +212 |
- #' @keywords internal+ # Upload a snapshot file ---- |
||
397 | +213 |
- #' @noRd+ # Select file. |
||
398 | -4x | -
- pasten <- function(...) paste0(..., "\n")- |
- ||
399 | -- | - - | -||
400 | -- |
- #' Convert character list to human readable html with commas and "and"- |
- ||
401 | -- |
- #' @noRd- |
- ||
402 | -- |
- paste_datanames_character <- function(x,- |
- ||
403 | -+ | 214 | +87x |
- tags = list(span = shiny::tags$span, code = shiny::tags$code),+ observeEvent(input$snapshot_load, { |
404 | -+ | |||
215 | +! |
- tagList = shiny::tagList) { # nolint: object_name.+ logger::log_debug("srv_snapshot_manager: snapshot_load button clicked") |
||
405 | +216 | ! |
- checkmate::assert_character(x)+ showModal( |
|
406 | +217 | ! |
- do.call(+ modalDialog( |
|
407 | +218 | ! |
- tagList,+ fileInput(ns("snapshot_file"), "Choose snapshot file", accept = ".json", width = "100%"), |
|
408 | +219 | ! |
- lapply(seq_along(x), function(.ix) {+ textInput( |
|
409 | +220 | ! |
- tagList(+ ns("snapshot_name"), |
|
410 | +221 | ! |
- tags$code(x[.ix]),+ "Name the snapshot (optional)", |
|
411 | +222 | ! |
- if (.ix != length(x)) {+ width = "100%", |
|
412 | +223 | ! |
- tags$span(if (.ix == length(x) - 1) " and " else ", ")+ placeholder = "Meaningful, unique name" |
|
413 | +224 |
- }+ ), |
||
414 | -+ | |||
225 | +! |
- )+ footer = tagList( |
||
415 | -+ | |||
226 | +! |
- })+ actionButton(ns("snaphot_file_accept"), "Accept", icon = icon("far fa-thumbs-up")), |
||
416 | -+ | |||
227 | +! |
- )+ modalButton(label = "Cancel", icon = icon("far fa-thumbs-down")) |
||
417 | +228 |
- }+ ) |
||
418 | +229 |
-
+ ) |
||
419 | +230 |
- #' Build datanames error string for error message+ ) |
||
420 | +231 |
- #'+ }) |
||
421 | +232 |
- #' tags and tagList are overwritten in arguments allowing to create strings for+ # Store new snapshot to list and restore filter states. |
||
422 | -+ | |||
233 | +87x |
- #' logging purposes+ observeEvent(input$snaphot_file_accept, { |
||
423 | -+ | |||
234 | +! |
- #' @noRd+ logger::log_debug("srv_snapshot_manager: snapshot_file_accept button clicked") |
||
424 | -+ | |||
235 | +! |
- build_datanames_error_message <- function(label = NULL,+ snapshot_name <- trimws(input$snapshot_name) |
||
425 | -+ | |||
236 | +! |
- datanames,+ if (identical(snapshot_name, "")) { |
||
426 | -+ | |||
237 | +! |
- extra_datanames,+ logger::log_debug("srv_snapshot_manager: no snapshot name provided, naming after file") |
||
427 | -+ | |||
238 | +! |
- tags = list(span = shiny::tags$span, code = shiny::tags$code),+ snapshot_name <- tools::file_path_sans_ext(input$snapshot_file$name) |
||
428 | +239 |
- tagList = shiny::tagList) { # nolint: object_name.+ } |
||
429 | +240 | ! |
- tags$span(+ if (is.element(make.names(snapshot_name), make.names(names(snapshot_history())))) { |
|
430 | +241 | ! |
- tags$span(pluralize(extra_datanames, "Dataset")),+ logger::log_debug("srv_snapshot_manager: snapshot name rejected") |
|
431 | +242 | ! |
- paste_datanames_character(extra_datanames, tags, tagList),+ showNotification( |
|
432 | +243 | ! |
- tags$span(+ "This name is in conflict with other snapshot names. Please choose a different one.", |
|
433 | +244 | ! |
- sprintf(+ type = "message" |
|
434 | -! | +|||
245 | +
- "%s missing%s",+ ) |
|||
435 | +246 | ! |
- pluralize(extra_datanames, "is", "are"),+ updateTextInput(inputId = "snapshot_name", value = "", placeholder = "Meaningful, unique name") |
|
436 | -! | +|||
247 | +
- if (is.null(label)) "" else sprintf(" for tab '%s'", label)+ } else { |
|||
437 | +248 |
- )+ # Restore snapshot and verify app compatibility. |
||
438 | -+ | |||
249 | +! |
- ),+ logger::log_debug("srv_snapshot_manager: snapshot name accepted, loading snapshot") |
||
439 | +250 | ! |
- if (length(datanames) >= 1) {+ snapshot_state <- try(slices_restore(input$snapshot_file$datapath)) |
|
440 | +251 | ! |
- tagList(+ if (!inherits(snapshot_state, "modules_teal_slices")) { |
|
441 | +252 | ! |
- tags$span(pluralize(datanames, "Dataset")),+ logger::log_debug("srv_snapshot_manager: snapshot file corrupt") |
|
442 | +253 | ! |
- tags$span("available in data:"),+ showNotification( |
|
443 | +254 | ! |
- tagList(+ "File appears to be corrupt.", |
|
444 | +255 | ! |
- tags$span(+ type = "error"+ |
+ |
256 | ++ |
+ ) |
||
445 | +257 | ! |
- paste_datanames_character(datanames, tags, tagList),+ } else if (!identical(attr(snapshot_state, "app_id"), attr(slices_global$all_slices(), "app_id"))) { |
|
446 | +258 | ! |
- tags$span(".", .noWS = "outside"),+ logger::log_debug("srv_snapshot_manager: snapshot not compatible with app") |
|
447 | +259 | ! |
- .noWS = c("outside")+ showNotification( |
|
448 | -+ | |||
260 | +! |
- )+ "This snapshot file is not compatible with the app and cannot be loaded.",+ |
+ ||
261 | +! | +
+ type = "warning" |
||
449 | +262 |
- )+ ) |
||
450 | +263 |
- )+ } else { |
||
451 | +264 |
- } else {+ # Add to snapshot history. |
||
452 | +265 | ! |
- tags$span("No datasets are available in data.")+ logger::log_debug("srv_snapshot_manager: snapshot loaded, adding to history") |
|
453 | -+ | |||
266 | +! |
- }+ snapshot <- as.list(slices_global$all_slices(), recursive = TRUE) |
||
454 | -+ | |||
267 | +! |
- )+ snapshot_update <- c(snapshot_history(), list(snapshot)) |
||
455 | -+ | |||
268 | +! |
- }+ names(snapshot_update)[length(snapshot_update)] <- snapshot_name |
||
456 | -+ | |||
269 | +! |
-
+ snapshot_history(snapshot_update) |
||
457 | +270 |
- #' Smart `rbind`+ ### Begin simplified restore procedure. ### |
||
458 | -+ | |||
271 | +! |
- #'+ logger::log_debug("srv_snapshot_manager: restoring snapshot") |
||
459 | -+ | |||
272 | +! |
- #' Combine `data.frame` objects which have different columns+ slices_global$slices_set(snapshot_state) |
||
460 | -+ | |||
273 | +! |
- #'+ removeModal() |
||
461 | +274 |
- #' @param ... (`data.frame`)+ ### End simplified restore procedure. ### |
||
462 | +275 |
- #' @keywords internal+ } |
||
463 | +276 |
- .smart_rbind <- function(...) {- |
- ||
464 | -89x | -
- dots <- list(...)- |
- ||
465 | -89x | -
- checkmate::assert_list(dots, "data.frame", .var.name = "...")- |
- ||
466 | -89x | -
- Reduce(- |
- ||
467 | -89x | -
- x = dots,- |
- ||
468 | -89x | -
- function(x, y) {- |
- ||
469 | -72x | -
- all_columns <- union(colnames(x), colnames(y))- |
- ||
470 | -72x | -
- x[setdiff(all_columns, colnames(x))] <- NA- |
- ||
471 | -72x | -
- y[setdiff(all_columns, colnames(y))] <- NA- |
- ||
472 | -72x | -
- rbind(x, y)- |
- ||
473 | -- |
- }- |
- ||
474 | -- |
- )- |
- ||
475 | -- |
- }- |
- ||
476 | -- | - - | -||
477 | -- |
- #' Pluralize a word depending on the size of the input- |
- ||
478 | -- |
- #'- |
- ||
479 | -- |
- #' @param x (`object`) to check length for plural.- |
- ||
480 | -- |
- #' @param singular (`character`) singular form of the word.- |
- ||
481 | -- |
- #' @param plural (optional `character`) plural form of the word. If not given an "s"- |
- ||
482 | -- |
- #' is added to the singular form.- |
- ||
483 | -- |
- #'- |
- ||
484 | -- |
- #' @return A `character` that correctly represents the size of the `x` argument.- |
- ||
485 | -- |
- #' @keywords internal- |
- ||
486 | -- |
- pluralize <- function(x, singular, plural = NULL) {- |
- ||
487 | -70x | -
- checkmate::assert_string(singular)- |
- ||
488 | -70x | -
- checkmate::assert_string(plural, null.ok = TRUE)- |
- ||
489 | -70x | -
- if (length(x) == 1L) { # Zero length object should use plural form.- |
- ||
490 | -42x | -
- singular- |
- ||
491 | -- |
- } else {- |
- ||
492 | -28x | -
- if (is.null(plural)) {- |
- ||
493 | -12x | -
- sprintf("%ss", singular)- |
- ||
494 | -- |
- } else {- |
- ||
495 | -16x | -
- plural- |
- ||
496 | -- |
- }- |
- ||
497 | -- |
- }- |
- ||
498 | -- |
- }- |
-
1 | -- |
- #' Create a `teal` module for previewing a report- |
-
2 | -- |
- #'- |
-
3 | -- |
- #' @description `r lifecycle::badge("experimental")`- |
-
4 | -- |
- #'- |
-
5 | -- |
- #' This function wraps [teal.reporter::reporter_previewer_ui()] and- |
-
6 | -- |
- #' [teal.reporter::reporter_previewer_srv()] into a `teal_module` to be- |
-
7 | -- |
- #' used in `teal` applications.- |
-
8 | -- |
- #'- |
-
9 | -- |
- #' If you are creating a `teal` application using [init()] then this- |
-
10 | -- |
- #' module will be added to your application automatically if any of your `teal_modules`- |
-
11 | -- |
- #' support report generation.- |
-
12 | -- |
- #'- |
-
13 | -- |
- #' @inheritParams teal_modules- |
-
14 | -- |
- #' @param server_args (named `list`)- |
-
15 | -- |
- #' Arguments passed to [teal.reporter::reporter_previewer_srv()].- |
-
16 | -- |
- #'- |
-
17 | -- |
- #' @return- |
-
18 | -- |
- #' `teal_module` (extended with `teal_module_previewer` class) containing the `teal.reporter` previewer functionality.- |
-
19 | -- |
- #'- |
-
20 | -- |
- #' @export- |
-
21 | -- |
- #'- |
-
22 | -- |
- reporter_previewer_module <- function(label = "Report previewer", server_args = list()) {- |
-
23 | -7x | -
- checkmate::assert_string(label)- |
-
24 | -5x | -
- checkmate::assert_list(server_args, names = "named")- |
-
25 | -5x | -
- checkmate::assert_true(all(names(server_args) %in% names(formals(teal.reporter::reporter_previewer_srv))))- |
-
26 | -- | - - | -
27 | -3x | -
- message("Initializing reporter_previewer_module")- |
-
28 | -- | - - | -
29 | -3x | -
- srv <- function(id, reporter, ...) {- |
-
30 | -! | -
- teal.reporter::reporter_previewer_srv(id, reporter, ...)- |
-
31 | -- |
- }- |
-
32 | -- | - - | -
33 | -3x | -
- ui <- function(id, ...) {- |
-
34 | -! | -
- teal.reporter::reporter_previewer_ui(id, ...)- |
-
35 | -- |
- }- |
-
36 | -- | - - | -
37 | -3x | -
- module <- module(- |
-
38 | -3x | -
- label = "temporary label",- |
-
39 | -3x | -
- server = srv, ui = ui,- |
-
40 | -3x | -
- server_args = server_args, ui_args = list(), datanames = NULL- |
-
41 | -- |
- )- |
-
42 | -- |
- # Module is created with a placeholder label and the label is changed later.- |
-
43 | -- |
- # This is to prevent another module being labeled "Report previewer".- |
-
44 | -3x | -
- class(module) <- c(class(module), "teal_module_previewer")- |
-
45 | -3x | -
- module$label <- label- |
-
46 | -3x | -
- attr(module, "teal_bookmarkable") <- TRUE- |
-
47 | -3x | -
- module- |
-
48 | -- |
- }- |
-
1 | -- |
- #' Data Module for teal- |
- ||
2 | -- |
- #'- |
- ||
3 | -- |
- #' This module manages the `data` argument for `srv_teal`. The `teal` framework uses [teal.data::teal_data()],- |
- ||
4 | -- |
- #' which can be provided in various ways:- |
- ||
5 | -- |
- #' 1. Directly as a [teal.data::teal_data()] object. This will automatically convert it into a `reactive` `teal_data`.- |
- ||
6 | -- |
- #' 2. As a `reactive` object that returns a [teal.data::teal_data()] object.- |
- ||
7 | -- |
- #'- |
- ||
8 | -- |
- #' @details- |
- ||
9 | -- |
- #' ## Reactive `teal_data`:- |
- ||
10 | -- |
- #'- |
- ||
11 | -- |
- #' The data in the application can be reactively updated, prompting [srv_teal()] to rebuild the- |
- ||
12 | -- |
- #' content accordingly. There are two methods for creating interactive `teal_data`:- |
- ||
13 | -- |
- #' 1. Using a `reactive` object provided from outside the `teal` application. In this scenario,- |
- ||
14 | -- |
- #' reactivity is controlled by an external module, and `srv_teal` responds to changes.- |
- ||
15 | -- |
- #' 2. Using [teal_data_module()], which is embedded within the `teal` application, allowing data to- |
- ||
16 | -- |
- #' be resubmitted by the user as needed.- |
- ||
17 | -- |
- #'- |
- ||
18 | -- |
- #' Since the server of [teal_data_module()] must return a `reactive` `teal_data` object, both- |
- ||
19 | -- |
- #' methods (1 and 2) produce the same reactive behavior within a `teal` application. The distinction- |
- ||
20 | -- |
- #' lies in data control: the first method involves external control, while the second method- |
- ||
21 | -- |
- #' involves control from a custom module within the app.- |
- ||
22 | -- |
- #'- |
- ||
23 | -- |
- #' For more details, see [`module_teal_data`].- |
- ||
24 | -- |
- #'- |
- ||
25 | -- |
- #' @inheritParams init- |
- ||
26 | -- |
- #'- |
- ||
27 | -- |
- #' @param data (`teal_data`, `teal_data_module`, or `reactive` returning `teal_data`)- |
- ||
28 | -- |
- #' The data which application will depend on.- |
- ||
29 | -- |
- #'- |
- ||
30 | -- |
- #' @return A `reactive` object that returns:- |
- ||
31 | -- |
- #' Output of the `data`. If `data` fails then returned error is handled (after [tryCatch()]) so that- |
- ||
32 | -- |
- #' rest of the application can respond to this respectively.- |
- ||
33 | -- |
- #'- |
- ||
34 | -- |
- #' @rdname module_init_data- |
- ||
35 | -- |
- #' @name module_init_data- |
- ||
36 | -- |
- #' @keywords internal- |
- ||
37 | -- |
- NULL- |
- ||
38 | -- | - - | -||
39 | -- |
- #' @rdname module_init_data- |
- ||
40 | -- |
- ui_init_data <- function(id) {- |
- ||
41 | -9x | -
- ns <- shiny::NS(id)- |
- ||
42 | -9x | -
- shiny::div(- |
- ||
43 | -9x | -
- id = ns("content"),- |
- ||
44 | -9x | -
- style = "display: inline-block; width: 100%;",- |
- ||
45 | -9x | -
- uiOutput(ns("data"))- |
- ||
46 | -- |
- )- |
- ||
47 | -- |
- }- |
- ||
48 | -- | - - | -||
49 | -- |
- #' @rdname module_init_data- |
- ||
50 | -- |
- srv_init_data <- function(id, data) {- |
- ||
51 | -88x | -
- checkmate::assert_character(id, max.len = 1, any.missing = FALSE)- |
- ||
52 | -88x | -
- checkmate::assert_multi_class(data, c("teal_data", "teal_data_module", "reactive"))- |
- ||
53 | -- | - - | -||
54 | -88x | -
- moduleServer(id, function(input, output, session) {- |
- ||
55 | -88x | -
- logger::log_debug("srv_data initializing.")- |
- ||
56 | -- |
- # data_rv contains teal_data object- |
- ||
57 | -- |
- # either passed to teal::init or returned from teal_data_module- |
- ||
58 | -88x | -
- data_out <- if (inherits(data, "teal_data_module")) {- |
- ||
59 | -10x | -
- output$data <- renderUI(data$ui(id = session$ns("teal_data_module")))- |
- ||
60 | -10x | -
- data$server("teal_data_module")- |
- ||
61 | -88x | -
- } else if (inherits(data, "teal_data")) {- |
- ||
62 | -48x | -
- reactiveVal(data)- |
- ||
63 | -88x | -
- } else if (test_reactive(data)) {- |
- ||
64 | -30x | -
- data- |
- ||
65 | -- |
- }- |
- ||
66 | -- | - - | -||
67 | -87x | -
- data_handled <- reactive({- |
- ||
68 | -80x | -
- tryCatch(data_out(), error = function(e) e)+ } |
||
69 | +277 |
}) |
||
70 | +278 |
-
+ # Apply newly added snapshot. |
||
71 | +279 |
- # We want to exclude teal_data_module elements from bookmarking as they might have some secrets+ |
||
72 | -87x | +|||
280 | +
- observeEvent(data_handled(), {+ # Restore initial state ---- |
|||
73 | -80x | +281 | +87x |
- if (inherits(data_handled(), "teal_data")) {+ observeEvent(input$snapshot_reset, { |
74 | -75x | +282 | +2x |
- app_session <- .subset2(shiny::getDefaultReactiveDomain(), "parent")+ logger::log_debug("srv_snapshot_manager: snapshot_reset button clicked, restoring snapshot") |
75 | -75x | +283 | +2x |
- setBookmarkExclude(+ s <- "Initial application state" |
76 | -75x | +|||
284 | +
- session$ns(+ ### Begin restore procedure. ### |
|||
77 | -75x | +285 | +2x |
- grep(+ snapshot <- snapshot_history()[[s]] |
78 | -75x | +286 | +2x |
- pattern = "teal_data_module-",+ snapshot_state <- as.teal_slices(snapshot) |
79 | -75x | +287 | +2x |
- x = names(reactiveValuesToList(input)),+ slices_global$slices_set(snapshot_state) |
80 | -75x | +288 | +2x |
- value = TRUE+ removeModal() |
81 | +289 |
- )+ ### End restore procedure. ### |
||
82 | +290 |
- ),+ }) |
||
83 | -75x | +|||
291 | +
- session = app_session+ |
|||
84 | +292 |
- )+ # Build snapshot table ---- |
||
85 | +293 |
- }+ # Create UI elements and server logic for the snapshot table. |
||
86 | +294 |
- })+ # Observers must be tracked to avoid duplication and excess reactivity. |
||
87 | +295 |
-
+ # Remaining elements are tracked likewise for consistency and a slight speed margin. |
||
88 | +296 | 87x |
- data_handled+ observers <- reactiveValues() |
|
89 | -+ | |||
297 | +87x |
- })+ handlers <- reactiveValues() |
||
90 | -+ | |||
298 | +87x |
- }+ divs <- reactiveValues() |
||
91 | +299 | |||
92 | -+ | |||
300 | +87x |
- #' Adds signature protection to the `datanames` in the data+ observeEvent(snapshot_history(), { |
||
93 | -+ | |||
301 | +77x |
- #' @param data (`teal_data`)+ logger::log_debug("srv_snapshot_manager: snapshot history modified, updating snapshot list") |
||
94 | -+ | |||
302 | +77x |
- #' @return `teal_data` with additional code that has signature of the `datanames`+ lapply(names(snapshot_history())[-1L], function(s) { |
||
95 | -+ | |||
303 | +! |
- #' @keywords internal+ id_pickme <- sprintf("pickme_%s", make.names(s)) |
||
96 | -+ | |||
304 | +! |
- .add_signature_to_data <- function(data) {+ id_saveme <- sprintf("saveme_%s", make.names(s)) |
||
97 | -75x | +|||
305 | +! |
- hashes <- .get_hashes_code(data)+ id_rowme <- sprintf("rowme_%s", make.names(s)) |
||
98 | -75x | +|||
306 | +
- tdata <- do.call(+ |
|||
99 | -75x | +|||
307 | +
- teal.data::teal_data,+ # Observer for restoring snapshot. |
|||
100 | -75x | +|||
308 | +! |
- c(+ if (!is.element(id_pickme, names(observers))) { |
||
101 | -75x | +|||
309 | +! |
- list(code = trimws(c(teal.code::get_code(data), hashes), which = "right")),+ observers[[id_pickme]] <- observeEvent(input[[id_pickme]], { |
||
102 | -75x | +|||
310 | +
- list(join_keys = teal.data::join_keys(data)),+ ### Begin restore procedure. ### |
|||
103 | -75x | +|||
311 | +! |
- sapply(+ snapshot <- snapshot_history()[[s]] |
||
104 | -75x | +|||
312 | +! |
- names(data),+ snapshot_state <- as.teal_slices(snapshot) |
||
105 | -75x | +|||
313 | +
- teal.code::get_var,+ |
|||
106 | -75x | +|||
314 | +! |
- object = data,+ slices_global$slices_set(snapshot_state) |
||
107 | -75x | +|||
315 | +! |
- simplify = FALSE+ removeModal() |
||
108 | +316 |
- )+ ### End restore procedure. ### |
||
109 | +317 |
- )+ }) |
||
110 | +318 |
- )+ } |
||
111 | +319 |
-
+ # Create handler for downloading snapshot. |
||
112 | -75x | +|||
320 | +! |
- tdata@verified <- data@verified+ if (!is.element(id_saveme, names(handlers))) { |
||
113 | -75x | +|||
321 | +! |
- tdata+ output[[id_saveme]] <- downloadHandler( |
||
114 | -+ | |||
322 | +! |
- }+ filename = function() { |
||
115 | -+ | |||
323 | +! |
-
+ sprintf("teal_snapshot_%s_%s.json", s, Sys.Date()) |
||
116 | +324 |
- #' Get code that tests the integrity of the reproducible data+ }, |
||
117 | -+ | |||
325 | +! |
- #'+ content = function(file) { |
||
118 | -+ | |||
326 | +! |
- #' @param data (`teal_data`) object holding the data+ snapshot <- snapshot_history()[[s]] |
||
119 | -+ | |||
327 | +! |
- #' @param datanames (`character`) names of `datasets`+ snapshot_state <- as.teal_slices(snapshot) |
||
120 | -+ | |||
328 | +! |
- #'+ slices_store(tss = snapshot_state, file = file) |
||
121 | +329 |
- #' @return A character vector with the code lines.+ } |
||
122 | +330 |
- #' @keywords internal+ )+ |
+ ||
331 | +! | +
+ handlers[[id_saveme]] <- id_saveme |
||
123 | +332 |
- #'+ } |
||
124 | +333 |
- .get_hashes_code <- function(data, datanames = names(data)) {+ # Create a row for the snapshot table. |
||
125 | -75x | +|||
334 | +! |
- vapply(+ if (!is.element(id_rowme, names(divs))) { |
||
126 | -75x | +|||
335 | +! |
- datanames,+ divs[[id_rowme]] <- tags$div( |
||
127 | -75x | +|||
336 | +! |
- function(dataname, datasets) {+ class = "manager_table_row", |
||
128 | -133x | +|||
337 | +! |
- x <- data[[dataname]]+ tags$span(tags$h5(s)), |
||
129 | -+ | |||
338 | +! |
-
+ actionLink(inputId = ns(id_pickme), label = icon("far fa-circle-check"), title = "select"), |
||
130 | -133x | +|||
339 | +! |
- code <- if (is.function(x) && !is.primitive(x)) {+ downloadLink(outputId = ns(id_saveme), label = icon("far fa-save"), title = "save to file") |
||
131 | -6x | +|||
340 | +
- x <- deparse1(x)+ ) |
|||
132 | -6x | +|||
341 | +
- bquote(rlang::hash(deparse1(.(as.name(dataname)))))+ } |
|||
133 | +342 |
- } else {+ }) |
||
134 | -127x | +|||
343 | +
- bquote(rlang::hash(.(as.name(dataname))))+ }) |
|||
135 | +344 |
- }+ + |
+ ||
345 | ++ |
+ # Create table to display list of snapshots and their actions. |
||
136 | -133x | +346 | +87x |
- sprintf(+ output$snapshot_list <- renderUI({ |
137 | -133x | +347 | +77x |
- "stopifnot(%s == %s) # @linksto %s",+ rows <- rev(reactiveValuesToList(divs)) |
138 | -133x | +348 | +77x |
- deparse1(code),+ if (length(rows) == 0L) { |
139 | -133x | +349 | +77x |
- deparse1(rlang::hash(x)),+ tags$div( |
140 | -133x | +350 | +77x |
- dataname+ class = "manager_placeholder",+ |
+
351 | +77x | +
+ "Snapshots will appear here." |
||
141 | +352 |
- )+ ) |
||
142 | +353 |
- },+ } else { |
||
143 | -75x | +|||
354 | +! | +
+ rows+ |
+ ||
355 | ++ |
+ }+ |
+ ||
356 | ++ |
+ })+ |
+ ||
357 | +
- character(1L),+ |
|||
144 | -75x | +358 | +87x |
- USE.NAMES = TRUE+ snapshot_history |
145 | +359 |
- )+ }) |
||
146 | +360 |
}@@ -8395,973 +7424,973 @@ teal coverage - 60.11% |
1 |
- #' Filter state snapshot management+ #' @title `TealReportCard` |
||
2 |
- #'+ #' @description `r lifecycle::badge("experimental")` |
||
3 |
- #' Capture and restore snapshots of the global (app) filter state.+ #' Child class of [`teal.reporter::ReportCard`] that is used for `teal` specific applications. |
||
4 |
- #'+ #' In addition to the parent methods, it supports rendering `teal` specific elements such as |
||
5 |
- #' This module introduces snapshots: stored descriptions of the filter state of the entire application.+ #' the source code, the encodings panel content and the filter panel content as part of the |
||
6 |
- #' Snapshots allow the user to save the current filter state of the application for later use in the session,+ #' meta data. |
||
7 |
- #' as well as to save it to file in order to share it with an app developer or other users,+ #' @export |
||
8 |
- #' who in turn can upload it to their own session.+ #' |
||
9 |
- #'+ TealReportCard <- R6::R6Class( # nolint: object_name. |
||
10 |
- #' The snapshot manager is accessed with the camera icon in the tabset bar.+ classname = "TealReportCard", |
||
11 |
- #' At the beginning of a session it presents three icons: a camera, an upload, and an circular arrow.+ inherit = teal.reporter::ReportCard, |
||
12 |
- #' Clicking the camera captures a snapshot, clicking the upload adds a snapshot from a file+ public = list( |
||
13 |
- #' and applies the filter states therein, and clicking the arrow resets initial application state.+ #' @description Appends the source code to the `content` meta data of this `TealReportCard`. |
||
14 |
- #' As snapshots are added, they will show up as rows in a table and each will have a select button and a save button.+ #' |
||
15 |
- #'+ #' @param src (`character(1)`) code as text. |
||
16 |
- #' @section Server logic:+ #' @param ... any `rmarkdown` `R` chunk parameter and its value. |
||
17 |
- #' Snapshots are basically `teal_slices` objects, however, since each module is served by a separate instance+ #' But `eval` parameter is always set to `FALSE`. |
||
18 |
- #' of `FilteredData` and these objects require shared state, `teal_slice` is a `reactiveVal` so `teal_slices`+ #' @return Object of class `TealReportCard`, invisibly. |
||
19 |
- #' cannot be stored as is. Therefore, `teal_slices` are reversibly converted to a list of lists representation+ #' @examples |
||
20 |
- #' (attributes are maintained).+ #' card <- TealReportCard$new()$append_src( |
||
21 |
- #'+ #' "plot(iris)" |
||
22 |
- #' Snapshots are stored in a `reactiveVal` as a named list.+ #' ) |
||
23 |
- #' The first snapshot is the initial state of the application and the user can add a snapshot whenever they see fit.+ #' card$get_content()[[1]]$get_content() |
||
24 |
- #'+ append_src = function(src, ...) { |
||
25 | -+ | 4x |
- #' For every snapshot except the initial one, a piece of UI is generated that contains+ checkmate::assert_character(src, min.len = 0, max.len = 1) |
26 | -+ | 4x |
- #' the snapshot name, a select button to restore that snapshot, and a save button to save it to a file.+ params <- list(...) |
27 | -+ | 4x |
- #' The initial snapshot is restored by a separate "reset" button.+ params$eval <- FALSE |
28 | -+ | 4x |
- #' It cannot be saved directly but a user is welcome to capture the initial state as a snapshot and save that.+ rblock <- RcodeBlock$new(src) |
29 | -+ | 4x |
- #'+ rblock$set_params(params) |
30 | -+ | 4x |
- #' @section Snapshot mechanics:+ self$append_content(rblock) |
31 | -+ | 4x |
- #' When a snapshot is captured, the user is prompted to name it.+ self$append_metadata("SRC", src) |
32 | -+ | 4x |
- #' Names are displayed as is but since they are used to create button ids,+ invisible(self) |
33 |
- #' under the hood they are converted to syntactically valid strings.+ }, |
||
34 |
- #' New snapshot names are validated so that their valid versions are unique.+ #' @description Appends the filter state list to the `content` and `metadata` of this `TealReportCard`. |
||
35 |
- #' Leading and trailing white space is trimmed.+ #' If the filter state list has an attribute named `formatted`, it appends it to the card otherwise it uses |
||
36 |
- #'+ #' the default `yaml::as.yaml` to format the list. |
||
37 |
- #' The module can read the global state of the application from `slices_global` and `mapping_matrix`.+ #' If the filter state list is empty, nothing is appended to the `content`. |
||
38 |
- #' The former provides a list of all existing `teal_slice`s and the latter says which slice is active in which module.+ #' |
||
39 |
- #' Once a name has been accepted, `slices_global` is converted to a list of lists - a snapshot.+ #' @param fs (`teal_slices`) object returned from [teal_slices()] function. |
||
40 |
- #' The snapshot contains the `mapping` attribute of the initial application state+ #' @return `self`, invisibly. |
||
41 |
- #' (or one that has been restored), which may not reflect the current one,+ append_fs = function(fs) { |
||
42 | -+ | 5x |
- #' so `mapping_matrix` is transformed to obtain the current mapping, i.e. a list that,+ checkmate::assert_class(fs, "teal_slices") |
43 | -+ | 4x |
- #' when passed to the `mapping` argument of [teal_slices()], would result in the current mapping.+ self$append_text("Filter State", "header3") |
44 | -+ | 4x |
- #' This is substituted as the snapshot's `mapping` attribute and the snapshot is added to the snapshot list.+ if (length(fs)) { |
45 | -+ | 3x |
- #'+ self$append_content(TealSlicesBlock$new(fs)) |
46 |
- #' To restore app state, a snapshot is retrieved from storage and rebuilt into a `teal_slices` object.+ } else { |
||
47 | -+ | 1x |
- #' Then state of all `FilteredData` objects (provided in `datasets`) is cleared+ self$append_text("No filters specified.") |
48 |
- #' and set anew according to the `mapping` attribute of the snapshot.+ } |
||
49 | -+ | 4x |
- #' The snapshot is then set as the current content of `slices_global`.+ invisible(self) |
50 |
- #'+ }, |
||
51 |
- #' To save a snapshot, the snapshot is retrieved and reassembled just like for restoring,+ #' @description Appends the encodings list to the `content` and `metadata` of this `TealReportCard`. |
||
52 |
- #' and then saved to file with [slices_store()].+ #' |
||
53 |
- #'+ #' @param encodings (`list`) list of encodings selections of the `teal` app. |
||
54 |
- #' When a snapshot is uploaded, it will first be added to storage just like a newly created one,+ #' @return `self`, invisibly. |
||
55 |
- #' and then used to restore app state much like a snapshot taken from storage.+ #' @examples |
||
56 |
- #' Upon clicking the upload icon the user will be prompted for a file to upload+ #' card <- TealReportCard$new()$append_encodings(list(variable1 = "X")) |
||
57 |
- #' and may choose to name the new snapshot. The name defaults to the name of the file (the extension is dropped)+ #' card$get_content()[[1]]$get_content() |
||
58 |
- #' and normal naming rules apply. Loading the file yields a `teal_slices` object,+ #' |
||
59 |
- #' which is disassembled for storage and used directly for restoring app state.+ append_encodings = function(encodings) { |
||
60 | -+ | 4x |
- #'+ checkmate::assert_list(encodings) |
61 | -+ | 4x |
- #' @section Transferring snapshots:+ self$append_text("Selected Options", "header3") |
62 | -+ | 4x |
- #' Snapshots uploaded from disk should only be used in the same application they come from,+ if (requireNamespace("yaml", quietly = TRUE)) { |
63 | -+ | 4x |
- #' _i.e._ an application that uses the same data and the same modules.+ self$append_text(yaml::as.yaml(encodings, handlers = list( |
64 | -+ | 4x |
- #' To ensure this is the case, `init` stamps `teal_slices` with an app id that is stored in the `app_id` attribute of+ POSIXct = function(x) format(x, "%Y-%m-%d"), |
65 | -+ | 4x |
- #' a `teal_slices` object. When a snapshot is restored from file, its `app_id` is compared to that+ POSIXlt = function(x) format(x, "%Y-%m-%d"), |
66 | -+ | 4x |
- #' of the current app state and only if the match is the snapshot admitted to the session.+ Date = function(x) format(x, "%Y-%m-%d") |
67 | -+ | 4x |
- #'+ )), "verbatim") |
68 |
- #' @section Bookmarks:+ } else { |
||
69 | -+ | ! |
- #' An `onBookmark` callback creates a snapshot of the current filter state.+ stop("yaml package is required to format the encodings list") |
70 |
- #' This is done on the app session, not the module session.+ } |
||
71 | -+ | 4x |
- #' (The snapshot will be retrieved by `module_teal` in order to set initial app state in a restored app.)+ self$append_metadata("Encodings", encodings) |
72 | -+ | 4x |
- #' Then that snapshot, and the previous snapshot history are dumped into the `values.rds` file in `<bookmark_dir>`.+ invisible(self) |
73 |
- #'+ } |
||
74 |
- #' @param id (`character(1)`) `shiny` module instance id.+ ), |
||
75 |
- #' @param slices_global (`reactiveVal`) that contains a `teal_slices` object+ private = list( |
||
76 |
- #' containing all `teal_slice`s existing in the app, both active and inactive.+ dispatch_block = function(block_class) { |
||
77 | -+ | ! |
- #'+ eval(str2lang(block_class)) |
78 |
- #' @return `list` containing the snapshot history, where each element is an unlisted `teal_slices` object.+ } |
||
79 |
- #'+ ) |
||
80 |
- #' @name module_snapshot_manager+ ) |
||
81 |
- #' @rdname module_snapshot_manager+ |
||
82 |
- #'+ #' @title `TealSlicesBlock` |
||
83 |
- #' @author Aleksander Chlebowski+ #' @docType class |
||
84 |
- #' @keywords internal+ #' @description |
||
85 |
- NULL+ #' Specialized `TealSlicesBlock` block for managing filter panel content in reports. |
||
86 |
-
+ #' @keywords internal |
||
87 |
- #' @rdname module_snapshot_manager+ TealSlicesBlock <- R6::R6Class( # nolint: object_name_linter. |
||
88 |
- ui_snapshot_manager_panel <- function(id) {+ classname = "TealSlicesBlock", |
||
89 | -! | +
- ns <- NS(id)+ inherit = teal.reporter:::TextBlock, |
|
90 | -! | +
- tags$button(+ public = list( |
|
91 | -! | +
- id = ns("show_snapshot_manager"),+ #' @description Returns a `TealSlicesBlock` object. |
|
92 | -! | +
- class = "btn action-button wunder_bar_button",+ #' |
|
93 | -! | +
- title = "View filter mapping",+ #' @details Returns a `TealSlicesBlock` object with no content and no parameters. |
|
94 | -! | +
- suppressMessages(icon("fas fa-camera"))+ #' |
|
95 |
- )+ #' @param content (`teal_slices`) object returned from [teal_slices()] function. |
||
96 |
- }+ #' @param style (`character(1)`) string specifying style to apply. |
||
97 |
-
+ #' |
||
98 |
- #' @rdname module_snapshot_manager+ #' @return Object of class `TealSlicesBlock`, invisibly. |
||
99 |
- srv_snapshot_manager_panel <- function(id, slices_global) {+ #' |
||
100 | -87x | +
- moduleServer(id, function(input, output, session) {+ initialize = function(content = teal_slices(), style = "verbatim") { |
|
101 | -87x | +9x |
- logger::log_debug("srv_snapshot_manager_panel initializing")+ self$set_content(content) |
102 | -87x | +8x |
- setBookmarkExclude(c("show_snapshot_manager"))+ self$set_style(style) |
103 | -87x | +8x |
- observeEvent(input$show_snapshot_manager, {+ invisible(self) |
104 | -! | +
- logger::log_debug("srv_snapshot_manager_panel@1 show_snapshot_manager button has been clicked.")+ }, |
|
105 | -! | +
- showModal(+ |
|
106 | -! | +
- modalDialog(+ #' @description Sets content of this `TealSlicesBlock`. |
|
107 | -! | +
- ui_snapshot_manager(session$ns("module")),+ #' Sets content as `YAML` text which represents a list generated from `teal_slices`. |
|
108 | -! | +
- class = "snapshot_manager_modal",+ #' The list displays limited number of fields from `teal_slice` objects, but this list is |
|
109 | -! | +
- size = "m",+ #' sufficient to conclude which filters were applied. |
|
110 | -! | +
- footer = NULL,+ #' When `selected` field in `teal_slice` object is a range, then it is displayed as a "min" |
|
111 | -! | +
- easyClose = TRUE+ #' |
|
112 |
- )+ #' |
||
113 |
- )+ #' @param content (`teal_slices`) object returned from [teal_slices()] function. |
||
114 |
- })+ #' @return `self`, invisibly. |
||
115 | -87x | +
- srv_snapshot_manager("module", slices_global = slices_global)+ set_content = function(content) { |
|
116 | -+ | 9x |
- })+ checkmate::assert_class(content, "teal_slices") |
117 | -+ | 8x |
- }+ if (length(content) != 0) { |
118 | -+ | 6x |
-
+ states_list <- lapply(content, function(x) { |
119 | -+ | 6x |
- #' @rdname module_snapshot_manager+ x_list <- shiny::isolate(as.list(x)) |
120 | -+ | 6x |
- ui_snapshot_manager <- function(id) {+ if ( |
121 | -! | +6x |
- ns <- NS(id)+ inherits(x_list$choices, c("integer", "numeric", "Date", "POSIXct", "POSIXlt")) && |
122 | -! | +6x |
- tags$div(+ length(x_list$choices) == 2 && |
123 | -! | +6x |
- class = "manager_content",+ length(x_list$selected) == 2 |
124 | -! | +
- tags$div(+ ) { |
|
125 | ! |
- class = "manager_table_row",+ x_list$range <- paste(x_list$selected, collapse = " - ") |
|
126 | ! |
- tags$span(tags$b("Snapshot manager")),+ x_list["selected"] <- NULL |
|
127 | -! | +
- actionLink(ns("snapshot_add"), label = NULL, icon = icon("fas fa-camera"), title = "add snapshot"),+ } |
|
128 | -! | +6x |
- actionLink(ns("snapshot_load"), label = NULL, icon = icon("fas fa-upload"), title = "upload snapshot"),+ if (!is.null(x_list$arg)) { |
129 | ! |
- actionLink(ns("snapshot_reset"), label = NULL, icon = icon("fas fa-undo"), title = "reset initial state"),+ x_list$arg <- if (x_list$arg == "subset") "Genes" else "Samples" |
|
130 | -! | +
- NULL+ } |
|
131 |
- ),+ |
||
132 | -! | +6x |
- uiOutput(ns("snapshot_list"))+ x_list <- x_list[ |
133 | -+ | 6x |
- )+ c("dataname", "varname", "experiment", "arg", "expr", "selected", "range", "keep_na", "keep_inf") |
134 |
- }+ ] |
||
135 | -+ | 6x |
-
+ names(x_list) <- c( |
136 | -+ | 6x |
- #' @rdname module_snapshot_manager+ "Dataset name", "Variable name", "Experiment", "Filtering by", "Applied expression", |
137 | -+ | 6x |
- srv_snapshot_manager <- function(id, slices_global) {+ "Selected Values", "Selected range", "Include NA values", "Include Inf values" |
138 | -87x | +
- checkmate::assert_character(id)+ ) |
|
140 | -87x | +6x |
- moduleServer(id, function(input, output, session) {+ Filter(Negate(is.null), x_list) |
141 | -87x | +
- logger::log_debug("srv_snapshot_manager initializing")+ }) |
|
143 | -+ | 6x |
- # Set up bookmarking callbacks ----+ if (requireNamespace("yaml", quietly = TRUE)) { |
144 | -+ | 6x |
- # Register bookmark exclusions (all buttons and text fields).+ super$set_content(yaml::as.yaml(states_list)) |
145 | -87x | +
- setBookmarkExclude(c(+ } else { |
|
146 | -87x | +! |
- "snapshot_add", "snapshot_load", "snapshot_reset",+ stop("yaml package is required to format the filter state list") |
147 | -87x | +
- "snapshot_name_accept", "snaphot_file_accept",+ } |
|
148 | -87x | +
- "snapshot_name", "snapshot_file"+ } |
|
149 | -+ | 8x |
- ))+ private$teal_slices <- content |
150 | -+ | 8x |
- # Add snapshot history to bookmark.+ invisible(self) |
151 | -87x | +
- session$onBookmark(function(state) {+ }, |
|
152 | -! | +
- logger::log_debug("srv_snapshot_manager@onBookmark: storing snapshot and bookmark history")+ #' @description Create the `TealSlicesBlock` from a list. |
|
153 | -! | +
- state$values$snapshot_history <- snapshot_history() # isolate this?+ #' |
|
154 |
- })+ #' @param x (`named list`) with two fields `text` and `style`. |
||
155 |
-
+ #' Use the `get_available_styles` method to get all possible styles. |
||
156 | -87x | +
- ns <- session$ns+ #' |
|
157 |
-
+ #' @return `self`, invisibly. |
||
158 |
- # Track global filter states ----+ #' @examples |
||
159 | -87x | +
- snapshot_history <- reactiveVal({+ #' TealSlicesBlock <- getFromNamespace("TealSlicesBlock", "teal") |
|
160 |
- # Restore directly from bookmarked state, if applicable.+ #' block <- TealSlicesBlock$new() |
||
161 | -87x | +
- restoreValue(+ #' block$from_list(list(text = "sth", style = "default")) |
|
162 | -87x | +
- ns("snapshot_history"),+ #' |
|
163 | -87x | +
- list("Initial application state" = shiny::isolate(as.list(slices_global$all_slices(), recursive = TRUE)))+ from_list = function(x) { |
|
164 | -+ | 1x |
- )+ checkmate::assert_list(x) |
165 | -+ | 1x |
- })+ checkmate::assert_names(names(x), must.include = c("text", "style")) |
166 | -+ | 1x |
-
+ super$set_content(x$text) |
167 | -+ | 1x |
- # Snapshot current application state ----+ super$set_style(x$style) |
168 | -+ | 1x |
- # Name snaphsot.+ invisible(self) |
169 | -87x | +
- observeEvent(input$snapshot_add, {+ }, |
|
170 | -! | +
- logger::log_debug("srv_snapshot_manager: snapshot_add button clicked")+ #' @description Convert the `TealSlicesBlock` to a list. |
|
171 | -! | +
- showModal(+ #' |
|
172 | -! | +
- modalDialog(+ #' @return `named list` with a text and style. |
|
173 | -! | +
- textInput(ns("snapshot_name"), "Name the snapshot", width = "100%", placeholder = "Meaningful, unique name"),+ #' @examples |
|
174 | -! | +
- footer = tagList(+ #' TealSlicesBlock <- getFromNamespace("TealSlicesBlock", "teal") |
|
175 | -! | +
- actionButton(ns("snapshot_name_accept"), "Accept", icon = icon("far fa-thumbs-up")),+ #' block <- TealSlicesBlock$new() |
|
176 | -! | +
- modalButton(label = "Cancel", icon = icon("far fa-thumbs-down"))+ #' block$to_list() |
|
177 |
- ),+ #' |
||
178 | -! | +
- size = "s"+ to_list = function() { |
|
179 | -+ | 2x |
- )+ content <- self$get_content() |
180 | -+ | 2x |
- )+ list( |
181 | -+ | 2x |
- })+ text = if (length(content)) content else "", |
182 | -+ | 2x |
- # Store snaphsot.+ style = self$get_style() |
183 | -87x | +
- observeEvent(input$snapshot_name_accept, {+ ) |
|
184 | -! | +
- logger::log_debug("srv_snapshot_manager: snapshot_name_accept button clicked")+ } |
|
185 | -! | +
- snapshot_name <- trimws(input$snapshot_name)+ ), |
|
186 | -! | +
- if (identical(snapshot_name, "")) {+ private = list( |
|
187 | -! | +
- logger::log_debug("srv_snapshot_manager: snapshot name rejected")+ style = "verbatim", |
|
188 | -! | +
- showNotification(+ teal_slices = NULL # teal_slices |
|
189 | -! | +
- "Please name the snapshot.",+ ) |
|
190 | -! | +
- type = "message"+ ) |
191 | +1 |
- )+ #' Send input validation messages to output |
||
192 | -! | +|||
2 | +
- updateTextInput(inputId = "snapshot_name", value = "", placeholder = "Meaningful, unique name")+ #' |
|||
193 | -! | +|||
3 | +
- } else if (is.element(make.names(snapshot_name), make.names(names(snapshot_history())))) {+ #' Captures messages from `InputValidator` objects and collates them |
|||
194 | -! | +|||
4 | +
- logger::log_debug("srv_snapshot_manager: snapshot name rejected")+ #' into one message passed to `validate`. |
|||
195 | -! | +|||
5 | +
- showNotification(+ #' |
|||
196 | -! | +|||
6 | +
- "This name is in conflict with other snapshot names. Please choose a different one.",+ #' `shiny::validate` is used to withhold rendering of an output element until |
|||
197 | -! | +|||
7 | +
- type = "message"+ #' certain conditions are met and to print a validation message in place |
|||
198 | +8 |
- )+ #' of the output element. |
||
199 | -! | +|||
9 | +
- updateTextInput(inputId = "snapshot_name", value = "", placeholder = "Meaningful, unique name")+ #' `shinyvalidate::InputValidator` allows to validate input elements |
|||
200 | +10 |
- } else {+ #' and to display specific messages in their respective input widgets. |
||
201 | -! | +|||
11 | +
- logger::log_debug("srv_snapshot_manager: snapshot name accepted, adding snapshot")+ #' `validate_inputs` provides a hybrid solution. |
|||
202 | -! | +|||
12 | +
- snapshot <- as.list(slices_global$all_slices(), recursive = TRUE)+ #' Given an `InputValidator` object, messages corresponding to inputs that fail validation |
|||
203 | -! | +|||
13 | ++ |
+ #' are extracted and placed in one validation message that is passed to a `validate`/`need` call.+ |
+ ||
14 | ++ |
+ #' This way the input `validator` messages are repeated in the output.+ |
+ ||
15 | ++ |
+ #'+ |
+ ||
16 | ++ |
+ #' The `...` argument accepts any number of `InputValidator` objects+ |
+ ||
17 | ++ |
+ #' or a nested list of such objects.+ |
+ ||
18 | ++ |
+ #' If `validators` are passed directly, all their messages are printed together+ |
+ ||
19 | ++ |
+ #' under one (optional) header message specified by `header`. If a list is passed,+ |
+ ||
20 | ++ |
+ #' messages are grouped by `validator`. The list's names are used as headers+ |
+ ||
21 | ++ |
+ #' for their respective message groups.+ |
+ ||
22 | ++ |
+ #' If neither of the nested list elements is named, a header message is taken from `header`.+ |
+ ||
23 | ++ |
+ #'+ |
+ ||
24 | ++ |
+ #' @param ... either any number of `InputValidator` objects+ |
+ ||
25 | ++ |
+ #' or an optionally named, possibly nested `list` of `InputValidator`+ |
+ ||
26 | ++ |
+ #' objects, see `Details`+ |
+ ||
27 | ++ |
+ #' @param header (`character(1)`) generic validation message; set to NULL to omit+ |
+ ||
28 | ++ |
+ #'+ |
+ ||
29 | +
- snapshot_update <- c(snapshot_history(), list(snapshot))+ #' @return |
|||
204 | -! | +|||
30 | +
- names(snapshot_update)[length(snapshot_update)] <- snapshot_name+ #' Returns NULL if the final validation call passes and a `shiny.silent.error` if it fails. |
|||
205 | -! | +|||
31 | +
- snapshot_history(snapshot_update)+ #' |
|||
206 | -! | +|||
32 | +
- removeModal()+ #' @seealso [`shinyvalidate::InputValidator`], [`shiny::validate`] |
|||
207 | +33 |
- # Reopen filter manager modal by clicking button in the main application.+ #' |
||
208 | -! | +|||
34 | +
- shinyjs::click(id = "teal-wunder_bar-show_snapshot_manager", asis = TRUE)+ #' @examplesIf require("shinyvalidate") |
|||
209 | +35 |
- }+ #' library(shiny) |
||
210 | +36 |
- })+ #' library(shinyvalidate) |
||
211 | +37 |
-
+ #' |
||
212 | +38 |
- # Upload a snapshot file ----+ #' ui <- fluidPage( |
||
213 | +39 |
- # Select file.+ #' selectInput("method", "validation method", c("sequential", "combined", "grouped")), |
||
214 | -87x | +|||
40 | +
- observeEvent(input$snapshot_load, {+ #' sidebarLayout( |
|||
215 | -! | +|||
41 | +
- logger::log_debug("srv_snapshot_manager: snapshot_load button clicked")+ #' sidebarPanel( |
|||
216 | -! | +|||
42 | +
- showModal(+ #' selectInput("letter", "select a letter:", c(letters[1:3], LETTERS[4:6])), |
|||
217 | -! | +|||
43 | +
- modalDialog(+ #' selectInput("number", "select a number:", 1:6), |
|||
218 | -! | +|||
44 | +
- fileInput(ns("snapshot_file"), "Choose snapshot file", accept = ".json", width = "100%"),+ #' tags$br(), |
|||
219 | -! | +|||
45 | +
- textInput(+ #' selectInput("color", "select a color:", |
|||
220 | -! | +|||
46 | +
- ns("snapshot_name"),+ #' c("black", "indianred2", "springgreen2", "cornflowerblue"), |
|||
221 | -! | +|||
47 | +
- "Name the snapshot (optional)",+ #' multiple = TRUE |
|||
222 | -! | +|||
48 | +
- width = "100%",+ #' ), |
|||
223 | -! | +|||
49 | +
- placeholder = "Meaningful, unique name"+ #' sliderInput("size", "select point size:", |
|||
224 | +50 |
- ),+ #' min = 0.1, max = 4, value = 0.25 |
||
225 | -! | +|||
51 | +
- footer = tagList(+ #' ) |
|||
226 | -! | +|||
52 | +
- actionButton(ns("snaphot_file_accept"), "Accept", icon = icon("far fa-thumbs-up")),+ #' ), |
|||
227 | -! | +|||
53 | +
- modalButton(label = "Cancel", icon = icon("far fa-thumbs-down"))+ #' mainPanel(plotOutput("plot")) |
|||
228 | +54 |
- )+ #' ) |
||
229 | +55 |
- )+ #' ) |
||
230 | +56 |
- )+ #' |
||
231 | +57 |
- })+ #' server <- function(input, output) { |
||
232 | +58 |
- # Store new snapshot to list and restore filter states.+ #' # set up input validation |
||
233 | -87x | +|||
59 | +
- observeEvent(input$snaphot_file_accept, {+ #' iv <- InputValidator$new() |
|||
234 | -! | +|||
60 | +
- logger::log_debug("srv_snapshot_manager: snapshot_file_accept button clicked")+ #' iv$add_rule("letter", sv_in_set(LETTERS, "choose a capital letter")) |
|||
235 | -! | +|||
61 | +
- snapshot_name <- trimws(input$snapshot_name)+ #' iv$add_rule("number", function(x) { |
|||
236 | -! | +|||
62 | +
- if (identical(snapshot_name, "")) {+ #' if (as.integer(x) %% 2L == 1L) "choose an even number" |
|||
237 | -! | +|||
63 | +
- logger::log_debug("srv_snapshot_manager: no snapshot name provided, naming after file")+ #' }) |
|||
238 | -! | +|||
64 | +
- snapshot_name <- tools::file_path_sans_ext(input$snapshot_file$name)+ #' iv$enable() |
|||
239 | +65 |
- }+ #' # more input validation |
||
240 | -! | +|||
66 | +
- if (is.element(make.names(snapshot_name), make.names(names(snapshot_history())))) {+ #' iv_par <- InputValidator$new() |
|||
241 | -! | +|||
67 | +
- logger::log_debug("srv_snapshot_manager: snapshot name rejected")+ #' iv_par$add_rule("color", sv_required(message = "choose a color")) |
|||
242 | -! | +|||
68 | +
- showNotification(+ #' iv_par$add_rule("color", function(x) { |
|||
243 | -! | +|||
69 | +
- "This name is in conflict with other snapshot names. Please choose a different one.",+ #' if (length(x) > 1L) "choose only one color" |
|||
244 | -! | +|||
70 | +
- type = "message"+ #' }) |
|||
245 | +71 |
- )+ #' iv_par$add_rule( |
||
246 | -! | +|||
72 | +
- updateTextInput(inputId = "snapshot_name", value = "", placeholder = "Meaningful, unique name")+ #' "size", |
|||
247 | +73 |
- } else {+ #' sv_between( |
||
248 | +74 |
- # Restore snapshot and verify app compatibility.+ #' left = 0.5, right = 3, |
||
249 | -! | +|||
75 | +
- logger::log_debug("srv_snapshot_manager: snapshot name accepted, loading snapshot")+ #' message_fmt = "choose a value between {left} and {right}" |
|||
250 | -! | +|||
76 | +
- snapshot_state <- try(slices_restore(input$snapshot_file$datapath))+ #' ) |
|||
251 | -! | +|||
77 | +
- if (!inherits(snapshot_state, "modules_teal_slices")) {+ #' ) |
|||
252 | -! | +|||
78 | +
- logger::log_debug("srv_snapshot_manager: snapshot file corrupt")+ #' iv_par$enable() |
|||
253 | -! | +|||
79 | +
- showNotification(+ #' |
|||
254 | -! | +|||
80 | +
- "File appears to be corrupt.",+ #' output$plot <- renderPlot({ |
|||
255 | -! | +|||
81 | +
- type = "error"+ #' # validate output |
|||
256 | +82 |
- )+ #' switch(input[["method"]], |
||
257 | -! | +|||
83 | +
- } else if (!identical(attr(snapshot_state, "app_id"), attr(slices_global$all_slices(), "app_id"))) {+ #' "sequential" = { |
|||
258 | -! | +|||
84 | +
- logger::log_debug("srv_snapshot_manager: snapshot not compatible with app")+ #' validate_inputs(iv) |
|||
259 | -! | +|||
85 | +
- showNotification(+ #' validate_inputs(iv_par, header = "Set proper graphical parameters") |
|||
260 | -! | +|||
86 | +
- "This snapshot file is not compatible with the app and cannot be loaded.",+ #' }, |
|||
261 | -! | +|||
87 | +
- type = "warning"+ #' "combined" = validate_inputs(iv, iv_par), |
|||
262 | +88 |
- )+ #' "grouped" = validate_inputs(list( |
||
263 | +89 |
- } else {+ #' "Some inputs require attention" = iv, |
||
264 | +90 |
- # Add to snapshot history.+ #' "Set proper graphical parameters" = iv_par |
||
265 | -! | +|||
91 | +
- logger::log_debug("srv_snapshot_manager: snapshot loaded, adding to history")+ #' )) |
|||
266 | -! | +|||
92 | +
- snapshot <- as.list(slices_global$all_slices(), recursive = TRUE)+ #' ) |
|||
267 | -! | +|||
93 | +
- snapshot_update <- c(snapshot_history(), list(snapshot))+ #' |
|||
268 | -! | +|||
94 | +
- names(snapshot_update)[length(snapshot_update)] <- snapshot_name+ #' plot(faithful$eruptions ~ faithful$waiting, |
|||
269 | -! | +|||
95 | +
- snapshot_history(snapshot_update)+ #' las = 1, pch = 16, |
|||
270 | +96 |
- ### Begin simplified restore procedure. ###+ #' col = input[["color"]], cex = input[["size"]] |
||
271 | -! | +|||
97 | +
- logger::log_debug("srv_snapshot_manager: restoring snapshot")+ #' ) |
|||
272 | -! | +|||
98 | +
- slices_global$slices_set(snapshot_state)+ #' }) |
|||
273 | -! | +|||
99 | +
- removeModal()+ #' } |
|||
274 | +100 |
- ### End simplified restore procedure. ###+ #' |
||
275 | +101 |
- }+ #' if (interactive()) { |
||
276 | +102 |
- }+ #' shinyApp(ui, server) |
||
277 | +103 |
- })+ #' } |
||
278 | +104 |
- # Apply newly added snapshot.+ #' |
||
279 | +105 |
-
+ #' @export |
||
280 | +106 |
- # Restore initial state ----+ #' |
||
281 | -87x | +|||
107 | +
- observeEvent(input$snapshot_reset, {+ validate_inputs <- function(..., header = "Some inputs require attention") { |
|||
282 | -2x | +108 | +36x |
- logger::log_debug("srv_snapshot_manager: snapshot_reset button clicked, restoring snapshot")+ dots <- list(...) |
283 | +109 | 2x |
- s <- "Initial application state"+ if (!is_validators(dots)) stop("validate_inputs accepts validators or a list thereof") |
|
284 | +110 |
- ### Begin restore procedure. ###+ |
||
285 | -2x | +111 | +34x |
- snapshot <- snapshot_history()[[s]]+ messages <- extract_validator(dots, header) |
286 | -2x | +112 | +34x |
- snapshot_state <- as.teal_slices(snapshot)+ failings <- if (!any_names(dots)) { |
287 | -2x | +113 | +29x |
- slices_global$slices_set(snapshot_state)+ add_header(messages, header) |
288 | -2x | +|||
114 | +
- removeModal()+ } else { |
|||
289 | -+ | |||
115 | +5x |
- ### End restore procedure. ###+ unlist(messages) |
||
290 | +116 |
- })+ } |
||
291 | +117 | |||
292 | -+ | |||
118 | +34x |
- # Build snapshot table ----+ shiny::validate(shiny::need(is.null(failings), failings)) |
||
293 | +119 |
- # Create UI elements and server logic for the snapshot table.+ } |
||
294 | +120 |
- # Observers must be tracked to avoid duplication and excess reactivity.+ |
||
295 | +121 |
- # Remaining elements are tracked likewise for consistency and a slight speed margin.+ ### internal functions |
||
296 | -87x | +|||
122 | +
- observers <- reactiveValues()+ |
|||
297 | -87x | +|||
123 | +
- handlers <- reactiveValues()+ #' @noRd |
|||
298 | -87x | +|||
124 | +
- divs <- reactiveValues()+ #' @keywords internal |
|||
299 | +125 |
-
+ # recursive object type test |
||
300 | -87x | +|||
126 | +
- observeEvent(snapshot_history(), {+ # returns logical of length 1 |
|||
301 | -77x | +|||
127 | +
- logger::log_debug("srv_snapshot_manager: snapshot history modified, updating snapshot list")+ is_validators <- function(x) { |
|||
302 | -77x | +128 | +118x |
- lapply(names(snapshot_history())[-1L], function(s) {+ all(if (is.list(x)) unlist(lapply(x, is_validators)) else inherits(x, "InputValidator")) |
303 | -! | +|||
129 | +
- id_pickme <- sprintf("pickme_%s", make.names(s))+ } |
|||
304 | -! | +|||
130 | +
- id_saveme <- sprintf("saveme_%s", make.names(s))+ |
|||
305 | -! | +|||
131 | +
- id_rowme <- sprintf("rowme_%s", make.names(s))+ #' @noRd |
|||
306 | +132 |
-
+ #' @keywords internal |
||
307 | +133 |
- # Observer for restoring snapshot.+ # test if an InputValidator object is enabled |
||
308 | -! | +|||
134 | +
- if (!is.element(id_pickme, names(observers))) {+ # returns logical of length 1 |
|||
309 | -! | +|||
135 | +
- observers[[id_pickme]] <- observeEvent(input[[id_pickme]], {+ # official method requested at https://github.com/rstudio/shinyvalidate/issues/64 |
|||
310 | +136 |
- ### Begin restore procedure. ###+ validator_enabled <- function(x) { |
||
311 | -! | +|||
137 | +49x |
- snapshot <- snapshot_history()[[s]]+ x$.__enclos_env__$private$enabled |
||
312 | -! | +|||
138 | +
- snapshot_state <- as.teal_slices(snapshot)+ } |
|||
313 | +139 | |||
314 | -! | +|||
140 | +
- slices_global$slices_set(snapshot_state)+ #' Recursively extract messages from validator list |
|||
315 | -! | +|||
141 | +
- removeModal()+ #' @return A character vector or a list of character vectors, possibly nested and named. |
|||
316 | +142 |
- ### End restore procedure. ###+ #' @noRd |
||
317 | +143 |
- })+ #' @keywords internal |
||
318 | +144 |
- }+ extract_validator <- function(iv, header) { |
||
319 | -+ | |||
145 | +113x |
- # Create handler for downloading snapshot.+ if (inherits(iv, "InputValidator")) { |
||
320 | -! | +|||
146 | +49x |
- if (!is.element(id_saveme, names(handlers))) {+ add_header(gather_messages(iv), header) |
||
321 | -! | +|||
147 | +
- output[[id_saveme]] <- downloadHandler(+ } else { |
|||
322 | -! | +|||
148 | +58x |
- filename = function() {+ if (is.null(names(iv))) names(iv) <- rep("", length(iv)) |
||
323 | -! | +|||
149 | +64x |
- sprintf("teal_snapshot_%s_%s.json", s, Sys.Date())+ mapply(extract_validator, iv = iv, header = names(iv), SIMPLIFY = FALSE) |
||
324 | +150 |
- },+ } |
||
325 | -! | +|||
151 | +
- content = function(file) {+ } |
|||
326 | -! | +|||
152 | +
- snapshot <- snapshot_history()[[s]]+ |
|||
327 | -! | +|||
153 | +
- snapshot_state <- as.teal_slices(snapshot)+ #' Collate failing messages from validator. |
|||
328 | -! | +|||
154 | +
- slices_store(tss = snapshot_state, file = file)+ #' @return `list` |
|||
329 | +155 |
- }+ #' @noRd |
||
330 | +156 |
- )+ #' @keywords internal |
||
331 | -! | +|||
157 | +
- handlers[[id_saveme]] <- id_saveme+ gather_messages <- function(iv) { |
|||
332 | -+ | |||
158 | +49x |
- }+ if (validator_enabled(iv)) { |
||
333 | -+ | |||
159 | +46x |
- # Create a row for the snapshot table.+ status <- iv$validate() |
||
334 | -! | +|||
160 | +46x |
- if (!is.element(id_rowme, names(divs))) {+ failing_inputs <- Filter(Negate(is.null), status) |
||
335 | -! | +|||
161 | +46x |
- divs[[id_rowme]] <- tags$div(+ unique(lapply(failing_inputs, function(x) x[["message"]])) |
||
336 | -! | +|||
162 | +
- class = "manager_table_row",+ } else { |
|||
337 | -! | +|||
163 | +3x |
- tags$span(tags$h5(s)),+ warning("Validator is disabled and will be omitted.") |
||
338 | -! | +|||
164 | +3x |
- actionLink(inputId = ns(id_pickme), label = icon("far fa-circle-check"), title = "select"),+ list() |
||
339 | -! | +|||
165 | +
- downloadLink(outputId = ns(id_saveme), label = icon("far fa-save"), title = "save to file")+ } |
|||
340 | +166 |
- )+ } |
||
341 | +167 |
- }+ |
||
342 | +168 |
- })+ #' Add optional header to failing messages |
||
343 | +169 |
- })+ #' @noRd |
||
344 | +170 |
-
+ #' @keywords internal |
||
345 | +171 |
- # Create table to display list of snapshots and their actions.+ add_header <- function(messages, header = "") { |
||
346 | -87x | +172 | +78x |
- output$snapshot_list <- renderUI({+ ans <- unlist(messages) |
347 | -77x | +173 | +78x |
- rows <- rev(reactiveValuesToList(divs))+ if (length(ans) != 0L && isTRUE(nchar(header) > 0L)) { |
348 | -77x | +174 | +31x |
- if (length(rows) == 0L) {+ ans <- c(paste0(header, "\n"), ans, "\n") |
349 | -77x | +|||
175 | +
- tags$div(+ } |
|||
350 | -77x | +176 | +78x |
- class = "manager_placeholder",+ ans |
351 | -77x | +|||
177 | +
- "Snapshots will appear here."+ } |
|||
352 | +178 |
- )+ |
||
353 | +179 |
- } else {+ #' Recursively check if the object contains a named list |
||
354 | -! | +|||
180 | +
- rows+ #' @noRd |
|||
355 | +181 |
- }+ #' @keywords internal |
||
356 | +182 |
- })+ any_names <- function(x) {+ |
+ ||
183 | +103x | +
+ any(+ |
+ ||
184 | +103x | +
+ if (is.list(x)) {+ |
+ ||
185 | +58x | +
+ if (!is.null(names(x)) && any(names(x) != "")) TRUE else unlist(lapply(x, any_names)) |
||
357 | +186 |
-
+ } else { |
||
358 | -87x | +187 | +40x |
- snapshot_history+ FALSE |
359 | +188 |
- })+ } |
||
360 | +189 | ++ |
+ )+ |
+ |
190 |
}@@ -13657,1350 +12832,1791 @@ teal coverage - 60.11% |
1 |
- #' @title `TealReportCard`+ #' Execute and validate `teal_data_module` |
|||
2 |
- #' @description `r lifecycle::badge("experimental")`+ #' |
|||
3 |
- #' Child class of [`teal.reporter::ReportCard`] that is used for `teal` specific applications.+ #' This is a low level module to handle `teal_data_module` execution and validation. |
|||
4 |
- #' In addition to the parent methods, it supports rendering `teal` specific elements such as+ #' [teal_transform_module()] inherits from [teal_data_module()] so it is handled by this module too. |
|||
5 |
- #' the source code, the encodings panel content and the filter panel content as part of the+ #' [srv_teal()] accepts various `data` objects and eventually they are all transformed to `reactive` |
|||
6 |
- #' meta data.+ #' [teal.data::teal_data()] which is a standard data class in whole `teal` framework. |
|||
7 |
- #' @export+ #' |
|||
8 |
- #'+ #' @section data validation: |
|||
9 |
- TealReportCard <- R6::R6Class( # nolint: object_name.+ #' |
|||
10 |
- classname = "TealReportCard",+ #' Executed [teal_data_module()] is validated and output is validated for consistency. |
|||
11 |
- inherit = teal.reporter::ReportCard,+ #' Output `data` is invalid if: |
|||
12 |
- public = list(+ #' 1. [teal_data_module()] is invalid if server doesn't return `reactive`. **Immediately crashes an app!** |
|||
13 |
- #' @description Appends the source code to the `content` meta data of this `TealReportCard`.+ #' 2. `reactive` throws a `shiny.error` - happens when module creating [teal.data::teal_data()] fails. |
|||
14 |
- #'+ #' 3. `reactive` returns `qenv.error` - happens when [teal.data::teal_data()] evaluates a failing code. |
|||
15 |
- #' @param src (`character(1)`) code as text.+ #' 4. `reactive` object doesn't return [teal.data::teal_data()]. |
|||
16 |
- #' @param ... any `rmarkdown` `R` chunk parameter and its value.+ #' 5. [teal.data::teal_data()] object lacks any `datanames` specified in the `modules` argument. |
|||
17 |
- #' But `eval` parameter is always set to `FALSE`.+ #'+ |
+ |||
18 | ++ |
+ #' `teal` (observers in `srv_teal`) always waits to render an app until `reactive` `teal_data` is+ |
+ ||
19 | ++ |
+ #' returned. If error 2-4 occurs, relevant error message is displayed to the app user. Once the issue is+ |
+ ||
20 | ++ |
+ #' resolved, the app will continue to run. `teal` guarantees that errors in data don't crash the app+ |
+ ||
21 | ++ |
+ #' (except error 1).+ |
+ ||
22 | ++ |
+ #'+ |
+ ||
23 | ++ |
+ #' @param id (`character(1)`) Module id+ |
+ ||
24 | ++ |
+ #' @param data (`reactive teal_data`)+ |
+ ||
25 | ++ |
+ #' @param data_module (`teal_data_module`)+ |
+ ||
26 | ++ |
+ #' @param modules (`teal_modules` or `teal_module`) For `datanames` validation purpose+ |
+ ||
27 | ++ |
+ #' @param validate_shiny_silent_error (`logical`) If `TRUE`, then `shiny.silent.error` is validated and+ |
+ ||
28 | ++ |
+ #' @param is_transform_failed (`reactiveValues`) contains `logical` flags named after each transformator.+ |
+ ||
29 | ++ |
+ #' Help to determine if any previous transformator failed, so that following transformators can be disabled+ |
+ ||
30 | ++ |
+ #' and display a generic failure message.+ |
+ ||
31 | ++ |
+ #'+ |
+ ||
32 | ++ |
+ #' @return `reactive` `teal_data`+ |
+ ||
33 | ++ |
+ #'+ |
+ ||
34 | ++ |
+ #' @rdname module_teal_data+ |
+ ||
35 | ++ |
+ #' @name module_teal_data+ |
+ ||
36 | ++ |
+ #' @keywords internal+ |
+ ||
37 | ++ |
+ NULL+ |
+ ||
38 | ++ | + + | +||
39 | ++ |
+ #' @rdname module_teal_data+ |
+ ||
40 | ++ |
+ #' @aliases ui_teal_data+ |
+ ||
41 | ++ |
+ #' @note+ |
+ ||
42 | ++ |
+ #' `ui_teal_data_module` was renamed from `ui_teal_data`.+ |
+ ||
43 | ++ |
+ ui_teal_data_module <- function(id, data_module = function(id) NULL) {+ |
+ ||
44 | +! | +
+ checkmate::assert_string(id)+ |
+ ||
45 | +! | +
+ checkmate::assert_function(data_module, args = "id")+ |
+ ||
46 | +! | +
+ ns <- NS(id)+ |
+ ||
47 | ++ | + + | +||
48 | +! | +
+ shiny::tagList(+ |
+ ||
49 | +! | +
+ tags$div(id = ns("wrapper"), data_module(id = ns("data"))),+ |
+ ||
50 | +! | +
+ ui_validate_reactive_teal_data(ns("validate"))+ |
+ ||
51 | ++ |
+ )+ |
+ ||
52 | ++ |
+ }+ |
+ ||
53 | ++ | + + | +||
54 | ++ |
+ #' @rdname module_teal_data+ |
+ ||
55 | ++ |
+ #' @aliases srv_teal_data+ |
+ ||
56 | ++ |
+ #' @note+ |
+ ||
57 | ++ |
+ #' `srv_teal_data_module` was renamed from `srv_teal_data`.+ |
+ ||
58 | ++ |
+ srv_teal_data_module <- function(id,+ |
+ ||
59 | ++ |
+ data_module = function(id) NULL,+ |
+ ||
60 | ++ |
+ modules = NULL,+ |
+ ||
61 | ++ |
+ validate_shiny_silent_error = TRUE,+ |
+ ||
62 | ++ |
+ is_transform_failed = reactiveValues()) {+ |
+ ||
63 | +! | +
+ checkmate::assert_string(id)+ |
+ ||
64 | +! | +
+ checkmate::assert_function(data_module, args = "id")+ |
+ ||
65 | +! | +
+ checkmate::assert_multi_class(modules, c("teal_modules", "teal_module"), null.ok = TRUE)+ |
+ ||
66 | +! | +
+ checkmate::assert_class(is_transform_failed, "reactivevalues")+ |
+ ||
67 | ++ | + + | +||
68 | +! | +
+ moduleServer(id, function(input, output, session) {+ |
+ ||
69 | +! | +
+ logger::log_debug("srv_teal_data_module initializing.")+ |
+ ||
70 | +! | +
+ is_transform_failed[[id]] <- FALSE+ |
+ ||
71 | +! | +
+ module_out <- data_module(id = "data")+ |
+ ||
72 | +! | +
+ try_module_out <- reactive(tryCatch(module_out(), error = function(e) e))+ |
+ ||
73 | +! | +
+ observeEvent(try_module_out(), {+ |
+ ||
74 | +! | +
+ if (!inherits(try_module_out(), "teal_data")) {+ |
+ ||
75 | +! | +
+ is_transform_failed[[id]] <- TRUE+ |
+ ||
76 | ++ |
+ } else {+ |
+ ||
77 | +! | +
+ is_transform_failed[[id]] <- FALSE+ |
+ ||
78 | ++ |
+ }+ |
+ ||
79 | ++ |
+ })+ |
+ ||
80 | ++ | + + | +||
81 | +! | +
+ is_previous_failed <- reactive({+ |
+ ||
82 | +! | +
+ idx_this <- which(names(is_transform_failed) == id)+ |
+ ||
83 | +! | +
+ is_transform_failed_list <- reactiveValuesToList(is_transform_failed)+ |
+ ||
84 | +! | +
+ idx_failures <- which(unlist(is_transform_failed_list))+ |
+ ||
85 | +! | +
+ any(idx_failures < idx_this)+ |
+ ||
86 | ++ |
+ })+ |
+ ||
87 | ++ | + | ||
18 | -+ | |||
88 | +! |
- #' @return Object of class `TealReportCard`, invisibly.+ observeEvent(is_previous_failed(), { |
||
19 | -+ | |||
89 | +! |
- #' @examples+ if (is_previous_failed()) { |
||
20 | -+ | |||
90 | +! |
- #' card <- TealReportCard$new()$append_src(+ shinyjs::disable("wrapper") |
||
21 | +91 |
- #' "plot(iris)"+ } else { |
||
22 | -+ | |||
92 | +! |
- #' )+ shinyjs::enable("wrapper") |
||
23 | +93 |
- #' card$get_content()[[1]]$get_content()+ } |
||
24 | +94 |
- append_src = function(src, ...) {+ }) |
||
25 | -4x | +|||
95 | +
- checkmate::assert_character(src, min.len = 0, max.len = 1)+ |
|||
26 | -4x | +|||
96 | +! |
- params <- list(...)+ srv_validate_reactive_teal_data( |
||
27 | -4x | +|||
97 | +! |
- params$eval <- FALSE+ "validate", |
||
28 | -4x | +|||
98 | +! |
- rblock <- RcodeBlock$new(src)+ data = try_module_out, |
||
29 | -4x | +|||
99 | +! |
- rblock$set_params(params)+ modules = modules, |
||
30 | -4x | +|||
100 | +! |
- self$append_content(rblock)+ validate_shiny_silent_error = validate_shiny_silent_error, |
||
31 | -4x | +|||
101 | +! |
- self$append_metadata("SRC", src)+ hide_validation_error = is_previous_failed |
||
32 | -4x | +|||
102 | +
- invisible(self)+ ) |
|||
33 | +103 |
- },+ }) |
||
34 | +104 |
- #' @description Appends the filter state list to the `content` and `metadata` of this `TealReportCard`.+ } |
||
35 | +105 |
- #' If the filter state list has an attribute named `formatted`, it appends it to the card otherwise it uses+ |
||
36 | +106 |
- #' the default `yaml::as.yaml` to format the list.+ #' @rdname module_teal_data |
||
37 | +107 |
- #' If the filter state list is empty, nothing is appended to the `content`.+ ui_validate_reactive_teal_data <- function(id) { |
||
38 | -+ | |||
108 | +! |
- #'+ ns <- NS(id) |
||
39 | -+ | |||
109 | +! |
- #' @param fs (`teal_slices`) object returned from [teal_slices()] function.+ tagList( |
||
40 | -+ | |||
110 | +! |
- #' @return `self`, invisibly.+ div( |
||
41 | -+ | |||
111 | +! |
- append_fs = function(fs) {+ id = ns("validate_messages"), |
||
42 | -5x | +|||
112 | +! |
- checkmate::assert_class(fs, "teal_slices")+ class = "teal_validated", |
||
43 | -4x | +|||
113 | +! |
- self$append_text("Filter State", "header3")+ ui_validate_error(ns("silent_error")), |
||
44 | -4x | +|||
114 | +! |
- if (length(fs)) {+ ui_check_class_teal_data(ns("class_teal_data")), |
||
45 | -3x | +|||
115 | +! |
- self$append_content(TealSlicesBlock$new(fs))+ ui_check_module_datanames(ns("shiny_warnings")) |
||
46 | +116 |
- } else {+ ), |
||
47 | -1x | +|||
117 | +! |
- self$append_text("No filters specified.")+ div( |
||
48 | -+ | |||
118 | +! |
- }+ class = "teal_validated", |
||
49 | -4x | +|||
119 | +! |
- invisible(self)+ uiOutput(ns("previous_failed")) |
||
50 | +120 |
- },+ ) |
||
51 | +121 |
- #' @description Appends the encodings list to the `content` and `metadata` of this `TealReportCard`.+ ) |
||
52 | +122 |
- #'+ } |
||
53 | +123 |
- #' @param encodings (`list`) list of encodings selections of the `teal` app.+ |
||
54 | +124 |
- #' @return `self`, invisibly.+ #' @rdname module_teal_data |
||
55 | +125 |
- #' @examples+ srv_validate_reactive_teal_data <- function(id, # nolint: object_length |
||
56 | +126 |
- #' card <- TealReportCard$new()$append_encodings(list(variable1 = "X"))+ data, |
||
57 | +127 |
- #' card$get_content()[[1]]$get_content()+ modules = NULL, |
||
58 | +128 |
- #'+ validate_shiny_silent_error = FALSE, |
||
59 | +129 |
- append_encodings = function(encodings) {- |
- ||
60 | -4x | -
- checkmate::assert_list(encodings)- |
- ||
61 | -4x | -
- self$append_text("Selected Options", "header3")- |
- ||
62 | -4x | -
- if (requireNamespace("yaml", quietly = TRUE)) {+ hide_validation_error = reactive(FALSE)) { |
||
63 | -4x | +|||
130 | +! |
- self$append_text(yaml::as.yaml(encodings, handlers = list(+ checkmate::assert_string(id) |
||
64 | -4x | +|||
131 | +! |
- POSIXct = function(x) format(x, "%Y-%m-%d"),+ checkmate::assert_multi_class(modules, c("teal_modules", "teal_module"), null.ok = TRUE) |
||
65 | -4x | +|||
132 | +! |
- POSIXlt = function(x) format(x, "%Y-%m-%d"),+ checkmate::assert_flag(validate_shiny_silent_error) |
||
66 | -4x | +|||
133 | +
- Date = function(x) format(x, "%Y-%m-%d")+ |
|||
67 | -4x | +|||
134 | +! |
- )), "verbatim")+ moduleServer(id, function(input, output, session) { |
||
68 | +135 |
- } else {+ # there is an empty reactive cycle on `init` and `data` has `shiny.silent.error` class |
||
69 | +136 | ! |
- stop("yaml package is required to format the encodings list")+ srv_validate_error("silent_error", data, validate_shiny_silent_error) |
|
70 | -+ | |||
137 | +! |
- }+ srv_check_class_teal_data("class_teal_data", data) |
||
71 | -4x | +|||
138 | +! |
- self$append_metadata("Encodings", encodings)+ srv_check_module_datanames("shiny_warnings", data, modules) |
||
72 | -4x | +|||
139 | +! |
- invisible(self)+ output$previous_failed <- renderUI({ |
||
73 | -+ | |||
140 | +! |
- }+ if (hide_validation_error()) { |
||
74 | -+ | |||
141 | +! |
- ),+ shinyjs::hide("validate_messages") |
||
75 | -+ | |||
142 | +! |
- private = list(+ tags$div("One of previous transformators failed. Please check its inputs.", class = "teal-output-warning") |
||
76 | +143 |
- dispatch_block = function(block_class) {+ } else { |
||
77 | +144 | ! |
- eval(str2lang(block_class))+ shinyjs::show("validate_messages") |
|
78 | -+ | |||
145 | +! |
- }+ NULL |
||
79 | +146 |
- )+ } |
||
80 | +147 |
- )+ }) |
||
81 | +148 | |||
82 | -+ | |||
149 | +! |
- #' @title `TealSlicesBlock`+ .trigger_on_success(data) |
||
83 | +150 |
- #' @docType class+ }) |
||
84 | +151 |
- #' @description+ } |
||
85 | +152 |
- #' Specialized `TealSlicesBlock` block for managing filter panel content in reports.+ |
||
86 | +153 |
#' @keywords internal |
||
87 | -- |
- TealSlicesBlock <- R6::R6Class( # nolint: object_name_linter.- |
- ||
88 | +154 |
- classname = "TealSlicesBlock",+ ui_validate_error <- function(id) { |
||
89 | -+ | |||
155 | +116x |
- inherit = teal.reporter:::TextBlock,+ ns <- NS(id) |
||
90 | -+ | |||
156 | +116x |
- public = list(+ uiOutput(ns("message")) |
||
91 | +157 |
- #' @description Returns a `TealSlicesBlock` object.+ } |
||
92 | +158 |
- #'+ |
||
93 | +159 |
- #' @details Returns a `TealSlicesBlock` object with no content and no parameters.+ #' @keywords internal |
||
94 | +160 |
- #'+ srv_validate_error <- function(id, data, validate_shiny_silent_error) { |
||
95 | -+ | |||
161 | +113x |
- #' @param content (`teal_slices`) object returned from [teal_slices()] function.+ checkmate::assert_string(id) |
||
96 | -+ | |||
162 | +113x |
- #' @param style (`character(1)`) string specifying style to apply.+ checkmate::assert_flag(validate_shiny_silent_error) |
||
97 | -+ | |||
163 | +113x |
- #'+ moduleServer(id, function(input, output, session) { |
||
98 | -+ | |||
164 | +113x |
- #' @return Object of class `TealSlicesBlock`, invisibly.+ output$message <- renderUI({ |
||
99 | -+ | |||
165 | +112x |
- #'+ is_shiny_silent_error <- inherits(data(), "shiny.silent.error") && identical(data()$message, "") |
||
100 | -+ | |||
166 | +112x |
- initialize = function(content = teal_slices(), style = "verbatim") {+ if (inherits(data(), "qenv.error")) { |
||
101 | -9x | +167 | +2x |
- self$set_content(content)+ validate( |
102 | -8x | +168 | +2x |
- self$set_style(style)+ need( |
103 | -8x | +169 | +2x |
- invisible(self)+ FALSE, |
104 | -+ | |||
170 | +2x |
- },+ paste( |
||
105 | -+ | |||
171 | +2x |
-
+ "Error when executing the `data` module:", |
||
106 | -+ | |||
172 | +2x |
- #' @description Sets content of this `TealSlicesBlock`.+ strip_style(paste(data()$message, collapse = "\n")), |
||
107 | -+ | |||
173 | +2x |
- #' Sets content as `YAML` text which represents a list generated from `teal_slices`.+ "\nCheck your inputs or contact app developer if error persists.", |
||
108 | -+ | |||
174 | +2x |
- #' The list displays limited number of fields from `teal_slice` objects, but this list is+ collapse = "\n" |
||
109 | +175 |
- #' sufficient to conclude which filters were applied.+ ) |
||
110 | +176 |
- #' When `selected` field in `teal_slice` object is a range, then it is displayed as a "min"+ ) |
||
111 | +177 |
- #'+ ) |
||
112 | -+ | |||
178 | +110x |
- #'+ } else if (inherits(data(), "error")) { |
||
113 | -+ | |||
179 | +11x |
- #' @param content (`teal_slices`) object returned from [teal_slices()] function.+ if (is_shiny_silent_error && !validate_shiny_silent_error) { |
||
114 | -+ | |||
180 | +4x |
- #' @return `self`, invisibly.+ return(NULL) |
||
115 | +181 |
- set_content = function(content) {- |
- ||
116 | -9x | -
- checkmate::assert_class(content, "teal_slices")+ } |
||
117 | -8x | +182 | +7x |
- if (length(content) != 0) {+ validate( |
118 | -6x | +183 | +7x |
- states_list <- lapply(content, function(x) {+ need( |
119 | -6x | +184 | +7x |
- x_list <- shiny::isolate(as.list(x))+ FALSE, |
120 | -6x | +185 | +7x |
- if (+ sprintf( |
121 | -6x | +186 | +7x |
- inherits(x_list$choices, c("integer", "numeric", "Date", "POSIXct", "POSIXlt")) &&+ "Shiny error when executing the `data` module.\n%s\n%s", |
122 | -6x | +187 | +7x |
- length(x_list$choices) == 2 &&+ data()$message, |
123 | -6x | +188 | +7x |
- length(x_list$selected) == 2+ "Check your inputs or contact app developer if error persists." |
124 | +189 |
- ) {+ ) |
||
125 | -! | +|||
190 | +
- x_list$range <- paste(x_list$selected, collapse = " - ")+ ) |
|||
126 | -! | +|||
191 | +
- x_list["selected"] <- NULL+ ) |
|||
127 | +192 |
- }+ } |
||
128 | -6x | +|||
193 | +
- if (!is.null(x_list$arg)) {+ }) |
|||
129 | -! | +|||
194 | +
- x_list$arg <- if (x_list$arg == "subset") "Genes" else "Samples"+ }) |
|||
130 | +195 |
- }+ } |
||
131 | +196 | |||
132 | -6x | -
- x_list <- x_list[- |
- ||
133 | -6x | +|||
197 | +
- c("dataname", "varname", "experiment", "arg", "expr", "selected", "range", "keep_na", "keep_inf")+ |
|||
134 | +198 |
- ]+ #' @keywords internal |
||
135 | -6x | +|||
199 | +
- names(x_list) <- c(+ ui_check_class_teal_data <- function(id) { |
|||
136 | -6x | +200 | +116x |
- "Dataset name", "Variable name", "Experiment", "Filtering by", "Applied expression",+ ns <- NS(id) |
137 | -6x | +201 | +116x |
- "Selected Values", "Selected range", "Include NA values", "Include Inf values"+ uiOutput(ns("message")) |
138 | +202 |
- )+ } |
||
139 | +203 | |||
140 | -6x | -
- Filter(Negate(is.null), x_list)- |
- ||
141 | +204 |
- })+ #' @keywords internal |
||
142 | +205 |
-
+ srv_check_class_teal_data <- function(id, data) { |
||
143 | -6x | +206 | +113x |
- if (requireNamespace("yaml", quietly = TRUE)) {+ checkmate::assert_string(id) |
144 | -6x | -
- super$set_content(yaml::as.yaml(states_list))- |
- ||
145 | -+ | 207 | +113x |
- } else {+ moduleServer(id, function(input, output, session) { |
146 | -! | +|||
208 | +113x |
- stop("yaml package is required to format the filter state list")+ output$message <- renderUI({ |
||
147 | -+ | |||
209 | +112x |
- }+ validate( |
||
148 | -+ | |||
210 | +112x |
- }+ need( |
||
149 | -8x | +211 | +112x |
- private$teal_slices <- content+ inherits(data(), c("teal_data", "error")), |
150 | -8x | +212 | +112x |
- invisible(self)+ "Did not receive `teal_data` object. Cannot proceed further." |
151 | +213 |
- },+ ) |
||
152 | +214 |
- #' @description Create the `TealSlicesBlock` from a list.+ ) |
||
153 | +215 |
- #'+ }) |
||
154 | +216 |
- #' @param x (`named list`) with two fields `text` and `style`.+ }) |
||
155 | +217 |
- #' Use the `get_available_styles` method to get all possible styles.+ } |
||
156 | +218 |
- #'+ |
||
157 | +219 |
- #' @return `self`, invisibly.+ #' @keywords internal |
||
158 | +220 |
- #' @examples+ ui_check_module_datanames <- function(id) { |
||
159 | -+ | |||
221 | +116x |
- #' TealSlicesBlock <- getFromNamespace("TealSlicesBlock", "teal")+ ns <- NS(id)+ |
+ ||
222 | +116x | +
+ uiOutput(NS(id, "message")) |
||
160 | +223 |
- #' block <- TealSlicesBlock$new()+ } |
||
161 | +224 |
- #' block$from_list(list(text = "sth", style = "default"))+ |
||
162 | +225 |
- #'+ #' @keywords internal |
||
163 | +226 |
- from_list = function(x) {+ srv_check_module_datanames <- function(id, data, modules) { |
||
164 | -1x | +227 | +193x |
- checkmate::assert_list(x)+ checkmate::assert_string(id) |
165 | -1x | +228 | +193x |
- checkmate::assert_names(names(x), must.include = c("text", "style"))+ moduleServer(id, function(input, output, session) { |
166 | -1x | +229 | +193x |
- super$set_content(x$text)+ output$message <- renderUI({ |
167 | -1x | +230 | +196x |
- super$set_style(x$style)+ if (inherits(data(), "teal_data")) { |
168 | -1x | +231 | +179x |
- invisible(self)+ is_modules_ok <- check_modules_datanames_html( |
169 | -+ | |||
232 | +179x |
- },+ modules = modules, datanames = names(data()) |
||
170 | +233 |
- #' @description Convert the `TealSlicesBlock` to a list.+ ) |
||
171 | -+ | |||
234 | +179x |
- #'+ if (!isTRUE(is_modules_ok)) { |
||
172 | -+ | |||
235 | +19x |
- #' @return `named list` with a text and style.+ tags$div(is_modules_ok, class = "teal-output-warning") |
||
173 | +236 |
- #' @examples+ } |
||
174 | +237 |
- #' TealSlicesBlock <- getFromNamespace("TealSlicesBlock", "teal")+ } |
||
175 | +238 |
- #' block <- TealSlicesBlock$new()+ }) |
||
176 | +239 |
- #' block$to_list()+ }) |
||
177 | +240 |
- #'+ } |
||
178 | +241 |
- to_list = function() {+ |
||
179 | -2x | +|||
242 | +
- content <- self$get_content()+ .trigger_on_success <- function(data) { |
|||
180 | -2x | +243 | +113x |
- list(+ out <- reactiveVal(NULL) |
181 | -2x | +244 | +113x |
- text = if (length(content)) content else "",+ observeEvent(data(), { |
182 | -2x | +245 | +112x |
- style = self$get_style()+ if (inherits(data(), "teal_data")) { |
183 | -+ | |||
246 | +97x |
- )+ if (!identical(data(), out())) { |
||
184 | -+ | |||
247 | +97x |
- }+ out(data()) |
||
185 | +248 |
- ),+ } |
||
186 | +249 |
- private = list(+ } |
||
187 | +250 |
- style = "verbatim",+ }) |
||
188 | +251 |
- teal_slices = NULL # teal_slices+ |
||
189 | -+ | |||
252 | +113x |
- )+ out |
||
190 | +253 |
- )+ } |
1 |
- #' An example `teal` module+ #' Data module for `teal` transformations and output customization |
||
3 |
- #' `r lifecycle::badge("experimental")`+ #' @description |
||
4 |
- #'+ #' `r lifecycle::badge("experimental")` |
||
5 |
- #' This module creates an object called `object` that can be modified with decorators.+ #' |
||
6 |
- #' The `object` is determined by what's selected in `Choose a dataset` input in UI.+ #' `teal_transform_module` provides a `shiny` module that enables data transformations within a `teal` application |
||
7 |
- #' The object can be anything that can be handled by `renderPrint()`.+ #' and allows for customization of outputs generated by modules. |
||
8 |
- #' See the `vignette("decorate-modules-output", package = "teal")` or [`teal_transform_module`]+ #' |
||
9 |
- #' to read more about decorators.+ #' # Transforming Module Inputs in `teal` |
||
11 |
- #' @inheritParams teal_modules+ #' Data transformations occur after data has been filtered in `teal`. |
||
12 |
- #' @param decorators `r lifecycle::badge("experimental")` (`list` of `teal_transform_module` or `NULL`) optional,+ #' The transformed data is then passed to the `server` of [`teal_module()`] and managed by `teal`'s internal processes. |
||
13 |
- #' if not `NULL`, decorator for tables or plots included in the module.+ #' The primary advantage of `teal_transform_module` over custom modules is in its error handling, where all warnings and |
||
14 |
- #'+ #' errors are managed by `teal`, allowing developers to focus on transformation logic. |
||
15 |
- #' @return A `teal` module which can be included in the `modules` argument to [init()].+ #' |
||
16 |
- #' @examples+ #' For more details, see the vignette: `vignette("data-transform-as-shiny-module", package = "teal")`. |
||
17 |
- #' app <- init(+ #' |
||
18 |
- #' data = teal_data(IRIS = iris, MTCARS = mtcars),+ #' # Customizing Module Outputs |
||
19 |
- #' modules = example_module()+ #' |
||
20 |
- #' )+ #' `teal_transform_module` also allows developers to modify any object created within [`teal.data::teal_data`]. |
||
21 |
- #' if (interactive()) {+ #' This means you can use it to customize not only datasets but also tables, listings, and graphs. |
||
22 |
- #' shinyApp(app$ui, app$server)+ #' Some [`teal_modules`] permit developers to inject custom `shiny` modules to enhance displayed outputs. |
||
23 |
- #' }+ #' To manage these `decorators` within your module, use [`ui_transform_teal_data()`] and [`srv_transform_teal_data()`]. |
||
24 |
- #' @export+ #' (For further guidance on managing decorators, refer to `ui_args` and `srv_args` in the vignette documentation.) |
||
25 |
- example_module <- function(label = "example teal module",+ #' |
||
26 |
- datanames = "all",+ #' See the vignette `vignette("decorate-modules-output", package = "teal")` for additional examples. |
||
27 |
- transformators = list(),+ #' |
||
28 |
- decorators = NULL) {+ #' # `server` as a language |
||
29 | -43x | -
- checkmate::assert_string(label)- |
- |
30 | -43x | +
- checkmate::assert_list(decorators, "teal_transform_module", null.ok = TRUE)+ #' |
|
31 | +30 | - - | -|
32 | -43x | -
- ans <- module(- |
- |
33 | -43x | -
- label,- |
- |
34 | -43x | -
- server = function(id, data, decorators) {- |
- |
35 | -5x | -
- checkmate::assert_class(isolate(data()), "teal_data")- |
- |
36 | -5x | -
- moduleServer(id, function(input, output, session) {- |
- |
37 | -5x | -
- datanames_rv <- reactive(names(req(data())))- |
- |
38 | -5x | -
- observeEvent(datanames_rv(), {- |
- |
39 | -5x | -
- selected <- input$dataname- |
- |
40 | -5x | -
- if (identical(selected, "")) {- |
- |
41 | -! | -
- selected <- restoreInput(session$ns("dataname"), NULL)- |
- |
42 | -5x | -
- } else if (isFALSE(selected %in% datanames_rv())) {- |
- |
43 | -! | -
- selected <- datanames_rv()[1]+ #' The `server` function in `teal_transform_module` must return a reactive [`teal.data::teal_data`] object. |
|
44 | +31 |
- }- |
- |
45 | -5x | -
- updateSelectInput(- |
- |
46 | -5x | -
- session = session,- |
- |
47 | -5x | -
- inputId = "dataname",- |
- |
48 | -5x | -
- choices = datanames_rv(),- |
- |
49 | -5x | -
- selected = selected+ #' For simple transformations without complex reactivity, the `server` function might look like this:s |
|
50 | +32 |
- )+ #' |
|
51 | +33 |
- })+ #' ``` |
|
52 | +34 | - - | -|
53 | -5x | -
- table_data <- reactive({- |
- |
54 | -8x | -
- req(input$dataname)- |
- |
55 | -3x | -
- within(data(),+ #' function(id, data) { |
|
56 | +35 |
- {- |
- |
57 | -3x | -
- object <- dataname+ #' moduleServer(id, function(input, output, session) { |
|
58 | +36 |
- },- |
- |
59 | -3x | -
- dataname = as.name(input$dataname)+ #' reactive({ |
|
60 | +37 |
- )+ #' within( |
|
61 | +38 |
- })+ #' data(), |
|
62 | +39 | - - | -|
63 | -5x | -
- table_data_decorated_no_print <- srv_transform_teal_data(- |
- |
64 | -5x | -
- "decorate",- |
- |
65 | -5x | -
- data = table_data,- |
- |
66 | -5x | -
- transformators = decorators+ #' expr = x <- subset(x, col == level), |
|
67 | +40 |
- )- |
- |
68 | -5x | -
- table_data_decorated <- reactive(within(req(table_data_decorated_no_print()), expr = object))+ #' level = input$level |
|
69 | +41 | - - | -|
70 | -5x | -
- output$text <- renderPrint({- |
- |
71 | -9x | -
- req(table_data()) # Ensure original errors from module are displayed- |
- |
72 | -4x | -
- table_data_decorated()[["object"]]+ #' ) |
|
73 | +42 |
- })+ #' }) |
|
74 | +43 | - - | -|
75 | -5x | -
- teal.widgets::verbatim_popup_srv(- |
- |
76 | -5x | -
- id = "rcode",- |
- |
77 | -5x | -
- verbatim_content = reactive(teal.code::get_code(req(table_data_decorated()))),- |
- |
78 | -5x | -
- title = "Example Code"+ #' }) |
|
79 | +44 |
- )+ #' } |
|
80 | +45 | - - | -|
81 | -5x | -
- table_data_decorated+ #' ``` |
|
82 | +46 |
- })+ #' |
|
83 | +47 |
- },- |
- |
84 | -43x | -
- ui = function(id, decorators) {- |
- |
85 | -! | -
- ns <- NS(id)- |
- |
86 | -! | -
- teal.widgets::standard_layout(- |
- |
87 | -! | -
- output = verbatimTextOutput(ns("text")),- |
- |
88 | -! | -
- encoding = tags$div(- |
- |
89 | -! | -
- selectInput(ns("dataname"), "Choose a dataset", choices = NULL),- |
- |
90 | -! | -
- ui_transform_teal_data(ns("decorate"), transformators = decorators),- |
- |
91 | -! | -
- teal.widgets::verbatim_popup_ui(ns("rcode"), "Show R code")+ #' The example above can be simplified using `make_teal_transform_server`, where `level` is automatically matched to the |
|
92 | +48 |
- )+ #' corresponding `input` parameter: |
|
93 | +49 |
- )+ #' |
|
94 | +50 |
- },- |
- |
95 | -43x | -
- ui_args = list(decorators = decorators),- |
- |
96 | -43x | -
- server_args = list(decorators = decorators),- |
- |
97 | -43x | -
- datanames = datanames,- |
- |
98 | -43x | -
- transformators = transformators+ #' ``` |
|
99 | +51 |
- )- |
- |
100 | -43x | -
- attr(ans, "teal_bookmarkable") <- TRUE- |
- |
101 | -43x | -
- ans+ #' make_teal_transform_server(expr = expression(x <- subset(x, col == level))) |
|
102 | +52 |
- }+ #' ``` |
1 | +53 |
- #' Filter settings for `teal` applications+ #' @inheritParams teal_data_module |
||
2 | +54 |
- #'+ #' @param server (`function(id, data)` or `expression`) |
||
3 | +55 |
- #' Specify initial filter states and filtering settings for a `teal` app.+ #' A `shiny` module server function that takes `id` and `data` as arguments, where `id` is the module id and `data` |
||
4 | +56 |
- #'+ #' is the reactive `teal_data` input. The `server` function must return a reactive expression containing a `teal_data` |
||
5 | +57 |
- #' Produces a `teal_slices` object.+ #' object. For simplified syntax, use [`make_teal_transform_server()`]. |
||
6 | +58 |
- #' The `teal_slice` components will specify filter states that will be active when the app starts.+ #' @param datanames (`character`) |
||
7 | +59 |
- #' Attributes (created with the named arguments) will configure the way the app applies filters.+ #' Specifies the names of datasets relevant to the module. Only filters for the specified `datanames` will be displayed |
||
8 | +60 |
- #' See argument descriptions for details.+ #' in the filter panel. The keyword `"all"` can be used to display filters for all datasets. `datanames` are |
||
9 | +61 |
- #'+ #' automatically appended to the [`modules()`] `datanames`. |
||
10 | +62 |
- #' @inheritParams teal.slice::teal_slices+ #' |
||
11 | +63 |
#' |
||
12 | +64 |
- #' @param module_specific (`logical(1)`) optional,+ #' @examples |
||
13 | +65 |
- #' - `FALSE` (default) when one filter panel applied to all modules.+ #' data_transformators <- list( |
||
14 | +66 |
- #' All filters will be shared by all modules.+ #' teal_transform_module( |
||
15 | +67 |
- #' - `TRUE` when filter panel module-specific.+ #' label = "Static transformator for iris", |
||
16 | +68 |
- #' Modules can have different set of filters specified - see `mapping` argument.+ #' datanames = "iris", |
||
17 | +69 |
- #' @param mapping `r lifecycle::badge("experimental")`+ #' server = function(id, data) { |
||
18 | +70 |
- #' _This is a new feature. Do kindly share your opinions on+ #' moduleServer(id, function(input, output, session) { |
||
19 | +71 |
- #' [`teal`'s GitHub repository](https://github.com/insightsengineering/teal/)._+ #' reactive({ |
||
20 | +72 |
- #'+ #' within(data(), { |
||
21 | +73 |
- #' (named `list`) specifies which filters will be active in which modules on app start.+ #' iris <- head(iris, 5) |
||
22 | +74 |
- #' Elements should contain character vector of `teal_slice` `id`s (see [`teal.slice::teal_slice`]).+ #' }) |
||
23 | +75 |
- #' Names of the list should correspond to `teal_module` `label` set in [module()] function.+ #' }) |
||
24 | +76 |
- #' - `id`s listed under `"global_filters` will be active in all modules.+ #' }) |
||
25 | +77 |
- #' - If missing, all filters will be applied to all modules.+ #' } |
||
26 | +78 |
- #' - If empty list, all filters will be available to all modules but will start inactive.+ #' ), |
||
27 | +79 |
- #' - If `module_specific` is `FALSE`, only `global_filters` will be active on start.+ #' teal_transform_module( |
||
28 | +80 |
- #' @param app_id (`character(1)`)+ #' label = "Interactive transformator for iris", |
||
29 | +81 |
- #' For internal use only, do not set manually.+ #' datanames = "iris", |
||
30 | +82 |
- #' Added by `init` so that a `teal_slices` can be matched to the app in which it was used.+ #' ui = function(id) { |
||
31 | +83 |
- #' Used for verifying snapshots uploaded from file. See `snapshot`.+ #' ns <- NS(id) |
||
32 | +84 |
- #'+ #' tags$div( |
||
33 | +85 |
- #' @param x (`list`) of lists to convert to `teal_slices`+ #' numericInput(ns("n_cols"), "Show n columns", value = 5, min = 1, max = 5, step = 1) |
||
34 | +86 |
- #'+ #' ) |
||
35 | +87 |
- #' @return+ #' }, |
||
36 | +88 |
- #' A `teal_slices` object.+ #' server = function(id, data) { |
||
37 | +89 |
- #'+ #' moduleServer(id, function(input, output, session) { |
||
38 | +90 |
- #' @seealso [`teal.slice::teal_slices`], [`teal.slice::teal_slice`], [slices_store()]+ #' reactive({ |
||
39 | +91 |
- #'+ #' within(data(), |
||
40 | +92 |
- #' @examples+ #' { |
||
41 | +93 |
- #' filter <- teal_slices(+ #' iris <- iris[, 1:n_cols] |
||
42 | +94 |
- #' teal_slice(dataname = "iris", varname = "Species", id = "species"),+ #' }, |
||
43 | +95 |
- #' teal_slice(dataname = "iris", varname = "Sepal.Length", id = "sepal_length"),+ #' n_cols = input$n_cols |
||
44 | +96 |
- #' teal_slice(+ #' ) |
||
45 | +97 |
- #' dataname = "iris", id = "long_petals", title = "Long petals", expr = "Petal.Length > 5"+ #' }) |
||
46 | +98 |
- #' ),+ #' }) |
||
47 | +99 |
- #' teal_slice(dataname = "mtcars", varname = "mpg", id = "mtcars_mpg"),+ #' } |
||
48 | +100 |
- #' mapping = list(+ #' ) |
||
49 | +101 |
- #' module1 = c("species", "sepal_length"),+ #' ) |
||
50 | +102 |
- #' module2 = c("mtcars_mpg"),+ #' |
||
51 | +103 |
- #' global_filters = "long_petals"+ #' output_decorator <- teal_transform_module( |
||
52 | +104 |
- #' )+ #' server = make_teal_transform_server( |
||
53 | +105 |
- #' )+ #' expression( |
||
54 | +106 |
- #'+ #' object <- rev(object) |
||
55 | +107 |
- #' app <- init(+ #' ) |
||
56 | +108 |
- #' data = teal_data(iris = iris, mtcars = mtcars),+ #' ) |
||
57 | +109 |
- #' modules = list(+ #' ) |
||
58 | +110 |
- #' module("module1"),+ #' |
||
59 | +111 |
- #' module("module2")+ #' app <- init( |
||
60 | +112 |
- #' ),+ #' data = teal_data(iris = iris), |
||
61 | +113 |
- #' filter = filter+ #' modules = example_module( |
||
62 | +114 |
- #' )+ #' transformators = data_transformators, |
||
63 | +115 |
- #'+ #' decorators = list(output_decorator) |
||
64 | +116 |
- #' if (interactive()) {+ #' ) |
||
65 | +117 |
- #' shinyApp(app$ui, app$server)+ #' ) |
||
66 | +118 |
- #' }+ #' if (interactive()) { |
||
67 | +119 |
- #'+ #' shinyApp(app$ui, app$server) |
||
68 | +120 |
- #' @export+ #' } |
||
69 | +121 |
- teal_slices <- function(...,+ #' |
||
70 | +122 |
- exclude_varnames = NULL,+ #' @name teal_transform_module |
||
71 | +123 |
- include_varnames = NULL,+ #' |
||
72 | +124 |
- count_type = NULL,+ #' @export |
||
73 | +125 |
- allow_add = TRUE,+ teal_transform_module <- function(ui = NULL, |
||
74 | +126 |
- module_specific = FALSE,+ server = function(id, data) data, |
||
75 | +127 |
- mapping,+ label = "transform module", |
||
76 | +128 |
- app_id = NULL) {+ datanames = "all") { |
||
77 | -170x | +129 | +25x |
- shiny::isolate({+ structure( |
78 | -170x | +130 | +25x |
- checkmate::assert_flag(allow_add)+ list( |
79 | -170x | +131 | +25x |
- checkmate::assert_flag(module_specific)+ ui = ui, |
80 | -53x | +132 | +25x |
- if (!missing(mapping)) checkmate::assert_list(mapping, types = c("character", "NULL"), names = "named")+ server = function(id, data) { |
81 | -167x | +133 | +26x |
- checkmate::assert_string(app_id, null.ok = TRUE)+ data_out <- server(id, data) |
82 | +134 | |||
83 | -167x | -
- slices <- list(...)- |
- ||
84 | -167x | +135 | +26x |
- all_slice_id <- vapply(slices, `[[`, character(1L), "id")+ if (inherits(data_out, "reactive.event")) { |
85 | +136 |
-
+ # This warning message partially detects when `eventReactive` is used in `data_module`. |
||
86 | -167x | +137 | +1x |
- if (missing(mapping)) {+ warning( |
87 | -117x | +138 | +1x |
- mapping <- if (length(all_slice_id)) {+ "teal_transform_module() ", |
88 | -26x | +139 | +1x |
- list(global_filters = all_slice_id)+ "Using eventReactive in teal_transform module server code should be avoided as it ", |
89 | -+ | |||
140 | +1x |
- } else {+ "may lead to unexpected behavior. See the vignettes for more information ", |
||
90 | -91x | +141 | +1x |
- list()+ "(`vignette(\"data-transform-as-shiny-module\", package = \"teal\")`).", |
91 | -+ | |||
142 | +1x |
- }+ call. = FALSE |
||
92 | +143 |
- }+ ) |
||
93 | +144 | - - | -||
94 | -167x | -
- if (!module_specific) {- |
- ||
95 | -148x | -
- mapping[setdiff(names(mapping), "global_filters")] <- NULL+ } |
||
96 | +145 |
- }+ |
||
97 | +146 | |||
98 | -167x | -
- failed_slice_id <- setdiff(unlist(mapping), all_slice_id)- |
- ||
99 | -167x | -
- if (length(failed_slice_id)) {- |
- ||
100 | -1x | +147 | +26x |
- stop(sprintf(+ decorate_err_msg( |
101 | -1x | +148 | +26x |
- "Filters in mapping don't match any available filter.\n %s not in %s",+ assert_reactive(data_out), |
102 | -1x | +149 | +26x |
- toString(failed_slice_id),+ pre = sprintf("From: 'teal_transform_module()':\nA 'teal_transform_module' with \"%s\" label:", label), |
103 | -1x | +150 | +26x |
- toString(all_slice_id)+ post = "Please make sure that this module returns a 'reactive` object containing 'teal_data' class of object." # nolint: line_length_linter. |
104 | +151 |
- ))+ ) |
||
105 | +152 |
- }+ } |
||
106 | +153 |
-
+ ), |
||
107 | -166x | +154 | +25x |
- tss <- teal.slice::teal_slices(+ label = label, |
108 | -+ | |||
155 | +25x |
- ...,+ datanames = datanames, |
||
109 | -166x | +156 | +25x |
- exclude_varnames = exclude_varnames,+ class = c("teal_transform_module", "teal_data_module") |
110 | -166x | +|||
157 | ++ |
+ )+ |
+ ||
158 | +
- include_varnames = include_varnames,+ } |
|||
111 | -166x | +|||
159 | +
- count_type = count_type,+ |
|||
112 | -166x | +|||
160 | +
- allow_add = allow_add+ #' Make teal_transform_module's server |
|||
113 | +161 |
- )+ #' |
||
114 | -166x | +|||
162 | +
- attr(tss, "mapping") <- mapping+ #' A factory function to simplify creation of a [`teal_transform_module`]'s server. Specified `expr` |
|||
115 | -166x | +|||
163 | +
- attr(tss, "module_specific") <- module_specific+ #' is wrapped in a shiny module function and output can be passed to the `server` argument in |
|||
116 | -166x | +|||
164 | +
- attr(tss, "app_id") <- app_id+ #' [teal_transform_module()] call. Such a server function can be linked with ui and values from the |
|||
117 | -166x | +|||
165 | +
- class(tss) <- c("modules_teal_slices", class(tss))+ #' inputs can be used in the expression. Object names specified in the expression will be substituted |
|||
118 | -166x | +|||
166 | +
- tss+ #' with the value of the respective input (matched by the name) - for example in |
|||
119 | +167 |
- })+ #' `expression(graph <- graph + ggtitle(title))` object `title` will be replaced with the value of |
||
120 | +168 |
- }+ #' `input$title`. |
||
121 | +169 |
-
+ #' @param expr (`language`) |
||
122 | +170 |
-
+ #' An R call which will be evaluated within [`teal.data::teal_data`] environment. |
||
123 | +171 |
- #' @rdname teal_slices+ #' @return `function(id, data)` returning `shiny` module |
||
124 | +172 |
- #' @export+ #' @examples |
||
125 | +173 |
- #' @keywords internal+ #' |
||
126 | +174 |
- #'+ #' trim_iris <- teal_transform_module( |
||
127 | +175 |
- as.teal_slices <- function(x) { # nolint: object_name.+ #' label = "Simplified interactive transformator for iris", |
||
128 | -15x | +|||
176 | +
- checkmate::assert_list(x)+ #' datanames = "iris", |
|||
129 | -15x | +|||
177 | +
- lapply(x, checkmate::assert_list, names = "named", .var.name = "list element")+ #' ui = function(id) { |
|||
130 | +178 |
-
+ #' ns <- NS(id) |
||
131 | -15x | +|||
179 | +
- attrs <- attributes(unclass(x))+ #' numericInput(ns("n_rows"), "Subset n rows", value = 6, min = 1, max = 150, step = 1) |
|||
132 | -15x | +|||
180 | +
- ans <- lapply(x, function(x) if (is.teal_slice(x)) x else as.teal_slice(x))+ #' }, |
|||
133 | -15x | +|||
181 | +
- do.call(teal_slices, c(ans, attrs))+ #' server = make_teal_transform_server(expression(iris <- head(iris, n_rows))) |
|||
134 | +182 |
- }+ #' ) |
||
135 | +183 |
-
+ #' |
||
136 | +184 |
-
+ #' app <- init( |
||
137 | +185 |
- #' @rdname teal_slices+ #' data = teal_data(iris = iris), |
||
138 | +186 |
- #' @export+ #' modules = example_module(transformators = trim_iris) |
||
139 | +187 |
- #' @keywords internal+ #' ) |
||
140 | +188 |
- #'+ #' if (interactive()) { |
||
141 | +189 |
- c.teal_slices <- function(...) {+ #' shinyApp(app$ui, app$server) |
||
142 | -6x | +|||
190 | +
- x <- list(...)+ #' } |
|||
143 | -6x | +|||
191 | +
- checkmate::assert_true(all(vapply(x, is.teal_slices, logical(1L))), .var.name = "all arguments are teal_slices")+ #' |
|||
144 | +192 |
-
+ #' @export |
||
145 | -6x | +|||
193 | +
- all_attributes <- lapply(x, attributes)+ make_teal_transform_server <- function(expr) { |
|||
146 | -6x | +194 | +3x |
- all_attributes <- coalesce_r(all_attributes)+ if (is.call(expr)) { |
147 | -6x | +195 | +1x |
- all_attributes <- all_attributes[names(all_attributes) != "class"]+ expr <- as.expression(expr) |
148 | +196 |
-
+ } |
||
149 | -6x | +197 | +3x |
- do.call(+ checkmate::assert_multi_class(expr, c("call", "expression"))+ |
+
198 | ++ | + | ||
150 | -6x | +199 | +3x |
- teal_slices,+ function(id, data) { |
151 | -6x | +200 | +3x |
- c(+ moduleServer(id, function(input, output, session) { |
152 | -6x | +201 | +3x |
- unique(unlist(x, recursive = FALSE)),+ list_env <- reactive( |
153 | -6x | +202 | +3x |
- all_attributes+ lapply(rlang::set_names(names(input)), function(x) input[[x]]) |
154 | +203 |
- )+ ) |
||
155 | +204 |
- )+ |
||
156 | -+ | |||
205 | +3x |
- }+ reactive({ |
||
157 | -+ | |||
206 | +4x |
-
+ call_with_inputs <- lapply(expr, function(x) { |
||
158 | -+ | |||
207 | +4x |
-
+ do.call(what = substitute, args = list(expr = x, env = list_env())) |
||
159 | +208 |
- #' Deep copy `teal_slices`+ }) |
||
160 | -+ | |||
209 | +4x |
- #'+ eval_code(object = data(), code = as.expression(call_with_inputs)) |
||
161 | +210 |
- #' it's important to create a new copy of `teal_slices` when+ }) |
||
162 | +211 |
- #' starting a new `shiny` session. Otherwise, object will be shared+ }) |
||
163 | +212 |
- #' by multiple users as it is created in global environment before+ } |
||
164 | +213 |
- #' `shiny` session starts.+ } |
||
165 | +214 |
- #' @param filter (`teal_slices`)+ |
||
166 | +215 |
- #' @return `teal_slices`+ #' Extract all `transformators` from `modules`. |
||
167 | +216 |
- #' @keywords internal+ #' |
||
168 | +217 |
- deep_copy_filter <- function(filter) {+ #' @param modules `teal_modules` or `teal_module` |
||
169 | -1x | +|||
218 | +
- checkmate::assert_class(filter, "teal_slices")+ #' @return A list of `teal_transform_module` nested in the same way as input `modules`. |
|||
170 | -1x | +|||
219 | +
- shiny::isolate({+ #' @keywords internal |
|||
171 | -1x | +|||
220 | +
- filter_copy <- lapply(filter, function(slice) {+ extract_transformators <- function(modules) { |
|||
172 | -2x | +221 | +10x |
- teal.slice::as.teal_slice(as.list(slice))+ if (inherits(modules, "teal_module")) { |
173 | -+ | |||
222 | +5x |
- })+ modules$transformators |
||
174 | -1x | +223 | +5x |
- attributes(filter_copy) <- attributes(filter)+ } else if (inherits(modules, "teal_modules")) { |
175 | -1x | +224 | +5x |
- filter_copy+ lapply(modules$children, extract_transformators) |
176 | +225 |
- })+ } |
||
177 | +226 |
}@@ -16958,7010 +16197,6966 @@ teal coverage - 60.11% |
1 |
- # This is the main function from teal to be used by the end-users. Although it delegates+ #' An example `teal` module |
|||
2 |
- # directly to `module_teal_with_splash.R`, we keep it in a separate file because its documentation is quite large+ #' |
|||
3 |
- # and it is very end-user oriented. It may also perform more argument checking with more informative+ #' `r lifecycle::badge("experimental")` |
|||
4 |
- # error messages.+ #' |
|||
5 |
-
+ #' This module creates an object called `object` that can be modified with decorators. |
|||
6 |
- #' Create the server and UI function for the `shiny` app+ #' The `object` is determined by what's selected in `Choose a dataset` input in UI. |
|||
7 |
- #'+ #' The object can be anything that can be handled by `renderPrint()`. |
|||
8 |
- #' @description `r lifecycle::badge("stable")`+ #' See the `vignette("decorate-modules-output", package = "teal")` or [`teal_transform_module`] |
|||
9 |
- #'+ #' to read more about decorators. |
|||
10 |
- #' End-users: This is the most important function for you to start a+ #' |
|||
11 |
- #' `teal` app that is composed of `teal` modules.+ #' @inheritParams teal_modules |
|||
12 |
- #'+ #' @param decorators `r lifecycle::badge("experimental")` (`list` of `teal_transform_module` or `NULL`) optional, |
|||
13 |
- #' @param data (`teal_data` or `teal_data_module`)+ #' if not `NULL`, decorator for tables or plots included in the module. |
|||
14 |
- #' For constructing the data object, refer to [teal.data::teal_data()] and [teal_data_module()].+ #' |
|||
15 |
- #' If `datanames` are not set for the `teal_data` object, defaults from the `teal_data` environment will be used.+ #' @return A `teal` module which can be included in the `modules` argument to [init()]. |
|||
16 |
- #' @param modules (`list` or `teal_modules` or `teal_module`)+ #' @examples |
|||
17 |
- #' Nested list of `teal_modules` or `teal_module` objects or a single+ #' app <- init( |
|||
18 |
- #' `teal_modules` or `teal_module` object. These are the specific output modules which+ #' data = teal_data(IRIS = iris, MTCARS = mtcars), |
|||
19 |
- #' will be displayed in the `teal` application. See [modules()] and [module()] for+ #' modules = example_module() |
|||
20 |
- #' more details.+ #' ) |
|||
21 |
- #' @param filter (`teal_slices`) Optionally,+ #' if (interactive()) { |
|||
22 |
- #' specifies the initial filter using [teal_slices()].+ #' shinyApp(app$ui, app$server) |
|||
23 |
- #' @param title (`shiny.tag` or `character(1)`) Optionally,+ #' } |
|||
24 |
- #' the browser window title. Defaults to a title "teal app" with the icon of NEST.+ #' @export |
|||
25 |
- #' Can be created using the `build_app_title()` or+ example_module <- function(label = "example teal module", |
|||
26 |
- #' by passing a valid `shiny.tag` which is a head tag with title and link tag.+ datanames = "all", |
|||
27 |
- #' @param header (`shiny.tag` or `character(1)`) Optionally,+ transformators = list(), |
|||
28 |
- #' the header of the app.+ decorators = NULL) { |
|||
29 | -+ | 43x |
- #' @param footer (`shiny.tag` or `character(1)`) Optionally,+ checkmate::assert_string(label) |
|
30 | -+ | 43x |
- #' the footer of the app.+ checkmate::assert_list(decorators, "teal_transform_module", null.ok = TRUE) |
|
31 |
- #' @param id (`character`) Optionally,+ |
|||
32 | -+ | 43x |
- #' a string specifying the `shiny` module id in cases it is used as a `shiny` module+ ans <- module( |
|
33 | -+ | 43x |
- #' rather than a standalone `shiny` app. This is a legacy feature.+ label, |
|
34 | -+ | 43x |
- #' @param landing_popup (`teal_module_landing`) Optionally,+ server = function(id, data, decorators) { |
|
35 | -+ | 5x |
- #' a `landing_popup_module` to show up as soon as the teal app is initialized.+ checkmate::assert_class(isolate(data()), "teal_data") |
|
36 | -+ | 5x |
- #'+ moduleServer(id, function(input, output, session) { |
|
37 | -+ | 5x |
- #' @return Named list containing server and UI functions.+ datanames_rv <- reactive(names(req(data()))) |
|
38 | -+ | 5x |
- #'+ observeEvent(datanames_rv(), { |
|
39 | -+ | 5x |
- #' @export+ selected <- input$dataname |
|
40 | -+ | 5x |
- #'+ if (identical(selected, "")) { |
|
41 | -+ | ! |
- #' @include modules.R+ selected <- restoreInput(session$ns("dataname"), NULL) |
|
42 | -+ | 5x |
- #'+ } else if (isFALSE(selected %in% datanames_rv())) { |
|
43 | -+ | ! |
- #' @examples+ selected <- datanames_rv()[1] |
|
44 |
- #' app <- init(+ } |
|||
45 | -+ | 5x |
- #' data = within(+ updateSelectInput( |
|
46 | -+ | 5x |
- #' teal_data(),+ session = session, |
|
47 | -+ | 5x |
- #' {+ inputId = "dataname", |
|
48 | -+ | 5x |
- #' new_iris <- transform(iris, id = seq_len(nrow(iris)))+ choices = datanames_rv(), |
|
49 | -+ | 5x |
- #' new_mtcars <- transform(mtcars, id = seq_len(nrow(mtcars)))+ selected = selected |
|
50 |
- #' }+ ) |
|||
51 |
- #' ),+ }) |
|||
52 |
- #' modules = modules(+ |
|||
53 | -+ | 5x |
- #' module(+ table_data <- reactive({ |
|
54 | -+ | 8x |
- #' label = "data source",+ req(input$dataname) |
|
55 | -+ | 3x |
- #' server = function(input, output, session, data) {},+ within(data(), |
|
56 |
- #' ui = function(id, ...) tags$div(p("information about data source")),+ { |
|||
57 | -+ | 3x |
- #' datanames = "all"+ object <- dataname |
|
58 |
- #' ),+ }, |
|||
59 | -+ | 3x |
- #' example_module(label = "example teal module"),+ dataname = as.name(input$dataname) |
|
60 |
- #' module(+ ) |
|||
61 |
- #' "Iris Sepal.Length histogram",+ }) |
|||
62 |
- #' server = function(input, output, session, data) {+ |
|||
63 | -+ | 5x |
- #' output$hist <- renderPlot(+ table_data_decorated_no_print <- srv_transform_teal_data( |
|
64 | -+ | 5x |
- #' hist(data()[["new_iris"]]$Sepal.Length)+ "decorate", |
|
65 | -+ | 5x |
- #' )+ data = table_data, |
|
66 | -+ | 5x |
- #' },+ transformators = decorators |
|
67 |
- #' ui = function(id, ...) {+ ) |
|||
68 | -+ | 5x |
- #' ns <- NS(id)+ table_data_decorated <- reactive(within(req(table_data_decorated_no_print()), expr = object)) |
|
69 |
- #' plotOutput(ns("hist"))+ |
|||
70 | -+ | 5x |
- #' },+ output$text <- renderPrint({ |
|
71 | -+ | 9x |
- #' datanames = "new_iris"+ req(table_data()) # Ensure original errors from module are displayed |
|
72 | -+ | 4x |
- #' )+ table_data_decorated()[["object"]] |
|
73 |
- #' ),+ }) |
|||
74 |
- #' filter = teal_slices(+ |
|||
75 | -+ | 5x |
- #' teal_slice(dataname = "new_iris", varname = "Species"),+ teal.widgets::verbatim_popup_srv( |
|
76 | -+ | 5x |
- #' teal_slice(dataname = "new_iris", varname = "Sepal.Length"),+ id = "rcode", |
|
77 | -+ | 5x |
- #' teal_slice(dataname = "new_mtcars", varname = "cyl"),+ verbatim_content = reactive(teal.code::get_code(req(table_data_decorated()))), |
|
78 | -+ | 5x |
- #' exclude_varnames = list(new_iris = c("Sepal.Width", "Petal.Width")),+ title = "Example Code" |
|
79 |
- #' module_specific = TRUE,+ ) |
|||
80 |
- #' mapping = list(+ |
|||
81 | -+ | 5x |
- #' `example teal module` = "new_iris Species",+ table_data_decorated |
|
82 |
- #' `Iris Sepal.Length histogram` = "new_iris Species",+ }) |
|||
83 |
- #' global_filters = "new_mtcars cyl"+ }, |
|||
84 | -+ | 43x |
- #' )+ ui = function(id, decorators) { |
|
85 | -+ | ! |
- #' ),+ ns <- NS(id) |
|
86 | -+ | ! |
- #' title = "App title",+ teal.widgets::standard_layout( |
|
87 | -+ | ! |
- #' header = tags$h1("Sample App"),+ output = verbatimTextOutput(ns("text")), |
|
88 | -+ | ! |
- #' footer = tags$p("Sample footer")+ encoding = tags$div( |
|
89 | -+ | ! |
- #' )+ selectInput(ns("dataname"), "Choose a dataset", choices = NULL), |
|
90 | -+ | ! |
- #' if (interactive()) {+ ui_transform_teal_data(ns("decorate"), transformators = decorators), |
|
91 | -+ | ! |
- #' shinyApp(app$ui, app$server)+ teal.widgets::verbatim_popup_ui(ns("rcode"), "Show R code") |
|
92 |
- #' }+ ) |
|||
93 |
- #'+ ) |
|||
94 |
- init <- function(data,+ }, |
|||
95 | -+ | 43x |
- modules,+ ui_args = list(decorators = decorators), |
|
96 | -+ | 43x |
- filter = teal_slices(),+ server_args = list(decorators = decorators), |
|
97 | -+ | 43x |
- title = build_app_title(),+ datanames = datanames, |
|
98 | -+ | 43x |
- header = tags$p(),+ transformators = transformators |
|
99 |
- footer = tags$p(),+ ) |
|||
100 | -- |
- id = character(0),- |
- ||
101 | -+ | 43x |
- landing_popup = NULL) {+ attr(ans, "teal_bookmarkable") <- TRUE |
|
102 | -14x | +101 | +43x |
- logger::log_debug("init initializing teal app with: data ('{ class(data) }').")+ ans |
103 | +102 |
-
+ } |
104 | +1 |
- # argument checking (independent)+ #' Get client timezone |
||
105 | +2 |
- ## `data`- |
- ||
106 | -14x | -
- checkmate::assert_multi_class(data, c("teal_data", "teal_data_module"))- |
- ||
107 | -14x | -
- checkmate::assert_class(landing_popup, "teal_module_landing", null.ok = TRUE)+ #' |
||
108 | +3 |
-
+ #' User timezone in the browser may be different to the one on the server. |
||
109 | +4 |
- ## `modules`- |
- ||
110 | -14x | -
- checkmate::assert(- |
- ||
111 | -14x | -
- .var.name = "modules",- |
- ||
112 | -14x | -
- checkmate::check_multi_class(modules, c("teal_modules", "teal_module")),- |
- ||
113 | -14x | -
- checkmate::check_list(modules, min.len = 1, any.missing = FALSE, types = c("teal_module", "teal_modules"))+ #' This script can be run to register a `shiny` input which contains information about the timezone in the browser. |
||
114 | +5 |
- )- |
- ||
115 | -14x | -
- if (inherits(modules, "teal_module")) {- |
- ||
116 | -1x | -
- modules <- list(modules)+ #' |
||
117 | +6 |
- }- |
- ||
118 | -14x | -
- if (checkmate::test_list(modules, min.len = 1, any.missing = FALSE, types = c("teal_module", "teal_modules"))) {- |
- ||
119 | -8x | -
- modules <- do.call(teal::modules, modules)+ #' @param ns (`function`) namespace function passed from the `session` object in the `shiny` server. |
||
120 | +7 |
- }+ #' For `shiny` modules this will allow for proper name spacing of the registered input. |
||
121 | +8 |
-
+ #' |
||
122 | +9 |
- ## `filter`- |
- ||
123 | -14x | -
- checkmate::assert_class(filter, "teal_slices")+ #' @return `NULL`, invisibly. |
||
124 | +10 |
-
+ #' |
||
125 | +11 |
- ## all other arguments- |
- ||
126 | -13x | -
- checkmate::assert(- |
- ||
127 | -13x | -
- .var.name = "title",- |
- ||
128 | -13x | -
- checkmate::check_string(title),- |
- ||
129 | -13x | -
- checkmate::check_multi_class(title, c("shiny.tag", "shiny.tag.list", "html"))+ #' @keywords internal |
||
130 | +12 |
- )- |
- ||
131 | -13x | -
- checkmate::assert(- |
- ||
132 | -13x | -
- .var.name = "header",- |
- ||
133 | -13x | -
- checkmate::check_string(header),- |
- ||
134 | -13x | -
- checkmate::check_multi_class(header, c("shiny.tag", "shiny.tag.list", "html"))+ #' |
||
135 | +13 |
- )- |
- ||
136 | -13x | -
- checkmate::assert(+ get_client_timezone <- function(ns) { |
||
137 | -13x | +14 | +88x |
- .var.name = "footer",+ script <- sprintf( |
138 | -13x | +15 | +88x |
- checkmate::check_string(footer),+ "Shiny.setInputValue(`%s`, Intl.DateTimeFormat().resolvedOptions().timeZone)", |
139 | -13x | +16 | +88x |
- checkmate::check_multi_class(footer, c("shiny.tag", "shiny.tag.list", "html"))+ ns("timezone") |
140 | +17 |
) |
||
141 | -13x | +18 | +88x |
- checkmate::assert_character(id, max.len = 1, any.missing = FALSE)+ shinyjs::runjs(script) # function does not return anything+ |
+
19 | +88x | +
+ invisible(NULL) |
||
142 | +20 |
-
+ } |
||
143 | +21 |
- # log+ |
||
144 | -13x | +|||
22 | +
- teal.logger::log_system_info()+ #' Resolve the expected bootstrap theme |
|||
145 | +23 |
-
+ #' @noRd |
||
146 | +24 |
- # argument transformations+ #' @keywords internal |
||
147 | +25 |
- ## `modules` - landing module+ get_teal_bs_theme <- function() { |
||
148 | -13x | +26 | +4x |
- landing <- extract_module(modules, "teal_module_landing")+ bs_theme <- getOption("teal.bs_theme") |
149 | -13x | +|||
27 | +
- if (length(landing) == 1L) {+ |
|||
150 | -! | +|||
28 | +4x |
- landing_popup <- landing[[1L]]+ if (is.null(bs_theme)) { |
||
151 | -! | +|||
29 | +1x |
- modules <- drop_module(modules, "teal_module_landing")+ return(NULL) |
||
152 | -! | +|||
30 | +
- lifecycle::deprecate_soft(+ } |
|||
153 | -! | +|||
31 | +
- when = "0.15.3",+ |
|||
154 | -! | +|||
32 | +3x |
- what = "landing_popup_module()",+ if (!checkmate::test_class(bs_theme, "bs_theme")) { |
||
155 | -! | +|||
33 | +2x |
- details = paste(+ warning( |
||
156 | -! | +|||
34 | +2x |
- "Pass `landing_popup_module` to the `landing_popup` argument of the `init` ",+ "Assertion on 'teal.bs_theme' option value failed: ", |
||
157 | -! | +|||
35 | +2x |
- "instead of wrapping it into `modules()` and passing to the `modules` argument"+ checkmate::check_class(bs_theme, "bs_theme"), |
||
158 | -+ | |||
36 | +2x |
- )+ ". The default Shiny Bootstrap theme will be used." |
||
159 | +37 |
) |
||
160 | -13x | -
- } else if (length(landing) > 1L) {- |
- ||
161 | -! | +38 | +2x |
- stop("Only one `landing_popup_module` can be used.")+ return(NULL) |
162 | +39 |
} |
||
163 | +40 | |||
164 | -- |
- ## `filter` - set app_id attribute unless present (when restoring bookmark)- |
- ||
165 | -13x | +41 | +1x |
- if (is.null(attr(filter, "app_id", exact = TRUE))) attr(filter, "app_id") <- create_app_id(data, modules)+ bs_theme |
166 | +42 |
-
+ } |
||
167 | +43 |
- ## `filter` - convert teal.slice::teal_slices to teal::teal_slices+ |
||
168 | -13x | +|||
44 | +
- filter <- as.teal_slices(as.list(filter))+ #' Return parentnames along with datanames. |
|||
169 | +45 |
-
+ #' @noRd |
||
170 | +46 |
- # argument checking (interdependent)+ #' @keywords internal |
||
171 | +47 |
- ## `filter` - `modules`+ .include_parent_datanames <- function(datanames, join_keys) { |
||
172 | -13x | +48 | +32x |
- if (isTRUE(attr(filter, "module_specific"))) {+ ordered_datanames <- datanames |
173 | -! | +|||
49 | +32x |
- module_names <- unlist(c(module_labels(modules), "global_filters"))+ for (current in datanames) { |
||
174 | -! | +|||
50 | +62x |
- failed_mod_names <- setdiff(names(attr(filter, "mapping")), module_names)+ parents <- character(0L) |
||
175 | -! | +|||
51 | +62x |
- if (length(failed_mod_names)) {+ while (length(current) > 0) { |
||
176 | -! | +|||
52 | +64x |
- stop(+ current <- teal.data::parent(join_keys, current) |
||
177 | -! | +|||
53 | +64x |
- sprintf(+ parents <- c(current, parents) |
||
178 | -! | +|||
54 | +
- "Some module names in the mapping arguments don't match module labels.\n %s not in %s",+ } |
|||
179 | -! | +|||
55 | +62x |
- toString(failed_mod_names),+ ordered_datanames <- c(parents, ordered_datanames) |
||
180 | -! | +|||
56 | +
- toString(unique(module_names))+ } |
|||
181 | +57 |
- )+ |
||
182 | -+ | |||
58 | +32x |
- )+ unique(ordered_datanames) |
||
183 | +59 |
- }+ } |
||
184 | +60 | |||
185 | -! | +|||
61 | +
- if (anyDuplicated(module_names)) {+ #' Create a `FilteredData` |
|||
186 | +62 |
- # In teal we are able to set nested modules with duplicated label.+ #' |
||
187 | +63 |
- # Because mapping argument bases on the relationship between module-label and filter-id,+ #' Create a `FilteredData` object from a `teal_data` object. |
||
188 | +64 |
- # it is possible that module-label in mapping might refer to multiple teal_module (identified by the same label)+ #' |
||
189 | -! | +|||
65 | +
- stop(+ #' @param x (`teal_data`) object |
|||
190 | -! | +|||
66 | +
- sprintf(+ #' @param datanames (`character`) vector of data set names to include; must be subset of `names(x)` |
|||
191 | -! | +|||
67 | +
- "Module labels should be unique when teal_slices(mapping = TRUE). Duplicated labels:\n%s ",+ #' @return A `FilteredData` object. |
|||
192 | -! | +|||
68 | +
- toString(module_names[duplicated(module_names)])+ #' @keywords internal |
|||
193 | +69 |
- )+ teal_data_to_filtered_data <- function(x, datanames = names(x)) { |
||
194 | -+ | |||
70 | +83x |
- )+ checkmate::assert_class(x, "teal_data") |
||
195 | -+ | |||
71 | +83x |
- }+ checkmate::assert_character(datanames, min.chars = 1L, any.missing = FALSE) |
||
196 | +72 |
- }+ # Otherwise, FilteredData will be created in the modules' scope later+ |
+ ||
73 | +83x | +
+ teal.slice::init_filtered_data(+ |
+ ||
74 | +83x | +
+ x = Filter(length, sapply(datanames, function(dn) x[[dn]], simplify = FALSE)),+ |
+ ||
75 | +83x | +
+ join_keys = teal.data::join_keys(x) |
||
197 | +76 |
-
+ ) |
||
198 | +77 |
- ## `data` - `modules`+ } |
||
199 | -13x | +|||
78 | +
- if (inherits(data, "teal_data")) {+ |
|||
200 | -12x | +|||
79 | +
- if (length(data) == 0) {+ |
|||
201 | -1x | +|||
80 | +
- stop("The environment of `data` is empty.")+ #' Template function for `TealReportCard` creation and customization |
|||
202 | +81 |
- }+ #' |
||
203 | +82 |
-
+ #' This function generates a report card with a title, |
||
204 | -11x | +|||
83 | +
- is_modules_ok <- check_modules_datanames(modules, names(data))+ #' an optional description, and the option to append the filter state list. |
|||
205 | -11x | +|||
84 | +
- if (!isTRUE(is_modules_ok) && length(unlist(extract_transformators(modules))) == 0) {+ #' |
|||
206 | -4x | +|||
85 | +
- warning(is_modules_ok, call. = FALSE)+ #' @param title (`character(1)`) title of the card (unless overwritten by label) |
|||
207 | +86 |
- }+ #' @param label (`character(1)`) label provided by the user when adding the card |
||
208 | +87 |
-
+ #' @param description (`character(1)`) optional, additional description |
||
209 | -11x | +|||
88 | +
- is_filter_ok <- check_filter_datanames(filter, names(data))+ #' @param with_filter (`logical(1)`) flag indicating to add filter state |
|||
210 | -11x | +|||
89 | +
- if (!isTRUE(is_filter_ok)) {+ #' @param filter_panel_api (`FilterPanelAPI`) object with API that allows the generation |
|||
211 | -1x | +|||
90 | +
- warning(is_filter_ok)+ #' of the filter state in the report |
|||
212 | +91 |
- # we allow app to continue if applied filters are outside+ #' |
||
213 | +92 |
- # of possible data range+ #' @return (`TealReportCard`) populated with a title, description and filter state. |
||
214 | +93 |
- }+ #' |
||
215 | +94 |
- }+ #' @export |
||
216 | +95 |
-
+ report_card_template <- function(title, label, description = NULL, with_filter, filter_panel_api) { |
||
217 | -12x | +96 | +2x |
- reporter <- teal.reporter::Reporter$new()$set_id(attr(filter, "app_id"))+ checkmate::assert_string(title) |
218 | -12x | +97 | +2x |
- if (is_arg_used(modules, "reporter") && length(extract_module(modules, "teal_module_previewer")) == 0) {+ checkmate::assert_string(label) |
219 | -! | +|||
98 | +2x |
- modules <- append_module(+ checkmate::assert_string(description, null.ok = TRUE) |
||
220 | -! | +|||
99 | +2x |
- modules,+ checkmate::assert_flag(with_filter) |
||
221 | -! | +|||
100 | +2x |
- reporter_previewer_module(server_args = list(previewer_buttons = c("download", "reset")))+ checkmate::assert_class(filter_panel_api, classes = "FilterPanelAPI") |
||
222 | +101 |
- )+ |
||
223 | -+ | |||
102 | +2x |
- }+ card <- teal::TealReportCard$new() |
||
224 | -+ | |||
103 | +2x |
-
+ title <- if (label == "") title else label |
||
225 | -12x | +104 | +2x |
- ns <- NS(id)+ card$set_name(title) |
226 | -+ | |||
105 | +2x |
- # Note: UI must be a function to support bookmarking.+ card$append_text(title, "header2") |
||
227 | -12x | +106 | +1x |
- res <- list(+ if (!is.null(description)) card$append_text(description, "header3") |
228 | -12x | +107 | +1x |
- ui = function(request) {+ if (with_filter) card$append_fs(filter_panel_api$get_filter_state()) |
229 | -! | +|||
108 | +2x |
- ui_teal(+ card |
||
230 | -! | +|||
109 | +
- id = ns("teal"),+ } |
|||
231 | -! | +|||
110 | +
- modules = modules,+ |
|||
232 | -! | +|||
111 | +
- title = title,+ |
|||
233 | -! | +|||
112 | +
- header = header,+ #' Check `datanames` in modules |
|||
234 | -! | +|||
113 | +
- footer = footer+ #' |
|||
235 | +114 |
- )+ #' These functions check if specified `datanames` in modules match those in the data object, |
||
236 | +115 |
- },+ #' returning error messages or `TRUE` for successful validation. Two functions return error message |
||
237 | -12x | +|||
116 | +
- server = function(input, output, session) {+ #' in different forms: |
|||
238 | -! | +|||
117 | +
- if (!is.null(landing_popup)) {+ #' - `check_modules_datanames` returns `character(1)` for basic assertion usage |
|||
239 | -! | +|||
118 | +
- do.call(landing_popup$server, c(list(id = "landing_module_shiny_id"), landing_popup$server_args))+ #' - `check_modules_datanames_html` returns `shiny.tag.list` to display it in the app. |
|||
240 | +119 |
- }+ #' |
||
241 | -! | +|||
120 | +
- srv_teal(id = ns("teal"), data = data, modules = modules, filter = deep_copy_filter(filter))+ #' @param modules (`teal_modules`) object |
|||
242 | +121 |
- }+ #' @param datanames (`character`) names of datasets available in the `data` object |
||
243 | +122 |
- )+ #' |
||
244 | +123 |
-
+ #' @return `TRUE` if validation passes, otherwise `character(1)` or `shiny.tag.list` |
||
245 | -12x | +|||
124 | +
- logger::log_debug("init teal app has been initialized.")+ #' @keywords internal |
|||
246 | +125 |
-
+ check_modules_datanames <- function(modules, datanames) { |
||
247 | -12x | +126 | +11x |
- res+ out <- check_modules_datanames_html(modules, datanames) |
248 | -+ | |||
127 | +11x |
- }+ if (inherits(out, "shiny.tag.list")) { |
1 | -+ | |||
128 | +5x |
- setOldClass("teal_module")+ out_with_ticks <- gsub("<code>|</code>", "`", toString(out)) |
||
2 | -+ | |||
129 | +5x |
- setOldClass("teal_modules")+ out_text <- gsub("<[^<>]+>", "", toString(out_with_ticks)) |
||
3 | -+ | |||
130 | +5x |
-
+ trimws(gsub("[[:space:]]+", " ", out_text)) |
||
4 | +131 |
- #' Create `teal_module` and `teal_modules` objects+ } else { |
||
5 | -+ | |||
132 | +6x |
- #'+ out |
||
6 | +133 |
- #' @description+ } |
||
7 | +134 |
- #' `r lifecycle::badge("stable")`+ } |
||
8 | +135 |
- #' Create a nested tab structure to embed modules in a `teal` application.+ |
||
9 | +136 |
- #'+ #' @rdname check_modules_datanames |
||
10 | +137 |
- #' @details+ check_reserved_datanames <- function(datanames) { |
||
11 | -+ | |||
138 | +190x |
- #' `module()` creates an instance of a `teal_module` that can be placed in a `teal` application.+ reserved_datanames <- datanames[datanames %in% c("all", ".raw_data")] |
||
12 | -+ | |||
139 | +190x |
- #' `modules()` shapes the structure of a the application by organizing `teal_module` within the navigation panel.+ if (length(reserved_datanames) == 0L) { |
||
13 | -+ | |||
140 | +184x |
- #' It wraps `teal_module` and `teal_modules` objects in a `teal_modules` object,+ return(NULL) |
||
14 | +141 |
- #' which results in a nested structure corresponding to the nested tabs in the final application.+ } |
||
15 | +142 |
- #'+ |
||
16 | -+ | |||
143 | +6x |
- #' Note that for `modules()` `label` comes after `...`, so it must be passed as a named argument,+ tags$span( |
||
17 | -+ | |||
144 | +6x |
- #' otherwise it will be captured by `...`.+ to_html_code_list(reserved_datanames), |
||
18 | -+ | |||
145 | +6x |
- #'+ sprintf( |
||
19 | -+ | |||
146 | +6x |
- #' The labels `"global_filters"` and `"Report previewer"` are reserved+ "%s reserved for internal use. Please avoid using %s as %s.", |
||
20 | -+ | |||
147 | +6x |
- #' because they are used by the `mapping` argument of [teal_slices()]+ pluralize(reserved_datanames, "is", "are"), |
||
21 | -+ | |||
148 | +6x |
- #' and the report previewer module [reporter_previewer_module()], respectively.+ pluralize(reserved_datanames, "it", "them"), |
||
22 | -+ | |||
149 | +6x |
- #'+ pluralize(reserved_datanames, "a dataset name", "dataset names") |
||
23 | +150 |
- #' # Restricting datasets used by `teal_module`:+ ) |
||
24 | +151 |
- #' The `datanames` argument controls which datasets are used by the module’s server. These datasets,+ ) |
||
25 | +152 |
- #' passed via server's `data` argument, are the only ones shown in the module's tab.+ } |
||
26 | +153 |
- #'+ |
||
27 | +154 |
- #' When `datanames` is set to `"all"`, all datasets in the data object are treated as relevant.+ #' @rdname check_modules_datanames |
||
28 | +155 |
- #' However, this may include unnecessary datasets, such as:+ check_modules_datanames_html <- function(modules, datanames) { |
||
29 | -+ | |||
156 | +190x |
- #' - Proxy variables for column modifications+ check_datanames <- check_modules_datanames_recursive(modules, datanames) |
||
30 | -+ | |||
157 | +190x |
- #' - Temporary datasets used to create final versions+ show_module_info <- inherits(modules, "teal_modules") # used in two contexts - module and app |
||
31 | +158 |
- #' - Connection objects+ |
||
32 | -+ | |||
159 | +190x |
- #'+ reserved_datanames <- check_reserved_datanames(datanames) |
||
33 | +160 |
- #' To exclude irrelevant datasets, use the [set_datanames()] function to change `datanames` from+ |
||
34 | -+ | |||
161 | +190x |
- #' `"all"` to specific names. Trying to modify non-`"all"` values with [set_datanames()] will result+ if (!length(check_datanames)) { |
||
35 | -+ | |||
162 | +172x |
- #' in a warning. Datasets with names starting with . are ignored globally unless explicitly listed+ out <- if (is.null(reserved_datanames)) { |
||
36 | -+ | |||
163 | +166x |
- #' in `datanames`.+ TRUE |
||
37 | +164 |
- #'+ } else { |
||
38 | -+ | |||
165 | +6x |
- #' # `datanames` with `transformators`+ shiny::tagList(reserved_datanames) |
||
39 | +166 |
- #' When transformators are specified, their `datanames` are added to the module’s `datanames`, which+ } |
||
40 | -+ | |||
167 | +172x |
- #' changes the behavior as follows:+ return(out) |
||
41 | +168 |
- #' - If `module(datanames)` is `NULL` and the `transformators` have defined `datanames`, the sidebar+ } |
||
42 | -+ | |||
169 | +18x |
- #' will appear showing the `transformators`' datasets, instead of being hidden.+ shiny::tagList( |
||
43 | -+ | |||
170 | +18x |
- #' - If `module(datanames)` is set to specific values and any `transformator` has `datanames = "all"`,+ reserved_datanames, |
||
44 | -+ | |||
171 | +18x |
- #' the module may receive extra datasets that could be unnecessary+ lapply( |
||
45 | -+ | |||
172 | +18x |
- #'+ check_datanames, |
||
46 | -+ | |||
173 | +18x |
- #' @param label (`character(1)`) Label shown in the navigation item for the module or module group.+ function(mod) { |
||
47 | -+ | |||
174 | +18x |
- #' For `modules()` defaults to `"root"`. See `Details`.+ tagList( |
||
48 | -+ | |||
175 | +18x | +
+ tags$span(+ |
+ ||
176 | +18x | +
+ tags$span(pluralize(mod$missing_datanames, "Dataset")),+ |
+ ||
177 | +18x |
- #' @param server (`function`) `shiny` module with following arguments:+ to_html_code_list(mod$missing_datanames), |
||
49 | -+ | |||
178 | +18x |
- #' - `id` - `teal` will set proper `shiny` namespace for this module (see [shiny::moduleServer()]).+ tags$span( |
||
50 | -+ | |||
179 | +18x |
- #' - `input`, `output`, `session` - (optional; not recommended) When provided, then [shiny::callModule()]+ sprintf( |
||
51 | -+ | |||
180 | +18x |
- #' will be used to call a module. From `shiny` 1.5.0, the recommended way is to use+ "%s missing%s.", |
||
52 | -+ | |||
181 | +18x |
- #' [shiny::moduleServer()] instead which doesn't require these arguments.+ pluralize(mod$missing_datanames, "is", "are"), |
||
53 | -+ | |||
182 | +18x |
- #' - `data` (optional) When provided, the module will be called with `teal_data` object (i.e. a list of+ if (show_module_info) sprintf(" for module '%s'", mod$label) else "" |
||
54 | +183 |
- #' reactive (filtered) data specified in the `filters` argument) as the value of this argument.+ ) |
||
55 | +184 |
- #' - `datasets` (optional) When provided, the module will be called with `FilteredData` object as the+ ) |
||
56 | +185 |
- #' value of this argument. (See [`teal.slice::FilteredData`]).+ ), |
||
57 | -+ | |||
186 | +18x |
- #' - `reporter` (optional) When provided, the module will be called with `Reporter` object as the value+ if (length(datanames) >= 1) { |
||
58 | -+ | |||
187 | +16x |
- #' of this argument. (See [`teal.reporter::Reporter`]).+ tagList( |
||
59 | -+ | |||
188 | +16x |
- #' - `filter_panel_api` (optional) When provided, the module will be called with `FilterPanelAPI` object+ tags$span(pluralize(datanames, "Dataset")), |
||
60 | -+ | |||
189 | +16x |
- #' as the value of this argument. (See [`teal.slice::FilterPanelAPI`]).+ tags$span("available in data:"), |
||
61 | -+ | |||
190 | +16x |
- #' - `...` (optional) When provided, `server_args` elements will be passed to the module named argument+ tagList( |
||
62 | -+ | |||
191 | +16x |
- #' or to the `...`.+ tags$span( |
||
63 | -+ | |||
192 | +16x |
- #' @param ui (`function`) `shiny` UI module function with following arguments:+ to_html_code_list(datanames), |
||
64 | -+ | |||
193 | +16x |
- #' - `id` - `teal` will set proper `shiny` namespace for this module.+ tags$span(".", .noWS = "outside"), |
||
65 | -+ | |||
194 | +16x |
- #' - `...` (optional) When provided, `ui_args` elements will be passed to the module named argument+ .noWS = c("outside") |
||
66 | +195 |
- #' or to the `...`.+ ) |
||
67 | +196 |
- #' @param filters (`character`) Deprecated. Use `datanames` instead.+ ) |
||
68 | +197 |
- #' @param datanames (`character`) Names of the datasets relevant to the item.+ ) |
||
69 | +198 |
- #' There are 2 reserved values that have specific behaviors:+ } else { |
||
70 | -+ | |||
199 | +2x |
- #' - The keyword `"all"` includes all datasets available in the data passed to the teal application.+ tags$span("No datasets are available in data.") |
||
71 | +200 |
- #' - `NULL` hides the sidebar panel completely.+ }, |
||
72 | -+ | |||
201 | +18x |
- #' - If `transformators` are specified, their `datanames` are automatically added to this `datanames`+ tags$br(.noWS = "before") |
||
73 | +202 |
- #' argument.+ ) |
||
74 | +203 |
- #' @param server_args (named `list`) with additional arguments passed on to the server function.+ } |
||
75 | +204 |
- #' @param ui_args (named `list`) with additional arguments passed on to the UI function.+ ) |
||
76 | +205 |
- #' @param x (`teal_module` or `teal_modules`) Object to format/print.+ ) |
||
77 | +206 |
- #' @param transformators (`list` of `teal_transform_module`) that will be applied to transformator module's data input.+ } |
||
78 | +207 |
- #'+ |
||
79 | +208 |
- #'+ #' Recursively checks modules and returns list for every datanames mismatch between module and data |
||
80 | +209 |
- #' @param ...+ #' @noRd |
||
81 | +210 |
- #' - For `modules()`: (`teal_module` or `teal_modules`) Objects to wrap into a tab.+ check_modules_datanames_recursive <- function(modules, datanames) { # nolint: object_name_length |
||
82 | -+ | |||
211 | +296x |
- #' - For `format()` and `print()`: Arguments passed to other methods.+ checkmate::assert_multi_class(modules, c("teal_module", "teal_modules")) |
||
83 | -+ | |||
212 | +296x |
- #'+ checkmate::assert_character(datanames) |
||
84 | -+ | |||
213 | +296x |
- #' @return+ if (inherits(modules, "teal_modules")) { |
||
85 | -+ | |||
214 | +86x |
- #' `module()` returns an object of class `teal_module`.+ unlist( |
||
86 | -+ | |||
215 | +86x |
- #'+ lapply(modules$children, check_modules_datanames_recursive, datanames = datanames), |
||
87 | -+ | |||
216 | +86x |
- #' `modules()` returns a `teal_modules` object which contains following fields:+ recursive = FALSE |
||
88 | +217 |
- #' - `label`: taken from the `label` argument.+ ) |
||
89 | +218 |
- #' - `children`: a list containing objects passed in `...`. List elements are named after+ } else { |
||
90 | -+ | |||
219 | +210x |
- #' their `label` attribute converted to a valid `shiny` id.+ missing_datanames <- setdiff(modules$datanames, c("all", datanames)) |
||
91 | -+ | |||
220 | +210x |
- #'+ if (length(missing_datanames)) { |
||
92 | -+ | |||
221 | +18x |
- #' @name teal_modules+ list(list( |
||
93 | -+ | |||
222 | +18x |
- #' @aliases teal_module+ label = modules$label, |
||
94 | -+ | |||
223 | +18x |
- #'+ missing_datanames = missing_datanames |
||
95 | +224 |
- #' @examples+ )) |
||
96 | +225 |
- #' library(shiny)+ } |
||
97 | +226 |
- #'+ } |
||
98 | +227 |
- #' module_1 <- module(+ } |
||
99 | +228 |
- #' label = "a module",+ |
||
100 | +229 |
- #' server = function(id, data) {+ #' Convert character vector to html code separated with commas and "and" |
||
101 | +230 |
- #' moduleServer(+ #' @noRd |
||
102 | +231 |
- #' id,+ to_html_code_list <- function(x) { |
||
103 | -+ | |||
232 | +40x |
- #' module = function(input, output, session) {+ checkmate::assert_character(x) |
||
104 | -+ | |||
233 | +40x |
- #' output$data <- renderDataTable(data()[["iris"]])+ do.call( |
||
105 | -+ | |||
234 | +40x |
- #' }+ tagList, |
||
106 | -+ | |||
235 | +40x |
- #' )+ lapply(seq_along(x), function(.ix) { |
||
107 | -+ | |||
236 | +56x |
- #' },+ tagList( |
||
108 | -+ | |||
237 | +56x |
- #' ui = function(id) {+ tags$code(x[.ix]), |
||
109 | -+ | |||
238 | +56x |
- #' ns <- NS(id)+ if (.ix != length(x)) { |
||
110 | -+ | |||
239 | +1x |
- #' tagList(dataTableOutput(ns("data")))+ if (.ix == length(x) - 1) tags$span(" and ") else tags$span(", ", .noWS = "before") |
||
111 | +240 |
- #' },+ } |
||
112 | +241 |
- #' datanames = "all"+ ) |
||
113 | +242 |
- #' )+ }) |
||
114 | +243 |
- #'+ ) |
||
115 | +244 |
- #' module_2 <- module(+ } |
||
116 | +245 |
- #' label = "another module",+ |
||
117 | +246 |
- #' server = function(id) {+ |
||
118 | +247 |
- #' moduleServer(+ #' Check `datanames` in filters |
||
119 | +248 |
- #' id,+ #' |
||
120 | +249 |
- #' module = function(input, output, session) {+ #' This function checks whether `datanames` in filters correspond to those in `data`, |
||
121 | +250 |
- #' output$text <- renderText("Another Module")+ #' returning character vector with error messages or `TRUE` if all checks pass. |
||
122 | +251 |
- #' }+ #' |
||
123 | +252 |
- #' )+ #' @param filters (`teal_slices`) object |
||
124 | +253 |
- #' },+ #' @param datanames (`character`) names of datasets available in the `data` object |
||
125 | +254 |
- #' ui = function(id) {+ #' |
||
126 | +255 |
- #' ns <- NS(id)+ #' @return A `character(1)` containing error message or TRUE if validation passes. |
||
127 | +256 |
- #' tagList(textOutput(ns("text")))+ #' @keywords internal |
||
128 | +257 |
- #' },+ check_filter_datanames <- function(filters, datanames) { |
||
129 | -+ | |||
258 | +86x |
- #' datanames = NULL+ checkmate::assert_class(filters, "teal_slices") |
||
130 | -+ | |||
259 | +86x |
- #' )+ checkmate::assert_character(datanames) |
||
131 | +260 |
- #'+ |
||
132 | +261 |
- #' modules <- modules(+ # check teal_slices against datanames |
||
133 | -+ | |||
262 | +86x |
- #' label = "modules",+ out <- unlist(sapply( |
||
134 | -+ | |||
263 | +86x |
- #' modules(+ filters, function(filter) { |
||
135 | -+ | |||
264 | +24x |
- #' label = "nested modules",+ dataname <- shiny::isolate(filter$dataname) |
||
136 | -+ | |||
265 | +24x |
- #' module_1+ if (!dataname %in% datanames) { |
||
137 | -+ | |||
266 | +3x |
- #' ),+ sprintf( |
||
138 | -+ | |||
267 | +3x |
- #' module_2+ "- Filter '%s' refers to dataname not available in 'data':\n %s not in (%s)", |
||
139 | -+ | |||
268 | +3x |
- #' )+ shiny::isolate(filter$id), |
||
140 | -+ | |||
269 | +3x |
- #'+ dQuote(dataname, q = FALSE), |
||
141 | -+ | |||
270 | +3x |
- #' app <- init(+ toString(dQuote(datanames, q = FALSE)) |
||
142 | +271 |
- #' data = teal_data(iris = iris),+ ) |
||
143 | +272 |
- #' modules = modules+ } |
||
144 | +273 |
- #' )+ } |
||
145 | +274 |
- #'+ )) |
||
146 | +275 |
- #' if (interactive()) {+ |
||
147 | +276 |
- #' shinyApp(app$ui, app$server)+ |
||
148 | -+ | |||
277 | +86x |
- #' }+ if (length(out)) { |
||
149 | -+ | |||
278 | +3x |
- #' @rdname teal_modules+ paste(out, collapse = "\n") |
||
150 | +279 |
- #' @export+ } else { |
||
151 | -+ | |||
280 | +83x |
- #'+ TRUE |
||
152 | +281 |
- module <- function(label = "module",+ } |
||
153 | +282 |
- server = function(id, data, ...) moduleServer(id, function(input, output, session) NULL),+ } |
||
154 | +283 |
- ui = function(id, ...) tags$p(paste0("This module has no UI (id: ", id, " )")),+ |
||
155 | +284 |
- filters,+ #' Function for validating the title parameter of `teal::init` |
||
156 | +285 |
- datanames = "all",+ #' |
||
157 | +286 |
- server_args = NULL,+ #' Checks if the input of the title from `teal::init` will create a valid title and favicon tag. |
||
158 | +287 |
- ui_args = NULL,+ #' @param shiny_tag (`shiny.tag`) Object to validate for a valid title. |
||
159 | +288 |
- transformators = list()) {+ #' @keywords internal |
||
160 | +289 |
- # argument checking (independent)+ validate_app_title_tag <- function(shiny_tag) { |
||
161 | -+ | |||
290 | +7x |
- ## `label`+ checkmate::assert_class(shiny_tag, "shiny.tag") |
||
162 | -220x | +291 | +7x |
- checkmate::assert_string(label)+ checkmate::assert_true(shiny_tag$name == "head") |
163 | -217x | +292 | +6x |
- if (label == "global_filters") {+ child_names <- vapply(shiny_tag$children, `[[`, character(1L), "name") |
164 | -1x | +293 | +6x |
- stop(+ checkmate::assert_subset(c("title", "link"), child_names, .var.name = "child tags") |
165 | -1x | +294 | +4x |
- sprintf("module(label = \"%s\", ...\n ", label),+ rel_attr <- shiny_tag$children[[which(child_names == "link")]]$attribs$rel |
166 | -1x | +295 | +4x |
- "Label 'global_filters' is reserved in teal. Please change to something else.",+ checkmate::assert_subset( |
167 | -1x | +296 | +4x |
- call. = FALSE+ rel_attr, |
168 | -+ | |||
297 | +4x |
- )+ c("icon", "shortcut icon"), |
||
169 | -+ | |||
298 | +4x |
- }+ .var.name = "Link tag's rel attribute", |
||
170 | -216x | +299 | +4x |
- if (label == "Report previewer") {+ empty.ok = FALSE |
171 | -! | +|||
300 | +
- stop(+ ) |
|||
172 | -! | +|||
301 | +
- sprintf("module(label = \"%s\", ...\n ", label),+ } |
|||
173 | -! | +|||
302 | +
- "Label 'Report previewer' is reserved in teal. Please change to something else.",+ |
|||
174 | -! | +|||
303 | +
- call. = FALSE+ #' Build app title with favicon |
|||
175 | +304 |
- )+ #' |
||
176 | +305 |
- }+ #' A helper function to create the browser title along with a logo. |
||
177 | +306 |
-
+ #' |
||
178 | +307 |
- ## server+ #' @param title (`character`) The browser title for the `teal` app. |
||
179 | -216x | +|||
308 | +
- checkmate::assert_function(server)+ #' @param favicon (`character`) The path for the icon for the title. |
|||
180 | -216x | +|||
309 | +
- server_formals <- names(formals(server))+ #' The image/icon path can be remote or the static path accessible by `shiny`, like the `www/` |
|||
181 | -216x | +|||
310 | +
- if (!(+ #' |
|||
182 | -216x | +|||
311 | +
- "id" %in% server_formals ||+ #' @return A `shiny.tag` containing the element that adds the title and logo to the `shiny` app. |
|||
183 | -216x | +|||
312 | +
- all(c("input", "output", "session") %in% server_formals)+ #' @export |
|||
184 | +313 |
- )) {+ build_app_title <- function( |
||
185 | -2x | +|||
314 | +
- stop(+ title = "teal app", |
|||
186 | -2x | +|||
315 | +
- "\nmodule() `server` argument requires a function with following arguments:",+ favicon = "https://raw.githubusercontent.com/insightsengineering/hex-stickers/main/PNG/nest.png") { |
|||
187 | -2x | +316 | +15x |
- "\n - id - `teal` will set proper `shiny` namespace for this module.",+ checkmate::assert_string(title, null.ok = TRUE) |
188 | -2x | +317 | +15x |
- "\n - input, output, session (not recommended) - then `shiny::callModule` will be used to call a module.",+ checkmate::assert_string(favicon, null.ok = TRUE) |
189 | -2x | +318 | +15x |
- "\n\nFollowing arguments can be used optionaly:",+ tags$head( |
190 | -2x | +319 | +15x |
- "\n - `data` - module will receive list of reactive (filtered) data specified in the `filters` argument",+ tags$title(title), |
191 | -2x | +320 | +15x |
- "\n - `datasets` - module will receive `FilteredData`. See `help(teal.slice::FilteredData)`",+ tags$link( |
192 | -2x | +321 | +15x |
- "\n - `reporter` - module will receive `Reporter`. See `help(teal.reporter::Reporter)`",+ rel = "icon", |
193 | -2x | +322 | +15x |
- "\n - `filter_panel_api` - module will receive `FilterPanelAPI`. (See [teal.slice::FilterPanelAPI]).",+ href = favicon, |
194 | -2x | +323 | +15x |
- "\n - `...` server_args elements will be passed to the module named argument or to the `...`"+ sizes = "any" |
195 | +324 |
) |
||
196 | +325 |
- }+ ) |
||
197 | +326 | - - | -||
198 | -214x | -
- if ("datasets" %in% server_formals) {- |
- ||
199 | -2x | -
- warning(- |
- ||
200 | -2x | -
- sprintf("Called from module(label = \"%s\", ...)\n ", label),- |
- ||
201 | -2x | -
- "`datasets` argument in the server is deprecated and will be removed in the next release. ",+ } |
||
202 | -2x | +|||
327 | +
- "Please use `data` instead.",+ |
|||
203 | -2x | +|||
328 | +
- call. = FALSE+ #' Application ID |
|||
204 | +329 |
- )+ #' |
||
205 | +330 |
- }+ #' Creates App ID used to match filter snapshots to application. |
||
206 | +331 |
-
+ #' |
||
207 | +332 |
- ## UI+ #' Calculate app ID that will be used to stamp filter state snapshots. |
||
208 | -214x | +|||
333 | +
- checkmate::assert_function(ui)+ #' App ID is a hash of the app's data and modules. |
|||
209 | -214x | +|||
334 | +
- ui_formals <- names(formals(ui))+ #' See "transferring snapshots" section in ?snapshot. |
|||
210 | -214x | +|||
335 | +
- if (!"id" %in% ui_formals) {+ #' |
|||
211 | -1x | +|||
336 | +
- stop(+ #' @param data (`teal_data` or `teal_data_module`) as accepted by `init` |
|||
212 | -1x | +|||
337 | +
- "\nmodule() `ui` argument requires a function with following arguments:",+ #' @param modules (`teal_modules`) object as accepted by `init` |
|||
213 | -1x | +|||
338 | +
- "\n - id - `teal` will set proper `shiny` namespace for this module.",+ #' |
|||
214 | -1x | +|||
339 | +
- "\n\nFollowing arguments can be used optionally:",+ #' @return A single character string. |
|||
215 | -1x | +|||
340 | +
- "\n - `...` ui_args elements will be passed to the module argument of the same name or to the `...`"+ #' |
|||
216 | +341 |
- )+ #' @keywords internal |
||
217 | +342 |
- }+ create_app_id <- function(data, modules) { |
||
218 | -+ | |||
343 | +23x |
-
+ checkmate::assert_multi_class(data, c("teal_data", "teal_data_module")) |
||
219 | -213x | +344 | +22x |
- if (any(c("data", "datasets") %in% ui_formals)) {+ checkmate::assert_class(modules, "teal_modules") |
220 | -2x | +|||
345 | +
- stop(+ |
|||
221 | -2x | +346 | +21x |
- sprintf("Called from module(label = \"%s\", ...)\n ", label),+ data <- if (inherits(data, "teal_data")) { |
222 | -2x | +347 | +19x |
- "UI with `data` or `datasets` argument is no longer accepted.\n ",+ as.list(data) |
223 | -2x | +348 | +21x |
- "If some UI inputs depend on data, please move the logic to your server instead.\n ",+ } else if (inherits(data, "teal_data_module")) { |
224 | +349 | 2x |
- "Possible solutions are renderUI() or updateXyzInput() functions."- |
- |
225 | -- |
- )+ deparse1(body(data$server)) |
||
226 | +350 |
} |
||
227 | -+ | |||
351 | +21x |
-
+ modules <- lapply(modules, defunction) |
||
228 | +352 |
- ## `filters`+ |
||
229 | -211x | -
- if (!missing(filters)) {- |
- ||
230 | -! | +353 | +21x |
- datanames <- filters+ rlang::hash(list(data = data, modules = modules)) |
231 | -! | +|||
354 | +
- msg <-+ } |
|||
232 | -! | +|||
355 | +
- "The `filters` argument is deprecated and will be removed in the next release. Please use `datanames` instead."+ |
|||
233 | -! | +|||
356 | +
- warning(msg)+ #' Go through list and extract bodies of encountered functions as string, recursively. |
|||
234 | +357 |
- }+ #' @keywords internal |
||
235 | +358 |
-
+ #' @noRd |
||
236 | +359 |
- ## `datanames` (also including deprecated `filters`)+ defunction <- function(x) { |
||
237 | -+ | |||
360 | +297x |
- # please note a race condition between datanames set when filters is not missing and data arg in server function+ if (is.list(x)) { |
||
238 | -211x | +361 | +121x |
- if (!is.element("data", server_formals) && !is.null(datanames)) {+ lapply(x, defunction) |
239 | -12x | +362 | +176x |
- message(sprintf("module \"%s\" server function takes no data so \"datanames\" will be ignored", label))+ } else if (is.function(x)) { |
240 | -12x | +363 | +54x |
- datanames <- NULL+ deparse1(body(x)) |
241 | +364 |
- }+ } else { |
||
242 | -211x | +365 | +122x |
- checkmate::assert_character(datanames, min.len = 1, null.ok = TRUE, any.missing = FALSE)+ x |
243 | +366 |
-
+ } |
||
244 | +367 |
- ## `server_args`- |
- ||
245 | -210x | -
- checkmate::assert_list(server_args, null.ok = TRUE, names = "named")- |
- ||
246 | -208x | -
- srv_extra_args <- setdiff(names(server_args), server_formals)- |
- ||
247 | -208x | -
- if (length(srv_extra_args) > 0 && !"..." %in% server_formals) {+ } |
||
248 | -1x | +|||
368 | +
- stop(+ |
|||
249 | -1x | +|||
369 | +
- "\nFollowing `server_args` elements have no equivalent in the formals of the server:\n",+ #' Get unique labels |
|||
250 | -1x | +|||
370 | +
- paste(paste(" -", srv_extra_args), collapse = "\n"),+ #' |
|||
251 | -1x | +|||
371 | +
- "\n\nUpdate the server arguments by including above or add `...`"+ #' Get unique labels for the modules to avoid namespace conflicts. |
|||
252 | +372 |
- )+ #' |
||
253 | +373 |
- }+ #' @param labels (`character`) vector of labels |
||
254 | +374 |
-
+ #' |
||
255 | +375 |
- ## `ui_args`+ #' @return (`character`) vector of unique labels |
||
256 | -207x | +|||
376 | +
- checkmate::assert_list(ui_args, null.ok = TRUE, names = "named")+ #' |
|||
257 | -205x | +|||
377 | +
- ui_extra_args <- setdiff(names(ui_args), ui_formals)+ #' @keywords internal |
|||
258 | -205x | +|||
378 | +
- if (length(ui_extra_args) > 0 && !"..." %in% ui_formals) {+ get_unique_labels <- function(labels) { |
|||
259 | -1x | +379 | +141x |
- stop(+ make.unique(gsub("[^[:alnum:]]", "_", tolower(labels)), sep = "_") |
260 | -1x | +|||
380 | +
- "\nFollowing `ui_args` elements have no equivalent in the formals of UI:\n",+ } |
|||
261 | -1x | +|||
381 | +
- paste(paste(" -", ui_extra_args), collapse = "\n"),+ |
|||
262 | -1x | +|||
382 | +
- "\n\nUpdate the UI arguments by including above or add `...`"+ #' Remove ANSI escape sequences from a string |
|||
263 | +383 |
- )+ #' @noRd |
||
264 | +384 |
- }+ strip_style <- function(string) { |
||
265 | -+ | |||
385 | +2x |
-
+ checkmate::assert_string(string) |
||
266 | +386 |
- ## `transformators`+ |
||
267 | -204x | +387 | +2x |
- if (inherits(transformators, "teal_transform_module")) {+ gsub( |
268 | -1x | +388 | +2x |
- transformators <- list(transformators)+ "(?:(?:\\x{001b}\\[)|\\x{009b})(?:(?:[0-9]{1,3})?(?:(?:;[0-9]{0,3})*)?[A-M|f-m])|\\x{001b}[A-M]", |
269 | +389 |
- }+ "", |
||
270 | -204x | +390 | +2x |
- checkmate::assert_list(transformators, types = "teal_transform_module")+ string, |
271 | -204x | +391 | +2x |
- transform_datanames <- unlist(lapply(transformators, attr, "datanames"))+ perl = TRUE, |
272 | -204x | +392 | +2x |
- combined_datanames <- if (identical(datanames, "all")) {+ useBytes = TRUE |
273 | -151x | +|||
393 | +
- "all"+ ) |
|||
274 | +394 |
- } else {+ } |
||
275 | -53x | +|||
395 | +
- union(datanames, transform_datanames)+ |
|||
276 | +396 |
- }+ #' @keywords internal |
||
277 | +397 |
-
+ #' @noRd |
||
278 | -204x | +398 | +4x |
- structure(+ pasten <- function(...) paste0(..., "\n") |
279 | -204x | +|||
399 | +
- list(+ |
|||
280 | -204x | +|||
400 | +
- label = label,+ #' Convert character list to human readable html with commas and "and" |
|||
281 | -204x | +|||
401 | +
- server = server,+ #' @noRd |
|||
282 | -204x | +|||
402 | +
- ui = ui,+ paste_datanames_character <- function(x, |
|||
283 | -204x | +|||
403 | +
- datanames = combined_datanames,+ tags = list(span = shiny::tags$span, code = shiny::tags$code), |
|||
284 | -204x | +|||
404 | +
- server_args = server_args,+ tagList = shiny::tagList) { # nolint: object_name. |
|||
285 | -204x | +|||
405 | +! |
- ui_args = ui_args,+ checkmate::assert_character(x) |
||
286 | -204x | +|||
406 | +! |
- transformators = transformators+ do.call( |
||
287 | -+ | |||
407 | +! |
- ),+ tagList, |
||
288 | -204x | +|||
408 | +! |
- class = "teal_module"+ lapply(seq_along(x), function(.ix) { |
||
289 | -+ | |||
409 | +! |
- )+ tagList( |
||
290 | -+ | |||
410 | +! |
- }+ tags$code(x[.ix]), |
||
291 | -+ | |||
411 | +! |
-
+ if (.ix != length(x)) { |
||
292 | -+ | |||
412 | +! |
- #' @rdname teal_modules+ tags$span(if (.ix == length(x) - 1) " and " else ", ") |
||
293 | +413 |
- #' @export+ } |
||
294 | +414 |
- #'+ ) |
||
295 | +415 |
- modules <- function(..., label = "root") {+ }) |
||
296 | -144x | +|||
416 | +
- checkmate::assert_string(label)+ ) |
|||
297 | -142x | +|||
417 | +
- submodules <- list(...)+ } |
|||
298 | -142x | +|||
418 | +
- if (any(vapply(submodules, is.character, FUN.VALUE = logical(1)))) {+ |
|||
299 | -2x | +|||
419 | +
- stop(+ #' Build datanames error string for error message |
|||
300 | -2x | +|||
420 | +
- "The only character argument to modules() must be 'label' and it must be named, ",+ #' |
|||
301 | -2x | +|||
421 | +
- "change modules('lab', ...) to modules(label = 'lab', ...)"+ #' tags and tagList are overwritten in arguments allowing to create strings for |
|||
302 | +422 |
- )+ #' logging purposes |
||
303 | +423 |
- }+ #' @noRd |
||
304 | +424 |
-
+ build_datanames_error_message <- function(label = NULL, |
||
305 | -140x | +|||
425 | +
- checkmate::assert_list(submodules, min.len = 1, any.missing = FALSE, types = c("teal_module", "teal_modules"))+ datanames, |
|||
306 | +426 |
- # name them so we can more easily access the children+ extra_datanames, |
||
307 | +427 |
- # beware however that the label of the submodules should not be changed as it must be kept synced+ tags = list(span = shiny::tags$span, code = shiny::tags$code), |
||
308 | -137x | +|||
428 | +
- labels <- vapply(submodules, function(submodule) submodule$label, character(1))+ tagList = shiny::tagList) { # nolint: object_name. |
|||
309 | -137x | +|||
429 | +! |
- names(submodules) <- get_unique_labels(labels)+ tags$span( |
||
310 | -137x | +|||
430 | +! |
- structure(+ tags$span(pluralize(extra_datanames, "Dataset")), |
||
311 | -137x | +|||
431 | +! |
- list(+ paste_datanames_character(extra_datanames, tags, tagList), |
||
312 | -137x | +|||
432 | +! |
- label = label,+ tags$span( |
||
313 | -137x | +|||
433 | +! |
- children = submodules+ sprintf( |
||
314 | -+ | |||
434 | +! |
- ),+ "%s missing%s", |
||
315 | -137x | +|||
435 | +! |
- class = "teal_modules"+ pluralize(extra_datanames, "is", "are"), |
||
316 | -+ | |||
436 | +! |
- )+ if (is.null(label)) "" else sprintf(" for tab '%s'", label) |
||
317 | +437 |
- }+ ) |
||
318 | +438 |
-
+ ), |
||
319 | -+ | |||
439 | +! |
- # printing methods ----+ if (length(datanames) >= 1) { |
||
320 | -+ | |||
440 | +! |
-
+ tagList( |
||
321 | -+ | |||
441 | +! |
- #' @rdname teal_modules+ tags$span(pluralize(datanames, "Dataset")), |
||
322 | -+ | |||
442 | +! |
- #' @param is_last (`logical(1)`) Whether this is the last item in its parent's children list.+ tags$span("available in data:"), |
||
323 | -+ | |||
443 | +! |
- #' Affects the tree branch character used (L- vs |-)+ tagList( |
||
324 | -+ | |||
444 | +! |
- #' @param parent_prefix (`character(1)`) The prefix inherited from parent nodes,+ tags$span( |
||
325 | -+ | |||
445 | +! |
- #' used to maintain the tree structure in nested levels+ paste_datanames_character(datanames, tags, tagList), |
||
326 | -+ | |||
446 | +! |
- #' @param is_root (`logical(1)`) Whether this is the root node of the tree. Only used in+ tags$span(".", .noWS = "outside"), |
||
327 | -+ | |||
447 | +! |
- #' format.teal_modules(). Determines whether to show "TEAL ROOT" header+ .noWS = c("outside") |
||
328 | +448 |
- #' @param what (`character`) Specifies which metadata to display.+ ) |
||
329 | +449 |
- #' Possible values: "datasets", "properties", "ui_args", "server_args", "transformators"+ ) |
||
330 | +450 |
- #' @examples+ ) |
||
331 | +451 |
- #' mod <- module(+ } else { |
||
332 | -+ | |||
452 | +! |
- #' label = "My Custom Module",+ tags$span("No datasets are available in data.") |
||
333 | +453 |
- #' server = function(id, data, ...) {},+ } |
||
334 | +454 |
- #' ui = function(id, ...) {},+ ) |
||
335 | +455 |
- #' datanames = c("ADSL", "ADTTE"),+ } |
||
336 | +456 |
- #' transformators = list(),+ |
||
337 | +457 |
- #' ui_args = list(a = 1, b = "b"),+ #' Smart `rbind` |
||
338 | +458 |
- #' server_args = list(x = 5, y = list(p = 1))+ #' |
||
339 | +459 |
- #' )+ #' Combine `data.frame` objects which have different columns |
||
340 | +460 |
- #' cat(format(mod))+ #' |
||
341 | +461 |
- #' @export+ #' @param ... (`data.frame`) |
||
342 | +462 |
- format.teal_module <- function(+ #' @keywords internal |
||
343 | +463 |
- x, is_last = FALSE, parent_prefix = "",+ .smart_rbind <- function(...) { |
||
344 | -+ | |||
464 | +89x |
- what = c("datasets", "properties", "ui_args", "server_args", "transformators"), ...) {+ dots <- list(...) |
||
345 | -3x | +465 | +89x |
- empty_text <- ""+ checkmate::assert_list(dots, "data.frame", .var.name = "...") |
346 | -3x | +466 | +89x |
- branch <- if (is_last) "L-" else "|-"+ Reduce( |
347 | -3x | +467 | +89x |
- current_prefix <- paste0(parent_prefix, branch, " ")+ x = dots, |
348 | -3x | +468 | +89x |
- content_prefix <- paste0(parent_prefix, if (is_last) " " else "| ")+ function(x, y) { |
349 | -+ | |||
469 | +72x |
-
+ all_columns <- union(colnames(x), colnames(y)) |
||
350 | -3x | +470 | +72x |
- format_list <- function(lst, empty = empty_text, label_width = 0) {+ x[setdiff(all_columns, colnames(x))] <- NA |
351 | -6x | +471 | +72x |
- if (is.null(lst) || length(lst) == 0) {+ y[setdiff(all_columns, colnames(y))] <- NA |
352 | -6x | +472 | +72x |
- empty+ rbind(x, y) |
353 | +473 |
- } else {+ } |
||
354 | -! | +|||
474 | +
- colon_space <- paste(rep(" ", label_width), collapse = "")+ ) |
|||
355 | +475 | ++ |
+ }+ |
+ |
476 | ||||
356 | -! | +|||
477 | +
- first_item <- sprintf("%s (%s)", names(lst)[1], crayon::silver(class(lst[[1]])[1]))+ #' Pluralize a word depending on the size of the input |
|||
357 | -! | +|||
478 | +
- rest_items <- if (length(lst) > 1) {+ #' |
|||
358 | -! | +|||
479 | +
- paste(+ #' @param x (`object`) to check length for plural. |
|||
359 | -! | +|||
480 | +
- vapply(+ #' @param singular (`character`) singular form of the word. |
|||
360 | -! | +|||
481 | +
- names(lst)[-1],+ #' @param plural (optional `character`) plural form of the word. If not given an "s" |
|||
361 | -! | +|||
482 | +
- function(name) {+ #' is added to the singular form. |
|||
362 | -! | +|||
483 | +
- sprintf(+ #' |
|||
363 | -! | +|||
484 | +
- "%s%s (%s)",+ #' @return A `character` that correctly represents the size of the `x` argument. |
|||
364 | -! | +|||
485 | +
- paste0(content_prefix, "| ", colon_space),+ #' @keywords internal |
|||
365 | -! | +|||
486 | +
- name,+ pluralize <- function(x, singular, plural = NULL) { |
|||
366 | -! | +|||
487 | +70x |
- crayon::silver(class(lst[[name]])[1])+ checkmate::assert_string(singular) |
||
367 | -+ | |||
488 | +70x |
- )+ checkmate::assert_string(plural, null.ok = TRUE) |
||
368 | -+ | |||
489 | +70x |
- },+ if (length(x) == 1L) { # Zero length object should use plural form. |
||
369 | -! | +|||
490 | +42x |
- character(1)+ singular |
||
370 | +491 |
- ),+ } else { |
||
371 | -! | +|||
492 | +28x |
- collapse = "\n"+ if (is.null(plural)) { |
||
372 | -+ | |||
493 | +12x |
- )+ sprintf("%ss", singular) |
||
373 | +494 |
- }+ } else { |
||
374 | -! | +|||
495 | +16x |
- if (length(lst) > 1) paste0(first_item, "\n", rest_items) else first_item+ plural |
||
375 | +496 |
} |
||
376 | +497 |
} |
||
377 | +498 | ++ |
+ }+ |
+
1 | ++ |
+ #' Data Module for teal+ |
+ ||
2 |
-
+ #' |
|||
378 | -3x | +|||
3 | +
- bookmarkable <- isTRUE(attr(x, "teal_bookmarkable"))+ #' This module manages the `data` argument for `srv_teal`. The `teal` framework uses [teal.data::teal_data()], |
|||
379 | -3x | +|||
4 | +
- reportable <- "reporter" %in% names(formals(x$server))+ #' which can be provided in various ways: |
|||
380 | +5 |
-
+ #' 1. Directly as a [teal.data::teal_data()] object. This will automatically convert it into a `reactive` `teal_data`. |
||
381 | -3x | +|||
6 | +
- transformators <- if (length(x$transformators) > 0) {+ #' 2. As a `reactive` object that returns a [teal.data::teal_data()] object. |
|||
382 | -! | +|||
7 | +
- paste(sapply(x$transformators, function(t) attr(t, "label")), collapse = ", ")+ #' |
|||
383 | +8 |
- } else {+ #' @details |
||
384 | -3x | +|||
9 | +
- empty_text+ #' ## Reactive `teal_data`: |
|||
385 | +10 |
- }+ #' |
||
386 | +11 |
-
+ #' The data in the application can be reactively updated, prompting [srv_teal()] to rebuild the |
||
387 | -3x | +|||
12 | +
- output <- pasten(current_prefix, crayon::bgWhite(x$label))+ #' content accordingly. There are two methods for creating interactive `teal_data`: |
|||
388 | +13 |
-
+ #' 1. Using a `reactive` object provided from outside the `teal` application. In this scenario, |
||
389 | -3x | +|||
14 | +
- if ("datasets" %in% what) {+ #' reactivity is controlled by an external module, and `srv_teal` responds to changes. |
|||
390 | -3x | +|||
15 | +
- output <- paste0(+ #' 2. Using [teal_data_module()], which is embedded within the `teal` application, allowing data to |
|||
391 | -3x | +|||
16 | +
- output,+ #' be resubmitted by the user as needed. |
|||
392 | -3x | +|||
17 | +
- content_prefix, "|- ", crayon::yellow("Datasets : "), paste(x$datanames, collapse = ", "), "\n"+ #' |
|||
393 | +18 |
- )+ #' Since the server of [teal_data_module()] must return a `reactive` `teal_data` object, both |
||
394 | +19 |
- }+ #' methods (1 and 2) produce the same reactive behavior within a `teal` application. The distinction |
||
395 | -3x | +|||
20 | +
- if ("properties" %in% what) {+ #' lies in data control: the first method involves external control, while the second method |
|||
396 | -3x | +|||
21 | +
- output <- paste0(+ #' involves control from a custom module within the app. |
|||
397 | -3x | +|||
22 | +
- output,+ #' |
|||
398 | -3x | +|||
23 | +
- content_prefix, "|- ", crayon::blue("Properties:"), "\n",+ #' For more details, see [`module_teal_data`]. |
|||
399 | -3x | +|||
24 | +
- content_prefix, "| |- ", crayon::cyan("Bookmarkable : "), bookmarkable, "\n",+ #' |
|||
400 | -3x | +|||
25 | +
- content_prefix, "| L- ", crayon::cyan("Reportable : "), reportable, "\n"+ #' @inheritParams init |
|||
401 | +26 |
- )+ #' |
||
402 | +27 |
- }+ #' @param data (`teal_data`, `teal_data_module`, or `reactive` returning `teal_data`) |
||
403 | -3x | +|||
28 | +
- if ("ui_args" %in% what) {+ #' The data which application will depend on. |
|||
404 | -3x | +|||
29 | +
- ui_args_formatted <- format_list(x$ui_args, label_width = 19)+ #' |
|||
405 | -3x | +|||
30 | +
- output <- paste0(+ #' @return A `reactive` object that returns: |
|||
406 | -3x | +|||
31 | +
- output,+ #' Output of the `data`. If `data` fails then returned error is handled (after [tryCatch()]) so that |
|||
407 | -3x | +|||
32 | +
- content_prefix, "|- ", crayon::green("UI Arguments : "), ui_args_formatted, "\n"+ #' rest of the application can respond to this respectively. |
|||
408 | +33 |
- )+ #' |
||
409 | +34 |
- }+ #' @rdname module_init_data |
||
410 | -3x | +|||
35 | +
- if ("server_args" %in% what) {+ #' @name module_init_data |
|||
411 | -3x | +|||
36 | +
- server_args_formatted <- format_list(x$server_args, label_width = 19)+ #' @keywords internal |
|||
412 | -3x | +|||
37 | +
- output <- paste0(+ NULL |
|||
413 | -3x | +|||
38 | +
- output,+ |
|||
414 | -3x | +|||
39 | +
- content_prefix, "|- ", crayon::green("Server Arguments : "), server_args_formatted, "\n"+ #' @rdname module_init_data |
|||
415 | +40 |
- )+ ui_init_data <- function(id) { |
||
416 | -+ | |||
41 | +9x |
- }+ ns <- shiny::NS(id) |
||
417 | -3x | +42 | +9x |
- if ("transformators" %in% what) {+ shiny::div( |
418 | -3x | +43 | +9x |
- output <- paste0(+ id = ns("content"), |
419 | -3x | +44 | +9x |
- output,+ style = "display: inline-block; width: 100%;", |
420 | -3x | +45 | +9x |
- content_prefix, "L- ", crayon::magenta("Transformators : "), transformators, "\n"+ uiOutput(ns("data")) |
421 | +46 |
- )+ ) |
||
422 | +47 |
- }+ } |
||
423 | +48 | |||
424 | -3x | +|||
49 | +
- output+ #' @rdname module_init_data |
|||
425 | +50 |
- }+ srv_init_data <- function(id, data) { |
||
426 | -+ | |||
51 | +88x |
-
+ checkmate::assert_character(id, max.len = 1, any.missing = FALSE) |
||
427 | -+ | |||
52 | +88x |
- #' @rdname teal_modules+ checkmate::assert_multi_class(data, c("teal_data", "teal_data_module", "reactive")) |
||
428 | +53 |
- #' @examples+ |
||
429 | -+ | |||
54 | +88x |
- #' custom_module <- function(+ moduleServer(id, function(input, output, session) { |
||
430 | -+ | |||
55 | +88x |
- #' label = "label", ui_args = NULL, server_args = NULL,+ logger::log_debug("srv_data initializing.") |
||
431 | -+ | |||
56 | +88x |
- #' datanames = "all", transformators = list(), bk = FALSE) {+ data_out <- if (inherits(data, "teal_data_module")) { |
||
432 | -+ | |||
57 | +10x |
- #' ans <- module(+ output$data <- renderUI(data$ui(id = session$ns("teal_data_module"))) |
||
433 | -+ | |||
58 | +10x |
- #' label,+ data$server("teal_data_module") |
||
434 | -+ | |||
59 | +88x |
- #' server = function(id, data, ...) {},+ } else if (inherits(data, "teal_data")) { |
||
435 | -+ | |||
60 | +48x |
- #' ui = function(id, ...) {+ reactiveVal(data) |
||
436 | -+ | |||
61 | +88x |
- #' },+ } else if (test_reactive(data)) { |
||
437 | -+ | |||
62 | +30x |
- #' datanames = datanames,+ data |
||
438 | +63 |
- #' transformators = transformators,+ } |
||
439 | +64 |
- #' ui_args = ui_args,+ |
||
440 | -+ | |||
65 | +87x |
- #' server_args = server_args+ data_handled <- reactive({ |
||
441 | -+ | |||
66 | +80x |
- #' )+ tryCatch(data_out(), error = function(e) e) |
||
442 | +67 |
- #' attr(ans, "teal_bookmarkable") <- bk+ }) |
||
443 | +68 |
- #' ans+ |
||
444 | +69 |
- #' }+ # We want to exclude teal_data_module elements from bookmarking as they might have some secrets |
||
445 | -+ | |||
70 | +87x |
- #'+ observeEvent(data_handled(), { |
||
446 | -+ | |||
71 | +80x |
- #' dummy_transformator <- teal_transform_module(+ if (inherits(data_handled(), "teal_data")) { |
||
447 | -+ | |||
72 | +75x |
- #' label = "Dummy Transform",+ app_session <- .subset2(shiny::getDefaultReactiveDomain(), "parent") |
||
448 | -+ | |||
73 | +75x |
- #' ui = function(id) div("(does nothing)"),+ setBookmarkExclude( |
||
449 | -+ | |||
74 | +75x |
- #' server = function(id, data) {+ session$ns( |
||
450 | -+ | |||
75 | +75x |
- #' moduleServer(id, function(input, output, session) data)+ grep( |
||
451 | -+ | |||
76 | +75x |
- #' }+ pattern = "teal_data_module-", |
||
452 | -+ | |||
77 | +75x |
- #' )+ x = names(reactiveValuesToList(input)), |
||
453 | -+ | |||
78 | +75x |
- #'+ value = TRUE |
||
454 | +79 |
- #' plot_transformator <- teal_transform_module(+ ) |
||
455 | +80 |
- #' label = "Plot Settings",+ ), |
||
456 | -+ | |||
81 | +75x |
- #' ui = function(id) div("(does nothing)"),+ session = app_session |
||
457 | +82 |
- #' server = function(id, data) {+ ) |
||
458 | +83 |
- #' moduleServer(id, function(input, output, session) data)+ } |
||
459 | +84 |
- #' }+ }) |
||
460 | +85 |
- #' )+ |
||
461 | -+ | |||
86 | +87x |
- #'+ data_handled |
||
462 | +87 |
- #' complete_modules <- modules(+ }) |
||
463 | +88 |
- #' custom_module(+ } |
||
464 | +89 |
- #' label = "Data Overview",+ |
||
465 | +90 |
- #' datanames = c("ADSL", "ADAE", "ADVS"),+ #' Adds signature protection to the `datanames` in the data |
||
466 | +91 |
- #' ui_args = list(+ #' @param data (`teal_data`) |
||
467 | +92 |
- #' view_type = "table",+ #' @return `teal_data` with additional code that has signature of the `datanames` |
||
468 | +93 |
- #' page_size = 10,+ #' @keywords internal |
||
469 | +94 |
- #' filters = c("ARM", "SEX", "RACE")+ .add_signature_to_data <- function(data) { |
||
470 | -+ | |||
95 | +75x |
- #' ),+ hashes <- .get_hashes_code(data) |
||
471 | -+ | |||
96 | +75x |
- #' server_args = list(+ tdata <- do.call( |
||
472 | -+ | |||
97 | +75x |
- #' cache = TRUE,+ teal.data::teal_data, |
||
473 | -+ | |||
98 | +75x |
- #' debounce = 1000+ c( |
||
474 | -+ | |||
99 | +75x |
- #' ),+ list(code = trimws(c(teal.code::get_code(data), hashes), which = "right")), |
||
475 | -+ | |||
100 | +75x |
- #' transformators = list(dummy_transformator),+ list(join_keys = teal.data::join_keys(data)), |
||
476 | -+ | |||
101 | +75x |
- #' bk = TRUE+ sapply( |
||
477 | -+ | |||
102 | +75x |
- #' ),+ names(data), |
||
478 | -+ | |||
103 | +75x |
- #' modules(+ teal.code::get_var, |
||
479 | -+ | |||
104 | +75x |
- #' label = "Nested 1",+ object = data, |
||
480 | -+ | |||
105 | +75x |
- #' custom_module(+ simplify = FALSE |
||
481 | +106 |
- #' label = "Interactive Plots",+ ) |
||
482 | +107 |
- #' datanames = c("ADSL", "ADVS"),+ ) |
||
483 | +108 |
- #' ui_args = list(+ ) |
||
484 | +109 |
- #' plot_type = c("scatter", "box", "line"),+ |
||
485 | -+ | |||
110 | +75x |
- #' height = 600,+ tdata@verified <- data@verified |
||
486 | -+ | |||
111 | +75x |
- #' width = 800,+ tdata |
||
487 | +112 |
- #' color_scheme = "viridis"+ } |
||
488 | +113 |
- #' ),+ |
||
489 | +114 |
- #' server_args = list(+ #' Get code that tests the integrity of the reproducible data |
||
490 | +115 |
- #' render_type = "svg",+ #' |
||
491 | +116 |
- #' cache_plots = TRUE+ #' @param data (`teal_data`) object holding the data |
||
492 | +117 |
- #' ),+ #' @param datanames (`character`) names of `datasets` |
||
493 | +118 |
- #' transformators = list(dummy_transformator, plot_transformator),+ #' |
||
494 | +119 |
- #' bk = TRUE+ #' @return A character vector with the code lines. |
||
495 | +120 |
- #' ),+ #' @keywords internal |
||
496 | +121 |
- #' modules(+ #' |
||
497 | +122 |
- #' label = "Nested 2",+ .get_hashes_code <- function(data, datanames = names(data)) { |
||
498 | -+ | |||
123 | +75x |
- #' custom_module(+ vapply( |
||
499 | -+ | |||
124 | +75x |
- #' label = "Summary Statistics",+ datanames, |
||
500 | -+ | |||
125 | +75x |
- #' datanames = "ADSL",+ function(dataname, datasets) { |
||
501 | -+ | |||
126 | +133x |
- #' ui_args = list(+ x <- data[[dataname]] |
||
502 | +127 |
- #' stats = c("mean", "median", "sd", "range"),+ |
||
503 | -+ | |||
128 | +133x |
- #' grouping = c("ARM", "SEX")+ code <- if (is.function(x) && !is.primitive(x)) { |
||
504 | -+ | |||
129 | +6x |
- #' )+ x <- deparse1(x) |
||
505 | -+ | |||
130 | +6x |
- #' ),+ bquote(rlang::hash(deparse1(.(as.name(dataname))))) |
||
506 | +131 |
- #' modules(+ } else { |
||
507 | -+ | |||
132 | +127x |
- #' label = "Labeled nested modules",+ bquote(rlang::hash(.(as.name(dataname)))) |
||
508 | +133 |
- #' custom_module(+ } |
||
509 | -+ | |||
134 | +133x |
- #' label = "Subgroup Analysis",+ sprintf( |
||
510 | -+ | |||
135 | +133x |
- #' datanames = c("ADSL", "ADAE"),+ "stopifnot(%s == %s) # @linksto %s", |
||
511 | -+ | |||
136 | +133x |
- #' ui_args = list(+ deparse1(code), |
||
512 | -+ | |||
137 | +133x |
- #' subgroups = c("AGE", "SEX", "RACE"),+ deparse1(rlang::hash(x)), |
||
513 | -+ | |||
138 | +133x |
- #' analysis_type = "stratified"+ dataname |
||
514 | +139 |
- #' ),+ ) |
||
515 | +140 |
- #' bk = TRUE+ }, |
||
516 | -+ | |||
141 | +75x |
- #' )+ character(1L), |
||
517 | -+ | |||
142 | +75x |
- #' ),+ USE.NAMES = TRUE |
||
518 | +143 |
- #' modules(custom_module(label = "Subgroup Analysis in non-labled modules"))+ ) |
||
519 | +144 |
- #' )+ } |
520 | +1 |
- #' ),+ # This is the main function from teal to be used by the end-users. Although it delegates |
||
521 | +2 |
- #' custom_module("Non-nested module")+ # directly to `module_teal_with_splash.R`, we keep it in a separate file because its documentation is quite large |
||
522 | +3 |
- #' )+ # and it is very end-user oriented. It may also perform more argument checking with more informative |
||
523 | +4 |
- #'+ # error messages. |
||
524 | +5 |
- #' cat(format(complete_modules))+ |
||
525 | +6 |
- #' cat(format(complete_modules, what = c("ui_args", "server_args", "transformators")))+ #' Create the server and UI function for the `shiny` app |
||
526 | +7 |
- #' @export+ #' |
||
527 | +8 |
- format.teal_modules <- function(x, is_root = TRUE, is_last = FALSE, parent_prefix = "", ...) {- |
- ||
528 | -1x | -
- if (is_root) {+ #' @description `r lifecycle::badge("stable")` |
||
529 | -1x | +|||
9 | +
- header <- pasten(crayon::bold("TEAL ROOT"))+ #' |
|||
530 | -1x | +|||
10 | +
- new_parent_prefix <- " " #' Initial indent for root level+ #' End-users: This is the most important function for you to start a |
|||
531 | +11 |
- } else {+ #' `teal` app that is composed of `teal` modules. |
||
532 | -! | +|||
12 | +
- if (!is.null(x$label)) {+ #' |
|||
533 | -! | +|||
13 | +
- branch <- if (is_last) "L-" else "|-"+ #' @param data (`teal_data` or `teal_data_module`) |
|||
534 | -! | +|||
14 | +
- header <- pasten(parent_prefix, branch, " ", crayon::bold(x$label))+ #' For constructing the data object, refer to [teal.data::teal_data()] and [teal_data_module()]. |
|||
535 | -! | +|||
15 | +
- new_parent_prefix <- paste0(parent_prefix, if (is_last) " " else "| ")+ #' If `datanames` are not set for the `teal_data` object, defaults from the `teal_data` environment will be used. |
|||
536 | +16 |
- } else {+ #' @param modules (`list` or `teal_modules` or `teal_module`) |
||
537 | -! | +|||
17 | +
- header <- ""+ #' Nested list of `teal_modules` or `teal_module` objects or a single |
|||
538 | -! | +|||
18 | +
- new_parent_prefix <- parent_prefix+ #' `teal_modules` or `teal_module` object. These are the specific output modules which |
|||
539 | +19 |
- }+ #' will be displayed in the `teal` application. See [modules()] and [module()] for |
||
540 | +20 |
- }+ #' more details. |
||
541 | +21 |
-
+ #' @param filter (`teal_slices`) Optionally, |
||
542 | -1x | +|||
22 | +
- if (length(x$children) > 0) {+ #' specifies the initial filter using [teal_slices()]. |
|||
543 | -1x | +|||
23 | +
- children_output <- character(0)+ #' @param title (`shiny.tag` or `character(1)`) Optionally, |
|||
544 | -1x | +|||
24 | +
- n_children <- length(x$children)+ #' the browser window title. Defaults to a title "teal app" with the icon of NEST. |
|||
545 | +25 |
-
+ #' Can be created using the `build_app_title()` or |
||
546 | -1x | +|||
26 | +
- for (i in seq_along(x$children)) {+ #' by passing a valid `shiny.tag` which is a head tag with title and link tag. |
|||
547 | -3x | +|||
27 | +
- child <- x$children[[i]]+ #' @param header (`shiny.tag` or `character(1)`) Optionally, |
|||
548 | -3x | +|||
28 | +
- is_last_child <- (i == n_children)+ #' the header of the app. |
|||
549 | +29 |
-
+ #' @param footer (`shiny.tag` or `character(1)`) Optionally, |
||
550 | -3x | +|||
30 | +
- if (inherits(child, "teal_modules")) {+ #' the footer of the app. |
|||
551 | -! | +|||
31 | +
- children_output <- c(+ #' @param id (`character`) Optionally, |
|||
552 | -! | +|||
32 | +
- children_output,+ #' a string specifying the `shiny` module id in cases it is used as a `shiny` module |
|||
553 | -! | +|||
33 | +
- format(child,+ #' rather than a standalone `shiny` app. This is a legacy feature. |
|||
554 | -! | +|||
34 | +
- is_root = FALSE,+ #' @param landing_popup (`teal_module_landing`) Optionally, |
|||
555 | -! | +|||
35 | +
- is_last = is_last_child,+ #' a `landing_popup_module` to show up as soon as the teal app is initialized. |
|||
556 | -! | +|||
36 | +
- parent_prefix = new_parent_prefix,+ #' |
|||
557 | +37 |
- ...+ #' @return Named list containing server and UI functions. |
||
558 | +38 |
- )+ #' |
||
559 | +39 |
- )+ #' @export |
||
560 | +40 |
- } else {+ #' |
||
561 | -3x | +|||
41 | +
- children_output <- c(+ #' @include modules.R |
|||
562 | -3x | +|||
42 | +
- children_output,+ #' |
|||
563 | -3x | +|||
43 | +
- format(child,+ #' @examples |
|||
564 | -3x | +|||
44 | +
- is_last = is_last_child,+ #' app <- init( |
|||
565 | -3x | +|||
45 | +
- parent_prefix = new_parent_prefix,+ #' data = within( |
|||
566 | +46 |
- ...+ #' teal_data(), |
||
567 | +47 |
- )+ #' { |
||
568 | +48 |
- )+ #' new_iris <- transform(iris, id = seq_len(nrow(iris))) |
||
569 | +49 |
- }+ #' new_mtcars <- transform(mtcars, id = seq_len(nrow(mtcars))) |
||
570 | +50 |
- }+ #' } |
||
571 | +51 |
-
+ #' ), |
||
572 | -1x | +|||
52 | +
- paste0(header, paste(children_output, collapse = ""))+ #' modules = modules( |
|||
573 | +53 |
- } else {+ #' module( |
||
574 | -! | +|||
54 | +
- header+ #' label = "data source", |
|||
575 | +55 |
- }+ #' server = function(input, output, session, data) {}, |
||
576 | +56 |
- }+ #' ui = function(id, ...) tags$div(p("information about data source")), |
||
577 | +57 |
-
+ #' datanames = "all" |
||
578 | +58 |
- #' @rdname teal_modules+ #' ), |
||
579 | +59 |
- #' @export+ #' example_module(label = "example teal module"), |
||
580 | +60 |
- print.teal_module <- function(x, ...) {+ #' module( |
||
581 | -! | +|||
61 | +
- cat(format(x, ...))+ #' "Iris Sepal.Length histogram", |
|||
582 | -! | +|||
62 | +
- invisible(x)+ #' server = function(input, output, session, data) { |
|||
583 | +63 |
- }+ #' output$hist <- renderPlot( |
||
584 | +64 |
-
+ #' hist(data()[["new_iris"]]$Sepal.Length) |
||
585 | +65 |
- #' @rdname teal_modules+ #' ) |
||
586 | +66 |
- #' @export+ #' }, |
||
587 | +67 |
- print.teal_modules <- function(x, ...) {+ #' ui = function(id, ...) { |
||
588 | -! | +|||
68 | +
- cat(format(x, ...))+ #' ns <- NS(id) |
|||
589 | -! | +|||
69 | +
- invisible(x)+ #' plotOutput(ns("hist")) |
|||
590 | +70 |
- }+ #' }, |
||
591 | +71 |
-
+ #' datanames = "new_iris" |
||
592 | +72 |
- #' @param modules (`teal_module` or `teal_modules`)+ #' ) |
||
593 | +73 |
- #' @rdname teal_modules+ #' ), |
||
594 | +74 |
- #' @examples+ #' filter = teal_slices( |
||
595 | +75 |
- #' # change the module's datanames+ #' teal_slice(dataname = "new_iris", varname = "Species"), |
||
596 | +76 |
- #' set_datanames(module(datanames = "all"), "a")+ #' teal_slice(dataname = "new_iris", varname = "Sepal.Length"), |
||
597 | +77 |
- #'+ #' teal_slice(dataname = "new_mtcars", varname = "cyl"), |
||
598 | +78 |
- #' # change modules' datanames+ #' exclude_varnames = list(new_iris = c("Sepal.Width", "Petal.Width")), |
||
599 | +79 |
- #' set_datanames(+ #' module_specific = TRUE, |
||
600 | +80 |
- #' modules(+ #' mapping = list( |
||
601 | +81 |
- #' module(datanames = "all"),+ #' `example teal module` = "new_iris Species", |
||
602 | +82 |
- #' module(datanames = "a")+ #' `Iris Sepal.Length histogram` = "new_iris Species", |
||
603 | +83 |
- #' ),+ #' global_filters = "new_mtcars cyl" |
||
604 | +84 |
- #' "b"+ #' ) |
||
605 | +85 |
- #' )+ #' ), |
||
606 | +86 |
- #' @export+ #' title = "App title", |
||
607 | +87 |
- set_datanames <- function(modules, datanames) {+ #' header = tags$h1("Sample App"), |
||
608 | -! | +|||
88 | +
- checkmate::assert_multi_class(modules, c("teal_modules", "teal_module"))+ #' footer = tags$p("Sample footer") |
|||
609 | -! | +|||
89 | +
- if (inherits(modules, "teal_modules")) {+ #' ) |
|||
610 | -! | +|||
90 | +
- modules$children <- lapply(modules$children, set_datanames, datanames)+ #' if (interactive()) { |
|||
611 | +91 |
- } else {+ #' shinyApp(app$ui, app$server) |
||
612 | -! | +|||
92 | +
- if (identical(modules$datanames, "all")) {+ #' } |
|||
613 | -! | +|||
93 | +
- modules$datanames <- datanames+ #' |
|||
614 | +94 |
- } else {+ init <- function(data, |
||
615 | -! | +|||
95 | +
- warning(+ modules, |
|||
616 | -! | +|||
96 | +
- "Not possible to modify datanames of the module ", modules$label,+ filter = teal_slices(), |
|||
617 | -! | +|||
97 | +
- ". set_datanames() can only change datanames if it was set to \"all\".",+ title = build_app_title(), |
|||
618 | -! | +|||
98 | +
- call. = FALSE+ header = tags$p(), |
|||
619 | +99 |
- )+ footer = tags$p(), |
||
620 | +100 |
- }+ id = character(0), |
||
621 | +101 |
- }+ landing_popup = NULL) { |
||
622 | -! | +|||
102 | +14x |
- modules+ logger::log_debug("init initializing teal app with: data ('{ class(data) }').") |
||
623 | +103 |
- }+ |
||
624 | +104 |
-
+ # argument checking (independent) |
||
625 | +105 |
- # utilities ----+ ## `data` |
||
626 | -+ | |||
106 | +14x |
- ## subset or modify modules ----+ checkmate::assert_multi_class(data, c("teal_data", "teal_data_module"))+ |
+ ||
107 | +14x | +
+ checkmate::assert_class(landing_popup, "teal_module_landing", null.ok = TRUE) |
||
627 | +108 | |||
628 | +109 |
- #' Append a `teal_module` to `children` of a `teal_modules` object+ ## `modules` |
||
629 | -+ | |||
110 | +14x |
- #' @keywords internal+ checkmate::assert( |
||
630 | -+ | |||
111 | +14x |
- #' @param modules (`teal_modules`)+ .var.name = "modules", |
||
631 | -+ | |||
112 | +14x |
- #' @param module (`teal_module`) object to be appended onto the children of `modules`+ checkmate::check_multi_class(modules, c("teal_modules", "teal_module")), |
||
632 | -+ | |||
113 | +14x |
- #' @return A `teal_modules` object with `module` appended.+ checkmate::check_list(modules, min.len = 1, any.missing = FALSE, types = c("teal_module", "teal_modules")) |
||
633 | +114 |
- append_module <- function(modules, module) {- |
- ||
634 | -8x | -
- checkmate::assert_class(modules, "teal_modules")+ ) |
||
635 | -6x | +115 | +14x |
- checkmate::assert_class(module, "teal_module")+ if (inherits(modules, "teal_module")) { |
636 | -4x | +116 | +1x |
- modules$children <- c(modules$children, list(module))+ modules <- list(modules) |
637 | -4x | +|||
117 | +
- labels <- vapply(modules$children, function(submodule) submodule$label, character(1))+ } |
|||
638 | -4x | +118 | +14x |
- names(modules$children) <- get_unique_labels(labels)+ if (checkmate::test_list(modules, min.len = 1, any.missing = FALSE, types = c("teal_module", "teal_modules"))) { |
639 | -4x | +119 | +8x |
- modules+ modules <- do.call(teal::modules, modules) |
640 | +120 |
- }+ } |
||
641 | +121 | |||
642 | +122 |
- #' Extract/Remove module(s) of specific class+ ## `filter` |
||
643 | -+ | |||
123 | +14x |
- #'+ checkmate::assert_class(filter, "teal_slices") |
||
644 | +124 |
- #' Given a `teal_module` or a `teal_modules`, return the elements of the structure according to `class`.+ |
||
645 | +125 |
- #'+ ## all other arguments |
||
646 | -+ | |||
126 | +13x |
- #' @param modules (`teal_modules`)+ checkmate::assert( |
||
647 | -+ | |||
127 | +13x |
- #' @param class The class name of `teal_module` to be extracted or dropped.+ .var.name = "title", |
||
648 | -+ | |||
128 | +13x |
- #' @keywords internal+ checkmate::check_string(title), |
||
649 | -+ | |||
129 | +13x |
- #' @return+ checkmate::check_multi_class(title, c("shiny.tag", "shiny.tag.list", "html")) |
||
650 | +130 |
- #' - For `extract_module`, a `teal_module` of class `class` or `teal_modules` containing modules of class `class`.+ ) |
||
651 | -+ | |||
131 | +13x |
- #' - For `drop_module`, the opposite, which is all `teal_modules` of class other than `class`.+ checkmate::assert( |
||
652 | -+ | |||
132 | +13x |
- #' @rdname module_management+ .var.name = "header", |
||
653 | -+ | |||
133 | +13x |
- extract_module <- function(modules, class) {+ checkmate::check_string(header), |
||
654 | -28x | +134 | +13x |
- if (inherits(modules, class)) {+ checkmate::check_multi_class(header, c("shiny.tag", "shiny.tag.list", "html")) |
655 | -! | +|||
135 | +
- modules+ ) |
|||
656 | -28x | +136 | +13x |
- } else if (inherits(modules, "teal_module")) {+ checkmate::assert( |
657 | -15x | +137 | +13x |
- NULL+ .var.name = "footer", |
658 | +138 | 13x |
- } else if (inherits(modules, "teal_modules")) {+ checkmate::check_string(footer), |
|
659 | +139 | 13x |
- Filter(function(x) length(x) > 0L, lapply(modules$children, extract_module, class))+ checkmate::check_multi_class(footer, c("shiny.tag", "shiny.tag.list", "html")) |
|
660 | +140 |
- }+ ) |
||
661 | -+ | |||
141 | +13x |
- }+ checkmate::assert_character(id, max.len = 1, any.missing = FALSE) |
||
662 | +142 | |||
663 | +143 |
- #' @keywords internal+ # log+ |
+ ||
144 | +13x | +
+ teal.logger::log_system_info() |
||
664 | +145 |
- #' @return `teal_modules`+ |
||
665 | +146 |
- #' @rdname module_management+ # argument transformations |
||
666 | +147 |
- drop_module <- function(modules, class) {+ ## `modules` - landing module+ |
+ ||
148 | +13x | +
+ landing <- extract_module(modules, "teal_module_landing")+ |
+ ||
149 | +13x | +
+ if (length(landing) == 1L) { |
||
667 | +150 | ! |
- if (inherits(modules, class)) {+ landing_popup <- landing[[1L]] |
|
668 | +151 | ! |
- NULL+ modules <- drop_module(modules, "teal_module_landing") |
|
669 | +152 | ! |
- } else if (inherits(modules, "teal_module")) {+ lifecycle::deprecate_soft( |
|
670 | +153 | ! |
- modules+ when = "0.15.3", |
|
671 | +154 | ! |
- } else if (inherits(modules, "teal_modules")) {+ what = "landing_popup_module()", |
|
672 | +155 | ! |
- do.call(+ details = paste( |
|
673 | +156 | ! |
- "modules",+ "Pass `landing_popup_module` to the `landing_popup` argument of the `init` ", |
|
674 | +157 | ! |
- c(Filter(function(x) length(x) > 0L, lapply(modules$children, drop_module, class)), label = modules$label)+ "instead of wrapping it into `modules()` and passing to the `modules` argument" |
|
675 | +158 |
- )+ ) |
||
676 | +159 |
- }+ ) |
||
677 | -+ | |||
160 | +13x |
- }+ } else if (length(landing) > 1L) { |
||
678 | -+ | |||
161 | +! |
-
+ stop("Only one `landing_popup_module` can be used.") |
||
679 | +162 |
- ## read modules ----+ } |
||
680 | +163 | |||
681 | +164 |
- #' Does the object make use of the `arg`+ ## `filter` - set app_id attribute unless present (when restoring bookmark) |
||
682 | -+ | |||
165 | +13x |
- #'+ if (is.null(attr(filter, "app_id", exact = TRUE))) attr(filter, "app_id") <- create_app_id(data, modules) |
||
683 | +166 |
- #' @param modules (`teal_module` or `teal_modules`) object+ |
||
684 | +167 |
- #' @param arg (`character(1)`) names of the arguments to be checked against formals of `teal` modules.+ ## `filter` - convert teal.slice::teal_slices to teal::teal_slices |
||
685 | -+ | |||
168 | +13x |
- #' @return `logical` whether the object makes use of `arg`.+ filter <- as.teal_slices(as.list(filter)) |
||
686 | +169 |
- #' @rdname is_arg_used+ |
||
687 | +170 |
- #' @keywords internal+ # argument checking (interdependent) |
||
688 | +171 |
- is_arg_used <- function(modules, arg) {+ ## `filter` - `modules` |
||
689 | -519x | +172 | +13x |
- checkmate::assert_string(arg)+ if (isTRUE(attr(filter, "module_specific"))) { |
690 | -516x | +|||
173 | +! |
- if (inherits(modules, "teal_modules")) {+ module_names <- unlist(c(module_labels(modules), "global_filters")) |
||
691 | -20x | +|||
174 | +! |
- any(unlist(lapply(modules$children, is_arg_used, arg)))+ failed_mod_names <- setdiff(names(attr(filter, "mapping")), module_names) |
||
692 | -496x | +|||
175 | +! |
- } else if (inherits(modules, "teal_module")) {+ if (length(failed_mod_names)) { |
||
693 | -32x | +|||
176 | +! |
- is_arg_used(modules$server, arg) || is_arg_used(modules$ui, arg)+ stop( |
||
694 | -464x | +|||
177 | +! |
- } else if (is.function(modules)) {+ sprintf( |
||
695 | -462x | +|||
178 | +! |
- isTRUE(arg %in% names(formals(modules)))+ "Some module names in the mapping arguments don't match module labels.\n %s not in %s",+ |
+ ||
179 | +! | +
+ toString(failed_mod_names),+ |
+ ||
180 | +! | +
+ toString(unique(module_names)) |
||
696 | +181 |
- } else {+ ) |
||
697 | -2x | +|||
182 | +
- stop("is_arg_used function not implemented for this object")+ ) |
|||
698 | +183 |
- }+ } |
||
699 | +184 |
- }+ + |
+ ||
185 | +! | +
+ if (anyDuplicated(module_names)) { |
||
700 | +186 |
-
+ # In teal we are able to set nested modules with duplicated label. |
||
701 | +187 |
-
+ # Because mapping argument bases on the relationship between module-label and filter-id, |
||
702 | +188 |
- #' Get module depth+ # it is possible that module-label in mapping might refer to multiple teal_module (identified by the same label)+ |
+ ||
189 | +! | +
+ stop(+ |
+ ||
190 | +! | +
+ sprintf(+ |
+ ||
191 | +! | +
+ "Module labels should be unique when teal_slices(mapping = TRUE). Duplicated labels:\n%s ",+ |
+ ||
192 | +! | +
+ toString(module_names[duplicated(module_names)]) |
||
703 | +193 |
- #'+ ) |
||
704 | +194 |
- #' Depth starts at 0, so a single `teal.module` has depth 0.+ ) |
||
705 | +195 | ++ |
+ }+ |
+ |
196 | ++ |
+ }+ |
+ ||
197 | ++ | + + | +||
198 |
- #' Nesting it increases overall depth by 1.+ ## `data` - `modules`+ |
+ |||
199 | +13x | +
+ if (inherits(data, "teal_data")) {+ |
+ ||
200 | +12x | +
+ if (length(data) == 0) { |
||
706 | -+ | |||
201 | +1x |
- #'+ stop("The environment of `data` is empty.") |
||
707 | +202 |
- #' @inheritParams init+ } |
||
708 | +203 |
- #' @param depth optional integer determining current depth level+ |
||
709 | -+ | |||
204 | +11x |
- #'+ is_modules_ok <- check_modules_datanames(modules, names(data)) |
||
710 | -+ | |||
205 | +11x |
- #' @return Depth level for given module.+ if (!isTRUE(is_modules_ok) && length(unlist(extract_transformators(modules))) == 0) { |
||
711 | -+ | |||
206 | +4x |
- #' @keywords internal+ warning(is_modules_ok, call. = FALSE) |
||
712 | +207 |
- modules_depth <- function(modules, depth = 0L) {+ } |
||
713 | -12x | +|||
208 | +
- checkmate::assert_multi_class(modules, c("teal_module", "teal_modules"))+ |
|||
714 | -12x | +209 | +11x |
- checkmate::assert_int(depth, lower = 0)+ is_filter_ok <- check_filter_datanames(filter, names(data)) |
715 | +210 | 11x |
- if (inherits(modules, "teal_modules")) {+ if (!isTRUE(is_filter_ok)) { |
|
716 | -4x | +211 | +1x |
- max(vapply(modules$children, modules_depth, integer(1), depth = depth + 1L))+ warning(is_filter_ok) |
717 | +212 |
- } else {+ # we allow app to continue if applied filters are outside |
||
718 | -7x | +|||
213 | +
- depth+ # of possible data range |
|||
719 | +214 |
- }+ } |
||
720 | +215 |
- }+ } |
||
721 | +216 | |||
722 | -+ | |||
217 | +12x |
- #' Retrieve labels from `teal_modules`+ reporter <- teal.reporter::Reporter$new()$set_id(attr(filter, "app_id")) |
||
723 | -+ | |||
218 | +12x |
- #'+ if (is_arg_used(modules, "reporter") && length(extract_module(modules, "teal_module_previewer")) == 0) { |
||
724 | -+ | |||
219 | +! |
- #' @param modules (`teal_modules`)+ modules <- append_module( |
||
725 | -+ | |||
220 | +! |
- #' @return A `list` containing the labels of the modules. If the modules are nested,+ modules, |
||
726 | -+ | |||
221 | +! |
- #' the function returns a nested `list` of labels.+ reporter_previewer_module(server_args = list(previewer_buttons = c("download", "reset"))) |
||
727 | +222 |
- #' @keywords internal+ ) |
||
728 | +223 |
- module_labels <- function(modules) {+ } |
||
729 | -199x | +|||
224 | +
- if (inherits(modules, "teal_modules")) {+ |
|||
730 | -87x | +225 | +12x |
- lapply(modules$children, module_labels)+ ns <- NS(id) |
731 | +226 |
- } else {+ # Note: UI must be a function to support bookmarking. |
||
732 | -112x | +227 | +12x |
- modules$label+ res <- list( |
733 | -+ | |||
228 | +12x |
- }+ ui = function(request) { |
||
734 | -+ | |||
229 | +! |
- }+ ui_teal( |
||
735 | -+ | |||
230 | +! |
-
+ id = ns("teal"), |
||
736 | -+ | |||
231 | +! |
- #' Retrieve `teal_bookmarkable` attribute from `teal_modules`+ modules = modules, |
||
737 | -+ | |||
232 | +! |
- #'+ title = title, |
||
738 | -+ | |||
233 | +! |
- #' @param modules (`teal_modules` or `teal_module`) object+ header = header, |
||
739 | -+ | |||
234 | +! |
- #' @return named list of the same structure as `modules` with `TRUE` or `FALSE` values indicating+ footer = footer |
||
740 | +235 |
- #' whether the module is bookmarkable.+ ) |
||
741 | +236 |
- #' @keywords internal+ }, |
||
742 | -+ | |||
237 | +12x |
- modules_bookmarkable <- function(modules) {+ server = function(input, output, session) { |
||
743 | -199x | +|||
238 | +! |
- checkmate::assert_multi_class(modules, c("teal_modules", "teal_module"))+ if (!is.null(landing_popup)) { |
||
744 | -199x | +|||
239 | +! |
- if (inherits(modules, "teal_modules")) {+ do.call(landing_popup$server, c(list(id = "landing_module_shiny_id"), landing_popup$server_args)) |
||
745 | -87x | +|||
240 | +
- setNames(+ } |
|||
746 | -87x | +|||
241 | +! |
- lapply(modules$children, modules_bookmarkable),+ srv_teal(id = ns("teal"), data = data, modules = modules, filter = deep_copy_filter(filter)) |
||
747 | -87x | +|||
242 | +
- vapply(modules$children, `[[`, "label", FUN.VALUE = character(1))+ } |
|||
748 | +243 |
- )+ ) |
||
749 | +244 |
- } else {+ |
||
750 | -112x | +245 | +12x |
- attr(modules, "teal_bookmarkable", exact = TRUE)+ logger::log_debug("init teal app has been initialized.") |
751 | +246 |
- }+ + |
+ ||
247 | +12x | +
+ res |
||
752 | +248 |
}@@ -23970,63 +23165,63 @@ teal coverage - 60.11% |
1 |
- # FilteredData ------+ setOldClass("teal_module") |
||
2 |
-
+ setOldClass("teal_modules") |
||
3 |
- #' Drive a `teal` application+ |
||
4 |
- #'+ #' Create `teal_module` and `teal_modules` objects |
||
5 |
- #' Extension of the `shinytest2::AppDriver` class with methods for+ #' |
||
6 |
- #' driving a teal application for performing interactions for `shinytest2` tests.+ #' @description |
||
7 |
- #'+ #' `r lifecycle::badge("stable")` |
||
8 |
- #' @keywords internal+ #' Create a nested tab structure to embed modules in a `teal` application. |
||
10 |
- TealAppDriver <- R6::R6Class( # nolint: object_name.+ #' @details |
||
11 |
- "TealAppDriver",+ #' `module()` creates an instance of a `teal_module` that can be placed in a `teal` application. |
||
12 |
- inherit = {+ #' `modules()` shapes the structure of a the application by organizing `teal_module` within the navigation panel. |
||
13 |
- if (!requireNamespace("shinytest2", quietly = TRUE)) {+ #' It wraps `teal_module` and `teal_modules` objects in a `teal_modules` object, |
||
14 |
- stop("Please install 'shinytest2' package to use this class.")+ #' which results in a nested structure corresponding to the nested tabs in the final application. |
||
15 |
- }+ #' |
||
16 |
- if (!requireNamespace("rvest", quietly = TRUE)) {+ #' Note that for `modules()` `label` comes after `...`, so it must be passed as a named argument, |
||
17 |
- stop("Please install 'rvest' package to use this class.")+ #' otherwise it will be captured by `...`. |
||
18 |
- }+ #' |
||
19 |
- shinytest2::AppDriver+ #' The labels `"global_filters"` and `"Report previewer"` are reserved |
||
20 |
- },+ #' because they are used by the `mapping` argument of [teal_slices()] |
||
21 |
- # public methods ----+ #' and the report previewer module [reporter_previewer_module()], respectively. |
||
22 |
- public = list(+ #' |
||
23 |
- #' @description+ #' # Restricting datasets used by `teal_module`: |
||
24 |
- #' Initialize a `TealAppDriver` object for testing a `teal` application.+ #' The `datanames` argument controls which datasets are used by the module’s server. These datasets, |
||
25 |
- #'+ #' passed via server's `data` argument, are the only ones shown in the module's tab. |
||
26 |
- #' @param data,modules,filter,title,header,footer,landing_popup arguments passed to `init`+ #' |
||
27 |
- #' @param timeout (`numeric`) Default number of milliseconds for any timeout or+ #' When `datanames` is set to `"all"`, all datasets in the data object are treated as relevant. |
||
28 |
- #' timeout_ parameter in the `TealAppDriver` class.+ #' However, this may include unnecessary datasets, such as: |
||
29 |
- #' Defaults to 20s.+ #' - Proxy variables for column modifications |
||
30 |
- #'+ #' - Temporary datasets used to create final versions |
||
31 |
- #' See [`shinytest2::AppDriver`] `new` method for more details on how to change it+ #' - Connection objects |
||
32 |
- #' via options or environment variables.+ #' |
||
33 |
- #' @param load_timeout (`numeric`) How long to wait for the app to load, in ms.+ #' To exclude irrelevant datasets, use the [set_datanames()] function to change `datanames` from |
||
34 |
- #' This includes the time to start R. Defaults to 100s.+ #' `"all"` to specific names. Trying to modify non-`"all"` values with [set_datanames()] will result |
||
35 |
- #'+ #' in a warning. Datasets with names starting with . are ignored globally unless explicitly listed |
||
36 |
- #' See [`shinytest2::AppDriver`] `new` method for more details on how to change it+ #' in `datanames`. |
||
37 |
- #' via options or environment variables+ #' |
||
38 |
- #' @param ... Additional arguments to be passed to `shinytest2::AppDriver$new`+ #' # `datanames` with `transformators` |
||
39 |
- #'+ #' When transformators are specified, their `datanames` are added to the module’s `datanames`, which |
||
40 |
- #'+ #' changes the behavior as follows: |
||
41 |
- #' @return Object of class `TealAppDriver`+ #' - If `module(datanames)` is `NULL` and the `transformators` have defined `datanames`, the sidebar |
||
42 |
- initialize = function(data,+ #' will appear showing the `transformators`' datasets, instead of being hidden. |
||
43 |
- modules,+ #' - If `module(datanames)` is set to specific values and any `transformator` has `datanames = "all"`, |
||
44 |
- filter = teal_slices(),+ #' the module may receive extra datasets that could be unnecessary |
||
45 |
- title = build_app_title(),+ #' |
||
46 |
- header = tags$p(),+ #' @param label (`character(1)`) Label shown in the navigation item for the module or module group. |
||
47 |
- footer = tags$p(),+ #' For `modules()` defaults to `"root"`. See `Details`. |
||
48 |
- landing_popup = NULL,+ #' @param server (`function`) `shiny` module with following arguments: |
||
49 |
- timeout = rlang::missing_arg(),+ #' - `id` - `teal` will set proper `shiny` namespace for this module (see [shiny::moduleServer()]). |
||
50 |
- load_timeout = rlang::missing_arg(),+ #' - `input`, `output`, `session` - (optional; not recommended) When provided, then [shiny::callModule()] |
||
51 |
- ...) {+ #' will be used to call a module. From `shiny` 1.5.0, the recommended way is to use |
||
52 | -! | +
- private$data <- data+ #' [shiny::moduleServer()] instead which doesn't require these arguments. |
|
53 | -! | +
- private$modules <- modules+ #' - `data` (optional) When provided, the module will be called with `teal_data` object (i.e. a list of |
|
54 | -! | +
- private$filter <- filter+ #' reactive (filtered) data specified in the `filters` argument) as the value of this argument. |
|
55 | -! | +
- app <- init(+ #' - `datasets` (optional) When provided, the module will be called with `FilteredData` object as the |
|
56 | -! | +
- data = data,+ #' value of this argument. (See [`teal.slice::FilteredData`]). |
|
57 | -! | +
- modules = modules,+ #' - `reporter` (optional) When provided, the module will be called with `Reporter` object as the value |
|
58 | -! | +
- filter = filter,+ #' of this argument. (See [`teal.reporter::Reporter`]). |
|
59 | -! | +
- title = title,+ #' - `filter_panel_api` (optional) When provided, the module will be called with `FilterPanelAPI` object |
|
60 | -! | +
- header = header,+ #' as the value of this argument. (See [`teal.slice::FilterPanelAPI`]). |
|
61 | -! | +
- footer = footer,+ #' - `...` (optional) When provided, `server_args` elements will be passed to the module named argument |
|
62 | -! | +
- landing_popup = landing_popup,+ #' or to the `...`. |
|
63 |
- )+ #' @param ui (`function`) `shiny` UI module function with following arguments: |
||
64 |
-
+ #' - `id` - `teal` will set proper `shiny` namespace for this module. |
||
65 |
- # Default timeout is hardcoded to 4s in shinytest2:::resolve_timeout+ #' - `...` (optional) When provided, `ui_args` elements will be passed to the module named argument |
||
66 |
- # It must be set as parameter to the AppDriver+ #' or to the `...`. |
||
67 | -! | +
- suppressWarnings(+ #' @param filters (`character`) Deprecated. Use `datanames` instead. |
|
68 | -! | +
- super$initialize(+ #' @param datanames (`character`) Names of the datasets relevant to the item. |
|
69 | -! | +
- app_dir = shinyApp(app$ui, app$server),+ #' There are 2 reserved values that have specific behaviors: |
|
70 | -! | +
- name = "teal",+ #' - The keyword `"all"` includes all datasets available in the data passed to the teal application. |
|
71 | -! | +
- variant = shinytest2::platform_variant(),+ #' - `NULL` hides the sidebar panel completely. |
|
72 | -! | +
- timeout = rlang::maybe_missing(timeout, 20 * 1000),+ #' - If `transformators` are specified, their `datanames` are automatically added to this `datanames` |
|
73 | -! | +
- load_timeout = rlang::maybe_missing(load_timeout, 100 * 1000),+ #' argument. |
|
74 |
- ...+ #' @param server_args (named `list`) with additional arguments passed on to the server function. |
||
75 |
- )+ #' @param ui_args (named `list`) with additional arguments passed on to the UI function. |
||
76 |
- )+ #' @param x (`teal_module` or `teal_modules`) Object to format/print. |
||
77 |
-
+ #' @param transformators (`list` of `teal_transform_module`) that will be applied to transformator module's data input. |
||
78 |
- # Check for minimum version of Chrome that supports the tests+ #' |
||
79 |
- # - Element.checkVisibility was added on 105+ #' |
||
80 | -! | +
- chrome_version <- numeric_version(+ #' @param ... |
|
81 | -! | +
- gsub(+ #' - For `modules()`: (`teal_module` or `teal_modules`) Objects to wrap into a tab. |
|
82 | -! | +
- "[[:alnum:]_]+/", # Prefix that ends with forward slash+ #' - For `format()` and `print()`: Arguments passed to other methods. |
|
83 |
- "",+ #' |
||
84 | -! | +
- self$get_chromote_session()$Browser$getVersion()$product+ #' @return |
|
85 |
- ),+ #' `module()` returns an object of class `teal_module`. |
||
86 | -! | +
- strict = FALSE+ #' |
|
87 |
- )+ #' `modules()` returns a `teal_modules` object which contains following fields: |
||
88 |
-
+ #' - `label`: taken from the `label` argument. |
||
89 | -! | +
- required_version <- "121"+ #' - `children`: a list containing objects passed in `...`. List elements are named after |
|
90 |
-
+ #' their `label` attribute converted to a valid `shiny` id. |
||
91 | -! | +
- testthat::skip_if(+ #' |
|
92 | -! | +
- is.na(chrome_version),+ #' @name teal_modules |
|
93 | -! | +
- "Problem getting Chrome version, please contact the developers."+ #' @aliases teal_module |
|
94 |
- )+ #' |
||
95 | -! | +
- testthat::skip_if(+ #' @examples |
|
96 | -! | +
- chrome_version < required_version,+ #' library(shiny) |
|
97 | -! | +
- sprintf(+ #' |
|
98 | -! | +
- "Chrome version '%s' is not supported, please upgrade to '%s' or higher",+ #' module_1 <- module( |
|
99 | -! | +
- chrome_version,+ #' label = "a module", |
|
100 | -! | +
- required_version+ #' server = function(id, data) { |
|
101 |
- )+ #' moduleServer( |
||
102 |
- )+ #' id, |
||
103 |
- # end od check+ #' module = function(input, output, session) { |
||
104 |
-
+ #' output$data <- renderDataTable(data()[["iris"]]) |
||
105 | -! | +
- private$set_active_ns()+ #' } |
|
106 | -! | +
- self$wait_for_idle()+ #' ) |
|
107 |
- },+ #' }, |
||
108 |
- #' @description+ #' ui = function(id) { |
||
109 |
- #' Append parent [`shinytest2::AppDriver`] `click` method with a call to `waif_for_idle()` method.+ #' ns <- NS(id) |
||
110 |
- #' @param ... arguments passed to parent [`shinytest2::AppDriver`] `click()` method.+ #' tagList(dataTableOutput(ns("data"))) |
||
111 |
- click = function(...) {+ #' }, |
||
112 | -! | +
- super$click(...)+ #' datanames = "all" |
|
113 | -! | +
- private$wait_for_page_stability()+ #' ) |
|
114 |
- },+ #' |
||
115 |
- #' @description+ #' module_2 <- module( |
||
116 |
- #' Check if the app has shiny errors. This checks for global shiny errors.+ #' label = "another module", |
||
117 |
- #' Note that any shiny errors dependent on shiny server render will only be captured after the teal module tab+ #' server = function(id) { |
||
118 |
- #' is visited because shiny will not trigger server computations when the tab is invisible.+ #' moduleServer( |
||
119 |
- #' So, navigate to the module tab you want to test before calling this function.+ #' id, |
||
120 |
- #' Although, this catches errors hidden in the other module tabs if they are already rendered.+ #' module = function(input, output, session) { |
||
121 |
- expect_no_shiny_error = function() {+ #' output$text <- renderText("Another Module") |
||
122 | -! | +
- testthat::expect_null(+ #' } |
|
123 | -! | +
- self$get_html(".shiny-output-error:not(.shiny-output-error-validation)"),+ #' ) |
|
124 | -! | +
- info = "Shiny error is observed"+ #' }, |
|
125 |
- )+ #' ui = function(id) { |
||
126 |
- },+ #' ns <- NS(id) |
||
127 |
- #' @description+ #' tagList(textOutput(ns("text"))) |
||
128 |
- #' Check if the app has no validation errors. This checks for global shiny validation errors.+ #' }, |
||
129 |
- expect_no_validation_error = function() {+ #' datanames = NULL |
||
130 | -! | +
- testthat::expect_null(+ #' ) |
|
131 | -! | +
- self$get_html(".shiny-output-error-validation"),+ #' |
|
132 | -! | +
- info = "No validation error is observed"+ #' modules <- modules( |
|
133 |
- )+ #' label = "modules", |
||
134 |
- },+ #' modules( |
||
135 |
- #' @description+ #' label = "nested modules", |
||
136 |
- #' Check if the app has validation errors. This checks for global shiny validation errors.+ #' module_1 |
||
137 |
- expect_validation_error = function() {+ #' ), |
||
138 | -! | +
- testthat::expect_false(+ #' module_2 |
|
139 | -! | +
- is.null(self$get_html(".shiny-output-error-validation")),+ #' ) |
|
140 | -! | +
- info = "Validation error is not observed"+ #' |
|
141 |
- )+ #' app <- init( |
||
142 |
- },+ #' data = teal_data(iris = iris), |
||
143 |
- #' @description+ #' modules = modules |
||
144 |
- #' Set the input in the `teal` app.+ #' ) |
||
145 |
- #'+ #' |
||
146 |
- #' @param input_id (character) The shiny input id with it's complete name space.+ #' if (interactive()) { |
||
147 |
- #' @param value The value to set the input to.+ #' shinyApp(app$ui, app$server) |
||
148 |
- #' @param ... Additional arguments to be passed to `shinytest2::AppDriver$set_inputs`+ #' } |
||
149 |
- #'+ #' @rdname teal_modules |
||
150 |
- #' @return The `TealAppDriver` object invisibly.+ #' @export |
||
151 |
- set_input = function(input_id, value, ...) {+ #' |
||
152 | -! | +
- do.call(+ module <- function(label = "module", |
|
153 | -! | +
- self$set_inputs,+ server = function(id, data, ...) moduleServer(id, function(input, output, session) NULL), |
|
154 | -! | +
- c(setNames(list(value), input_id), list(...))+ ui = function(id, ...) tags$p(paste0("This module has no UI (id: ", id, " )")), |
|
155 |
- )+ filters, |
||
156 | -! | +
- invisible(self)+ datanames = "all", |
|
157 |
- },+ server_args = NULL, |
||
158 |
- #' @description+ ui_args = NULL, |
||
159 |
- #' Navigate the teal tabs in the `teal` app.+ transformators = list()) { |
||
160 |
- #'+ # argument checking (independent) |
||
161 |
- #' @param tabs (character) Labels of tabs to navigate to. The order of the tabs is important,+ ## `label` |
||
162 | -+ | 220x |
- #' and it should start with the most parent level tab.+ checkmate::assert_string(label) |
163 | -+ | 217x |
- #' Note: In case the teal tab group has duplicate names, the first tab will be selected,+ if (label == "global_filters") { |
164 | -+ | 1x |
- #' If you wish to select the second tab with the same name, use the suffix "_1".+ stop( |
165 | -+ | 1x |
- #' If you wish to select the third tab with the same name, use the suffix "_2" and so on.+ sprintf("module(label = \"%s\", ...\n ", label), |
166 | -+ | 1x |
- #'+ "Label 'global_filters' is reserved in teal. Please change to something else.", |
167 | -+ | 1x |
- #' @return The `TealAppDriver` object invisibly.+ call. = FALSE |
168 |
- navigate_teal_tab = function(tabs) {+ ) |
||
169 | -! | +
- checkmate::check_character(tabs, min.len = 1)+ } |
|
170 | -! | +216x |
- for (tab in tabs) {+ if (label == "Report previewer") { |
171 | ! |
- self$set_input(+ stop( |
|
172 | ! |
- "teal-teal_modules-active_tab",+ sprintf("module(label = \"%s\", ...\n ", label), |
|
173 | ! |
- get_unique_labels(tab),+ "Label 'Report previewer' is reserved in teal. Please change to something else.", |
|
174 | ! |
- wait_ = FALSE+ call. = FALSE |
|
175 |
- )+ ) |
||
176 |
- }+ } |
||
177 | -! | +
- self$wait_for_idle()+ |
|
178 | -! | +
- private$set_active_ns()+ ## server |
|
179 | -! | +216x |
- invisible(self)+ checkmate::assert_function(server) |
180 | -+ | 216x |
- },+ server_formals <- names(formals(server)) |
181 | -+ | 216x |
- #' @description+ if (!( |
182 | -+ | 216x |
- #' Get the active shiny name space for different components of the teal app.+ "id" %in% server_formals || |
183 | -+ | 216x |
- #'+ all(c("input", "output", "session") %in% server_formals) |
184 |
- #' @return (`list`) The list of active shiny name space of the teal components.+ )) { |
||
185 | -+ | 2x |
- active_ns = function() {+ stop( |
186 | -! | +2x |
- if (identical(private$ns$module, character(0))) {+ "\nmodule() `server` argument requires a function with following arguments:", |
187 | -! | +2x |
- private$set_active_ns()+ "\n - id - `teal` will set proper `shiny` namespace for this module.", |
188 | -+ | 2x |
- }+ "\n - input, output, session (not recommended) - then `shiny::callModule` will be used to call a module.", |
189 | -! | +2x |
- private$ns+ "\n\nFollowing arguments can be used optionaly:", |
190 | -+ | 2x |
- },+ "\n - `data` - module will receive list of reactive (filtered) data specified in the `filters` argument", |
191 | -+ | 2x |
- #' @description+ "\n - `datasets` - module will receive `FilteredData`. See `help(teal.slice::FilteredData)`", |
192 | -+ | 2x |
- #' Get the active shiny name space for interacting with the module content.+ "\n - `reporter` - module will receive `Reporter`. See `help(teal.reporter::Reporter)`", |
193 | -+ | 2x |
- #'+ "\n - `filter_panel_api` - module will receive `FilterPanelAPI`. (See [teal.slice::FilterPanelAPI]).", |
194 | -+ | 2x |
- #' @return (`string`) The active shiny name space of the component.+ "\n - `...` server_args elements will be passed to the module named argument or to the `...`" |
195 |
- active_module_ns = function() {+ ) |
||
196 | -! | +
- if (identical(private$ns$module, character(0))) {+ } |
|
197 | -! | +
- private$set_active_ns()+ |
|
198 | -+ | 214x |
- }+ if ("datasets" %in% server_formals) { |
199 | -! | +2x |
- private$ns$module+ warning( |
200 | -+ | 2x |
- },+ sprintf("Called from module(label = \"%s\", ...)\n ", label), |
201 | -+ | 2x |
- #' @description+ "`datasets` argument in the server is deprecated and will be removed in the next release. ", |
202 | -+ | 2x |
- #' Get the active shiny name space bound with a custom `element` name.+ "Please use `data` instead.", |
203 | -+ | 2x |
- #'+ call. = FALSE |
204 |
- #' @param element `character(1)` custom element name.+ ) |
||
205 |
- #'+ } |
||
206 |
- #' @return (`string`) The active shiny name space of the component bound with the input `element`.+ |
||
207 |
- active_module_element = function(element) {+ ## UI |
||
208 | -! | +214x |
- checkmate::assert_string(element)+ checkmate::assert_function(ui) |
209 | -! | +214x |
- sprintf("#%s-%s", self$active_module_ns(), element)+ ui_formals <- names(formals(ui)) |
210 | -+ | 214x |
- },+ if (!"id" %in% ui_formals) { |
211 | -+ | 1x |
- #' @description+ stop( |
212 | -+ | 1x |
- #' Get the text of the active shiny name space bound with a custom `element` name.+ "\nmodule() `ui` argument requires a function with following arguments:", |
213 | -+ | 1x |
- #'+ "\n - id - `teal` will set proper `shiny` namespace for this module.", |
214 | -+ | 1x |
- #' @param element `character(1)` the text of the custom element name.+ "\n\nFollowing arguments can be used optionally:", |
215 | -+ | 1x |
- #'+ "\n - `...` ui_args elements will be passed to the module argument of the same name or to the `...`" |
216 |
- #' @return (`string`) The text of the active shiny name space of the component bound with the input `element`.+ ) |
||
217 |
- active_module_element_text = function(element) {+ } |
||
218 | -! | +
- checkmate::assert_string(element)+ |
|
219 | -! | +213x |
- self$get_text(self$active_module_element(element))+ if (any(c("data", "datasets") %in% ui_formals)) { |
220 | -+ | 2x |
- },+ stop( |
221 | -+ | 2x |
- #' @description+ sprintf("Called from module(label = \"%s\", ...)\n ", label), |
222 | -+ | 2x |
- #' Get the active shiny name space for interacting with the filter panel.+ "UI with `data` or `datasets` argument is no longer accepted.\n ", |
223 | -+ | 2x |
- #'+ "If some UI inputs depend on data, please move the logic to your server instead.\n ", |
224 | -+ | 2x |
- #' @return (`string`) The active shiny name space of the component.+ "Possible solutions are renderUI() or updateXyzInput() functions." |
225 |
- active_filters_ns = function() {+ ) |
||
226 | -! | +
- if (identical(private$ns$filter_panel, character(0))) {+ } |
|
227 | -! | +
- private$set_active_ns()+ |
|
228 |
- }+ ## `filters` |
||
229 | -! | +211x |
- private$ns$filter_panel+ if (!missing(filters)) { |
230 | -+ | ! |
- },+ datanames <- filters |
231 | -+ | ! |
- #' @description+ msg <- |
232 | -+ | ! |
- #' Get the active shiny name space for interacting with the data-summary panel.+ "The `filters` argument is deprecated and will be removed in the next release. Please use `datanames` instead." |
233 | -+ | ! |
- #'+ warning(msg) |
234 |
- #' @return (`string`) The active shiny name space of the data-summary component.+ } |
||
235 |
- active_data_summary_ns = function() {+ |
||
236 | -! | +
- if (identical(private$ns$data_summary, character(0))) {+ ## `datanames` (also including deprecated `filters`) |
|
237 | -! | +
- private$set_active_ns()+ # please note a race condition between datanames set when filters is not missing and data arg in server function |
|
238 | -+ | 211x |
- }+ if (!is.element("data", server_formals) && !is.null(datanames)) { |
239 | -! | +12x |
- private$ns$data_summary+ message(sprintf("module \"%s\" server function takes no data so \"datanames\" will be ignored", label)) |
240 | -+ | 12x |
- },+ datanames <- NULL |
241 |
- #' @description+ } |
||
242 | -+ | 211x |
- #' Get the active shiny name space bound with a custom `element` name.+ checkmate::assert_character(datanames, min.len = 1, null.ok = TRUE, any.missing = FALSE) |
243 |
- #'+ |
||
244 |
- #' @param element `character(1)` custom element name.+ ## `server_args` |
||
245 | -+ | 210x |
- #'+ checkmate::assert_list(server_args, null.ok = TRUE, names = "named") |
246 | -+ | 208x |
- #' @return (`string`) The active shiny name space of the component bound with the input `element`.+ srv_extra_args <- setdiff(names(server_args), server_formals) |
247 | -+ | 208x |
- active_data_summary_element = function(element) {+ if (length(srv_extra_args) > 0 && !"..." %in% server_formals) { |
248 | -! | +1x |
- checkmate::assert_string(element)+ stop( |
249 | -! | +1x |
- sprintf("#%s-%s", self$active_data_summary_ns(), element)+ "\nFollowing `server_args` elements have no equivalent in the formals of the server:\n", |
250 | -+ | 1x |
- },+ paste(paste(" -", srv_extra_args), collapse = "\n"), |
251 | -+ | 1x |
- #' @description+ "\n\nUpdate the server arguments by including above or add `...`" |
252 |
- #' Get the input from the module in the `teal` app.+ ) |
||
253 |
- #' This function will only access inputs from the name space of the current active teal module.+ } |
||
254 |
- #'+ |
||
255 |
- #' @param input_id (character) The shiny input id to get the value from.+ ## `ui_args` |
||
256 | -+ | 207x |
- #'+ checkmate::assert_list(ui_args, null.ok = TRUE, names = "named") |
257 | -+ | 205x |
- #' @return The value of the shiny input.+ ui_extra_args <- setdiff(names(ui_args), ui_formals) |
258 | -+ | 205x |
- get_active_module_input = function(input_id) {+ if (length(ui_extra_args) > 0 && !"..." %in% ui_formals) { |
259 | -! | +1x |
- checkmate::check_string(input_id)+ stop( |
260 | -! | +1x |
- self$get_value(input = sprintf("%s-%s", self$active_module_ns(), input_id))+ "\nFollowing `ui_args` elements have no equivalent in the formals of UI:\n", |
261 | -+ | 1x |
- },+ paste(paste(" -", ui_extra_args), collapse = "\n"), |
262 | -+ | 1x |
- #' @description+ "\n\nUpdate the UI arguments by including above or add `...`" |
263 |
- #' Get the output from the module in the `teal` app.+ ) |
||
264 |
- #' This function will only access outputs from the name space of the current active teal module.+ } |
||
265 |
- #'+ |
||
266 |
- #' @param output_id (character) The shiny output id to get the value from.+ ## `transformators` |
||
267 | -+ | 204x |
- #'+ if (inherits(transformators, "teal_transform_module")) { |
268 | -+ | 1x |
- #' @return The value of the shiny output.+ transformators <- list(transformators) |
269 |
- get_active_module_output = function(output_id) {+ } |
||
270 | -! | +204x |
- checkmate::check_string(output_id)+ checkmate::assert_list(transformators, types = "teal_transform_module") |
271 | -! | +204x |
- self$get_value(output = sprintf("%s-%s", self$active_module_ns(), output_id))+ transform_datanames <- unlist(lapply(transformators, attr, "datanames")) |
272 | -+ | 204x |
- },+ combined_datanames <- if (identical(datanames, "all")) { |
273 | -+ | 151x |
- #' @description+ "all" |
274 |
- #' Get the output from the module's `teal.widgets::table_with_settings` or `DT::DTOutput` in the `teal` app.+ } else { |
||
275 | -+ | 53x |
- #' This function will only access outputs from the name space of the current active teal module.+ union(datanames, transform_datanames) |
276 |
- #'+ } |
||
277 |
- #' @param table_id (`character(1)`) The id of the table in the active teal module's name space.+ |
||
278 | -+ | 204x |
- #' @param which (integer) If there is more than one table, which should be extracted.+ structure( |
279 | -+ | 204x |
- #' By default it will look for a table that is built using `teal.widgets::table_with_settings`.+ list( |
280 | -+ | 204x |
- #'+ label = label, |
281 | -+ | 204x |
- #' @return The data.frame with table contents.+ server = server, |
282 | -+ | 204x |
- get_active_module_table_output = function(table_id, which = 1) {+ ui = ui, |
283 | -! | +204x |
- checkmate::check_number(which, lower = 1)+ datanames = combined_datanames, |
284 | -! | +204x |
- checkmate::check_string(table_id)+ server_args = server_args, |
285 | -! | +204x |
- table <- rvest::html_table(+ ui_args = ui_args, |
286 | -! | +204x |
- self$get_html_rvest(self$active_module_element(table_id)),+ transformators = transformators |
287 | -! | +
- fill = TRUE+ ), |
|
288 | -+ | 204x |
- )+ class = "teal_module" |
289 | -! | +
- if (length(table) == 0) {+ ) |
|
290 | -! | +
- data.frame()+ } |
|
291 |
- } else {+ |
||
292 | -! | +
- table[[which]]+ #' @rdname teal_modules |
|
293 |
- }+ #' @export |
||
294 |
- },+ #' |
||
295 |
- #' @description+ modules <- function(..., label = "root") { |
||
296 | -+ | 144x |
- #' Get the output from the module's `teal.widgets::plot_with_settings` in the `teal` app.+ checkmate::assert_string(label) |
297 | -+ | 142x |
- #' This function will only access plots from the name space of the current active teal module.+ submodules <- list(...) |
298 | -+ | 142x |
- #'+ if (any(vapply(submodules, is.character, FUN.VALUE = logical(1)))) { |
299 | -+ | 2x |
- #' @param plot_id (`character(1)`) The id of the plot in the active teal module's name space.+ stop( |
300 | -+ | 2x |
- #'+ "The only character argument to modules() must be 'label' and it must be named, ", |
301 | -+ | 2x |
- #' @return The `src` attribute as `character(1)` vector.+ "change modules('lab', ...) to modules(label = 'lab', ...)" |
302 |
- get_active_module_plot_output = function(plot_id) {+ ) |
||
303 | -! | +
- checkmate::check_string(plot_id)+ } |
|
304 | -! | +
- self$get_attr(+ |
|
305 | -! | +140x |
- self$active_module_element(sprintf("%s-plot_main > img", plot_id)),+ checkmate::assert_list(submodules, min.len = 1, any.missing = FALSE, types = c("teal_module", "teal_modules")) |
306 | -! | +
- "src"+ # name them so we can more easily access the children |
|
307 |
- )+ # beware however that the label of the submodules should not be changed as it must be kept synced |
||
308 | -+ | 137x |
- },+ labels <- vapply(submodules, function(submodule) submodule$label, character(1)) |
309 | -+ | 137x |
- #' @description+ names(submodules) <- get_unique_labels(labels) |
310 | -+ | 137x |
- #' Set the input in the module in the `teal` app.+ structure( |
311 | -+ | 137x |
- #' This function will only set inputs in the name space of the current active teal module.+ list( |
312 | -+ | 137x |
- #'+ label = label, |
313 | -+ | 137x |
- #' @param input_id (character) The shiny input id to get the value from.+ children = submodules |
314 |
- #' @param value The value to set the input to.+ ), |
||
315 | -+ | 137x |
- #' @param ... Additional arguments to be passed to `shinytest2::AppDriver$set_inputs`+ class = "teal_modules" |
316 |
- #'+ ) |
||
317 |
- #' @return The `TealAppDriver` object invisibly.+ } |
||
318 |
- set_active_module_input = function(input_id, value, ...) {+ |
||
319 | -! | +
- checkmate::check_string(input_id)+ # printing methods ---- |
|
320 | -! | +
- checkmate::check_string(value)+ |
|
321 | -! | +
- self$set_input(+ #' @rdname teal_modules |
|
322 | -! | +
- sprintf("%s-%s", self$active_module_ns(), input_id),+ #' @param is_last (`logical(1)`) Whether this is the last item in its parent's children list. |
|
323 | -! | +
- value,+ #' Affects the tree branch character used (L- vs |-) |
|
324 |
- ...+ #' @param parent_prefix (`character(1)`) The prefix inherited from parent nodes, |
||
325 |
- )+ #' used to maintain the tree structure in nested levels |
||
326 | -! | +
- dots <- rlang::list2(...)+ #' @param is_root (`logical(1)`) Whether this is the root node of the tree. Only used in |
|
327 | -! | +
- if (!isFALSE(dots[["wait"]])) self$wait_for_idle() # Default behavior is to wait+ #' format.teal_modules(). Determines whether to show "TEAL ROOT" header |
|
328 | -! | +
- invisible(self)+ #' @param what (`character`) Specifies which metadata to display. |
|
329 |
- },+ #' Possible values: "datasets", "properties", "ui_args", "server_args", "transformators" |
||
330 |
- #' @description+ #' @examples |
||
331 |
- #' Get the active datasets that can be accessed via the filter panel of the current active teal module.+ #' mod <- module( |
||
332 |
- get_active_filter_vars = function() {+ #' label = "My Custom Module", |
||
333 | -! | +
- displayed_datasets_index <- self$is_visible(+ #' server = function(id, data, ...) {}, |
|
334 | -! | +
- sprintf("#%s-filters-filter_active_vars_contents > span", self$active_filters_ns())+ #' ui = function(id, ...) {}, |
|
335 |
- )+ #' datanames = c("ADSL", "ADTTE"), |
||
336 |
-
+ #' transformators = list(), |
||
337 | -! | +
- available_datasets <- self$get_text(+ #' ui_args = list(a = 1, b = "b"), |
|
338 | -! | +
- sprintf(+ #' server_args = list(x = 5, y = list(p = 1)) |
|
339 | -! | +
- "#%s-filters-filter_active_vars_contents .filter_panel_dataname",+ #' ) |
|
340 | -! | +
- self$active_filters_ns()+ #' cat(format(mod)) |
|
341 |
- )+ #' @export |
||
342 |
- )+ format.teal_module <- function( |
||
343 |
-
+ x, is_last = FALSE, parent_prefix = "", |
||
344 | -! | +
- available_datasets[displayed_datasets_index]+ what = c("datasets", "properties", "ui_args", "server_args", "transformators"), ...) { |
|
345 | -+ | 3x |
- },+ empty_text <- "" |
346 | -+ | 3x |
- #' @description+ branch <- if (is_last) "L-" else "|-" |
347 | -+ | 3x |
- #' Get the active data summary table+ current_prefix <- paste0(parent_prefix, branch, " ") |
348 | -+ | 3x |
- #' @return `data.frame`+ content_prefix <- paste0(parent_prefix, if (is_last) " " else "| ") |
349 |
- get_active_data_summary_table = function() {+ |
||
350 | -! | +3x |
- summary_table <- rvest::html_table(+ format_list <- function(lst, empty = empty_text, label_width = 0) { |
351 | -! | +6x |
- self$get_html_rvest(self$active_data_summary_element("table")),+ if (is.null(lst) || length(lst) == 0) { |
352 | -! | +6x |
- fill = TRUE+ empty |
353 | -! | +
- )[[1]]+ } else { |
|
354 | -+ | ! |
-
+ colon_space <- paste(rep(" ", label_width), collapse = "") |
355 | -! | +
- col_names <- unlist(summary_table[1, ], use.names = FALSE)+ |
|
356 | ! |
- summary_table <- summary_table[-1, ]+ first_item <- sprintf("%s (%s)", names(lst)[1], crayon::silver(class(lst[[1]])[1])) |
|
357 | ! |
- colnames(summary_table) <- col_names+ rest_items <- if (length(lst) > 1) { |
|
358 | ! |
- if (nrow(summary_table) > 0) {+ paste( |
|
359 | ! |
- summary_table+ vapply( |
|
360 | -+ | ! |
- } else {+ names(lst)[-1], |
361 | ! |
- NULL+ function(name) { |
|
362 | -+ | ! |
- }+ sprintf( |
363 | -+ | ! |
- },+ "%s%s (%s)", |
364 | -+ | ! |
- #' @description+ paste0(content_prefix, "| ", colon_space), |
365 | -+ | ! |
- #' Test if `DOM` elements are visible on the page with a JavaScript call.+ name, |
366 | -+ | ! |
- #' @param selector (`character(1)`) `CSS` selector to check visibility.+ crayon::silver(class(lst[[name]])[1]) |
367 |
- #' A `CSS` id will return only one element if the UI is well formed.+ ) |
||
368 |
- #' @param content_visibility_auto,opacity_property,visibility_property (`logical(1)`) See more information+ }, |
||
369 | -+ | ! |
- #' on <https://developer.mozilla.org/en-US/docs/Web/API/Element/checkVisibility>.+ character(1) |
370 |
- #'+ ), |
||
371 | -+ | ! |
- #' @return Logical vector with all occurrences of the selector.+ collapse = "\n" |
372 |
- is_visible = function(selector,+ ) |
||
373 |
- content_visibility_auto = FALSE,+ } |
||
374 | -+ | ! |
- opacity_property = FALSE,+ if (length(lst) > 1) paste0(first_item, "\n", rest_items) else first_item |
375 |
- visibility_property = FALSE) {+ } |
||
376 | -! | +
- checkmate::assert_string(selector)+ } |
|
377 | -! | +
- checkmate::assert_flag(content_visibility_auto)+ |
|
378 | -! | +3x |
- checkmate::assert_flag(opacity_property)+ bookmarkable <- isTRUE(attr(x, "teal_bookmarkable")) |
379 | -! | +3x |
- checkmate::assert_flag(visibility_property)+ reportable <- "reporter" %in% names(formals(x$server)) |
381 | -! | +3x |
- private$wait_for_page_stability()+ transformators <- if (length(x$transformators) > 0) { |
382 | -+ | ! |
-
+ paste(sapply(x$transformators, function(t) attr(t, "label")), collapse = ", ") |
383 | -! | +
- testthat::skip_if_not(+ } else { |
|
384 | -! | +3x |
- self$get_js("typeof Element.prototype.checkVisibility === 'function'"),+ empty_text |
385 | -! | +
- "Element.prototype.checkVisibility is not supported in the current browser."+ } |
|
386 |
- )+ |
||
387 | -+ | 3x |
-
+ output <- pasten(current_prefix, crayon::bgWhite(x$label)) |
388 | -! | +
- unlist(+ |
|
389 | -! | +3x |
- self$get_js(+ if ("datasets" %in% what) { |
390 | -! | +3x |
- sprintf(+ output <- paste0( |
391 | -! | +3x |
- "Array.from(document.querySelectorAll('%s')).map(el => el.checkVisibility({%s, %s, %s}))",+ output, |
392 | -! | +3x |
- selector,+ content_prefix, "|- ", crayon::yellow("Datasets : "), paste(x$datanames, collapse = ", "), "\n" |
393 |
- # Extra parameters+ ) |
||
394 | -! | +
- sprintf("contentVisibilityAuto: %s", tolower(content_visibility_auto)),+ } |
|
395 | -! | +3x |
- sprintf("opacityProperty: %s", tolower(opacity_property)),+ if ("properties" %in% what) { |
396 | -! | +3x |
- sprintf("visibilityProperty: %s", tolower(visibility_property))+ output <- paste0( |
397 | -+ | 3x |
- )+ output, |
398 | -+ | 3x |
- )+ content_prefix, "|- ", crayon::blue("Properties:"), "\n", |
399 | -+ | 3x |
- )+ content_prefix, "| |- ", crayon::cyan("Bookmarkable : "), bookmarkable, "\n", |
400 | -+ | 3x |
- },+ content_prefix, "| L- ", crayon::cyan("Reportable : "), reportable, "\n" |
401 |
- #' @description+ ) |
||
402 |
- #' Get the active filter variables from a dataset in the `teal` app.+ } |
||
403 | -+ | 3x |
- #'+ if ("ui_args" %in% what) { |
404 | -+ | 3x |
- #' @param dataset_name (character) The name of the dataset to get the filter variables from.+ ui_args_formatted <- format_list(x$ui_args, label_width = 19) |
405 | -+ | 3x |
- #' If `NULL`, the filter variables for all the datasets will be returned in a list.+ output <- paste0( |
406 | -+ | 3x |
- get_active_data_filters = function(dataset_name = NULL) {+ output, |
407 | -! | +3x |
- checkmate::check_string(dataset_name, null.ok = TRUE)+ content_prefix, "|- ", crayon::green("UI Arguments : "), ui_args_formatted, "\n" |
408 | -! | +
- datasets <- self$get_active_filter_vars()+ ) |
|
409 | -! | +
- checkmate::assert_subset(dataset_name, datasets)+ } |
|
410 | -! | +3x |
- active_filters <- lapply(+ if ("server_args" %in% what) { |
411 | -! | +3x |
- datasets,+ server_args_formatted <- format_list(x$server_args, label_width = 19) |
412 | -! | +3x |
- function(x) {+ output <- paste0( |
413 | -! | +3x |
- var_names <- gsub(+ output, |
414 | -! | +3x |
- pattern = "\\s",+ content_prefix, "|- ", crayon::green("Server Arguments : "), server_args_formatted, "\n" |
415 | -! | +
- replacement = "",+ ) |
|
416 | -! | +
- self$get_text(+ } |
|
417 | -! | +3x |
- sprintf(+ if ("transformators" %in% what) { |
418 | -! | +3x |
- "#%s-filters-%s .filter-card-varname",+ output <- paste0( |
419 | -! | +3x |
- self$active_filters_ns(),+ output, |
420 | -! | +3x |
- x+ content_prefix, "L- ", crayon::magenta("Transformators : "), transformators, "\n" |
421 |
- )+ ) |
||
422 |
- )+ } |
||
423 |
- )+ |
||
424 | -! | +3x |
- structure(+ output |
425 | -! | +
- lapply(var_names, private$get_active_filter_selection, dataset_name = x),+ } |
|
426 | -! | +
- names = var_names+ |
|
427 |
- )+ #' @rdname teal_modules |
||
428 |
- }+ #' @examples |
||
429 |
- )+ #' custom_module <- function( |
||
430 | -! | +
- names(active_filters) <- datasets+ #' label = "label", ui_args = NULL, server_args = NULL, |
|
431 | -! | +
- if (is.null(dataset_name)) {+ #' datanames = "all", transformators = list(), bk = FALSE) { |
|
432 | -! | +
- return(active_filters)+ #' ans <- module( |
|
433 |
- }+ #' label, |
||
434 | -! | +
- active_filters[[dataset_name]]+ #' server = function(id, data, ...) {}, |
|
435 |
- },+ #' ui = function(id, ...) { |
||
436 |
- #' @description+ #' }, |
||
437 |
- #' Add a new variable from the dataset to be filtered.+ #' datanames = datanames, |
||
438 |
- #'+ #' transformators = transformators, |
||
439 |
- #' @param dataset_name (character) The name of the dataset to add the filter variable to.+ #' ui_args = ui_args, |
||
440 |
- #' @param var_name (character) The name of the variable to add to the filter panel.+ #' server_args = server_args |
||
441 |
- #' @param ... Additional arguments to be passed to `shinytest2::AppDriver$set_inputs`+ #' ) |
||
442 |
- #'+ #' attr(ans, "teal_bookmarkable") <- bk |
||
443 |
- #' @return The `TealAppDriver` object invisibly.+ #' ans |
||
444 |
- add_filter_var = function(dataset_name, var_name, ...) {+ #' } |
||
445 | -! | +
- checkmate::check_string(dataset_name)+ #' |
|
446 | -! | +
- checkmate::check_string(var_name)+ #' dummy_transformator <- teal_transform_module( |
|
447 | -! | +
- private$set_active_ns()+ #' label = "Dummy Transform", |
|
448 | -! | +
- self$click(+ #' ui = function(id) div("(does nothing)"), |
|
449 | -! | +
- selector = sprintf(+ #' server = function(id, data) { |
|
450 | -! | +
- "#%s-filters-%s-add_filter_icon",+ #' moduleServer(id, function(input, output, session) data) |
|
451 | -! | +
- private$ns$filter_panel,+ #' } |
|
452 | -! | +
- dataset_name+ #' ) |
|
453 |
- )+ #' |
||
454 |
- )+ #' plot_transformator <- teal_transform_module( |
||
455 | -! | +
- self$set_input(+ #' label = "Plot Settings", |
|
456 | -! | +
- sprintf(+ #' ui = function(id) div("(does nothing)"), |
|
457 | -! | +
- "%s-filters-%s-%s-filter-var_to_add",+ #' server = function(id, data) { |
|
458 | -! | +
- private$ns$filter_panel,+ #' moduleServer(id, function(input, output, session) data) |
|
459 | -! | +
- dataset_name,+ #' } |
|
460 | -! | +
- dataset_name+ #' ) |
|
461 |
- ),+ #' |
||
462 | -! | +
- var_name,+ #' complete_modules <- modules( |
|
463 |
- ...+ #' custom_module( |
||
464 |
- )+ #' label = "Data Overview", |
||
465 | -! | +
- invisible(self)+ #' datanames = c("ADSL", "ADAE", "ADVS"), |
|
466 |
- },+ #' ui_args = list( |
||
467 |
- #' @description+ #' view_type = "table", |
||
468 |
- #' Remove an active filter variable of a dataset from the active filter variables panel.+ #' page_size = 10, |
||
469 |
- #'+ #' filters = c("ARM", "SEX", "RACE") |
||
470 |
- #' @param dataset_name (character) The name of the dataset to remove the filter variable from.+ #' ), |
||
471 |
- #' If `NULL`, all the filter variables will be removed.+ #' server_args = list( |
||
472 |
- #' @param var_name (character) The name of the variable to remove from the filter panel.+ #' cache = TRUE, |
||
473 |
- #' If `NULL`, all the filter variables of the dataset will be removed.+ #' debounce = 1000 |
||
474 |
- #'+ #' ), |
||
475 |
- #' @return The `TealAppDriver` object invisibly.+ #' transformators = list(dummy_transformator), |
||
476 |
- remove_filter_var = function(dataset_name = NULL, var_name = NULL) {+ #' bk = TRUE |
||
477 | -! | +
- checkmate::check_string(dataset_name, null.ok = TRUE)+ #' ), |
|
478 | -! | +
- checkmate::check_string(var_name, null.ok = TRUE)+ #' modules( |
|
479 | -! | +
- if (is.null(dataset_name)) {+ #' label = "Nested 1", |
|
480 | -! | +
- remove_selector <- sprintf(+ #' custom_module( |
|
481 | -! | +
- "#%s-active-remove_all_filters",+ #' label = "Interactive Plots", |
|
482 | -! | +
- self$active_filters_ns()+ #' datanames = c("ADSL", "ADVS"), |
|
483 |
- )+ #' ui_args = list( |
||
484 | -! | +
- } else if (is.null(var_name)) {+ #' plot_type = c("scatter", "box", "line"), |
|
485 | -! | +
- remove_selector <- sprintf(+ #' height = 600, |
|
486 | -! | +
- "#%s-active-%s-remove_filters",+ #' width = 800, |
|
487 | -! | +
- self$active_filters_ns(),+ #' color_scheme = "viridis" |
|
488 | -! | +
- dataset_name+ #' ), |
|
489 |
- )+ #' server_args = list( |
||
490 |
- } else {+ #' render_type = "svg", |
||
491 | -! | +
- remove_selector <- sprintf(+ #' cache_plots = TRUE |
|
492 | -! | +
- "#%s-active-%s-filter-%s_%s-remove",+ #' ), |
|
493 | -! | +
- self$active_filters_ns(),+ #' transformators = list(dummy_transformator, plot_transformator), |
|
494 | -! | +
- dataset_name,+ #' bk = TRUE |
|
495 | -! | +
- dataset_name,+ #' ), |
|
496 | -! | +
- var_name+ #' modules( |
|
497 |
- )+ #' label = "Nested 2", |
||
498 |
- }+ #' custom_module( |
||
499 | -! | +
- self$click(+ #' label = "Summary Statistics", |
|
500 | -! | +
- selector = remove_selector+ #' datanames = "ADSL", |
|
501 |
- )+ #' ui_args = list( |
||
502 | -! | +
- invisible(self)+ #' stats = c("mean", "median", "sd", "range"), |
|
503 |
- },+ #' grouping = c("ARM", "SEX") |
||
504 |
- #' @description+ #' ) |
||
505 |
- #' Set the active filter values for a variable of a dataset in the active filter variable panel.+ #' ), |
||
506 |
- #'+ #' modules( |
||
507 |
- #' @param dataset_name (character) The name of the dataset to set the filter value for.+ #' label = "Labeled nested modules", |
||
508 |
- #' @param var_name (character) The name of the variable to set the filter value for.+ #' custom_module( |
||
509 |
- #' @param input The value to set the filter to.+ #' label = "Subgroup Analysis", |
||
510 |
- #' @param ... Additional arguments to be passed to `shinytest2::AppDriver$set_inputs`+ #' datanames = c("ADSL", "ADAE"), |
||
511 |
- #'+ #' ui_args = list( |
||
512 |
- #' @return The `TealAppDriver` object invisibly.+ #' subgroups = c("AGE", "SEX", "RACE"), |
||
513 |
- set_active_filter_selection = function(dataset_name,+ #' analysis_type = "stratified" |
||
514 |
- var_name,+ #' ), |
||
515 |
- input,+ #' bk = TRUE |
||
516 |
- ...) {+ #' ) |
||
517 | -! | +
- checkmate::check_string(dataset_name)+ #' ), |
|
518 | -! | +
- checkmate::check_string(var_name)+ #' modules(custom_module(label = "Subgroup Analysis in non-labled modules")) |
|
519 | -! | +
- checkmate::check_string(input)+ #' ) |
|
520 |
-
+ #' ), |
||
521 | -! | +
- input_id_prefix <- sprintf(+ #' custom_module("Non-nested module") |
|
522 | -! | +
- "%s-filters-%s-filter-%s_%s-inputs",+ #' ) |
|
523 | -! | +
- self$active_filters_ns(),+ #' |
|
524 | -! | +
- dataset_name,+ #' cat(format(complete_modules)) |
|
525 | -! | +
- dataset_name,+ #' cat(format(complete_modules, what = c("ui_args", "server_args", "transformators"))) |
|
526 | -! | +
- var_name+ #' @export |
|
527 |
- )+ format.teal_modules <- function(x, is_root = TRUE, is_last = FALSE, parent_prefix = "", ...) { |
||
528 | -+ | 1x |
-
+ if (is_root) { |
529 | -+ | 1x |
- # Find the type of filter (based on filter panel)+ header <- pasten(crayon::bold("TEAL ROOT")) |
530 | -! | +1x |
- supported_suffix <- c("selection", "selection_manual")+ new_parent_prefix <- " " #' Initial indent for root level |
531 | -! | +
- slices_suffix <- supported_suffix[+ } else { |
|
532 | ! |
- match(+ if (!is.null(x$label)) { |
|
533 | ! |
- TRUE,+ branch <- if (is_last) "L-" else "|-" |
|
534 | ! |
- vapply(+ header <- pasten(parent_prefix, branch, " ", crayon::bold(x$label)) |
|
535 | ! |
- supported_suffix,+ new_parent_prefix <- paste0(parent_prefix, if (is_last) " " else "| ") |
|
536 | -! | +
- function(suffix) {+ } else { |
|
537 | ! |
- !is.null(self$get_html(sprintf("#%s-%s", input_id_prefix, suffix)))+ header <- "" |
|
538 | -+ | ! |
- },+ new_parent_prefix <- parent_prefix |
539 | -! | +
- logical(1)+ } |
|
540 |
- )+ } |
||
541 |
- )+ |
||
542 | -+ | 1x |
- ]+ if (length(x$children) > 0) { |
543 | -+ | 1x |
-
+ children_output <- character(0) |
544 | -+ | 1x |
- # Generate correct namespace+ n_children <- length(x$children) |
545 | -! | +
- slices_input_id <- sprintf(+ |
|
546 | -! | +1x |
- "%s-filters-%s-filter-%s_%s-inputs-%s",+ for (i in seq_along(x$children)) { |
547 | -! | +3x |
- self$active_filters_ns(),+ child <- x$children[[i]] |
548 | -! | +3x |
- dataset_name,+ is_last_child <- (i == n_children) |
549 | -! | +
- dataset_name,+ |
|
550 | -! | +3x |
- var_name,+ if (inherits(child, "teal_modules")) { |
551 | ! |
- slices_suffix+ children_output <- c( |
|
552 | -+ | ! |
- )+ children_output, |
553 | -+ | ! |
-
+ format(child, |
554 | ! |
- if (identical(slices_suffix, "selection_manual")) {+ is_root = FALSE, |
|
555 | ! |
- checkmate::assert_numeric(input, len = 2)+ is_last = is_last_child, |
|
556 | -+ | ! |
-
+ parent_prefix = new_parent_prefix, |
557 | -! | +
- dots <- rlang::list2(...)+ ... |
|
558 | -! | +
- checkmate::assert_choice(dots$priority_, formals(self$set_inputs)[["priority_"]], null.ok = TRUE)+ ) |
|
559 | -! | +
- checkmate::assert_flag(dots$wait_, null.ok = TRUE)+ ) |
|
560 |
-
+ } else { |
||
561 | -! | +3x |
- self$run_js(+ children_output <- c( |
562 | -! | +3x |
- sprintf(+ children_output, |
563 | -! | +3x |
- "Shiny.setInputValue('%s:sw.numericRange', [%f, %f], {priority: '%s'})",+ format(child, |
564 | -! | +3x |
- slices_input_id,+ is_last = is_last_child, |
565 | -! | +3x |
- input[[1]],+ parent_prefix = new_parent_prefix, |
566 | -! | +
- input[[2]],+ ... |
|
567 | -! | +
- priority_ = ifelse(is.null(dots$priority_), "input", dots$priority_)+ ) |
|
568 |
- )+ ) |
||
569 |
- )+ } |
||
570 |
-
+ } |
||
571 | -! | +
- if (isTRUE(dots$wait_) || is.null(dots$wait_)) {+ |
|
572 | -! | +1x |
- self$wait_for_idle(+ paste0(header, paste(children_output, collapse = "")) |
573 | -! | +
- timeout = if (is.null(dots$timeout_)) rlang::missing_arg() else dots$timeout_+ } else { |
|
574 | -+ | ! |
- )+ header |
575 |
- }+ } |
||
576 | -! | +
- } else if (identical(slices_suffix, "selection")) {+ } |
|
577 | -! | +
- self$set_input(+ |
|
578 | -! | +
- slices_input_id,+ #' @rdname teal_modules |
|
579 | -! | +
- input,+ #' @export |
|
580 |
- ...+ print.teal_module <- function(x, ...) { |
||
581 | -+ | ! |
- )+ cat(format(x, ...)) |
582 | -+ | ! |
- } else {+ invisible(x) |
583 | -! | +
- stop("Filter selection set not supported for this slice.")+ } |
|
584 |
- }+ |
||
585 |
-
+ #' @rdname teal_modules |
||
586 | -! | +
- invisible(self)+ #' @export |
|
587 |
- },+ print.teal_modules <- function(x, ...) { |
||
588 | -+ | ! |
- #' @description+ cat(format(x, ...)) |
589 | -+ | ! |
- #' Extract `html` attribute (found by a `selector`).+ invisible(x) |
590 |
- #'+ } |
||
591 |
- #' @param selector (`character(1)`) specifying the selector to be used to get the content of a specific node.+ |
||
592 |
- #' @param attribute (`character(1)`) name of an attribute to retrieve from a node specified by `selector`.+ #' @param modules (`teal_module` or `teal_modules`) |
||
593 |
- #'+ #' @rdname teal_modules |
||
594 |
- #' @return The `character` vector.+ #' @examples |
||
595 |
- get_attr = function(selector, attribute) {+ #' # change the module's datanames |
||
596 | -! | +
- rvest::html_attr(+ #' set_datanames(module(datanames = "all"), "a") |
|
597 | -! | +
- rvest::html_nodes(self$get_html_rvest("html"), selector),+ #' |
|
598 | -! | +
- attribute+ #' # change modules' datanames |
|
599 |
- )+ #' set_datanames( |
||
600 |
- },+ #' modules( |
||
601 |
- #' @description+ #' module(datanames = "all"), |
||
602 |
- #' Wrapper around `get_html` that passes the output directly to `rvest::read_html`.+ #' module(datanames = "a") |
||
603 |
- #'+ #' ), |
||
604 |
- #' @param selector `(character(1))` passed to `get_html`.+ #' "b" |
||
605 |
- #'+ #' ) |
||
606 |
- #' @return An XML document.+ #' @export |
||
607 |
- get_html_rvest = function(selector) {+ set_datanames <- function(modules, datanames) { |
||
608 | ! |
- rvest::read_html(self$get_html(selector))+ checkmate::assert_multi_class(modules, c("teal_modules", "teal_module")) |
|
609 | -+ | ! |
- },+ if (inherits(modules, "teal_modules")) { |
610 | -+ | ! |
- #' Wrapper around `get_url()` method that opens the app in the browser.+ modules$children <- lapply(modules$children, set_datanames, datanames) |
611 |
- #'+ } else { |
||
612 | -+ | ! |
- #' @return Nothing. Opens the underlying teal app in the browser.+ if (identical(modules$datanames, "all")) { |
613 | -+ | ! |
- open_url = function() {+ modules$datanames <- datanames |
614 | -! | +
- browseURL(self$get_url())+ } else { |
|
615 | -+ | ! |
- },+ warning( |
616 | -+ | ! |
- #' @description+ "Not possible to modify datanames of the module ", modules$label, |
617 | -+ | ! |
- #' Waits until a specified input, output, or export value.+ ". set_datanames() can only change datanames if it was set to \"all\".", |
618 | -+ | ! |
- #' This function serves as a wrapper around the `wait_for_value` method,+ call. = FALSE |
619 |
- #' providing a more flexible interface for waiting on different types of values within the active module namespace.+ ) |
||
620 |
- #' @param input,output,export A name of an input, output, or export value.+ } |
||
621 |
- #' Only one of these parameters may be used.+ } |
||
622 | -+ | ! |
- #' @param ... Must be empty. Allows for parameter expansion.+ modules |
623 |
- #' Parameter with additional value to passed in `wait_for_value`.+ } |
||
624 |
- wait_for_active_module_value = function(input = rlang::missing_arg(),+ |
||
625 |
- output = rlang::missing_arg(),+ # utilities ---- |
||
626 |
- export = rlang::missing_arg(),+ ## subset or modify modules ---- |
||
627 |
- ...) {+ |
||
628 | -! | +
- ns <- shiny::NS(self$active_module_ns())+ #' Append a `teal_module` to `children` of a `teal_modules` object |
|
629 |
-
+ #' @keywords internal |
||
630 | -! | +
- if (!rlang::is_missing(input) && checkmate::test_string(input, min.chars = 1)) input <- ns(input)+ #' @param modules (`teal_modules`) |
|
631 | -! | +
- if (!rlang::is_missing(output) && checkmate::test_string(output, min.chars = 1)) output <- ns(output)+ #' @param module (`teal_module`) object to be appended onto the children of `modules` |
|
632 | -! | +
- if (!rlang::is_missing(export) && checkmate::test_string(export, min.chars = 1)) export <- ns(export)+ #' @return A `teal_modules` object with `module` appended. |
|
633 |
-
+ append_module <- function(modules, module) { |
||
634 | -! | +8x |
- self$wait_for_value(+ checkmate::assert_class(modules, "teal_modules") |
635 | -! | +6x |
- input = input,+ checkmate::assert_class(module, "teal_module") |
636 | -! | +4x |
- output = output,+ modules$children <- c(modules$children, list(module)) |
637 | -! | +4x |
- export = export,+ labels <- vapply(modules$children, function(submodule) submodule$label, character(1)) |
638 | -+ | 4x |
- ...+ names(modules$children) <- get_unique_labels(labels) |
639 | -+ | 4x |
- )+ modules |
640 |
- }+ } |
||
641 |
- ),+ |
||
642 |
- # private members ----+ #' Extract/Remove module(s) of specific class |
||
643 |
- private = list(+ #' |
||
644 |
- # private attributes ----+ #' Given a `teal_module` or a `teal_modules`, return the elements of the structure according to `class`. |
||
645 |
- data = NULL,+ #' |
||
646 |
- modules = NULL,+ #' @param modules (`teal_modules`) |
||
647 |
- filter = teal_slices(),+ #' @param class The class name of `teal_module` to be extracted or dropped. |
||
648 |
- ns = list(+ #' @keywords internal |
||
649 |
- module = character(0),+ #' @return |
||
650 |
- filter_panel = character(0)+ #' - For `extract_module`, a `teal_module` of class `class` or `teal_modules` containing modules of class `class`. |
||
651 |
- ),+ #' - For `drop_module`, the opposite, which is all `teal_modules` of class other than `class`. |
||
652 |
- # private methods ----+ #' @rdname module_management |
||
653 |
- set_active_ns = function() {+ extract_module <- function(modules, class) { |
||
654 | -! | +28x |
- all_inputs <- self$get_values()$input+ if (inherits(modules, class)) { |
655 | ! |
- active_tab_inputs <- all_inputs[grepl("-active_tab$", names(all_inputs))]+ modules |
|
656 | -+ | 28x |
-
+ } else if (inherits(modules, "teal_module")) { |
657 | -! | +15x |
- tab_ns <- unlist(lapply(names(active_tab_inputs), function(name) {+ NULL |
658 | -! | +13x |
- gsub(+ } else if (inherits(modules, "teal_modules")) { |
659 | -! | +13x |
- pattern = "-active_tab$",+ Filter(function(x) length(x) > 0L, lapply(modules$children, extract_module, class)) |
660 | -! | +
- replacement = sprintf("-%s", active_tab_inputs[[name]]),+ } |
|
661 | -! | +
- name+ } |
|
662 |
- )+ |
||
663 |
- }))+ #' @keywords internal |
||
664 | -! | +
- active_ns <- tab_ns[1]+ #' @return `teal_modules` |
|
665 | -! | +
- if (length(tab_ns) > 1) {+ #' @rdname module_management |
|
666 | -! | +
- for (i in 2:length(tab_ns)) {+ drop_module <- function(modules, class) { |
|
667 | ! |
- next_ns <- tab_ns[i]+ if (inherits(modules, class)) { |
|
668 | ! |
- if (grepl(pattern = active_ns, next_ns)) {+ NULL |
|
669 | ! |
- active_ns <- next_ns+ } else if (inherits(modules, "teal_module")) { |
|
670 | -+ | ! |
- }+ modules |
671 | -+ | ! |
- }+ } else if (inherits(modules, "teal_modules")) { |
672 | -+ | ! |
- }+ do.call( |
673 | ! |
- private$ns$module <- sprintf("%s-%s", active_ns, "module")+ "modules", |
|
674 | -+ | ! |
-
+ c(Filter(function(x) length(x) > 0L, lapply(modules$children, drop_module, class)), label = modules$label) |
675 | -! | +
- components <- c("filter_panel", "data_summary")+ ) |
|
676 | -! | +
- for (component in components) {+ } |
|
677 |
- if (+ } |
||
678 | -! | +
- !is.null(self$get_html(sprintf("#%s-%s-panel", active_ns, component))) ||+ |
|
679 | -! | +
- !is.null(self$get_html(sprintf("#%s-%s-table", active_ns, component)))+ ## read modules ---- |
|
680 |
- ) {+ |
||
681 | -! | +
- private$ns[[component]] <- sprintf("%s-%s", active_ns, component)+ #' Does the object make use of the `arg` |
|
682 |
- } else {+ #' |
||
683 | -! | +
- private$ns[[component]] <- sprintf("%s-module_%s", active_ns, component)+ #' @param modules (`teal_module` or `teal_modules`) object |
|
684 |
- }+ #' @param arg (`character(1)`) names of the arguments to be checked against formals of `teal` modules. |
||
685 |
- }+ #' @return `logical` whether the object makes use of `arg`. |
||
686 |
- },+ #' @rdname is_arg_used |
||
687 |
- # @description+ #' @keywords internal |
||
688 |
- # Get the active filter values from the active filter selection of dataset from the filter panel.+ is_arg_used <- function(modules, arg) { |
||
689 | -+ | 519x |
- #+ checkmate::assert_string(arg) |
690 | -+ | 516x |
- # @param dataset_name (character) The name of the dataset to get the filter values from.+ if (inherits(modules, "teal_modules")) { |
691 | -+ | 20x |
- # @param var_name (character) The name of the variable to get the filter values from.+ any(unlist(lapply(modules$children, is_arg_used, arg))) |
692 | -+ | 496x |
- #+ } else if (inherits(modules, "teal_module")) { |
693 | -+ | 32x |
- # @return The value of the active filter selection.+ is_arg_used(modules$server, arg) || is_arg_used(modules$ui, arg) |
694 | -+ | 464x |
- get_active_filter_selection = function(dataset_name, var_name) {+ } else if (is.function(modules)) { |
695 | -! | +462x |
- checkmate::check_string(dataset_name)+ isTRUE(arg %in% names(formals(modules))) |
696 | -! | +
- checkmate::check_string(var_name)+ } else { |
|
697 | -! | +2x |
- input_id_prefix <- sprintf(+ stop("is_arg_used function not implemented for this object") |
698 | -! | +
- "%s-filters-%s-filter-%s_%s-inputs",+ } |
|
699 | -! | +
- self$active_filters_ns(),+ } |
|
700 | -! | +
- dataset_name,+ |
|
701 | -! | +
- dataset_name,+ |
|
702 | -! | +
- var_name+ #' Get module depth |
|
703 |
- )+ #' |
||
704 |
-
+ #' Depth starts at 0, so a single `teal.module` has depth 0. |
||
705 |
- # Find the type of filter (categorical or range)+ #' Nesting it increases overall depth by 1. |
||
706 | -! | +
- supported_suffix <- c("selection", "selection_manual")+ #' |
|
707 | -! | +
- for (suffix in supported_suffix) {+ #' @inheritParams init |
|
708 | -! | +
- if (!is.null(self$get_html(sprintf("#%s-%s", input_id_prefix, suffix)))) {+ #' @param depth optional integer determining current depth level |
|
709 | -! | +
- return(self$get_value(input = sprintf("%s-%s", input_id_prefix, suffix)))+ #' |
|
710 |
- }+ #' @return Depth level for given module. |
||
711 |
- }+ #' @keywords internal |
||
712 |
-
+ modules_depth <- function(modules, depth = 0L) { |
||
713 | -! | +12x |
- NULL # If there are not any supported filters+ checkmate::assert_multi_class(modules, c("teal_module", "teal_modules")) |
714 | -+ | 12x |
- },+ checkmate::assert_int(depth, lower = 0) |
715 | -+ | 11x |
- # @description+ if (inherits(modules, "teal_modules")) { |
716 | -+ | 4x |
- # Check if the page is stable without any `DOM` updates in the body of the app.+ max(vapply(modules$children, modules_depth, integer(1), depth = depth + 1L)) |
717 |
- # This is achieved by blocing the R process by sleeping until the page is unchanged till the `stability_period`.+ } else { |
||
718 | -+ | 7x |
- # @param stability_period (`numeric(1)`) The time in milliseconds to wait till the page to be stable.+ depth |
719 |
- # @param check_interval (`numeric(1)`) The time in milliseconds to check for changes in the page.+ } |
||
720 |
- # The stability check is reset when a change is detected in the page after sleeping for check_interval.+ } |
||
721 |
- wait_for_page_stability = function(stability_period = 2000, check_interval = 200) {+ |
||
722 | -! | +
- previous_content <- self$get_html("body")+ #' Retrieve labels from `teal_modules` |
|
723 | -! | +
- end_time <- Sys.time() + (stability_period / 1000)+ #' |
|
724 |
-
+ #' @param modules (`teal_modules`) |
||
725 | -! | +
- repeat {+ #' @return A `list` containing the labels of the modules. If the modules are nested, |
|
726 | -! | +
- Sys.sleep(check_interval / 1000)+ #' the function returns a nested `list` of labels. |
|
727 | -! | +
- current_content <- self$get_html("body")+ #' @keywords internal |
|
728 |
-
+ module_labels <- function(modules) { |
||
729 | -! | +199x |
- if (!identical(previous_content, current_content)) {+ if (inherits(modules, "teal_modules")) { |
730 | -! | +87x |
- previous_content <- current_content+ lapply(modules$children, module_labels) |
731 | -! | +
- end_time <- Sys.time() + (stability_period / 1000)+ } else { |
|
732 | -! | +112x |
- } else if (Sys.time() >= end_time) {+ modules$label |
733 | -! | +
- break+ } |
|
734 |
- }+ } |
||
735 |
- }+ |
||
736 |
- }+ #' Retrieve `teal_bookmarkable` attribute from `teal_modules` |
||
737 |
- )+ #' |
||
738 |
- )+ #' @param modules (`teal_modules` or `teal_module`) object+ |
+ ||
739 | ++ |
+ #' @return named list of the same structure as `modules` with `TRUE` or `FALSE` values indicating+ |
+ |
740 | ++ |
+ #' whether the module is bookmarkable.+ |
+ |
741 | ++ |
+ #' @keywords internal+ |
+ |
742 | ++ |
+ modules_bookmarkable <- function(modules) {+ |
+ |
743 | +199x | +
+ checkmate::assert_multi_class(modules, c("teal_modules", "teal_module"))+ |
+ |
744 | +199x | +
+ if (inherits(modules, "teal_modules")) {+ |
+ |
745 | +87x | +
+ setNames(+ |
+ |
746 | +87x | +
+ lapply(modules$children, modules_bookmarkable),+ |
+ |
747 | +87x | +
+ vapply(modules$children, `[[`, "label", FUN.VALUE = character(1))+ |
+ |
748 | ++ |
+ )+ |
+ |
749 | ++ |
+ } else {+ |
+ |
750 | +112x | +
+ attr(modules, "teal_bookmarkable", exact = TRUE)+ |
+ |
751 | ++ |
+ }+ |
+ |
752 | ++ |
+ } |
1 |
- #' Landing popup module+ # FilteredData ------ |
||
2 |
- #'+ |
||
3 |
- #' @description Creates a landing welcome popup for `teal` applications.+ #' Drive a `teal` application |
||
5 |
- #' This module is used to display a popup dialog when the application starts.+ #' Extension of the `shinytest2::AppDriver` class with methods for |
||
6 |
- #' The dialog blocks access to the application and must be closed with a button before the application can be viewed.+ #' driving a teal application for performing interactions for `shinytest2` tests. |
||
8 |
- #' @param label (`character(1)`) Label of the module.+ #' @keywords internal |
||
9 |
- #' @param title (`character(1)`) Text to be displayed as popup title.+ #' |
||
10 |
- #' @param content (`character(1)`, `shiny.tag` or `shiny.tag.list`) with the content of the popup.+ TealAppDriver <- R6::R6Class( # nolint: object_name. |
||
11 |
- #' Passed to `...` of `shiny::modalDialog`. See examples.+ "TealAppDriver", |
||
12 |
- #' @param buttons (`shiny.tag` or `shiny.tag.list`) Typically a `modalButton` or `actionButton`. See examples.+ inherit = { |
||
13 |
- #'+ if (!requireNamespace("shinytest2", quietly = TRUE)) { |
||
14 |
- #' @return A `teal_module` (extended with `teal_landing_module` class) to be used in `teal` applications.+ stop("Please install 'shinytest2' package to use this class.") |
||
15 |
- #'+ } |
||
16 |
- #' @examples+ if (!requireNamespace("rvest", quietly = TRUE)) { |
||
17 |
- #' app1 <- init(+ stop("Please install 'rvest' package to use this class.") |
||
18 |
- #' data = teal_data(iris = iris),+ } |
||
19 |
- #' modules = modules(+ shinytest2::AppDriver |
||
20 |
- #' example_module()+ }, |
||
21 |
- #' ),+ # public methods ---- |
||
22 |
- #' landing_popup = landing_popup_module(+ public = list( |
||
23 |
- #' content = "A place for the welcome message or a disclaimer statement.",+ #' @description |
||
24 |
- #' buttons = modalButton("Proceed")+ #' Initialize a `TealAppDriver` object for testing a `teal` application. |
||
25 |
- #' )+ #' |
||
26 |
- #' )+ #' @param data,modules,filter,title,header,footer,landing_popup arguments passed to `init` |
||
27 |
- #' if (interactive()) {+ #' @param timeout (`numeric`) Default number of milliseconds for any timeout or |
||
28 |
- #' shinyApp(app1$ui, app1$server)+ #' timeout_ parameter in the `TealAppDriver` class. |
||
29 |
- #' }+ #' Defaults to 20s. |
||
30 |
- #'+ #' |
||
31 |
- #' app2 <- init(+ #' See [`shinytest2::AppDriver`] `new` method for more details on how to change it |
||
32 |
- #' data = teal_data(iris = iris),+ #' via options or environment variables. |
||
33 |
- #' modules = modules(+ #' @param load_timeout (`numeric`) How long to wait for the app to load, in ms. |
||
34 |
- #' example_module()+ #' This includes the time to start R. Defaults to 100s. |
||
35 |
- #' ),+ #' |
||
36 |
- #' landing_popup = landing_popup_module(+ #' See [`shinytest2::AppDriver`] `new` method for more details on how to change it |
||
37 |
- #' title = "Welcome",+ #' via options or environment variables |
||
38 |
- #' content = tags$b(+ #' @param ... Additional arguments to be passed to `shinytest2::AppDriver$new` |
||
39 |
- #' "A place for the welcome message or a disclaimer statement.",+ #' |
||
40 |
- #' style = "color: red;"+ #' |
||
41 |
- #' ),+ #' @return Object of class `TealAppDriver` |
||
42 |
- #' buttons = tagList(+ initialize = function(data, |
||
43 |
- #' modalButton("Proceed"),+ modules, |
||
44 |
- #' actionButton("read", "Read more",+ filter = teal_slices(), |
||
45 |
- #' onclick = "window.open('http://google.com', '_blank')"+ title = build_app_title(), |
||
46 |
- #' ),+ header = tags$p(), |
||
47 |
- #' actionButton("close", "Reject", onclick = "window.close()")+ footer = tags$p(), |
||
48 |
- #' )+ landing_popup = NULL, |
||
49 |
- #' )+ timeout = rlang::missing_arg(), |
||
50 |
- #' )+ load_timeout = rlang::missing_arg(), |
||
51 |
- #'+ ...) { |
||
52 | -+ | ! |
- #' if (interactive()) {+ private$data <- data |
53 | -+ | ! |
- #' shinyApp(app2$ui, app2$server)+ private$modules <- modules |
54 | -+ | ! |
- #' }+ private$filter <- filter |
55 | -+ | ! |
- #'+ app <- init( |
56 | -+ | ! |
- #' @export+ data = data, |
57 | -+ | ! |
- landing_popup_module <- function(label = "Landing Popup",+ modules = modules, |
58 | -+ | ! |
- title = NULL,+ filter = filter, |
59 | -+ | ! |
- content = NULL,+ title = title, |
60 | -+ | ! |
- buttons = modalButton("Accept")) {+ header = header, |
61 | ! |
- checkmate::assert_string(label)+ footer = footer, |
|
62 | ! |
- checkmate::assert_string(title, null.ok = TRUE)+ landing_popup = landing_popup, |
|
63 | -! | +
- checkmate::assert_multi_class(+ ) |
|
64 | -! | +
- content,+ |
|
65 | -! | +
- classes = c("character", "shiny.tag", "shiny.tag.list", "html"), null.ok = TRUE+ # Default timeout is hardcoded to 4s in shinytest2:::resolve_timeout |
|
66 |
- )+ # It must be set as parameter to the AppDriver |
||
67 | ! |
- checkmate::assert_multi_class(buttons, classes = c("shiny.tag", "shiny.tag.list"))+ suppressWarnings( |
|
68 | -+ | ! |
-
+ super$initialize( |
69 | ! |
- message("Initializing landing_popup_module")+ app_dir = shinyApp(app$ui, app$server), |
|
70 | -+ | ! |
-
+ name = "teal", |
71 | ! |
- module <- module(+ variant = shinytest2::platform_variant(), |
|
72 | ! |
- label = label,+ timeout = rlang::maybe_missing(timeout, 20 * 1000), |
|
73 | ! |
- server = function(id) {+ load_timeout = rlang::maybe_missing(load_timeout, 100 * 1000), |
|
74 | -! | +
- moduleServer(id, function(input, output, session) {+ ... |
|
75 | -! | +
- showModal(+ ) |
|
76 | -! | +
- modalDialog(+ ) |
|
77 | ++ | + + | +|
78 | ++ |
+ # Check for minimum version of Chrome that supports the tests+ |
+ |
79 | ++ |
+ # - Element.checkVisibility was added on 105+ |
+ |
80 | ! |
- id = "landingpopup",+ chrome_version <- numeric_version( |
|
78 | +81 | ! |
- title = title,+ gsub( |
79 | +82 | ! |
- content,+ "[[:alnum:]_]+/", # Prefix that ends with forward slash+ |
+
83 | ++ |
+ "", |
|
80 | +84 | ! |
- footer = buttons+ self$get_chromote_session()$Browser$getVersion()$product |
81 | +85 |
- )+ ),+ |
+ |
86 | +! | +
+ strict = FALSE |
|
82 | +87 |
- )+ ) |
|
83 | +88 |
- })+ + |
+ |
89 | +! | +
+ required_version <- "121" |
|
84 | +90 |
- }+ + |
+ |
91 | +! | +
+ testthat::skip_if(+ |
+ |
92 | +! | +
+ is.na(chrome_version),+ |
+ |
93 | +! | +
+ "Problem getting Chrome version, please contact the developers." |
|
85 | +94 |
- )+ ) |
|
86 | +95 | ! |
- class(module) <- c("teal_module_landing", class(module))+ testthat::skip_if( |
87 | +96 | ! |
- module+ chrome_version < required_version,+ |
+
97 | +! | +
+ sprintf(+ |
+ |
98 | +! | +
+ "Chrome version '%s' is not supported, please upgrade to '%s' or higher",+ |
+ |
99 | +! | +
+ chrome_version,+ |
+ |
100 | +! | +
+ required_version |
|
88 | +101 |
- }+ ) |
1 | +102 |
- #' App state management.+ ) |
|
2 | +103 |
- #'+ # end od check |
|
3 | +104 |
- #' @description+ + |
+ |
105 | +! | +
+ private$set_active_ns()+ |
+ |
106 | +! | +
+ self$wait_for_idle() |
|
4 | +107 |
- #' `r lifecycle::badge("experimental")`+ }, |
|
5 | +108 |
- #'+ #' @description |
|
6 | +109 |
- #' Capture and restore the global (app) input state.+ #' Append parent [`shinytest2::AppDriver`] `click` method with a call to `waif_for_idle()` method. |
|
7 | +110 |
- #'+ #' @param ... arguments passed to parent [`shinytest2::AppDriver`] `click()` method. |
|
8 | +111 |
- #' @details+ click = function(...) {+ |
+ |
112 | +! | +
+ super$click(...)+ |
+ |
113 | +! | +
+ private$wait_for_page_stability() |
|
9 | +114 |
- #' This module introduces bookmarks into `teal` apps: the `shiny` bookmarking mechanism becomes enabled+ }, |
|
10 | +115 |
- #' and server-side bookmarks can be created.+ #' @description |
|
11 | +116 |
- #'+ #' Check if the app has shiny errors. This checks for global shiny errors. |
|
12 | +117 |
- #' The bookmark manager presents a button with the bookmark icon and is placed in the tab-bar.+ #' Note that any shiny errors dependent on shiny server render will only be captured after the teal module tab |
|
13 | +118 |
- #' When clicked, the button creates a bookmark and opens a modal which displays the bookmark URL.+ #' is visited because shiny will not trigger server computations when the tab is invisible. |
|
14 | +119 |
- #'+ #' So, navigate to the module tab you want to test before calling this function. |
|
15 | +120 |
- #' `teal` does not guarantee that all modules (`teal_module` objects) are bookmarkable.+ #' Although, this catches errors hidden in the other module tabs if they are already rendered. |
|
16 | +121 |
- #' Those that are, have a `teal_bookmarkable` attribute set to `TRUE`. If any modules are not bookmarkable,+ expect_no_shiny_error = function() {+ |
+ |
122 | +! | +
+ testthat::expect_null(+ |
+ |
123 | +! | +
+ self$get_html(".shiny-output-error:not(.shiny-output-error-validation)"),+ |
+ |
124 | +! | +
+ info = "Shiny error is observed" |
|
17 | +125 |
- #' the bookmark manager modal displays a warning and the bookmark button displays a flag.+ ) |
|
18 | +126 |
- #' In order to communicate that a external module is bookmarkable, the module developer+ }, |
|
19 | +127 |
- #' should set the `teal_bookmarkable` attribute to `TRUE`.+ #' @description |
|
20 | +128 |
- #'+ #' Check if the app has no validation errors. This checks for global shiny validation errors. |
|
21 | +129 |
- #' @section Server logic:+ expect_no_validation_error = function() {+ |
+ |
130 | +! | +
+ testthat::expect_null(+ |
+ |
131 | +! | +
+ self$get_html(".shiny-output-error-validation"),+ |
+ |
132 | +! | +
+ info = "No validation error is observed" |
|
22 | +133 |
- #' A bookmark is a URL that contains the app address with a `/?_state_id_=<bookmark_dir>` suffix.+ ) |
|
23 | +134 |
- #' `<bookmark_dir>` is a directory created on the server, where the state of the application is saved.+ }, |
|
24 | +135 |
- #' Accessing the bookmark URL opens a new session of the app that starts in the previously saved state.+ #' @description |
|
25 | +136 |
- #'+ #' Check if the app has validation errors. This checks for global shiny validation errors. |
|
26 | +137 |
- #' @section Note:+ expect_validation_error = function() {+ |
+ |
138 | +! | +
+ testthat::expect_false(+ |
+ |
139 | +! | +
+ is.null(self$get_html(".shiny-output-error-validation")),+ |
+ |
140 | +! | +
+ info = "Validation error is not observed" |
|
27 | +141 |
- #' To enable bookmarking use either:+ ) |
|
28 | +142 |
- #' - `shiny` app by using `shinyApp(..., enableBookmarking = "server")` (not supported in `shinytest2`)+ }, |
|
29 | +143 |
- #' - set `options(shiny.bookmarkStore = "server")` before running the app+ #' @description |
|
30 | +144 |
- #'+ #' Set the input in the `teal` app. |
|
31 | +145 |
- #'+ #' |
|
32 | +146 |
- #' @inheritParams init+ #' @param input_id (character) The shiny input id with it's complete name space.+ |
+ |
147 | ++ |
+ #' @param value The value to set the input to. |
|
33 | +148 |
- #'+ #' @param ... Additional arguments to be passed to `shinytest2::AppDriver$set_inputs` |
|
34 | +149 |
- #' @return Invisible `NULL`.+ #' |
|
35 | +150 |
- #'+ #' @return The `TealAppDriver` object invisibly. |
|
36 | +151 |
- #' @aliases bookmark bookmark_manager bookmark_manager_module+ set_input = function(input_id, value, ...) { |
|
37 | -+ | ||
152 | +! |
- #'+ do.call( |
|
38 | -+ | ||
153 | +! |
- #' @name module_bookmark_manager+ self$set_inputs, |
|
39 | -+ | ||
154 | +! |
- #' @rdname module_bookmark_manager+ c(setNames(list(value), input_id), list(...)) |
|
40 | +155 |
- #'+ ) |
|
41 | -+ | ||
156 | +! |
- #' @keywords internal+ invisible(self) |
|
42 | +157 |
- #'+ }, |
|
43 | +158 |
- NULL+ #' @description |
|
44 | +159 |
-
+ #' Navigate the teal tabs in the `teal` app. |
|
45 | +160 |
- #' @rdname module_bookmark_manager+ #' |
|
46 | +161 |
- ui_bookmark_panel <- function(id, modules) {+ #' @param tabs (character) Labels of tabs to navigate to. The order of the tabs is important, |
|
47 | -! | +||
162 | +
- ns <- NS(id)+ #' and it should start with the most parent level tab. |
||
48 | +163 |
-
+ #' Note: In case the teal tab group has duplicate names, the first tab will be selected, |
|
49 | -! | +||
164 | +
- bookmark_option <- get_bookmarking_option()+ #' If you wish to select the second tab with the same name, use the suffix "_1". |
||
50 | -! | +||
165 | +
- is_unbookmarkable <- need_bookmarking(modules)+ #' If you wish to select the third tab with the same name, use the suffix "_2" and so on. |
||
51 | -! | +||
166 | +
- shinyOptions(bookmarkStore = bookmark_option)+ #' |
||
52 | +167 |
-
+ #' @return The `TealAppDriver` object invisibly. |
|
53 | +168 |
- # Render bookmark warnings count+ navigate_teal_tab = function(tabs) { |
|
54 | +169 | ! |
- if (!all(is_unbookmarkable) && identical(bookmark_option, "server")) {+ checkmate::check_character(tabs, min.len = 1) |
55 | +170 | ! |
- tags$button(+ for (tab in tabs) { |
56 | +171 | ! |
- id = ns("do_bookmark"),+ self$set_input( |
57 | +172 | ! |
- class = "btn action-button wunder_bar_button bookmark_manager_button",+ "teal-teal_modules-active_tab", |
58 | +173 | ! |
- title = "Add bookmark",+ get_unique_labels(tab), |
59 | +174 | ! |
- tags$span(+ wait_ = FALSE |
60 | -! | +||
175 | +
- suppressMessages(icon("fas fa-bookmark")),+ ) |
||
61 | -! | +||
176 | +
- if (any(is_unbookmarkable)) {+ } |
||
62 | +177 | ! |
- tags$span(+ self$wait_for_idle() |
63 | +178 | ! |
- sum(is_unbookmarkable),+ private$set_active_ns() |
64 | +179 | ! |
- class = "badge-warning badge-count text-white bg-danger"+ invisible(self) |
65 | +180 |
- )+ }, |
|
66 | +181 |
- }+ #' @description |
|
67 | +182 |
- )+ #' Get the active shiny name space for different components of the teal app. |
|
68 | +183 |
- )+ #' |
|
69 | +184 |
- }+ #' @return (`list`) The list of active shiny name space of the teal components. |
|
70 | +185 |
- }+ active_ns = function() { |
|
71 | -+ | ||
186 | +! |
-
+ if (identical(private$ns$module, character(0))) { |
|
72 | -+ | ||
187 | +! |
- #' @rdname module_bookmark_manager+ private$set_active_ns() |
|
73 | +188 |
- srv_bookmark_panel <- function(id, modules) {- |
- |
74 | -87x | -
- checkmate::assert_character(id)- |
- |
75 | -87x | -
- checkmate::assert_class(modules, "teal_modules")- |
- |
76 | -87x | -
- moduleServer(id, function(input, output, session) {- |
- |
77 | -87x | -
- logger::log_debug("bookmark_manager_srv initializing")- |
- |
78 | -87x | -
- ns <- session$ns- |
- |
79 | -87x | -
- bookmark_option <- get_bookmarking_option()+ } |
|
80 | -87x | +||
189 | +! |
- is_unbookmarkable <- need_bookmarking(modules)+ private$ns |
|
81 | +190 |
-
+ }, |
|
82 | +191 |
- # Set up bookmarking callbacks ----+ #' @description |
|
83 | +192 |
- # Register bookmark exclusions: do_bookmark button to avoid re-bookmarking- |
- |
84 | -87x | -
- setBookmarkExclude(c("do_bookmark"))+ #' Get the active shiny name space for interacting with the module content. |
|
85 | +193 |
- # This bookmark can only be used on the app session.+ #' |
|
86 | -87x | +||
194 | +
- app_session <- .subset2(session, "parent")+ #' @return (`string`) The active shiny name space of the component. |
||
87 | -87x | +||
195 | +
- app_session$onBookmarked(function(url) {+ active_module_ns = function() { |
||
88 | +196 | ! |
- logger::log_debug("bookmark_manager_srv@onBookmarked: bookmark button clicked, registering bookmark")+ if (identical(private$ns$module, character(0))) { |
89 | +197 | ! |
- modal_content <- if (bookmark_option != "server") {+ private$set_active_ns() |
90 | -! | +||
198 | +
- msg <- sprintf(+ } |
||
91 | +199 | ! |
- "Bookmarking has been set to \"%s\".\n%s\n%s",+ private$ns$module |
92 | -! | +||
200 | +
- bookmark_option,+ }, |
||
93 | -! | +||
201 | +
- "Only server-side bookmarking is supported.",+ #' @description |
||
94 | -! | +||
202 | +
- "Please contact your app developer."+ #' Get the active shiny name space bound with a custom `element` name. |
||
95 | +203 |
- )+ #' |
|
96 | -! | +||
204 | +
- tags$div(+ #' @param element `character(1)` custom element name. |
||
97 | -! | +||
205 | +
- tags$p(msg, class = "text-warning")+ #' |
||
98 | +206 |
- )+ #' @return (`string`) The active shiny name space of the component bound with the input `element`. |
|
99 | +207 |
- } else {+ active_module_element = function(element) { |
|
100 | +208 | ! |
- tags$div(+ checkmate::assert_string(element) |
101 | +209 | ! |
- tags$span(+ sprintf("#%s-%s", self$active_module_ns(), element) |
102 | -! | +||
210 | +
- tags$pre(url)+ }, |
||
103 | +211 |
- ),+ #' @description |
|
104 | -! | +||
212 | +
- if (any(is_unbookmarkable)) {+ #' Get the text of the active shiny name space bound with a custom `element` name. |
||
105 | -! | +||
213 | +
- bkmb_summary <- rapply2(+ #' |
||
106 | -! | +||
214 | +
- modules_bookmarkable(modules),+ #' @param element `character(1)` the text of the custom element name. |
||
107 | -! | +||
215 | +
- function(x) {+ #' |
||
108 | -! | +||
216 | +
- if (isTRUE(x)) {+ #' @return (`string`) The text of the active shiny name space of the component bound with the input `element`. |
||
109 | -! | +||
217 | +
- "\u2705" # check mark+ active_module_element_text = function(element) { |
||
110 | +218 | ! |
- } else if (isFALSE(x)) {+ checkmate::assert_string(element) |
111 | +219 | ! |
- "\u274C" # cross mark+ self$get_text(self$active_module_element(element)) |
112 | +220 |
- } else {- |
- |
113 | -! | -
- "\u2753" # question mark+ }, |
|
114 | +221 |
- }+ #' @description |
|
115 | +222 |
- }+ #' Get the active shiny name space for interacting with the filter panel. |
|
116 | +223 |
- )- |
- |
117 | -! | -
- tags$div(- |
- |
118 | -! | -
- tags$p(- |
- |
119 | -! | -
- icon("fas fa-exclamation-triangle"),+ #' |
|
120 | -! | +||
224 | +
- "Some modules will not be restored when using this bookmark.",+ #' @return (`string`) The active shiny name space of the component. |
||
121 | -! | +||
225 | +
- tags$br(),+ active_filters_ns = function() { |
||
122 | +226 | ! |
- "Check the list below to see which modules are not bookmarkable.",+ if (identical(private$ns$filter_panel, character(0))) { |
123 | +227 | ! |
- class = "text-warning"+ private$set_active_ns() |
124 | +228 |
- ),+ } |
|
125 | +229 | ! |
- tags$pre(yaml::as.yaml(bkmb_summary))+ private$ns$filter_panel |
126 | +230 |
- )+ }, |
|
127 | +231 |
- }+ #' @description |
|
128 | +232 |
- )+ #' Get the active shiny name space for interacting with the data-summary panel. |
|
129 | +233 |
- }+ #' |
|
130 | +234 |
-
+ #' @return (`string`) The active shiny name space of the data-summary component. |
|
131 | -! | +||
235 | +
- showModal(+ active_data_summary_ns = function() { |
||
132 | +236 | ! |
- modalDialog(+ if (identical(private$ns$data_summary, character(0))) { |
133 | +237 | ! |
- id = ns("bookmark_modal"),+ private$set_active_ns() |
134 | -! | +||
238 | +
- title = "Bookmarked teal app url",+ } |
||
135 | +239 | ! |
- modal_content,+ private$ns$data_summary |
136 | -! | +||
240 | +
- easyClose = TRUE+ }, |
||
137 | +241 |
- )+ #' @description |
|
138 | +242 |
- )+ #' Get the active shiny name space bound with a custom `element` name. |
|
139 | +243 |
- })+ #' |
|
140 | +244 |
-
+ #' @param element `character(1)` custom element name. |
|
141 | +245 |
- # manually trigger bookmarking because of the problems reported on windows with bookmarkButton in teal+ #' |
|
142 | -87x | +||
246 | +
- observeEvent(input$do_bookmark, {+ #' @return (`string`) The active shiny name space of the component bound with the input `element`.+ |
+ ||
247 | ++ |
+ active_data_summary_element = function(element) { |
|
143 | +248 | ! |
- logger::log_debug("bookmark_manager_srv@1 do_bookmark module clicked.")+ checkmate::assert_string(element) |
144 | +249 | ! |
- session$doBookmark()+ sprintf("#%s-%s", self$active_data_summary_ns(), element) |
145 | +250 |
- })+ }, |
|
146 | +251 |
-
+ #' @description |
|
147 | -87x | +||
252 | +
- invisible(NULL)+ #' Get the input from the module in the `teal` app. |
||
148 | +253 |
- })+ #' This function will only access inputs from the name space of the current active teal module. |
|
149 | +254 |
- }+ #' |
|
150 | +255 |
-
+ #' @param input_id (character) The shiny input id to get the value from. |
|
151 | +256 |
-
+ #' |
|
152 | +257 |
- #' @rdname module_bookmark_manager+ #' @return The value of the shiny input. |
|
153 | +258 |
- get_bookmarking_option <- function() {+ get_active_module_input = function(input_id) { |
|
154 | -87x | +||
259 | +! |
- bookmark_option <- getShinyOption("bookmarkStore")+ checkmate::check_string(input_id) |
|
155 | -87x | +||
260 | +! |
- if (is.null(bookmark_option) && identical(getOption("shiny.bookmarkStore"), "server")) {+ self$get_value(input = sprintf("%s-%s", self$active_module_ns(), input_id)) |
|
156 | -! | +||
261 | +
- bookmark_option <- getOption("shiny.bookmarkStore")+ }, |
||
157 | +262 |
- }+ #' @description |
|
158 | -87x | +||
263 | +
- bookmark_option+ #' Get the output from the module in the `teal` app. |
||
159 | +264 |
- }+ #' This function will only access outputs from the name space of the current active teal module. |
|
160 | +265 |
-
+ #' |
|
161 | +266 |
- #' @rdname module_bookmark_manager+ #' @param output_id (character) The shiny output id to get the value from. |
|
162 | +267 |
- need_bookmarking <- function(modules) {+ #' |
|
163 | -87x | +||
268 | +
- unlist(rapply2(+ #' @return The value of the shiny output. |
||
164 | -87x | +||
269 | +
- modules_bookmarkable(modules),+ get_active_module_output = function(output_id) { |
||
165 | -87x | +||
270 | +! |
- Negate(isTRUE)+ checkmate::check_string(output_id) |
|
166 | -+ | ||
271 | +! |
- ))+ self$get_value(output = sprintf("%s-%s", self$active_module_ns(), output_id)) |
|
167 | +272 |
- }+ }, |
|
168 | +273 |
-
+ #' @description |
|
169 | +274 |
-
+ #' Get the output from the module's `teal.widgets::table_with_settings` or `DT::DTOutput` in the `teal` app. |
|
170 | +275 |
- # utilities ----+ #' This function will only access outputs from the name space of the current active teal module. |
|
171 | +276 |
-
+ #' |
|
172 | +277 |
- #' Restore value from bookmark.+ #' @param table_id (`character(1)`) The id of the table in the active teal module's name space. |
|
173 | +278 |
- #'+ #' @param which (integer) If there is more than one table, which should be extracted. |
|
174 | +279 |
- #' Get value from bookmark or return default.+ #' By default it will look for a table that is built using `teal.widgets::table_with_settings`. |
|
175 | +280 |
- #'+ #' |
|
176 | +281 |
- #' Bookmarks can store not only inputs but also arbitrary values.+ #' @return The data.frame with table contents. |
|
177 | +282 |
- #' These values are stored by `onBookmark` callbacks and restored by `onBookmarked` callbacks,+ get_active_module_table_output = function(table_id, which = 1) { |
|
178 | -+ | ||
283 | +! |
- #' and they are placed in the `values` environment in the `session$restoreContext` field.+ checkmate::check_number(which, lower = 1) |
|
179 | -+ | ||
284 | +! |
- #' Using `teal_data_module` makes it impossible to run the callbacks+ checkmate::check_string(table_id) |
|
180 | -+ | ||
285 | +! |
- #' because the app becomes ready before modules execute and callbacks are registered.+ table <- rvest::html_table( |
|
181 | -+ | ||
286 | +! |
- #' In those cases the stored values can still be recovered from the `session` object directly.+ self$get_html_rvest(self$active_module_element(table_id)), |
|
182 | -+ | ||
287 | +! |
- #'+ fill = TRUE |
|
183 | +288 |
- #' Note that variable names in the `values` environment are prefixed with module name space names,+ ) |
|
184 | -+ | ||
289 | +! |
- #' therefore, when using this function in modules, `value` must be run through the name space function.+ if (length(table) == 0) { |
|
185 | -+ | ||
290 | +! |
- #'+ data.frame() |
|
186 | +291 |
- #' @param value (`character(1)`) name of value to restore+ } else {+ |
+ |
292 | +! | +
+ table[[which]] |
|
187 | +293 |
- #' @param default fallback value+ } |
|
188 | +294 |
- #'+ }, |
|
189 | +295 |
- #' @return+ #' @description |
|
190 | +296 |
- #' In an application restored from a server-side bookmark,+ #' Get the output from the module's `teal.widgets::plot_with_settings` in the `teal` app. |
|
191 | +297 |
- #' the variable specified by `value` from the `values` environment.+ #' This function will only access plots from the name space of the current active teal module. |
|
192 | +298 |
- #' Otherwise `default`.+ #' |
|
193 | +299 |
- #'+ #' @param plot_id (`character(1)`) The id of the plot in the active teal module's name space. |
|
194 | +300 |
- #' @keywords internal+ #' |
|
195 | +301 |
- #'+ #' @return The `src` attribute as `character(1)` vector. |
|
196 | +302 |
- restoreValue <- function(value, default) { # nolint: object_name.+ get_active_module_plot_output = function(plot_id) { |
|
197 | -174x | +||
303 | +! |
- checkmate::assert_character("value")+ checkmate::check_string(plot_id) |
|
198 | -174x | +||
304 | +! |
- session_default <- shiny::getDefaultReactiveDomain()+ self$get_attr( |
|
199 | -174x | +||
305 | +! |
- session_parent <- .subset2(session_default, "parent")+ self$active_module_element(sprintf("%s-plot_main > img", plot_id)), |
|
200 | -174x | +||
306 | +! |
- session <- if (is.null(session_parent)) session_default else session_parent+ "src" |
|
201 | +307 |
-
+ ) |
|
202 | -174x | +||
308 | +
- if (isTRUE(session$restoreContext$active) && exists(value, session$restoreContext$values, inherits = FALSE)) {+ }, |
||
203 | -! | +||
309 | +
- session$restoreContext$values[[value]]+ #' @description |
||
204 | +310 |
- } else {+ #' Set the input in the module in the `teal` app. |
|
205 | -174x | +||
311 | +
- default+ #' This function will only set inputs in the name space of the current active teal module. |
||
206 | +312 |
- }+ #' |
|
207 | +313 |
- }+ #' @param input_id (character) The shiny input id to get the value from. |
|
208 | +314 |
-
+ #' @param value The value to set the input to. |
|
209 | +315 |
- #' Compare bookmarks.+ #' @param ... Additional arguments to be passed to `shinytest2::AppDriver$set_inputs`+ |
+ |
316 | ++ |
+ #'+ |
+ |
317 | ++ |
+ #' @return The `TealAppDriver` object invisibly.+ |
+ |
318 | ++ |
+ set_active_module_input = function(input_id, value, ...) {+ |
+ |
319 | +! | +
+ checkmate::check_string(input_id)+ |
+ |
320 | +! | +
+ checkmate::check_string(value)+ |
+ |
321 | +! | +
+ self$set_input( |
|
210 | -+ | ||
322 | +! |
- #'+ sprintf("%s-%s", self$active_module_ns(), input_id), |
|
211 | -+ | ||
323 | +! |
- #' Test if two bookmarks store identical state.+ value, |
|
212 | +324 |
- #'+ ... |
|
213 | +325 |
- #' `input` environments are compared one variable at a time and if not identical,+ ) |
|
214 | -+ | ||
326 | +! |
- #' values in both bookmarks are reported. States of `datatable`s are stripped+ dots <- rlang::list2(...) |
|
215 | -+ | ||
327 | +! |
- #' of the `time` element before comparing because the time stamp is always different.+ if (!isFALSE(dots[["wait"]])) self$wait_for_idle() # Default behavior is to wait |
|
216 | -+ | ||
328 | +! |
- #' The contents themselves are not printed as they are large and the contents are not informative.+ invisible(self) |
|
217 | +329 |
- #' Elements present in one bookmark and absent in the other are also reported.+ }, |
|
218 | +330 |
- #' Differences are printed as messages.+ #' @description |
|
219 | +331 |
- #'+ #' Get the active datasets that can be accessed via the filter panel of the current active teal module. |
|
220 | +332 |
- #' `values` environments are compared with `all.equal`.+ get_active_filter_vars = function() { |
|
221 | -+ | ||
333 | +! |
- #'+ displayed_datasets_index <- self$is_visible( |
|
222 | -+ | ||
334 | +! |
- #' @section How to use:+ sprintf("#%s-filters-filter_active_vars_contents > span", self$active_filters_ns()) |
|
223 | +335 |
- #' Open an application, change relevant inputs (typically, all of them), and create a bookmark.+ ) |
|
224 | +336 |
- #' Then open that bookmark and immediately create a bookmark of that.+ |
|
225 | -+ | ||
337 | +! |
- #' If restoring bookmarks occurred properly, the two bookmarks should store the same state.+ available_datasets <- self$get_text( |
|
226 | -+ | ||
338 | +! |
- #'+ sprintf( |
|
227 | -+ | ||
339 | +! |
- #'+ "#%s-filters-filter_active_vars_contents .filter_panel_dataname", |
|
228 | -+ | ||
340 | +! |
- #' @param book1,book2 bookmark directories stored in `shiny_bookmarks/`;+ self$active_filters_ns() |
|
229 | +341 |
- #' default to the two most recently modified directories+ ) |
|
230 | +342 |
- #'+ ) |
|
231 | +343 |
- #' @return+ |
|
232 | -+ | ||
344 | +! |
- #' Invisible `NULL` if bookmarks are identical or if there are no bookmarks to test.+ available_datasets[displayed_datasets_index] |
|
233 | +345 |
- #' `FALSE` if inconsistencies are detected.+ }, |
|
234 | +346 |
- #'+ #' @description |
|
235 | +347 |
- #' @keywords internal+ #' Get the active data summary table |
|
236 | +348 |
- #'+ #' @return `data.frame` |
|
237 | +349 |
- bookmarks_identical <- function(book1, book2) {+ get_active_data_summary_table = function() { |
|
238 | +350 | ! |
- if (!dir.exists("shiny_bookmarks")) {+ summary_table <- rvest::html_table( |
239 | +351 | ! |
- message("no bookmark directory")+ self$get_html_rvest(self$active_data_summary_element("table")), |
240 | +352 | ! |
- return(invisible(NULL))+ fill = TRUE |
241 | -+ | ||
353 | +! |
- }+ )[[1]] |
|
242 | +354 | ||
243 | +355 | ! |
- ans <- TRUE- |
-
244 | -- |
-
+ col_names <- unlist(summary_table[1, ], use.names = FALSE) |
|
245 | +356 | ! |
- if (missing(book1) && missing(book2)) {+ summary_table <- summary_table[-1, ] |
246 | +357 | ! |
- dirs <- list.dirs("shiny_bookmarks", recursive = FALSE)+ colnames(summary_table) <- col_names |
247 | +358 | ! |
- bookmarks_sorted <- basename(rev(dirs[order(file.mtime(dirs))]))+ if (nrow(summary_table) > 0) { |
248 | +359 | ! |
- if (length(bookmarks_sorted) < 2L) {+ summary_table |
249 | -! | +||
360 | +
- message("no bookmarks to compare")+ } else { |
||
250 | +361 | ! |
- return(invisible(NULL))+ NULL |
251 | +362 |
- }+ } |
|
252 | -! | +||
363 | +
- book1 <- bookmarks_sorted[2L]+ }, |
||
253 | -! | +||
364 | +
- book2 <- bookmarks_sorted[1L]+ #' @description |
||
254 | +365 |
- } else {+ #' Test if `DOM` elements are visible on the page with a JavaScript call. |
|
255 | -! | +||
366 | +
- if (!dir.exists(file.path("shiny_bookmarks", book1))) stop(book1, " not found")+ #' @param selector (`character(1)`) `CSS` selector to check visibility. |
||
256 | -! | +||
367 | +
- if (!dir.exists(file.path("shiny_bookmarks", book2))) stop(book2, " not found")+ #' A `CSS` id will return only one element if the UI is well formed. |
||
257 | +368 |
- }+ #' @param content_visibility_auto,opacity_property,visibility_property (`logical(1)`) See more information |
|
258 | +369 |
-
+ #' on <https://developer.mozilla.org/en-US/docs/Web/API/Element/checkVisibility>. |
|
259 | -! | +||
370 | +
- book1_input <- readRDS(file.path("shiny_bookmarks", book1, "input.rds"))+ #' |
||
260 | -! | +||
371 | +
- book2_input <- readRDS(file.path("shiny_bookmarks", book2, "input.rds"))+ #' @return Logical vector with all occurrences of the selector. |
||
261 | +372 |
-
+ is_visible = function(selector, |
|
262 | -! | +||
373 | +
- elements_common <- intersect(names(book1_input), names(book2_input))+ content_visibility_auto = FALSE, |
||
263 | -! | +||
374 | +
- dt_states <- grepl("_state$", elements_common)+ opacity_property = FALSE, |
||
264 | -! | +||
375 | +
- if (any(dt_states)) {+ visibility_property = FALSE) { |
||
265 | +376 | ! |
- for (el in elements_common[dt_states]) {+ checkmate::assert_string(selector) |
266 | +377 | ! |
- book1_input[[el]][["time"]] <- NULL+ checkmate::assert_flag(content_visibility_auto) |
267 | +378 | ! |
- book2_input[[el]][["time"]] <- NULL- |
-
268 | -- |
- }+ checkmate::assert_flag(opacity_property) |
|
269 | -+ | ||
379 | +! |
- }+ checkmate::assert_flag(visibility_property) |
|
270 | +380 | ||
271 | -! | -
- identicals <- mapply(identical, book1_input[elements_common], book2_input[elements_common])- |
- |
272 | +381 | ! |
- non_identicals <- names(identicals[!identicals])+ private$wait_for_page_stability() |
273 | -! | +||
382 | +
- compares <- sprintf("$ %s:\t%s --- %s", non_identicals, book1_input[non_identicals], book2_input[non_identicals])+ |
||
274 | +383 | ! |
- if (length(compares) != 0L) {+ testthat::skip_if_not( |
275 | +384 | ! |
- message("common elements not identical: \n", paste(compares, collapse = "\n"))+ self$get_js("typeof Element.prototype.checkVisibility === 'function'"), |
276 | +385 | ! |
- ans <- FALSE+ "Element.prototype.checkVisibility is not supported in the current browser." |
277 | +386 |
- }+ ) |
|
278 | +387 | ||
279 | -! | -
- elements_boook1 <- setdiff(names(book1_input), names(book2_input))- |
- |
280 | +388 | ! |
- if (length(elements_boook1) != 0L) {+ unlist( |
281 | +389 | ! |
- dt_states <- grepl("_state$", elements_boook1)+ self$get_js( |
282 | +390 | ! |
- if (any(dt_states)) {+ sprintf( |
283 | +391 | ! |
- for (el in elements_boook1[dt_states]) {+ "Array.from(document.querySelectorAll('%s')).map(el => el.checkVisibility({%s, %s, %s}))", |
284 | +392 | ! |
- if (is.list(book1_input[[el]])) book1_input[[el]] <- "--- data table state ---"- |
-
285 | -- |
- }+ selector, |
|
286 | +393 |
- }+ # Extra parameters |
|
287 | +394 | ! |
- excess1 <- sprintf("$ %s:\t%s", elements_boook1, book1_input[elements_boook1])+ sprintf("contentVisibilityAuto: %s", tolower(content_visibility_auto)), |
288 | +395 | ! |
- message("elements only in book1: \n", paste(excess1, collapse = "\n"))+ sprintf("opacityProperty: %s", tolower(opacity_property)), |
289 | +396 | ! |
- ans <- FALSE+ sprintf("visibilityProperty: %s", tolower(visibility_property)) |
290 | +397 |
- }+ ) |
|
291 | +398 |
-
+ ) |
|
292 | -! | +||
399 | +
- elements_boook2 <- setdiff(names(book2_input), names(book1_input))+ ) |
||
293 | -! | +||
400 | +
- if (length(elements_boook2) != 0L) {+ }, |
||
294 | -! | +||
401 | +
- dt_states <- grepl("_state$", elements_boook1)+ #' @description |
||
295 | -! | +||
402 | +
- if (any(dt_states)) {+ #' Get the active filter variables from a dataset in the `teal` app. |
||
296 | -! | +||
403 | +
- for (el in elements_boook1[dt_states]) {+ #' |
||
297 | -! | +||
404 | +
- if (is.list(book2_input[[el]])) book2_input[[el]] <- "--- data table state ---"+ #' @param dataset_name (character) The name of the dataset to get the filter variables from. |
||
298 | +405 |
- }+ #' If `NULL`, the filter variables for all the datasets will be returned in a list. |
|
299 | +406 |
- }+ get_active_data_filters = function(dataset_name = NULL) { |
|
300 | +407 | ! |
- excess2 <- sprintf("$ %s:\t%s", elements_boook2, book2_input[elements_boook2])+ checkmate::check_string(dataset_name, null.ok = TRUE)+ |
+
408 | +! | +
+ datasets <- self$get_active_filter_vars()+ |
+ |
409 | +! | +
+ checkmate::assert_subset(dataset_name, datasets) |
|
301 | +410 | ! |
- message("elements only in book2: \n", paste(excess2, collapse = "\n"))+ active_filters <- lapply( |
302 | +411 | ! |
- ans <- FALSE+ datasets, |
303 | -+ | ||
412 | +! |
- }+ function(x) { |
|
304 | -+ | ||
413 | +! |
-
+ var_names <- gsub( |
|
305 | +414 | ! |
- book1_values <- readRDS(file.path("shiny_bookmarks", book1, "values.rds"))+ pattern = "\\s", |
306 | +415 | ! |
- book2_values <- readRDS(file.path("shiny_bookmarks", book2, "values.rds"))+ replacement = "", |
307 | -+ | ||
416 | +! |
-
+ self$get_text( |
|
308 | +417 | ! |
- if (!isTRUE(all.equal(book1_values, book2_values))) {+ sprintf( |
309 | +418 | ! |
- message("different values detected")+ "#%s-filters-%s .filter-card-varname", |
310 | +419 | ! |
- message("choices for numeric filters MAY be different, see RangeFilterState$set_choices")+ self$active_filters_ns(), |
311 | +420 | ! |
- ans <- FALSE+ x |
312 | +421 |
- }+ ) |
|
313 | +422 |
-
+ ) |
|
314 | -! | +||
423 | +
- if (ans) message("perfect!")+ ) |
||
315 | +424 | ! |
- invisible(NULL)+ structure( |
316 | -+ | ||
425 | +! |
- }+ lapply(var_names, private$get_active_filter_selection, dataset_name = x), |
|
317 | -+ | ||
426 | +! |
-
+ names = var_names |
|
318 | +427 |
-
+ ) |
|
319 | +428 |
- # Replacement for [base::rapply] which doesn't handle NULL values - skips the evaluation+ } |
|
320 | +429 |
- # of the function and returns NULL for given element.+ ) |
|
321 | -+ | ||
430 | +! |
- rapply2 <- function(x, f) {+ names(active_filters) <- datasets |
|
322 | -199x | +||
431 | +! |
- if (inherits(x, "list")) {+ if (is.null(dataset_name)) { |
|
323 | -87x | +||
432 | +! |
- lapply(x, rapply2, f = f)+ return(active_filters) |
|
324 | +433 |
- } else {+ } |
|
325 | -112x | +||
434 | +! |
- f(x)+ active_filters[[dataset_name]] |
|
326 | +435 |
- }+ }, |
|
327 | +436 |
- }+ #' @description |
1 | +437 |
- #' Execute and validate `teal_data_module`+ #' Add a new variable from the dataset to be filtered. |
|
2 | +438 |
- #'+ #' |
|
3 | +439 |
- #' This is a low level module to handle `teal_data_module` execution and validation.+ #' @param dataset_name (character) The name of the dataset to add the filter variable to. |
|
4 | +440 |
- #' [teal_transform_module()] inherits from [teal_data_module()] so it is handled by this module too.+ #' @param var_name (character) The name of the variable to add to the filter panel. |
|
5 | +441 |
- #' [srv_teal()] accepts various `data` objects and eventually they are all transformed to `reactive`+ #' @param ... Additional arguments to be passed to `shinytest2::AppDriver$set_inputs` |
|
6 | +442 |
- #' [teal.data::teal_data()] which is a standard data class in whole `teal` framework.+ #' |
|
7 | +443 |
- #'+ #' @return The `TealAppDriver` object invisibly. |
|
8 | +444 |
- #' @section data validation:+ add_filter_var = function(dataset_name, var_name, ...) { |
|
9 | -+ | ||
445 | +! |
- #'+ checkmate::check_string(dataset_name) |
|
10 | -+ | ||
446 | +! |
- #' Executed [teal_data_module()] is validated and output is validated for consistency.+ checkmate::check_string(var_name) |
|
11 | -+ | ||
447 | +! |
- #' Output `data` is invalid if:+ private$set_active_ns() |
|
12 | -+ | ||
448 | +! |
- #' 1. [teal_data_module()] is invalid if server doesn't return `reactive`. **Immediately crashes an app!**+ self$click( |
|
13 | -+ | ||
449 | +! |
- #' 2. `reactive` throws a `shiny.error` - happens when module creating [teal.data::teal_data()] fails.+ selector = sprintf( |
|
14 | -+ | ||
450 | +! |
- #' 3. `reactive` returns `qenv.error` - happens when [teal.data::teal_data()] evaluates a failing code.+ "#%s-filters-%s-add_filter_icon", |
|
15 | -+ | ||
451 | +! |
- #' 4. `reactive` object doesn't return [teal.data::teal_data()].+ private$ns$filter_panel, |
|
16 | -+ | ||
452 | +! |
- #' 5. [teal.data::teal_data()] object lacks any `datanames` specified in the `modules` argument.+ dataset_name |
|
17 | +453 |
- #'+ ) |
|
18 | +454 |
- #' `teal` (observers in `srv_teal`) always waits to render an app until `reactive` `teal_data` is+ ) |
|
19 | -+ | ||
455 | +! |
- #' returned. If error 2-4 occurs, relevant error message is displayed to the app user. Once the issue is+ self$set_input( |
|
20 | -+ | ||
456 | +! |
- #' resolved, the app will continue to run. `teal` guarantees that errors in data don't crash the app+ sprintf( |
|
21 | -+ | ||
457 | +! |
- #' (except error 1).+ "%s-filters-%s-%s-filter-var_to_add", |
|
22 | -+ | ||
458 | +! |
- #'+ private$ns$filter_panel, |
|
23 | -+ | ||
459 | +! |
- #' @param id (`character(1)`) Module id+ dataset_name, |
|
24 | -+ | ||
460 | +! |
- #' @param data (`reactive teal_data`)+ dataset_name |
|
25 | +461 |
- #' @param data_module (`teal_data_module`)+ ), |
|
26 | -+ | ||
462 | +! |
- #' @param modules (`teal_modules` or `teal_module`) For `datanames` validation purpose+ var_name, |
|
27 | +463 |
- #' @param validate_shiny_silent_error (`logical`) If `TRUE`, then `shiny.silent.error` is validated and+ ... |
|
28 | +464 |
- #' @param is_transform_failed (`reactiveValues`) contains `logical` flags named after each transformator.+ ) |
|
29 | -+ | ||
465 | +! |
- #' Help to determine if any previous transformator failed, so that following transformators can be disabled+ invisible(self) |
|
30 | +466 |
- #' and display a generic failure message.+ }, |
|
31 | +467 |
- #'+ #' @description |
|
32 | +468 |
- #' @return `reactive` `teal_data`+ #' Remove an active filter variable of a dataset from the active filter variables panel. |
|
33 | +469 |
- #'+ #' |
|
34 | +470 |
- #' @rdname module_teal_data+ #' @param dataset_name (character) The name of the dataset to remove the filter variable from. |
|
35 | +471 |
- #' @name module_teal_data+ #' If `NULL`, all the filter variables will be removed. |
|
36 | +472 |
- #' @keywords internal+ #' @param var_name (character) The name of the variable to remove from the filter panel. |
|
37 | +473 |
- NULL+ #' If `NULL`, all the filter variables of the dataset will be removed. |
|
38 | +474 |
-
+ #' |
|
39 | +475 |
- #' @rdname module_teal_data+ #' @return The `TealAppDriver` object invisibly. |
|
40 | +476 |
- ui_teal_data <- function(id, data_module = function(id) NULL) {+ remove_filter_var = function(dataset_name = NULL, var_name = NULL) { |
|
41 | +477 | ! |
- checkmate::assert_string(id)+ checkmate::check_string(dataset_name, null.ok = TRUE) |
42 | +478 | ! |
- checkmate::assert_function(data_module, args = "id")+ checkmate::check_string(var_name, null.ok = TRUE) |
43 | +479 | ! |
- ns <- NS(id)- |
-
44 | -- |
-
+ if (is.null(dataset_name)) { |
|
45 | +480 | ! |
- shiny::tagList(+ remove_selector <- sprintf( |
46 | +481 | ! |
- tags$div(id = ns("wrapper"), data_module(id = ns("data"))),+ "#%s-active-remove_all_filters", |
47 | +482 | ! |
- ui_validate_reactive_teal_data(ns("validate"))- |
-
48 | -- |
- )+ self$active_filters_ns() |
|
49 | +483 |
- }+ ) |
|
50 | -+ | ||
484 | +! |
-
+ } else if (is.null(var_name)) { |
|
51 | -+ | ||
485 | +! |
- #' @rdname module_teal_data+ remove_selector <- sprintf( |
|
52 | -+ | ||
486 | +! |
- srv_teal_data <- function(id,+ "#%s-active-%s-remove_filters", |
|
53 | -+ | ||
487 | +! |
- data_module = function(id) NULL,+ self$active_filters_ns(), |
|
54 | -+ | ||
488 | +! |
- modules = NULL,+ dataset_name |
|
55 | +489 |
- validate_shiny_silent_error = TRUE,+ ) |
|
56 | +490 |
- is_transform_failed = reactiveValues()) {- |
- |
57 | -! | -
- checkmate::assert_string(id)- |
- |
58 | -! | -
- checkmate::assert_function(data_module, args = "id")+ } else { |
|
59 | +491 | ! |
- checkmate::assert_multi_class(modules, c("teal_modules", "teal_module"), null.ok = TRUE)+ remove_selector <- sprintf( |
60 | +492 | ! |
- checkmate::assert_class(is_transform_failed, "reactivevalues")- |
-
61 | -- |
-
+ "#%s-active-%s-filter-%s_%s-remove", |
|
62 | +493 | ! |
- moduleServer(id, function(input, output, session) {+ self$active_filters_ns(), |
63 | +494 | ! |
- logger::log_debug("srv_teal_data initializing.")+ dataset_name, |
64 | +495 | ! |
- is_transform_failed[[id]] <- FALSE+ dataset_name, |
65 | +496 | ! |
- data_out <- data_module(id = "data")+ var_name |
66 | -! | +||
497 | +
- data_handled <- reactive(tryCatch(data_out(), error = function(e) e))+ ) |
||
67 | -! | +||
498 | +
- observeEvent(data_handled(), {+ } |
||
68 | +499 | ! |
- if (!inherits(data_handled(), "teal_data")) {+ self$click( |
69 | +500 | ! |
- is_transform_failed[[id]] <- TRUE+ selector = remove_selector |
70 | +501 |
- } else {+ ) |
|
71 | +502 | ! |
- is_transform_failed[[id]] <- FALSE+ invisible(self) |
72 | +503 |
- }+ }, |
|
73 | +504 |
- })+ #' @description |
|
74 | +505 |
-
+ #' Set the active filter values for a variable of a dataset in the active filter variable panel. |
|
75 | -! | +||
506 | +
- is_previous_failed <- reactive({+ #' |
||
76 | -! | +||
507 | +
- idx_this <- which(names(is_transform_failed) == id)+ #' @param dataset_name (character) The name of the dataset to set the filter value for. |
||
77 | -! | +||
508 | +
- is_transform_failed_list <- reactiveValuesToList(is_transform_failed)+ #' @param var_name (character) The name of the variable to set the filter value for. |
||
78 | -! | +||
509 | +
- idx_failures <- which(unlist(is_transform_failed_list))+ #' @param input The value to set the filter to. |
||
79 | -! | +||
510 | +
- any(idx_failures < idx_this)+ #' @param ... Additional arguments to be passed to `shinytest2::AppDriver$set_inputs` |
||
80 | +511 |
- })+ #' |
|
81 | +512 |
-
+ #' @return The `TealAppDriver` object invisibly. |
|
82 | -! | +||
513 | +
- observeEvent(is_previous_failed(), {+ set_active_filter_selection = function(dataset_name, |
||
83 | -! | +||
514 | +
- if (is_previous_failed()) {+ var_name, |
||
84 | -! | +||
515 | +
- shinyjs::disable("wrapper")+ input, |
||
85 | +516 |
- } else {+ ...) { |
|
86 | +517 | ! |
- shinyjs::enable("wrapper")+ checkmate::check_string(dataset_name) |
87 | -+ | ||
518 | +! |
- }+ checkmate::check_string(var_name) |
|
88 | -+ | ||
519 | +! |
- })+ checkmate::check_string(input) |
|
89 | +520 | ||
90 | +521 | ! |
- srv_validate_reactive_teal_data(+ input_id_prefix <- sprintf( |
91 | +522 | ! |
- "validate",+ "%s-filters-%s-filter-%s_%s-inputs", |
92 | +523 | ! |
- data = data_handled,+ self$active_filters_ns(), |
93 | +524 | ! |
- modules = modules,+ dataset_name, |
94 | +525 | ! |
- validate_shiny_silent_error = validate_shiny_silent_error,+ dataset_name, |
95 | +526 | ! |
- hide_validation_error = is_previous_failed- |
-
96 | -- |
- )- |
- |
97 | -- |
- })+ var_name |
|
98 | +527 |
- }+ ) |
|
99 | +528 | ||
100 | -- |
- #' @rdname module_teal_data- |
- |
101 | +529 |
- ui_validate_reactive_teal_data <- function(id) {+ # Find the type of filter (based on filter panel) |
|
102 | +530 | ! |
- ns <- NS(id)+ supported_suffix <- c("selection", "selection_manual") |
103 | +531 | ! |
- tagList(+ slices_suffix <- supported_suffix[ |
104 | +532 | ! |
- div(+ match( |
105 | +533 | ! |
- id = ns("validate_messages"),+ TRUE, |
106 | +534 | ! |
- class = "teal_validated",+ vapply( |
107 | +535 | ! |
- ui_validate_error(ns("silent_error")),+ supported_suffix, |
108 | +536 | ! |
- ui_check_class_teal_data(ns("class_teal_data")),+ function(suffix) { |
109 | +537 | ! |
- ui_check_module_datanames(ns("shiny_warnings"))+ !is.null(self$get_html(sprintf("#%s-%s", input_id_prefix, suffix))) |
110 | +538 |
- ),- |
- |
111 | -! | -
- div(- |
- |
112 | -! | -
- class = "teal_validated",+ }, |
|
113 | +539 | ! |
- uiOutput(ns("previous_failed"))+ logical(1) |
114 | +540 |
- )+ ) |
|
115 | +541 |
- )+ ) |
|
116 | +542 |
- }+ ] |
|
117 | +543 | ||
118 | +544 |
- #' @rdname module_teal_data+ # Generate correct namespace |
|
119 | -+ | ||
545 | +! |
- srv_validate_reactive_teal_data <- function(id, # nolint: object_length+ slices_input_id <- sprintf( |
|
120 | -+ | ||
546 | +! |
- data,+ "%s-filters-%s-filter-%s_%s-inputs-%s", |
|
121 | -+ | ||
547 | +! |
- modules = NULL,+ self$active_filters_ns(), |
|
122 | -+ | ||
548 | +! |
- validate_shiny_silent_error = FALSE,+ dataset_name, |
|
123 | -+ | ||
549 | +! |
- hide_validation_error = reactive(FALSE)) {+ dataset_name, |
|
124 | +550 | ! |
- checkmate::assert_string(id)+ var_name, |
125 | +551 | ! |
- checkmate::assert_multi_class(modules, c("teal_modules", "teal_module"), null.ok = TRUE)+ slices_suffix |
126 | -! | +||
552 | +
- checkmate::assert_flag(validate_shiny_silent_error)+ ) |
||
127 | +553 | ||
128 | +554 | ! |
- moduleServer(id, function(input, output, session) {+ if (identical(slices_suffix, "selection_manual")) {+ |
+
555 | +! | +
+ checkmate::assert_numeric(input, len = 2) |
|
129 | +556 |
- # there is an empty reactive cycle on `init` and `data_rv` has `shiny.silent.error` class+ |
|
130 | +557 | ! |
- srv_validate_error("silent_error", data, validate_shiny_silent_error)+ dots <- rlang::list2(...) |
131 | +558 | ! |
- srv_check_class_teal_data("class_teal_data", data)+ checkmate::assert_choice(dots$priority_, formals(self$set_inputs)[["priority_"]], null.ok = TRUE) |
132 | +559 | ! |
- srv_check_module_datanames("shiny_warnings", data, modules)+ checkmate::assert_flag(dots$wait_, null.ok = TRUE)+ |
+
560 | ++ | + | |
133 | +561 | ! |
- output$previous_failed <- renderUI({+ self$run_js( |
134 | +562 | ! |
- if (hide_validation_error()) {+ sprintf( |
135 | +563 | ! |
- shinyjs::hide("validate_messages")+ "Shiny.setInputValue('%s:sw.numericRange', [%f, %f], {priority: '%s'})", |
136 | +564 | ! |
- tags$div("One of previous transformators failed. Please check its inputs.", class = "teal-output-warning")+ slices_input_id, |
137 | -+ | ||
565 | +! |
- } else {+ input[[1]], |
|
138 | +566 | ! |
- shinyjs::show("validate_messages")+ input[[2]], |
139 | +567 | ! |
- NULL+ priority_ = ifelse(is.null(dots$priority_), "input", dots$priority_) |
140 | +568 |
- }+ ) |
|
141 | +569 |
- })+ ) |
|
142 | +570 | ||
143 | +571 | ! |
- .trigger_on_success(data)+ if (isTRUE(dots$wait_) || is.null(dots$wait_)) { |
144 | -+ | ||
572 | +! |
- })+ self$wait_for_idle( |
|
145 | -+ | ||
573 | +! |
- }+ timeout = if (is.null(dots$timeout_)) rlang::missing_arg() else dots$timeout_ |
|
146 | +574 |
-
+ ) |
|
147 | +575 |
- #' @keywords internal+ } |
|
148 | -+ | ||
576 | +! |
- ui_validate_error <- function(id) {+ } else if (identical(slices_suffix, "selection")) { |
|
149 | -116x | +||
577 | +! |
- ns <- NS(id)+ self$set_input( |
|
150 | -116x | +||
578 | +! |
- uiOutput(ns("message"))+ slices_input_id,+ |
+ |
579 | +! | +
+ input, |
|
151 | +580 |
- }+ ... |
|
152 | +581 |
-
+ ) |
|
153 | +582 |
- #' @keywords internal+ } else {+ |
+ |
583 | +! | +
+ stop("Filter selection set not supported for this slice.") |
|
154 | +584 |
- srv_validate_error <- function(id, data, validate_shiny_silent_error) {+ } |
|
155 | -113x | +||
585 | +
- checkmate::assert_string(id)+ |
||
156 | -113x | +||
586 | +! |
- checkmate::assert_flag(validate_shiny_silent_error)+ invisible(self) |
|
157 | -113x | +||
587 | +
- moduleServer(id, function(input, output, session) {+ }, |
||
158 | -113x | +||
588 | +
- output$message <- renderUI({+ #' @description |
||
159 | -112x | +||
589 | +
- is_shiny_silent_error <- inherits(data(), "shiny.silent.error") && identical(data()$message, "")+ #' Extract `html` attribute (found by a `selector`). |
||
160 | -112x | +||
590 | +
- if (inherits(data(), "qenv.error")) {+ #' |
||
161 | -2x | +||
591 | +
- validate(+ #' @param selector (`character(1)`) specifying the selector to be used to get the content of a specific node. |
||
162 | -2x | +||
592 | +
- need(+ #' @param attribute (`character(1)`) name of an attribute to retrieve from a node specified by `selector`. |
||
163 | -2x | +||
593 | +
- FALSE,+ #' |
||
164 | -2x | +||
594 | +
- paste(+ #' @return The `character` vector. |
||
165 | -2x | +||
595 | +
- "Error when executing the `data` module:",+ get_attr = function(selector, attribute) { |
||
166 | -2x | +||
596 | +! |
- strip_style(paste(data()$message, collapse = "\n")),+ rvest::html_attr( |
|
167 | -2x | +||
597 | +! |
- "\nCheck your inputs or contact app developer if error persists.",+ rvest::html_nodes(self$get_html_rvest("html"), selector), |
|
168 | -2x | +||
598 | +! |
- collapse = "\n"+ attribute |
|
169 | +599 |
- )+ ) |
|
170 | +600 |
- )+ }, |
|
171 | +601 |
- )+ #' @description |
|
172 | -110x | +||
602 | +
- } else if (inherits(data(), "error")) {+ #' Wrapper around `get_html` that passes the output directly to `rvest::read_html`. |
||
173 | -11x | +||
603 | +
- if (is_shiny_silent_error && !validate_shiny_silent_error) {+ #' |
||
174 | -4x | +||
604 | +
- return(NULL)+ #' @param selector `(character(1))` passed to `get_html`. |
||
175 | +605 |
- }+ #' |
|
176 | -7x | +||
606 | +
- validate(+ #' @return An XML document. |
||
177 | -7x | +||
607 | +
- need(+ get_html_rvest = function(selector) { |
||
178 | -7x | +||
608 | +! |
- FALSE,+ rvest::read_html(self$get_html(selector)) |
|
179 | -7x | +||
609 | +
- sprintf(+ }, |
||
180 | -7x | +||
610 | +
- "Shiny error when executing the `data` module.\n%s\n%s",+ #' Wrapper around `get_url()` method that opens the app in the browser. |
||
181 | -7x | +||
611 | +
- data()$message,+ #' |
||
182 | -7x | +||
612 | +
- "Check your inputs or contact app developer if error persists."+ #' @return Nothing. Opens the underlying teal app in the browser. |
||
183 | +613 |
- )+ open_url = function() { |
|
184 | -+ | ||
614 | +! |
- )+ browseURL(self$get_url()) |
|
185 | +615 |
- )+ }, |
|
186 | +616 |
- }+ #' @description |
|
187 | +617 |
- })+ #' Waits until a specified input, output, or export value. |
|
188 | +618 |
- })+ #' This function serves as a wrapper around the `wait_for_value` method, |
|
189 | +619 |
- }+ #' providing a more flexible interface for waiting on different types of values within the active module namespace. |
|
190 | +620 |
-
+ #' @param input,output,export A name of an input, output, or export value. |
|
191 | +621 |
-
+ #' Only one of these parameters may be used. |
|
192 | +622 |
- #' @keywords internal+ #' @param ... Must be empty. Allows for parameter expansion. |
|
193 | +623 |
- ui_check_class_teal_data <- function(id) {+ #' Parameter with additional value to passed in `wait_for_value`. |
|
194 | -116x | +||
624 | +
- ns <- NS(id)+ wait_for_active_module_value = function(input = rlang::missing_arg(), |
||
195 | -116x | +||
625 | +
- uiOutput(ns("message"))+ output = rlang::missing_arg(), |
||
196 | +626 |
- }+ export = rlang::missing_arg(), |
|
197 | +627 |
-
+ ...) { |
|
198 | -+ | ||
628 | +! |
- #' @keywords internal+ ns <- shiny::NS(self$active_module_ns()) |
|
199 | +629 |
- srv_check_class_teal_data <- function(id, data) {+ |
|
200 | -113x | +||
630 | +! |
- checkmate::assert_string(id)+ if (!rlang::is_missing(input) && checkmate::test_string(input, min.chars = 1)) input <- ns(input) |
|
201 | -113x | +||
631 | +! |
- moduleServer(id, function(input, output, session) {+ if (!rlang::is_missing(output) && checkmate::test_string(output, min.chars = 1)) output <- ns(output) |
|
202 | -113x | +||
632 | +! |
- output$message <- renderUI({+ if (!rlang::is_missing(export) && checkmate::test_string(export, min.chars = 1)) export <- ns(export) |
|
203 | -112x | +||
633 | +
- validate(+ |
||
204 | -112x | +||
634 | +! |
- need(+ self$wait_for_value( |
|
205 | -112x | +||
635 | +! |
- inherits(data(), c("teal_data", "error")),+ input = input, |
|
206 | -112x | +||
636 | +! |
- "Did not receive `teal_data` object. Cannot proceed further."+ output = output, |
|
207 | -+ | ||
637 | +! |
- )+ export = export, |
|
208 | +638 |
- )+ ... |
|
209 | +639 |
- })+ ) |
|
210 | +640 |
- })+ } |
|
211 | +641 |
- }+ ), |
|
212 | +642 |
-
+ # private members ---- |
|
213 | +643 |
- #' @keywords internal+ private = list( |
|
214 | +644 |
- ui_check_module_datanames <- function(id) {- |
- |
215 | -116x | -
- ns <- NS(id)+ # private attributes ---- |
|
216 | -116x | +||
645 | +
- uiOutput(NS(id, "message"))+ data = NULL, |
||
217 | +646 |
- }+ modules = NULL, |
|
218 | +647 |
-
+ filter = teal_slices(), |
|
219 | +648 |
- #' @keywords internal+ ns = list( |
|
220 | +649 |
- srv_check_module_datanames <- function(id, data, modules) {+ module = character(0), |
|
221 | -193x | +||
650 | +
- checkmate::assert_string(id)+ filter_panel = character(0) |
||
222 | -193x | +||
651 | +
- moduleServer(id, function(input, output, session) {+ ), |
||
223 | -193x | +||
652 | +
- output$message <- renderUI({+ # private methods ---- |
||
224 | -196x | +||
653 | +
- if (inherits(data(), "teal_data")) {+ set_active_ns = function() { |
||
225 | -179x | +||
654 | +! |
- is_modules_ok <- check_modules_datanames_html(+ all_inputs <- self$get_values()$input |
|
226 | -179x | +||
655 | +! |
- modules = modules, datanames = names(data())+ active_tab_inputs <- all_inputs[grepl("-active_tab$", names(all_inputs))] |
|
227 | +656 |
- )- |
- |
228 | -179x | -
- if (!isTRUE(is_modules_ok)) {+ |
|
229 | -19x | +||
657 | +! |
- tags$div(is_modules_ok, class = "teal-output-warning")+ tab_ns <- unlist(lapply(names(active_tab_inputs), function(name) { |
|
230 | -+ | ||
658 | +! |
- }+ gsub( |
|
231 | -+ | ||
659 | +! |
- }+ pattern = "-active_tab$", |
|
232 | -+ | ||
660 | +! |
- })+ replacement = sprintf("-%s", active_tab_inputs[[name]]), |
|
233 | -+ | ||
661 | +! |
- })+ name |
|
234 | +662 |
- }+ ) |
|
235 | +663 |
-
+ })) |
|
236 | -+ | ||
664 | +! |
- .trigger_on_success <- function(data) {+ active_ns <- tab_ns[1] |
|
237 | -113x | +||
665 | +! |
- out <- reactiveVal(NULL)+ if (length(tab_ns) > 1) { |
|
238 | -113x | +||
666 | +! |
- observeEvent(data(), {+ for (i in 2:length(tab_ns)) { |
- |
239 | -112x | +||
667 | +! |
- if (inherits(data(), "teal_data")) {+ next_ns <- tab_ns[i] |
|
240 | -97x | +||
668 | +! |
- if (!identical(data(), out())) {+ if (grepl(pattern = active_ns, next_ns)) { |
|
241 | -97x | +||
669 | +! |
- out(data())+ active_ns <- next_ns |
|
242 | +670 |
- }+ } |
|
243 | +671 |
- }+ } |
|
244 | +672 |
- })+ }+ |
+ |
673 | +! | +
+ private$ns$module <- sprintf("%s-%s", active_ns, "module") |
|
245 | +674 | ||
246 | -113x | +||
675 | +! |
- out+ components <- c("filter_panel", "data_summary") |
|
247 | -+ | ||
676 | +! |
- }+ for (component in components) { |
1 | +677 |
- #' Module to transform `reactive` `teal_data`+ if ( |
|
2 | -+ | ||
678 | +! |
- #'+ !is.null(self$get_html(sprintf("#%s-%s-panel", active_ns, component))) || |
|
3 | -+ | ||
679 | +! |
- #' Module calls [teal_transform_module()] in sequence so that `reactive teal_data` output+ !is.null(self$get_html(sprintf("#%s-%s-table", active_ns, component))) |
|
4 | +680 |
- #' from one module is handed over to the following module's input.+ ) { |
|
5 | -+ | ||
681 | +! |
- #'+ private$ns[[component]] <- sprintf("%s-%s", active_ns, component) |
|
6 | +682 |
- #' @inheritParams module_teal_data+ } else {+ |
+ |
683 | +! | +
+ private$ns[[component]] <- sprintf("%s-module_%s", active_ns, component) |
|
7 | +684 |
- #' @inheritParams teal_modules+ } |
|
8 | +685 |
- #' @param class (character(1)) CSS class to be added in the `div` wrapper tag.+ } |
|
9 | +686 |
-
+ }, |
|
10 | +687 |
- #' @return `reactive` `teal_data`+ # @description |
|
11 | +688 |
- #'+ # Get the active filter values from the active filter selection of dataset from the filter panel. |
|
12 | +689 |
- #' @name module_transform_data+ # |
|
13 | +690 |
- NULL+ # @param dataset_name (character) The name of the dataset to get the filter values from. |
|
14 | +691 |
-
+ # @param var_name (character) The name of the variable to get the filter values from. |
|
15 | +692 |
- #' @export+ # |
|
16 | +693 |
- #' @rdname module_transform_data+ # @return The value of the active filter selection. |
|
17 | +694 |
- ui_transform_teal_data <- function(id, transformators, class = "well") {+ get_active_filter_selection = function(dataset_name, var_name) { |
|
18 | -1x | +||
695 | +! |
- checkmate::assert_string(id)+ checkmate::check_string(dataset_name) |
|
19 | -1x | +||
696 | +! |
- if (length(transformators) == 0L) {+ checkmate::check_string(var_name) |
|
20 | +697 | ! |
- return(NULL)+ input_id_prefix <- sprintf( |
21 | -+ | ||
698 | +! |
- }+ "%s-filters-%s-filter-%s_%s-inputs", |
|
22 | -1x | +||
699 | +! |
- if (inherits(transformators, "teal_transform_module")) {+ self$active_filters_ns(), |
|
23 | -1x | +||
700 | +! |
- transformators <- list(transformators)+ dataset_name, |
|
24 | -+ | ||
701 | +! |
- }+ dataset_name, |
|
25 | -1x | +||
702 | +! |
- checkmate::assert_list(transformators, "teal_transform_module")+ var_name |
|
26 | -1x | +||
703 | +
- names(transformators) <- sprintf("transform_%d", seq_len(length(transformators)))+ ) |
||
27 | +704 | ||
28 | -1x | +||
705 | +
- lapply(+ # Find the type of filter (categorical or range) |
||
29 | -1x | +||
706 | +! |
- names(transformators),+ supported_suffix <- c("selection", "selection_manual") |
|
30 | -1x | +||
707 | +! |
- function(name) {+ for (suffix in supported_suffix) { |
|
31 | -1x | +||
708 | +! |
- child_id <- NS(id, name)+ if (!is.null(self$get_html(sprintf("#%s-%s", input_id_prefix, suffix)))) { |
|
32 | -1x | +||
709 | +! |
- ns <- NS(child_id)+ return(self$get_value(input = sprintf("%s-%s", input_id_prefix, suffix))) |
|
33 | -1x | +||
710 | +
- data_mod <- transformators[[name]]+ } |
||
34 | -1x | +||
711 | +
- transform_wrapper_id <- ns(sprintf("wrapper_%s", name))+ } |
||
35 | +712 | ||
36 | -1x | +||
713 | +! |
- display_fun <- if (is.null(data_mod$ui)) shinyjs::hidden else function(x) x+ NULL # If there are not any supported filters |
|
37 | +714 | - - | -|
38 | -1x | -
- display_fun(+ }, |
|
39 | -1x | +||
715 | +
- div(+ # @description |
||
40 | +716 |
- # class .teal_validated changes the color of the boarder on error in ui_validate_reactive_teal_data+ # Check if the page is stable without any `DOM` updates in the body of the app. |
|
41 | +717 |
- # For details see tealValidate.js file.+ # This is achieved by blocing the R process by sleeping until the page is unchanged till the `stability_period`. |
|
42 | -1x | +||
718 | +
- id = ns("wrapper"),+ # @param stability_period (`numeric(1)`) The time in milliseconds to wait till the page to be stable. |
||
43 | -1x | +||
719 | +
- class = c(class, "teal_validated"),+ # @param check_interval (`numeric(1)`) The time in milliseconds to check for changes in the page. |
||
44 | -1x | +||
720 | +
- title = attr(data_mod, "label"),+ # The stability check is reset when a change is detected in the page after sleeping for check_interval. |
||
45 | -1x | +||
721 | +
- tags$span(+ wait_for_page_stability = function(stability_period = 2000, check_interval = 200) { |
||
46 | -1x | +||
722 | +! |
- class = "text-primary mb-4",+ previous_content <- self$get_html("body") |
|
47 | -1x | +||
723 | +! |
- icon("fas fa-square-pen"),+ end_time <- Sys.time() + (stability_period / 1000) |
|
48 | -1x | +||
724 | +
- attr(data_mod, "label")+ |
||
49 | -+ | ||
725 | +! |
- ),+ repeat { |
|
50 | -1x | +||
726 | +! |
- tags$i(+ Sys.sleep(check_interval / 1000) |
|
51 | -1x | +||
727 | +! |
- class = "remove pull-right fa fa-angle-down",+ current_content <- self$get_html("body") |
|
52 | -1x | +||
728 | +
- style = "cursor: pointer;",+ |
||
53 | -1x | +||
729 | +! |
- title = "fold/expand transformator panel",+ if (!identical(previous_content, current_content)) { |
|
54 | -1x | +||
730 | +! |
- onclick = sprintf("togglePanelItems(this, '%s', 'fa-angle-right', 'fa-angle-down');", transform_wrapper_id)+ previous_content <- current_content |
|
55 | -+ | ||
731 | +! |
- ),+ end_time <- Sys.time() + (stability_period / 1000) |
|
56 | -1x | +||
732 | +! |
- tags$div(+ } else if (Sys.time() >= end_time) { |
|
57 | -1x | +||
733 | +! |
- id = transform_wrapper_id,+ break |
|
58 | -1x | +||
734 | +
- if (is.null(data_mod$ui)) {+ } |
||
59 | -! | +||
735 | +
- return(NULL)+ } |
||
60 | +736 |
- } else {+ } |
|
61 | -1x | +||
737 | +
- data_mod$ui(id = ns("transform"))+ ) |
||
62 | +738 |
- },+ ) |
|
63 | -1x | +
1 | +
- div(+ #' Landing popup module |
||
64 | -1x | +||
2 | +
- id = ns("validate_messages"),+ #' |
||
65 | -1x | +||
3 | +
- class = "teal_validated",+ #' @description Creates a landing welcome popup for `teal` applications. |
||
66 | -1x | +||
4 | +
- uiOutput(ns("error_wrapper"))+ #' |
||
67 | +5 |
- )+ #' This module is used to display a popup dialog when the application starts. |
|
68 | +6 |
- )+ #' The dialog blocks access to the application and must be closed with a button before the application can be viewed. |
|
69 | +7 |
- )+ #' |
|
70 | +8 |
- )+ #' @param label (`character(1)`) Label of the module. |
|
71 | +9 |
- }+ #' @param title (`character(1)`) Text to be displayed as popup title. |
|
72 | +10 |
- )+ #' @param content (`character(1)`, `shiny.tag` or `shiny.tag.list`) with the content of the popup. |
|
73 | +11 |
- }+ #' Passed to `...` of `shiny::modalDialog`. See examples. |
|
74 | +12 |
-
+ #' @param buttons (`shiny.tag` or `shiny.tag.list`) Typically a `modalButton` or `actionButton`. See examples. |
|
75 | +13 |
- #' @export+ #' |
|
76 | +14 |
- #' @rdname module_transform_data+ #' @return A `teal_module` (extended with `teal_landing_module` class) to be used in `teal` applications. |
|
77 | +15 |
- srv_transform_teal_data <- function(id, data, transformators, modules = NULL, is_transform_failed = reactiveValues()) {+ #' |
|
78 | -94x | +||
16 | +
- checkmate::assert_string(id)+ #' @examples |
||
79 | -94x | +||
17 | +
- assert_reactive(data)+ #' app1 <- init( |
||
80 | -94x | +||
18 | +
- checkmate::assert_class(modules, "teal_module", null.ok = TRUE)+ #' data = teal_data(iris = iris), |
||
81 | -94x | +||
19 | +
- if (length(transformators) == 0L) {+ #' modules = modules( |
||
82 | -71x | +||
20 | +
- return(data)+ #' example_module() |
||
83 | +21 |
- }+ #' ), |
|
84 | -23x | +||
22 | +
- if (inherits(transformators, "teal_transform_module")) {+ #' landing_popup = landing_popup_module( |
||
85 | -3x | +||
23 | +
- transformators <- list(transformators)+ #' content = "A place for the welcome message or a disclaimer statement.", |
||
86 | +24 |
- }+ #' buttons = modalButton("Proceed") |
|
87 | -23x | +||
25 | +
- checkmate::assert_list(transformators, "teal_transform_module", null.ok = TRUE)+ #' ) |
||
88 | -23x | +||
26 | +
- names(transformators) <- sprintf("transform_%d", seq_len(length(transformators)))+ #' ) |
||
89 | +27 |
-
+ #' if (interactive()) { |
|
90 | -23x | +||
28 | +
- moduleServer(id, function(input, output, session) {+ #' shinyApp(app1$ui, app1$server) |
||
91 | -23x | +||
29 | +
- module_output <- Reduce(+ #' } |
||
92 | -23x | +||
30 | +
- function(data_previous, name) {+ #' |
||
93 | -26x | +||
31 | +
- moduleServer(name, function(input, output, session) {+ #' app2 <- init( |
||
94 | -26x | +||
32 | +
- logger::log_debug("srv_transform_teal_data initializing for { name }.")+ #' data = teal_data(iris = iris), |
||
95 | -26x | +||
33 | +
- is_transform_failed[[name]] <- FALSE+ #' modules = modules( |
||
96 | -26x | +||
34 | +
- data_out <- transformators[[name]]$server("transform", data = data_previous)+ #' example_module() |
||
97 | -26x | +||
35 | +
- data_handled <- reactive(tryCatch(data_out(), error = function(e) e))+ #' ), |
||
98 | -26x | +||
36 | +
- observeEvent(data_handled(), {+ #' landing_popup = landing_popup_module( |
||
99 | -32x | +||
37 | +
- if (inherits(data_handled(), "teal_data")) {+ #' title = "Welcome", |
||
100 | -22x | +||
38 | +
- is_transform_failed[[name]] <- FALSE+ #' content = tags$b( |
||
101 | +39 |
- } else {+ #' "A place for the welcome message or a disclaimer statement.", |
|
102 | -10x | +||
40 | +
- is_transform_failed[[name]] <- TRUE+ #' style = "color: red;" |
||
103 | +41 |
- }+ #' ), |
|
104 | +42 |
- })+ #' buttons = tagList( |
|
105 | +43 |
-
+ #' modalButton("Proceed"), |
|
106 | -26x | +||
44 | +
- is_previous_failed <- reactive({+ #' actionButton("read", "Read more", |
||
107 | -29x | +||
45 | +
- idx_this <- which(names(is_transform_failed) == name)+ #' onclick = "window.open('http://google.com', '_blank')" |
||
108 | -29x | +||
46 | +
- is_transform_failed_list <- reactiveValuesToList(is_transform_failed)+ #' ), |
||
109 | -29x | +||
47 | +
- idx_failures <- which(unlist(is_transform_failed_list))+ #' actionButton("close", "Reject", onclick = "window.close()") |
||
110 | -29x | +||
48 | +
- any(idx_failures < idx_this)+ #' ) |
||
111 | +49 |
- })+ #' ) |
|
112 | +50 |
-
+ #' ) |
|
113 | -26x | +||
51 | +
- srv_validate_error("silent_error", data_handled, validate_shiny_silent_error = FALSE)+ #' |
||
114 | -26x | +||
52 | +
- srv_check_class_teal_data("class_teal_data", data_handled)+ #' if (interactive()) { |
||
115 | -26x | +||
53 | +
- if (!is.null(modules)) {+ #' shinyApp(app2$ui, app2$server) |
||
116 | -20x | +||
54 | +
- srv_check_module_datanames("datanames_warning", data_handled, modules)+ #' } |
||
117 | +55 |
- }+ #' |
|
118 | +56 |
-
+ #' @export |
|
119 | +57 |
- # When there is no UI (`ui = NULL`) it should still show the errors+ landing_popup_module <- function(label = "Landing Popup", |
|
120 | -26x | +||
58 | +
- observe({+ title = NULL, |
||
121 | -32x | +||
59 | +
- if (!inherits(data_handled(), "teal_data") && !is_previous_failed()) {+ content = NULL, |
||
122 | -10x | +||
60 | +
- shinyjs::show("wrapper")+ buttons = modalButton("Accept")) { |
||
123 | -+ | ||
61 | +! |
- }+ checkmate::assert_string(label) |
|
124 | -+ | ||
62 | +! |
- })+ checkmate::assert_string(title, null.ok = TRUE) |
|
125 | -+ | ||
63 | +! |
-
+ checkmate::assert_multi_class( |
|
126 | -26x | +||
64 | +! |
- transform_wrapper_id <- sprintf("wrapper_%s", name)+ content, |
|
127 | -26x | +||
65 | +! |
- output$error_wrapper <- renderUI({+ classes = c("character", "shiny.tag", "shiny.tag.list", "html"), null.ok = TRUE |
|
128 | -29x | +||
66 | +
- if (is_previous_failed()) {+ ) |
||
129 | +67 | ! |
- shinyjs::disable(transform_wrapper_id)+ checkmate::assert_multi_class(buttons, classes = c("shiny.tag", "shiny.tag.list"))+ |
+
68 | ++ | + | |
130 | +69 | ! |
- tags$div("One of previous transformators failed. Please check its inputs.", class = "teal-output-warning")+ message("Initializing landing_popup_module") |
131 | +70 |
- } else {+ |
|
132 | -29x | +||
71 | +! |
- shinyjs::enable(transform_wrapper_id)+ module <- module( |
|
133 | -29x | +||
72 | +! |
- shiny::tagList(+ label = label, |
|
134 | -29x | +||
73 | +! |
- ui_validate_error(session$ns("silent_error")),+ server = function(id) { |
|
135 | -29x | +||
74 | +! |
- ui_check_class_teal_data(session$ns("class_teal_data")),+ moduleServer(id, function(input, output, session) { |
|
136 | -29x | +||
75 | +! |
- ui_check_module_datanames(session$ns("datanames_warning"))+ showModal( |
|
137 | -+ | ||
76 | +! |
- )+ modalDialog( |
|
138 | -+ | ||
77 | +! |
- }+ id = "landingpopup", |
|
139 | -+ | ||
78 | +! |
- })+ title = title, |
|
140 | -+ | ||
79 | +! |
-
+ content, |
|
141 | -26x | +||
80 | +! |
- .trigger_on_success(data_handled)+ footer = buttons |
|
142 | +81 |
- })+ ) |
|
143 | +82 |
- },+ ) |
|
144 | -23x | +||
83 | +
- x = names(transformators),+ }) |
||
145 | -23x | +||
84 | +
- init = data+ } |
||
146 | +85 |
- )+ ) |
|
147 | -23x | +||
86 | +! |
- module_output+ class(module) <- c("teal_module_landing", class(module)) |
|
148 | -+ | ||
87 | +! |
- })+ module |
|
149 | +88 |
}@@ -34843,14 +34229,14 @@ teal coverage - 60.11% |
1 |
- #' Evaluate expression on `teal_data_module`+ #' App state management. |
||
3 |
- #' @details+ #' @description |
||
4 |
- #' `within` is a convenience function for evaluating inline code inside the environment of a `teal_data_module`.+ #' `r lifecycle::badge("experimental")` |
||
5 |
- #' It accepts only inline expressions (both simple and compound) and allows for injecting values into `expr` through+ #' |
||
6 |
- #' the `...` argument: as `name:value` pairs are passed to `...`, `name` in `expr` will be replaced with `value.`+ #' Capture and restore the global (app) input state. |
||
8 |
- #' @param data (`teal_data_module`) object+ #' @details |
||
9 |
- #' @param expr (`expression`) to evaluate. Must be inline code. See [within()]+ #' This module introduces bookmarks into `teal` apps: the `shiny` bookmarking mechanism becomes enabled |
||
10 |
- #' @param ... See `Details`.+ #' and server-side bookmarks can be created. |
||
12 |
- #' @return+ #' The bookmark manager presents a button with the bookmark icon and is placed in the tab-bar. |
||
13 |
- #' `within` returns a `teal_data_module` object with a delayed evaluation of `expr` when the module is run.+ #' When clicked, the button creates a bookmark and opens a modal which displays the bookmark URL. |
||
15 |
- #' @examples+ #' `teal` does not guarantee that all modules (`teal_module` objects) are bookmarkable. |
||
16 |
- #' within(tdm, dataset1 <- subset(dataset1, Species == "virginica"))+ #' Those that are, have a `teal_bookmarkable` attribute set to `TRUE`. If any modules are not bookmarkable, |
||
17 |
- #'+ #' the bookmark manager modal displays a warning and the bookmark button displays a flag. |
||
18 |
- #' # use additional parameter for expression value substitution.+ #' In order to communicate that a external module is bookmarkable, the module developer |
||
19 |
- #' valid_species <- "versicolor"+ #' should set the `teal_bookmarkable` attribute to `TRUE`. |
||
20 |
- #' within(tdm, dataset1 <- subset(dataset1, Species %in% species), species = valid_species)+ #' |
||
21 |
- #' @include teal_data_module.R+ #' @section Server logic: |
||
22 |
- #' @name within+ #' A bookmark is a URL that contains the app address with a `/?_state_id_=<bookmark_dir>` suffix. |
||
23 |
- #' @rdname teal_data_module+ #' `<bookmark_dir>` is a directory created on the server, where the state of the application is saved. |
||
24 |
- #'+ #' Accessing the bookmark URL opens a new session of the app that starts in the previously saved state. |
||
25 |
- #' @export+ #' |
||
26 |
- #'+ #' @section Note: |
||
27 |
- within.teal_data_module <- function(data, expr, ...) {+ #' To enable bookmarking use either: |
||
28 | -2x | +
- expr <- substitute(expr)+ #' - `shiny` app by using `shinyApp(..., enableBookmarking = "server")` (not supported in `shinytest2`) |
|
29 | -2x | +
- extras <- list(...)+ #' - set `options(shiny.bookmarkStore = "server")` before running the app |
|
30 |
-
+ #' |
||
31 |
- # Add braces for consistency.+ #' |
||
32 | -2x | +
- if (!identical(as.list(expr)[[1L]], as.symbol("{"))) {+ #' @inheritParams init |
|
33 | -2x | +
- expr <- call("{", expr)+ #' |
|
34 |
- }+ #' @return Invisible `NULL`. |
||
35 |
-
+ #' |
||
36 | -2x | +
- calls <- as.list(expr)[-1]+ #' @aliases bookmark bookmark_manager bookmark_manager_module |
|
37 |
-
+ #' |
||
38 |
- # Inject extra values into expressions.+ #' @name module_bookmark_manager |
||
39 | -2x | +
- calls <- lapply(calls, function(x) do.call(substitute, list(x, env = extras)))+ #' @rdname module_bookmark_manager |
|
40 |
-
+ #' |
||
41 | -2x | +
- eval_code(object = data, code = as.expression(calls))+ #' @keywords internal |
|
42 |
- }+ #' |
1 | +43 |
- #' Calls all `modules`+ NULL |
||
2 | +44 |
- #'+ |
||
3 | +45 |
- #' On the UI side each `teal_modules` is translated to a `tabsetPanel` and each `teal_module` is a+ #' @rdname module_bookmark_manager |
||
4 | +46 |
- #' `tabPanel`. Both, UI and server are called recursively so that each tab is a separate module and+ ui_bookmark_panel <- function(id, modules) { |
||
5 | -+ | |||
47 | +! |
- #' reflect nested structure of `modules` argument.+ ns <- NS(id) |
||
6 | +48 |
- #'+ |
||
7 | -+ | |||
49 | +! |
- #' @name module_teal_module+ bookmark_option <- get_bookmarking_option() |
||
8 | -+ | |||
50 | +! |
- #'+ is_unbookmarkable <- need_bookmarking(modules) |
||
9 | -+ | |||
51 | +! |
- #' @inheritParams module_teal+ shinyOptions(bookmarkStore = bookmark_option) |
||
10 | +52 |
- #'+ |
||
11 | +53 |
- #' @param data_rv (`reactive` returning `teal_data`)+ # Render bookmark warnings count |
||
12 | -+ | |||
54 | +! |
- #'+ if (!all(is_unbookmarkable) && identical(bookmark_option, "server")) { |
||
13 | -+ | |||
55 | +! |
- #' @param slices_global (`reactiveVal` returning `modules_teal_slices`)+ tags$button( |
||
14 | -+ | |||
56 | +! |
- #' see [`module_filter_manager`]+ id = ns("do_bookmark"), |
||
15 | -+ | |||
57 | +! |
- #'+ class = "btn action-button wunder_bar_button bookmark_manager_button", |
||
16 | -+ | |||
58 | +! |
- #' @param depth (`integer(1)`)+ title = "Add bookmark", |
||
17 | -+ | |||
59 | +! |
- #' number which helps to determine depth of the modules nesting.+ tags$span( |
||
18 | -+ | |||
60 | +! |
- #'+ suppressMessages(icon("fas fa-bookmark")), |
||
19 | -+ | |||
61 | +! |
- #' @param datasets (`reactive` returning `FilteredData` or `NULL`)+ if (any(is_unbookmarkable)) { |
||
20 | -+ | |||
62 | +! |
- #' When `datasets` is passed from the parent module (`srv_teal`) then `dataset` is a singleton+ tags$span( |
||
21 | -+ | |||
63 | +! |
- #' which implies in filter-panel to be "global". When `NULL` then filter-panel is "module-specific".+ sum(is_unbookmarkable),+ |
+ ||
64 | +! | +
+ class = "badge-warning badge-count text-white bg-danger" |
||
22 | +65 |
- #'+ ) |
||
23 | +66 |
- #' @param data_load_status (`reactive` returning `character`)+ } |
||
24 | +67 |
- #' Determines action dependent on a data loading status:+ ) |
||
25 | +68 |
- #' - `"ok"` when `teal_data` is returned from the data loading.+ ) |
||
26 | +69 |
- #' - `"teal_data_module failed"` when [teal_data_module()] didn't return `teal_data`. Disables tabs buttons.+ } |
||
27 | +70 |
- #' - `"external failed"` when a `reactive` passed to `srv_teal(data)` didn't return `teal_data`. Hides the whole tab+ } |
||
28 | +71 |
- #' panel.+ |
||
29 | +72 |
- #'+ #' @rdname module_bookmark_manager |
||
30 | +73 |
- #' @return+ srv_bookmark_panel <- function(id, modules) {+ |
+ ||
74 | +87x | +
+ checkmate::assert_character(id)+ |
+ ||
75 | +87x | +
+ checkmate::assert_class(modules, "teal_modules")+ |
+ ||
76 | +87x | +
+ moduleServer(id, function(input, output, session) {+ |
+ ||
77 | +87x | +
+ logger::log_debug("bookmark_manager_srv initializing")+ |
+ ||
78 | +87x | +
+ ns <- session$ns+ |
+ ||
79 | +87x | +
+ bookmark_option <- get_bookmarking_option()+ |
+ ||
80 | +87x | +
+ is_unbookmarkable <- need_bookmarking(modules) |
||
31 | +81 |
- #' output of currently active module.+ |
||
32 | +82 |
- #' - `srv_teal_module.teal_module` returns `reactiveVal` containing output of the called module.+ # Set up bookmarking callbacks ---- |
||
33 | +83 |
- #' - `srv_teal_module.teal_modules` returns output of module selected by `input$active_tab`.+ # Register bookmark exclusions: do_bookmark button to avoid re-bookmarking+ |
+ ||
84 | +87x | +
+ setBookmarkExclude(c("do_bookmark")) |
||
34 | +85 |
- #'+ # This bookmark can only be used on the app session.+ |
+ ||
86 | +87x | +
+ app_session <- .subset2(session, "parent")+ |
+ ||
87 | +87x | +
+ app_session$onBookmarked(function(url) {+ |
+ ||
88 | +! | +
+ logger::log_debug("bookmark_manager_srv@onBookmarked: bookmark button clicked, registering bookmark")+ |
+ ||
89 | +! | +
+ modal_content <- if (bookmark_option != "server") {+ |
+ ||
90 | +! | +
+ msg <- sprintf(+ |
+ ||
91 | +! | +
+ "Bookmarking has been set to \"%s\".\n%s\n%s",+ |
+ ||
92 | +! | +
+ bookmark_option,+ |
+ ||
93 | +! | +
+ "Only server-side bookmarking is supported.",+ |
+ ||
94 | +! | +
+ "Please contact your app developer." |
||
35 | +95 |
- #' @keywords internal+ )+ |
+ ||
96 | +! | +
+ tags$div(+ |
+ ||
97 | +! | +
+ tags$p(msg, class = "text-warning") |
||
36 | +98 |
- NULL+ ) |
||
37 | +99 |
-
+ } else {+ |
+ ||
100 | +! | +
+ tags$div(+ |
+ ||
101 | +! | +
+ tags$span(+ |
+ ||
102 | +! | +
+ tags$pre(url) |
||
38 | +103 |
- #' @rdname module_teal_module+ ), |
||
39 | -+ | |||
104 | +! |
- ui_teal_module <- function(id, modules, depth = 0L) {+ if (any(is_unbookmarkable)) { |
||
40 | +105 | ! |
- checkmate::assert_multi_class(modules, c("teal_modules", "teal_module", "shiny.tag"))+ bkmb_summary <- rapply2( |
|
41 | +106 | ! |
- checkmate::assert_count(depth)+ modules_bookmarkable(modules), |
|
42 | +107 | ! |
- UseMethod("ui_teal_module", modules)+ function(x) { |
|
43 | -+ | |||
108 | +! |
- }+ if (isTRUE(x)) { |
||
44 | -+ | |||
109 | +! |
-
+ "\u2705" # check mark |
||
45 | -+ | |||
110 | +! |
- #' @rdname module_teal_module+ } else if (isFALSE(x)) { |
||
46 | -+ | |||
111 | +! |
- #' @export+ "\u274C" # cross mark |
||
47 | +112 |
- ui_teal_module.default <- function(id, modules, depth = 0L) {+ } else { |
||
48 | +113 | ! |
- stop("Modules class not supported: ", paste(class(modules), collapse = " "))+ "\u2753" # question mark |
|
49 | +114 |
- }+ } |
||
50 | +115 |
-
+ } |
||
51 | +116 |
- #' @rdname module_teal_module+ ) |
||
52 | -+ | |||
117 | +! |
- #' @export+ tags$div( |
||
53 | -+ | |||
118 | +! |
- ui_teal_module.teal_modules <- function(id, modules, depth = 0L) {+ tags$p( |
||
54 | +119 | ! |
- ns <- NS(id)+ icon("fas fa-exclamation-triangle"), |
|
55 | +120 | ! |
- tags$div(+ "Some modules will not be restored when using this bookmark.", |
|
56 | +121 | ! |
- id = ns("wrapper"),+ tags$br(), |
|
57 | +122 | ! |
- do.call(+ "Check the list below to see which modules are not bookmarkable.", |
|
58 | +123 | ! |
- tabsetPanel,+ class = "text-warning"+ |
+ |
124 | ++ |
+ ), |
||
59 | +125 | ! |
- c(+ tags$pre(yaml::as.yaml(bkmb_summary)) |
|
60 | +126 |
- # by giving an id, we can reactively respond to tab changes+ ) |
||
61 | -! | +|||
127 | +
- list(+ } |
|||
62 | -! | +|||
128 | +
- id = ns("active_tab"),+ ) |
|||
63 | -! | +|||
129 | +
- type = if (modules$label == "root") "pills" else "tabs"+ } |
|||
64 | +130 |
- ),+ |
||
65 | +131 | ! |
- lapply(+ showModal( |
|
66 | +132 | ! |
- names(modules$children),+ modalDialog( |
|
67 | +133 | ! |
- function(module_id) {+ id = ns("bookmark_modal"), |
|
68 | +134 | ! |
- module_label <- modules$children[[module_id]]$label+ title = "Bookmarked teal app url", |
|
69 | +135 | ! |
- if (is.null(module_label)) {+ modal_content, |
|
70 | +136 | ! |
- module_label <- icon("fas fa-database")+ easyClose = TRUE |
|
71 | +137 |
- }+ ) |
||
72 | -! | +|||
138 | +
- tabPanel(+ ) |
|||
73 | -! | +|||
139 | +
- title = module_label,+ }) |
|||
74 | -! | +|||
140 | +
- value = module_id, # when clicked this tab value changes input$<tabset panel id>+ |
|||
75 | -! | +|||
141 | +
- ui_teal_module(+ # manually trigger bookmarking because of the problems reported on windows with bookmarkButton in teal |
|||
76 | -! | +|||
142 | +87x |
- id = ns(module_id),+ observeEvent(input$do_bookmark, { |
||
77 | +143 | ! |
- modules = modules$children[[module_id]],+ logger::log_debug("bookmark_manager_srv@1 do_bookmark module clicked.") |
|
78 | +144 | ! |
- depth = depth + 1L+ session$doBookmark() |
|
79 | +145 |
- )+ }) |
||
80 | +146 |
- )+ |
||
81 | -+ | |||
147 | +87x |
- }+ invisible(NULL) |
||
82 | +148 |
- )+ }) |
||
83 | +149 |
- )+ } |
||
84 | +150 |
- )+ |
||
85 | +151 |
- )+ |
||
86 | +152 |
- }+ #' @rdname module_bookmark_manager |
||
87 | +153 |
-
+ get_bookmarking_option <- function() { |
||
88 | -+ | |||
154 | +87x |
- #' @rdname module_teal_module+ bookmark_option <- getShinyOption("bookmarkStore")+ |
+ ||
155 | +87x | +
+ if (is.null(bookmark_option) && identical(getOption("shiny.bookmarkStore"), "server")) {+ |
+ ||
156 | +! | +
+ bookmark_option <- getOption("shiny.bookmarkStore") |
||
89 | +157 |
- #' @export+ }+ |
+ ||
158 | +87x | +
+ bookmark_option |
||
90 | +159 |
- ui_teal_module.teal_module <- function(id, modules, depth = 0L) {+ } |
||
91 | -! | +|||
160 | +
- ns <- NS(id)+ |
|||
92 | -! | +|||
161 | +
- args <- c(list(id = ns("module")), modules$ui_args)+ #' @rdname module_bookmark_manager |
|||
93 | +162 |
-
+ need_bookmarking <- function(modules) { |
||
94 | -! | +|||
163 | +87x |
- ui_teal <- tagList(+ unlist(rapply2( |
||
95 | -! | +|||
164 | +87x |
- shinyjs::hidden(+ modules_bookmarkable(modules), |
||
96 | -! | +|||
165 | +87x |
- tags$div(+ Negate(isTRUE) |
||
97 | -! | +|||
166 | +
- id = ns("transform_failure_info"),+ )) |
|||
98 | -! | +|||
167 | +
- class = "teal_validated",+ } |
|||
99 | -! | +|||
168 | +
- div(+ |
|||
100 | -! | +|||
169 | +
- class = "teal-output-warning",+ |
|||
101 | -! | +|||
170 | +
- "One of transformators failed. Please check its inputs."+ # utilities ---- |
|||
102 | +171 |
- )+ |
||
103 | +172 |
- )+ #' Restore value from bookmark. |
||
104 | +173 |
- ),+ #' |
||
105 | -! | +|||
174 | +
- tags$div(+ #' Get value from bookmark or return default. |
|||
106 | -! | +|||
175 | +
- id = ns("teal_module_ui"),+ #' |
|||
107 | -! | +|||
176 | +
- tags$div(+ #' Bookmarks can store not only inputs but also arbitrary values. |
|||
108 | -! | +|||
177 | +
- class = "teal_validated",+ #' These values are stored by `onBookmark` callbacks and restored by `onBookmarked` callbacks, |
|||
109 | -! | +|||
178 | +
- ui_check_module_datanames(ns("validate_datanames"))+ #' and they are placed in the `values` environment in the `session$restoreContext` field. |
|||
110 | +179 |
- ),+ #' Using `teal_data_module` makes it impossible to run the callbacks |
||
111 | -! | +|||
180 | +
- do.call(modules$ui, args)+ #' because the app becomes ready before modules execute and callbacks are registered. |
|||
112 | +181 |
- )+ #' In those cases the stored values can still be recovered from the `session` object directly. |
||
113 | +182 |
- )+ #' |
||
114 | +183 |
-
+ #' Note that variable names in the `values` environment are prefixed with module name space names, |
||
115 | -! | +|||
184 | +
- div(+ #' therefore, when using this function in modules, `value` must be run through the name space function. |
|||
116 | -! | +|||
185 | +
- id = id,+ #' |
|||
117 | -! | +|||
186 | +
- class = "teal_module",+ #' @param value (`character(1)`) name of value to restore |
|||
118 | -! | +|||
187 | +
- uiOutput(ns("data_reactive"), inline = TRUE),+ #' @param default fallback value |
|||
119 | -! | +|||
188 | ++ |
+ #'+ |
+ ||
189 | +
- tagList(+ #' @return |
|||
120 | -! | +|||
190 | +
- if (depth >= 2L) tags$div(style = "mt-6"),+ #' In an application restored from a server-side bookmark, |
|||
121 | -! | +|||
191 | +
- if (!is.null(modules$datanames)) {+ #' the variable specified by `value` from the `values` environment. |
|||
122 | -! | +|||
192 | +
- fluidRow(+ #' Otherwise `default`. |
|||
123 | -! | +|||
193 | +
- column(width = 9, ui_teal, class = "teal_primary_col"),+ #' |
|||
124 | -! | +|||
194 | +
- column(+ #' @keywords internal |
|||
125 | -! | +|||
195 | +
- width = 3,+ #' |
|||
126 | -! | +|||
196 | +
- ui_data_summary(ns("data_summary")),+ restoreValue <- function(value, default) { # nolint: object_name. |
|||
127 | -! | +|||
197 | +174x |
- ui_filter_data(ns("filter_panel")),+ checkmate::assert_character("value") |
||
128 | -! | +|||
198 | +174x |
- ui_transform_teal_data(ns("data_transform"), transformators = modules$transformators, class = "well"),+ session_default <- shiny::getDefaultReactiveDomain() |
||
129 | -! | +|||
199 | +174x |
- class = "teal_secondary_col"+ session_parent <- .subset2(session_default, "parent") |
||
130 | -+ | |||
200 | +174x |
- )+ session <- if (is.null(session_parent)) session_default else session_parent |
||
131 | +201 |
- )+ |
||
132 | -+ | |||
202 | +174x |
- } else {+ if (isTRUE(session$restoreContext$active) && exists(value, session$restoreContext$values, inherits = FALSE)) { |
||
133 | +203 | ! |
- ui_teal+ session$restoreContext$values[[value]] |
|
134 | +204 |
- }+ } else { |
||
135 | -+ | |||
205 | +174x |
- )+ default |
||
136 | +206 |
- )+ } |
||
137 | +207 |
} |
||
138 | +208 | |||
139 | +209 |
- #' @rdname module_teal_module+ #' Compare bookmarks. |
||
140 | +210 |
- srv_teal_module <- function(id,+ #' |
||
141 | +211 |
- data_rv,+ #' Test if two bookmarks store identical state. |
||
142 | +212 |
- modules,+ #' |
||
143 | +213 |
- datasets = NULL,+ #' `input` environments are compared one variable at a time and if not identical, |
||
144 | +214 |
- slices_global,+ #' values in both bookmarks are reported. States of `datatable`s are stripped |
||
145 | +215 |
- reporter = teal.reporter::Reporter$new(),+ #' of the `time` element before comparing because the time stamp is always different. |
||
146 | +216 |
- data_load_status = reactive("ok"),+ #' The contents themselves are not printed as they are large and the contents are not informative. |
||
147 | +217 |
- is_active = reactive(TRUE)) {+ #' Elements present in one bookmark and absent in the other are also reported. |
||
148 | -199x | +|||
218 | +
- checkmate::assert_string(id)+ #' Differences are printed as messages. |
|||
149 | -199x | +|||
219 | +
- assert_reactive(data_rv)+ #' |
|||
150 | -199x | +|||
220 | +
- checkmate::assert_multi_class(modules, c("teal_modules", "teal_module"))+ #' `values` environments are compared with `all.equal`. |
|||
151 | -199x | +|||
221 | +
- assert_reactive(datasets, null.ok = TRUE)+ #' |
|||
152 | -199x | +|||
222 | +
- checkmate::assert_class(slices_global, ".slicesGlobal")+ #' @section How to use: |
|||
153 | -199x | +|||
223 | +
- checkmate::assert_class(reporter, "Reporter")+ #' Open an application, change relevant inputs (typically, all of them), and create a bookmark. |
|||
154 | -199x | +|||
224 | +
- assert_reactive(data_load_status)+ #' Then open that bookmark and immediately create a bookmark of that. |
|||
155 | -199x | +|||
225 | +
- UseMethod("srv_teal_module", modules)+ #' If restoring bookmarks occurred properly, the two bookmarks should store the same state. |
|||
156 | +226 |
- }+ #' |
||
157 | +227 |
-
+ #' |
||
158 | +228 |
- #' @rdname module_teal_module+ #' @param book1,book2 bookmark directories stored in `shiny_bookmarks/`; |
||
159 | +229 |
- #' @export+ #' default to the two most recently modified directories |
||
160 | +230 |
- srv_teal_module.default <- function(id,+ #' |
||
161 | +231 |
- data_rv,+ #' @return |
||
162 | +232 |
- modules,+ #' Invisible `NULL` if bookmarks are identical or if there are no bookmarks to test. |
||
163 | +233 |
- datasets = NULL,+ #' `FALSE` if inconsistencies are detected. |
||
164 | +234 |
- slices_global,+ #' |
||
165 | +235 |
- reporter = teal.reporter::Reporter$new(),+ #' @keywords internal |
||
166 | +236 |
- data_load_status = reactive("ok"),+ #' |
||
167 | +237 |
- is_active = reactive(TRUE)) {+ bookmarks_identical <- function(book1, book2) { |
||
168 | +238 | ! |
- stop("Modules class not supported: ", paste(class(modules), collapse = " "))+ if (!dir.exists("shiny_bookmarks")) {+ |
+ |
239 | +! | +
+ message("no bookmark directory")+ |
+ ||
240 | +! | +
+ return(invisible(NULL)) |
||
169 | +241 |
- }+ } |
||
170 | +242 | |||
171 | -+ | |||
243 | +! |
- #' @rdname module_teal_module+ ans <- TRUE |
||
172 | +244 |
- #' @export+ |
||
173 | -+ | |||
245 | +! |
- srv_teal_module.teal_modules <- function(id,+ if (missing(book1) && missing(book2)) { |
||
174 | -+ | |||
246 | +! |
- data_rv,+ dirs <- list.dirs("shiny_bookmarks", recursive = FALSE) |
||
175 | -+ | |||
247 | +! |
- modules,+ bookmarks_sorted <- basename(rev(dirs[order(file.mtime(dirs))])) |
||
176 | -+ | |||
248 | +! |
- datasets = NULL,+ if (length(bookmarks_sorted) < 2L) {+ |
+ ||
249 | +! | +
+ message("no bookmarks to compare")+ |
+ ||
250 | +! | +
+ return(invisible(NULL)) |
||
177 | +251 |
- slices_global,+ }+ |
+ ||
252 | +! | +
+ book1 <- bookmarks_sorted[2L]+ |
+ ||
253 | +! | +
+ book2 <- bookmarks_sorted[1L] |
||
178 | +254 |
- reporter = teal.reporter::Reporter$new(),+ } else {+ |
+ ||
255 | +! | +
+ if (!dir.exists(file.path("shiny_bookmarks", book1))) stop(book1, " not found")+ |
+ ||
256 | +! | +
+ if (!dir.exists(file.path("shiny_bookmarks", book2))) stop(book2, " not found") |
||
179 | +257 |
- data_load_status = reactive("ok"),+ } |
||
180 | +258 |
- is_active = reactive(TRUE)) {+ |
||
181 | -87x | +|||
259 | +! |
- moduleServer(id = id, module = function(input, output, session) {+ book1_input <- readRDS(file.path("shiny_bookmarks", book1, "input.rds")) |
||
182 | -87x | +|||
260 | +! |
- logger::log_debug("srv_teal_module.teal_modules initializing the module { deparse1(modules$label) }.")+ book2_input <- readRDS(file.path("shiny_bookmarks", book2, "input.rds")) |
||
183 | +261 | |||
184 | -87x | +|||
262 | +! |
- observeEvent(data_load_status(), {+ elements_common <- intersect(names(book1_input), names(book2_input)) |
||
185 | -80x | +|||
263 | +! |
- tabs_selector <- sprintf("#%s li a", session$ns("active_tab"))+ dt_states <- grepl("_state$", elements_common) |
||
186 | -80x | +|||
264 | +! |
- if (identical(data_load_status(), "ok")) {+ if (any(dt_states)) { |
||
187 | -75x | +|||
265 | +! |
- logger::log_debug("srv_teal_module@1 enabling modules tabs.")+ for (el in elements_common[dt_states]) { |
||
188 | -75x | +|||
266 | +! |
- shinyjs::show("wrapper")+ book1_input[[el]][["time"]] <- NULL |
||
189 | -75x | +|||
267 | +! |
- shinyjs::enable(selector = tabs_selector)+ book2_input[[el]][["time"]] <- NULL |
||
190 | -5x | +|||
268 | +
- } else if (identical(data_load_status(), "teal_data_module failed")) {+ } |
|||
191 | -5x | +|||
269 | +
- logger::log_debug("srv_teal_module@1 disabling modules tabs.")+ } |
|||
192 | -5x | +|||
270 | +
- shinyjs::disable(selector = tabs_selector)+ |
|||
193 | +271 | +! | +
+ identicals <- mapply(identical, book1_input[elements_common], book2_input[elements_common])+ |
+ |
272 | +! | +
+ non_identicals <- names(identicals[!identicals])+ |
+ ||
273 | +! | +
+ compares <- sprintf("$ %s:\t%s --- %s", non_identicals, book1_input[non_identicals], book2_input[non_identicals])+ |
+ ||
274 | ! |
- } else if (identical(data_load_status(), "external failed")) {+ if (length(compares) != 0L) { |
||
194 | +275 | ! |
- logger::log_debug("srv_teal_module@1 hiding modules tabs.")+ message("common elements not identical: \n", paste(compares, collapse = "\n")) |
|
195 | +276 | ! |
- shinyjs::hide("wrapper")+ ans <- FALSE |
|
196 | +277 |
- }+ } |
||
197 | +278 |
- })+ |
||
198 | -+ | |||
279 | +! |
-
+ elements_boook1 <- setdiff(names(book1_input), names(book2_input)) |
||
199 | -87x | +|||
280 | +! |
- modules_output <- sapply(+ if (length(elements_boook1) != 0L) { |
||
200 | -87x | +|||
281 | +! |
- names(modules$children),+ dt_states <- grepl("_state$", elements_boook1) |
||
201 | -87x | +|||
282 | +! |
- function(module_id) {+ if (any(dt_states)) { |
||
202 | -112x | +|||
283 | +! |
- srv_teal_module(+ for (el in elements_boook1[dt_states]) { |
||
203 | -112x | +|||
284 | +! |
- id = module_id,+ if (is.list(book1_input[[el]])) book1_input[[el]] <- "--- data table state ---" |
||
204 | -112x | +|||
285 | +
- data_rv = data_rv,+ } |
|||
205 | -112x | +|||
286 | +
- modules = modules$children[[module_id]],+ } |
|||
206 | -112x | +|||
287 | +! |
- datasets = datasets,+ excess1 <- sprintf("$ %s:\t%s", elements_boook1, book1_input[elements_boook1]) |
||
207 | -112x | +|||
288 | +! |
- slices_global = slices_global,+ message("elements only in book1: \n", paste(excess1, collapse = "\n")) |
||
208 | -112x | +|||
289 | +! |
- reporter = reporter,+ ans <- FALSE |
||
209 | -112x | +|||
290 | +
- is_active = reactive(+ } |
|||
210 | -112x | +|||
291 | +
- is_active() &&+ |
|||
211 | -112x | +|||
292 | +! |
- input$active_tab == module_id &&+ elements_boook2 <- setdiff(names(book2_input), names(book1_input)) |
||
212 | -112x | +|||
293 | +! |
- identical(data_load_status(), "ok")+ if (length(elements_boook2) != 0L) { |
||
213 | -+ | |||
294 | +! |
- )+ dt_states <- grepl("_state$", elements_boook1) |
||
214 | -+ | |||
295 | +! |
- )+ if (any(dt_states)) { |
||
215 | -+ | |||
296 | +! |
- },+ for (el in elements_boook1[dt_states]) { |
||
216 | -87x | +|||
297 | +! |
- simplify = FALSE+ if (is.list(book2_input[[el]])) book2_input[[el]] <- "--- data table state ---" |
||
217 | +298 |
- )+ } |
||
218 | +299 |
-
+ } |
||
219 | -87x | +|||
300 | +! |
- modules_output+ excess2 <- sprintf("$ %s:\t%s", elements_boook2, book2_input[elements_boook2]) |
||
220 | -+ | |||
301 | +! |
- })+ message("elements only in book2: \n", paste(excess2, collapse = "\n")) |
||
221 | -+ | |||
302 | +! |
- }+ ans <- FALSE |
||
222 | +303 |
-
+ } |
||
223 | +304 |
- #' @rdname module_teal_module+ |
||
224 | -+ | |||
305 | +! |
- #' @export+ book1_values <- readRDS(file.path("shiny_bookmarks", book1, "values.rds")) |
||
225 | -+ | |||
306 | +! |
- srv_teal_module.teal_module <- function(id,+ book2_values <- readRDS(file.path("shiny_bookmarks", book2, "values.rds")) |
||
226 | +307 |
- data_rv,+ |
||
227 | -+ | |||
308 | +! |
- modules,+ if (!isTRUE(all.equal(book1_values, book2_values))) { |
||
228 | -+ | |||
309 | +! |
- datasets = NULL,+ message("different values detected") |
||
229 | -+ | |||
310 | +! |
- slices_global,+ message("choices for numeric filters MAY be different, see RangeFilterState$set_choices") |
||
230 | -+ | |||
311 | +! |
- reporter = teal.reporter::Reporter$new(),+ ans <- FALSE |
||
231 | +312 |
- data_load_status = reactive("ok"),+ } |
||
232 | +313 |
- is_active = reactive(TRUE)) {+ |
||
233 | -112x | +|||
314 | +! |
- logger::log_debug("srv_teal_module.teal_module initializing the module: { deparse1(modules$label) }.")+ if (ans) message("perfect!") |
||
234 | -112x | +|||
315 | +! |
- moduleServer(id = id, module = function(input, output, session) {+ invisible(NULL) |
||
235 | -112x | +|||
316 | +
- module_out <- reactiveVal()+ } |
|||
236 | +317 | |||
237 | -112x | +|||
318 | +
- active_datanames <- reactive({+ |
|||
238 | -89x | +|||
319 | +
- .resolve_module_datanames(data = data_rv(), modules = modules)+ # Replacement for [base::rapply] which doesn't handle NULL values - skips the evaluation |
|||
239 | +320 |
- })+ # of the function and returns NULL for given element. |
||
240 | -112x | +|||
321 | +
- if (is.null(datasets)) {+ rapply2 <- function(x, f) { |
|||
241 | -20x | +322 | +199x |
- datasets <- eventReactive(data_rv(), {+ if (inherits(x, "list")) { |
242 | -16x | +323 | +87x |
- req(inherits(data_rv(), "teal_data"))+ lapply(x, rapply2, f = f) |
243 | -16x | +|||
324 | +
- logger::log_debug("srv_teal_module@1 initializing module-specific FilteredData")+ } else { |
|||
244 | -16x | +325 | +112x |
- teal_data_to_filtered_data(data_rv(), datanames = active_datanames())+ f(x) |
245 | +326 |
- })+ } |
||
246 | +327 |
- }+ } |
247 | +1 |
-
+ #' Validate that dataset has a minimum number of observations |
||
248 | +2 |
- # manage module filters on the module level+ #' |
||
249 | +3 |
- # important:+ #' `r lifecycle::badge("stable")` |
||
250 | +4 |
- # filter_manager_module_srv needs to be called before filter_panel_srv+ #' |
||
251 | +5 |
- # Because available_teal_slices is used in FilteredData$srv_available_slices (via srv_filter_panel)+ #' This function is a wrapper for `shiny::validate`. |
||
252 | +6 |
- # and if it is not set, then it won't be available in the srv_filter_panel+ #' |
||
253 | -112x | +|||
7 | +
- srv_module_filter_manager(modules$label, module_fd = datasets, slices_global = slices_global)+ #' @param x (`data.frame`) |
|||
254 | +8 |
-
+ #' @param min_nrow (`numeric(1)`) Minimum allowed number of rows in `x`. |
||
255 | -112x | +|||
9 | +
- call_once_when(is_active(), {+ #' @param complete (`logical(1)`) Flag specifying whether to check only complete cases. Defaults to `FALSE`. |
|||
256 | -86x | +|||
10 | +
- filtered_teal_data <- srv_filter_data(+ #' @param allow_inf (`logical(1)`) Flag specifying whether to allow infinite values. Defaults to `TRUE`. |
|||
257 | -86x | +|||
11 | +
- "filter_panel",+ #' @param msg (`character(1)`) Additional message to display alongside the default message. |
|||
258 | -86x | +|||
12 | +
- datasets = datasets,+ #' |
|||
259 | -86x | +|||
13 | +
- active_datanames = active_datanames,+ #' @export |
|||
260 | -86x | +|||
14 | +
- data_rv = data_rv,+ #' |
|||
261 | -86x | +|||
15 | +
- is_active = is_active+ #' @examples |
|||
262 | +16 |
- )+ #' library(teal) |
||
263 | -86x | +|||
17 | +
- is_transform_failed <- reactiveValues()+ #' ui <- fluidPage( |
|||
264 | -86x | +|||
18 | +
- transformed_teal_data <- srv_transform_teal_data(+ #' sliderInput("len", "Max Length of Sepal", |
|||
265 | -86x | +|||
19 | +
- "data_transform",+ #' min = 4.3, max = 7.9, value = 5 |
|||
266 | -86x | +|||
20 | +
- data = filtered_teal_data,+ #' ), |
|||
267 | -86x | +|||
21 | +
- transformators = modules$transformators,+ #' plotOutput("plot") |
|||
268 | -86x | +|||
22 | +
- modules = modules,+ #' ) |
|||
269 | -86x | +|||
23 | +
- is_transform_failed = is_transform_failed+ #' |
|||
270 | +24 |
- )+ #' server <- function(input, output) { |
||
271 | -86x | +|||
25 | +
- any_transform_failed <- reactive({+ #' output$plot <- renderPlot({ |
|||
272 | -86x | +|||
26 | +
- any(unlist(reactiveValuesToList(is_transform_failed)))+ #' iris_df <- iris[iris$Sepal.Length <= input$len, ] |
|||
273 | +27 |
- })+ #' validate_has_data( |
||
274 | +28 |
-
+ #' iris_df, |
||
275 | -86x | +|||
29 | +
- observeEvent(any_transform_failed(), {+ #' min_nrow = 10, |
|||
276 | -86x | +|||
30 | +
- if (isTRUE(any_transform_failed())) {+ #' complete = FALSE, |
|||
277 | -6x | +|||
31 | +
- shinyjs::hide("teal_module_ui")+ #' msg = "Please adjust Max Length of Sepal" |
|||
278 | -6x | +|||
32 | +
- shinyjs::show("transform_failure_info")+ #' ) |
|||
279 | +33 |
- } else {+ #' |
||
280 | -80x | +|||
34 | +
- shinyjs::show("teal_module_ui")+ #' hist(iris_df$Sepal.Length, breaks = 5) |
|||
281 | -80x | +|||
35 | +
- shinyjs::hide("transform_failure_info")+ #' }) |
|||
282 | +36 |
- }+ #' } |
||
283 | +37 |
- })+ #' if (interactive()) { |
||
284 | +38 |
-
+ #' shinyApp(ui, server) |
||
285 | -86x | +|||
39 | +
- module_teal_data <- reactive({+ #' } |
|||
286 | -94x | +|||
40 | +
- req(inherits(transformed_teal_data(), "teal_data"))+ #' |
|||
287 | -88x | +|||
41 | +
- all_teal_data <- transformed_teal_data()+ validate_has_data <- function(x, |
|||
288 | -88x | +|||
42 | +
- module_datanames <- .resolve_module_datanames(data = all_teal_data, modules = modules)+ min_nrow = NULL, |
|||
289 | -88x | +|||
43 | +
- all_teal_data[c(module_datanames, ".raw_data")]+ complete = FALSE, |
|||
290 | +44 |
- })+ allow_inf = TRUE, |
||
291 | +45 |
-
+ msg = NULL) { |
||
292 | -86x | +46 | +17x |
- srv_check_module_datanames(+ checkmate::assert_string(msg, null.ok = TRUE) |
293 | -86x | +47 | +15x |
- "validate_datanames",+ checkmate::assert_data_frame(x) |
294 | -86x | +48 | +15x |
- data = module_teal_data,+ if (!is.null(min_nrow)) { |
295 | -86x | +49 | +15x |
- modules = modules+ if (complete) { |
296 | -+ | |||
50 | +5x |
- )+ complete_index <- stats::complete.cases(x) |
||
297 | -+ | |||
51 | +5x |
-
+ validate(need( |
||
298 | -86x | +52 | +5x |
- summary_table <- srv_data_summary("data_summary", module_teal_data)+ sum(complete_index) > 0 && nrow(x[complete_index, , drop = FALSE]) >= min_nrow, |
299 | -+ | |||
53 | +5x |
-
+ paste(c(paste("Number of complete cases is less than:", min_nrow), msg), collapse = "\n") |
||
300 | +54 |
- # Call modules.+ )) |
||
301 | -86x | +|||
55 | +
- if (!inherits(modules, "teal_module_previewer")) {+ } else { |
|||
302 | -86x | +56 | +10x |
- obs_module <- call_once_when(+ validate(need( |
303 | -86x | +57 | +10x |
- !is.null(module_teal_data()),+ nrow(x) >= min_nrow, |
304 | -86x | +58 | +10x |
- ignoreNULL = TRUE,+ paste( |
305 | -86x | +59 | +10x |
- handlerExpr = {+ c(paste("Minimum number of records not met: >=", min_nrow, "records required."), msg), |
306 | -80x | +60 | +10x |
- module_out(.call_teal_module(modules, datasets, module_teal_data, reporter))+ collapse = "\n" |
307 | +61 |
- }+ ) |
||
308 | +62 |
- )+ )) |
||
309 | +63 |
- } else {+ } |
||
310 | +64 |
- # Report previewer must be initiated on app start for report cards to be included in bookmarks.+ |
||
311 | -+ | |||
65 | +10x |
- # When previewer is delayed, cards are bookmarked only if previewer has been initiated (visited).+ if (!allow_inf) { |
||
312 | -! | +|||
66 | +6x |
- module_out(.call_teal_module(modules, datasets, module_teal_data, reporter))+ validate(need( |
||
313 | -+ | |||
67 | +6x |
- }+ all(vapply(x, function(col) !is.numeric(col) || !any(is.infinite(col)), logical(1))), |
||
314 | -+ | |||
68 | +6x |
- })+ "Dataframe contains Inf values which is not allowed." |
||
315 | +69 |
-
+ )) |
||
316 | -112x | +|||
70 | +
- module_out+ } |
|||
317 | +71 |
- })+ } |
||
318 | +72 |
} |
||
319 | +73 | |||
320 | +74 |
- # This function calls a module server function.+ #' Validate that dataset has unique rows for key variables |
||
321 | +75 |
- .call_teal_module <- function(modules, datasets, filtered_teal_data, reporter) {+ #' |
||
322 | +76 |
- # collect arguments to run teal_module- |
- ||
323 | -80x | -
- args <- c(list(id = "module"), modules$server_args)- |
- ||
324 | -80x | -
- if (is_arg_used(modules$server, "reporter")) {- |
- ||
325 | -1x | -
- args <- c(args, list(reporter = reporter))+ #' `r lifecycle::badge("stable")` |
||
326 | +77 |
- }+ #' |
||
327 | +78 | - - | -||
328 | -80x | -
- if (is_arg_used(modules$server, "datasets")) {- |
- ||
329 | -1x | -
- args <- c(args, datasets = datasets())- |
- ||
330 | -1x | -
- warning("datasets argument is not reactive and therefore it won't be updated when data is refreshed.")+ #' This function is a wrapper for `shiny::validate`. |
||
331 | +79 |
- }+ #' |
||
332 | +80 | - - | -||
333 | -80x | -
- if (is_arg_used(modules$server, "data")) {+ #' @param x (`data.frame`) |
||
334 | -76x | +|||
81 | +
- args <- c(args, data = list(filtered_teal_data))+ #' @param key (`character`) Vector of ID variables from `x` that identify unique records. |
|||
335 | +82 |
- }+ #' |
||
336 | +83 |
-
+ #' @export |
||
337 | -80x | +|||
84 | +
- if (is_arg_used(modules$server, "filter_panel_api")) {+ #' |
|||
338 | -1x | +|||
85 | +
- args <- c(args, filter_panel_api = teal.slice::FilterPanelAPI$new(datasets()))+ #' @examples |
|||
339 | +86 |
- }+ #' iris$id <- rep(1:50, times = 3) |
||
340 | +87 |
-
+ #' ui <- fluidPage( |
||
341 | -80x | +|||
88 | +
- if (is_arg_used(modules$server, "id")) {+ #' selectInput( |
|||
342 | -80x | +|||
89 | +
- do.call(modules$server, args)+ #' inputId = "species", |
|||
343 | +90 |
- } else {+ #' label = "Select species", |
||
344 | -! | +|||
91 | +
- do.call(callModule, c(args, list(module = modules$server)))+ #' choices = c("setosa", "versicolor", "virginica"), |
|||
345 | +92 |
- }+ #' selected = "setosa", |
||
346 | +93 |
- }+ #' multiple = TRUE |
||
347 | +94 |
-
+ #' ), |
||
348 | +95 |
- .resolve_module_datanames <- function(data, modules) {+ #' plotOutput("plot") |
||
349 | -177x | +|||
96 | +
- stopifnot("data_rv must be teal_data object." = inherits(data, "teal_data"))+ #' ) |
|||
350 | -177x | +|||
97 | +
- if (is.null(modules$datanames) || identical(modules$datanames, "all")) {+ #' server <- function(input, output) { |
|||
351 | -145x | +|||
98 | +
- names(data)+ #' output$plot <- renderPlot({ |
|||
352 | +99 |
- } else {+ #' iris_f <- iris[iris$Species %in% input$species, ] |
||
353 | -32x | +|||
100 | +
- intersect(+ #' validate_one_row_per_id(iris_f, key = c("id")) |
|||
354 | -32x | +|||
101 | +
- names(data), # Keep topological order from teal.data::names()+ #' |
|||
355 | -32x | +|||
102 | +
- .include_parent_datanames(modules$datanames, teal.data::join_keys(data))+ #' hist(iris_f$Sepal.Length, breaks = 5) |
|||
356 | +103 |
- )+ #' }) |
||
357 | +104 |
- }+ #' } |
||
358 | +105 |
- }+ #' if (interactive()) { |
||
359 | +106 |
-
+ #' shinyApp(ui, server) |
||
360 | +107 |
- #' Calls expression when condition is met+ #' } |
||
361 | +108 |
#' |
||
362 | +109 |
- #' Function postpones `handlerExpr` to the moment when `eventExpr` (condition) returns `TRUE`,+ validate_one_row_per_id <- function(x, key = c("USUBJID", "STUDYID")) { |
||
363 | -+ | |||
110 | +! |
- #' otherwise nothing happens.+ validate(need(!any(duplicated(x[key])), paste("Found more than one row per id."))) |
||
364 | +111 |
- #' @param eventExpr A (quoted or unquoted) logical expression that represents the event;+ } |
||
365 | +112 |
- #' this can be a simple reactive value like input$click, a call to a reactive expression+ |
||
366 | +113 |
- #' like dataset(), or even a complex expression inside curly braces.+ #' Validates that vector includes all expected values |
||
367 | +114 |
- #' @param ... additional arguments passed to `observeEvent` with the exception of `eventExpr` that is not allowed.+ #' |
||
368 | +115 |
- #' @inheritParams shiny::observeEvent+ #' `r lifecycle::badge("stable")` |
||
369 | +116 |
#' |
||
370 | +117 |
- #' @return An observer.+ #' This function is a wrapper for `shiny::validate`. |
||
371 | +118 |
#' |
||
372 | +119 |
- #' @keywords internal+ #' @param x Vector of values to test. |
||
373 | +120 |
- call_once_when <- function(eventExpr, # nolint: object_name.+ #' @param choices Vector to test against. |
||
374 | +121 |
- handlerExpr, # nolint: object_name.+ #' @param msg (`character(1)`) Error message to display if some elements of `x` are not elements of `choices`. |
||
375 | +122 |
- event.env = parent.frame(), # nolint: object_name.+ #' |
||
376 | +123 |
- handler.env = parent.frame(), # nolint: object_name.+ #' @export |
||
377 | +124 |
- ...) {- |
- ||
378 | -198x | -
- event_quo <- rlang::new_quosure(substitute(eventExpr), env = event.env)+ #' |
||
379 | -198x | +|||
125 | +
- handler_quo <- rlang::new_quosure(substitute(handlerExpr), env = handler.env)+ #' @examples |
|||
380 | +126 |
-
+ #' ui <- fluidPage( |
||
381 | +127 |
- # When `condExpr` is TRUE, then `handlerExpr` is evaluated once.+ #' selectInput( |
||
382 | -198x | +|||
128 | +
- activator <- reactive({+ #' "species", |
|||
383 | -198x | +|||
129 | +
- if (isTRUE(rlang::eval_tidy(event_quo))) {+ #' "Select species", |
|||
384 | -166x | +|||
130 | +
- TRUE+ #' choices = c("setosa", "versicolor", "virginica", "unknown species"), |
|||
385 | +131 |
- }+ #' selected = "setosa", |
||
386 | +132 |
- })+ #' multiple = FALSE |
||
387 | +133 |
-
+ #' ), |
||
388 | -198x | +|||
134 | +
- observeEvent(+ #' verbatimTextOutput("summary") |
|||
389 | -198x | +|||
135 | +
- eventExpr = activator(),+ #' ) |
|||
390 | -198x | +|||
136 | +
- once = TRUE,+ #' |
|||
391 | -198x | +|||
137 | +
- handlerExpr = rlang::eval_tidy(handler_quo),+ #' server <- function(input, output) { |
|||
392 | +138 |
- ...+ #' output$summary <- renderPrint({ |
||
393 | +139 |
- )+ #' validate_in(input$species, iris$Species, "Species does not exist.") |
||
394 | +140 |
- }+ #' nrow(iris[iris$Species == input$species, ]) |
1 | +141 |
- #' Validate that dataset has a minimum number of observations+ #' }) |
|
2 | +142 |
- #'+ #' } |
|
3 | +143 |
- #' `r lifecycle::badge("stable")`+ #' if (interactive()) { |
|
4 | +144 |
- #'+ #' shinyApp(ui, server) |
|
5 | +145 |
- #' This function is a wrapper for `shiny::validate`.+ #' } |
|
6 | +146 |
#' |
|
7 | +147 |
- #' @param x (`data.frame`)+ validate_in <- function(x, choices, msg) { |
|
8 | -+ | ||
148 | +! |
- #' @param min_nrow (`numeric(1)`) Minimum allowed number of rows in `x`.+ validate(need(length(x) > 0 && length(choices) > 0 && all(x %in% choices), msg)) |
|
9 | +149 |
- #' @param complete (`logical(1)`) Flag specifying whether to check only complete cases. Defaults to `FALSE`.+ } |
|
10 | +150 |
- #' @param allow_inf (`logical(1)`) Flag specifying whether to allow infinite values. Defaults to `TRUE`.+ |
|
11 | +151 |
- #' @param msg (`character(1)`) Additional message to display alongside the default message.+ #' Validates that vector has length greater than 0 |
|
12 | +152 |
#' |
|
13 | +153 |
- #' @export+ #' `r lifecycle::badge("stable")` |
|
14 | +154 |
#' |
|
15 | +155 |
- #' @examples+ #' This function is a wrapper for `shiny::validate`. |
|
16 | +156 |
- #' library(teal)+ #' |
|
17 | +157 |
- #' ui <- fluidPage(+ #' @param x vector |
|
18 | +158 |
- #' sliderInput("len", "Max Length of Sepal",+ #' @param msg message to display |
|
19 | +159 |
- #' min = 4.3, max = 7.9, value = 5+ #' |
|
20 | +160 |
- #' ),+ #' @export |
|
21 | +161 |
- #' plotOutput("plot")+ #' |
|
22 | +162 |
- #' )+ #' @examples |
|
23 | +163 |
- #'+ #' data <- data.frame( |
|
24 | +164 |
- #' server <- function(input, output) {+ #' id = c(1:10, 11:20, 1:10), |
|
25 | +165 |
- #' output$plot <- renderPlot({+ #' strata = rep(c("A", "B"), each = 15) |
|
26 | +166 |
- #' iris_df <- iris[iris$Sepal.Length <= input$len, ]+ #' ) |
|
27 | +167 |
- #' validate_has_data(+ #' ui <- fluidPage( |
|
28 | +168 |
- #' iris_df,+ #' selectInput("ref1", "Select strata1 to compare", |
|
29 | +169 |
- #' min_nrow = 10,+ #' choices = c("A", "B", "C"), selected = "A" |
|
30 | +170 |
- #' complete = FALSE,+ #' ), |
|
31 | +171 |
- #' msg = "Please adjust Max Length of Sepal"+ #' selectInput("ref2", "Select strata2 to compare", |
|
32 | +172 |
- #' )+ #' choices = c("A", "B", "C"), selected = "B" |
|
33 | +173 |
- #'+ #' ), |
|
34 | +174 |
- #' hist(iris_df$Sepal.Length, breaks = 5)+ #' verbatimTextOutput("arm_summary") |
|
35 | +175 |
- #' })+ #' ) |
|
36 | +176 |
- #' }+ #' |
|
37 | +177 |
- #' if (interactive()) {+ #' server <- function(input, output) { |
|
38 | +178 |
- #' shinyApp(ui, server)+ #' output$arm_summary <- renderText({ |
|
39 | +179 |
- #' }+ #' sample_1 <- data$id[data$strata == input$ref1] |
|
40 | +180 |
- #'+ #' sample_2 <- data$id[data$strata == input$ref2] |
|
41 | +181 |
- validate_has_data <- function(x,+ #' |
|
42 | +182 |
- min_nrow = NULL,+ #' validate_has_elements(sample_1, "No subjects in strata1.") |
|
43 | +183 |
- complete = FALSE,+ #' validate_has_elements(sample_2, "No subjects in strata2.") |
|
44 | +184 |
- allow_inf = TRUE,+ #' |
|
45 | +185 |
- msg = NULL) {- |
- |
46 | -17x | -
- checkmate::assert_string(msg, null.ok = TRUE)- |
- |
47 | -15x | -
- checkmate::assert_data_frame(x)+ #' paste0( |
|
48 | -15x | +||
186 | +
- if (!is.null(min_nrow)) {+ #' "Number of samples in: strata1=", length(sample_1), |
||
49 | -15x | +||
187 | +
- if (complete) {+ #' " comparions strata2=", length(sample_2) |
||
50 | -5x | +||
188 | +
- complete_index <- stats::complete.cases(x)+ #' ) |
||
51 | -5x | +||
189 | +
- validate(need(+ #' }) |
||
52 | -5x | +||
190 | +
- sum(complete_index) > 0 && nrow(x[complete_index, , drop = FALSE]) >= min_nrow,+ #' } |
||
53 | -5x | +||
191 | +
- paste(c(paste("Number of complete cases is less than:", min_nrow), msg), collapse = "\n")+ #' if (interactive()) { |
||
54 | +192 |
- ))+ #' shinyApp(ui, server) |
|
55 | +193 |
- } else {+ #' } |
|
56 | -10x | +||
194 | +
- validate(need(+ validate_has_elements <- function(x, msg) { |
||
57 | -10x | +||
195 | +! |
- nrow(x) >= min_nrow,+ validate(need(length(x) > 0, msg)) |
|
58 | -10x | +||
196 | +
- paste(+ } |
||
59 | -10x | +||
197 | +
- c(paste("Minimum number of records not met: >=", min_nrow, "records required."), msg),+ |
||
60 | -10x | +||
198 | +
- collapse = "\n"+ #' Validates no intersection between two vectors |
||
61 | +199 |
- )+ #' |
|
62 | +200 |
- ))+ #' `r lifecycle::badge("stable")` |
|
63 | +201 |
- }+ #' |
|
64 | +202 |
-
+ #' This function is a wrapper for `shiny::validate`. |
|
65 | -10x | +||
203 | +
- if (!allow_inf) {+ #' |
||
66 | -6x | +||
204 | +
- validate(need(+ #' @param x vector |
||
67 | -6x | +||
205 | +
- all(vapply(x, function(col) !is.numeric(col) || !any(is.infinite(col)), logical(1))),+ #' @param y vector |
||
68 | -6x | +||
206 | +
- "Dataframe contains Inf values which is not allowed."+ #' @param msg (`character(1)`) message to display if `x` and `y` intersect |
||
69 | +207 |
- ))+ #' |
|
70 | +208 |
- }+ #' @export |
|
71 | +209 |
- }+ #' |
|
72 | +210 |
- }+ #' @examples |
|
73 | +211 |
-
+ #' data <- data.frame( |
|
74 | +212 |
- #' Validate that dataset has unique rows for key variables+ #' id = c(1:10, 11:20, 1:10), |
|
75 | +213 |
- #'+ #' strata = rep(c("A", "B", "C"), each = 10) |
|
76 | +214 |
- #' `r lifecycle::badge("stable")`+ #' ) |
|
77 | +215 |
#' |
|
78 | +216 |
- #' This function is a wrapper for `shiny::validate`.+ #' ui <- fluidPage( |
|
79 | +217 |
- #'+ #' selectInput("ref1", "Select strata1 to compare", |
|
80 | +218 |
- #' @param x (`data.frame`)+ #' choices = c("A", "B", "C"), |
|
81 | +219 |
- #' @param key (`character`) Vector of ID variables from `x` that identify unique records.+ #' selected = "A" |
|
82 | +220 |
- #'+ #' ), |
|
83 | +221 |
- #' @export+ #' selectInput("ref2", "Select strata2 to compare", |
|
84 | +222 |
- #'+ #' choices = c("A", "B", "C"), |
|
85 | +223 |
- #' @examples+ #' selected = "B" |
|
86 | +224 |
- #' iris$id <- rep(1:50, times = 3)+ #' ), |
|
87 | +225 |
- #' ui <- fluidPage(+ #' verbatimTextOutput("summary") |
|
88 | +226 |
- #' selectInput(+ #' ) |
|
89 | +227 |
- #' inputId = "species",+ #' |
|
90 | +228 |
- #' label = "Select species",+ #' server <- function(input, output) { |
|
91 | +229 |
- #' choices = c("setosa", "versicolor", "virginica"),+ #' output$summary <- renderText({ |
|
92 | +230 |
- #' selected = "setosa",+ #' sample_1 <- data$id[data$strata == input$ref1] |
|
93 | +231 |
- #' multiple = TRUE+ #' sample_2 <- data$id[data$strata == input$ref2] |
|
94 | +232 |
- #' ),+ #' |
|
95 | +233 |
- #' plotOutput("plot")+ #' validate_no_intersection( |
|
96 | +234 |
- #' )+ #' sample_1, sample_2, |
|
97 | +235 |
- #' server <- function(input, output) {+ #' "subjects within strata1 and strata2 cannot overlap" |
|
98 | +236 |
- #' output$plot <- renderPlot({+ #' ) |
|
99 | +237 |
- #' iris_f <- iris[iris$Species %in% input$species, ]+ #' paste0( |
|
100 | +238 |
- #' validate_one_row_per_id(iris_f, key = c("id"))+ #' "Number of subject in: reference treatment=", length(sample_1), |
|
101 | +239 |
- #'+ #' " comparions treatment=", length(sample_2) |
|
102 | +240 |
- #' hist(iris_f$Sepal.Length, breaks = 5)+ #' ) |
|
103 | +241 |
#' }) |
|
104 | +242 |
#' } |
|
105 | +243 |
#' if (interactive()) { |
|
106 | +244 |
#' shinyApp(ui, server) |
|
107 | +245 |
#' } |
|
108 | +246 |
#' |
|
109 | +247 |
- validate_one_row_per_id <- function(x, key = c("USUBJID", "STUDYID")) {+ validate_no_intersection <- function(x, y, msg) { |
|
110 | +248 | ! |
- validate(need(!any(duplicated(x[key])), paste("Found more than one row per id.")))+ validate(need(length(intersect(x, y)) == 0, msg)) |
111 | +249 |
} |
|
112 | +250 | ||
113 | +251 |
- #' Validates that vector includes all expected values+ |
|
114 | +252 | ++ |
+ #' Validates that dataset contains specific variable+ |
+
253 |
#' |
||
115 | +254 |
#' `r lifecycle::badge("stable")` |
|
116 | +255 |
#' |
|
117 | +256 |
#' This function is a wrapper for `shiny::validate`. |
|
118 | +257 |
#' |
|
119 | +258 |
- #' @param x Vector of values to test.+ #' @param data (`data.frame`) |
|
120 | +259 |
- #' @param choices Vector to test against.+ #' @param varname (`character(1)`) name of variable to check for in `data` |
|
121 | +260 |
- #' @param msg (`character(1)`) Error message to display if some elements of `x` are not elements of `choices`.+ #' @param msg (`character(1)`) message to display if `data` does not include `varname` |
|
122 | +261 |
#' |
|
123 | +262 |
#' @export |
|
124 | +263 |
#' |
|
125 | +264 |
#' @examples |
|
126 | +265 |
- #' ui <- fluidPage(+ #' data <- data.frame( |
|
127 | +266 |
- #' selectInput(+ #' one = rep("a", length.out = 20), |
|
128 | +267 |
- #' "species",+ #' two = rep(c("a", "b"), length.out = 20) |
|
129 | +268 |
- #' "Select species",+ #' ) |
|
130 | +269 |
- #' choices = c("setosa", "versicolor", "virginica", "unknown species"),+ #' ui <- fluidPage( |
|
131 | +270 |
- #' selected = "setosa",+ #' selectInput( |
|
132 | +271 |
- #' multiple = FALSE+ #' "var", |
|
133 | +272 | ++ |
+ #' "Select variable",+ |
+
273 | ++ |
+ #' choices = c("one", "two", "three", "four"),+ |
+ |
274 | ++ |
+ #' selected = "one"+ |
+ |
275 |
#' ), |
||
134 | +276 |
#' verbatimTextOutput("summary") |
|
135 | +277 |
#' ) |
|
136 | +278 |
#' |
|
137 | +279 |
#' server <- function(input, output) { |
|
138 | +280 |
- #' output$summary <- renderPrint({+ #' output$summary <- renderText({ |
|
139 | +281 |
- #' validate_in(input$species, iris$Species, "Species does not exist.")+ #' validate_has_variable(data, input$var) |
|
140 | +282 |
- #' nrow(iris[iris$Species == input$species, ])+ #' paste0("Selected treatment variables: ", paste(input$var, collapse = ", ")) |
|
141 | +283 |
#' }) |
|
142 | +284 |
#' } |
|
143 | +285 |
#' if (interactive()) { |
|
144 | +286 |
#' shinyApp(ui, server) |
|
145 | +287 |
#' } |
|
146 | +288 |
- #'+ validate_has_variable <- function(data, varname, msg) {+ |
+ |
289 | +! | +
+ if (length(varname) != 0) {+ |
+ |
290 | +! | +
+ has_vars <- varname %in% names(data) |
|
147 | +291 |
- validate_in <- function(x, choices, msg) {+ |
|
148 | +292 | ! |
- validate(need(length(x) > 0 && length(choices) > 0 && all(x %in% choices), msg))+ if (!all(has_vars)) {+ |
+
293 | +! | +
+ if (missing(msg)) {+ |
+ |
294 | +! | +
+ msg <- sprintf(+ |
+ |
295 | +! | +
+ "%s does not have the required variables: %s.",+ |
+ |
296 | +! | +
+ deparse(substitute(data)),+ |
+ |
297 | +! | +
+ toString(varname[!has_vars]) |
|
149 | +298 | ++ |
+ )+ |
+
299 | ++ |
+ }+ |
+ |
300 | +! | +
+ validate(need(FALSE, msg))+ |
+ |
301 | ++ |
+ }+ |
+ |
302 | ++ |
+ }+ |
+ |
303 |
} |
||
150 | +304 | ||
151 | +305 |
- #' Validates that vector has length greater than 0+ #' Validate that variables has expected number of levels |
|
152 | +306 |
#' |
|
153 | +307 |
#' `r lifecycle::badge("stable")` |
|
154 | +308 |
#' |
|
155 | +309 | ++ |
+ #' If the number of levels of `x` is less than `min_levels`+ |
+
310 | ++ |
+ #' or greater than `max_levels` the validation will fail.+ |
+ |
311 |
#' This function is a wrapper for `shiny::validate`. |
||
156 | +312 |
#' |
|
157 | +313 |
- #' @param x vector+ #' @param x variable name. If `x` is not a factor, the unique values |
|
158 | +314 |
- #' @param msg message to display+ #' are treated as levels. |
|
159 | +315 |
- #'+ #' @param min_levels cutoff for minimum number of levels of `x` |
|
160 | +316 |
- #' @export+ #' @param max_levels cutoff for maximum number of levels of `x` |
|
161 | +317 | ++ |
+ #' @param var_name name of variable being validated for use in+ |
+
318 | ++ |
+ #' validation message+ |
+ |
319 |
#' |
||
162 | +320 | ++ |
+ #' @export+ |
+
321 |
#' @examples |
||
163 | +322 |
#' data <- data.frame( |
|
164 | +323 |
- #' id = c(1:10, 11:20, 1:10),+ #' one = rep("a", length.out = 20), |
|
165 | +324 |
- #' strata = rep(c("A", "B"), each = 15)+ #' two = rep(c("a", "b"), length.out = 20), |
|
166 | +325 | ++ |
+ #' three = rep(c("a", "b", "c"), length.out = 20),+ |
+
326 | ++ |
+ #' four = rep(c("a", "b", "c", "d"), length.out = 20),+ |
+ |
327 | ++ |
+ #' stringsAsFactors = TRUE+ |
+ |
328 |
#' ) |
||
167 | +329 |
#' ui <- fluidPage( |
|
168 | +330 |
- #' selectInput("ref1", "Select strata1 to compare",+ #' selectInput( |
|
169 | +331 |
- #' choices = c("A", "B", "C"), selected = "A"+ #' "var", |
|
170 | +332 |
- #' ),+ #' "Select variable", |
|
171 | +333 |
- #' selectInput("ref2", "Select strata2 to compare",+ #' choices = c("one", "two", "three", "four"), |
|
172 | +334 |
- #' choices = c("A", "B", "C"), selected = "B"+ #' selected = "one" |
|
173 | +335 |
#' ), |
|
174 | +336 |
- #' verbatimTextOutput("arm_summary")+ #' verbatimTextOutput("summary") |
|
175 | +337 |
#' ) |
|
176 | +338 |
#' |
|
177 | +339 |
#' server <- function(input, output) { |
|
178 | +340 |
- #' output$arm_summary <- renderText({+ #' output$summary <- renderText({ |
|
179 | +341 |
- #' sample_1 <- data$id[data$strata == input$ref1]+ #' validate_n_levels(data[[input$var]], min_levels = 2, max_levels = 15, var_name = input$var) |
|
180 | +342 |
- #' sample_2 <- data$id[data$strata == input$ref2]+ #' paste0( |
|
181 | +343 |
- #'+ #' "Levels of selected treatment variable: ", |
|
182 | +344 |
- #' validate_has_elements(sample_1, "No subjects in strata1.")+ #' paste(levels(data[[input$var]]), |
|
183 | +345 |
- #' validate_has_elements(sample_2, "No subjects in strata2.")+ #' collapse = ", " |
|
184 | +346 |
- #'+ #' ) |
|
185 | +347 |
- #' paste0(+ #' ) |
|
186 | +348 |
- #' "Number of samples in: strata1=", length(sample_1),+ #' }) |
|
187 | +349 |
- #' " comparions strata2=", length(sample_2)+ #' } |
|
188 | +350 |
- #' )+ #' if (interactive()) { |
|
189 | +351 |
- #' })+ #' shinyApp(ui, server) |
|
190 | +352 |
#' } |
|
191 | +353 |
- #' if (interactive()) {+ validate_n_levels <- function(x, min_levels = 1, max_levels = 12, var_name) { |
|
192 | -+ | ||
354 | +! |
- #' shinyApp(ui, server)+ x_levels <- if (is.factor(x)) { |
|
193 | -+ | ||
355 | +! |
- #' }+ levels(x) |
|
194 | +356 |
- validate_has_elements <- function(x, msg) {+ } else { |
|
195 | +357 | ! |
- validate(need(length(x) > 0, msg))+ unique(x) |
196 | +358 |
- }+ } |
|
197 | +359 | ||
198 | -+ | ||
360 | +! |
- #' Validates no intersection between two vectors+ if (!is.null(min_levels) && !(is.null(max_levels))) { |
|
199 | -+ | ||
361 | +! |
- #'+ validate(need( |
|
200 | -+ | ||
362 | +! |
- #' `r lifecycle::badge("stable")`+ length(x_levels) >= min_levels && length(x_levels) <= max_levels, |
|
201 | -+ | ||
363 | +! |
- #'+ sprintf( |
|
202 | -+ | ||
364 | +! |
- #' This function is a wrapper for `shiny::validate`.+ "%s variable needs minimum %s level(s) and maximum %s level(s).", |
|
203 | -+ | ||
365 | +! |
- #'+ var_name, min_levels, max_levels |
|
204 | +366 |
- #' @param x vector+ ) |
|
205 | +367 |
- #' @param y vector+ )) |
|
206 | -+ | ||
368 | +! |
- #' @param msg (`character(1)`) message to display if `x` and `y` intersect+ } else if (!is.null(min_levels)) { |
|
207 | -+ | ||
369 | +! |
- #'+ validate(need( |
|
208 | -+ | ||
370 | +! |
- #' @export+ length(x_levels) >= min_levels, |
|
209 | -+ | ||
371 | +! |
- #'+ sprintf("%s variable needs minimum %s levels(s)", var_name, min_levels) |
|
210 | +372 |
- #' @examples+ )) |
|
211 | -+ | ||
373 | +! |
- #' data <- data.frame(+ } else if (!is.null(max_levels)) { |
|
212 | -+ | ||
374 | +! |
- #' id = c(1:10, 11:20, 1:10),+ validate(need( |
|
213 | -+ | ||
375 | +! |
- #' strata = rep(c("A", "B", "C"), each = 10)+ length(x_levels) <= max_levels,+ |
+ |
376 | +! | +
+ sprintf("%s variable needs maximum %s level(s)", var_name, max_levels) |
|
214 | +377 |
- #' )+ )) |
|
215 | +378 |
- #'+ } |
|
216 | +379 |
- #' ui <- fluidPage(+ } |
217 | +1 |
- #' selectInput("ref1", "Select strata1 to compare",+ #' Data summary |
|
218 | +2 |
- #' choices = c("A", "B", "C"),+ #' @description |
|
219 | +3 |
- #' selected = "A"+ #' Module and its utils to display the number of rows and subjects in the filtered and unfiltered data. |
|
220 | +4 |
- #' ),+ #' |
|
221 | +5 |
- #' selectInput("ref2", "Select strata2 to compare",+ #' @details Handling different data classes: |
|
222 | +6 |
- #' choices = c("A", "B", "C"),+ #' `get_filter_overview()` is a pseudo S3 method which has variants for: |
|
223 | +7 |
- #' selected = "B"+ #' - `array` (`data.frame`, `DataFrame`, `array`, `Matrix` and `SummarizedExperiment`): Method variant |
|
224 | +8 |
- #' ),+ #' can be applied to any two-dimensional objects on which [ncol()] can be used. |
|
225 | +9 |
- #' verbatimTextOutput("summary")+ #' - `MultiAssayExperiment`: for which summary contains counts for `colData` and all `experiments`. |
|
226 | +10 |
- #' )+ #' - For other data types module displays data name with warning icon and no more details. |
|
227 | +11 |
#' |
|
228 | +12 |
- #' server <- function(input, output) {+ #' Module includes also "Show/Hide unsupported" button to toggle rows of the summary table |
|
229 | +13 |
- #' output$summary <- renderText({+ #' containing datasets where number of observations are not calculated. |
|
230 | +14 |
- #' sample_1 <- data$id[data$strata == input$ref1]+ #' |
|
231 | +15 |
- #' sample_2 <- data$id[data$strata == input$ref2]+ #' @param id (`character(1)`) `shiny` module instance id. |
|
232 | +16 |
- #'+ #' @param teal_data (`reactive` returning `teal_data`) |
|
233 | +17 |
- #' validate_no_intersection(+ #' |
|
234 | +18 |
- #' sample_1, sample_2,+ #' @name module_data_summary |
|
235 | +19 |
- #' "subjects within strata1 and strata2 cannot overlap"+ #' @rdname module_data_summary |
|
236 | +20 |
- #' )+ #' @keywords internal |
|
237 | +21 |
- #' paste0(+ #' @return `NULL`. |
|
238 | +22 |
- #' "Number of subject in: reference treatment=", length(sample_1),+ NULL |
|
239 | +23 |
- #' " comparions treatment=", length(sample_2)+ |
|
240 | +24 |
- #' )+ #' @rdname module_data_summary |
|
241 | +25 |
- #' })+ ui_data_summary <- function(id) { |
|
242 | -+ | ||
26 | +! |
- #' }+ ns <- NS(id) |
|
243 | -+ | ||
27 | +! |
- #' if (interactive()) {+ content_id <- ns("filters_overview_contents") |
|
244 | -+ | ||
28 | +! |
- #' shinyApp(ui, server)+ tags$div( |
|
245 | -+ | ||
29 | +! |
- #' }+ id = id, |
|
246 | -+ | ||
30 | +! |
- #'+ class = "well", |
|
247 | -+ | ||
31 | +! |
- validate_no_intersection <- function(x, y, msg) {+ tags$div( |
|
248 | +32 | ! |
- validate(need(length(intersect(x, y)) == 0, msg))+ class = "row", |
249 | -+ | ||
33 | +! |
- }+ tags$div( |
|
250 | -+ | ||
34 | +! |
-
+ class = "col-sm-9", |
|
251 | -+ | ||
35 | +! |
-
+ tags$label("Active Filter Summary", class = "text-primary mb-4") |
|
252 | +36 |
- #' Validates that dataset contains specific variable+ ), |
|
253 | -+ | ||
37 | +! |
- #'+ tags$div( |
|
254 | -+ | ||
38 | +! |
- #' `r lifecycle::badge("stable")`+ class = "col-sm-3", |
|
255 | -+ | ||
39 | +! |
- #'+ tags$i( |
|
256 | -+ | ||
40 | +! |
- #' This function is a wrapper for `shiny::validate`.+ class = "remove pull-right fa fa-angle-down", |
|
257 | -+ | ||
41 | +! |
- #'+ style = "cursor: pointer;", |
|
258 | -+ | ||
42 | +! |
- #' @param data (`data.frame`)+ title = "fold/expand data summary panel", |
|
259 | -+ | ||
43 | +! |
- #' @param varname (`character(1)`) name of variable to check for in `data`+ onclick = sprintf("togglePanelItems(this, '%s', 'fa-angle-right', 'fa-angle-down');", content_id) |
|
260 | +44 |
- #' @param msg (`character(1)`) message to display if `data` does not include `varname`+ ) |
|
261 | +45 |
- #'+ ) |
|
262 | +46 |
- #' @export+ ), |
|
263 | -+ | ||
47 | +! |
- #'+ tags$div( |
|
264 | -+ | ||
48 | +! | +
+ id = content_id,+ |
+ |
49 | +! |
- #' @examples+ tags$div( |
|
265 | -+ | ||
50 | +! |
- #' data <- data.frame(+ class = "teal_active_summary_filter_panel", |
|
266 | -+ | ||
51 | +! |
- #' one = rep("a", length.out = 20),+ tableOutput(ns("table")) |
|
267 | +52 |
- #' two = rep(c("a", "b"), length.out = 20)+ ) |
|
268 | +53 |
- #' )+ ) |
|
269 | +54 |
- #' ui <- fluidPage(+ ) |
|
270 | +55 |
- #' selectInput(+ } |
|
271 | +56 |
- #' "var",+ |
|
272 | +57 |
- #' "Select variable",+ #' @rdname module_data_summary |
|
273 | +58 |
- #' choices = c("one", "two", "three", "four"),+ srv_data_summary <- function(id, data) { |
|
274 | -+ | ||
59 | +86x |
- #' selected = "one"+ assert_reactive(data) |
|
275 | -+ | ||
60 | +86x |
- #' ),+ moduleServer( |
|
276 | -+ | ||
61 | +86x |
- #' verbatimTextOutput("summary")+ id = id, |
|
277 | -+ | ||
62 | +86x |
- #' )+ function(input, output, session) { |
|
278 | -+ | ||
63 | +86x |
- #'+ logger::log_debug("srv_data_summary initializing") |
|
279 | +64 |
- #' server <- function(input, output) {+ |
|
280 | -+ | ||
65 | +86x |
- #' output$summary <- renderText({+ summary_table <- reactive({ |
|
281 | -+ | ||
66 | +94x |
- #' validate_has_variable(data, input$var)+ req(inherits(data(), "teal_data")) |
|
282 | -+ | ||
67 | +88x |
- #' paste0("Selected treatment variables: ", paste(input$var, collapse = ", "))+ if (!length(data())) { |
|
283 | -+ | ||
68 | +! |
- #' })+ return(NULL) |
|
284 | +69 |
- #' }+ } |
|
285 | -+ | ||
70 | +88x |
- #' if (interactive()) {+ get_filter_overview_wrapper(data) |
|
286 | +71 |
- #' shinyApp(ui, server)+ }) |
|
287 | +72 |
- #' }+ |
|
288 | -+ | ||
73 | +86x |
- validate_has_variable <- function(data, varname, msg) {+ output$table <- renderUI({ |
|
289 | -! | +||
74 | +94x |
- if (length(varname) != 0) {+ summary_table_out <- try(summary_table(), silent = TRUE) |
|
290 | -! | +||
75 | +94x |
- has_vars <- varname %in% names(data)+ if (inherits(summary_table_out, "try-error")) { |
|
291 | +76 | - - | -|
292 | -! | -
- if (!all(has_vars)) {+ # Ignore silent shiny error |
|
293 | -! | +||
77 | +6x |
- if (missing(msg)) {+ if (!inherits(attr(summary_table_out, "condition"), "shiny.silent.error")) { |
|
294 | +78 | ! |
- msg <- sprintf(+ stop("Error occurred during data processing. See details in the main panel.") |
295 | -! | +||
79 | +
- "%s does not have the required variables: %s.",+ } |
||
296 | -! | +||
80 | +88x |
- deparse(substitute(data)),+ } else if (is.null(summary_table_out)) { |
|
297 | -! | +||
81 | +2x |
- toString(varname[!has_vars])+ "no datasets to show" |
|
298 | +82 |
- )+ } else { |
|
299 | -+ | ||
83 | +86x |
- }+ is_unsupported <- apply(summary_table(), 1, function(x) all(is.na(x[-1]))) |
|
300 | -! | +||
84 | +86x |
- validate(need(FALSE, msg))+ summary_table_out[is.na(summary_table_out)] <- "" |
|
301 | -+ | ||
85 | +86x |
- }+ body_html <- apply( |
|
302 | -+ | ||
86 | +86x |
- }+ summary_table_out, |
|
303 | -+ | ||
87 | +86x |
- }+ 1, |
|
304 | -+ | ||
88 | +86x |
-
+ function(x) { |
|
305 | -+ | ||
89 | +162x |
- #' Validate that variables has expected number of levels+ is_supported <- !all(x[-1] == "") |
|
306 | -+ | ||
90 | +162x |
- #'+ if (is_supported) { |
|
307 | -+ | ||
91 | +153x |
- #' `r lifecycle::badge("stable")`+ tags$tr( |
|
308 | -+ | ||
92 | +153x |
- #'+ tagList( |
|
309 | -+ | ||
93 | +153x |
- #' If the number of levels of `x` is less than `min_levels`+ tags$td(x[1]), |
|
310 | -+ | ||
94 | +153x |
- #' or greater than `max_levels` the validation will fail.+ lapply(x[-1], tags$td) |
|
311 | +95 |
- #' This function is a wrapper for `shiny::validate`.+ ) |
|
312 | +96 |
- #'+ ) |
|
313 | +97 |
- #' @param x variable name. If `x` is not a factor, the unique values+ } |
|
314 | +98 |
- #' are treated as levels.+ } |
|
315 | +99 |
- #' @param min_levels cutoff for minimum number of levels of `x`+ ) |
|
316 | +100 |
- #' @param max_levels cutoff for maximum number of levels of `x`+ |
|
317 | -+ | ||
101 | +86x |
- #' @param var_name name of variable being validated for use in+ header_labels <- tools::toTitleCase(names(summary_table_out)) |
|
318 | -+ | ||
102 | +86x |
- #' validation message+ header_labels[header_labels == "Dataname"] <- "Data Name" |
|
319 | -+ | ||
103 | +86x |
- #'+ header_html <- tags$tr(tagList(lapply(header_labels, tags$td))) |
|
320 | +104 |
- #' @export+ |
|
321 | -+ | ||
105 | +86x |
- #' @examples+ table_html <- tags$table( |
|
322 | -+ | ||
106 | +86x |
- #' data <- data.frame(+ class = "table custom-table", |
|
323 | -+ | ||
107 | +86x |
- #' one = rep("a", length.out = 20),+ tags$thead(header_html), |
|
324 | -+ | ||
108 | +86x |
- #' two = rep(c("a", "b"), length.out = 20),+ tags$tbody(body_html) |
|
325 | +109 |
- #' three = rep(c("a", "b", "c"), length.out = 20),+ ) |
|
326 | -+ | ||
110 | +86x |
- #' four = rep(c("a", "b", "c", "d"), length.out = 20),+ div( |
|
327 | -+ | ||
111 | +86x |
- #' stringsAsFactors = TRUE+ table_html, |
|
328 | -+ | ||
112 | +86x |
- #' )+ if (any(is_unsupported)) { |
|
329 | -+ | ||
113 | +9x |
- #' ui <- fluidPage(+ p( |
|
330 | -+ | ||
114 | +9x |
- #' selectInput(+ class = c("pull-right", "float-right", "text-secondary"), |
|
331 | -+ | ||
115 | +9x |
- #' "var",+ style = "font-size: 0.8em;", |
|
332 | -+ | ||
116 | +9x |
- #' "Select variable",+ sprintf("And %s more unfilterable object(s)", sum(is_unsupported)), |
|
333 | -+ | ||
117 | +9x |
- #' choices = c("one", "two", "three", "four"),+ icon( |
|
334 | -+ | ||
118 | +9x |
- #' selected = "one"+ name = "far fa-circle-question", |
|
335 | -+ | ||
119 | +9x |
- #' ),+ title = paste( |
|
336 | -+ | ||
120 | +9x |
- #' verbatimTextOutput("summary")+ sep = "", |
|
337 | -+ | ||
121 | +9x |
- #' )+ collapse = "\n", |
|
338 | -+ | ||
122 | +9x |
- #'+ shQuote(summary_table()[is_unsupported, "dataname"]), |
|
339 | +123 |
- #' server <- function(input, output) {+ " (", |
|
340 | -+ | ||
124 | +9x |
- #' output$summary <- renderText({+ vapply( |
|
341 | -+ | ||
125 | +9x |
- #' validate_n_levels(data[[input$var]], min_levels = 2, max_levels = 15, var_name = input$var)+ summary_table()[is_unsupported, "dataname"], |
|
342 | -+ | ||
126 | +9x |
- #' paste0(+ function(x) class(data()[[x]])[1], |
|
343 | -+ | ||
127 | +9x |
- #' "Levels of selected treatment variable: ",+ character(1L) |
|
344 | +128 |
- #' paste(levels(data[[input$var]]),+ ), |
|
345 | +129 |
- #' collapse = ", "+ ")" |
|
346 | +130 |
- #' )+ ) |
|
347 | +131 |
- #' )+ ) |
|
348 | +132 |
- #' })+ ) |
|
349 | +133 |
- #' }+ } |
|
350 | +134 |
- #' if (interactive()) {+ ) |
|
351 | +135 |
- #' shinyApp(ui, server)+ } |
|
352 | +136 |
- #' }+ }) |
|
353 | +137 |
- validate_n_levels <- function(x, min_levels = 1, max_levels = 12, var_name) {- |
- |
354 | -! | -
- x_levels <- if (is.factor(x)) {+ |
|
355 | -! | +||
138 | +86x |
- levels(x)+ NULL |
|
356 | +139 |
- } else {+ } |
|
357 | -! | +||
140 | +
- unique(x)+ ) |
||
358 | +141 |
- }+ } |
|
359 | +142 | ||
360 | -! | -
- if (!is.null(min_levels) && !(is.null(max_levels))) {- |
- |
361 | -! | -
- validate(need(- |
- |
362 | -! | +||
143 | +
- length(x_levels) >= min_levels && length(x_levels) <= max_levels,+ #' @rdname module_data_summary |
||
363 | -! | +||
144 | +
- sprintf(+ get_filter_overview_wrapper <- function(teal_data) { |
||
364 | -! | +||
145 | +
- "%s variable needs minimum %s level(s) and maximum %s level(s).",+ # Sort datanames in topological order |
||
365 | -! | +||
146 | +88x |
- var_name, min_levels, max_levels+ datanames <- names(teal_data()) |
|
366 | -+ | ||
147 | +88x |
- )+ joinkeys <- teal.data::join_keys(teal_data()) |
|
367 | +148 |
- ))+ |
|
368 | -! | +||
149 | +88x |
- } else if (!is.null(min_levels)) {+ current_data_objs <- sapply( |
|
369 | -! | +||
150 | +88x |
- validate(need(+ datanames, |
|
370 | -! | +||
151 | +88x |
- length(x_levels) >= min_levels,+ function(name) teal_data()[[name]], |
|
371 | -! | +||
152 | +88x |
- sprintf("%s variable needs minimum %s levels(s)", var_name, min_levels)+ simplify = FALSE |
|
372 | +153 |
- ))- |
- |
373 | -! | -
- } else if (!is.null(max_levels)) {+ ) |
|
374 | -! | +||
154 | +88x |
- validate(need(+ initial_data_objs <- teal_data()[[".raw_data"]] |
|
375 | -! | +||
155 | +
- length(x_levels) <= max_levels,+ |
||
376 | -! | +||
156 | +88x |
- sprintf("%s variable needs maximum %s level(s)", var_name, max_levels)+ out <- lapply( |
|
377 | -+ | ||
157 | +88x |
- ))+ datanames, |
|
378 | -+ | ||
158 | +88x |
- }+ function(dataname) { |
|
379 | -+ | ||
159 | +157x |
- }+ parent <- teal.data::parent(joinkeys, dataname) |
1 | -+ | |||
160 | +157x |
- #' Data summary+ subject_keys <- if (length(parent) > 0) { |
||
2 | -+ | |||
161 | +8x |
- #' @description+ names(joinkeys[dataname, parent]) |
||
3 | +162 |
- #' Module and its utils to display the number of rows and subjects in the filtered and unfiltered data.+ } else { |
||
4 | -+ | |||
163 | +149x |
- #'+ joinkeys[dataname, dataname] |
||
5 | +164 |
- #' @details Handling different data classes:+ } |
||
6 | -+ | |||
165 | +157x |
- #' `get_filter_overview()` is a pseudo S3 method which has variants for:+ get_filter_overview( |
||
7 | -+ | |||
166 | +157x |
- #' - `array` (`data.frame`, `DataFrame`, `array`, `Matrix` and `SummarizedExperiment`): Method variant+ current_data = current_data_objs[[dataname]], |
||
8 | -+ | |||
167 | +157x |
- #' can be applied to any two-dimensional objects on which [ncol()] can be used.+ initial_data = initial_data_objs[[dataname]], |
||
9 | -+ | |||
168 | +157x |
- #' - `MultiAssayExperiment`: for which summary contains counts for `colData` and all `experiments`.+ dataname = dataname, |
||
10 | -+ | |||
169 | +157x |
- #' - For other data types module displays data name with warning icon and no more details.+ subject_keys = subject_keys |
||
11 | +170 |
- #'+ ) |
||
12 | +171 |
- #' Module includes also "Show/Hide unsupported" button to toggle rows of the summary table+ } |
||
13 | +172 |
- #' containing datasets where number of observations are not calculated.+ ) |
||
14 | +173 |
- #'+ |
||
15 | -+ | |||
174 | +88x |
- #' @param id (`character(1)`) `shiny` module instance id.+ do.call(.smart_rbind, out) |
||
16 | +175 |
- #' @param teal_data (`reactive` returning `teal_data`)+ } |
||
17 | +176 |
- #'+ |
||
18 | +177 |
- #' @name module_data_summary+ |
||
19 | +178 |
#' @rdname module_data_summary |
||
20 | -- |
- #' @keywords internal- |
- ||
21 | +179 |
- #' @return `NULL`.+ #' @param current_data (`object`) current object (after filtering and transforming). |
||
22 | +180 |
- NULL+ #' @param initial_data (`object`) initial object. |
||
23 | +181 |
-
+ #' @param dataname (`character(1)`) |
||
24 | +182 |
- #' @rdname module_data_summary+ #' @param subject_keys (`character`) names of the columns which determine a single unique subjects |
||
25 | +183 |
- ui_data_summary <- function(id) {- |
- ||
26 | -! | -
- ns <- NS(id)- |
- ||
27 | -! | -
- content_id <- ns("filters_overview_contents")- |
- ||
28 | -! | -
- tags$div(- |
- ||
29 | -! | -
- id = id,- |
- ||
30 | -! | -
- class = "well",- |
- ||
31 | -! | -
- tags$div(+ get_filter_overview <- function(current_data, initial_data, dataname, subject_keys) { |
||
32 | -! | +|||
184 | +162x |
- class = "row",+ if (inherits(current_data, c("data.frame", "DataFrame", "array", "Matrix", "SummarizedExperiment"))) { |
||
33 | -! | +|||
185 | +152x |
- tags$div(+ get_filter_overview_array(current_data, initial_data, dataname, subject_keys) |
||
34 | -! | +|||
186 | +10x |
- class = "col-sm-9",+ } else if (inherits(current_data, "MultiAssayExperiment")) { |
||
35 | -! | +|||
187 | +1x |
- tags$label("Active Filter Summary", class = "text-primary mb-4")+ get_filter_overview_MultiAssayExperiment(current_data, initial_data, dataname) |
||
36 | +188 |
- ),- |
- ||
37 | -! | -
- tags$div(- |
- ||
38 | -! | -
- class = "col-sm-3",- |
- ||
39 | -! | -
- tags$i(+ } else { |
||
40 | -! | +|||
189 | +9x |
- class = "remove pull-right fa fa-angle-down",+ data.frame(dataname = dataname) |
||
41 | -! | +|||
190 | +
- style = "cursor: pointer;",+ } |
|||
42 | -! | +|||
191 | +
- title = "fold/expand data summary panel",+ } |
|||
43 | -! | +|||
192 | +
- onclick = sprintf("togglePanelItems(this, '%s', 'fa-angle-right', 'fa-angle-down');", content_id)+ |
|||
44 | +193 |
- )+ #' @rdname module_data_summary |
||
45 | +194 |
- )+ get_filter_overview_array <- function(current_data, |
||
46 | +195 |
- ),+ initial_data, |
||
47 | -! | +|||
196 | +
- tags$div(+ dataname, |
|||
48 | -! | +|||
197 | +
- id = content_id,+ subject_keys) { |
|||
49 | -! | +|||
198 | +152x |
- tags$div(+ if (length(subject_keys) == 0) { |
||
50 | -! | +|||
199 | +138x |
- class = "teal_active_summary_filter_panel",+ data.frame( |
||
51 | -! | +|||
200 | +138x |
- tableOutput(ns("table"))+ dataname = dataname, |
||
52 | -+ | |||
201 | +138x |
- )+ obs = if (!is.null(initial_data)) { |
||
53 | -+ | |||
202 | +127x |
- )+ sprintf("%s/%s", nrow(current_data), nrow(initial_data)) |
||
54 | +203 |
- )+ } else { |
||
55 | -+ | |||
204 | +11x |
- }+ nrow(current_data) |
||
56 | +205 |
-
+ } |
||
57 | +206 |
- #' @rdname module_data_summary+ ) |
||
58 | +207 |
- srv_data_summary <- function(id, teal_data) {+ } else { |
||
59 | -86x | +208 | +14x |
- assert_reactive(teal_data)+ data.frame( |
60 | -86x | +209 | +14x |
- moduleServer(+ dataname = dataname, |
61 | -86x | +210 | +14x |
- id = id,+ obs = if (!is.null(initial_data)) { |
62 | -86x | +211 | +13x |
- function(input, output, session) {+ sprintf("%s/%s", nrow(current_data), nrow(initial_data))+ |
+
212 | ++ |
+ } else { |
||
63 | -86x | +213 | +1x |
- logger::log_debug("srv_data_summary initializing")+ nrow(current_data) |
64 | +214 |
-
+ }, |
||
65 | -86x | +215 | +14x |
- summary_table <- reactive({+ subjects = if (!is.null(initial_data)) { |
66 | -94x | +216 | +13x | +
+ sprintf("%s/%s", nrow(unique(current_data[subject_keys])), nrow(unique(initial_data[subject_keys])))+ |
+
217 | +
- req(inherits(teal_data(), "teal_data"))+ } else { |
|||
67 | -88x | +218 | +1x |
- if (!length(teal_data())) {+ nrow(unique(current_data[subject_keys])) |
68 | -! | +|||
219 | +
- return(NULL)+ } |
|||
69 | +220 |
- }+ ) |
||
70 | -88x | +|||
221 | +
- get_filter_overview_wrapper(teal_data)+ } |
|||
71 | +222 |
- })+ } |
||
72 | +223 | |||
73 | -86x | +|||
224 | +
- output$table <- renderUI({+ #' @rdname module_data_summary |
|||
74 | -94x | +|||
225 | +
- summary_table_out <- try(summary_table(), silent = TRUE)+ get_filter_overview_MultiAssayExperiment <- function(current_data, # nolint: object_length, object_name. |
|||
75 | -94x | +|||
226 | +
- if (inherits(summary_table_out, "try-error")) {+ initial_data, |
|||
76 | +227 |
- # Ignore silent shiny error+ dataname) { |
||
77 | -6x | +228 | +1x |
- if (!inherits(attr(summary_table_out, "condition"), "shiny.silent.error")) {+ experiment_names <- names(current_data) |
78 | -! | +|||
229 | +1x |
- stop("Error occurred during data processing. See details in the main panel.")+ mae_info <- data.frame( |
||
79 | -+ | |||
230 | +1x |
- }+ dataname = dataname, |
||
80 | -88x | +231 | +1x |
- } else if (is.null(summary_table_out)) {+ subjects = if (!is.null(initial_data)) { |
81 | -2x | +|||
232 | +! |
- "no datasets to show"+ sprintf("%s/%s", nrow(current_data@colData), nrow(initial_data@colData)) |
||
82 | +233 |
- } else {+ } else { |
||
83 | -86x | +234 | +1x |
- is_unsupported <- apply(summary_table(), 1, function(x) all(is.na(x[-1])))+ nrow(current_data@colData) |
84 | -86x | +|||
235 | +
- summary_table_out[is.na(summary_table_out)] <- ""+ } |
|||
85 | -86x | +|||
236 | +
- body_html <- apply(+ )+ |
+ |||
237 | ++ | + | ||
86 | -86x | +238 | +1x |
- summary_table_out,+ experiment_obs_info <- do.call("rbind", lapply( |
87 | -86x | +239 | +1x |
- 1,+ experiment_names, |
88 | -86x | +240 | +1x |
- function(x) {+ function(experiment_name) { |
89 | -162x | +241 | +5x |
- is_supported <- !all(x[-1] == "")+ transform( |
90 | -162x | +242 | +5x |
- if (is_supported) {+ get_filter_overview( |
91 | -153x | +243 | +5x |
- tags$tr(+ current_data[[experiment_name]], |
92 | -153x | +244 | +5x |
- tagList(+ initial_data[[experiment_name]], |
93 | -153x | +245 | +5x |
- tags$td(x[1]),+ dataname = experiment_name, |
94 | -153x | +246 | +5x |
- lapply(x[-1], tags$td)+ subject_keys = join_keys() # empty join keys |
95 | +247 |
- )+ ), |
||
96 | -+ | |||
248 | +5x |
- )+ dataname = paste0(" - ", experiment_name) |
||
97 | +249 |
- }+ ) |
||
98 | +250 |
- }+ } |
||
99 | +251 |
- )+ )) |
||
100 | +252 | |||
101 | -86x | +253 | +1x |
- header_labels <- tools::toTitleCase(names(summary_table_out))+ get_experiment_keys <- function(mae, experiment) { |
102 | -86x | +254 | +5x |
- header_labels[header_labels == "Dataname"] <- "Data Name"+ sample_subset <- mae@sampleMap[mae@sampleMap$colname %in% colnames(experiment), ] |
103 | -86x | +255 | +5x |
- header_html <- tags$tr(tagList(lapply(header_labels, tags$td)))+ length(unique(sample_subset$primary)) |
104 | +256 | - - | -||
105 | -86x | -
- table_html <- tags$table(- |
- ||
106 | -86x | -
- class = "table custom-table",+ } |
||
107 | -86x | +|||
257 | +
- tags$thead(header_html),+ |
|||
108 | -86x | -
- tags$tbody(body_html)- |
- ||
109 | -+ | 258 | +1x |
- )+ experiment_subjects_info <- do.call("rbind", lapply( |
110 | -86x | +259 | +1x |
- div(+ experiment_names, |
111 | -86x | +260 | +1x |
- table_html,+ function(experiment_name) { |
112 | -86x | +261 | +5x |
- if (any(is_unsupported)) {+ data.frame( |
113 | -9x | +262 | +5x |
- p(+ subjects = if (!is.null(initial_data)) { |
114 | -9x | +|||
263 | +! |
- class = c("pull-right", "float-right", "text-secondary"),+ sprintf( |
||
115 | -9x | +|||
264 | +! |
- style = "font-size: 0.8em;",+ "%s/%s", |
||
116 | -9x | +|||
265 | +! |
- sprintf("And %s more unfilterable object(s)", sum(is_unsupported)),+ get_experiment_keys(current_data, current_data[[experiment_name]]), |
||
117 | -9x | +|||
266 | +! |
- icon(+ get_experiment_keys(current_data, initial_data[[experiment_name]]) |
||
118 | -9x | +|||
267 | +
- name = "far fa-circle-question",+ ) |
|||
119 | -9x | +|||
268 | +
- title = paste(+ } else { |
|||
120 | -9x | +269 | +5x |
- sep = "",+ get_experiment_keys(current_data, current_data[[experiment_name]]) |
121 | -9x | +|||
270 | +
- collapse = "\n",+ } |
|||
122 | -9x | +|||
271 | +
- shQuote(summary_table()[is_unsupported, "dataname"]),+ ) |
|||
123 | +272 |
- " (",+ } |
||
124 | -9x | +|||
273 | +
- vapply(+ )) |
|||
125 | -9x | +|||
274 | +
- summary_table()[is_unsupported, "dataname"],+ |
|||
126 | -9x | +275 | +1x |
- function(x) class(teal_data()[[x]])[1],+ experiment_info <- cbind(experiment_obs_info, experiment_subjects_info) |
127 | -9x | +276 | +1x |
- character(1L)+ .smart_rbind(mae_info, experiment_info) |
128 | +277 |
- ),+ } |
129 | +1 |
- ")"+ #' Filter panel module in teal |
||
130 | +2 |
- )+ #' |
||
131 | +3 |
- )+ #' Creates filter panel module from `teal_data` object and returns `teal_data`. It is build in a way |
||
132 | +4 |
- )+ #' that filter panel changes and anything what happens before (e.g. [`module_init_data`]) is triggering |
||
133 | +5 |
- }+ #' further reactive events only if something has changed and if the module is visible. Thanks to |
||
134 | +6 |
- )+ #' this special implementation all modules' data are recalculated only for those modules which are |
||
135 | +7 |
- }+ #' currently displayed. |
||
136 | +8 |
- })+ #' |
||
137 | +9 | - - | -||
138 | -86x | -
- NULL+ #' @return A `eventReactive` containing `teal_data` containing filtered objects and filter code. |
||
139 | +10 |
- }+ #' `eventReactive` triggers only if all conditions are met: |
||
140 | +11 |
- )+ #' - tab is selected (`is_active`) |
||
141 | +12 |
- }+ #' - when filters are changed (`get_filter_expr` is different than previous) |
||
142 | +13 |
-
+ #' |
||
143 | +14 |
- #' @rdname module_data_summary+ #' @inheritParams module_teal_module |
||
144 | +15 |
- get_filter_overview_wrapper <- function(teal_data) {+ #' @param active_datanames (`reactive` returning `character`) this module's data names |
||
145 | +16 |
- # Sort datanames in topological order+ #' @name module_filter_data |
||
146 | -88x | +|||
17 | +
- datanames <- names(teal_data())+ #' @keywords internal |
|||
147 | -88x | +|||
18 | +
- joinkeys <- teal.data::join_keys(teal_data())+ NULL |
|||
148 | +19 | |||
149 | -88x | +|||
20 | +
- current_data_objs <- sapply(+ #' @rdname module_filter_data |
|||
150 | -88x | +|||
21 | +
- datanames,+ ui_filter_data <- function(id) { |
|||
151 | -88x | +|||
22 | +! |
- function(name) teal_data()[[name]],+ ns <- shiny::NS(id) |
||
152 | -88x | +|||
23 | +! |
- simplify = FALSE+ uiOutput(ns("panel")) |
||
153 | +24 |
- )+ } |
||
154 | -88x | +|||
25 | +
- initial_data_objs <- teal_data()[[".raw_data"]]+ |
|||
155 | +26 |
-
+ #' @rdname module_filter_data |
||
156 | -88x | +|||
27 | +
- out <- lapply(+ srv_filter_data <- function(id, datasets, active_datanames, data, is_active) { |
|||
157 | -88x | +28 | +86x |
- datanames,+ assert_reactive(datasets) |
158 | -88x | +29 | +86x |
- function(dataname) {+ moduleServer(id, function(input, output, session) { |
159 | -157x | +30 | +86x |
- parent <- teal.data::parent(joinkeys, dataname)+ active_corrected <- reactive(intersect(active_datanames(), datasets()$datanames())) |
160 | -157x | +|||
31 | +
- subject_keys <- if (length(parent) > 0) {+ |
|||
161 | -8x | +32 | +86x |
- names(joinkeys[dataname, parent])+ output$panel <- renderUI({ |
162 | -+ | |||
33 | +88x |
- } else {+ req(inherits(datasets(), "FilteredData")) |
||
163 | -149x | +34 | +88x |
- joinkeys[dataname, dataname]+ isolate({ |
164 | +35 |
- }+ # render will be triggered only when FilteredData object changes (not when filters change) |
||
165 | -157x | +|||
36 | +
- get_filter_overview(+ # technically it means that teal_data_module needs to be refreshed |
|||
166 | -157x | +37 | +88x |
- current_data = current_data_objs[[dataname]],+ logger::log_debug("srv_filter_panel rendering filter panel.") |
167 | -157x | +38 | +88x |
- initial_data = initial_data_objs[[dataname]],+ if (length(active_corrected())) { |
168 | -157x | +39 | +86x |
- dataname = dataname,+ datasets()$srv_active("filters", active_datanames = active_corrected) |
169 | -157x | +40 | +86x |
- subject_keys = subject_keys+ datasets()$ui_active(session$ns("filters"), active_datanames = active_corrected) |
170 | +41 |
- )+ } |
||
171 | +42 |
- }+ }) |
||
172 | +43 |
- )+ }) |
||
173 | +44 | |||
174 | -88x | +45 | +86x |
- do.call(.smart_rbind, out)+ trigger_data <- .observe_active_filter_changed(datasets, is_active, active_corrected, data) |
175 | +46 |
- }+ |
||
176 | -+ | |||
47 | +86x |
-
+ eventReactive(trigger_data(), { |
||
177 | -+ | |||
48 | +89x |
-
+ .make_filtered_teal_data(modules, data = data(), datasets = datasets(), datanames = active_corrected()) |
||
178 | +49 |
- #' @rdname module_data_summary+ }) |
||
179 | +50 |
- #' @param current_data (`object`) current object (after filtering and transforming).+ }) |
||
180 | +51 |
- #' @param initial_data (`object`) initial object.+ } |
||
181 | +52 |
- #' @param dataname (`character(1)`)+ |
||
182 | +53 |
- #' @param subject_keys (`character`) names of the columns which determine a single unique subjects+ #' @rdname module_filter_data |
||
183 | +54 |
- get_filter_overview <- function(current_data, initial_data, dataname, subject_keys) {+ .make_filtered_teal_data <- function(modules, data, datasets = NULL, datanames) { |
||
184 | -162x | +55 | +89x |
- if (inherits(current_data, c("data.frame", "DataFrame", "array", "Matrix", "SummarizedExperiment"))) {+ data <- eval_code( |
185 | -152x | +56 | +89x |
- get_filter_overview_array(current_data, initial_data, dataname, subject_keys)+ data, |
186 | -10x | +57 | +89x |
- } else if (inherits(current_data, "MultiAssayExperiment")) {+ paste0( |
187 | -1x | +58 | +89x |
- get_filter_overview_MultiAssayExperiment(current_data, initial_data, dataname)+ ".raw_data <- list2env(list(", |
188 | -+ | |||
59 | +89x |
- } else {+ toString(sprintf("%1$s = %1$s", sapply(datanames, as.name))), |
||
189 | -9x | +60 | +89x |
- data.frame(dataname = dataname)+ "))\n", |
190 | -+ | |||
61 | +89x |
- }+ "lockEnvironment(.raw_data) # @linksto .raw_data" # this is environment and it is shared by qenvs. CAN'T MODIFY! |
||
191 | +62 |
- }+ ) |
||
192 | +63 |
-
+ ) |
||
193 | -+ | |||
64 | +89x |
- #' @rdname module_data_summary+ filtered_code <- .get_filter_expr(datasets = datasets, datanames = datanames)+ |
+ ||
65 | +89x | +
+ filtered_teal_data <- .append_evaluated_code(data, filtered_code)+ |
+ ||
66 | +89x | +
+ filtered_datasets <- sapply(datanames, function(x) datasets$get_data(x, filtered = TRUE), simplify = FALSE)+ |
+ ||
67 | +89x | +
+ filtered_teal_data <- .append_modified_data(filtered_teal_data, filtered_datasets)+ |
+ ||
68 | +89x | +
+ filtered_teal_data |
||
194 | +69 |
- get_filter_overview_array <- function(current_data,+ } |
||
195 | +70 |
- initial_data,+ |
||
196 | +71 |
- dataname,+ #' @rdname module_filter_data |
||
197 | +72 |
- subject_keys) {+ .observe_active_filter_changed <- function(datasets, is_active, active_datanames, data) { |
||
198 | -152x | +73 | +86x |
- if (length(subject_keys) == 0) {+ previous_signature <- reactiveVal(NULL) |
199 | -138x | +74 | +86x |
- data.frame(+ filter_changed <- reactive({ |
200 | -138x | +75 | +195x |
- dataname = dataname,+ req(inherits(datasets(), "FilteredData")) |
201 | -138x | +76 | +195x |
- obs = if (!is.null(initial_data)) {+ new_signature <- c( |
202 | -127x | +77 | +195x |
- sprintf("%s/%s", nrow(current_data), nrow(initial_data))+ teal.code::get_code(data()),+ |
+
78 | +195x | +
+ .get_filter_expr(datasets = datasets(), datanames = active_datanames()) |
||
203 | +79 |
- } else {+ ) |
||
204 | -11x | +80 | +195x |
- nrow(current_data)+ if (!identical(previous_signature(), new_signature)) {+ |
+
81 | +94x | +
+ previous_signature(new_signature)+ |
+ ||
82 | +94x | +
+ TRUE+ |
+ ||
83 | ++ |
+ } else {+ |
+ ||
84 | +101x | +
+ FALSE |
||
205 | +85 |
- }+ } |
||
206 | +86 |
- )+ }) |
||
207 | +87 |
- } else {- |
- ||
208 | -14x | -
- data.frame(+ |
||
209 | -14x | +88 | +86x |
- dataname = dataname,+ trigger_data <- reactiveVal(NULL) |
210 | -14x | +89 | +86x |
- obs = if (!is.null(initial_data)) {+ observe({ |
211 | -13x | -
- sprintf("%s/%s", nrow(current_data), nrow(initial_data))- |
- ||
212 | -+ | 90 | +208x |
- } else {+ if (isTRUE(is_active() && filter_changed())) { |
213 | -1x | -
- nrow(current_data)- |
- ||
214 | -+ | 91 | +94x |
- },+ isolate({ |
215 | -14x | +92 | +94x |
- subjects = if (!is.null(initial_data)) {+ if (is.null(trigger_data())) { |
216 | -13x | +93 | +86x |
- sprintf("%s/%s", nrow(unique(current_data[subject_keys])), nrow(unique(initial_data[subject_keys])))+ trigger_data(0) |
217 | +94 |
- } else {+ } else { |
||
218 | -1x | +95 | +8x |
- nrow(unique(current_data[subject_keys]))+ trigger_data(trigger_data() + 1) |
219 | +96 |
- }+ } |
||
220 | +97 |
- )+ }) |
||
221 | +98 |
- }+ } |
||
222 | +99 |
- }+ }) |
||
223 | +100 | |||
224 | -+ | |||
101 | +86x |
- #' @rdname module_data_summary+ trigger_data |
||
225 | +102 |
- get_filter_overview_MultiAssayExperiment <- function(current_data, # nolint: object_length, object_name.+ } |
||
226 | +103 |
- initial_data,+ |
||
227 | +104 |
- dataname) {- |
- ||
228 | -1x | -
- experiment_names <- names(current_data)+ #' @rdname module_filter_data |
||
229 | -1x | +|||
105 | +
- mae_info <- data.frame(+ .get_filter_expr <- function(datasets, datanames) { |
|||
230 | -1x | +106 | +284x |
- dataname = dataname,+ if (length(datanames)) { |
231 | -1x | -
- subjects = if (!is.null(initial_data)) {- |
- ||
232 | -! | +107 | +278x |
- sprintf("%s/%s", nrow(current_data@colData), nrow(initial_data@colData))+ teal.slice::get_filter_expr(datasets = datasets, datanames = datanames) |
233 | +108 |
- } else {+ } else { |
||
234 | -1x | +109 | +6x |
- nrow(current_data@colData)+ NULL |
235 | +110 |
- }+ } |
||
236 | +111 |
- )+ } |
237 | +1 | - - | -|
238 | -1x | -
- experiment_obs_info <- do.call("rbind", lapply(- |
- |
239 | -1x | -
- experiment_names,- |
- |
240 | -1x | -
- function(experiment_name) {- |
- |
241 | -5x | -
- transform(- |
- |
242 | -5x | -
- get_filter_overview(- |
- |
243 | -5x | -
- current_data[[experiment_name]],+ #' Data module for `teal` applications |
|
244 | -5x | +||
2 | +
- initial_data[[experiment_name]],+ #' |
||
245 | -5x | +||
3 | +
- dataname = experiment_name,+ #' @description |
||
246 | -5x | +||
4 | +
- subject_keys = join_keys() # empty join keys+ #' `r lifecycle::badge("experimental")` |
||
247 | +5 |
- ),+ #' |
|
248 | -5x | +||
6 | +
- dataname = paste0(" - ", experiment_name)+ #' Create a `teal_data_module` object and evaluate code on it with history tracking. |
||
249 | +7 |
- )+ #' |
|
250 | +8 |
- }+ #' @details |
|
251 | +9 |
- ))+ #' `teal_data_module` creates a `shiny` module to interactively supply or modify data in a `teal` application. |
|
252 | +10 |
-
+ #' The module allows for running any code (creation _and_ some modification) after the app starts or reloads. |
|
253 | -1x | +||
11 | +
- get_experiment_keys <- function(mae, experiment) {+ #' The body of the server function will be run in the app rather than in the global environment. |
||
254 | -5x | +||
12 | +
- sample_subset <- mae@sampleMap[mae@sampleMap$colname %in% colnames(experiment), ]+ #' This means it will be run every time the app starts, so use sparingly. |
||
255 | -5x | +||
13 | +
- length(unique(sample_subset$primary))+ #' |
||
256 | +14 |
- }+ #' Pass this module instead of a `teal_data` object in a call to [init()]. |
|
257 | +15 |
-
+ #' Note that the server function must always return a `teal_data` object wrapped in a reactive expression. |
|
258 | -1x | +||
16 | +
- experiment_subjects_info <- do.call("rbind", lapply(+ #' |
||
259 | -1x | +||
17 | +
- experiment_names,+ #' See vignette `vignette("data-as-shiny-module", package = "teal")` for more details. |
||
260 | -1x | +||
18 | +
- function(experiment_name) {+ #' |
||
261 | -5x | +||
19 | +
- data.frame(+ #' @param ui (`function(id)`) |
||
262 | -5x | +||
20 | +
- subjects = if (!is.null(initial_data)) {+ #' `shiny` module UI function; must only take `id` argument |
||
263 | -! | +||
21 | +
- sprintf(+ #' @param server (`function(id)`) |
||
264 | -! | +||
22 | +
- "%s/%s",+ #' `shiny` module server function; must only take `id` argument; |
||
265 | -! | +||
23 | +
- get_experiment_keys(current_data, current_data[[experiment_name]]),+ #' must return reactive expression containing `teal_data` object |
||
266 | -! | +||
24 | +
- get_experiment_keys(current_data, initial_data[[experiment_name]])+ #' @param label (`character(1)`) Label of the module. |
||
267 | +25 |
- )+ #' @param once (`logical(1)`) |
|
268 | +26 |
- } else {+ #' If `TRUE`, the data module will be shown only once and will disappear after successful data loading. |
|
269 | -5x | +||
27 | +
- get_experiment_keys(current_data, current_data[[experiment_name]])+ #' App user will no longer be able to interact with this module anymore. |
||
270 | +28 |
- }+ #' If `FALSE`, the data module can be reused multiple times. |
|
271 | +29 |
- )+ #' App user will be able to interact and change the data output from the module multiple times. |
|
272 | +30 |
- }+ #' |
|
273 | +31 |
- ))+ #' @return |
|
274 | +32 |
-
+ #' `teal_data_module` returns a list of class `teal_data_module` containing two elements, `ui` and |
|
275 | -1x | +||
33 | +
- experiment_info <- cbind(experiment_obs_info, experiment_subjects_info)+ #' `server` provided via arguments. |
||
276 | -1x | +||
34 | +
- .smart_rbind(mae_info, experiment_info)+ #' |
||
277 | +35 |
- }+ #' @examples |
1 | +36 |
- #' Filter panel module in teal+ #' tdm <- teal_data_module( |
||
2 | +37 |
- #'+ #' ui = function(id) { |
||
3 | +38 |
- #' Creates filter panel module from `teal_data` object and returns `teal_data`. It is build in a way+ #' ns <- NS(id) |
||
4 | +39 |
- #' that filter panel changes and anything what happens before (e.g. [`module_init_data`]) is triggering+ #' actionButton(ns("submit"), label = "Load data") |
||
5 | +40 |
- #' further reactive events only if something has changed and if the module is visible. Thanks to+ #' }, |
||
6 | +41 |
- #' this special implementation all modules' data are recalculated only for those modules which are+ #' server = function(id) { |
||
7 | +42 |
- #' currently displayed.+ #' moduleServer(id, function(input, output, session) { |
||
8 | +43 |
- #'+ #' eventReactive(input$submit, { |
||
9 | +44 |
- #' @return A `eventReactive` containing `teal_data` containing filtered objects and filter code.+ #' data <- within( |
||
10 | +45 |
- #' `eventReactive` triggers only if all conditions are met:+ #' teal_data(), |
||
11 | +46 |
- #' - tab is selected (`is_active`)+ #' { |
||
12 | +47 |
- #' - when filters are changed (`get_filter_expr` is different than previous)+ #' dataset1 <- iris |
||
13 | +48 |
- #'+ #' dataset2 <- mtcars |
||
14 | +49 |
- #' @inheritParams module_teal_module+ #' } |
||
15 | +50 |
- #' @param active_datanames (`reactive` returning `character`) this module's data names+ #' ) |
||
16 | +51 |
- #' @name module_filter_data+ #' |
||
17 | +52 |
- #' @keywords internal+ #' data |
||
18 | +53 |
- NULL+ #' }) |
||
19 | +54 |
-
+ #' }) |
||
20 | +55 |
- #' @rdname module_filter_data+ #' } |
||
21 | +56 |
- ui_filter_data <- function(id) {+ #' ) |
||
22 | -! | +|||
57 | +
- ns <- shiny::NS(id)+ #' |
|||
23 | -! | +|||
58 | +
- uiOutput(ns("panel"))+ #' @name teal_data_module |
|||
24 | +59 |
- }+ #' @seealso [`teal.data::teal_data-class`], [teal.code::qenv()] |
||
25 | +60 |
-
+ #' |
||
26 | +61 |
- #' @rdname module_filter_data+ #' @export |
||
27 | +62 |
- srv_filter_data <- function(id, datasets, active_datanames, data_rv, is_active) {+ teal_data_module <- function(ui, server, label = "data module", once = TRUE) { |
||
28 | -86x | +63 | +33x |
- assert_reactive(datasets)+ checkmate::assert_function(ui, args = "id", nargs = 1) |
29 | -86x | +64 | +32x |
- moduleServer(id, function(input, output, session) {+ checkmate::assert_function(server, args = "id", nargs = 1) |
30 | -86x | +65 | +30x |
- active_corrected <- reactive(intersect(active_datanames(), datasets()$datanames()))+ checkmate::assert_string(label) |
31 | -+ | |||
66 | +30x |
-
+ checkmate::assert_flag(once) |
||
32 | -86x | +67 | +30x |
- output$panel <- renderUI({+ structure( |
33 | -88x | +68 | +30x |
- req(inherits(datasets(), "FilteredData"))+ list( |
34 | -88x | +69 | +30x |
- isolate({+ ui = ui, |
35 | -+ | |||
70 | +30x |
- # render will be triggered only when FilteredData object changes (not when filters change)+ server = function(id) { |
||
36 | -+ | |||
71 | +23x |
- # technically it means that teal_data_module needs to be refreshed+ data_out <- server(id) |
||
37 | -88x | +72 | +22x |
- logger::log_debug("srv_filter_panel rendering filter panel.")+ decorate_err_msg( |
38 | -88x | +73 | +22x |
- if (length(active_corrected())) {+ assert_reactive(data_out), |
39 | -86x | +74 | +22x |
- datasets()$srv_active("filters", active_datanames = active_corrected)+ pre = sprintf("From: 'teal_data_module()':\nA 'teal_data_module' with \"%s\" label:", label), |
40 | -86x | +75 | +22x |
- datasets()$ui_active(session$ns("filters"), active_datanames = active_corrected)+ post = "Please make sure that this module returns a 'reactive` object containing 'teal_data' class of object." # nolint: line_length_linter. |
41 | +76 |
- }+ ) |
||
42 | +77 |
- })+ } |
||
43 | +78 |
- })+ ), |
||
44 | -+ | |||
79 | +30x |
-
+ label = label, |
||
45 | -86x | +80 | +30x |
- trigger_data <- .observe_active_filter_changed(datasets, is_active, active_corrected, data_rv)+ class = "teal_data_module", |
46 | -+ | |||
81 | +30x |
-
+ once = once |
||
47 | -86x | +|||
82 | +
- eventReactive(trigger_data(), {+ ) |
|||
48 | -89x | +|||
83 | +
- .make_filtered_teal_data(modules, data = data_rv(), datasets = datasets(), datanames = active_corrected())+ } |
49 | +1 |
- })+ #' Generate lockfile for application's environment reproducibility |
||
50 | +2 |
- })+ #' |
||
51 | +3 |
- }+ #' @param lockfile_path (`character`) path to the lockfile. |
||
52 | +4 |
-
+ #' |
||
53 | +5 |
- #' @rdname module_filter_data+ #' @section Different ways of creating lockfile: |
||
54 | +6 |
- .make_filtered_teal_data <- function(modules, data, datasets = NULL, datanames) {+ #' `teal` leverages [renv::snapshot()], which offers multiple methods for lockfile creation. |
||
55 | -89x | +|||
7 | +
- data <- eval_code(+ #' |
|||
56 | -89x | +|||
8 | +
- data,+ #' - **Working directory lockfile**: `teal`, by default, will create an `implicit` type lockfile that uses |
|||
57 | -89x | +|||
9 | +
- paste0(+ #' `renv::dependencies()` to detect all R packages in the current project's working directory. |
|||
58 | -89x | +|||
10 | +
- ".raw_data <- list2env(list(",+ #' - **`DESCRIPTION`-based lockfile**: To generate a lockfile based on a `DESCRIPTION` file in your working |
|||
59 | -89x | +|||
11 | +
- toString(sprintf("%1$s = %1$s", sapply(datanames, as.name))),+ #' directory, set `renv::settings$snapshot.type("explicit")`. The naming convention for `type` follows |
|||
60 | -89x | +|||
12 | +
- "))\n",+ #' `renv::snapshot()`. For the `"explicit"` type, refer to `renv::settings$package.dependency.fields()` for the |
|||
61 | -89x | +|||
13 | +
- "lockEnvironment(.raw_data) # @linksto .raw_data" # this is environment and it is shared by qenvs. CAN'T MODIFY!+ #' `DESCRIPTION` fields included in the lockfile. |
|||
62 | +14 |
- )+ #' - **Custom files-based lockfile**: To specify custom files as the basis for the lockfile, set |
||
63 | +15 |
- )+ #' `renv::settings$snapshot.type("custom")` and configure the `renv.snapshot.filter` option. |
||
64 | -89x | +|||
16 | +
- filtered_code <- .get_filter_expr(datasets = datasets, datanames = datanames)+ #' |
|||
65 | -89x | +|||
17 | +
- filtered_teal_data <- .append_evaluated_code(data, filtered_code)+ #' @section lockfile usage: |
|||
66 | -89x | +|||
18 | +
- filtered_datasets <- sapply(datanames, function(x) datasets$get_data(x, filtered = TRUE), simplify = FALSE)+ #' After creating the lockfile, you can restore the application's environment using `renv::restore()`. |
|||
67 | -89x | +|||
19 | +
- filtered_teal_data <- .append_modified_data(filtered_teal_data, filtered_datasets)+ #' |
|||
68 | -89x | +|||
20 | +
- filtered_teal_data+ #' @seealso [renv::snapshot()], [renv::restore()]. |
|||
69 | +21 |
- }+ #' |
||
70 | +22 |
-
+ #' @return `NULL` |
||
71 | +23 |
- #' @rdname module_filter_data+ #' |
||
72 | +24 |
- .observe_active_filter_changed <- function(datasets, is_active, active_datanames, data_rv) {+ #' @name module_teal_lockfile |
||
73 | -86x | +|||
25 | +
- previous_signature <- reactiveVal(NULL)+ #' @rdname module_teal_lockfile |
|||
74 | -86x | +|||
26 | +
- filter_changed <- reactive({+ #' |
|||
75 | -195x | +|||
27 | +
- req(inherits(datasets(), "FilteredData"))+ #' @keywords internal |
|||
76 | -195x | +|||
28 | +
- new_signature <- c(+ NULL |
|||
77 | -195x | +|||
29 | +
- teal.code::get_code(data_rv()),+ |
|||
78 | -195x | +|||
30 | +
- .get_filter_expr(datasets = datasets(), datanames = active_datanames())+ #' @rdname module_teal_lockfile |
|||
79 | +31 |
- )+ ui_teal_lockfile <- function(id) { |
||
80 | -195x | +|||
32 | +! |
- if (!identical(previous_signature(), new_signature)) {+ ns <- NS(id) |
||
81 | -94x | +|||
33 | +! |
- previous_signature(new_signature)+ shiny::tagList( |
||
82 | -94x | +|||
34 | +! |
- TRUE+ tags$span("", id = ns("lockFileStatus")),+ |
+ ||
35 | +! | +
+ shinyjs::disabled(downloadLink(ns("lockFileLink"), "Download lockfile")) |
||
83 | +36 |
- } else {+ ) |
||
84 | -101x | +|||
37 | +
- FALSE+ } |
|||
85 | +38 |
- }+ |
||
86 | +39 |
- })+ #' @rdname module_teal_lockfile |
||
87 | +40 |
-
+ srv_teal_lockfile <- function(id) { |
||
88 | -86x | +41 | +88x |
- trigger_data <- reactiveVal(NULL)+ moduleServer(id, function(input, output, session) { |
89 | -86x | +42 | +88x |
- observe({+ logger::log_debug("Initialize srv_teal_lockfile.") |
90 | -208x | +43 | +88x |
- if (isTRUE(is_active() && filter_changed())) {+ enable_lockfile_download <- function() { |
91 | -94x | +|||
44 | +! |
- isolate({+ shinyjs::html("lockFileStatus", "Application lockfile ready.") |
||
92 | -94x | +|||
45 | +! |
- if (is.null(trigger_data())) {+ shinyjs::hide("lockFileStatus", anim = TRUE) |
||
93 | -86x | +|||
46 | +! |
- trigger_data(0)+ shinyjs::enable("lockFileLink")+ |
+ ||
47 | +! | +
+ output$lockFileLink <- shiny::downloadHandler(+ |
+ ||
48 | +! | +
+ filename = function() {+ |
+ ||
49 | +! | +
+ "renv.lock" |
||
94 | +50 |
- } else {+ }, |
||
95 | -8x | +|||
51 | +! |
- trigger_data(trigger_data() + 1)+ content = function(file) {+ |
+ ||
52 | +! | +
+ file.copy(lockfile_path, file) |
||
96 | -+ | |||
53 | +! |
- }+ file |
||
97 | +54 |
- })+ }, |
||
98 | -+ | |||
55 | +! |
- }+ contentType = "application/json" |
||
99 | +56 |
- })+ ) |
||
100 | +57 |
-
+ } |
||
101 | -86x | +58 | +88x |
- trigger_data+ disable_lockfile_download <- function() { |
102 | -+ | |||
59 | +! |
- }+ warning("Lockfile creation failed.", call. = FALSE) |
||
103 | -+ | |||
60 | +! |
-
+ shinyjs::html("lockFileStatus", "Lockfile creation failed.")+ |
+ ||
61 | +! | +
+ shinyjs::hide("lockFileLink") |
||
104 | +62 |
- #' @rdname module_filter_data+ } |
||
105 | +63 |
- .get_filter_expr <- function(datasets, datanames) {+ |
||
106 | -284x | +64 | +88x |
- if (length(datanames)) {+ shiny::onStop(function() { |
107 | -278x | +65 | +88x |
- teal.slice::get_filter_expr(datasets = datasets, datanames = datanames)+ if (file.exists(lockfile_path) && !shiny::isRunning()) { |
108 | -+ | |||
66 | +1x |
- } else {+ logger::log_debug("Removing lockfile after shutting down the app") |
||
109 | -6x | +67 | +1x |
- NULL+ file.remove(lockfile_path) |
110 | +68 |
- }+ } |
||
111 | +69 |
- }+ }) |
1 | +70 |
- #' `teal_data` utils+ |
||
2 | -+ | |||
71 | +88x |
- #'+ lockfile_path <- "teal_app.lock" |
||
3 | -+ | |||
72 | +88x |
- #' In `teal` we need to recreate the `teal_data` object due to two operations:+ mode <- getOption("teal.lockfile.mode", default = "") |
||
4 | +73 |
- #' - we need to append filter-data code and objects which have been evaluated in `FilteredData` and+ |
||
5 | -+ | |||
74 | +88x |
- #' we want to avoid double-evaluation.+ if (!(mode %in% c("auto", "enabled", "disabled"))) { |
||
6 | -+ | |||
75 | +! |
- #' - we need to subset `teal_data` to `datanames` used by the module, to shorten obtainable R-code+ stop("'teal.lockfile.mode' option can only be one of \"auto\", \"disabled\" or \"disabled\". ") |
||
7 | +76 |
- #'+ } |
||
8 | +77 |
- #' Due to above recreation of `teal_data` object can't be done simply by using public+ |
||
9 | -+ | |||
78 | +88x |
- #' `teal.code` and `teal.data` methods.+ if (mode == "disabled") { |
||
10 | -+ | |||
79 | +1x |
- #'+ logger::log_debug("'teal.lockfile.mode' option is set to 'disabled'. Hiding lockfile download button.") |
||
11 | -+ | |||
80 | +1x |
- #' @param data (`teal_data`)+ shinyjs::hide("lockFileLink") |
||
12 | -+ | |||
81 | +1x |
- #' @param code (`character`) code to append to the object's code slot.+ return(NULL) |
||
13 | +82 |
- #' @param objects (`list`) objects to append to object's environment.+ } |
||
14 | +83 |
- #' @return modified `teal_data`+ |
||
15 | -+ | |||
84 | +87x |
- #' @keywords internal+ if (file.exists(lockfile_path)) { |
||
16 | -+ | |||
85 | +! |
- #' @name teal_data_utilities+ logger::log_debug("Lockfile has already been created for this app - skipping automatic creation.") |
||
17 | -+ | |||
86 | +! |
- NULL+ enable_lockfile_download() |
||
18 | -+ | |||
87 | +! |
-
+ return(NULL) |
||
19 | +88 |
- #' @rdname teal_data_utilities+ } |
||
20 | +89 |
- .append_evaluated_code <- function(data, code) {- |
- ||
21 | -89x | -
- checkmate::assert_class(data, "teal_data")+ |
||
22 | -89x | +90 | +87x |
- data@code <- c(data@code, code2list(code))+ if (mode == "auto" && .is_disabled_lockfile_scenario()) { |
23 | -89x | +91 | +86x |
- methods::validObject(data)+ logger::log_debug( |
24 | -89x | +92 | +86x |
- data+ "Automatic lockfile creation disabled. Execution scenario satisfies teal:::.is_disabled_lockfile_scenario()." |
25 | +93 |
- }+ ) |
||
26 | -+ | |||
94 | +86x |
-
+ shinyjs::hide("lockFileLink") |
||
27 | -+ | |||
95 | +86x |
- #' @rdname teal_data_utilities+ return(NULL) |
||
28 | +96 |
- .append_modified_data <- function(data, objects) {+ } |
||
29 | -89x | +|||
97 | +
- checkmate::assert_class(data, "teal_data")+ |
|||
30 | -89x | +98 | +1x |
- checkmate::assert_class(objects, "list")+ if (!.is_lockfile_deps_installed()) { |
31 | -89x | +|||
99 | +! |
- new_env <- list2env(objects, parent = .GlobalEnv)+ warning("Automatic lockfile creation disabled. `mirai` and `renv` packages must be installed.") |
||
32 | -89x | +|||
100 | +! |
- rlang::env_coalesce(new_env, as.environment(data))+ shinyjs::hide("lockFileLink") |
||
33 | -89x | +|||
101 | +! |
- data@.xData <- new_env+ return(NULL) |
||
34 | -89x | +|||
102 | +
- data+ } |
|||
35 | +103 |
- }+ |
1 | +104 |
- #' UI and server modules of `teal`+ # - Will be run only if the lockfile doesn't exist (see the if-s above) |
|
2 | +105 |
- #'+ # - We render to the tempfile because the process might last after session is closed and we don't |
|
3 | +106 |
- #' @description `r lifecycle::badge("deprecated")`+ # want to make a "teal_app.renv" then. This is why we copy only during active session. |
|
4 | -+ | ||
107 | +1x |
- #' Please use [`module_teal`] instead.+ process <- .teal_lockfile_process_invoke(lockfile_path) |
|
5 | -+ | ||
108 | +1x |
- #'+ observeEvent(process$status(), { |
|
6 | -+ | ||
109 | +! |
- #' @inheritParams ui_teal+ if (process$status() %in% c("initial", "running")) { |
|
7 | -+ | ||
110 | +! |
- #' @inheritParams srv_teal+ shinyjs::html("lockFileStatus", "Creating lockfile...") |
|
8 | -+ | ||
111 | +! |
- #'+ } else if (process$status() == "success") { |
|
9 | -+ | ||
112 | +! |
- #' @return+ result <- process$result() |
|
10 | -+ | ||
113 | +! |
- #' Returns a `reactive` expression containing a `teal_data` object when data is loaded or `NULL` when it is not.+ if (any(grepl("Lockfile written to", result$out))) { |
|
11 | -+ | ||
114 | +! |
- #' @name module_teal_with_splash+ logger::log_debug("Lockfile containing { length(result$res$Packages) } packages created.") |
|
12 | -+ | ||
115 | +! |
- #'+ if (any(grepl("(WARNING|ERROR):", result$out))) { |
|
13 | -+ | ||
116 | +! |
- NULL+ warning("Lockfile created with warning(s) or error(s):", call. = FALSE) |
|
14 | -+ | ||
117 | +! |
-
+ for (i in result$out) { |
|
15 | -+ | ||
118 | +! |
- #' @export+ warning(i, call. = FALSE) |
|
16 | +119 |
- #' @rdname module_teal_with_splash+ } |
|
17 | +120 |
- ui_teal_with_splash <- function(id,+ } |
|
18 | -+ | ||
121 | +! |
- data,+ enable_lockfile_download() |
|
19 | +122 |
- title = build_app_title(),+ } else { |
|
20 | -+ | ||
123 | +! |
- header = tags$p(),+ disable_lockfile_download() |
|
21 | +124 |
- footer = tags$p()) {+ } |
|
22 | +125 | ! |
- lifecycle::deprecate_soft(+ } else if (process$status() == "error") { |
23 | +126 | ! |
- when = "0.16",+ disable_lockfile_download() |
24 | -! | +||
127 | +
- what = "ui_teal_with_splash()",+ } |
||
25 | -! | +||
128 | ++ |
+ })+ |
+ |
129 | ++ | + + | +|
130 | +1x |
- details = "Deprecated, please use `ui_teal` instead"+ NULL |
|
26 | +131 |
- )+ }) |
|
27 | -! | +||
132 | +
- ui_teal(id = id, title = title, header = header, footer = footer)+ } |
||
28 | +133 |
- }+ |
|
29 | +134 |
-
+ utils::globalVariables(c("opts", "sysenv", "libpaths", "wd", "lockfilepath", "run")) # needed for mirai call |
|
30 | +135 |
- #' @export+ #' @rdname module_teal_lockfile |
|
31 | +136 |
- #' @rdname module_teal_with_splash+ .teal_lockfile_process_invoke <- function(lockfile_path) {+ |
+ |
137 | +1x | +
+ mirai_obj <- NULL+ |
+ |
138 | +1x | +
+ process <- shiny::ExtendedTask$new(function() {+ |
+ |
139 | +1x | +
+ m <- mirai::mirai( |
|
32 | +140 |
- srv_teal_with_splash <- function(id, data, modules, filter = teal_slices()) {+ { |
|
33 | -! | +||
141 | +1x |
- lifecycle::deprecate_soft(+ options(opts) |
|
34 | -! | +||
142 | +1x |
- when = "0.16",+ do.call(Sys.setenv, sysenv) |
|
35 | -! | +||
143 | +1x |
- what = "srv_teal_with_splash()",+ .libPaths(libpaths) |
|
36 | -! | +||
144 | +1x |
- details = "Deprecated, please use `srv_teal` instead"+ setwd(wd)+ |
+ |
145 | +1x | +
+ run(lockfile_path = lockfile_path) |
|
37 | +146 |
- )+ }, |
|
38 | -! | +||
147 | +1x |
- srv_teal(id = id, data = data, modules = modules, filter = filter)+ run = .renv_snapshot, |
|
39 | -+ | ||
148 | +1x |
- }+ lockfile_path = lockfile_path, |
1 | -+ | ||
149 | +1x |
- #' Data module for `teal` transformations and output customization+ opts = options(), |
|
2 | -+ | ||
150 | +1x |
- #'+ libpaths = .libPaths(), |
|
3 | -+ | ||
151 | +1x |
- #' @description+ sysenv = as.list(Sys.getenv()), |
|
4 | -+ | ||
152 | +1x |
- #' `r lifecycle::badge("experimental")`+ wd = getwd() |
|
5 | +153 |
- #'+ ) |
|
6 | -+ | ||
154 | +1x |
- #' `teal_transform_module` provides a `shiny` module that enables data transformations within a `teal` application+ mirai_obj <<- m |
|
7 | -+ | ||
155 | +1x |
- #' and allows for customization of outputs generated by modules.+ m |
|
8 | +156 |
- #'+ }) |
|
9 | +157 |
- #' # Transforming Module Inputs in `teal`+ |
|
10 | -+ | ||
158 | +1x |
- #'+ shiny::onStop(function() { |
|
11 | -+ | ||
159 | +1x |
- #' Data transformations occur after data has been filtered in `teal`.+ if (mirai::unresolved(mirai_obj)) { |
|
12 | -+ | ||
160 | +! |
- #' The transformed data is then passed to the `server` of [`teal_module()`] and managed by `teal`'s internal processes.+ logger::log_debug("Terminating a running lockfile process...") |
|
13 | -+ | ||
161 | +! |
- #' The primary advantage of `teal_transform_module` over custom modules is in its error handling, where all warnings and+ mirai::stop_mirai(mirai_obj) # this doesn't stop running - renv will be created even if session is closed |
|
14 | +162 |
- #' errors are managed by `teal`, allowing developers to focus on transformation logic.+ } |
|
15 | +163 |
- #'+ }) |
|
16 | +164 |
- #' For more details, see the vignette: `vignette("data-transform-as-shiny-module", package = "teal")`.+ |
|
17 | -+ | ||
165 | +1x |
- #'+ suppressWarnings({ # 'package:stats' may not be available when loading |
|
18 | -+ | ||
166 | +1x |
- #' # Customizing Module Outputs+ process$invoke() |
|
19 | +167 |
- #'+ }) |
|
20 | +168 |
- #' `teal_transform_module` also allows developers to modify any object created within [`teal.data::teal_data`].+ |
|
21 | -+ | ||
169 | +1x |
- #' This means you can use it to customize not only datasets but also tables, listings, and graphs.+ logger::log_debug("Lockfile creation started based on { getwd() }.") |
|
22 | +170 |
- #' Some [`teal_modules`] permit developers to inject custom `shiny` modules to enhance displayed outputs.+ |
|
23 | -+ | ||
171 | +1x |
- #' To manage these `decorators` within your module, use [`ui_transform_teal_data()`] and [`srv_transform_teal_data()`].+ process |
|
24 | +172 |
- #' (For further guidance on managing decorators, refer to `ui_args` and `srv_args` in the vignette documentation.)+ } |
|
25 | +173 |
- #'+ |
|
26 | +174 |
- #' See the vignette `vignette("decorate-modules-output", package = "teal")` for additional examples.+ #' @rdname module_teal_lockfile |
|
27 | +175 |
- #'+ .renv_snapshot <- function(lockfile_path) { |
|
28 | -+ | ||
176 | +1x |
- #' # `server` as a language+ out <- utils::capture.output( |
|
29 | -+ | ||
177 | +1x |
- #'+ res <- renv::snapshot( |
|
30 | -+ | ||
178 | +1x |
- #' The `server` function in `teal_transform_module` must return a reactive [`teal.data::teal_data`] object.+ lockfile = lockfile_path, |
|
31 | -+ | ||
179 | +1x |
- #' For simple transformations without complex reactivity, the `server` function might look like this:s+ prompt = FALSE, |
|
32 | -+ | ||
180 | +1x |
- #'+ force = TRUE, |
|
33 | -+ | ||
181 | +1x |
- #' ```+ type = renv::settings$snapshot.type() # see the section "Different ways of creating lockfile" above here |
|
34 | +182 |
- #' function(id, data) {+ ) |
|
35 | +183 |
- #' moduleServer(id, function(input, output, session) {+ ) |
|
36 | +184 |
- #' reactive({+ |
|
37 | -+ | ||
185 | +1x |
- #' within(+ list(out = out, res = res) |
|
38 | +186 |
- #' data(),+ } |
|
39 | +187 |
- #' expr = x <- subset(x, col == level),+ |
|
40 | +188 |
- #' level = input$level+ #' @rdname module_teal_lockfile |
|
41 | +189 |
- #' )+ .is_lockfile_deps_installed <- function() { |
|
42 | -+ | ||
190 | +1x |
- #' })+ requireNamespace("mirai", quietly = TRUE) && requireNamespace("renv", quietly = TRUE) |
|
43 | +191 |
- #' })+ } |
|
44 | +192 |
- #' }+ |
|
45 | +193 |
- #' ```+ #' @rdname module_teal_lockfile |
|
46 | +194 |
- #'+ .is_disabled_lockfile_scenario <- function() { |
|
47 | -+ | ||
195 | +86x |
- #' The example above can be simplified using `make_teal_transform_server`, where `level` is automatically matched to the+ identical(Sys.getenv("CALLR_IS_RUNNING"), "true") || # inside callr process |
|
48 | -+ | ||
196 | +86x |
- #' corresponding `input` parameter:+ identical(Sys.getenv("TESTTHAT"), "true") || # inside devtools::test |
|
49 | -+ | ||
197 | +86x |
- #'+ !identical(Sys.getenv("QUARTO_PROJECT_ROOT"), "") || # inside Quarto process |
|
50 | +198 |
- #' ```+ ( |
|
51 | -+ | ||
199 | +86x |
- #' make_teal_transform_server(expr = expression(x <- subset(x, col == level)))+ ("CheckExEnv" %in% search()) || any(c("_R_CHECK_TIMINGS_", "_R_CHECK_LICENSE_") %in% names(Sys.getenv())) |
|
52 | -+ | ||
200 | +86x |
- #' ```+ ) # inside R CMD CHECK |
|
53 | +201 |
- #' @inheritParams teal_data_module+ } |
54 | +1 |
- #' @param server (`function(id, data)` or `expression`)+ #' Module to transform `reactive` `teal_data` |
||
55 | +2 |
- #' A `shiny` module server function that takes `id` and `data` as arguments, where `id` is the module id and `data`+ #' |
||
56 | +3 |
- #' is the reactive `teal_data` input. The `server` function must return a reactive expression containing a `teal_data`+ #' Module calls [teal_transform_module()] in sequence so that `reactive teal_data` output |
||
57 | +4 |
- #' object. For simplified syntax, use [`make_teal_transform_server()`].+ #' from one module is handed over to the following module's input. |
||
58 | +5 |
- #' @param datanames (`character`)+ #' |
||
59 | +6 |
- #' Specifies the names of datasets relevant to the module. Only filters for the specified `datanames` will be displayed+ #' @inheritParams module_teal_data |
||
60 | +7 |
- #' in the filter panel. The keyword `"all"` can be used to display filters for all datasets. `datanames` are+ #' @inheritParams teal_modules |
||
61 | +8 |
- #' automatically appended to the [`modules()`] `datanames`.+ #' @param class (character(1)) CSS class to be added in the `div` wrapper tag. |
||
62 | +9 |
- #'+ |
||
63 | +10 |
- #'+ #' @return `reactive` `teal_data` |
||
64 | +11 |
- #' @examples+ #' |
||
65 | +12 |
- #' data_transformators <- list(+ #' @name module_transform_data |
||
66 | +13 |
- #' teal_transform_module(+ NULL |
||
67 | +14 |
- #' label = "Static transformator for iris",+ |
||
68 | +15 |
- #' datanames = "iris",+ #' @export |
||
69 | +16 |
- #' server = function(id, data) {+ #' @rdname module_transform_data |
||
70 | +17 |
- #' moduleServer(id, function(input, output, session) {+ ui_transform_teal_data <- function(id, transformators, class = "well") { |
||
71 | -+ | |||
18 | +1x |
- #' reactive({+ checkmate::assert_string(id) |
||
72 | -+ | |||
19 | +1x |
- #' within(data(), {+ if (length(transformators) == 0L) { |
||
73 | -+ | |||
20 | +! |
- #' iris <- head(iris, 5)+ return(NULL) |
||
74 | +21 |
- #' })+ } |
||
75 | -+ | |||
22 | +1x |
- #' })+ if (inherits(transformators, "teal_transform_module")) { |
||
76 | -+ | |||
23 | +1x |
- #' })+ transformators <- list(transformators) |
||
77 | +24 |
- #' }+ } |
||
78 | -+ | |||
25 | +1x |
- #' ),+ checkmate::assert_list(transformators, "teal_transform_module") |
||
79 | -+ | |||
26 | +1x |
- #' teal_transform_module(+ names(transformators) <- sprintf("transform_%d", seq_len(length(transformators))) |
||
80 | +27 |
- #' label = "Interactive transformator for iris",+ |
||
81 | -+ | |||
28 | +1x |
- #' datanames = "iris",+ lapply( |
||
82 | -+ | |||
29 | +1x |
- #' ui = function(id) {+ names(transformators), |
||
83 | -+ | |||
30 | +1x |
- #' ns <- NS(id)+ function(name) { |
||
84 | -+ | |||
31 | +1x |
- #' tags$div(+ child_id <- NS(id, name) |
||
85 | -+ | |||
32 | +1x |
- #' numericInput(ns("n_cols"), "Show n columns", value = 5, min = 1, max = 5, step = 1)+ ns <- NS(child_id) |
||
86 | -+ | |||
33 | +1x |
- #' )+ data_mod <- transformators[[name]] |
||
87 | -+ | |||
34 | +1x |
- #' },+ transform_wrapper_id <- ns(sprintf("wrapper_%s", name)) |
||
88 | +35 |
- #' server = function(id, data) {+ |
||
89 | -+ | |||
36 | +1x |
- #' moduleServer(id, function(input, output, session) {+ display_fun <- if (is.null(data_mod$ui)) shinyjs::hidden else function(x) x |
||
90 | +37 |
- #' reactive({+ |
||
91 | -+ | |||
38 | +1x |
- #' within(data(),+ display_fun( |
||
92 | -+ | |||
39 | +1x |
- #' {+ div( |
||
93 | +40 |
- #' iris <- iris[, 1:n_cols]+ # class .teal_validated changes the color of the boarder on error in ui_validate_reactive_teal_data |
||
94 | +41 |
- #' },+ # For details see tealValidate.js file. |
||
95 | -+ | |||
42 | +1x |
- #' n_cols = input$n_cols+ id = ns("wrapper"), |
||
96 | -+ | |||
43 | +1x |
- #' )+ class = c(class, "teal_validated"), |
||
97 | -+ | |||
44 | +1x |
- #' })+ title = attr(data_mod, "label"), |
||
98 | -+ | |||
45 | +1x |
- #' })+ tags$span( |
||
99 | -+ | |||
46 | +1x |
- #' }+ class = "text-primary mb-4", |
||
100 | -+ | |||
47 | +1x |
- #' )+ icon("fas fa-square-pen"), |
||
101 | -+ | |||
48 | +1x |
- #' )+ attr(data_mod, "label") |
||
102 | +49 |
- #'+ ), |
||
103 | -+ | |||
50 | +1x |
- #' output_decorator <- teal_transform_module(+ tags$i( |
||
104 | -+ | |||
51 | +1x |
- #' server = make_teal_transform_server(+ class = "remove pull-right fa fa-angle-down", |
||
105 | -+ | |||
52 | +1x |
- #' expression(+ style = "cursor: pointer;", |
||
106 | -+ | |||
53 | +1x |
- #' object <- rev(object)+ title = "fold/expand transformator panel", |
||
107 | -+ | |||
54 | +1x |
- #' )+ onclick = sprintf("togglePanelItems(this, '%s', 'fa-angle-right', 'fa-angle-down');", transform_wrapper_id) |
||
108 | +55 |
- #' )+ ), |
||
109 | -+ | |||
56 | +1x |
- #' )+ tags$div( |
||
110 | -+ | |||
57 | +1x |
- #'+ id = transform_wrapper_id, |
||
111 | -+ | |||
58 | +1x |
- #' app <- init(+ if (is.null(data_mod$ui)) { |
||
112 | -+ | |||
59 | +! |
- #' data = teal_data(iris = iris),+ return(NULL) |
||
113 | +60 |
- #' modules = example_module(+ } else { |
||
114 | -+ | |||
61 | +1x |
- #' transformators = data_transformators,+ data_mod$ui(id = ns("transform")) |
||
115 | +62 |
- #' decorators = list(output_decorator)+ }, |
||
116 | -+ | |||
63 | +1x |
- #' )+ div( |
||
117 | -+ | |||
64 | +1x |
- #' )+ id = ns("validate_messages"), |
||
118 | -+ | |||
65 | +1x |
- #' if (interactive()) {+ class = "teal_validated", |
||
119 | -+ | |||
66 | +1x |
- #' shinyApp(app$ui, app$server)+ uiOutput(ns("error_wrapper")) |
||
120 | +67 |
- #' }+ ) |
||
121 | +68 |
- #'+ ) |
||
122 | +69 |
- #' @name teal_transform_module+ ) |
||
123 | +70 |
- #'+ ) |
||
124 | +71 |
- #' @export+ } |
||
125 | +72 |
- teal_transform_module <- function(ui = NULL,+ ) |
||
126 | +73 |
- server = function(id, data) data,+ } |
||
127 | +74 |
- label = "transform module",+ |
||
128 | +75 |
- datanames = "all") {+ #' @export |
||
129 | -25x | +|||
76 | +
- structure(+ #' @rdname module_transform_data |
|||
130 | -25x | +|||
77 | +
- list(+ srv_transform_teal_data <- function(id, data, transformators, modules = NULL, is_transform_failed = reactiveValues()) { |
|||
131 | -25x | +78 | +94x |
- ui = ui,+ checkmate::assert_string(id) |
132 | -25x | +79 | +94x |
- server = function(id, data) {+ assert_reactive(data) |
133 | -26x | +80 | +94x |
- data_out <- server(id, data)+ checkmate::assert_class(modules, "teal_module", null.ok = TRUE) |
134 | -+ | |||
81 | +94x |
-
+ if (length(transformators) == 0L) { |
||
135 | -26x | +82 | +71x |
- if (inherits(data_out, "reactive.event")) {+ return(data) |
136 | +83 |
- # This warning message partially detects when `eventReactive` is used in `data_module`.- |
- ||
137 | -1x | -
- warning(+ } |
||
138 | -1x | +84 | +23x |
- "teal_transform_module() ",+ if (inherits(transformators, "teal_transform_module")) { |
139 | -1x | +85 | +3x |
- "Using eventReactive in teal_transform module server code should be avoided as it ",+ transformators <- list(transformators) |
140 | -1x | +|||
86 | +
- "may lead to unexpected behavior. See the vignettes for more information ",+ } |
|||
141 | -1x | +87 | +23x |
- "(`vignette(\"data-transform-as-shiny-module\", package = \"teal\")`).",+ checkmate::assert_list(transformators, "teal_transform_module", null.ok = TRUE) |
142 | -1x | +88 | +23x |
- call. = FALSE+ names(transformators) <- sprintf("transform_%d", seq_len(length(transformators))) |
143 | +89 |
- )+ |
||
144 | -+ | |||
90 | +23x |
- }+ moduleServer(id, function(input, output, session) { |
||
145 | -+ | |||
91 | +23x |
-
+ module_output <- Reduce( |
||
146 | -+ | |||
92 | +23x |
-
+ function(data_previous, name) { |
||
147 | +93 | 26x |
- decorate_err_msg(+ moduleServer(name, function(input, output, session) { |
|
148 | +94 | 26x |
- assert_reactive(data_out),+ logger::log_debug("srv_transform_teal_data initializing for { name }.") |
|
149 | +95 | 26x |
- pre = sprintf("From: 'teal_transform_module()':\nA 'teal_transform_module' with \"%s\" label:", label),+ is_transform_failed[[name]] <- FALSE |
|
150 | +96 | 26x |
- post = "Please make sure that this module returns a 'reactive` object containing 'teal_data' class of object." # nolint: line_length_linter.+ data_out <- transformators[[name]]$server("transform", data = data_previous) |
|
151 | -+ | |||
97 | +26x |
- )+ data_handled <- reactive(tryCatch(data_out(), error = function(e) e)) |
||
152 | -+ | |||
98 | +26x |
- }+ observeEvent(data_handled(), { |
||
153 | -+ | |||
99 | +32x |
- ),+ if (inherits(data_handled(), "teal_data")) { |
||
154 | -25x | +100 | +22x |
- label = label,+ is_transform_failed[[name]] <- FALSE |
155 | -25x | +|||
101 | +
- datanames = datanames,+ } else { |
|||
156 | -25x | +102 | +10x |
- class = c("teal_transform_module", "teal_data_module")+ is_transform_failed[[name]] <- TRUE |
157 | +103 |
- )+ } |
||
158 | +104 |
- }+ }) |
||
159 | +105 | |||
160 | -+ | |||
106 | +26x |
- #' Make teal_transform_module's server+ is_previous_failed <- reactive({ |
||
161 | -+ | |||
107 | +29x |
- #'+ idx_this <- which(names(is_transform_failed) == name) |
||
162 | -+ | |||
108 | +29x |
- #' A factory function to simplify creation of a [`teal_transform_module`]'s server. Specified `expr`+ is_transform_failed_list <- reactiveValuesToList(is_transform_failed) |
||
163 | -+ | |||
109 | +29x |
- #' is wrapped in a shiny module function and output can be passed to the `server` argument in+ idx_failures <- which(unlist(is_transform_failed_list)) |
||
164 | -+ | |||
110 | +29x |
- #' [teal_transform_module()] call. Such a server function can be linked with ui and values from the+ any(idx_failures < idx_this) |
||
165 | +111 |
- #' inputs can be used in the expression. Object names specified in the expression will be substituted+ }) |
||
166 | +112 |
- #' with the value of the respective input (matched by the name) - for example in+ |
||
167 | -+ | |||
113 | +26x |
- #' `expression(graph <- graph + ggtitle(title))` object `title` will be replaced with the value of+ srv_validate_error("silent_error", data_handled, validate_shiny_silent_error = FALSE) |
||
168 | -+ | |||
114 | +26x |
- #' `input$title`.+ srv_check_class_teal_data("class_teal_data", data_handled) |
||
169 | -+ | |||
115 | +26x |
- #' @param expr (`language`)+ if (!is.null(modules)) { |
||
170 | -+ | |||
116 | +20x |
- #' An R call which will be evaluated within [`teal.data::teal_data`] environment.+ srv_check_module_datanames("datanames_warning", data_handled, modules) |
||
171 | +117 |
- #' @return `function(id, data)` returning `shiny` module+ } |
||
172 | +118 |
- #' @examples+ |
||
173 | +119 |
- #'+ # When there is no UI (`ui = NULL`) it should still show the errors |
||
174 | -+ | |||
120 | +26x |
- #' trim_iris <- teal_transform_module(+ observe({ |
||
175 | -+ | |||
121 | +32x |
- #' label = "Simplified interactive transformator for iris",+ if (!inherits(data_handled(), "teal_data") && !is_previous_failed()) { |
||
176 | -+ | |||
122 | +10x |
- #' datanames = "iris",+ shinyjs::show("wrapper") |
||
177 | +123 |
- #' ui = function(id) {+ } |
||
178 | +124 |
- #' ns <- NS(id)+ }) |
||
179 | +125 |
- #' numericInput(ns("n_rows"), "Subset n rows", value = 6, min = 1, max = 150, step = 1)+ |
||
180 | -+ | |||
126 | +26x |
- #' },+ transform_wrapper_id <- sprintf("wrapper_%s", name) |
||
181 | -+ | |||
127 | +26x |
- #' server = make_teal_transform_server(expression(iris <- head(iris, n_rows)))+ output$error_wrapper <- renderUI({ |
||
182 | -+ | |||
128 | +29x |
- #' )+ if (is_previous_failed()) { |
||
183 | -+ | |||
129 | +! |
- #'+ shinyjs::disable(transform_wrapper_id) |
||
184 | -+ | |||
130 | +! |
- #' app <- init(+ tags$div("One of previous transformators failed. Please check its inputs.", class = "teal-output-warning") |
||
185 | +131 |
- #' data = teal_data(iris = iris),+ } else { |
||
186 | -+ | |||
132 | +29x |
- #' modules = example_module(transformators = trim_iris)+ shinyjs::enable(transform_wrapper_id) |
||
187 | -+ | |||
133 | +29x |
- #' )+ shiny::tagList( |
||
188 | -+ | |||
134 | +29x |
- #' if (interactive()) {+ ui_validate_error(session$ns("silent_error")), |
||
189 | -+ | |||
135 | +29x |
- #' shinyApp(app$ui, app$server)+ ui_check_class_teal_data(session$ns("class_teal_data")), |
||
190 | -+ | |||
136 | +29x |
- #' }+ ui_check_module_datanames(session$ns("datanames_warning")) |
||
191 | +137 |
- #'+ ) |
||
192 | +138 |
- #' @export+ } |
||
193 | +139 |
- make_teal_transform_server <- function(expr) {+ }) |
||
194 | -3x | +|||
140 | +
- if (is.call(expr)) {+ |
|||
195 | -1x | +141 | +26x |
- expr <- as.expression(expr)+ .trigger_on_success(data_handled) |
196 | +142 |
- }- |
- ||
197 | -3x | -
- checkmate::assert_multi_class(expr, c("call", "expression"))+ }) |
||
198 | +143 |
-
+ }, |
||
199 | -3x | +144 | +23x |
- function(id, data) {+ x = names(transformators), |
200 | -3x | +145 | +23x |
- moduleServer(id, function(input, output, session) {+ init = data |
201 | -3x | +|||
146 | +
- list_env <- reactive(+ ) |
|||
202 | -3x | +147 | +23x |
- lapply(rlang::set_names(names(input)), function(x) input[[x]])+ module_output |
203 | +148 |
- )+ }) |
||
204 | +149 |
-
+ } |
||
205 | -3x | +
1 | +
- reactive({+ #' Create a `tdata` object |
||
206 | -4x | +||
2 | +
- call_with_inputs <- lapply(expr, function(x) {+ #' |
||
207 | -4x | +||
3 | +
- do.call(what = substitute, args = list(expr = x, env = list_env()))+ #' @description `r lifecycle::badge("superseded")` |
||
208 | +4 |
- })+ #' |
|
209 | -4x | +||
5 | +
- eval_code(object = data(), code = as.expression(call_with_inputs))+ #' Recent changes in `teal` cause modules to fail because modules expect a `tdata` object |
||
210 | +6 |
- })+ #' to be passed to the `data` argument but instead they receive a `teal_data` object, |
|
211 | +7 |
- })+ #' which is additionally wrapped in a reactive expression in the server functions. |
|
212 | +8 |
- }+ #' In order to easily adapt such modules without a proper refactor, |
|
213 | +9 |
- }+ #' use this function to downgrade the `data` argument. |
|
214 | +10 |
-
+ #' |
|
215 | +11 |
- #' Extract all `transformators` from `modules`.+ #' @name tdata |
|
216 | +12 |
- #'+ #' @param ... ignored |
|
217 | +13 |
- #' @param modules `teal_modules` or `teal_module`+ #' @return nothing |
|
218 | +14 |
- #' @return A list of `teal_transform_module` nested in the same way as input `modules`.+ NULL |
|
219 | +15 |
- #' @keywords internal+ |
|
220 | +16 |
- extract_transformators <- function(modules) {+ #' @rdname tdata |
|
221 | -10x | +||
17 | +
- if (inherits(modules, "teal_module")) {+ #' @export |
||
222 | -5x | +||
18 | +
- modules$transformators+ new_tdata <- function(...) { |
||
223 | -5x | +||
19 | +! |
- } else if (inherits(modules, "teal_modules")) {+ .deprecate_tdata_msg() |
|
224 | -5x | +||
20 | +
- lapply(modules$children, extract_transformators)+ } |
||
225 | +21 |
- }+ |
|
226 | +22 |
- }+ #' @rdname tdata |
1 | +23 |
- #' Data module for `teal` applications+ #' @export |
|
2 | +24 |
- #'+ tdata2env <- function(...) { |
|
3 | -+ | ||
25 | +! |
- #' @description+ .deprecate_tdata_msg() |
|
4 | +26 |
- #' `r lifecycle::badge("experimental")`+ } |
|
5 | +27 |
- #'+ |
|
6 | +28 |
- #' Create a `teal_data_module` object and evaluate code on it with history tracking.+ #' @rdname tdata |
|
7 | +29 |
- #'+ #' @export |
|
8 | +30 |
- #' @details+ get_code_tdata <- function(...) { |
|
9 | -+ | ||
31 | +! |
- #' `teal_data_module` creates a `shiny` module to interactively supply or modify data in a `teal` application.+ .deprecate_tdata_msg() |
|
10 | +32 |
- #' The module allows for running any code (creation _and_ some modification) after the app starts or reloads.+ } |
|
11 | +33 |
- #' The body of the server function will be run in the app rather than in the global environment.+ |
|
12 | +34 |
- #' This means it will be run every time the app starts, so use sparingly.+ #' @rdname tdata |
|
13 | +35 |
- #'+ #' @export |
|
14 | +36 |
- #' Pass this module instead of a `teal_data` object in a call to [init()].+ join_keys.tdata <- function(...) { |
|
15 | -+ | ||
37 | +! |
- #' Note that the server function must always return a `teal_data` object wrapped in a reactive expression.+ .deprecate_tdata_msg() |
|
16 | +38 |
- #'+ } |
|
17 | +39 |
- #' See vignette `vignette("data-as-shiny-module", package = "teal")` for more details.+ |
|
18 | +40 |
- #'+ #' @rdname tdata |
|
19 | +41 |
- #' @param ui (`function(id)`)+ #' @export |
|
20 | +42 |
- #' `shiny` module UI function; must only take `id` argument+ get_metadata <- function(...) { |
|
21 | -+ | ||
43 | +! |
- #' @param server (`function(id)`)+ .deprecate_tdata_msg() |
|
22 | +44 |
- #' `shiny` module server function; must only take `id` argument;+ } |
|
23 | +45 |
- #' must return reactive expression containing `teal_data` object+ |
|
24 | +46 |
- #' @param label (`character(1)`) Label of the module.+ #' @rdname tdata |
|
25 | +47 |
- #' @param once (`logical(1)`)+ #' @export |
|
26 | +48 |
- #' If `TRUE`, the data module will be shown only once and will disappear after successful data loading.+ as_tdata <- function(...) { |
|
27 | -+ | ||
49 | +! |
- #' App user will no longer be able to interact with this module anymore.+ .deprecate_tdata_msg() |
|
28 | +50 |
- #' If `FALSE`, the data module can be reused multiple times.+ } |
|
29 | +51 |
- #' App user will be able to interact and change the data output from the module multiple times.+ |
|
30 | +52 |
- #'+ |
|
31 | +53 |
- #' @return+ .deprecate_tdata_msg <- function() { |
|
32 | -+ | ||
54 | +! |
- #' `teal_data_module` returns a list of class `teal_data_module` containing two elements, `ui` and+ lifecycle::deprecate_stop( |
|
33 | -+ | ||
55 | +! |
- #' `server` provided via arguments.+ when = "0.16", |
|
34 | -+ | ||
56 | +! |
- #'+ what = "tdata()", |
|
35 | -+ | ||
57 | +! |
- #' @examples+ details = paste( |
|
36 | -+ | ||
58 | +! |
- #' tdm <- teal_data_module(+ "tdata has been removed in favour of `teal_data`.\n", |
|
37 | -+ | ||
59 | +! |
- #' ui = function(id) {+ "Please follow migration instructions https://github.com/insightsengineering/teal/discussions/987." |
|
38 | +60 |
- #' ns <- NS(id)+ ) |
|
39 | +61 |
- #' actionButton(ns("submit"), label = "Load data")+ ) |
|
40 | +62 |
- #' },+ } |
41 | +1 |
- #' server = function(id) {+ #' Evaluate expression on `teal_data_module` |
||
42 | +2 |
- #' moduleServer(id, function(input, output, session) {+ #' |
||
43 | +3 |
- #' eventReactive(input$submit, {+ #' @details |
||
44 | +4 |
- #' data <- within(+ #' `within` is a convenience function for evaluating inline code inside the environment of a `teal_data_module`. |
||
45 | +5 |
- #' teal_data(),+ #' It accepts only inline expressions (both simple and compound) and allows for injecting values into `expr` through |
||
46 | +6 |
- #' {+ #' the `...` argument: as `name:value` pairs are passed to `...`, `name` in `expr` will be replaced with `value.` |
||
47 | +7 |
- #' dataset1 <- iris+ #' |
||
48 | +8 |
- #' dataset2 <- mtcars+ #' @param data (`teal_data_module`) object |
||
49 | +9 |
- #' }+ #' @param expr (`expression`) to evaluate. Must be inline code. See [within()] |
||
50 | +10 |
- #' )+ #' @param ... See `Details`. |
||
51 | +11 |
#' |
||
52 | +12 |
- #' data+ #' @return |
||
53 | +13 |
- #' })+ #' `within` returns a `teal_data_module` object with a delayed evaluation of `expr` when the module is run. |
||
54 | +14 |
- #' })+ #' |
||
55 | +15 |
- #' }+ #' @examples |
||
56 | +16 |
- #' )+ #' within(tdm, dataset1 <- subset(dataset1, Species == "virginica")) |
||
57 | +17 |
#' |
||
58 | +18 |
- #' @name teal_data_module+ #' # use additional parameter for expression value substitution. |
||
59 | +19 |
- #' @seealso [`teal.data::teal_data-class`], [teal.code::qenv()]+ #' valid_species <- "versicolor" |
||
60 | +20 |
- #'+ #' within(tdm, dataset1 <- subset(dataset1, Species %in% species), species = valid_species) |
||
61 | +21 |
- #' @export+ #' @include teal_data_module.R |
||
62 | +22 |
- teal_data_module <- function(ui, server, label = "data module", once = TRUE) {+ #' @name within |
||
63 | -33x | +|||
23 | +
- checkmate::assert_function(ui, args = "id", nargs = 1)+ #' @rdname teal_data_module |
|||
64 | -32x | +|||
24 | +
- checkmate::assert_function(server, args = "id", nargs = 1)+ #' |
|||
65 | -30x | +|||
25 | +
- checkmate::assert_string(label)+ #' @export |
|||
66 | -30x | +|||
26 | +
- checkmate::assert_flag(once)+ #' |
|||
67 | -30x | +|||
27 | +
- structure(+ within.teal_data_module <- function(data, expr, ...) { |
|||
68 | -30x | +28 | +2x |
- list(+ expr <- substitute(expr) |
69 | -30x | +29 | +2x |
- ui = ui,+ extras <- list(...) |
70 | -30x | +|||
30 | +
- server = function(id) {+ |
|||
71 | -23x | +|||
31 | +
- data_out <- server(id)+ # Add braces for consistency. |
|||
72 | -22x | +32 | +2x |
- decorate_err_msg(+ if (!identical(as.list(expr)[[1L]], as.symbol("{"))) { |
73 | -22x | +33 | +2x |
- assert_reactive(data_out),+ expr <- call("{", expr) |
74 | -22x | +|||
34 | +
- pre = sprintf("From: 'teal_data_module()':\nA 'teal_data_module' with \"%s\" label:", label),+ } |
|||
75 | -22x | +|||
35 | +
- post = "Please make sure that this module returns a 'reactive` object containing 'teal_data' class of object." # nolint: line_length_linter.+ |
|||
76 | -+ | |||
36 | +2x |
- )+ calls <- as.list(expr)[-1] |
||
77 | +37 |
- }+ |
||
78 | +38 |
- ),+ # Inject extra values into expressions. |
||
79 | -30x | +39 | +2x |
- label = label,+ calls <- lapply(calls, function(x) do.call(substitute, list(x, env = extras))) |
80 | -30x | +|||
40 | +
- class = "teal_data_module",+ |
|||
81 | -30x | -
- once = once- |
- ||
82 | -+ | 41 | +2x |
- )+ eval_code(object = data, code = as.expression(calls)) |
83 | +42 |
}@@ -45999,2165 +45700,2129 @@ teal coverage - 60.11% |
1 |
- #' Send input validation messages to output+ .onLoad <- function(libname, pkgname) { |
||
2 |
- #'+ # adapted from https://github.com/r-lib/devtools/blob/master/R/zzz.R |
||
3 |
- #' Captures messages from `InputValidator` objects and collates them+ |
||
4 | -+ | ! |
- #' into one message passed to `validate`.+ teal_default_options <- list( |
5 | -+ | ! |
- #'+ teal.show_js_log = FALSE, |
6 | -+ | ! |
- #' `shiny::validate` is used to withhold rendering of an output element until+ teal.lockfile.mode = "auto", |
7 | -+ | ! |
- #' certain conditions are met and to print a validation message in place+ shiny.sanitize.errors = FALSE |
8 |
- #' of the output element.+ ) |
||
9 |
- #' `shinyvalidate::InputValidator` allows to validate input elements+ |
||
10 | -+ | ! |
- #' and to display specific messages in their respective input widgets.+ op <- options() |
11 | -+ | ! |
- #' `validate_inputs` provides a hybrid solution.+ toset <- !(names(teal_default_options) %in% names(op)) |
12 | -+ | ! |
- #' Given an `InputValidator` object, messages corresponding to inputs that fail validation+ if (any(toset)) options(teal_default_options[toset]) |
13 |
- #' are extracted and placed in one validation message that is passed to a `validate`/`need` call.+ |
||
14 |
- #' This way the input `validator` messages are repeated in the output.+ # Set up the teal logger instance |
||
15 | -+ | ! |
- #'+ teal.logger::register_logger("teal") |
16 | -+ | ! |
- #' The `...` argument accepts any number of `InputValidator` objects+ teal.logger::register_handlers("teal") |
17 |
- #' or a nested list of such objects.+ |
||
18 | -+ | ! |
- #' If `validators` are passed directly, all their messages are printed together+ invisible() |
19 |
- #' under one (optional) header message specified by `header`. If a list is passed,+ } |
||
20 |
- #' messages are grouped by `validator`. The list's names are used as headers+ |
||
21 |
- #' for their respective message groups.+ .onAttach <- function(libname, pkgname) { |
||
22 | -+ | 2x |
- #' If neither of the nested list elements is named, a header message is taken from `header`.+ packageStartupMessage( |
23 | -+ | 2x |
- #'+ "\nYou are using teal version ", |
24 |
- #' @param ... either any number of `InputValidator` objects+ # `system.file` uses the `shim` of `system.file` by `teal` |
||
25 |
- #' or an optionally named, possibly nested `list` of `InputValidator`+ # we avoid `desc` dependency here to get the version |
||
26 | -+ | 2x |
- #' objects, see `Details`+ read.dcf(system.file("DESCRIPTION", package = "teal"))[, "Version"] |
27 |
- #' @param header (`character(1)`) generic validation message; set to NULL to omit+ ) |
||
28 |
- #'+ } |
||
29 |
- #' @return+ |
||
30 |
- #' Returns NULL if the final validation call passes and a `shiny.silent.error` if it fails.+ # This one is here because setdiff_teal_slice should not be exported from teal.slice. |
||
31 |
- #'+ setdiff_teal_slices <- getFromNamespace("setdiff_teal_slices", "teal.slice") |
||
32 |
- #' @seealso [`shinyvalidate::InputValidator`], [`shiny::validate`]+ # This one is here because it is needed by c.teal_slices but we don't want it exported from teal.slice. |
||
33 |
- #'+ coalesce_r <- getFromNamespace("coalesce_r", "teal.slice") |
||
34 |
- #' @examplesIf require("shinyvalidate")+ # all *Block objects are private in teal.reporter |
||
35 |
- #' library(shiny)+ RcodeBlock <- getFromNamespace("RcodeBlock", "teal.reporter") # nolint: object_name. |
||
36 |
- #' library(shinyvalidate)+ |
||
37 |
- #'+ # Use non-exported function(s) from teal.code |
||
38 |
- #' ui <- fluidPage(+ # This one is here because lang2calls should not be exported from teal.code |
||
39 |
- #' selectInput("method", "validation method", c("sequential", "combined", "grouped")),+ lang2calls <- getFromNamespace("lang2calls", "teal.code") |
||
40 |
- #' sidebarLayout(+ code2list <- getFromNamespace("code2list", "teal.data") |
41 | +1 |
- #' sidebarPanel(+ #' Check that argument is reactive. |
|
42 | +2 |
- #' selectInput("letter", "select a letter:", c(letters[1:3], LETTERS[4:6])),+ #' |
|
43 | +3 |
- #' selectInput("number", "select a number:", 1:6),+ #' @inherit checkmate::check_class params return |
|
44 | +4 |
- #' tags$br(),+ #' |
|
45 | +5 |
- #' selectInput("color", "select a color:",+ #' @keywords internal |
|
46 | +6 |
- #' c("black", "indianred2", "springgreen2", "cornflowerblue"),+ check_reactive <- function(x, null.ok = FALSE) { # nolint: object_name_linter. |
|
47 | -+ | ||
7 | +1134x |
- #' multiple = TRUE+ if (!isTRUE(checkmate::test_class(x, classes = "reactive", null.ok = null.ok))) { |
|
48 | -+ | ||
8 | +4x |
- #' ),+ cl <- class(x) |
|
49 | -+ | ||
9 | +4x |
- #' sliderInput("size", "select point size:",+ return(sprintf( |
|
50 | -+ | ||
10 | +4x |
- #' min = 0.1, max = 4, value = 0.25+ "Must be a reactive (i.e. inherit from 'reactive' class) but has class%s '%s'", |
|
51 | -+ | ||
11 | +4x |
- #' )+ if (length(cl) > 1L) "es" else "", |
|
52 | -+ | ||
12 | +4x |
- #' ),+ paste0(cl, collapse = "','") |
|
53 | +13 |
- #' mainPanel(plotOutput("plot"))+ )) |
|
54 | +14 |
- #' )+ } |
|
55 | -+ | ||
15 | +1130x |
- #' )+ return(TRUE) |
|
56 | +16 |
- #'+ } |
|
57 | +17 |
- #' server <- function(input, output) {+ #' @rdname check_reactive |
|
58 | +18 |
- #' # set up input validation+ test_reactive <- function(x, null.ok = FALSE) { # nolint: object_name_linter. |
|
59 | -+ | ||
19 | +30x |
- #' iv <- InputValidator$new()+ isTRUE(check_reactive(x, null.ok = null.ok)) |
|
60 | +20 |
- #' iv$add_rule("letter", sv_in_set(LETTERS, "choose a capital letter"))+ } |
|
61 | +21 |
- #' iv$add_rule("number", function(x) {+ #' @rdname check_reactive |
|
62 | +22 |
- #' if (as.integer(x) %% 2L == 1L) "choose an even number"+ assert_reactive <- checkmate::makeAssertionFunction(check_reactive) |
|
63 | +23 |
- #' })+ |
|
64 | +24 |
- #' iv$enable()+ #' Capture error and decorate error message. |
|
65 | +25 |
- #' # more input validation+ #' |
|
66 | +26 |
- #' iv_par <- InputValidator$new()+ #' @param x object to evaluate |
|
67 | +27 |
- #' iv_par$add_rule("color", sv_required(message = "choose a color"))+ #' @param pre (`character(1)`) A string to prepend to error message |
|
68 | +28 |
- #' iv_par$add_rule("color", function(x) {+ #' @param post (`character(1)`) A string to append to error message |
|
69 | +29 |
- #' if (length(x) > 1L) "choose only one color"+ #' |
|
70 | +30 |
- #' })+ #' @return `x` if no error, otherwise throws error with decorated message |
|
71 | +31 |
- #' iv_par$add_rule(+ #' |
|
72 | +32 |
- #' "size",+ #' @keywords internal |
|
73 | +33 |
- #' sv_between(+ decorate_err_msg <- function(x, pre = character(0), post = character(0)) { |
|
74 | -+ | ||
34 | +47x |
- #' left = 0.5, right = 3,+ tryCatch( |
|
75 | -+ | ||
35 | +47x |
- #' message_fmt = "choose a value between {left} and {right}"+ x, |
|
76 | -+ | ||
36 | +47x |
- #' )+ error = function(e) { |
|
77 | -+ | ||
37 | +2x |
- #' )+ stop( |
|
78 | -+ | ||
38 | +2x |
- #' iv_par$enable()+ "\n", |
|
79 | -+ | ||
39 | +2x |
- #'+ pre, |
|
80 | -+ | ||
40 | +2x |
- #' output$plot <- renderPlot({+ "\n", |
|
81 | -+ | ||
41 | +2x |
- #' # validate output+ e$message, |
|
82 | -+ | ||
42 | +2x |
- #' switch(input[["method"]],+ "\n",+ |
+ |
43 | +2x | +
+ post,+ |
+ |
44 | +2x | +
+ call. = FALSE |
|
83 | +45 |
- #' "sequential" = {+ ) |
|
84 | +46 |
- #' validate_inputs(iv)+ } |
|
85 | +47 |
- #' validate_inputs(iv_par, header = "Set proper graphical parameters")+ )+ |
+ |
48 | +45x | +
+ x |
|
86 | +49 |
- #' },+ } |
87 | +1 |
- #' "combined" = validate_inputs(iv, iv_par),+ #' Filter settings for `teal` applications |
||
88 | +2 |
- #' "grouped" = validate_inputs(list(+ #' |
||
89 | +3 |
- #' "Some inputs require attention" = iv,+ #' Specify initial filter states and filtering settings for a `teal` app. |
||
90 | +4 |
- #' "Set proper graphical parameters" = iv_par+ #' |
||
91 | +5 |
- #' ))+ #' Produces a `teal_slices` object. |
||
92 | +6 |
- #' )+ #' The `teal_slice` components will specify filter states that will be active when the app starts. |
||
93 | +7 |
- #'+ #' Attributes (created with the named arguments) will configure the way the app applies filters. |
||
94 | +8 |
- #' plot(faithful$eruptions ~ faithful$waiting,+ #' See argument descriptions for details. |
||
95 | +9 |
- #' las = 1, pch = 16,+ #' |
||
96 | +10 |
- #' col = input[["color"]], cex = input[["size"]]+ #' @inheritParams teal.slice::teal_slices |
||
97 | +11 |
- #' )+ #' |
||
98 | +12 |
- #' })+ #' @param module_specific (`logical(1)`) optional, |
||
99 | +13 |
- #' }+ #' - `FALSE` (default) when one filter panel applied to all modules. |
||
100 | +14 |
- #'+ #' All filters will be shared by all modules. |
||
101 | +15 |
- #' if (interactive()) {+ #' - `TRUE` when filter panel module-specific. |
||
102 | +16 |
- #' shinyApp(ui, server)+ #' Modules can have different set of filters specified - see `mapping` argument. |
||
103 | +17 |
- #' }+ #' @param mapping `r lifecycle::badge("experimental")` |
||
104 | +18 |
- #'+ #' _This is a new feature. Do kindly share your opinions on |
||
105 | +19 |
- #' @export+ #' [`teal`'s GitHub repository](https://github.com/insightsengineering/teal/)._ |
||
106 | +20 |
#' |
||
107 | +21 |
- validate_inputs <- function(..., header = "Some inputs require attention") {+ #' (named `list`) specifies which filters will be active in which modules on app start. |
||
108 | -36x | +|||
22 | +
- dots <- list(...)+ #' Elements should contain character vector of `teal_slice` `id`s (see [`teal.slice::teal_slice`]). |
|||
109 | -2x | +|||
23 | +
- if (!is_validators(dots)) stop("validate_inputs accepts validators or a list thereof")+ #' Names of the list should correspond to `teal_module` `label` set in [module()] function. |
|||
110 | +24 |
-
+ #' - `id`s listed under `"global_filters` will be active in all modules. |
||
111 | -34x | +|||
25 | +
- messages <- extract_validator(dots, header)+ #' - If missing, all filters will be applied to all modules. |
|||
112 | -34x | +|||
26 | +
- failings <- if (!any_names(dots)) {+ #' - If empty list, all filters will be available to all modules but will start inactive. |
|||
113 | -29x | +|||
27 | +
- add_header(messages, header)+ #' - If `module_specific` is `FALSE`, only `global_filters` will be active on start. |
|||
114 | +28 |
- } else {+ #' @param app_id (`character(1)`) |
||
115 | -5x | +|||
29 | +
- unlist(messages)+ #' For internal use only, do not set manually. |
|||
116 | +30 |
- }+ #' Added by `init` so that a `teal_slices` can be matched to the app in which it was used. |
||
117 | +31 |
-
+ #' Used for verifying snapshots uploaded from file. See `snapshot`. |
||
118 | -34x | +|||
32 | +
- shiny::validate(shiny::need(is.null(failings), failings))+ #' |
|||
119 | +33 |
- }+ #' @param x (`list`) of lists to convert to `teal_slices` |
||
120 | +34 |
-
+ #' |
||
121 | +35 |
- ### internal functions+ #' @return |
||
122 | +36 |
-
+ #' A `teal_slices` object. |
||
123 | +37 |
- #' @noRd+ #' |
||
124 | +38 |
- #' @keywords internal+ #' @seealso [`teal.slice::teal_slices`], [`teal.slice::teal_slice`], [slices_store()] |
||
125 | +39 |
- # recursive object type test+ #' |
||
126 | +40 |
- # returns logical of length 1+ #' @examples |
||
127 | +41 |
- is_validators <- function(x) {+ #' filter <- teal_slices( |
||
128 | -118x | +|||
42 | +
- all(if (is.list(x)) unlist(lapply(x, is_validators)) else inherits(x, "InputValidator"))+ #' teal_slice(dataname = "iris", varname = "Species", id = "species"), |
|||
129 | +43 |
- }+ #' teal_slice(dataname = "iris", varname = "Sepal.Length", id = "sepal_length"), |
||
130 | +44 |
-
+ #' teal_slice( |
||
131 | +45 |
- #' @noRd+ #' dataname = "iris", id = "long_petals", title = "Long petals", expr = "Petal.Length > 5" |
||
132 | +46 |
- #' @keywords internal+ #' ), |
||
133 | +47 |
- # test if an InputValidator object is enabled+ #' teal_slice(dataname = "mtcars", varname = "mpg", id = "mtcars_mpg"), |
||
134 | +48 |
- # returns logical of length 1+ #' mapping = list( |
||
135 | +49 |
- # official method requested at https://github.com/rstudio/shinyvalidate/issues/64+ #' module1 = c("species", "sepal_length"), |
||
136 | +50 |
- validator_enabled <- function(x) {+ #' module2 = c("mtcars_mpg"), |
||
137 | -49x | +|||
51 | +
- x$.__enclos_env__$private$enabled+ #' global_filters = "long_petals" |
|||
138 | +52 |
- }+ #' ) |
||
139 | +53 |
-
+ #' ) |
||
140 | +54 |
- #' Recursively extract messages from validator list+ #' |
||
141 | +55 |
- #' @return A character vector or a list of character vectors, possibly nested and named.+ #' app <- init( |
||
142 | +56 |
- #' @noRd+ #' data = teal_data(iris = iris, mtcars = mtcars), |
||
143 | +57 |
- #' @keywords internal+ #' modules = list( |
||
144 | +58 |
- extract_validator <- function(iv, header) {+ #' module("module1"), |
||
145 | -113x | +|||
59 | +
- if (inherits(iv, "InputValidator")) {+ #' module("module2") |
|||
146 | -49x | +|||
60 | +
- add_header(gather_messages(iv), header)+ #' ), |
|||
147 | +61 |
- } else {+ #' filter = filter |
||
148 | -58x | +|||
62 | +
- if (is.null(names(iv))) names(iv) <- rep("", length(iv))+ #' ) |
|||
149 | -64x | +|||
63 | +
- mapply(extract_validator, iv = iv, header = names(iv), SIMPLIFY = FALSE)+ #' |
|||
150 | +64 |
- }+ #' if (interactive()) { |
||
151 | +65 |
- }+ #' shinyApp(app$ui, app$server) |
||
152 | +66 |
-
+ #' } |
||
153 | +67 |
- #' Collate failing messages from validator.+ #' |
||
154 | +68 |
- #' @return `list`+ #' @export |
||
155 | +69 |
- #' @noRd+ teal_slices <- function(..., |
||
156 | +70 |
- #' @keywords internal+ exclude_varnames = NULL, |
||
157 | +71 |
- gather_messages <- function(iv) {+ include_varnames = NULL, |
||
158 | -49x | +|||
72 | +
- if (validator_enabled(iv)) {+ count_type = NULL, |
|||
159 | -46x | +|||
73 | +
- status <- iv$validate()+ allow_add = TRUE, |
|||
160 | -46x | +|||
74 | +
- failing_inputs <- Filter(Negate(is.null), status)+ module_specific = FALSE, |
|||
161 | -46x | +|||
75 | +
- unique(lapply(failing_inputs, function(x) x[["message"]]))+ mapping, |
|||
162 | +76 |
- } else {+ app_id = NULL) { |
||
163 | -3x | +77 | +170x |
- warning("Validator is disabled and will be omitted.")+ shiny::isolate({ |
164 | -3x | +78 | +170x |
- list()+ checkmate::assert_flag(allow_add) |
165 | -+ | |||
79 | +170x |
- }+ checkmate::assert_flag(module_specific) |
||
166 | -+ | |||
80 | +53x |
- }+ if (!missing(mapping)) checkmate::assert_list(mapping, types = c("character", "NULL"), names = "named") |
||
167 | -+ | |||
81 | +167x |
-
+ checkmate::assert_string(app_id, null.ok = TRUE) |
||
168 | +82 |
- #' Add optional header to failing messages+ |
||
169 | -+ | |||
83 | +167x |
- #' @noRd+ slices <- list(...) |
||
170 | -+ | |||
84 | +167x |
- #' @keywords internal+ all_slice_id <- vapply(slices, `[[`, character(1L), "id") |
||
171 | +85 |
- add_header <- function(messages, header = "") {+ |
||
172 | -78x | +86 | +167x |
- ans <- unlist(messages)+ if (missing(mapping)) { |
173 | -78x | +87 | +117x |
- if (length(ans) != 0L && isTRUE(nchar(header) > 0L)) {+ mapping <- if (length(all_slice_id)) { |
174 | -31x | +88 | +26x |
- ans <- c(paste0(header, "\n"), ans, "\n")+ list(global_filters = all_slice_id) |
175 | +89 |
- }+ } else { |
||
176 | -78x | +90 | +91x |
- ans+ list() |
177 | +91 |
- }+ } |
||
178 | +92 |
-
+ } |
||
179 | +93 |
- #' Recursively check if the object contains a named list+ |
||
180 | -+ | |||
94 | +167x |
- #' @noRd+ if (!module_specific) {+ |
+ ||
95 | +148x | +
+ mapping[setdiff(names(mapping), "global_filters")] <- NULL |
||
181 | +96 |
- #' @keywords internal+ } |
||
182 | +97 |
- any_names <- function(x) {+ |
||
183 | -103x | +98 | +167x |
- any(+ failed_slice_id <- setdiff(unlist(mapping), all_slice_id) |
184 | -103x | +99 | +167x |
- if (is.list(x)) {+ if (length(failed_slice_id)) { |
185 | -58x | +100 | +1x |
- if (!is.null(names(x)) && any(names(x) != "")) TRUE else unlist(lapply(x, any_names))+ stop(sprintf( |
186 | -+ | |||
101 | +1x |
- } else {+ "Filters in mapping don't match any available filter.\n %s not in %s", |
||
187 | -40x | +102 | +1x |
- FALSE+ toString(failed_slice_id), |
188 | -+ | |||
103 | +1x |
- }+ toString(all_slice_id) |
||
189 | +104 |
- )+ )) |
||
190 | +105 |
- }+ } |
1 | +106 |
- #' Check that argument is reactive.+ |
||
2 | -+ | |||
107 | +166x |
- #'+ tss <- teal.slice::teal_slices( |
||
3 | +108 |
- #' @inherit checkmate::check_class params return+ ..., |
||
4 | -+ | |||
109 | +166x |
- #'+ exclude_varnames = exclude_varnames, |
||
5 | -+ | |||
110 | +166x |
- #' @keywords internal+ include_varnames = include_varnames, |
||
6 | -+ | |||
111 | +166x |
- check_reactive <- function(x, null.ok = FALSE) { # nolint: object_name_linter.+ count_type = count_type, |
||
7 | -1054x | +112 | +166x |
- if (!isTRUE(checkmate::test_class(x, classes = "reactive", null.ok = null.ok))) {+ allow_add = allow_add+ |
+
113 | ++ |
+ ) |
||
8 | -4x | +114 | +166x |
- cl <- class(x)+ attr(tss, "mapping") <- mapping |
9 | -4x | +115 | +166x |
- return(sprintf(+ attr(tss, "module_specific") <- module_specific |
10 | -4x | +116 | +166x |
- "Must be a reactive (i.e. inherit from 'reactive' class) but has class%s '%s'",+ attr(tss, "app_id") <- app_id |
11 | -4x | +117 | +166x |
- if (length(cl) > 1L) "es" else "",+ class(tss) <- c("modules_teal_slices", class(tss)) |
12 | -4x | +118 | +166x |
- paste0(cl, collapse = "','")+ tss |
13 | +119 |
- ))+ }) |
||
14 | +120 |
- }+ } |
||
15 | -1050x | +|||
121 | +
- return(TRUE)+ |
|||
16 | +122 |
- }+ |
||
17 | +123 |
- #' @rdname check_reactive+ #' @rdname teal_slices |
||
18 | +124 |
- test_reactive <- function(x, null.ok = FALSE) { # nolint: object_name_linter.+ #' @export |
||
19 | -30x | +|||
125 | +
- isTRUE(check_reactive(x, null.ok = null.ok))+ #' @keywords internal |
|||
20 | +126 |
- }+ #' |
||
21 | +127 |
- #' @rdname check_reactive+ as.teal_slices <- function(x) { # nolint: object_name. |
||
22 | -+ | |||
128 | +15x |
- assert_reactive <- checkmate::makeAssertionFunction(check_reactive)+ checkmate::assert_list(x)+ |
+ ||
129 | +15x | +
+ lapply(x, checkmate::assert_list, names = "named", .var.name = "list element") |
||
23 | +130 | |||
24 | -+ | |||
131 | +15x |
- #' Capture error and decorate error message.+ attrs <- attributes(unclass(x)) |
||
25 | -+ | |||
132 | +15x |
- #'+ ans <- lapply(x, function(x) if (is.teal_slice(x)) x else as.teal_slice(x))+ |
+ ||
133 | +15x | +
+ do.call(teal_slices, c(ans, attrs)) |
||
26 | +134 |
- #' @param x object to evaluate+ } |
||
27 | +135 |
- #' @param pre (`character(1)`) A string to prepend to error message+ |
||
28 | +136 |
- #' @param post (`character(1)`) A string to append to error message+ |
||
29 | +137 |
- #'+ #' @rdname teal_slices |
||
30 | +138 |
- #' @return `x` if no error, otherwise throws error with decorated message+ #' @export |
||
31 | +139 |
- #'+ #' @keywords internal |
||
32 | +140 |
- #' @keywords internal+ #' |
||
33 | +141 |
- decorate_err_msg <- function(x, pre = character(0), post = character(0)) {+ c.teal_slices <- function(...) { |
||
34 | -47x | +142 | +6x |
- tryCatch(+ x <- list(...) |
35 | -47x | +143 | +6x |
- x,+ checkmate::assert_true(all(vapply(x, is.teal_slices, logical(1L))), .var.name = "all arguments are teal_slices") |
36 | -47x | +|||
144 | +
- error = function(e) {+ |
|||
37 | -2x | +145 | +6x |
- stop(+ all_attributes <- lapply(x, attributes) |
38 | -2x | +146 | +6x |
- "\n",+ all_attributes <- coalesce_r(all_attributes) |
39 | -2x | +147 | +6x |
- pre,+ all_attributes <- all_attributes[names(all_attributes) != "class"] |
40 | -2x | +|||
148 | +
- "\n",+ |
|||
41 | -2x | +149 | +6x |
- e$message,+ do.call( |
42 | -2x | +150 | +6x |
- "\n",+ teal_slices, |
43 | -2x | +151 | +6x |
- post,+ c( |
44 | -2x | +152 | +6x |
- call. = FALSE+ unique(unlist(x, recursive = FALSE)), |
45 | -+ | |||
153 | +6x |
- )+ all_attributes |
||
46 | +154 |
- }+ ) |
||
47 | +155 |
) |
||
48 | -45x | -
- x- |
- ||
49 | +156 |
} |
1 | +157 |
- #' Store and restore `teal_slices` object+ |
|
2 | +158 |
- #'+ |
|
3 | +159 |
- #' Functions that write a `teal_slices` object to a file in the `JSON` format,+ #' Deep copy `teal_slices` |
|
4 | +160 |
- #' and also restore the object from disk.+ #' |
|
5 | +161 |
- #'+ #' it's important to create a new copy of `teal_slices` when |
|
6 | +162 |
- #' Date and date time objects are stored in the following formats:+ #' starting a new `shiny` session. Otherwise, object will be shared |
|
7 | +163 |
- #'+ #' by multiple users as it is created in global environment before |
|
8 | +164 |
- #' - `Date` class is converted to the `"ISO8601"` standard (`YYYY-MM-DD`).+ #' `shiny` session starts. |
|
9 | +165 |
- #' - `POSIX*t` classes are converted to character by using+ #' @param filter (`teal_slices`) |
|
10 | +166 |
- #' `format.POSIX*t(usetz = TRUE, tz = "UTC")` (`YYYY-MM-DD HH:MM:SS UTC`, where+ #' @return `teal_slices` |
|
11 | +167 |
- #' `UTC` is the `Coordinated Universal Time` timezone short-code).+ #' @keywords internal |
|
12 | +168 |
- #'+ deep_copy_filter <- function(filter) { |
|
13 | -+ | ||
169 | +1x |
- #' This format is assumed during `slices_restore`. All `POSIX*t` objects in+ checkmate::assert_class(filter, "teal_slices") |
|
14 | -+ | ||
170 | +1x |
- #' `selected` or `choices` fields of `teal_slice` objects are always printed in+ shiny::isolate({ |
|
15 | -+ | ||
171 | +1x |
- #' `UTC` timezone as well.+ filter_copy <- lapply(filter, function(slice) { |
|
16 | -+ | ||
172 | +2x |
- #'+ teal.slice::as.teal_slice(as.list(slice)) |
|
17 | +173 |
- #' @param tss (`teal_slices`) object to be stored.+ }) |
|
18 | -+ | ||
174 | +1x |
- #' @param file (`character(1)`) file path where `teal_slices` object will be+ attributes(filter_copy) <- attributes(filter) |
|
19 | -+ | ||
175 | +1x |
- #' saved and restored. The file extension should be `".json"`.+ filter_copy |
|
20 | +176 |
- #'+ }) |
|
21 | +177 |
- #' @return `slices_store` returns `NULL`, invisibly.+ } |
22 | +1 |
- #'+ #' `teal_data` utils |
||
23 | +2 |
- #' @seealso [teal_slices()]+ #' |
||
24 | +3 |
- #'+ #' In `teal` we need to recreate the `teal_data` object due to two operations: |
||
25 | +4 |
- #' @keywords internal+ #' - we need to append filter-data code and objects which have been evaluated in `FilteredData` and |
||
26 | +5 |
- #'+ #' we want to avoid double-evaluation. |
||
27 | +6 |
- slices_store <- function(tss, file) {+ #' - we need to subset `teal_data` to `datanames` used by the module, to shorten obtainable R-code |
||
28 | -9x | +|||
7 | +
- checkmate::assert_class(tss, "teal_slices")+ #' |
|||
29 | -9x | +|||
8 | +
- checkmate::assert_path_for_output(file, overwrite = TRUE, extension = "json")+ #' Due to above recreation of `teal_data` object can't be done simply by using public |
|||
30 | +9 |
-
+ #' `teal.code` and `teal.data` methods. |
||
31 | -9x | +|||
10 | +
- cat(format(tss, trim_lines = FALSE), "\n", file = file)+ #' |
|||
32 | +11 |
- }+ #' @param data (`teal_data`) |
||
33 | +12 |
-
+ #' @param code (`character`) code to append to the object's code slot. |
||
34 | +13 |
- #' @rdname slices_store+ #' @param objects (`list`) objects to append to object's environment. |
||
35 | +14 |
- #' @return `slices_restore` returns a `teal_slices` object restored from the file.+ #' @return modified `teal_data` |
||
36 | +15 |
#' @keywords internal |
||
37 | +16 |
- slices_restore <- function(file) {- |
- ||
38 | -9x | -
- checkmate::assert_file_exists(file, access = "r", extension = "json")+ #' @name teal_data_utilities |
||
39 | +17 | - - | -||
40 | -9x | -
- tss_json <- jsonlite::fromJSON(file, simplifyDataFrame = FALSE)- |
- ||
41 | -9x | -
- tss_json$slices <-- |
- ||
42 | -9x | -
- lapply(tss_json$slices, function(slice) {- |
- ||
43 | -9x | -
- for (field in c("selected", "choices")) {- |
- ||
44 | -18x | -
- if (!is.null(slice[[field]])) {- |
- ||
45 | -12x | -
- if (length(slice[[field]]) > 0) {- |
- ||
46 | -9x | -
- date_partial_regex <- "^[0-9]{4}-[0-9]{2}-[0-9]{2}"- |
- ||
47 | -9x | -
- time_stamp_regex <- paste0(date_partial_regex, "\\s[0-9]{2}:[0-9]{2}:[0-9]{2}\\sUTC$")+ NULL |
||
48 | +18 | |||
49 | -9x | +|||
19 | +
- slice[[field]] <-+ #' @rdname teal_data_utilities |
|||
50 | -9x | +|||
20 | +
- if (all(grepl(paste0(date_partial_regex, "$"), slice[[field]]))) {+ .append_evaluated_code <- function(data, code) { |
|||
51 | -3x | +21 | +89x |
- as.Date(slice[[field]])+ checkmate::assert_class(data, "teal_data") |
52 | -9x | +22 | +89x |
- } else if (all(grepl(time_stamp_regex, slice[[field]]))) {+ data@code <- c(data@code, code2list(code)) |
53 | -3x | -
- as.POSIXct(slice[[field]], tz = "UTC")- |
- ||
54 | -+ | 23 | +89x |
- } else {+ methods::validObject(data) |
55 | -3x | -
- slice[[field]]- |
- ||
56 | -+ | 24 | +89x |
- }+ data |
57 | +25 |
- } else {- |
- ||
58 | -3x | -
- slice[[field]] <- character(0)+ } |
||
59 | +26 |
- }+ |
||
60 | +27 |
- }+ #' @rdname teal_data_utilities |
||
61 | +28 |
- }+ .append_modified_data <- function(data, objects) { |
||
62 | -9x | +29 | +89x |
- slice+ checkmate::assert_class(data, "teal_data") |
63 | -+ | |||
30 | +89x |
- })+ checkmate::assert_class(objects, "list") |
||
64 | -+ | |||
31 | +89x |
-
+ new_env <- list2env(objects, parent = .GlobalEnv) |
||
65 | -9x | +32 | +89x |
- tss_elements <- lapply(tss_json$slices, as.teal_slice)+ rlang::env_coalesce(new_env, as.environment(data)) |
66 | -+ | |||
33 | +89x |
-
+ data@.xData <- new_env |
||
67 | -9x | +34 | +89x |
- do.call(teal_slices, c(tss_elements, tss_json$attributes))+ data |
68 | +35 |
}@@ -48166,196 +47831,196 @@ teal coverage - 60.11% |
1 |
- .onLoad <- function(libname, pkgname) {+ #' UI and server modules of `teal` |
||
2 |
- # adapted from https://github.com/r-lib/devtools/blob/master/R/zzz.R+ #' |
||
3 |
-
+ #' @description `r lifecycle::badge("deprecated")` |
||
4 | -! | +
- teal_default_options <- list(+ #' Please use [`module_teal`] instead. |
|
5 | -! | +
- teal.show_js_log = FALSE,+ #' |
|
6 | -! | +
- teal.lockfile.mode = "auto",+ #' @inheritParams ui_teal |
|
7 | -! | +
- shiny.sanitize.errors = FALSE+ #' @inheritParams srv_teal |
|
8 |
- )+ #' |
||
9 |
-
+ #' @return |
||
10 | -! | +
- op <- options()+ #' Returns a `reactive` expression containing a `teal_data` object when data is loaded or `NULL` when it is not. |
|
11 | -! | +
- toset <- !(names(teal_default_options) %in% names(op))+ #' @name module_teal_with_splash |
|
12 | -! | +
- if (any(toset)) options(teal_default_options[toset])+ #' |
|
13 |
-
+ NULL |
||
14 |
- # Set up the teal logger instance+ |
||
15 | -! | +
- teal.logger::register_logger("teal")+ #' @export |
|
16 | -! | +
- teal.logger::register_handlers("teal")+ #' @rdname module_teal_with_splash |
|
17 |
-
+ ui_teal_with_splash <- function(id, |
||
18 | -! | +
- invisible()+ data, |
|
19 |
- }+ title = build_app_title(), |
||
20 |
-
+ header = tags$p(), |
||
21 |
- .onAttach <- function(libname, pkgname) {+ footer = tags$p()) { |
||
22 | -2x | +! |
- packageStartupMessage(+ lifecycle::deprecate_soft( |
23 | -2x | +! |
- "\nYou are using teal version ",+ when = "0.16", |
24 | -+ | ! |
- # `system.file` uses the `shim` of `system.file` by `teal`+ what = "ui_teal_with_splash()", |
25 | -+ | ! |
- # we avoid `desc` dependency here to get the version+ details = "Deprecated, please use `ui_teal` instead" |
26 | -2x | +
- read.dcf(system.file("DESCRIPTION", package = "teal"))[, "Version"]+ ) |
|
27 | -+ | ! |
- )+ ui_teal(id = id, title = title, header = header, footer = footer) |
30 |
- # This one is here because setdiff_teal_slice should not be exported from teal.slice.+ #' @export |
||
31 |
- setdiff_teal_slices <- getFromNamespace("setdiff_teal_slices", "teal.slice")+ #' @rdname module_teal_with_splash |
||
32 |
- # This one is here because it is needed by c.teal_slices but we don't want it exported from teal.slice.+ srv_teal_with_splash <- function(id, data, modules, filter = teal_slices()) { |
||
33 | -+ | ! |
- coalesce_r <- getFromNamespace("coalesce_r", "teal.slice")+ lifecycle::deprecate_soft( |
34 | -+ | ! |
- # all *Block objects are private in teal.reporter+ when = "0.16", |
35 | -+ | ! |
- RcodeBlock <- getFromNamespace("RcodeBlock", "teal.reporter") # nolint: object_name.+ what = "srv_teal_with_splash()", |
36 | -+ | ! |
-
+ details = "Deprecated, please use `srv_teal` instead" |
37 |
- # Use non-exported function(s) from teal.code+ ) |
||
38 | -+ | ! |
- # This one is here because lang2calls should not be exported from teal.code+ srv_teal(id = id, data = data, modules = modules, filter = filter) |
39 |
- lang2calls <- getFromNamespace("lang2calls", "teal.code")- |
- ||
40 | -- |
- code2list <- getFromNamespace("code2list", "teal.data")+ } |
49 |
- #' not work with `devtools`. Therefore, we redefine this method in each package+ #' not work with `devtools`. Therefore, we redefine this method in each package+ |
+
+
50 | ++ |
+ #' as needed. Thus, we do not export this method.+ |
+ |
51 | ++ |
+ #'+ |
+ |
52 | ++ |
+ #' @param files (`character`) vector of filenames.+ |
+ |
53 | ++ |
+ #'+ |
+ |
54 | ++ |
+ #' @return `NULL`, invisibly.+ |
+ |
55 | ++ |
+ #' @keywords internal+ |
+ |
56 | ++ |
+ run_js_files <- function(files) {+ |
+ |
57 | +88x | +
+ checkmate::assert_character(files, min.len = 1, any.missing = FALSE)+ |
+ |
58 | +88x | +
+ lapply(files, function(file) {+ |
+ |
59 | +88x | +
+ shinyjs::runjs(paste0(readLines(system.file("js", file, package = "teal", mustWork = TRUE)), collapse = "\n"))+ |
+ |
60 | ++ |
+ })+ |
+ |
61 | +88x | +
+ invisible(NULL)+ |
+ |
62 | ++ |
+ }+ |
+ |
63 | ++ | + + | +|
64 | ++ |
+ #' Code to include `teal` `CSS` and `JavaScript` files+ |
+ |
65 | ++ |
+ #'+ |
+ |
66 | ++ |
+ #' This is useful when you want to use the same `JavaScript` and `CSS` files that are+ |
+ |
67 | ++ |
+ #' used with the `teal` application.+ |
+ |
68 | ++ |
+ #' This is also useful for running standalone modules in `teal` with the correct+ |
+ |
69 | ++ |
+ #' styles.+ |
+ |
70 | ++ |
+ #' Also initializes `shinyjs` so you can use it.+ |
+ |
71 | ++ |
+ #'+ |
+ |
72 | ++ |
+ #' Simply add `include_teal_css_js()` as one of the UI elements.+ |
+ |
73 | ++ |
+ #' @return A `shiny.tag.list`.+ |
+ |
74 | ++ |
+ #' @keywords internal+ |
+ |
75 | ++ |
+ include_teal_css_js <- function() {+ |
+ |
76 | +! | +
+ tagList(+ |
+ |
77 | +! | +
+ shinyjs::useShinyjs(),+ |
+ |
78 | +! | +
+ include_css_files(),+ |
+ |
79 | ++ |
+ # init.js is executed from the server+ |
+ |
80 | +! | +
+ include_js_files(except = "init.js"),+ |
+ |
81 | +! | +
+ shinyjs::hidden(icon("fas fa-gear")), # add hidden icon to load font-awesome css for icons+ |
+ |
82 | ++ |
+ )+ |
+ |
83 | ++ |
+ }+ |
+
1 | ++ |
+ #' Create a `teal` module for previewing a report+ |
+ ||
2 | ++ |
+ #'+ |
+ ||
3 | ++ |
+ #' @description `r lifecycle::badge("experimental")`+ |
+ ||
4 | ++ |
+ #'+ |
+ ||
5 | ++ |
+ #' This function wraps [teal.reporter::reporter_previewer_ui()] and+ |
+ ||
6 | ++ |
+ #' [teal.reporter::reporter_previewer_srv()] into a `teal_module` to be+ |
+ ||
7 | ++ |
+ #' used in `teal` applications.+ |
+ ||
8 | ++ |
+ #'+ |
+ ||
9 | ++ |
+ #' If you are creating a `teal` application using [init()] then this+ |
+ ||
10 | ++ |
+ #' module will be added to your application automatically if any of your `teal_modules`+ |
+ ||
11 | ++ |
+ #' support report generation.+ |
+ ||
12 | ++ |
+ #'+ |
+ ||
13 | ++ |
+ #' @inheritParams teal_modules+ |
+ ||
14 | ++ |
+ #' @param server_args (named `list`)+ |
+ ||
15 | ++ |
+ #' Arguments passed to [teal.reporter::reporter_previewer_srv()]. |
||
50 | +16 |
- #' as needed. Thus, we do not export this method.+ #' |
||
51 | +17 |
- #'+ #' @return |
||
52 | +18 |
- #' @param files (`character`) vector of filenames.+ #' `teal_module` (extended with `teal_module_previewer` class) containing the `teal.reporter` previewer functionality. |
||
53 | +19 |
#' |
||
54 | +20 |
- #' @return `NULL`, invisibly.+ #' @export |
||
55 | +21 |
- #' @keywords internal+ #' |
||
56 | +22 |
- run_js_files <- function(files) {+ reporter_previewer_module <- function(label = "Report previewer", server_args = list()) { |
||
57 | -88x | +23 | +7x |
- checkmate::assert_character(files, min.len = 1, any.missing = FALSE)+ checkmate::assert_string(label) |
58 | -88x | +24 | +5x |
- lapply(files, function(file) {+ checkmate::assert_list(server_args, names = "named") |
59 | -88x | +25 | +5x |
- shinyjs::runjs(paste0(readLines(system.file("js", file, package = "teal", mustWork = TRUE)), collapse = "\n"))+ checkmate::assert_true(all(names(server_args) %in% names(formals(teal.reporter::reporter_previewer_srv)))) |
60 | +26 |
- })+ |
||
61 | -88x | +27 | +3x |
- invisible(NULL)+ message("Initializing reporter_previewer_module") |
62 | +28 |
- }+ |
||
63 | -+ | |||
29 | +3x |
-
+ srv <- function(id, reporter, ...) { |
||
64 | -+ | |||
30 | +! |
- #' Code to include `teal` `CSS` and `JavaScript` files+ teal.reporter::reporter_previewer_srv(id, reporter, ...) |
||
65 | +31 |
- #'+ } |
||
66 | +32 |
- #' This is useful when you want to use the same `JavaScript` and `CSS` files that are+ |
||
67 | -+ | |||
33 | +3x |
- #' used with the `teal` application.+ ui <- function(id, ...) { |
||
68 | -+ | |||
34 | +! |
- #' This is also useful for running standalone modules in `teal` with the correct+ teal.reporter::reporter_previewer_ui(id, ...) |
||
69 | +35 |
- #' styles.+ } |
||
70 | +36 |
- #' Also initializes `shinyjs` so you can use it.+ |
||
71 | -+ | |||
37 | +3x |
- #'+ module <- module( |
||
72 | -+ | |||
38 | +3x |
- #' Simply add `include_teal_css_js()` as one of the UI elements.+ label = "temporary label", |
||
73 | -+ | |||
39 | +3x |
- #' @return A `shiny.tag.list`.+ server = srv, ui = ui, |
||
74 | -+ | |||
40 | +3x |
- #' @keywords internal+ server_args = server_args, ui_args = list(), datanames = NULL |
||
75 | +41 |
- include_teal_css_js <- function() {- |
- ||
76 | -! | -
- tagList(+ ) |
||
77 | -! | +|||
42 | +
- shinyjs::useShinyjs(),+ # Module is created with a placeholder label and the label is changed later. |
|||
78 | -! | +|||
43 | +
- include_css_files(),+ # This is to prevent another module being labeled "Report previewer". |
|||
79 | -+ | |||
44 | +3x |
- # init.js is executed from the server+ class(module) <- c(class(module), "teal_module_previewer") |
||
80 | -! | +|||
45 | +3x |
- include_js_files(except = "init.js"),+ module$label <- label |
||
81 | -! | +|||
46 | +3x |
- shinyjs::hidden(icon("fas fa-gear")), # add hidden icon to load font-awesome css for icons+ attr(module, "teal_bookmarkable") <- TRUE |
||
82 | -+ | |||
47 | +3x |
- )+ module |
||
83 | +48 |
}@@ -49241,28 +49241,28 @@ teal coverage - 60.11% |
1 |
- #' Show `R` code modal+ setOldClass("teal_data_module") |
||
2 |
- #'+ |
||
3 |
- #' @description `r lifecycle::badge("deprecated")`+ #' Evaluate code on `teal_data_module` |
||
5 |
- #' Use the [shiny::showModal()] function to show the `R` code inside.+ #' @details |
||
6 |
- #'+ #' `eval_code` evaluates given code in the environment of the `teal_data` object created by the `teal_data_module`. |
||
7 |
- #' @param title (`character(1)`)+ #' The code is added to the `@code` slot of the `teal_data`. |
||
8 |
- #' Title of the modal, displayed in the first comment of the `R` code.+ #' |
||
9 |
- #' @param rcode (`character`)+ #' @param object (`teal_data_module`) |
||
10 |
- #' vector with `R` code to show inside the modal.+ #' @inheritParams teal.code::eval_code |
||
11 |
- #' @param session (`ShinySession`) optional+ #' |
||
12 |
- #' `shiny` session object, defaults to [shiny::getDefaultReactiveDomain()].+ #' @return |
||
13 |
- #'+ #' `eval_code` returns a `teal_data_module` object with a delayed evaluation of `code` when the module is run. |
||
14 |
- #' @references [shiny::showModal()]+ #' |
||
15 |
- #' @export+ #' @examples |
||
16 |
- show_rcode_modal <- function(title = NULL, rcode, session = getDefaultReactiveDomain()) {+ #' eval_code(tdm, "dataset1 <- subset(dataset1, Species == 'virginica')") |
||
17 | -! | +
- lifecycle::deprecate_soft(+ #' |
|
18 | -! | +
- when = "0.16",+ #' @include teal_data_module.R |
|
19 | -! | +
- what = "show_rcode_modal()",+ #' @name eval_code |
|
20 | -! | +
- details = "This function will be removed in the next release."+ #' @rdname teal_data_module |
|
21 |
- )+ #' @aliases eval_code,teal_data_module,character-method |
||
22 |
-
+ #' @aliases eval_code,teal_data_module,language-method |
||
23 | -! | +
- rcode <- paste(rcode, collapse = "\n")+ #' @aliases eval_code,teal_data_module,expression-method |
|
24 |
-
+ #' |
||
25 | -! | +
- ns <- session$ns+ #' @importFrom methods setMethod |
|
26 | -! | +
- showModal(modalDialog(+ #' @importMethodsFrom teal.code eval_code |
|
27 | -! | +
- tagList(+ #' |
|
28 | -! | +
- tags$div(+ setMethod("eval_code", signature = c("teal_data_module", "character"), function(object, code) { |
|
29 | -! | +9x |
- actionButton(ns("copyRCode"), "Copy to Clipboard", `data-clipboard-target` = paste0("#", ns("r_code"))),+ teal_data_module( |
30 | -! | +9x |
- modalButton("Dismiss"),+ ui = function(id) { |
31 | -! | +1x |
- style = "mb-4"+ ns <- NS(id) |
32 | -+ | 1x |
- ),+ object$ui(ns("mutate_inner")) |
33 | -! | +
- tags$div(tags$pre(id = ns("r_code"), rcode)),+ }, |
|
34 | -+ | 9x |
- ),+ server = function(id) { |
35 | -! | +7x |
- title = title,+ moduleServer(id, function(input, output, session) { |
36 | -! | +7x |
- footer = tagList(+ data <- object$server("mutate_inner") |
37 | -! | +6x |
- actionButton(ns("copyRCode"), "Copy to Clipboard", `data-clipboard-target` = paste0("#", ns("r_code"))),+ td <- eventReactive(data(), |
38 | -! | +
- modalButton("Dismiss")+ { |
|
39 | -+ | 6x |
- ),+ if (inherits(data(), c("teal_data", "qenv.error"))) { |
40 | -! | +4x |
- size = "l",+ eval_code(data(), code) |
41 | -! | +
- easyClose = TRUE+ } else { |
|
42 | -+ | 2x |
- ))+ data() |
43 |
- }+ }+ |
+ ||
44 | ++ |
+ },+ |
+ |
45 | +6x | +
+ ignoreNULL = FALSE+ |
+ |
46 | ++ |
+ )+ |
+ |
47 | +6x | +
+ td+ |
+ |
48 | ++ |
+ })+ |
+ |
49 | ++ |
+ }+ |
+ |
50 | ++ |
+ )+ |
+ |
51 | ++ |
+ })+ |
+ |
52 | ++ | + + | +|
53 | ++ |
+ setMethod("eval_code", signature = c("teal_data_module", "language"), function(object, code) {+ |
+ |
54 | +1x | +
+ eval_code(object, code = paste(lang2calls(code), collapse = "\n"))+ |
+ |
55 | ++ |
+ })+ |
+ |
56 | ++ | + + | +|
57 | ++ |
+ setMethod("eval_code", signature = c("teal_data_module", "expression"), function(object, code) {+ |
+ |
58 | +2x | +
+ eval_code(object, code = paste(lang2calls(code), collapse = "\n"))+ |
+ |
59 | ++ |
+ }) |
1 |
- setOldClass("teal_data_module")+ #' Store and restore `teal_slices` object |
|||
2 |
-
+ #' |
|||
3 |
- #' Evaluate code on `teal_data_module`+ #' Functions that write a `teal_slices` object to a file in the `JSON` format, |
|||
4 |
- #'+ #' and also restore the object from disk. |
|||
5 |
- #' @details+ #' |
|||
6 |
- #' `eval_code` evaluates given code in the environment of the `teal_data` object created by the `teal_data_module`.+ #' Date and date time objects are stored in the following formats: |
|||
7 |
- #' The code is added to the `@code` slot of the `teal_data`.+ #' |
|||
8 |
- #'+ #' - `Date` class is converted to the `"ISO8601"` standard (`YYYY-MM-DD`). |
|||
9 |
- #' @param object (`teal_data_module`)+ #' - `POSIX*t` classes are converted to character by using |
|||
10 |
- #' @inheritParams teal.code::eval_code+ #' `format.POSIX*t(usetz = TRUE, tz = "UTC")` (`YYYY-MM-DD HH:MM:SS UTC`, where |
|||
11 |
- #'+ #' `UTC` is the `Coordinated Universal Time` timezone short-code). |
|||
12 |
- #' @return+ #' |
|||
13 |
- #' `eval_code` returns a `teal_data_module` object with a delayed evaluation of `code` when the module is run.+ #' This format is assumed during `slices_restore`. All `POSIX*t` objects in |
|||
14 |
- #'+ #' `selected` or `choices` fields of `teal_slice` objects are always printed in |
|||
15 |
- #' @examples+ #' `UTC` timezone as well. |
|||
16 |
- #' eval_code(tdm, "dataset1 <- subset(dataset1, Species == 'virginica')")+ #' |
|||
17 |
- #'+ #' @param tss (`teal_slices`) object to be stored. |
|||
18 |
- #' @include teal_data_module.R+ #' @param file (`character(1)`) file path where `teal_slices` object will be |
|||
19 |
- #' @name eval_code+ #' saved and restored. The file extension should be `".json"`. |
|||
20 |
- #' @rdname teal_data_module+ #' |
|||
21 |
- #' @aliases eval_code,teal_data_module,character-method+ #' @return `slices_store` returns `NULL`, invisibly. |
|||
22 |
- #' @aliases eval_code,teal_data_module,language-method+ #' |
|||
23 |
- #' @aliases eval_code,teal_data_module,expression-method+ #' @seealso [teal_slices()] |
|||
25 |
- #' @importFrom methods setMethod+ #' @keywords internal |
|||
26 |
- #' @importMethodsFrom teal.code eval_code+ #' |
|||
27 |
- #'+ slices_store <- function(tss, file) { |
|||
28 | -+ | 9x |
- setMethod("eval_code", signature = c("teal_data_module", "character"), function(object, code) {+ checkmate::assert_class(tss, "teal_slices") |
|
29 | 9x |
- teal_data_module(+ checkmate::assert_path_for_output(file, overwrite = TRUE, extension = "json") |
||
30 | -9x | +
- ui = function(id) {+ |
||
31 | -1x | +9x |
- ns <- NS(id)+ cat(format(tss, trim_lines = FALSE), "\n", file = file) |
|
32 | -1x | +
- object$ui(ns("mutate_inner"))+ } |
||
33 |
- },+ |
|||
34 | -9x | +
- server = function(id) {+ #' @rdname slices_store |
||
35 | -7x | +
- moduleServer(id, function(input, output, session) {+ #' @return `slices_restore` returns a `teal_slices` object restored from the file. |
||
36 | -7x | +
- teal_data_rv <- object$server("mutate_inner")+ #' @keywords internal |
||
37 | -6x | +
- td <- eventReactive(teal_data_rv(),+ slices_restore <- function(file) { |
||
38 | -+ | 9x |
- {+ checkmate::assert_file_exists(file, access = "r", extension = "json") |
|
39 | -6x | +
- if (inherits(teal_data_rv(), c("teal_data", "qenv.error"))) {+ |
||
40 | -4x | +9x |
- eval_code(teal_data_rv(), code)+ tss_json <- jsonlite::fromJSON(file, simplifyDataFrame = FALSE) |
|
41 | -+ | 9x |
- } else {+ tss_json$slices <- |
|
42 | -2x | +9x |
- teal_data_rv()+ lapply(tss_json$slices, function(slice) { |
|
43 | -+ | 9x |
- }+ for (field in c("selected", "choices")) { |
|
44 | -+ | 18x |
- },+ if (!is.null(slice[[field]])) { |
|
45 | -6x | +12x |
- ignoreNULL = FALSE+ if (length(slice[[field]]) > 0) { |
|
46 | -+ | 9x |
- )+ date_partial_regex <- "^[0-9]{4}-[0-9]{2}-[0-9]{2}" |
|
47 | -6x | +9x |
- td+ time_stamp_regex <- paste0(date_partial_regex, "\\s[0-9]{2}:[0-9]{2}:[0-9]{2}\\sUTC$") |
|
48 |
- })+ |
|||
49 | +9x | +
+ slice[[field]] <-+ |
+ ||
50 | +9x | +
+ if (all(grepl(paste0(date_partial_regex, "$"), slice[[field]]))) {+ |
+ ||
51 | +3x | +
+ as.Date(slice[[field]])+ |
+ ||
52 | +9x | +
+ } else if (all(grepl(time_stamp_regex, slice[[field]]))) {+ |
+ ||
53 | +3x | +
+ as.POSIXct(slice[[field]], tz = "UTC")+ |
+ ||
54 |
- }+ } else {+ |
+ |||
55 | +3x | +
+ slice[[field]] |
||
50 | +56 |
- )+ } |
||
51 | +57 |
- })+ } else {+ |
+ ||
58 | +3x | +
+ slice[[field]] <- character(0) |
||
52 | +59 |
-
+ } |
||
53 | +60 |
- setMethod("eval_code", signature = c("teal_data_module", "language"), function(object, code) {+ }+ |
+ ||
61 | ++ |
+ } |
||
54 | -1x | +62 | +9x |
- eval_code(object, code = paste(lang2calls(code), collapse = "\n"))+ slice |
55 | +63 |
- })+ }) |
||
56 | +64 | |||
65 | +9x | +
+ tss_elements <- lapply(tss_json$slices, as.teal_slice)+ |
+ ||
57 | +66 |
- setMethod("eval_code", signature = c("teal_data_module", "expression"), function(object, code) {+ |
||
58 | -2x | +67 | +9x |
- eval_code(object, code = paste(lang2calls(code), collapse = "\n"))+ do.call(teal_slices, c(tss_elements, tss_json$attributes)) |
59 | +68 |
- })+ } |
1 |
- #' Create a `tdata` object+ #' Show `R` code modal |
||
3 |
- #' @description `r lifecycle::badge("superseded")`+ #' @description `r lifecycle::badge("deprecated")` |
||
5 |
- #' Recent changes in `teal` cause modules to fail because modules expect a `tdata` object+ #' Use the [shiny::showModal()] function to show the `R` code inside. |
||
6 |
- #' to be passed to the `data` argument but instead they receive a `teal_data` object,+ #' |
||
7 |
- #' which is additionally wrapped in a reactive expression in the server functions.+ #' @param title (`character(1)`) |
||
8 |
- #' In order to easily adapt such modules without a proper refactor,+ #' Title of the modal, displayed in the first comment of the `R` code. |
||
9 |
- #' use this function to downgrade the `data` argument.+ #' @param rcode (`character`) |
||
10 |
- #'+ #' vector with `R` code to show inside the modal. |
||
11 |
- #' @name tdata+ #' @param session (`ShinySession`) optional |
||
12 |
- #' @param ... ignored+ #' `shiny` session object, defaults to [shiny::getDefaultReactiveDomain()]. |
||
13 |
- #' @return nothing+ #' |
||
14 |
- NULL+ #' @references [shiny::showModal()] |
||
15 |
-
+ #' @export |
||
16 |
- #' @rdname tdata+ show_rcode_modal <- function(title = NULL, rcode, session = getDefaultReactiveDomain()) { |
||
17 | -+ | ! |
- #' @export+ lifecycle::deprecate_soft( |
18 | -+ | ! |
- new_tdata <- function(...) {+ when = "0.16", |
19 | ! |
- .deprecate_tdata_msg()+ what = "show_rcode_modal()", |
|
20 | -+ | ! |
- }+ details = "This function will be removed in the next release." |
21 |
-
+ ) |
||
22 |
- #' @rdname tdata+ |
||
23 | -+ | ! |
- #' @export+ rcode <- paste(rcode, collapse = "\n") |
24 |
- tdata2env <- function(...) {+ |
||
25 | ! |
- .deprecate_tdata_msg()+ ns <- session$ns |
|
26 | -+ | ! |
- }+ showModal(modalDialog( |
27 | -+ | ! |
-
+ tagList( |
28 | -+ | ! |
- #' @rdname tdata+ tags$div( |
29 | -+ | ! |
- #' @export+ actionButton(ns("copyRCode"), "Copy to Clipboard", `data-clipboard-target` = paste0("#", ns("r_code"))), |
30 | -+ | ! |
- get_code_tdata <- function(...) {+ modalButton("Dismiss"), |
31 | ! |
- .deprecate_tdata_msg()+ style = "mb-4" |
|
32 |
- }+ ), |
||
33 | -+ | ! |
-
+ tags$div(tags$pre(id = ns("r_code"), rcode)), |
34 |
- #' @rdname tdata+ ), |
||
35 | -- |
- #' @export- |
- |
36 | -+ | ! |
- join_keys.tdata <- function(...) {+ title = title, |
37 | +36 | ! |
- .deprecate_tdata_msg()- |
-
38 | -- |
- }- |
- |
39 | -- | - - | -|
40 | -- |
- #' @rdname tdata- |
- |
41 | -- |
- #' @export- |
- |
42 | -- |
- get_metadata <- function(...) {+ footer = tagList( |
|
43 | +37 | ! |
- .deprecate_tdata_msg()- |
-
44 | -- |
- }- |
- |
45 | -- | - - | -|
46 | -- |
- #' @rdname tdata- |
- |
47 | -- |
- #' @export- |
- |
48 | -- |
- as_tdata <- function(...) {+ actionButton(ns("copyRCode"), "Copy to Clipboard", `data-clipboard-target` = paste0("#", ns("r_code"))), |
|
49 | +38 | ! |
- .deprecate_tdata_msg()- |
-
50 | -- |
- }- |
- |
51 | -- | - - | -|
52 | -- |
-
+ modalButton("Dismiss") |
|
53 | +39 |
- .deprecate_tdata_msg <- function() {- |
- |
54 | -! | -
- lifecycle::deprecate_stop(- |
- |
55 | -! | -
- when = "0.16",- |
- |
56 | -! | -
- what = "tdata()",- |
- |
57 | -! | -
- details = paste(+ ), |
|
58 | +40 | ! |
- "tdata has been removed in favour of `teal_data`.\n",+ size = "l", |
59 | +41 | ! |
- "Please follow migration instructions https://github.com/insightsengineering/teal/discussions/987."- |
-
60 | -- |
- )+ easyClose = TRUE |
|
61 | +42 |
- )+ )) |
|
62 | +43 |
} |