diff --git a/coverage-report/index.html b/coverage-report/index.html index 40c982490c..f9fdd34d0a 100644 --- a/coverage-report/index.html +++ b/coverage-report/index.html @@ -95,7 +95,7 @@ font-size: 11px; }
1 |
- #' Execute and validate `teal_data_module`+ # FilteredData ------ |
||
2 |
- #'+ |
||
3 |
- #' This is a low level module to handle `teal_data_module` execution and validation.+ #' Drive a `teal` application |
||
4 |
- #' [teal_transform_module()] inherits from [teal_data_module()] so it is handled by this module too.+ #' |
||
5 |
- #' [srv_teal()] accepts various `data` objects and eventually they are all transformed to `reactive`+ #' Extension of the `shinytest2::AppDriver` class with methods for |
||
6 |
- #' [teal_data()] which is a standard data class in whole `teal` framework.+ #' driving a teal application for performing interactions for `shinytest2` tests. |
||
8 |
- #' @section data validation:+ #' @keywords internal |
||
10 |
- #' Executed [teal_data_module()] is validated and output is validated for consistency.+ TealAppDriver <- R6::R6Class( # nolint: object_name. |
||
11 |
- #' Output `data` is invalid if:+ "TealAppDriver", |
||
12 |
- #' 1. [teal_data_module()] is invalid if server doesn't return `reactive`. **Immediately crashes an app!**+ inherit = { |
||
13 |
- #' 2. `reactive` throws a `shiny.error` - happens when module creating [teal_data()] fails.+ if (!requireNamespace("shinytest2", quietly = TRUE)) { |
||
14 |
- #' 3. `reactive` returns `qenv.error` - happens when [teal_data()] evaluates a failing code.+ stop("Please install 'shinytest2' package to use this class.") |
||
15 |
- #' 4. `reactive` object doesn't return [teal_data()].+ } |
||
16 |
- #' 5. [teal_data()] object lacks any `datanames` specified in the `modules` argument.+ if (!requireNamespace("rvest", quietly = TRUE)) { |
||
17 |
- #'+ stop("Please install 'rvest' package to use this class.") |
||
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+ shinytest2::AppDriver |
||
20 |
- #' resolved, the app will continue to run. `teal` guarantees that errors in data don't crash the app+ }, |
||
21 |
- #' (except error 1).+ # public methods ---- |
||
22 |
- #'+ public = list( |
||
23 |
- #' @param id (`character(1)`) Module id+ #' @description |
||
24 |
- #' @param data (`reactive teal_data`)+ #' Initialize a `TealAppDriver` object for testing a `teal` application. |
||
25 |
- #' @param data_module (`teal_data_module`)+ #' |
||
26 |
- #' @param modules (`teal_modules` or `teal_module`) For `datanames` validation purpose+ #' @param data,modules,filter,title,header,footer,landing_popup arguments passed to `init` |
||
27 |
- #' @param validate_shiny_silent_error (`logical`) If `TRUE`, then `shiny.silent.error` is validated and+ #' @param timeout (`numeric`) Default number of milliseconds for any timeout or |
||
28 |
- #' @param is_transformer_failed (`reactiveValues`) contains `logical` flags named after each transformer.+ #' timeout_ parameter in the `TealAppDriver` class. |
||
29 |
- #' Help to determine if any previous transformer failed, so that following transformers can be disabled+ #' Defaults to 20s. |
||
30 |
- #' and display a generic failure message.+ #' |
||
31 |
- #'+ #' See [`shinytest2::AppDriver`] `new` method for more details on how to change it |
||
32 |
- #' @return `reactive` `teal_data`+ #' via options or environment variables. |
||
33 |
- #'+ #' @param load_timeout (`numeric`) How long to wait for the app to load, in ms. |
||
34 |
- #' @rdname module_teal_data+ #' This includes the time to start R. Defaults to 100s. |
||
35 |
- #' @name module_teal_data+ #' |
||
36 |
- #' @keywords internal+ #' See [`shinytest2::AppDriver`] `new` method for more details on how to change it |
||
37 |
- NULL+ #' via options or environment variables |
||
38 |
-
+ #' @param ... Additional arguments to be passed to `shinytest2::AppDriver$new` |
||
39 |
- #' @rdname module_teal_data+ #' |
||
40 |
- ui_teal_data <- function(id, data_module = function(id) NULL) {+ #' |
||
41 | -! | +
- checkmate::assert_string(id)+ #' @return Object of class `TealAppDriver` |
|
42 | -! | +
- checkmate::assert_function(data_module, args = "id")+ initialize = function(data, |
|
43 | -! | +
- ns <- NS(id)+ modules, |
|
44 |
-
+ filter = teal_slices(), |
||
45 | -! | +
- shiny::tagList(+ title = build_app_title(), |
|
46 | -! | +
- tags$div(id = ns("wrapper"), data_module(id = ns("data"))),+ header = tags$p(), |
|
47 | -! | +
- ui_validate_reactive_teal_data(ns("validate"))+ footer = tags$p(), |
|
48 |
- )+ landing_popup = NULL, |
||
49 |
- }+ timeout = rlang::missing_arg(), |
||
50 |
-
+ load_timeout = rlang::missing_arg(), |
||
51 |
- #' @rdname module_teal_data+ ...) { |
||
52 | -+ | ! |
- srv_teal_data <- function(id,+ private$data <- data |
53 | -+ | ! |
- data_module = function(id) NULL,+ private$modules <- modules |
54 | -+ | ! |
- modules = NULL,+ private$filter <- filter |
55 | -+ | ! |
- validate_shiny_silent_error = TRUE,+ app <- init( |
56 | -+ | ! |
- is_transformer_failed = reactiveValues()) {+ data = data, |
57 | -20x | +! |
- checkmate::assert_string(id)+ modules = modules, |
58 | -20x | +! |
- checkmate::assert_function(data_module, args = "id")+ filter = filter, |
59 | -20x | +! |
- checkmate::assert_multi_class(modules, c("teal_modules", "teal_module"), null.ok = TRUE)+ title = title, |
60 | -20x | +! |
- checkmate::assert_class(is_transformer_failed, "reactivevalues")+ header = header, |
61 | -+ | ! |
-
+ footer = footer, |
62 | -20x | +! |
- moduleServer(id, function(input, output, session) {+ landing_popup = landing_popup, |
63 | -20x | +
- logger::log_debug("srv_teal_data initializing.")+ ) |
|
64 | -20x | +
- is_transformer_failed[[id]] <- FALSE+ |
|
65 | -20x | +
- data_out <- data_module(id = "data")+ # Default timeout is hardcoded to 4s in shinytest2:::resolve_timeout |
|
66 | -20x | +
- data_handled <- reactive(tryCatch(data_out(), error = function(e) e))+ # It must be set as parameter to the AppDriver |
|
67 | -20x | +! |
- observeEvent(data_handled(), {+ suppressWarnings( |
68 | -22x | +! |
- if (!inherits(data_handled(), "teal_data")) {+ super$initialize( |
69 | -6x | +! |
- is_transformer_failed[[id]] <- TRUE+ app_dir = shinyApp(app$ui, app$server), |
70 | -+ | ! |
- } else {+ name = "teal", |
71 | -16x | +! |
- is_transformer_failed[[id]] <- FALSE+ variant = shinytest2::platform_variant(), |
72 | -+ | ! |
- }+ timeout = rlang::maybe_missing(timeout, 20 * 1000), |
73 | -+ | ! |
- })+ load_timeout = rlang::maybe_missing(load_timeout, 100 * 1000), |
74 |
-
+ ... |
||
75 | -20x | +
- is_previous_failed <- reactive({+ ) |
|
76 | -20x | +
- idx_this <- which(names(is_transformer_failed) == id)+ ) |
|
77 | -20x | +
- is_transformer_failed_list <- reactiveValuesToList(is_transformer_failed)+ |
|
78 | -20x | +
- idx_failures <- which(unlist(is_transformer_failed_list))+ # Check for minimum version of Chrome that supports the tests |
|
79 | -20x | +
- any(idx_failures < idx_this)+ # - Element.checkVisibility was added on 105 |
|
80 | -+ | ! |
- })+ chrome_version <- numeric_version( |
81 | -+ | ! |
-
+ gsub( |
82 | -20x | +! |
- observeEvent(is_previous_failed(), {+ "[[:alnum:]_]+/", # Prefix that ends with forward slash |
83 | -20x | +
- if (is_previous_failed()) {+ "", |
|
84 | ! |
- shinyjs::disable("wrapper")+ self$get_chromote_session()$Browser$getVersion()$product |
|
85 |
- } else {+ ), |
||
86 | -20x | +! |
- shinyjs::enable("wrapper")+ strict = FALSE |
87 |
- }+ ) |
||
88 |
- })+ |
||
89 | -+ | ! |
-
+ required_version <- "121" |
90 | -20x | +
- srv_validate_reactive_teal_data(+ |
|
91 | -20x | +! |
- "validate",+ testthat::skip_if( |
92 | -20x | +! |
- data = data_handled,+ is.na(chrome_version), |
93 | -20x | +! |
- modules = modules,+ "Problem getting Chrome version, please contact the developers." |
94 | -20x | +
- validate_shiny_silent_error = validate_shiny_silent_error,+ ) |
|
95 | -20x | +! |
- hide_validation_error = is_previous_failed+ testthat::skip_if( |
96 | -+ | ! |
- )+ chrome_version < required_version, |
97 | -+ | ! |
- })+ sprintf( |
98 | -+ | ! |
- }+ "Chrome version '%s' is not supported, please upgrade to '%s' or higher", |
99 | -+ | ! |
-
+ chrome_version, |
100 | -+ | ! |
- #' @rdname module_teal_data+ required_version |
101 |
- ui_validate_reactive_teal_data <- function(id) {+ ) |
||
102 | -82x | +
- ns <- NS(id)+ ) |
|
103 | -82x | +
- tagList(+ # end od check |
|
104 | -82x | +
- div(+ |
|
105 | -82x | +! |
- id = ns("validate_messages"),+ private$set_active_ns() |
106 | -82x | +! |
- class = "teal_validated",+ self$wait_for_idle() |
107 | -82x | +
- ui_validate_error(ns("silent_error")),+ }, |
|
108 | -82x | +
- ui_check_class_teal_data(ns("class_teal_data")),+ #' @description |
|
109 | -82x | +
- ui_check_shiny_warnings(ns("shiny_warnings"))+ #' Append parent [`shinytest2::AppDriver`] `click` method with a call to `waif_for_idle()` method. |
|
110 |
- ),+ #' @param ... arguments passed to parent [`shinytest2::AppDriver`] `click()` method. |
||
111 | -82x | +
- div(+ click = function(...) { |
|
112 | -82x | +! |
- class = "teal_validated",+ super$click(...) |
113 | -82x | +! |
- uiOutput(ns("previous_failed"))+ private$wait_for_page_stability() |
114 |
- )+ }, |
||
115 |
- )+ #' @description |
||
116 |
- }+ #' Check if the app has shiny errors. This checks for global shiny errors. |
||
117 |
-
+ #' Note that any shiny errors dependent on shiny server render will only be captured after the teal module tab |
||
118 |
- #' @rdname module_teal_data+ #' is visited because shiny will not trigger server computations when the tab is invisible. |
||
119 |
- srv_validate_reactive_teal_data <- function(id, # nolint: object_length+ #' So, navigate to the module tab you want to test before calling this function. |
||
120 |
- data,+ #' Although, this catches errors hidden in the other module tabs if they are already rendered. |
||
121 |
- modules = NULL,+ expect_no_shiny_error = function() { |
||
122 | -+ | ! |
- validate_shiny_silent_error = FALSE,+ testthat::expect_null( |
123 | -+ | ! |
- hide_validation_error = reactive(FALSE)) {+ self$get_html(".shiny-output-error:not(.shiny-output-error-validation)"), |
124 | -183x | +! |
- checkmate::assert_string(id)+ info = "Shiny error is observed" |
125 | -183x | +
- checkmate::assert_multi_class(modules, c("teal_modules", "teal_module"), null.ok = TRUE)+ ) |
|
126 | -183x | +
- checkmate::assert_flag(validate_shiny_silent_error)+ }, |
|
127 |
-
+ #' @description |
||
128 | -183x | +
- moduleServer(id, function(input, output, session) {+ #' Check if the app has no validation errors. This checks for global shiny validation errors. |
|
129 |
- # there is an empty reactive cycle on `init` and `data_rv` has `shiny.silent.error` class+ expect_no_validation_error = function() { |
||
130 | -183x | +! |
- srv_validate_error("silent_error", data, validate_shiny_silent_error)+ testthat::expect_null( |
131 | -183x | +! |
- srv_check_class_teal_data("class_teal_data", data)+ self$get_html(".shiny-output-error-validation"), |
132 | -183x | +! |
- srv_check_shiny_warnings("shiny_warnings", data, modules)+ info = "No validation error is observed" |
133 | -183x | +
- output$previous_failed <- renderUI({+ ) |
|
134 | -173x | +
- if (hide_validation_error()) {+ }, |
|
135 | -! | +
- shinyjs::hide("validate_messages")+ #' @description |
|
136 | -! | +
- tags$div("One of previous transformers failed. Please fix and continue.", class = "teal-output-warning")+ #' Check if the app has validation errors. This checks for global shiny validation errors. |
|
137 |
- } else {+ expect_validation_error = function() { |
||
138 | -173x | +! |
- shinyjs::show("validate_messages")+ testthat::expect_false( |
139 | -173x | +! |
- NULL+ is.null(self$get_html(".shiny-output-error-validation")), |
140 | -+ | ! |
- }+ info = "Validation error is not observed" |
141 |
- })+ ) |
||
142 |
-
+ }, |
||
143 | -183x | +
- .trigger_on_success(data)+ #' @description |
|
144 |
- })+ #' Set the input in the `teal` app. |
||
145 |
- }+ #' |
||
146 |
-
+ #' @param input_id (character) The shiny input id with it's complete name space. |
||
147 |
- #' @keywords internal+ #' @param value The value to set the input to. |
||
148 |
- ui_validate_error <- function(id) {+ #' @param ... Additional arguments to be passed to `shinytest2::AppDriver$set_inputs` |
||
149 | -82x | +
- ns <- NS(id)+ #' |
|
150 | -82x | +
- uiOutput(ns("message"))+ #' @return The `TealAppDriver` object invisibly. |
|
151 |
- }+ set_input = function(input_id, value, ...) { |
||
152 | -+ | ! |
-
+ do.call( |
153 | -+ | ! |
- #' @keywords internal+ self$set_inputs, |
154 | -+ | ! |
- srv_validate_error <- function(id, data, validate_shiny_silent_error) {+ c(setNames(list(value), input_id), list(...)) |
155 | -183x | +
- checkmate::assert_string(id)+ ) |
|
156 | -183x | +! |
- checkmate::assert_flag(validate_shiny_silent_error)+ invisible(self) |
157 | -183x | +
- moduleServer(id, function(input, output, session) {+ }, |
|
158 | -183x | +
- output$message <- renderUI({+ #' @description |
|
159 | -186x | +
- is_shiny_silent_error <- inherits(data(), "shiny.silent.error") && identical(data()$message, "")+ #' Navigate the teal tabs in the `teal` app. |
|
160 | -180x | +
- if (inherits(data(), "qenv.error")) {+ #' |
|
161 | -2x | +
- validate(+ #' @param tabs (character) Labels of tabs to navigate to. The order of the tabs is important, |
|
162 | -2x | +
- need(+ #' and it should start with the most parent level tab. |
|
163 | -2x | +
- FALSE,+ #' Note: In case the teal tab group has duplicate names, the first tab will be selected, |
|
164 | -2x | +
- paste(+ #' If you wish to select the second tab with the same name, use the suffix "_1". |
|
165 | -2x | +
- "Error when executing the `data` module:",+ #' If you wish to select the third tab with the same name, use the suffix "_2" and so on. |
|
166 | -2x | +
- strip_style(paste(data()$message, collapse = "\n")),+ #' |
|
167 | -2x | +
- "\nCheck your inputs or contact app developer if error persists.",+ #' @return The `TealAppDriver` object invisibly. |
|
168 | -2x | +
- collapse = "\n"+ navigate_teal_tab = function(tabs) { |
|
169 | -+ | ! |
- )+ checkmate::check_character(tabs, min.len = 1) |
170 | -+ | ! |
- )+ for (tab in tabs) { |
171 | -+ | ! |
- )+ self$set_input( |
172 | -178x | +! |
- } else if (inherits(data(), "error")) {+ "teal-teal_modules-active_tab", |
173 | -7x | +! |
- if (is_shiny_silent_error && !validate_shiny_silent_error) {+ get_unique_labels(tab), |
174 | -1x | +! |
- return(NULL)+ wait_ = FALSE |
175 |
- }+ ) |
||
176 | -6x | +
- validate(+ } |
|
177 | -6x | +! |
- need(+ self$wait_for_idle() |
178 | -6x | +! |
- FALSE,+ private$set_active_ns() |
179 | -6x | +! |
- sprintf(+ invisible(self) |
180 | -6x | +
- "Shiny error when executing the `data` module.\n%s\n%s",+ }, |
|
181 | -6x | +
- data()$message,+ #' @description |
|
182 | -6x | +
- "Check your inputs or contact app developer if error persists."+ #' Get the active shiny name space for different components of the teal app. |
|
183 |
- )+ #' |
||
184 |
- )+ #' @return (`list`) The list of active shiny name space of the teal components. |
||
185 |
- )+ active_ns = function() { |
||
186 | -+ | ! |
- }+ if (identical(private$ns$module, character(0))) { |
187 | -+ | ! |
- })+ private$set_active_ns() |
188 |
- })+ } |
||
189 | -+ | ! |
- }+ private$ns |
190 |
-
+ }, |
||
191 |
-
+ #' @description |
||
192 |
- #' @keywords internal+ #' Get the active shiny name space for interacting with the module content. |
||
193 |
- ui_check_class_teal_data <- function(id) {+ #' |
||
194 | -82x | +
- ns <- NS(id)+ #' @return (`string`) The active shiny name space of the component. |
|
195 | -82x | +
- uiOutput(ns("message"))+ active_module_ns = function() { |
|
196 | -+ | ! |
- }+ if (identical(private$ns$module, character(0))) { |
197 | -+ | ! |
-
+ private$set_active_ns() |
198 |
- #' @keywords internal+ } |
||
199 | -+ | ! |
- srv_check_class_teal_data <- function(id, data) {+ private$ns$module |
200 | -183x | +
- checkmate::assert_string(id)+ }, |
|
201 | -183x | +
- moduleServer(id, function(input, output, session) {+ #' @description |
|
202 | -183x | +
- output$message <- renderUI({+ #' Get the active shiny name space bound with a custom `element` name. |
|
203 | -186x | +
- validate(+ #' |
|
204 | -186x | +
- need(+ #' @param element `character(1)` custom element name. |
|
205 | -186x | +
- inherits(data(), c("teal_data", "error")),+ #' |
|
206 | -186x | +
- "Did not receive `teal_data` object. Cannot proceed further."+ #' @return (`string`) The active shiny name space of the component bound with the input `element`. |
|
207 |
- )+ active_module_element = function(element) { |
||
208 | -+ | ! |
- )+ checkmate::assert_string(element) |
209 | -+ | ! |
- })+ sprintf("#%s-%s", self$active_module_ns(), element) |
210 |
- })+ }, |
||
211 |
- }+ #' @description |
||
212 |
-
+ #' Get the text of the active shiny name space bound with a custom `element` name. |
||
213 |
- #' @keywords internal+ #' |
||
214 |
- ui_check_shiny_warnings <- function(id) {+ #' @param element `character(1)` the text of the custom element name. |
||
215 | -82x | +
- ns <- NS(id)+ #' |
|
216 | -82x | +
- uiOutput(NS(id, "message"))+ #' @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 | -+ | ! |
- #' @keywords internal+ self$get_text(self$active_module_element(element)) |
220 |
- srv_check_shiny_warnings <- function(id, data, modules) {+ }, |
||
221 | -183x | +
- checkmate::assert_string(id)+ #' @description |
|
222 | -183x | +
- moduleServer(id, function(input, output, session) {+ #' Get the active shiny name space for interacting with the filter panel. |
|
223 | -183x | +
- output$message <- renderUI({+ #' |
|
224 | -186x | +
- if (inherits(data(), "teal_data")) {+ #' @return (`string`) The active shiny name space of the component. |
|
225 | -169x | +
- is_modules_ok <- check_modules_datanames_html(+ active_filters_ns = function() { |
|
226 | -169x | +! |
- modules = modules, datanames = ls(teal.code::get_env(data()))+ if (identical(private$ns$filter_panel, character(0))) { |
227 | -+ | ! |
- )+ private$set_active_ns() |
228 | -169x | +
- if (!isTRUE(is_modules_ok)) {+ } |
|
229 | -15x | +! |
- tags$div(is_modules_ok, class = "teal-output-warning")+ private$ns$filter_panel |
230 |
- }+ }, |
||
231 |
- }+ #' @description |
||
232 |
- })+ #' Get the active shiny name space for interacting with the data-summary panel. |
||
233 |
- })+ #' |
||
234 |
- }+ #' @return (`string`) The active shiny name space of the data-summary component. |
||
235 |
-
+ active_data_summary_ns = function() { |
||
236 | -+ | ! |
- .trigger_on_success <- function(data) {+ if (identical(private$ns$data_summary, character(0))) { |
237 | -183x | +! |
- out <- reactiveVal(NULL)+ private$set_active_ns() |
238 | -183x | +
- observeEvent(data(), {+ } |
|
239 | -180x | +! |
- if (inherits(data(), "teal_data")) {+ private$ns$data_summary |
240 | -169x | +
- if (!identical(data(), out())) {+ }, |
|
241 | -169x | +
- out(data())+ #' @description |
|
242 |
- }+ #' Get the active shiny name space bound with a custom `element` name. |
||
243 |
- }+ #' |
||
244 |
- })+ #' @param element `character(1)` custom element name. |
||
245 |
-
+ #' |
||
246 | -183x | +
- out+ #' @return (`string`) The active shiny name space of the component bound with the input `element`. |
|
247 |
- }+ active_data_summary_element = function(element) {+ |
+ ||
248 | +! | +
+ checkmate::assert_string(element)+ |
+ |
249 | +! | +
+ sprintf("#%s-%s", self$active_data_summary_ns(), element) |
1 | +250 |
- #' Get client timezone+ }, |
|
2 | +251 |
- #'+ #' @description |
|
3 | +252 |
- #' User timezone in the browser may be different to the one on the server.+ #' Get the input from the module in the `teal` app. |
|
4 | +253 |
- #' This script can be run to register a `shiny` input which contains information about the timezone in the browser.+ #' This function will only access inputs from the name space of the current active teal module. |
|
5 | +254 |
- #'+ #' |
|
6 | +255 |
- #' @param ns (`function`) namespace function passed from the `session` object in the `shiny` server.+ #' @param input_id (character) The shiny input id to get the value from. |
|
7 | +256 |
- #' For `shiny` modules this will allow for proper name spacing of the registered input.+ #' |
|
8 | +257 |
- #'+ #' @return The value of the shiny input. |
|
9 | +258 |
- #' @return `NULL`, invisibly.+ get_active_module_input = function(input_id) {+ |
+ |
259 | +! | +
+ checkmate::check_string(input_id)+ |
+ |
260 | +! | +
+ self$get_value(input = sprintf("%s-%s", self$active_module_ns(), input_id)) |
|
10 | +261 |
- #'+ }, |
|
11 | +262 |
- #' @keywords internal+ #' @description |
|
12 | +263 |
- #'+ #' Get the output from the module in the `teal` app. |
|
13 | +264 |
- get_client_timezone <- function(ns) {+ #' This function will only access outputs from the name space of the current active teal module. |
|
14 | -83x | +||
265 | +
- script <- sprintf(+ #' |
||
15 | -83x | +||
266 | +
- "Shiny.setInputValue(`%s`, Intl.DateTimeFormat().resolvedOptions().timeZone)",+ #' @param output_id (character) The shiny output id to get the value from. |
||
16 | -83x | +||
267 | +
- ns("timezone")+ #' |
||
17 | +268 |
- )+ #' @return The value of the shiny output. |
|
18 | -83x | +||
269 | +
- shinyjs::runjs(script) # function does not return anything+ get_active_module_output = function(output_id) { |
||
19 | -83x | +||
270 | +! |
- invisible(NULL)+ checkmate::check_string(output_id) |
|
20 | -+ | ||
271 | +! |
- }+ self$get_value(output = sprintf("%s-%s", self$active_module_ns(), output_id)) |
|
21 | +272 |
-
+ }, |
|
22 | +273 |
- #' Resolve the expected bootstrap theme+ #' @description |
|
23 | +274 |
- #' @noRd+ #' Get the output from the module's `teal.widgets::table_with_settings` or `DT::DTOutput` in the `teal` app. |
|
24 | +275 |
- #' @keywords internal+ #' This function will only access outputs from the name space of the current active teal module. |
|
25 | +276 |
- get_teal_bs_theme <- function() {+ #' |
|
26 | -4x | +||
277 | +
- bs_theme <- getOption("teal.bs_theme")+ #' @param table_id (`character(1)`) The id of the table in the active teal module's name space. |
||
27 | +278 |
-
+ #' @param which (integer) If there is more than one table, which should be extracted. |
|
28 | -4x | +||
279 | +
- if (is.null(bs_theme)) {+ #' By default it will look for a table that is built using `teal.widgets::table_with_settings`. |
||
29 | -1x | +||
280 | +
- return(NULL)+ #' |
||
30 | +281 |
- }+ #' @return The data.frame with table contents. |
|
31 | +282 |
-
+ get_active_module_table_output = function(table_id, which = 1) { |
|
32 | -3x | +||
283 | +! |
- if (!checkmate::test_class(bs_theme, "bs_theme")) {+ checkmate::check_number(which, lower = 1) |
|
33 | -2x | +||
284 | +! |
- warning(+ checkmate::check_string(table_id) |
|
34 | -2x | +||
285 | +! |
- "Assertion on 'teal.bs_theme' option value failed: ",+ table <- rvest::html_table( |
|
35 | -2x | +||
286 | +! |
- checkmate::check_class(bs_theme, "bs_theme"),+ self$get_html_rvest(self$active_module_element(table_id)), |
|
36 | -2x | +||
287 | +! |
- ". The default Shiny Bootstrap theme will be used."+ fill = TRUE |
|
37 | +288 |
- )+ ) |
|
38 | -2x | +||
289 | +! |
- return(NULL)+ if (length(table) == 0) { |
|
39 | -+ | ||
290 | +! |
- }+ data.frame() |
|
40 | +291 |
-
+ } else { |
|
41 | -1x | +||
292 | +! |
- bs_theme+ table[[which]] |
|
42 | +293 |
- }+ } |
|
43 | +294 |
-
+ }, |
|
44 | +295 |
- #' Return parentnames along with datanames.+ #' @description |
|
45 | +296 |
- #' @noRd+ #' Get the output from the module's `teal.widgets::plot_with_settings` in the `teal` app. |
|
46 | +297 |
- #' @keywords internal+ #' This function will only access plots from the name space of the current active teal module. |
|
47 | +298 |
- .include_parent_datanames <- function(datanames, join_keys) {- |
- |
48 | -167x | -
- ordered_datanames <- datanames+ #' |
|
49 | -167x | +||
299 | +
- for (i in datanames) {+ #' @param plot_id (`character(1)`) The id of the plot in the active teal module's name space. |
||
50 | -306x | +||
300 | +
- parents <- character(0)+ #' |
||
51 | -306x | +||
301 | +
- while (length(i) > 0) {+ #' @return The `src` attribute as `character(1)` vector. |
||
52 | -319x | +||
302 | +
- parent_i <- teal.data::parent(join_keys, i)+ get_active_module_plot_output = function(plot_id) { |
||
53 | -319x | +||
303 | +! |
- parents <- c(parent_i, parents)+ checkmate::check_string(plot_id) |
|
54 | -319x | +||
304 | +! |
- i <- parent_i+ self$get_attr( |
|
55 | -+ | ||
305 | +! |
- }+ self$active_module_element(sprintf("%s-plot_main > img", plot_id)), |
|
56 | -306x | +||
306 | +! |
- ordered_datanames <- c(parents, ordered_datanames)+ "src" |
|
57 | +307 |
- }- |
- |
58 | -167x | -
- unique(ordered_datanames)+ ) |
|
59 | +308 |
- }+ }, |
|
60 | +309 |
-
+ #' @description |
|
61 | +310 |
- #' Return topologicaly sorted datanames+ #' Set the input in the module in the `teal` app. |
|
62 | +311 |
- #' @noRd+ #' This function will only set inputs in the name space of the current active teal module. |
|
63 | +312 |
- #' @keywords internal+ #' |
|
64 | +313 |
- .topologically_sort_datanames <- function(datanames, join_keys) {- |
- |
65 | -135x | -
- datanames_with_parents <- .include_parent_datanames(datanames, join_keys)+ #' @param input_id (character) The shiny input id to get the value from. |
|
66 | -135x | +||
314 | +
- intersect(datanames, datanames_with_parents)+ #' @param value The value to set the input to. |
||
67 | +315 |
- }+ #' @param ... Additional arguments to be passed to `shinytest2::AppDriver$set_inputs` |
|
68 | +316 |
-
+ #' |
|
69 | +317 |
- #' Create a `FilteredData`+ #' @return The `TealAppDriver` object invisibly. |
|
70 | +318 |
- #'+ set_active_module_input = function(input_id, value, ...) { |
|
71 | -+ | ||
319 | +! |
- #' Create a `FilteredData` object from a `teal_data` object.+ checkmate::check_string(input_id) |
|
72 | -+ | ||
320 | +! |
- #'+ checkmate::check_string(value) |
|
73 | -+ | ||
321 | +! |
- #' @param x (`teal_data`) object+ self$set_input( |
|
74 | -+ | ||
322 | +! |
- #' @param datanames (`character`) vector of data set names to include; must be subset of `datanames(x)`+ sprintf("%s-%s", self$active_module_ns(), input_id), |
|
75 | -+ | ||
323 | +! |
- #' @return A `FilteredData` object.+ value, |
|
76 | +324 |
- #' @keywords internal+ ... |
|
77 | +325 |
- teal_data_to_filtered_data <- function(x, datanames = ls(teal.code::get_env(x))) {+ ) |
|
78 | -78x | -
- checkmate::assert_class(x, "teal_data")- |
- |
79 | -78x | -
- checkmate::assert_character(datanames, min.chars = 1L, any.missing = FALSE)- |
- |
80 | -- |
- # Otherwise, FilteredData will be created in the modules' scope later- |
- |
81 | -78x | -
- teal.slice::init_filtered_data(- |
- |
82 | -78x | +||
326 | +! |
- x = Filter(+ dots <- rlang::list2(...) |
|
83 | -78x | +||
327 | +! |
- length,+ if (!isFALSE(dots[["wait"]])) self$wait_for_idle() # Default behavior is to wait |
|
84 | -78x | +||
328 | +! |
- sapply(datanames, function(dn) x[[dn]], simplify = FALSE)+ invisible(self) |
|
85 | +329 |
- ),- |
- |
86 | -78x | -
- join_keys = teal.data::join_keys(x)+ }, |
|
87 | +330 |
- )+ #' @description |
|
88 | +331 |
- }+ #' Get the active datasets that can be accessed via the filter panel of the current active teal module. |
|
89 | +332 |
-
+ get_active_filter_vars = function() { |
|
90 | -+ | ||
333 | +! |
-
+ displayed_datasets_index <- self$is_visible( |
|
91 | -+ | ||
334 | +! |
- #' Template function for `TealReportCard` creation and customization+ sprintf("#%s-filters-filter_active_vars_contents > span", self$active_filters_ns()) |
|
92 | +335 |
- #'+ ) |
|
93 | +336 |
- #' This function generates a report card with a title,+ |
|
94 | -+ | ||
337 | +! |
- #' an optional description, and the option to append the filter state list.+ available_datasets <- self$get_text( |
|
95 | -+ | ||
338 | +! |
- #'+ sprintf( |
|
96 | -+ | ||
339 | +! |
- #' @param title (`character(1)`) title of the card (unless overwritten by label)+ "#%s-filters-filter_active_vars_contents .filter_panel_dataname", |
|
97 | -+ | ||
340 | +! |
- #' @param label (`character(1)`) label provided by the user when adding the card+ self$active_filters_ns() |
|
98 | +341 |
- #' @param description (`character(1)`) optional, additional description+ ) |
|
99 | +342 |
- #' @param with_filter (`logical(1)`) flag indicating to add filter state+ ) |
|
100 | +343 |
- #' @param filter_panel_api (`FilterPanelAPI`) object with API that allows the generation+ |
|
101 | -+ | ||
344 | +! |
- #' of the filter state in the report+ available_datasets[displayed_datasets_index] |
|
102 | +345 |
- #'+ }, |
|
103 | +346 |
- #' @return (`TealReportCard`) populated with a title, description and filter state.+ #' @description |
|
104 | +347 |
- #'+ #' Get the active data summary table |
|
105 | +348 |
- #' @export+ #' @return `data.frame` |
|
106 | +349 |
- report_card_template <- function(title, label, description = NULL, with_filter, filter_panel_api) {- |
- |
107 | -2x | -
- checkmate::assert_string(title)+ get_active_data_summary_table = function() { |
|
108 | -2x | +||
350 | +! |
- checkmate::assert_string(label)+ summary_table <- rvest::html_table( |
|
109 | -2x | +||
351 | +! |
- checkmate::assert_string(description, null.ok = TRUE)+ self$get_html_rvest(self$active_data_summary_element("table")), |
|
110 | -2x | +||
352 | +! |
- checkmate::assert_flag(with_filter)+ fill = TRUE |
|
111 | -2x | +||
353 | +! |
- checkmate::assert_class(filter_panel_api, classes = "FilterPanelAPI")+ )[[1]] |
|
112 | +354 | ||
113 | -2x | -
- card <- teal::TealReportCard$new()- |
- |
114 | -2x | -
- title <- if (label == "") title else label- |
- |
115 | -2x | +||
355 | +! |
- card$set_name(title)+ col_names <- unlist(summary_table[1, ], use.names = FALSE) |
|
116 | -2x | +||
356 | +! |
- card$append_text(title, "header2")+ summary_table <- summary_table[-1, ] |
|
117 | -1x | +||
357 | +! |
- if (!is.null(description)) card$append_text(description, "header3")+ colnames(summary_table) <- col_names |
|
118 | -1x | +||
358 | +! |
- if (with_filter) card$append_fs(filter_panel_api$get_filter_state())+ if (nrow(summary_table) > 0) { |
|
119 | -2x | +||
359 | +! |
- card+ summary_table |
|
120 | +360 |
- }+ } else { |
|
121 | -+ | ||
361 | +! |
-
+ NULL |
|
122 | +362 |
-
+ } |
|
123 | +363 |
- #' Check `datanames` in modules+ }, |
|
124 | +364 |
- #'+ #' @description |
|
125 | +365 |
- #' These functions check if specified `datanames` in modules match those in the data object,+ #' Test if `DOM` elements are visible on the page with a JavaScript call. |
|
126 | +366 |
- #' returning error messages or `TRUE` for successful validation. Two functions return error message+ #' @param selector (`character(1)`) `CSS` selector to check visibility. |
|
127 | +367 |
- #' in different forms:+ #' A `CSS` id will return only one element if the UI is well formed. |
|
128 | +368 |
- #' - `check_modules_datanames` returns `character(1)` for basic assertion usage+ #' @param content_visibility_auto,opacity_property,visibility_property (`logical(1)`) See more information |
|
129 | +369 |
- #' - `check_modules_datanames_html` returns `shiny.tag.list` to display it in the app.+ #' on <https://developer.mozilla.org/en-US/docs/Web/API/Element/checkVisibility>. |
|
130 | +370 |
- #'+ #' |
|
131 | +371 |
- #' @param modules (`teal_modules`) object+ #' @return Logical vector with all occurrences of the selector. |
|
132 | +372 |
- #' @param datanames (`character`) names of datasets available in the `data` object+ is_visible = function(selector, |
|
133 | +373 |
- #'+ content_visibility_auto = FALSE, |
|
134 | +374 |
- #' @return `TRUE` if validation passes, otherwise `character(1)` or `shiny.tag.list`+ opacity_property = FALSE, |
|
135 | +375 |
- #' @keywords internal+ visibility_property = FALSE) { |
|
136 | -+ | ||
376 | +! |
- check_modules_datanames <- function(modules, datanames) {+ checkmate::assert_string(selector) |
|
137 | -9x | +||
377 | +! |
- out <- check_modules_datanames_html(modules, datanames)+ checkmate::assert_flag(content_visibility_auto) |
|
138 | -9x | +||
378 | +! |
- if (inherits(out, "shiny.tag.list")) {+ checkmate::assert_flag(opacity_property) |
|
139 | -3x | +||
379 | +! |
- out_with_ticks <- gsub("<code>|</code>", "`", toString(out))+ checkmate::assert_flag(visibility_property) |
|
140 | -3x | +||
380 | +
- out_text <- gsub("<[^<>]+>", "", toString(out_with_ticks))+ |
||
141 | -3x | +||
381 | +! |
- trimws(gsub("[[:space:]]+", " ", out_text))+ private$wait_for_page_stability() |
|
142 | +382 |
- } else {- |
- |
143 | -6x | -
- out+ |
|
144 | -+ | ||
383 | +! |
- }+ testthat::skip_if_not( |
|
145 | -+ | ||
384 | +! |
- }+ self$get_js("typeof Element.prototype.checkVisibility === 'function'"), |
|
146 | -+ | ||
385 | +! |
-
+ "Element.prototype.checkVisibility is not supported in the current browser." |
|
147 | +386 |
- #' @rdname check_modules_datanames+ ) |
|
148 | +387 |
- check_modules_datanames_html <- function(modules,+ |
|
149 | -+ | ||
388 | +! |
- datanames) {+ unlist( |
|
150 | -178x | +||
389 | +! |
- check_datanames <- check_modules_datanames_recursive(modules, datanames)+ self$get_js( |
|
151 | -178x | +||
390 | +! |
- show_module_info <- inherits(modules, "teal_modules") # used in two contexts - module and app+ sprintf( |
|
152 | -178x | +||
391 | +! |
- if (!length(check_datanames)) {+ "Array.from(document.querySelectorAll('%s')).map(el => el.checkVisibility({%s, %s, %s}))", |
|
153 | -160x | +||
392 | +! |
- return(TRUE)+ selector, |
|
154 | +393 |
- }+ # Extra parameters |
|
155 | -18x | +||
394 | +! |
- shiny::tagList(+ sprintf("contentVisibilityAuto: %s", tolower(content_visibility_auto)), |
|
156 | -18x | +||
395 | +! |
- lapply(+ sprintf("opacityProperty: %s", tolower(opacity_property)), |
|
157 | -18x | +||
396 | +! |
- check_datanames,+ sprintf("visibilityProperty: %s", tolower(visibility_property)) |
|
158 | -18x | +||
397 | +
- function(mod) {+ ) |
||
159 | -18x | +||
398 | +
- tagList(+ ) |
||
160 | -18x | +||
399 | +
- tags$span(+ ) |
||
161 | -18x | +||
400 | +
- tags$span(if (length(mod$missing_datanames) == 1) "Dataset" else "Datasets"),+ }, |
||
162 | -18x | +||
401 | +
- to_html_code_list(mod$missing_datanames),+ #' @description |
||
163 | -18x | +||
402 | +
- tags$span(+ #' Get the active filter variables from a dataset in the `teal` app. |
||
164 | -18x | +||
403 | +
- paste0(+ #' |
||
165 | -18x | +||
404 | +
- if (length(mod$missing_datanames) > 1) "are missing" else "is missing",+ #' @param dataset_name (character) The name of the dataset to get the filter variables from. |
||
166 | -18x | +||
405 | +
- if (show_module_info) sprintf(" for module '%s'.", mod$label) else "."+ #' If `NULL`, the filter variables for all the datasets will be returned in a list. |
||
167 | +406 |
- )+ get_active_data_filters = function(dataset_name = NULL) { |
|
168 | -+ | ||
407 | +! |
- )+ checkmate::check_string(dataset_name, null.ok = TRUE) |
|
169 | -+ | ||
408 | +! |
- ),+ datasets <- self$get_active_filter_vars() |
|
170 | -18x | +||
409 | +! |
- if (length(datanames) >= 1) {+ checkmate::assert_subset(dataset_name, datasets) |
|
171 | -16x | +||
410 | +! |
- tagList(+ active_filters <- lapply( |
|
172 | -16x | +||
411 | +! |
- tags$span(if (length(datanames) == 1) "Dataset" else "Datasets"),+ datasets, |
|
173 | -16x | +||
412 | +! |
- tags$span("available in data:"),+ function(x) { |
|
174 | -16x | +||
413 | +! |
- tagList(+ var_names <- gsub( |
|
175 | -16x | +||
414 | +! |
- tags$span(+ pattern = "\\s", |
|
176 | -16x | +||
415 | +! |
- to_html_code_list(datanames),+ replacement = "", |
|
177 | -16x | +||
416 | +! |
- tags$span(".", .noWS = "outside"),+ self$get_text( |
|
178 | -16x | +||
417 | +! |
- .noWS = c("outside")+ sprintf( |
|
179 | -+ | ||
418 | +! |
- )+ "#%s-filters-%s .filter-card-varname",+ |
+ |
419 | +! | +
+ self$active_filters_ns(),+ |
+ |
420 | +! | +
+ x |
|
180 | +421 |
) |
|
181 | +422 |
) |
|
182 | +423 |
- } else {+ ) |
|
183 | -2x | +||
424 | +! |
- tags$span("No datasets are available in data.")+ structure( |
|
184 | -+ | ||
425 | +! |
- },+ lapply(var_names, private$get_active_filter_selection, dataset_name = x), |
|
185 | -18x | +||
426 | +! |
- tags$br(.noWS = "before")+ names = var_names |
|
186 | +427 |
- )+ ) |
|
187 | +428 |
- }+ } |
|
188 | +429 |
- )+ ) |
|
189 | -+ | ||
430 | +! |
- )+ names(active_filters) <- datasets |
|
190 | -+ | ||
431 | +! |
- }+ if (is.null(dataset_name)) { |
|
191 | -+ | ||
432 | +! |
-
+ return(active_filters) |
|
192 | +433 |
- #' Recursively checks modules and returns list for every datanames mismatch between module and data+ }+ |
+ |
434 | +! | +
+ active_filters[[dataset_name]] |
|
193 | +435 |
- #' @noRd+ }, |
|
194 | +436 |
- check_modules_datanames_recursive <- function(modules, datanames) { # nolint: object_name_length+ #' @description |
|
195 | -277x | +||
437 | +
- checkmate::assert_multi_class(modules, c("teal_module", "teal_modules"))+ #' Add a new variable from the dataset to be filtered. |
||
196 | -277x | +||
438 | +
- checkmate::assert_character(datanames)+ #' |
||
197 | -277x | +||
439 | +
- if (inherits(modules, "teal_modules")) {+ #' @param dataset_name (character) The name of the dataset to add the filter variable to. |
||
198 | -79x | +||
440 | +
- unlist(+ #' @param var_name (character) The name of the variable to add to the filter panel. |
||
199 | -79x | +||
441 | +
- lapply(modules$children, check_modules_datanames_recursive, datanames = datanames),+ #' @param ... Additional arguments to be passed to `shinytest2::AppDriver$set_inputs` |
||
200 | -79x | +||
442 | +
- recursive = FALSE+ #' |
||
201 | +443 |
- )+ #' @return The `TealAppDriver` object invisibly. |
|
202 | +444 |
- } else {+ add_filter_var = function(dataset_name, var_name, ...) { |
|
203 | -198x | +||
445 | +! |
- missing_datanames <- setdiff(modules$datanames, c("all", datanames))+ checkmate::check_string(dataset_name) |
|
204 | -198x | +||
446 | +! |
- if (length(missing_datanames)) {+ checkmate::check_string(var_name) |
|
205 | -18x | +||
447 | +! |
- list(list(+ private$set_active_ns() |
|
206 | -18x | +||
448 | +! |
- label = modules$label,+ self$click( |
|
207 | -18x | +||
449 | +! |
- missing_datanames = missing_datanames+ selector = sprintf( |
|
208 | -+ | ||
450 | +! |
- ))+ "#%s-filters-%s-add_filter_icon", |
|
209 | -+ | ||
451 | +! |
- }+ private$ns$filter_panel, |
|
210 | -+ | ||
452 | +! |
- }+ dataset_name |
|
211 | +453 |
- }+ ) |
|
212 | +454 |
-
+ ) |
|
213 | -+ | ||
455 | +! |
- #' Convert character vector to html code separated with commas and "and"+ self$set_input( |
|
214 | -+ | ||
456 | +! |
- #' @noRd+ sprintf( |
|
215 | -+ | ||
457 | +! |
- to_html_code_list <- function(x) {+ "%s-filters-%s-%s-filter-var_to_add", |
|
216 | -34x | +||
458 | +! |
- checkmate::assert_character(x)+ private$ns$filter_panel, |
|
217 | -34x | +||
459 | +! |
- do.call(+ dataset_name, |
|
218 | -34x | +||
460 | +! |
- tagList,+ dataset_name |
|
219 | -34x | +||
461 | +
- lapply(seq_along(x), function(.ix) {+ ), |
||
220 | -47x | +||
462 | +! |
- tagList(+ var_name, |
|
221 | -47x | +||
463 | +
- tags$code(x[.ix]),+ ... |
||
222 | -47x | +||
464 | +
- if (.ix != length(x)) {+ ) |
||
223 | -1x | +||
465 | +! |
- if (.ix == length(x) - 1) tags$span(" and ") else tags$span(", ", .noWS = "before")+ invisible(self) |
|
224 | +466 |
- }+ }, |
|
225 | +467 |
- )+ #' @description |
|
226 | +468 |
- })+ #' Remove an active filter variable of a dataset from the active filter variables panel. |
|
227 | +469 |
- )+ #' |
|
228 | +470 |
- }+ #' @param dataset_name (character) The name of the dataset to remove the filter variable from. |
|
229 | +471 |
-
+ #' If `NULL`, all the filter variables will be removed. |
|
230 | +472 |
-
+ #' @param var_name (character) The name of the variable to remove from the filter panel. |
|
231 | +473 |
- #' Check `datanames` in filters+ #' If `NULL`, all the filter variables of the dataset will be removed. |
|
232 | +474 |
- #'+ #' |
|
233 | +475 |
- #' This function checks whether `datanames` in filters correspond to those in `data`,+ #' @return The `TealAppDriver` object invisibly. |
|
234 | +476 |
- #' returning character vector with error messages or `TRUE` if all checks pass.+ remove_filter_var = function(dataset_name = NULL, var_name = NULL) { |
|
235 | -+ | ||
477 | +! |
- #'+ checkmate::check_string(dataset_name, null.ok = TRUE) |
|
236 | -+ | ||
478 | +! |
- #' @param filters (`teal_slices`) object+ checkmate::check_string(var_name, null.ok = TRUE) |
|
237 | -+ | ||
479 | +! |
- #' @param datanames (`character`) names of datasets available in the `data` object+ if (is.null(dataset_name)) { |
|
238 | -+ | ||
480 | +! |
- #'+ remove_selector <- sprintf( |
|
239 | -+ | ||
481 | +! |
- #' @return A `character(1)` containing error message or TRUE if validation passes.+ "#%s-active-remove_all_filters", |
|
240 | -+ | ||
482 | +! |
- #' @keywords internal+ self$active_filters_ns() |
|
241 | +483 |
- check_filter_datanames <- function(filters, datanames) {+ ) |
|
242 | -79x | +||
484 | +! |
- checkmate::assert_class(filters, "teal_slices")+ } else if (is.null(var_name)) { |
|
243 | -79x | +||
485 | +! |
- checkmate::assert_character(datanames)+ remove_selector <- sprintf( |
|
244 | -+ | ||
486 | +! |
-
+ "#%s-active-%s-remove_filters", |
|
245 | -+ | ||
487 | +! |
- # check teal_slices against datanames+ self$active_filters_ns(), |
|
246 | -79x | +||
488 | +! |
- out <- unlist(sapply(+ dataset_name |
|
247 | -79x | +||
489 | +
- filters, function(filter) {+ ) |
||
248 | -24x | +||
490 | +
- dataname <- shiny::isolate(filter$dataname)+ } else { |
||
249 | -24x | +||
491 | +! |
- if (!dataname %in% datanames) {+ remove_selector <- sprintf( |
|
250 | -3x | +||
492 | +! |
- sprintf(+ "#%s-active-%s-filter-%s_%s-remove", |
|
251 | -3x | +||
493 | +! |
- "- Filter '%s' refers to dataname not available in 'data':\n %s not in (%s)",+ self$active_filters_ns(), |
|
252 | -3x | +||
494 | +! |
- shiny::isolate(filter$id),+ dataset_name, |
|
253 | -3x | +||
495 | +! |
- dQuote(dataname, q = FALSE),+ dataset_name, |
|
254 | -3x | +||
496 | +! |
- toString(dQuote(datanames, q = FALSE))+ var_name |
|
255 | +497 |
) |
|
256 | +498 |
} |
|
257 | -+ | ||
499 | +! |
- }+ self$click( |
|
258 | -+ | ||
500 | +! |
- ))+ selector = remove_selector |
|
259 | +501 |
-
+ )+ |
+ |
502 | +! | +
+ invisible(self) |
|
260 | +503 |
-
+ }, |
|
261 | -79x | +||
504 | +
- if (length(out)) {+ #' @description |
||
262 | -3x | +||
505 | +
- paste(out, collapse = "\n")+ #' Set the active filter values for a variable of a dataset in the active filter variable panel. |
||
263 | +506 |
- } else {+ #' |
|
264 | -76x | +||
507 | +
- TRUE+ #' @param dataset_name (character) The name of the dataset to set the filter value for. |
||
265 | +508 |
- }+ #' @param var_name (character) The name of the variable to set the filter value for. |
|
266 | +509 |
- }+ #' @param input The value to set the filter to. |
|
267 | +510 |
-
+ #' @param ... Additional arguments to be passed to `shinytest2::AppDriver$set_inputs` |
|
268 | +511 |
- #' Function for validating the title parameter of `teal::init`+ #' |
|
269 | +512 |
- #'+ #' @return The `TealAppDriver` object invisibly. |
|
270 | +513 |
- #' Checks if the input of the title from `teal::init` will create a valid title and favicon tag.+ set_active_filter_selection = function(dataset_name, |
|
271 | +514 |
- #' @param shiny_tag (`shiny.tag`) Object to validate for a valid title.+ var_name, |
|
272 | +515 |
- #' @keywords internal+ input, |
|
273 | +516 |
- validate_app_title_tag <- function(shiny_tag) {+ ...) { |
|
274 | -7x | +||
517 | +! |
- checkmate::assert_class(shiny_tag, "shiny.tag")+ checkmate::check_string(dataset_name) |
|
275 | -7x | +||
518 | +! |
- checkmate::assert_true(shiny_tag$name == "head")+ checkmate::check_string(var_name) |
|
276 | -6x | +||
519 | +! |
- child_names <- vapply(shiny_tag$children, `[[`, character(1L), "name")+ checkmate::check_string(input) |
|
277 | -6x | +||
520 | +
- checkmate::assert_subset(c("title", "link"), child_names, .var.name = "child tags")+ |
||
278 | -4x | +||
521 | +! |
- rel_attr <- shiny_tag$children[[which(child_names == "link")]]$attribs$rel+ input_id_prefix <- sprintf( |
|
279 | -4x | +||
522 | +! |
- checkmate::assert_subset(+ "%s-filters-%s-filter-%s_%s-inputs", |
|
280 | -4x | +||
523 | +! |
- rel_attr,+ self$active_filters_ns(), |
|
281 | -4x | +||
524 | +! |
- c("icon", "shortcut icon"),+ dataset_name, |
|
282 | -4x | +||
525 | +! |
- .var.name = "Link tag's rel attribute",+ dataset_name, |
|
283 | -4x | +||
526 | +! |
- empty.ok = FALSE+ var_name |
|
284 | +527 |
- )+ ) |
|
285 | +528 |
- }+ |
|
286 | +529 |
-
+ # Find the type of filter (based on filter panel) |
|
287 | -+ | ||
530 | +! |
- #' Build app title with favicon+ supported_suffix <- c("selection", "selection_manual") |
|
288 | -+ | ||
531 | +! |
- #'+ slices_suffix <- supported_suffix[ |
|
289 | -+ | ||
532 | +! |
- #' A helper function to create the browser title along with a logo.+ match( |
|
290 | -+ | ||
533 | +! |
- #'+ TRUE, |
|
291 | -+ | ||
534 | +! |
- #' @param title (`character`) The browser title for the `teal` app.+ vapply( |
|
292 | -+ | ||
535 | +! |
- #' @param favicon (`character`) The path for the icon for the title.+ supported_suffix, |
|
293 | -+ | ||
536 | +! |
- #' The image/icon path can be remote or the static path accessible by `shiny`, like the `www/`+ function(suffix) { |
|
294 | -+ | ||
537 | +! |
- #'+ !is.null(self$get_html(sprintf("#%s-%s", input_id_prefix, suffix))) |
|
295 | +538 |
- #' @return A `shiny.tag` containing the element that adds the title and logo to the `shiny` app.+ },+ |
+ |
539 | +! | +
+ logical(1) |
|
296 | +540 |
- #' @export+ ) |
|
297 | +541 |
- build_app_title <- function(+ ) |
|
298 | +542 |
- title = "teal app",+ ] |
|
299 | +543 |
- favicon = "https://raw.githubusercontent.com/insightsengineering/hex-stickers/main/PNG/nest.png") {+ |
|
300 | -13x | +||
544 | +
- checkmate::assert_string(title, null.ok = TRUE)+ # Generate correct namespace |
||
301 | -13x | +||
545 | +! |
- checkmate::assert_string(favicon, null.ok = TRUE)+ slices_input_id <- sprintf( |
|
302 | -13x | +||
546 | +! |
- tags$head(+ "%s-filters-%s-filter-%s_%s-inputs-%s", |
|
303 | -13x | +||
547 | +! |
- tags$title(title),+ self$active_filters_ns(), |
|
304 | -13x | +||
548 | +! |
- tags$link(+ dataset_name, |
|
305 | -13x | +||
549 | +! |
- rel = "icon",+ dataset_name, |
|
306 | -13x | +||
550 | +! |
- href = favicon,+ var_name, |
|
307 | -13x | +||
551 | +! |
- sizes = "any"+ slices_suffix |
|
308 | +552 |
- )+ ) |
|
309 | +553 |
- )+ |
|
310 | -+ | ||
554 | +! |
- }+ if (identical(slices_suffix, "selection_manual")) {+ |
+ |
555 | +! | +
+ checkmate::assert_numeric(input, len = 2) |
|
311 | +556 | ||
312 | -+ | ||
557 | +! |
- #' Application ID+ dots <- rlang::list2(...) |
|
313 | -+ | ||
558 | +! |
- #'+ checkmate::assert_choice(dots$priority_, formals(self$set_inputs)[["priority_"]], null.ok = TRUE) |
|
314 | -+ | ||
559 | +! |
- #' Creates App ID used to match filter snapshots to application.+ checkmate::assert_flag(dots$wait_, null.ok = TRUE) |
|
315 | +560 |
- #'+ |
|
316 | -+ | ||
561 | +! |
- #' Calculate app ID that will be used to stamp filter state snapshots.+ self$run_js( |
|
317 | -+ | ||
562 | +! |
- #' App ID is a hash of the app's data and modules.+ sprintf( |
|
318 | -+ | ||
563 | +! |
- #' See "transferring snapshots" section in ?snapshot.+ "Shiny.setInputValue('%s:sw.numericRange', [%f, %f], {priority: '%s'})", |
|
319 | -+ | ||
564 | +! |
- #'+ slices_input_id, |
|
320 | -+ | ||
565 | +! |
- #' @param data (`teal_data` or `teal_data_module`) as accepted by `init`+ input[[1]], |
|
321 | -+ | ||
566 | +! |
- #' @param modules (`teal_modules`) object as accepted by `init`+ input[[2]], |
|
322 | -+ | ||
567 | +! |
- #'+ priority_ = ifelse(is.null(dots$priority_), "input", dots$priority_) |
|
323 | +568 |
- #' @return A single character string.+ ) |
|
324 | +569 |
- #'+ ) |
|
325 | +570 |
- #' @keywords internal+ |
|
326 | -+ | ||
571 | +! |
- create_app_id <- function(data, modules) {+ if (isTRUE(dots$wait_) || is.null(dots$wait_)) { |
|
327 | -21x | +||
572 | +! |
- checkmate::assert_multi_class(data, c("teal_data", "teal_data_module"))+ self$wait_for_idle( |
|
328 | -20x | +||
573 | +! |
- checkmate::assert_class(modules, "teal_modules")+ timeout = if (is.null(dots$timeout_)) rlang::missing_arg() else dots$timeout_ |
|
329 | +574 |
-
+ ) |
|
330 | -19x | +||
575 | +
- data <- if (inherits(data, "teal_data")) {+ } |
||
331 | -17x | +||
576 | +! |
- as.list(teal.code::get_env(data))+ } else if (identical(slices_suffix, "selection")) { |
|
332 | -19x | +||
577 | +! |
- } else if (inherits(data, "teal_data_module")) {+ self$set_input( |
|
333 | -2x | +||
578 | +! |
- deparse1(body(data$server))+ slices_input_id,+ |
+ |
579 | +! | +
+ input, |
|
334 | +580 |
- }+ ... |
|
335 | -19x | +||
581 | +
- modules <- lapply(modules, defunction)+ ) |
||
336 | +582 |
-
+ } else { |
|
337 | -19x | +||
583 | +! |
- rlang::hash(list(data = data, modules = modules))+ stop("Filter selection set not supported for this slice.") |
|
338 | +584 |
- }+ } |
|
339 | +585 | ||
340 | -+ | ||
586 | +! |
- #' Go through list and extract bodies of encountered functions as string, recursively.+ invisible(self) |
|
341 | +587 |
- #' @keywords internal+ }, |
|
342 | +588 |
- #' @noRd+ #' @description |
|
343 | +589 |
- defunction <- function(x) {- |
- |
344 | -229x | -
- if (is.list(x)) {+ #' Extract `html` attribute (found by a `selector`). |
|
345 | -67x | +||
590 | +
- lapply(x, defunction)+ #' |
||
346 | -162x | +||
591 | +
- } else if (is.function(x)) {+ #' @param selector (`character(1)`) specifying the selector to be used to get the content of a specific node. |
||
347 | -50x | +||
592 | +
- deparse1(body(x))+ #' @param attribute (`character(1)`) name of an attribute to retrieve from a node specified by `selector`. |
||
348 | +593 |
- } else {+ #' |
|
349 | -112x | +||
594 | +
- x+ #' @return The `character` vector. |
||
350 | +595 |
- }+ get_attr = function(selector, attribute) { |
|
351 | -+ | ||
596 | +! |
- }+ rvest::html_attr( |
|
352 | -+ | ||
597 | +! |
-
+ rvest::html_nodes(self$get_html_rvest("html"), selector), |
|
353 | -+ | ||
598 | +! |
- #' Get unique labels+ attribute |
|
354 | +599 |
- #'+ ) |
|
355 | +600 |
- #' Get unique labels for the modules to avoid namespace conflicts.+ }, |
|
356 | +601 |
- #'+ #' @description |
|
357 | +602 |
- #' @param labels (`character`) vector of labels+ #' Wrapper around `get_html` that passes the output directly to `rvest::read_html`. |
|
358 | +603 |
- #'+ #' |
|
359 | +604 |
- #' @return (`character`) vector of unique labels+ #' @param selector `(character(1))` passed to `get_html`. |
|
360 | +605 |
- #'+ #' |
|
361 | +606 |
- #' @keywords internal+ #' @return An XML document. |
|
362 | +607 |
- get_unique_labels <- function(labels) {+ get_html_rvest = function(selector) { |
|
363 | -215x | +||
608 | +! |
- make.unique(gsub("[^[:alnum:]]", "_", tolower(labels)), sep = "_")+ rvest::read_html(self$get_html(selector)) |
|
364 | +609 |
- }+ }, |
|
365 | +610 |
-
+ #' Wrapper around `get_url()` method that opens the app in the browser. |
|
366 | +611 |
- #' Remove ANSI escape sequences from a string+ #' |
|
367 | +612 |
- #' @noRd+ #' @return Nothing. Opens the underlying teal app in the browser. |
|
368 | +613 |
- strip_style <- function(string) {+ open_url = function() { |
|
369 | -2x | +||
614 | +! |
- checkmate::assert_string(string)+ browseURL(self$get_url()) |
|
370 | +615 | - - | -|
371 | -2x | -
- gsub(- |
- |
372 | -2x | -
- "(?:(?:\\x{001b}\\[)|\\x{009b})(?:(?:[0-9]{1,3})?(?:(?:;[0-9]{0,3})*)?[A-M|f-m])|\\x{001b}[A-M]",+ }, |
|
373 | +616 |
- "",- |
- |
374 | -2x | -
- string,- |
- |
375 | -2x | -
- perl = TRUE,+ #' @description |
|
376 | -2x | +||
617 | +
- useBytes = TRUE+ #' Waits until a specified input, output, or export value. |
||
377 | +618 |
- )+ #' This function serves as a wrapper around the `wait_for_value` method, |
|
378 | +619 |
- }+ #' providing a more flexible interface for waiting on different types of values within the active module namespace. |
|
379 | +620 |
-
+ #' @param input,output,export A name of an input, output, or export value. |
|
380 | +621 |
- #' @keywords internal+ #' Only one of these parameters may be used. |
|
381 | +622 |
- #' @noRd+ #' @param ... Must be empty. Allows for parameter expansion. |
|
382 | -4x | +||
623 | +
- pasten <- function(...) paste0(..., "\n")+ #' Parameter with additional value to passed in `wait_for_value`. |
||
383 | +624 |
-
+ wait_for_active_module_value = function(input = rlang::missing_arg(), |
|
384 | +625 |
- #' Convert character list to human readable html with commas and "and"+ output = rlang::missing_arg(), |
|
385 | +626 |
- #' @noRd+ export = rlang::missing_arg(), |
|
386 | +627 |
- paste_datanames_character <- function(x,+ ...) { |
|
387 | -+ | ||
628 | +! |
- tags = list(span = shiny::tags$span, code = shiny::tags$code),+ ns <- shiny::NS(self$active_module_ns()) |
|
388 | +629 |
- tagList = shiny::tagList) { # nolint: object_name.+ |
|
389 | +630 | ! |
- checkmate::assert_character(x)+ if (!rlang::is_missing(input) && checkmate::test_string(input, min.chars = 1)) input <- ns(input) |
390 | +631 | ! |
- do.call(+ if (!rlang::is_missing(output) && checkmate::test_string(output, min.chars = 1)) output <- ns(output) |
391 | +632 | ! |
- tagList,+ if (!rlang::is_missing(export) && checkmate::test_string(export, min.chars = 1)) export <- ns(export) |
392 | -! | +||
633 | +
- lapply(seq_along(x), function(.ix) {+ |
||
393 | +634 | ! |
- tagList(+ self$wait_for_value( |
394 | +635 | ! |
- tags$code(x[.ix]),+ input = input, |
395 | +636 | ! |
- if (.ix != length(x)) {+ output = output, |
396 | +637 | ! |
- tags$span(ifelse(.ix == length(x) - 1, " and ", ", "))+ export = export, |
397 | +638 |
- }+ ... |
|
398 | +639 |
) |
|
399 | +640 |
- })+ } |
|
400 | +641 |
- )+ ), |
|
401 | +642 |
- }+ # private members ---- |
|
402 | +643 |
-
+ private = list( |
|
403 | +644 |
- #' Build datanames error string for error message+ # private attributes ---- |
|
404 | +645 |
- #'+ data = NULL, |
|
405 | +646 |
- #' tags and tagList are overwritten in arguments allowing to create strings for+ modules = NULL, |
|
406 | +647 |
- #' logging purposes+ filter = teal_slices(), |
|
407 | +648 |
- #' @noRd+ ns = list( |
|
408 | +649 |
- build_datanames_error_message <- function(label = NULL,+ module = character(0), |
|
409 | +650 |
- datanames,+ filter_panel = character(0) |
|
410 | +651 |
- extra_datanames,+ ), |
|
411 | +652 |
- tags = list(span = shiny::tags$span, code = shiny::tags$code),+ # private methods ---- |
|
412 | +653 |
- tagList = shiny::tagList) { # nolint: object_name.+ set_active_ns = function() { |
|
413 | +654 | ! |
- tags$span(+ all_inputs <- self$get_values()$input |
414 | +655 | ! |
- tags$span(ifelse(length(extra_datanames) > 1, "Datasets", "Dataset")),+ active_tab_inputs <- all_inputs[grepl("-active_tab$", names(all_inputs))]+ |
+
656 | ++ | + | |
415 | +657 | ! |
- paste_datanames_character(extra_datanames, tags, tagList),+ tab_ns <- unlist(lapply(names(active_tab_inputs), function(name) { |
416 | +658 | ! |
- tags$span(+ gsub( |
417 | +659 | ! |
- paste0(+ pattern = "-active_tab$", |
418 | +660 | ! |
- ifelse(length(extra_datanames) > 1, "are missing", "is missing"),+ replacement = sprintf("-%s", active_tab_inputs[[name]]), |
419 | +661 | ! |
- ifelse(is.null(label), ".", sprintf(" for tab '%s'.", label))+ name |
420 | +662 |
- )+ ) |
|
421 | +663 |
- ),+ })) |
|
422 | +664 | ! |
- if (length(datanames) >= 1) {+ active_ns <- tab_ns[1] |
423 | +665 | ! |
- tagList(+ if (length(tab_ns) > 1) { |
424 | +666 | ! |
- tags$span(ifelse(length(datanames) > 1, "Datasets", "Dataset")),+ for (i in 2:length(tab_ns)) { |
425 | +667 | ! |
- tags$span("available in data:"),+ next_ns <- tab_ns[i] |
426 | +668 | ! |
- tagList(+ if (grepl(pattern = active_ns, next_ns)) { |
427 | +669 | ! |
- tags$span(+ active_ns <- next_ns+ |
+
670 | ++ |
+ }+ |
+ |
671 | ++ |
+ }+ |
+ |
672 | ++ |
+ } |
|
428 | +673 | ! |
- paste_datanames_character(datanames, tags, tagList),+ private$ns$module <- sprintf("%s-%s", active_ns, "module")+ |
+
674 | ++ | + | |
429 | +675 | ! |
- tags$span(".", .noWS = "outside"),+ components <- c("filter_panel", "data_summary") |
430 | +676 | ! |
- .noWS = c("outside")+ for (component in components) { |
431 | +677 |
- )+ if ( |
|
432 | -+ | ||
678 | +! |
- )+ !is.null(self$get_html(sprintf("#%s-%s-panel", active_ns, component))) || |
|
433 | -+ | ||
679 | +! |
- )+ !is.null(self$get_html(sprintf("#%s-%s-table", active_ns, component))) |
|
434 | +680 |
- } else {+ ) { |
|
435 | +681 | ! |
- tags$span("No datasets are available in data.")+ private$ns[[component]] <- sprintf("%s-%s", active_ns, component) |
436 | +682 |
- }+ } else {+ |
+ |
683 | +! | +
+ private$ns[[component]] <- sprintf("%s-module_%s", active_ns, component) |
|
437 | +684 |
- )+ } |
|
438 | +685 |
- }+ } |
|
439 | +686 |
-
+ }, |
|
440 | +687 |
- #' Smart `rbind`+ # @description |
|
441 | +688 |
- #'+ # Get the active filter values from the active filter selection of dataset from the filter panel. |
|
442 | +689 |
- #' Combine `data.frame` objects which have different columns+ # |
|
443 | +690 |
- #'+ # @param dataset_name (character) The name of the dataset to get the filter values from. |
|
444 | +691 |
- #' @param ... (`data.frame`)+ # @param var_name (character) The name of the variable to get the filter values from. |
|
445 | +692 |
- #' @keywords internal+ # |
|
446 | +693 |
- .smart_rbind <- function(...) {+ # @return The value of the active filter selection. |
|
447 | -82x | +||
694 | +
- dots <- list(...)+ get_active_filter_selection = function(dataset_name, var_name) { |
||
448 | -82x | +||
695 | +! |
- checkmate::assert_list(dots, "data.frame", .var.name = "...")+ checkmate::check_string(dataset_name) |
|
449 | -82x | +||
696 | +! |
- Reduce(+ checkmate::check_string(var_name) |
|
450 | -82x | +||
697 | +! |
- x = dots,+ input_id_prefix <- sprintf( |
|
451 | -82x | +||
698 | +! |
- function(x, y) {+ "%s-filters-%s-filter-%s_%s-inputs", |
|
452 | -69x | +||
699 | +! |
- all_columns <- union(colnames(x), colnames(y))+ self$active_filters_ns(), |
|
453 | -69x | +||
700 | +! |
- x[setdiff(all_columns, colnames(x))] <- NA+ dataset_name, |
|
454 | -69x | +||
701 | +! |
- y[setdiff(all_columns, colnames(y))] <- NA+ dataset_name, |
|
455 | -69x | +||
702 | +! |
- rbind(x, y)+ var_name |
|
456 | +703 |
- }+ ) |
|
457 | +704 |
- )+ |
|
458 | +705 |
- }+ # Find the type of filter (categorical or range) |
1 | -+ | ||
706 | +! |
- #' Manage multiple `FilteredData` objects+ supported_suffix <- c("selection", "selection_manual") |
|
2 | -+ | ||
707 | +! |
- #'+ for (suffix in supported_suffix) { |
|
3 | -+ | ||
708 | +! |
- #' @description+ if (!is.null(self$get_html(sprintf("#%s-%s", input_id_prefix, suffix)))) { |
|
4 | -+ | ||
709 | +! |
- #' Oversee filter states across the entire application.+ return(self$get_value(input = sprintf("%s-%s", input_id_prefix, suffix))) |
|
5 | +710 |
- #'+ } |
|
6 | +711 |
- #' @section Slices global:+ } |
|
7 | +712 |
- #' The key role in maintaining the module-specific filter states is played by the `.slicesGlobal`+ |
|
8 | -+ | ||
713 | +! |
- #' object. It is a reference class that holds the following fields:+ NULL # If there are not any supported filters |
|
9 | +714 |
- #' - `all_slices` (`reactiveVal`) - reactive value containing all filters registered in an app.+ }, |
|
10 | +715 |
- #' - `module_slices_api` (`reactiveValues`) - reactive field containing references to each modules'+ # @description |
|
11 | +716 |
- #' `FilteredData` object methods. At this moment it is used only in `srv_filter_manager` to display+ # Check if the page is stable without any `DOM` updates in the body of the app. |
|
12 | +717 |
- #' the filter states in a table combining informations from `all_slices` and from+ # This is achieved by blocing the R process by sleeping until the page is unchanged till the `stability_period`. |
|
13 | +718 |
- #' `FilteredData$get_available_teal_slices()`.+ # @param stability_period (`numeric(1)`) The time in milliseconds to wait till the page to be stable. |
|
14 | +719 |
- #'+ # @param check_interval (`numeric(1)`) The time in milliseconds to check for changes in the page. |
|
15 | +720 |
- #' During a session only new filters are added to `all_slices` unless [`module_snapshot_manager`] is+ # The stability check is reset when a change is detected in the page after sleeping for check_interval. |
|
16 | +721 |
- #' used to restore previous state. Filters from `all_slices` can be activated or deactivated in a+ wait_for_page_stability = function(stability_period = 2000, check_interval = 200) { |
|
17 | -+ | ||
722 | +! |
- #' module which is linked (both ways) by `attr(, "mapping")` so that:+ previous_content <- self$get_html("body") |
|
18 | -+ | ||
723 | +! |
- #' - If module's filter is added or removed in its `FilteredData` object, this information is passed+ end_time <- Sys.time() + (stability_period / 1000) |
|
19 | +724 |
- #' to `SlicesGlobal` which updates `attr(, "mapping")` accordingly.+ |
|
20 | -+ | ||
725 | +! |
- #' - When mapping changes in a `SlicesGlobal`, filters are set or removed from module's+ repeat { |
|
21 | -+ | ||
726 | +! |
- #' `FilteredData`.+ Sys.sleep(check_interval / 1000) |
|
22 | -+ | ||
727 | +! |
- #'+ current_content <- self$get_html("body") |
|
23 | +728 |
- #' @section Filter manager:+ |
|
24 | -+ | ||
729 | +! |
- #' Filter-manager is split into two parts:+ if (!identical(previous_content, current_content)) { |
|
25 | -+ | ||
730 | +! |
- #' 1. `ui/srv_filter_manager_panel` - Called once for the whole app. This module observes changes in+ previous_content <- current_content |
|
26 | -+ | ||
731 | +! |
- #' the filters in `slices_global` and displays them in a table utilizing information from `mapping`:+ end_time <- Sys.time() + (stability_period / 1000) |
|
27 | -+ | ||
732 | +! |
- #' - (`TRUE`) - filter is active in the module+ } else if (Sys.time() >= end_time) { |
|
28 | -+ | ||
733 | +! |
- #' - (`FALSE`) - filter is inactive in the module+ break |
|
29 | +734 |
- #' - (`NA`) - filter is not available in the module+ } |
|
30 | +735 |
- #' 2. `ui/srv_module_filter_manager` - Called once for each `teal_module`. Handling filter states+ } |
|
31 | +736 |
- #' for of single module and keeping module `FilteredData` consistent with `slices_global`, so that+ }+ |
+ |
737 | ++ |
+ )+ |
+ |
738 | ++ |
+ )+ |
+
1 | ++ |
+ setOldClass("teal_module")+ |
+ |
2 | ++ |
+ setOldClass("teal_modules")+ |
+ |
3 | ++ | + + | +|
4 | ++ |
+ #' Create `teal_module` and `teal_modules` objects+ |
+ |
5 | ++ |
+ #'+ |
+ |
6 | ++ |
+ #' @description+ |
+ |
7 | ++ |
+ #' `r lifecycle::badge("stable")`+ |
+ |
8 | ++ |
+ #' Create a nested tab structure to embed modules in a `teal` application.+ |
+ |
9 | ++ |
+ #'+ |
+ |
10 | ++ |
+ #' @details+ |
+ |
11 | ++ |
+ #' `module()` creates an instance of a `teal_module` that can be placed in a `teal` application.+ |
+ |
12 | ++ |
+ #' `modules()` shapes the structure of a the application by organizing `teal_module` within the navigation panel.+ |
+ |
13 | ++ |
+ #' It wraps `teal_module` and `teal_modules` objects in a `teal_modules` object,+ |
+ |
14 | ++ |
+ #' which results in a nested structure corresponding to the nested tabs in the final application.+ |
+ |
15 | ++ |
+ #'+ |
+ |
16 | ++ |
+ #' Note that for `modules()` `label` comes after `...`, so it must be passed as a named argument,+ |
+ |
17 | ++ |
+ #' otherwise it will be captured by `...`.+ |
+ |
18 | ++ |
+ #'+ |
+ |
19 | ++ |
+ #' The labels `"global_filters"` and `"Report previewer"` are reserved+ |
+ |
20 | ++ |
+ #' because they are used by the `mapping` argument of [teal_slices()]+ |
+ |
21 | ++ |
+ #' and the report previewer module [reporter_previewer_module()], respectively.+ |
+ |
22 | ++ |
+ #'+ |
+ |
23 | ++ |
+ #' # Restricting datasets used by `teal_module`:+ |
+ |
24 | ++ |
+ #' 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 | ++ |
+ #'+ |
+ |
27 | ++ |
+ #' When `datanames` is set to `"all"`, all datasets in the data object are treated as relevant.+ |
+ |
28 | ++ |
+ #' However, this may include unnecessary datasets, such as:+ |
+ |
29 | ++ |
+ #' - Proxy variables for column modifications+ |
+ |
30 | ++ |
+ #' - Temporary datasets used to create final versions+ |
+ |
31 | ++ |
+ #' - Connection objects |
|
32 |
- #' local filters are always reflected in the `slices_global` and its mapping and vice versa.+ #' |
||
33 |
- #'+ #' To exclude irrelevant datasets, use the [set_datanames()] function to change `datanames` from |
||
34 |
- #'+ #' `"all"` to specific names. Trying to modify non-`"all"` values with [set_datanames()] will result |
||
35 |
- #' @param id (`character(1)`)+ #' in a warning. Datasets with names starting with . are ignored globally unless explicitly listed |
||
36 |
- #' `shiny` module instance id.+ #' in `datanames`. |
||
38 |
- #' @param slices_global (`reactiveVal`)+ #' # `datanames` with `transformers` |
||
39 |
- #' containing `teal_slices`.+ #' When transformers are specified, their `datanames` are added to the module’s `datanames`, which |
||
40 |
- #'+ #' changes the behavior as follows: |
||
41 |
- #' @param module_fd (`FilteredData`)+ #' - If `module(datanames)` is `NULL` and the `transformers` have defined `datanames`, the sidebar |
||
42 |
- #' Object containing the data to be filtered in a single `teal` module.+ #' will appear showing the `transformers`' datasets, instead of being hidden. |
||
43 |
- #'+ #' - If `module(datanames)` is set to specific values and any `transformer` has `datanames = "all"`, |
||
44 |
- #' @return+ #' the module may receive extra datasets that could be unnecessary |
||
45 |
- #' Module returns a `slices_global` (`reactiveVal`) containing a `teal_slices` object with mapping.+ #' |
||
46 |
- #'+ #' @param label (`character(1)`) Label shown in the navigation item for the module or module group. |
||
47 |
- #' @encoding UTF-8+ #' For `modules()` defaults to `"root"`. See `Details`. |
||
48 |
- #'+ #' @param server (`function`) `shiny` module with following arguments: |
||
49 |
- #' @name module_filter_manager+ #' - `id` - `teal` will set proper `shiny` namespace for this module (see [shiny::moduleServer()]). |
||
50 |
- #' @rdname module_filter_manager+ #' - `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 |
- NULL+ #' [shiny::moduleServer()] instead which doesn't require these arguments. |
||
53 |
-
+ #' - `data` (optional) When provided, the module will be called with `teal_data` object (i.e. a list of |
||
54 |
- #' @rdname module_filter_manager+ #' reactive (filtered) data specified in the `filters` argument) as the value of this argument. |
||
55 |
- ui_filter_manager_panel <- function(id) {+ #' - `datasets` (optional) When provided, the module will be called with `FilteredData` object as the |
||
56 | -! | +
- ns <- NS(id)+ #' value of this argument. (See [`teal.slice::FilteredData`]). |
|
57 | -! | +
- tags$button(+ #' - `reporter` (optional) When provided, the module will be called with `Reporter` object as the value |
|
58 | -! | +
- id = ns("show_filter_manager"),+ #' of this argument. (See [`teal.reporter::Reporter`]). |
|
59 | -! | +
- class = "btn action-button wunder_bar_button",+ #' - `filter_panel_api` (optional) When provided, the module will be called with `FilterPanelAPI` object |
|
60 | -! | +
- title = "View filter mapping",+ #' as the value of this argument. (See [`teal.slice::FilterPanelAPI`]). |
|
61 | -! | +
- suppressMessages(icon("fas fa-grip"))+ #' - `...` (optional) When provided, `server_args` elements will be passed to the module named argument |
|
62 |
- )+ #' 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 |
- #' @rdname module_filter_manager+ #' - `...` (optional) When provided, `ui_args` elements will be passed to the module named argument |
||
66 |
- #' @keywords internal+ #' or to the `...`. |
||
67 |
- srv_filter_manager_panel <- function(id, slices_global) {+ #' @param filters (`character`) Deprecated. Use `datanames` instead. |
||
68 | -82x | +
- checkmate::assert_string(id)+ #' @param datanames (`character`) Names of the datasets relevant to the item. |
|
69 | -82x | +
- checkmate::assert_class(slices_global, ".slicesGlobal")+ #' There are 2 reserved values that have specific behaviors: |
|
70 | -82x | +
- moduleServer(id, function(input, output, session) {+ #' - The keyword `"all"` includes all datasets available in the data passed to the teal application. |
|
71 | -82x | +
- setBookmarkExclude(c("show_filter_manager"))+ #' - `NULL` hides the sidebar panel completely. |
|
72 | -82x | +
- observeEvent(input$show_filter_manager, {+ #' - If `transformers` are specified, their `datanames` are automatically added to this `datanames` |
|
73 | -! | +
- logger::log_debug("srv_filter_manager_panel@1 show_filter_manager button has been clicked.")+ #' argument. |
|
74 | -! | +
- showModal(+ #' @param server_args (named `list`) with additional arguments passed on to the server function. |
|
75 | -! | +
- modalDialog(+ #' @param ui_args (named `list`) with additional arguments passed on to the UI function. |
|
76 | -! | +
- ui_filter_manager(session$ns("filter_manager")),+ #' @param x (`teal_module` or `teal_modules`) Object to format/print. |
|
77 | -! | +
- class = "filter_manager_modal",+ #' @param indent (`integer(1)`) Indention level; each nested element is indented one level more. |
|
78 | -! | +
- size = "l",+ #' @param transformers (`list` of `teal_data_module`) that will be applied to transform the data. |
|
79 | -! | +
- footer = NULL,+ #' Each transform module UI will appear in the `teal`'s sidebar panel. |
|
80 | -! | +
- easyClose = TRUE+ #' Transformers' `datanames` are added to the `datanames`. See [teal_transform_module()]. |
|
81 |
- )+ #' |
||
82 |
- )+ #' @param ... |
||
83 |
- })+ #' - For `modules()`: (`teal_module` or `teal_modules`) Objects to wrap into a tab. |
||
84 | -82x | +
- srv_filter_manager("filter_manager", slices_global = slices_global)+ #' - For `format()` and `print()`: Arguments passed to other methods. |
|
85 |
- })+ #' |
||
86 |
- }+ #' @return |
||
87 |
-
+ #' `module()` returns an object of class `teal_module`. |
||
88 |
- #' @rdname module_filter_manager+ #' |
||
89 |
- ui_filter_manager <- function(id) {+ #' `modules()` returns a `teal_modules` object which contains following fields: |
||
90 | -! | +
- ns <- NS(id)+ #' - `label`: taken from the `label` argument. |
|
91 | -! | +
- actionButton(ns("filter_manager"), NULL, icon = icon("fas fa-filter"))+ #' - `children`: a list containing objects passed in `...`. List elements are named after |
|
92 | -! | +
- tags$div(+ #' their `label` attribute converted to a valid `shiny` id. |
|
93 | -! | +
- class = "filter_manager_content",+ #' |
|
94 | -! | +
- tableOutput(ns("slices_table"))+ #' @name teal_modules |
|
95 |
- )+ #' @aliases teal_module |
||
96 |
- }+ #' |
||
97 |
-
+ #' @examples |
||
98 |
- #' @rdname module_filter_manager+ #' library(shiny) |
||
99 |
- srv_filter_manager <- function(id, slices_global) {+ #' |
||
100 | -82x | +
- checkmate::assert_string(id)+ #' module_1 <- module( |
|
101 | -82x | +
- checkmate::assert_class(slices_global, ".slicesGlobal")+ #' label = "a module", |
|
102 |
-
+ #' server = function(id, data) { |
||
103 | -82x | +
- moduleServer(id, function(input, output, session) {+ #' moduleServer( |
|
104 | -82x | +
- logger::log_debug("filter_manager_srv initializing.")+ #' id, |
|
105 |
-
+ #' module = function(input, output, session) { |
||
106 |
- # Bookmark slices global with mapping.+ #' output$data <- renderDataTable(data()[["iris"]]) |
||
107 | -82x | +
- session$onBookmark(function(state) {+ #' } |
|
108 | -! | +
- logger::log_debug("filter_manager_srv@onBookmark: storing filter state")+ #' ) |
|
109 | -! | +
- state$values$filter_state_on_bookmark <- as.list(+ #' }, |
|
110 | -! | +
- slices_global$all_slices(),+ #' ui = function(id) { |
|
111 | -! | +
- recursive = TRUE+ #' ns <- NS(id) |
|
112 |
- )+ #' tagList(dataTableOutput(ns("data"))) |
||
113 |
- })+ #' }, |
||
114 |
-
+ #' datanames = "all" |
||
115 | -82x | +
- bookmarked_slices <- restoreValue(session$ns("filter_state_on_bookmark"), NULL)+ #' ) |
|
116 | -82x | +
- if (!is.null(bookmarked_slices)) {+ #' |
|
117 | -! | +
- logger::log_debug("filter_manager_srv: restoring filter state from bookmark.")+ #' module_2 <- module( |
|
118 | -! | +
- slices_global$slices_set(bookmarked_slices)+ #' label = "another module", |
|
119 |
- }+ #' server = function(id) { |
||
120 |
-
+ #' moduleServer( |
||
121 | -82x | +
- mapping_table <- reactive({+ #' id, |
|
122 |
- # We want this to be reactive on slices_global$all_slices() only as get_available_teal_slices()+ #' module = function(input, output, session) { |
||
123 |
- # is dependent on slices_global$all_slices().+ #' output$text <- renderText("Another Module") |
||
124 | -91x | +
- module_labels <- setdiff(+ #' } |
|
125 | -91x | +
- names(attr(slices_global$all_slices(), "mapping")),+ #' ) |
|
126 | -91x | +
- "Report previewer"+ #' }, |
|
127 |
- )+ #' ui = function(id) { |
||
128 | -91x | +
- isolate({+ #' ns <- NS(id) |
|
129 | -91x | +
- mm <- as.data.frame(+ #' tagList(textOutput(ns("text"))) |
|
130 | -91x | +
- sapply(+ #' }, |
|
131 | -91x | +
- module_labels,+ #' datanames = NULL |
|
132 | -91x | +
- simplify = FALSE,+ #' ) |
|
133 | -91x | +
- function(module_label) {+ #' |
|
134 | -104x | +
- available_slices <- slices_global$module_slices_api[[module_label]]$get_available_teal_slices()+ #' modules <- modules( |
|
135 | -96x | +
- global_ids <- sapply(slices_global$all_slices(), `[[`, "id", simplify = FALSE)+ #' label = "modules", |
|
136 | -96x | +
- module_ids <- sapply(slices_global$slices_get(module_label), `[[`, "id", simplify = FALSE)+ #' modules( |
|
137 | -96x | +
- allowed_ids <- vapply(available_slices, `[[`, character(1L), "id")+ #' label = "nested modules", |
|
138 | -96x | +
- active_ids <- global_ids %in% module_ids+ #' module_1 |
|
139 | -96x | +
- setNames(nm = global_ids, ifelse(global_ids %in% allowed_ids, active_ids, NA))+ #' ), |
|
140 |
- }+ #' module_2 |
||
141 |
- ),+ #' ) |
||
142 | -91x | +
- check.names = FALSE+ #' |
|
143 |
- )+ #' app <- init( |
||
144 | -83x | +
- colnames(mm)[colnames(mm) == "global_filters"] <- "Global filters"+ #' data = teal_data(iris = iris), |
|
145 |
-
+ #' modules = modules |
||
146 | -83x | +
- mm+ #' ) |
|
147 |
- })+ #' |
||
148 |
- })+ #' if (interactive()) { |
||
149 |
-
+ #' shinyApp(app$ui, app$server) |
||
150 | -82x | +
- output$slices_table <- renderTable(+ #' } |
|
151 | -82x | +
- expr = {+ #' @rdname teal_modules |
|
152 | -91x | +
- logger::log_debug("filter_manager_srv@1 rendering slices_table.")+ #' @export |
|
153 | -91x | +
- mm <- mapping_table()+ #' |
|
154 |
-
+ module <- function(label = "module", |
||
155 |
- # Display logical values as UTF characters.+ server = function(id, data, ...) moduleServer(id, function(input, output, session) NULL), |
||
156 | -83x | +
- mm[] <- lapply(mm, ifelse, yes = intToUtf8(9989), no = intToUtf8(10060))+ ui = function(id, ...) tags$p(paste0("This module has no UI (id: ", id, " )")), |
|
157 | -83x | +
- mm[] <- lapply(mm, function(x) ifelse(is.na(x), intToUtf8(128306), x))+ filters, |
|
158 |
-
+ datanames = "all", |
||
159 |
- # Display placeholder if no filters defined.+ server_args = NULL, |
||
160 | -83x | +
- if (nrow(mm) == 0L) {+ ui_args = NULL, |
|
161 | -59x | +
- mm <- data.frame(`Filter manager` = "No filters specified.", check.names = FALSE)+ transformers = list()) { |
|
162 | -59x | +
- rownames(mm) <- ""+ # argument checking (independent) |
|
163 |
- }+ ## `label` |
||
164 | -83x | +213x |
- mm+ checkmate::assert_string(label) |
165 | -+ | 210x |
- },+ if (label == "global_filters") { |
166 | -82x | +1x |
- rownames = TRUE+ stop( |
167 | -+ | 1x |
- )+ sprintf("module(label = \"%s\", ...\n ", label), |
168 | -+ | 1x |
-
+ "Label 'global_filters' is reserved in teal. Please change to something else.", |
169 | -82x | +1x |
- mapping_table # for testing purpose+ call. = FALSE |
170 |
- })+ ) |
||
171 |
- }+ } |
||
172 | -+ | 209x |
-
+ if (label == "Report previewer") { |
173 | -+ | ! |
- #' @rdname module_filter_manager+ stop( |
174 | -+ | ! |
- srv_module_filter_manager <- function(id, module_fd, slices_global) {+ sprintf("module(label = \"%s\", ...\n ", label), |
175 | -107x | +! |
- checkmate::assert_string(id)+ "Label 'Report previewer' is reserved in teal. Please change to something else.", |
176 | -107x | +! |
- assert_reactive(module_fd)+ call. = FALSE |
177 | -107x | +
- checkmate::assert_class(slices_global, ".slicesGlobal")+ ) |
|
178 |
-
+ } |
||
179 | -107x | +
- moduleServer(id, function(input, output, session) {+ |
|
180 | -107x | +
- logger::log_debug("srv_module_filter_manager initializing for module: { id }.")+ ## server |
|
181 | -+ | 209x |
- # Track filter global and local states.+ checkmate::assert_function(server) |
182 | -107x | +209x |
- slices_global_module <- reactive({+ server_formals <- names(formals(server)) |
183 | -193x | +209x |
- slices_global$slices_get(module_label = id)+ if (!( |
184 | -+ | 209x |
- })+ "id" %in% server_formals || |
185 | -107x | +209x |
- slices_module <- reactive(req(module_fd())$get_filter_state())+ all(c("input", "output", "session") %in% server_formals) |
186 |
-
+ )) { |
||
187 | -107x | +2x |
- module_fd_previous <- reactiveVal(NULL)+ stop( |
188 | -+ | 2x |
-
+ "\nmodule() `server` argument requires a function with following arguments:", |
189 | -+ | 2x |
- # Set (reactively) available filters for the module.+ "\n - id - `teal` will set proper `shiny` namespace for this module.", |
190 | -107x | +2x |
- obs1 <- observeEvent(module_fd(), priority = 1, {+ "\n - input, output, session (not recommended) - then `shiny::callModule` will be used to call a module.", |
191 | -88x | +2x |
- logger::log_debug("srv_module_filter_manager@1 setting initial slices for module: { id }.")+ "\n\nFollowing arguments can be used optionaly:", |
192 | -+ | 2x |
- # Filters relevant for the module in module-specific app.+ "\n - `data` - module will receive list of reactive (filtered) data specified in the `filters` argument", |
193 | -88x | +2x |
- slices <- slices_global_module()+ "\n - `datasets` - module will receive `FilteredData`. See `help(teal.slice::FilteredData)`", |
194 | -+ | 2x |
-
+ "\n - `reporter` - module will receive `Reporter`. See `help(teal.reporter::Reporter)`", |
195 | -+ | 2x |
- # Clean up previous filter states and refresh cache of previous module_fd with current+ "\n - `filter_panel_api` - module will receive `FilterPanelAPI`. (See [teal.slice::FilterPanelAPI]).", |
196 | -3x | +2x |
- if (!is.null(module_fd_previous())) module_fd_previous()$finalize()+ "\n - `...` server_args elements will be passed to the module named argument or to the `...`" |
197 | -88x | +
- module_fd_previous(module_fd())+ ) |
|
198 |
-
+ } |
||
199 | -+ | 207x |
- # Setting filter states from slices_global:+ if ("datasets" %in% server_formals) { |
200 | -+ | 2x |
- # 1. when app initializes slices_global set to initial filters (specified by app developer)+ warning( |
201 | -+ | 2x |
- # 2. when data reinitializes slices_global reflects latest filter states+ sprintf("Called from module(label = \"%s\", ...)\n ", label), |
202 | -+ | 2x |
-
+ "`datasets` argument in the server is deprecated and will be removed in the next release. ", |
203 | -88x | +2x |
- module_fd()$set_filter_state(slices)+ "Please use `data` instead.", |
204 | -+ | 2x |
-
+ call. = FALSE |
205 |
- # irrelevant filters are discarded in FilteredData$set_available_teal_slices+ ) |
||
206 |
- # it means we don't need to subset slices_global$all_slices() from filters refering to irrelevant datasets+ } |
||
207 | -88x | +
- module_fd()$set_available_teal_slices(slices_global$all_slices)+ |
|
209 |
- # this needed in filter_manager_srv+ ## UI |
||
210 | -88x | +207x |
- slices_global$module_slices_api_set(+ checkmate::assert_function(ui) |
211 | -88x | +207x |
- id,+ ui_formals <- names(formals(ui)) |
212 | -88x | +207x |
- list(+ if (!"id" %in% ui_formals) { |
213 | -88x | +1x |
- get_available_teal_slices = module_fd()$get_available_teal_slices(),+ stop( |
214 | -88x | +1x |
- set_filter_state = module_fd()$set_filter_state, # for testing purpose+ "\nmodule() `ui` argument requires a function with following arguments:", |
215 | -88x | +1x |
- get_filter_state = module_fd()$get_filter_state # for testing purpose+ "\n - id - `teal` will set proper `shiny` namespace for this module.", |
216 | -+ | 1x |
- )+ "\n\nFollowing arguments can be used optionally:", |
217 | -+ | 1x |
- )+ "\n - `...` ui_args elements will be passed to the module argument of the same name or to the `...`" |
218 |
- })+ ) |
||
219 |
-
+ } |
||
220 | -+ | 206x |
- # Update global state and mapping matrix when module filters change.+ if (any(c("data", "datasets") %in% ui_formals)) { |
221 | -107x | +2x |
- obs2 <- observeEvent(slices_module(), priority = 0, {+ stop( |
222 | -110x | +2x |
- this_slices <- slices_module()+ sprintf("Called from module(label = \"%s\", ...)\n ", label), |
223 | -110x | +2x |
- slices_global$slices_append(this_slices) # append new slices to the all_slices list+ "UI with `data` or `datasets` argument is no longer accepted.\n ", |
224 | -110x | +2x |
- mapping_elem <- setNames(nm = id, list(vapply(this_slices, `[[`, character(1L), "id")))+ "If some UI inputs depend on data, please move the logic to your server instead.\n ", |
225 | -110x | +2x |
- slices_global$slices_active(mapping_elem)+ "Possible solutions are renderUI() or updateXyzInput() functions." |
226 |
- })+ ) |
||
227 |
-
+ } |
||
228 | -107x | +
- obs3 <- observeEvent(slices_global_module(), {+ |
|
229 | -130x | +
- global_vs_module <- setdiff_teal_slices(slices_global_module(), slices_module())+ |
|
230 | -130x | +
- module_vs_global <- setdiff_teal_slices(slices_module(), slices_global_module())+ ## `filters` |
|
231 | -121x | +204x |
- if (length(global_vs_module) || length(module_vs_global)) {+ if (!missing(filters)) { |
232 | -+ | ! |
- # Comment: (Nota Bene) Normally new filters for a module are added through module-filter-panel, and slices+ datanames <- filters |
233 | -+ | ! |
- # global are updated automatically so slices_module -> slices_global_module are equal.+ msg <- |
234 | -+ | ! |
- # this if is valid only when a change is made on the global level so the change needs to be propagated down+ "The `filters` argument is deprecated and will be removed in the next release. Please use `datanames` instead." |
235 | -+ | ! |
- # to the module (for example through snapshot manager). If it happens both slices are different+ warning(msg) |
236 | -13x | +
- logger::log_debug("srv_module_filter_manager@3 (N.B.) global state has changed for a module:{ id }.")+ } |
|
237 | -13x | +
- module_fd()$clear_filter_states()+ |
|
238 | -13x | +
- module_fd()$set_filter_state(slices_global_module())+ ## `datanames` (also including deprecated `filters`) |
|
239 |
- }+ # please note a race condition between datanames set when filters is not missing and data arg in server function |
||
240 | -+ | 204x |
- })+ if (!is.element("data", server_formals) && !is.null(datanames)) { |
241 | -+ | 12x |
-
+ message(sprintf("module \"%s\" server function takes no data so \"datanames\" will be ignored", label)) |
242 | -107x | +12x |
- slices_module # returned for testing purpose+ datanames <- NULL |
243 |
- })+ } |
||
244 | -+ | 204x |
- }+ checkmate::assert_character(datanames, min.len = 1, null.ok = TRUE, any.missing = FALSE) |
246 |
- #' @importFrom shiny reactiveVal reactiveValues+ ## `server_args` |
||
247 | -+ | 203x |
- methods::setOldClass("reactiveVal")+ checkmate::assert_list(server_args, null.ok = TRUE, names = "named") |
248 | -+ | 201x |
- methods::setOldClass("reactivevalues")+ srv_extra_args <- setdiff(names(server_args), server_formals) |
249 | -+ | 201x |
-
+ if (length(srv_extra_args) > 0 && !"..." %in% server_formals) { |
250 | -+ | 1x |
- #' @importFrom methods new+ stop( |
251 | -+ | 1x |
- #' @rdname module_filter_manager+ "\nFollowing `server_args` elements have no equivalent in the formals of the server:\n", |
252 | -+ | 1x |
- .slicesGlobal <- methods::setRefClass(".slicesGlobal", # nolint: object_name.+ paste(paste(" -", srv_extra_args), collapse = "\n"), |
253 | -+ | 1x |
- fields = list(+ "\n\nUpdate the server arguments by including above or add `...`" |
254 |
- all_slices = "reactiveVal",+ ) |
||
255 |
- module_slices_api = "reactivevalues"+ } |
||
256 |
- ),+ |
||
257 |
- methods = list(+ ## `ui_args` |
||
258 | -+ | 200x |
- initialize = function(slices = teal_slices(), module_labels) {+ checkmate::assert_list(ui_args, null.ok = TRUE, names = "named") |
259 | -82x | +198x |
- shiny::isolate({+ ui_extra_args <- setdiff(names(ui_args), ui_formals) |
260 | -82x | +198x |
- checkmate::assert_class(slices, "teal_slices")+ if (length(ui_extra_args) > 0 && !"..." %in% ui_formals) { |
261 | -+ | 1x |
- # needed on init to not mix "global_filters" with module-specific-slots+ stop( |
262 | -82x | +1x |
- if (isTRUE(attr(slices, "module_specific"))) {+ "\nFollowing `ui_args` elements have no equivalent in the formals of UI:\n", |
263 | -11x | +1x |
- old_mapping <- attr(slices, "mapping")+ paste(paste(" -", ui_extra_args), collapse = "\n"), |
264 | -11x | +1x |
- new_mapping <- sapply(module_labels, simplify = FALSE, function(module_label) {+ "\n\nUpdate the UI arguments by including above or add `...`" |
265 | -20x | +
- unique(unlist(old_mapping[c(module_label, "global_filters")]))+ ) |
|
266 |
- })+ } |
||
267 | -11x | +
- attr(slices, "mapping") <- new_mapping+ |
|
268 |
- }+ ## `transformers` |
||
269 | -82x | +197x |
- .self$all_slices <<- shiny::reactiveVal(slices)+ if (inherits(transformers, "teal_transform_module")) { |
270 | -82x | +1x |
- .self$module_slices_api <<- shiny::reactiveValues()+ transformers <- list(transformers) |
271 | -82x | +
- .self$slices_append(slices)+ } |
|
272 | -82x | +197x |
- .self$slices_active(attr(slices, "mapping"))+ checkmate::assert_list(transformers, types = "teal_transform_module") |
273 | -82x | +197x |
- invisible(.self)+ transformer_datanames <- unlist(lapply(transformers, attr, "datanames")) |
274 | -+ | 197x |
- })+ combined_datanames <- if (identical(datanames, "all")) { |
275 | -+ | 144x |
- },+ "all" |
276 |
- is_module_specific = function() {+ } else { |
||
277 | -283x | +53x |
- isTRUE(attr(.self$all_slices(), "module_specific"))+ union(datanames, transformer_datanames) |
278 |
- },+ } |
||
279 |
- module_slices_api_set = function(module_label, functions_list) {+ |
||
280 | -88x | +197x |
- shiny::isolate({+ structure( |
281 | -88x | +197x |
- if (!.self$is_module_specific()) {+ list( |
282 | -72x | +197x |
- module_label <- "global_filters"+ label = label, |
283 | -+ | 197x |
- }+ server = server, |
284 | -88x | +197x |
- if (!identical(.self$module_slices_api[[module_label]], functions_list)) {+ ui = ui, |
285 | -88x | +197x |
- .self$module_slices_api[[module_label]] <- functions_list+ datanames = combined_datanames, |
286 | -+ | 197x |
- }+ server_args = server_args, |
287 | -88x | +197x |
- invisible(.self)+ ui_args = ui_args, |
288 | -+ | 197x |
- })+ transformers = transformers |
289 |
- },+ ), |
||
290 | -+ | 197x |
- slices_deactivate_all = function(module_label) {+ class = "teal_module" |
291 | -! | +
- shiny::isolate({+ ) |
|
292 | -! | +
- new_slices <- .self$all_slices()+ } |
|
293 | -! | +
- old_mapping <- attr(new_slices, "mapping")+ |
|
294 |
-
+ #' @rdname teal_modules |
||
295 | -! | +
- new_mapping <- if (.self$is_module_specific()) {+ #' @export |
|
296 | -! | +
- new_module_mapping <- setNames(nm = module_label, list(character(0)))+ #' |
|
297 | -! | +
- modifyList(old_mapping, new_module_mapping)+ modules <- function(..., label = "root") { |
|
298 | -! | +137x |
- } else if (missing(module_label)) {+ checkmate::assert_string(label) |
299 | -! | +135x |
- lapply(+ submodules <- list(...) |
300 | -! | +135x |
- attr(.self$all_slices(), "mapping"),+ if (any(vapply(submodules, is.character, FUN.VALUE = logical(1)))) { |
301 | -! | +2x |
- function(x) character(0)+ stop( |
302 | -+ | 2x |
- )+ "The only character argument to modules() must be 'label' and it must be named, ", |
303 | -+ | 2x |
- } else {+ "change modules('lab', ...) to modules(label = 'lab', ...)" |
304 | -! | +
- old_mapping[[module_label]] <- character(0)+ ) |
|
305 | -! | +
- old_mapping+ } |
|
306 |
- }+ |
||
307 | -+ | 133x |
-
+ checkmate::assert_list(submodules, min.len = 1, any.missing = FALSE, types = c("teal_module", "teal_modules")) |
308 | -! | +
- if (!identical(new_mapping, old_mapping)) {+ # name them so we can more easily access the children |
|
309 | -! | +
- logger::log_debug(".slicesGlobal@slices_deactivate_all: deactivating all slices.")+ # beware however that the label of the submodules should not be changed as it must be kept synced |
|
310 | -! | +130x |
- attr(new_slices, "mapping") <- new_mapping+ labels <- vapply(submodules, function(submodule) submodule$label, character(1)) |
311 | -! | +130x |
- .self$all_slices(new_slices)+ names(submodules) <- get_unique_labels(labels) |
312 | -+ | 130x |
- }+ structure( |
313 | -! | +130x |
- invisible(.self)+ list( |
314 | -+ | 130x |
- })+ label = label, |
315 | -+ | 130x |
- },+ children = submodules |
316 |
- slices_active = function(mapping_elem) {+ ), |
||
317 | -195x | +130x |
- shiny::isolate({+ class = "teal_modules" |
318 | -195x | +
- if (.self$is_module_specific()) {+ ) |
|
319 | -36x | +
- new_mapping <- modifyList(attr(.self$all_slices(), "mapping"), mapping_elem)+ } |
|
320 |
- } else {+ |
||
321 | -159x | +
- new_mapping <- setNames(nm = "global_filters", list(unique(unlist(mapping_elem))))+ # printing methods ---- |
|
322 |
- }+ |
||
323 |
-
+ #' @rdname teal_modules |
||
324 | -195x | +
- if (!identical(new_mapping, attr(.self$all_slices(), "mapping"))) {+ #' @param is_last (`logical(1)`) Whether this is the last item in its parent's children list. |
|
325 | -138x | +
- mapping_modules <- toString(names(new_mapping))+ #' Affects the tree branch character used (L- vs |-) |
|
326 | -138x | +
- logger::log_debug(".slicesGlobal@slices_active: changing mapping for module(s): { mapping_modules }.")+ #' @param parent_prefix (`character(1)`) The prefix inherited from parent nodes, |
|
327 | -138x | +
- new_slices <- .self$all_slices()+ #' used to maintain the tree structure in nested levels |
|
328 | -138x | +
- attr(new_slices, "mapping") <- new_mapping+ #' @param is_root (`logical(1)`) Whether this is the root node of the tree. Only used in |
|
329 | -138x | +
- .self$all_slices(new_slices)+ #' format.teal_modules(). Determines whether to show "TEAL ROOT" header |
|
330 |
- }+ #' @param what (`character`) Specifies which metadata to display. |
||
331 |
-
+ #' Possible values: "datasets", "properties", "ui_args", "server_args", "transformers" |
||
332 | -195x | +
- invisible(.self)+ #' @examples |
|
333 |
- })+ #' mod <- module( |
||
334 |
- },+ #' label = "My Custom Module", |
||
335 |
- # - only new filters are appended to the $all_slices+ #' server = function(id, data, ...) {}, |
||
336 |
- # - mapping is not updated here+ #' ui = function(id, ...) {}, |
||
337 |
- slices_append = function(slices, activate = FALSE) {+ #' datanames = c("ADSL", "ADTTE"), |
||
338 | -195x | +
- shiny::isolate({+ #' transformers = list(), |
|
339 | -195x | +
- if (!is.teal_slices(slices)) {+ #' ui_args = list(a = 1, b = "b"), |
|
340 | -! | +
- slices <- as.teal_slices(slices)+ #' server_args = list(x = 5, y = list(p = 1)) |
|
341 |
- }+ #' ) |
||
342 |
-
+ #' cat(format(mod)) |
||
343 |
- # to make sure that we don't unnecessary trigger $all_slices <reactiveVal>+ #' @export |
||
344 | -195x | +
- new_slices <- setdiff_teal_slices(slices, .self$all_slices())+ format.teal_module <- function( |
|
345 | -195x | +
- old_mapping <- attr(.self$all_slices(), "mapping")+ x, indent = 0, is_last = FALSE, parent_prefix = "", |
|
346 | -195x | +
- if (length(new_slices)) {+ what = c("datasets", "properties", "ui_args", "server_args", "transformers"), ...) { |
|
347 | -6x | +3x |
- new_ids <- vapply(new_slices, `[[`, character(1L), "id")+ empty_text <- "" |
348 | -6x | +3x |
- logger::log_debug(".slicesGlobal@slices_append: appending new slice(s): { new_ids }.")+ branch <- if (is_last) "L-" else "|-" |
349 | -6x | +3x |
- slices_ids <- vapply(.self$all_slices(), `[[`, character(1L), "id")+ current_prefix <- paste0(parent_prefix, branch, " ") |
350 | -6x | +3x |
- lapply(new_slices, function(slice) {+ content_prefix <- paste0(parent_prefix, if (is_last) " " else "| ") |
351 |
- # In case the new state has the same id as an existing one, add a suffix+ |
||
352 | -6x | +3x |
- if (slice$id %in% slices_ids) {+ format_list <- function(lst, empty = empty_text, label_width = 0) { |
353 | -1x | +6x |
- slice$id <- utils::tail(make.unique(c(slices_ids, slice$id), sep = "_"), 1)+ if (is.null(lst) || length(lst) == 0) { |
354 | -+ | 6x |
- }+ empty |
355 |
- })+ } else { |
||
356 | -+ | ! |
-
+ colon_space <- paste(rep(" ", label_width), collapse = "") |
357 | -6x | +
- new_slices_all <- c(.self$all_slices(), new_slices)+ |
|
358 | -6x | +! |
- attr(new_slices_all, "mapping") <- old_mapping+ first_item <- sprintf("%s (%s)", names(lst)[1], crayon::silver(class(lst[[1]])[1])) |
359 | -6x | +! |
- .self$all_slices(new_slices_all)+ rest_items <- if (length(lst) > 1) { |
360 | -+ | ! |
- }+ paste( |
361 | -+ | ! |
-
+ vapply( |
362 | -195x | +! |
- invisible(.self)+ names(lst)[-1], |
363 | -+ | ! |
- })+ function(name) { |
364 | -+ | ! |
- },+ sprintf( |
365 | -+ | ! |
- slices_get = function(module_label) {+ "%s%s (%s)", |
366 | -289x | +! |
- if (missing(module_label)) {+ paste0(content_prefix, "| ", colon_space), |
367 | ! |
- .self$all_slices()+ name, |
|
368 | -+ | ! |
- } else {+ crayon::silver(class(lst[[name]])[1]) |
369 | -289x | +
- module_ids <- unlist(attr(.self$all_slices(), "mapping")[c(module_label, "global_filters")])+ ) |
|
370 | -289x | +
- Filter(+ }, |
|
371 | -289x | +! |
- function(slice) slice$id %in% module_ids,+ character(1) |
372 | -289x | +
- .self$all_slices()+ ), |
|
373 | -+ | ! |
- )+ collapse = "\n" |
374 |
- }+ ) |
||
375 |
- },+ } |
||
376 | -+ | ! |
- slices_set = function(slices) {+ if (length(lst) > 1) paste0(first_item, "\n", rest_items) else first_item |
377 | -7x | +
- shiny::isolate({+ } |
|
378 | -7x | +
- if (!is.teal_slices(slices)) {+ } |
|
379 | -! | +
- slices <- as.teal_slices(slices)+ |
|
380 | -+ | 3x |
- }+ bookmarkable <- isTRUE(attr(x, "teal_bookmarkable")) |
381 | -7x | +3x |
- .self$all_slices(slices)+ reportable <- "reporter" %in% names(formals(x$server)) |
382 | -7x | +
- invisible(.self)+ |
|
383 | -+ | 3x |
- })+ transformers <- if (length(x$transformers) > 0) { |
384 | -+ | ! |
- },+ paste(sapply(x$transformers, function(t) attr(t, "label")), collapse = ", ") |
385 |
- show = function() {+ } else { |
||
386 | -! | +3x |
- shiny::isolate(print(.self$all_slices()))+ empty_text |
387 | -! | +
- invisible(.self)+ } |
|
388 |
- }+ |
||
389 | -+ | 3x |
- )+ output <- pasten(current_prefix, crayon::bgWhite(x$label)) |
390 |
- )+ |
||
391 | -+ | 3x |
- # todo: prevent any teal_slices attribute except mapping+ if ("datasets" %in% what) { |
1 | -+ | ||
392 | +3x |
- # FilteredData ------+ output <- paste0( |
|
2 | -+ | ||
393 | +3x |
-
+ output, |
|
3 | -+ | ||
394 | +3x |
- #' Drive a `teal` application+ content_prefix, "|- ", crayon::yellow("Datasets : "), paste(x$datanames, collapse = ", "), "\n" |
|
4 | +395 |
- #'+ ) |
|
5 | +396 |
- #' Extension of the `shinytest2::AppDriver` class with methods for+ } |
|
6 | -+ | ||
397 | +3x |
- #' driving a teal application for performing interactions for `shinytest2` tests.+ if ("properties" %in% what) { |
|
7 | -+ | ||
398 | +3x |
- #'+ output <- paste0( |
|
8 | -+ | ||
399 | +3x |
- #' @keywords internal+ output, |
|
9 | -+ | ||
400 | +3x |
- #'+ content_prefix, "|- ", crayon::blue("Properties:"), "\n", |
|
10 | -+ | ||
401 | +3x |
- TealAppDriver <- R6::R6Class( # nolint: object_name.+ content_prefix, "| |- ", crayon::cyan("Bookmarkable : "), bookmarkable, "\n", |
|
11 | -+ | ||
402 | +3x |
- "TealAppDriver",+ content_prefix, "| L- ", crayon::cyan("Reportable : "), reportable, "\n" |
|
12 | +403 |
- inherit = {+ ) |
|
13 | +404 |
- if (!requireNamespace("shinytest2", quietly = TRUE)) {+ } |
|
14 | -+ | ||
405 | +3x |
- stop("Please install 'shinytest2' package to use this class.")+ if ("ui_args" %in% what) { |
|
15 | -+ | ||
406 | +3x |
- }+ ui_args_formatted <- format_list(x$ui_args, label_width = 19) |
|
16 | -+ | ||
407 | +3x |
- if (!requireNamespace("rvest", quietly = TRUE)) {+ output <- paste0( |
|
17 | -+ | ||
408 | +3x |
- stop("Please install 'rvest' package to use this class.")+ output, |
|
18 | -+ | ||
409 | +3x |
- }+ content_prefix, "|- ", crayon::green("UI Arguments : "), ui_args_formatted, "\n" |
|
19 | +410 |
- shinytest2::AppDriver+ ) |
|
20 | +411 |
- },+ } |
|
21 | -+ | ||
412 | +3x |
- # public methods ----+ if ("server_args" %in% what) { |
|
22 | -+ | ||
413 | +3x |
- public = list(+ server_args_formatted <- format_list(x$server_args, label_width = 19) |
|
23 | -+ | ||
414 | +3x |
- #' @description+ output <- paste0( |
|
24 | -+ | ||
415 | +3x |
- #' Initialize a `TealAppDriver` object for testing a `teal` application.+ output, |
|
25 | -+ | ||
416 | +3x |
- #'+ content_prefix, "|- ", crayon::green("Server Arguments : "), server_args_formatted, "\n" |
|
26 | +417 |
- #' @param data,modules,filter,title,header,footer,landing_popup arguments passed to `init`+ ) |
|
27 | +418 |
- #' @param timeout (`numeric`) Default number of milliseconds for any timeout or+ } |
|
28 | -+ | ||
419 | +3x |
- #' timeout_ parameter in the `TealAppDriver` class.+ if ("transformers" %in% what) { |
|
29 | -+ | ||
420 | +3x |
- #' Defaults to 20s.+ output <- paste0( |
|
30 | -+ | ||
421 | +3x |
- #'+ output, |
|
31 | -+ | ||
422 | +3x |
- #' See [`shinytest2::AppDriver`] `new` method for more details on how to change it+ content_prefix, "L- ", crayon::magenta("Transformers : "), transformers, "\n" |
|
32 | +423 |
- #' via options or environment variables.+ ) |
|
33 | +424 |
- #' @param load_timeout (`numeric`) How long to wait for the app to load, in ms.+ } |
|
34 | +425 |
- #' This includes the time to start R. Defaults to 100s.+ |
|
35 | -+ | ||
426 | +3x |
- #'+ output |
|
36 | +427 |
- #' See [`shinytest2::AppDriver`] `new` method for more details on how to change it+ } |
|
37 | +428 |
- #' via options or environment variables+ |
|
38 | +429 |
- #' @param ... Additional arguments to be passed to `shinytest2::AppDriver$new`+ #' @rdname teal_modules |
|
39 | +430 |
- #'+ #' @examples |
|
40 | +431 |
- #'+ #' custom_module <- function( |
|
41 | +432 |
- #' @return Object of class `TealAppDriver`+ #' label = "label", ui_args = NULL, server_args = NULL, |
|
42 | +433 |
- initialize = function(data,+ #' datanames = "all", transformers = list(), bk = FALSE) { |
|
43 | +434 |
- modules,+ #' ans <- module( |
|
44 | +435 |
- filter = teal_slices(),+ #' label, |
|
45 | +436 |
- title = build_app_title(),+ #' server = function(id, data, ...) {}, |
|
46 | +437 |
- header = tags$p(),+ #' ui = function(id, ...) { |
|
47 | +438 |
- footer = tags$p(),+ #' }, |
|
48 | +439 |
- landing_popup = NULL,+ #' datanames = datanames, |
|
49 | +440 |
- timeout = rlang::missing_arg(),+ #' transformers = transformers, |
|
50 | +441 |
- load_timeout = rlang::missing_arg(),+ #' ui_args = ui_args, |
|
51 | +442 |
- ...) {+ #' server_args = server_args |
|
52 | -! | +||
443 | +
- private$data <- data+ #' ) |
||
53 | -! | +||
444 | +
- private$modules <- modules+ #' attr(ans, "teal_bookmarkable") <- bk |
||
54 | -! | +||
445 | +
- private$filter <- filter+ #' ans |
||
55 | -! | +||
446 | +
- app <- init(+ #' } |
||
56 | -! | +||
447 | +
- data = data,+ #' |
||
57 | -! | +||
448 | +
- modules = modules,+ #' dummy_transformer <- teal_transform_module( |
||
58 | -! | +||
449 | +
- filter = filter,+ #' label = "Dummy Transform", |
||
59 | -! | +||
450 | +
- title = title,+ #' ui = function(id) div("(does nothing)"), |
||
60 | -! | +||
451 | +
- header = header,+ #' server = function(id, data) { |
||
61 | -! | +||
452 | +
- footer = footer,+ #' moduleServer(id, function(input, output, session) data) |
||
62 | -! | +||
453 | +
- landing_popup = landing_popup,+ #' } |
||
63 | +454 |
- )+ #' ) |
|
64 | +455 |
-
+ #' |
|
65 | +456 |
- # Default timeout is hardcoded to 4s in shinytest2:::resolve_timeout+ #' plot_transformer <- teal_transform_module( |
|
66 | +457 |
- # It must be set as parameter to the AppDriver+ #' label = "Plot Settings", |
|
67 | -! | +||
458 | +
- suppressWarnings(+ #' ui = function(id) div("(does nothing)"), |
||
68 | -! | +||
459 | +
- super$initialize(+ #' server = function(id, data) { |
||
69 | -! | +||
460 | +
- app_dir = shinyApp(app$ui, app$server),+ #' moduleServer(id, function(input, output, session) data) |
||
70 | -! | +||
461 | +
- name = "teal",+ #' } |
||
71 | -! | +||
462 | +
- variant = shinytest2::platform_variant(),+ #' ) |
||
72 | -! | +||
463 | +
- timeout = rlang::maybe_missing(timeout, 20 * 1000),+ #' |
||
73 | -! | +||
464 | +
- load_timeout = rlang::maybe_missing(load_timeout, 100 * 1000),+ #' complete_modules <- modules( |
||
74 | +465 |
- ...+ #' custom_module( |
|
75 | +466 |
- )+ #' label = "Data Overview", |
|
76 | +467 |
- )+ #' datanames = c("ADSL", "ADAE", "ADVS"), |
|
77 | +468 |
-
+ #' ui_args = list( |
|
78 | +469 |
- # Check for minimum version of Chrome that supports the tests+ #' view_type = "table", |
|
79 | +470 |
- # - Element.checkVisibility was added on 105+ #' page_size = 10, |
|
80 | -! | +||
471 | +
- chrome_version <- numeric_version(+ #' filters = c("ARM", "SEX", "RACE") |
||
81 | -! | +||
472 | +
- gsub(+ #' ), |
||
82 | -! | +||
473 | +
- "[[:alnum:]_]+/", # Prefix that ends with forward slash+ #' server_args = list( |
||
83 | +474 |
- "",+ #' cache = TRUE, |
|
84 | -! | +||
475 | +
- self$get_chromote_session()$Browser$getVersion()$product+ #' debounce = 1000 |
||
85 | +476 |
- ),+ #' ), |
|
86 | -! | +||
477 | +
- strict = FALSE+ #' transformers = list(dummy_transformer), |
||
87 | +478 |
- )+ #' bk = TRUE |
|
88 | +479 |
-
+ #' ), |
|
89 | -! | +||
480 | +
- required_version <- "121"+ #' modules( |
||
90 | +481 |
-
+ #' label = "Nested 1", |
|
91 | -! | +||
482 | +
- testthat::skip_if(+ #' custom_module( |
||
92 | -! | +||
483 | +
- is.na(chrome_version),+ #' label = "Interactive Plots", |
||
93 | -! | +||
484 | +
- "Problem getting Chrome version, please contact the developers."+ #' datanames = c("ADSL", "ADVS"), |
||
94 | +485 |
- )+ #' ui_args = list( |
|
95 | -! | +||
486 | +
- testthat::skip_if(+ #' plot_type = c("scatter", "box", "line"), |
||
96 | -! | +||
487 | +
- chrome_version < required_version,+ #' height = 600, |
||
97 | -! | +||
488 | +
- sprintf(+ #' width = 800, |
||
98 | -! | +||
489 | +
- "Chrome version '%s' is not supported, please upgrade to '%s' or higher",+ #' color_scheme = "viridis" |
||
99 | -! | +||
490 | +
- chrome_version,+ #' ), |
||
100 | -! | +||
491 | +
- required_version+ #' server_args = list( |
||
101 | +492 |
- )+ #' render_type = "svg", |
|
102 | +493 |
- )+ #' cache_plots = TRUE |
|
103 | +494 |
- # end od check+ #' ), |
|
104 | +495 |
-
+ #' transformers = list(dummy_transformer, plot_transformer), |
|
105 | -! | +||
496 | +
- private$set_active_ns()+ #' bk = TRUE |
||
106 | -! | +||
497 | +
- self$wait_for_idle()+ #' ), |
||
107 | +498 |
- },+ #' modules( |
|
108 | +499 |
- #' @description+ #' label = "Nested 2", |
|
109 | +500 |
- #' Append parent [`shinytest2::AppDriver`] `click` method with a call to `waif_for_idle()` method.+ #' custom_module( |
|
110 | +501 |
- #' @param ... arguments passed to parent [`shinytest2::AppDriver`] `click()` method.+ #' label = "Summary Statistics", |
|
111 | +502 |
- click = function(...) {+ #' datanames = "ADSL", |
|
112 | -! | +||
503 | +
- super$click(...)+ #' ui_args = list( |
||
113 | -! | +||
504 | +
- private$wait_for_page_stability()+ #' stats = c("mean", "median", "sd", "range"), |
||
114 | +505 |
- },+ #' grouping = c("ARM", "SEX") |
|
115 | +506 |
- #' @description+ #' ) |
|
116 | +507 |
- #' Check if the app has shiny errors. This checks for global shiny errors.+ #' ), |
|
117 | +508 |
- #' Note that any shiny errors dependent on shiny server render will only be captured after the teal module tab+ #' modules( |
|
118 | +509 |
- #' is visited because shiny will not trigger server computations when the tab is invisible.+ #' label = "Labeled nested modules", |
|
119 | +510 |
- #' So, navigate to the module tab you want to test before calling this function.+ #' custom_module( |
|
120 | +511 |
- #' Although, this catches errors hidden in the other module tabs if they are already rendered.+ #' label = "Subgroup Analysis", |
|
121 | +512 |
- 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"+ #' datanames = c("ADSL", "ADAE"), |
|
125 | +513 |
- )+ #' ui_args = list( |
|
126 | +514 |
- },+ #' subgroups = c("AGE", "SEX", "RACE"), |
|
127 | +515 |
- #' @description+ #' analysis_type = "stratified" |
|
128 | +516 |
- #' Check if the app has no validation errors. This checks for global shiny validation errors.+ #' ), |
|
129 | +517 |
- expect_no_validation_error = function() {- |
- |
130 | -! | -
- testthat::expect_null(- |
- |
131 | -! | -
- self$get_html(".shiny-output-error-validation"),- |
- |
132 | -! | -
- info = "No validation error is observed"+ #' bk = TRUE |
|
133 | +518 |
- )+ #' ) |
|
134 | +519 |
- },+ #' ), |
|
135 | +520 |
- #' @description+ #' modules(custom_module(label = "Subgroup Analysis in non-labled modules")) |
|
136 | +521 |
- #' Check if the app has validation errors. This checks for global shiny validation errors.+ #' ) |
|
137 | +522 |
- expect_validation_error = function() {- |
- |
138 | -! | -
- testthat::expect_false(- |
- |
139 | -! | -
- is.null(self$get_html(".shiny-output-error-validation")),+ #' ), |
|
140 | -! | +||
523 | +
- info = "Validation error is not observed"+ #' custom_module("Non-nested module") |
||
141 | +524 |
- )+ #' ) |
|
142 | +525 |
- },+ #' |
|
143 | +526 |
- #' @description+ #' cat(format(complete_modules)) |
|
144 | +527 |
- #' Set the input in the `teal` app.+ #' cat(format(complete_modules, what = c("ui_args", "server_args", "transformers"))) |
|
145 | +528 |
- #'+ #' @export |
|
146 | +529 |
- #' @param input_id (character) The shiny input id with it's complete name space.+ format.teal_modules <- function(x, indent = 0, is_root = TRUE, is_last = FALSE, parent_prefix = "", ...) { |
|
147 | -+ | ||
530 | +1x |
- #' @param value The value to set the input to.+ if (is_root) { |
|
148 | -+ | ||
531 | +1x |
- #' @param ... Additional arguments to be passed to `shinytest2::AppDriver$set_inputs`+ header <- pasten(crayon::bold("TEAL ROOT")) |
|
149 | -+ | ||
532 | +1x |
- #'+ new_parent_prefix <- " " #' Initial indent for root level |
|
150 | +533 |
- #' @return The `TealAppDriver` object invisibly.+ } else { |
|
151 | -+ | ||
534 | +! |
- set_input = function(input_id, value, ...) {+ if (!is.null(x$label)) { |
|
152 | +535 | ! |
- do.call(+ branch <- if (is_last) "L-" else "|-" |
153 | +536 | ! |
- self$set_inputs,+ header <- pasten(parent_prefix, branch, " ", crayon::bold(x$label)) |
154 | +537 | ! |
- c(setNames(list(value), input_id), list(...))+ new_parent_prefix <- paste0(parent_prefix, if (is_last) " " else "| ") |
155 | +538 |
- )+ } else { |
|
156 | +539 | ! |
- invisible(self)+ header <- "" |
157 | -+ | ||
540 | +! |
- },+ new_parent_prefix <- parent_prefix |
|
158 | +541 |
- #' @description+ } |
|
159 | +542 |
- #' Navigate the teal tabs in the `teal` app.+ } |
|
160 | +543 |
- #'+ |
|
161 | -+ | ||
544 | +1x |
- #' @param tabs (character) Labels of tabs to navigate to. The order of the tabs is important,+ if (length(x$children) > 0) { |
|
162 | -+ | ||
545 | +1x |
- #' and it should start with the most parent level tab.+ children_output <- character(0) |
|
163 | -+ | ||
546 | +1x |
- #' Note: In case the teal tab group has duplicate names, the first tab will be selected,+ n_children <- length(x$children) |
|
164 | +547 |
- #' If you wish to select the second tab with the same name, use the suffix "_1".+ |
|
165 | -+ | ||
548 | +1x |
- #' If you wish to select the third tab with the same name, use the suffix "_2" and so on.+ for (i in seq_along(x$children)) { |
|
166 | -+ | ||
549 | +3x |
- #'+ child <- x$children[[i]] |
|
167 | -+ | ||
550 | +3x |
- #' @return The `TealAppDriver` object invisibly.+ is_last_child <- (i == n_children) |
|
168 | +551 |
- navigate_teal_tab = function(tabs) {- |
- |
169 | -! | -
- checkmate::check_character(tabs, min.len = 1)+ |
|
170 | -! | +||
552 | +3x |
- for (tab in tabs) {+ if (inherits(child, "teal_modules")) { |
|
171 | +553 | ! |
- self$set_input(+ children_output <- c( |
172 | +554 | ! |
- "teal-teal_modules-active_tab",+ children_output, |
173 | +555 | ! |
- get_unique_labels(tab),+ format(child, |
174 | +556 | ! |
- wait_ = FALSE- |
-
175 | -- |
- )- |
- |
176 | -- |
- }+ indent = indent, |
|
177 | +557 | ! |
- self$wait_for_idle()+ is_root = FALSE, |
178 | +558 | ! |
- private$set_active_ns()+ is_last = is_last_child, |
179 | +559 | ! |
- invisible(self)+ parent_prefix = new_parent_prefix, |
180 | +560 |
- },+ ... |
|
181 | +561 |
- #' @description+ ) |
|
182 | +562 |
- #' Get the active shiny name space for different components of the teal app.+ ) |
|
183 | +563 |
- #'+ } else { |
|
184 | -+ | ||
564 | +3x |
- #' @return (`list`) The list of active shiny name space of the teal components.+ children_output <- c( |
|
185 | -+ | ||
565 | +3x |
- active_ns = function() {+ children_output, |
|
186 | -! | +||
566 | +3x |
- if (identical(private$ns$module, character(0))) {+ format(child, |
|
187 | -! | +||
567 | +3x |
- private$set_active_ns()+ indent = indent, |
|
188 | -+ | ||
568 | +3x |
- }+ is_last = is_last_child, |
|
189 | -! | +||
569 | +3x |
- private$ns+ parent_prefix = new_parent_prefix, |
|
190 | +570 |
- },+ ... |
|
191 | +571 |
- #' @description+ ) |
|
192 | +572 |
- #' Get the active shiny name space for interacting with the module content.+ ) |
|
193 | +573 |
- #'+ } |
|
194 | +574 |
- #' @return (`string`) The active shiny name space of the component.+ } |
|
195 | +575 |
- active_module_ns = function() {- |
- |
196 | -! | -
- if (identical(private$ns$module, character(0))) {+ |
|
197 | -! | +||
576 | +1x |
- private$set_active_ns()+ paste0(header, paste(children_output, collapse = "")) |
|
198 | +577 |
- }+ } else { |
|
199 | +578 | ! |
- private$ns$module- |
-
200 | -- |
- },- |
- |
201 | -- |
- #' @description+ header |
|
202 | +579 |
- #' Get the active shiny name space bound with a custom `element` name.+ } |
|
203 | +580 |
- #'+ } |
|
204 | +581 |
- #' @param element `character(1)` custom element name.+ |
|
205 | +582 |
- #'+ #' @rdname teal_modules |
|
206 | +583 |
- #' @return (`string`) The active shiny name space of the component bound with the input `element`.+ #' @export |
|
207 | +584 |
- active_module_element = function(element) {+ print.teal_module <- function(x, ...) { |
|
208 | +585 | ! |
- checkmate::assert_string(element)+ cat(format(x, ...)) |
209 | +586 | ! |
- sprintf("#%s-%s", self$active_module_ns(), element)+ invisible(x) |
210 | +587 |
- },+ } |
|
211 | +588 |
- #' @description+ |
|
212 | +589 |
- #' Get the text of the active shiny name space bound with a custom `element` name.+ #' @rdname teal_modules |
|
213 | +590 |
- #'+ #' @export |
|
214 | +591 |
- #' @param element `character(1)` the text of the custom element name.+ print.teal_modules <- function(x, ...) { |
|
215 | -+ | ||
592 | +! |
- #'+ cat(format(x, ...)) |
|
216 | -+ | ||
593 | +! |
- #' @return (`string`) The text of the active shiny name space of the component bound with the input `element`.+ invisible(x) |
|
217 | +594 |
- active_module_element_text = function(element) {+ } |
|
218 | -! | +||
595 | +
- checkmate::assert_string(element)+ |
||
219 | -! | +||
596 | +
- self$get_text(self$active_module_element(element))+ #' @param modules (`teal_module` or `teal_modules`) |
||
220 | +597 |
- },+ #' @rdname teal_modules |
|
221 | +598 |
- #' @description+ #' @examples |
|
222 | +599 |
- #' Get the active shiny name space for interacting with the filter panel.+ #' # change the module's datanames |
|
223 | +600 |
- #'+ #' set_datanames(module(datanames = "all"), "a") |
|
224 | +601 |
- #' @return (`string`) The active shiny name space of the component.+ #' |
|
225 | +602 |
- active_filters_ns = function() {+ #' # change modules' datanames |
|
226 | -! | +||
603 | +
- if (identical(private$ns$filter_panel, character(0))) {+ #' set_datanames( |
||
227 | -! | +||
604 | +
- private$set_active_ns()+ #' modules( |
||
228 | +605 |
- }+ #' module(datanames = "all"), |
|
229 | -! | +||
606 | +
- private$ns$filter_panel+ #' module(datanames = "a") |
||
230 | +607 |
- },+ #' ), |
|
231 | +608 |
- #' @description+ #' "b" |
|
232 | +609 |
- #' Get the active shiny name space for interacting with the data-summary panel.+ #' ) |
|
233 | +610 |
- #'+ #' @export |
|
234 | +611 |
- #' @return (`string`) The active shiny name space of the data-summary component.+ set_datanames <- function(modules, datanames) { |
|
235 | -+ | ||
612 | +! |
- active_data_summary_ns = function() {+ checkmate::assert_multi_class(modules, c("teal_modules", "teal_module")) |
|
236 | +613 | ! |
- if (identical(private$ns$data_summary, character(0))) {+ if (inherits(modules, "teal_modules")) { |
237 | +614 | ! |
- private$set_active_ns()+ modules$children <- lapply(modules$children, set_datanames, datanames) |
238 | +615 |
- }+ } else { |
|
239 | +616 | ! |
- private$ns$data_summary+ if (identical(modules$datanames, "all")) { |
240 | -+ | ||
617 | +! |
- },+ modules$datanames <- datanames |
|
241 | +618 |
- #' @description+ } else { |
|
242 | -+ | ||
619 | +! |
- #' Get the active shiny name space bound with a custom `element` name.+ warning( |
|
243 | -+ | ||
620 | +! |
- #'+ "Not possible to modify datanames of the module ", modules$label, |
|
244 | -+ | ||
621 | +! |
- #' @param element `character(1)` custom element name.+ ". set_datanames() can only change datanames if it was set to \"all\".",+ |
+ |
622 | +! | +
+ call. = FALSE |
|
245 | +623 |
- #'+ ) |
|
246 | +624 |
- #' @return (`string`) The active shiny name space of the component bound with the input `element`.+ } |
|
247 | +625 |
- active_data_summary_element = function(element) {+ } |
|
248 | +626 | ! |
- checkmate::assert_string(element)+ modules |
249 | -! | +||
627 | +
- sprintf("#%s-%s", self$active_data_summary_ns(), element)+ } |
||
250 | +628 |
- },+ |
|
251 | +629 |
- #' @description+ # utilities ---- |
|
252 | +630 |
- #' Get the input from the module in the `teal` app.+ ## subset or modify modules ---- |
|
253 | +631 |
- #' This function will only access inputs from the name space of the current active teal module.+ |
|
254 | +632 |
- #'+ #' Append a `teal_module` to `children` of a `teal_modules` object |
|
255 | +633 |
- #' @param input_id (character) The shiny input id to get the value from.+ #' @keywords internal |
|
256 | +634 |
- #'+ #' @param modules (`teal_modules`) |
|
257 | +635 |
- #' @return The value of the shiny input.+ #' @param module (`teal_module`) object to be appended onto the children of `modules` |
|
258 | +636 |
- get_active_module_input = function(input_id) {+ #' @return A `teal_modules` object with `module` appended. |
|
259 | -! | +||
637 | +
- checkmate::check_string(input_id)+ append_module <- function(modules, module) { |
||
260 | -! | +||
638 | +8x |
- self$get_value(input = sprintf("%s-%s", self$active_module_ns(), input_id))+ checkmate::assert_class(modules, "teal_modules") |
|
261 | -+ | ||
639 | +6x |
- },+ checkmate::assert_class(module, "teal_module")+ |
+ |
640 | +4x | +
+ modules$children <- c(modules$children, list(module))+ |
+ |
641 | +4x | +
+ labels <- vapply(modules$children, function(submodule) submodule$label, character(1))+ |
+ |
642 | +4x | +
+ names(modules$children) <- get_unique_labels(labels)+ |
+ |
643 | +4x | +
+ modules |
|
262 | +644 |
- #' @description+ } |
|
263 | +645 |
- #' Get the output from the module in the `teal` app.+ |
|
264 | +646 |
- #' This function will only access outputs from the name space of the current active teal module.+ #' Extract/Remove module(s) of specific class |
|
265 | +647 |
- #'+ #' |
|
266 | +648 |
- #' @param output_id (character) The shiny output id to get the value from.+ #' Given a `teal_module` or a `teal_modules`, return the elements of the structure according to `class`. |
|
267 | +649 |
- #'+ #' |
|
268 | +650 |
- #' @return The value of the shiny output.+ #' @param modules (`teal_modules`) |
|
269 | +651 |
- get_active_module_output = function(output_id) {+ #' @param class The class name of `teal_module` to be extracted or dropped. |
|
270 | -! | +||
652 | +
- checkmate::check_string(output_id)+ #' @keywords internal |
||
271 | -! | +||
653 | +
- self$get_value(output = sprintf("%s-%s", self$active_module_ns(), output_id))+ #' @return |
||
272 | +654 |
- },+ #' - For `extract_module`, a `teal_module` of class `class` or `teal_modules` containing modules of class `class`. |
|
273 | +655 |
- #' @description+ #' - For `drop_module`, the opposite, which is all `teal_modules` of class other than `class`. |
|
274 | +656 |
- #' Get the output from the module's `teal.widgets::table_with_settings` or `DT::DTOutput` in the `teal` app.+ #' @rdname module_management |
|
275 | +657 |
- #' This function will only access outputs from the name space of the current active teal module.+ extract_module <- function(modules, class) {+ |
+ |
658 | +24x | +
+ if (inherits(modules, class)) {+ |
+ |
659 | +! | +
+ modules+ |
+ |
660 | +24x | +
+ } else if (inherits(modules, "teal_module")) {+ |
+ |
661 | +13x | +
+ NULL+ |
+ |
662 | +11x | +
+ } else if (inherits(modules, "teal_modules")) {+ |
+ |
663 | +11x | +
+ Filter(function(x) length(x) > 0L, lapply(modules$children, extract_module, class)) |
|
276 | +664 |
- #'+ } |
|
277 | +665 |
- #' @param table_id (`character(1)`) The id of the table in the active teal module's name space.+ } |
|
278 | +666 |
- #' @param which (integer) If there is more than one table, which should be extracted.+ |
|
279 | +667 |
- #' By default it will look for a table that is built using `teal.widgets::table_with_settings`.+ #' @keywords internal |
|
280 | +668 |
- #'+ #' @return `teal_modules` |
|
281 | +669 |
- #' @return The data.frame with table contents.+ #' @rdname module_management |
|
282 | +670 |
- get_active_module_table_output = function(table_id, which = 1) {+ drop_module <- function(modules, class) { |
|
283 | +671 | ! |
- checkmate::check_number(which, lower = 1)+ if (inherits(modules, class)) { |
284 | +672 | ! |
- checkmate::check_string(table_id)+ NULL |
285 | +673 | ! |
- table <- rvest::html_table(+ } else if (inherits(modules, "teal_module")) { |
286 | +674 | ! |
- self$get_html_rvest(self$active_module_element(table_id)),+ modules |
287 | +675 | ! |
- fill = TRUE+ } else if (inherits(modules, "teal_modules")) { |
288 | -+ | ||
676 | +! |
- )+ do.call( |
|
289 | +677 | ! |
- if (length(table) == 0) {+ "modules", |
290 | +678 | ! |
- data.frame()+ c(Filter(function(x) length(x) > 0L, lapply(modules$children, drop_module, class)), label = modules$label) |
291 | +679 |
- } else {+ ) |
|
292 | -! | +||
680 | +
- table[[which]]+ } |
||
293 | +681 |
- }+ } |
|
294 | +682 |
- },+ |
|
295 | +683 |
- #' @description+ ## read modules ---- |
|
296 | +684 |
- #' Get the output from the module's `teal.widgets::plot_with_settings` in the `teal` app.+ |
|
297 | +685 |
- #' This function will only access plots from the name space of the current active teal module.+ #' Does the object make use of the `arg` |
|
298 | +686 |
- #'+ #' |
|
299 | +687 |
- #' @param plot_id (`character(1)`) The id of the plot in the active teal module's name space.+ #' @param modules (`teal_module` or `teal_modules`) object |
|
300 | +688 |
- #'+ #' @param arg (`character(1)`) names of the arguments to be checked against formals of `teal` modules. |
|
301 | +689 |
- #' @return The `src` attribute as `character(1)` vector.+ #' @return `logical` whether the object makes use of `arg`. |
|
302 | +690 |
- get_active_module_plot_output = function(plot_id) {+ #' @rdname is_arg_used |
|
303 | -! | +||
691 | +
- checkmate::check_string(plot_id)+ #' @keywords internal |
||
304 | -! | +||
692 | +
- self$get_attr(+ is_arg_used <- function(modules, arg) { |
||
305 | -! | +||
693 | +486x |
- self$active_module_element(sprintf("%s-plot_main > img", plot_id)),+ checkmate::assert_string(arg) |
|
306 | -! | +||
694 | +483x |
- "src"+ if (inherits(modules, "teal_modules")) {+ |
+ |
695 | +18x | +
+ any(unlist(lapply(modules$children, is_arg_used, arg)))+ |
+ |
696 | +465x | +
+ } else if (inherits(modules, "teal_module")) {+ |
+ |
697 | +30x | +
+ is_arg_used(modules$server, arg) || is_arg_used(modules$ui, arg)+ |
+ |
698 | +435x | +
+ } else if (is.function(modules)) {+ |
+ |
699 | +433x | +
+ isTRUE(arg %in% names(formals(modules))) |
|
307 | +700 |
- )+ } else {+ |
+ |
701 | +2x | +
+ stop("is_arg_used function not implemented for this object") |
|
308 | +702 |
- },+ } |
|
309 | +703 |
- #' @description+ } |
|
310 | +704 |
- #' Set the input in the module in the `teal` app.+ |
|
311 | +705 |
- #' This function will only set inputs in the name space of the current active teal module.+ |
|
312 | +706 |
- #'+ #' Get module depth |
|
313 | +707 |
- #' @param input_id (character) The shiny input id to get the value from.+ #' |
|
314 | +708 |
- #' @param value The value to set the input to.+ #' Depth starts at 0, so a single `teal.module` has depth 0. |
|
315 | +709 |
- #' @param ... Additional arguments to be passed to `shinytest2::AppDriver$set_inputs`+ #' Nesting it increases overall depth by 1. |
|
316 | +710 |
- #'+ #' |
|
317 | +711 |
- #' @return The `TealAppDriver` object invisibly.+ #' @inheritParams init |
|
318 | +712 |
- set_active_module_input = function(input_id, value, ...) {+ #' @param depth optional integer determining current depth level |
|
319 | -! | +||
713 | +
- checkmate::check_string(input_id)+ #' |
||
320 | -! | +||
714 | +
- checkmate::check_string(value)+ #' @return Depth level for given module. |
||
321 | -! | +||
715 | +
- self$set_input(+ #' @keywords internal |
||
322 | -! | +||
716 | +
- sprintf("%s-%s", self$active_module_ns(), input_id),+ modules_depth <- function(modules, depth = 0L) { |
||
323 | -! | +||
717 | +12x |
- value,+ checkmate::assert_multi_class(modules, c("teal_module", "teal_modules")) |
|
324 | -+ | ||
718 | +12x |
- ...+ checkmate::assert_int(depth, lower = 0)+ |
+ |
719 | +11x | +
+ if (inherits(modules, "teal_modules")) {+ |
+ |
720 | +4x | +
+ max(vapply(modules$children, modules_depth, integer(1), depth = depth + 1L)) |
|
325 | +721 |
- )+ } else { |
|
326 | -! | +||
722 | +7x |
- dots <- rlang::list2(...)+ depth |
|
327 | -! | +||
723 | +
- if (!isFALSE(dots[["wait"]])) self$wait_for_idle() # Default behavior is to wait+ } |
||
328 | -! | +||
724 | +
- invisible(self)+ } |
||
329 | +725 |
- },+ |
|
330 | +726 |
- #' @description+ #' Retrieve labels from `teal_modules` |
|
331 | +727 |
- #' Get the active datasets that can be accessed via the filter panel of the current active teal module.+ #' |
|
332 | +728 |
- get_active_filter_vars = function() {+ #' @param modules (`teal_modules`) |
|
333 | -! | +||
729 | +
- displayed_datasets_index <- self$is_visible(+ #' @return A `list` containing the labels of the modules. If the modules are nested, |
||
334 | -! | +||
730 | +
- sprintf("#%s-filters-filter_active_vars_contents > span", self$active_filters_ns())+ #' the function returns a nested `list` of labels. |
||
335 | +731 |
- )+ #' @keywords internal |
|
336 | +732 |
-
+ module_labels <- function(modules) { |
|
337 | -! | +||
733 | +189x |
- available_datasets <- self$get_text(+ if (inherits(modules, "teal_modules")) { |
|
338 | -! | +||
734 | +82x |
- sprintf(+ lapply(modules$children, module_labels) |
|
339 | -! | +||
735 | +
- "#%s-filters-filter_active_vars_contents .filter_panel_dataname",+ } else { |
||
340 | -! | +||
736 | +107x |
- self$active_filters_ns()+ modules$label |
|
341 | +737 |
- )+ } |
|
342 | +738 |
- )+ } |
|
343 | +739 | ||
344 | -! | +||
740 | +
- available_datasets[displayed_datasets_index]+ #' Retrieve `teal_bookmarkable` attribute from `teal_modules` |
||
345 | +741 |
- },+ #' |
|
346 | +742 |
- #' @description+ #' @param modules (`teal_modules` or `teal_module`) object |
|
347 | +743 |
- #' Get the active data summary table+ #' @return named list of the same structure as `modules` with `TRUE` or `FALSE` values indicating |
|
348 | +744 |
- #' @return `data.frame`+ #' whether the module is bookmarkable. |
|
349 | +745 |
- get_active_data_summary_table = function() {+ #' @keywords internal |
|
350 | -! | +||
746 | +
- summary_table <- rvest::html_table(+ modules_bookmarkable <- function(modules) { |
||
351 | -! | +||
747 | +189x |
- self$get_html_rvest(self$active_data_summary_element("table")),+ checkmate::assert_multi_class(modules, c("teal_modules", "teal_module")) |
|
352 | -! | +||
748 | +189x |
- fill = TRUE+ if (inherits(modules, "teal_modules")) { |
|
353 | -! | +||
749 | +82x |
- )[[1]]+ setNames( |
|
354 | -+ | ||
750 | +82x |
-
+ lapply(modules$children, modules_bookmarkable), |
|
355 | -! | +||
751 | +82x |
- col_names <- unlist(summary_table[1, ], use.names = FALSE)+ vapply(modules$children, `[[`, "label", FUN.VALUE = character(1)) |
|
356 | -! | +||
752 | +
- summary_table <- summary_table[-1, ]+ ) |
||
357 | -! | +||
753 | +
- colnames(summary_table) <- col_names+ } else { |
||
358 | -! | +||
754 | +107x |
- if (nrow(summary_table) > 0) {+ attr(modules, "teal_bookmarkable", exact = TRUE) |
|
359 | -! | +||
755 | +
- summary_table+ } |
||
360 | +756 |
- } else {+ } |
|
361 | -! | +
1 | +
- NULL+ #' Generate lockfile for application's environment reproducibility |
||
362 | +2 |
- }+ #' |
|
363 | +3 |
- },+ #' @param lockfile_path (`character`) path to the lockfile. |
|
364 | +4 |
- #' @description+ #' |
|
365 | +5 |
- #' Test if `DOM` elements are visible on the page with a JavaScript call.+ #' @section Different ways of creating lockfile: |
|
366 | +6 |
- #' @param selector (`character(1)`) `CSS` selector to check visibility.+ #' `teal` leverages [renv::snapshot()], which offers multiple methods for lockfile creation. |
|
367 | +7 |
- #' A `CSS` id will return only one element if the UI is well formed.+ #' |
|
368 | +8 |
- #' @param content_visibility_auto,opacity_property,visibility_property (`logical(1)`) See more information+ #' - **Working directory lockfile**: `teal`, by default, will create an `implicit` type lockfile that uses |
|
369 | +9 |
- #' on <https://developer.mozilla.org/en-US/docs/Web/API/Element/checkVisibility>.+ #' `renv::dependencies()` to detect all R packages in the current project's working directory. |
|
370 | +10 |
- #'+ #' - **`DESCRIPTION`-based lockfile**: To generate a lockfile based on a `DESCRIPTION` file in your working |
|
371 | +11 |
- #' @return Logical vector with all occurrences of the selector.+ #' directory, set `renv::settings$snapshot.type("explicit")`. The naming convention for `type` follows |
|
372 | +12 |
- is_visible = function(selector,+ #' `renv::snapshot()`. For the `"explicit"` type, refer to `renv::settings$package.dependency.fields()` for the |
|
373 | +13 |
- content_visibility_auto = FALSE,+ #' `DESCRIPTION` fields included in the lockfile. |
|
374 | +14 |
- opacity_property = FALSE,+ #' - **Custom files-based lockfile**: To specify custom files as the basis for the lockfile, set |
|
375 | +15 |
- visibility_property = FALSE) {+ #' `renv::settings$snapshot.type("custom")` and configure the `renv.snapshot.filter` option. |
|
376 | -! | +||
16 | +
- checkmate::assert_string(selector)+ #' |
||
377 | -! | +||
17 | +
- checkmate::assert_flag(content_visibility_auto)+ #' @section lockfile usage: |
||
378 | -! | +||
18 | +
- checkmate::assert_flag(opacity_property)+ #' After creating the lockfile, you can restore the application's environment using `renv::restore()`. |
||
379 | -! | +||
19 | +
- checkmate::assert_flag(visibility_property)+ #' |
||
380 | +20 |
-
+ #' @seealso [renv::snapshot()], [renv::restore()]. |
|
381 | -! | +||
21 | +
- private$wait_for_page_stability()+ #' |
||
382 | +22 |
-
+ #' @return `NULL` |
|
383 | -! | +||
23 | +
- testthat::skip_if_not(- |
- ||
384 | -! | -
- self$get_js("typeof Element.prototype.checkVisibility === 'function'"),- |
- |
385 | -! | -
- "Element.prototype.checkVisibility is not supported in the current browser."+ #' |
|
386 | +24 |
- )+ #' @name module_teal_lockfile |
|
387 | +25 |
-
+ #' @rdname module_teal_lockfile |
|
388 | -! | +||
26 | +
- unlist(+ #' |
||
389 | -! | +||
27 | +
- self$get_js(+ #' @keywords internal |
||
390 | -! | +||
28 | +
- sprintf(+ NULL |
||
391 | -! | +||
29 | +
- "Array.from(document.querySelectorAll('%s')).map(el => el.checkVisibility({%s, %s, %s}))",+ |
||
392 | -! | +||
30 | +
- selector,+ #' @rdname module_teal_lockfile |
||
393 | +31 |
- # Extra parameters+ ui_teal_lockfile <- function(id) { |
|
394 | +32 | ! |
- sprintf("contentVisibilityAuto: %s", tolower(content_visibility_auto)),+ ns <- NS(id) |
395 | +33 | ! |
- sprintf("opacityProperty: %s", tolower(opacity_property)),+ shiny::tagList( |
396 | +34 | ! |
- sprintf("visibilityProperty: %s", tolower(visibility_property))- |
-
397 | -- |
- )- |
- |
398 | -- |
- )- |
- |
399 | -- |
- )+ tags$span("", id = ns("lockFileStatus")), |
|
400 | -+ | ||
35 | +! |
- },+ shinyjs::disabled(downloadLink(ns("lockFileLink"), "Download lockfile")) |
|
401 | +36 |
- #' @description+ ) |
|
402 | +37 |
- #' Get the active filter variables from a dataset in the `teal` app.+ } |
|
403 | +38 |
- #'+ |
|
404 | +39 |
- #' @param dataset_name (character) The name of the dataset to get the filter variables from.+ #' @rdname module_teal_lockfile |
|
405 | +40 |
- #' If `NULL`, the filter variables for all the datasets will be returned in a list.+ srv_teal_lockfile <- function(id) { |
|
406 | -+ | ||
41 | +83x |
- get_active_data_filters = function(dataset_name = NULL) {+ moduleServer(id, function(input, output, session) { |
|
407 | -! | +||
42 | +83x |
- checkmate::check_string(dataset_name, null.ok = TRUE)+ logger::log_debug("Initialize srv_teal_lockfile.") |
|
408 | -! | +||
43 | +83x |
- datasets <- self$get_active_filter_vars()+ enable_lockfile_download <- function() { |
|
409 | +44 | ! |
- checkmate::assert_subset(dataset_name, datasets)+ shinyjs::html("lockFileStatus", "Application lockfile ready.") |
410 | +45 | ! |
- active_filters <- lapply(+ shinyjs::hide("lockFileStatus", anim = TRUE) |
411 | +46 | ! |
- datasets,+ shinyjs::enable("lockFileLink") |
412 | +47 | ! |
- function(x) {+ output$lockFileLink <- shiny::downloadHandler( |
413 | +48 | ! |
- var_names <- gsub(+ filename = function() { |
414 | +49 | ! |
- pattern = "\\s",+ "renv.lock" |
415 | -! | +||
50 | +
- replacement = "",+ }, |
||
416 | +51 | ! |
- self$get_text(+ content = function(file) { |
417 | +52 | ! |
- sprintf(+ file.copy(lockfile_path, file) |
418 | +53 | ! |
- "#%s-filters-%s .filter-card-varname",+ file |
419 | -! | +||
54 | +
- self$active_filters_ns(),+ }, |
||
420 | +55 | ! |
- x+ contentType = "application/json" |
421 | +56 |
- )+ ) |
|
422 | +57 |
- )+ } |
|
423 | -+ | ||
58 | +83x |
- )+ disable_lockfile_download <- function() { |
|
424 | +59 | ! |
- structure(+ warning("Lockfile creation failed.", call. = FALSE) |
425 | +60 | ! |
- lapply(var_names, private$get_active_filter_selection, dataset_name = x),+ shinyjs::html("lockFileStatus", "Lockfile creation failed.") |
426 | +61 | ! |
- names = var_names+ shinyjs::hide("lockFileLink") |
427 | +62 |
- )+ } |
|
428 | +63 |
- }+ |
|
429 | -+ | ||
64 | +83x |
- )+ shiny::onStop(function() { |
|
430 | -! | +||
65 | +83x |
- names(active_filters) <- datasets+ if (file.exists(lockfile_path) && !shiny::isRunning()) { |
|
431 | -! | +||
66 | +1x |
- if (is.null(dataset_name)) {+ logger::log_debug("Removing lockfile after shutting down the app") |
|
432 | -! | +||
67 | +1x |
- return(active_filters)+ file.remove(lockfile_path) |
|
433 | +68 |
} |
|
434 | -! | +||
69 | +
- active_filters[[dataset_name]]+ }) |
||
435 | +70 |
- },+ |
|
436 | -+ | ||
71 | +83x |
- #' @description+ lockfile_path <- "teal_app.lock" |
|
437 | -+ | ||
72 | +83x |
- #' Add a new variable from the dataset to be filtered.+ mode <- getOption("teal.lockfile.mode", default = "") |
|
438 | +73 |
- #'+ |
|
439 | -+ | ||
74 | +83x |
- #' @param dataset_name (character) The name of the dataset to add the filter variable to.+ if (!(mode %in% c("auto", "enabled", "disabled"))) { |
|
440 | -+ | ||
75 | +! |
- #' @param var_name (character) The name of the variable to add to the filter panel.+ stop("'teal.lockfile.mode' option can only be one of \"auto\", \"disabled\" or \"disabled\". ") |
|
441 | +76 |
- #' @param ... Additional arguments to be passed to `shinytest2::AppDriver$set_inputs`+ } |
|
442 | +77 |
- #'+ |
|
443 | -+ | ||
78 | +83x |
- #' @return The `TealAppDriver` object invisibly.+ if (mode == "disabled") { |
|
444 | -+ | ||
79 | +1x |
- add_filter_var = function(dataset_name, var_name, ...) {+ logger::log_debug("'teal.lockfile.mode' option is set to 'disabled'. Hiding lockfile download button.") |
|
445 | -! | +||
80 | +1x |
- checkmate::check_string(dataset_name)+ shinyjs::hide("lockFileLink") |
|
446 | -! | +||
81 | +1x |
- checkmate::check_string(var_name)+ return(NULL) |
|
447 | -! | +||
82 | +
- private$set_active_ns()+ } |
||
448 | -! | +||
83 | +
- self$click(+ |
||
449 | -! | +||
84 | +82x |
- selector = sprintf(+ if (file.exists(lockfile_path)) { |
|
450 | +85 | ! |
- "#%s-filters-%s-add_filter_icon",+ logger::log_debug("Lockfile has already been created for this app - skipping automatic creation.") |
451 | +86 | ! |
- private$ns$filter_panel,+ enable_lockfile_download() |
452 | +87 | ! |
- dataset_name+ return(NULL) |
453 | +88 |
- )+ } |
|
454 | +89 |
- )+ |
|
455 | -! | +||
90 | +82x |
- self$set_input(+ if (mode == "auto" && .is_disabled_lockfile_scenario()) { |
|
456 | -! | +||
91 | +81x |
- sprintf(+ logger::log_debug( |
|
457 | -! | +||
92 | +81x |
- "%s-filters-%s-%s-filter-var_to_add",+ "Automatic lockfile creation disabled. Execution scenario satisfies teal:::.is_disabled_lockfile_scenario()." |
|
458 | -! | +||
93 | +
- private$ns$filter_panel,+ ) |
||
459 | -! | +||
94 | +81x |
- dataset_name,+ shinyjs::hide("lockFileLink") |
|
460 | -! | +||
95 | +81x |
- dataset_name+ return(NULL) |
|
461 | +96 |
- ),+ } |
|
462 | -! | +||
97 | +
- var_name,+ |
||
463 | -+ | ||
98 | +1x |
- ...+ if (!.is_lockfile_deps_installed()) { |
|
464 | -+ | ||
99 | +! |
- )+ warning("Automatic lockfile creation disabled. `mirai` and `renv` packages must be installed.") |
|
465 | +100 | ! |
- invisible(self)+ shinyjs::hide("lockFileLink") |
466 | -+ | ||
101 | +! |
- },+ return(NULL) |
|
467 | +102 |
- #' @description+ } |
|
468 | +103 |
- #' Remove an active filter variable of a dataset from the active filter variables panel.+ |
|
469 | +104 |
- #'+ # - Will be run only if the lockfile doesn't exist (see the if-s above) |
|
470 | +105 |
- #' @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.- |
- |
472 | -- |
- #' @param var_name (character) The name of the variable to remove from the filter panel.- |
- |
473 | -- |
- #' If `NULL`, all the filter variables of the dataset will be removed.- |
- |
474 | -- |
- #'+ # - We render to the tempfile because the process might last after session is closed and we don't |
|
475 | +106 |
- #' @return The `TealAppDriver` object invisibly.+ # want to make a "teal_app.renv" then. This is why we copy only during active session. |
|
476 | -+ | ||
107 | +1x |
- remove_filter_var = function(dataset_name = NULL, var_name = NULL) {+ process <- .teal_lockfile_process_invoke(lockfile_path) |
|
477 | -! | +||
108 | +1x |
- checkmate::check_string(dataset_name, null.ok = TRUE)+ observeEvent(process$status(), { |
|
478 | +109 | ! |
- checkmate::check_string(var_name, null.ok = TRUE)+ if (process$status() %in% c("initial", "running")) { |
479 | +110 | ! |
- if (is.null(dataset_name)) {+ shinyjs::html("lockFileStatus", "Creating lockfile...") |
480 | +111 | ! |
- remove_selector <- sprintf(+ } else if (process$status() == "success") { |
481 | +112 | ! |
- "#%s-active-remove_all_filters",+ result <- process$result() |
482 | +113 | ! |
- self$active_filters_ns()- |
-
483 | -- |
- )+ if (any(grepl("Lockfile written to", result$out))) { |
|
484 | +114 | ! |
- } else if (is.null(var_name)) {+ logger::log_debug("Lockfile containing { length(result$res$Packages) } packages created.") |
485 | +115 | ! |
- remove_selector <- sprintf(+ if (any(grepl("(WARNING|ERROR):", result$out))) { |
486 | +116 | ! |
- "#%s-active-%s-remove_filters",+ warning("Lockfile created with warning(s) or error(s):", call. = FALSE) |
487 | +117 | ! |
- self$active_filters_ns(),+ for (i in result$out) { |
488 | +118 | ! |
- dataset_name+ warning(i, call. = FALSE) |
489 | +119 |
- )+ } |
|
490 | +120 |
- } else {+ } |
|
491 | +121 | ! |
- remove_selector <- sprintf(+ enable_lockfile_download() |
492 | -! | +||
122 | +
- "#%s-active-%s-filter-%s_%s-remove",+ } else { |
||
493 | +123 | ! |
- self$active_filters_ns(),+ disable_lockfile_download() |
494 | -! | +||
124 | +
- dataset_name,+ } |
||
495 | +125 | ! |
- dataset_name,+ } else if (process$status() == "error") { |
496 | +126 | ! |
- var_name+ disable_lockfile_download() |
497 | +127 |
- )+ } |
|
498 | +128 |
- }+ }) |
|
499 | -! | +||
129 | +
- self$click(+ |
||
500 | -! | +||
130 | +1x |
- selector = remove_selector+ NULL |
|
501 | +131 |
- )- |
- |
502 | -! | -
- invisible(self)+ }) |
|
503 | +132 |
- },+ } |
|
504 | +133 |
- #' @description+ |
|
505 | +134 |
- #' Set the active filter values for a variable of a dataset in the active filter variable panel.+ utils::globalVariables(c("opts", "sysenv", "libpaths", "wd", "lockfilepath", "run")) # needed for mirai call |
|
506 | +135 |
- #'+ #' @rdname module_teal_lockfile |
|
507 | +136 |
- #' @param dataset_name (character) The name of the dataset to set the filter value for.+ .teal_lockfile_process_invoke <- function(lockfile_path) { |
|
508 | -+ | ||
137 | +1x |
- #' @param var_name (character) The name of the variable to set the filter value for.+ mirai_obj <- NULL |
|
509 | -+ | ||
138 | +1x |
- #' @param input The value to set the filter to.+ process <- shiny::ExtendedTask$new(function() { |
|
510 | -+ | ||
139 | +1x |
- #' @param ... Additional arguments to be passed to `shinytest2::AppDriver$set_inputs`+ m <- mirai::mirai( |
|
511 | +140 |
- #'+ { |
|
512 | -+ | ||
141 | +1x |
- #' @return The `TealAppDriver` object invisibly.+ options(opts) |
|
513 | -+ | ||
142 | +1x |
- set_active_filter_selection = function(dataset_name,+ do.call(Sys.setenv, sysenv) |
|
514 | -+ | ||
143 | +1x |
- var_name,+ .libPaths(libpaths) |
|
515 | -+ | ||
144 | +1x |
- input,+ setwd(wd) |
|
516 | -+ | ||
145 | +1x |
- ...) {+ run(lockfile_path = lockfile_path) |
|
517 | -! | +||
146 | +
- checkmate::check_string(dataset_name)+ }, |
||
518 | -! | +||
147 | +1x |
- checkmate::check_string(var_name)+ run = .renv_snapshot, |
|
519 | -! | +||
148 | +1x |
- checkmate::check_string(input)+ lockfile_path = lockfile_path, |
|
520 | -+ | ||
149 | +1x |
-
+ opts = options(), |
|
521 | -! | +||
150 | +1x |
- input_id_prefix <- sprintf(+ libpaths = .libPaths(), |
|
522 | -! | +||
151 | +1x |
- "%s-filters-%s-filter-%s_%s-inputs",+ sysenv = as.list(Sys.getenv()), |
|
523 | -! | +||
152 | +1x |
- self$active_filters_ns(),+ wd = getwd() |
|
524 | -! | +||
153 | +
- dataset_name,+ ) |
||
525 | -! | +||
154 | +1x |
- dataset_name,+ mirai_obj <<- m |
|
526 | -! | +||
155 | +1x |
- var_name+ m |
|
527 | +156 |
- )+ }) |
|
528 | +157 | ||
529 | -+ | ||
158 | +1x |
- # Find the type of filter (based on filter panel)+ shiny::onStop(function() { |
|
530 | -! | +||
159 | +1x |
- supported_suffix <- c("selection", "selection_manual")+ if (mirai::unresolved(mirai_obj)) { |
|
531 | +160 | ! |
- slices_suffix <- supported_suffix[+ logger::log_debug("Terminating a running lockfile process...") |
532 | +161 | ! |
- match(+ mirai::stop_mirai(mirai_obj) # this doesn't stop running - renv will be created even if session is closed |
533 | -! | +||
162 | +
- TRUE,+ } |
||
534 | -! | +||
163 | +
- vapply(+ }) |
||
535 | -! | +||
164 | +
- supported_suffix,+ |
||
536 | -! | +||
165 | +1x |
- function(suffix) {+ suppressWarnings({ # 'package:stats' may not be available when loading |
|
537 | -! | +||
166 | +1x |
- !is.null(self$get_html(sprintf("#%s-%s", input_id_prefix, suffix)))+ process$invoke() |
|
538 | +167 |
- },+ }) |
|
539 | -! | +||
168 | +
- logical(1)+ |
||
540 | -+ | ||
169 | +1x |
- )+ logger::log_debug("Lockfile creation started based on { getwd() }.") |
|
541 | +170 |
- )+ + |
+ |
171 | +1x | +
+ process |
|
542 | +172 |
- ]+ } |
|
543 | +173 | ||
544 | +174 |
- # Generate correct namespace+ #' @rdname module_teal_lockfile |
|
545 | -! | +||
175 | +
- slices_input_id <- sprintf(+ .renv_snapshot <- function(lockfile_path) { |
||
546 | -! | +||
176 | +1x |
- "%s-filters-%s-filter-%s_%s-inputs-%s",+ out <- utils::capture.output( |
|
547 | -! | +||
177 | +1x |
- self$active_filters_ns(),+ res <- renv::snapshot( |
|
548 | -! | +||
178 | +1x |
- dataset_name,+ lockfile = lockfile_path, |
|
549 | -! | +||
179 | +1x |
- dataset_name,+ prompt = FALSE, |
|
550 | -! | +||
180 | +1x |
- var_name,+ force = TRUE, |
|
551 | -! | +||
181 | +1x |
- slices_suffix+ type = renv::settings$snapshot.type() # see the section "Different ways of creating lockfile" above here |
|
552 | +182 |
- )+ ) |
|
553 | +183 | ++ |
+ )+ |
+
184 | |||
554 | -! | +||
185 | +1x |
- if (identical(slices_suffix, "selection_manual")) {+ list(out = out, res = res) |
|
555 | -! | +||
186 | +
- checkmate::assert_numeric(input, len = 2)+ } |
||
556 | +187 | ||
557 | -! | +||
188 | +
- dots <- rlang::list2(...)+ #' @rdname module_teal_lockfile |
||
558 | -! | +||
189 | +
- checkmate::assert_choice(dots$priority_, formals(self$set_inputs)[["priority_"]], null.ok = TRUE)+ .is_lockfile_deps_installed <- function() { |
||
559 | -! | +||
190 | +1x |
- checkmate::assert_flag(dots$wait_, null.ok = TRUE)+ requireNamespace("mirai", quietly = TRUE) && requireNamespace("renv", quietly = TRUE) |
|
560 | +191 | ++ |
+ }+ |
+
192 | |||
561 | -! | +||
193 | +
- self$run_js(+ #' @rdname module_teal_lockfile |
||
562 | -! | +||
194 | +
- sprintf(+ .is_disabled_lockfile_scenario <- function() { |
||
563 | -! | +||
195 | +81x |
- "Shiny.setInputValue('%s:sw.numericRange', [%f, %f], {priority: '%s'})",+ identical(Sys.getenv("CALLR_IS_RUNNING"), "true") || # inside callr process |
|
564 | -! | +||
196 | +81x |
- slices_input_id,+ identical(Sys.getenv("TESTTHAT"), "true") || # inside devtools::test |
|
565 | -! | +||
197 | +81x |
- input[[1]],+ !identical(Sys.getenv("QUARTO_PROJECT_ROOT"), "") || # inside Quarto process |
|
566 | -! | +||
198 | +
- input[[2]],+ ( |
||
567 | -! | +||
199 | +81x |
- priority_ = ifelse(is.null(dots$priority_), "input", dots$priority_)+ ("CheckExEnv" %in% search()) || any(c("_R_CHECK_TIMINGS_", "_R_CHECK_LICENSE_") %in% names(Sys.getenv()))+ |
+ |
200 | +81x | +
+ ) # inside R CMD CHECK |
|
568 | +201 |
- )+ } |
569 | +1 |
- )+ #' Calls all `modules` |
|
570 | +2 |
-
+ #' |
|
571 | -! | +||
3 | +
- if (isTRUE(dots$wait_) || is.null(dots$wait_)) {+ #' On the UI side each `teal_modules` is translated to a `tabsetPanel` and each `teal_module` is a |
||
572 | -! | +||
4 | +
- self$wait_for_idle(+ #' `tabPanel`. Both, UI and server are called recursively so that each tab is a separate module and |
||
573 | -! | +||
5 | +
- timeout = if (is.null(dots$timeout_)) rlang::missing_arg() else dots$timeout_+ #' reflect nested structure of `modules` argument. |
||
574 | +6 |
- )+ #' |
|
575 | +7 |
- }+ #' @name module_teal_module |
|
576 | -! | +||
8 | +
- } else if (identical(slices_suffix, "selection")) {+ #' |
||
577 | -! | +||
9 | +
- self$set_input(+ #' @inheritParams module_teal |
||
578 | -! | +||
10 | +
- slices_input_id,+ #' |
||
579 | -! | +||
11 | +
- input,+ #' @param data_rv (`reactive` returning `teal_data`) |
||
580 | +12 |
- ...+ #' |
|
581 | +13 |
- )+ #' @param slices_global (`reactiveVal` returning `modules_teal_slices`) |
|
582 | +14 |
- } else {+ #' see [`module_filter_manager`] |
|
583 | -! | +||
15 | +
- stop("Filter selection set not supported for this slice.")+ #' |
||
584 | +16 |
- }+ #' @param depth (`integer(1)`) |
|
585 | +17 |
-
+ #' number which helps to determine depth of the modules nesting. |
|
586 | -! | +||
18 | +
- invisible(self)+ #' |
||
587 | +19 |
- },+ #' @param datasets (`reactive` returning `FilteredData` or `NULL`) |
|
588 | +20 |
- #' @description+ #' When `datasets` is passed from the parent module (`srv_teal`) then `dataset` is a singleton |
|
589 | +21 |
- #' Extract `html` attribute (found by a `selector`).+ #' which implies in filter-panel to be "global". When `NULL` then filter-panel is "module-specific". |
|
590 | +22 |
- #'+ #' |
|
591 | +23 |
- #' @param selector (`character(1)`) specifying the selector to be used to get the content of a specific node.+ #' @param data_load_status (`reactive` returning `character`) |
|
592 | +24 |
- #' @param attribute (`character(1)`) name of an attribute to retrieve from a node specified by `selector`.+ #' Determines action dependent on a data loading status: |
|
593 | +25 |
- #'+ #' - `"ok"` when `teal_data` is returned from the data loading. |
|
594 | +26 |
- #' @return The `character` vector.+ #' - `"teal_data_module failed"` when [teal_data_module()] didn't return `teal_data`. Disables tabs buttons. |
|
595 | +27 |
- get_attr = function(selector, attribute) {+ #' - `"external failed"` when a `reactive` passed to `srv_teal(data)` didn't return `teal_data`. Hides the whole tab |
|
596 | -! | +||
28 | +
- rvest::html_attr(+ #' panel. |
||
597 | -! | +||
29 | +
- rvest::html_nodes(self$get_html_rvest("html"), selector),+ #' |
||
598 | -! | +||
30 | +
- attribute+ #' @return |
||
599 | +31 |
- )+ #' output of currently active module. |
|
600 | +32 |
- },+ #' - `srv_teal_module.teal_module` returns `reactiveVal` containing output of the called module. |
|
601 | +33 |
- #' @description+ #' - `srv_teal_module.teal_modules` returns output of module selected by `input$active_tab`. |
|
602 | +34 |
- #' Wrapper around `get_html` that passes the output directly to `rvest::read_html`.+ #' |
|
603 | +35 |
- #'+ #' @keywords internal |
|
604 | +36 |
- #' @param selector `(character(1))` passed to `get_html`.+ NULL |
|
605 | +37 |
- #'+ |
|
606 | +38 |
- #' @return An XML document.+ #' @rdname module_teal_module |
|
607 | +39 |
- get_html_rvest = function(selector) {+ ui_teal_module <- function(id, modules, depth = 0L) { |
|
608 | +40 | ! |
- rvest::read_html(self$get_html(selector))+ checkmate::assert_multi_class(modules, c("teal_modules", "teal_module", "shiny.tag")) |
609 | -+ | ||
41 | +! |
- },+ checkmate::assert_count(depth) |
|
610 | -+ | ||
42 | +! |
- #' Wrapper around `get_url()` method that opens the app in the browser.+ UseMethod("ui_teal_module", modules) |
|
611 | +43 |
- #'+ } |
|
612 | +44 |
- #' @return Nothing. Opens the underlying teal app in the browser.+ |
|
613 | +45 |
- open_url = function() {- |
- |
614 | -! | -
- browseURL(self$get_url())+ #' @rdname module_teal_module |
|
615 | +46 |
- },+ #' @export |
|
616 | +47 |
- #' @description+ ui_teal_module.default <- function(id, modules, depth = 0L) { |
|
617 | -+ | ||
48 | +! |
- #' Waits until a specified input, output, or export value.+ stop("Modules class not supported: ", paste(class(modules), collapse = " ")) |
|
618 | +49 |
- #' This function serves as a wrapper around the `wait_for_value` method,+ } |
|
619 | +50 |
- #' providing a more flexible interface for waiting on different types of values within the active module namespace.+ |
|
620 | +51 |
- #' @param input,output,export A name of an input, output, or export value.+ #' @rdname module_teal_module |
|
621 | +52 |
- #' Only one of these parameters may be used.+ #' @export |
|
622 | +53 |
- #' @param ... Must be empty. Allows for parameter expansion.+ ui_teal_module.teal_modules <- function(id, modules, depth = 0L) { |
|
623 | -+ | ||
54 | +! |
- #' Parameter with additional value to passed in `wait_for_value`.+ ns <- NS(id) |
|
624 | -+ | ||
55 | +! |
- wait_for_active_module_value = function(input = rlang::missing_arg(),+ tags$div( |
|
625 | -+ | ||
56 | +! |
- output = rlang::missing_arg(),+ id = ns("wrapper"), |
|
626 | -+ | ||
57 | +! |
- export = rlang::missing_arg(),+ do.call( |
|
627 | -+ | ||
58 | +! |
- ...) {+ tabsetPanel, |
|
628 | +59 | ! |
- ns <- shiny::NS(self$active_module_ns())+ c( |
629 | +60 |
-
+ # by giving an id, we can reactively respond to tab changes |
|
630 | +61 | ! |
- if (!rlang::is_missing(input) && checkmate::test_string(input, min.chars = 1)) input <- ns(input)+ list( |
631 | +62 | ! |
- if (!rlang::is_missing(output) && checkmate::test_string(output, min.chars = 1)) output <- ns(output)+ id = ns("active_tab"), |
632 | +63 | ! |
- if (!rlang::is_missing(export) && checkmate::test_string(export, min.chars = 1)) export <- ns(export)+ type = if (modules$label == "root") "pills" else "tabs" |
633 | +64 |
-
+ ), |
|
634 | +65 | ! |
- self$wait_for_value(+ lapply( |
635 | +66 | ! |
- input = input,+ names(modules$children), |
636 | +67 | ! |
- output = output,+ function(module_id) { |
637 | +68 | ! |
- export = export,+ module_label <- modules$children[[module_id]]$label |
638 | -+ | ||
69 | +! |
- ...+ if (is.null(module_label)) { |
|
639 | -+ | ||
70 | +! |
- )+ module_label <- icon("fas fa-database") |
|
640 | +71 |
- }+ } |
|
641 | -+ | ||
72 | +! |
- ),+ tabPanel(+ |
+ |
73 | +! | +
+ title = module_label,+ |
+ |
74 | +! | +
+ value = module_id, # when clicked this tab value changes input$<tabset panel id>+ |
+ |
75 | +! | +
+ ui_teal_module(+ |
+ |
76 | +! | +
+ id = ns(module_id),+ |
+ |
77 | +! | +
+ modules = modules$children[[module_id]],+ |
+ |
78 | +! | +
+ depth = depth + 1L |
|
642 | +79 |
- # private members ----+ ) |
|
643 | +80 |
- private = list(+ ) |
|
644 | +81 |
- # private attributes ----+ } |
|
645 | +82 |
- data = NULL,+ ) |
|
646 | +83 |
- modules = NULL,+ ) |
|
647 | +84 |
- filter = teal_slices(),+ ) |
|
648 | +85 |
- ns = list(+ ) |
|
649 | +86 |
- module = character(0),+ } |
|
650 | +87 |
- filter_panel = character(0)+ |
|
651 | +88 |
- ),+ #' @rdname module_teal_module |
|
652 | +89 |
- # private methods ----+ #' @export |
|
653 | +90 |
- set_active_ns = function() {+ ui_teal_module.teal_module <- function(id, modules, depth = 0L) { |
|
654 | +91 | ! |
- all_inputs <- self$get_values()$input+ ns <- NS(id) |
655 | +92 | ! |
- active_tab_inputs <- all_inputs[grepl("-active_tab$", names(all_inputs))]+ args <- c(list(id = ns("module")), modules$ui_args) |
656 | +93 | ||
657 | -! | -
- tab_ns <- unlist(lapply(names(active_tab_inputs), function(name) {- |
- |
658 | +94 | ! |
- gsub(+ ui_teal <- tagList( |
659 | +95 | ! |
- pattern = "-active_tab$",+ div( |
660 | +96 | ! |
- replacement = sprintf("-%s", active_tab_inputs[[name]]),+ id = ns("validate_datanames"), |
661 | +97 | ! |
- name+ ui_validate_reactive_teal_data(ns("validate_datanames")) |
662 | +98 |
- )+ ), |
|
663 | -+ | ||
99 | +! |
- }))+ shinyjs::hidden( |
|
664 | +100 | ! |
- active_ns <- tab_ns[1]+ tags$div( |
665 | +101 | ! |
- if (length(tab_ns) > 1) {+ id = ns("transformer_failure_info"), |
666 | +102 | ! |
- for (i in 2:length(tab_ns)) {+ class = "teal_validated", |
667 | +103 | ! |
- next_ns <- tab_ns[i]+ div( |
668 | +104 | ! |
- if (grepl(pattern = active_ns, next_ns)) {+ class = "teal-output-warning", |
669 | +105 | ! |
- active_ns <- next_ns+ "One of transformers failed. Please fix and continue." |
670 | +106 |
- }+ ) |
|
671 | +107 |
- }+ ) |
|
672 | +108 |
- }+ ), |
|
673 | +109 | ! |
- private$ns$module <- sprintf("%s-%s", active_ns, "module")- |
-
674 | -- |
-
+ tags$div( |
|
675 | +110 | ! |
- components <- c("filter_panel", "data_summary")+ id = ns("teal_module_ui"), |
676 | +111 | ! |
- for (component in components) {+ do.call(modules$ui, args) |
677 | +112 |
- 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)))+ ) |
|
680 | +113 |
- ) {- |
- |
681 | -! | -
- private$ns[[component]] <- sprintf("%s-%s", active_ns, component)+ ) |
|
682 | +114 |
- } else {+ |
|
683 | +115 | ! |
- private$ns[[component]] <- sprintf("%s-module_%s", active_ns, component)- |
-
684 | -- |
- }- |
- |
685 | -- |
- }- |
- |
686 | -- |
- },- |
- |
687 | -- |
- # @description- |
- |
688 | -- |
- # Get the active filter values from the active filter selection of dataset from the filter panel.+ div( |
|
689 | -+ | ||
116 | +! |
- #+ id = id, |
|
690 | -+ | ||
117 | +! |
- # @param dataset_name (character) The name of the dataset to get the filter values from.+ class = "teal_module", |
|
691 | -+ | ||
118 | +! |
- # @param var_name (character) The name of the variable to get the filter values from.+ uiOutput(ns("data_reactive"), inline = TRUE), |
|
692 | -+ | ||
119 | +! |
- #+ tagList( |
|
693 | -+ | ||
120 | +! |
- # @return The value of the active filter selection.+ if (depth >= 2L) tags$div(style = "mt-6"), |
|
694 | -+ | ||
121 | +! |
- get_active_filter_selection = function(dataset_name, var_name) {+ if (!is.null(modules$datanames)) { |
|
695 | +122 | ! |
- checkmate::check_string(dataset_name)+ fluidRow( |
696 | +123 | ! |
- checkmate::check_string(var_name)+ column(width = 9, ui_teal, class = "teal_primary_col"), |
697 | +124 | ! |
- input_id_prefix <- sprintf(+ column( |
698 | +125 | ! |
- "%s-filters-%s-filter-%s_%s-inputs",+ width = 3, |
699 | +126 | ! |
- self$active_filters_ns(),+ ui_data_summary(ns("data_summary")), |
700 | +127 | ! |
- dataset_name,+ ui_filter_data(ns("filter_panel")), |
701 | +128 | ! |
- dataset_name,+ ui_transform_data(ns("data_transform"), transformers = modules$transformers, class = "well"), |
702 | +129 | ! |
- var_name+ class = "teal_secondary_col" |
703 | +130 |
- )+ ) |
|
704 | +131 |
-
+ ) |
|
705 | +132 |
- # Find the type of filter (categorical or range)+ } else { |
|
706 | +133 | ! |
- supported_suffix <- c("selection", "selection_manual")+ div( |
707 | +134 | ! |
- for (suffix in supported_suffix) {+ div( |
708 | +135 | ! |
- if (!is.null(self$get_html(sprintf("#%s-%s", input_id_prefix, suffix)))) {+ class = "teal_validated", |
709 | +136 | ! |
- return(self$get_value(input = sprintf("%s-%s", input_id_prefix, suffix)))+ uiOutput(ns("data_input_error")) |
710 | +137 |
- }+ ),+ |
+ |
138 | +! | +
+ ui_teal |
|
711 | +139 |
- }+ ) |
|
712 | +140 |
-
+ } |
|
713 | -! | +||
141 | +
- NULL # If there are not any supported filters+ ) |
||
714 | +142 |
- },+ ) |
|
715 | +143 |
- # @description+ } |
|
716 | +144 |
- # Check if the page is stable without any `DOM` updates in the body of the app.+ |
|
717 | +145 |
- # This is achieved by blocing the R process by sleeping until the page is unchanged till the `stability_period`.+ #' @rdname module_teal_module |
|
718 | +146 |
- # @param stability_period (`numeric(1)`) The time in milliseconds to wait till the page to be stable.+ srv_teal_module <- function(id, |
|
719 | +147 |
- # @param check_interval (`numeric(1)`) The time in milliseconds to check for changes in the page.+ data_rv, |
|
720 | +148 |
- # The stability check is reset when a change is detected in the page after sleeping for check_interval.+ modules, |
|
721 | +149 |
- wait_for_page_stability = function(stability_period = 2000, check_interval = 200) {+ datasets = NULL, |
|
722 | -! | +||
150 | +
- previous_content <- self$get_html("body")+ slices_global, |
||
723 | -! | +||
151 | +
- end_time <- Sys.time() + (stability_period / 1000)+ reporter = teal.reporter::Reporter$new(), |
||
724 | +152 |
-
+ data_load_status = reactive("ok"), |
|
725 | -! | +||
153 | +
- repeat {+ is_active = reactive(TRUE)) { |
||
726 | -! | +||
154 | +189x |
- Sys.sleep(check_interval / 1000)+ checkmate::assert_string(id) |
|
727 | -! | +||
155 | +189x |
- current_content <- self$get_html("body")+ assert_reactive(data_rv) |
|
728 | -+ | ||
156 | +189x |
-
+ checkmate::assert_multi_class(modules, c("teal_modules", "teal_module")) |
|
729 | -! | +||
157 | +189x |
- if (!identical(previous_content, current_content)) {+ assert_reactive(datasets, null.ok = TRUE) |
|
730 | -! | +||
158 | +189x |
- previous_content <- current_content+ checkmate::assert_class(slices_global, ".slicesGlobal") |
|
731 | -! | +||
159 | +189x |
- end_time <- Sys.time() + (stability_period / 1000)+ checkmate::assert_class(reporter, "Reporter") |
|
732 | -! | +||
160 | +189x |
- } else if (Sys.time() >= end_time) {+ assert_reactive(data_load_status) |
|
733 | -! | +||
161 | +189x |
- break+ UseMethod("srv_teal_module", modules) |
|
734 | +162 |
- }+ } |
|
735 | +163 |
- }+ |
|
736 | +164 |
- }+ #' @rdname module_teal_module |
|
737 | +165 |
- )+ #' @export |
|
738 | +166 |
- )+ srv_teal_module.default <- function(id, |
1 | +167 |
- setOldClass("teal_module")+ data_rv, |
||
2 | +168 |
- setOldClass("teal_modules")+ modules, |
||
3 | +169 |
-
+ datasets = NULL, |
||
4 | +170 |
- #' Create `teal_module` and `teal_modules` objects+ slices_global, |
||
5 | +171 |
- #'+ reporter = teal.reporter::Reporter$new(), |
||
6 | +172 |
- #' @description+ data_load_status = reactive("ok"), |
||
7 | +173 |
- #' `r lifecycle::badge("stable")`+ is_active = reactive(TRUE)) { |
||
8 | -+ | |||
174 | +! |
- #' Create a nested tab structure to embed modules in a `teal` application.+ stop("Modules class not supported: ", paste(class(modules), collapse = " ")) |
||
9 | +175 |
- #'+ } |
||
10 | +176 |
- #' @details+ |
||
11 | +177 |
- #' `module()` creates an instance of a `teal_module` that can be placed in a `teal` application.+ #' @rdname module_teal_module |
||
12 | +178 |
- #' `modules()` shapes the structure of a the application by organizing `teal_module` within the navigation panel.+ #' @export |
||
13 | +179 |
- #' It wraps `teal_module` and `teal_modules` objects in a `teal_modules` object,+ srv_teal_module.teal_modules <- function(id, |
||
14 | +180 |
- #' which results in a nested structure corresponding to the nested tabs in the final application.+ data_rv, |
||
15 | +181 |
- #'+ modules, |
||
16 | +182 |
- #' Note that for `modules()` `label` comes after `...`, so it must be passed as a named argument,+ datasets = NULL, |
||
17 | +183 |
- #' otherwise it will be captured by `...`.+ slices_global, |
||
18 | +184 |
- #'+ reporter = teal.reporter::Reporter$new(), |
||
19 | +185 |
- #' The labels `"global_filters"` and `"Report previewer"` are reserved+ data_load_status = reactive("ok"), |
||
20 | +186 |
- #' because they are used by the `mapping` argument of [teal_slices()]+ is_active = reactive(TRUE)) { |
||
21 | -+ | |||
187 | +82x |
- #' and the report previewer module [reporter_previewer_module()], respectively.+ moduleServer(id = id, module = function(input, output, session) { |
||
22 | -+ | |||
188 | +82x |
- #'+ logger::log_debug("srv_teal_module.teal_modules initializing the module { deparse1(modules$label) }.") |
||
23 | +189 |
- #' # Restricting datasets used by `teal_module`:+ |
||
24 | -+ | |||
190 | +82x |
- #' The `datanames` argument controls which datasets are used by the module’s server. These datasets,+ observeEvent(data_load_status(), { |
||
25 | -+ | |||
191 | +75x |
- #' passed via server's `data` argument, are the only ones shown in the module's tab.+ tabs_selector <- sprintf("#%s li a", session$ns("active_tab")) |
||
26 | -+ | |||
192 | +75x |
- #'+ if (identical(data_load_status(), "ok")) { |
||
27 | -+ | |||
193 | +70x |
- #' When `datanames` is set to `"all"`, all datasets in the data object are treated as relevant.+ logger::log_debug("srv_teal_module@1 enabling modules tabs.") |
||
28 | -+ | |||
194 | +70x |
- #' However, this may include unnecessary datasets, such as:+ shinyjs::show("wrapper") |
||
29 | -+ | |||
195 | +70x |
- #' - Proxy variables for column modifications+ shinyjs::enable(selector = tabs_selector) |
||
30 | -+ | |||
196 | +5x |
- #' - Temporary datasets used to create final versions+ } else if (identical(data_load_status(), "teal_data_module failed")) { |
||
31 | -+ | |||
197 | +5x |
- #' - Connection objects+ logger::log_debug("srv_teal_module@1 disabling modules tabs.") |
||
32 | -+ | |||
198 | +5x |
- #'+ shinyjs::disable(selector = tabs_selector) |
||
33 | -+ | |||
199 | +! |
- #' To exclude irrelevant datasets, use the [set_datanames()] function to change `datanames` from+ } else if (identical(data_load_status(), "external failed")) { |
||
34 | -+ | |||
200 | +! |
- #' `"all"` to specific names. Trying to modify non-`"all"` values with [set_datanames()] will result+ logger::log_debug("srv_teal_module@1 hiding modules tabs.") |
||
35 | -+ | |||
201 | +! |
- #' in a warning. Datasets with names starting with . are ignored globally unless explicitly listed+ shinyjs::hide("wrapper") |
||
36 | +202 |
- #' in `datanames`.+ } |
||
37 | +203 |
- #'+ }) |
||
38 | +204 |
- #' # `datanames` with `transformers`+ |
||
39 | -+ | |||
205 | +82x |
- #' When transformers are specified, their `datanames` are added to the module’s `datanames`, which+ modules_output <- sapply( |
||
40 | -+ | |||
206 | +82x |
- #' changes the behavior as follows:+ names(modules$children), |
||
41 | -+ | |||
207 | +82x |
- #' - If `module(datanames)` is `NULL` and the `transformers` have defined `datanames`, the sidebar+ function(module_id) { |
||
42 | -+ | |||
208 | +107x |
- #' will appear showing the `transformers`' datasets, instead of being hidden.+ srv_teal_module( |
||
43 | -+ | |||
209 | +107x |
- #' - If `module(datanames)` is set to specific values and any `transformer` has `datanames = "all"`,+ id = module_id, |
||
44 | -+ | |||
210 | +107x |
- #' the module may receive extra datasets that could be unnecessary+ data_rv = data_rv, |
||
45 | -+ | |||
211 | +107x |
- #'+ modules = modules$children[[module_id]], |
||
46 | -+ | |||
212 | +107x |
- #' @param label (`character(1)`) Label shown in the navigation item for the module or module group.+ datasets = datasets, |
||
47 | -+ | |||
213 | +107x |
- #' For `modules()` defaults to `"root"`. See `Details`.+ slices_global = slices_global, |
||
48 | -+ | |||
214 | +107x |
- #' @param server (`function`) `shiny` module with following arguments:+ reporter = reporter, |
||
49 | -+ | |||
215 | +107x |
- #' - `id` - `teal` will set proper `shiny` namespace for this module (see [shiny::moduleServer()]).+ is_active = reactive( |
||
50 | -+ | |||
216 | +107x |
- #' - `input`, `output`, `session` - (optional; not recommended) When provided, then [shiny::callModule()]+ is_active() && |
||
51 | -+ | |||
217 | +107x |
- #' will be used to call a module. From `shiny` 1.5.0, the recommended way is to use+ input$active_tab == module_id && |
||
52 | -+ | |||
218 | +107x |
- #' [shiny::moduleServer()] instead which doesn't require these arguments.+ identical(data_load_status(), "ok") |
||
53 | +219 |
- #' - `data` (optional) When provided, the module will be called with `teal_data` object (i.e. a list of+ ) |
||
54 | +220 |
- #' reactive (filtered) data specified in the `filters` argument) as the value of this argument.+ ) |
||
55 | +221 |
- #' - `datasets` (optional) When provided, the module will be called with `FilteredData` object as the+ }, |
||
56 | -+ | |||
222 | +82x |
- #' value of this argument. (See [`teal.slice::FilteredData`]).+ simplify = FALSE |
||
57 | +223 |
- #' - `reporter` (optional) When provided, the module will be called with `Reporter` object as the value+ ) |
||
58 | +224 |
- #' of this argument. (See [`teal.reporter::Reporter`]).+ |
||
59 | -+ | |||
225 | +82x |
- #' - `filter_panel_api` (optional) When provided, the module will be called with `FilterPanelAPI` object+ modules_output |
||
60 | +226 |
- #' as the value of this argument. (See [`teal.slice::FilterPanelAPI`]).+ }) |
||
61 | +227 |
- #' - `...` (optional) When provided, `server_args` elements will be passed to the module named argument+ } |
||
62 | +228 |
- #' or to the `...`.+ |
||
63 | +229 |
- #' @param ui (`function`) `shiny` UI module function with following arguments:+ #' @rdname module_teal_module |
||
64 | +230 |
- #' - `id` - `teal` will set proper `shiny` namespace for this module.+ #' @export |
||
65 | +231 |
- #' - `...` (optional) When provided, `ui_args` elements will be passed to the module named argument+ srv_teal_module.teal_module <- function(id, |
||
66 | +232 |
- #' or to the `...`.+ data_rv, |
||
67 | +233 |
- #' @param filters (`character`) Deprecated. Use `datanames` instead.+ modules, |
||
68 | +234 |
- #' @param datanames (`character`) Names of the datasets relevant to the item.+ datasets = NULL, |
||
69 | +235 |
- #' There are 2 reserved values that have specific behaviors:+ slices_global, |
||
70 | +236 |
- #' - The keyword `"all"` includes all datasets available in the data passed to the teal application.+ reporter = teal.reporter::Reporter$new(), |
||
71 | +237 |
- #' - `NULL` hides the sidebar panel completely.+ data_load_status = reactive("ok"), |
||
72 | +238 |
- #' - If `transformers` are specified, their `datanames` are automatically added to this `datanames`+ is_active = reactive(TRUE)) { |
||
73 | -+ | |||
239 | +107x |
- #' argument.+ logger::log_debug("srv_teal_module.teal_module initializing the module: { deparse1(modules$label) }.") |
||
74 | -+ | |||
240 | +107x |
- #' @param server_args (named `list`) with additional arguments passed on to the server function.+ moduleServer(id = id, module = function(input, output, session) { |
||
75 | -+ | |||
241 | +107x |
- #' @param ui_args (named `list`) with additional arguments passed on to the UI function.+ module_out <- reactiveVal() |
||
76 | +242 |
- #' @param x (`teal_module` or `teal_modules`) Object to format/print.+ |
||
77 | -+ | |||
243 | +107x |
- #' @param indent (`integer(1)`) Indention level; each nested element is indented one level more.+ active_datanames <- reactive({ |
||
78 | -+ | |||
244 | +84x |
- #' @param transformers (`list` of `teal_data_module`) that will be applied to transform the data.+ .resolve_module_datanames(data = data_rv(), modules = modules) |
||
79 | +245 |
- #' Each transform module UI will appear in the `teal`'s sidebar panel.+ }) |
||
80 | -+ | |||
246 | +107x |
- #' Transformers' `datanames` are added to the `datanames`. See [teal_transform_module()].+ if (is.null(datasets)) { |
||
81 | -+ | |||
247 | +20x |
- #'+ datasets <- eventReactive(data_rv(), { |
||
82 | -+ | |||
248 | +16x |
- #' @param ...+ req(inherits(data_rv(), "teal_data")) |
||
83 | -+ | |||
249 | +16x |
- #' - For `modules()`: (`teal_module` or `teal_modules`) Objects to wrap into a tab.+ logger::log_debug("srv_teal_module@1 initializing module-specific FilteredData") |
||
84 | -+ | |||
250 | +16x |
- #' - For `format()` and `print()`: Arguments passed to other methods.+ teal_data_to_filtered_data(data_rv(), datanames = active_datanames()) |
||
85 | +251 |
- #'+ }) |
||
86 | +252 |
- #' @return+ } |
||
87 | +253 |
- #' `module()` returns an object of class `teal_module`.+ |
||
88 | +254 |
- #'+ # manage module filters on the module level |
||
89 | +255 |
- #' `modules()` returns a `teal_modules` object which contains following fields:+ # important: |
||
90 | +256 |
- #' - `label`: taken from the `label` argument.+ # filter_manager_module_srv needs to be called before filter_panel_srv |
||
91 | +257 |
- #' - `children`: a list containing objects passed in `...`. List elements are named after+ # Because available_teal_slices is used in FilteredData$srv_available_slices (via srv_filter_panel) |
||
92 | +258 |
- #' their `label` attribute converted to a valid `shiny` id.+ # and if it is not set, then it won't be available in the srv_filter_panel |
||
93 | -+ | |||
259 | +107x |
- #'+ srv_module_filter_manager(modules$label, module_fd = datasets, slices_global = slices_global) |
||
94 | +260 |
- #' @name teal_modules+ |
||
95 | -+ | |||
261 | +107x |
- #' @aliases teal_module+ call_once_when(is_active(), { |
||
96 | -+ | |||
262 | +81x |
- #'+ filtered_teal_data <- srv_filter_data( |
||
97 | -+ | |||
263 | +81x |
- #' @examples+ "filter_panel", |
||
98 | -+ | |||
264 | +81x |
- #' library(shiny)+ datasets = datasets, |
||
99 | -+ | |||
265 | +81x |
- #'+ active_datanames = active_datanames, |
||
100 | -+ | |||
266 | +81x |
- #' module_1 <- module(+ data_rv = data_rv, |
||
101 | -+ | |||
267 | +81x |
- #' label = "a module",+ is_active = is_active |
||
102 | +268 |
- #' server = function(id, data) {+ ) |
||
103 | -+ | |||
269 | +81x |
- #' moduleServer(+ is_transformer_failed <- reactiveValues() |
||
104 | -+ | |||
270 | +81x |
- #' id,+ transformed_teal_data <- srv_transform_data( |
||
105 | -+ | |||
271 | +81x |
- #' module = function(input, output, session) {+ "data_transform", |
||
106 | -+ | |||
272 | +81x |
- #' output$data <- renderDataTable(data()[["iris"]])+ data = filtered_teal_data, |
||
107 | -+ | |||
273 | +81x |
- #' }+ transformers = modules$transformers, |
||
108 | -+ | |||
274 | +81x |
- #' )+ modules = modules, |
||
109 | -+ | |||
275 | +81x |
- #' },+ is_transformer_failed = is_transformer_failed |
||
110 | +276 |
- #' ui = function(id) {+ ) |
||
111 | -+ | |||
277 | +81x |
- #' ns <- NS(id)+ any_transformer_failed <- reactive({ |
||
112 | -+ | |||
278 | +81x |
- #' tagList(dataTableOutput(ns("data")))+ any(unlist(reactiveValuesToList(is_transformer_failed))) |
||
113 | +279 |
- #' },+ }) |
||
114 | +280 |
- #' datanames = "all"+ |
||
115 | -+ | |||
281 | +81x |
- #' )+ observeEvent(any_transformer_failed(), { |
||
116 | -+ | |||
282 | +81x |
- #'+ if (isTRUE(any_transformer_failed())) { |
||
117 | -+ | |||
283 | +6x |
- #' module_2 <- module(+ shinyjs::hide("teal_module_ui") |
||
118 | -+ | |||
284 | +6x |
- #' label = "another module",+ shinyjs::hide("validate_datanames") |
||
119 | -+ | |||
285 | +6x |
- #' server = function(id) {+ shinyjs::show("transformer_failure_info") |
||
120 | +286 |
- #' moduleServer(+ } else { |
||
121 | -+ | |||
287 | +75x |
- #' id,+ shinyjs::show("teal_module_ui") |
||
122 | -+ | |||
288 | +75x |
- #' module = function(input, output, session) {+ shinyjs::show("validate_datanames") |
||
123 | -+ | |||
289 | +75x |
- #' output$text <- renderText("Another Module")+ shinyjs::hide("transformer_failure_info") |
||
124 | +290 |
- #' }+ } |
||
125 | +291 |
- #' )+ }) |
||
126 | +292 |
- #' },+ |
||
127 | -+ | |||
293 | +81x |
- #' ui = function(id) {+ module_teal_data <- reactive({ |
||
128 | -+ | |||
294 | +89x |
- #' ns <- NS(id)+ req(inherits(transformed_teal_data(), "teal_data")) |
||
129 | -+ | |||
295 | +83x |
- #' tagList(textOutput(ns("text")))+ all_teal_data <- transformed_teal_data() |
||
130 | -+ | |||
296 | +83x |
- #' },+ module_datanames <- .resolve_module_datanames(data = all_teal_data, modules = modules) |
||
131 | -+ | |||
297 | +83x |
- #' datanames = NULL+ .subset_teal_data(all_teal_data, module_datanames) |
||
132 | +298 |
- #' )+ }) |
||
133 | +299 |
- #'+ |
||
134 | -+ | |||
300 | +81x |
- #' modules <- modules(+ srv_validate_reactive_teal_data( |
||
135 | -+ | |||
301 | +81x |
- #' label = "modules",+ "validate_datanames", |
||
136 | -+ | |||
302 | +81x |
- #' modules(+ data = module_teal_data, |
||
137 | -+ | |||
303 | +81x |
- #' label = "nested modules",+ modules = modules |
||
138 | +304 |
- #' module_1+ ) |
||
139 | +305 |
- #' ),+ |
||
140 | -+ | |||
306 | +81x |
- #' module_2+ summary_table <- srv_data_summary("data_summary", module_teal_data) |
||
141 | +307 |
- #' )+ |
||
142 | +308 |
- #'+ # Call modules. |
||
143 | -+ | |||
309 | +81x |
- #' app <- init(+ if (!inherits(modules, "teal_module_previewer")) { |
||
144 | -+ | |||
310 | +81x |
- #' data = teal_data(iris = iris),+ obs_module <- call_once_when( |
||
145 | -+ | |||
311 | +81x |
- #' modules = modules+ !is.null(module_teal_data()), |
||
146 | -+ | |||
312 | +81x |
- #' )+ ignoreNULL = TRUE, |
||
147 | -+ | |||
313 | +81x |
- #'+ handlerExpr = { |
||
148 | -+ | |||
314 | +75x |
- #' if (interactive()) {+ module_out(.call_teal_module(modules, datasets, module_teal_data, reporter)) |
||
149 | +315 |
- #' shinyApp(app$ui, app$server)+ } |
||
150 | +316 |
- #' }+ ) |
||
151 | +317 |
- #' @rdname teal_modules+ } else { |
||
152 | +318 |
- #' @export+ # Report previewer must be initiated on app start for report cards to be included in bookmarks. |
||
153 | +319 |
- #'+ # When previewer is delayed, cards are bookmarked only if previewer has been initiated (visited). |
||
154 | -+ | |||
320 | +! |
- module <- function(label = "module",+ module_out(.call_teal_module(modules, datasets, module_teal_data, reporter)) |
||
155 | +321 |
- server = function(id, data, ...) moduleServer(id, function(input, output, session) NULL),+ } |
||
156 | +322 |
- ui = function(id, ...) tags$p(paste0("This module has no UI (id: ", id, " )")),+ |
||
157 | +323 |
- filters,+ # todo: (feature request) add a ReporterCard to the reporter as an output from the teal_module |
||
158 | +324 |
- datanames = "all",+ # how to determine if module returns a ReporterCard so that reportPreviewer is needed? |
||
159 | +325 |
- server_args = NULL,+ # Should we insertUI of the ReportPreviewer then? |
||
160 | +326 |
- ui_args = NULL,+ # What about attr(module, "reportable") - similar to attr(module, "bookmarkable") |
||
161 | -+ | |||
327 | +81x |
- transformers = list()) {+ if ("report" %in% names(module_out)) { |
||
162 | +328 |
- # argument checking (independent)+ # (reactively) add card to the reporter |
||
163 | +329 |
- ## `label`- |
- ||
164 | -213x | -
- checkmate::assert_string(label)- |
- ||
165 | -210x | -
- if (label == "global_filters") {- |
- ||
166 | -1x | -
- stop(- |
- ||
167 | -1x | -
- sprintf("module(label = \"%s\", ...\n ", label),- |
- ||
168 | -1x | -
- "Label 'global_filters' is reserved in teal. Please change to something else.",- |
- ||
169 | -1x | -
- call. = FALSE+ } |
||
170 | +330 |
- )+ }) |
||
171 | +331 |
- }+ |
||
172 | -209x | -
- if (label == "Report previewer") {- |
- ||
173 | -! | -
- stop(- |
- ||
174 | -! | -
- sprintf("module(label = \"%s\", ...\n ", label),- |
- ||
175 | -! | -
- "Label 'Report previewer' is reserved in teal. Please change to something else.",- |
- ||
176 | -! | +332 | +107x |
- call. = FALSE+ module_out |
177 | +333 |
- )+ }) |
||
178 | +334 |
- }+ } |
||
179 | +335 | |||
180 | +336 |
- ## server+ # This function calls a module server function. |
||
181 | -209x | +|||
337 | +
- checkmate::assert_function(server)+ .call_teal_module <- function(modules, datasets, filtered_teal_data, reporter) { |
|||
182 | -209x | +|||
338 | +
- server_formals <- names(formals(server))+ # collect arguments to run teal_module |
|||
183 | -209x | +339 | +75x |
- if (!(+ args <- c(list(id = "module"), modules$server_args) |
184 | -209x | +340 | +75x |
- "id" %in% server_formals ||+ if (is_arg_used(modules$server, "reporter")) { |
185 | -209x | +341 | +1x |
- all(c("input", "output", "session") %in% server_formals)+ args <- c(args, list(reporter = reporter)) |
186 | +342 |
- )) {- |
- ||
187 | -2x | -
- stop(- |
- ||
188 | -2x | -
- "\nmodule() `server` argument requires a function with following arguments:",+ } |
||
189 | -2x | +|||
343 | +
- "\n - id - `teal` will set proper `shiny` namespace for this module.",+ |
|||
190 | -2x | +344 | +75x |
- "\n - input, output, session (not recommended) - then `shiny::callModule` will be used to call a module.",+ if (is_arg_used(modules$server, "datasets")) { |
191 | -2x | +345 | +1x |
- "\n\nFollowing arguments can be used optionaly:",+ args <- c(args, datasets = datasets()) |
192 | -2x | +346 | +1x |
- "\n - `data` - module will receive list of reactive (filtered) data specified in the `filters` argument",+ warning("datasets argument is not reactive and therefore it won't be updated when data is refreshed.") |
193 | -2x | +|||
347 | +
- "\n - `datasets` - module will receive `FilteredData`. See `help(teal.slice::FilteredData)`",+ } |
|||
194 | -2x | +|||
348 | +
- "\n - `reporter` - module will receive `Reporter`. See `help(teal.reporter::Reporter)`",+ |
|||
195 | -2x | +349 | +75x |
- "\n - `filter_panel_api` - module will receive `FilterPanelAPI`. (See [teal.slice::FilterPanelAPI]).",+ if (is_arg_used(modules$server, "data")) { |
196 | -2x | +350 | +71x |
- "\n - `...` server_args elements will be passed to the module named argument or to the `...`"+ args <- c(args, data = list(filtered_teal_data)) |
197 | +351 |
- )+ } |
||
198 | +352 |
- }+ |
||
199 | -207x | +353 | +75x |
- if ("datasets" %in% server_formals) {+ if (is_arg_used(modules$server, "filter_panel_api")) { |
200 | -2x | +354 | +1x |
- warning(+ args <- c(args, filter_panel_api = teal.slice::FilterPanelAPI$new(datasets())) |
201 | -2x | +|||
355 | +
- sprintf("Called from module(label = \"%s\", ...)\n ", label),+ } |
|||
202 | -2x | +|||
356 | +
- "`datasets` argument in the server is deprecated and will be removed in the next release. ",+ |
|||
203 | -2x | +357 | +75x |
- "Please use `data` instead.",+ if (is_arg_used(modules$server, "id")) { |
204 | -2x | +358 | +75x |
- call. = FALSE+ do.call(modules$server, args) |
205 | +359 |
- )+ } else {+ |
+ ||
360 | +! | +
+ do.call(callModule, c(args, list(module = modules$server))) |
||
206 | +361 |
} |
||
207 | +362 |
-
+ } |
||
208 | +363 | |||
209 | +364 |
- ## UI- |
- ||
210 | -207x | -
- checkmate::assert_function(ui)+ .resolve_module_datanames <- function(data, modules) { |
||
211 | -207x | +365 | +167x |
- ui_formals <- names(formals(ui))+ stopifnot("data_rv must be teal_data object." = inherits(data, "teal_data")) |
212 | -207x | +366 | +167x |
- if (!"id" %in% ui_formals) {+ if (is.null(modules$datanames) || identical(modules$datanames, "all")) { |
213 | -1x | +367 | +135x |
- stop(+ names(data) |
214 | -1x | +|||
368 | +
- "\nmodule() `ui` argument requires a function with following arguments:",+ } else { |
|||
215 | -1x | +369 | +32x |
- "\n - id - `teal` will set proper `shiny` namespace for this module.",+ intersect( |
216 | -1x | +370 | +32x |
- "\n\nFollowing arguments can be used optionally:",+ names(data), # Keep topological order from teal.data::names() |
217 | -1x | +371 | +32x |
- "\n - `...` ui_args elements will be passed to the module argument of the same name or to the `...`"+ .include_parent_datanames(modules$datanames, teal.data::join_keys(data)) |
218 | +372 |
) |
||
219 | +373 |
} |
||
220 | -206x | +|||
374 | +
- if (any(c("data", "datasets") %in% ui_formals)) {+ } |
|||
221 | -2x | +|||
375 | +
- stop(+ |
|||
222 | -2x | +|||
376 | +
- sprintf("Called from module(label = \"%s\", ...)\n ", label),+ #' Calls expression when condition is met |
|||
223 | -2x | +|||
377 | +
- "UI with `data` or `datasets` argument is no longer accepted.\n ",+ #' |
|||
224 | -2x | +|||
378 | +
- "If some UI inputs depend on data, please move the logic to your server instead.\n ",+ #' Function postpones `handlerExpr` to the moment when `eventExpr` (condition) returns `TRUE`, |
|||
225 | -2x | +|||
379 | +
- "Possible solutions are renderUI() or updateXyzInput() functions."+ #' otherwise nothing happens. |
|||
226 | +380 |
- )+ #' @param eventExpr A (quoted or unquoted) logical expression that represents the event; |
||
227 | +381 |
- }+ #' this can be a simple reactive value like input$click, a call to a reactive expression |
||
228 | +382 |
-
+ #' like dataset(), or even a complex expression inside curly braces. |
||
229 | +383 |
-
+ #' @param ... additional arguments passed to `observeEvent` with the exception of `eventExpr` that is not allowed. |
||
230 | +384 |
- ## `filters`+ #' @inheritParams shiny::observeEvent |
||
231 | -204x | +|||
385 | +
- if (!missing(filters)) {+ #' |
|||
232 | -! | +|||
386 | +
- datanames <- filters+ #' @return An observer. |
|||
233 | -! | +|||
387 | +
- msg <-+ #' |
|||
234 | -! | +|||
388 | +
- "The `filters` argument is deprecated and will be removed in the next release. Please use `datanames` instead."+ #' @keywords internal |
|||
235 | -! | +|||
389 | +
- warning(msg)+ call_once_when <- function(eventExpr, # nolint: object_name. |
|||
236 | +390 |
- }+ handlerExpr, # nolint: object_name. |
||
237 | +391 |
-
+ event.env = parent.frame(), # nolint: object_name. |
||
238 | +392 |
- ## `datanames` (also including deprecated `filters`)+ handler.env = parent.frame(), # nolint: object_name. |
||
239 | +393 |
- # please note a race condition between datanames set when filters is not missing and data arg in server function+ ...) { |
||
240 | -204x | +394 | +188x |
- if (!is.element("data", server_formals) && !is.null(datanames)) {+ event_quo <- rlang::new_quosure(substitute(eventExpr), env = event.env) |
241 | -12x | +395 | +188x |
- message(sprintf("module \"%s\" server function takes no data so \"datanames\" will be ignored", label))+ handler_quo <- rlang::new_quosure(substitute(handlerExpr), env = handler.env) |
242 | -12x | +|||
396 | +
- datanames <- NULL+ |
|||
243 | +397 |
- }+ # When `condExpr` is TRUE, then `handlerExpr` is evaluated once. |
||
244 | -204x | +398 | +188x |
- checkmate::assert_character(datanames, min.len = 1, null.ok = TRUE, any.missing = FALSE)+ activator <- reactive({+ |
+
399 | +188x | +
+ if (isTRUE(rlang::eval_tidy(event_quo))) {+ |
+ ||
400 | +156x | +
+ TRUE |
||
245 | +401 |
-
+ } |
||
246 | +402 |
- ## `server_args`+ }) |
||
247 | -203x | +|||
403 | +
- checkmate::assert_list(server_args, null.ok = TRUE, names = "named")+ |
|||
248 | -201x | +404 | +188x |
- srv_extra_args <- setdiff(names(server_args), server_formals)+ observeEvent( |
249 | -201x | +405 | +188x |
- if (length(srv_extra_args) > 0 && !"..." %in% server_formals) {+ eventExpr = activator(), |
250 | -1x | +406 | +188x |
- stop(+ once = TRUE, |
251 | -1x | +407 | +188x |
- "\nFollowing `server_args` elements have no equivalent in the formals of the server:\n",+ handlerExpr = rlang::eval_tidy(handler_quo), |
252 | -1x | +|||
408 | +
- paste(paste(" -", srv_extra_args), collapse = "\n"),+ ... |
|||
253 | -1x | +|||
409 | +
- "\n\nUpdate the server arguments by including above or add `...`"+ ) |
|||
254 | +410 |
- )+ } |
255 | +1 |
- }+ #' Get client timezone |
||
256 | +2 |
-
+ #' |
||
257 | +3 |
- ## `ui_args`+ #' User timezone in the browser may be different to the one on the server. |
||
258 | -200x | +|||
4 | +
- checkmate::assert_list(ui_args, null.ok = TRUE, names = "named")+ #' This script can be run to register a `shiny` input which contains information about the timezone in the browser. |
|||
259 | -198x | +|||
5 | +
- ui_extra_args <- setdiff(names(ui_args), ui_formals)+ #' |
|||
260 | -198x | +|||
6 | +
- if (length(ui_extra_args) > 0 && !"..." %in% ui_formals) {+ #' @param ns (`function`) namespace function passed from the `session` object in the `shiny` server. |
|||
261 | -1x | +|||
7 | +
- stop(+ #' For `shiny` modules this will allow for proper name spacing of the registered input. |
|||
262 | -1x | +|||
8 | +
- "\nFollowing `ui_args` elements have no equivalent in the formals of UI:\n",+ #' |
|||
263 | -1x | +|||
9 | +
- paste(paste(" -", ui_extra_args), collapse = "\n"),+ #' @return `NULL`, invisibly. |
|||
264 | -1x | +|||
10 | +
- "\n\nUpdate the UI arguments by including above or add `...`"+ #' |
|||
265 | +11 |
- )+ #' @keywords internal |
||
266 | +12 |
- }+ #' |
||
267 | +13 |
-
+ get_client_timezone <- function(ns) { |
||
268 | -+ | |||
14 | +83x |
- ## `transformers`+ script <- sprintf( |
||
269 | -197x | +15 | +83x |
- if (inherits(transformers, "teal_transform_module")) {+ "Shiny.setInputValue(`%s`, Intl.DateTimeFormat().resolvedOptions().timeZone)", |
270 | -1x | +16 | +83x |
- transformers <- list(transformers)+ ns("timezone") |
271 | +17 |
- }+ ) |
||
272 | -197x | +18 | +83x |
- checkmate::assert_list(transformers, types = "teal_transform_module")+ shinyjs::runjs(script) # function does not return anything |
273 | -197x | +19 | +83x |
- transformer_datanames <- unlist(lapply(transformers, attr, "datanames"))+ invisible(NULL) |
274 | -197x | +|||
20 | +
- combined_datanames <- if (identical(datanames, "all")) {+ } |
|||
275 | -144x | +|||
21 | +
- "all"+ |
|||
276 | +22 |
- } else {+ #' Resolve the expected bootstrap theme |
||
277 | -53x | +|||
23 | +
- union(datanames, transformer_datanames)+ #' @noRd |
|||
278 | +24 |
- }+ #' @keywords internal |
||
279 | +25 |
-
+ get_teal_bs_theme <- function() { |
||
280 | -197x | +26 | +4x |
- structure(+ bs_theme <- getOption("teal.bs_theme") |
281 | -197x | +|||
27 | +
- list(+ |
|||
282 | -197x | +28 | +4x |
- label = label,+ if (is.null(bs_theme)) { |
283 | -197x | +29 | +1x |
- server = server,+ return(NULL)+ |
+
30 | ++ |
+ }+ |
+ ||
31 | ++ | + | ||
284 | -197x | +32 | +3x |
- ui = ui,+ if (!checkmate::test_class(bs_theme, "bs_theme")) { |
285 | -197x | +33 | +2x |
- datanames = combined_datanames,+ warning( |
286 | -197x | +34 | +2x |
- server_args = server_args,+ "Assertion on 'teal.bs_theme' option value failed: ", |
287 | -197x | +35 | +2x |
- ui_args = ui_args,+ checkmate::check_class(bs_theme, "bs_theme"), |
288 | -197x | +36 | +2x |
- transformers = transformers+ ". The default Shiny Bootstrap theme will be used." |
289 | +37 |
- ),+ ) |
||
290 | -197x | +38 | +2x |
- class = "teal_module"+ return(NULL) |
291 | +39 |
- )+ } |
||
292 | +40 | ++ | + + | +|
41 | +1x | +
+ bs_theme+ |
+ ||
42 |
} |
|||
293 | +43 | |||
294 | +44 |
- #' @rdname teal_modules+ #' Return parentnames along with datanames. |
||
295 | +45 |
- #' @export+ #' @noRd |
||
296 | +46 |
- #'+ #' @keywords internal |
||
297 | +47 |
- modules <- function(..., label = "root") {+ .include_parent_datanames <- function(datanames, join_keys) { |
||
298 | -137x | +48 | +32x |
- checkmate::assert_string(label)+ ordered_datanames <- datanames |
299 | -135x | +49 | +32x |
- submodules <- list(...)+ for (current in datanames) { |
300 | -135x | +50 | +62x |
- if (any(vapply(submodules, is.character, FUN.VALUE = logical(1)))) {+ parents <- character(0L) |
301 | -2x | +51 | +62x |
- stop(+ while (length(current) > 0) { |
302 | -2x | +52 | +64x |
- "The only character argument to modules() must be 'label' and it must be named, ",+ current <- teal.data::parent(join_keys, current) |
303 | -2x | +53 | +64x |
- "change modules('lab', ...) to modules(label = 'lab', ...)"+ parents <- c(current, parents) |
304 | +54 |
- )+ }+ |
+ ||
55 | +62x | +
+ ordered_datanames <- c(parents, ordered_datanames) |
||
305 | +56 |
} |
||
306 | +57 | |||
307 | -133x | +58 | +32x |
- checkmate::assert_list(submodules, min.len = 1, any.missing = FALSE, types = c("teal_module", "teal_modules"))+ unique(ordered_datanames) |
308 | +59 |
- # name them so we can more easily access the children+ } |
||
309 | +60 |
- # beware however that the label of the submodules should not be changed as it must be kept synced+ |
||
310 | -130x | +|||
61 | +
- labels <- vapply(submodules, function(submodule) submodule$label, character(1))+ #' Create a `FilteredData` |
|||
311 | -130x | +|||
62 | +
- names(submodules) <- get_unique_labels(labels)+ #' |
|||
312 | -130x | +|||
63 | +
- structure(+ #' Create a `FilteredData` object from a `teal_data` object. |
|||
313 | -130x | +|||
64 | +
- list(+ #' |
|||
314 | -130x | +|||
65 | +
- label = label,+ #' @param x (`teal_data`) object |
|||
315 | -130x | +|||
66 | +
- children = submodules+ #' @param datanames (`character`) vector of data set names to include; must be subset of `names(x)` |
|||
316 | +67 |
- ),+ #' @return A `FilteredData` object. |
||
317 | -130x | +|||
68 | +
- class = "teal_modules"+ #' @keywords internal |
|||
318 | +69 |
- )+ teal_data_to_filtered_data <- function(x, datanames = names(x)) { |
||
319 | -+ | |||
70 | +78x |
- }+ checkmate::assert_class(x, "teal_data") |
||
320 | -+ | |||
71 | +78x |
-
+ checkmate::assert_character(datanames, min.chars = 1L, any.missing = FALSE) |
||
321 | +72 |
- # printing methods ----+ # Otherwise, FilteredData will be created in the modules' scope later |
||
322 | -+ | |||
73 | +78x |
-
+ teal.slice::init_filtered_data( |
||
323 | -+ | |||
74 | +78x |
- #' @rdname teal_modules+ x = Filter(length, sapply(datanames, function(dn) x[[dn]], simplify = FALSE)), |
||
324 | -+ | |||
75 | +78x |
- #' @param is_last (`logical(1)`) Whether this is the last item in its parent's children list.+ join_keys = teal.data::join_keys(x) |
||
325 | +76 |
- #' Affects the tree branch character used (L- vs |-)+ ) |
||
326 | +77 |
- #' @param parent_prefix (`character(1)`) The prefix inherited from parent nodes,+ } |
||
327 | +78 |
- #' used to maintain the tree structure in nested levels+ |
||
328 | +79 |
- #' @param is_root (`logical(1)`) Whether this is the root node of the tree. Only used in+ |
||
329 | +80 |
- #' format.teal_modules(). Determines whether to show "TEAL ROOT" header+ #' Template function for `TealReportCard` creation and customization |
||
330 | +81 |
- #' @param what (`character`) Specifies which metadata to display.+ #' |
||
331 | +82 |
- #' Possible values: "datasets", "properties", "ui_args", "server_args", "transformers"+ #' This function generates a report card with a title, |
||
332 | +83 |
- #' @examples+ #' an optional description, and the option to append the filter state list. |
||
333 | +84 |
- #' mod <- module(+ #' |
||
334 | +85 |
- #' label = "My Custom Module",+ #' @param title (`character(1)`) title of the card (unless overwritten by label) |
||
335 | +86 |
- #' server = function(id, data, ...) {},+ #' @param label (`character(1)`) label provided by the user when adding the card |
||
336 | +87 |
- #' ui = function(id, ...) {},+ #' @param description (`character(1)`) optional, additional description |
||
337 | +88 |
- #' datanames = c("ADSL", "ADTTE"),+ #' @param with_filter (`logical(1)`) flag indicating to add filter state |
||
338 | +89 |
- #' transformers = list(),+ #' @param filter_panel_api (`FilterPanelAPI`) object with API that allows the generation |
||
339 | +90 |
- #' ui_args = list(a = 1, b = "b"),+ #' of the filter state in the report |
||
340 | +91 |
- #' server_args = list(x = 5, y = list(p = 1))+ #' |
||
341 | +92 |
- #' )+ #' @return (`TealReportCard`) populated with a title, description and filter state. |
||
342 | +93 |
- #' cat(format(mod))+ #' |
||
343 | +94 |
#' @export |
||
344 | -- |
- format.teal_module <- function(- |
- ||
345 | +95 |
- x, indent = 0, is_last = FALSE, parent_prefix = "",+ report_card_template <- function(title, label, description = NULL, with_filter, filter_panel_api) { |
||
346 | -+ | |||
96 | +2x |
- what = c("datasets", "properties", "ui_args", "server_args", "transformers"), ...) {+ checkmate::assert_string(title) |
||
347 | -3x | +97 | +2x |
- empty_text <- ""+ checkmate::assert_string(label) |
348 | -3x | +98 | +2x |
- branch <- if (is_last) "L-" else "|-"+ checkmate::assert_string(description, null.ok = TRUE) |
349 | -3x | +99 | +2x |
- current_prefix <- paste0(parent_prefix, branch, " ")+ checkmate::assert_flag(with_filter) |
350 | -3x | +100 | +2x |
- content_prefix <- paste0(parent_prefix, if (is_last) " " else "| ")+ checkmate::assert_class(filter_panel_api, classes = "FilterPanelAPI") |
351 | +101 | |||
352 | -3x | +102 | +2x |
- format_list <- function(lst, empty = empty_text, label_width = 0) {+ card <- teal::TealReportCard$new() |
353 | -6x | +103 | +2x |
- if (is.null(lst) || length(lst) == 0) {+ title <- if (label == "") title else label |
354 | -6x | -
- empty- |
- ||
355 | -- |
- } else {- |
- ||
356 | -! | -
- colon_space <- paste(rep(" ", label_width), collapse = "")- |
- ||
357 | -- | - - | -||
358 | -! | +104 | +2x |
- first_item <- sprintf("%s (%s)", names(lst)[1], crayon::silver(class(lst[[1]])[1]))+ card$set_name(title) |
359 | -! | +|||
105 | +2x |
- rest_items <- if (length(lst) > 1) {+ card$append_text(title, "header2") |
||
360 | -! | +|||
106 | +1x |
- paste(+ if (!is.null(description)) card$append_text(description, "header3") |
||
361 | -! | +|||
107 | +1x |
- vapply(+ if (with_filter) card$append_fs(filter_panel_api$get_filter_state()) |
||
362 | -! | +|||
108 | +2x |
- names(lst)[-1],+ card |
||
363 | -! | +|||
109 | +
- function(name) {+ } |
|||
364 | -! | +|||
110 | +
- sprintf(+ |
|||
365 | -! | +|||
111 | +
- "%s%s (%s)",+ |
|||
366 | -! | +|||
112 | +
- paste0(content_prefix, "| ", colon_space),+ #' Check `datanames` in modules |
|||
367 | -! | +|||
113 | +
- name,+ #' |
|||
368 | -! | +|||
114 | +
- crayon::silver(class(lst[[name]])[1])+ #' These functions check if specified `datanames` in modules match those in the data object, |
|||
369 | +115 |
- )+ #' returning error messages or `TRUE` for successful validation. Two functions return error message |
||
370 | +116 |
- },+ #' in different forms: |
||
371 | -! | +|||
117 | +
- character(1)+ #' - `check_modules_datanames` returns `character(1)` for basic assertion usage |
|||
372 | +118 |
- ),+ #' - `check_modules_datanames_html` returns `shiny.tag.list` to display it in the app. |
||
373 | -! | +|||
119 | +
- collapse = "\n"+ #' |
|||
374 | +120 |
- )+ #' @param modules (`teal_modules`) object |
||
375 | +121 |
- }+ #' @param datanames (`character`) names of datasets available in the `data` object |
||
376 | -! | +|||
122 | +
- if (length(lst) > 1) paste0(first_item, "\n", rest_items) else first_item+ #' |
|||
377 | +123 |
- }+ #' @return `TRUE` if validation passes, otherwise `character(1)` or `shiny.tag.list` |
||
378 | +124 |
- }+ #' @keywords internal |
||
379 | +125 |
-
+ check_modules_datanames <- function(modules, datanames) { |
||
380 | -3x | +126 | +9x |
- bookmarkable <- isTRUE(attr(x, "teal_bookmarkable"))+ out <- check_modules_datanames_html(modules, datanames) |
381 | -3x | +127 | +9x |
- reportable <- "reporter" %in% names(formals(x$server))+ if (inherits(out, "shiny.tag.list")) { |
382 | -+ | |||
128 | +3x |
-
+ out_with_ticks <- gsub("<code>|</code>", "`", toString(out)) |
||
383 | +129 | 3x |
- transformers <- if (length(x$transformers) > 0) {+ out_text <- gsub("<[^<>]+>", "", toString(out_with_ticks)) |
|
384 | -! | +|||
130 | +3x |
- paste(sapply(x$transformers, function(t) attr(t, "label")), collapse = ", ")+ trimws(gsub("[[:space:]]+", " ", out_text)) |
||
385 | +131 |
} else { |
||
386 | -3x | +132 | +6x |
- empty_text+ out |
387 | +133 |
} |
||
388 | +134 | ++ |
+ }+ |
+ |
135 | ||||
389 | -3x | +|||
136 | +
- output <- pasten(current_prefix, crayon::bgWhite(x$label))+ #' @rdname check_modules_datanames |
|||
390 | +137 |
-
+ check_modules_datanames_html <- function(modules, |
||
391 | -3x | +|||
138 | +
- if ("datasets" %in% what) {+ datanames) { |
|||
392 | -3x | +139 | +178x |
- output <- paste0(+ check_datanames <- check_modules_datanames_recursive(modules, datanames) |
393 | -3x | +140 | +178x |
- output,+ show_module_info <- inherits(modules, "teal_modules") # used in two contexts - module and app |
394 | -3x | +141 | +178x |
- content_prefix, "|- ", crayon::yellow("Datasets : "), paste(x$datanames, collapse = ", "), "\n"+ if (!length(check_datanames)) { |
395 | -+ | |||
142 | +160x |
- )+ return(TRUE) |
||
396 | +143 |
} |
||
397 | -3x | +144 | +18x |
- if ("properties" %in% what) {+ shiny::tagList( |
398 | -3x | +145 | +18x |
- output <- paste0(+ lapply( |
399 | -3x | +146 | +18x |
- output,+ check_datanames, |
400 | -3x | +147 | +18x |
- content_prefix, "|- ", crayon::blue("Properties:"), "\n",+ function(mod) { |
401 | -3x | +148 | +18x |
- content_prefix, "| |- ", crayon::cyan("Bookmarkable : "), bookmarkable, "\n",+ tagList( |
402 | -3x | -
- content_prefix, "| L- ", crayon::cyan("Reportable : "), reportable, "\n"- |
- ||
403 | -+ | 149 | +18x |
- )+ tags$span( |
404 | -+ | |||
150 | +18x |
- }+ tags$span(if (length(mod$missing_datanames) == 1) "Dataset" else "Datasets"), |
||
405 | -3x | +151 | +18x |
- if ("ui_args" %in% what) {+ to_html_code_list(mod$missing_datanames), |
406 | -3x | +152 | +18x |
- ui_args_formatted <- format_list(x$ui_args, label_width = 19)+ tags$span( |
407 | -3x | +153 | +18x |
- output <- paste0(+ paste0( |
408 | -3x | +154 | +18x |
- output,+ if (length(mod$missing_datanames) > 1) "are missing" else "is missing", |
409 | -3x | +155 | +18x |
- content_prefix, "|- ", crayon::green("UI Arguments : "), ui_args_formatted, "\n"+ if (show_module_info) sprintf(" for module '%s'.", mod$label) else "." |
410 | +156 |
- )+ ) |
||
411 | +157 |
- }+ ) |
||
412 | -3x | +|||
158 | +
- if ("server_args" %in% what) {+ ), |
|||
413 | -3x | +159 | +18x |
- server_args_formatted <- format_list(x$server_args, label_width = 19)+ if (length(datanames) >= 1) { |
414 | -3x | +160 | +16x |
- output <- paste0(+ tagList( |
415 | -3x | +161 | +16x |
- output,+ tags$span(if (length(datanames) == 1) "Dataset" else "Datasets"), |
416 | -3x | +162 | +16x |
- content_prefix, "|- ", crayon::green("Server Arguments : "), server_args_formatted, "\n"+ tags$span("available in data:"), |
417 | -+ | |||
163 | +16x |
- )+ tagList( |
||
418 | -+ | |||
164 | +16x |
- }+ tags$span( |
||
419 | -3x | +165 | +16x |
- if ("transformers" %in% what) {+ to_html_code_list(datanames), |
420 | -3x | +166 | +16x |
- output <- paste0(+ tags$span(".", .noWS = "outside"), |
421 | -3x | +167 | +16x |
- output,+ .noWS = c("outside") |
422 | -3x | +|||
168 | +
- content_prefix, "L- ", crayon::magenta("Transformers : "), transformers, "\n"+ ) |
|||
423 | +169 |
- )+ ) |
||
424 | +170 |
- }+ ) |
||
425 | +171 |
-
+ } else { |
||
426 | -3x | +172 | +2x |
- output+ tags$span("No datasets are available in data.") |
427 | +173 |
- }+ }, |
||
428 | -+ | |||
174 | +18x |
-
+ tags$br(.noWS = "before") |
||
429 | +175 |
- #' @rdname teal_modules+ ) |
||
430 | +176 |
- #' @examples+ } |
||
431 | +177 |
- #' custom_module <- function(+ ) |
||
432 | +178 |
- #' label = "label", ui_args = NULL, server_args = NULL,+ ) |
||
433 | +179 |
- #' datanames = "all", transformers = list(), bk = FALSE) {+ } |
||
434 | +180 |
- #' ans <- module(+ |
||
435 | +181 |
- #' label,+ #' Recursively checks modules and returns list for every datanames mismatch between module and data |
||
436 | +182 |
- #' server = function(id, data, ...) {},+ #' @noRd |
||
437 | +183 |
- #' ui = function(id, ...) {+ check_modules_datanames_recursive <- function(modules, datanames) { # nolint: object_name_length |
||
438 | -+ | |||
184 | +277x |
- #' },+ checkmate::assert_multi_class(modules, c("teal_module", "teal_modules")) |
||
439 | -+ | |||
185 | +277x |
- #' datanames = datanames,+ checkmate::assert_character(datanames) |
||
440 | -+ | |||
186 | +277x |
- #' transformers = transformers,+ if (inherits(modules, "teal_modules")) { |
||
441 | -+ | |||
187 | +79x |
- #' ui_args = ui_args,+ unlist( |
||
442 | -+ | |||
188 | +79x |
- #' server_args = server_args+ lapply(modules$children, check_modules_datanames_recursive, datanames = datanames), |
||
443 | -+ | |||
189 | +79x |
- #' )+ recursive = FALSE |
||
444 | +190 |
- #' attr(ans, "teal_bookmarkable") <- bk+ ) |
||
445 | +191 |
- #' ans+ } else { |
||
446 | -+ | |||
192 | +198x |
- #' }+ missing_datanames <- setdiff(modules$datanames, c("all", datanames)) |
||
447 | -+ | |||
193 | +198x |
- #'+ if (length(missing_datanames)) { |
||
448 | -+ | |||
194 | +18x |
- #' dummy_transformer <- teal_transform_module(+ list(list( |
||
449 | -+ | |||
195 | +18x |
- #' label = "Dummy Transform",+ label = modules$label, |
||
450 | -+ | |||
196 | +18x |
- #' ui = function(id) div("(does nothing)"),+ missing_datanames = missing_datanames |
||
451 | +197 |
- #' server = function(id, data) {+ )) |
||
452 | +198 |
- #' moduleServer(id, function(input, output, session) data)+ } |
||
453 | +199 |
- #' }+ } |
||
454 | +200 |
- #' )+ } |
||
455 | +201 |
- #'+ |
||
456 | +202 |
- #' plot_transformer <- teal_transform_module(+ #' Convert character vector to html code separated with commas and "and" |
||
457 | +203 |
- #' label = "Plot Settings",+ #' @noRd |
||
458 | +204 |
- #' ui = function(id) div("(does nothing)"),+ to_html_code_list <- function(x) { |
||
459 | -+ | |||
205 | +34x |
- #' server = function(id, data) {+ checkmate::assert_character(x) |
||
460 | -+ | |||
206 | +34x |
- #' moduleServer(id, function(input, output, session) data)+ do.call( |
||
461 | -+ | |||
207 | +34x |
- #' }+ tagList, |
||
462 | -+ | |||
208 | +34x |
- #' )+ lapply(seq_along(x), function(.ix) { |
||
463 | -+ | |||
209 | +47x |
- #'+ tagList( |
||
464 | -+ | |||
210 | +47x |
- #' complete_modules <- modules(+ tags$code(x[.ix]), |
||
465 | -+ | |||
211 | +47x |
- #' custom_module(+ if (.ix != length(x)) { |
||
466 | -+ | |||
212 | +1x |
- #' label = "Data Overview",+ if (.ix == length(x) - 1) tags$span(" and ") else tags$span(", ", .noWS = "before") |
||
467 | +213 |
- #' datanames = c("ADSL", "ADAE", "ADVS"),+ } |
||
468 | +214 |
- #' ui_args = list(+ ) |
||
469 | +215 |
- #' view_type = "table",+ }) |
||
470 | +216 |
- #' page_size = 10,+ ) |
||
471 | +217 |
- #' filters = c("ARM", "SEX", "RACE")+ } |
||
472 | +218 |
- #' ),+ |
||
473 | +219 |
- #' server_args = list(+ |
||
474 | +220 |
- #' cache = TRUE,+ #' Check `datanames` in filters |
||
475 | +221 |
- #' debounce = 1000+ #' |
||
476 | +222 |
- #' ),+ #' This function checks whether `datanames` in filters correspond to those in `data`, |
||
477 | +223 |
- #' transformers = list(dummy_transformer),+ #' returning character vector with error messages or `TRUE` if all checks pass. |
||
478 | +224 |
- #' bk = TRUE+ #' |
||
479 | +225 |
- #' ),+ #' @param filters (`teal_slices`) object |
||
480 | +226 |
- #' modules(+ #' @param datanames (`character`) names of datasets available in the `data` object |
||
481 | +227 |
- #' label = "Nested 1",+ #' |
||
482 | +228 |
- #' custom_module(+ #' @return A `character(1)` containing error message or TRUE if validation passes. |
||
483 | +229 |
- #' label = "Interactive Plots",+ #' @keywords internal |
||
484 | +230 |
- #' datanames = c("ADSL", "ADVS"),+ check_filter_datanames <- function(filters, datanames) { |
||
485 | -+ | |||
231 | +79x |
- #' ui_args = list(+ checkmate::assert_class(filters, "teal_slices") |
||
486 | -+ | |||
232 | +79x |
- #' plot_type = c("scatter", "box", "line"),+ checkmate::assert_character(datanames) |
||
487 | +233 |
- #' height = 600,+ |
||
488 | +234 |
- #' width = 800,+ # check teal_slices against datanames |
||
489 | -+ | |||
235 | +79x |
- #' color_scheme = "viridis"+ out <- unlist(sapply( |
||
490 | -+ | |||
236 | +79x |
- #' ),+ filters, function(filter) { |
||
491 | -+ | |||
237 | +24x |
- #' server_args = list(+ dataname <- shiny::isolate(filter$dataname) |
||
492 | -+ | |||
238 | +24x |
- #' render_type = "svg",+ if (!dataname %in% datanames) { |
||
493 | -+ | |||
239 | +3x |
- #' cache_plots = TRUE+ sprintf( |
||
494 | -+ | |||
240 | +3x |
- #' ),+ "- Filter '%s' refers to dataname not available in 'data':\n %s not in (%s)", |
||
495 | -+ | |||
241 | +3x |
- #' transformers = list(dummy_transformer, plot_transformer),+ shiny::isolate(filter$id), |
||
496 | -+ | |||
242 | +3x |
- #' bk = TRUE+ dQuote(dataname, q = FALSE), |
||
497 | -+ | |||
243 | +3x |
- #' ),+ toString(dQuote(datanames, q = FALSE)) |
||
498 | +244 |
- #' modules(+ ) |
||
499 | +245 |
- #' label = "Nested 2",+ } |
||
500 | +246 |
- #' custom_module(+ } |
||
501 | +247 |
- #' label = "Summary Statistics",+ )) |
||
502 | +248 |
- #' datanames = "ADSL",+ |
||
503 | +249 |
- #' ui_args = list(+ |
||
504 | -+ | |||
250 | +79x |
- #' stats = c("mean", "median", "sd", "range"),+ if (length(out)) { |
||
505 | -+ | |||
251 | +3x |
- #' grouping = c("ARM", "SEX")+ paste(out, collapse = "\n") |
||
506 | +252 |
- #' )+ } else { |
||
507 | -+ | |||
253 | +76x |
- #' ),+ TRUE |
||
508 | +254 |
- #' modules(+ } |
||
509 | +255 |
- #' label = "Labeled nested modules",+ } |
||
510 | +256 |
- #' custom_module(+ |
||
511 | +257 |
- #' label = "Subgroup Analysis",+ #' Function for validating the title parameter of `teal::init` |
||
512 | +258 |
- #' datanames = c("ADSL", "ADAE"),+ #' |
||
513 | +259 |
- #' ui_args = list(+ #' Checks if the input of the title from `teal::init` will create a valid title and favicon tag. |
||
514 | +260 |
- #' subgroups = c("AGE", "SEX", "RACE"),+ #' @param shiny_tag (`shiny.tag`) Object to validate for a valid title. |
||
515 | +261 |
- #' analysis_type = "stratified"+ #' @keywords internal |
||
516 | +262 |
- #' ),+ validate_app_title_tag <- function(shiny_tag) {+ |
+ ||
263 | +7x | +
+ checkmate::assert_class(shiny_tag, "shiny.tag")+ |
+ ||
264 | +7x | +
+ checkmate::assert_true(shiny_tag$name == "head")+ |
+ ||
265 | +6x | +
+ child_names <- vapply(shiny_tag$children, `[[`, character(1L), "name")+ |
+ ||
266 | +6x | +
+ checkmate::assert_subset(c("title", "link"), child_names, .var.name = "child tags")+ |
+ ||
267 | +4x | +
+ rel_attr <- shiny_tag$children[[which(child_names == "link")]]$attribs$rel+ |
+ ||
268 | +4x | +
+ checkmate::assert_subset(+ |
+ ||
269 | +4x | +
+ rel_attr,+ |
+ ||
270 | +4x | +
+ c("icon", "shortcut icon"),+ |
+ ||
271 | +4x | +
+ .var.name = "Link tag's rel attribute",+ |
+ ||
272 | +4x | +
+ empty.ok = FALSE |
||
517 | +273 |
- #' bk = TRUE+ ) |
||
518 | +274 |
- #' )+ } |
||
519 | +275 |
- #' ),+ |
||
520 | +276 |
- #' modules(custom_module(label = "Subgroup Analysis in non-labled modules"))+ #' Build app title with favicon |
||
521 | +277 |
- #' )+ #' |
||
522 | +278 |
- #' ),+ #' A helper function to create the browser title along with a logo. |
||
523 | +279 |
- #' custom_module("Non-nested module")+ #' |
||
524 | +280 |
- #' )+ #' @param title (`character`) The browser title for the `teal` app. |
||
525 | +281 |
- #'+ #' @param favicon (`character`) The path for the icon for the title. |
||
526 | +282 |
- #' cat(format(complete_modules))+ #' The image/icon path can be remote or the static path accessible by `shiny`, like the `www/` |
||
527 | +283 |
- #' cat(format(complete_modules, what = c("ui_args", "server_args", "transformers")))+ #' |
||
528 | +284 | ++ |
+ #' @return A `shiny.tag` containing the element that adds the title and logo to the `shiny` app.+ |
+ |
285 |
#' @export |
|||
529 | +286 |
- format.teal_modules <- function(x, indent = 0, is_root = TRUE, is_last = FALSE, parent_prefix = "", ...) {+ build_app_title <- function( |
||
530 | -1x | +|||
287 | +
- if (is_root) {+ title = "teal app", |
|||
531 | -1x | +|||
288 | +
- header <- pasten(crayon::bold("TEAL ROOT"))+ favicon = "https://raw.githubusercontent.com/insightsengineering/hex-stickers/main/PNG/nest.png") { |
|||
532 | -1x | +289 | +13x |
- new_parent_prefix <- " " #' Initial indent for root level+ checkmate::assert_string(title, null.ok = TRUE) |
533 | -+ | |||
290 | +13x |
- } else {+ checkmate::assert_string(favicon, null.ok = TRUE) |
||
534 | -! | +|||
291 | +13x |
- if (!is.null(x$label)) {+ tags$head( |
||
535 | -! | +|||
292 | +13x |
- branch <- if (is_last) "L-" else "|-"+ tags$title(title), |
||
536 | -! | +|||
293 | +13x |
- header <- pasten(parent_prefix, branch, " ", crayon::bold(x$label))+ tags$link( |
||
537 | -! | +|||
294 | +13x |
- new_parent_prefix <- paste0(parent_prefix, if (is_last) " " else "| ")+ rel = "icon", |
||
538 | -+ | |||
295 | +13x |
- } else {+ href = favicon, |
||
539 | -! | +|||
296 | +13x |
- header <- ""+ sizes = "any" |
||
540 | -! | +|||
297 | +
- new_parent_prefix <- parent_prefix+ ) |
|||
541 | +298 |
- }+ ) |
||
542 | +299 |
- }+ } |
||
543 | +300 | |||
544 | -1x | +|||
301 | +
- if (length(x$children) > 0) {+ #' Application ID |
|||
545 | -1x | +|||
302 | +
- children_output <- character(0)+ #' |
|||
546 | -1x | +|||
303 | +
- n_children <- length(x$children)+ #' Creates App ID used to match filter snapshots to application. |
|||
547 | +304 |
-
+ #' |
||
548 | -1x | +|||
305 | +
- for (i in seq_along(x$children)) {+ #' Calculate app ID that will be used to stamp filter state snapshots. |
|||
549 | -3x | +|||
306 | +
- child <- x$children[[i]]+ #' App ID is a hash of the app's data and modules. |
|||
550 | -3x | +|||
307 | +
- is_last_child <- (i == n_children)+ #' See "transferring snapshots" section in ?snapshot. |
|||
551 | +308 |
-
+ #' |
||
552 | -3x | +|||
309 | +
- if (inherits(child, "teal_modules")) {+ #' @param data (`teal_data` or `teal_data_module`) as accepted by `init` |
|||
553 | -! | +|||
310 | +
- children_output <- c(+ #' @param modules (`teal_modules`) object as accepted by `init` |
|||
554 | -! | +|||
311 | +
- children_output,+ #' |
|||
555 | -! | +|||
312 | +
- format(child,+ #' @return A single character string. |
|||
556 | -! | +|||
313 | +
- indent = indent,+ #' |
|||
557 | -! | +|||
314 | +
- is_root = FALSE,+ #' @keywords internal |
|||
558 | -! | +|||
315 | +
- is_last = is_last_child,+ create_app_id <- function(data, modules) { |
|||
559 | -! | +|||
316 | +21x |
- parent_prefix = new_parent_prefix,+ checkmate::assert_multi_class(data, c("teal_data", "teal_data_module")) |
||
560 | -+ | |||
317 | +20x |
- ...+ checkmate::assert_class(modules, "teal_modules") |
||
561 | +318 |
- )+ |
||
562 | -+ | |||
319 | +19x |
- )+ data <- if (inherits(data, "teal_data")) { |
||
563 | -+ | |||
320 | +17x |
- } else {+ as.list(data) |
||
564 | -3x | +321 | +19x |
- children_output <- c(+ } else if (inherits(data, "teal_data_module")) { |
565 | -3x | +322 | +2x |
- children_output,+ deparse1(body(data$server)) |
566 | -3x | +|||
323 | +
- format(child,+ } |
|||
567 | -3x | +324 | +19x |
- indent = indent,+ modules <- lapply(modules, defunction) |
568 | -3x | +|||
325 | +
- is_last = is_last_child,+ |
|||
569 | -3x | +326 | +19x |
- parent_prefix = new_parent_prefix,+ rlang::hash(list(data = data, modules = modules)) |
570 | +327 |
- ...+ } |
||
571 | +328 |
- )+ |
||
572 | +329 |
- )+ #' Go through list and extract bodies of encountered functions as string, recursively. |
||
573 | +330 |
- }+ #' @keywords internal |
||
574 | +331 |
- }+ #' @noRd |
||
575 | +332 |
-
+ defunction <- function(x) { |
||
576 | -1x | +333 | +229x |
- paste0(header, paste(children_output, collapse = ""))+ if (is.list(x)) {+ |
+
334 | +67x | +
+ lapply(x, defunction)+ |
+ ||
335 | +162x | +
+ } else if (is.function(x)) {+ |
+ ||
336 | +50x | +
+ deparse1(body(x)) |
||
577 | +337 |
} else { |
||
578 | -! | +|||
338 | +112x |
- header+ x |
||
579 | +339 |
} |
||
580 | +340 |
} |
||
581 | +341 | |||
582 | +342 |
- #' @rdname teal_modules+ #' Get unique labels |
||
583 | +343 |
- #' @export+ #' |
||
584 | +344 |
- print.teal_module <- function(x, ...) {- |
- ||
585 | -! | -
- cat(format(x, ...))+ #' Get unique labels for the modules to avoid namespace conflicts. |
||
586 | -! | +|||
345 | +
- invisible(x)+ #' |
|||
587 | +346 |
- }+ #' @param labels (`character`) vector of labels |
||
588 | +347 |
-
+ #' |
||
589 | +348 |
- #' @rdname teal_modules+ #' @return (`character`) vector of unique labels |
||
590 | +349 |
- #' @export+ #' |
||
591 | +350 |
- print.teal_modules <- function(x, ...) {+ #' @keywords internal |
||
592 | -! | +|||
351 | +
- cat(format(x, ...))+ get_unique_labels <- function(labels) { |
|||
593 | -! | +|||
352 | +215x |
- invisible(x)+ make.unique(gsub("[^[:alnum:]]", "_", tolower(labels)), sep = "_") |
||
594 | +353 |
} |
||
595 | +354 | |||
596 | +355 |
- #' @param modules (`teal_module` or `teal_modules`)+ #' Remove ANSI escape sequences from a string |
||
597 | +356 |
- #' @rdname teal_modules+ #' @noRd |
||
598 | +357 |
- #' @examples+ strip_style <- function(string) {+ |
+ ||
358 | +2x | +
+ checkmate::assert_string(string) |
||
599 | +359 |
- #' # change the module's datanames+ + |
+ ||
360 | +2x | +
+ gsub(+ |
+ ||
361 | +2x | +
+ "(?:(?:\\x{001b}\\[)|\\x{009b})(?:(?:[0-9]{1,3})?(?:(?:;[0-9]{0,3})*)?[A-M|f-m])|\\x{001b}[A-M]", |
||
600 | +362 |
- #' set_datanames(module(datanames = "all"), "a")+ "",+ |
+ ||
363 | +2x | +
+ string,+ |
+ ||
364 | +2x | +
+ perl = TRUE,+ |
+ ||
365 | +2x | +
+ useBytes = TRUE |
||
601 | +366 |
- #'+ ) |
||
602 | +367 |
- #' # change modules' datanames+ } |
||
603 | +368 |
- #' set_datanames(+ |
||
604 | +369 |
- #' modules(+ #' @keywords internal |
||
605 | +370 |
- #' module(datanames = "all"),+ #' @noRd+ |
+ ||
371 | +4x | +
+ pasten <- function(...) paste0(..., "\n") |
||
606 | +372 |
- #' module(datanames = "a")+ |
||
607 | +373 |
- #' ),+ #' Convert character list to human readable html with commas and "and" |
||
608 | +374 |
- #' "b"+ #' @noRd |
||
609 | +375 |
- #' )+ paste_datanames_character <- function(x, |
||
610 | +376 |
- #' @export+ tags = list(span = shiny::tags$span, code = shiny::tags$code), |
||
611 | +377 |
- set_datanames <- function(modules, datanames) {+ tagList = shiny::tagList) { # nolint: object_name. |
||
612 | +378 | ! |
- checkmate::assert_multi_class(modules, c("teal_modules", "teal_module"))+ checkmate::assert_character(x) |
|
613 | +379 | ! |
- if (inherits(modules, "teal_modules")) {+ do.call( |
|
614 | +380 | ! |
- modules$children <- lapply(modules$children, set_datanames, datanames)- |
- |
615 | -- |
- } else {+ tagList, |
||
616 | +381 | ! |
- if (identical(modules$datanames, "all")) {+ lapply(seq_along(x), function(.ix) { |
|
617 | +382 | ! |
- modules$datanames <- datanames- |
- |
618 | -- |
- } else {+ tagList( |
||
619 | +383 | ! |
- warning(+ tags$code(x[.ix]), |
|
620 | +384 | ! |
- "Not possible to modify datanames of the module ", modules$label,+ if (.ix != length(x)) { |
|
621 | +385 | ! |
- ". set_datanames() can only change datanames if it was set to \"all\".",+ tags$span(ifelse(.ix == length(x) - 1, " and ", ", ")) |
|
622 | -! | +|||
386 | +
- call. = FALSE+ } |
|||
623 | +387 |
) |
||
624 | +388 |
- }+ }) |
||
625 | +389 |
- }+ ) |
||
626 | -! | +|||
390 | +
- modules+ } |
|||
627 | +391 |
- }+ |
||
628 | +392 |
-
+ #' Build datanames error string for error message |
||
629 | +393 |
- # utilities ----+ #' |
||
630 | +394 |
- ## subset or modify modules ----+ #' tags and tagList are overwritten in arguments allowing to create strings for |
||
631 | +395 |
-
+ #' logging purposes |
||
632 | +396 |
- #' Append a `teal_module` to `children` of a `teal_modules` object+ #' @noRd |
||
633 | +397 |
- #' @keywords internal+ build_datanames_error_message <- function(label = NULL, |
||
634 | +398 |
- #' @param modules (`teal_modules`)+ datanames, |
||
635 | +399 |
- #' @param module (`teal_module`) object to be appended onto the children of `modules`+ extra_datanames, |
||
636 | +400 |
- #' @return A `teal_modules` object with `module` appended.+ tags = list(span = shiny::tags$span, code = shiny::tags$code), |
||
637 | +401 |
- append_module <- function(modules, module) {+ tagList = shiny::tagList) { # nolint: object_name. |
||
638 | -8x | +|||
402 | +! |
- checkmate::assert_class(modules, "teal_modules")+ tags$span( |
||
639 | -6x | +|||
403 | +! |
- checkmate::assert_class(module, "teal_module")+ tags$span(ifelse(length(extra_datanames) > 1, "Datasets", "Dataset")), |
||
640 | -4x | +|||
404 | +! |
- modules$children <- c(modules$children, list(module))+ paste_datanames_character(extra_datanames, tags, tagList), |
||
641 | -4x | +|||
405 | +! |
- labels <- vapply(modules$children, function(submodule) submodule$label, character(1))+ tags$span( |
||
642 | -4x | +|||
406 | +! |
- names(modules$children) <- get_unique_labels(labels)+ paste0( |
||
643 | -4x | +|||
407 | +! |
- modules+ ifelse(length(extra_datanames) > 1, "are missing", "is missing"), |
||
644 | -+ | |||
408 | +! |
- }+ ifelse(is.null(label), ".", sprintf(" for tab '%s'.", label)) |
||
645 | +409 |
-
+ ) |
||
646 | +410 |
- #' Extract/Remove module(s) of specific class+ ), |
||
647 | -+ | |||
411 | +! |
- #'+ if (length(datanames) >= 1) { |
||
648 | -+ | |||
412 | +! |
- #' Given a `teal_module` or a `teal_modules`, return the elements of the structure according to `class`.+ tagList( |
||
649 | -+ | |||
413 | +! |
- #'+ tags$span(ifelse(length(datanames) > 1, "Datasets", "Dataset")), |
||
650 | -+ | |||
414 | +! |
- #' @param modules (`teal_modules`)+ tags$span("available in data:"), |
||
651 | -+ | |||
415 | +! |
- #' @param class The class name of `teal_module` to be extracted or dropped.+ tagList( |
||
652 | -+ | |||
416 | +! |
- #' @keywords internal+ tags$span( |
||
653 | -+ | |||
417 | +! |
- #' @return+ paste_datanames_character(datanames, tags, tagList), |
||
654 | -+ | |||
418 | +! |
- #' - For `extract_module`, a `teal_module` of class `class` or `teal_modules` containing modules of class `class`.+ tags$span(".", .noWS = "outside"),+ |
+ ||
419 | +! | +
+ .noWS = c("outside") |
||
655 | +420 |
- #' - For `drop_module`, the opposite, which is all `teal_modules` of class other than `class`.+ ) |
||
656 | +421 |
- #' @rdname module_management+ ) |
||
657 | +422 |
- extract_module <- function(modules, class) {+ ) |
||
658 | -24x | +|||
423 | +
- if (inherits(modules, class)) {+ } else { |
|||
659 | +424 | ! |
- modules+ tags$span("No datasets are available in data.") |
|
660 | -24x | +|||
425 | +
- } else if (inherits(modules, "teal_module")) {+ } |
|||
661 | -13x | +|||
426 | +
- NULL+ ) |
|||
662 | -11x | +|||
427 | +
- } else if (inherits(modules, "teal_modules")) {+ } |
|||
663 | -11x | +|||
428 | +
- Filter(function(x) length(x) > 0L, lapply(modules$children, extract_module, class))+ |
|||
664 | +429 |
- }+ #' Smart `rbind` |
||
665 | +430 |
- }+ #' |
||
666 | +431 |
-
+ #' Combine `data.frame` objects which have different columns |
||
667 | +432 |
- #' @keywords internal+ #' |
||
668 | +433 |
- #' @return `teal_modules`+ #' @param ... (`data.frame`) |
||
669 | +434 |
- #' @rdname module_management+ #' @keywords internal |
||
670 | +435 |
- drop_module <- function(modules, class) {+ .smart_rbind <- function(...) { |
||
671 | -! | -
- if (inherits(modules, class)) {+ | ||
436 | +82x | +
+ dots <- list(...) |
||
672 | -! | +|||
437 | +82x |
- NULL+ checkmate::assert_list(dots, "data.frame", .var.name = "...") |
||
673 | -! | +|||
438 | +82x |
- } else if (inherits(modules, "teal_module")) {+ Reduce( |
||
674 | -! | +|||
439 | +82x |
- modules+ x = dots, |
||
675 | -! | +|||
440 | +82x |
- } else if (inherits(modules, "teal_modules")) {+ function(x, y) { |
||
676 | -! | +|||
441 | +69x |
- do.call(+ all_columns <- union(colnames(x), colnames(y)) |
||
677 | -! | +|||
442 | +69x |
- "modules",+ x[setdiff(all_columns, colnames(x))] <- NA |
||
678 | -! | +|||
443 | +69x |
- c(Filter(function(x) length(x) > 0L, lapply(modules$children, drop_module, class)), label = modules$label)+ y[setdiff(all_columns, colnames(y))] <- NA+ |
+ ||
444 | +69x | +
+ rbind(x, y) |
||
679 | +445 |
- )+ } |
||
680 | +446 |
- }+ ) |
||
681 | +447 |
} |
682 | +1 |
-
+ #' Manage multiple `FilteredData` objects |
||
683 | +2 |
- ## read modules ----+ #' |
||
684 | +3 |
-
+ #' @description |
||
685 | +4 |
- #' Does the object make use of the `arg`+ #' Oversee filter states across the entire application. |
||
686 | +5 |
#' |
||
687 | +6 |
- #' @param modules (`teal_module` or `teal_modules`) object+ #' @section Slices global: |
||
688 | +7 |
- #' @param arg (`character(1)`) names of the arguments to be checked against formals of `teal` modules.+ #' The key role in maintaining the module-specific filter states is played by the `.slicesGlobal` |
||
689 | +8 |
- #' @return `logical` whether the object makes use of `arg`.+ #' object. It is a reference class that holds the following fields: |
||
690 | +9 |
- #' @rdname is_arg_used+ #' - `all_slices` (`reactiveVal`) - reactive value containing all filters registered in an app. |
||
691 | +10 |
- #' @keywords internal+ #' - `module_slices_api` (`reactiveValues`) - reactive field containing references to each modules' |
||
692 | +11 |
- is_arg_used <- function(modules, arg) {+ #' `FilteredData` object methods. At this moment it is used only in `srv_filter_manager` to display |
||
693 | -486x | +|||
12 | +
- checkmate::assert_string(arg)+ #' the filter states in a table combining informations from `all_slices` and from |
|||
694 | -483x | +|||
13 | +
- if (inherits(modules, "teal_modules")) {+ #' `FilteredData$get_available_teal_slices()`. |
|||
695 | -18x | +|||
14 | +
- any(unlist(lapply(modules$children, is_arg_used, arg)))+ #' |
|||
696 | -465x | +|||
15 | +
- } else if (inherits(modules, "teal_module")) {+ #' During a session only new filters are added to `all_slices` unless [`module_snapshot_manager`] is |
|||
697 | -30x | +|||
16 | +
- is_arg_used(modules$server, arg) || is_arg_used(modules$ui, arg)+ #' used to restore previous state. Filters from `all_slices` can be activated or deactivated in a |
|||
698 | -435x | +|||
17 | +
- } else if (is.function(modules)) {+ #' module which is linked (both ways) by `attr(, "mapping")` so that: |
|||
699 | -433x | +|||
18 | +
- isTRUE(arg %in% names(formals(modules)))+ #' - If module's filter is added or removed in its `FilteredData` object, this information is passed |
|||
700 | +19 |
- } else {+ #' to `SlicesGlobal` which updates `attr(, "mapping")` accordingly. |
||
701 | -2x | +|||
20 | +
- stop("is_arg_used function not implemented for this object")+ #' - When mapping changes in a `SlicesGlobal`, filters are set or removed from module's |
|||
702 | +21 |
- }+ #' `FilteredData`. |
||
703 | +22 |
- }+ #' |
||
704 | +23 |
-
+ #' @section Filter manager: |
||
705 | +24 |
-
+ #' Filter-manager is split into two parts: |
||
706 | +25 |
- #' Get module depth+ #' 1. `ui/srv_filter_manager_panel` - Called once for the whole app. This module observes changes in |
||
707 | +26 |
- #'+ #' the filters in `slices_global` and displays them in a table utilizing information from `mapping`: |
||
708 | +27 |
- #' Depth starts at 0, so a single `teal.module` has depth 0.+ #' - (`TRUE`) - filter is active in the module |
||
709 | +28 |
- #' Nesting it increases overall depth by 1.+ #' - (`FALSE`) - filter is inactive in the module |
||
710 | +29 |
- #'+ #' - (`NA`) - filter is not available in the module |
||
711 | +30 |
- #' @inheritParams init+ #' 2. `ui/srv_module_filter_manager` - Called once for each `teal_module`. Handling filter states |
||
712 | +31 |
- #' @param depth optional integer determining current depth level+ #' for of single module and keeping module `FilteredData` consistent with `slices_global`, so that |
||
713 | +32 |
- #'+ #' local filters are always reflected in the `slices_global` and its mapping and vice versa. |
||
714 | +33 |
- #' @return Depth level for given module.+ #' |
||
715 | +34 |
- #' @keywords internal+ #' |
||
716 | +35 |
- modules_depth <- function(modules, depth = 0L) {+ #' @param id (`character(1)`) |
||
717 | -12x | +|||
36 | +
- checkmate::assert_multi_class(modules, c("teal_module", "teal_modules"))+ #' `shiny` module instance id. |
|||
718 | -12x | +|||
37 | +
- checkmate::assert_int(depth, lower = 0)+ #' |
|||
719 | -11x | +|||
38 | +
- if (inherits(modules, "teal_modules")) {+ #' @param slices_global (`reactiveVal`) |
|||
720 | -4x | +|||
39 | +
- max(vapply(modules$children, modules_depth, integer(1), depth = depth + 1L))+ #' containing `teal_slices`. |
|||
721 | +40 |
- } else {+ #' |
||
722 | -7x | +|||
41 | +
- depth+ #' @param module_fd (`FilteredData`) |
|||
723 | +42 |
- }+ #' Object containing the data to be filtered in a single `teal` module. |
||
724 | +43 |
- }+ #' |
||
725 | +44 |
-
+ #' @return |
||
726 | +45 |
- #' Retrieve labels from `teal_modules`+ #' Module returns a `slices_global` (`reactiveVal`) containing a `teal_slices` object with mapping. |
||
727 | +46 |
#' |
||
728 | +47 |
- #' @param modules (`teal_modules`)+ #' @encoding UTF-8 |
||
729 | +48 |
- #' @return A `list` containing the labels of the modules. If the modules are nested,+ #' |
||
730 | +49 |
- #' the function returns a nested `list` of labels.+ #' @name module_filter_manager |
||
731 | +50 |
- #' @keywords internal+ #' @rdname module_filter_manager |
||
732 | +51 |
- module_labels <- function(modules) {+ #' |
||
733 | -189x | +|||
52 | +
- if (inherits(modules, "teal_modules")) {+ NULL |
|||
734 | -82x | +|||
53 | +
- lapply(modules$children, module_labels)+ |
|||
735 | +54 |
- } else {+ #' @rdname module_filter_manager |
||
736 | -107x | +|||
55 | +
- modules$label+ ui_filter_manager_panel <- function(id) { |
|||
737 | -+ | |||
56 | +! |
- }+ ns <- NS(id) |
||
738 | -+ | |||
57 | +! |
- }+ tags$button( |
||
739 | -+ | |||
58 | +! |
-
+ id = ns("show_filter_manager"), |
||
740 | -+ | |||
59 | +! |
- #' Retrieve `teal_bookmarkable` attribute from `teal_modules`+ class = "btn action-button wunder_bar_button",+ |
+ ||
60 | +! | +
+ title = "View filter mapping",+ |
+ ||
61 | +! | +
+ suppressMessages(icon("fas fa-grip")) |
||
741 | +62 |
- #'+ ) |
||
742 | +63 |
- #' @param modules (`teal_modules` or `teal_module`) object+ } |
||
743 | +64 |
- #' @return named list of the same structure as `modules` with `TRUE` or `FALSE` values indicating+ |
||
744 | +65 |
- #' whether the module is bookmarkable.+ #' @rdname module_filter_manager |
||
745 | +66 |
#' @keywords internal |
||
746 | +67 |
- modules_bookmarkable <- function(modules) {+ srv_filter_manager_panel <- function(id, slices_global) { |
||
747 | -189x | +68 | +82x |
- checkmate::assert_multi_class(modules, c("teal_modules", "teal_module"))+ checkmate::assert_string(id) |
748 | -189x | +69 | +82x |
- if (inherits(modules, "teal_modules")) {+ checkmate::assert_class(slices_global, ".slicesGlobal") |
749 | +70 | 82x |
- setNames(+ moduleServer(id, function(input, output, session) { |
|
750 | +71 | 82x |
- lapply(modules$children, modules_bookmarkable),+ setBookmarkExclude(c("show_filter_manager")) |
|
751 | +72 | 82x |
- vapply(modules$children, `[[`, "label", FUN.VALUE = character(1))+ observeEvent(input$show_filter_manager, { |
|
752 | -+ | |||
73 | +! |
- )+ logger::log_debug("srv_filter_manager_panel@1 show_filter_manager button has been clicked.") |
||
753 | -+ | |||
74 | +! |
- } else {+ showModal( |
||
754 | -107x | +|||
75 | +! |
- attr(modules, "teal_bookmarkable", exact = TRUE)+ modalDialog( |
||
755 | -+ | |||
76 | +! |
- }+ ui_filter_manager(session$ns("filter_manager")), |
||
756 | -+ | |||
77 | +! |
- }+ class = "filter_manager_modal", |
1 | -+ | |||
78 | +! |
- #' Validate that dataset has a minimum number of observations+ size = "l", |
||
2 | -+ | |||
79 | +! |
- #'+ footer = NULL, |
||
3 | -+ | |||
80 | +! |
- #' `r lifecycle::badge("stable")`+ easyClose = TRUE |
||
4 | +81 |
- #'+ ) |
||
5 | +82 |
- #' This function is a wrapper for `shiny::validate`.+ ) |
||
6 | +83 |
- #'+ }) |
||
7 | -+ | |||
84 | +82x |
- #' @param x (`data.frame`)+ srv_filter_manager("filter_manager", slices_global = slices_global) |
||
8 | +85 |
- #' @param min_nrow (`numeric(1)`) Minimum allowed number of rows in `x`.+ }) |
||
9 | +86 |
- #' @param complete (`logical(1)`) Flag specifying whether to check only complete cases. Defaults to `FALSE`.+ } |
||
10 | +87 |
- #' @param allow_inf (`logical(1)`) Flag specifying whether to allow infinite values. Defaults to `TRUE`.+ |
||
11 | +88 |
- #' @param msg (`character(1)`) Additional message to display alongside the default message.+ #' @rdname module_filter_manager |
||
12 | +89 |
- #'+ ui_filter_manager <- function(id) { |
||
13 | -+ | |||
90 | +! |
- #' @export+ ns <- NS(id) |
||
14 | -+ | |||
91 | +! |
- #'+ actionButton(ns("filter_manager"), NULL, icon = icon("fas fa-filter")) |
||
15 | -+ | |||
92 | +! |
- #' @examples+ tags$div( |
||
16 | -+ | |||
93 | +! |
- #' library(teal)+ class = "filter_manager_content", |
||
17 | -+ | |||
94 | +! |
- #' ui <- fluidPage(+ tableOutput(ns("slices_table")) |
||
18 | +95 |
- #' sliderInput("len", "Max Length of Sepal",+ ) |
||
19 | +96 |
- #' min = 4.3, max = 7.9, value = 5+ } |
||
20 | +97 |
- #' ),+ |
||
21 | +98 |
- #' plotOutput("plot")+ #' @rdname module_filter_manager |
||
22 | +99 |
- #' )+ srv_filter_manager <- function(id, slices_global) { |
||
23 | -+ | |||
100 | +82x |
- #'+ checkmate::assert_string(id) |
||
24 | -+ | |||
101 | +82x |
- #' server <- function(input, output) {+ checkmate::assert_class(slices_global, ".slicesGlobal") |
||
25 | +102 |
- #' output$plot <- renderPlot({+ |
||
26 | -+ | |||
103 | +82x |
- #' iris_df <- iris[iris$Sepal.Length <= input$len, ]+ moduleServer(id, function(input, output, session) { |
||
27 | -+ | |||
104 | +82x |
- #' validate_has_data(+ logger::log_debug("filter_manager_srv initializing.") |
||
28 | +105 |
- #' iris_df,+ |
||
29 | +106 |
- #' min_nrow = 10,+ # Bookmark slices global with mapping. |
||
30 | -+ | |||
107 | +82x |
- #' complete = FALSE,+ session$onBookmark(function(state) { |
||
31 | -+ | |||
108 | +! |
- #' msg = "Please adjust Max Length of Sepal"+ logger::log_debug("filter_manager_srv@onBookmark: storing filter state") |
||
32 | -+ | |||
109 | +! |
- #' )+ state$values$filter_state_on_bookmark <- as.list( |
||
33 | -+ | |||
110 | +! |
- #'+ slices_global$all_slices(), |
||
34 | -+ | |||
111 | +! |
- #' hist(iris_df$Sepal.Length, breaks = 5)+ recursive = TRUE |
||
35 | +112 |
- #' })+ ) |
||
36 | +113 |
- #' }+ }) |
||
37 | +114 |
- #' if (interactive()) {+ |
||
38 | -+ | |||
115 | +82x |
- #' shinyApp(ui, server)+ bookmarked_slices <- restoreValue(session$ns("filter_state_on_bookmark"), NULL) |
||
39 | -+ | |||
116 | +82x |
- #' }+ if (!is.null(bookmarked_slices)) { |
||
40 | -+ | |||
117 | +! |
- #'+ logger::log_debug("filter_manager_srv: restoring filter state from bookmark.") |
||
41 | -+ | |||
118 | +! |
- validate_has_data <- function(x,+ slices_global$slices_set(bookmarked_slices) |
||
42 | +119 |
- min_nrow = NULL,+ } |
||
43 | +120 |
- complete = FALSE,+ + |
+ ||
121 | +82x | +
+ mapping_table <- reactive({ |
||
44 | +122 |
- allow_inf = TRUE,+ # We want this to be reactive on slices_global$all_slices() only as get_available_teal_slices() |
||
45 | +123 |
- msg = NULL) {+ # is dependent on slices_global$all_slices(). |
||
46 | -17x | +124 | +91x |
- checkmate::assert_string(msg, null.ok = TRUE)+ module_labels <- setdiff( |
47 | -15x | +125 | +91x |
- checkmate::assert_data_frame(x)+ names(attr(slices_global$all_slices(), "mapping")), |
48 | -15x | +126 | +91x |
- if (!is.null(min_nrow)) {+ "Report previewer"+ |
+
127 | ++ |
+ ) |
||
49 | -15x | +128 | +91x |
- if (complete) {+ isolate({ |
50 | -5x | +129 | +91x |
- complete_index <- stats::complete.cases(x)+ mm <- as.data.frame( |
51 | -5x | +130 | +91x |
- validate(need(+ sapply( |
52 | -5x | +131 | +91x |
- sum(complete_index) > 0 && nrow(x[complete_index, , drop = FALSE]) >= min_nrow,+ module_labels, |
53 | -5x | +132 | +91x |
- paste(c(paste("Number of complete cases is less than:", min_nrow), msg), collapse = "\n")+ simplify = FALSE, |
54 | -+ | |||
133 | +91x |
- ))+ function(module_label) { |
||
55 | -+ | |||
134 | +104x |
- } else {+ available_slices <- slices_global$module_slices_api[[module_label]]$get_available_teal_slices() |
||
56 | -10x | +135 | +96x |
- validate(need(+ global_ids <- sapply(slices_global$all_slices(), `[[`, "id", simplify = FALSE) |
57 | -10x | +136 | +96x |
- nrow(x) >= min_nrow,+ module_ids <- sapply(slices_global$slices_get(module_label), `[[`, "id", simplify = FALSE) |
58 | -10x | +137 | +96x |
- paste(+ allowed_ids <- vapply(available_slices, `[[`, character(1L), "id") |
59 | -10x | +138 | +96x |
- c(paste("Minimum number of records not met: >=", min_nrow, "records required."), msg),+ active_ids <- global_ids %in% module_ids |
60 | -10x | +139 | +96x |
- collapse = "\n"+ setNames(nm = global_ids, ifelse(global_ids %in% allowed_ids, active_ids, NA)) |
61 | +140 |
- )+ } |
||
62 | +141 |
- ))+ ), |
||
63 | -+ | |||
142 | +91x |
- }+ check.names = FALSE |
||
64 | +143 |
-
+ ) |
||
65 | -10x | +144 | +83x |
- if (!allow_inf) {+ colnames(mm)[colnames(mm) == "global_filters"] <- "Global filters" |
66 | -6x | +|||
145 | +
- validate(need(+ |
|||
67 | -6x | +146 | +83x |
- all(vapply(x, function(col) !is.numeric(col) || !any(is.infinite(col)), logical(1))),+ mm |
68 | -6x | +|||
147 | +
- "Dataframe contains Inf values which is not allowed."+ }) |
|||
69 | +148 |
- ))+ }) |
||
70 | +149 |
- }+ |
||
71 | -+ | |||
150 | +82x |
- }+ output$slices_table <- renderTable( |
||
72 | -+ | |||
151 | +82x |
- }+ expr = { |
||
73 | -+ | |||
152 | +91x |
-
+ logger::log_debug("filter_manager_srv@1 rendering slices_table.") |
||
74 | -+ | |||
153 | +91x |
- #' Validate that dataset has unique rows for key variables+ mm <- mapping_table() |
||
75 | +154 |
- #'+ |
||
76 | +155 |
- #' `r lifecycle::badge("stable")`+ # Display logical values as UTF characters. |
||
77 | -+ | |||
156 | +83x |
- #'+ mm[] <- lapply(mm, ifelse, yes = intToUtf8(9989), no = intToUtf8(10060)) |
||
78 | -+ | |||
157 | +83x |
- #' This function is a wrapper for `shiny::validate`.+ mm[] <- lapply(mm, function(x) ifelse(is.na(x), intToUtf8(128306), x)) |
||
79 | +158 |
- #'+ |
||
80 | +159 |
- #' @param x (`data.frame`)+ # Display placeholder if no filters defined. |
||
81 | -+ | |||
160 | +83x |
- #' @param key (`character`) Vector of ID variables from `x` that identify unique records.+ if (nrow(mm) == 0L) { |
||
82 | -+ | |||
161 | +59x |
- #'+ mm <- data.frame(`Filter manager` = "No filters specified.", check.names = FALSE) |
||
83 | -+ | |||
162 | +59x |
- #' @export+ rownames(mm) <- "" |
||
84 | +163 |
- #'+ } |
||
85 | -+ | |||
164 | +83x |
- #' @examples+ mm |
||
86 | +165 |
- #' iris$id <- rep(1:50, times = 3)+ }, |
||
87 | -+ | |||
166 | +82x |
- #' ui <- fluidPage(+ rownames = TRUE |
||
88 | +167 |
- #' selectInput(+ ) |
||
89 | +168 |
- #' inputId = "species",+ |
||
90 | -+ | |||
169 | +82x |
- #' label = "Select species",+ mapping_table # for testing purpose |
||
91 | +170 |
- #' choices = c("setosa", "versicolor", "virginica"),+ }) |
||
92 | +171 |
- #' selected = "setosa",+ } |
||
93 | +172 |
- #' multiple = TRUE+ |
||
94 | +173 |
- #' ),+ #' @rdname module_filter_manager |
||
95 | +174 |
- #' plotOutput("plot")+ srv_module_filter_manager <- function(id, module_fd, slices_global) { |
||
96 | -+ | |||
175 | +107x |
- #' )+ checkmate::assert_string(id) |
||
97 | -+ | |||
176 | +107x |
- #' server <- function(input, output) {+ assert_reactive(module_fd) |
||
98 | -+ | |||
177 | +107x |
- #' output$plot <- renderPlot({+ checkmate::assert_class(slices_global, ".slicesGlobal") |
||
99 | +178 |
- #' iris_f <- iris[iris$Species %in% input$species, ]+ |
||
100 | -+ | |||
179 | +107x |
- #' validate_one_row_per_id(iris_f, key = c("id"))+ moduleServer(id, function(input, output, session) { |
||
101 | -+ | |||
180 | +107x |
- #'+ logger::log_debug("srv_module_filter_manager initializing for module: { id }.") |
||
102 | +181 |
- #' hist(iris_f$Sepal.Length, breaks = 5)+ # Track filter global and local states. |
||
103 | -+ | |||
182 | +107x |
- #' })+ slices_global_module <- reactive({ |
||
104 | -+ | |||
183 | +193x |
- #' }+ slices_global$slices_get(module_label = id) |
||
105 | +184 |
- #' if (interactive()) {+ }) |
||
106 | -+ | |||
185 | +107x |
- #' shinyApp(ui, server)+ slices_module <- reactive(req(module_fd())$get_filter_state()) |
||
107 | +186 |
- #' }+ + |
+ ||
187 | +107x | +
+ module_fd_previous <- reactiveVal(NULL) |
||
108 | +188 |
- #'+ |
||
109 | +189 |
- validate_one_row_per_id <- function(x, key = c("USUBJID", "STUDYID")) {+ # Set (reactively) available filters for the module. |
||
110 | -! | +|||
190 | +107x |
- validate(need(!any(duplicated(x[key])), paste("Found more than one row per id.")))+ obs1 <- observeEvent(module_fd(), priority = 1, { |
||
111 | -+ | |||
191 | +88x |
- }+ logger::log_debug("srv_module_filter_manager@1 setting initial slices for module: { id }.") |
||
112 | +192 |
-
+ # Filters relevant for the module in module-specific app. |
||
113 | -+ | |||
193 | +88x |
- #' Validates that vector includes all expected values+ slices <- slices_global_module() |
||
114 | +194 |
- #'+ |
||
115 | +195 |
- #' `r lifecycle::badge("stable")`+ # Clean up previous filter states and refresh cache of previous module_fd with current |
||
116 | -+ | |||
196 | +3x |
- #'+ if (!is.null(module_fd_previous())) module_fd_previous()$finalize() |
||
117 | -+ | |||
197 | +88x |
- #' This function is a wrapper for `shiny::validate`.+ module_fd_previous(module_fd()) |
||
118 | +198 |
- #'+ |
||
119 | +199 |
- #' @param x Vector of values to test.+ # Setting filter states from slices_global: |
||
120 | +200 |
- #' @param choices Vector to test against.+ # 1. when app initializes slices_global set to initial filters (specified by app developer) |
||
121 | +201 |
- #' @param msg (`character(1)`) Error message to display if some elements of `x` are not elements of `choices`.+ # 2. when data reinitializes slices_global reflects latest filter states |
||
122 | +202 |
- #'+ |
||
123 | -+ | |||
203 | +88x |
- #' @export+ module_fd()$set_filter_state(slices) |
||
124 | +204 |
- #'+ |
||
125 | +205 |
- #' @examples+ # irrelevant filters are discarded in FilteredData$set_available_teal_slices |
||
126 | +206 |
- #' ui <- fluidPage(+ # it means we don't need to subset slices_global$all_slices() from filters refering to irrelevant datasets |
||
127 | -+ | |||
207 | +88x |
- #' selectInput(+ module_fd()$set_available_teal_slices(slices_global$all_slices) |
||
128 | +208 |
- #' "species",+ |
||
129 | +209 |
- #' "Select species",+ # this needed in filter_manager_srv |
||
130 | -+ | |||
210 | +88x |
- #' choices = c("setosa", "versicolor", "virginica", "unknown species"),+ slices_global$module_slices_api_set( |
||
131 | -+ | |||
211 | +88x |
- #' selected = "setosa",+ id, |
||
132 | -+ | |||
212 | +88x |
- #' multiple = FALSE+ list( |
||
133 | -+ | |||
213 | +88x |
- #' ),+ get_available_teal_slices = module_fd()$get_available_teal_slices(), |
||
134 | -+ | |||
214 | +88x |
- #' verbatimTextOutput("summary")+ set_filter_state = module_fd()$set_filter_state, # for testing purpose |
||
135 | -+ | |||
215 | +88x |
- #' )+ get_filter_state = module_fd()$get_filter_state # for testing purpose |
||
136 | +216 |
- #'+ ) |
||
137 | +217 |
- #' server <- function(input, output) {+ ) |
||
138 | +218 |
- #' output$summary <- renderPrint({+ }) |
||
139 | +219 |
- #' validate_in(input$species, iris$Species, "Species does not exist.")+ |
||
140 | +220 |
- #' nrow(iris[iris$Species == input$species, ])+ # Update global state and mapping matrix when module filters change. |
||
141 | -+ | |||
221 | +107x |
- #' })+ obs2 <- observeEvent(slices_module(), priority = 0, { |
||
142 | -+ | |||
222 | +110x |
- #' }+ this_slices <- slices_module() |
||
143 | -+ | |||
223 | +110x |
- #' if (interactive()) {+ slices_global$slices_append(this_slices) # append new slices to the all_slices list |
||
144 | -+ | |||
224 | +110x |
- #' shinyApp(ui, server)+ mapping_elem <- setNames(nm = id, list(vapply(this_slices, `[[`, character(1L), "id"))) |
||
145 | -+ | |||
225 | +110x |
- #' }+ slices_global$slices_active(mapping_elem) |
||
146 | +226 |
- #'+ }) |
||
147 | +227 |
- validate_in <- function(x, choices, msg) {+ |
||
148 | -! | +|||
228 | +107x |
- validate(need(length(x) > 0 && length(choices) > 0 && all(x %in% choices), msg))+ obs3 <- observeEvent(slices_global_module(), { |
||
149 | -+ | |||
229 | +130x |
- }+ global_vs_module <- setdiff_teal_slices(slices_global_module(), slices_module()) |
||
150 | -+ | |||
230 | +130x |
-
+ module_vs_global <- setdiff_teal_slices(slices_module(), slices_global_module()) |
||
151 | -+ | |||
231 | +121x |
- #' Validates that vector has length greater than 0+ if (length(global_vs_module) || length(module_vs_global)) { |
||
152 | +232 |
- #'+ # Comment: (Nota Bene) Normally new filters for a module are added through module-filter-panel, and slices |
||
153 | +233 |
- #' `r lifecycle::badge("stable")`+ # global are updated automatically so slices_module -> slices_global_module are equal. |
||
154 | +234 |
- #'+ # this if is valid only when a change is made on the global level so the change needs to be propagated down |
||
155 | +235 |
- #' This function is a wrapper for `shiny::validate`.+ # to the module (for example through snapshot manager). If it happens both slices are different |
||
156 | -+ | |||
236 | +13x |
- #'+ logger::log_debug("srv_module_filter_manager@3 (N.B.) global state has changed for a module:{ id }.") |
||
157 | -+ | |||
237 | +13x |
- #' @param x vector+ module_fd()$clear_filter_states() |
||
158 | -+ | |||
238 | +13x |
- #' @param msg message to display+ module_fd()$set_filter_state(slices_global_module()) |
||
159 | +239 |
- #'+ } |
||
160 | +240 |
- #' @export+ }) |
||
161 | +241 |
- #'+ |
||
162 | -+ | |||
242 | +107x |
- #' @examples+ slices_module # returned for testing purpose |
||
163 | +243 |
- #' data <- data.frame(+ }) |
||
164 | +244 |
- #' id = c(1:10, 11:20, 1:10),+ } |
||
165 | +245 |
- #' strata = rep(c("A", "B"), each = 15)+ |
||
166 | +246 |
- #' )+ #' @importFrom shiny reactiveVal reactiveValues |
||
167 | +247 |
- #' ui <- fluidPage(+ methods::setOldClass("reactiveVal") |
||
168 | +248 |
- #' selectInput("ref1", "Select strata1 to compare",+ methods::setOldClass("reactivevalues") |
||
169 | +249 |
- #' choices = c("A", "B", "C"), selected = "A"+ |
||
170 | +250 |
- #' ),+ #' @importFrom methods new |
||
171 | +251 |
- #' selectInput("ref2", "Select strata2 to compare",+ #' @rdname module_filter_manager |
||
172 | +252 |
- #' choices = c("A", "B", "C"), selected = "B"+ .slicesGlobal <- methods::setRefClass(".slicesGlobal", # nolint: object_name. |
||
173 | +253 |
- #' ),+ fields = list( |
||
174 | +254 |
- #' verbatimTextOutput("arm_summary")+ all_slices = "reactiveVal", |
||
175 | +255 |
- #' )+ module_slices_api = "reactivevalues" |
||
176 | +256 |
- #'+ ), |
||
177 | +257 |
- #' server <- function(input, output) {+ methods = list( |
||
178 | +258 |
- #' output$arm_summary <- renderText({+ initialize = function(slices = teal_slices(), module_labels) { |
||
179 | -+ | |||
259 | +82x |
- #' sample_1 <- data$id[data$strata == input$ref1]+ shiny::isolate({ |
||
180 | -+ | |||
260 | +82x |
- #' sample_2 <- data$id[data$strata == input$ref2]+ checkmate::assert_class(slices, "teal_slices") |
||
181 | +261 |
- #'+ # needed on init to not mix "global_filters" with module-specific-slots |
||
182 | -+ | |||
262 | +82x |
- #' validate_has_elements(sample_1, "No subjects in strata1.")+ if (isTRUE(attr(slices, "module_specific"))) { |
||
183 | -+ | |||
263 | +11x |
- #' validate_has_elements(sample_2, "No subjects in strata2.")+ old_mapping <- attr(slices, "mapping") |
||
184 | -+ | |||
264 | +11x |
- #'+ new_mapping <- sapply(module_labels, simplify = FALSE, function(module_label) { |
||
185 | -+ | |||
265 | +20x |
- #' paste0(+ unique(unlist(old_mapping[c(module_label, "global_filters")])) |
||
186 | +266 |
- #' "Number of samples in: strata1=", length(sample_1),+ }) |
||
187 | -+ | |||
267 | +11x |
- #' " comparions strata2=", length(sample_2)+ attr(slices, "mapping") <- new_mapping |
||
188 | +268 |
- #' )+ } |
||
189 | -+ | |||
269 | +82x |
- #' })+ .self$all_slices <<- shiny::reactiveVal(slices) |
||
190 | -+ | |||
270 | +82x |
- #' }+ .self$module_slices_api <<- shiny::reactiveValues() |
||
191 | -+ | |||
271 | +82x |
- #' if (interactive()) {+ .self$slices_append(slices) |
||
192 | -+ | |||
272 | +82x |
- #' shinyApp(ui, server)+ .self$slices_active(attr(slices, "mapping")) |
||
193 | -+ | |||
273 | +82x |
- #' }+ invisible(.self) |
||
194 | +274 |
- validate_has_elements <- function(x, msg) {+ }) |
||
195 | -! | +|||
275 | +
- validate(need(length(x) > 0, msg))+ }, |
|||
196 | +276 |
- }+ is_module_specific = function() { |
||
197 | -+ | |||
277 | +283x |
-
+ isTRUE(attr(.self$all_slices(), "module_specific")) |
||
198 | +278 |
- #' Validates no intersection between two vectors+ }, |
||
199 | +279 |
- #'+ module_slices_api_set = function(module_label, functions_list) { |
||
200 | -+ | |||
280 | +88x |
- #' `r lifecycle::badge("stable")`+ shiny::isolate({ |
||
201 | -+ | |||
281 | +88x |
- #'+ if (!.self$is_module_specific()) { |
||
202 | -+ | |||
282 | +72x |
- #' This function is a wrapper for `shiny::validate`.+ module_label <- "global_filters" |
||
203 | +283 |
- #'+ } |
||
204 | -+ | |||
284 | +88x |
- #' @param x vector+ if (!identical(.self$module_slices_api[[module_label]], functions_list)) { |
||
205 | -+ | |||
285 | +88x |
- #' @param y vector+ .self$module_slices_api[[module_label]] <- functions_list |
||
206 | +286 |
- #' @param msg (`character(1)`) message to display if `x` and `y` intersect+ } |
||
207 | -+ | |||
287 | +88x |
- #'+ invisible(.self) |
||
208 | +288 |
- #' @export+ }) |
||
209 | +289 |
- #'+ }, |
||
210 | +290 |
- #' @examples+ slices_deactivate_all = function(module_label) { |
||
211 | -+ | |||
291 | +! |
- #' data <- data.frame(+ shiny::isolate({ |
||
212 | -+ | |||
292 | +! |
- #' id = c(1:10, 11:20, 1:10),+ new_slices <- .self$all_slices() |
||
213 | -+ | |||
293 | +! |
- #' strata = rep(c("A", "B", "C"), each = 10)+ old_mapping <- attr(new_slices, "mapping") |
||
214 | +294 |
- #' )+ |
||
215 | -+ | |||
295 | +! |
- #'+ new_mapping <- if (.self$is_module_specific()) { |
||
216 | -+ | |||
296 | +! |
- #' ui <- fluidPage(+ new_module_mapping <- setNames(nm = module_label, list(character(0))) |
||
217 | -+ | |||
297 | +! |
- #' selectInput("ref1", "Select strata1 to compare",+ modifyList(old_mapping, new_module_mapping) |
||
218 | -+ | |||
298 | +! |
- #' choices = c("A", "B", "C"),+ } else if (missing(module_label)) { |
||
219 | -+ | |||
299 | +! |
- #' selected = "A"+ lapply( |
||
220 | -+ | |||
300 | +! |
- #' ),+ attr(.self$all_slices(), "mapping"), |
||
221 | -+ | |||
301 | +! |
- #' selectInput("ref2", "Select strata2 to compare",+ function(x) character(0) |
||
222 | +302 |
- #' choices = c("A", "B", "C"),+ ) |
||
223 | +303 |
- #' selected = "B"+ } else { |
||
224 | -+ | |||
304 | +! |
- #' ),+ old_mapping[[module_label]] <- character(0) |
||
225 | -+ | |||
305 | +! |
- #' verbatimTextOutput("summary")+ old_mapping |
||
226 | +306 |
- #' )+ } |
||
227 | +307 |
- #'+ |
||
228 | -+ | |||
308 | +! |
- #' server <- function(input, output) {+ if (!identical(new_mapping, old_mapping)) { |
||
229 | -+ | |||
309 | +! |
- #' output$summary <- renderText({+ logger::log_debug(".slicesGlobal@slices_deactivate_all: deactivating all slices.") |
||
230 | -+ | |||
310 | +! |
- #' sample_1 <- data$id[data$strata == input$ref1]+ attr(new_slices, "mapping") <- new_mapping |
||
231 | -+ | |||
311 | +! |
- #' sample_2 <- data$id[data$strata == input$ref2]+ .self$all_slices(new_slices) |
||
232 | +312 |
- #'+ } |
||
233 | -+ | |||
313 | +! |
- #' validate_no_intersection(+ invisible(.self) |
||
234 | +314 |
- #' sample_1, sample_2,+ }) |
||
235 | +315 |
- #' "subjects within strata1 and strata2 cannot overlap"+ }, |
||
236 | +316 |
- #' )+ slices_active = function(mapping_elem) { |
||
237 | -+ | |||
317 | +195x |
- #' paste0(+ shiny::isolate({ |
||
238 | -+ | |||
318 | +195x |
- #' "Number of subject in: reference treatment=", length(sample_1),+ if (.self$is_module_specific()) { |
||
239 | -+ | |||
319 | +36x |
- #' " comparions treatment=", length(sample_2)+ new_mapping <- modifyList(attr(.self$all_slices(), "mapping"), mapping_elem) |
||
240 | +320 |
- #' )+ } else { |
||
241 | -+ | |||
321 | +159x |
- #' })+ new_mapping <- setNames(nm = "global_filters", list(unique(unlist(mapping_elem)))) |
||
242 | +322 |
- #' }+ } |
||
243 | +323 |
- #' if (interactive()) {+ |
||
244 | -+ | |||
324 | +195x |
- #' shinyApp(ui, server)+ if (!identical(new_mapping, attr(.self$all_slices(), "mapping"))) { |
||
245 | -+ | |||
325 | +138x |
- #' }+ mapping_modules <- toString(names(new_mapping)) |
||
246 | -+ | |||
326 | +138x |
- #'+ logger::log_debug(".slicesGlobal@slices_active: changing mapping for module(s): { mapping_modules }.") |
||
247 | -+ | |||
327 | +138x |
- validate_no_intersection <- function(x, y, msg) {+ new_slices <- .self$all_slices() |
||
248 | -! | +|||
328 | +138x |
- validate(need(length(intersect(x, y)) == 0, msg))+ attr(new_slices, "mapping") <- new_mapping |
||
249 | -+ | |||
329 | +138x |
- }+ .self$all_slices(new_slices) |
||
250 | +330 |
-
+ } |
||
251 | +331 | |||
252 | -+ | |||
332 | +195x |
- #' Validates that dataset contains specific variable+ invisible(.self) |
||
253 | +333 |
- #'+ }) |
||
254 | +334 |
- #' `r lifecycle::badge("stable")`+ }, |
||
255 | +335 |
- #'+ # - only new filters are appended to the $all_slices |
||
256 | +336 |
- #' This function is a wrapper for `shiny::validate`.+ # - mapping is not updated here |
||
257 | +337 |
- #'+ slices_append = function(slices, activate = FALSE) { |
||
258 | -+ | |||
338 | +195x |
- #' @param data (`data.frame`)+ shiny::isolate({ |
||
259 | -+ | |||
339 | +195x |
- #' @param varname (`character(1)`) name of variable to check for in `data`+ if (!is.teal_slices(slices)) { |
||
260 | -+ | |||
340 | +! |
- #' @param msg (`character(1)`) message to display if `data` does not include `varname`+ slices <- as.teal_slices(slices) |
||
261 | +341 |
- #'+ } |
||
262 | +342 |
- #' @export+ |
||
263 | +343 |
- #'+ # to make sure that we don't unnecessary trigger $all_slices <reactiveVal> |
||
264 | -+ | |||
344 | +195x |
- #' @examples+ new_slices <- setdiff_teal_slices(slices, .self$all_slices()) |
||
265 | -+ | |||
345 | +195x |
- #' data <- data.frame(+ old_mapping <- attr(.self$all_slices(), "mapping") |
||
266 | -+ | |||
346 | +195x |
- #' one = rep("a", length.out = 20),+ if (length(new_slices)) { |
||
267 | -+ | |||
347 | +6x |
- #' two = rep(c("a", "b"), length.out = 20)+ new_ids <- vapply(new_slices, `[[`, character(1L), "id") |
||
268 | -+ | |||
348 | +6x |
- #' )+ logger::log_debug(".slicesGlobal@slices_append: appending new slice(s): { new_ids }.") |
||
269 | -+ | |||
349 | +6x |
- #' ui <- fluidPage(+ slices_ids <- vapply(.self$all_slices(), `[[`, character(1L), "id") |
||
270 | -+ | |||
350 | +6x |
- #' selectInput(+ lapply(new_slices, function(slice) { |
||
271 | +351 |
- #' "var",+ # In case the new state has the same id as an existing one, add a suffix |
||
272 | -+ | |||
352 | +6x |
- #' "Select variable",+ if (slice$id %in% slices_ids) { |
||
273 | -+ | |||
353 | +1x |
- #' choices = c("one", "two", "three", "four"),+ slice$id <- utils::tail(make.unique(c(slices_ids, slice$id), sep = "_"), 1) |
||
274 | +354 |
- #' selected = "one"+ } |
||
275 | +355 |
- #' ),+ }) |
||
276 | +356 |
- #' verbatimTextOutput("summary")+ |
||
277 | -+ | |||
357 | +6x |
- #' )+ new_slices_all <- c(.self$all_slices(), new_slices) |
||
278 | -+ | |||
358 | +6x |
- #'+ attr(new_slices_all, "mapping") <- old_mapping |
||
279 | -+ | |||
359 | +6x |
- #' server <- function(input, output) {+ .self$all_slices(new_slices_all) |
||
280 | +360 |
- #' output$summary <- renderText({+ } |
||
281 | +361 |
- #' validate_has_variable(data, input$var)+ |
||
282 | -+ | |||
362 | +195x |
- #' paste0("Selected treatment variables: ", paste(input$var, collapse = ", "))+ invisible(.self) |
||
283 | +363 |
- #' })+ }) |
||
284 | +364 |
- #' }+ }, |
||
285 | +365 |
- #' if (interactive()) {+ slices_get = function(module_label) { |
||
286 | -+ | |||
366 | +289x |
- #' shinyApp(ui, server)+ if (missing(module_label)) { |
||
287 | -+ | |||
367 | +! |
- #' }+ .self$all_slices() |
||
288 | +368 |
- validate_has_variable <- function(data, varname, msg) {+ } else { |
||
289 | -! | +|||
369 | +289x |
- if (length(varname) != 0) {+ module_ids <- unlist(attr(.self$all_slices(), "mapping")[c(module_label, "global_filters")]) |
||
290 | -! | +|||
370 | +289x |
- has_vars <- varname %in% names(data)+ Filter(+ |
+ ||
371 | +289x | +
+ function(slice) slice$id %in% module_ids,+ |
+ ||
372 | +289x | +
+ .self$all_slices() |
||
291 | +373 |
-
+ ) |
||
292 | -! | +|||
374 | +
- if (!all(has_vars)) {+ } |
|||
293 | -! | +|||
375 | +
- if (missing(msg)) {+ }, |
|||
294 | -! | +|||
376 | +
- msg <- sprintf(+ slices_set = function(slices) { |
|||
295 | -! | +|||
377 | +7x |
- "%s does not have the required variables: %s.",+ shiny::isolate({ |
||
296 | -! | +|||
378 | +7x |
- deparse(substitute(data)),+ if (!is.teal_slices(slices)) { |
||
297 | +379 | ! |
- toString(varname[!has_vars])+ slices <- as.teal_slices(slices) |
|
298 | +380 |
- )+ } |
||
299 | -+ | |||
381 | +7x |
- }+ .self$all_slices(slices) |
||
300 | -! | +|||
382 | +7x |
- validate(need(FALSE, msg))+ invisible(.self) |
||
301 | +383 |
- }+ }) |
||
302 | +384 |
- }+ }, |
||
303 | +385 |
- }+ show = function() { |
||
304 | -+ | |||
386 | +! |
-
+ shiny::isolate(print(.self$all_slices())) |
||
305 | -+ | |||
387 | +! |
- #' Validate that variables has expected number of levels+ invisible(.self) |
||
306 | +388 |
- #'+ } |
||
307 | +389 |
- #' `r lifecycle::badge("stable")`+ ) |
||
308 | +390 |
- #'+ ) |
||
309 | +391 |
- #' If the number of levels of `x` is less than `min_levels`+ # todo: prevent any teal_slices attribute except mapping |
310 | +1 |
- #' or greater than `max_levels` the validation will fail.+ # This is the main function from teal to be used by the end-users. Although it delegates |
|
311 | +2 |
- #' This function is a wrapper for `shiny::validate`.+ # directly to `module_teal_with_splash.R`, we keep it in a separate file because its documentation is quite large |
|
312 | +3 |
- #'+ # and it is very end-user oriented. It may also perform more argument checking with more informative |
|
313 | +4 |
- #' @param x variable name. If `x` is not a factor, the unique values+ # error messages. |
|
314 | +5 |
- #' are treated as levels.+ |
|
315 | +6 |
- #' @param min_levels cutoff for minimum number of levels of `x`+ #' Create the server and UI function for the `shiny` app |
|
316 | +7 |
- #' @param max_levels cutoff for maximum number of levels of `x`+ #' |
|
317 | +8 |
- #' @param var_name name of variable being validated for use in+ #' @description `r lifecycle::badge("stable")` |
|
318 | +9 |
- #' validation message+ #' |
|
319 | +10 |
- #'+ #' End-users: This is the most important function for you to start a |
|
320 | +11 |
- #' @export+ #' `teal` app that is composed of `teal` modules. |
|
321 | +12 |
- #' @examples+ #' |
|
322 | +13 |
- #' data <- data.frame(+ #' @param data (`teal_data` or `teal_data_module`) |
|
323 | +14 |
- #' one = rep("a", length.out = 20),+ #' For constructing the data object, refer to [teal_data()] and [teal_data_module()]. |
|
324 | +15 |
- #' two = rep(c("a", "b"), length.out = 20),+ #' If `datanames` are not set for the `teal_data` object, defaults from the `teal_data` environment will be used. |
|
325 | +16 |
- #' three = rep(c("a", "b", "c"), length.out = 20),+ #' @param modules (`list` or `teal_modules` or `teal_module`) |
|
326 | +17 |
- #' four = rep(c("a", "b", "c", "d"), length.out = 20),+ #' Nested list of `teal_modules` or `teal_module` objects or a single |
|
327 | +18 |
- #' stringsAsFactors = TRUE+ #' `teal_modules` or `teal_module` object. These are the specific output modules which |
|
328 | +19 |
- #' )+ #' will be displayed in the `teal` application. See [modules()] and [module()] for |
|
329 | +20 |
- #' ui <- fluidPage(+ #' more details. |
|
330 | +21 |
- #' selectInput(+ #' @param filter (`teal_slices`) Optionally, |
|
331 | +22 |
- #' "var",+ #' specifies the initial filter using [teal_slices()]. |
|
332 | +23 |
- #' "Select variable",+ #' @param title (`shiny.tag` or `character(1)`) Optionally, |
|
333 | +24 |
- #' choices = c("one", "two", "three", "four"),+ #' the browser window title. Defaults to a title "teal app" with the icon of NEST. |
|
334 | +25 |
- #' selected = "one"+ #' Can be created using the `build_app_title()` or |
|
335 | +26 |
- #' ),+ #' by passing a valid `shiny.tag` which is a head tag with title and link tag. |
|
336 | +27 |
- #' verbatimTextOutput("summary")+ #' @param header (`shiny.tag` or `character(1)`) Optionally, |
|
337 | +28 |
- #' )+ #' the header of the app. |
|
338 | +29 |
- #'+ #' @param footer (`shiny.tag` or `character(1)`) Optionally, |
|
339 | +30 |
- #' server <- function(input, output) {+ #' the footer of the app. |
|
340 | +31 |
- #' output$summary <- renderText({+ #' @param id (`character`) Optionally, |
|
341 | +32 |
- #' validate_n_levels(data[[input$var]], min_levels = 2, max_levels = 15, var_name = input$var)+ #' a string specifying the `shiny` module id in cases it is used as a `shiny` module |
|
342 | +33 |
- #' paste0(+ #' rather than a standalone `shiny` app. This is a legacy feature. |
|
343 | +34 |
- #' "Levels of selected treatment variable: ",+ #' @param landing_popup (`teal_module_landing`) Optionally, |
|
344 | +35 |
- #' paste(levels(data[[input$var]]),+ #' a `landing_popup_module` to show up as soon as the teal app is initialized. |
|
345 | +36 |
- #' collapse = ", "+ #' |
|
346 | +37 |
- #' )+ #' @return Named list containing server and UI functions. |
|
347 | +38 |
- #' )+ #' |
|
348 | +39 |
- #' })+ #' @export |
|
349 | +40 |
- #' }+ #' |
|
350 | +41 |
- #' if (interactive()) {+ #' @include modules.R |
|
351 | +42 |
- #' shinyApp(ui, server)+ #' |
|
352 | +43 |
- #' }+ #' @examples |
|
353 | +44 |
- validate_n_levels <- function(x, min_levels = 1, max_levels = 12, var_name) {- |
- |
354 | -! | -
- x_levels <- if (is.factor(x)) {- |
- |
355 | -! | -
- levels(x)+ #' app <- init( |
|
356 | +45 |
- } else {- |
- |
357 | -! | -
- unique(x)+ #' data = within( |
|
358 | +46 |
- }+ #' teal_data(), |
|
359 | +47 | - - | -|
360 | -! | -
- if (!is.null(min_levels) && !(is.null(max_levels))) {- |
- |
361 | -! | -
- validate(need(- |
- |
362 | -! | -
- length(x_levels) >= min_levels && length(x_levels) <= max_levels,- |
- |
363 | -! | -
- sprintf(- |
- |
364 | -! | -
- "%s variable needs minimum %s level(s) and maximum %s level(s).",- |
- |
365 | -! | -
- var_name, min_levels, max_levels+ #' { |
|
366 | +48 |
- )+ #' new_iris <- transform(iris, id = seq_len(nrow(iris))) |
|
367 | +49 |
- ))- |
- |
368 | -! | -
- } else if (!is.null(min_levels)) {- |
- |
369 | -! | -
- validate(need(- |
- |
370 | -! | -
- length(x_levels) >= min_levels,- |
- |
371 | -! | -
- sprintf("%s variable needs minimum %s levels(s)", var_name, min_levels)+ #' new_mtcars <- transform(mtcars, id = seq_len(nrow(mtcars))) |
|
372 | +50 |
- ))+ #' } |
|
373 | -! | +||
51 | +
- } else if (!is.null(max_levels)) {+ #' ), |
||
374 | -! | +||
52 | +
- validate(need(+ #' modules = modules( |
||
375 | -! | +||
53 | +
- length(x_levels) <= max_levels,+ #' module( |
||
376 | -! | +||
54 | +
- sprintf("%s variable needs maximum %s level(s)", var_name, max_levels)+ #' label = "data source", |
||
377 | +55 |
- ))+ #' server = function(input, output, session, data) {}, |
|
378 | +56 |
- }+ #' ui = function(id, ...) tags$div(p("information about data source")), |
|
379 | +57 |
- }+ #' datanames = "all" |
1 | +58 |
- #' Filter state snapshot management+ #' ), |
||
2 | +59 |
- #'+ #' example_module(label = "example teal module"), |
||
3 | +60 |
- #' Capture and restore snapshots of the global (app) filter state.+ #' module( |
||
4 | +61 |
- #'+ #' "Iris Sepal.Length histogram", |
||
5 | +62 |
- #' This module introduces snapshots: stored descriptions of the filter state of the entire application.+ #' server = function(input, output, session, data) { |
||
6 | +63 |
- #' Snapshots allow the user to save the current filter state of the application for later use in the session,+ #' output$hist <- renderPlot( |
||
7 | +64 |
- #' as well as to save it to file in order to share it with an app developer or other users,+ #' hist(data()[["new_iris"]]$Sepal.Length) |
||
8 | +65 |
- #' who in turn can upload it to their own session.+ #' ) |
||
9 | +66 |
- #'+ #' }, |
||
10 | +67 |
- #' The snapshot manager is accessed with the camera icon in the tabset bar.+ #' ui = function(id, ...) { |
||
11 | +68 |
- #' At the beginning of a session it presents three icons: a camera, an upload, and an circular arrow.+ #' ns <- NS(id) |
||
12 | +69 |
- #' Clicking the camera captures a snapshot, clicking the upload adds a snapshot from a file+ #' plotOutput(ns("hist")) |
||
13 | +70 |
- #' and applies the filter states therein, and clicking the arrow resets initial application state.+ #' }, |
||
14 | +71 |
- #' As snapshots are added, they will show up as rows in a table and each will have a select button and a save button.+ #' datanames = "new_iris" |
||
15 | +72 |
- #'+ #' ) |
||
16 | +73 |
- #' @section Server logic:+ #' ), |
||
17 | +74 |
- #' Snapshots are basically `teal_slices` objects, however, since each module is served by a separate instance+ #' filter = teal_slices( |
||
18 | +75 |
- #' of `FilteredData` and these objects require shared state, `teal_slice` is a `reactiveVal` so `teal_slices`+ #' teal_slice(dataname = "new_iris", varname = "Species"), |
||
19 | +76 |
- #' cannot be stored as is. Therefore, `teal_slices` are reversibly converted to a list of lists representation+ #' teal_slice(dataname = "new_iris", varname = "Sepal.Length"), |
||
20 | +77 |
- #' (attributes are maintained).+ #' teal_slice(dataname = "new_mtcars", varname = "cyl"), |
||
21 | +78 |
- #'+ #' exclude_varnames = list(new_iris = c("Sepal.Width", "Petal.Width")), |
||
22 | +79 |
- #' Snapshots are stored in a `reactiveVal` as a named list.+ #' module_specific = TRUE, |
||
23 | +80 |
- #' The first snapshot is the initial state of the application and the user can add a snapshot whenever they see fit.+ #' mapping = list( |
||
24 | +81 |
- #'+ #' `example teal module` = "new_iris Species", |
||
25 | +82 |
- #' For every snapshot except the initial one, a piece of UI is generated that contains+ #' `Iris Sepal.Length histogram` = "new_iris Species", |
||
26 | +83 |
- #' the snapshot name, a select button to restore that snapshot, and a save button to save it to a file.+ #' global_filters = "new_mtcars cyl" |
||
27 | +84 |
- #' The initial snapshot is restored by a separate "reset" button.+ #' ) |
||
28 | +85 |
- #' It cannot be saved directly but a user is welcome to capture the initial state as a snapshot and save that.+ #' ), |
||
29 | +86 |
- #'+ #' title = "App title", |
||
30 | +87 |
- #' @section Snapshot mechanics:+ #' header = tags$h1("Sample App"), |
||
31 | +88 |
- #' When a snapshot is captured, the user is prompted to name it.+ #' footer = tags$p("Sample footer") |
||
32 | +89 |
- #' Names are displayed as is but since they are used to create button ids,+ #' ) |
||
33 | +90 |
- #' under the hood they are converted to syntactically valid strings.+ #' if (interactive()) { |
||
34 | +91 |
- #' New snapshot names are validated so that their valid versions are unique.+ #' shinyApp(app$ui, app$server) |
||
35 | +92 |
- #' Leading and trailing white space is trimmed.+ #' } |
||
36 | +93 |
#' |
||
37 | +94 |
- #' The module can read the global state of the application from `slices_global` and `mapping_matrix`.+ init <- function(data, |
||
38 | +95 |
- #' The former provides a list of all existing `teal_slice`s and the latter says which slice is active in which module.+ modules, |
||
39 | +96 |
- #' Once a name has been accepted, `slices_global` is converted to a list of lists - a snapshot.+ filter = teal_slices(), |
||
40 | +97 |
- #' The snapshot contains the `mapping` attribute of the initial application state+ title = build_app_title(), |
||
41 | +98 |
- #' (or one that has been restored), which may not reflect the current one,+ header = tags$p(), |
||
42 | +99 |
- #' so `mapping_matrix` is transformed to obtain the current mapping, i.e. a list that,+ footer = tags$p(), |
||
43 | +100 |
- #' when passed to the `mapping` argument of [teal_slices()], would result in the current mapping.+ id = character(0), |
||
44 | +101 |
- #' This is substituted as the snapshot's `mapping` attribute and the snapshot is added to the snapshot list.+ landing_popup = NULL) { |
||
45 | -+ | |||
102 | +12x |
- #'+ logger::log_debug("init initializing teal app with: data ('{ class(data) }').") |
||
46 | +103 |
- #' To restore app state, a snapshot is retrieved from storage and rebuilt into a `teal_slices` object.+ |
||
47 | +104 |
- #' Then state of all `FilteredData` objects (provided in `datasets`) is cleared+ # argument checking (independent) |
||
48 | +105 |
- #' and set anew according to the `mapping` attribute of the snapshot.+ ## `data` |
||
49 | -+ | |||
106 | +12x |
- #' The snapshot is then set as the current content of `slices_global`.+ if (inherits(data, "TealData")) { |
||
50 | -+ | |||
107 | +! |
- #'+ lifecycle::deprecate_stop( |
||
51 | -+ | |||
108 | +! |
- #' To save a snapshot, the snapshot is retrieved and reassembled just like for restoring,+ when = "0.15.0", |
||
52 | -+ | |||
109 | +! |
- #' and then saved to file with [slices_store()].+ what = "init(data)", |
||
53 | -+ | |||
110 | +! |
- #'+ paste( |
||
54 | -+ | |||
111 | +! |
- #' When a snapshot is uploaded, it will first be added to storage just like a newly created one,+ "TealData is no longer supported. Use teal_data() instead.", |
||
55 | -+ | |||
112 | +! |
- #' and then used to restore app state much like a snapshot taken from storage.+ "Please follow migration instructions https://github.com/insightsengineering/teal/discussions/988." |
||
56 | +113 |
- #' Upon clicking the upload icon the user will be prompted for a file to upload+ ) |
||
57 | +114 |
- #' and may choose to name the new snapshot. The name defaults to the name of the file (the extension is dropped)+ ) |
||
58 | +115 |
- #' and normal naming rules apply. Loading the file yields a `teal_slices` object,+ } |
||
59 | -+ | |||
116 | +12x |
- #' which is disassembled for storage and used directly for restoring app state.+ checkmate::assert_multi_class(data, c("teal_data", "teal_data_module")) |
||
60 | -+ | |||
117 | +12x |
- #'+ checkmate::assert_class(landing_popup, "teal_module_landing", null.ok = TRUE) |
||
61 | +118 |
- #' @section Transferring snapshots:+ |
||
62 | +119 |
- #' Snapshots uploaded from disk should only be used in the same application they come from,+ ## `modules` |
||
63 | -+ | |||
120 | +12x |
- #' _i.e._ an application that uses the same data and the same modules.+ checkmate::assert( |
||
64 | -+ | |||
121 | +12x |
- #' To ensure this is the case, `init` stamps `teal_slices` with an app id that is stored in the `app_id` attribute of+ .var.name = "modules", |
||
65 | -+ | |||
122 | +12x |
- #' a `teal_slices` object. When a snapshot is restored from file, its `app_id` is compared to that+ checkmate::check_multi_class(modules, c("teal_modules", "teal_module")), |
||
66 | -+ | |||
123 | +12x |
- #' of the current app state and only if the match is the snapshot admitted to the session.+ checkmate::check_list(modules, min.len = 1, any.missing = FALSE, types = c("teal_module", "teal_modules")) |
||
67 | +124 |
- #'+ ) |
||
68 | -+ | |||
125 | +12x |
- #' @section Bookmarks:+ if (inherits(modules, "teal_module")) { |
||
69 | -+ | |||
126 | +1x |
- #' An `onBookmark` callback creates a snapshot of the current filter state.+ modules <- list(modules) |
||
70 | +127 |
- #' This is done on the app session, not the module session.+ } |
||
71 | -+ | |||
128 | +12x |
- #' (The snapshot will be retrieved by `module_teal` in order to set initial app state in a restored app.)+ if (checkmate::test_list(modules, min.len = 1, any.missing = FALSE, types = c("teal_module", "teal_modules"))) { |
||
72 | -+ | |||
129 | +6x |
- #' Then that snapshot, and the previous snapshot history are dumped into the `values.rds` file in `<bookmark_dir>`.+ modules <- do.call(teal::modules, modules) |
||
73 | +130 |
- #'+ } |
||
74 | +131 |
- #' @param id (`character(1)`) `shiny` module instance id.+ |
||
75 | +132 |
- #' @param slices_global (`reactiveVal`) that contains a `teal_slices` object+ ## `filter` |
||
76 | -+ | |||
133 | +12x |
- #' containing all `teal_slice`s existing in the app, both active and inactive.+ checkmate::assert_class(filter, "teal_slices") |
||
77 | +134 |
- #'+ |
||
78 | +135 |
- #' @return `list` containing the snapshot history, where each element is an unlisted `teal_slices` object.+ ## all other arguments |
||
79 | -+ | |||
136 | +11x |
- #'+ checkmate::assert( |
||
80 | -+ | |||
137 | +11x |
- #' @name module_snapshot_manager+ .var.name = "title", |
||
81 | -+ | |||
138 | +11x |
- #' @rdname module_snapshot_manager+ checkmate::check_string(title), |
||
82 | -+ | |||
139 | +11x |
- #'+ checkmate::check_multi_class(title, c("shiny.tag", "shiny.tag.list", "html")) |
||
83 | +140 |
- #' @author Aleksander Chlebowski+ ) |
||
84 | -+ | |||
141 | +11x |
- #' @keywords internal+ checkmate::assert( |
||
85 | -+ | |||
142 | +11x |
- NULL+ .var.name = "header", |
||
86 | -+ | |||
143 | +11x |
-
+ checkmate::check_string(header), |
||
87 | -+ | |||
144 | +11x |
- #' @rdname module_snapshot_manager+ checkmate::check_multi_class(header, c("shiny.tag", "shiny.tag.list", "html")) |
||
88 | +145 |
- ui_snapshot_manager_panel <- function(id) {+ ) |
||
89 | -! | +|||
146 | +11x |
- ns <- NS(id)+ checkmate::assert( |
||
90 | -! | +|||
147 | +11x |
- tags$button(+ .var.name = "footer", |
||
91 | -! | +|||
148 | +11x |
- id = ns("show_snapshot_manager"),+ checkmate::check_string(footer), |
||
92 | -! | +|||
149 | +11x |
- class = "btn action-button wunder_bar_button",+ checkmate::check_multi_class(footer, c("shiny.tag", "shiny.tag.list", "html")) |
||
93 | -! | +|||
150 | +
- title = "View filter mapping",+ ) |
|||
94 | -! | +|||
151 | +11x |
- suppressMessages(icon("fas fa-camera"))+ checkmate::assert_character(id, max.len = 1, any.missing = FALSE) |
||
95 | +152 |
- )+ |
||
96 | +153 |
- }+ # log+ |
+ ||
154 | +11x | +
+ teal.logger::log_system_info() |
||
97 | +155 | |||
98 | +156 |
- #' @rdname module_snapshot_manager+ # argument transformations |
||
99 | +157 |
- srv_snapshot_manager_panel <- function(id, slices_global) {+ ## `modules` - landing module |
||
100 | -82x | +158 | +11x |
- moduleServer(id, function(input, output, session) {+ landing <- extract_module(modules, "teal_module_landing") |
101 | -82x | +159 | +11x |
- logger::log_debug("srv_snapshot_manager_panel initializing")+ if (length(landing) == 1L) { |
102 | -82x | +|||
160 | +! |
- setBookmarkExclude(c("show_snapshot_manager"))+ landing_popup <- landing[[1L]] |
||
103 | -82x | +|||
161 | +! |
- observeEvent(input$show_snapshot_manager, {+ modules <- drop_module(modules, "teal_module_landing") |
||
104 | +162 | ! |
- logger::log_debug("srv_snapshot_manager_panel@1 show_snapshot_manager button has been clicked.")+ lifecycle::deprecate_soft( |
|
105 | +163 | ! |
- showModal(+ when = "0.15.3", |
|
106 | +164 | ! |
- modalDialog(+ what = "landing_popup_module()", |
|
107 | +165 | ! |
- ui_snapshot_manager(session$ns("module")),+ details = paste( |
|
108 | +166 | ! |
- class = "snapshot_manager_modal",+ "Pass `landing_popup_module` to the `landing_popup` argument of the `init` ", |
|
109 | +167 | ! |
- size = "m",+ "instead of wrapping it into `modules()` and passing to the `modules` argument" |
|
110 | -! | +|||
168 | +
- footer = NULL,+ )+ |
+ |||
169 | ++ |
+ )+ |
+ ||
170 | +11x | +
+ } else if (length(landing) > 1L) { |
||
111 | +171 | ! |
- easyClose = TRUE+ stop("Only one `landing_popup_module` can be used.") |
|
112 | +172 |
- )+ } |
||
113 | +173 |
- )+ |
||
114 | +174 |
- })+ ## `filter` - set app_id attribute unless present (when restoring bookmark) |
||
115 | -82x | +175 | +11x |
- srv_snapshot_manager("module", slices_global = slices_global)+ if (is.null(attr(filter, "app_id", exact = TRUE))) attr(filter, "app_id") <- create_app_id(data, modules) |
116 | +176 |
- })+ |
||
117 | +177 |
- }+ ## `filter` - convert teal.slice::teal_slices to teal::teal_slices+ |
+ ||
178 | +11x | +
+ filter <- as.teal_slices(as.list(filter)) |
||
118 | +179 | |||
119 | +180 |
- #' @rdname module_snapshot_manager+ # argument checking (interdependent) |
||
120 | +181 |
- ui_snapshot_manager <- function(id) {+ ## `filter` - `modules` |
||
121 | -! | +|||
182 | +11x |
- ns <- NS(id)+ if (isTRUE(attr(filter, "module_specific"))) { |
||
122 | +183 | ! |
- tags$div(+ module_names <- unlist(c(module_labels(modules), "global_filters")) |
|
123 | +184 | ! |
- class = "manager_content",+ failed_mod_names <- setdiff(names(attr(filter, "mapping")), module_names) |
|
124 | +185 | ! |
- tags$div(+ if (length(failed_mod_names)) { |
|
125 | +186 | ! |
- class = "manager_table_row",+ stop( |
|
126 | +187 | ! |
- tags$span(tags$b("Snapshot manager")),+ sprintf( |
|
127 | +188 | ! |
- actionLink(ns("snapshot_add"), label = NULL, icon = icon("fas fa-camera"), title = "add snapshot"),+ "Some module names in the mapping arguments don't match module labels.\n %s not in %s", |
|
128 | +189 | ! |
- actionLink(ns("snapshot_load"), label = NULL, icon = icon("fas fa-upload"), title = "upload snapshot"),+ toString(failed_mod_names), |
|
129 | +190 | ! |
- actionLink(ns("snapshot_reset"), label = NULL, icon = icon("fas fa-undo"), title = "reset initial state"),+ toString(unique(module_names)) |
|
130 | -! | +|||
191 | +
- NULL+ ) |
|||
131 | +192 |
- ),+ ) |
||
132 | -! | +|||
193 | +
- uiOutput(ns("snapshot_list"))+ } |
|||
133 | +194 |
- )+ |
||
134 | -+ | |||
195 | +! |
- }+ if (anyDuplicated(module_names)) { |
||
135 | +196 |
-
+ # In teal we are able to set nested modules with duplicated label. |
||
136 | +197 |
- #' @rdname module_snapshot_manager+ # Because mapping argument bases on the relationship between module-label and filter-id, |
||
137 | +198 |
- srv_snapshot_manager <- function(id, slices_global) {+ # it is possible that module-label in mapping might refer to multiple teal_module (identified by the same label) |
||
138 | -82x | +|||
199 | +! |
- checkmate::assert_character(id)+ stop( |
||
139 | -+ | |||
200 | +! |
-
+ sprintf( |
||
140 | -82x | +|||
201 | +! |
- moduleServer(id, function(input, output, session) {+ "Module labels should be unique when teal_slices(mapping = TRUE). Duplicated labels:\n%s ", |
||
141 | -82x | +|||
202 | +! |
- logger::log_debug("srv_snapshot_manager initializing")+ toString(module_names[duplicated(module_names)]) |
||
142 | +203 |
-
+ ) |
||
143 | +204 |
- # Set up bookmarking callbacks ----+ ) |
||
144 | +205 |
- # Register bookmark exclusions (all buttons and text fields).+ } |
||
145 | -82x | +|||
206 | +
- setBookmarkExclude(c(+ }+ |
+ |||
207 | ++ | + + | +||
208 | ++ |
+ ## `data` - `modules` |
||
146 | -82x | +209 | +11x |
- "snapshot_add", "snapshot_load", "snapshot_reset",+ if (inherits(data, "teal_data")) { |
147 | -82x | +210 | +10x |
- "snapshot_name_accept", "snaphot_file_accept",+ if (length(data) == 0) { |
148 | -82x | +211 | +1x |
- "snapshot_name", "snapshot_file"+ stop("The environment of `data` is empty.") |
149 | +212 |
- ))+ } |
||
150 | +213 |
- # Add snapshot history to bookmark.+ |
||
151 | -82x | +214 | +9x |
- session$onBookmark(function(state) {- |
-
152 | -! | -
- logger::log_debug("srv_snapshot_manager@onBookmark: storing snapshot and bookmark history")- |
- ||
153 | -! | -
- state$values$snapshot_history <- snapshot_history() # isolate this?- |
- ||
154 | -- |
- })- |
- ||
155 | -- |
-
+ is_modules_ok <- check_modules_datanames(modules, names(data)) |
||
156 | -82x | +215 | +9x |
- ns <- session$ns+ if (!isTRUE(is_modules_ok) && length(unlist(extract_transformers(modules))) == 0) { |
157 | -+ | |||
216 | +2x |
-
+ warning(is_modules_ok, call. = FALSE) |
||
158 | +217 |
- # Track global filter states ----- |
- ||
159 | -82x | -
- snapshot_history <- reactiveVal({+ } |
||
160 | +218 |
- # Restore directly from bookmarked state, if applicable.+ |
||
161 | -82x | +219 | +9x |
- restoreValue(+ is_filter_ok <- check_filter_datanames(filter, names(data)) |
162 | -82x | +220 | +9x |
- ns("snapshot_history"),+ if (!isTRUE(is_filter_ok)) { |
163 | -82x | +221 | +1x |
- list("Initial application state" = shiny::isolate(as.list(slices_global$all_slices(), recursive = TRUE)))+ warning(is_filter_ok) |
164 | +222 |
- )+ # we allow app to continue if applied filters are outside |
||
165 | +223 |
- })+ # of possible data range |
||
166 | +224 |
-
+ } |
||
167 | +225 |
- # Snapshot current application state ----+ } |
||
168 | +226 |
- # Name snaphsot.+ |
||
169 | -82x | -
- observeEvent(input$snapshot_add, {- |
- ||
170 | -! | -
- logger::log_debug("srv_snapshot_manager: snapshot_add button clicked")- |
- ||
171 | -! | -
- showModal(- |
- ||
172 | -! | +227 | +10x |
- modalDialog(+ reporter <- teal.reporter::Reporter$new()$set_id(attr(filter, "app_id")) |
173 | -! | +|||
228 | +10x |
- textInput(ns("snapshot_name"), "Name the snapshot", width = "100%", placeholder = "Meaningful, unique name"),+ if (is_arg_used(modules, "reporter") && length(extract_module(modules, "teal_module_previewer")) == 0) { |
||
174 | +229 | ! |
- footer = tagList(+ modules <- append_module( |
|
175 | +230 | ! |
- actionButton(ns("snapshot_name_accept"), "Accept", icon = icon("far fa-thumbs-up")),+ modules, |
|
176 | +231 | ! |
- modalButton(label = "Cancel", icon = icon("far fa-thumbs-down"))+ reporter_previewer_module(server_args = list(previewer_buttons = c("download", "reset"))) |
|
177 | +232 |
- ),- |
- ||
178 | -! | -
- size = "s"+ ) |
||
179 | +233 |
- )+ } |
||
180 | +234 |
- )+ |
||
181 | -+ | |||
235 | +10x |
- })+ ns <- NS(id) |
||
182 | +236 |
- # Store snaphsot.+ # Note: UI must be a function to support bookmarking. |
||
183 | -82x | +237 | +10x |
- observeEvent(input$snapshot_name_accept, {+ res <- list( |
184 | -! | +|||
238 | +10x |
- logger::log_debug("srv_snapshot_manager: snapshot_name_accept button clicked")+ ui = function(request) { |
||
185 | +239 | ! |
- snapshot_name <- trimws(input$snapshot_name)+ ui_teal( |
|
186 | +240 | ! |
- if (identical(snapshot_name, "")) {+ id = ns("teal"), |
|
187 | +241 | ! |
- logger::log_debug("srv_snapshot_manager: snapshot name rejected")+ modules = modules, |
|
188 | +242 | ! |
- showNotification(+ title = title, |
|
189 | +243 | ! |
- "Please name the snapshot.",+ header = header, |
|
190 | +244 | ! |
- type = "message"+ footer = footer |
|
191 | +245 |
- )+ ) |
||
192 | -! | +|||
246 | +
- updateTextInput(inputId = "snapshot_name", value = "", placeholder = "Meaningful, unique name")+ }, |
|||
193 | -! | +|||
247 | +10x |
- } else if (is.element(make.names(snapshot_name), make.names(names(snapshot_history())))) {+ server = function(input, output, session) { |
||
194 | +248 | ! |
- logger::log_debug("srv_snapshot_manager: snapshot name rejected")+ if (!is.null(landing_popup)) { |
|
195 | +249 | ! |
- showNotification(+ do.call(landing_popup$server, c(list(id = "landing_module_shiny_id"), landing_popup$server_args)) |
|
196 | -! | +|||
250 | +
- "This name is in conflict with other snapshot names. Please choose a different one.",+ } |
|||
197 | +251 | ! |
- type = "message"+ srv_teal(id = ns("teal"), data = data, modules = modules, filter = deep_copy_filter(filter)) |
|
198 | +252 |
- )+ } |
||
199 | -! | +|||
253 | +
- updateTextInput(inputId = "snapshot_name", value = "", placeholder = "Meaningful, unique name")+ ) |
|||
200 | +254 |
- } else {+ |
||
201 | -! | +|||
255 | +10x |
- logger::log_debug("srv_snapshot_manager: snapshot name accepted, adding snapshot")+ logger::log_debug("init teal app has been initialized.") |
||
202 | -! | +|||
256 | +
- snapshot <- as.list(slices_global$all_slices(), recursive = TRUE)+ |
|||
203 | -! | +|||
257 | +10x |
- snapshot_update <- c(snapshot_history(), list(snapshot))+ res |
||
204 | -! | +|||
258 | +
- names(snapshot_update)[length(snapshot_update)] <- snapshot_name+ } |
|||
205 | -! | +
1 | +
- snapshot_history(snapshot_update)+ #' Filter state snapshot management |
|||
206 | -! | +|||
2 | +
- removeModal()+ #' |
|||
207 | +3 |
- # Reopen filter manager modal by clicking button in the main application.+ #' Capture and restore snapshots of the global (app) filter state. |
||
208 | -! | +|||
4 | +
- shinyjs::click(id = "teal-wunder_bar-show_snapshot_manager", asis = TRUE)+ #' |
|||
209 | +5 |
- }+ #' This module introduces snapshots: stored descriptions of the filter state of the entire application. |
||
210 | +6 |
- })+ #' Snapshots allow the user to save the current filter state of the application for later use in the session, |
||
211 | +7 |
-
+ #' as well as to save it to file in order to share it with an app developer or other users, |
||
212 | +8 |
- # Upload a snapshot file ----+ #' who in turn can upload it to their own session. |
||
213 | +9 |
- # Select file.+ #' |
||
214 | -82x | +|||
10 | +
- observeEvent(input$snapshot_load, {+ #' The snapshot manager is accessed with the camera icon in the tabset bar. |
|||
215 | -! | +|||
11 | +
- logger::log_debug("srv_snapshot_manager: snapshot_load button clicked")+ #' At the beginning of a session it presents three icons: a camera, an upload, and an circular arrow. |
|||
216 | -! | +|||
12 | +
- showModal(+ #' Clicking the camera captures a snapshot, clicking the upload adds a snapshot from a file |
|||
217 | -! | +|||
13 | +
- modalDialog(+ #' and applies the filter states therein, and clicking the arrow resets initial application state. |
|||
218 | -! | +|||
14 | +
- fileInput(ns("snapshot_file"), "Choose snapshot file", accept = ".json", width = "100%"),+ #' As snapshots are added, they will show up as rows in a table and each will have a select button and a save button. |
|||
219 | -! | +|||
15 | +
- textInput(+ #' |
|||
220 | -! | +|||
16 | +
- ns("snapshot_name"),+ #' @section Server logic: |
|||
221 | -! | +|||
17 | +
- "Name the snapshot (optional)",+ #' Snapshots are basically `teal_slices` objects, however, since each module is served by a separate instance |
|||
222 | -! | +|||
18 | +
- width = "100%",+ #' of `FilteredData` and these objects require shared state, `teal_slice` is a `reactiveVal` so `teal_slices` |
|||
223 | -! | +|||
19 | +
- placeholder = "Meaningful, unique name"+ #' cannot be stored as is. Therefore, `teal_slices` are reversibly converted to a list of lists representation |
|||
224 | +20 |
- ),+ #' (attributes are maintained). |
||
225 | -! | +|||
21 | +
- footer = tagList(+ #' |
|||
226 | -! | +|||
22 | +
- actionButton(ns("snaphot_file_accept"), "Accept", icon = icon("far fa-thumbs-up")),+ #' Snapshots are stored in a `reactiveVal` as a named list. |
|||
227 | -! | +|||
23 | +
- modalButton(label = "Cancel", icon = icon("far fa-thumbs-down"))+ #' The first snapshot is the initial state of the application and the user can add a snapshot whenever they see fit. |
|||
228 | +24 |
- )+ #' |
||
229 | +25 |
- )+ #' For every snapshot except the initial one, a piece of UI is generated that contains |
||
230 | +26 |
- )+ #' the snapshot name, a select button to restore that snapshot, and a save button to save it to a file. |
||
231 | +27 |
- })+ #' The initial snapshot is restored by a separate "reset" button. |
||
232 | +28 |
- # Store new snapshot to list and restore filter states.+ #' It cannot be saved directly but a user is welcome to capture the initial state as a snapshot and save that. |
||
233 | -82x | +|||
29 | +
- observeEvent(input$snaphot_file_accept, {+ #' |
|||
234 | -! | +|||
30 | +
- logger::log_debug("srv_snapshot_manager: snapshot_file_accept button clicked")+ #' @section Snapshot mechanics: |
|||
235 | -! | +|||
31 | +
- snapshot_name <- trimws(input$snapshot_name)+ #' When a snapshot is captured, the user is prompted to name it. |
|||
236 | -! | +|||
32 | +
- if (identical(snapshot_name, "")) {+ #' Names are displayed as is but since they are used to create button ids, |
|||
237 | -! | +|||
33 | +
- logger::log_debug("srv_snapshot_manager: no snapshot name provided, naming after file")+ #' under the hood they are converted to syntactically valid strings. |
|||
238 | -! | +|||
34 | +
- snapshot_name <- tools::file_path_sans_ext(input$snapshot_file$name)+ #' New snapshot names are validated so that their valid versions are unique. |
|||
239 | +35 |
- }+ #' Leading and trailing white space is trimmed. |
||
240 | -! | +|||
36 | +
- if (is.element(make.names(snapshot_name), make.names(names(snapshot_history())))) {+ #' |
|||
241 | -! | +|||
37 | +
- logger::log_debug("srv_snapshot_manager: snapshot name rejected")+ #' The module can read the global state of the application from `slices_global` and `mapping_matrix`. |
|||
242 | -! | +|||
38 | +
- showNotification(+ #' The former provides a list of all existing `teal_slice`s and the latter says which slice is active in which module. |
|||
243 | -! | +|||
39 | +
- "This name is in conflict with other snapshot names. Please choose a different one.",+ #' Once a name has been accepted, `slices_global` is converted to a list of lists - a snapshot. |
|||
244 | -! | +|||
40 | +
- type = "message"+ #' The snapshot contains the `mapping` attribute of the initial application state |
|||
245 | +41 |
- )+ #' (or one that has been restored), which may not reflect the current one, |
||
246 | -! | +|||
42 | +
- updateTextInput(inputId = "snapshot_name", value = "", placeholder = "Meaningful, unique name")+ #' so `mapping_matrix` is transformed to obtain the current mapping, i.e. a list that, |
|||
247 | +43 |
- } else {+ #' when passed to the `mapping` argument of [teal_slices()], would result in the current mapping. |
||
248 | +44 |
- # Restore snapshot and verify app compatibility.+ #' This is substituted as the snapshot's `mapping` attribute and the snapshot is added to the snapshot list. |
||
249 | -! | +|||
45 | +
- logger::log_debug("srv_snapshot_manager: snapshot name accepted, loading snapshot")+ #' |
|||
250 | -! | +|||
46 | +
- snapshot_state <- try(slices_restore(input$snapshot_file$datapath))+ #' To restore app state, a snapshot is retrieved from storage and rebuilt into a `teal_slices` object. |
|||
251 | -! | +|||
47 | +
- if (!inherits(snapshot_state, "modules_teal_slices")) {+ #' Then state of all `FilteredData` objects (provided in `datasets`) is cleared |
|||
252 | -! | +|||
48 | +
- logger::log_debug("srv_snapshot_manager: snapshot file corrupt")+ #' and set anew according to the `mapping` attribute of the snapshot. |
|||
253 | -! | +|||
49 | +
- showNotification(+ #' The snapshot is then set as the current content of `slices_global`. |
|||
254 | -! | +|||
50 | +
- "File appears to be corrupt.",+ #' |
|||
255 | -! | +|||
51 | +
- type = "error"+ #' To save a snapshot, the snapshot is retrieved and reassembled just like for restoring, |
|||
256 | +52 |
- )+ #' and then saved to file with [slices_store()]. |
||
257 | -! | +|||
53 | +
- } else if (!identical(attr(snapshot_state, "app_id"), attr(slices_global$all_slices(), "app_id"))) {+ #' |
|||
258 | -! | +|||
54 | +
- logger::log_debug("srv_snapshot_manager: snapshot not compatible with app")+ #' When a snapshot is uploaded, it will first be added to storage just like a newly created one, |
|||
259 | -! | +|||
55 | +
- showNotification(+ #' and then used to restore app state much like a snapshot taken from storage. |
|||
260 | -! | +|||
56 | +
- "This snapshot file is not compatible with the app and cannot be loaded.",+ #' Upon clicking the upload icon the user will be prompted for a file to upload |
|||
261 | -! | +|||
57 | +
- type = "warning"+ #' and may choose to name the new snapshot. The name defaults to the name of the file (the extension is dropped) |
|||
262 | +58 |
- )+ #' and normal naming rules apply. Loading the file yields a `teal_slices` object, |
||
263 | +59 |
- } else {+ #' which is disassembled for storage and used directly for restoring app state. |
||
264 | +60 |
- # Add to snapshot history.+ #' |
||
265 | -! | +|||
61 | +
- logger::log_debug("srv_snapshot_manager: snapshot loaded, adding to history")+ #' @section Transferring snapshots: |
|||
266 | -! | +|||
62 | +
- snapshot <- as.list(slices_global$all_slices(), recursive = TRUE)+ #' Snapshots uploaded from disk should only be used in the same application they come from, |
|||
267 | -! | +|||
63 | +
- snapshot_update <- c(snapshot_history(), list(snapshot))+ #' _i.e._ an application that uses the same data and the same modules. |
|||
268 | -! | +|||
64 | +
- names(snapshot_update)[length(snapshot_update)] <- snapshot_name+ #' To ensure this is the case, `init` stamps `teal_slices` with an app id that is stored in the `app_id` attribute of |
|||
269 | -! | +|||
65 | +
- snapshot_history(snapshot_update)+ #' a `teal_slices` object. When a snapshot is restored from file, its `app_id` is compared to that |
|||
270 | +66 |
- ### Begin simplified restore procedure. ###+ #' of the current app state and only if the match is the snapshot admitted to the session. |
||
271 | -! | +|||
67 | +
- logger::log_debug("srv_snapshot_manager: restoring snapshot")+ #' |
|||
272 | -! | +|||
68 | +
- slices_global$slices_set(snapshot_state)+ #' @section Bookmarks: |
|||
273 | -! | +|||
69 | +
- removeModal()+ #' An `onBookmark` callback creates a snapshot of the current filter state. |
|||
274 | +70 |
- ### End simplified restore procedure. ###+ #' This is done on the app session, not the module session. |
||
275 | +71 |
- }+ #' (The snapshot will be retrieved by `module_teal` in order to set initial app state in a restored app.) |
||
276 | +72 |
- }+ #' Then that snapshot, and the previous snapshot history are dumped into the `values.rds` file in `<bookmark_dir>`. |
||
277 | +73 |
- })+ #' |
||
278 | +74 |
- # Apply newly added snapshot.+ #' @param id (`character(1)`) `shiny` module instance id. |
||
279 | +75 |
-
+ #' @param slices_global (`reactiveVal`) that contains a `teal_slices` object |
||
280 | +76 |
- # Restore initial state ----+ #' containing all `teal_slice`s existing in the app, both active and inactive. |
||
281 | -82x | +|||
77 | +
- observeEvent(input$snapshot_reset, {+ #' |
|||
282 | -2x | +|||
78 | +
- logger::log_debug("srv_snapshot_manager: snapshot_reset button clicked, restoring snapshot")+ #' @return `list` containing the snapshot history, where each element is an unlisted `teal_slices` object. |
|||
283 | -2x | +|||
79 | +
- s <- "Initial application state"+ #' |
|||
284 | +80 |
- ### Begin restore procedure. ###+ #' @name module_snapshot_manager |
||
285 | -2x | +|||
81 | +
- snapshot <- snapshot_history()[[s]]+ #' @rdname module_snapshot_manager |
|||
286 | +82 |
- # todo: as.teal_slices looses module-mapping if is not global+ #' |
||
287 | -2x | +|||
83 | +
- snapshot_state <- as.teal_slices(snapshot)+ #' @author Aleksander Chlebowski |
|||
288 | -2x | +|||
84 | +
- slices_global$slices_set(snapshot_state)+ #' @keywords internal |
|||
289 | -2x | +|||
85 | +
- removeModal()+ NULL |
|||
290 | +86 |
- ### End restore procedure. ###+ |
||
291 | +87 |
- })+ #' @rdname module_snapshot_manager |
||
292 | +88 |
-
+ ui_snapshot_manager_panel <- function(id) {+ |
+ ||
89 | +! | +
+ ns <- NS(id)+ |
+ ||
90 | +! | +
+ tags$button(+ |
+ ||
91 | +! | +
+ id = ns("show_snapshot_manager"),+ |
+ ||
92 | +! | +
+ class = "btn action-button wunder_bar_button",+ |
+ ||
93 | +! | +
+ title = "View filter mapping",+ |
+ ||
94 | +! | +
+ suppressMessages(icon("fas fa-camera")) |
||
293 | +95 |
- # Build snapshot table ----+ ) |
||
294 | +96 |
- # Create UI elements and server logic for the snapshot table.+ } |
||
295 | +97 |
- # Observers must be tracked to avoid duplication and excess reactivity.+ |
||
296 | +98 |
- # Remaining elements are tracked likewise for consistency and a slight speed margin.+ #' @rdname module_snapshot_manager |
||
297 | -82x | +|||
99 | +
- observers <- reactiveValues()+ srv_snapshot_manager_panel <- function(id, slices_global) { |
|||
298 | +100 | 82x |
- handlers <- reactiveValues()+ moduleServer(id, function(input, output, session) { |
|
299 | +101 | 82x |
- divs <- reactiveValues()- |
- |
300 | -- |
-
+ logger::log_debug("srv_snapshot_manager_panel initializing") |
||
301 | +102 | 82x |
- observeEvent(snapshot_history(), {+ setBookmarkExclude(c("show_snapshot_manager")) |
|
302 | -72x | +103 | +82x |
- logger::log_debug("srv_snapshot_manager: snapshot history modified, updating snapshot list")+ observeEvent(input$show_snapshot_manager, { |
303 | -72x | +|||
104 | +! |
- lapply(names(snapshot_history())[-1L], function(s) {+ logger::log_debug("srv_snapshot_manager_panel@1 show_snapshot_manager button has been clicked.") |
||
304 | +105 | ! |
- id_pickme <- sprintf("pickme_%s", make.names(s))+ showModal( |
|
305 | +106 | ! |
- id_saveme <- sprintf("saveme_%s", make.names(s))+ modalDialog( |
|
306 | +107 | ! |
- id_rowme <- sprintf("rowme_%s", make.names(s))+ ui_snapshot_manager(session$ns("module")), |
|
307 | -+ | |||
108 | +! |
-
+ class = "snapshot_manager_modal", |
||
308 | -+ | |||
109 | +! |
- # Observer for restoring snapshot.+ size = "m", |
||
309 | +110 | ! |
- if (!is.element(id_pickme, names(observers))) {+ footer = NULL, |
|
310 | +111 | ! |
- observers[[id_pickme]] <- observeEvent(input[[id_pickme]], {+ easyClose = TRUE |
|
311 | +112 |
- ### Begin restore procedure. ###+ ) |
||
312 | -! | +|||
113 | +
- snapshot <- snapshot_history()[[s]]- |
- |||
313 | -! | -
- snapshot_state <- as.teal_slices(snapshot)+ ) |
||
314 | +114 |
-
+ }) |
||
315 | -! | +|||
115 | +82x |
- slices_global$slices_set(snapshot_state)+ srv_snapshot_manager("module", slices_global = slices_global) |
||
316 | -! | +|||
116 | +
- removeModal()+ }) |
|||
317 | +117 |
- ### End restore procedure. ###+ } |
||
318 | +118 |
- })+ |
||
319 | +119 |
- }+ #' @rdname module_snapshot_manager |
||
320 | +120 |
- # Create handler for downloading snapshot.+ ui_snapshot_manager <- function(id) { |
||
321 | +121 | ! |
- if (!is.element(id_saveme, names(handlers))) {+ ns <- NS(id) |
|
322 | +122 | ! |
- output[[id_saveme]] <- downloadHandler(+ tags$div( |
|
323 | +123 | ! |
- filename = function() {+ class = "manager_content", |
|
324 | +124 | ! |
- sprintf("teal_snapshot_%s_%s.json", s, Sys.Date())+ tags$div( |
|
325 | -+ | |||
125 | +! |
- },+ class = "manager_table_row", |
||
326 | +126 | ! |
- content = function(file) {+ tags$span(tags$b("Snapshot manager")), |
|
327 | +127 | ! |
- snapshot <- snapshot_history()[[s]]+ actionLink(ns("snapshot_add"), label = NULL, icon = icon("fas fa-camera"), title = "add snapshot"), |
|
328 | +128 | ! |
- snapshot_state <- as.teal_slices(snapshot)+ actionLink(ns("snapshot_load"), label = NULL, icon = icon("fas fa-upload"), title = "upload snapshot"), |
|
329 | +129 | ! |
- slices_store(tss = snapshot_state, file = file)+ actionLink(ns("snapshot_reset"), label = NULL, icon = icon("fas fa-undo"), title = "reset initial state"), |
|
330 | -+ | |||
130 | +! |
- }+ NULL |
||
331 | +131 |
- )+ ), |
||
332 | +132 | ! |
- handlers[[id_saveme]] <- id_saveme+ uiOutput(ns("snapshot_list")) |
|
333 | +133 |
- }+ ) |
||
334 | +134 |
- # Create a row for the snapshot table.- |
- ||
335 | -! | -
- if (!is.element(id_rowme, names(divs))) {- |
- ||
336 | -! | -
- divs[[id_rowme]] <- tags$div(+ } |
||
337 | -! | +|||
135 | +
- class = "manager_table_row",+ |
|||
338 | -! | +|||
136 | +
- tags$span(tags$h5(s)),+ #' @rdname module_snapshot_manager |
|||
339 | -! | +|||
137 | +
- actionLink(inputId = ns(id_pickme), label = icon("far fa-circle-check"), title = "select"),+ srv_snapshot_manager <- function(id, slices_global) { |
|||
340 | -! | +|||
138 | +82x |
- downloadLink(outputId = ns(id_saveme), label = icon("far fa-save"), title = "save to file")+ checkmate::assert_character(id) |
||
341 | +139 |
- )+ |
||
342 | -+ | |||
140 | +82x |
- }+ moduleServer(id, function(input, output, session) { |
||
343 | -+ | |||
141 | +82x |
- })+ logger::log_debug("srv_snapshot_manager initializing") |
||
344 | +142 |
- })+ |
||
345 | +143 |
-
+ # Set up bookmarking callbacks ---- |
||
346 | +144 |
- # Create table to display list of snapshots and their actions.+ # Register bookmark exclusions (all buttons and text fields). |
||
347 | +145 | 82x |
- output$snapshot_list <- renderUI({- |
- |
348 | -72x | -
- rows <- rev(reactiveValuesToList(divs))+ setBookmarkExclude(c( |
||
349 | -72x | +146 | +82x |
- if (length(rows) == 0L) {+ "snapshot_add", "snapshot_load", "snapshot_reset", |
350 | -72x | +147 | +82x |
- tags$div(+ "snapshot_name_accept", "snaphot_file_accept", |
351 | -72x | +148 | +82x |
- class = "manager_placeholder",+ "snapshot_name", "snapshot_file" |
352 | -72x | +|||
149 | +
- "Snapshots will appear here."+ )) |
|||
353 | +150 |
- )+ # Add snapshot history to bookmark. |
||
354 | -+ | |||
151 | +82x |
- } else {+ session$onBookmark(function(state) { |
||
355 | +152 | ! |
- rows+ logger::log_debug("srv_snapshot_manager@onBookmark: storing snapshot and bookmark history") |
|
356 | -+ | |||
153 | +! |
- }+ state$values$snapshot_history <- snapshot_history() # isolate this? |
||
357 | +154 |
}) |
||
358 | +155 | |||
359 | +156 | 82x |
- snapshot_history+ ns <- session$ns |
|
360 | +157 |
- })+ |
||
361 | +158 |
- }+ # Track global filter states ---- |
1 | -+ | |||
159 | +82x |
- #' `teal` main module+ snapshot_history <- reactiveVal({ |
||
2 | +160 |
- #'+ # Restore directly from bookmarked state, if applicable. |
||
3 | -+ | |||
161 | +82x |
- #' @description+ restoreValue( |
||
4 | -+ | |||
162 | +82x |
- #' `r lifecycle::badge("stable")`+ ns("snapshot_history"), |
||
5 | -+ | |||
163 | +82x |
- #' Module to create a `teal` app. This module can be called directly instead of [init()] and+ list("Initial application state" = shiny::isolate(as.list(slices_global$all_slices(), recursive = TRUE))) |
||
6 | +164 |
- #' included in your custom application. Please note that [init()] adds `reporter_previewer_module`+ ) |
||
7 | +165 |
- #' automatically, which is not a case when calling `ui/srv_teal` directly.+ }) |
||
8 | +166 |
- #'+ |
||
9 | +167 |
- #' @details+ # Snapshot current application state ---- |
||
10 | +168 |
- #'+ # Name snaphsot. |
||
11 | -+ | |||
169 | +82x |
- #' Module is responsible for creating the main `shiny` app layout and initializing all the necessary+ observeEvent(input$snapshot_add, { |
||
12 | -+ | |||
170 | +! |
- #' components. This module establishes reactive connection between the input `data` and every other+ logger::log_debug("srv_snapshot_manager: snapshot_add button clicked") |
||
13 | -+ | |||
171 | +! |
- #' component in the app. Reactive change of the `data` passed as an argument, reloads the app and+ showModal( |
||
14 | -+ | |||
172 | +! |
- #' possibly keeps all input settings the same so the user can continue where one left off.+ modalDialog( |
||
15 | -+ | |||
173 | +! |
- #'+ textInput(ns("snapshot_name"), "Name the snapshot", width = "100%", placeholder = "Meaningful, unique name"), |
||
16 | -+ | |||
174 | +! |
- #' ## data flow in `teal` application+ footer = tagList( |
||
17 | -+ | |||
175 | +! |
- #'+ actionButton(ns("snapshot_name_accept"), "Accept", icon = icon("far fa-thumbs-up")), |
||
18 | -+ | |||
176 | +! |
- #' This module supports multiple data inputs but eventually, they are all converted to `reactive`+ modalButton(label = "Cancel", icon = icon("far fa-thumbs-down")) |
||
19 | +177 |
- #' returning `teal_data` in this module. On this `reactive teal_data` object several actions are+ ), |
||
20 | -+ | |||
178 | +! |
- #' performed:+ size = "s" |
||
21 | +179 |
- #' - data loading in [`module_init_data`]+ ) |
||
22 | +180 |
- #' - data filtering in [`module_filter_data`]+ ) |
||
23 | +181 |
- #' - data transformation in [`module_transform_data`]+ }) |
||
24 | +182 |
- #'+ # Store snaphsot. |
||
25 | -+ | |||
183 | +82x |
- #' ## Fallback on failure+ observeEvent(input$snapshot_name_accept, { |
||
26 | -+ | |||
184 | +! |
- #'+ logger::log_debug("srv_snapshot_manager: snapshot_name_accept button clicked") |
||
27 | -+ | |||
185 | +! |
- #' `teal` is designed in such way that app will never crash if the error is introduced in any+ snapshot_name <- trimws(input$snapshot_name) |
||
28 | -+ | |||
186 | +! |
- #' custom `shiny` module provided by app developer (e.g. [teal_data_module()], [teal_transform_module()]).+ if (identical(snapshot_name, "")) { |
||
29 | -+ | |||
187 | +! |
- #' If any module returns a failing object, the app will halt the evaluation and display a warning message.+ logger::log_debug("srv_snapshot_manager: snapshot name rejected") |
||
30 | -+ | |||
188 | +! |
- #' App user should always have a chance to fix the improper input and continue without restarting the session.+ showNotification( |
||
31 | -+ | |||
189 | +! |
- #'+ "Please name the snapshot.", |
||
32 | -+ | |||
190 | +! |
- #' @rdname module_teal+ type = "message" |
||
33 | +191 |
- #' @name module_teal+ ) |
||
34 | -+ | |||
192 | +! |
- #'+ updateTextInput(inputId = "snapshot_name", value = "", placeholder = "Meaningful, unique name") |
||
35 | -+ | |||
193 | +! |
- #' @inheritParams module_init_data+ } else if (is.element(make.names(snapshot_name), make.names(names(snapshot_history())))) { |
||
36 | -+ | |||
194 | +! |
- #' @inheritParams init+ logger::log_debug("srv_snapshot_manager: snapshot name rejected") |
||
37 | -+ | |||
195 | +! |
- #'+ showNotification( |
||
38 | -- |
- #' @return `NULL` invisibly- |
- ||
39 | -- |
- NULL- |
- ||
40 | -- | - - | -||
41 | -- |
- #' @rdname module_teal- |
- ||
42 | -+ | |||
196 | +! |
- #' @export+ "This name is in conflict with other snapshot names. Please choose a different one.", |
||
43 | -+ | |||
197 | +! |
- ui_teal <- function(id,+ type = "message" |
||
44 | +198 |
- modules,+ ) |
||
45 | -+ | |||
199 | +! |
- title = build_app_title(),+ updateTextInput(inputId = "snapshot_name", value = "", placeholder = "Meaningful, unique name") |
||
46 | +200 |
- header = tags$p(),+ } else { |
||
47 | -+ | |||
201 | +! |
- footer = tags$p()) {+ logger::log_debug("srv_snapshot_manager: snapshot name accepted, adding snapshot") |
||
48 | +202 | ! |
- checkmate::assert_character(id, max.len = 1, any.missing = FALSE)+ snapshot <- as.list(slices_global$all_slices(), recursive = TRUE) |
|
49 | +203 | ! |
- checkmate::assert(+ snapshot_update <- c(snapshot_history(), list(snapshot)) |
|
50 | +204 | ! |
- .var.name = "title",+ names(snapshot_update)[length(snapshot_update)] <- snapshot_name |
|
51 | +205 | ! |
- checkmate::check_string(title),+ snapshot_history(snapshot_update) |
|
52 | +206 | ! |
- checkmate::check_multi_class(title, c("shiny.tag", "shiny.tag.list", "html"))+ removeModal() |
|
53 | +207 |
- )+ # Reopen filter manager modal by clicking button in the main application. |
||
54 | +208 | ! |
- checkmate::assert(+ shinyjs::click(id = "teal-wunder_bar-show_snapshot_manager", asis = TRUE) |
|
55 | -! | +|||
209 | +
- .var.name = "header",+ } |
|||
56 | -! | +|||
210 | +
- checkmate::check_string(header),+ }) |
|||
57 | -! | +|||
211 | +
- checkmate::check_multi_class(header, c("shiny.tag", "shiny.tag.list", "html"))+ |
|||
58 | +212 |
- )+ # Upload a snapshot file ---- |
||
59 | -! | +|||
213 | +
- checkmate::assert(+ # Select file. |
|||
60 | -! | +|||
214 | +82x |
- .var.name = "footer",+ observeEvent(input$snapshot_load, { |
||
61 | +215 | ! |
- checkmate::check_string(footer),+ logger::log_debug("srv_snapshot_manager: snapshot_load button clicked") |
|
62 | +216 | ! |
- checkmate::check_multi_class(footer, c("shiny.tag", "shiny.tag.list", "html"))- |
- |
63 | -- |
- )- |
- ||
64 | -- |
-
+ showModal( |
||
65 | +217 | ! |
- if (is.character(title)) {+ modalDialog( |
|
66 | +218 | ! |
- title <- build_app_title(title)- |
- |
67 | -- |
- } else {+ fileInput(ns("snapshot_file"), "Choose snapshot file", accept = ".json", width = "100%"), |
||
68 | +219 | ! |
- validate_app_title_tag(title)+ textInput( |
|
69 | -+ | |||
220 | +! |
- }+ ns("snapshot_name"), |
||
70 | -+ | |||
221 | +! |
-
+ "Name the snapshot (optional)", |
||
71 | +222 | ! |
- if (checkmate::test_string(header)) {+ width = "100%", |
|
72 | +223 | ! |
- header <- tags$p(header)+ placeholder = "Meaningful, unique name" |
|
73 | +224 |
- }+ ), |
||
74 | -+ | |||
225 | +! |
-
+ footer = tagList( |
||
75 | +226 | ! |
- if (checkmate::test_string(footer)) {+ actionButton(ns("snaphot_file_accept"), "Accept", icon = icon("far fa-thumbs-up")), |
|
76 | +227 | ! |
- footer <- tags$p(footer)+ modalButton(label = "Cancel", icon = icon("far fa-thumbs-down")) |
|
77 | +228 |
- }+ ) |
||
78 | +229 |
-
+ ) |
||
79 | -! | +|||
230 | +
- ns <- NS(id)+ ) |
|||
80 | +231 |
-
+ }) |
||
81 | +232 |
- # show busy icon when `shiny` session is busy computing stuff+ # Store new snapshot to list and restore filter states. |
||
82 | -+ | |||
233 | +82x |
- # based on https://stackoverflow.com/questions/17325521/r-shiny-display-loading-message-while-function-is-running/22475216#22475216 # nolint: line_length.+ observeEvent(input$snaphot_file_accept, { |
||
83 | +234 | ! |
- shiny_busy_message_panel <- conditionalPanel(+ logger::log_debug("srv_snapshot_manager: snapshot_file_accept button clicked") |
|
84 | +235 | ! |
- condition = "(($('html').hasClass('shiny-busy')) && (document.getElementById('shiny-notification-panel') == null))", # nolint: line_length.+ snapshot_name <- trimws(input$snapshot_name) |
|
85 | +236 | ! |
- tags$div(+ if (identical(snapshot_name, "")) { |
|
86 | +237 | ! |
- icon("arrows-rotate", class = "fa-spin", prefer_type = "solid"),+ logger::log_debug("srv_snapshot_manager: no snapshot name provided, naming after file") |
|
87 | +238 | ! |
- "Computing ...",+ snapshot_name <- tools::file_path_sans_ext(input$snapshot_file$name) |
|
88 | +239 |
- # CSS defined in `custom.css`+ } |
||
89 | +240 | ! |
- class = "shinybusymessage"+ if (is.element(make.names(snapshot_name), make.names(names(snapshot_history())))) { |
|
90 | -+ | |||
241 | +! |
- )+ logger::log_debug("srv_snapshot_manager: snapshot name rejected") |
||
91 | -+ | |||
242 | +! |
- )+ showNotification( |
||
92 | -+ | |||
243 | +! |
-
+ "This name is in conflict with other snapshot names. Please choose a different one.", |
||
93 | +244 | ! |
- fluidPage(+ type = "message" |
|
94 | -! | +|||
245 | +
- id = id,+ ) |
|||
95 | +246 | ! |
- title = title,+ updateTextInput(inputId = "snapshot_name", value = "", placeholder = "Meaningful, unique name") |
|
96 | -! | +|||
247 | +
- theme = get_teal_bs_theme(),+ } else { |
|||
97 | -! | +|||
248 | +
- include_teal_css_js(),+ # Restore snapshot and verify app compatibility. |
|||
98 | +249 | ! |
- tags$header(header),+ logger::log_debug("srv_snapshot_manager: snapshot name accepted, loading snapshot") |
|
99 | +250 | ! |
- tags$hr(class = "my-2"),+ snapshot_state <- try(slices_restore(input$snapshot_file$datapath)) |
|
100 | +251 | ! |
- shiny_busy_message_panel,+ if (!inherits(snapshot_state, "modules_teal_slices")) { |
|
101 | +252 | ! |
- tags$div(+ logger::log_debug("srv_snapshot_manager: snapshot file corrupt") |
|
102 | +253 | ! |
- id = ns("tabpanel_wrapper"),+ showNotification( |
|
103 | +254 | ! |
- class = "teal-body",+ "File appears to be corrupt.", |
|
104 | +255 | ! |
- ui_teal_module(id = ns("teal_modules"), modules = modules)+ type = "error" |
|
105 | +256 |
- ),+ ) |
||
106 | +257 | ! |
- tags$div(+ } else if (!identical(attr(snapshot_state, "app_id"), attr(slices_global$all_slices(), "app_id"))) { |
|
107 | +258 | ! |
- id = ns("options_buttons"),+ logger::log_debug("srv_snapshot_manager: snapshot not compatible with app") |
|
108 | +259 | ! |
- style = "position: absolute; right: 10px;",+ showNotification( |
|
109 | +260 | ! |
- ui_bookmark_panel(ns("bookmark_manager"), modules),+ "This snapshot file is not compatible with the app and cannot be loaded.", |
|
110 | +261 | ! |
- tags$button(+ type = "warning" |
|
111 | -! | +|||
262 | +
- class = "btn action-button filter_hamburger", # see sidebar.css for style filter_hamburger+ ) |
|||
112 | -! | +|||
263 | +
- href = "javascript:void(0)",+ } else { |
|||
113 | -! | +|||
264 | +
- onclick = sprintf("toggleFilterPanel('%s');", ns("tabpanel_wrapper")),+ # Add to snapshot history. |
|||
114 | +265 | ! |
- title = "Toggle filter panel",+ logger::log_debug("srv_snapshot_manager: snapshot loaded, adding to history") |
|
115 | +266 | ! |
- icon("fas fa-bars")+ snapshot <- as.list(slices_global$all_slices(), recursive = TRUE) |
|
116 | -+ | |||
267 | +! |
- ),+ snapshot_update <- c(snapshot_history(), list(snapshot)) |
||
117 | +268 | ! |
- ui_snapshot_manager_panel(ns("snapshot_manager_panel")),+ names(snapshot_update)[length(snapshot_update)] <- snapshot_name |
|
118 | +269 | ! |
- ui_filter_manager_panel(ns("filter_manager_panel"))+ snapshot_history(snapshot_update) |
|
119 | +270 |
- ),+ ### Begin simplified restore procedure. ### |
||
120 | +271 | ! |
- tags$script(+ logger::log_debug("srv_snapshot_manager: restoring snapshot") |
|
121 | +272 | ! |
- HTML(+ slices_global$slices_set(snapshot_state) |
|
122 | +273 | ! |
- sprintf(+ removeModal() |
|
123 | +274 |
- "- |
- ||
124 | -! | -
- $(document).ready(function() {- |
- ||
125 | -! | -
- $('#%s').appendTo('#%s');+ ### End simplified restore procedure. ### |
||
126 | +275 |
- });+ } |
||
127 | +276 |
- ",- |
- ||
128 | -! | -
- ns("options_buttons"),+ } |
||
129 | -! | +|||
277 | +
- ns("teal_modules-active_tab")+ }) |
|||
130 | +278 |
- )+ # Apply newly added snapshot. |
||
131 | +279 |
- )+ |
||
132 | +280 |
- ),+ # Restore initial state ---- |
||
133 | -! | +|||
281 | +82x |
- tags$hr(),+ observeEvent(input$snapshot_reset, { |
||
134 | -! | +|||
282 | +2x |
- tags$footer(+ logger::log_debug("srv_snapshot_manager: snapshot_reset button clicked, restoring snapshot") |
||
135 | -! | +|||
283 | +2x |
- tags$div(+ s <- "Initial application state" |
||
136 | -! | +|||
284 | +
- footer,+ ### Begin restore procedure. ### |
|||
137 | -! | +|||
285 | +2x |
- teal.widgets::verbatim_popup_ui(ns("sessionInfo"), "Session Info", type = "link"),+ snapshot <- snapshot_history()[[s]] |
||
138 | -! | +|||
286 | +
- br(),+ # todo: as.teal_slices looses module-mapping if is not global |
|||
139 | -! | +|||
287 | +2x |
- ui_teal_lockfile(ns("lockfile")),+ snapshot_state <- as.teal_slices(snapshot) |
||
140 | -! | +|||
288 | +2x |
- textOutput(ns("identifier"))+ slices_global$slices_set(snapshot_state) |
||
141 | -+ | |||
289 | +2x |
- )+ removeModal() |
||
142 | +290 |
- )+ ### End restore procedure. ### |
||
143 | +291 |
- )+ }) |
||
144 | +292 |
- }+ |
||
145 | +293 |
-
+ # Build snapshot table ---- |
||
146 | +294 |
- #' @rdname module_teal+ # Create UI elements and server logic for the snapshot table. |
||
147 | +295 |
- #' @export+ # Observers must be tracked to avoid duplication and excess reactivity. |
||
148 | +296 |
- srv_teal <- function(id, data, modules, filter = teal_slices()) {- |
- ||
149 | -84x | -
- checkmate::assert_character(id, max.len = 1, any.missing = FALSE)+ # Remaining elements are tracked likewise for consistency and a slight speed margin. |
||
150 | -84x | +297 | +82x |
- checkmate::assert_multi_class(data, c("teal_data", "teal_data_module", "reactive"))+ observers <- reactiveValues() |
151 | -83x | +298 | +82x |
- checkmate::assert_class(modules, "teal_modules")+ handlers <- reactiveValues() |
152 | -83x | +299 | +82x |
- checkmate::assert_class(filter, "teal_slices")+ divs <- reactiveValues() |
153 | +300 | |||
154 | -83x | +301 | +82x |
- moduleServer(id, function(input, output, session) {+ observeEvent(snapshot_history(), { |
155 | -83x | +302 | +72x |
- logger::log_debug("srv_teal initializing.")+ logger::log_debug("srv_snapshot_manager: snapshot history modified, updating snapshot list") |
156 | -+ | |||
303 | +72x |
-
+ lapply(names(snapshot_history())[-1L], function(s) { |
||
157 | -83x | +|||
304 | +! |
- if (getOption("teal.show_js_log", default = FALSE)) {+ id_pickme <- sprintf("pickme_%s", make.names(s)) |
||
158 | +305 | ! |
- shinyjs::showLog()+ id_saveme <- sprintf("saveme_%s", make.names(s)) |
|
159 | -+ | |||
306 | +! |
- }+ id_rowme <- sprintf("rowme_%s", make.names(s)) |
||
160 | +307 | |||
161 | -83x | -
- srv_teal_lockfile("lockfile")- |
- ||
162 | +308 |
-
+ # Observer for restoring snapshot. |
||
163 | -83x | +|||
309 | +! |
- output$identifier <- renderText(+ if (!is.element(id_pickme, names(observers))) { |
||
164 | -83x | +|||
310 | +! |
- paste0("Pid:", Sys.getpid(), " Token:", substr(session$token, 25, 32))+ observers[[id_pickme]] <- observeEvent(input[[id_pickme]], { |
||
165 | +311 |
- )+ ### Begin restore procedure. ### |
||
166 | -+ | |||
312 | +! |
-
+ snapshot <- snapshot_history()[[s]] |
||
167 | -83x | +|||
313 | +! |
- teal.widgets::verbatim_popup_srv(+ snapshot_state <- as.teal_slices(snapshot) |
||
168 | -83x | +|||
314 | +
- "sessionInfo",+ |
|||
169 | -83x | +|||
315 | +! |
- verbatim_content = utils::capture.output(utils::sessionInfo()),+ slices_global$slices_set(snapshot_state) |
||
170 | -83x | +|||
316 | +! |
- title = "SessionInfo"+ removeModal() |
||
171 | +317 |
- )+ ### End restore procedure. ### |
||
172 | +318 |
-
+ }) |
||
173 | +319 |
- # `JavaScript` code+ } |
||
174 | -83x | +|||
320 | +
- run_js_files(files = "init.js")+ # Create handler for downloading snapshot. |
|||
175 | -+ | |||
321 | +! |
-
+ if (!is.element(id_saveme, names(handlers))) { |
||
176 | -+ | |||
322 | +! |
- # set timezone in shiny app+ output[[id_saveme]] <- downloadHandler( |
||
177 | -+ | |||
323 | +! |
- # timezone is set in the early beginning so it will be available also+ filename = function() {+ |
+ ||
324 | +! | +
+ sprintf("teal_snapshot_%s_%s.json", s, Sys.Date()) |
||
178 | +325 |
- # for `DDL` and all shiny modules+ }, |
||
179 | -83x | +|||
326 | +! |
- get_client_timezone(session$ns)+ content = function(file) { |
||
180 | -83x | +|||
327 | +! |
- observeEvent(+ snapshot <- snapshot_history()[[s]] |
||
181 | -83x | +|||
328 | +! |
- eventExpr = input$timezone,+ snapshot_state <- as.teal_slices(snapshot) |
||
182 | -83x | +|||
329 | +! |
- once = TRUE,+ slices_store(tss = snapshot_state, file = file) |
||
183 | -83x | +|||
330 | +
- handlerExpr = {+ } |
|||
184 | -! | +|||
331 | +
- session$userData$timezone <- input$timezone+ ) |
|||
185 | +332 | ! |
- logger::log_debug("srv_teal@1 Timezone set to client's timezone: { input$timezone }.")+ handlers[[id_saveme]] <- id_saveme |
|
186 | +333 |
- }+ } |
||
187 | +334 |
- )+ # Create a row for the snapshot table. |
||
188 | -+ | |||
335 | +! |
-
+ if (!is.element(id_rowme, names(divs))) { |
||
189 | -83x | +|||
336 | +! |
- data_pulled <- srv_init_data("data", data = data)+ divs[[id_rowme]] <- tags$div( |
||
190 | -82x | +|||
337 | +! |
- data_validated <- srv_validate_reactive_teal_data(+ class = "manager_table_row", |
||
191 | -82x | +|||
338 | +! |
- "validate",+ tags$span(tags$h5(s)), |
||
192 | -82x | +|||
339 | +! |
- data = data_pulled,+ actionLink(inputId = ns(id_pickme), label = icon("far fa-circle-check"), title = "select"), |
||
193 | -82x | +|||
340 | +! |
- modules = modules,+ downloadLink(outputId = ns(id_saveme), label = icon("far fa-save"), title = "save to file") |
||
194 | -82x | +|||
341 | +
- validate_shiny_silent_error = FALSE+ ) |
|||
195 | +342 |
- )+ } |
||
196 | -82x | +|||
343 | +
- data_rv <- reactive({+ }) |
|||
197 | -142x | +|||
344 | +
- req(inherits(data_validated(), "teal_data"))+ })+ |
+ |||
345 | ++ | + + | +||
346 | ++ |
+ # Create table to display list of snapshots and their actions. |
||
198 | -70x | +347 | +82x |
- is_filter_ok <- check_filter_datanames(filter, ls(teal.code::get_env(data_validated())))+ output$snapshot_list <- renderUI({ |
199 | -70x | +348 | +72x |
- if (!isTRUE(is_filter_ok)) {+ rows <- rev(reactiveValuesToList(divs)) |
200 | -2x | +349 | +72x |
- showNotification(+ if (length(rows) == 0L) { |
201 | -2x | +350 | +72x |
- "Some filters were not applied because of incompatibility with data. Contact app developer.",+ tags$div( |
202 | -2x | +351 | +72x |
- type = "warning",+ class = "manager_placeholder", |
203 | -2x | +352 | +72x |
- duration = 10+ "Snapshots will appear here." |
204 | +353 |
) |
||
205 | -2x | +|||
354 | +
- warning(is_filter_ok)+ } else { |
|||
206 | -+ | |||
355 | +! |
- }+ rows |
||
207 | -70x | +|||
356 | +
- .add_signature_to_data(data_validated())+ } |
|||
208 | +357 |
}) |
||
209 | +358 | |||
210 | +359 | 82x |
- data_load_status <- reactive({- |
- |
211 | -75x | -
- if (inherits(data_pulled(), "teal_data")) {- |
- ||
212 | -70x | -
- "ok"+ snapshot_history |
||
213 | +360 |
- # todo: should we hide warnings on top for a data?- |
- ||
214 | -5x | -
- } else if (inherits(data, "teal_data_module")) {- |
- ||
215 | -5x | -
- "teal_data_module failed"+ }) |
||
216 | +361 |
- } else {- |
- ||
217 | -! | -
- "external failed"+ } |
218 | +1 |
- }+ #' Data summary |
|
219 | +2 |
- })+ #' @description |
|
220 | +3 | - - | -|
221 | -82x | -
- datasets_rv <- if (!isTRUE(attr(filter, "module_specific"))) {- |
- |
222 | -71x | -
- eventReactive(data_rv(), {- |
- |
223 | -61x | -
- req(inherits(data_rv(), "teal_data"))- |
- |
224 | -61x | -
- logger::log_debug("srv_teal@1 initializing FilteredData")- |
- |
225 | -61x | -
- teal_data_to_filtered_data(data_rv())+ #' Module and its utils to display the number of rows and subjects in the filtered and unfiltered data. |
|
226 | +4 |
- })+ #' |
|
227 | +5 |
- }+ #' @details Handling different data classes: |
|
228 | +6 | - - | -|
229 | -82x | -
- if (inherits(data, "teal_data_module")) {- |
- |
230 | -9x | -
- setBookmarkExclude(c("teal_modules-active_tab"))- |
- |
231 | -9x | -
- shiny::insertTab(- |
- |
232 | -9x | -
- inputId = "teal_modules-active_tab",- |
- |
233 | -9x | -
- position = "before",- |
- |
234 | -9x | -
- select = TRUE,- |
- |
235 | -9x | -
- tabPanel(- |
- |
236 | -9x | -
- title = icon("fas fa-database"),- |
- |
237 | -9x | -
- value = "teal_data_module",- |
- |
238 | -9x | -
- tags$div(- |
- |
239 | -9x | -
- ui_init_data(session$ns("data")),- |
- |
240 | -9x | -
- ui_validate_reactive_teal_data(session$ns("validate"))+ #' `get_filter_overview()` is a pseudo S3 method which has variants for: |
|
241 | +7 |
- )+ #' - `array` (`data.frame`, `DataFrame`, `array`, `Matrix` and `SummarizedExperiment`): Method variant |
|
242 | +8 |
- )+ #' can be applied to any two-dimensional objects on which [ncol()] can be used. |
|
243 | +9 |
- )+ #' - `MultiAssayExperiment`: for which summary contains counts for `colData` and all `experiments`. |
|
244 | +10 | - - | -|
245 | -9x | -
- if (attr(data, "once")) {- |
- |
246 | -9x | -
- observeEvent(data_rv(), once = TRUE, {- |
- |
247 | -4x | -
- logger::log_debug("srv_teal@2 removing data tab.")+ #' - For other data types module displays data name with warning icon and no more details. |
|
248 | +11 |
- # when once = TRUE we pull data once and then remove data tab+ #' |
|
249 | -4x | +||
12 | +
- removeTab("teal_modules-active_tab", target = "teal_data_module")+ #' Module includes also "Show/Hide unsupported" button to toggle rows of the summary table |
||
250 | +13 |
- })+ #' containing datasets where number of observations are not calculated. |
|
251 | +14 |
- }+ #' |
|
252 | +15 |
- } else {+ #' @param id (`character(1)`) `shiny` module instance id. |
|
253 | +16 |
- # when no teal_data_module then we want to display messages above tabsetPanel (because there is no data-tab)+ #' @param teal_data (`reactive` returning `teal_data`) |
|
254 | -73x | +||
17 | +
- insertUI(+ #' |
||
255 | -73x | +||
18 | +
- selector = sprintf("#%s", session$ns("tabpanel_wrapper")),+ #' @name module_data_summary |
||
256 | -73x | +||
19 | +
- where = "beforeBegin",+ #' @rdname module_data_summary |
||
257 | -73x | +||
20 | +
- ui = tags$div(ui_validate_reactive_teal_data(session$ns("validate")), tags$br())+ #' @keywords internal |
||
258 | +21 |
- )+ #' @return `NULL`. |
|
259 | +22 |
- }+ NULL |
|
260 | +23 | ||
261 | -82x | -
- module_labels <- unlist(module_labels(modules), use.names = FALSE)- |
- |
262 | -82x | -
- slices_global <- methods::new(".slicesGlobal", filter, module_labels)- |
- |
263 | -82x | -
- modules_output <- srv_teal_module(- |
- |
264 | -82x | -
- id = "teal_modules",- |
- |
265 | -82x | +||
24 | +
- data_rv = data_rv,+ #' @rdname module_data_summary |
||
266 | -82x | +||
25 | +
- datasets = datasets_rv,+ ui_data_summary <- function(id) { |
||
267 | -82x | +||
26 | +! |
- modules = modules,+ ns <- NS(id) |
|
268 | -82x | +||
27 | +! |
- slices_global = slices_global,+ content_id <- ns("filters_overview_contents") |
|
269 | -82x | +||
28 | +! |
- data_load_status = data_load_status+ tags$div( |
|
270 | -+ | ||
29 | +! |
- )+ id = id, |
|
271 | -82x | +||
30 | +! |
- mapping_table <- srv_filter_manager_panel("filter_manager_panel", slices_global = slices_global)+ class = "well", |
|
272 | -82x | +||
31 | +! |
- snapshots <- srv_snapshot_manager_panel("snapshot_manager_panel", slices_global = slices_global)+ tags$div( |
|
273 | -82x | +||
32 | +! |
- srv_bookmark_panel("bookmark_manager", modules)+ class = "row", |
|
274 | -+ | ||
33 | +! |
- })+ tags$div( |
|
275 | -+ | ||
34 | +! |
-
+ class = "col-sm-9", |
|
276 | -82x | +||
35 | +! |
- invisible(NULL)+ tags$label("Active Filter Summary", class = "text-primary mb-4") |
|
277 | +36 |
- }+ ), |
1 | -+ | |||
37 | +! |
- # This is the main function from teal to be used by the end-users. Although it delegates+ tags$div( |
||
2 | -+ | |||
38 | +! |
- # directly to `module_teal_with_splash.R`, we keep it in a separate file because its documentation is quite large+ class = "col-sm-3", |
||
3 | -+ | |||
39 | +! |
- # and it is very end-user oriented. It may also perform more argument checking with more informative+ tags$i( |
||
4 | -+ | |||
40 | +! |
- # error messages.+ class = "remove pull-right fa fa-angle-down", |
||
5 | -+ | |||
41 | +! |
-
+ style = "cursor: pointer;", |
||
6 | -+ | |||
42 | +! |
- #' Create the server and UI function for the `shiny` app+ title = "fold/expand data summary panel", |
||
7 | -+ | |||
43 | +! |
- #'+ onclick = sprintf("togglePanelItems(this, '%s', 'fa-angle-right', 'fa-angle-down');", content_id) |
||
8 | +44 |
- #' @description `r lifecycle::badge("stable")`+ ) |
||
9 | +45 |
- #'+ ) |
||
10 | +46 |
- #' End-users: This is the most important function for you to start a+ ), |
||
11 | -+ | |||
47 | +! |
- #' `teal` app that is composed of `teal` modules.+ tags$div( |
||
12 | -+ | |||
48 | +! |
- #'+ id = content_id, |
||
13 | -+ | |||
49 | +! |
- #' @param data (`teal_data` or `teal_data_module`)+ tags$div( |
||
14 | -+ | |||
50 | +! |
- #' For constructing the data object, refer to [teal_data()] and [teal_data_module()].+ class = "teal_active_summary_filter_panel", |
||
15 | -+ | |||
51 | +! |
- #' If `datanames` are not set for the `teal_data` object, defaults from the `teal_data` environment will be used.+ tableOutput(ns("table")) |
||
16 | +52 |
- #' @param modules (`list` or `teal_modules` or `teal_module`)+ ) |
||
17 | +53 |
- #' Nested list of `teal_modules` or `teal_module` objects or a single+ ) |
||
18 | +54 |
- #' `teal_modules` or `teal_module` object. These are the specific output modules which+ ) |
||
19 | +55 |
- #' will be displayed in the `teal` application. See [modules()] and [module()] for+ } |
||
20 | +56 |
- #' more details.+ |
||
21 | +57 |
- #' @param filter (`teal_slices`) Optionally,+ #' @rdname module_data_summary |
||
22 | +58 |
- #' specifies the initial filter using [teal_slices()].+ srv_data_summary <- function(id, teal_data) { |
||
23 | -+ | |||
59 | +81x |
- #' @param title (`shiny.tag` or `character(1)`) Optionally,+ assert_reactive(teal_data) |
||
24 | -+ | |||
60 | +81x |
- #' the browser window title. Defaults to a title "teal app" with the icon of NEST.+ moduleServer( |
||
25 | -+ | |||
61 | +81x |
- #' Can be created using the `build_app_title()` or+ id = id, |
||
26 | -+ | |||
62 | +81x |
- #' by passing a valid `shiny.tag` which is a head tag with title and link tag.+ function(input, output, session) { |
||
27 | -+ | |||
63 | +81x |
- #' @param header (`shiny.tag` or `character(1)`) Optionally,+ logger::log_debug("srv_data_summary initializing") |
||
28 | +64 |
- #' the header of the app.+ |
||
29 | -+ | |||
65 | +81x |
- #' @param footer (`shiny.tag` or `character(1)`) Optionally,+ summary_table <- reactive({ |
||
30 | -+ | |||
66 | +89x |
- #' the footer of the app.+ req(inherits(teal_data(), "teal_data")) |
||
31 | -+ | |||
67 | +83x |
- #' @param id (`character`) Optionally,+ if (!length(teal_data())) { |
||
32 | -+ | |||
68 | +2x |
- #' a string specifying the `shiny` module id in cases it is used as a `shiny` module+ return(NULL) |
||
33 | +69 |
- #' rather than a standalone `shiny` app. This is a legacy feature.+ } |
||
34 | -+ | |||
70 | +81x |
- #' @param landing_popup (`teal_module_landing`) Optionally,+ get_filter_overview_wrapper(teal_data) |
||
35 | +71 |
- #' a `landing_popup_module` to show up as soon as the teal app is initialized.+ }) |
||
36 | +72 |
- #'+ |
||
37 | -+ | |||
73 | +81x |
- #' @return Named list containing server and UI functions.+ output$table <- renderUI({ |
||
38 | -+ | |||
74 | +89x |
- #'+ summary_table_out <- try(summary_table(), silent = TRUE) |
||
39 | -+ | |||
75 | +89x |
- #' @export+ if (inherits(summary_table_out, "try-error")) { |
||
40 | +76 |
- #'+ # Ignore silent shiny error |
||
41 | -+ | |||
77 | +6x |
- #' @include modules.R+ if (!inherits(attr(summary_table_out, "condition"), "shiny.silent.error")) { |
||
42 | -+ | |||
78 | +! |
- #'+ stop("Error occurred during data processing. See details in the main panel.") |
||
43 | +79 |
- #' @examples+ } |
||
44 | -+ | |||
80 | +83x |
- #' app <- init(+ } else if (is.null(summary_table_out)) { |
||
45 | -+ | |||
81 | +2x |
- #' data = within(+ "no datasets to show" |
||
46 | +82 |
- #' teal_data(),+ } else { |
||
47 | -+ | |||
83 | +81x |
- #' {+ is_unsupported <- apply(summary_table(), 1, function(x) all(is.na(x[-1]))) |
||
48 | -+ | |||
84 | +81x |
- #' new_iris <- transform(iris, id = seq_len(nrow(iris)))+ summary_table_out[is.na(summary_table_out)] <- "" |
||
49 | -+ | |||
85 | +81x |
- #' new_mtcars <- transform(mtcars, id = seq_len(nrow(mtcars)))+ body_html <- apply( |
||
50 | -+ | |||
86 | +81x |
- #' }+ summary_table_out, |
||
51 | -+ | |||
87 | +81x |
- #' ),+ 1, |
||
52 | -+ | |||
88 | +81x |
- #' modules = modules(+ function(x) { |
||
53 | -+ | |||
89 | +154x |
- #' module(+ is_supported <- !all(x[-1] == "") |
||
54 | -+ | |||
90 | +154x |
- #' label = "data source",+ if (is_supported) { |
||
55 | -+ | |||
91 | +147x |
- #' server = function(input, output, session, data) {},+ tags$tr( |
||
56 | -+ | |||
92 | +147x |
- #' ui = function(id, ...) tags$div(p("information about data source")),+ tagList( |
||
57 | -+ | |||
93 | +147x |
- #' datanames = "all"+ tags$td(x[1]), |
||
58 | -+ | |||
94 | +147x |
- #' ),+ lapply(x[-1], tags$td) |
||
59 | +95 |
- #' example_module(label = "example teal module"),+ ) |
||
60 | +96 |
- #' module(+ ) |
||
61 | +97 |
- #' "Iris Sepal.Length histogram",+ } |
||
62 | +98 |
- #' server = function(input, output, session, data) {+ } |
||
63 | +99 |
- #' output$hist <- renderPlot(+ ) |
||
64 | +100 |
- #' hist(data()[["new_iris"]]$Sepal.Length)+ |
||
65 | -+ | |||
101 | +81x |
- #' )+ header_labels <- tools::toTitleCase(names(summary_table_out)) |
||
66 | -+ | |||
102 | +81x |
- #' },+ header_labels[header_labels == "Dataname"] <- "Data Name" |
||
67 | -+ | |||
103 | +81x |
- #' ui = function(id, ...) {+ header_html <- tags$tr(tagList(lapply(header_labels, tags$td))) |
||
68 | +104 |
- #' ns <- NS(id)+ |
||
69 | -+ | |||
105 | +81x |
- #' plotOutput(ns("hist"))+ table_html <- tags$table( |
||
70 | -+ | |||
106 | +81x |
- #' },+ class = "table custom-table", |
||
71 | -+ | |||
107 | +81x |
- #' datanames = "new_iris"+ tags$thead(header_html), |
||
72 | -+ | |||
108 | +81x |
- #' )+ tags$tbody(body_html) |
||
73 | +109 |
- #' ),+ ) |
||
74 | -+ | |||
110 | +81x |
- #' filter = teal_slices(+ div( |
||
75 | -+ | |||
111 | +81x |
- #' teal_slice(dataname = "new_iris", varname = "Species"),+ table_html, |
||
76 | -+ | |||
112 | +81x |
- #' teal_slice(dataname = "new_iris", varname = "Sepal.Length"),+ if (any(is_unsupported)) { |
||
77 | -+ | |||
113 | +7x |
- #' teal_slice(dataname = "new_mtcars", varname = "cyl"),+ p( |
||
78 | -+ | |||
114 | +7x |
- #' exclude_varnames = list(new_iris = c("Sepal.Width", "Petal.Width")),+ class = c("pull-right", "float-right", "text-secondary"), |
||
79 | -+ | |||
115 | +7x |
- #' module_specific = TRUE,+ style = "font-size: 0.8em;", |
||
80 | -+ | |||
116 | +7x |
- #' mapping = list(+ sprintf("And %s more unfilterable object(s)", sum(is_unsupported)), |
||
81 | -+ | |||
117 | +7x |
- #' `example teal module` = "new_iris Species",+ icon( |
||
82 | -+ | |||
118 | +7x |
- #' `Iris Sepal.Length histogram` = "new_iris Species",+ name = "far fa-circle-question", |
||
83 | -+ | |||
119 | +7x |
- #' global_filters = "new_mtcars cyl"+ title = paste( |
||
84 | -+ | |||
120 | +7x |
- #' )+ sep = "", |
||
85 | -+ | |||
121 | +7x |
- #' ),+ collapse = "\n", |
||
86 | -+ | |||
122 | +7x |
- #' title = "App title",+ shQuote(summary_table()[is_unsupported, "dataname"]), |
||
87 | +123 |
- #' header = tags$h1("Sample App"),+ " (", |
||
88 | -+ | |||
124 | +7x |
- #' footer = tags$p("Sample footer")+ vapply( |
||
89 | -+ | |||
125 | +7x |
- #' )+ summary_table()[is_unsupported, "dataname"], |
||
90 | -+ | |||
126 | +7x |
- #' if (interactive()) {+ function(x) class(teal_data()[[x]])[1], |
||
91 | -+ | |||
127 | +7x |
- #' shinyApp(app$ui, app$server)+ character(1L) |
||
92 | +128 |
- #' }+ ), |
||
93 | +129 |
- #'+ ")" |
||
94 | +130 |
- init <- function(data,+ ) |
||
95 | +131 |
- modules,+ ) |
||
96 | +132 |
- filter = teal_slices(),+ ) |
||
97 | +133 |
- title = build_app_title(),+ } |
||
98 | +134 |
- header = tags$p(),+ ) |
||
99 | +135 |
- footer = tags$p(),+ } |
||
100 | +136 |
- id = character(0),+ }) |
||
101 | +137 |
- landing_popup = NULL) {+ |
||
102 | -12x | +138 | +81x |
- logger::log_debug("init initializing teal app with: data ('{ class(data) }').")+ NULL |
103 | +139 |
-
+ } |
||
104 | +140 |
- # argument checking (independent)+ ) |
||
105 | +141 |
- ## `data`- |
- ||
106 | -12x | -
- if (inherits(data, "TealData")) {- |
- ||
107 | -! | -
- lifecycle::deprecate_stop(- |
- ||
108 | -! | -
- when = "0.15.0",- |
- ||
109 | -! | -
- what = "init(data)",- |
- ||
110 | -! | -
- paste(- |
- ||
111 | -! | -
- "TealData is no longer supported. Use teal_data() instead.",+ } |
||
112 | -! | +|||
142 | +
- "Please follow migration instructions https://github.com/insightsengineering/teal/discussions/988."+ |
|||
113 | +143 |
- )+ #' @rdname module_data_summary |
||
114 | +144 |
- )+ get_filter_overview_wrapper <- function(teal_data) { |
||
115 | +145 |
- }+ # Sort datanames in topological order |
||
116 | -12x | +146 | +81x |
- checkmate::assert_multi_class(data, c("teal_data", "teal_data_module"))+ datanames <- names(teal_data()) |
117 | -12x | +147 | +81x |
- checkmate::assert_class(landing_popup, "teal_module_landing", null.ok = TRUE)+ joinkeys <- teal.data::join_keys(teal_data()) |
118 | +148 | |||
119 | -- |
- ## `modules`- |
- ||
120 | -12x | +149 | +81x |
- checkmate::assert(+ current_data_objs <- sapply( |
121 | -12x | +150 | +81x |
- .var.name = "modules",+ datanames, |
122 | -12x | +151 | +81x |
- checkmate::check_multi_class(modules, c("teal_modules", "teal_module")),+ function(name) teal.code::get_var(teal_data(), name), |
123 | -12x | +152 | +81x |
- checkmate::check_list(modules, min.len = 1, any.missing = FALSE, types = c("teal_module", "teal_modules"))+ simplify = FALSE |
124 | +153 |
) |
||
125 | -12x | +154 | +81x |
- if (inherits(modules, "teal_module")) {+ initial_data_objs <- teal.code::get_var(teal_data(), ".raw_data")+ |
+
155 | ++ | + | ||
126 | -1x | +156 | +81x |
- modules <- list(modules)+ out <- lapply( |
127 | -+ | |||
157 | +81x |
- }+ datanames, |
||
128 | -12x | +158 | +81x |
- if (checkmate::test_list(modules, min.len = 1, any.missing = FALSE, types = c("teal_module", "teal_modules"))) {+ function(dataname) { |
129 | -6x | +159 | +149x |
- modules <- do.call(teal::modules, modules)+ parent <- teal.data::parent(joinkeys, dataname) |
130 | +160 |
- }+ # todo: what should we display for a parent dataset? |
||
131 | +161 |
-
+ # - Obs and Subjects |
||
132 | +162 |
- ## `filter`+ # - Obs only |
||
133 | -12x | +|||
163 | +
- checkmate::assert_class(filter, "teal_slices")+ # - Subjects only |
|||
134 | +164 |
-
+ # todo (for later): summary table should be displayed in a way that child datasets |
||
135 | +165 |
- ## all other arguments+ # are indented under their parent dataset to form a tree structure |
||
136 | -11x | +166 | +149x |
- checkmate::assert(+ subject_keys <- if (length(parent) > 0) { |
137 | -11x | +167 | +7x |
- .var.name = "title",+ names(joinkeys[dataname, parent]) |
138 | -11x | +|||
168 | +
- checkmate::check_string(title),+ } else { |
|||
139 | -11x | +169 | +142x |
- checkmate::check_multi_class(title, c("shiny.tag", "shiny.tag.list", "html"))+ joinkeys[dataname, dataname] |
140 | +170 |
- )+ } |
||
141 | -11x | +171 | +149x |
- checkmate::assert(+ get_filter_overview( |
142 | -11x | +172 | +149x |
- .var.name = "header",+ current_data = current_data_objs[[dataname]], |
143 | -11x | +173 | +149x |
- checkmate::check_string(header),+ initial_data = initial_data_objs[[dataname]], |
144 | -11x | +174 | +149x |
- checkmate::check_multi_class(header, c("shiny.tag", "shiny.tag.list", "html"))+ dataname = dataname,+ |
+
175 | +149x | +
+ subject_keys = subject_keys |
||
145 | +176 |
- )+ ) |
||
146 | -11x | +|||
177 | +
- checkmate::assert(+ } |
|||
147 | -11x | +|||
178 | +
- .var.name = "footer",+ ) |
|||
148 | -11x | +|||
179 | +
- checkmate::check_string(footer),+ |
|||
149 | -11x | +180 | +81x |
- checkmate::check_multi_class(footer, c("shiny.tag", "shiny.tag.list", "html"))+ do.call(.smart_rbind, out) |
150 | +181 |
- )+ } |
||
151 | -11x | +|||
182 | +
- checkmate::assert_character(id, max.len = 1, any.missing = FALSE)+ |
|||
152 | +183 | |||
153 | +184 |
- # log+ #' @rdname module_data_summary |
||
154 | -11x | +|||
185 | +
- teal.logger::log_system_info()+ #' @param current_data (`object`) current object (after filtering and transforming). |
|||
155 | +186 |
-
+ #' @param initial_data (`object`) initial object. |
||
156 | +187 |
- # argument transformations+ #' @param dataname (`character(1)`) |
||
157 | +188 |
- ## `modules` - landing module+ #' @param subject_keys (`character`) names of the columns which determine a single unique subjects+ |
+ ||
189 | ++ |
+ get_filter_overview <- function(current_data, initial_data, dataname, subject_keys) { |
||
158 | -11x | +190 | +154x |
- landing <- extract_module(modules, "teal_module_landing")+ if (inherits(current_data, c("data.frame", "DataFrame", "array", "Matrix", "SummarizedExperiment"))) { |
159 | -11x | +191 | +146x |
- if (length(landing) == 1L) {+ get_filter_overview_array(current_data, initial_data, dataname, subject_keys) |
160 | -! | +|||
192 | +8x |
- landing_popup <- landing[[1L]]+ } else if (inherits(current_data, "MultiAssayExperiment")) { |
||
161 | -! | +|||
193 | +1x |
- modules <- drop_module(modules, "teal_module_landing")+ get_filter_overview_MultiAssayExperiment(current_data, initial_data, dataname) |
||
162 | -! | +|||
194 | +
- lifecycle::deprecate_soft(+ } else { |
|||
163 | -! | +|||
195 | +7x |
- when = "0.15.3",+ data.frame(dataname = dataname) |
||
164 | -! | +|||
196 | +
- what = "landing_popup_module()",+ } |
|||
165 | -! | +|||
197 | +
- details = paste(+ } |
|||
166 | -! | +|||
198 | +
- "Pass `landing_popup_module` to the `landing_popup` argument of the `init` ",+ |
|||
167 | -! | +|||
199 | +
- "instead of wrapping it into `modules()` and passing to the `modules` argument"+ #' @rdname module_data_summary |
|||
168 | +200 |
- )+ get_filter_overview_array <- function(current_data, |
||
169 | +201 | ++ |
+ initial_data,+ |
+ |
202 | ++ |
+ dataname,+ |
+ ||
203 |
- )+ subject_keys) {+ |
+ |||
204 | +146x | +
+ if (length(subject_keys) == 0) { |
||
170 | -11x | +205 | +133x |
- } else if (length(landing) > 1L) {+ data.frame( |
171 | -! | +|||
206 | +133x |
- stop("Only one `landing_popup_module` can be used.")+ dataname = dataname, |
||
172 | -+ | |||
207 | +133x |
- }+ obs = if (!is.null(initial_data)) { |
||
173 | -+ | |||
208 | +124x |
-
+ sprintf("%s/%s", nrow(current_data), nrow(initial_data)) |
||
174 | +209 |
- ## `filter` - set app_id attribute unless present (when restoring bookmark)+ } else { |
||
175 | -11x | +210 | +9x |
- if (is.null(attr(filter, "app_id", exact = TRUE))) attr(filter, "app_id") <- create_app_id(data, modules)+ nrow(current_data) |
176 | +211 |
-
+ } |
||
177 | +212 |
- ## `filter` - convert teal.slice::teal_slices to teal::teal_slices+ ) |
||
178 | -11x | +|||
213 | +
- filter <- as.teal_slices(as.list(filter))+ } else { |
|||
179 | -+ | |||
214 | +13x |
-
+ data.frame( |
||
180 | -+ | |||
215 | +13x |
- # argument checking (interdependent)+ dataname = dataname, |
||
181 | -+ | |||
216 | +13x |
- ## `filter` - `modules`+ obs = if (!is.null(initial_data)) { |
||
182 | -11x | +217 | +13x |
- if (isTRUE(attr(filter, "module_specific"))) {+ sprintf("%s/%s", nrow(current_data), nrow(initial_data)) |
183 | -! | +|||
218 | +
- module_names <- unlist(c(module_labels(modules), "global_filters"))+ } else { |
|||
184 | +219 | ! |
- failed_mod_names <- setdiff(names(attr(filter, "mapping")), module_names)+ nrow(current_data) |
|
185 | -! | +|||
220 | +
- if (length(failed_mod_names)) {+ }, |
|||
186 | -! | +|||
221 | +13x |
- stop(+ subjects = if (!is.null(initial_data)) { |
||
187 | -! | +|||
222 | +13x |
- sprintf(+ sprintf("%s/%s", nrow(unique(current_data[subject_keys])), nrow(unique(initial_data[subject_keys]))) |
||
188 | -! | +|||
223 | +
- "Some module names in the mapping arguments don't match module labels.\n %s not in %s",+ } else { |
|||
189 | +224 | ! |
- toString(failed_mod_names),+ nrow(unique(current_data[subject_keys])) |
|
190 | -! | +|||
225 | +
- toString(unique(module_names))+ } |
|||
191 | +226 |
- )+ ) |
||
192 | +227 |
- )+ } |
||
193 | +228 |
- }+ } |
||
194 | +229 | |||
195 | -! | +|||
230 | +
- if (anyDuplicated(module_names)) {+ #' @rdname module_data_summary |
|||
196 | +231 |
- # In teal we are able to set nested modules with duplicated label.+ get_filter_overview_MultiAssayExperiment <- function(current_data, # nolint: object_length, object_name. |
||
197 | +232 |
- # Because mapping argument bases on the relationship between module-label and filter-id,+ initial_data, |
||
198 | +233 |
- # it is possible that module-label in mapping might refer to multiple teal_module (identified by the same label)+ dataname) { |
||
199 | -! | +|||
234 | +1x |
- stop(+ experiment_names <- names(current_data) |
||
200 | -! | +|||
235 | +1x |
- sprintf(+ mae_info <- data.frame( |
||
201 | -! | +|||
236 | +1x |
- "Module labels should be unique when teal_slices(mapping = TRUE). Duplicated labels:\n%s ",+ dataname = dataname,+ |
+ ||
237 | +1x | +
+ subjects = if (!is.null(initial_data)) { |
||
202 | +238 | ! |
- toString(module_names[duplicated(module_names)])+ sprintf("%s/%s", nrow(current_data@colData), nrow(initial_data@colData)) |
|
203 | +239 |
- )+ } else { |
||
204 | -+ | |||
240 | +1x |
- )+ nrow(current_data@colData) |
||
205 | +241 |
} |
||
206 | +242 |
- }+ ) |
||
207 | +243 | |||
208 | -- |
- ## `data` - `modules`- |
- ||
209 | -11x | +244 | +1x |
- if (inherits(data, "teal_data")) {+ experiment_obs_info <- do.call("rbind", lapply( |
210 | -10x | +245 | +1x |
- if (length(ls(teal.code::get_env(data))) == 0) {+ experiment_names, |
211 | +246 | 1x |
- stop("The environment of `data` is empty.")+ function(experiment_name) { |
|
212 | -+ | |||
247 | +5x |
- }+ transform( |
||
213 | -+ | |||
248 | +5x |
-
+ get_filter_overview( |
||
214 | -9x | +249 | +5x |
- is_modules_ok <- check_modules_datanames(modules, ls(teal.code::get_env(data)))+ current_data[[experiment_name]], |
215 | -9x | +250 | +5x |
- if (!isTRUE(is_modules_ok) && length(unlist(extract_transformers(modules))) == 0) {+ initial_data[[experiment_name]], |
216 | -2x | +251 | +5x |
- warning(is_modules_ok, call. = FALSE)+ dataname = experiment_name, |
217 | -+ | |||
252 | +5x |
- }+ subject_keys = join_keys() # empty join keys |
||
218 | +253 | - - | -||
219 | -9x | -
- is_filter_ok <- check_filter_datanames(filter, ls(teal.code::get_env(data)))- |
- ||
220 | -9x | -
- if (!isTRUE(is_filter_ok)) {+ ), |
||
221 | -1x | -
- warning(is_filter_ok)- |
- ||
222 | -+ | 254 | +5x |
- # we allow app to continue if applied filters are outside+ dataname = paste0(" - ", experiment_name) |
223 | +255 |
- # of possible data range+ ) |
||
224 | +256 |
} |
||
225 | +257 |
- }+ )) |
||
226 | +258 | |||
227 | -10x | +259 | +1x |
- reporter <- teal.reporter::Reporter$new()$set_id(attr(filter, "app_id"))+ get_experiment_keys <- function(mae, experiment) { |
228 | -10x | -
- if (is_arg_used(modules, "reporter") && length(extract_module(modules, "teal_module_previewer")) == 0) {- |
- ||
229 | -! | -
- modules <- append_module(- |
- ||
230 | -! | -
- modules,- |
- ||
231 | -! | +260 | +5x |
- reporter_previewer_module(server_args = list(previewer_buttons = c("download", "reset")))+ sample_subset <- mae@sampleMap[mae@sampleMap$colname %in% colnames(experiment), ] |
232 | -+ | |||
261 | +5x |
- )+ length(unique(sample_subset$primary)) |
||
233 | +262 |
} |
||
234 | +263 | |||
235 | -10x | -
- ns <- NS(id)- |
- ||
236 | -+ | 264 | +1x |
- # Note: UI must be a function to support bookmarking.+ experiment_subjects_info <- do.call("rbind", lapply( |
237 | -10x | +265 | +1x |
- res <- list(+ experiment_names, |
238 | -10x | +266 | +1x |
- ui = function(request) {+ function(experiment_name) { |
239 | -! | +|||
267 | +5x |
- ui_teal(+ data.frame( |
||
240 | -! | +|||
268 | +5x |
- id = ns("teal"),+ subjects = if (!is.null(initial_data)) { |
||
241 | +269 | ! |
- modules = modules,+ sprintf( |
|
242 | +270 | ! |
- title = title,+ "%s/%s", |
|
243 | +271 | ! |
- header = header,+ get_experiment_keys(current_data, current_data[[experiment_name]]), |
|
244 | +272 | ! |
- footer = footer+ get_experiment_keys(current_data, initial_data[[experiment_name]]) |
|
245 | +273 |
- )+ ) |
||
246 | +274 |
- },+ } else { |
||
247 | -10x | -
- server = function(input, output, session) {- |
- ||
248 | -! | -
- if (!is.null(landing_popup)) {- |
- ||
249 | -! | +275 | +5x |
- do.call(landing_popup$server, c(list(id = "landing_module_shiny_id"), landing_popup$server_args))+ get_experiment_keys(current_data, current_data[[experiment_name]]) |
250 | +276 |
- }+ } |
||
251 | -! | +|||
277 | +
- srv_teal(id = ns("teal"), data = data, modules = modules, filter = deep_copy_filter(filter))+ ) |
|||
252 | +278 |
} |
||
253 | +279 |
- )+ )) |
||
254 | +280 | |||
255 | -10x | -
- logger::log_debug("init teal app has been initialized.")- |
- ||
256 | -+ | 281 | +1x |
-
+ experiment_info <- cbind(experiment_obs_info, experiment_subjects_info) |
257 | -10x | +282 | +1x |
- res+ .smart_rbind(mae_info, experiment_info) |
258 | +283 |
}@@ -28004,28 +27864,28 @@ teal coverage - 59.99% |
1 |
- #' Data summary+ #' Validate that dataset has a minimum number of observations |
||
2 |
- #' @description+ #' |
||
3 |
- #' Module and its utils to display the number of rows and subjects in the filtered and unfiltered data.+ #' `r lifecycle::badge("stable")` |
||
5 |
- #' @details Handling different data classes:+ #' This function is a wrapper for `shiny::validate`. |
||
6 |
- #' `get_filter_overview()` is a pseudo S3 method which has variants for:+ #' |
||
7 |
- #' - `array` (`data.frame`, `DataFrame`, `array`, `Matrix` and `SummarizedExperiment`): Method variant+ #' @param x (`data.frame`) |
||
8 |
- #' can be applied to any two-dimensional objects on which [ncol()] can be used.+ #' @param min_nrow (`numeric(1)`) Minimum allowed number of rows in `x`. |
||
9 |
- #' - `MultiAssayExperiment`: for which summary contains counts for `colData` and all `experiments`.+ #' @param complete (`logical(1)`) Flag specifying whether to check only complete cases. Defaults to `FALSE`. |
||
10 |
- #' - For other data types module displays data name with warning icon and no more details.+ #' @param allow_inf (`logical(1)`) Flag specifying whether to allow infinite values. Defaults to `TRUE`. |
||
11 |
- #'+ #' @param msg (`character(1)`) Additional message to display alongside the default message. |
||
12 |
- #' Module includes also "Show/Hide unsupported" button to toggle rows of the summary table+ #' |
||
13 |
- #' containing datasets where number of observations are not calculated.+ #' @export |
||
15 |
- #' @param id (`character(1)`) `shiny` module instance id.+ #' @examples |
||
16 |
- #' @param teal_data (`reactive` returning `teal_data`)+ #' library(teal) |
||
17 |
- #'+ #' ui <- fluidPage( |
||
18 |
- #' @name module_data_summary+ #' sliderInput("len", "Max Length of Sepal", |
||
19 |
- #' @rdname module_data_summary+ #' min = 4.3, max = 7.9, value = 5 |
||
20 |
- #' @keywords internal+ #' ), |
||
21 |
- #' @return `NULL`.+ #' plotOutput("plot") |
||
22 |
- NULL+ #' ) |
||
23 |
-
+ #' |
||
24 |
- #' @rdname module_data_summary+ #' server <- function(input, output) { |
||
25 |
- ui_data_summary <- function(id) {+ #' output$plot <- renderPlot({ |
||
26 | -! | +
- ns <- NS(id)+ #' iris_df <- iris[iris$Sepal.Length <= input$len, ] |
|
27 | -! | +
- content_id <- ns("filters_overview_contents")+ #' validate_has_data( |
|
28 | -! | +
- tags$div(+ #' iris_df, |
|
29 | -! | +
- id = id,+ #' min_nrow = 10, |
|
30 | -! | +
- class = "well",+ #' complete = FALSE, |
|
31 | -! | +
- tags$div(+ #' msg = "Please adjust Max Length of Sepal" |
|
32 | -! | +
- class = "row",+ #' ) |
|
33 | -! | +
- tags$div(+ #' |
|
34 | -! | +
- class = "col-sm-9",+ #' hist(iris_df$Sepal.Length, breaks = 5) |
|
35 | -! | +
- tags$label("Active Filter Summary", class = "text-primary mb-4")+ #' }) |
|
36 |
- ),+ #' } |
||
37 | -! | +
- tags$div(+ #' if (interactive()) { |
|
38 | -! | +
- class = "col-sm-3",+ #' shinyApp(ui, server) |
|
39 | -! | +
- tags$i(+ #' } |
|
40 | -! | +
- class = "remove pull-right fa fa-angle-down",+ #' |
|
41 | -! | +
- style = "cursor: pointer;",+ validate_has_data <- function(x, |
|
42 | -! | +
- title = "fold/expand data summary panel",+ min_nrow = NULL, |
|
43 | -! | +
- onclick = sprintf("togglePanelItems(this, '%s', 'fa-angle-right', 'fa-angle-down');", content_id)+ complete = FALSE, |
|
44 |
- )+ allow_inf = TRUE, |
||
45 |
- )+ msg = NULL) { |
||
46 | -+ | 17x |
- ),+ checkmate::assert_string(msg, null.ok = TRUE) |
47 | -! | +15x |
- tags$div(+ checkmate::assert_data_frame(x) |
48 | -! | +15x |
- id = content_id,+ if (!is.null(min_nrow)) { |
49 | -! | +15x |
- tags$div(+ if (complete) { |
50 | -! | +5x |
- class = "teal_active_summary_filter_panel",+ complete_index <- stats::complete.cases(x) |
51 | -! | +5x |
- tableOutput(ns("table"))+ validate(need( |
52 | -+ | 5x |
- )+ sum(complete_index) > 0 && nrow(x[complete_index, , drop = FALSE]) >= min_nrow, |
53 | -+ | 5x |
- )+ paste(c(paste("Number of complete cases is less than:", min_nrow), msg), collapse = "\n") |
54 |
- )+ )) |
||
55 |
- }+ } else { |
||
56 | -+ | 10x |
-
+ validate(need( |
57 | -+ | 10x |
- #' @rdname module_data_summary+ nrow(x) >= min_nrow, |
58 | -+ | 10x |
- srv_data_summary <- function(id, teal_data) {+ paste( |
59 | -81x | +10x |
- assert_reactive(teal_data)+ c(paste("Minimum number of records not met: >=", min_nrow, "records required."), msg), |
60 | -81x | +10x |
- moduleServer(+ collapse = "\n" |
61 | -81x | +
- id = id,+ ) |
|
62 | -81x | +
- function(input, output, session) {+ )) |
|
63 | -81x | +
- logger::log_debug("srv_data_summary initializing")+ } |
|
65 | -81x | +10x |
- summary_table <- reactive({+ if (!allow_inf) { |
66 | -89x | +6x |
- req(inherits(teal_data(), "teal_data"))+ validate(need( |
67 | -83x | +6x |
- if (!length(ls(teal.code::get_env(teal_data())))) {+ all(vapply(x, function(col) !is.numeric(col) || !any(is.infinite(col)), logical(1))), |
68 | -2x | +6x |
- return(NULL)+ "Dataframe contains Inf values which is not allowed." |
69 |
- }+ )) |
||
70 | -81x | +
- get_filter_overview_wrapper(teal_data)+ } |
|
71 |
- })+ } |
||
72 |
-
+ } |
||
73 | -81x | +
- output$table <- renderUI({+ |
|
74 | -89x | +
- summary_table_out <- try(summary_table(), silent = TRUE)+ #' Validate that dataset has unique rows for key variables |
|
75 | -89x | +
- if (inherits(summary_table_out, "try-error")) {+ #' |
|
76 |
- # Ignore silent shiny error+ #' `r lifecycle::badge("stable")` |
||
77 | -6x | +
- if (!inherits(attr(summary_table_out, "condition"), "shiny.silent.error")) {+ #' |
|
78 | -! | +
- stop("Error occurred during data processing. See details in the main panel.")+ #' This function is a wrapper for `shiny::validate`. |
|
79 |
- }+ #' |
||
80 | -83x | +
- } else if (is.null(summary_table_out)) {+ #' @param x (`data.frame`) |
|
81 | -2x | +
- "no datasets to show"+ #' @param key (`character`) Vector of ID variables from `x` that identify unique records. |
|
82 |
- } else {+ #' |
||
83 | -81x | +
- is_unsupported <- apply(summary_table(), 1, function(x) all(is.na(x[-1])))+ #' @export |
|
84 | -81x | +
- summary_table_out[is.na(summary_table_out)] <- ""+ #' |
|
85 | -81x | +
- body_html <- apply(+ #' @examples |
|
86 | -81x | +
- summary_table_out,+ #' iris$id <- rep(1:50, times = 3) |
|
87 | -81x | +
- 1,+ #' ui <- fluidPage( |
|
88 | -81x | +
- function(x) {+ #' selectInput( |
|
89 | -154x | +
- is_supported <- !all(x[-1] == "")+ #' inputId = "species", |
|
90 | -154x | +
- if (is_supported) {+ #' label = "Select species", |
|
91 | -147x | +
- tags$tr(+ #' choices = c("setosa", "versicolor", "virginica"), |
|
92 | -147x | +
- tagList(+ #' selected = "setosa", |
|
93 | -147x | +
- tags$td(x[1]),+ #' multiple = TRUE |
|
94 | -147x | +
- lapply(x[-1], tags$td)+ #' ), |
|
95 |
- )+ #' plotOutput("plot") |
||
96 |
- )+ #' ) |
||
97 |
- }+ #' server <- function(input, output) { |
||
98 |
- }+ #' output$plot <- renderPlot({ |
||
99 |
- )+ #' iris_f <- iris[iris$Species %in% input$species, ] |
||
100 |
-
+ #' validate_one_row_per_id(iris_f, key = c("id")) |
||
101 | -81x | +
- header_labels <- tools::toTitleCase(names(summary_table_out))+ #' |
|
102 | -81x | +
- header_labels[header_labels == "Dataname"] <- "Data Name"+ #' hist(iris_f$Sepal.Length, breaks = 5) |
|
103 | -81x | +
- header_html <- tags$tr(tagList(lapply(header_labels, tags$td)))+ #' }) |
|
104 |
-
+ #' } |
||
105 | -81x | +
- table_html <- tags$table(+ #' if (interactive()) { |
|
106 | -81x | +
- class = "table custom-table",+ #' shinyApp(ui, server) |
|
107 | -81x | +
- tags$thead(header_html),+ #' } |
|
108 | -81x | +
- tags$tbody(body_html)+ #' |
|
109 |
- )+ validate_one_row_per_id <- function(x, key = c("USUBJID", "STUDYID")) { |
||
110 | -81x | +! |
- div(+ validate(need(!any(duplicated(x[key])), paste("Found more than one row per id."))) |
111 | -81x | +
- table_html,+ } |
|
112 | -81x | +
- if (any(is_unsupported)) {+ |
|
113 | -7x | +
- p(+ #' Validates that vector includes all expected values |
|
114 | -7x | +
- class = c("pull-right", "float-right", "text-secondary"),+ #' |
|
115 | -7x | +
- style = "font-size: 0.8em;",+ #' `r lifecycle::badge("stable")` |
|
116 | -7x | +
- sprintf("And %s more unfilterable object(s)", sum(is_unsupported)),+ #' |
|
117 | -7x | +
- icon(+ #' This function is a wrapper for `shiny::validate`. |
|
118 | -7x | +
- name = "far fa-circle-question",+ #' |
|
119 | -7x | +
- title = paste(+ #' @param x Vector of values to test. |
|
120 | -7x | +
- sep = "",+ #' @param choices Vector to test against. |
|
121 | -7x | +
- collapse = "\n",+ #' @param msg (`character(1)`) Error message to display if some elements of `x` are not elements of `choices`. |
|
122 | -7x | +
- shQuote(summary_table()[is_unsupported, "dataname"]),+ #' |
|
123 |
- " (",+ #' @export |
||
124 | -7x | +
- vapply(+ #' |
|
125 | -7x | +
- summary_table()[is_unsupported, "dataname"],+ #' @examples |
|
126 | -7x | +
- function(x) class(teal_data()[[x]])[1],+ #' ui <- fluidPage( |
|
127 | -7x | +
- character(1L)+ #' selectInput( |
|
128 |
- ),+ #' "species", |
||
129 |
- ")"+ #' "Select species", |
||
130 |
- )+ #' choices = c("setosa", "versicolor", "virginica", "unknown species"), |
||
131 |
- )+ #' selected = "setosa", |
||
132 |
- )+ #' multiple = FALSE |
||
133 |
- }+ #' ), |
||
134 |
- )+ #' verbatimTextOutput("summary") |
||
135 |
- }+ #' ) |
||
136 |
- })+ #' |
||
137 |
-
+ #' server <- function(input, output) { |
||
138 | -81x | +
- NULL+ #' output$summary <- renderPrint({ |
|
139 |
- }+ #' validate_in(input$species, iris$Species, "Species does not exist.") |
||
140 |
- )+ #' nrow(iris[iris$Species == input$species, ]) |
||
141 |
- }+ #' }) |
||
142 |
-
+ #' } |
||
143 |
- #' @rdname module_data_summary+ #' if (interactive()) { |
||
144 |
- get_filter_overview_wrapper <- function(teal_data) {+ #' shinyApp(ui, server) |
||
145 | -81x | +
- datanames <- teal.data::datanames(teal_data())+ #' } |
|
146 | -81x | +
- joinkeys <- teal.data::join_keys(teal_data())+ #' |
|
147 |
-
+ validate_in <- function(x, choices, msg) { |
||
148 | -81x | +! |
- current_data_objs <- sapply(+ validate(need(length(x) > 0 && length(choices) > 0 && all(x %in% choices), msg)) |
149 | -81x | +
- datanames,+ } |
|
150 | -81x | +
- function(name) teal.code::get_var(teal_data(), name),+ |
|
151 | -81x | +
- simplify = FALSE+ #' Validates that vector has length greater than 0 |
|
152 |
- )+ #' |
||
153 | -81x | +
- initial_data_objs <- teal.code::get_var(teal_data(), ".raw_data")+ #' `r lifecycle::badge("stable")` |
|
154 |
-
+ #' |
||
155 | -81x | +
- out <- lapply(+ #' This function is a wrapper for `shiny::validate`. |
|
156 | -81x | +
- datanames,+ #' |
|
157 | -81x | +
- function(dataname) {+ #' @param x vector |
|
158 | -149x | +
- parent <- teal.data::parent(joinkeys, dataname)+ #' @param msg message to display |
|
159 |
- # todo: what should we display for a parent dataset?+ #' |
||
160 |
- # - Obs and Subjects+ #' @export |
||
161 |
- # - Obs only+ #' |
||
162 |
- # - Subjects only+ #' @examples |
||
163 |
- # todo (for later): summary table should be displayed in a way that child datasets+ #' data <- data.frame( |
||
164 |
- # are indented under their parent dataset to form a tree structure+ #' id = c(1:10, 11:20, 1:10), |
||
165 | -149x | +
- subject_keys <- if (length(parent) > 0) {+ #' strata = rep(c("A", "B"), each = 15) |
|
166 | -7x | +
- names(joinkeys[dataname, parent])+ #' ) |
|
167 |
- } else {+ #' ui <- fluidPage( |
||
168 | -142x | +
- joinkeys[dataname, dataname]+ #' selectInput("ref1", "Select strata1 to compare", |
|
169 |
- }+ #' choices = c("A", "B", "C"), selected = "A" |
||
170 | -149x | +
- get_filter_overview(+ #' ), |
|
171 | -149x | +
- current_data = current_data_objs[[dataname]],+ #' selectInput("ref2", "Select strata2 to compare", |
|
172 | -149x | +
- initial_data = initial_data_objs[[dataname]],+ #' choices = c("A", "B", "C"), selected = "B" |
|
173 | -149x | +
- dataname = dataname,+ #' ), |
|
174 | -149x | +
- subject_keys = subject_keys+ #' verbatimTextOutput("arm_summary") |
|
175 |
- )+ #' ) |
||
176 |
- }+ #' |
||
177 |
- )+ #' server <- function(input, output) { |
||
178 |
-
+ #' output$arm_summary <- renderText({ |
||
179 | -81x | +
- do.call(.smart_rbind, out)+ #' sample_1 <- data$id[data$strata == input$ref1] |
|
180 |
- }+ #' sample_2 <- data$id[data$strata == input$ref2] |
||
181 |
-
+ #' |
||
182 |
-
+ #' validate_has_elements(sample_1, "No subjects in strata1.") |
||
183 |
- #' @rdname module_data_summary+ #' validate_has_elements(sample_2, "No subjects in strata2.") |
||
184 |
- #' @param current_data (`object`) current object (after filtering and transforming).+ #' |
||
185 |
- #' @param initial_data (`object`) initial object.+ #' paste0( |
||
186 |
- #' @param dataname (`character(1)`)+ #' "Number of samples in: strata1=", length(sample_1), |
||
187 |
- #' @param subject_keys (`character`) names of the columns which determine a single unique subjects+ #' " comparions strata2=", length(sample_2) |
||
188 |
- get_filter_overview <- function(current_data, initial_data, dataname, subject_keys) {+ #' ) |
||
189 | -154x | +
- if (inherits(current_data, c("data.frame", "DataFrame", "array", "Matrix", "SummarizedExperiment"))) {+ #' }) |
|
190 | -146x | +
- get_filter_overview_array(current_data, initial_data, dataname, subject_keys)+ #' } |
|
191 | -8x | +
- } else if (inherits(current_data, "MultiAssayExperiment")) {+ #' if (interactive()) { |
|
192 | -1x | +
- get_filter_overview_MultiAssayExperiment(current_data, initial_data, dataname)+ #' shinyApp(ui, server) |
|
193 |
- } else {+ #' } |
||
194 | -7x | +
- data.frame(dataname = dataname)+ validate_has_elements <- function(x, msg) { |
|
195 | -+ | ! |
- }+ validate(need(length(x) > 0, msg)) |
198 |
- #' @rdname module_data_summary+ #' Validates no intersection between two vectors |
||
199 |
- get_filter_overview_array <- function(current_data,+ #' |
||
200 |
- initial_data,+ #' `r lifecycle::badge("stable")` |
||
201 |
- dataname,+ #' |
||
202 |
- subject_keys) {+ #' This function is a wrapper for `shiny::validate`. |
||
203 | -146x | +
- if (length(subject_keys) == 0) {+ #' |
|
204 | -133x | +
- data.frame(+ #' @param x vector |
|
205 | -133x | +
- dataname = dataname,+ #' @param y vector |
|
206 | -133x | +
- obs = if (!is.null(initial_data)) {+ #' @param msg (`character(1)`) message to display if `x` and `y` intersect |
|
207 | -124x | +
- sprintf("%s/%s", nrow(current_data), nrow(initial_data))+ #' |
|
208 |
- } else {+ #' @export |
||
209 | -9x | +
- nrow(current_data)+ #' |
|
210 |
- }+ #' @examples |
||
211 |
- )+ #' data <- data.frame( |
||
212 |
- } else {+ #' id = c(1:10, 11:20, 1:10), |
||
213 | -13x | +
- data.frame(+ #' strata = rep(c("A", "B", "C"), each = 10) |
|
214 | -13x | +
- dataname = dataname,+ #' ) |
|
215 | -13x | +
- obs = if (!is.null(initial_data)) {+ #' |
|
216 | -13x | +
- sprintf("%s/%s", nrow(current_data), nrow(initial_data))+ #' ui <- fluidPage( |
|
217 |
- } else {+ #' selectInput("ref1", "Select strata1 to compare", |
||
218 | -! | +
- nrow(current_data)+ #' choices = c("A", "B", "C"), |
|
219 |
- },+ #' selected = "A" |
||
220 | -13x | +
- subjects = if (!is.null(initial_data)) {+ #' ), |
|
221 | -13x | +
- sprintf("%s/%s", nrow(unique(current_data[subject_keys])), nrow(unique(initial_data[subject_keys])))+ #' selectInput("ref2", "Select strata2 to compare", |
|
222 |
- } else {+ #' choices = c("A", "B", "C"), |
||
223 | -! | +
- nrow(unique(current_data[subject_keys]))+ #' selected = "B" |
|
224 |
- }+ #' ), |
||
225 |
- )+ #' verbatimTextOutput("summary") |
||
226 |
- }+ #' ) |
||
227 |
- }+ #' |
||
228 |
-
+ #' server <- function(input, output) { |
||
229 |
- #' @rdname module_data_summary+ #' output$summary <- renderText({ |
||
230 |
- get_filter_overview_MultiAssayExperiment <- function(current_data, # nolint: object_length, object_name.+ #' sample_1 <- data$id[data$strata == input$ref1] |
||
231 |
- initial_data,+ #' sample_2 <- data$id[data$strata == input$ref2] |
||
232 |
- dataname) {+ #' |
||
233 | -1x | +
- experiment_names <- names(current_data)+ #' validate_no_intersection( |
|
234 | -1x | +
- mae_info <- data.frame(+ #' sample_1, sample_2, |
|
235 | -1x | +
- dataname = dataname,+ #' "subjects within strata1 and strata2 cannot overlap" |
|
236 | -1x | +
- subjects = if (!is.null(initial_data)) {+ #' ) |
|
237 | -! | +
- sprintf("%s/%s", nrow(current_data@colData), nrow(initial_data@colData))+ #' paste0( |
|
238 |
- } else {+ #' "Number of subject in: reference treatment=", length(sample_1), |
||
239 | -1x | +
- nrow(current_data@colData)+ #' " comparions treatment=", length(sample_2) |
|
240 |
- }+ #' ) |
||
241 |
- )+ #' }) |
||
242 |
-
+ #' } |
||
243 | -1x | +
- experiment_obs_info <- do.call("rbind", lapply(+ #' if (interactive()) { |
|
244 | -1x | +
- experiment_names,+ #' shinyApp(ui, server) |
|
245 | -1x | +
- function(experiment_name) {+ #' } |
|
246 | -5x | -
- transform(- |
- |
247 | -5x | -
- get_filter_overview(- |
- |
248 | -5x | -
- current_data[[experiment_name]],- |
- |
249 | -5x | -
- initial_data[[experiment_name]],- |
- |
250 | -5x | -
- dataname = experiment_name,- |
- |
251 | -5x | +
- subject_keys = join_keys() # empty join keys+ #' |
|
252 | +247 |
- ),- |
- |
253 | -5x | -
- dataname = paste0(" - ", experiment_name)+ validate_no_intersection <- function(x, y, msg) { |
|
254 | -+ | ||
248 | +! |
- )+ validate(need(length(intersect(x, y)) == 0, msg)) |
|
255 | +249 |
- }+ } |
|
256 | +250 |
- ))+ |
|
257 | +251 | ||
258 | -1x | -
- get_experiment_keys <- function(mae, experiment) {- |
- |
259 | -5x | -
- sample_subset <- mae@sampleMap[mae@sampleMap$colname %in% colnames(experiment), ]- |
- |
260 | -5x | -
- length(unique(sample_subset$primary))- |
- |
261 | +252 |
- }+ #' Validates that dataset contains specific variable |
|
262 | +253 | - - | -|
263 | -1x | -
- experiment_subjects_info <- do.call("rbind", lapply(- |
- |
264 | -1x | -
- experiment_names,- |
- |
265 | -1x | -
- function(experiment_name) {- |
- |
266 | -5x | -
- data.frame(- |
- |
267 | -5x | -
- subjects = if (!is.null(initial_data)) {- |
- |
268 | -! | -
- sprintf(- |
- |
269 | -! | -
- "%s/%s",- |
- |
270 | -! | -
- get_experiment_keys(current_data, current_data[[experiment_name]]),- |
- |
271 | -! | -
- get_experiment_keys(current_data, initial_data[[experiment_name]])+ #' |
|
272 | +254 |
- )+ #' `r lifecycle::badge("stable")` |
|
273 | +255 |
- } else {- |
- |
274 | -5x | -
- get_experiment_keys(current_data, current_data[[experiment_name]])+ #' |
|
275 | +256 |
- }+ #' This function is a wrapper for `shiny::validate`. |
|
276 | +257 |
- )+ #' |
|
277 | +258 |
- }+ #' @param data (`data.frame`) |
|
278 | +259 |
- ))+ #' @param varname (`character(1)`) name of variable to check for in `data` |
|
279 | +260 | - - | -|
280 | -1x | -
- experiment_info <- cbind(experiment_obs_info, experiment_subjects_info)- |
- |
281 | -1x | -
- .smart_rbind(mae_info, experiment_info)+ #' @param msg (`character(1)`) message to display if `data` does not include `varname` |
|
282 | +261 |
- }+ #' |
1 | +262 |
- #' App state management.+ #' @export |
|
2 | +263 |
#' |
|
3 | +264 |
- #' @description+ #' @examples |
|
4 | +265 |
- #' `r lifecycle::badge("experimental")`+ #' data <- data.frame( |
|
5 | +266 |
- #'+ #' one = rep("a", length.out = 20), |
|
6 | +267 |
- #' Capture and restore the global (app) input state.+ #' two = rep(c("a", "b"), length.out = 20) |
|
7 | +268 |
- #'+ #' ) |
|
8 | +269 |
- #' @details+ #' ui <- fluidPage( |
|
9 | +270 |
- #' This module introduces bookmarks into `teal` apps: the `shiny` bookmarking mechanism becomes enabled+ #' selectInput( |
|
10 | +271 |
- #' and server-side bookmarks can be created.+ #' "var", |
|
11 | +272 |
- #'+ #' "Select variable", |
|
12 | +273 |
- #' The bookmark manager presents a button with the bookmark icon and is placed in the tab-bar.+ #' choices = c("one", "two", "three", "four"), |
|
13 | +274 |
- #' When clicked, the button creates a bookmark and opens a modal which displays the bookmark URL.+ #' selected = "one" |
|
14 | +275 |
- #'+ #' ), |
|
15 | +276 |
- #' `teal` does not guarantee that all modules (`teal_module` objects) are bookmarkable.+ #' verbatimTextOutput("summary") |
|
16 | +277 |
- #' Those that are, have a `teal_bookmarkable` attribute set to `TRUE`. If any modules are not bookmarkable,+ #' ) |
|
17 | +278 |
- #' the bookmark manager modal displays a warning and the bookmark button displays a flag.+ #' |
|
18 | +279 |
- #' In order to communicate that a external module is bookmarkable, the module developer+ #' server <- function(input, output) { |
|
19 | +280 |
- #' should set the `teal_bookmarkable` attribute to `TRUE`.+ #' output$summary <- renderText({ |
|
20 | +281 |
- #'+ #' validate_has_variable(data, input$var) |
|
21 | +282 |
- #' @section Server logic:+ #' paste0("Selected treatment variables: ", paste(input$var, collapse = ", ")) |
|
22 | +283 |
- #' A bookmark is a URL that contains the app address with a `/?_state_id_=<bookmark_dir>` suffix.+ #' }) |
|
23 | +284 |
- #' `<bookmark_dir>` is a directory created on the server, where the state of the application is saved.+ #' } |
|
24 | +285 |
- #' Accessing the bookmark URL opens a new session of the app that starts in the previously saved state.+ #' if (interactive()) { |
|
25 | +286 |
- #'+ #' shinyApp(ui, server) |
|
26 | +287 |
- #' @section Note:+ #' } |
|
27 | +288 |
- #' To enable bookmarking use either:+ validate_has_variable <- function(data, varname, msg) { |
|
28 | -+ | ||
289 | +! |
- #' - `shiny` app by using `shinyApp(..., enableBookmarking = "server")` (not supported in `shinytest2`)+ if (length(varname) != 0) { |
|
29 | -+ | ||
290 | +! |
- #' - set `options(shiny.bookmarkStore = "server")` before running the app+ has_vars <- varname %in% names(data) |
|
30 | +291 |
- #'+ |
|
31 | -+ | ||
292 | +! |
- #'+ if (!all(has_vars)) { |
|
32 | -+ | ||
293 | +! |
- #' @inheritParams init+ if (missing(msg)) { |
|
33 | -+ | ||
294 | +! |
- #'+ msg <- sprintf( |
|
34 | -+ | ||
295 | +! |
- #' @return Invisible `NULL`.+ "%s does not have the required variables: %s.", |
|
35 | -+ | ||
296 | +! |
- #'+ deparse(substitute(data)), |
|
36 | -+ | ||
297 | +! |
- #' @aliases bookmark bookmark_manager bookmark_manager_module+ toString(varname[!has_vars]) |
|
37 | +298 |
- #'+ ) |
|
38 | +299 |
- #' @name module_bookmark_manager+ } |
|
39 | -+ | ||
300 | +! |
- #' @rdname module_bookmark_manager+ validate(need(FALSE, msg)) |
|
40 | +301 |
- #'+ } |
|
41 | +302 |
- #' @keywords internal+ } |
|
42 | +303 |
- #'+ } |
|
43 | +304 |
- NULL+ |
|
44 | +305 |
-
+ #' Validate that variables has expected number of levels |
|
45 | +306 |
- #' @rdname module_bookmark_manager+ #' |
|
46 | +307 |
- ui_bookmark_panel <- function(id, modules) {+ #' `r lifecycle::badge("stable")` |
|
47 | -! | +||
308 | +
- ns <- NS(id)+ #' |
||
48 | +309 |
-
+ #' If the number of levels of `x` is less than `min_levels` |
|
49 | -! | +||
310 | +
- bookmark_option <- get_bookmarking_option()+ #' or greater than `max_levels` the validation will fail. |
||
50 | -! | +||
311 | +
- is_unbookmarkable <- need_bookmarking(modules)+ #' This function is a wrapper for `shiny::validate`. |
||
51 | -! | +||
312 | +
- shinyOptions(bookmarkStore = bookmark_option)+ #' |
||
52 | +313 |
-
+ #' @param x variable name. If `x` is not a factor, the unique values |
|
53 | +314 |
- # Render bookmark warnings count+ #' are treated as levels. |
|
54 | -! | +||
315 | +
- if (!all(is_unbookmarkable) && identical(bookmark_option, "server")) {+ #' @param min_levels cutoff for minimum number of levels of `x` |
||
55 | -! | +||
316 | +
- tags$button(+ #' @param max_levels cutoff for maximum number of levels of `x` |
||
56 | -! | +||
317 | +
- id = ns("do_bookmark"),+ #' @param var_name name of variable being validated for use in |
||
57 | -! | +||
318 | +
- class = "btn action-button wunder_bar_button bookmark_manager_button",+ #' validation message |
||
58 | -! | +||
319 | +
- title = "Add bookmark",+ #' |
||
59 | -! | +||
320 | +
- tags$span(+ #' @export |
||
60 | -! | +||
321 | +
- suppressMessages(icon("fas fa-bookmark")),+ #' @examples |
||
61 | -! | +||
322 | +
- if (any(is_unbookmarkable)) {+ #' data <- data.frame( |
||
62 | -! | +||
323 | +
- tags$span(+ #' one = rep("a", length.out = 20), |
||
63 | -! | +||
324 | +
- sum(is_unbookmarkable),+ #' two = rep(c("a", "b"), length.out = 20), |
||
64 | -! | +||
325 | +
- class = "badge-warning badge-count text-white bg-danger"+ #' three = rep(c("a", "b", "c"), length.out = 20), |
||
65 | +326 |
- )+ #' four = rep(c("a", "b", "c", "d"), length.out = 20), |
|
66 | +327 |
- }+ #' stringsAsFactors = TRUE |
|
67 | +328 |
- )+ #' ) |
|
68 | +329 |
- )+ #' ui <- fluidPage( |
|
69 | +330 |
- }+ #' selectInput( |
|
70 | +331 |
- }+ #' "var", |
|
71 | +332 |
-
+ #' "Select variable", |
|
72 | +333 |
- #' @rdname module_bookmark_manager+ #' choices = c("one", "two", "three", "four"), |
|
73 | +334 |
- srv_bookmark_panel <- function(id, modules) {+ #' selected = "one" |
|
74 | -82x | +||
335 | +
- checkmate::assert_character(id)+ #' ), |
||
75 | -82x | +||
336 | +
- checkmate::assert_class(modules, "teal_modules")+ #' verbatimTextOutput("summary") |
||
76 | -82x | +||
337 | +
- moduleServer(id, function(input, output, session) {+ #' ) |
||
77 | -82x | +||
338 | +
- logger::log_debug("bookmark_manager_srv initializing")+ #' |
||
78 | -82x | +||
339 | +
- ns <- session$ns+ #' server <- function(input, output) { |
||
79 | -82x | +||
340 | +
- bookmark_option <- get_bookmarking_option()+ #' output$summary <- renderText({ |
||
80 | -82x | +||
341 | +
- is_unbookmarkable <- need_bookmarking(modules)+ #' validate_n_levels(data[[input$var]], min_levels = 2, max_levels = 15, var_name = input$var) |
||
81 | +342 |
-
+ #' paste0( |
|
82 | +343 |
- # Set up bookmarking callbacks ----+ #' "Levels of selected treatment variable: ", |
|
83 | +344 |
- # Register bookmark exclusions: do_bookmark button to avoid re-bookmarking+ #' paste(levels(data[[input$var]]), |
|
84 | -82x | +||
345 | +
- setBookmarkExclude(c("do_bookmark"))+ #' collapse = ", " |
||
85 | +346 |
- # This bookmark can only be used on the app session.+ #' ) |
|
86 | -82x | +||
347 | +
- app_session <- .subset2(session, "parent")+ #' ) |
||
87 | -82x | +||
348 | +
- app_session$onBookmarked(function(url) {+ #' }) |
||
88 | -! | +||
349 | +
- logger::log_debug("bookmark_manager_srv@onBookmarked: bookmark button clicked, registering bookmark")+ #' } |
||
89 | -! | +||
350 | +
- modal_content <- if (bookmark_option != "server") {+ #' if (interactive()) { |
||
90 | -! | +||
351 | +
- msg <- sprintf(+ #' shinyApp(ui, server) |
||
91 | -! | +||
352 | +
- "Bookmarking has been set to \"%s\".\n%s\n%s",+ #' } |
||
92 | -! | +||
353 | +
- bookmark_option,+ validate_n_levels <- function(x, min_levels = 1, max_levels = 12, var_name) { |
||
93 | +354 | ! |
- "Only server-side bookmarking is supported.",+ x_levels <- if (is.factor(x)) { |
94 | +355 | ! |
- "Please contact your app developer."+ levels(x) |
95 | +356 |
- )- |
- |
96 | -! | -
- tags$div(+ } else { |
|
97 | +357 | ! |
- tags$p(msg, class = "text-warning")+ unique(x) |
98 | +358 |
- )+ } |
|
99 | +359 |
- } else {+ |
|
100 | +360 | ! |
- tags$div(+ if (!is.null(min_levels) && !(is.null(max_levels))) { |
101 | +361 | ! |
- tags$span(+ validate(need( |
102 | +362 | ! |
- tags$pre(url)- |
-
103 | -- |
- ),+ length(x_levels) >= min_levels && length(x_levels) <= max_levels, |
|
104 | +363 | ! |
- if (any(is_unbookmarkable)) {+ sprintf( |
105 | +364 | ! |
- bkmb_summary <- rapply2(+ "%s variable needs minimum %s level(s) and maximum %s level(s).", |
106 | +365 | ! |
- modules_bookmarkable(modules),+ var_name, min_levels, max_levels |
107 | -! | +||
366 | +
- function(x) {+ ) |
||
108 | -! | +||
367 | +
- if (isTRUE(x)) {+ )) |
||
109 | +368 | ! |
- "\u2705" # check mark+ } else if (!is.null(min_levels)) { |
110 | +369 | ! |
- } else if (isFALSE(x)) {+ validate(need( |
111 | +370 | ! |
- "\u274C" # cross mark- |
-
112 | -- |
- } else {+ length(x_levels) >= min_levels, |
|
113 | +371 | ! |
- "\u2753" # question mark- |
-
114 | -- |
- }+ sprintf("%s variable needs minimum %s levels(s)", var_name, min_levels) |
|
115 | +372 |
- }+ )) |
|
116 | -+ | ||
373 | +! |
- )+ } else if (!is.null(max_levels)) { |
|
117 | +374 | ! |
- tags$div(+ validate(need( |
118 | +375 | ! |
- tags$p(+ length(x_levels) <= max_levels, |
119 | +376 | ! |
- icon("fas fa-exclamation-triangle"),+ sprintf("%s variable needs maximum %s level(s)", var_name, max_levels) |
120 | -! | +||
377 | +
- "Some modules will not be restored when using this bookmark.",+ )) |
||
121 | -! | +||
378 | +
- tags$br(),+ } |
||
122 | -! | +||
379 | +
- "Check the list below to see which modules are not bookmarkable.",+ } |
||
123 | -! | +
1 | +
- class = "text-warning"+ #' Execute and validate `teal_data_module` |
|||
124 | +2 |
- ),+ #' |
||
125 | -! | +|||
3 | +
- tags$pre(yaml::as.yaml(bkmb_summary))+ #' This is a low level module to handle `teal_data_module` execution and validation. |
|||
126 | +4 |
- )+ #' [teal_transform_module()] inherits from [teal_data_module()] so it is handled by this module too. |
||
127 | +5 |
- }+ #' [srv_teal()] accepts various `data` objects and eventually they are all transformed to `reactive` |
||
128 | +6 |
- )+ #' [teal_data()] which is a standard data class in whole `teal` framework. |
||
129 | +7 |
- }+ #' |
||
130 | +8 |
-
+ #' @section data validation: |
||
131 | -! | +|||
9 | +
- showModal(+ #' |
|||
132 | -! | +|||
10 | +
- modalDialog(+ #' Executed [teal_data_module()] is validated and output is validated for consistency. |
|||
133 | -! | +|||
11 | +
- id = ns("bookmark_modal"),+ #' Output `data` is invalid if: |
|||
134 | -! | +|||
12 | +
- title = "Bookmarked teal app url",+ #' 1. [teal_data_module()] is invalid if server doesn't return `reactive`. **Immediately crashes an app!** |
|||
135 | -! | +|||
13 | +
- modal_content,+ #' 2. `reactive` throws a `shiny.error` - happens when module creating [teal_data()] fails. |
|||
136 | -! | +|||
14 | +
- easyClose = TRUE+ #' 3. `reactive` returns `qenv.error` - happens when [teal_data()] evaluates a failing code. |
|||
137 | +15 |
- )+ #' 4. `reactive` object doesn't return [teal_data()]. |
||
138 | +16 |
- )+ #' 5. [teal_data()] object lacks any `datanames` specified in the `modules` argument. |
||
139 | +17 |
- })+ #' |
||
140 | +18 |
-
+ #' `teal` (observers in `srv_teal`) always waits to render an app until `reactive` `teal_data` is |
||
141 | +19 |
- # manually trigger bookmarking because of the problems reported on windows with bookmarkButton in teal+ #' returned. If error 2-4 occurs, relevant error message is displayed to the app user. Once the issue is |
||
142 | -82x | +|||
20 | +
- observeEvent(input$do_bookmark, {+ #' resolved, the app will continue to run. `teal` guarantees that errors in data don't crash the app |
|||
143 | -! | +|||
21 | +
- logger::log_debug("bookmark_manager_srv@1 do_bookmark module clicked.")+ #' (except error 1). |
|||
144 | -! | +|||
22 | +
- session$doBookmark()+ #' |
|||
145 | +23 |
- })+ #' @param id (`character(1)`) Module id |
||
146 | +24 |
-
+ #' @param data (`reactive teal_data`) |
||
147 | -82x | +|||
25 | +
- invisible(NULL)+ #' @param data_module (`teal_data_module`) |
|||
148 | +26 |
- })+ #' @param modules (`teal_modules` or `teal_module`) For `datanames` validation purpose |
||
149 | +27 |
- }+ #' @param validate_shiny_silent_error (`logical`) If `TRUE`, then `shiny.silent.error` is validated and |
||
150 | +28 |
-
+ #' @param is_transformer_failed (`reactiveValues`) contains `logical` flags named after each transformer. |
||
151 | +29 |
-
+ #' Help to determine if any previous transformer failed, so that following transformers can be disabled |
||
152 | +30 |
- #' @rdname module_bookmark_manager+ #' and display a generic failure message. |
||
153 | +31 |
- get_bookmarking_option <- function() {+ #' |
||
154 | -82x | +|||
32 | +
- bookmark_option <- getShinyOption("bookmarkStore")+ #' @return `reactive` `teal_data` |
|||
155 | -82x | +|||
33 | +
- if (is.null(bookmark_option) && identical(getOption("shiny.bookmarkStore"), "server")) {+ #' |
|||
156 | -! | +|||
34 | +
- bookmark_option <- getOption("shiny.bookmarkStore")+ #' @rdname module_teal_data |
|||
157 | +35 |
- }+ #' @name module_teal_data |
||
158 | -82x | +|||
36 | +
- bookmark_option+ #' @keywords internal |
|||
159 | +37 |
- }+ NULL |
||
160 | +38 | |||
161 | +39 |
- #' @rdname module_bookmark_manager+ #' @rdname module_teal_data |
||
162 | +40 |
- need_bookmarking <- function(modules) {+ ui_teal_data <- function(id, data_module = function(id) NULL) { |
||
163 | -82x | +|||
41 | +! |
- unlist(rapply2(+ checkmate::assert_string(id) |
||
164 | -82x | +|||
42 | +! |
- modules_bookmarkable(modules),+ checkmate::assert_function(data_module, args = "id") |
||
165 | -82x | +|||
43 | +! |
- Negate(isTRUE)+ ns <- NS(id) |
||
166 | +44 |
- ))+ |
||
167 | -+ | |||
45 | +! |
- }+ shiny::tagList( |
||
168 | -+ | |||
46 | +! |
-
+ tags$div(id = ns("wrapper"), data_module(id = ns("data"))),+ |
+ ||
47 | +! | +
+ ui_validate_reactive_teal_data(ns("validate")) |
||
169 | +48 |
-
+ ) |
||
170 | +49 |
- # utilities ----+ } |
||
171 | +50 | |||
172 | +51 |
- #' Restore value from bookmark.+ #' @rdname module_teal_data |
||
173 | +52 |
- #'+ srv_teal_data <- function(id, |
||
174 | +53 |
- #' Get value from bookmark or return default.+ data_module = function(id) NULL, |
||
175 | +54 |
- #'+ modules = NULL, |
||
176 | +55 |
- #' Bookmarks can store not only inputs but also arbitrary values.+ validate_shiny_silent_error = TRUE, |
||
177 | +56 |
- #' These values are stored by `onBookmark` callbacks and restored by `onBookmarked` callbacks,+ is_transformer_failed = reactiveValues()) { |
||
178 | -+ | |||
57 | +20x |
- #' and they are placed in the `values` environment in the `session$restoreContext` field.+ checkmate::assert_string(id) |
||
179 | -+ | |||
58 | +20x |
- #' Using `teal_data_module` makes it impossible to run the callbacks+ checkmate::assert_function(data_module, args = "id") |
||
180 | -+ | |||
59 | +20x |
- #' because the app becomes ready before modules execute and callbacks are registered.+ checkmate::assert_multi_class(modules, c("teal_modules", "teal_module"), null.ok = TRUE) |
||
181 | -+ | |||
60 | +20x |
- #' In those cases the stored values can still be recovered from the `session` object directly.+ checkmate::assert_class(is_transformer_failed, "reactivevalues") |
||
182 | +61 |
- #'+ |
||
183 | -+ | |||
62 | +20x |
- #' Note that variable names in the `values` environment are prefixed with module name space names,+ moduleServer(id, function(input, output, session) { |
||
184 | -+ | |||
63 | +20x |
- #' therefore, when using this function in modules, `value` must be run through the name space function.+ logger::log_debug("srv_teal_data initializing.") |
||
185 | -+ | |||
64 | +20x |
- #'+ is_transformer_failed[[id]] <- FALSE |
||
186 | -+ | |||
65 | +20x |
- #' @param value (`character(1)`) name of value to restore+ data_out <- data_module(id = "data") |
||
187 | -+ | |||
66 | +20x |
- #' @param default fallback value+ data_handled <- reactive(tryCatch(data_out(), error = function(e) e)) |
||
188 | -+ | |||
67 | +20x |
- #'+ observeEvent(data_handled(), { |
||
189 | -+ | |||
68 | +22x |
- #' @return+ if (!inherits(data_handled(), "teal_data")) { |
||
190 | -+ | |||
69 | +6x |
- #' In an application restored from a server-side bookmark,+ is_transformer_failed[[id]] <- TRUE |
||
191 | +70 |
- #' the variable specified by `value` from the `values` environment.+ } else { |
||
192 | -+ | |||
71 | +16x |
- #' Otherwise `default`.+ is_transformer_failed[[id]] <- FALSE |
||
193 | +72 |
- #'+ } |
||
194 | +73 |
- #' @keywords internal+ }) |
||
195 | +74 |
- #'+ |
||
196 | -+ | |||
75 | +20x |
- restoreValue <- function(value, default) { # nolint: object_name.+ is_previous_failed <- reactive({ |
||
197 | -164x | +76 | +20x |
- checkmate::assert_character("value")+ idx_this <- which(names(is_transformer_failed) == id) |
198 | -164x | +77 | +20x |
- session_default <- shiny::getDefaultReactiveDomain()+ is_transformer_failed_list <- reactiveValuesToList(is_transformer_failed) |
199 | -164x | +78 | +20x |
- session_parent <- .subset2(session_default, "parent")+ idx_failures <- which(unlist(is_transformer_failed_list)) |
200 | -164x | +79 | +20x |
- session <- if (is.null(session_parent)) session_default else session_parent+ any(idx_failures < idx_this) |
201 | +80 | ++ |
+ })+ |
+ |
81 | ||||
202 | -164x | +82 | +20x |
- if (isTRUE(session$restoreContext$active) && exists(value, session$restoreContext$values, inherits = FALSE)) {+ observeEvent(is_previous_failed(), {+ |
+
83 | +20x | +
+ if (is_previous_failed()) { |
||
203 | +84 | ! |
- session$restoreContext$values[[value]]+ shinyjs::disable("wrapper") |
|
204 | +85 |
- } else {+ } else { |
||
205 | -164x | +86 | +20x |
- default+ shinyjs::enable("wrapper") |
206 | +87 |
- }+ } |
||
207 | +88 |
- }+ }) |
||
208 | +89 | - + + | +||
90 | +20x | +
+ srv_validate_reactive_teal_data(+ |
+ ||
91 | +20x | +
+ "validate",+ |
+ ||
92 | +20x | +
+ data = data_handled,+ |
+ ||
93 | +20x | +
+ modules = modules, |
||
209 | -+ | |||
94 | +20x |
- #' Compare bookmarks.+ validate_shiny_silent_error = validate_shiny_silent_error, |
||
210 | -+ | |||
95 | +20x |
- #'+ hide_validation_error = is_previous_failed |
||
211 | +96 |
- #' Test if two bookmarks store identical state.+ ) |
||
212 | +97 |
- #'+ }) |
||
213 | +98 |
- #' `input` environments are compared one variable at a time and if not identical,+ } |
||
214 | +99 |
- #' values in both bookmarks are reported. States of `datatable`s are stripped+ |
||
215 | +100 |
- #' of the `time` element before comparing because the time stamp is always different.+ #' @rdname module_teal_data |
||
216 | +101 |
- #' The contents themselves are not printed as they are large and the contents are not informative.+ ui_validate_reactive_teal_data <- function(id) { |
||
217 | -+ | |||
102 | +82x |
- #' Elements present in one bookmark and absent in the other are also reported.+ ns <- NS(id) |
||
218 | -+ | |||
103 | +82x |
- #' Differences are printed as messages.+ tagList( |
||
219 | -+ | |||
104 | +82x |
- #'+ div( |
||
220 | -+ | |||
105 | +82x |
- #' `values` environments are compared with `all.equal`.+ id = ns("validate_messages"), |
||
221 | -+ | |||
106 | +82x |
- #'+ class = "teal_validated", |
||
222 | -+ | |||
107 | +82x |
- #' @section How to use:+ ui_validate_error(ns("silent_error")), |
||
223 | -+ | |||
108 | +82x |
- #' Open an application, change relevant inputs (typically, all of them), and create a bookmark.+ ui_check_class_teal_data(ns("class_teal_data")), |
||
224 | -+ | |||
109 | +82x |
- #' Then open that bookmark and immediately create a bookmark of that.+ ui_check_shiny_warnings(ns("shiny_warnings")) |
||
225 | +110 |
- #' If restoring bookmarks occurred properly, the two bookmarks should store the same state.+ ), |
||
226 | -+ | |||
111 | +82x |
- #'+ div( |
||
227 | -+ | |||
112 | +82x |
- #'+ class = "teal_validated", |
||
228 | -+ | |||
113 | +82x |
- #' @param book1,book2 bookmark directories stored in `shiny_bookmarks/`;+ uiOutput(ns("previous_failed")) |
||
229 | +114 |
- #' default to the two most recently modified directories+ ) |
||
230 | +115 |
- #'+ ) |
||
231 | +116 |
- #' @return+ } |
||
232 | +117 |
- #' Invisible `NULL` if bookmarks are identical or if there are no bookmarks to test.+ |
||
233 | +118 |
- #' `FALSE` if inconsistencies are detected.+ #' @rdname module_teal_data |
||
234 | +119 |
- #'+ srv_validate_reactive_teal_data <- function(id, # nolint: object_length |
||
235 | +120 |
- #' @keywords internal+ data, |
||
236 | +121 |
- #'+ modules = NULL, |
||
237 | +122 |
- bookmarks_identical <- function(book1, book2) {+ validate_shiny_silent_error = FALSE, |
||
238 | -! | +|||
123 | +
- if (!dir.exists("shiny_bookmarks")) {+ hide_validation_error = reactive(FALSE)) { |
|||
239 | -! | +|||
124 | +183x |
- message("no bookmark directory")+ checkmate::assert_string(id) |
||
240 | -! | +|||
125 | +183x |
- return(invisible(NULL))+ checkmate::assert_multi_class(modules, c("teal_modules", "teal_module"), null.ok = TRUE) |
||
241 | -+ | |||
126 | +183x |
- }+ checkmate::assert_flag(validate_shiny_silent_error) |
||
242 | +127 | |||
243 | -! | +|||
128 | +183x |
- ans <- TRUE+ moduleServer(id, function(input, output, session) { |
||
244 | +129 | - - | -||
245 | -! | -
- if (missing(book1) && missing(book2)) {- |
- ||
246 | -! | -
- dirs <- list.dirs("shiny_bookmarks", recursive = FALSE)+ # there is an empty reactive cycle on `init` and `data_rv` has `shiny.silent.error` class |
||
247 | -! | +|||
130 | +183x |
- bookmarks_sorted <- basename(rev(dirs[order(file.mtime(dirs))]))+ srv_validate_error("silent_error", data, validate_shiny_silent_error) |
||
248 | -! | +|||
131 | +183x |
- if (length(bookmarks_sorted) < 2L) {+ srv_check_class_teal_data("class_teal_data", data) |
||
249 | -! | +|||
132 | +183x |
- message("no bookmarks to compare")+ srv_check_shiny_warnings("shiny_warnings", data, modules) |
||
250 | -! | +|||
133 | +183x |
- return(invisible(NULL))+ output$previous_failed <- renderUI({ |
||
251 | -+ | |||
134 | +173x |
- }+ if (hide_validation_error()) { |
||
252 | +135 | ! |
- book1 <- bookmarks_sorted[2L]+ shinyjs::hide("validate_messages") |
|
253 | +136 | ! |
- book2 <- bookmarks_sorted[1L]+ tags$div("One of previous transformers failed. Please fix and continue.", class = "teal-output-warning") |
|
254 | +137 |
- } else {+ } else { |
||
255 | -! | +|||
138 | +173x |
- if (!dir.exists(file.path("shiny_bookmarks", book1))) stop(book1, " not found")+ shinyjs::show("validate_messages") |
||
256 | -! | +|||
139 | +173x |
- if (!dir.exists(file.path("shiny_bookmarks", book2))) stop(book2, " not found")+ NULL |
||
257 | +140 |
- }+ } |
||
258 | +141 | - - | -||
259 | -! | -
- book1_input <- readRDS(file.path("shiny_bookmarks", book1, "input.rds"))- |
- ||
260 | -! | -
- book2_input <- readRDS(file.path("shiny_bookmarks", book2, "input.rds"))+ }) |
||
261 | +142 | |||
262 | -! | -
- elements_common <- intersect(names(book1_input), names(book2_input))- |
- ||
263 | -! | -
- dt_states <- grepl("_state$", elements_common)- |
- ||
264 | -! | -
- if (any(dt_states)) {- |
- ||
265 | -! | -
- for (el in elements_common[dt_states]) {- |
- ||
266 | -! | -
- book1_input[[el]][["time"]] <- NULL- |
- ||
267 | -! | +|||
143 | +183x |
- book2_input[[el]][["time"]] <- NULL+ .trigger_on_success(data) |
||
268 | +144 |
- }+ }) |
||
269 | +145 |
- }+ } |
||
270 | +146 | |||
271 | -! | -
- identicals <- mapply(identical, book1_input[elements_common], book2_input[elements_common])- |
- ||
272 | -! | -
- non_identicals <- names(identicals[!identicals])- |
- ||
273 | -! | +|||
147 | +
- compares <- sprintf("$ %s:\t%s --- %s", non_identicals, book1_input[non_identicals], book2_input[non_identicals])+ #' @keywords internal |
|||
274 | -! | +|||
148 | +
- if (length(compares) != 0L) {+ ui_validate_error <- function(id) { |
|||
275 | -! | +|||
149 | +82x |
- message("common elements not identical: \n", paste(compares, collapse = "\n"))+ ns <- NS(id) |
||
276 | -! | +|||
150 | +82x |
- ans <- FALSE+ uiOutput(ns("message")) |
||
277 | +151 |
- }+ } |
||
278 | +152 | |||
279 | -! | -
- elements_boook1 <- setdiff(names(book1_input), names(book2_input))- |
- ||
280 | -! | -
- if (length(elements_boook1) != 0L) {- |
- ||
281 | -! | -
- dt_states <- grepl("_state$", elements_boook1)- |
- ||
282 | -! | +|||
153 | +
- if (any(dt_states)) {+ #' @keywords internal |
|||
283 | -! | +|||
154 | +
- for (el in elements_boook1[dt_states]) {+ srv_validate_error <- function(id, data, validate_shiny_silent_error) { |
|||
284 | -! | +|||
155 | +183x |
- if (is.list(book1_input[[el]])) book1_input[[el]] <- "--- data table state ---"+ checkmate::assert_string(id) |
||
285 | -+ | |||
156 | +183x |
- }+ checkmate::assert_flag(validate_shiny_silent_error) |
||
286 | -+ | |||
157 | +183x |
- }+ moduleServer(id, function(input, output, session) { |
||
287 | -! | +|||
158 | +183x |
- excess1 <- sprintf("$ %s:\t%s", elements_boook1, book1_input[elements_boook1])+ output$message <- renderUI({ |
||
288 | -! | +|||
159 | +186x |
- message("elements only in book1: \n", paste(excess1, collapse = "\n"))+ is_shiny_silent_error <- inherits(data(), "shiny.silent.error") && identical(data()$message, "") |
||
289 | -! | +|||
160 | +180x |
- ans <- FALSE+ if (inherits(data(), "qenv.error")) { |
||
290 | -+ | |||
161 | +2x |
- }+ validate( |
||
291 | -+ | |||
162 | +2x |
-
+ need( |
||
292 | -! | +|||
163 | +2x |
- elements_boook2 <- setdiff(names(book2_input), names(book1_input))+ FALSE, |
||
293 | -! | +|||
164 | +2x |
- if (length(elements_boook2) != 0L) {+ paste( |
||
294 | -! | +|||
165 | +2x |
- dt_states <- grepl("_state$", elements_boook1)+ "Error when executing the `data` module:", |
||
295 | -! | +|||
166 | +2x |
- if (any(dt_states)) {+ strip_style(paste(data()$message, collapse = "\n")), |
||
296 | -! | +|||
167 | +2x |
- for (el in elements_boook1[dt_states]) {+ "\nCheck your inputs or contact app developer if error persists.", |
||
297 | -! | +|||
168 | +2x |
- if (is.list(book2_input[[el]])) book2_input[[el]] <- "--- data table state ---"+ collapse = "\n" |
||
298 | +169 |
- }+ ) |
||
299 | +170 |
- }+ ) |
||
300 | -! | +|||
171 | +
- excess2 <- sprintf("$ %s:\t%s", elements_boook2, book2_input[elements_boook2])+ ) |
|||
301 | -! | +|||
172 | +178x |
- message("elements only in book2: \n", paste(excess2, collapse = "\n"))+ } else if (inherits(data(), "error")) { |
||
302 | -! | +|||
173 | +7x |
- ans <- FALSE+ if (is_shiny_silent_error && !validate_shiny_silent_error) { |
||
303 | -+ | |||
174 | +1x |
- }+ return(NULL) |
||
304 | +175 |
-
+ } |
||
305 | -! | +|||
176 | +6x |
- book1_values <- readRDS(file.path("shiny_bookmarks", book1, "values.rds"))+ validate( |
||
306 | -! | +|||
177 | +6x |
- book2_values <- readRDS(file.path("shiny_bookmarks", book2, "values.rds"))+ need( |
||
307 | -+ | |||
178 | +6x |
-
+ FALSE, |
||
308 | -! | +|||
179 | +6x |
- if (!isTRUE(all.equal(book1_values, book2_values))) {+ sprintf( |
||
309 | -! | +|||
180 | +6x |
- message("different values detected")+ "Shiny error when executing the `data` module.\n%s\n%s", |
||
310 | -! | +|||
181 | +6x |
- message("choices for numeric filters MAY be different, see RangeFilterState$set_choices")+ data()$message, |
||
311 | -! | +|||
182 | +6x |
- ans <- FALSE+ "Check your inputs or contact app developer if error persists." |
||
312 | +183 |
- }+ ) |
||
313 | +184 |
-
+ ) |
||
314 | -! | +|||
185 | +
- if (ans) message("perfect!")+ ) |
|||
315 | -! | +|||
186 | +
- invisible(NULL)+ } |
|||
316 | +187 |
- }+ }) |
||
317 | +188 |
-
+ }) |
||
318 | +189 |
-
+ } |
||
319 | +190 |
- # Replacement for [base::rapply] which doesn't handle NULL values - skips the evaluation+ |
||
320 | +191 |
- # of the function and returns NULL for given element.+ |
||
321 | +192 |
- rapply2 <- function(x, f) {+ #' @keywords internal |
||
322 | -189x | +|||
193 | +
- if (inherits(x, "list")) {+ ui_check_class_teal_data <- function(id) { |
|||
323 | +194 | 82x |
- lapply(x, rapply2, f = f)- |
- |
324 | -- |
- } else {+ ns <- NS(id) |
||
325 | -107x | +195 | +82x |
- f(x)+ uiOutput(ns("message")) |
326 | +196 |
- }+ } |
||
327 | +197 |
- }+ |
1 | +198 |
- #' Generate lockfile for application's environment reproducibility+ #' @keywords internal |
||
2 | +199 |
- #'+ srv_check_class_teal_data <- function(id, data) { |
||
3 | -+ | |||
200 | +183x |
- #' @param lockfile_path (`character`) path to the lockfile.+ checkmate::assert_string(id) |
||
4 | -+ | |||
201 | +183x |
- #'+ moduleServer(id, function(input, output, session) { |
||
5 | -+ | |||
202 | +183x |
- #' @section Different ways of creating lockfile:+ output$message <- renderUI({ |
||
6 | -+ | |||
203 | +186x |
- #' `teal` leverages [renv::snapshot()], which offers multiple methods for lockfile creation.+ validate( |
||
7 | -+ | |||
204 | +186x |
- #'+ need( |
||
8 | -+ | |||
205 | +186x |
- #' - **Working directory lockfile**: `teal`, by default, will create an `implicit` type lockfile that uses+ inherits(data(), c("teal_data", "error")), |
||
9 | -+ | |||
206 | +186x |
- #' `renv::dependencies()` to detect all R packages in the current project's working directory.+ "Did not receive `teal_data` object. Cannot proceed further." |
||
10 | +207 |
- #' - **`DESCRIPTION`-based lockfile**: To generate a lockfile based on a `DESCRIPTION` file in your working+ ) |
||
11 | +208 |
- #' directory, set `renv::settings$snapshot.type("explicit")`. The naming convention for `type` follows+ ) |
||
12 | +209 |
- #' `renv::snapshot()`. For the `"explicit"` type, refer to `renv::settings$package.dependency.fields()` for the+ }) |
||
13 | +210 |
- #' `DESCRIPTION` fields included in the lockfile.+ }) |
||
14 | +211 |
- #' - **Custom files-based lockfile**: To specify custom files as the basis for the lockfile, set+ } |
||
15 | +212 |
- #' `renv::settings$snapshot.type("custom")` and configure the `renv.snapshot.filter` option.+ |
||
16 | +213 |
- #'+ #' @keywords internal |
||
17 | +214 |
- #' @section lockfile usage:+ ui_check_shiny_warnings <- function(id) { |
||
18 | -+ | |||
215 | +82x |
- #' After creating the lockfile, you can restore the application's environment using `renv::restore()`.+ ns <- NS(id) |
||
19 | -+ | |||
216 | +82x |
- #'+ uiOutput(NS(id, "message")) |
||
20 | +217 |
- #' @seealso [renv::snapshot()], [renv::restore()].+ } |
||
21 | +218 |
- #'+ |
||
22 | +219 |
- #' @return `NULL`+ #' @keywords internal |
||
23 | +220 |
- #'+ srv_check_shiny_warnings <- function(id, data, modules) { |
||
24 | -+ | |||
221 | +183x |
- #' @name module_teal_lockfile+ checkmate::assert_string(id) |
||
25 | -+ | |||
222 | +183x |
- #' @rdname module_teal_lockfile+ moduleServer(id, function(input, output, session) { |
||
26 | -+ | |||
223 | +183x |
- #'+ output$message <- renderUI({ |
||
27 | -+ | |||
224 | +186x |
- #' @keywords internal+ if (inherits(data(), "teal_data")) { |
||
28 | -+ | |||
225 | +169x |
- NULL+ is_modules_ok <- check_modules_datanames_html( |
||
29 | -+ | |||
226 | +169x |
-
+ modules = modules, datanames = names(data()) |
||
30 | +227 |
- #' @rdname module_teal_lockfile+ ) |
||
31 | -+ | |||
228 | +169x |
- ui_teal_lockfile <- function(id) {+ if (!isTRUE(is_modules_ok)) { |
||
32 | -! | +|||
229 | +15x |
- ns <- NS(id)+ tags$div(is_modules_ok, class = "teal-output-warning") |
||
33 | -! | +|||
230 | +
- shiny::tagList(+ } |
|||
34 | -! | +|||
231 | +
- tags$span("", id = ns("lockFileStatus")),+ } |
|||
35 | -! | +|||
232 | +
- shinyjs::disabled(downloadLink(ns("lockFileLink"), "Download lockfile"))+ }) |
|||
36 | +233 |
- )+ }) |
||
37 | +234 |
} |
||
38 | +235 | |||
39 | +236 |
- #' @rdname module_teal_lockfile+ .trigger_on_success <- function(data) { |
||
40 | -+ | |||
237 | +183x |
- srv_teal_lockfile <- function(id) {+ out <- reactiveVal(NULL) |
||
41 | -83x | +238 | +183x |
- moduleServer(id, function(input, output, session) {+ observeEvent(data(), { |
42 | -83x | +239 | +180x |
- logger::log_debug("Initialize srv_teal_lockfile.")+ if (inherits(data(), "teal_data")) { |
43 | -83x | +240 | +169x |
- enable_lockfile_download <- function() {+ if (!identical(data(), out())) { |
44 | -! | +|||
241 | +169x |
- shinyjs::html("lockFileStatus", "Application lockfile ready.")+ out(data()) |
||
45 | -! | +|||
242 | +
- shinyjs::hide("lockFileStatus", anim = TRUE)+ } |
|||
46 | -! | +|||
243 | +
- shinyjs::enable("lockFileLink")+ } |
|||
47 | -! | +|||
244 | +
- output$lockFileLink <- shiny::downloadHandler(+ }) |
|||
48 | -! | +|||
245 | +
- filename = function() {+ |
|||
49 | -! | +|||
246 | +183x |
- "renv.lock"+ out |
||
50 | +247 |
- },+ } |
||
51 | -! | +
1 | +
- content = function(file) {+ #' Store and restore `teal_slices` object |
|||
52 | -! | +|||
2 | +
- file.copy(lockfile_path, file)+ #' |
|||
53 | -! | +|||
3 | +
- file+ #' Functions that write a `teal_slices` object to a file in the `JSON` format, |
|||
54 | +4 |
- },+ #' and also restore the object from disk. |
||
55 | -! | +|||
5 | +
- contentType = "application/json"+ #' |
|||
56 | +6 |
- )+ #' Date and date time objects are stored in the following formats: |
||
57 | +7 |
- }+ #' |
||
58 | -83x | +|||
8 | +
- disable_lockfile_download <- function() {+ #' - `Date` class is converted to the `"ISO8601"` standard (`YYYY-MM-DD`). |
|||
59 | -! | +|||
9 | +
- warning("Lockfile creation failed.", call. = FALSE)+ #' - `POSIX*t` classes are converted to character by using |
|||
60 | -! | +|||
10 | +
- shinyjs::html("lockFileStatus", "Lockfile creation failed.")+ #' `format.POSIX*t(usetz = TRUE, tz = "UTC")` (`YYYY-MM-DD HH:MM:SS UTC`, where |
|||
61 | -! | +|||
11 | +
- shinyjs::hide("lockFileLink")+ #' `UTC` is the `Coordinated Universal Time` timezone short-code). |
|||
62 | +12 |
- }+ #' |
||
63 | +13 |
-
+ #' This format is assumed during `slices_restore`. All `POSIX*t` objects in |
||
64 | -83x | +|||
14 | +
- shiny::onStop(function() {+ #' `selected` or `choices` fields of `teal_slice` objects are always printed in |
|||
65 | -83x | +|||
15 | +
- if (file.exists(lockfile_path) && !shiny::isRunning()) {+ #' `UTC` timezone as well. |
|||
66 | -1x | +|||
16 | +
- logger::log_debug("Removing lockfile after shutting down the app")+ #' |
|||
67 | -1x | +|||
17 | +
- file.remove(lockfile_path)+ #' @param tss (`teal_slices`) object to be stored. |
|||
68 | +18 |
- }+ #' @param file (`character(1)`) file path where `teal_slices` object will be |
||
69 | +19 |
- })+ #' saved and restored. The file extension should be `".json"`. |
||
70 | +20 |
-
+ #' |
||
71 | -83x | +|||
21 | +
- lockfile_path <- "teal_app.lock"+ #' @return `slices_store` returns `NULL`, invisibly. |
|||
72 | -83x | +|||
22 | +
- mode <- getOption("teal.lockfile.mode", default = "")+ #' |
|||
73 | +23 |
-
+ #' @seealso [teal_slices()] |
||
74 | -83x | +|||
24 | +
- if (!(mode %in% c("auto", "enabled", "disabled"))) {+ #' |
|||
75 | -! | +|||
25 | +
- stop("'teal.lockfile.mode' option can only be one of \"auto\", \"disabled\" or \"disabled\". ")+ #' @keywords internal |
|||
76 | +26 |
- }+ #' |
||
77 | +27 |
-
+ slices_store <- function(tss, file) { |
||
78 | -83x | +28 | +9x |
- if (mode == "disabled") {+ checkmate::assert_class(tss, "teal_slices") |
79 | -1x | +29 | +9x |
- logger::log_debug("'teal.lockfile.mode' option is set to 'disabled'. Hiding lockfile download button.")+ checkmate::assert_path_for_output(file, overwrite = TRUE, extension = "json") |
80 | -1x | +|||
30 | +
- shinyjs::hide("lockFileLink")+ |
|||
81 | -1x | +31 | +9x |
- return(NULL)+ cat(format(tss, trim_lines = FALSE), "\n", file = file) |
82 | +32 |
- }+ } |
||
83 | +33 | |||
84 | -82x | +|||
34 | +
- if (file.exists(lockfile_path)) {+ #' @rdname slices_store |
|||
85 | -! | +|||
35 | +
- logger::log_debug("Lockfile has already been created for this app - skipping automatic creation.")+ #' @return `slices_restore` returns a `teal_slices` object restored from the file. |
|||
86 | -! | +|||
36 | +
- enable_lockfile_download()+ #' @keywords internal |
|||
87 | -! | +|||
37 | +
- return(NULL)+ slices_restore <- function(file) { |
|||
88 | -+ | |||
38 | +9x |
- }+ checkmate::assert_file_exists(file, access = "r", extension = "json") |
||
89 | +39 | |||
90 | -82x | +40 | +9x |
- if (mode == "auto" && .is_disabled_lockfile_scenario()) {+ tss_json <- jsonlite::fromJSON(file, simplifyDataFrame = FALSE) |
91 | -81x | +41 | +9x |
- logger::log_debug(+ tss_json$slices <- |
92 | -81x | +42 | +9x |
- "Automatic lockfile creation disabled. Execution scenario satisfies teal:::.is_disabled_lockfile_scenario()."+ lapply(tss_json$slices, function(slice) { |
93 | -+ | |||
43 | +9x |
- )+ for (field in c("selected", "choices")) { |
||
94 | -81x | +44 | +18x |
- shinyjs::hide("lockFileLink")+ if (!is.null(slice[[field]])) { |
95 | -81x | +45 | +12x |
- return(NULL)+ if (length(slice[[field]]) > 0) { |
96 | -+ | |||
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$") |
||
97 | +48 | |||
98 | -1x | +49 | +9x |
- if (!.is_lockfile_deps_installed()) {+ slice[[field]] <- |
99 | -! | +|||
50 | +9x |
- warning("Automatic lockfile creation disabled. `mirai` and `renv` packages must be installed.")+ if (all(grepl(paste0(date_partial_regex, "$"), slice[[field]]))) { |
||
100 | -! | +|||
51 | +3x |
- shinyjs::hide("lockFileLink")+ as.Date(slice[[field]]) |
||
101 | -! | +|||
52 | +9x |
- return(NULL)+ } else if (all(grepl(time_stamp_regex, slice[[field]]))) { |
||
102 | -+ | |||
53 | +3x |
- }+ as.POSIXct(slice[[field]], tz = "UTC") |
||
103 | +54 |
-
+ } else { |
||
104 | -+ | |||
55 | +3x |
- # - Will be run only if the lockfile doesn't exist (see the if-s above)+ slice[[field]] |
||
105 | +56 |
- # - We render to the tempfile because the process might last after session is closed and we don't+ } |
||
106 | +57 |
- # want to make a "teal_app.renv" then. This is why we copy only during active session.- |
- ||
107 | -1x | -
- process <- .teal_lockfile_process_invoke(lockfile_path)+ } else { |
||
108 | -1x | -
- observeEvent(process$status(), {- |
- ||
109 | -! | -
- if (process$status() %in% c("initial", "running")) {- |
- ||
110 | -! | -
- shinyjs::html("lockFileStatus", "Creating lockfile...")- |
- ||
111 | -! | -
- } else if (process$status() == "success") {- |
- ||
112 | -! | +58 | +3x |
- result <- process$result()+ slice[[field]] <- character(0) |
113 | -! | +|||
59 | +
- if (any(grepl("Lockfile written to", result$out))) {+ } |
|||
114 | -! | +|||
60 | +
- logger::log_debug("Lockfile containing { length(result$res$Packages) } packages created.")+ } |
|||
115 | -! | +|||
61 | +
- if (any(grepl("(WARNING|ERROR):", result$out))) {+ } |
|||
116 | -! | +|||
62 | +9x |
- warning("Lockfile created with warning(s) or error(s):", call. = FALSE)+ slice |
||
117 | -! | +|||
63 | +
- for (i in result$out) {+ }) |
|||
118 | -! | +|||
64 | +
- warning(i, call. = FALSE)+ |
|||
119 | -+ | |||
65 | +9x |
- }+ tss_elements <- lapply(tss_json$slices, as.teal_slice) |
||
120 | +66 |
- }+ |
||
121 | -! | +|||
67 | +9x |
- enable_lockfile_download()+ do.call(teal_slices, c(tss_elements, tss_json$attributes)) |
||
122 | +68 |
- } else {+ } |
||
123 | -! | +
1 | +
- disable_lockfile_download()+ #' @title `TealReportCard` |
|||
124 | +2 |
- }+ #' @description `r lifecycle::badge("experimental")` |
||
125 | -! | +|||
3 | +
- } else if (process$status() == "error") {+ #' Child class of [`ReportCard`] that is used for `teal` specific applications. |
|||
126 | -! | +|||
4 | +
- disable_lockfile_download()+ #' In addition to the parent methods, it supports rendering `teal` specific elements such as |
|||
127 | +5 |
- }+ #' the source code, the encodings panel content and the filter panel content as part of the |
||
128 | +6 |
- })+ #' meta data. |
||
129 | +7 |
-
+ #' @export |
||
130 | -1x | +|||
8 | +
- NULL+ #' |
|||
131 | +9 |
- })+ TealReportCard <- R6::R6Class( # nolint: object_name. |
||
132 | +10 |
- }+ classname = "TealReportCard", |
||
133 | +11 |
-
+ inherit = teal.reporter::ReportCard, |
||
134 | +12 |
- utils::globalVariables(c("opts", "sysenv", "libpaths", "wd", "lockfilepath", "run")) # needed for mirai call+ public = list( |
||
135 | +13 |
- #' @rdname module_teal_lockfile+ #' @description Appends the source code to the `content` meta data of this `TealReportCard`. |
||
136 | +14 |
- .teal_lockfile_process_invoke <- function(lockfile_path) {+ #' |
||
137 | -1x | +|||
15 | +
- mirai_obj <- NULL+ #' @param src (`character(1)`) code as text. |
|||
138 | -1x | +|||
16 | +
- process <- shiny::ExtendedTask$new(function() {+ #' @param ... any `rmarkdown` `R` chunk parameter and its value. |
|||
139 | -1x | +|||
17 | +
- m <- mirai::mirai(+ #' But `eval` parameter is always set to `FALSE`. |
|||
140 | +18 |
- {+ #' @return Object of class `TealReportCard`, invisibly. |
||
141 | -1x | +|||
19 | +
- options(opts)+ #' @examples |
|||
142 | -1x | +|||
20 | +
- do.call(Sys.setenv, sysenv)+ #' card <- TealReportCard$new()$append_src( |
|||
143 | -1x | +|||
21 | +
- .libPaths(libpaths)+ #' "plot(iris)" |
|||
144 | -1x | +|||
22 | +
- setwd(wd)+ #' ) |
|||
145 | -1x | +|||
23 | +
- run(lockfile_path = lockfile_path)+ #' card$get_content()[[1]]$get_content() |
|||
146 | +24 |
- },+ append_src = function(src, ...) { |
||
147 | -1x | +25 | +4x |
- run = .renv_snapshot,+ checkmate::assert_character(src, min.len = 0, max.len = 1) |
148 | -1x | +26 | +4x |
- lockfile_path = lockfile_path,+ params <- list(...) |
149 | -1x | +27 | +4x |
- opts = options(),+ params$eval <- FALSE |
150 | -1x | +28 | +4x |
- libpaths = .libPaths(),+ rblock <- RcodeBlock$new(src) |
151 | -1x | +29 | +4x |
- sysenv = as.list(Sys.getenv()),+ rblock$set_params(params) |
152 | -1x | -
- wd = getwd()- |
- ||
153 | -+ | 30 | +4x |
- )+ self$append_content(rblock) |
154 | -1x | +31 | +4x |
- mirai_obj <<- m+ self$append_metadata("SRC", src) |
155 | -1x | +32 | +4x |
- m+ invisible(self) |
156 | +33 |
- })+ }, |
||
157 | +34 |
-
+ #' @description Appends the filter state list to the `content` and `metadata` of this `TealReportCard`. |
||
158 | -1x | +|||
35 | +
- shiny::onStop(function() {+ #' If the filter state list has an attribute named `formatted`, it appends it to the card otherwise it uses |
|||
159 | -1x | +|||
36 | +
- if (mirai::unresolved(mirai_obj)) {+ #' the default `yaml::as.yaml` to format the list. |
|||
160 | -! | +|||
37 | +
- logger::log_debug("Terminating a running lockfile process...")+ #' If the filter state list is empty, nothing is appended to the `content`. |
|||
161 | -! | +|||
38 | +
- mirai::stop_mirai(mirai_obj) # this doesn't stop running - renv will be created even if session is closed+ #' |
|||
162 | +39 |
- }+ #' @param fs (`teal_slices`) object returned from [teal_slices()] function. |
||
163 | +40 |
- })+ #' @return `self`, invisibly. |
||
164 | +41 |
-
+ append_fs = function(fs) { |
||
165 | -1x | +42 | +5x |
- suppressWarnings({ # 'package:stats' may not be available when loading+ checkmate::assert_class(fs, "teal_slices") |
166 | -1x | +43 | +4x |
- process$invoke()+ self$append_text("Filter State", "header3") |
167 | -+ | |||
44 | +4x |
- })+ if (length(fs)) {+ |
+ ||
45 | +3x | +
+ self$append_content(TealSlicesBlock$new(fs)) |
||
168 | +46 |
-
+ } else { |
||
169 | +47 | 1x |
- logger::log_debug("Lockfile creation started based on { getwd() }.")+ self$append_text("No filters specified.") |
|
170 | +48 |
-
+ } |
||
171 | -1x | +49 | +4x |
- process+ invisible(self) |
172 | +50 |
- }+ }, |
||
173 | +51 |
-
+ #' @description Appends the encodings list to the `content` and `metadata` of this `TealReportCard`. |
||
174 | +52 |
- #' @rdname module_teal_lockfile+ #' |
||
175 | +53 |
- .renv_snapshot <- function(lockfile_path) {- |
- ||
176 | -1x | -
- out <- utils::capture.output(- |
- ||
177 | -1x | -
- res <- renv::snapshot(- |
- ||
178 | -1x | -
- lockfile = lockfile_path,+ #' @param encodings (`list`) list of encodings selections of the `teal` app. |
||
179 | -1x | +|||
54 | +
- prompt = FALSE,+ #' @return `self`, invisibly. |
|||
180 | -1x | +|||
55 | +
- force = TRUE,+ #' @examples |
|||
181 | -1x | +|||
56 | +
- type = renv::settings$snapshot.type() # see the section "Different ways of creating lockfile" above here+ #' card <- TealReportCard$new()$append_encodings(list(variable1 = "X")) |
|||
182 | +57 |
- )+ #' card$get_content()[[1]]$get_content() |
||
183 | +58 |
- )+ #' |
||
184 | +59 |
-
+ append_encodings = function(encodings) { |
||
185 | -1x | +60 | +4x |
- list(out = out, res = res)+ checkmate::assert_list(encodings) |
186 | -+ | |||
61 | +4x |
- }+ self$append_text("Selected Options", "header3") |
||
187 | -+ | |||
62 | +4x |
-
+ if (requireNamespace("yaml", quietly = TRUE)) { |
||
188 | -+ | |||
63 | +4x |
- #' @rdname module_teal_lockfile+ self$append_text(yaml::as.yaml(encodings, handlers = list( |
||
189 | -+ | |||
64 | +4x |
- .is_lockfile_deps_installed <- function() {+ POSIXct = function(x) format(x, "%Y-%m-%d"), |
||
190 | -1x | +65 | +4x |
- requireNamespace("mirai", quietly = TRUE) && requireNamespace("renv", quietly = TRUE)+ POSIXlt = function(x) format(x, "%Y-%m-%d"), |
191 | -+ | |||
66 | +4x |
- }+ Date = function(x) format(x, "%Y-%m-%d") |
||
192 | -+ | |||
67 | +4x |
-
+ )), "verbatim") |
||
193 | +68 |
- #' @rdname module_teal_lockfile+ } else { |
||
194 | -+ | |||
69 | +! |
- .is_disabled_lockfile_scenario <- function() {+ stop("yaml package is required to format the encodings list") |
||
195 | -81x | +|||
70 | +
- identical(Sys.getenv("CALLR_IS_RUNNING"), "true") || # inside callr process+ } |
|||
196 | -81x | +71 | +4x |
- identical(Sys.getenv("TESTTHAT"), "true") || # inside devtools::test+ self$append_metadata("Encodings", encodings) |
197 | -81x | +72 | +4x |
- !identical(Sys.getenv("QUARTO_PROJECT_ROOT"), "") || # inside Quarto process+ invisible(self) |
198 | +73 |
- (- |
- ||
199 | -81x | -
- ("CheckExEnv" %in% search()) || any(c("_R_CHECK_TIMINGS_", "_R_CHECK_LICENSE_") %in% names(Sys.getenv()))+ } |
||
200 | -81x | +|||
74 | +
- ) # inside R CMD CHECK+ ), |
|||
201 | +75 |
- }+ private = list( |
1 | +76 |
- #' An example `teal` module+ dispatch_block = function(block_class) { |
||
2 | -+ | |||
77 | +! |
- #'+ eval(str2lang(block_class)) |
||
3 | +78 |
- #' `r lifecycle::badge("experimental")`+ } |
||
4 | +79 |
- #'+ ) |
||
5 | +80 |
- #' @inheritParams teal_modules+ ) |
||
6 | +81 |
- #' @return A `teal` module which can be included in the `modules` argument to [init()].+ |
||
7 | +82 |
- #' @examples+ #' @title `TealSlicesBlock` |
||
8 | +83 |
- #' app <- init(+ #' @docType class |
||
9 | +84 |
- #' data = teal_data(IRIS = iris, MTCARS = mtcars),+ #' @description |
||
10 | +85 |
- #' modules = example_module()+ #' Specialized `TealSlicesBlock` block for managing filter panel content in reports. |
||
11 | +86 |
- #' )+ #' @keywords internal |
||
12 | +87 |
- #' if (interactive()) {+ TealSlicesBlock <- R6::R6Class( # nolint: object_name_linter. |
||
13 | +88 |
- #' shinyApp(app$ui, app$server)+ classname = "TealSlicesBlock", |
||
14 | +89 |
- #' }+ inherit = teal.reporter:::TextBlock, |
||
15 | +90 |
- #' @export+ public = list( |
||
16 | +91 |
- example_module <- function(label = "example teal module", datanames = "all", transformers = list()) {+ #' @description Returns a `TealSlicesBlock` object. |
||
17 | -38x | +|||
92 | +
- checkmate::assert_string(label)+ #' |
|||
18 | -38x | +|||
93 | +
- ans <- module(+ #' @details Returns a `TealSlicesBlock` object with no content and no parameters. |
|||
19 | -38x | +|||
94 | +
- label,+ #' |
|||
20 | -38x | +|||
95 | +
- server = function(id, data) {+ #' @param content (`teal_slices`) object returned from [teal_slices()] function. |
|||
21 | -2x | +|||
96 | +
- checkmate::assert_class(isolate(data()), "teal_data")+ #' @param style (`character(1)`) string specifying style to apply. |
|||
22 | -2x | +|||
97 | +
- moduleServer(id, function(input, output, session) {+ #' |
|||
23 | -2x | +|||
98 | +
- datanames_rv <- reactive(ls(teal.code::get_env((req(data())))))+ #' @return Object of class `TealSlicesBlock`, invisibly. |
|||
24 | -2x | +|||
99 | +
- observeEvent(datanames_rv(), {+ #' |
|||
25 | -2x | +|||
100 | +
- selected <- input$dataname+ initialize = function(content = teal_slices(), style = "verbatim") { |
|||
26 | -2x | -
- if (identical(selected, "")) {- |
- ||
27 | -! | +101 | +9x |
- selected <- restoreInput(session$ns("dataname"), NULL)+ self$set_content(content) |
28 | -2x | +102 | +8x |
- } else if (isFALSE(selected %in% datanames_rv())) {+ self$set_style(style) |
29 | -! | +|||
103 | +8x |
- selected <- datanames_rv()[1]+ invisible(self) |
||
30 | +104 |
- }- |
- ||
31 | -2x | -
- updateSelectInput(- |
- ||
32 | -2x | -
- session = session,+ }, |
||
33 | -2x | +|||
105 | +
- inputId = "dataname",+ |
|||
34 | -2x | +|||
106 | +
- choices = datanames_rv(),+ #' @description Sets content of this `TealSlicesBlock`. |
|||
35 | -2x | +|||
107 | +
- selected = selected+ #' Sets content as `YAML` text which represents a list generated from `teal_slices`. |
|||
36 | +108 |
- )+ #' The list displays limited number of fields from `teal_slice` objects, but this list is |
||
37 | +109 |
- })+ #' sufficient to conclude which filters were applied. |
||
38 | +110 |
-
+ #' When `selected` field in `teal_slice` object is a range, then it is displayed as a "min" |
||
39 | -2x | +|||
111 | +
- output$text <- renderPrint({+ #' |
|||
40 | -2x | +|||
112 | +
- req(input$dataname)+ #' |
|||
41 | -! | +|||
113 | +
- data()[[input$dataname]]+ #' @param content (`teal_slices`) object returned from [teal_slices()] function. |
|||
42 | +114 |
- })+ #' @return `self`, invisibly. |
||
43 | +115 |
-
+ set_content = function(content) { |
||
44 | -2x | +116 | +9x |
- teal.widgets::verbatim_popup_srv(+ checkmate::assert_class(content, "teal_slices") |
45 | -2x | +117 | +8x |
- id = "rcode",+ if (length(content) != 0) { |
46 | -2x | +118 | +6x |
- verbatim_content = reactive(teal.code::get_code(data())),+ states_list <- lapply(content, function(x) { |
47 | -2x | +119 | +6x |
- title = "Example Code"+ x_list <- shiny::isolate(as.list(x)) |
48 | -+ | |||
120 | +6x |
- )+ if ( |
||
49 | -+ | |||
121 | +6x |
- })+ inherits(x_list$choices, c("integer", "numeric", "Date", "POSIXct", "POSIXlt")) && |
||
50 | -+ | |||
122 | +6x |
- },+ length(x_list$choices) == 2 && |
||
51 | -38x | +123 | +6x |
- ui = function(id) {+ length(x_list$selected) == 2 |
52 | -! | +|||
124 | +
- ns <- NS(id)+ ) { |
|||
53 | +125 | ! |
- teal.widgets::standard_layout(+ x_list$range <- paste(x_list$selected, collapse = " - ") |
|
54 | +126 | ! |
- output = verbatimTextOutput(ns("text")),+ x_list["selected"] <- NULL |
|
55 | -! | +|||
127 | +
- encoding = tags$div(+ } |
|||
56 | -! | +|||
128 | +6x |
- selectInput(ns("dataname"), "Choose a dataset", choices = NULL),+ if (!is.null(x_list$arg)) { |
||
57 | +129 | ! |
- teal.widgets::verbatim_popup_ui(ns("rcode"), "Show R code")- |
- |
58 | -- |
- )+ x_list$arg <- if (x_list$arg == "subset") "Genes" else "Samples" |
||
59 | +130 |
- )+ } |
||
60 | +131 |
- },+ |
||
61 | -38x | +132 | +6x |
- datanames = datanames,+ x_list <- x_list[ |
62 | -38x | +133 | +6x |
- transformers = transformers+ c("dataname", "varname", "experiment", "arg", "expr", "selected", "range", "keep_na", "keep_inf") |
63 | +134 |
- )+ ] |
||
64 | -38x | +135 | +6x |
- attr(ans, "teal_bookmarkable") <- TRUE+ names(x_list) <- c( |
65 | -38x | +136 | +6x |
- ans+ "Dataset name", "Variable name", "Experiment", "Filtering by", "Applied expression", |
66 | -+ | |||
137 | +6x |
- }+ "Selected Values", "Selected range", "Include NA values", "Include Inf values" |
1 | +138 |
- #' Create a `teal` module for previewing a report+ ) |
||
2 | +139 |
- #'+ |
||
3 | -+ | |||
140 | +6x |
- #' @description `r lifecycle::badge("experimental")`+ Filter(Negate(is.null), x_list) |
||
4 | +141 |
- #'+ }) |
||
5 | +142 |
- #' This function wraps [teal.reporter::reporter_previewer_ui()] and+ |
||
6 | -+ | |||
143 | +6x |
- #' [teal.reporter::reporter_previewer_srv()] into a `teal_module` to be+ if (requireNamespace("yaml", quietly = TRUE)) {+ |
+ ||
144 | +6x | +
+ super$set_content(yaml::as.yaml(states_list)) |
||
7 | +145 |
- #' used in `teal` applications.+ } else {+ |
+ ||
146 | +! | +
+ stop("yaml package is required to format the filter state list") |
||
8 | +147 |
- #'+ } |
||
9 | +148 |
- #' If you are creating a `teal` application using [init()] then this+ }+ |
+ ||
149 | +8x | +
+ private$teal_slices <- content+ |
+ ||
150 | +8x | +
+ invisible(self) |
||
10 | +151 |
- #' module will be added to your application automatically if any of your `teal_modules`+ }, |
||
11 | +152 |
- #' support report generation.+ #' @description Create the `TealSlicesBlock` from a list. |
||
12 | +153 |
- #'+ #' |
||
13 | +154 |
- #' @inheritParams teal_modules+ #' @param x (`named list`) with two fields `text` and `style`. |
||
14 | +155 |
- #' @param server_args (named `list`)+ #' Use the `get_available_styles` method to get all possible styles. |
||
15 | +156 |
- #' Arguments passed to [teal.reporter::reporter_previewer_srv()].+ #' |
||
16 | +157 |
- #'+ #' @return `self`, invisibly. |
||
17 | +158 |
- #' @return+ #' @examples |
||
18 | +159 |
- #' `teal_module` (extended with `teal_module_previewer` class) containing the `teal.reporter` previewer functionality.+ #' TealSlicesBlock <- getFromNamespace("TealSlicesBlock", "teal") |
||
19 | +160 |
- #'+ #' block <- TealSlicesBlock$new() |
||
20 | +161 |
- #' @export+ #' block$from_list(list(text = "sth", style = "default")) |
||
21 | +162 |
- #'+ #' |
||
22 | +163 |
- reporter_previewer_module <- function(label = "Report previewer", server_args = list()) {+ from_list = function(x) { |
||
23 | -7x | +164 | +1x |
- checkmate::assert_string(label)+ checkmate::assert_list(x) |
24 | -5x | +165 | +1x |
- checkmate::assert_list(server_args, names = "named")+ checkmate::assert_names(names(x), must.include = c("text", "style")) |
25 | -5x | +166 | +1x |
- checkmate::assert_true(all(names(server_args) %in% names(formals(teal.reporter::reporter_previewer_srv))))+ super$set_content(x$text) |
26 | -+ | |||
167 | +1x |
-
+ super$set_style(x$style) |
||
27 | -3x | +168 | +1x |
- message("Initializing reporter_previewer_module")+ invisible(self) |
28 | +169 |
-
+ }, |
||
29 | -3x | +|||
170 | +
- srv <- function(id, reporter, ...) {+ #' @description Convert the `TealSlicesBlock` to a list. |
|||
30 | -! | +|||
171 | +
- teal.reporter::reporter_previewer_srv(id, reporter, ...)+ #' |
|||
31 | +172 |
- }+ #' @return `named list` with a text and style. |
||
32 | +173 |
-
+ #' @examples |
||
33 | -3x | +|||
174 | +
- ui <- function(id, ...) {+ #' TealSlicesBlock <- getFromNamespace("TealSlicesBlock", "teal") |
|||
34 | -! | +|||
175 | +
- teal.reporter::reporter_previewer_ui(id, ...)+ #' block <- TealSlicesBlock$new() |
|||
35 | +176 |
- }+ #' block$to_list() |
||
36 | +177 |
-
+ #'+ |
+ ||
178 | ++ |
+ to_list = function() { |
||
37 | -3x | +179 | +2x |
- module <- module(+ content <- self$get_content() |
38 | -3x | +180 | +2x |
- label = "temporary label",+ list( |
39 | -3x | +181 | +2x |
- server = srv, ui = ui,+ text = if (length(content)) content else "", |
40 | -3x | +182 | +2x |
- server_args = server_args, ui_args = list(), datanames = NULL+ style = self$get_style() |
41 | +183 |
- )+ ) |
||
42 | +184 |
- # Module is created with a placeholder label and the label is changed later.+ } |
||
43 | +185 |
- # This is to prevent another module being labeled "Report previewer".+ ), |
||
44 | -3x | +|||
186 | +
- class(module) <- c(class(module), "teal_module_previewer")+ private = list( |
|||
45 | -3x | +|||
187 | +
- module$label <- label+ style = "verbatim", |
|||
46 | -3x | +|||
188 | +
- attr(module, "teal_bookmarkable") <- TRUE+ teal_slices = NULL # teal_slices |
|||
47 | -3x | +|||
189 | +
- module+ ) |
|||
48 | +190 |
- }+ ) |
1 |
- #' Data Module for teal+ #' App state management. |
||
3 |
- #' This module manages the `data` argument for `srv_teal`. The `teal` framework uses [teal_data()],+ #' @description |
||
4 |
- #' which can be provided in various ways:+ #' `r lifecycle::badge("experimental")` |
||
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.+ #' Capture and restore the global (app) input state. |
||
9 |
- #' ## Reactive `teal_data`:+ #' This module introduces bookmarks into `teal` apps: the `shiny` bookmarking mechanism becomes enabled |
||
10 |
- #'+ #' and server-side bookmarks can be created. |
||
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`:+ #' The bookmark manager presents a button with the bookmark icon and is placed in the tab-bar. |
||
13 |
- #' 1. Using a `reactive` object provided from outside the `teal` application. In this scenario,+ #' When clicked, the button creates a bookmark and opens a modal which displays the bookmark URL. |
||
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+ #' `teal` does not guarantee that all modules (`teal_module` objects) are bookmarkable. |
||
16 |
- #' be resubmitted by the user as needed.+ #' 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 |
- #' Since the server of [teal_data_module()] must return a `reactive` `teal_data` object, both+ #' In order to communicate that a external module is bookmarkable, the module developer |
||
19 |
- #' methods (1 and 2) produce the same reactive behavior within a `teal` application. The distinction+ #' should set the `teal_bookmarkable` attribute to `TRUE`. |
||
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.+ #' @section Server logic: |
||
22 |
- #'+ #' A bookmark is a URL that contains the app address with a `/?_state_id_=<bookmark_dir>` suffix. |
||
23 |
- #' For more details, see [`module_teal_data`].+ #' `<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 |
- #' @inheritParams init+ #' |
||
26 |
- #'+ #' @section Note: |
||
27 |
- #' @param data (`teal_data`, `teal_data_module`, or `reactive` returning `teal_data`)+ #' To enable bookmarking use either: |
||
28 |
- #' The data which application will depend on.+ #' - `shiny` app by using `shinyApp(..., enableBookmarking = "server")` (not supported in `shinytest2`) |
||
29 |
- #'+ #' - set `options(shiny.bookmarkStore = "server")` before running the app |
||
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.+ #' @inheritParams init |
||
34 |
- #' @rdname module_init_data+ #' @return Invisible `NULL`. |
||
35 |
- #' @name module_init_data+ #' |
||
36 |
- #' @keywords internal+ #' @aliases bookmark bookmark_manager bookmark_manager_module |
||
37 |
- NULL+ #' |
||
38 |
-
+ #' @name module_bookmark_manager |
||
39 |
- #' @rdname module_init_data+ #' @rdname module_bookmark_manager |
||
40 |
- ui_init_data <- function(id) {+ #' |
||
41 | -9x | +
- ns <- shiny::NS(id)+ #' @keywords internal |
|
42 | -9x | +
- shiny::div(+ #' |
|
43 | -9x | +
- id = ns("content"),+ NULL |
|
44 | -9x | +
- style = "display: inline-block; width: 100%;",+ |
|
45 | -9x | +
- uiOutput(ns("data"))+ #' @rdname module_bookmark_manager |
|
46 |
- )+ ui_bookmark_panel <- function(id, modules) { |
||
47 | -+ | ! |
- }+ ns <- NS(id) |
49 | -+ | ! |
- #' @rdname module_init_data+ bookmark_option <- get_bookmarking_option() |
50 | -+ | ! |
- srv_init_data <- function(id, data) {+ is_unbookmarkable <- need_bookmarking(modules) |
51 | -83x | +! |
- checkmate::assert_character(id, max.len = 1, any.missing = FALSE)+ shinyOptions(bookmarkStore = bookmark_option) |
52 | -83x | +
- checkmate::assert_multi_class(data, c("teal_data", "teal_data_module", "reactive"))+ |
|
53 |
-
+ # Render bookmark warnings count |
||
54 | -83x | +! |
- moduleServer(id, function(input, output, session) {+ if (!all(is_unbookmarkable) && identical(bookmark_option, "server")) { |
55 | -83x | +! |
- logger::log_debug("srv_data initializing.")+ tags$button( |
56 | -+ | ! |
- # data_rv contains teal_data object+ id = ns("do_bookmark"), |
57 | -+ | ! |
- # either passed to teal::init or returned from teal_data_module+ class = "btn action-button wunder_bar_button bookmark_manager_button", |
58 | -83x | +! |
- data_out <- if (inherits(data, "teal_data_module")) {+ title = "Add bookmark", |
59 | -10x | +! |
- output$data <- renderUI(data$ui(id = session$ns("teal_data_module")))+ tags$span( |
60 | -10x | +! |
- data$server("teal_data_module")+ suppressMessages(icon("fas fa-bookmark")), |
61 | -83x | +! |
- } else if (inherits(data, "teal_data")) {+ if (any(is_unbookmarkable)) { |
62 | -43x | +! |
- reactiveVal(data)+ tags$span( |
63 | -83x | +! |
- } else if (test_reactive(data)) {+ sum(is_unbookmarkable), |
64 | -30x | +! |
- data+ class = "badge-warning badge-count text-white bg-danger" |
65 |
- }+ ) |
||
66 |
-
+ } |
||
67 | -82x | +
- data_handled <- reactive({+ ) |
|
68 | -75x | +
- tryCatch(data_out(), error = function(e) e)+ ) |
|
69 |
- })+ } |
||
70 |
-
+ } |
||
71 |
- # We want to exclude teal_data_module elements from bookmarking as they might have some secrets+ |
||
72 | -82x | +
- observeEvent(data_handled(), {+ #' @rdname module_bookmark_manager |
|
73 | -75x | +
- if (inherits(data_handled(), "teal_data")) {+ srv_bookmark_panel <- function(id, modules) { |
|
74 | -70x | +82x |
- app_session <- .subset2(shiny::getDefaultReactiveDomain(), "parent")+ checkmate::assert_character(id) |
75 | -70x | +82x |
- setBookmarkExclude(+ checkmate::assert_class(modules, "teal_modules") |
76 | -70x | +82x |
- session$ns(+ moduleServer(id, function(input, output, session) { |
77 | -70x | +82x |
- grep(+ logger::log_debug("bookmark_manager_srv initializing") |
78 | -70x | +82x |
- pattern = "teal_data_module-",+ ns <- session$ns |
79 | -70x | +82x |
- x = names(reactiveValuesToList(input)),+ bookmark_option <- get_bookmarking_option() |
80 | -70x | +82x |
- value = TRUE+ is_unbookmarkable <- need_bookmarking(modules) |
81 |
- )+ |
||
82 |
- ),+ # Set up bookmarking callbacks ---- |
||
83 | -70x | +
- session = app_session+ # Register bookmark exclusions: do_bookmark button to avoid re-bookmarking |
|
84 | -+ | 82x |
- )+ setBookmarkExclude(c("do_bookmark")) |
85 |
- }+ # This bookmark can only be used on the app session. |
||
86 | -+ | 82x |
- })+ app_session <- .subset2(session, "parent") |
87 | -+ | 82x |
-
+ app_session$onBookmarked(function(url) { |
88 | -82x | +! |
- data_handled+ 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 | -+ | ! |
- #' Adds signature protection to the `datanames` in the data+ bookmark_option, |
93 | -+ | ! |
- #' @param data (`teal_data`)+ "Only server-side bookmarking is supported.", |
94 | -+ | ! |
- #' @return `teal_data` with additional code that has signature of the `datanames`+ "Please contact your app developer." |
95 |
- #' @keywords internal+ ) |
||
96 | -+ | ! |
- .add_signature_to_data <- function(data) {+ tags$div( |
97 | -70x | +! |
- hashes <- .get_hashes_code(data)+ tags$p(msg, class = "text-warning") |
98 | -70x | +
- tdata <- do.call(+ ) |
|
99 | -70x | +
- teal.data::teal_data,+ } else { |
|
100 | -70x | +! |
- c(+ tags$div( |
101 | -70x | +! |
- list(code = trimws(c(teal.code::get_code(data), hashes), which = "right")),+ tags$span( |
102 | -70x | +! |
- list(join_keys = teal.data::join_keys(data)),+ tags$pre(url) |
103 | -70x | +
- sapply(+ ), |
|
104 | -70x | +! |
- ls(teal.code::get_env(data)),+ if (any(is_unbookmarkable)) { |
105 | -70x | +! |
- teal.code::get_var,+ bkmb_summary <- rapply2( |
106 | -70x | +! |
- object = data,+ modules_bookmarkable(modules), |
107 | -70x | +! |
- simplify = FALSE+ function(x) { |
108 | -+ | ! |
- )+ if (isTRUE(x)) { |
109 | -+ | ! |
- )+ "\u2705" # check mark |
110 | -+ | ! |
- )+ } else if (isFALSE(x)) { |
111 | -+ | ! |
-
+ "\u274C" # cross mark |
112 | -70x | +
- tdata@verified <- data@verified+ } else { |
|
113 | -70x | +! |
- tdata+ "\u2753" # question mark |
114 |
- }+ } |
||
115 |
-
+ } |
||
116 |
- #' Get code that tests the integrity of the reproducible data+ ) |
||
117 | -+ | ! |
- #'+ tags$div( |
118 | -+ | ! |
- #' @param data (`teal_data`) object holding the data+ tags$p( |
119 | -+ | ! |
- #' @param datanames (`character`) names of `datasets`+ icon("fas fa-exclamation-triangle"), |
120 | -+ | ! |
- #'+ "Some modules will not be restored when using this bookmark.", |
121 | -+ | ! |
- #' @return A character vector with the code lines.+ tags$br(), |
122 | -+ | ! |
- #' @keywords internal+ "Check the list below to see which modules are not bookmarkable.", |
123 | -+ | ! |
- #'+ class = "text-warning" |
124 |
- .get_hashes_code <- function(data, datanames = ls(teal.code::get_env(data))) {+ ), |
||
125 | -70x | +! |
- vapply(+ tags$pre(yaml::as.yaml(bkmb_summary)) |
126 | -70x | +
- datanames,+ ) |
|
127 | -70x | +
- function(dataname, datasets) {+ } |
|
128 | -125x | +
- x <- data[[dataname]]+ ) |
|
129 |
-
+ } |
||
130 | -125x | +
- code <- if (is.function(x) && !is.primitive(x)) {+ |
|
131 | -6x | +! |
- x <- deparse1(x)+ showModal( |
132 | -6x | +! |
- bquote(rlang::hash(deparse1(.(as.name(dataname)))))+ modalDialog( |
133 | -+ | ! |
- } else {+ id = ns("bookmark_modal"), |
134 | -119x | +! |
- bquote(rlang::hash(.(as.name(dataname))))+ title = "Bookmarked teal app url", |
135 | -+ | ! |
- }+ modal_content, |
136 | -125x | +! |
- sprintf(+ easyClose = TRUE |
137 | -125x | +
- "stopifnot(%s == %s) # @linksto %s",+ ) |
|
138 | -125x | +
- deparse1(code),+ ) |
|
139 | -125x | +
- deparse1(rlang::hash(x)),+ }) |
|
140 | -125x | +
- dataname+ |
|
141 |
- )+ # manually trigger bookmarking because of the problems reported on windows with bookmarkButton in teal |
||
142 | -+ | 82x |
- },+ observeEvent(input$do_bookmark, { |
143 | -70x | +! |
- character(1L),+ logger::log_debug("bookmark_manager_srv@1 do_bookmark module clicked.") |
144 | -70x | +! |
- USE.NAMES = TRUE+ session$doBookmark() |
145 |
- )+ }) |
||
146 |
- }+ |
1 | -+ | ||
147 | +82x |
- #' Calls all `modules`+ invisible(NULL) |
|
2 | +148 |
- #'+ }) |
|
3 | +149 |
- #' On the UI side each `teal_modules` is translated to a `tabsetPanel` and each `teal_module` is a+ } |
|
4 | +150 |
- #' `tabPanel`. Both, UI and server are called recursively so that each tab is a separate module and+ |
|
5 | +151 |
- #' reflect nested structure of `modules` argument.+ |
|
6 | +152 |
- #'+ #' @rdname module_bookmark_manager |
|
7 | +153 |
- #' @name module_teal_module+ get_bookmarking_option <- function() { |
|
8 | -+ | ||
154 | +82x |
- #'+ bookmark_option <- getShinyOption("bookmarkStore") |
|
9 | -+ | ||
155 | +82x |
- #' @inheritParams module_teal+ if (is.null(bookmark_option) && identical(getOption("shiny.bookmarkStore"), "server")) { |
|
10 | -+ | ||
156 | +! |
- #'+ bookmark_option <- getOption("shiny.bookmarkStore") |
|
11 | +157 |
- #' @param data_rv (`reactive` returning `teal_data`)+ } |
|
12 | -+ | ||
158 | +82x |
- #'+ bookmark_option |
|
13 | +159 |
- #' @param slices_global (`reactiveVal` returning `modules_teal_slices`)+ } |
|
14 | +160 |
- #' see [`module_filter_manager`]+ |
|
15 | +161 |
- #'+ #' @rdname module_bookmark_manager |
|
16 | +162 |
- #' @param depth (`integer(1)`)+ need_bookmarking <- function(modules) { |
|
17 | -+ | ||
163 | +82x |
- #' number which helps to determine depth of the modules nesting.+ unlist(rapply2( |
|
18 | -+ | ||
164 | +82x |
- #'+ modules_bookmarkable(modules), |
|
19 | -+ | ||
165 | +82x |
- #' @param datasets (`reactive` returning `FilteredData` or `NULL`)+ Negate(isTRUE) |
|
20 | +166 |
- #' When `datasets` is passed from the parent module (`srv_teal`) then `dataset` is a singleton+ )) |
|
21 | +167 |
- #' which implies in filter-panel to be "global". When `NULL` then filter-panel is "module-specific".+ } |
|
22 | +168 |
- #'+ |
|
23 | +169 |
- #' @param data_load_status (`reactive` returning `character`)+ |
|
24 | +170 |
- #' Determines action dependent on a data loading status:+ # utilities ---- |
|
25 | +171 |
- #' - `"ok"` when `teal_data` is returned from the data loading.+ |
|
26 | +172 |
- #' - `"teal_data_module failed"` when [teal_data_module()] didn't return `teal_data`. Disables tabs buttons.+ #' Restore value from bookmark. |
|
27 | +173 |
- #' - `"external failed"` when a `reactive` passed to `srv_teal(data)` didn't return `teal_data`. Hides the whole tab+ #' |
|
28 | +174 |
- #' panel.+ #' Get value from bookmark or return default. |
|
29 | +175 |
#' |
|
30 | +176 |
- #' @return+ #' Bookmarks can store not only inputs but also arbitrary values. |
|
31 | +177 |
- #' output of currently active module.+ #' These values are stored by `onBookmark` callbacks and restored by `onBookmarked` callbacks, |
|
32 | +178 |
- #' - `srv_teal_module.teal_module` returns `reactiveVal` containing output of the called module.+ #' and they are placed in the `values` environment in the `session$restoreContext` field. |
|
33 | +179 |
- #' - `srv_teal_module.teal_modules` returns output of module selected by `input$active_tab`.+ #' Using `teal_data_module` makes it impossible to run the callbacks |
|
34 | +180 |
- #'+ #' because the app becomes ready before modules execute and callbacks are registered. |
|
35 | +181 |
- #' @keywords internal+ #' In those cases the stored values can still be recovered from the `session` object directly. |
|
36 | +182 |
- NULL+ #' |
|
37 | +183 |
-
+ #' Note that variable names in the `values` environment are prefixed with module name space names, |
|
38 | +184 |
- #' @rdname module_teal_module+ #' therefore, when using this function in modules, `value` must be run through the name space function. |
|
39 | +185 |
- ui_teal_module <- function(id, modules, depth = 0L) {- |
- |
40 | -! | -
- checkmate::assert_multi_class(modules, c("teal_modules", "teal_module", "shiny.tag"))- |
- |
41 | -! | -
- checkmate::assert_count(depth)+ #' |
|
42 | -! | +||
186 | +
- UseMethod("ui_teal_module", modules)+ #' @param value (`character(1)`) name of value to restore |
||
43 | +187 |
- }+ #' @param default fallback value |
|
44 | +188 |
-
+ #' |
|
45 | +189 |
- #' @rdname module_teal_module+ #' @return |
|
46 | +190 |
- #' @export+ #' In an application restored from a server-side bookmark, |
|
47 | +191 |
- ui_teal_module.default <- function(id, modules, depth = 0L) {+ #' the variable specified by `value` from the `values` environment. |
|
48 | -! | +||
192 | +
- stop("Modules class not supported: ", paste(class(modules), collapse = " "))+ #' Otherwise `default`. |
||
49 | +193 |
- }+ #' |
|
50 | +194 |
-
+ #' @keywords internal |
|
51 | +195 |
- #' @rdname module_teal_module+ #' |
|
52 | +196 |
- #' @export+ restoreValue <- function(value, default) { # nolint: object_name. |
|
53 | -+ | ||
197 | +164x |
- ui_teal_module.teal_modules <- function(id, modules, depth = 0L) {+ checkmate::assert_character("value") |
|
54 | -! | +||
198 | +164x |
- ns <- NS(id)+ session_default <- shiny::getDefaultReactiveDomain() |
|
55 | -! | +||
199 | +164x |
- tags$div(+ session_parent <- .subset2(session_default, "parent") |
|
56 | -! | +||
200 | +164x |
- id = ns("wrapper"),+ session <- if (is.null(session_parent)) session_default else session_parent |
|
57 | -! | +||
201 | +
- do.call(+ |
||
58 | -! | +||
202 | +164x |
- tabsetPanel,+ if (isTRUE(session$restoreContext$active) && exists(value, session$restoreContext$values, inherits = FALSE)) { |
|
59 | +203 | ! |
- c(+ session$restoreContext$values[[value]] |
60 | +204 |
- # by giving an id, we can reactively respond to tab changes+ } else { |
|
61 | -! | +||
205 | +164x |
- list(+ default |
|
62 | -! | +||
206 | +
- id = ns("active_tab"),+ } |
||
63 | -! | +||
207 | +
- type = if (modules$label == "root") "pills" else "tabs"+ } |
||
64 | +208 |
- ),+ |
|
65 | -! | +||
209 | +
- lapply(+ #' Compare bookmarks. |
||
66 | -! | +||
210 | +
- names(modules$children),+ #' |
||
67 | -! | +||
211 | +
- function(module_id) {+ #' Test if two bookmarks store identical state. |
||
68 | -! | +||
212 | +
- module_label <- modules$children[[module_id]]$label+ #' |
||
69 | -! | +||
213 | +
- if (is.null(module_label)) {+ #' `input` environments are compared one variable at a time and if not identical, |
||
70 | -! | +||
214 | +
- module_label <- icon("fas fa-database")+ #' values in both bookmarks are reported. States of `datatable`s are stripped |
||
71 | +215 |
- }+ #' of the `time` element before comparing because the time stamp is always different. |
|
72 | -! | +||
216 | +
- tabPanel(+ #' The contents themselves are not printed as they are large and the contents are not informative. |
||
73 | -! | +||
217 | +
- title = module_label,+ #' Elements present in one bookmark and absent in the other are also reported. |
||
74 | -! | +||
218 | +
- value = module_id, # when clicked this tab value changes input$<tabset panel id>+ #' Differences are printed as messages. |
||
75 | -! | +||
219 | +
- ui_teal_module(+ #' |
||
76 | -! | +||
220 | +
- id = ns(module_id),+ #' `values` environments are compared with `all.equal`. |
||
77 | -! | +||
221 | +
- modules = modules$children[[module_id]],+ #' |
||
78 | -! | +||
222 | +
- depth = depth + 1L+ #' @section How to use: |
||
79 | +223 |
- )+ #' Open an application, change relevant inputs (typically, all of them), and create a bookmark. |
|
80 | +224 |
- )+ #' Then open that bookmark and immediately create a bookmark of that. |
|
81 | +225 |
- }+ #' If restoring bookmarks occurred properly, the two bookmarks should store the same state. |
|
82 | +226 |
- )+ #' |
|
83 | +227 |
- )+ #' |
|
84 | +228 |
- )+ #' @param book1,book2 bookmark directories stored in `shiny_bookmarks/`; |
|
85 | +229 |
- )+ #' default to the two most recently modified directories |
|
86 | +230 |
- }+ #' |
|
87 | +231 |
-
+ #' @return |
|
88 | +232 |
- #' @rdname module_teal_module+ #' Invisible `NULL` if bookmarks are identical or if there are no bookmarks to test. |
|
89 | +233 |
- #' @export+ #' `FALSE` if inconsistencies are detected. |
|
90 | +234 |
- ui_teal_module.teal_module <- function(id, modules, depth = 0L) {+ #' |
|
91 | -! | +||
235 | +
- ns <- NS(id)+ #' @keywords internal |
||
92 | -! | +||
236 | +
- args <- c(list(id = ns("module")), modules$ui_args)+ #' |
||
93 | +237 |
-
+ bookmarks_identical <- function(book1, book2) { |
|
94 | +238 | ! |
- ui_teal <- tagList(+ if (!dir.exists("shiny_bookmarks")) { |
95 | +239 | ! |
- div(+ message("no bookmark directory") |
96 | +240 | ! |
- id = ns("validate_datanames"),+ return(invisible(NULL)) |
97 | -! | +||
241 | +
- ui_validate_reactive_teal_data(ns("validate_datanames"))+ } |
||
98 | +242 |
- ),+ |
|
99 | +243 | ! |
- shinyjs::hidden(+ ans <- TRUE |
100 | -! | +||
244 | +
- tags$div(+ |
||
101 | +245 | ! |
- id = ns("transformer_failure_info"),+ if (missing(book1) && missing(book2)) { |
102 | +246 | ! |
- class = "teal_validated",+ dirs <- list.dirs("shiny_bookmarks", recursive = FALSE) |
103 | +247 | ! |
- div(+ bookmarks_sorted <- basename(rev(dirs[order(file.mtime(dirs))])) |
104 | +248 | ! |
- class = "teal-output-warning",+ if (length(bookmarks_sorted) < 2L) { |
105 | +249 | ! |
- "One of transformers failed. Please fix and continue."+ message("no bookmarks to compare") |
106 | -+ | ||
250 | +! |
- )+ return(invisible(NULL)) |
|
107 | +251 |
- )+ } |
|
108 | -+ | ||
252 | +! |
- ),+ book1 <- bookmarks_sorted[2L] |
|
109 | +253 | ! |
- tags$div(+ book2 <- bookmarks_sorted[1L]+ |
+
254 | ++ |
+ } else { |
|
110 | +255 | ! |
- id = ns("teal_module_ui"),+ if (!dir.exists(file.path("shiny_bookmarks", book1))) stop(book1, " not found") |
111 | +256 | ! |
- do.call(modules$ui, args)+ if (!dir.exists(file.path("shiny_bookmarks", book2))) stop(book2, " not found") |
112 | +257 |
- )+ } |
|
113 | +258 |
- )+ + |
+ |
259 | +! | +
+ book1_input <- readRDS(file.path("shiny_bookmarks", book1, "input.rds"))+ |
+ |
260 | +! | +
+ book2_input <- readRDS(file.path("shiny_bookmarks", book2, "input.rds")) |
|
114 | +261 | ||
115 | +262 | ! |
- div(+ elements_common <- intersect(names(book1_input), names(book2_input)) |
116 | +263 | ! |
- id = id,+ dt_states <- grepl("_state$", elements_common) |
117 | +264 | ! |
- class = "teal_module",+ if (any(dt_states)) { |
118 | +265 | ! |
- uiOutput(ns("data_reactive"), inline = TRUE),+ for (el in elements_common[dt_states]) { |
119 | +266 | ! |
- tagList(+ book1_input[[el]][["time"]] <- NULL |
120 | +267 | ! |
- if (depth >= 2L) tags$div(style = "mt-6"),+ book2_input[[el]][["time"]] <- NULL+ |
+
268 | ++ |
+ }+ |
+ |
269 | ++ |
+ }+ |
+ |
270 | ++ | + | |
121 | +271 | ! |
- if (!is.null(modules$datanames)) {+ identicals <- mapply(identical, book1_input[elements_common], book2_input[elements_common]) |
122 | +272 | ! |
- fluidRow(+ non_identicals <- names(identicals[!identicals]) |
123 | +273 | ! |
- column(width = 9, ui_teal, class = "teal_primary_col"),+ compares <- sprintf("$ %s:\t%s --- %s", non_identicals, book1_input[non_identicals], book2_input[non_identicals]) |
124 | +274 | ! |
- column(+ if (length(compares) != 0L) { |
125 | +275 | ! |
- width = 3,+ message("common elements not identical: \n", paste(compares, collapse = "\n")) |
126 | +276 | ! |
- ui_data_summary(ns("data_summary")),+ ans <- FALSE+ |
+
277 | ++ |
+ }+ |
+ |
278 | ++ | + | |
127 | +279 | ! |
- ui_filter_data(ns("filter_panel")),+ elements_boook1 <- setdiff(names(book1_input), names(book2_input)) |
128 | +280 | ! |
- ui_transform_data(ns("data_transform"), transformers = modules$transformers, class = "well"),+ if (length(elements_boook1) != 0L) { |
129 | +281 | ! |
- class = "teal_secondary_col"+ dt_states <- grepl("_state$", elements_boook1) |
130 | -+ | ||
282 | +! | +
+ if (any(dt_states)) {+ |
+ |
283 | +! | +
+ for (el in elements_boook1[dt_states]) {+ |
+ |
284 | +! |
- )+ if (is.list(book1_input[[el]])) book1_input[[el]] <- "--- data table state ---" |
|
131 | +285 |
- )+ } |
|
132 | +286 |
- } else {+ } |
|
133 | +287 | ! |
- div(+ excess1 <- sprintf("$ %s:\t%s", elements_boook1, book1_input[elements_boook1]) |
134 | +288 | ! |
- div(+ message("elements only in book1: \n", paste(excess1, collapse = "\n")) |
135 | +289 | ! |
- class = "teal_validated",+ ans <- FALSE |
136 | -! | +||
290 | +
- uiOutput(ns("data_input_error"))+ } |
||
137 | +291 |
- ),+ |
|
138 | +292 | ! |
- ui_teal+ elements_boook2 <- setdiff(names(book2_input), names(book1_input)) |
139 | -+ | ||
293 | +! |
- )+ if (length(elements_boook2) != 0L) { |
|
140 | -+ | ||
294 | +! |
- }+ dt_states <- grepl("_state$", elements_boook1) |
|
141 | -+ | ||
295 | +! |
- )+ if (any(dt_states)) { |
|
142 | -+ | ||
296 | +! |
- )+ for (el in elements_boook1[dt_states]) { |
|
143 | -+ | ||
297 | +! |
- }+ if (is.list(book2_input[[el]])) book2_input[[el]] <- "--- data table state ---" |
|
144 | +298 |
-
+ } |
|
145 | +299 |
- #' @rdname module_teal_module+ } |
|
146 | -+ | ||
300 | +! |
- srv_teal_module <- function(id,+ excess2 <- sprintf("$ %s:\t%s", elements_boook2, book2_input[elements_boook2]) |
|
147 | -+ | ||
301 | +! |
- data_rv,+ message("elements only in book2: \n", paste(excess2, collapse = "\n")) |
|
148 | -+ | ||
302 | +! |
- modules,+ ans <- FALSE |
|
149 | +303 |
- datasets = NULL,+ } |
|
150 | +304 |
- slices_global,+ |
|
151 | -+ | ||
305 | +! |
- reporter = teal.reporter::Reporter$new(),+ book1_values <- readRDS(file.path("shiny_bookmarks", book1, "values.rds")) |
|
152 | -+ | ||
306 | +! |
- data_load_status = reactive("ok"),+ book2_values <- readRDS(file.path("shiny_bookmarks", book2, "values.rds")) |
|
153 | +307 |
- is_active = reactive(TRUE)) {+ |
|
154 | -189x | +||
308 | +! |
- checkmate::assert_string(id)+ if (!isTRUE(all.equal(book1_values, book2_values))) { |
|
155 | -189x | +||
309 | +! |
- assert_reactive(data_rv)+ message("different values detected") |
|
156 | -189x | +||
310 | +! |
- checkmate::assert_multi_class(modules, c("teal_modules", "teal_module"))+ message("choices for numeric filters MAY be different, see RangeFilterState$set_choices") |
|
157 | -189x | +||
311 | +! |
- assert_reactive(datasets, null.ok = TRUE)+ ans <- FALSE |
|
158 | -189x | +||
312 | +
- checkmate::assert_class(slices_global, ".slicesGlobal")+ } |
||
159 | -189x | +||
313 | +
- checkmate::assert_class(reporter, "Reporter")+ |
||
160 | -189x | +||
314 | +! |
- assert_reactive(data_load_status)+ if (ans) message("perfect!") |
|
161 | -189x | +||
315 | +! |
- UseMethod("srv_teal_module", modules)+ invisible(NULL) |
|
162 | +316 |
} |
|
163 | +317 | ||
164 | +318 |
- #' @rdname module_teal_module+ |
|
165 | +319 |
- #' @export+ # Replacement for [base::rapply] which doesn't handle NULL values - skips the evaluation |
|
166 | +320 |
- srv_teal_module.default <- function(id,+ # of the function and returns NULL for given element. |
|
167 | +321 |
- data_rv,+ rapply2 <- function(x, f) { |
|
168 | -+ | ||
322 | +189x |
- modules,+ if (inherits(x, "list")) { |
|
169 | -+ | ||
323 | +82x |
- datasets = NULL,+ lapply(x, rapply2, f = f) |
|
170 | +324 |
- slices_global,+ } else { |
|
171 | -+ | ||
325 | +107x |
- reporter = teal.reporter::Reporter$new(),+ f(x) |
|
172 | +326 |
- data_load_status = reactive("ok"),+ } |
|
173 | +327 |
- is_active = reactive(TRUE)) {+ } |
|
174 | -! | +
1 | +
- stop("Modules class not supported: ", paste(class(modules), collapse = " "))+ #' An example `teal` module |
|||
175 | +2 |
- }+ #' |
||
176 | +3 |
-
+ #' `r lifecycle::badge("experimental")` |
||
177 | +4 |
- #' @rdname module_teal_module+ #' |
||
178 | +5 |
- #' @export+ #' @inheritParams teal_modules |
||
179 | +6 |
- srv_teal_module.teal_modules <- function(id,+ #' @return A `teal` module which can be included in the `modules` argument to [init()]. |
||
180 | +7 |
- data_rv,+ #' @examples |
||
181 | +8 |
- modules,+ #' app <- init( |
||
182 | +9 |
- datasets = NULL,+ #' data = teal_data(IRIS = iris, MTCARS = mtcars), |
||
183 | +10 |
- slices_global,+ #' modules = example_module() |
||
184 | +11 |
- reporter = teal.reporter::Reporter$new(),+ #' ) |
||
185 | +12 |
- data_load_status = reactive("ok"),+ #' if (interactive()) { |
||
186 | +13 |
- is_active = reactive(TRUE)) {+ #' shinyApp(app$ui, app$server) |
||
187 | -82x | +|||
14 | +
- moduleServer(id = id, module = function(input, output, session) {+ #' } |
|||
188 | -82x | +|||
15 | +
- logger::log_debug("srv_teal_module.teal_modules initializing the module { deparse1(modules$label) }.")+ #' @export |
|||
189 | +16 |
-
+ example_module <- function(label = "example teal module", datanames = "all", transformers = list()) { |
||
190 | -82x | +17 | +38x |
- observeEvent(data_load_status(), {+ checkmate::assert_string(label) |
191 | -75x | +18 | +38x |
- tabs_selector <- sprintf("#%s li a", session$ns("active_tab"))+ ans <- module( |
192 | -75x | +19 | +38x |
- if (identical(data_load_status(), "ok")) {+ label, |
193 | -70x | +20 | +38x |
- logger::log_debug("srv_teal_module@1 enabling modules tabs.")+ server = function(id, data) { |
194 | -70x | +21 | +2x |
- shinyjs::show("wrapper")+ checkmate::assert_class(isolate(data()), "teal_data") |
195 | -70x | +22 | +2x |
- shinyjs::enable(selector = tabs_selector)+ moduleServer(id, function(input, output, session) { |
196 | -5x | +23 | +2x |
- } else if (identical(data_load_status(), "teal_data_module failed")) {+ datanames_rv <- reactive(names(req(data()))) |
197 | -5x | +24 | +2x |
- logger::log_debug("srv_teal_module@1 disabling modules tabs.")+ observeEvent(datanames_rv(), { |
198 | -5x | -
- shinyjs::disable(selector = tabs_selector)- |
- ||
199 | -! | +25 | +2x |
- } else if (identical(data_load_status(), "external failed")) {+ selected <- input$dataname |
200 | -! | +|||
26 | +2x |
- logger::log_debug("srv_teal_module@1 hiding modules tabs.")+ if (identical(selected, "")) { |
||
201 | +27 | ! |
- shinyjs::hide("wrapper")+ selected <- restoreInput(session$ns("dataname"), NULL) |
|
202 | -+ | |||
28 | +2x |
- }+ } else if (isFALSE(selected %in% datanames_rv())) { |
||
203 | -+ | |||
29 | +! |
- })+ selected <- datanames_rv()[1] |
||
204 | +30 | - - | -||
205 | -82x | -
- modules_output <- sapply(- |
- ||
206 | -82x | -
- names(modules$children),- |
- ||
207 | -82x | -
- function(module_id) {- |
- ||
208 | -107x | -
- srv_teal_module(- |
- ||
209 | -107x | -
- id = module_id,- |
- ||
210 | -107x | -
- data_rv = data_rv,- |
- ||
211 | -107x | -
- modules = modules$children[[module_id]],- |
- ||
212 | -107x | -
- datasets = datasets,- |
- ||
213 | -107x | -
- slices_global = slices_global,+ } |
||
214 | -107x | +31 | +2x |
- reporter = reporter,+ updateSelectInput( |
215 | -107x | +32 | +2x |
- is_active = reactive(+ session = session, |
216 | -107x | +33 | +2x |
- is_active() &&+ inputId = "dataname", |
217 | -107x | +34 | +2x |
- input$active_tab == module_id &&+ choices = datanames_rv(), |
218 | -107x | +35 | +2x |
- identical(data_load_status(), "ok")+ selected = selected |
219 | +36 |
) |
||
220 | +37 |
- )+ }) |
||
221 | +38 |
- },+ |
||
222 | -82x | +39 | +2x |
- simplify = FALSE+ output$text <- renderPrint({+ |
+
40 | +2x | +
+ req(input$dataname)+ |
+ ||
41 | +! | +
+ data()[[input$dataname]] |
||
223 | +42 |
- )+ }) |
||
224 | +43 | |||
225 | -82x | +44 | +2x |
- modules_output+ teal.widgets::verbatim_popup_srv( |
226 | -+ | |||
45 | +2x |
- })+ id = "rcode", |
||
227 | -+ | |||
46 | +2x |
- }+ verbatim_content = reactive(teal.code::get_code(data())), |
||
228 | -+ | |||
47 | +2x |
-
+ title = "Example Code" |
||
229 | +48 |
- #' @rdname module_teal_module+ ) |
||
230 | +49 |
- #' @export+ }) |
||
231 | +50 |
- srv_teal_module.teal_module <- function(id,+ }, |
||
232 | -+ | |||
51 | +38x |
- data_rv,+ ui = function(id) { |
||
233 | -+ | |||
52 | +! |
- modules,+ ns <- NS(id) |
||
234 | -+ | |||
53 | +! |
- datasets = NULL,+ teal.widgets::standard_layout( |
||
235 | -+ | |||
54 | +! |
- slices_global,+ output = verbatimTextOutput(ns("text")),+ |
+ ||
55 | +! | +
+ encoding = tags$div(+ |
+ ||
56 | +! | +
+ selectInput(ns("dataname"), "Choose a dataset", choices = NULL),+ |
+ ||
57 | +! | +
+ teal.widgets::verbatim_popup_ui(ns("rcode"), "Show R code") |
||
236 | +58 |
- reporter = teal.reporter::Reporter$new(),+ ) |
||
237 | +59 |
- data_load_status = reactive("ok"),+ ) |
||
238 | +60 |
- is_active = reactive(TRUE)) {+ }, |
||
239 | -107x | +61 | +38x |
- logger::log_debug("srv_teal_module.teal_module initializing the module: { deparse1(modules$label) }.")+ datanames = datanames, |
240 | -107x | +62 | +38x |
- moduleServer(id = id, module = function(input, output, session) {+ transformers = transformers+ |
+
63 | ++ |
+ ) |
||
241 | -107x | +64 | +38x |
- module_out <- reactiveVal()+ attr(ans, "teal_bookmarkable") <- TRUE+ |
+
65 | +38x | +
+ ans |
||
242 | +66 |
-
+ } |
||
243 | -107x | +
1 | +
- active_datanames <- reactive({+ #' Filter settings for `teal` applications |
|||
244 | -84x | +|||
2 | +
- .resolve_module_datanames(data = data_rv(), modules = modules)+ #' |
|||
245 | +3 |
- })+ #' Specify initial filter states and filtering settings for a `teal` app. |
||
246 | -107x | +|||
4 | +
- if (is.null(datasets)) {+ #' |
|||
247 | -20x | +|||
5 | +
- datasets <- eventReactive(data_rv(), {+ #' Produces a `teal_slices` object. |
|||
248 | -16x | +|||
6 | +
- req(inherits(data_rv(), "teal_data"))+ #' The `teal_slice` components will specify filter states that will be active when the app starts. |
|||
249 | -16x | +|||
7 | +
- logger::log_debug("srv_teal_module@1 initializing module-specific FilteredData")+ #' Attributes (created with the named arguments) will configure the way the app applies filters. |
|||
250 | -16x | +|||
8 | +
- teal_data_to_filtered_data(data_rv(), datanames = active_datanames())+ #' See argument descriptions for details. |
|||
251 | +9 |
- })+ #' |
||
252 | +10 |
- }+ #' @inheritParams teal.slice::teal_slices |
||
253 | +11 |
-
+ #' |
||
254 | +12 |
- # manage module filters on the module level+ #' @param module_specific (`logical(1)`) optional, |
||
255 | +13 |
- # important:+ #' - `FALSE` (default) when one filter panel applied to all modules. |
||
256 | +14 |
- # filter_manager_module_srv needs to be called before filter_panel_srv+ #' All filters will be shared by all modules. |
||
257 | +15 |
- # Because available_teal_slices is used in FilteredData$srv_available_slices (via srv_filter_panel)+ #' - `TRUE` when filter panel module-specific. |
||
258 | +16 |
- # and if it is not set, then it won't be available in the srv_filter_panel+ #' Modules can have different set of filters specified - see `mapping` argument. |
||
259 | -107x | +|||
17 | +
- srv_module_filter_manager(modules$label, module_fd = datasets, slices_global = slices_global)+ #' @param mapping `r lifecycle::badge("experimental")` |
|||
260 | +18 |
-
+ #' _This is a new feature. Do kindly share your opinions on |
||
261 | -107x | +|||
19 | +
- call_once_when(is_active(), {+ #' [`teal`'s GitHub repository](https://github.com/insightsengineering/teal/)._ |
|||
262 | -81x | +|||
20 | +
- filtered_teal_data <- srv_filter_data(+ #' |
|||
263 | -81x | +|||
21 | +
- "filter_panel",+ #' (named `list`) specifies which filters will be active in which modules on app start. |
|||
264 | -81x | +|||
22 | +
- datasets = datasets,+ #' Elements should contain character vector of `teal_slice` `id`s (see [`teal.slice::teal_slice`]). |
|||
265 | -81x | +|||
23 | +
- active_datanames = active_datanames,+ #' Names of the list should correspond to `teal_module` `label` set in [module()] function. |
|||
266 | -81x | +|||
24 | +
- data_rv = data_rv,+ #' - `id`s listed under `"global_filters` will be active in all modules. |
|||
267 | -81x | +|||
25 | +
- is_active = is_active+ #' - If missing, all filters will be applied to all modules. |
|||
268 | +26 |
- )+ #' - If empty list, all filters will be available to all modules but will start inactive. |
||
269 | -81x | +|||
27 | +
- is_transformer_failed <- reactiveValues()+ #' - If `module_specific` is `FALSE`, only `global_filters` will be active on start. |
|||
270 | -81x | +|||
28 | +
- transformed_teal_data <- srv_transform_data(+ #' @param app_id (`character(1)`) |
|||
271 | -81x | +|||
29 | +
- "data_transform",+ #' For internal use only, do not set manually. |
|||
272 | -81x | +|||
30 | +
- data = filtered_teal_data,+ #' Added by `init` so that a `teal_slices` can be matched to the app in which it was used. |
|||
273 | -81x | +|||
31 | +
- transformers = modules$transformers,+ #' Used for verifying snapshots uploaded from file. See `snapshot`. |
|||
274 | -81x | +|||
32 | +
- modules = modules,+ #' |
|||
275 | -81x | +|||
33 | +
- is_transformer_failed = is_transformer_failed+ #' @param x (`list`) of lists to convert to `teal_slices` |
|||
276 | +34 |
- )+ #' |
||
277 | -81x | +|||
35 | +
- any_transformer_failed <- reactive({+ #' @return |
|||
278 | -81x | +|||
36 | +
- any(unlist(reactiveValuesToList(is_transformer_failed)))+ #' A `teal_slices` object. |
|||
279 | +37 |
- })+ #' |
||
280 | +38 |
-
+ #' @seealso [`teal.slice::teal_slices`], [`teal.slice::teal_slice`], [slices_store()] |
||
281 | -81x | +|||
39 | +
- observeEvent(any_transformer_failed(), {+ #' |
|||
282 | -81x | +|||
40 | +
- if (isTRUE(any_transformer_failed())) {+ #' @examples |
|||
283 | -6x | +|||
41 | +
- shinyjs::hide("teal_module_ui")+ #' filter <- teal_slices( |
|||
284 | -6x | +|||
42 | +
- shinyjs::hide("validate_datanames")+ #' teal_slice(dataname = "iris", varname = "Species", id = "species"), |
|||
285 | -6x | +|||
43 | +
- shinyjs::show("transformer_failure_info")+ #' teal_slice(dataname = "iris", varname = "Sepal.Length", id = "sepal_length"), |
|||
286 | +44 |
- } else {+ #' teal_slice( |
||
287 | -75x | +|||
45 | +
- shinyjs::show("teal_module_ui")+ #' dataname = "iris", id = "long_petals", title = "Long petals", expr = "Petal.Length > 5" |
|||
288 | -75x | +|||
46 | +
- shinyjs::show("validate_datanames")+ #' ), |
|||
289 | -75x | +|||
47 | +
- shinyjs::hide("transformer_failure_info")+ #' teal_slice(dataname = "mtcars", varname = "mpg", id = "mtcars_mpg"), |
|||
290 | +48 |
- }+ #' mapping = list( |
||
291 | +49 |
- })+ #' module1 = c("species", "sepal_length"), |
||
292 | +50 |
-
+ #' module2 = c("mtcars_mpg"), |
||
293 | -81x | +|||
51 | +
- module_teal_data <- reactive({+ #' global_filters = "long_petals" |
|||
294 | -89x | +|||
52 | +
- req(inherits(transformed_teal_data(), "teal_data"))+ #' ) |
|||
295 | -83x | +|||
53 | +
- all_teal_data <- transformed_teal_data()+ #' ) |
|||
296 | -83x | +|||
54 | +
- module_datanames <- .resolve_module_datanames(data = all_teal_data, modules = modules)+ #' |
|||
297 | -83x | +|||
55 | +
- .subset_teal_data(all_teal_data, module_datanames)+ #' app <- init( |
|||
298 | +56 |
- })+ #' data = teal_data(iris = iris, mtcars = mtcars), |
||
299 | +57 |
-
+ #' modules = list( |
||
300 | -81x | +|||
58 | +
- srv_validate_reactive_teal_data(+ #' module("module1"), |
|||
301 | -81x | +|||
59 | +
- "validate_datanames",+ #' module("module2") |
|||
302 | -81x | +|||
60 | +
- data = module_teal_data,+ #' ), |
|||
303 | -81x | +|||
61 | +
- modules = modules+ #' filter = filter |
|||
304 | +62 |
- )+ #' ) |
||
305 | +63 |
-
+ #' |
||
306 | -81x | +|||
64 | +
- summary_table <- srv_data_summary("data_summary", module_teal_data)+ #' if (interactive()) { |
|||
307 | +65 |
-
+ #' shinyApp(app$ui, app$server) |
||
308 | +66 |
- # Call modules.+ #' } |
||
309 | -81x | +|||
67 | +
- if (!inherits(modules, "teal_module_previewer")) {+ #' |
|||
310 | -81x | +|||
68 | +
- obs_module <- call_once_when(+ #' @export |
|||
311 | -81x | +|||
69 | +
- !is.null(module_teal_data()),+ teal_slices <- function(..., |
|||
312 | -81x | +|||
70 | +
- ignoreNULL = TRUE,+ exclude_varnames = NULL, |
|||
313 | -81x | +|||
71 | +
- handlerExpr = {+ include_varnames = NULL, |
|||
314 | -75x | +|||
72 | +
- module_out(.call_teal_module(modules, datasets, module_teal_data, reporter))+ count_type = NULL, |
|||
315 | +73 |
- }+ allow_add = TRUE, |
||
316 | +74 |
- )+ module_specific = FALSE, |
||
317 | +75 |
- } else {+ mapping, |
||
318 | +76 |
- # Report previewer must be initiated on app start for report cards to be included in bookmarks.+ app_id = NULL) { |
||
319 | -+ | |||
77 | +161x |
- # When previewer is delayed, cards are bookmarked only if previewer has been initiated (visited).+ shiny::isolate({ |
||
320 | -! | +|||
78 | +161x |
- module_out(.call_teal_module(modules, datasets, module_teal_data, reporter))+ checkmate::assert_flag(allow_add) |
||
321 | -+ | |||
79 | +161x |
- }+ checkmate::assert_flag(module_specific)+ |
+ ||
80 | +51x | +
+ if (!missing(mapping)) checkmate::assert_list(mapping, types = c("character", "NULL"), names = "named")+ |
+ ||
81 | +158x | +
+ checkmate::assert_string(app_id, null.ok = TRUE) |
||
322 | +82 | |||
323 | -+ | |||
83 | +158x |
- # todo: (feature request) add a ReporterCard to the reporter as an output from the teal_module+ slices <- list(...) |
||
324 | -+ | |||
84 | +158x |
- # how to determine if module returns a ReporterCard so that reportPreviewer is needed?+ all_slice_id <- vapply(slices, `[[`, character(1L), "id") |
||
325 | +85 |
- # Should we insertUI of the ReportPreviewer then?+ |
||
326 | -+ | |||
86 | +158x |
- # What about attr(module, "reportable") - similar to attr(module, "bookmarkable")+ if (missing(mapping)) { |
||
327 | -81x | +87 | +110x |
- if ("report" %in% names(module_out)) {+ mapping <- if (length(all_slice_id)) {+ |
+
88 | +26x | +
+ list(global_filters = all_slice_id) |
||
328 | +89 |
- # (reactively) add card to the reporter+ } else {+ |
+ ||
90 | +84x | +
+ list() |
||
329 | +91 |
} |
||
330 | +92 |
- })+ } |
||
331 | +93 | |||
332 | -107x | +94 | +158x |
- module_out+ if (!module_specific) { |
333 | -+ | |||
95 | +139x |
- })+ mapping[setdiff(names(mapping), "global_filters")] <- NULL |
||
334 | +96 |
- }+ } |
||
335 | +97 | |||
336 | -+ | |||
98 | +158x |
- # This function calls a module server function.+ failed_slice_id <- setdiff(unlist(mapping), all_slice_id) |
||
337 | -+ | |||
99 | +158x |
- .call_teal_module <- function(modules, datasets, filtered_teal_data, reporter) {+ if (length(failed_slice_id)) { |
||
338 | -+ | |||
100 | +1x |
- # collect arguments to run teal_module+ stop(sprintf( |
||
339 | -75x | +101 | +1x |
- args <- c(list(id = "module"), modules$server_args)+ "Filters in mapping don't match any available filter.\n %s not in %s", |
340 | -75x | +102 | +1x |
- if (is_arg_used(modules$server, "reporter")) {+ toString(failed_slice_id), |
341 | +103 | 1x |
- args <- c(args, list(reporter = reporter))+ toString(all_slice_id) |
|
342 | +104 |
- }+ )) |
||
343 | +105 | - - | -||
344 | -75x | -
- if (is_arg_used(modules$server, "datasets")) {+ } |
||
345 | -1x | +|||
106 | +
- args <- c(args, datasets = datasets())+ |
|||
346 | -1x | +107 | +157x |
- warning("datasets argument is not reactive and therefore it won't be updated when data is refreshed.")+ tss <- teal.slice::teal_slices( |
347 | +108 |
- }+ ..., |
||
348 | -+ | |||
109 | +157x |
-
+ exclude_varnames = exclude_varnames, |
||
349 | -75x | +110 | +157x |
- if (is_arg_used(modules$server, "data")) {+ include_varnames = include_varnames, |
350 | -71x | +111 | +157x |
- args <- c(args, data = list(filtered_teal_data))+ count_type = count_type, |
351 | -+ | |||
112 | +157x |
- }+ allow_add = allow_add |
||
352 | +113 |
-
+ ) |
||
353 | -75x | +114 | +157x |
- if (is_arg_used(modules$server, "filter_panel_api")) {+ attr(tss, "mapping") <- mapping |
354 | -1x | +115 | +157x |
- args <- c(args, filter_panel_api = teal.slice::FilterPanelAPI$new(datasets()))+ attr(tss, "module_specific") <- module_specific |
355 | -+ | |||
116 | +157x |
- }+ attr(tss, "app_id") <- app_id |
||
356 | -+ | |||
117 | +157x |
-
+ class(tss) <- c("modules_teal_slices", class(tss)) |
||
357 | -75x | +118 | +157x |
- if (is_arg_used(modules$server, "id")) {+ tss |
358 | -75x | +|||
119 | +
- do.call(modules$server, args)+ }) |
|||
359 | +120 |
- } else {+ } |
||
360 | -! | +|||
121 | +
- do.call(callModule, c(args, list(module = modules$server)))+ |
|||
361 | +122 |
- }+ |
||
362 | +123 |
- }+ #' @rdname teal_slices |
||
363 | +124 |
-
+ #' @export |
||
364 | +125 |
- .resolve_module_datanames <- function(data, modules) {+ #' @keywords internal |
||
365 | -167x | +|||
126 | +
- stopifnot("data_rv must be teal_data object." = inherits(data, "teal_data"))+ #'+ |
+ |||
127 | ++ |
+ as.teal_slices <- function(x) { # nolint: object_name. |
||
366 | -167x | +128 | +13x |
- if (is.null(modules$datanames) || identical(modules$datanames, "all")) {+ checkmate::assert_list(x) |
367 | -135x | +129 | +13x |
- .topologically_sort_datanames(ls(teal.code::get_env(data)), teal.data::join_keys(data))+ lapply(x, checkmate::assert_list, names = "named", .var.name = "list element") |
368 | +130 |
- } else {+ + |
+ ||
131 | +13x | +
+ attrs <- attributes(unclass(x)) |
||
369 | -32x | +132 | +13x |
- intersect(+ ans <- lapply(x, function(x) if (is.teal_slice(x)) x else as.teal_slice(x)) |
370 | -32x | +133 | +13x |
- .include_parent_datanames(modules$datanames, teal.data::join_keys(data)),+ do.call(teal_slices, c(ans, attrs)) |
371 | -32x | +|||
134 | +
- ls(teal.code::get_env(data))+ } |
|||
372 | +135 |
- )+ |
||
373 | +136 |
- }+ |
||
374 | +137 |
- }+ #' @rdname teal_slices |
||
375 | +138 |
-
+ #' @export |
||
376 | +139 |
- #' Calls expression when condition is met+ #' @keywords internal |
||
377 | +140 |
#' |
||
378 | +141 |
- #' Function postpones `handlerExpr` to the moment when `eventExpr` (condition) returns `TRUE`,+ c.teal_slices <- function(...) { |
||
379 | -+ | |||
142 | +6x |
- #' otherwise nothing happens.+ x <- list(...) |
||
380 | -+ | |||
143 | +6x |
- #' @param eventExpr A (quoted or unquoted) logical expression that represents the event;+ checkmate::assert_true(all(vapply(x, is.teal_slices, logical(1L))), .var.name = "all arguments are teal_slices") |
||
381 | +144 |
- #' this can be a simple reactive value like input$click, a call to a reactive expression+ |
||
382 | -+ | |||
145 | +6x |
- #' like dataset(), or even a complex expression inside curly braces.+ all_attributes <- lapply(x, attributes) |
||
383 | -+ | |||
146 | +6x |
- #' @param ... additional arguments passed to `observeEvent` with the exception of `eventExpr` that is not allowed.+ all_attributes <- coalesce_r(all_attributes) |
||
384 | -+ | |||
147 | +6x |
- #' @inheritParams shiny::observeEvent+ all_attributes <- all_attributes[names(all_attributes) != "class"] |
||
385 | +148 |
- #'+ |
||
386 | -+ | |||
149 | +6x |
- #' @return An observer.+ do.call( |
||
387 | -+ | |||
150 | +6x |
- #'+ teal_slices, |
||
388 | -+ | |||
151 | +6x |
- #' @keywords internal+ c(+ |
+ ||
152 | +6x | +
+ unique(unlist(x, recursive = FALSE)),+ |
+ ||
153 | +6x | +
+ all_attributes |
||
389 | +154 |
- call_once_when <- function(eventExpr, # nolint: object_name.+ ) |
||
390 | +155 |
- handlerExpr, # nolint: object_name.+ ) |
||
391 | +156 |
- event.env = parent.frame(), # nolint: object_name.+ } |
||
392 | +157 |
- handler.env = parent.frame(), # nolint: object_name.+ |
||
393 | +158 |
- ...) {+ |
||
394 | -188x | +|||
159 | +
- event_quo <- rlang::new_quosure(substitute(eventExpr), env = event.env)+ #' Deep copy `teal_slices` |
|||
395 | -188x | +|||
160 | +
- handler_quo <- rlang::new_quosure(substitute(handlerExpr), env = handler.env)+ #' |
|||
396 | +161 |
-
+ #' it's important to create a new copy of `teal_slices` when |
||
397 | +162 |
- # When `condExpr` is TRUE, then `handlerExpr` is evaluated once.+ #' starting a new `shiny` session. Otherwise, object will be shared |
||
398 | -188x | +|||
163 | +
- activator <- reactive({+ #' by multiple users as it is created in global environment before |
|||
399 | -188x | +|||
164 | +
- if (isTRUE(rlang::eval_tidy(event_quo))) {+ #' `shiny` session starts. |
|||
400 | -156x | +|||
165 | +
- TRUE+ #' @param filter (`teal_slices`) |
|||
401 | +166 |
- }+ #' @return `teal_slices` |
||
402 | +167 |
- })+ #' @keywords internal |
||
403 | +168 |
-
+ deep_copy_filter <- function(filter) { |
||
404 | -188x | +169 | +1x |
- observeEvent(+ checkmate::assert_class(filter, "teal_slices") |
405 | -188x | +170 | +1x |
- eventExpr = activator(),+ shiny::isolate({ |
406 | -188x | +171 | +1x |
- once = TRUE,+ filter_copy <- lapply(filter, function(slice) { |
407 | -188x | +172 | +2x |
- handlerExpr = rlang::eval_tidy(handler_quo),+ teal.slice::as.teal_slice(as.list(slice)) |
408 | +173 |
- ...+ })+ |
+ ||
174 | +1x | +
+ attributes(filter_copy) <- attributes(filter)+ |
+ ||
175 | +1x | +
+ filter_copy |
||
409 | +176 |
- )+ }) |
||
410 | +177 |
}@@ -39615,14 +39293,14 @@ teal coverage - 59.99% |
1 |
- #' Send input validation messages to output+ #' `teal` main module |
|||
3 |
- #' Captures messages from `InputValidator` objects and collates them+ #' @description |
|||
4 |
- #' into one message passed to `validate`.+ #' `r lifecycle::badge("stable")` |
|||
5 |
- #'+ #' Module to create a `teal` app. This module can be called directly instead of [init()] and |
|||
6 |
- #' `shiny::validate` is used to withhold rendering of an output element until+ #' included in your custom application. Please note that [init()] adds `reporter_previewer_module` |
|||
7 |
- #' certain conditions are met and to print a validation message in place+ #' automatically, which is not a case when calling `ui/srv_teal` directly. |
|||
8 |
- #' of the output element.+ #' |
|||
9 |
- #' `shinyvalidate::InputValidator` allows to validate input elements+ #' @details |
|||
10 |
- #' and to display specific messages in their respective input widgets.+ #' |
|||
11 |
- #' `validate_inputs` provides a hybrid solution.+ #' Module is responsible for creating the main `shiny` app layout and initializing all the necessary |
|||
12 |
- #' Given an `InputValidator` object, messages corresponding to inputs that fail validation+ #' components. This module establishes reactive connection between the input `data` and every other |
|||
13 |
- #' are extracted and placed in one validation message that is passed to a `validate`/`need` call.+ #' component in the app. Reactive change of the `data` passed as an argument, reloads the app and |
|||
14 |
- #' This way the input `validator` messages are repeated in the output.+ #' possibly keeps all input settings the same so the user can continue where one left off. |
|||
16 |
- #' The `...` argument accepts any number of `InputValidator` objects+ #' ## data flow in `teal` application |
|||
17 |
- #' or a nested list of such objects.+ #' |
|||
18 |
- #' If `validators` are passed directly, all their messages are printed together+ #' This module supports multiple data inputs but eventually, they are all converted to `reactive` |
|||
19 |
- #' under one (optional) header message specified by `header`. If a list is passed,+ #' returning `teal_data` in this module. On this `reactive teal_data` object several actions are |
|||
20 |
- #' messages are grouped by `validator`. The list's names are used as headers+ #' performed: |
|||
21 |
- #' for their respective message groups.+ #' - data loading in [`module_init_data`] |
|||
22 |
- #' If neither of the nested list elements is named, a header message is taken from `header`.+ #' - data filtering in [`module_filter_data`] |
|||
23 |
- #'+ #' - data transformation in [`module_transform_data`] |
|||
24 |
- #' @param ... either any number of `InputValidator` objects+ #' |
|||
25 |
- #' or an optionally named, possibly nested `list` of `InputValidator`+ #' ## Fallback on failure |
|||
26 |
- #' objects, see `Details`+ #' |
|||
27 |
- #' @param header (`character(1)`) generic validation message; set to NULL to omit+ #' `teal` is designed in such way that app will never crash if the error is introduced in any |
|||
28 |
- #'+ #' custom `shiny` module provided by app developer (e.g. [teal_data_module()], [teal_transform_module()]). |
|||
29 |
- #' @return+ #' If any module returns a failing object, the app will halt the evaluation and display a warning message. |
|||
30 |
- #' Returns NULL if the final validation call passes and a `shiny.silent.error` if it fails.+ #' App user should always have a chance to fix the improper input and continue without restarting the session. |
|||
32 |
- #' @seealso [`shinyvalidate::InputValidator`], [`shiny::validate`]+ #' @rdname module_teal |
|||
33 |
- #'+ #' @name module_teal |
|||
34 |
- #' @examplesIf require("shinyvalidate")+ #' |
|||
35 |
- #' library(shiny)+ #' @inheritParams module_init_data |
|||
36 |
- #' library(shinyvalidate)+ #' @inheritParams init |
|||
38 |
- #' ui <- fluidPage(+ #' @return `NULL` invisibly |
|||
39 |
- #' selectInput("method", "validation method", c("sequential", "combined", "grouped")),+ NULL |
|||
40 |
- #' sidebarLayout(+ |
|||
41 |
- #' sidebarPanel(+ #' @rdname module_teal |
|||
42 |
- #' selectInput("letter", "select a letter:", c(letters[1:3], LETTERS[4:6])),+ #' @export |
|||
43 |
- #' selectInput("number", "select a number:", 1:6),+ ui_teal <- function(id, |
|||
44 |
- #' tags$br(),+ modules, |
|||
45 |
- #' selectInput("color", "select a color:",+ title = build_app_title(), |
|||
46 |
- #' c("black", "indianred2", "springgreen2", "cornflowerblue"),+ header = tags$p(), |
|||
47 |
- #' multiple = TRUE+ footer = tags$p()) { |
|||
48 | -+ | ! |
- #' ),+ checkmate::assert_character(id, max.len = 1, any.missing = FALSE) |
|
49 | -+ | ! |
- #' sliderInput("size", "select point size:",+ checkmate::assert( |
|
50 | -+ | ! |
- #' min = 0.1, max = 4, value = 0.25+ .var.name = "title", |
|
51 | -+ | ! |
- #' )+ checkmate::check_string(title), |
|
52 | -+ | ! |
- #' ),+ checkmate::check_multi_class(title, c("shiny.tag", "shiny.tag.list", "html")) |
|
53 |
- #' mainPanel(plotOutput("plot"))+ ) |
|||
54 | -+ | ! |
- #' )+ checkmate::assert( |
|
55 | -+ | ! |
- #' )+ .var.name = "header", |
|
56 | -+ | ! |
- #'+ checkmate::check_string(header), |
|
57 | -+ | ! |
- #' server <- function(input, output) {+ checkmate::check_multi_class(header, c("shiny.tag", "shiny.tag.list", "html")) |
|
58 |
- #' # set up input validation+ ) |
|||
59 | -+ | ! |
- #' iv <- InputValidator$new()+ checkmate::assert( |
|
60 | -+ | ! |
- #' iv$add_rule("letter", sv_in_set(LETTERS, "choose a capital letter"))+ .var.name = "footer", |
|
61 | -+ | ! |
- #' iv$add_rule("number", function(x) {+ checkmate::check_string(footer), |
|
62 | -+ | ! |
- #' if (as.integer(x) %% 2L == 1L) "choose an even number"+ checkmate::check_multi_class(footer, c("shiny.tag", "shiny.tag.list", "html")) |
|
63 |
- #' })+ ) |
|||
64 |
- #' iv$enable()+ |
|||
65 | -+ | ! |
- #' # more input validation+ if (is.character(title)) { |
|
66 | -+ | ! |
- #' iv_par <- InputValidator$new()+ title <- build_app_title(title) |
|
67 |
- #' iv_par$add_rule("color", sv_required(message = "choose a color"))+ } else { |
|||
68 | -+ | ! |
- #' iv_par$add_rule("color", function(x) {+ validate_app_title_tag(title) |
|
69 |
- #' if (length(x) > 1L) "choose only one color"+ } |
|||
70 |
- #' })+ |
|||
71 | -+ | ! |
- #' iv_par$add_rule(+ if (checkmate::test_string(header)) { |
|
72 | -+ | ! |
- #' "size",+ header <- tags$p(header) |
|
73 |
- #' sv_between(+ } |
|||
74 |
- #' left = 0.5, right = 3,+ |
|||
75 | -+ | ! |
- #' message_fmt = "choose a value between {left} and {right}"+ if (checkmate::test_string(footer)) { |
|
76 | -+ | ! |
- #' )+ footer <- tags$p(footer) |
|
77 |
- #' )+ } |
|||
78 |
- #' iv_par$enable()+ |
|||
79 | -+ | ! |
- #'+ ns <- NS(id) |
|
80 |
- #' output$plot <- renderPlot({+ |
|||
81 |
- #' # validate output+ # show busy icon when `shiny` session is busy computing stuff |
|||
82 |
- #' switch(input[["method"]],+ # based on https://stackoverflow.com/questions/17325521/r-shiny-display-loading-message-while-function-is-running/22475216#22475216 # nolint: line_length. |
|||
83 | -+ | ! |
- #' "sequential" = {+ shiny_busy_message_panel <- conditionalPanel( |
|
84 | -+ | ! |
- #' validate_inputs(iv)+ condition = "(($('html').hasClass('shiny-busy')) && (document.getElementById('shiny-notification-panel') == null))", # nolint: line_length. |
|
85 | -+ | ! |
- #' validate_inputs(iv_par, header = "Set proper graphical parameters")+ tags$div( |
|
86 | -+ | ! |
- #' },+ icon("arrows-rotate", class = "fa-spin", prefer_type = "solid"), |
|
87 | -+ | ! |
- #' "combined" = validate_inputs(iv, iv_par),+ "Computing ...", |
|
88 |
- #' "grouped" = validate_inputs(list(+ # CSS defined in `custom.css` |
|||
89 | -+ | ! |
- #' "Some inputs require attention" = iv,+ class = "shinybusymessage" |
|
90 |
- #' "Set proper graphical parameters" = iv_par+ ) |
|||
91 |
- #' ))+ ) |
|||
92 |
- #' )+ |
|||
93 | -+ | ! |
- #'+ fluidPage( |
|
94 | -+ | ! |
- #' plot(faithful$eruptions ~ faithful$waiting,+ id = id, |
|
95 | -+ | ! |
- #' las = 1, pch = 16,+ title = title, |
|
96 | -+ | ! |
- #' col = input[["color"]], cex = input[["size"]]+ theme = get_teal_bs_theme(), |
|
97 | -+ | ! |
- #' )+ include_teal_css_js(), |
|
98 | -+ | ! |
- #' })+ tags$header(header), |
|
99 | -+ | ! |
- #' }+ tags$hr(class = "my-2"), |
|
100 | -+ | ! |
- #'+ shiny_busy_message_panel, |
|
101 | -+ | ! |
- #' if (interactive()) {+ tags$div( |
|
102 | -+ | ! |
- #' shinyApp(ui, server)+ id = ns("tabpanel_wrapper"), |
|
103 | -+ | ! |
- #' }+ class = "teal-body", |
|
104 | -+ | ! |
- #'+ ui_teal_module(id = ns("teal_modules"), modules = modules) |
|
105 |
- #' @export+ ), |
|||
106 | -+ | ! |
- #'+ tags$div( |
|
107 | -+ | ! |
- validate_inputs <- function(..., header = "Some inputs require attention") {+ id = ns("options_buttons"), |
|
108 | -36x | +! |
- dots <- list(...)+ style = "position: absolute; right: 10px;", |
|
109 | -2x | +! |
- if (!is_validators(dots)) stop("validate_inputs accepts validators or a list thereof")+ ui_bookmark_panel(ns("bookmark_manager"), modules), |
|
110 | -+ | ! |
-
+ tags$button( |
|
111 | -34x | +! |
- messages <- extract_validator(dots, header)+ class = "btn action-button filter_hamburger", # see sidebar.css for style filter_hamburger |
|
112 | -34x | +! |
- failings <- if (!any_names(dots)) {+ href = "javascript:void(0)", |
|
113 | -29x | +! |
- add_header(messages, header)+ onclick = sprintf("toggleFilterPanel('%s');", ns("tabpanel_wrapper")), |
|
114 | -+ | ! |
- } else {+ title = "Toggle filter panel", |
|
115 | -5x | +! |
- unlist(messages)+ icon("fas fa-bars") |
|
116 |
- }+ ), |
|||
117 | -+ | ! |
-
+ ui_snapshot_manager_panel(ns("snapshot_manager_panel")), |
|
118 | -34x | +! |
- shiny::validate(shiny::need(is.null(failings), failings))+ ui_filter_manager_panel(ns("filter_manager_panel")) |
|
119 |
- }+ ), |
|||
120 | -+ | ! |
-
+ tags$script( |
|
121 | -+ | ! |
- ### internal functions+ HTML( |
|
122 | -+ | ! |
-
+ sprintf( |
|
123 |
- #' @noRd+ " |
|||
124 | -+ | ! |
- #' @keywords internal+ $(document).ready(function() { |
|
125 | -+ | ! |
- # recursive object type test+ $('#%s').appendTo('#%s'); |
|
126 |
- # returns logical of length 1+ }); |
|||
127 |
- is_validators <- function(x) {+ ", |
|||
128 | -118x | +! |
- all(if (is.list(x)) unlist(lapply(x, is_validators)) else inherits(x, "InputValidator"))+ ns("options_buttons"), |
|
129 | -+ | ! |
- }+ ns("teal_modules-active_tab") |
|
130 |
-
+ ) |
|||
131 |
- #' @noRd+ ) |
|||
132 |
- #' @keywords internal+ ), |
|||
133 | -+ | ! |
- # test if an InputValidator object is enabled+ tags$hr(), |
|
134 | -+ | ! |
- # returns logical of length 1+ tags$footer( |
|
135 | -+ | ! |
- # official method requested at https://github.com/rstudio/shinyvalidate/issues/64+ tags$div( |
|
136 | -+ | ! |
- validator_enabled <- function(x) {+ footer, |
|
137 | -49x | +! |
- x$.__enclos_env__$private$enabled+ teal.widgets::verbatim_popup_ui(ns("sessionInfo"), "Session Info", type = "link"), |
|
138 | -+ | ! |
- }+ br(), |
|
139 | -+ | ! |
-
+ ui_teal_lockfile(ns("lockfile")), |
|
140 | -+ | ! |
- #' Recursively extract messages from validator list+ textOutput(ns("identifier")) |
|
141 |
- #' @return A character vector or a list of character vectors, possibly nested and named.+ ) |
|||
142 |
- #' @noRd+ ) |
|||
143 |
- #' @keywords internal+ ) |
|||
144 | - |
- extract_validator <- function(iv, header) {- |
- ||
145 | -113x | -
- if (inherits(iv, "InputValidator")) {- |
- ||
146 | -49x | -
- add_header(gather_messages(iv), header)- |
- ||
147 | -- |
- } else {- |
- ||
148 | -58x | -
- if (is.null(names(iv))) names(iv) <- rep("", length(iv))- |
- ||
149 | -64x | -
- mapply(extract_validator, iv = iv, header = names(iv), SIMPLIFY = FALSE)- |
- ||
150 | -- |
- }- |
- ||
151 | -
} |
|||
152 | +145 | |||
153 | -- |
- #' Collate failing messages from validator.- |
- ||
154 | -- |
- #' @return `list`- |
- ||
155 | +146 |
- #' @noRd+ #' @rdname module_teal |
||
156 | +147 |
- #' @keywords internal+ #' @export |
||
157 | +148 |
- gather_messages <- function(iv) {- |
- ||
158 | -49x | -
- if (validator_enabled(iv)) {- |
- ||
159 | -46x | -
- status <- iv$validate()+ srv_teal <- function(id, data, modules, filter = teal_slices()) { |
||
160 | -46x | +149 | +84x |
- failing_inputs <- Filter(Negate(is.null), status)+ checkmate::assert_character(id, max.len = 1, any.missing = FALSE) |
161 | -46x | -
- unique(lapply(failing_inputs, function(x) x[["message"]]))- |
- ||
162 | -+ | 150 | +84x |
- } else {+ checkmate::assert_multi_class(data, c("teal_data", "teal_data_module", "reactive")) |
163 | -3x | +151 | +83x |
- warning("Validator is disabled and will be omitted.")+ checkmate::assert_class(modules, "teal_modules") |
164 | -3x | -
- list()- |
- ||
165 | -- |
- }- |
- ||
166 | -+ | 152 | +83x |
- }+ checkmate::assert_class(filter, "teal_slices") |
167 | +153 | |||
168 | -- |
- #' Add optional header to failing messages- |
- ||
169 | -- |
- #' @noRd- |
- ||
170 | -- |
- #' @keywords internal- |
- ||
171 | -- |
- add_header <- function(messages, header = "") {- |
- ||
172 | -78x | -
- ans <- unlist(messages)- |
- ||
173 | -78x | -
- if (length(ans) != 0L && isTRUE(nchar(header) > 0L)) {- |
- ||
174 | -31x | -
- ans <- c(paste0(header, "\n"), ans, "\n")- |
- ||
175 | -+ | 154 | +83x |
- }+ moduleServer(id, function(input, output, session) { |
176 | -78x | -
- ans- |
- ||
177 | -- |
- }- |
- ||
178 | -- | - - | -||
179 | -+ | 155 | +83x |
- #' Recursively check if the object contains a named list+ logger::log_debug("srv_teal initializing.") |
180 | +156 |
- #' @noRd+ |
||
181 | -+ | |||
157 | +83x |
- #' @keywords internal+ if (getOption("teal.show_js_log", default = FALSE)) { |
||
182 | -+ | |||
158 | +! |
- any_names <- function(x) {+ shinyjs::showLog() |
||
183 | -103x | +|||
159 | +
- any(+ } |
|||
184 | -103x | +|||
160 | +
- if (is.list(x)) {+ |
|||
185 | -58x | +161 | +83x |
- if (!is.null(names(x)) && any(names(x) != "")) TRUE else unlist(lapply(x, any_names))+ srv_teal_lockfile("lockfile") |
186 | +162 |
- } else {+ |
||
187 | -40x | +163 | +83x |
- FALSE+ output$identifier <- renderText( |
188 | -+ | |||
164 | +83x |
- }+ paste0("Pid:", Sys.getpid(), " Token:", substr(session$token, 25, 32)) |
||
189 | +165 |
- )+ ) |
||
190 | +166 |
- }+ |
1 | -+ | ||
167 | +83x |
- #' Create a `tdata` object+ teal.widgets::verbatim_popup_srv( |
|
2 | -+ | ||
168 | +83x |
- #'+ "sessionInfo", |
|
3 | -+ | ||
169 | +83x |
- #' @description `r lifecycle::badge("superseded")`+ verbatim_content = utils::capture.output(utils::sessionInfo()), |
|
4 | -+ | ||
170 | +83x |
- #'+ title = "SessionInfo" |
|
5 | +171 |
- #' Recent changes in `teal` cause modules to fail because modules expect a `tdata` object+ ) |
|
6 | +172 |
- #' to be passed to the `data` argument but instead they receive a `teal_data` object,+ |
|
7 | +173 |
- #' which is additionally wrapped in a reactive expression in the server functions.+ # `JavaScript` code |
|
8 | -+ | ||
174 | +83x |
- #' In order to easily adapt such modules without a proper refactor,+ run_js_files(files = "init.js") |
|
9 | +175 |
- #' use this function to downgrade the `data` argument.+ |
|
10 | +176 |
- #'+ # set timezone in shiny app |
|
11 | +177 |
- #' @name tdata+ # timezone is set in the early beginning so it will be available also |
|
12 | +178 |
- #' @param ... ignored+ # for `DDL` and all shiny modules |
|
13 | -+ | ||
179 | +83x |
- #' @return nothing+ get_client_timezone(session$ns) |
|
14 | -+ | ||
180 | +83x |
- NULL+ observeEvent( |
|
15 | -+ | ||
181 | +83x |
-
+ eventExpr = input$timezone, |
|
16 | -+ | ||
182 | +83x |
- #' @rdname tdata+ once = TRUE, |
|
17 | -+ | ||
183 | +83x |
- #' @export+ handlerExpr = { |
|
18 | -+ | ||
184 | +! |
- new_tdata <- function(...) {+ session$userData$timezone <- input$timezone |
|
19 | +185 | ! |
- .deprecate_tdata_msg()+ logger::log_debug("srv_teal@1 Timezone set to client's timezone: { input$timezone }.") |
20 | +186 |
- }+ } |
|
21 | +187 |
-
+ ) |
|
22 | +188 |
- #' @rdname tdata+ |
|
23 | -+ | ||
189 | +83x |
- #' @export+ data_pulled <- srv_init_data("data", data = data) |
|
24 | -+ | ||
190 | +82x |
- tdata2env <- function(...) {+ data_validated <- srv_validate_reactive_teal_data( |
|
25 | -! | +||
191 | +82x |
- .deprecate_tdata_msg()+ "validate", |
|
26 | -+ | ||
192 | +82x |
- }+ data = data_pulled, |
|
27 | -+ | ||
193 | +82x |
-
+ modules = modules, |
|
28 | -+ | ||
194 | +82x |
- #' @rdname tdata+ validate_shiny_silent_error = FALSE |
|
29 | +195 |
- #' @export+ ) |
|
30 | -+ | ||
196 | +82x |
- get_code_tdata <- function(...) {+ data_rv <- reactive({ |
|
31 | -! | +||
197 | +142x |
- .deprecate_tdata_msg()+ req(inherits(data_validated(), "teal_data")) |
|
32 | -+ | ||
198 | +70x |
- }+ is_filter_ok <- check_filter_datanames(filter, names(data_validated())) |
|
33 | -+ | ||
199 | +70x |
-
+ if (!isTRUE(is_filter_ok)) { |
|
34 | -+ | ||
200 | +2x |
- #' @rdname tdata+ showNotification( |
|
35 | -+ | ||
201 | +2x |
- #' @export+ "Some filters were not applied because of incompatibility with data. Contact app developer.", |
|
36 | -+ | ||
202 | +2x |
- join_keys.tdata <- function(...) {+ type = "warning", |
|
37 | -! | +||
203 | +2x |
- .deprecate_tdata_msg()+ duration = 10 |
|
38 | +204 |
- }+ ) |
|
39 | -+ | ||
205 | +2x |
-
+ warning(is_filter_ok) |
|
40 | +206 |
- #' @rdname tdata+ }+ |
+ |
207 | +70x | +
+ .add_signature_to_data(data_validated()) |
|
41 | +208 |
- #' @export+ }) |
|
42 | +209 |
- get_metadata <- function(...) {+ |
|
43 | -! | +||
210 | +82x |
- .deprecate_tdata_msg()+ data_load_status <- reactive({ |
|
44 | -+ | ||
211 | +75x |
- }+ if (inherits(data_pulled(), "teal_data")) { |
|
45 | -+ | ||
212 | +70x |
-
+ "ok" |
|
46 | +213 |
- #' @rdname tdata+ # todo: should we hide warnings on top for a data? |
|
47 | -+ | ||
214 | +5x |
- #' @export+ } else if (inherits(data, "teal_data_module")) {+ |
+ |
215 | +5x | +
+ "teal_data_module failed" |
|
48 | +216 |
- as_tdata <- function(...) {+ } else { |
|
49 | +217 | ! |
- .deprecate_tdata_msg()+ "external failed" |
50 | +218 |
- }+ } |
|
51 | +219 |
-
+ }) |
|
52 | +220 | ||
53 | -- |
- .deprecate_tdata_msg <- function() {- |
- |
54 | -! | +||
221 | +82x |
- lifecycle::deprecate_stop(+ datasets_rv <- if (!isTRUE(attr(filter, "module_specific"))) { |
|
55 | -! | +||
222 | +71x |
- when = "0.16",+ eventReactive(data_rv(), { |
|
56 | -! | +||
223 | +61x |
- what = "tdata()",+ req(inherits(data_rv(), "teal_data")) |
|
57 | -! | +||
224 | +61x |
- details = paste(+ logger::log_debug("srv_teal@1 initializing FilteredData") |
|
58 | -! | +||
225 | +61x |
- "tdata has been removed in favour of `teal_data`.\n",+ teal_data_to_filtered_data(data_rv()) |
|
59 | -! | +||
226 | +
- "Please follow migration instructions https://github.com/insightsengineering/teal/discussions/987."+ }) |
||
60 | +227 |
- )+ } |
|
61 | +228 |
- )+ |
|
62 | -+ | ||
229 | +82x |
- }+ if (inherits(data, "teal_data_module")) { |
1 | -+ | |||
230 | +9x |
- #' @title `TealReportCard`+ setBookmarkExclude(c("teal_modules-active_tab")) |
||
2 | -+ | |||
231 | +9x |
- #' @description `r lifecycle::badge("experimental")`+ shiny::insertTab( |
||
3 | -+ | |||
232 | +9x |
- #' Child class of [`ReportCard`] that is used for `teal` specific applications.+ inputId = "teal_modules-active_tab", |
||
4 | -+ | |||
233 | +9x |
- #' In addition to the parent methods, it supports rendering `teal` specific elements such as+ position = "before", |
||
5 | -+ | |||
234 | +9x |
- #' the source code, the encodings panel content and the filter panel content as part of the+ select = TRUE, |
||
6 | -+ | |||
235 | +9x |
- #' meta data.+ tabPanel( |
||
7 | -+ | |||
236 | +9x |
- #' @export+ title = icon("fas fa-database"), |
||
8 | -+ | |||
237 | +9x |
- #'+ value = "teal_data_module", |
||
9 | -+ | |||
238 | +9x |
- TealReportCard <- R6::R6Class( # nolint: object_name.+ tags$div( |
||
10 | -+ | |||
239 | +9x |
- classname = "TealReportCard",+ ui_init_data(session$ns("data")), |
||
11 | -+ | |||
240 | +9x |
- inherit = teal.reporter::ReportCard,+ ui_validate_reactive_teal_data(session$ns("validate")) |
||
12 | +241 |
- public = list(+ ) |
||
13 | +242 |
- #' @description Appends the source code to the `content` meta data of this `TealReportCard`.+ ) |
||
14 | +243 |
- #'+ ) |
||
15 | +244 |
- #' @param src (`character(1)`) code as text.+ |
||
16 | -+ | |||
245 | +9x |
- #' @param ... any `rmarkdown` `R` chunk parameter and its value.+ if (attr(data, "once")) { |
||
17 | -+ | |||
246 | +9x |
- #' But `eval` parameter is always set to `FALSE`.+ observeEvent(data_rv(), once = TRUE, { |
||
18 | -+ | |||
247 | +4x |
- #' @return Object of class `TealReportCard`, invisibly.+ logger::log_debug("srv_teal@2 removing data tab.") |
||
19 | +248 |
- #' @examples+ # when once = TRUE we pull data once and then remove data tab |
||
20 | -+ | |||
249 | +4x |
- #' card <- TealReportCard$new()$append_src(+ removeTab("teal_modules-active_tab", target = "teal_data_module") |
||
21 | +250 |
- #' "plot(iris)"+ }) |
||
22 | +251 |
- #' )+ } |
||
23 | +252 |
- #' card$get_content()[[1]]$get_content()+ } else { |
||
24 | +253 |
- append_src = function(src, ...) {- |
- ||
25 | -4x | -
- checkmate::assert_character(src, min.len = 0, max.len = 1)- |
- ||
26 | -4x | -
- params <- list(...)- |
- ||
27 | -4x | -
- params$eval <- FALSE- |
- ||
28 | -4x | -
- rblock <- RcodeBlock$new(src)+ # when no teal_data_module then we want to display messages above tabsetPanel (because there is no data-tab) |
||
29 | -4x | +254 | +73x |
- rblock$set_params(params)+ insertUI( |
30 | -4x | +255 | +73x |
- self$append_content(rblock)+ selector = sprintf("#%s", session$ns("tabpanel_wrapper")), |
31 | -4x | +256 | +73x |
- self$append_metadata("SRC", src)+ where = "beforeBegin", |
32 | -4x | -
- invisible(self)- |
- ||
33 | -+ | 257 | +73x |
- },+ ui = tags$div(ui_validate_reactive_teal_data(session$ns("validate")), tags$br()) |
34 | +258 |
- #' @description Appends the filter state list to the `content` and `metadata` of this `TealReportCard`.+ ) |
||
35 | +259 |
- #' If the filter state list has an attribute named `formatted`, it appends it to the card otherwise it uses+ } |
||
36 | +260 |
- #' the default `yaml::as.yaml` to format the list.+ |
||
37 | -+ | |||
261 | +82x |
- #' If the filter state list is empty, nothing is appended to the `content`.+ module_labels <- unlist(module_labels(modules), use.names = FALSE) |
||
38 | -+ | |||
262 | +82x |
- #'+ slices_global <- methods::new(".slicesGlobal", filter, module_labels) |
||
39 | -+ | |||
263 | +82x |
- #' @param fs (`teal_slices`) object returned from [teal_slices()] function.+ modules_output <- srv_teal_module( |
||
40 | -+ | |||
264 | +82x |
- #' @return `self`, invisibly.+ id = "teal_modules", |
||
41 | -+ | |||
265 | +82x |
- append_fs = function(fs) {+ data_rv = data_rv, |
||
42 | -5x | +266 | +82x |
- checkmate::assert_class(fs, "teal_slices")+ datasets = datasets_rv, |
43 | -4x | +267 | +82x |
- self$append_text("Filter State", "header3")+ modules = modules, |
44 | -4x | +268 | +82x |
- if (length(fs)) {+ slices_global = slices_global, |
45 | -3x | +269 | +82x |
- self$append_content(TealSlicesBlock$new(fs))+ data_load_status = data_load_status |
46 | +270 |
- } else {+ ) |
||
47 | -1x | +271 | +82x |
- self$append_text("No filters specified.")+ mapping_table <- srv_filter_manager_panel("filter_manager_panel", slices_global = slices_global) |
48 | -+ | |||
272 | +82x |
- }+ snapshots <- srv_snapshot_manager_panel("snapshot_manager_panel", slices_global = slices_global) |
||
49 | -4x | +273 | +82x |
- invisible(self)+ srv_bookmark_panel("bookmark_manager", modules) |
50 | +274 |
- },+ }) |
||
51 | +275 |
- #' @description Appends the encodings list to the `content` and `metadata` of this `TealReportCard`.+ |
||
52 | -+ | |||
276 | +82x |
- #'+ invisible(NULL) |
||
53 | +277 |
- #' @param encodings (`list`) list of encodings selections of the `teal` app.+ } |
54 | +1 |
- #' @return `self`, invisibly.+ #' Module to transform `reactive` `teal_data` |
||
55 | +2 |
- #' @examples+ #' |
||
56 | +3 |
- #' card <- TealReportCard$new()$append_encodings(list(variable1 = "X"))+ #' Module calls multiple [`module_teal_data`] in sequence so that `reactive teal_data` output |
||
57 | +4 |
- #' card$get_content()[[1]]$get_content()+ #' from one module is handed over to the following module's input. |
||
58 | +5 |
- #'+ #' |
||
59 | +6 |
- append_encodings = function(encodings) {- |
- ||
60 | -4x | -
- checkmate::assert_list(encodings)+ #' @inheritParams module_teal_data |
||
61 | -4x | +|||
7 | +
- self$append_text("Selected Options", "header3")+ #' @inheritParams teal_modules |
|||
62 | -4x | +|||
8 | +
- if (requireNamespace("yaml", quietly = TRUE)) {+ #' @return `reactive` `teal_data` |
|||
63 | -4x | +|||
9 | +
- self$append_text(yaml::as.yaml(encodings, handlers = list(+ #' |
|||
64 | -4x | +|||
10 | +
- POSIXct = function(x) format(x, "%Y-%m-%d"),+ #' |
|||
65 | -4x | +|||
11 | +
- POSIXlt = function(x) format(x, "%Y-%m-%d"),+ #' @name module_transform_data |
|||
66 | -4x | +|||
12 | +
- Date = function(x) format(x, "%Y-%m-%d")+ #' @keywords internal |
|||
67 | -4x | +|||
13 | +
- )), "verbatim")+ NULL |
|||
68 | +14 |
- } else {+ |
||
69 | -! | +|||
15 | +
- stop("yaml package is required to format the encodings list")+ #' @rdname module_transform_data |
|||
70 | +16 |
- }+ ui_transform_data <- function(id, transformers = list(), class = "well") { |
||
71 | -4x | +|||
17 | +! |
- self$append_metadata("Encodings", encodings)+ checkmate::assert_string(id) |
||
72 | -4x | +|||
18 | +! |
- invisible(self)+ checkmate::assert_list(transformers, "teal_transform_module") |
||
73 | +19 |
- }+ |
||
74 | -+ | |||
20 | +! |
- ),+ ns <- NS(id) |
||
75 | -+ | |||
21 | +! |
- private = list(+ labels <- lapply(transformers, function(x) attr(x, "label")) |
||
76 | -+ | |||
22 | +! |
- dispatch_block = function(block_class) {+ ids <- get_unique_labels(labels) |
||
77 | +23 | ! |
- eval(str2lang(block_class))+ names(transformers) <- ids |
|
78 | +24 |
- }+ |
||
79 | -+ | |||
25 | +! |
- )+ lapply( |
||
80 | -+ | |||
26 | +! |
- )+ names(transformers), |
||
81 | -+ | |||
27 | +! |
-
+ function(name) { |
||
82 | -+ | |||
28 | +! |
- #' @title `TealSlicesBlock`+ data_mod <- transformers[[name]] |
||
83 | -+ | |||
29 | +! |
- #' @docType class+ wrapper_id <- ns(sprintf("wrapper_%s", name)) |
||
84 | -+ | |||
30 | +! |
- #' @description+ div( # todo: accordion? |
||
85 | +31 |
- #' Specialized `TealSlicesBlock` block for managing filter panel content in reports.+ # class .teal_validated changes the color of the boarder on error in ui_validate_reactive_teal_data |
||
86 | +32 |
- #' @keywords internal+ # For details see tealValidate.js file. |
||
87 | -+ | |||
33 | +! |
- TealSlicesBlock <- R6::R6Class( # nolint: object_name_linter.+ class = c(class, "teal_validated"), |
||
88 | -+ | |||
34 | +! |
- classname = "TealSlicesBlock",+ title = attr(data_mod, "label"), |
||
89 | -+ | |||
35 | +! |
- inherit = teal.reporter:::TextBlock,+ tags$span( |
||
90 | -+ | |||
36 | +! |
- public = list(+ class = "text-primary mb-4", |
||
91 | -+ | |||
37 | +! |
- #' @description Returns a `TealSlicesBlock` object.+ icon("fas fa-square-pen"), |
||
92 | -+ | |||
38 | +! |
- #'+ attr(data_mod, "label") |
||
93 | +39 |
- #' @details Returns a `TealSlicesBlock` object with no content and no parameters.+ ), |
||
94 | -+ | |||
40 | +! |
- #'+ tags$i( |
||
95 | -+ | |||
41 | +! |
- #' @param content (`teal_slices`) object returned from [teal_slices()] function.+ class = "remove pull-right fa fa-angle-down", |
||
96 | -+ | |||
42 | +! |
- #' @param style (`character(1)`) string specifying style to apply.+ style = "cursor: pointer;", |
||
97 | -+ | |||
43 | +! |
- #'+ title = "fold/expand transform panel", |
||
98 | -+ | |||
44 | +! |
- #' @return Object of class `TealSlicesBlock`, invisibly.+ onclick = sprintf("togglePanelItems(this, '%s', 'fa-angle-right', 'fa-angle-down');", wrapper_id) |
||
99 | +45 |
- #'+ ), |
||
100 | -+ | |||
46 | +! |
- initialize = function(content = teal_slices(), style = "verbatim") {+ div( |
||
101 | -9x | +|||
47 | +! |
- self$set_content(content)+ id = wrapper_id, |
||
102 | -8x | +|||
48 | +! |
- self$set_style(style)+ ui_teal_data(id = ns(name), data_module = transformers[[name]]$ui) |
||
103 | -8x | +|||
49 | +
- invisible(self)+ ) |
|||
104 | +50 |
- },+ ) |
||
105 | +51 |
-
+ } |
||
106 | +52 |
- #' @description Sets content of this `TealSlicesBlock`.+ ) |
||
107 | +53 |
- #' Sets content as `YAML` text which represents a list generated from `teal_slices`.+ } |
||
108 | +54 |
- #' The list displays limited number of fields from `teal_slice` objects, but this list is+ |
||
109 | +55 |
- #' sufficient to conclude which filters were applied.+ #' @rdname module_transform_data |
||
110 | +56 |
- #' When `selected` field in `teal_slice` object is a range, then it is displayed as a "min"+ srv_transform_data <- function(id, data, transformers = list(), modules, is_transformer_failed = reactiveValues()) { |
||
111 | -+ | |||
57 | +81x |
- #'+ checkmate::assert_string(id) |
||
112 | -+ | |||
58 | +81x |
- #'+ assert_reactive(data) |
||
113 | -+ | |||
59 | +81x |
- #' @param content (`teal_slices`) object returned from [teal_slices()] function.+ checkmate::assert_list(transformers, "teal_transform_module") |
||
114 | -+ | |||
60 | +81x |
- #' @return `self`, invisibly.+ checkmate::assert_class(modules, "teal_module") |
||
115 | -+ | |||
61 | +81x |
- set_content = function(content) {+ labels <- lapply(transformers, function(x) attr(x, "label")) |
||
116 | -9x | +62 | +81x |
- checkmate::assert_class(content, "teal_slices")+ ids <- get_unique_labels(labels) |
117 | -8x | +63 | +81x |
- if (length(content) != 0) {+ names(transformers) <- ids |
118 | -6x | +64 | +81x |
- states_list <- lapply(content, function(x) {+ moduleServer(id, function(input, output, session) { |
119 | -6x | +65 | +81x |
- x_list <- shiny::isolate(as.list(x))+ logger::log_debug("srv_teal_data_modules initializing.") |
120 | -6x | +66 | +81x |
- if (+ Reduce( |
121 | -6x | +67 | +81x |
- inherits(x_list$choices, c("integer", "numeric", "Date", "POSIXct", "POSIXlt")) &&+ function(previous_result, name) { |
122 | -6x | +68 | +20x |
- length(x_list$choices) == 2 &&+ srv_teal_data( |
123 | -6x | +69 | +20x |
- length(x_list$selected) == 2+ id = name, |
124 | -+ | |||
70 | +20x |
- ) {+ data_module = function(id) transformers[[name]]$server(id, previous_result), |
||
125 | -! | +|||
71 | +20x |
- x_list$range <- paste(x_list$selected, collapse = " - ")+ modules = modules, |
||
126 | -! | +|||
72 | +20x |
- x_list["selected"] <- NULL+ is_transformer_failed = is_transformer_failed |
||
127 | +73 |
- }+ )+ |
+ ||
74 | ++ |
+ }, |
||
128 | -6x | +75 | +81x |
- if (!is.null(x_list$arg)) {+ x = names(transformers), |
129 | -! | +|||
76 | +81x |
- x_list$arg <- if (x_list$arg == "subset") "Genes" else "Samples"+ init = data |
||
130 | +77 |
- }+ ) |
||
131 | +78 |
-
+ }) |
||
132 | -6x | +|||
79 | +
- x_list <- x_list[+ } |
|||
133 | -6x | +
1 | +
- c("dataname", "varname", "experiment", "arg", "expr", "selected", "range", "keep_na", "keep_inf")+ #' Create a `tdata` object |
||
134 | +2 |
- ]+ #' |
|
135 | -6x | +||
3 | +
- names(x_list) <- c(+ #' @description `r lifecycle::badge("superseded")` |
||
136 | -6x | +||
4 | +
- "Dataset name", "Variable name", "Experiment", "Filtering by", "Applied expression",+ #' |
||
137 | -6x | +||
5 | +
- "Selected Values", "Selected range", "Include NA values", "Include Inf values"+ #' Recent changes in `teal` cause modules to fail because modules expect a `tdata` object |
||
138 | +6 |
- )+ #' to be passed to the `data` argument but instead they receive a `teal_data` object, |
|
139 | +7 |
-
+ #' which is additionally wrapped in a reactive expression in the server functions. |
|
140 | -6x | +||
8 | +
- Filter(Negate(is.null), x_list)+ #' In order to easily adapt such modules without a proper refactor, |
||
141 | +9 |
- })+ #' use this function to downgrade the `data` argument. |
|
142 | +10 |
-
+ #' |
|
143 | -6x | +||
11 | +
- if (requireNamespace("yaml", quietly = TRUE)) {+ #' @name tdata |
||
144 | -6x | +||
12 | +
- super$set_content(yaml::as.yaml(states_list))+ #' @param ... ignored |
||
145 | +13 |
- } else {+ #' @return nothing |
|
146 | -! | +||
14 | +
- stop("yaml package is required to format the filter state list")+ NULL |
||
147 | +15 |
- }+ |
|
148 | +16 |
- }+ #' @rdname tdata |
|
149 | -8x | +||
17 | +
- private$teal_slices <- content+ #' @export |
||
150 | -8x | +||
18 | +
- invisible(self)+ new_tdata <- function(...) {+ |
+ ||
19 | +! | +
+ .deprecate_tdata_msg() |
|
151 | +20 |
- },+ } |
|
152 | +21 |
- #' @description Create the `TealSlicesBlock` from a list.+ |
|
153 | +22 |
- #'+ #' @rdname tdata |
|
154 | +23 |
- #' @param x (`named list`) with two fields `text` and `style`.+ #' @export |
|
155 | +24 |
- #' Use the `get_available_styles` method to get all possible styles.+ tdata2env <- function(...) {+ |
+ |
25 | +! | +
+ .deprecate_tdata_msg() |
|
156 | +26 |
- #'+ } |
|
157 | +27 |
- #' @return `self`, invisibly.+ |
|
158 | +28 |
- #' @examples+ #' @rdname tdata |
|
159 | +29 |
- #' TealSlicesBlock <- getFromNamespace("TealSlicesBlock", "teal")+ #' @export |
|
160 | +30 |
- #' block <- TealSlicesBlock$new()+ get_code_tdata <- function(...) {+ |
+ |
31 | +! | +
+ .deprecate_tdata_msg()+ |
+ |
32 | ++ |
+ } |
|
161 | +33 |
- #' block$from_list(list(text = "sth", style = "default"))+ |
|
162 | +34 |
- #'+ #' @rdname tdata |
|
163 | +35 |
- from_list = function(x) {+ #' @export |
|
164 | -1x | +||
36 | +
- checkmate::assert_list(x)+ join_keys.tdata <- function(...) { |
||
165 | -1x | +||
37 | +! |
- checkmate::assert_names(names(x), must.include = c("text", "style"))+ .deprecate_tdata_msg() |
|
166 | -1x | +||
38 | +
- super$set_content(x$text)+ } |
||
167 | -1x | +||
39 | +
- super$set_style(x$style)+ |
||
168 | -1x | +||
40 | +
- invisible(self)+ #' @rdname tdata |
||
169 | +41 |
- },+ #' @export |
|
170 | +42 |
- #' @description Convert the `TealSlicesBlock` to a list.+ get_metadata <- function(...) { |
|
171 | -+ | ||
43 | +! |
- #'+ .deprecate_tdata_msg() |
|
172 | +44 |
- #' @return `named list` with a text and style.+ } |
|
173 | +45 |
- #' @examples+ |
|
174 | +46 |
- #' TealSlicesBlock <- getFromNamespace("TealSlicesBlock", "teal")+ #' @rdname tdata |
|
175 | +47 |
- #' block <- TealSlicesBlock$new()+ #' @export |
|
176 | +48 |
- #' block$to_list()+ as_tdata <- function(...) { |
|
177 | -+ | ||
49 | +! |
- #'+ .deprecate_tdata_msg() |
|
178 | +50 |
- to_list = function() {+ } |
|
179 | -2x | +||
51 | +
- content <- self$get_content()+ |
||
180 | -2x | +||
52 | +
- list(+ |
||
181 | -2x | +||
53 | +
- text = if (length(content)) content else "",+ .deprecate_tdata_msg <- function() { |
||
182 | -2x | +||
54 | +! |
- style = self$get_style()+ lifecycle::deprecate_stop( |
|
183 | -+ | ||
55 | +! |
- )+ when = "0.16", |
|
184 | -+ | ||
56 | +! |
- }+ what = "tdata()", |
|
185 | -+ | ||
57 | +! |
- ),+ details = paste( |
|
186 | -+ | ||
58 | +! |
- private = list(+ "tdata has been removed in favour of `teal_data`.\n", |
|
187 | -+ | ||
59 | +! |
- style = "verbatim",+ "Please follow migration instructions https://github.com/insightsengineering/teal/discussions/987." |
|
188 | +60 |
- teal_slices = NULL # teal_slices+ ) |
|
189 | +61 |
) |
|
190 | +62 |
- )+ } |
1 |
- #' Data module for `teal` applications+ #' Send input validation messages to output |
||
3 |
- #' @description+ #' Captures messages from `InputValidator` objects and collates them |
||
4 |
- #' `r lifecycle::badge("experimental")`+ #' into one message passed to `validate`. |
||
6 |
- #' Create a `teal_data_module` object and evaluate code on it with history tracking.+ #' `shiny::validate` is used to withhold rendering of an output element until |
||
7 |
- #'+ #' certain conditions are met and to print a validation message in place |
||
8 |
- #' @details+ #' of the output element. |
||
9 |
- #' `teal_data_module` creates a `shiny` module to interactively supply or modify data in a `teal` application.+ #' `shinyvalidate::InputValidator` allows to validate input elements |
||
10 |
- #' The module allows for running any code (creation _and_ some modification) after the app starts or reloads.+ #' and to display specific messages in their respective input widgets. |
||
11 |
- #' The body of the server function will be run in the app rather than in the global environment.+ #' `validate_inputs` provides a hybrid solution. |
||
12 |
- #' This means it will be run every time the app starts, so use sparingly.+ #' Given an `InputValidator` object, messages corresponding to inputs that fail validation |
||
13 |
- #'+ #' are extracted and placed in one validation message that is passed to a `validate`/`need` call. |
||
14 |
- #' Pass this module instead of a `teal_data` object in a call to [init()].+ #' This way the input `validator` messages are repeated in the output. |
||
15 |
- #' Note that the server function must always return a `teal_data` object wrapped in a reactive expression.+ #' |
||
16 |
- #'+ #' The `...` argument accepts any number of `InputValidator` objects |
||
17 |
- #' See vignette `vignette("data-as-shiny-module", package = "teal")` for more details.+ #' or a nested list of such objects. |
||
18 |
- #'+ #' If `validators` are passed directly, all their messages are printed together |
||
19 |
- #' @param ui (`function(id)`)+ #' under one (optional) header message specified by `header`. If a list is passed, |
||
20 |
- #' `shiny` module UI function; must only take `id` argument+ #' messages are grouped by `validator`. The list's names are used as headers |
||
21 |
- #' @param server (`function(id)`)+ #' for their respective message groups. |
||
22 |
- #' `shiny` module server function; must only take `id` argument;+ #' If neither of the nested list elements is named, a header message is taken from `header`. |
||
23 |
- #' must return reactive expression containing `teal_data` object+ #' |
||
24 |
- #' @param label (`character(1)`) Label of the module.+ #' @param ... either any number of `InputValidator` objects |
||
25 |
- #' @param once (`logical(1)`)+ #' or an optionally named, possibly nested `list` of `InputValidator` |
||
26 |
- #' If `TRUE`, the data module will be shown only once and will disappear after successful data loading.+ #' objects, see `Details` |
||
27 |
- #' App user will no longer be able to interact with this module anymore.+ #' @param header (`character(1)`) generic validation message; set to NULL to omit |
||
28 |
- #' If `FALSE`, the data module can be reused multiple times.+ #' |
||
29 |
- #' App user will be able to interact and change the data output from the module multiple times.+ #' @return |
||
30 |
- #'+ #' Returns NULL if the final validation call passes and a `shiny.silent.error` if it fails. |
||
31 |
- #' @return+ #' |
||
32 |
- #' `teal_data_module` returns a list of class `teal_data_module` containing two elements, `ui` and+ #' @seealso [`shinyvalidate::InputValidator`], [`shiny::validate`] |
||
33 |
- #' `server` provided via arguments.+ #' |
||
34 |
- #'+ #' @examplesIf require("shinyvalidate") |
||
35 |
- #' @examples+ #' library(shiny) |
||
36 |
- #' tdm <- teal_data_module(+ #' library(shinyvalidate) |
||
37 |
- #' ui = function(id) {+ #' |
||
38 |
- #' ns <- NS(id)+ #' ui <- fluidPage( |
||
39 |
- #' actionButton(ns("submit"), label = "Load data")+ #' selectInput("method", "validation method", c("sequential", "combined", "grouped")), |
||
40 |
- #' },+ #' sidebarLayout( |
||
41 |
- #' server = function(id) {+ #' sidebarPanel( |
||
42 |
- #' moduleServer(id, function(input, output, session) {+ #' selectInput("letter", "select a letter:", c(letters[1:3], LETTERS[4:6])), |
||
43 |
- #' eventReactive(input$submit, {+ #' selectInput("number", "select a number:", 1:6), |
||
44 |
- #' data <- within(+ #' tags$br(), |
||
45 |
- #' teal_data(),+ #' selectInput("color", "select a color:", |
||
46 |
- #' {+ #' c("black", "indianred2", "springgreen2", "cornflowerblue"), |
||
47 |
- #' dataset1 <- iris+ #' multiple = TRUE |
||
48 |
- #' dataset2 <- mtcars+ #' ), |
||
49 |
- #' }+ #' sliderInput("size", "select point size:", |
||
50 |
- #' )+ #' min = 0.1, max = 4, value = 0.25 |
||
51 |
- #' datanames(data) <- c("dataset1", "dataset2")+ #' ) |
||
52 |
- #'+ #' ), |
||
53 |
- #' data+ #' mainPanel(plotOutput("plot")) |
||
54 |
- #' })+ #' ) |
||
55 |
- #' })+ #' ) |
||
56 |
- #' }+ #' |
||
57 |
- #' )+ #' server <- function(input, output) { |
||
58 |
- #'+ #' # set up input validation |
||
59 |
- #' @name teal_data_module+ #' iv <- InputValidator$new() |
||
60 |
- #' @seealso [`teal.data::teal_data-class`], [teal.code::qenv()]+ #' iv$add_rule("letter", sv_in_set(LETTERS, "choose a capital letter")) |
||
61 |
- #'+ #' iv$add_rule("number", function(x) { |
||
62 |
- #' @export+ #' if (as.integer(x) %% 2L == 1L) "choose an even number" |
||
63 |
- teal_data_module <- function(ui, server, label = "data module", once = TRUE) {+ #' }) |
||
64 | -33x | +
- checkmate::assert_function(ui, args = "id", nargs = 1)+ #' iv$enable() |
|
65 | -32x | +
- checkmate::assert_function(server, args = "id", nargs = 1)+ #' # more input validation |
|
66 | -30x | +
- checkmate::assert_string(label)+ #' iv_par <- InputValidator$new() |
|
67 | -30x | +
- checkmate::assert_flag(once)+ #' iv_par$add_rule("color", sv_required(message = "choose a color")) |
|
68 | -30x | +
- structure(+ #' iv_par$add_rule("color", function(x) { |
|
69 | -30x | +
- list(+ #' if (length(x) > 1L) "choose only one color" |
|
70 | -30x | +
- ui = ui,+ #' }) |
|
71 | -30x | +
- server = function(id) {+ #' iv_par$add_rule( |
|
72 | -23x | +
- data_out <- server(id)+ #' "size", |
|
73 | -22x | +
- decorate_err_msg(+ #' sv_between( |
|
74 | -22x | +
- assert_reactive(data_out),+ #' left = 0.5, right = 3, |
|
75 | -22x | +
- pre = sprintf("From: 'teal_data_module()':\nA 'teal_data_module' with \"%s\" label:", label),+ #' message_fmt = "choose a value between {left} and {right}" |
|
76 | -22x | +
- post = "Please make sure that this module returns a 'reactive` object containing 'teal_data' class of object." # nolint: line_length_linter.+ #' ) |
|
77 |
- )+ #' ) |
||
78 |
- }+ #' iv_par$enable() |
||
79 |
- ),+ #' |
||
80 | -30x | +
- label = label,+ #' output$plot <- renderPlot({ |
|
81 | -30x | +
- class = "teal_data_module",+ #' # validate output |
|
82 | -30x | +
- once = once+ #' switch(input[["method"]], |
|
83 |
- )+ #' "sequential" = { |
||
84 |
- }+ #' validate_inputs(iv) |
||
85 |
-
+ #' validate_inputs(iv_par, header = "Set proper graphical parameters") |
||
86 |
- #' Data module for `teal` transformers.+ #' }, |
||
87 |
- #'+ #' "combined" = validate_inputs(iv, iv_par), |
||
88 |
- #' @description+ #' "grouped" = validate_inputs(list( |
||
89 |
- #' `r lifecycle::badge("experimental")`+ #' "Some inputs require attention" = iv, |
||
90 |
- #'+ #' "Set proper graphical parameters" = iv_par |
||
91 |
- #' Create a `teal_data_module` object for custom transformation of data for pre-processing+ #' )) |
||
92 |
- #' before passing the data into the module.+ #' ) |
||
94 |
- #' @details+ #' plot(faithful$eruptions ~ faithful$waiting, |
||
95 |
- #' `teal_transform_module` creates a [`teal_data_module`] object to transform data in a `teal`+ #' las = 1, pch = 16, |
||
96 |
- #' application. This transformation happens after the data has passed through the filtering activity+ #' col = input[["color"]], cex = input[["size"]] |
||
97 |
- #' in teal. The transformed data is then sent to the server of the [teal_module()].+ #' ) |
||
98 |
- #'+ #' }) |
||
99 |
- #' See vignette `vignette("data-transform-as-shiny-module", package = "teal")` for more details.+ #' } |
||
101 |
- #'+ #' if (interactive()) { |
||
102 |
- #' @inheritParams teal_data_module+ #' shinyApp(ui, server) |
||
103 |
- #' @param server (`function(id, data)`)+ #' } |
||
104 |
- #' `shiny` module server function; that takes `id` and `data` argument,+ #' |
||
105 |
- #' where the `id` is the module id and `data` is the reactive `teal_data` input.+ #' @export |
||
106 |
- #' The server function must return reactive expression containing `teal_data` object.+ #' |
||
107 |
- #'+ validate_inputs <- function(..., header = "Some inputs require attention") { |
||
108 | -+ | 36x |
- #' The server function definition should not use `eventReactive` as it may lead to+ dots <- list(...) |
109 | -+ | 2x |
- #' unexpected behavior.+ if (!is_validators(dots)) stop("validate_inputs accepts validators or a list thereof") |
110 |
- #' See `vignettes("data-transform-as-shiny-module")` for more information.+ |
||
111 | -+ | 34x |
- #' @param datanames (`character`)+ messages <- extract_validator(dots, header) |
112 | -+ | 34x |
- #' Names of the datasets that are relevant for this module to evaluate. If set to `character(0)`+ failings <- if (!any_names(dots)) { |
113 | -+ | 29x |
- #' then module would receive [modules()] `datanames`.+ add_header(messages, header) |
114 |
- #' @examples+ } else { |
||
115 | -+ | 5x |
- #' my_transformers <- list(+ unlist(messages) |
116 |
- #' teal_transform_module(+ } |
||
117 |
- #' label = "Custom transform for iris",+ |
||
118 | -+ | 34x |
- #' datanames = "iris",+ shiny::validate(shiny::need(is.null(failings), failings)) |
119 |
- #' ui = function(id) {+ } |
||
120 |
- #' ns <- NS(id)+ |
||
121 |
- #' tags$div(+ ### internal functions |
||
122 |
- #' numericInput(ns("n_rows"), "Subset n rows", value = 6, min = 1, max = 150, step = 1)+ |
||
123 |
- #' )+ #' @noRd |
||
124 |
- #' },+ #' @keywords internal |
||
125 |
- #' server = function(id, data) {+ # recursive object type test |
||
126 |
- #' moduleServer(id, function(input, output, session) {+ # returns logical of length 1 |
||
127 |
- #' reactive({+ is_validators <- function(x) { |
||
128 | -+ | 118x |
- #' within(data(),+ all(if (is.list(x)) unlist(lapply(x, is_validators)) else inherits(x, "InputValidator")) |
129 |
- #' {+ } |
||
130 |
- #' iris <- head(iris, num_rows)+ |
||
131 |
- #' },+ #' @noRd |
||
132 |
- #' num_rows = input$n_rows+ #' @keywords internal |
||
133 |
- #' )+ # test if an InputValidator object is enabled |
||
134 |
- #' })+ # returns logical of length 1 |
||
135 |
- #' })+ # official method requested at https://github.com/rstudio/shinyvalidate/issues/64 |
||
136 |
- #' }+ validator_enabled <- function(x) { |
||
137 | -+ | 49x |
- #' )+ x$.__enclos_env__$private$enabled |
138 |
- #' )+ } |
||
139 |
- #'+ |
||
140 |
- #' @name teal_transform_module+ #' Recursively extract messages from validator list |
||
141 |
- #'+ #' @return A character vector or a list of character vectors, possibly nested and named. |
||
142 |
- #' @export+ #' @noRd |
||
143 |
- teal_transform_module <- function(ui = function(id) NULL,+ #' @keywords internal |
||
144 |
- server = function(id, data) data,+ extract_validator <- function(iv, header) { |
||
145 | -+ | 113x |
- label = "transform module",+ if (inherits(iv, "InputValidator")) { |
146 | -+ | 49x |
- datanames = character(0)) {+ add_header(gather_messages(iv), header) |
147 | -20x | +
- checkmate::assert_function(ui, args = "id", nargs = 1)+ } else { |
|
148 | -20x | +58x |
- checkmate::assert_function(server, args = c("id", "data"), nargs = 2)+ if (is.null(names(iv))) names(iv) <- rep("", length(iv)) |
149 | -20x | +64x |
- checkmate::assert_string(label)+ mapply(extract_validator, iv = iv, header = names(iv), SIMPLIFY = FALSE) |
150 | -20x | +
- checkmate::assert_character(datanames)+ } |
|
151 | -20x | +
- if (identical(datanames, "all")) {+ } |
|
152 | -1x | +
- stop(+ |
|
153 | -1x | +
- "teal_transform_module can't have datanames property equal to 'all'. Set `datanames = character(0)` instead.",+ #' Collate failing messages from validator. |
|
154 | -1x | +
- call. = FALSE+ #' @return `list` |
|
155 |
- )+ #' @noRd |
||
156 |
- }+ #' @keywords internal |
||
157 | -19x | +
- structure(+ gather_messages <- function(iv) { |
|
158 | -19x | +49x |
- list(+ if (validator_enabled(iv)) { |
159 | -19x | +46x |
- ui = ui,+ status <- iv$validate() |
160 | -19x | +46x |
- server = function(id, data) {+ failing_inputs <- Filter(Negate(is.null), status) |
161 | -20x | +46x |
- data_out <- server(id, data)+ unique(lapply(failing_inputs, function(x) x[["message"]])) |
162 |
-
+ } else { |
||
163 | -20x | +3x |
- if (inherits(data_out, "reactive.event")) {+ warning("Validator is disabled and will be omitted.") |
164 | -+ | 3x |
- # This warning message partially detects when `eventReactive` is used in `data_module`.+ list() |
165 | -1x | +
- warning(+ } |
|
166 | -1x | +
- "teal_transform_module() ",+ } |
|
167 | -1x | +
- "Using eventReactive in teal_transform module server code should be avoided as it ",+ |
|
168 | -1x | +
- "may lead to unexpected behavior. See the vignettes for more information ",+ #' Add optional header to failing messages |
|
169 | -1x | +
- "(`vignette(\"data-transform-as-shiny-module\", package = \"teal\")`).",+ #' @noRd |
|
170 | -1x | +
- call. = FALSE+ #' @keywords internal |
|
171 |
- )+ add_header <- function(messages, header = "") { |
||
172 | -+ | 78x |
- }+ ans <- unlist(messages) |
173 | -+ | 78x |
-
+ if (length(ans) != 0L && isTRUE(nchar(header) > 0L)) { |
174 | -20x | +31x |
- decorate_err_msg(+ ans <- c(paste0(header, "\n"), ans, "\n") |
175 | -20x | +
- assert_reactive(data_out),+ } |
|
176 | -20x | +78x |
- pre = sprintf("From: 'teal_transform_module()':\nA 'teal_transform_module' with \"%s\" label:", label),+ ans |
177 | -20x | +
- post = "Please make sure that this module returns a 'reactive` object containing 'teal_data' class of object." # nolint: line_length_linter.+ } |
|
178 |
- )+ |
||
179 |
- }+ #' Recursively check if the object contains a named list |
||
180 |
- ),+ #' @noRd |
||
181 | -19x | +
- label = label,+ #' @keywords internal |
|
182 | -19x | +
- datanames = datanames,+ any_names <- function(x) { |
|
183 | -19x | +103x |
- class = c("teal_transform_module", "teal_data_module")+ any( |
184 | -+ | 103x |
- )+ if (is.list(x)) { |
185 | -+ | 58x |
- }+ if (!is.null(names(x)) && any(names(x) != "")) TRUE else unlist(lapply(x, any_names)) |
186 |
-
+ } else { |
||
187 | -+ | 40x |
-
+ FALSE |
188 |
- #' Extract all `transformers` from `modules`.+ } |
||
189 |
- #'+ ) |
||
190 |
- #' @param modules `teal_modules` or `teal_module`+ } |
191 | +1 |
- #' @return A list of `teal_transform_module` nested in the same way as input `modules`.+ #' Data module for `teal` applications |
|
192 | +2 |
- #' @keywords internal+ #' |
|
193 | +3 |
- extract_transformers <- function(modules) {+ #' @description |
|
194 | -6x | +||
4 | +
- if (inherits(modules, "teal_module")) {+ #' `r lifecycle::badge("experimental")` |
||
195 | -3x | +||
5 | +
- modules$transformers+ #' |
||
196 | -3x | +||
6 | +
- } else if (inherits(modules, "teal_modules")) {+ #' Create a `teal_data_module` object and evaluate code on it with history tracking. |
||
197 | -3x | +||
7 | +
- lapply(modules$children, extract_transformers)+ #' |
||
198 | +8 |
- }+ #' @details |
|
199 | +9 |
- }+ #' `teal_data_module` creates a `shiny` module to interactively supply or modify data in a `teal` application. |
1 | +10 |
- .onLoad <- function(libname, pkgname) {+ #' The module allows for running any code (creation _and_ some modification) after the app starts or reloads. |
|
2 | +11 |
- # adapted from https://github.com/r-lib/devtools/blob/master/R/zzz.R+ #' The body of the server function will be run in the app rather than in the global environment. |
|
3 | +12 |
-
+ #' This means it will be run every time the app starts, so use sparingly. |
|
4 | -! | +||
13 | +
- teal_default_options <- list(+ #' |
||
5 | -! | +||
14 | +
- teal.show_js_log = FALSE,+ #' Pass this module instead of a `teal_data` object in a call to [init()]. |
||
6 | -! | +||
15 | +
- teal.lockfile.mode = "auto",+ #' Note that the server function must always return a `teal_data` object wrapped in a reactive expression. |
||
7 | -! | +||
16 | +
- shiny.sanitize.errors = FALSE+ #' |
||
8 | +17 |
- )+ #' See vignette `vignette("data-as-shiny-module", package = "teal")` for more details. |
|
9 | +18 |
-
+ #' |
|
10 | -! | +||
19 | +
- op <- options()+ #' @param ui (`function(id)`) |
||
11 | -! | +||
20 | +
- toset <- !(names(teal_default_options) %in% names(op))+ #' `shiny` module UI function; must only take `id` argument |
||
12 | -! | +||
21 | +
- if (any(toset)) options(teal_default_options[toset])+ #' @param server (`function(id)`) |
||
13 | +22 |
-
+ #' `shiny` module server function; must only take `id` argument; |
|
14 | +23 |
- # Set up the teal logger instance+ #' must return reactive expression containing `teal_data` object |
|
15 | -! | +||
24 | +
- teal.logger::register_logger("teal")+ #' @param label (`character(1)`) Label of the module. |
||
16 | -! | +||
25 | +
- teal.logger::register_handlers("teal")+ #' @param once (`logical(1)`) |
||
17 | +26 |
-
+ #' If `TRUE`, the data module will be shown only once and will disappear after successful data loading. |
|
18 | -! | +||
27 | +
- invisible()+ #' App user will no longer be able to interact with this module anymore. |
||
19 | +28 |
- }+ #' If `FALSE`, the data module can be reused multiple times. |
|
20 | +29 |
-
+ #' App user will be able to interact and change the data output from the module multiple times. |
|
21 | +30 |
- .onAttach <- function(libname, pkgname) {+ #' |
|
22 | -2x | +||
31 | +
- packageStartupMessage(+ #' @return |
||
23 | -2x | +||
32 | +
- "\nYou are using teal version ",+ #' `teal_data_module` returns a list of class `teal_data_module` containing two elements, `ui` and |
||
24 | +33 |
- # `system.file` uses the `shim` of `system.file` by `teal`+ #' `server` provided via arguments. |
|
25 | +34 |
- # we avoid `desc` dependency here to get the version+ #' |
|
26 | -2x | +||
35 | +
- read.dcf(system.file("DESCRIPTION", package = "teal"))[, "Version"]+ #' @examples+ |
+ ||
36 | ++ |
+ #' tdm <- teal_data_module(+ |
+ |
37 | ++ |
+ #' ui = function(id) {+ |
+ |
38 | ++ |
+ #' ns <- NS(id)+ |
+ |
39 | ++ |
+ #' actionButton(ns("submit"), label = "Load data") |
|
27 | +40 |
- )+ #' }, |
|
28 | +41 |
- }+ #' server = function(id) { |
|
29 | +42 |
-
+ #' moduleServer(id, function(input, output, session) { |
|
30 | +43 |
- # This one is here because setdiff_teal_slice should not be exported from teal.slice.+ #' eventReactive(input$submit, { |
|
31 | +44 |
- setdiff_teal_slices <- getFromNamespace("setdiff_teal_slices", "teal.slice")+ #' data <- within( |
|
32 | +45 |
- # This one is here because it is needed by c.teal_slices but we don't want it exported from teal.slice.+ #' teal_data(), |
|
33 | +46 |
- coalesce_r <- getFromNamespace("coalesce_r", "teal.slice")+ #' { |
|
34 | +47 |
- # all *Block objects are private in teal.reporter+ #' dataset1 <- iris |
|
35 | +48 |
- RcodeBlock <- getFromNamespace("RcodeBlock", "teal.reporter") # nolint: object_name.+ #' dataset2 <- mtcars |
|
36 | +49 |
-
+ #' } |
|
37 | +50 |
- # Use non-exported function(s) from teal.code+ #' ) |
|
38 | +51 |
- # This one is here because lang2calls should not be exported from teal.code+ #' |
|
39 | +52 |
- lang2calls <- getFromNamespace("lang2calls", "teal.code")+ #' data |
1 | +53 |
- #' Store and restore `teal_slices` object+ #' }) |
||
2 | +54 |
- #'+ #' }) |
||
3 | +55 |
- #' Functions that write a `teal_slices` object to a file in the `JSON` format,+ #' } |
||
4 | +56 |
- #' and also restore the object from disk.+ #' ) |
||
5 | +57 |
#' |
||
6 | +58 |
- #' Date and date time objects are stored in the following formats:+ #' @name teal_data_module |
||
7 | +59 |
- #'+ #' @seealso [`teal.data::teal_data-class`], [teal.code::qenv()] |
||
8 | +60 |
- #' - `Date` class is converted to the `"ISO8601"` standard (`YYYY-MM-DD`).+ #' |
||
9 | +61 |
- #' - `POSIX*t` classes are converted to character by using+ #' @export |
||
10 | +62 |
- #' `format.POSIX*t(usetz = TRUE, tz = "UTC")` (`YYYY-MM-DD HH:MM:SS UTC`, where+ teal_data_module <- function(ui, server, label = "data module", once = TRUE) { |
||
11 | -+ | |||
63 | +33x |
- #' `UTC` is the `Coordinated Universal Time` timezone short-code).+ checkmate::assert_function(ui, args = "id", nargs = 1) |
||
12 | -+ | |||
64 | +32x |
- #'+ checkmate::assert_function(server, args = "id", nargs = 1) |
||
13 | -+ | |||
65 | +30x |
- #' This format is assumed during `slices_restore`. All `POSIX*t` objects in+ checkmate::assert_string(label) |
||
14 | -+ | |||
66 | +30x |
- #' `selected` or `choices` fields of `teal_slice` objects are always printed in+ checkmate::assert_flag(once) |
||
15 | -+ | |||
67 | +30x |
- #' `UTC` timezone as well.+ structure( |
||
16 | -+ | |||
68 | +30x |
- #'+ list( |
||
17 | -+ | |||
69 | +30x |
- #' @param tss (`teal_slices`) object to be stored.+ ui = ui, |
||
18 | -+ | |||
70 | +30x |
- #' @param file (`character(1)`) file path where `teal_slices` object will be+ server = function(id) { |
||
19 | -+ | |||
71 | +23x |
- #' saved and restored. The file extension should be `".json"`.+ data_out <- server(id) |
||
20 | -+ | |||
72 | +22x |
- #'+ decorate_err_msg( |
||
21 | -+ | |||
73 | +22x |
- #' @return `slices_store` returns `NULL`, invisibly.+ assert_reactive(data_out), |
||
22 | -+ | |||
74 | +22x |
- #'+ pre = sprintf("From: 'teal_data_module()':\nA 'teal_data_module' with \"%s\" label:", label), |
||
23 | -+ | |||
75 | +22x |
- #' @seealso [teal_slices()]+ post = "Please make sure that this module returns a 'reactive` object containing 'teal_data' class of object." # nolint: line_length_linter. |
||
24 | +76 |
- #'+ ) |
||
25 | +77 |
- #' @keywords internal+ } |
||
26 | +78 |
- #'+ ), |
||
27 | -+ | |||
79 | +30x |
- slices_store <- function(tss, file) {+ label = label, |
||
28 | -9x | +80 | +30x |
- checkmate::assert_class(tss, "teal_slices")+ class = "teal_data_module", |
29 | -9x | +81 | +30x |
- checkmate::assert_path_for_output(file, overwrite = TRUE, extension = "json")+ once = once |
30 | +82 | ++ |
+ )+ |
+ |
83 | ++ |
+ }+ |
+ ||
84 | ||||
31 | -9x | +|||
85 | +
- cat(format(tss, trim_lines = FALSE), "\n", file = file)+ #' Data module for `teal` transformers. |
|||
32 | +86 |
- }+ #' |
||
33 | +87 |
-
+ #' @description |
||
34 | +88 |
- #' @rdname slices_store+ #' `r lifecycle::badge("experimental")` |
||
35 | +89 |
- #' @return `slices_restore` returns a `teal_slices` object restored from the file.+ #' |
||
36 | +90 |
- #' @keywords internal+ #' Create a `teal_data_module` object for custom transformation of data for pre-processing |
||
37 | +91 |
- slices_restore <- function(file) {+ #' before passing the data into the module. |
||
38 | -9x | +|||
92 | +
- checkmate::assert_file_exists(file, access = "r", extension = "json")+ #' |
|||
39 | +93 |
-
+ #' @details |
||
40 | -9x | +|||
94 | +
- tss_json <- jsonlite::fromJSON(file, simplifyDataFrame = FALSE)+ #' `teal_transform_module` creates a [`teal_data_module`] object to transform data in a `teal` |
|||
41 | -9x | +|||
95 | +
- tss_json$slices <-+ #' application. This transformation happens after the data has passed through the filtering activity |
|||
42 | -9x | +|||
96 | +
- lapply(tss_json$slices, function(slice) {+ #' in teal. The transformed data is then sent to the server of the [teal_module()]. |
|||
43 | -9x | +|||
97 | +
- for (field in c("selected", "choices")) {+ #' |
|||
44 | -18x | +|||
98 | +
- if (!is.null(slice[[field]])) {+ #' See vignette `vignette("data-transform-as-shiny-module", package = "teal")` for more details. |
|||
45 | -12x | +|||
99 | +
- if (length(slice[[field]]) > 0) {+ #' |
|||
46 | -9x | +|||
100 | +
- date_partial_regex <- "^[0-9]{4}-[0-9]{2}-[0-9]{2}"+ #' |
|||
47 | -9x | +|||
101 | +
- time_stamp_regex <- paste0(date_partial_regex, "\\s[0-9]{2}:[0-9]{2}:[0-9]{2}\\sUTC$")+ #' @inheritParams teal_data_module |
|||
48 | +102 |
-
+ #' @param server (`function(id, data)`) |
||
49 | -9x | +|||
103 | +
- slice[[field]] <-+ #' `shiny` module server function; that takes `id` and `data` argument, |
|||
50 | -9x | +|||
104 | +
- if (all(grepl(paste0(date_partial_regex, "$"), slice[[field]]))) {+ #' where the `id` is the module id and `data` is the reactive `teal_data` input. |
|||
51 | -3x | +|||
105 | +
- as.Date(slice[[field]])+ #' The server function must return reactive expression containing `teal_data` object. |
|||
52 | -9x | +|||
106 | +
- } else if (all(grepl(time_stamp_regex, slice[[field]]))) {+ #' |
|||
53 | -3x | +|||
107 | +
- as.POSIXct(slice[[field]], tz = "UTC")+ #' The server function definition should not use `eventReactive` as it may lead to |
|||
54 | +108 |
- } else {+ #' unexpected behavior. |
||
55 | -3x | +|||
109 | +
- slice[[field]]+ #' See `vignettes("data-transform-as-shiny-module")` for more information. |
|||
56 | +110 |
- }+ #' @param datanames (`character`) |
||
57 | +111 |
- } else {+ #' Names of the datasets that are relevant for this module to evaluate. If set to `character(0)` |
||
58 | -3x | +|||
112 | +
- slice[[field]] <- character(0)+ #' then module would receive [modules()] `datanames`. |
|||
59 | +113 |
- }+ #' @examples |
||
60 | +114 |
- }+ #' my_transformers <- list( |
||
61 | +115 |
- }+ #' teal_transform_module( |
||
62 | -9x | +|||
116 | +
- slice+ #' label = "Custom transform for iris", |
|||
63 | +117 |
- })+ #' datanames = "iris", |
||
64 | +118 |
-
+ #' ui = function(id) { |
||
65 | -9x | +|||
119 | +
- tss_elements <- lapply(tss_json$slices, as.teal_slice)+ #' ns <- NS(id) |
|||
66 | +120 |
-
+ #' tags$div( |
||
67 | -9x | +|||
121 | +
- do.call(teal_slices, c(tss_elements, tss_json$attributes))+ #' numericInput(ns("n_rows"), "Subset n rows", value = 6, min = 1, max = 150, step = 1) |
|||
68 | +122 |
- }+ #' ) |
1 | +123 |
- #' Module to transform `reactive` `teal_data`+ #' }, |
||
2 | +124 |
- #'+ #' server = function(id, data) { |
||
3 | +125 |
- #' Module calls multiple [`module_teal_data`] in sequence so that `reactive teal_data` output+ #' moduleServer(id, function(input, output, session) { |
||
4 | +126 |
- #' from one module is handed over to the following module's input.+ #' reactive({ |
||
5 | +127 |
- #'+ #' within(data(),+ |
+ ||
128 | ++ |
+ #' { |
||
6 | +129 |
- #' @inheritParams module_teal_data+ #' iris <- head(iris, num_rows) |
||
7 | +130 |
- #' @inheritParams teal_modules+ #' }, |
||
8 | +131 |
- #' @return `reactive` `teal_data`+ #' num_rows = input$n_rows |
||
9 | +132 |
- #'+ #' ) |
||
10 | +133 |
- #'+ #' }) |
||
11 | +134 |
- #' @name module_transform_data+ #' }) |
||
12 | +135 |
- #' @keywords internal+ #' } |
||
13 | +136 |
- NULL+ #' ) |
||
14 | +137 |
-
+ #' ) |
||
15 | +138 |
- #' @rdname module_transform_data+ #' |
||
16 | +139 |
- ui_transform_data <- function(id, transformers = list(), class = "well") {+ #' @name teal_transform_module |
||
17 | -! | +|||
140 | +
- checkmate::assert_string(id)+ #' |
|||
18 | -! | +|||
141 | +
- checkmate::assert_list(transformers, "teal_transform_module")+ #' @export |
|||
19 | +142 |
-
+ teal_transform_module <- function(ui = function(id) NULL, |
||
20 | -! | +|||
143 | +
- ns <- NS(id)+ server = function(id, data) data, |
|||
21 | -! | +|||
144 | +
- labels <- lapply(transformers, function(x) attr(x, "label"))+ label = "transform module", |
|||
22 | -! | +|||
145 | +
- ids <- get_unique_labels(labels)+ datanames = character(0)) { |
|||
23 | -! | +|||
146 | +20x |
- names(transformers) <- ids+ checkmate::assert_function(ui, args = "id", nargs = 1) |
||
24 | -+ | |||
147 | +20x |
-
+ checkmate::assert_function(server, args = c("id", "data"), nargs = 2) |
||
25 | -! | +|||
148 | +20x |
- lapply(+ checkmate::assert_string(label) |
||
26 | -! | +|||
149 | +20x |
- names(transformers),+ checkmate::assert_character(datanames) |
||
27 | -! | +|||
150 | +20x |
- function(name) {+ if (identical(datanames, "all")) { |
||
28 | -! | +|||
151 | +1x |
- data_mod <- transformers[[name]]+ stop( |
||
29 | -! | +|||
152 | +1x |
- wrapper_id <- ns(sprintf("wrapper_%s", name))+ "teal_transform_module can't have datanames property equal to 'all'. Set `datanames = character(0)` instead.", |
||
30 | -! | +|||
153 | +1x |
- div( # todo: accordion?+ call. = FALSE |
||
31 | +154 |
- # class .teal_validated changes the color of the boarder on error in ui_validate_reactive_teal_data+ ) |
||
32 | +155 |
- # For details see tealValidate.js file.- |
- ||
33 | -! | -
- class = c(class, "teal_validated"),+ } |
||
34 | -! | +|||
156 | +19x |
- title = attr(data_mod, "label"),+ structure( |
||
35 | -! | +|||
157 | +19x |
- tags$span(+ list( |
||
36 | -! | +|||
158 | +19x |
- class = "text-primary mb-4",+ ui = ui, |
||
37 | -! | +|||
159 | +19x |
- icon("fas fa-square-pen"),+ server = function(id, data) { |
||
38 | -! | +|||
160 | +20x |
- attr(data_mod, "label")+ data_out <- server(id, data) |
||
39 | +161 |
- ),- |
- ||
40 | -! | -
- tags$i(- |
- ||
41 | -! | -
- class = "remove pull-right fa fa-angle-down",- |
- ||
42 | -! | -
- style = "cursor: pointer;",- |
- ||
43 | -! | -
- title = "fold/expand transform panel",+ |
||
44 | -! | +|||
162 | +20x |
- onclick = sprintf("togglePanelItems(this, '%s', 'fa-angle-right', 'fa-angle-down');", wrapper_id)+ if (inherits(data_out, "reactive.event")) { |
||
45 | +163 |
- ),+ # This warning message partially detects when `eventReactive` is used in `data_module`. |
||
46 | -! | +|||
164 | +1x |
- div(+ warning( |
||
47 | -! | +|||
165 | +1x |
- id = wrapper_id,+ "teal_transform_module() ", |
||
48 | -! | +|||
166 | +1x |
- ui_teal_data(id = ns(name), data_module = transformers[[name]]$ui)+ "Using eventReactive in teal_transform module server code should be avoided as it ", |
||
49 | -+ | |||
167 | +1x |
- )+ "may lead to unexpected behavior. See the vignettes for more information ", |
||
50 | -+ | |||
168 | +1x |
- )+ "(`vignette(\"data-transform-as-shiny-module\", package = \"teal\")`).", |
||
51 | -+ | |||
169 | +1x |
- }+ call. = FALSE |
||
52 | +170 |
- )+ ) |
||
53 | +171 |
- }+ } |
||
54 | +172 | |||
55 | -+ | |||
173 | +20x |
- #' @rdname module_transform_data+ decorate_err_msg( |
||
56 | -+ | |||
174 | +20x |
- srv_transform_data <- function(id, data, transformers = list(), modules, is_transformer_failed = reactiveValues()) {+ assert_reactive(data_out), |
||
57 | -81x | +175 | +20x |
- checkmate::assert_string(id)+ pre = sprintf("From: 'teal_transform_module()':\nA 'teal_transform_module' with \"%s\" label:", label), |
58 | -81x | +176 | +20x |
- assert_reactive(data)+ post = "Please make sure that this module returns a 'reactive` object containing 'teal_data' class of object." # nolint: line_length_linter. |
59 | -81x | +|||
177 | +
- checkmate::assert_list(transformers, "teal_transform_module")+ ) |
|||
60 | -81x | +|||
178 | +
- checkmate::assert_class(modules, "teal_module")+ } |
|||
61 | -81x | +|||
179 | +
- labels <- lapply(transformers, function(x) attr(x, "label"))+ ), |
|||
62 | -81x | +180 | +19x |
- ids <- get_unique_labels(labels)+ label = label, |
63 | -81x | +181 | +19x |
- names(transformers) <- ids+ datanames = datanames, |
64 | -81x | +182 | +19x |
- moduleServer(id, function(input, output, session) {+ class = c("teal_transform_module", "teal_data_module") |
65 | -81x | +|||
183 | +
- logger::log_debug("srv_teal_data_modules initializing.")+ ) |
|||
66 | -81x | +|||
184 | +
- Reduce(+ } |
|||
67 | -81x | +|||
185 | +
- function(previous_result, name) {+ |
|||
68 | -20x | +|||
186 | +
- srv_teal_data(+ |
|||
69 | -20x | +|||
187 | +
- id = name,+ #' Extract all `transformers` from `modules`. |
|||
70 | -20x | +|||
188 | +
- data_module = function(id) transformers[[name]]$server(id, previous_result),+ #' |
|||
71 | -20x | +|||
189 | +
- modules = modules,+ #' @param modules `teal_modules` or `teal_module` |
|||
72 | -20x | +|||
190 | +
- is_transformer_failed = is_transformer_failed+ #' @return A list of `teal_transform_module` nested in the same way as input `modules`. |
|||
73 | +191 |
- )+ #' @keywords internal |
||
74 | +192 |
- },+ extract_transformers <- function(modules) { |
||
75 | -81x | +193 | +6x |
- x = names(transformers),+ if (inherits(modules, "teal_module")) { |
76 | -81x | +194 | +3x |
- init = data+ modules$transformers |
77 | -+ | |||
195 | +3x |
- )+ } else if (inherits(modules, "teal_modules")) {+ |
+ ||
196 | +3x | +
+ lapply(modules$children, extract_transformers) |
||
78 | +197 |
- })+ } |
||
79 | +198 |
}@@ -45446,14 +44965,14 @@ teal coverage - 59.99% |
1 |
- #' Filter settings for `teal` applications+ #' Data Module for teal |
|||
3 |
- #' Specify initial filter states and filtering settings for a `teal` app.+ #' This module manages the `data` argument for `srv_teal`. The `teal` framework uses [teal_data()], |
|||
4 |
- #'+ #' which can be provided in various ways: |
|||
5 |
- #' Produces a `teal_slices` object.+ #' 1. Directly as a [teal.data::teal_data()] object. This will automatically convert it into a `reactive` `teal_data`. |
|||
6 |
- #' The `teal_slice` components will specify filter states that will be active when the app starts.+ #' 2. As a `reactive` object that returns a [teal.data::teal_data()] object. |
|||
7 |
- #' Attributes (created with the named arguments) will configure the way the app applies filters.+ #' |
|||
8 |
- #' See argument descriptions for details.+ #' @details |
|||
9 |
- #'+ #' ## Reactive `teal_data`: |
|||
10 |
- #' @inheritParams teal.slice::teal_slices+ #' |
|||
11 |
- #'+ #' The data in the application can be reactively updated, prompting [srv_teal()] to rebuild the |
|||
12 |
- #' @param module_specific (`logical(1)`) optional,+ #' content accordingly. There are two methods for creating interactive `teal_data`: |
|||
13 |
- #' - `FALSE` (default) when one filter panel applied to all modules.+ #' 1. Using a `reactive` object provided from outside the `teal` application. In this scenario, |
|||
14 |
- #' All filters will be shared by all modules.+ #' reactivity is controlled by an external module, and `srv_teal` responds to changes. |
|||
15 |
- #' - `TRUE` when filter panel module-specific.+ #' 2. Using [teal_data_module()], which is embedded within the `teal` application, allowing data to |
|||
16 |
- #' Modules can have different set of filters specified - see `mapping` argument.+ #' be resubmitted by the user as needed. |
|||
17 |
- #' @param mapping `r lifecycle::badge("experimental")`+ #' |
|||
18 |
- #' _This is a new feature. Do kindly share your opinions on+ #' Since the server of [teal_data_module()] must return a `reactive` `teal_data` object, both |
|||
19 |
- #' [`teal`'s GitHub repository](https://github.com/insightsengineering/teal/)._+ #' 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 |
- #' (named `list`) specifies which filters will be active in which modules on app start.+ #' involves control from a custom module within the app. |
|||
22 |
- #' Elements should contain character vector of `teal_slice` `id`s (see [`teal.slice::teal_slice`]).+ #' |
|||
23 |
- #' Names of the list should correspond to `teal_module` `label` set in [module()] function.+ #' For more details, see [`module_teal_data`]. |
|||
24 |
- #' - `id`s listed under `"global_filters` will be active in all modules.+ #' |
|||
25 |
- #' - If missing, all filters will be applied to all modules.+ #' @inheritParams init |
|||
26 |
- #' - If empty list, all filters will be available to all modules but will start inactive.+ #' |
|||
27 |
- #' - If `module_specific` is `FALSE`, only `global_filters` will be active on start.+ #' @param data (`teal_data`, `teal_data_module`, or `reactive` returning `teal_data`) |
|||
28 |
- #' @param app_id (`character(1)`)+ #' The data which application will depend on. |
|||
29 |
- #' For internal use only, do not set manually.+ #' |
|||
30 |
- #' Added by `init` so that a `teal_slices` can be matched to the app in which it was used.+ #' @return A `reactive` object that returns: |
|||
31 |
- #' Used for verifying snapshots uploaded from file. See `snapshot`.+ #' 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 |
- #' @param x (`list`) of lists to convert to `teal_slices`+ #' |
|||
34 |
- #'+ #' @rdname module_init_data |
|||
35 |
- #' @return+ #' @name module_init_data |
|||
36 |
- #' A `teal_slices` object.+ #' @keywords internal |
|||
37 |
- #'+ NULL |
|||
38 |
- #' @seealso [`teal.slice::teal_slices`], [`teal.slice::teal_slice`], [slices_store()]+ |
|||
39 |
- #'+ #' @rdname module_init_data |
|||
40 |
- #' @examples+ ui_init_data <- function(id) { |
|||
41 | -+ | 9x |
- #' filter <- teal_slices(+ ns <- shiny::NS(id) |
|
42 | -+ | 9x |
- #' teal_slice(dataname = "iris", varname = "Species", id = "species"),+ shiny::div( |
|
43 | -+ | 9x |
- #' teal_slice(dataname = "iris", varname = "Sepal.Length", id = "sepal_length"),+ id = ns("content"), |
|
44 | -+ | 9x |
- #' teal_slice(+ style = "display: inline-block; width: 100%;", |
|
45 | -+ | 9x |
- #' dataname = "iris", id = "long_petals", title = "Long petals", expr = "Petal.Length > 5"+ uiOutput(ns("data")) |
|
46 |
- #' ),+ ) |
|||
47 |
- #' teal_slice(dataname = "mtcars", varname = "mpg", id = "mtcars_mpg"),+ } |
|||
48 |
- #' mapping = list(+ |
|||
49 |
- #' module1 = c("species", "sepal_length"),+ #' @rdname module_init_data |
|||
50 |
- #' module2 = c("mtcars_mpg"),+ srv_init_data <- function(id, data) { |
|||
51 | -+ | 83x |
- #' global_filters = "long_petals"+ checkmate::assert_character(id, max.len = 1, any.missing = FALSE) |
|
52 | -+ | 83x |
- #' )+ checkmate::assert_multi_class(data, c("teal_data", "teal_data_module", "reactive")) |
|
53 |
- #' )+ |
|||
54 | -+ | 83x |
- #'+ moduleServer(id, function(input, output, session) { |
|
55 | -+ | 83x |
- #' app <- init(+ logger::log_debug("srv_data initializing.") |
|
56 |
- #' data = teal_data(iris = iris, mtcars = mtcars),+ # data_rv contains teal_data object |
|||
57 |
- #' modules = list(+ # either passed to teal::init or returned from teal_data_module |
|||
58 | -+ | 83x |
- #' module("module1"),+ data_out <- if (inherits(data, "teal_data_module")) { |
|
59 | -+ | 10x |
- #' module("module2")+ output$data <- renderUI(data$ui(id = session$ns("teal_data_module"))) |
|
60 | -+ | 10x |
- #' ),+ data$server("teal_data_module") |
|
61 | -+ | 83x |
- #' filter = filter+ } else if (inherits(data, "teal_data")) { |
|
62 | -+ | 43x |
- #' )+ reactiveVal(data) |
|
63 | -+ | 83x |
- #'+ } else if (test_reactive(data)) { |
|
64 | -+ | 30x |
- #' if (interactive()) {+ data |
|
65 |
- #' shinyApp(app$ui, app$server)+ } |
|||
66 |
- #' }+ |
|||
67 | -+ | 82x |
- #'+ data_handled <- reactive({ |
|
68 | -+ | 75x |
- #' @export+ tryCatch(data_out(), error = function(e) e) |
|
69 |
- teal_slices <- function(...,+ }) |
|||
70 |
- exclude_varnames = NULL,+ |
|||
71 |
- include_varnames = NULL,+ # We want to exclude teal_data_module elements from bookmarking as they might have some secrets |
|||
72 | -+ | 82x |
- count_type = NULL,+ observeEvent(data_handled(), { |
|
73 | -+ | 75x |
- allow_add = TRUE,+ if (inherits(data_handled(), "teal_data")) { |
|
74 | -+ | 70x |
- module_specific = FALSE,+ app_session <- .subset2(shiny::getDefaultReactiveDomain(), "parent") |
|
75 | -+ | 70x |
- mapping,+ setBookmarkExclude( |
|
76 | -+ | 70x |
- app_id = NULL) {+ session$ns( |
|
77 | -161x | +70x |
- shiny::isolate({+ grep( |
|
78 | -161x | +70x |
- checkmate::assert_flag(allow_add)+ pattern = "teal_data_module-", |
|
79 | -161x | +70x |
- checkmate::assert_flag(module_specific)+ x = names(reactiveValuesToList(input)), |
|
80 | -51x | +70x |
- if (!missing(mapping)) checkmate::assert_list(mapping, types = c("character", "NULL"), names = "named")+ value = TRUE |
|
81 | -158x | +
- checkmate::assert_string(app_id, null.ok = TRUE)+ ) |
||
82 |
-
+ ), |
|||
83 | -158x | +70x |
- slices <- list(...)+ session = app_session |
|
84 | -158x | +
- all_slice_id <- vapply(slices, `[[`, character(1L), "id")+ ) |
||
85 |
-
+ } |
|||
86 | -158x | +
- if (missing(mapping)) {+ }) |
||
87 | -110x | +
- mapping <- if (length(all_slice_id)) {+ |
||
88 | -26x | +82x |
- list(global_filters = all_slice_id)+ data_handled |
|
89 |
- } else {+ }) |
|||
90 | -84x | +
- list()+ } |
||
91 |
- }+ |
|||
92 |
- }+ #' Adds signature protection to the `datanames` in the data |
|||
93 |
-
+ #' @param data (`teal_data`) |
|||
94 | -158x | +
- if (!module_specific) {+ #' @return `teal_data` with additional code that has signature of the `datanames` |
||
95 | -139x | +
- mapping[setdiff(names(mapping), "global_filters")] <- NULL+ #' @keywords internal |
||
96 |
- }+ .add_signature_to_data <- function(data) { |
|||
97 | -+ | 70x |
-
+ hashes <- .get_hashes_code(data) |
|
98 | -158x | +70x |
- failed_slice_id <- setdiff(unlist(mapping), all_slice_id)+ tdata <- do.call( |
|
99 | -158x | +70x |
- if (length(failed_slice_id)) {+ teal.data::teal_data, |
|
100 | -1x | +70x |
- stop(sprintf(+ c( |
|
101 | -1x | +70x |
- "Filters in mapping don't match any available filter.\n %s not in %s",+ list(code = trimws(c(teal.code::get_code(data), hashes), which = "right")), |
|
102 | -1x | +70x |
- toString(failed_slice_id),+ list(join_keys = teal.data::join_keys(data)), |
|
103 | -1x | +70x | +
+ sapply(+ |
+ |
104 | +70x | +
+ names(data),+ |
+ ||
105 | +70x | +
+ teal.code::get_var,+ |
+ ||
106 | +70x | +
+ object = data,+ |
+ ||
107 | +70x | +
+ simplify = FALSE+ |
+ ||
108 | ++ |
+ )+ |
+ ||
109 | ++ |
+ )+ |
+ ||
110 | ++ |
+ )+ |
+ ||
111 | ++ | + + | +||
112 | +70x | +
+ tdata@verified <- data@verified+ |
+ ||
113 | +70x | +
+ tdata+ |
+ ||
114 | ++ |
+ }+ |
+ ||
115 | ++ | + + | +||
116 | ++ |
+ #' Get code that tests the integrity of the reproducible data+ |
+ ||
117 | ++ |
+ #'+ |
+ ||
118 | ++ |
+ #' @param data (`teal_data`) object holding the data+ |
+ ||
119 | ++ |
+ #' @param datanames (`character`) names of `datasets`+ |
+ ||
120 | ++ |
+ #'+ |
+ ||
121 | ++ |
+ #' @return A character vector with the code lines.+ |
+ ||
122 | ++ |
+ #' @keywords internal+ |
+ ||
123 | ++ |
+ #'+ |
+ ||
124 | ++ |
+ .get_hashes_code <- function(data, datanames = names(data)) {+ |
+ ||
125 | +70x | +
+ vapply(+ |
+ ||
126 | +70x | +
+ datanames,+ |
+ ||
127 | +70x | +
+ function(dataname, datasets) {+ |
+ ||
128 | +125x | +
+ x <- data[[dataname]]+ |
+ ||
129 | ++ | + + | +||
130 | +125x |
- toString(all_slice_id)+ code <- if (is.function(x) && !is.primitive(x)) { |
||
104 | -+ | |||
131 | +6x |
- ))+ x <- deparse1(x) |
||
105 | -+ | |||
132 | +6x |
- }+ bquote(rlang::hash(deparse1(.(as.name(dataname))))) |
||
106 | +133 |
-
+ } else { |
||
107 | -157x | +134 | +119x |
- tss <- teal.slice::teal_slices(+ bquote(rlang::hash(.(as.name(dataname)))) |
108 | +135 |
- ...,+ } |
||
109 | -157x | +136 | +125x |
- exclude_varnames = exclude_varnames,+ sprintf( |
110 | -157x | +137 | +125x |
- include_varnames = include_varnames,+ "stopifnot(%s == %s) # @linksto %s", |
111 | -157x | +138 | +125x |
- count_type = count_type,+ deparse1(code), |
112 | -157x | -
- allow_add = allow_add- |
- ||
113 | -+ | 139 | +125x |
- )+ deparse1(rlang::hash(x)), |
114 | -157x | +140 | +125x |
- attr(tss, "mapping") <- mapping+ dataname |
115 | -157x | +|||
141 | +
- attr(tss, "module_specific") <- module_specific+ ) |
|||
116 | -157x | +|||
142 | +
- attr(tss, "app_id") <- app_id+ }, |
|||
117 | -157x | +143 | +70x |
- class(tss) <- c("modules_teal_slices", class(tss))+ character(1L), |
118 | -157x | +144 | +70x |
- tss+ USE.NAMES = TRUE |
119 | +145 |
- })+ ) |
||
120 | +146 |
} |
121 | +1 |
-
+ #' `teal_data` utils |
||
122 | +2 |
-
+ #' |
||
123 | +3 |
- #' @rdname teal_slices+ #' In `teal` we need to recreate the `teal_data` object due to two operations: |
||
124 | +4 |
- #' @export+ #' - we need to append filter-data code and objects which have been evaluated in `FilteredData` and |
||
125 | +5 |
- #' @keywords internal+ #' we want to avoid double-evaluation. |
||
126 | +6 |
- #'+ #' - we need to subset `teal_data` to `datanames` used by the module, to shorten obtainable R-code |
||
127 | +7 |
- as.teal_slices <- function(x) { # nolint: object_name.+ #' |
||
128 | -13x | +|||
8 | +
- checkmate::assert_list(x)+ #' Due to above recreation of `teal_data` object can't be done simply by using public |
|||
129 | -13x | +|||
9 | +
- lapply(x, checkmate::assert_list, names = "named", .var.name = "list element")+ #' `teal.code` and `teal.data` methods. |
|||
130 | +10 |
-
+ #' |
||
131 | -13x | +|||
11 | +
- attrs <- attributes(unclass(x))+ #' @param data (`teal_data`) |
|||
132 | -13x | +|||
12 | +
- ans <- lapply(x, function(x) if (is.teal_slice(x)) x else as.teal_slice(x))+ #' @param code (`character`) code to append to the object's code slot. |
|||
133 | -13x | +|||
13 | +
- do.call(teal_slices, c(ans, attrs))+ #' @param objects (`list`) objects to append to object's environment. |
|||
134 | +14 |
- }+ #' @param datanames (`character`) names of the datasets |
||
135 | +15 |
-
+ #' @return modified `teal_data` |
||
136 | +16 |
-
+ #' @keywords internal |
||
137 | +17 |
- #' @rdname teal_slices+ #' @name teal_data_utilities |
||
138 | +18 |
- #' @export+ NULL |
||
139 | +19 |
- #' @keywords internal+ |
||
140 | +20 |
- #'+ #' @rdname teal_data_utilities |
||
141 | +21 |
- c.teal_slices <- function(...) {+ .append_evaluated_code <- function(data, code) { |
||
142 | -6x | +22 | +84x |
- x <- list(...)+ checkmate::assert_class(data, "teal_data") |
143 | -6x | +23 | +84x |
- checkmate::assert_true(all(vapply(x, is.teal_slices, logical(1L))), .var.name = "all arguments are teal_slices")+ data@code <- c(data@code, code) |
144 | -+ | |||
24 | +84x |
-
+ data@id <- c(data@id, max(data@id) + 1L + seq_along(code)) |
||
145 | -6x | +25 | +84x |
- all_attributes <- lapply(x, attributes)+ data@messages <- c(data@messages, rep("", length(code))) |
146 | -6x | +26 | +84x |
- all_attributes <- coalesce_r(all_attributes)+ data@warnings <- c(data@warnings, rep("", length(code))) |
147 | -6x | +27 | +84x |
- all_attributes <- all_attributes[names(all_attributes) != "class"]+ methods::validObject(data)+ |
+
28 | +84x | +
+ data |
||
148 | +29 | ++ |
+ }+ |
+ |
30 | ||||
149 | -6x | +|||
31 | +
- do.call(+ #' @rdname teal_data_utilities+ |
+ |||
32 | ++ |
+ .append_modified_data <- function(data, objects) { |
||
150 | -6x | +33 | +84x |
- teal_slices,+ checkmate::assert_class(data, "teal_data") |
151 | -6x | +34 | +84x |
- c(+ checkmate::assert_class(objects, "list") |
152 | -6x | +35 | +84x |
- unique(unlist(x, recursive = FALSE)),+ new_env <- list2env(objects, parent = .GlobalEnv) |
153 | -6x | +36 | +84x |
- all_attributes+ rlang::env_coalesce(new_env, as.environment(data)) |
154 | -+ | |||
37 | +84x |
- )+ data@.xData <- new_env |
||
155 | -+ | |||
38 | +84x |
- )+ data |
||
156 | +39 |
} |
||
157 | +40 | |||
158 | +41 |
-
+ #' @rdname teal_data_utilities |
||
159 | +42 |
- #' Deep copy `teal_slices`+ .subset_teal_data <- function(data, datanames) { |
||
160 | -+ | |||
43 | +83x |
- #'+ checkmate::assert_class(data, "teal_data") |
||
161 | -+ | |||
44 | +83x |
- #' it's important to create a new copy of `teal_slices` when+ checkmate::assert_class(datanames, "character") |
||
162 | -+ | |||
45 | +83x |
- #' starting a new `shiny` session. Otherwise, object will be shared+ datanames_corrected <- intersect(datanames, names(data)) |
||
163 | -+ | |||
46 | +83x |
- #' by multiple users as it is created in global environment before+ datanames_corrected_with_raw <- c(datanames_corrected, ".raw_data") |
||
164 | -+ | |||
47 | +83x |
- #' `shiny` session starts.+ if (!length(datanames_corrected)) { |
||
165 | -+ | |||
48 | +2x |
- #' @param filter (`teal_slices`)+ return(teal_data()) |
||
166 | +49 |
- #' @return `teal_slices`+ } |
||
167 | +50 |
- #' @keywords internal+ |
||
168 | -+ | |||
51 | +81x |
- deep_copy_filter <- function(filter) {+ new_data <- do.call( |
||
169 | -1x | +52 | +81x |
- checkmate::assert_class(filter, "teal_slices")+ teal.data::teal_data, |
170 | -1x | +53 | +81x |
- shiny::isolate({+ args = c( |
171 | -1x | +54 | +81x |
- filter_copy <- lapply(filter, function(slice) {+ mget(x = datanames_corrected_with_raw, envir = as.environment(data)), |
172 | -2x | +55 | +81x |
- teal.slice::as.teal_slice(as.list(slice))+ list( |
173 | -+ | |||
56 | +81x |
- })+ code = teal.code::get_code(data, names = datanames_corrected_with_raw), |
||
174 | -1x | +57 | +81x |
- attributes(filter_copy) <- attributes(filter)+ join_keys = teal.data::join_keys(data)[datanames_corrected] |
175 | -1x | +|||
58 | +
- filter_copy+ ) |
|||
176 | +59 |
- })+ ) |
||
177 | +60 | ++ |
+ )+ |
+ |
61 | +81x | +
+ new_data@verified <- data@verified+ |
+ ||
62 | +81x | +
+ new_data+ |
+ ||
63 |
}@@ -46691,452 +46440,479 @@ teal coverage - 59.99% |
1 |
- #' `teal_data` utils+ .onLoad <- function(libname, pkgname) { |
||
2 |
- #'+ # adapted from https://github.com/r-lib/devtools/blob/master/R/zzz.R |
||
3 |
- #' In `teal` we need to recreate the `teal_data` object due to two operations:+ |
||
4 | -+ | ! |
- #' - we need to append filter-data code and objects which have been evaluated in `FilteredData` and+ teal_default_options <- list( |
5 | -+ | ! |
- #' we want to avoid double-evaluation.+ teal.show_js_log = FALSE, |
6 | -+ | ! |
- #' - we need to subset `teal_data` to `datanames` used by the module, to shorten obtainable R-code+ teal.lockfile.mode = "auto", |
7 | -+ | ! |
- #'+ shiny.sanitize.errors = FALSE |
8 |
- #' Due to above recreation of `teal_data` object can't be done simply by using public+ ) |
||
9 |
- #' `teal.code` and `teal.data` methods.+ |
||
10 | -+ | ! |
- #'+ op <- options() |
11 | -+ | ! |
- #' @param data (`teal_data`)+ toset <- !(names(teal_default_options) %in% names(op)) |
12 | -+ | ! |
- #' @param code (`character`) code to append to `data@code`+ if (any(toset)) options(teal_default_options[toset]) |
13 |
- #' @param objects (`list`) objects to append to `data@env`+ |
||
14 |
- #' @param datanames (`character`) names of the datasets+ # Set up the teal logger instance |
||
15 | -+ | ! |
- #' @return modified `teal_data`+ teal.logger::register_logger("teal") |
16 | -+ | ! |
- #' @keywords internal+ teal.logger::register_handlers("teal") |
17 |
- #' @name teal_data_utilities+ |
||
18 | -+ | ! |
- NULL+ invisible() |
19 |
-
+ } |
||
20 |
- #' @rdname teal_data_utilities+ |
||
21 |
- .append_evaluated_code <- function(data, code) {+ .onAttach <- function(libname, pkgname) { |
||
22 | -84x | +2x |
- checkmate::assert_class(data, "teal_data")+ packageStartupMessage( |
23 | -84x | +2x |
- data@code <- c(data@code, code)+ "\nYou are using teal version ", |
24 | -84x | +
- data@id <- c(data@id, max(data@id) + 1L + seq_along(code))+ # `system.file` uses the `shim` of `system.file` by `teal` |
|
25 | -84x | +
- data@messages <- c(data@messages, rep("", length(code)))+ # we avoid `desc` dependency here to get the version |
|
26 | -84x | +2x |
- data@warnings <- c(data@warnings, rep("", length(code)))+ read.dcf(system.file("DESCRIPTION", package = "teal"))[, "Version"] |
27 | -84x | +
- methods::validObject(data)+ ) |
|
28 | -84x | +
- data+ } |
|
29 |
- }+ |
||
30 |
-
+ # This one is here because setdiff_teal_slice should not be exported from teal.slice. |
||
31 |
- #' @rdname teal_data_utilities+ setdiff_teal_slices <- getFromNamespace("setdiff_teal_slices", "teal.slice") |
||
32 |
- .append_modified_data <- function(data, objects) {+ # This one is here because it is needed by c.teal_slices but we don't want it exported from teal.slice. |
||
33 | -84x | +
- checkmate::assert_class(data, "teal_data")+ coalesce_r <- getFromNamespace("coalesce_r", "teal.slice") |
|
34 | -84x | +
- checkmate::assert_class(objects, "list")+ # all *Block objects are private in teal.reporter |
|
35 | -84x | +
- new_env <- list2env(objects, parent = .GlobalEnv)+ RcodeBlock <- getFromNamespace("RcodeBlock", "teal.reporter") # nolint: object_name. |
|
36 | -84x | +
- rlang::env_coalesce(new_env, teal.code::get_env(data))+ |
|
37 | -84x | +
- data@env <- new_env+ # Use non-exported function(s) from teal.code |
|
38 | -84x | +
- data+ # This one is here because lang2calls should not be exported from teal.code |
|
39 |
- }+ lang2calls <- getFromNamespace("lang2calls", "teal.code") |
40 | +1 |
-
+ #' Generates library calls from current session info |
||
41 | +2 |
- #' @rdname teal_data_utilities+ #' |
||
42 | +3 |
- .subset_teal_data <- function(data, datanames) {+ #' Function to create multiple library calls out of current session info to ensure reproducible code works. |
||
43 | -83x | +|||
4 | +
- checkmate::assert_class(data, "teal_data")+ #' |
|||
44 | -83x | +|||
5 | +
- checkmate::assert_class(datanames, "character")+ #' @return Character vector of `library(<package>)` calls. |
|||
45 | -83x | +|||
6 | ++ |
+ #' @keywords internal+ |
+ ||
7 | +
- datanames_corrected <- intersect(datanames, ls(teal.code::get_env(data)))+ get_rcode_libraries <- function() { |
|||
46 | -83x | +8 | +1x |
- datanames_corrected_with_raw <- c(datanames_corrected, ".raw_data")+ libraries <- vapply( |
47 | -83x | +9 | +1x |
- if (!length(datanames_corrected)) {+ utils::sessionInfo()$otherPkgs, |
48 | -2x | +10 | +1x |
- return(teal_data())+ function(x) { |
49 | -+ | |||
11 | +15x |
- }+ paste0("library(", x$Package, ")") |
||
50 | +12 |
-
+ }, |
||
51 | -81x | +13 | +1x |
- new_data <- do.call(+ character(1) |
52 | -81x | +|||
14 | +
- teal.data::teal_data,+ ) |
|||
53 | -81x | +15 | +1x |
- args = c(+ paste0(paste0(rev(libraries), sep = "\n"), collapse = "") |
54 | -81x | +|||
16 | +
- mget(x = datanames_corrected_with_raw, envir = teal.code::get_env(data)),+ } |
|||
55 | -81x | +|||
17 | +
- list(+ |
|||
56 | -81x | +|||
18 | +
- code = teal.code::get_code(data, names = datanames_corrected_with_raw),+ |
|||
57 | -81x | +|||
19 | +
- join_keys = teal.data::join_keys(data)[datanames_corrected]+ #' @noRd |
|||
58 | +20 |
- )+ #' @keywords internal |
||
59 | +21 |
- )+ get_rcode_str_install <- function() { |
||
60 | -+ | |||
22 | +5x |
- )+ code_string <- getOption("teal.load_nest_code") |
||
61 | -81x | +23 | +5x |
- new_data@verified <- data@verified+ if (is.character(code_string)) { |
62 | -81x | +24 | +2x | +
+ code_string+ |
+
25 | +
- teal.data::datanames(new_data) <- datanames_corrected+ } else { |
|||
63 | -81x | +26 | +3x |
- new_data+ "# Add any code to install/load your NEST environment here\n" |
64 | +27 | ++ |
+ }+ |
+ |
28 |
}@@ -47145,14 +46921,14 @@ teal coverage - 59.99% |
1 |
- #' Generates library calls from current session info+ #' Show `R` code modal |
||
3 |
- #' Function to create multiple library calls out of current session info to ensure reproducible code works.+ #' @description `r lifecycle::badge("deprecated")` |
||
5 |
- #' @return Character vector of `library(<package>)` calls.+ #' Use the [shiny::showModal()] function to show the `R` code inside. |
||
6 |
- #' @keywords internal+ #' |
||
7 |
- get_rcode_libraries <- function() {+ #' @param title (`character(1)`) |
||
8 | -1x | +
- libraries <- vapply(+ #' Title of the modal, displayed in the first comment of the `R` code. |
|
9 | -1x | +
- utils::sessionInfo()$otherPkgs,+ #' @param rcode (`character`) |
|
10 | -1x | +
- function(x) {+ #' vector with `R` code to show inside the modal. |
|
11 | -15x | +
- paste0("library(", x$Package, ")")+ #' @param session (`ShinySession`) optional |
|
12 |
- },+ #' `shiny` session object, defaults to [shiny::getDefaultReactiveDomain()]. |
||
13 | -1x | +
- character(1)+ #' |
|
14 |
- )+ #' @references [shiny::showModal()] |
||
15 | -1x | +
- paste0(paste0(rev(libraries), sep = "\n"), collapse = "")+ #' @export |
|
16 |
- }+ show_rcode_modal <- function(title = NULL, rcode, session = getDefaultReactiveDomain()) { |
||
17 | +! | +
+ lifecycle::deprecate_soft(+ |
+ |
18 | +! | +
+ when = "0.16",+ |
+ |
19 | +! | +
+ what = "show_rcode_modal()",+ |
+ |
20 | +! | +
+ details = "This function will be removed in the next release."+ |
+ |
21 |
-
+ ) |
||
18 | +22 | ||
23 | +! | +
+ rcode <- paste(rcode, collapse = "\n")+ |
+ |
19 | +24 |
- #' @noRd+ + |
+ |
25 | +! | +
+ ns <- session$ns+ |
+ |
26 | +! | +
+ showModal(modalDialog(+ |
+ |
27 | +! | +
+ tagList(+ |
+ |
28 | +! | +
+ tags$div(+ |
+ |
29 | +! | +
+ actionButton(ns("copyRCode"), "Copy to Clipboard", `data-clipboard-target` = paste0("#", ns("r_code"))),+ |
+ |
30 | +! | +
+ modalButton("Dismiss"),+ |
+ |
31 | +! | +
+ style = "mb-4" |
|
20 | +32 |
- #' @keywords internal+ ),+ |
+ |
33 | +! | +
+ tags$div(tags$pre(id = ns("r_code"), rcode)), |
|
21 | +34 |
- get_rcode_str_install <- function() {+ ), |
|
22 | -5x | +||
35 | +! |
- code_string <- getOption("teal.load_nest_code")+ title = title, |
|
23 | -5x | +||
36 | +! |
- if (is.character(code_string)) {+ footer = tagList( |
|
24 | -2x | +||
37 | +! |
- code_string+ actionButton(ns("copyRCode"), "Copy to Clipboard", `data-clipboard-target` = paste0("#", ns("r_code"))),+ |
+ |
38 | +! | +
+ modalButton("Dismiss") |
|
25 | +39 |
- } else {+ ), |
|
26 | -3x | +||
40 | +! |
- "# Add any code to install/load your NEST environment here\n"+ size = "l",+ |
+ |
41 | +! | +
+ easyClose = TRUE |
|
27 | +42 |
- }+ )) |
|
28 | +43 |
}@@ -48066,14 +47947,14 @@ teal coverage - 59.99% |
1 |
- #' UI and server modules of `teal`+ #' Create a `teal` module for previewing a report |
||
3 |
- #' @description `r lifecycle::badge("deprecated")`+ #' @description `r lifecycle::badge("experimental")` |
||
4 |
- #' Please use [`module_teal`] instead.+ #' |
||
5 |
- #'+ #' This function wraps [teal.reporter::reporter_previewer_ui()] and |
||
6 |
- #' @inheritParams ui_teal+ #' [teal.reporter::reporter_previewer_srv()] into a `teal_module` to be |
||
7 |
- #' @inheritParams srv_teal+ #' used in `teal` applications. |
||
9 |
- #' @return+ #' If you are creating a `teal` application using [init()] then this |
||
10 |
- #' Returns a `reactive` expression containing a `teal_data` object when data is loaded or `NULL` when it is not.+ #' module will be added to your application automatically if any of your `teal_modules` |
||
11 |
- #' @name module_teal_with_splash+ #' support report generation. |
||
13 |
- NULL+ #' @inheritParams teal_modules |
||
14 |
-
+ #' @param server_args (named `list`) |
||
15 |
- #' @export+ #' Arguments passed to [teal.reporter::reporter_previewer_srv()]. |
||
16 |
- #' @rdname module_teal_with_splash+ #' |
||
17 |
- ui_teal_with_splash <- function(id,+ #' @return |
||
18 |
- data,+ #' `teal_module` (extended with `teal_module_previewer` class) containing the `teal.reporter` previewer functionality. |
||
19 |
- title = build_app_title(),+ #' |
||
20 |
- header = tags$p(),+ #' @export |
||
21 |
- footer = tags$p()) {+ #' |
||
22 | -! | +
- lifecycle::deprecate_soft(+ reporter_previewer_module <- function(label = "Report previewer", server_args = list()) { |
|
23 | -! | +7x |
- when = "0.16",+ checkmate::assert_string(label) |
24 | -! | +5x |
- what = "ui_teal_with_splash()",+ checkmate::assert_list(server_args, names = "named") |
25 | -! | +5x |
- details = "Deprecated, please use `ui_teal` instead"+ checkmate::assert_true(all(names(server_args) %in% names(formals(teal.reporter::reporter_previewer_srv)))) |
26 |
- )+ |
||
27 | -! | +3x |
- ui_teal(id = id, title = title, header = header, footer = footer)+ message("Initializing reporter_previewer_module") |
28 |
- }+ |
||
29 | -+ | 3x |
-
+ srv <- function(id, reporter, ...) { |
30 | -+ | ! |
- #' @export+ teal.reporter::reporter_previewer_srv(id, reporter, ...) |
31 |
- #' @rdname module_teal_with_splash+ } |
||
32 |
- srv_teal_with_splash <- function(id, data, modules, filter = teal_slices()) {+ |
||
33 | -! | +3x |
- lifecycle::deprecate_soft(+ ui <- function(id, ...) { |
34 | ! |
- when = "0.16",+ teal.reporter::reporter_previewer_ui(id, ...) |
|
35 | -! | +
- what = "srv_teal_with_splash()",+ } |
|
36 | -! | +
- details = "Deprecated, please use `srv_teal` instead"+ |
|
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 |
) |
||
38 | -! | +||
42 | +
- srv_teal(id = id, data = data, modules = modules, filter = filter)+ # Module is created with a placeholder label and the label is changed later. |
||
39 | +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 |
}@@ -48694,14 +48638,14 @@ teal coverage - 59.99% |
1 |
- #' Show `R` code modal+ #' UI and server modules of `teal` |
||
4 |
- #'+ #' Please use [`module_teal`] instead. |
||
5 |
- #' Use the [shiny::showModal()] function to show the `R` code inside.+ #' |
||
6 |
- #'+ #' @inheritParams ui_teal |
||
7 |
- #' @param title (`character(1)`)+ #' @inheritParams srv_teal |
||
8 |
- #' Title of the modal, displayed in the first comment of the `R` code.+ #' |
||
9 |
- #' @param rcode (`character`)+ #' @return |
||
10 |
- #' vector with `R` code to show inside the modal.+ #' Returns a `reactive` expression containing a `teal_data` object when data is loaded or `NULL` when it is not. |
||
11 |
- #' @param session (`ShinySession`) optional+ #' @name module_teal_with_splash |
||
12 |
- #' `shiny` session object, defaults to [shiny::getDefaultReactiveDomain()].+ #' |
||
13 |
- #'+ NULL |
||
14 |
- #' @references [shiny::showModal()]+ |
||
16 |
- show_rcode_modal <- function(title = NULL, rcode, session = getDefaultReactiveDomain()) {+ #' @rdname module_teal_with_splash |
||
17 | -! | +
- lifecycle::deprecate_soft(+ ui_teal_with_splash <- function(id, |
|
18 | -! | +
- when = "0.16",+ data, |
|
19 | -! | +
- what = "show_rcode_modal()",+ title = build_app_title(), |
|
20 | -! | +
- details = "This function will be removed in the next release."+ header = tags$p(), |
|
21 |
- )+ footer = tags$p()) { |
||
22 | -+ | ! |
-
+ lifecycle::deprecate_soft( |
23 | ! |
- rcode <- paste(rcode, collapse = "\n")+ when = "0.16", |
|
24 | -+ | ! |
-
+ what = "ui_teal_with_splash()", |
25 | ! |
- ns <- session$ns+ details = "Deprecated, please use `ui_teal` instead" |
|
26 | -! | +
- showModal(modalDialog(+ ) |
|
27 | ! |
- tagList(+ ui_teal(id = id, title = title, header = header, footer = footer) |
|
28 | -! | +
- tags$div(+ } |
|
29 | -! | +
- actionButton(ns("copyRCode"), "Copy to Clipboard", `data-clipboard-target` = paste0("#", ns("r_code"))),+ |
|
30 | -! | +
- modalButton("Dismiss"),+ #' @export |
|
31 | -! | +
- style = "mb-4"+ #' @rdname module_teal_with_splash |
|
32 |
- ),+ srv_teal_with_splash <- function(id, data, modules, filter = teal_slices()) { |
||
33 | ! |
- tags$div(tags$pre(id = ns("r_code"), rcode)),+ lifecycle::deprecate_soft( |
|
34 | -+ | ! |
- ),+ when = "0.16", |
35 | ! |
- title = title,+ what = "srv_teal_with_splash()", |
|
36 | ! |
- footer = tagList(+ details = "Deprecated, please use `srv_teal` instead" |
|
37 | -! | +
- actionButton(ns("copyRCode"), "Copy to Clipboard", `data-clipboard-target` = paste0("#", ns("r_code"))),+ ) |
|
38 | ! |
- modalButton("Dismiss")+ srv_teal(id = id, data = data, modules = modules, filter = filter) |
|
39 | - |
- ),- |
- |
40 | -! | -
- size = "l",- |
- |
41 | -! | -
- easyClose = TRUE- |
- |
42 | -- |
- ))- |
- |
43 | -
} |