diff --git a/coverage-report/index.html b/coverage-report/index.html index 104b2e12bd..40c982490c 100644 --- a/coverage-report/index.html +++ b/coverage-report/index.html @@ -107,19 +107,19 @@
1 |
- #' Manage multiple `FilteredData` objects+ #' Execute and validate `teal_data_module` |
||
3 |
- #' @description+ #' This is a low level module to handle `teal_data_module` execution and validation. |
||
4 |
- #' Oversee filter states across the entire application.+ #' [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` |
||
6 |
- #' @section Slices global:+ #' [teal_data()] which is a standard data class in whole `teal` framework. |
||
7 |
- #' The key role in maintaining the module-specific filter states is played by the `.slicesGlobal`+ #' |
||
8 |
- #' object. It is a reference class that holds the following fields:+ #' @section data validation: |
||
9 |
- #' - `all_slices` (`reactiveVal`) - reactive value containing all filters registered in an app.+ #' |
||
10 |
- #' - `module_slices_api` (`reactiveValues`) - reactive field containing references to each modules'+ #' Executed [teal_data_module()] is validated and output is validated for consistency. |
||
11 |
- #' `FilteredData` object methods. At this moment it is used only in `srv_filter_manager` to display+ #' Output `data` is invalid if: |
||
12 |
- #' the filter states in a table combining informations from `all_slices` and from+ #' 1. [teal_data_module()] is invalid if server doesn't return `reactive`. **Immediately crashes an app!** |
||
13 |
- #' `FilteredData$get_available_teal_slices()`.+ #' 2. `reactive` throws a `shiny.error` - happens when module creating [teal_data()] fails. |
||
14 |
- #'+ #' 3. `reactive` returns `qenv.error` - happens when [teal_data()] evaluates a failing code. |
||
15 |
- #' During a session only new filters are added to `all_slices` unless [`module_snapshot_manager`] is+ #' 4. `reactive` object doesn't return [teal_data()]. |
||
16 |
- #' used to restore previous state. Filters from `all_slices` can be activated or deactivated in a+ #' 5. [teal_data()] object lacks any `datanames` specified in the `modules` argument. |
||
17 |
- #' module which is linked (both ways) by `attr(, "mapping")` so that:+ #' |
||
18 |
- #' - If module's filter is added or removed in its `FilteredData` object, this information is passed+ #' `teal` (observers in `srv_teal`) always waits to render an app until `reactive` `teal_data` is |
||
19 |
- #' to `SlicesGlobal` which updates `attr(, "mapping")` accordingly.+ #' returned. If error 2-4 occurs, relevant error message is displayed to the app user. Once the issue is |
||
20 |
- #' - When mapping changes in a `SlicesGlobal`, filters are set or removed from module's+ #' resolved, the app will continue to run. `teal` guarantees that errors in data don't crash the app |
||
21 |
- #' `FilteredData`.+ #' (except error 1). |
||
23 |
- #' @section Filter manager:+ #' @param id (`character(1)`) Module id |
||
24 |
- #' Filter-manager is split into two parts:+ #' @param data (`reactive teal_data`) |
||
25 |
- #' 1. `ui/srv_filter_manager_panel` - Called once for the whole app. This module observes changes in+ #' @param data_module (`teal_data_module`) |
||
26 |
- #' the filters in `slices_global` and displays them in a table utilizing information from `mapping`:+ #' @param modules (`teal_modules` or `teal_module`) For `datanames` validation purpose |
||
27 |
- #' - (`TRUE`) - filter is active in the module+ #' @param validate_shiny_silent_error (`logical`) If `TRUE`, then `shiny.silent.error` is validated and |
||
28 |
- #' - (`FALSE`) - filter is inactive in the module+ #' @param is_transformer_failed (`reactiveValues`) contains `logical` flags named after each transformer. |
||
29 |
- #' - (`NA`) - filter is not available in the module+ #' Help to determine if any previous transformer failed, so that following transformers can be disabled |
||
30 |
- #' 2. `ui/srv_module_filter_manager` - Called once for each `teal_module`. Handling filter states+ #' and display a generic failure message. |
||
31 |
- #' for of single module and keeping module `FilteredData` consistent with `slices_global`, so that+ #' |
||
32 |
- #' local filters are always reflected in the `slices_global` and its mapping and vice versa.+ #' @return `reactive` `teal_data` |
||
34 |
- #'+ #' @rdname module_teal_data |
||
35 |
- #' @param id (`character(1)`)+ #' @name module_teal_data |
||
36 |
- #' `shiny` module instance id.+ #' @keywords internal |
||
37 |
- #'+ NULL |
||
38 |
- #' @param slices_global (`reactiveVal`)+ |
||
39 |
- #' containing `teal_slices`.+ #' @rdname module_teal_data |
||
40 |
- #'+ ui_teal_data <- function(id, data_module = function(id) NULL) { |
||
41 | -+ | ! |
- #' @param module_fd (`FilteredData`)+ checkmate::assert_string(id) |
42 | -+ | ! |
- #' Object containing the data to be filtered in a single `teal` module.+ checkmate::assert_function(data_module, args = "id") |
43 | -+ | ! |
- #'+ ns <- NS(id) |
44 |
- #' @return+ |
||
45 | -+ | ! |
- #' Module returns a `slices_global` (`reactiveVal`) containing a `teal_slices` object with mapping.+ shiny::tagList( |
46 | -+ | ! |
- #'+ tags$div(id = ns("wrapper"), data_module(id = ns("data"))), |
47 | -+ | ! |
- #' @encoding UTF-8+ ui_validate_reactive_teal_data(ns("validate")) |
48 |
- #'+ ) |
||
49 |
- #' @name module_filter_manager+ } |
||
50 |
- #' @rdname module_filter_manager+ |
||
51 |
- #'+ #' @rdname module_teal_data |
||
52 |
- NULL+ srv_teal_data <- function(id, |
||
53 |
-
+ data_module = function(id) NULL, |
||
54 |
- #' @rdname module_filter_manager+ modules = NULL, |
||
55 |
- ui_filter_manager_panel <- function(id) {+ validate_shiny_silent_error = TRUE, |
||
56 | -! | +
- ns <- NS(id)+ is_transformer_failed = reactiveValues()) { |
|
57 | -! | +20x |
- tags$button(+ checkmate::assert_string(id) |
58 | -! | +20x |
- id = ns("show_filter_manager"),+ checkmate::assert_function(data_module, args = "id") |
59 | -! | +20x |
- class = "btn action-button wunder_bar_button",+ checkmate::assert_multi_class(modules, c("teal_modules", "teal_module"), null.ok = TRUE) |
60 | -! | +20x |
- title = "View filter mapping",+ checkmate::assert_class(is_transformer_failed, "reactivevalues") |
61 | -! | +
- suppressMessages(icon("fas fa-grip"))+ |
|
62 | -+ | 20x |
- )+ moduleServer(id, function(input, output, session) { |
63 | -+ | 20x |
- }+ logger::log_debug("srv_teal_data initializing.") |
64 | -+ | 20x |
-
+ is_transformer_failed[[id]] <- FALSE |
65 | -+ | 20x |
- #' @rdname module_filter_manager+ data_out <- data_module(id = "data") |
66 | -+ | 20x |
- #' @keywords internal+ data_handled <- reactive(tryCatch(data_out(), error = function(e) e)) |
67 | -+ | 20x |
- srv_filter_manager_panel <- function(id, slices_global) {+ observeEvent(data_handled(), { |
68 | -82x | +22x |
- checkmate::assert_string(id)+ if (!inherits(data_handled(), "teal_data")) { |
69 | -82x | +6x |
- checkmate::assert_class(slices_global, ".slicesGlobal")+ is_transformer_failed[[id]] <- TRUE |
70 | -82x | +
- moduleServer(id, function(input, output, session) {+ } else { |
|
71 | -82x | +16x |
- setBookmarkExclude(c("show_filter_manager"))+ is_transformer_failed[[id]] <- FALSE |
72 | -82x | +
- observeEvent(input$show_filter_manager, {+ } |
|
73 | -! | +
- logger::log_debug("srv_filter_manager_panel@1 show_filter_manager button has been clicked.")+ }) |
|
74 | -! | +
- showModal(+ |
|
75 | -! | +20x |
- modalDialog(+ is_previous_failed <- reactive({ |
76 | -! | +20x |
- ui_filter_manager(session$ns("filter_manager")),+ idx_this <- which(names(is_transformer_failed) == id) |
77 | -! | +20x |
- class = "filter_manager_modal",+ is_transformer_failed_list <- reactiveValuesToList(is_transformer_failed) |
78 | -! | +20x |
- size = "l",+ idx_failures <- which(unlist(is_transformer_failed_list)) |
79 | -! | +20x |
- footer = NULL,+ any(idx_failures < idx_this) |
80 | -! | +
- easyClose = TRUE+ }) |
|
81 |
- )+ |
||
82 | -+ | 20x |
- )+ observeEvent(is_previous_failed(), { |
83 | -+ | 20x |
- })+ if (is_previous_failed()) { |
84 | -82x | +! |
- srv_filter_manager("filter_manager", slices_global = slices_global)+ shinyjs::disable("wrapper") |
85 |
- })+ } else { |
||
86 | -+ | 20x |
- }+ shinyjs::enable("wrapper") |
87 |
-
+ } |
||
88 |
- #' @rdname module_filter_manager+ }) |
||
89 |
- ui_filter_manager <- function(id) {+ |
||
90 | -! | +20x |
- ns <- NS(id)+ srv_validate_reactive_teal_data( |
91 | -! | +20x |
- actionButton(ns("filter_manager"), NULL, icon = icon("fas fa-filter"))+ "validate", |
92 | -! | +20x |
- tags$div(+ data = data_handled, |
93 | -! | +20x |
- class = "filter_manager_content",+ modules = modules, |
94 | -! | +20x |
- tableOutput(ns("slices_table"))+ validate_shiny_silent_error = validate_shiny_silent_error, |
95 | -+ | 20x |
- )+ hide_validation_error = is_previous_failed |
96 |
- }+ ) |
||
97 |
-
+ }) |
||
98 |
- #' @rdname module_filter_manager+ } |
||
99 |
- srv_filter_manager <- function(id, slices_global) {+ |
||
100 | -82x | +
- checkmate::assert_string(id)+ #' @rdname module_teal_data |
|
101 | -82x | +
- checkmate::assert_class(slices_global, ".slicesGlobal")+ ui_validate_reactive_teal_data <- function(id) { |
|
102 | -+ | 82x |
-
+ ns <- NS(id) |
103 | 82x |
- moduleServer(id, function(input, output, session) {+ tagList( |
|
104 | 82x |
- logger::log_debug("filter_manager_srv initializing.")+ div( |
|
105 | -+ | 82x |
-
+ id = ns("validate_messages"), |
106 | -+ | 82x |
- # Bookmark slices global with mapping.+ class = "teal_validated", |
107 | 82x |
- session$onBookmark(function(state) {+ ui_validate_error(ns("silent_error")), |
|
108 | -! | +82x |
- logger::log_debug("filter_manager_srv@onBookmark: storing filter state")+ ui_check_class_teal_data(ns("class_teal_data")), |
109 | -! | +82x |
- state$values$filter_state_on_bookmark <- as.list(+ ui_check_shiny_warnings(ns("shiny_warnings")) |
110 | -! | +
- slices_global$all_slices(),+ ), |
|
111 | -! | +82x |
- recursive = TRUE+ div( |
112 | -+ | 82x |
- )+ class = "teal_validated", |
113 | -+ | 82x |
- })+ uiOutput(ns("previous_failed")) |
114 |
-
+ ) |
||
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.")+ |
|
118 | -! | +
- slices_global$slices_set(bookmarked_slices)+ #' @rdname module_teal_data |
|
119 |
- }+ srv_validate_reactive_teal_data <- function(id, # nolint: object_length |
||
120 |
-
+ data, |
||
121 | -82x | +
- mapping_table <- reactive({+ modules = NULL, |
|
122 |
- # We want this to be reactive on slices_global$all_slices() only as get_available_teal_slices()+ validate_shiny_silent_error = FALSE, |
||
123 |
- # is dependent on slices_global$all_slices().+ hide_validation_error = reactive(FALSE)) { |
||
124 | -91x | +183x |
- module_labels <- setdiff(+ checkmate::assert_string(id) |
125 | -91x | +183x |
- names(attr(slices_global$all_slices(), "mapping")),+ checkmate::assert_multi_class(modules, c("teal_modules", "teal_module"), null.ok = TRUE) |
126 | -91x | +183x |
- "Report previewer"+ checkmate::assert_flag(validate_shiny_silent_error) |
127 |
- )+ |
||
128 | -91x | +183x |
- isolate({+ moduleServer(id, function(input, output, session) { |
129 | -91x | +
- mm <- as.data.frame(+ # there is an empty reactive cycle on `init` and `data_rv` has `shiny.silent.error` class |
|
130 | -91x | +183x |
- sapply(+ srv_validate_error("silent_error", data, validate_shiny_silent_error) |
131 | -91x | +183x |
- module_labels,+ srv_check_class_teal_data("class_teal_data", data) |
132 | -91x | +183x |
- simplify = FALSE,+ srv_check_shiny_warnings("shiny_warnings", data, modules) |
133 | -91x | +183x |
- function(module_label) {+ output$previous_failed <- renderUI({ |
134 | -104x | +173x |
- available_slices <- slices_global$module_slices_api[[module_label]]$get_available_teal_slices()+ if (hide_validation_error()) { |
135 | -96x | +! |
- global_ids <- sapply(slices_global$all_slices(), `[[`, "id", simplify = FALSE)+ shinyjs::hide("validate_messages") |
136 | -96x | +! |
- module_ids <- sapply(slices_global$slices_get(module_label), `[[`, "id", simplify = FALSE)+ tags$div("One of previous transformers failed. Please fix and continue.", class = "teal-output-warning") |
137 | -96x | +
- allowed_ids <- vapply(available_slices, `[[`, character(1L), "id")+ } else { |
|
138 | -96x | +173x |
- active_ids <- global_ids %in% module_ids+ shinyjs::show("validate_messages") |
139 | -96x | +173x |
- setNames(nm = global_ids, ifelse(global_ids %in% allowed_ids, active_ids, NA))+ NULL |
140 |
- }+ } |
||
141 |
- ),+ }) |
||
142 | -91x | +
- check.names = FALSE+ |
|
143 | -+ | 183x |
- )+ .trigger_on_success(data) |
144 | -83x | +
- colnames(mm)[colnames(mm) == "global_filters"] <- "Global filters"+ }) |
|
145 |
-
+ } |
||
146 | -83x | +
- mm+ |
|
147 |
- })+ #' @keywords internal |
||
148 |
- })+ ui_validate_error <- function(id) { |
||
149 | -+ | 82x |
-
+ ns <- NS(id) |
150 | 82x |
- output$slices_table <- renderTable(+ uiOutput(ns("message")) |
|
151 | -82x | +
- expr = {+ } |
|
152 | -91x | +
- logger::log_debug("filter_manager_srv@1 rendering slices_table.")+ |
|
153 | -91x | +
- mm <- mapping_table()+ #' @keywords internal |
|
154 |
-
+ srv_validate_error <- function(id, data, validate_shiny_silent_error) { |
||
155 | -+ | 183x |
- # Display logical values as UTF characters.+ checkmate::assert_string(id) |
156 | -83x | +183x |
- mm[] <- lapply(mm, ifelse, yes = intToUtf8(9989), no = intToUtf8(10060))+ checkmate::assert_flag(validate_shiny_silent_error) |
157 | -83x | +183x |
- mm[] <- lapply(mm, function(x) ifelse(is.na(x), intToUtf8(128306), x))+ moduleServer(id, function(input, output, session) { |
158 | -+ | 183x |
-
+ output$message <- renderUI({ |
159 | -+ | 186x |
- # Display placeholder if no filters defined.+ is_shiny_silent_error <- inherits(data(), "shiny.silent.error") && identical(data()$message, "") |
160 | -83x | +180x |
- if (nrow(mm) == 0L) {+ if (inherits(data(), "qenv.error")) { |
161 | -59x | +2x |
- mm <- data.frame(`Filter manager` = "No filters specified.", check.names = FALSE)+ validate( |
162 | -59x | +2x |
- rownames(mm) <- ""+ need( |
163 | -+ | 2x |
- }+ FALSE, |
164 | -83x | +2x |
- mm+ paste( |
165 | -+ | 2x |
- },+ "Error when executing the `data` module:", |
166 | -82x | +2x |
- rownames = TRUE+ strip_style(paste(data()$message, collapse = "\n")), |
167 | -+ | 2x |
- )+ "\nCheck your inputs or contact app developer if error persists.", |
168 | -+ | 2x |
-
+ collapse = "\n" |
169 | -82x | +
- mapping_table # for testing purpose+ ) |
|
170 |
- })+ ) |
||
171 |
- }+ ) |
||
172 | -+ | 178x |
-
+ } else if (inherits(data(), "error")) { |
173 | -+ | 7x |
- #' @rdname module_filter_manager+ if (is_shiny_silent_error && !validate_shiny_silent_error) { |
174 | -+ | 1x |
- srv_module_filter_manager <- function(id, module_fd, slices_global) {+ return(NULL) |
175 | -107x | +
- checkmate::assert_string(id)+ } |
|
176 | -107x | +6x |
- assert_reactive(module_fd)+ validate( |
177 | -107x | +6x |
- checkmate::assert_class(slices_global, ".slicesGlobal")+ need( |
178 | -+ | 6x |
-
+ FALSE, |
179 | -107x | +6x |
- moduleServer(id, function(input, output, session) {+ sprintf( |
180 | -107x | +6x |
- logger::log_debug("srv_module_filter_manager initializing for module: { id }.")+ "Shiny error when executing the `data` module.\n%s\n%s", |
181 | -+ | 6x |
- # Track filter global and local states.+ data()$message, |
182 | -107x | +6x |
- slices_global_module <- reactive({+ "Check your inputs or contact app developer if error persists." |
183 | -193x | +
- slices_global$slices_get(module_label = id)+ ) |
|
184 |
- })+ ) |
||
185 | -107x | +
- slices_module <- reactive(req(module_fd())$get_filter_state())+ ) |
|
186 |
-
+ } |
||
187 | -107x | +
- module_fd_previous <- reactiveVal(NULL)+ }) |
|
188 |
-
+ }) |
||
189 |
- # Set (reactively) available filters for the module.+ } |
||
190 | -107x | +
- obs1 <- observeEvent(module_fd(), priority = 1, {+ |
|
191 | -88x | +
- logger::log_debug("srv_module_filter_manager@1 setting initial slices for module: { id }.")+ |
|
192 |
- # Filters relevant for the module in module-specific app.+ #' @keywords internal |
||
193 | -88x | +
- slices <- slices_global_module()+ ui_check_class_teal_data <- function(id) { |
|
194 | -+ | 82x |
-
+ ns <- NS(id) |
195 | -+ | 82x |
- # Clean up previous filter states and refresh cache of previous module_fd with current+ uiOutput(ns("message")) |
196 | -3x | +
- if (!is.null(module_fd_previous())) module_fd_previous()$finalize()+ } |
|
197 | -88x | +
- module_fd_previous(module_fd())+ |
|
198 |
-
+ #' @keywords internal |
||
199 |
- # Setting filter states from slices_global:+ srv_check_class_teal_data <- function(id, data) { |
||
200 | -+ | 183x |
- # 1. when app initializes slices_global set to initial filters (specified by app developer)+ checkmate::assert_string(id) |
201 | -+ | 183x |
- # 2. when data reinitializes slices_global reflects latest filter states+ moduleServer(id, function(input, output, session) { |
202 | -+ | 183x |
-
+ output$message <- renderUI({ |
203 | -88x | +186x |
- module_fd()$set_filter_state(slices)+ validate( |
204 | -+ | 186x |
-
+ need( |
205 | -+ | 186x |
- # irrelevant filters are discarded in FilteredData$set_available_teal_slices+ inherits(data(), c("teal_data", "error")), |
206 | -+ | 186x |
- # it means we don't need to subset slices_global$all_slices() from filters refering to irrelevant datasets+ "Did not receive `teal_data` object. Cannot proceed further." |
207 | -88x | +
- module_fd()$set_available_teal_slices(slices_global$all_slices)+ ) |
|
208 |
-
+ ) |
||
209 |
- # this needed in filter_manager_srv+ }) |
||
210 | -88x | +
- slices_global$module_slices_api_set(+ }) |
|
211 | -88x | +
- id,+ } |
|
212 | -88x | +
- list(+ |
|
213 | -88x | +
- get_available_teal_slices = module_fd()$get_available_teal_slices(),+ #' @keywords internal |
|
214 | -88x | +
- set_filter_state = module_fd()$set_filter_state, # for testing purpose+ ui_check_shiny_warnings <- function(id) { |
|
215 | -88x | +82x |
- get_filter_state = module_fd()$get_filter_state # for testing purpose+ ns <- NS(id) |
216 | -+ | 82x |
- )+ uiOutput(NS(id, "message")) |
217 |
- )+ } |
||
218 |
- })+ |
||
219 |
-
+ #' @keywords internal |
||
220 |
- # Update global state and mapping matrix when module filters change.+ srv_check_shiny_warnings <- function(id, data, modules) { |
||
221 | -107x | +183x |
- obs2 <- observeEvent(slices_module(), priority = 0, {+ checkmate::assert_string(id) |
222 | -110x | +183x |
- this_slices <- slices_module()+ moduleServer(id, function(input, output, session) { |
223 | -110x | +183x |
- slices_global$slices_append(this_slices) # append new slices to the all_slices list+ output$message <- renderUI({ |
224 | -110x | +186x |
- mapping_elem <- setNames(nm = id, list(vapply(this_slices, `[[`, character(1L), "id")))+ if (inherits(data(), "teal_data")) { |
225 | -110x | +169x |
- slices_global$slices_active(mapping_elem)+ is_modules_ok <- check_modules_datanames_html( |
226 | -+ | 169x |
- })+ modules = modules, datanames = ls(teal.code::get_env(data())) |
227 |
-
+ ) |
||
228 | -107x | +169x |
- obs3 <- observeEvent(slices_global_module(), {+ if (!isTRUE(is_modules_ok)) { |
229 | -130x | +15x |
- global_vs_module <- setdiff_teal_slices(slices_global_module(), slices_module())+ tags$div(is_modules_ok, class = "teal-output-warning") |
230 | -130x | +
- module_vs_global <- setdiff_teal_slices(slices_module(), slices_global_module())+ } |
|
231 | -121x | +
- if (length(global_vs_module) || length(module_vs_global)) {+ } |
|
232 |
- # Comment: (Nota Bene) Normally new filters for a module are added through module-filter-panel, and slices+ }) |
||
233 |
- # global are updated automatically so slices_module -> slices_global_module are equal.+ }) |
||
234 |
- # this if is valid only when a change is made on the global level so the change needs to be propagated down+ } |
||
235 |
- # to the module (for example through snapshot manager). If it happens both slices are different+ |
||
236 | -13x | +
- logger::log_debug("srv_module_filter_manager@3 (N.B.) global state has changed for a module:{ id }.")+ .trigger_on_success <- function(data) { |
|
237 | -13x | +183x |
- module_fd()$clear_filter_states()+ out <- reactiveVal(NULL) |
238 | -13x | +183x |
- module_fd()$set_filter_state(slices_global_module())+ observeEvent(data(), { |
239 | -+ | 180x |
- }+ if (inherits(data(), "teal_data")) { |
240 | -+ | 169x |
- })+ if (!identical(data(), out())) { |
241 | -+ | 169x |
-
+ out(data()) |
242 | -107x | +
- slices_module # returned for testing purpose+ } |
|
243 |
- })+ } |
||
244 |
- }+ }) |
||
246 | -+ | 183x |
- #' @importFrom shiny reactiveVal reactiveValues+ out |
247 |
- methods::setOldClass("reactiveVal")+ } |
248 | +1 |
- methods::setOldClass("reactivevalues")+ #' Get client timezone |
||
249 | +2 |
-
+ #' |
||
250 | +3 |
- #' @importFrom methods new+ #' User timezone in the browser may be different to the one on the server. |
||
251 | +4 |
- #' @rdname module_filter_manager+ #' This script can be run to register a `shiny` input which contains information about the timezone in the browser. |
||
252 | +5 |
- .slicesGlobal <- methods::setRefClass(".slicesGlobal", # nolint: object_name.+ #' |
||
253 | +6 |
- fields = list(+ #' @param ns (`function`) namespace function passed from the `session` object in the `shiny` server. |
||
254 | +7 |
- all_slices = "reactiveVal",+ #' For `shiny` modules this will allow for proper name spacing of the registered input. |
||
255 | +8 |
- module_slices_api = "reactivevalues"+ #' |
||
256 | +9 |
- ),+ #' @return `NULL`, invisibly. |
||
257 | +10 |
- methods = list(+ #' |
||
258 | +11 |
- initialize = function(slices = teal_slices(), module_labels) {+ #' @keywords internal+ |
+ ||
12 | ++ |
+ #'+ |
+ ||
13 | ++ |
+ get_client_timezone <- function(ns) { |
||
259 | -82x | +14 | +83x |
- shiny::isolate({+ script <- sprintf( |
260 | -82x | +15 | +83x |
- checkmate::assert_class(slices, "teal_slices")+ "Shiny.setInputValue(`%s`, Intl.DateTimeFormat().resolvedOptions().timeZone)",+ |
+
16 | +83x | +
+ ns("timezone") |
||
261 | +17 |
- # needed on init to not mix "global_filters" with module-specific-slots+ ) |
||
262 | -82x | +18 | +83x |
- if (isTRUE(attr(slices, "module_specific"))) {+ shinyjs::runjs(script) # function does not return anything |
263 | -11x | +19 | +83x |
- old_mapping <- attr(slices, "mapping")+ invisible(NULL) |
264 | -11x | +|||
20 | +
- new_mapping <- sapply(module_labels, simplify = FALSE, function(module_label) {+ } |
|||
265 | -20x | +|||
21 | +
- unique(unlist(old_mapping[c(module_label, "global_filters")]))+ |
|||
266 | +22 |
- })+ #' Resolve the expected bootstrap theme |
||
267 | -11x | +|||
23 | +
- attr(slices, "mapping") <- new_mapping+ #' @noRd |
|||
268 | +24 |
- }+ #' @keywords internal |
||
269 | -82x | +|||
25 | +
- .self$all_slices <<- shiny::reactiveVal(slices)+ get_teal_bs_theme <- function() { |
|||
270 | -82x | +26 | +4x |
- .self$module_slices_api <<- shiny::reactiveValues()+ bs_theme <- getOption("teal.bs_theme") |
271 | -82x | +|||
27 | +
- .self$slices_append(slices)+ |
|||
272 | -82x | +28 | +4x |
- .self$slices_active(attr(slices, "mapping"))+ if (is.null(bs_theme)) { |
273 | -82x | +29 | +1x |
- invisible(.self)+ return(NULL) |
274 | +30 |
- })+ } |
||
275 | +31 |
- },+ |
||
276 | -+ | |||
32 | +3x |
- is_module_specific = function() {+ if (!checkmate::test_class(bs_theme, "bs_theme")) { |
||
277 | -283x | +33 | +2x |
- isTRUE(attr(.self$all_slices(), "module_specific"))+ warning( |
278 | -+ | |||
34 | +2x |
- },+ "Assertion on 'teal.bs_theme' option value failed: ", |
||
279 | -+ | |||
35 | +2x |
- module_slices_api_set = function(module_label, functions_list) {+ checkmate::check_class(bs_theme, "bs_theme"), |
||
280 | -88x | +36 | +2x |
- shiny::isolate({+ ". The default Shiny Bootstrap theme will be used." |
281 | -88x | +|||
37 | +
- if (!.self$is_module_specific()) {+ ) |
|||
282 | -72x | +38 | +2x |
- module_label <- "global_filters"+ return(NULL) |
283 | +39 |
- }+ } |
||
284 | -88x | +|||
40 | +
- if (!identical(.self$module_slices_api[[module_label]], functions_list)) {+ |
|||
285 | -88x | +41 | +1x |
- .self$module_slices_api[[module_label]] <- functions_list+ bs_theme |
286 | +42 |
- }+ } |
||
287 | -88x | +|||
43 | +
- invisible(.self)+ |
|||
288 | +44 |
- })+ #' Return parentnames along with datanames. |
||
289 | +45 |
- },+ #' @noRd |
||
290 | +46 |
- slices_deactivate_all = function(module_label) {+ #' @keywords internal |
||
291 | -! | +|||
47 | +
- shiny::isolate({+ .include_parent_datanames <- function(datanames, join_keys) { |
|||
292 | -! | +|||
48 | +167x |
- new_slices <- .self$all_slices()+ ordered_datanames <- datanames |
||
293 | -! | +|||
49 | +167x |
- old_mapping <- attr(new_slices, "mapping")+ for (i in datanames) { |
||
294 | -+ | |||
50 | +306x |
-
+ parents <- character(0) |
||
295 | -! | +|||
51 | +306x |
- new_mapping <- if (.self$is_module_specific()) {+ while (length(i) > 0) { |
||
296 | -! | +|||
52 | +319x |
- new_module_mapping <- setNames(nm = module_label, list(character(0)))+ parent_i <- teal.data::parent(join_keys, i) |
||
297 | -! | +|||
53 | +319x |
- modifyList(old_mapping, new_module_mapping)+ parents <- c(parent_i, parents) |
||
298 | -! | +|||
54 | +319x |
- } else if (missing(module_label)) {+ i <- parent_i |
||
299 | -! | +|||
55 | +
- lapply(+ } |
|||
300 | -! | +|||
56 | +306x |
- attr(.self$all_slices(), "mapping"),+ ordered_datanames <- c(parents, ordered_datanames) |
||
301 | -! | +|||
57 | +
- function(x) character(0)+ }+ |
+ |||
58 | +167x | +
+ unique(ordered_datanames) |
||
302 | +59 |
- )+ } |
||
303 | +60 |
- } else {+ |
||
304 | -! | +|||
61 | +
- old_mapping[[module_label]] <- character(0)+ #' Return topologicaly sorted datanames |
|||
305 | -! | +|||
62 | +
- old_mapping+ #' @noRd |
|||
306 | +63 |
- }+ #' @keywords internal |
||
307 | +64 |
-
+ .topologically_sort_datanames <- function(datanames, join_keys) { |
||
308 | -! | +|||
65 | +135x |
- if (!identical(new_mapping, old_mapping)) {+ datanames_with_parents <- .include_parent_datanames(datanames, join_keys) |
||
309 | -! | +|||
66 | +135x |
- logger::log_debug(".slicesGlobal@slices_deactivate_all: deactivating all slices.")+ intersect(datanames, datanames_with_parents) |
||
310 | -! | +|||
67 | +
- attr(new_slices, "mapping") <- new_mapping+ } |
|||
311 | -! | +|||
68 | +
- .self$all_slices(new_slices)+ |
|||
312 | +69 |
- }+ #' Create a `FilteredData` |
||
313 | -! | +|||
70 | +
- invisible(.self)+ #' |
|||
314 | +71 |
- })+ #' Create a `FilteredData` object from a `teal_data` object. |
||
315 | +72 |
- },+ #' |
||
316 | +73 |
- slices_active = function(mapping_elem) {+ #' @param x (`teal_data`) object |
||
317 | -195x | +|||
74 | +
- shiny::isolate({+ #' @param datanames (`character`) vector of data set names to include; must be subset of `datanames(x)` |
|||
318 | -195x | +|||
75 | +
- if (.self$is_module_specific()) {+ #' @return A `FilteredData` object. |
|||
319 | -36x | +|||
76 | +
- new_mapping <- modifyList(attr(.self$all_slices(), "mapping"), mapping_elem)+ #' @keywords internal |
|||
320 | +77 |
- } else {+ teal_data_to_filtered_data <- function(x, datanames = ls(teal.code::get_env(x))) { |
||
321 | -159x | +78 | +78x |
- new_mapping <- setNames(nm = "global_filters", list(unique(unlist(mapping_elem))))+ checkmate::assert_class(x, "teal_data") |
322 | -+ | |||
79 | +78x |
- }+ checkmate::assert_character(datanames, min.chars = 1L, any.missing = FALSE) |
||
323 | +80 |
-
+ # Otherwise, FilteredData will be created in the modules' scope later |
||
324 | -195x | +81 | +78x |
- if (!identical(new_mapping, attr(.self$all_slices(), "mapping"))) {+ teal.slice::init_filtered_data( |
325 | -138x | +82 | +78x |
- mapping_modules <- toString(names(new_mapping))+ x = Filter( |
326 | -138x | +83 | +78x |
- logger::log_debug(".slicesGlobal@slices_active: changing mapping for module(s): { mapping_modules }.")+ length, |
327 | -138x | +84 | +78x |
- new_slices <- .self$all_slices()+ sapply(datanames, function(dn) x[[dn]], simplify = FALSE) |
328 | -138x | +|||
85 | +
- attr(new_slices, "mapping") <- new_mapping+ ), |
|||
329 | -138x | +86 | +78x |
- .self$all_slices(new_slices)+ join_keys = teal.data::join_keys(x) |
330 | +87 |
- }+ ) |
||
331 | +88 | - - | -||
332 | -195x | -
- invisible(.self)+ } |
||
333 | +89 |
- })+ |
||
334 | +90 |
- },+ |
||
335 | +91 |
- # - only new filters are appended to the $all_slices+ #' Template function for `TealReportCard` creation and customization |
||
336 | +92 |
- # - mapping is not updated here+ #' |
||
337 | +93 |
- slices_append = function(slices, activate = FALSE) {- |
- ||
338 | -195x | -
- shiny::isolate({- |
- ||
339 | -195x | -
- if (!is.teal_slices(slices)) {- |
- ||
340 | -! | -
- slices <- as.teal_slices(slices)+ #' This function generates a report card with a title, |
||
341 | +94 |
- }+ #' an optional description, and the option to append the filter state list. |
||
342 | +95 |
-
+ #' |
||
343 | +96 |
- # to make sure that we don't unnecessary trigger $all_slices <reactiveVal>- |
- ||
344 | -195x | -
- new_slices <- setdiff_teal_slices(slices, .self$all_slices())- |
- ||
345 | -195x | -
- old_mapping <- attr(.self$all_slices(), "mapping")- |
- ||
346 | -195x | -
- if (length(new_slices)) {- |
- ||
347 | -6x | -
- new_ids <- vapply(new_slices, `[[`, character(1L), "id")- |
- ||
348 | -6x | -
- logger::log_debug(".slicesGlobal@slices_append: appending new slice(s): { new_ids }.")- |
- ||
349 | -6x | -
- slices_ids <- vapply(.self$all_slices(), `[[`, character(1L), "id")- |
- ||
350 | -6x | -
- lapply(new_slices, function(slice) {+ #' @param title (`character(1)`) title of the card (unless overwritten by label) |
||
351 | +97 |
- # In case the new state has the same id as an existing one, add a suffix- |
- ||
352 | -6x | -
- if (slice$id %in% slices_ids) {- |
- ||
353 | -1x | -
- slice$id <- utils::tail(make.unique(c(slices_ids, slice$id), sep = "_"), 1)+ #' @param label (`character(1)`) label provided by the user when adding the card |
||
354 | +98 |
- }+ #' @param description (`character(1)`) optional, additional description |
||
355 | +99 |
- })+ #' @param with_filter (`logical(1)`) flag indicating to add filter state |
||
356 | +100 | - - | -||
357 | -6x | -
- new_slices_all <- c(.self$all_slices(), new_slices)- |
- ||
358 | -6x | -
- attr(new_slices_all, "mapping") <- old_mapping- |
- ||
359 | -6x | -
- .self$all_slices(new_slices_all)+ #' @param filter_panel_api (`FilterPanelAPI`) object with API that allows the generation |
||
360 | +101 |
- }+ #' of the filter state in the report |
||
361 | +102 | - - | -||
362 | -195x | -
- invisible(.self)+ #' |
||
363 | +103 |
- })+ #' @return (`TealReportCard`) populated with a title, description and filter state. |
||
364 | +104 |
- },+ #' |
||
365 | +105 |
- slices_get = function(module_label) {- |
- ||
366 | -289x | -
- if (missing(module_label)) {- |
- ||
367 | -! | -
- .self$all_slices()+ #' @export |
||
368 | +106 |
- } else {+ report_card_template <- function(title, label, description = NULL, with_filter, filter_panel_api) { |
||
369 | -289x | +107 | +2x |
- module_ids <- unlist(attr(.self$all_slices(), "mapping")[c(module_label, "global_filters")])+ checkmate::assert_string(title) |
370 | -289x | +108 | +2x |
- Filter(+ checkmate::assert_string(label) |
371 | -289x | +109 | +2x |
- function(slice) slice$id %in% module_ids,+ checkmate::assert_string(description, null.ok = TRUE) |
372 | -289x | -
- .self$all_slices()- |
- ||
373 | -+ | 110 | +2x |
- )+ checkmate::assert_flag(with_filter) |
374 | -+ | |||
111 | +2x |
- }+ checkmate::assert_class(filter_panel_api, classes = "FilterPanelAPI") |
||
375 | +112 |
- },+ |
||
376 | -+ | |||
113 | +2x |
- slices_set = function(slices) {+ card <- teal::TealReportCard$new() |
||
377 | -7x | +114 | +2x |
- shiny::isolate({+ title <- if (label == "") title else label |
378 | -7x | +115 | +2x |
- if (!is.teal_slices(slices)) {+ card$set_name(title) |
379 | -! | +|||
116 | +2x |
- slices <- as.teal_slices(slices)+ card$append_text(title, "header2") |
||
380 | -+ | |||
117 | +1x |
- }+ if (!is.null(description)) card$append_text(description, "header3") |
||
381 | -7x | +118 | +1x |
- .self$all_slices(slices)+ if (with_filter) card$append_fs(filter_panel_api$get_filter_state()) |
382 | -7x | +119 | +2x |
- invisible(.self)+ card |
383 | +120 |
- })+ } |
||
384 | +121 |
- },+ |
||
385 | +122 |
- show = function() {- |
- ||
386 | -! | -
- shiny::isolate(print(.self$all_slices()))- |
- ||
387 | -! | -
- invisible(.self)+ |
||
388 | +123 |
- }+ #' Check `datanames` in modules |
||
389 | +124 |
- )+ #' |
||
390 | +125 |
- )+ #' These functions check if specified `datanames` in modules match those in the data object, |
||
391 | +126 |
- # todo: prevent any teal_slices attribute except mapping+ #' returning error messages or `TRUE` for successful validation. Two functions return error message |
1 | +127 |
- # FilteredData ------+ #' in different forms: |
|
2 | +128 |
-
+ #' - `check_modules_datanames` returns `character(1)` for basic assertion usage |
|
3 | +129 |
- #' Drive a `teal` application+ #' - `check_modules_datanames_html` returns `shiny.tag.list` to display it in the app. |
|
4 | +130 |
#' |
|
5 | +131 |
- #' Extension of the `shinytest2::AppDriver` class with methods for+ #' @param modules (`teal_modules`) object |
|
6 | +132 |
- #' driving a teal application for performing interactions for `shinytest2` tests.+ #' @param datanames (`character`) names of datasets available in the `data` object |
|
7 | +133 |
#' |
|
8 | +134 |
- #' @keywords internal+ #' @return `TRUE` if validation passes, otherwise `character(1)` or `shiny.tag.list` |
|
9 | +135 |
- #'+ #' @keywords internal |
|
10 | +136 |
- TealAppDriver <- R6::R6Class( # nolint: object_name.+ check_modules_datanames <- function(modules, datanames) { |
|
11 | -+ | ||
137 | +9x |
- "TealAppDriver",+ out <- check_modules_datanames_html(modules, datanames) |
|
12 | -+ | ||
138 | +9x |
- inherit = {+ if (inherits(out, "shiny.tag.list")) { |
|
13 | -+ | ||
139 | +3x |
- if (!requireNamespace("shinytest2", quietly = TRUE)) {+ out_with_ticks <- gsub("<code>|</code>", "`", toString(out)) |
|
14 | -+ | ||
140 | +3x |
- stop("Please install 'shinytest2' package to use this class.")+ out_text <- gsub("<[^<>]+>", "", toString(out_with_ticks)) |
|
15 | -+ | ||
141 | +3x |
- }+ trimws(gsub("[[:space:]]+", " ", out_text)) |
|
16 | +142 |
- if (!requireNamespace("rvest", quietly = TRUE)) {+ } else { |
|
17 | -+ | ||
143 | +6x |
- stop("Please install 'rvest' package to use this class.")+ out |
|
18 | +144 |
- }+ } |
|
19 | +145 |
- shinytest2::AppDriver+ } |
|
20 | +146 |
- },+ |
|
21 | +147 |
- # public methods ----+ #' @rdname check_modules_datanames |
|
22 | +148 |
- public = list(+ check_modules_datanames_html <- function(modules, |
|
23 | +149 |
- #' @description+ datanames) { |
|
24 | -+ | ||
150 | +178x |
- #' Initialize a `TealAppDriver` object for testing a `teal` application.+ check_datanames <- check_modules_datanames_recursive(modules, datanames) |
|
25 | -+ | ||
151 | +178x |
- #'+ show_module_info <- inherits(modules, "teal_modules") # used in two contexts - module and app |
|
26 | -+ | ||
152 | +178x |
- #' @param data,modules,filter,title,header,footer,landing_popup arguments passed to `init`+ if (!length(check_datanames)) { |
|
27 | -+ | ||
153 | +160x |
- #' @param timeout (`numeric`) Default number of milliseconds for any timeout or+ return(TRUE) |
|
28 | +154 |
- #' timeout_ parameter in the `TealAppDriver` class.+ } |
|
29 | -+ | ||
155 | +18x |
- #' Defaults to 20s.- |
- |
30 | -- |
- #'+ shiny::tagList( |
|
31 | -+ | ||
156 | +18x |
- #' See [`shinytest2::AppDriver`] `new` method for more details on how to change it+ lapply( |
|
32 | -+ | ||
157 | +18x |
- #' via options or environment variables.+ check_datanames, |
|
33 | -+ | ||
158 | +18x |
- #' @param load_timeout (`numeric`) How long to wait for the app to load, in ms.+ function(mod) { |
|
34 | -+ | ||
159 | +18x |
- #' This includes the time to start R. Defaults to 100s.+ tagList( |
|
35 | -+ | ||
160 | +18x |
- #'+ tags$span( |
|
36 | -+ | ||
161 | +18x |
- #' See [`shinytest2::AppDriver`] `new` method for more details on how to change it+ tags$span(if (length(mod$missing_datanames) == 1) "Dataset" else "Datasets"), |
|
37 | -+ | ||
162 | +18x |
- #' via options or environment variables+ to_html_code_list(mod$missing_datanames), |
|
38 | -+ | ||
163 | +18x |
- #' @param ... Additional arguments to be passed to `shinytest2::AppDriver$new`+ tags$span( |
|
39 | -+ | ||
164 | +18x |
- #'+ paste0( |
|
40 | -+ | ||
165 | +18x |
- #'+ if (length(mod$missing_datanames) > 1) "are missing" else "is missing", |
|
41 | -+ | ||
166 | +18x |
- #' @return Object of class `TealAppDriver`+ if (show_module_info) sprintf(" for module '%s'.", mod$label) else "." |
|
42 | +167 |
- initialize = function(data,+ ) |
|
43 | +168 |
- modules,+ ) |
|
44 | +169 |
- filter = teal_slices(),+ ), |
|
45 | -+ | ||
170 | +18x |
- title = build_app_title(),+ if (length(datanames) >= 1) { |
|
46 | -+ | ||
171 | +16x |
- header = tags$p(),+ tagList( |
|
47 | -+ | ||
172 | +16x |
- footer = tags$p(),+ tags$span(if (length(datanames) == 1) "Dataset" else "Datasets"), |
|
48 | -+ | ||
173 | +16x |
- landing_popup = NULL,+ tags$span("available in data:"), |
|
49 | -+ | ||
174 | +16x |
- timeout = rlang::missing_arg(),+ tagList( |
|
50 | -+ | ||
175 | +16x |
- load_timeout = rlang::missing_arg(),+ tags$span( |
|
51 | -+ | ||
176 | +16x |
- ...) {+ to_html_code_list(datanames), |
|
52 | -! | +||
177 | +16x |
- private$data <- data+ tags$span(".", .noWS = "outside"), |
|
53 | -! | +||
178 | +16x |
- private$modules <- modules+ .noWS = c("outside") |
|
54 | -! | +||
179 | +
- private$filter <- filter+ ) |
||
55 | -! | +||
180 | +
- app <- init(+ ) |
||
56 | -! | +||
181 | +
- data = data,+ ) |
||
57 | -! | +||
182 | +
- modules = modules,+ } else { |
||
58 | -! | +||
183 | +2x |
- filter = filter,+ tags$span("No datasets are available in data.") |
|
59 | -! | +||
184 | +
- title = title,+ }, |
||
60 | -! | +||
185 | +18x |
- header = header,+ tags$br(.noWS = "before") |
|
61 | -! | +||
186 | +
- footer = footer,+ ) |
||
62 | -! | +||
187 | +
- landing_popup = landing_popup,+ } |
||
63 | +188 |
- )+ ) |
|
64 | +189 |
-
+ ) |
|
65 | +190 |
- # Default timeout is hardcoded to 4s in shinytest2:::resolve_timeout+ } |
|
66 | +191 |
- # It must be set as parameter to the AppDriver+ |
|
67 | -! | +||
192 | +
- suppressWarnings(+ #' Recursively checks modules and returns list for every datanames mismatch between module and data |
||
68 | -! | +||
193 | +
- super$initialize(+ #' @noRd |
||
69 | -! | +||
194 | +
- app_dir = shinyApp(app$ui, app$server),+ check_modules_datanames_recursive <- function(modules, datanames) { # nolint: object_name_length |
||
70 | -! | +||
195 | +277x |
- name = "teal",+ checkmate::assert_multi_class(modules, c("teal_module", "teal_modules")) |
|
71 | -! | +||
196 | +277x |
- variant = shinytest2::platform_variant(),+ checkmate::assert_character(datanames) |
|
72 | -! | +||
197 | +277x |
- timeout = rlang::maybe_missing(timeout, 20 * 1000),+ if (inherits(modules, "teal_modules")) { |
|
73 | -! | +||
198 | +79x |
- load_timeout = rlang::maybe_missing(load_timeout, 100 * 1000),+ unlist( |
|
74 | -+ | ||
199 | +79x |
- ...+ lapply(modules$children, check_modules_datanames_recursive, datanames = datanames), |
|
75 | -+ | ||
200 | +79x |
- )+ recursive = FALSE |
|
76 | +201 |
- )+ ) |
|
77 | +202 |
-
+ } else { |
|
78 | -+ | ||
203 | +198x |
- # Check for minimum version of Chrome that supports the tests+ missing_datanames <- setdiff(modules$datanames, c("all", datanames)) |
|
79 | -+ | ||
204 | +198x |
- # - Element.checkVisibility was added on 105+ if (length(missing_datanames)) { |
|
80 | -! | +||
205 | +18x |
- chrome_version <- numeric_version(+ list(list( |
|
81 | -! | +||
206 | +18x |
- gsub(+ label = modules$label, |
|
82 | -! | +||
207 | +18x |
- "[[:alnum:]_]+/", # Prefix that ends with forward slash+ missing_datanames = missing_datanames |
|
83 | +208 |
- "",- |
- |
84 | -! | -
- self$get_chromote_session()$Browser$getVersion()$product+ )) |
|
85 | +209 |
- ),+ } |
|
86 | -! | +||
210 | +
- strict = FALSE+ } |
||
87 | +211 |
- )+ } |
|
88 | +212 | ||
89 | -! | +||
213 | +
- required_version <- "121"+ #' Convert character vector to html code separated with commas and "and" |
||
90 | +214 |
-
+ #' @noRd |
|
91 | -! | +||
215 | +
- testthat::skip_if(+ to_html_code_list <- function(x) { |
||
92 | -! | +||
216 | +34x |
- is.na(chrome_version),+ checkmate::assert_character(x) |
|
93 | -! | +||
217 | +34x |
- "Problem getting Chrome version, please contact the developers."+ do.call( |
|
94 | -+ | ||
218 | +34x |
- )+ tagList, |
|
95 | -! | +||
219 | +34x |
- testthat::skip_if(+ lapply(seq_along(x), function(.ix) { |
|
96 | -! | +||
220 | +47x |
- chrome_version < required_version,+ tagList( |
|
97 | -! | +||
221 | +47x |
- sprintf(+ tags$code(x[.ix]), |
|
98 | -! | +||
222 | +47x |
- "Chrome version '%s' is not supported, please upgrade to '%s' or higher",+ if (.ix != length(x)) { |
|
99 | -! | +||
223 | +1x |
- chrome_version,+ if (.ix == length(x) - 1) tags$span(" and ") else tags$span(", ", .noWS = "before") |
|
100 | -! | +||
224 | +
- required_version+ } |
||
101 | +225 |
- )+ ) |
|
102 | +226 |
- )+ }) |
|
103 | +227 |
- # end od check+ ) |
|
104 | +228 |
-
+ } |
|
105 | -! | +||
229 | +
- private$set_active_ns()+ |
||
106 | -! | +||
230 | +
- self$wait_for_idle()+ |
||
107 | +231 |
- },+ #' Check `datanames` in filters |
|
108 | +232 |
- #' @description+ #' |
|
109 | +233 |
- #' Append parent [`shinytest2::AppDriver`] `click` method with a call to `waif_for_idle()` method.+ #' This function checks whether `datanames` in filters correspond to those in `data`, |
|
110 | +234 |
- #' @param ... arguments passed to parent [`shinytest2::AppDriver`] `click()` method.+ #' returning character vector with error messages or `TRUE` if all checks pass. |
|
111 | +235 |
- click = function(...) {+ #' |
|
112 | -! | +||
236 | +
- super$click(...)+ #' @param filters (`teal_slices`) object |
||
113 | -! | +||
237 | +
- private$wait_for_page_stability()+ #' @param datanames (`character`) names of datasets available in the `data` object |
||
114 | +238 |
- },+ #' |
|
115 | +239 |
- #' @description+ #' @return A `character(1)` containing error message or TRUE if validation passes. |
|
116 | +240 |
- #' Check if the app has shiny errors. This checks for global shiny errors.+ #' @keywords internal |
|
117 | +241 |
- #' Note that any shiny errors dependent on shiny server render will only be captured after the teal module tab+ check_filter_datanames <- function(filters, datanames) { |
|
118 | -+ | ||
242 | +79x |
- #' is visited because shiny will not trigger server computations when the tab is invisible.+ checkmate::assert_class(filters, "teal_slices") |
|
119 | -+ | ||
243 | +79x |
- #' So, navigate to the module tab you want to test before calling this function.+ checkmate::assert_character(datanames) |
|
120 | +244 |
- #' Although, this catches errors hidden in the other module tabs if they are already rendered.+ |
|
121 | +245 |
- expect_no_shiny_error = function() {+ # check teal_slices against datanames |
|
122 | -! | +||
246 | +79x |
- testthat::expect_null(+ out <- unlist(sapply( |
|
123 | -! | +||
247 | +79x |
- self$get_html(".shiny-output-error:not(.shiny-output-error-validation)"),+ filters, function(filter) { |
|
124 | -! | +||
248 | +24x |
- info = "Shiny error is observed"+ dataname <- shiny::isolate(filter$dataname) |
|
125 | -+ | ||
249 | +24x |
- )+ if (!dataname %in% datanames) { |
|
126 | -+ | ||
250 | +3x |
- },+ sprintf( |
|
127 | -+ | ||
251 | +3x |
- #' @description+ "- Filter '%s' refers to dataname not available in 'data':\n %s not in (%s)", |
|
128 | -+ | ||
252 | +3x |
- #' Check if the app has no validation errors. This checks for global shiny validation errors.+ shiny::isolate(filter$id), |
|
129 | -+ | ||
253 | +3x |
- expect_no_validation_error = function() {+ dQuote(dataname, q = FALSE), |
|
130 | -! | +||
254 | +3x |
- testthat::expect_null(+ toString(dQuote(datanames, q = FALSE)) |
|
131 | -! | +||
255 | +
- self$get_html(".shiny-output-error-validation"),+ ) |
||
132 | -! | +||
256 | +
- info = "No validation error is observed"+ } |
||
133 | +257 |
- )+ } |
|
134 | +258 |
- },+ )) |
|
135 | +259 |
- #' @description+ |
|
136 | +260 |
- #' Check if the app has validation errors. This checks for global shiny validation errors.+ |
|
137 | -+ | ||
261 | +79x |
- expect_validation_error = function() {+ if (length(out)) { |
|
138 | -! | +||
262 | +3x |
- testthat::expect_false(+ paste(out, collapse = "\n") |
|
139 | -! | +||
263 | +
- is.null(self$get_html(".shiny-output-error-validation")),+ } else { |
||
140 | -! | +||
264 | +76x |
- info = "Validation error is not observed"+ TRUE |
|
141 | +265 |
- )+ } |
|
142 | +266 |
- },+ } |
|
143 | +267 |
- #' @description+ |
|
144 | +268 |
- #' Set the input in the `teal` app.+ #' Function for validating the title parameter of `teal::init` |
|
145 | +269 |
- #'+ #' |
|
146 | +270 |
- #' @param input_id (character) The shiny input id with it's complete name space.+ #' Checks if the input of the title from `teal::init` will create a valid title and favicon tag. |
|
147 | +271 |
- #' @param value The value to set the input to.+ #' @param shiny_tag (`shiny.tag`) Object to validate for a valid title. |
|
148 | +272 |
- #' @param ... Additional arguments to be passed to `shinytest2::AppDriver$set_inputs`+ #' @keywords internal |
|
149 | +273 |
- #'+ validate_app_title_tag <- function(shiny_tag) { |
|
150 | -+ | ||
274 | +7x |
- #' @return The `TealAppDriver` object invisibly.+ checkmate::assert_class(shiny_tag, "shiny.tag") |
|
151 | -+ | ||
275 | +7x |
- set_input = function(input_id, value, ...) {+ checkmate::assert_true(shiny_tag$name == "head") |
|
152 | -! | +||
276 | +6x |
- do.call(+ child_names <- vapply(shiny_tag$children, `[[`, character(1L), "name") |
|
153 | -! | +||
277 | +6x |
- self$set_inputs,+ checkmate::assert_subset(c("title", "link"), child_names, .var.name = "child tags") |
|
154 | -! | +||
278 | +4x |
- c(setNames(list(value), input_id), list(...))+ rel_attr <- shiny_tag$children[[which(child_names == "link")]]$attribs$rel |
|
155 | -+ | ||
279 | +4x |
- )+ checkmate::assert_subset( |
|
156 | -! | +||
280 | +4x |
- invisible(self)+ rel_attr,+ |
+ |
281 | +4x | +
+ c("icon", "shortcut icon"),+ |
+ |
282 | +4x | +
+ .var.name = "Link tag's rel attribute",+ |
+ |
283 | +4x | +
+ empty.ok = FALSE |
|
157 | +284 |
- },+ ) |
|
158 | +285 |
- #' @description+ } |
|
159 | +286 |
- #' Navigate the teal tabs in the `teal` app.+ |
|
160 | +287 |
- #'+ #' Build app title with favicon |
|
161 | +288 |
- #' @param tabs (character) Labels of tabs to navigate to. The order of the tabs is important,+ #' |
|
162 | +289 |
- #' and it should start with the most parent level tab.+ #' A helper function to create the browser title along with a logo. |
|
163 | +290 |
- #' Note: In case the teal tab group has duplicate names, the first tab will be selected,+ #' |
|
164 | +291 |
- #' If you wish to select the second tab with the same name, use the suffix "_1".+ #' @param title (`character`) The browser title for the `teal` app. |
|
165 | +292 |
- #' If you wish to select the third tab with the same name, use the suffix "_2" and so on.+ #' @param favicon (`character`) The path for the icon for the title. |
|
166 | +293 |
- #'+ #' The image/icon path can be remote or the static path accessible by `shiny`, like the `www/` |
|
167 | +294 |
- #' @return The `TealAppDriver` object invisibly.+ #' |
|
168 | +295 |
- navigate_teal_tab = function(tabs) {+ #' @return A `shiny.tag` containing the element that adds the title and logo to the `shiny` app. |
|
169 | -! | +||
296 | +
- checkmate::check_character(tabs, min.len = 1)+ #' @export |
||
170 | -! | +||
297 | +
- for (tab in tabs) {+ build_app_title <- function( |
||
171 | -! | +||
298 | +
- self$set_input(+ title = "teal app", |
||
172 | -! | +||
299 | +
- "teal-teal_modules-active_tab",+ favicon = "https://raw.githubusercontent.com/insightsengineering/hex-stickers/main/PNG/nest.png") { |
||
173 | -! | +||
300 | +13x |
- get_unique_labels(tab),+ checkmate::assert_string(title, null.ok = TRUE) |
|
174 | -! | +||
301 | +13x |
- wait_ = FALSE+ checkmate::assert_string(favicon, null.ok = TRUE) |
|
175 | -+ | ||
302 | +13x |
- )+ tags$head( |
|
176 | -+ | ||
303 | +13x |
- }+ tags$title(title), |
|
177 | -! | +||
304 | +13x |
- self$wait_for_idle()+ tags$link( |
|
178 | -! | +||
305 | +13x |
- private$set_active_ns()+ rel = "icon", |
|
179 | -! | +||
306 | +13x |
- invisible(self)+ href = favicon, |
|
180 | -+ | ||
307 | +13x |
- },+ sizes = "any" |
|
181 | +308 |
- #' @description+ ) |
|
182 | +309 |
- #' Get the active shiny name space for different components of the teal app.+ ) |
|
183 | +310 |
- #'+ } |
|
184 | +311 |
- #' @return (`list`) The list of active shiny name space of the teal components.+ |
|
185 | +312 |
- active_ns = function() {- |
- |
186 | -! | -
- if (identical(private$ns$module, character(0))) {- |
- |
187 | -! | -
- private$set_active_ns()+ #' Application ID |
|
188 | +313 |
- }- |
- |
189 | -! | -
- private$ns+ #' |
|
190 | +314 |
- },+ #' Creates App ID used to match filter snapshots to application. |
|
191 | +315 |
- #' @description+ #' |
|
192 | +316 |
- #' Get the active shiny name space for interacting with the module content.+ #' Calculate app ID that will be used to stamp filter state snapshots. |
|
193 | +317 |
- #'+ #' App ID is a hash of the app's data and modules. |
|
194 | +318 |
- #' @return (`string`) The active shiny name space of the component.+ #' See "transferring snapshots" section in ?snapshot. |
|
195 | +319 |
- active_module_ns = function() {- |
- |
196 | -! | -
- if (identical(private$ns$module, character(0))) {- |
- |
197 | -! | -
- private$set_active_ns()+ #' |
|
198 | +320 |
- }+ #' @param data (`teal_data` or `teal_data_module`) as accepted by `init` |
|
199 | -! | +||
321 | +
- private$ns$module+ #' @param modules (`teal_modules`) object as accepted by `init` |
||
200 | +322 |
- },+ #' |
|
201 | +323 |
- #' @description+ #' @return A single character string. |
|
202 | +324 |
- #' Get the active shiny name space bound with a custom `element` name.+ #' |
|
203 | +325 |
- #'+ #' @keywords internal |
|
204 | +326 |
- #' @param element `character(1)` custom element name.+ create_app_id <- function(data, modules) { |
|
205 | -+ | ||
327 | +21x |
- #'+ checkmate::assert_multi_class(data, c("teal_data", "teal_data_module")) |
|
206 | -+ | ||
328 | +20x |
- #' @return (`string`) The active shiny name space of the component bound with the input `element`.+ checkmate::assert_class(modules, "teal_modules") |
|
207 | +329 |
- active_module_element = function(element) {+ |
|
208 | -! | +||
330 | +19x |
- checkmate::assert_string(element)+ data <- if (inherits(data, "teal_data")) { |
|
209 | -! | +||
331 | +17x |
- sprintf("#%s-%s", self$active_module_ns(), element)+ as.list(teal.code::get_env(data)) |
|
210 | -+ | ||
332 | +19x |
- },+ } else if (inherits(data, "teal_data_module")) { |
|
211 | -+ | ||
333 | +2x |
- #' @description+ deparse1(body(data$server)) |
|
212 | +334 |
- #' Get the text of the active shiny name space bound with a custom `element` name.+ } |
|
213 | -+ | ||
335 | +19x |
- #'+ modules <- lapply(modules, defunction) |
|
214 | +336 |
- #' @param element `character(1)` the text of the custom element name.+ |
|
215 | -+ | ||
337 | +19x |
- #'+ rlang::hash(list(data = data, modules = modules)) |
|
216 | +338 |
- #' @return (`string`) The text of the active shiny name space of the component bound with the input `element`.+ } |
|
217 | +339 |
- active_module_element_text = function(element) {- |
- |
218 | -! | -
- checkmate::assert_string(element)- |
- |
219 | -! | -
- self$get_text(self$active_module_element(element))+ |
|
220 | +340 |
- },+ #' Go through list and extract bodies of encountered functions as string, recursively. |
|
221 | +341 |
- #' @description+ #' @keywords internal |
|
222 | +342 |
- #' Get the active shiny name space for interacting with the filter panel.+ #' @noRd |
|
223 | +343 |
- #'+ defunction <- function(x) { |
|
224 | -+ | ||
344 | +229x |
- #' @return (`string`) The active shiny name space of the component.+ if (is.list(x)) { |
|
225 | -+ | ||
345 | +67x |
- active_filters_ns = function() {+ lapply(x, defunction) |
|
226 | -! | +||
346 | +162x |
- if (identical(private$ns$filter_panel, character(0))) {+ } else if (is.function(x)) { |
|
227 | -! | +||
347 | +50x |
- private$set_active_ns()+ deparse1(body(x)) |
|
228 | +348 |
- }+ } else { |
|
229 | -! | +||
349 | +112x |
- private$ns$filter_panel+ x |
|
230 | +350 |
- },+ } |
|
231 | +351 |
- #' @description+ } |
|
232 | +352 |
- #' Get the active shiny name space for interacting with the data-summary panel.+ |
|
233 | +353 |
- #'+ #' Get unique labels |
|
234 | +354 |
- #' @return (`string`) The active shiny name space of the data-summary component.+ #' |
|
235 | +355 |
- active_data_summary_ns = function() {+ #' Get unique labels for the modules to avoid namespace conflicts. |
|
236 | -! | +||
356 | +
- if (identical(private$ns$data_summary, character(0))) {+ #' |
||
237 | -! | +||
357 | +
- private$set_active_ns()+ #' @param labels (`character`) vector of labels |
||
238 | +358 |
- }+ #' |
|
239 | -! | +||
359 | +
- private$ns$data_summary+ #' @return (`character`) vector of unique labels |
||
240 | +360 |
- },+ #' |
|
241 | +361 |
- #' @description+ #' @keywords internal |
|
242 | +362 |
- #' Get the active shiny name space bound with a custom `element` name.+ get_unique_labels <- function(labels) { |
|
243 | -+ | ||
363 | +215x |
- #'+ make.unique(gsub("[^[:alnum:]]", "_", tolower(labels)), sep = "_") |
|
244 | +364 |
- #' @param element `character(1)` custom element name.+ } |
|
245 | +365 |
- #'+ |
|
246 | +366 |
- #' @return (`string`) The active shiny name space of the component bound with the input `element`.+ #' Remove ANSI escape sequences from a string |
|
247 | +367 |
- active_data_summary_element = function(element) {+ #' @noRd |
|
248 | -! | +||
368 | +
- checkmate::assert_string(element)+ strip_style <- function(string) { |
||
249 | -! | +||
369 | +2x |
- sprintf("#%s-%s", self$active_data_summary_ns(), element)+ checkmate::assert_string(string) |
|
250 | +370 |
- },+ |
|
251 | -+ | ||
371 | +2x |
- #' @description+ gsub( |
|
252 | -+ | ||
372 | +2x |
- #' Get the input from the module in the `teal` app.+ "(?:(?:\\x{001b}\\[)|\\x{009b})(?:(?:[0-9]{1,3})?(?:(?:;[0-9]{0,3})*)?[A-M|f-m])|\\x{001b}[A-M]", |
|
253 | +373 |
- #' This function will only access inputs from the name space of the current active teal module.+ "", |
|
254 | -+ | ||
374 | +2x |
- #'+ string, |
|
255 | -+ | ||
375 | +2x |
- #' @param input_id (character) The shiny input id to get the value from.+ perl = TRUE, |
|
256 | -+ | ||
376 | +2x |
- #'+ useBytes = TRUE |
|
257 | +377 |
- #' @return The value of the shiny input.+ ) |
|
258 | +378 |
- get_active_module_input = function(input_id) {- |
- |
259 | -! | -
- checkmate::check_string(input_id)+ } |
|
260 | -! | +||
379 | +
- self$get_value(input = sprintf("%s-%s", self$active_module_ns(), input_id))+ |
||
261 | +380 |
- },+ #' @keywords internal |
|
262 | +381 |
- #' @description+ #' @noRd |
|
263 | -+ | ||
382 | +4x |
- #' Get the output from the module in the `teal` app.+ pasten <- function(...) paste0(..., "\n") |
|
264 | +383 |
- #' This function will only access outputs from the name space of the current active teal module.+ |
|
265 | +384 |
- #'+ #' Convert character list to human readable html with commas and "and" |
|
266 | +385 |
- #' @param output_id (character) The shiny output id to get the value from.+ #' @noRd |
|
267 | +386 |
- #'+ paste_datanames_character <- function(x, |
|
268 | +387 |
- #' @return The value of the shiny output.+ tags = list(span = shiny::tags$span, code = shiny::tags$code), |
|
269 | +388 |
- get_active_module_output = function(output_id) {+ tagList = shiny::tagList) { # nolint: object_name. |
|
270 | +389 | ! |
- checkmate::check_string(output_id)+ checkmate::assert_character(x) |
271 | +390 | ! |
- self$get_value(output = sprintf("%s-%s", self$active_module_ns(), output_id))+ do.call( |
272 | -+ | ||
391 | +! |
- },+ tagList, |
|
273 | -+ | ||
392 | +! |
- #' @description+ lapply(seq_along(x), function(.ix) { |
|
274 | -+ | ||
393 | +! |
- #' Get the output from the module's `teal.widgets::table_with_settings` or `DT::DTOutput` in the `teal` app.+ tagList( |
|
275 | -+ | ||
394 | +! |
- #' This function will only access outputs from the name space of the current active teal module.+ tags$code(x[.ix]),+ |
+ |
395 | +! | +
+ if (.ix != length(x)) {+ |
+ |
396 | +! | +
+ tags$span(ifelse(.ix == length(x) - 1, " and ", ", ")) |
|
276 | +397 |
- #'+ } |
|
277 | +398 |
- #' @param table_id (`character(1)`) The id of the table in the active teal module's name space.+ ) |
|
278 | +399 |
- #' @param which (integer) If there is more than one table, which should be extracted.+ }) |
|
279 | +400 |
- #' By default it will look for a table that is built using `teal.widgets::table_with_settings`.+ ) |
|
280 | +401 |
- #'+ } |
|
281 | +402 |
- #' @return The data.frame with table contents.+ |
|
282 | +403 |
- get_active_module_table_output = function(table_id, which = 1) {+ #' Build datanames error string for error message |
|
283 | -! | +||
404 | +
- checkmate::check_number(which, lower = 1)+ #' |
||
284 | -! | +||
405 | +
- checkmate::check_string(table_id)+ #' tags and tagList are overwritten in arguments allowing to create strings for |
||
285 | -! | +||
406 | +
- table <- rvest::html_table(+ #' logging purposes |
||
286 | -! | +||
407 | +
- self$get_html_rvest(self$active_module_element(table_id)),+ #' @noRd |
||
287 | -! | +||
408 | +
- fill = TRUE+ build_datanames_error_message <- function(label = NULL, |
||
288 | +409 |
- )+ datanames,+ |
+ |
410 | ++ |
+ extra_datanames,+ |
+ |
411 | ++ |
+ tags = list(span = shiny::tags$span, code = shiny::tags$code),+ |
+ |
412 | ++ |
+ tagList = shiny::tagList) { # nolint: object_name. |
|
289 | +413 | ! |
- if (length(table) == 0) {+ tags$span( |
290 | +414 | ! |
- data.frame()+ tags$span(ifelse(length(extra_datanames) > 1, "Datasets", "Dataset")), |
291 | -+ | ||
415 | +! |
- } else {+ paste_datanames_character(extra_datanames, tags, tagList), |
|
292 | +416 | ! |
- table[[which]]+ tags$span( |
293 | -+ | ||
417 | +! |
- }+ paste0( |
|
294 | -+ | ||
418 | +! |
- },+ ifelse(length(extra_datanames) > 1, "are missing", "is missing"), |
|
295 | -+ | ||
419 | +! |
- #' @description+ ifelse(is.null(label), ".", sprintf(" for tab '%s'.", label)) |
|
296 | +420 |
- #' Get the output from the module's `teal.widgets::plot_with_settings` in the `teal` app.+ ) |
|
297 | +421 |
- #' This function will only access plots from the name space of the current active teal module.+ ), |
|
298 | -+ | ||
422 | +! |
- #'+ if (length(datanames) >= 1) { |
|
299 | -+ | ||
423 | +! |
- #' @param plot_id (`character(1)`) The id of the plot in the active teal module's name space.+ tagList( |
|
300 | -+ | ||
424 | +! |
- #'+ tags$span(ifelse(length(datanames) > 1, "Datasets", "Dataset")), |
|
301 | -+ | ||
425 | +! |
- #' @return The `src` attribute as `character(1)` vector.+ tags$span("available in data:"), |
|
302 | -+ | ||
426 | +! |
- get_active_module_plot_output = function(plot_id) {+ tagList( |
|
303 | +427 | ! |
- checkmate::check_string(plot_id)+ tags$span( |
304 | +428 | ! |
- self$get_attr(+ paste_datanames_character(datanames, tags, tagList), |
305 | +429 | ! |
- self$active_module_element(sprintf("%s-plot_main > img", plot_id)),+ tags$span(".", .noWS = "outside"), |
306 | +430 | ! |
- "src"+ .noWS = c("outside") |
307 | +431 |
- )+ ) |
|
308 | +432 |
- },+ ) |
|
309 | +433 |
- #' @description+ ) |
|
310 | +434 |
- #' Set the input in the module in the `teal` app.+ } else {+ |
+ |
435 | +! | +
+ tags$span("No datasets are available in data.") |
|
311 | +436 |
- #' This function will only set inputs in the name space of the current active teal module.+ } |
|
312 | +437 |
- #'+ ) |
|
313 | +438 |
- #' @param input_id (character) The shiny input id to get the value from.+ } |
|
314 | +439 |
- #' @param value The value to set the input to.+ |
|
315 | +440 |
- #' @param ... Additional arguments to be passed to `shinytest2::AppDriver$set_inputs`+ #' Smart `rbind` |
|
316 | +441 |
- #'+ #' |
|
317 | +442 |
- #' @return The `TealAppDriver` object invisibly.+ #' Combine `data.frame` objects which have different columns |
|
318 | +443 |
- set_active_module_input = function(input_id, value, ...) {+ #' |
|
319 | -! | +||
444 | +
- checkmate::check_string(input_id)+ #' @param ... (`data.frame`) |
||
320 | -! | +||
445 | +
- checkmate::check_string(value)+ #' @keywords internal |
||
321 | -! | +||
446 | +
- self$set_input(+ .smart_rbind <- function(...) { |
||
322 | -! | +||
447 | +82x |
- sprintf("%s-%s", self$active_module_ns(), input_id),+ dots <- list(...) |
|
323 | -! | +||
448 | +82x |
- value,+ checkmate::assert_list(dots, "data.frame", .var.name = "...") |
|
324 | -+ | ||
449 | +82x |
- ...+ Reduce( |
|
325 | -+ | ||
450 | +82x |
- )+ x = dots, |
|
326 | -! | +||
451 | +82x |
- dots <- rlang::list2(...)+ function(x, y) { |
|
327 | -! | +||
452 | +69x |
- if (!isFALSE(dots[["wait"]])) self$wait_for_idle() # Default behavior is to wait+ all_columns <- union(colnames(x), colnames(y)) |
|
328 | -! | +||
453 | +69x |
- invisible(self)+ x[setdiff(all_columns, colnames(x))] <- NA |
|
329 | -+ | ||
454 | +69x |
- },+ y[setdiff(all_columns, colnames(y))] <- NA |
|
330 | -+ | ||
455 | +69x |
- #' @description+ rbind(x, y) |
|
331 | +456 |
- #' Get the active datasets that can be accessed via the filter panel of the current active teal module.+ } |
|
332 | +457 |
- get_active_filter_vars = function() {+ ) |
|
333 | -! | +||
458 | +
- displayed_datasets_index <- self$is_visible(+ } |
||
334 | -! | +
1 | +
- sprintf("#%s-filters-filter_active_vars_contents > span", self$active_filters_ns())+ #' Manage multiple `FilteredData` objects |
||
335 | +2 |
- )+ #' |
|
336 | +3 |
-
+ #' @description |
|
337 | -! | +||
4 | +
- available_datasets <- self$get_text(+ #' Oversee filter states across the entire application. |
||
338 | -! | +||
5 | +
- sprintf(+ #' |
||
339 | -! | +||
6 | +
- "#%s-filters-filter_active_vars_contents .filter_panel_dataname",+ #' @section Slices global: |
||
340 | -! | +||
7 | +
- self$active_filters_ns()+ #' The key role in maintaining the module-specific filter states is played by the `.slicesGlobal` |
||
341 | +8 |
- )+ #' object. It is a reference class that holds the following fields: |
|
342 | +9 |
- )+ #' - `all_slices` (`reactiveVal`) - reactive value containing all filters registered in an app. |
|
343 | +10 |
-
+ #' - `module_slices_api` (`reactiveValues`) - reactive field containing references to each modules' |
|
344 | -! | +||
11 | +
- available_datasets[displayed_datasets_index]+ #' `FilteredData` object methods. At this moment it is used only in `srv_filter_manager` to display |
||
345 | +12 |
- },+ #' the filter states in a table combining informations from `all_slices` and from |
|
346 | +13 |
- #' @description+ #' `FilteredData$get_available_teal_slices()`. |
|
347 | +14 |
- #' Get the active data summary table+ #' |
|
348 | +15 |
- #' @return `data.frame`+ #' During a session only new filters are added to `all_slices` unless [`module_snapshot_manager`] is |
|
349 | +16 |
- get_active_data_summary_table = function() {+ #' used to restore previous state. Filters from `all_slices` can be activated or deactivated in a |
|
350 | -! | +||
17 | +
- summary_table <- rvest::html_table(+ #' module which is linked (both ways) by `attr(, "mapping")` so that: |
||
351 | -! | +||
18 | +
- self$get_html_rvest(self$active_data_summary_element("table")),+ #' - If module's filter is added or removed in its `FilteredData` object, this information is passed |
||
352 | -! | +||
19 | +
- fill = TRUE+ #' to `SlicesGlobal` which updates `attr(, "mapping")` accordingly. |
||
353 | -! | +||
20 | +
- )[[1]]+ #' - When mapping changes in a `SlicesGlobal`, filters are set or removed from module's |
||
354 | +21 | - - | -|
355 | -! | -
- col_names <- unlist(summary_table[1, ], use.names = FALSE)+ #' `FilteredData`. |
|
356 | -! | +||
22 | +
- summary_table <- summary_table[-1, ]+ #' |
||
357 | -! | +||
23 | +
- colnames(summary_table) <- col_names+ #' @section Filter manager: |
||
358 | -! | +||
24 | +
- if (nrow(summary_table) > 0) {+ #' Filter-manager is split into two parts: |
||
359 | -! | +||
25 | +
- summary_table+ #' 1. `ui/srv_filter_manager_panel` - Called once for the whole app. This module observes changes in |
||
360 | +26 |
- } else {+ #' the filters in `slices_global` and displays them in a table utilizing information from `mapping`: |
|
361 | -! | +||
27 | +
- NULL+ #' - (`TRUE`) - filter is active in the module |
||
362 | +28 |
- }+ #' - (`FALSE`) - filter is inactive in the module |
|
363 | +29 |
- },+ #' - (`NA`) - filter is not available in the module |
|
364 | +30 |
- #' @description+ #' 2. `ui/srv_module_filter_manager` - Called once for each `teal_module`. Handling filter states |
|
365 | +31 |
- #' Test if `DOM` elements are visible on the page with a JavaScript call.+ #' for of single module and keeping module `FilteredData` consistent with `slices_global`, so that |
|
366 | +32 |
- #' @param selector (`character(1)`) `CSS` selector to check visibility.+ #' local filters are always reflected in the `slices_global` and its mapping and vice versa. |
|
367 | +33 |
- #' A `CSS` id will return only one element if the UI is well formed.+ #' |
|
368 | +34 |
- #' @param content_visibility_auto,opacity_property,visibility_property (`logical(1)`) See more information+ #' |
|
369 | +35 |
- #' on <https://developer.mozilla.org/en-US/docs/Web/API/Element/checkVisibility>.+ #' @param id (`character(1)`) |
|
370 | +36 |
- #'+ #' `shiny` module instance id. |
|
371 | +37 |
- #' @return Logical vector with all occurrences of the selector.+ #' |
|
372 | +38 |
- is_visible = function(selector,+ #' @param slices_global (`reactiveVal`) |
|
373 | +39 |
- content_visibility_auto = FALSE,+ #' containing `teal_slices`. |
|
374 | +40 |
- opacity_property = FALSE,+ #' |
|
375 | +41 |
- visibility_property = FALSE) {+ #' @param module_fd (`FilteredData`) |
|
376 | -! | +||
42 | +
- checkmate::assert_string(selector)+ #' Object containing the data to be filtered in a single `teal` module. |
||
377 | -! | +||
43 | +
- checkmate::assert_flag(content_visibility_auto)+ #' |
||
378 | -! | +||
44 | +
- checkmate::assert_flag(opacity_property)+ #' @return |
||
379 | -! | +||
45 | +
- checkmate::assert_flag(visibility_property)+ #' Module returns a `slices_global` (`reactiveVal`) containing a `teal_slices` object with mapping. |
||
380 | +46 |
-
+ #' |
|
381 | -! | +||
47 | +
- private$wait_for_page_stability()+ #' @encoding UTF-8 |
||
382 | +48 |
-
+ #' |
|
383 | -! | +||
49 | +
- testthat::skip_if_not(+ #' @name module_filter_manager |
||
384 | -! | +||
50 | +
- self$get_js("typeof Element.prototype.checkVisibility === 'function'"),+ #' @rdname module_filter_manager |
||
385 | -! | +||
51 | +
- "Element.prototype.checkVisibility is not supported in the current browser."+ #' |
||
386 | +52 |
- )+ NULL |
|
387 | +53 | ||
388 | -! | +||
54 | +
- unlist(+ #' @rdname module_filter_manager |
||
389 | -! | +||
55 | +
- self$get_js(+ ui_filter_manager_panel <- function(id) { |
||
390 | +56 | ! |
- sprintf(+ ns <- NS(id) |
391 | +57 | ! |
- "Array.from(document.querySelectorAll('%s')).map(el => el.checkVisibility({%s, %s, %s}))",+ tags$button( |
392 | +58 | ! |
- selector,- |
-
393 | -- |
- # Extra parameters+ id = ns("show_filter_manager"), |
|
394 | +59 | ! |
- sprintf("contentVisibilityAuto: %s", tolower(content_visibility_auto)),+ class = "btn action-button wunder_bar_button", |
395 | +60 | ! |
- sprintf("opacityProperty: %s", tolower(opacity_property)),+ title = "View filter mapping", |
396 | +61 | ! |
- sprintf("visibilityProperty: %s", tolower(visibility_property))- |
-
397 | -- |
- )- |
- |
398 | -- |
- )- |
- |
399 | -- |
- )- |
- |
400 | -- |
- },+ suppressMessages(icon("fas fa-grip")) |
|
401 | +62 |
- #' @description+ ) |
|
402 | +63 |
- #' Get the active filter variables from a dataset in the `teal` app.+ } |
|
403 | +64 |
- #'+ |
|
404 | +65 |
- #' @param dataset_name (character) The name of the dataset to get the filter variables from.+ #' @rdname module_filter_manager |
|
405 | +66 |
- #' If `NULL`, the filter variables for all the datasets will be returned in a list.+ #' @keywords internal |
|
406 | +67 |
- get_active_data_filters = function(dataset_name = NULL) {- |
- |
407 | -! | -
- checkmate::check_string(dataset_name, null.ok = TRUE)+ srv_filter_manager_panel <- function(id, slices_global) { |
|
408 | -! | +||
68 | +82x |
- datasets <- self$get_active_filter_vars()+ checkmate::assert_string(id) |
|
409 | -! | +||
69 | +82x |
- checkmate::assert_subset(dataset_name, datasets)+ checkmate::assert_class(slices_global, ".slicesGlobal") |
|
410 | -! | +||
70 | +82x |
- active_filters <- lapply(+ moduleServer(id, function(input, output, session) { |
|
411 | -! | +||
71 | +82x |
- datasets,+ setBookmarkExclude(c("show_filter_manager")) |
|
412 | -! | +||
72 | +82x |
- function(x) {+ observeEvent(input$show_filter_manager, { |
|
413 | +73 | ! |
- var_names <- gsub(+ logger::log_debug("srv_filter_manager_panel@1 show_filter_manager button has been clicked.") |
414 | +74 | ! |
- pattern = "\\s",+ showModal( |
415 | +75 | ! |
- replacement = "",+ modalDialog( |
416 | +76 | ! |
- self$get_text(+ ui_filter_manager(session$ns("filter_manager")), |
417 | +77 | ! |
- sprintf(+ class = "filter_manager_modal", |
418 | +78 | ! |
- "#%s-filters-%s .filter-card-varname",+ size = "l", |
419 | +79 | ! |
- self$active_filters_ns(),+ footer = NULL, |
420 | +80 | ! |
- x+ easyClose = TRUE |
421 | +81 |
- )+ ) |
|
422 | +82 |
- )+ ) |
|
423 | +83 |
- )+ }) |
|
424 | -! | +||
84 | +82x |
- structure(+ srv_filter_manager("filter_manager", slices_global = slices_global) |
|
425 | -! | +||
85 | +
- lapply(var_names, private$get_active_filter_selection, dataset_name = x),+ }) |
||
426 | -! | +||
86 | +
- names = var_names+ } |
||
427 | +87 |
- )+ |
|
428 | +88 |
- }+ #' @rdname module_filter_manager |
|
429 | +89 |
- )+ ui_filter_manager <- function(id) { |
|
430 | +90 | ! |
- names(active_filters) <- datasets+ ns <- NS(id) |
431 | +91 | ! |
- if (is.null(dataset_name)) {+ actionButton(ns("filter_manager"), NULL, icon = icon("fas fa-filter")) |
432 | +92 | ! |
- return(active_filters)+ tags$div( |
433 | -+ | ||
93 | +! |
- }+ class = "filter_manager_content", |
|
434 | +94 | ! |
- active_filters[[dataset_name]]+ tableOutput(ns("slices_table")) |
435 | +95 |
- },+ ) |
|
436 | +96 |
- #' @description+ } |
|
437 | +97 |
- #' Add a new variable from the dataset to be filtered.+ |
|
438 | +98 |
- #'+ #' @rdname module_filter_manager |
|
439 | +99 |
- #' @param dataset_name (character) The name of the dataset to add the filter variable to.+ srv_filter_manager <- function(id, slices_global) { |
|
440 | -+ | ||
100 | +82x |
- #' @param var_name (character) The name of the variable to add to the filter panel.+ checkmate::assert_string(id) |
|
441 | -+ | ||
101 | +82x |
- #' @param ... Additional arguments to be passed to `shinytest2::AppDriver$set_inputs`+ checkmate::assert_class(slices_global, ".slicesGlobal") |
|
442 | +102 |
- #'+ + |
+ |
103 | +82x | +
+ moduleServer(id, function(input, output, session) {+ |
+ |
104 | +82x | +
+ logger::log_debug("filter_manager_srv initializing.") |
|
443 | +105 |
- #' @return The `TealAppDriver` object invisibly.+ |
|
444 | +106 |
- add_filter_var = function(dataset_name, var_name, ...) {+ # Bookmark slices global with mapping. |
|
445 | -! | +||
107 | +82x |
- checkmate::check_string(dataset_name)+ session$onBookmark(function(state) { |
|
446 | +108 | ! |
- checkmate::check_string(var_name)+ logger::log_debug("filter_manager_srv@onBookmark: storing filter state") |
447 | -! | -
- private$set_active_ns()- |
- |
448 | -! | -
- self$click(- |
- |
449 | -! | -
- selector = sprintf(- |
- |
450 | +109 | ! |
- "#%s-filters-%s-add_filter_icon",+ state$values$filter_state_on_bookmark <- as.list( |
451 | +110 | ! |
- private$ns$filter_panel,+ slices_global$all_slices(), |
452 | +111 | ! |
- dataset_name+ recursive = TRUE |
453 | +112 |
- )+ ) |
|
454 | +113 |
- )+ }) |
|
455 | -! | +||
114 | +
- self$set_input(+ |
||
456 | -! | +||
115 | +82x |
- sprintf(+ bookmarked_slices <- restoreValue(session$ns("filter_state_on_bookmark"), NULL) |
|
457 | -! | +||
116 | +82x |
- "%s-filters-%s-%s-filter-var_to_add",+ if (!is.null(bookmarked_slices)) { |
|
458 | +117 | ! |
- private$ns$filter_panel,+ logger::log_debug("filter_manager_srv: restoring filter state from bookmark.") |
459 | +118 | ! |
- dataset_name,+ slices_global$slices_set(bookmarked_slices) |
460 | -! | +||
119 | +
- dataset_name+ } |
||
461 | +120 |
- ),+ |
|
462 | -! | +||
121 | +82x |
- var_name,+ mapping_table <- reactive({ |
|
463 | +122 |
- ...+ # We want this to be reactive on slices_global$all_slices() only as get_available_teal_slices() |
|
464 | +123 |
- )- |
- |
465 | -! | -
- invisible(self)+ # is dependent on slices_global$all_slices(). |
|
466 | -+ | ||
124 | +91x |
- },+ module_labels <- setdiff( |
|
467 | -+ | ||
125 | +91x |
- #' @description+ names(attr(slices_global$all_slices(), "mapping")), |
|
468 | -+ | ||
126 | +91x |
- #' Remove an active filter variable of a dataset from the active filter variables panel.+ "Report previewer" |
|
469 | +127 |
- #'+ ) |
|
470 | -+ | ||
128 | +91x |
- #' @param dataset_name (character) The name of the dataset to remove the filter variable from.+ isolate({ |
|
471 | -+ | ||
129 | +91x |
- #' If `NULL`, all the filter variables will be removed.+ mm <- as.data.frame( |
|
472 | -+ | ||
130 | +91x |
- #' @param var_name (character) The name of the variable to remove from the filter panel.+ sapply( |
|
473 | -+ | ||
131 | +91x |
- #' If `NULL`, all the filter variables of the dataset will be removed.+ module_labels, |
|
474 | -+ | ||
132 | +91x |
- #'+ simplify = FALSE, |
|
475 | -+ | ||
133 | +91x |
- #' @return The `TealAppDriver` object invisibly.+ function(module_label) { |
|
476 | -+ | ||
134 | +104x |
- remove_filter_var = function(dataset_name = NULL, var_name = NULL) {+ available_slices <- slices_global$module_slices_api[[module_label]]$get_available_teal_slices() |
|
477 | -! | +||
135 | +96x |
- checkmate::check_string(dataset_name, null.ok = TRUE)+ global_ids <- sapply(slices_global$all_slices(), `[[`, "id", simplify = FALSE) |
|
478 | -! | +||
136 | +96x |
- checkmate::check_string(var_name, null.ok = TRUE)+ module_ids <- sapply(slices_global$slices_get(module_label), `[[`, "id", simplify = FALSE) |
|
479 | -! | +||
137 | +96x |
- if (is.null(dataset_name)) {+ allowed_ids <- vapply(available_slices, `[[`, character(1L), "id") |
|
480 | -! | +||
138 | +96x |
- remove_selector <- sprintf(+ active_ids <- global_ids %in% module_ids |
|
481 | -! | +||
139 | +96x |
- "#%s-active-remove_all_filters",+ setNames(nm = global_ids, ifelse(global_ids %in% allowed_ids, active_ids, NA)) |
|
482 | -! | +||
140 | +
- self$active_filters_ns()+ } |
||
483 | +141 |
- )+ ), |
|
484 | -! | +||
142 | +91x |
- } else if (is.null(var_name)) {+ check.names = FALSE |
|
485 | -! | +||
143 | +
- remove_selector <- sprintf(+ ) |
||
486 | -! | +||
144 | +83x |
- "#%s-active-%s-remove_filters",+ colnames(mm)[colnames(mm) == "global_filters"] <- "Global filters" |
|
487 | -! | +||
145 | +
- self$active_filters_ns(),+ |
||
488 | -! | +||
146 | +83x |
- dataset_name+ mm |
|
489 | +147 |
- )+ }) |
|
490 | +148 |
- } else {+ }) |
|
491 | -! | +||
149 | +
- remove_selector <- sprintf(+ |
||
492 | -! | +||
150 | +82x |
- "#%s-active-%s-filter-%s_%s-remove",+ output$slices_table <- renderTable( |
|
493 | -! | +||
151 | +82x |
- self$active_filters_ns(),+ expr = { |
|
494 | -! | +||
152 | +91x |
- dataset_name,+ logger::log_debug("filter_manager_srv@1 rendering slices_table.") |
|
495 | -! | +||
153 | +91x |
- dataset_name,+ mm <- mapping_table() |
|
496 | -! | +||
154 | +
- var_name+ |
||
497 | +155 |
- )+ # Display logical values as UTF characters. |
|
498 | -+ | ||
156 | +83x |
- }+ mm[] <- lapply(mm, ifelse, yes = intToUtf8(9989), no = intToUtf8(10060)) |
|
499 | -! | +||
157 | +83x |
- self$click(+ mm[] <- lapply(mm, function(x) ifelse(is.na(x), intToUtf8(128306), x)) |
|
500 | -! | +||
158 | +
- selector = remove_selector+ |
||
501 | +159 |
- )+ # Display placeholder if no filters defined. |
|
502 | -! | +||
160 | +83x |
- invisible(self)+ if (nrow(mm) == 0L) { |
|
503 | -+ | ||
161 | +59x |
- },+ mm <- data.frame(`Filter manager` = "No filters specified.", check.names = FALSE) |
|
504 | -+ | ||
162 | +59x |
- #' @description+ rownames(mm) <- "" |
|
505 | +163 |
- #' Set the active filter values for a variable of a dataset in the active filter variable panel.+ } |
|
506 | -+ | ||
164 | +83x |
- #'+ mm |
|
507 | +165 |
- #' @param dataset_name (character) The name of the dataset to set the filter value for.+ }, |
|
508 | -+ | ||
166 | +82x |
- #' @param var_name (character) The name of the variable to set the filter value for.+ rownames = TRUE |
|
509 | +167 |
- #' @param input The value to set the filter to.+ ) |
|
510 | +168 |
- #' @param ... Additional arguments to be passed to `shinytest2::AppDriver$set_inputs`+ |
|
511 | -+ | ||
169 | +82x |
- #'+ mapping_table # for testing purpose |
|
512 | +170 |
- #' @return The `TealAppDriver` object invisibly.+ }) |
|
513 | +171 |
- set_active_filter_selection = function(dataset_name,+ } |
|
514 | +172 |
- var_name,+ |
|
515 | +173 |
- input,+ #' @rdname module_filter_manager |
|
516 | +174 |
- ...) {+ srv_module_filter_manager <- function(id, module_fd, slices_global) { |
|
517 | -! | +||
175 | +107x |
- checkmate::check_string(dataset_name)+ checkmate::assert_string(id) |
|
518 | -! | +||
176 | +107x |
- checkmate::check_string(var_name)+ assert_reactive(module_fd) |
|
519 | -! | +||
177 | +107x |
- checkmate::check_string(input)+ checkmate::assert_class(slices_global, ".slicesGlobal") |
|
520 | +178 | ||
521 | -! | +||
179 | +107x |
- input_id_prefix <- sprintf(+ moduleServer(id, function(input, output, session) { |
|
522 | -! | +||
180 | +107x |
- "%s-filters-%s-filter-%s_%s-inputs",+ logger::log_debug("srv_module_filter_manager initializing for module: { id }.") |
|
523 | -! | +||
181 | +
- self$active_filters_ns(),+ # Track filter global and local states. |
||
524 | -! | +||
182 | +107x |
- dataset_name,- |
- |
525 | -! | -
- dataset_name,+ slices_global_module <- reactive({ |
|
526 | -! | +||
183 | +193x |
- var_name+ slices_global$slices_get(module_label = id) |
|
527 | +184 |
- )+ }) |
|
528 | -+ | ||
185 | +107x |
-
+ slices_module <- reactive(req(module_fd())$get_filter_state()) |
|
529 | +186 |
- # Find the type of filter (based on filter panel)+ |
|
530 | -! | +||
187 | +107x |
- supported_suffix <- c("selection", "selection_manual")+ module_fd_previous <- reactiveVal(NULL) |
|
531 | -! | +||
188 | +
- slices_suffix <- supported_suffix[+ |
||
532 | -! | +||
189 | +
- match(+ # Set (reactively) available filters for the module. |
||
533 | -! | +||
190 | +107x |
- TRUE,+ obs1 <- observeEvent(module_fd(), priority = 1, { |
|
534 | -! | +||
191 | +88x |
- vapply(+ logger::log_debug("srv_module_filter_manager@1 setting initial slices for module: { id }.") |
|
535 | -! | +||
192 | +
- supported_suffix,+ # Filters relevant for the module in module-specific app. |
||
536 | -! | +||
193 | +88x |
- function(suffix) {+ slices <- slices_global_module() |
|
537 | -! | +||
194 | +
- !is.null(self$get_html(sprintf("#%s-%s", input_id_prefix, suffix)))+ |
||
538 | +195 |
- },+ # Clean up previous filter states and refresh cache of previous module_fd with current |
|
539 | -! | +||
196 | +3x |
- logical(1)+ if (!is.null(module_fd_previous())) module_fd_previous()$finalize() |
|
540 | -+ | ||
197 | +88x |
- )+ module_fd_previous(module_fd()) |
|
541 | +198 |
- )+ |
|
542 | +199 |
- ]+ # Setting filter states from slices_global: |
|
543 | +200 |
-
+ # 1. when app initializes slices_global set to initial filters (specified by app developer) |
|
544 | +201 |
- # Generate correct namespace+ # 2. when data reinitializes slices_global reflects latest filter states |
|
545 | -! | +||
202 | +
- slices_input_id <- sprintf(+ |
||
546 | -! | +||
203 | +88x |
- "%s-filters-%s-filter-%s_%s-inputs-%s",+ module_fd()$set_filter_state(slices) |
|
547 | -! | +||
204 | +
- self$active_filters_ns(),+ |
||
548 | -! | +||
205 | +
- dataset_name,+ # irrelevant filters are discarded in FilteredData$set_available_teal_slices |
||
549 | -! | +||
206 | +
- dataset_name,+ # it means we don't need to subset slices_global$all_slices() from filters refering to irrelevant datasets |
||
550 | -! | +||
207 | +88x |
- var_name,+ module_fd()$set_available_teal_slices(slices_global$all_slices) |
|
551 | -! | +||
208 | +
- slices_suffix+ |
||
552 | +209 |
- )+ # this needed in filter_manager_srv |
|
553 | -+ | ||
210 | +88x |
-
+ slices_global$module_slices_api_set( |
|
554 | -! | +||
211 | +88x |
- if (identical(slices_suffix, "selection_manual")) {+ id, |
|
555 | -! | +||
212 | +88x |
- checkmate::assert_numeric(input, len = 2)+ list( |
|
556 | -+ | ||
213 | +88x |
-
+ get_available_teal_slices = module_fd()$get_available_teal_slices(), |
|
557 | -! | +||
214 | +88x |
- dots <- rlang::list2(...)+ set_filter_state = module_fd()$set_filter_state, # for testing purpose |
|
558 | -! | +||
215 | +88x |
- checkmate::assert_choice(dots$priority_, formals(self$set_inputs)[["priority_"]], null.ok = TRUE)+ get_filter_state = module_fd()$get_filter_state # for testing purpose |
|
559 | -! | +||
216 | +
- checkmate::assert_flag(dots$wait_, null.ok = TRUE)+ ) |
||
560 | +217 |
-
+ ) |
|
561 | -! | +||
218 | +
- self$run_js(+ }) |
||
562 | -! | +||
219 | +
- sprintf(+ |
||
563 | -! | +||
220 | +
- "Shiny.setInputValue('%s:sw.numericRange', [%f, %f], {priority: '%s'})",+ # Update global state and mapping matrix when module filters change. |
||
564 | -! | +||
221 | +107x |
- slices_input_id,+ obs2 <- observeEvent(slices_module(), priority = 0, { |
|
565 | -! | +||
222 | +110x |
- input[[1]],+ this_slices <- slices_module() |
|
566 | -! | +||
223 | +110x |
- input[[2]],+ slices_global$slices_append(this_slices) # append new slices to the all_slices list |
|
567 | -! | +||
224 | +110x |
- priority_ = ifelse(is.null(dots$priority_), "input", dots$priority_)+ mapping_elem <- setNames(nm = id, list(vapply(this_slices, `[[`, character(1L), "id"))) |
|
568 | -+ | ||
225 | +110x |
- )+ slices_global$slices_active(mapping_elem) |
|
569 | +226 |
- )+ }) |
|
570 | +227 | ||
571 | -! | +||
228 | +107x |
- if (isTRUE(dots$wait_) || is.null(dots$wait_)) {+ obs3 <- observeEvent(slices_global_module(), { |
|
572 | -! | +||
229 | +130x |
- self$wait_for_idle(+ global_vs_module <- setdiff_teal_slices(slices_global_module(), slices_module()) |
|
573 | -! | +||
230 | +130x |
- timeout = if (is.null(dots$timeout_)) rlang::missing_arg() else dots$timeout_+ module_vs_global <- setdiff_teal_slices(slices_module(), slices_global_module()) |
|
574 | -+ | ||
231 | +121x |
- )+ if (length(global_vs_module) || length(module_vs_global)) { |
|
575 | +232 |
- }+ # Comment: (Nota Bene) Normally new filters for a module are added through module-filter-panel, and slices |
|
576 | -! | +||
233 | +
- } else if (identical(slices_suffix, "selection")) {+ # global are updated automatically so slices_module -> slices_global_module are equal. |
||
577 | -! | +||
234 | +
- self$set_input(+ # this if is valid only when a change is made on the global level so the change needs to be propagated down |
||
578 | -! | +||
235 | +
- slices_input_id,+ # to the module (for example through snapshot manager). If it happens both slices are different |
||
579 | -! | +||
236 | +13x |
- input,+ logger::log_debug("srv_module_filter_manager@3 (N.B.) global state has changed for a module:{ id }.") |
|
580 | -+ | ||
237 | +13x |
- ...+ module_fd()$clear_filter_states() |
|
581 | -+ | ||
238 | +13x |
- )+ module_fd()$set_filter_state(slices_global_module()) |
|
582 | +239 |
- } else {- |
- |
583 | -! | -
- stop("Filter selection set not supported for this slice.")+ } |
|
584 | +240 |
- }+ }) |
|
585 | +241 | ||
586 | -! | +||
242 | +107x |
- invisible(self)+ slices_module # returned for testing purpose |
|
587 | +243 |
- },+ }) |
|
588 | +244 |
- #' @description+ } |
|
589 | +245 |
- #' Extract `html` attribute (found by a `selector`).+ |
|
590 | +246 |
- #'+ #' @importFrom shiny reactiveVal reactiveValues |
|
591 | +247 |
- #' @param selector (`character(1)`) specifying the selector to be used to get the content of a specific node.+ methods::setOldClass("reactiveVal") |
|
592 | +248 |
- #' @param attribute (`character(1)`) name of an attribute to retrieve from a node specified by `selector`.+ methods::setOldClass("reactivevalues") |
|
593 | +249 |
- #'+ |
|
594 | +250 |
- #' @return The `character` vector.+ #' @importFrom methods new |
|
595 | +251 |
- get_attr = function(selector, attribute) {- |
- |
596 | -! | -
- rvest::html_attr(- |
- |
597 | -! | -
- rvest::html_nodes(self$get_html_rvest("html"), selector),- |
- |
598 | -! | -
- attribute+ #' @rdname module_filter_manager |
|
599 | +252 |
- )+ .slicesGlobal <- methods::setRefClass(".slicesGlobal", # nolint: object_name. |
|
600 | +253 |
- },+ fields = list( |
|
601 | +254 |
- #' @description+ all_slices = "reactiveVal", |
|
602 | +255 |
- #' Wrapper around `get_html` that passes the output directly to `rvest::read_html`.+ module_slices_api = "reactivevalues" |
|
603 | +256 |
- #'+ ), |
|
604 | +257 |
- #' @param selector `(character(1))` passed to `get_html`.+ methods = list( |
|
605 | +258 |
- #'+ initialize = function(slices = teal_slices(), module_labels) { |
|
606 | -+ | ||
259 | +82x |
- #' @return An XML document.+ shiny::isolate({+ |
+ |
260 | +82x | +
+ checkmate::assert_class(slices, "teal_slices") |
|
607 | +261 |
- get_html_rvest = function(selector) {+ # needed on init to not mix "global_filters" with module-specific-slots |
|
608 | -! | +||
262 | +82x |
- rvest::read_html(self$get_html(selector))+ if (isTRUE(attr(slices, "module_specific"))) { |
|
609 | -+ | ||
263 | +11x |
- },+ old_mapping <- attr(slices, "mapping") |
|
610 | -+ | ||
264 | +11x |
- #' Wrapper around `get_url()` method that opens the app in the browser.+ new_mapping <- sapply(module_labels, simplify = FALSE, function(module_label) { |
|
611 | -+ | ||
265 | +20x |
- #'+ unique(unlist(old_mapping[c(module_label, "global_filters")])) |
|
612 | +266 |
- #' @return Nothing. Opens the underlying teal app in the browser.+ })+ |
+ |
267 | +11x | +
+ attr(slices, "mapping") <- new_mapping |
|
613 | +268 |
- open_url = function() {+ } |
|
614 | -! | +||
269 | +82x |
- browseURL(self$get_url())+ .self$all_slices <<- shiny::reactiveVal(slices) |
|
615 | -+ | ||
270 | +82x |
- },+ .self$module_slices_api <<- shiny::reactiveValues() |
|
616 | -+ | ||
271 | +82x |
- #' @description+ .self$slices_append(slices) |
|
617 | -+ | ||
272 | +82x |
- #' Waits until a specified input, output, or export value.+ .self$slices_active(attr(slices, "mapping")) |
|
618 | -+ | ||
273 | +82x |
- #' This function serves as a wrapper around the `wait_for_value` method,+ invisible(.self) |
|
619 | +274 |
- #' providing a more flexible interface for waiting on different types of values within the active module namespace.+ }) |
|
620 | +275 |
- #' @param input,output,export A name of an input, output, or export value.+ }, |
|
621 | +276 |
- #' Only one of these parameters may be used.+ is_module_specific = function() { |
|
622 | -+ | ||
277 | +283x |
- #' @param ... Must be empty. Allows for parameter expansion.+ isTRUE(attr(.self$all_slices(), "module_specific")) |
|
623 | +278 |
- #' Parameter with additional value to passed in `wait_for_value`.+ }, |
|
624 | +279 |
- wait_for_active_module_value = function(input = rlang::missing_arg(),+ module_slices_api_set = function(module_label, functions_list) {+ |
+ |
280 | +88x | +
+ shiny::isolate({+ |
+ |
281 | +88x | +
+ if (!.self$is_module_specific()) {+ |
+ |
282 | +72x | +
+ module_label <- "global_filters" |
|
625 | +283 |
- output = rlang::missing_arg(),+ }+ |
+ |
284 | +88x | +
+ if (!identical(.self$module_slices_api[[module_label]], functions_list)) {+ |
+ |
285 | +88x | +
+ .self$module_slices_api[[module_label]] <- functions_list |
|
626 | +286 |
- export = rlang::missing_arg(),+ }+ |
+ |
287 | +88x | +
+ invisible(.self) |
|
627 | +288 |
- ...) {+ }) |
|
628 | -! | +||
289 | +
- ns <- shiny::NS(self$active_module_ns())+ }, |
||
629 | +290 |
-
+ slices_deactivate_all = function(module_label) { |
|
630 | +291 | ! |
- if (!rlang::is_missing(input) && checkmate::test_string(input, min.chars = 1)) input <- ns(input)+ shiny::isolate({ |
631 | +292 | ! |
- if (!rlang::is_missing(output) && checkmate::test_string(output, min.chars = 1)) output <- ns(output)+ new_slices <- .self$all_slices() |
632 | +293 | ! |
- if (!rlang::is_missing(export) && checkmate::test_string(export, min.chars = 1)) export <- ns(export)+ old_mapping <- attr(new_slices, "mapping") |
633 | +294 | ||
634 | +295 | ! |
- self$wait_for_value(+ new_mapping <- if (.self$is_module_specific()) { |
635 | +296 | ! |
- input = input,+ new_module_mapping <- setNames(nm = module_label, list(character(0))) |
636 | +297 | ! |
- output = output,+ modifyList(old_mapping, new_module_mapping) |
637 | +298 | ! |
- export = export,+ } else if (missing(module_label)) { |
638 | -+ | ||
299 | +! |
- ...+ lapply( |
|
639 | -+ | ||
300 | +! |
- )+ attr(.self$all_slices(), "mapping"), |
|
640 | -+ | ||
301 | +! |
- }+ function(x) character(0) |
|
641 | +302 |
- ),+ ) |
|
642 | +303 |
- # private members ----+ } else { |
|
643 | -+ | ||
304 | +! |
- private = list(+ old_mapping[[module_label]] <- character(0) |
|
644 | -+ | ||
305 | +! |
- # private attributes ----+ old_mapping |
|
645 | +306 |
- data = NULL,+ } |
|
646 | +307 |
- modules = NULL,+ |
|
647 | -+ | ||
308 | +! |
- filter = teal_slices(),+ if (!identical(new_mapping, old_mapping)) { |
|
648 | -+ | ||
309 | +! |
- ns = list(+ logger::log_debug(".slicesGlobal@slices_deactivate_all: deactivating all slices.") |
|
649 | -+ | ||
310 | +! |
- module = character(0),+ attr(new_slices, "mapping") <- new_mapping |
|
650 | -+ | ||
311 | +! |
- filter_panel = character(0)+ .self$all_slices(new_slices) |
|
651 | +312 |
- ),+ } |
|
652 | -+ | ||
313 | +! |
- # private methods ----+ invisible(.self) |
|
653 | +314 |
- set_active_ns = function() {- |
- |
654 | -! | -
- all_inputs <- self$get_values()$input+ }) |
|
655 | -! | +||
315 | +
- active_tab_inputs <- all_inputs[grepl("-active_tab$", names(all_inputs))]+ }, |
||
656 | +316 |
-
+ slices_active = function(mapping_elem) { |
|
657 | -! | +||
317 | +195x |
- tab_ns <- unlist(lapply(names(active_tab_inputs), function(name) {+ shiny::isolate({ |
|
658 | -! | +||
318 | +195x |
- gsub(+ if (.self$is_module_specific()) { |
|
659 | -! | +||
319 | +36x |
- pattern = "-active_tab$",+ new_mapping <- modifyList(attr(.self$all_slices(), "mapping"), mapping_elem) |
|
660 | -! | +||
320 | +
- replacement = sprintf("-%s", active_tab_inputs[[name]]),+ } else { |
||
661 | -! | +||
321 | +159x |
- name+ new_mapping <- setNames(nm = "global_filters", list(unique(unlist(mapping_elem)))) |
|
662 | +322 |
- )+ } |
|
663 | +323 |
- }))+ |
|
664 | -! | +||
324 | +195x |
- active_ns <- tab_ns[1]+ if (!identical(new_mapping, attr(.self$all_slices(), "mapping"))) { |
|
665 | -! | +||
325 | +138x |
- if (length(tab_ns) > 1) {+ mapping_modules <- toString(names(new_mapping)) |
|
666 | -! | +||
326 | +138x |
- for (i in 2:length(tab_ns)) {+ logger::log_debug(".slicesGlobal@slices_active: changing mapping for module(s): { mapping_modules }.") |
|
667 | -! | +||
327 | +138x |
- next_ns <- tab_ns[i]+ new_slices <- .self$all_slices() |
|
668 | -! | +||
328 | +138x |
- if (grepl(pattern = active_ns, next_ns)) {+ attr(new_slices, "mapping") <- new_mapping |
|
669 | -! | +||
329 | +138x |
- active_ns <- next_ns+ .self$all_slices(new_slices) |
|
670 | +330 |
- }+ } |
|
671 | +331 |
- }+ |
|
672 | -+ | ||
332 | +195x |
- }+ invisible(.self) |
|
673 | -! | +||
333 | +
- private$ns$module <- sprintf("%s-%s", active_ns, "module")+ }) |
||
674 | +334 |
-
+ }, |
|
675 | -! | +||
335 | +
- components <- c("filter_panel", "data_summary")+ # - only new filters are appended to the $all_slices |
||
676 | -! | +||
336 | +
- for (component in components) {+ # - mapping is not updated here |
||
677 | +337 |
- if (+ slices_append = function(slices, activate = FALSE) { |
|
678 | -! | +||
338 | +195x |
- !is.null(self$get_html(sprintf("#%s-%s-panel", active_ns, component))) ||+ shiny::isolate({ |
|
679 | -! | -
- !is.null(self$get_html(sprintf("#%s-%s-table", active_ns, component)))- |
- |
680 | -- |
- ) {- |
- |
681 | -! | -
- private$ns[[component]] <- sprintf("%s-%s", active_ns, component)- |
- |
682 | -+ | ||
339 | +195x |
- } else {+ if (!is.teal_slices(slices)) { |
|
683 | +340 | ! |
- private$ns[[component]] <- sprintf("%s-module_%s", active_ns, component)+ slices <- as.teal_slices(slices) |
684 | +341 |
} |
|
685 | +342 |
- }+ |
|
686 | +343 |
- },+ # to make sure that we don't unnecessary trigger $all_slices <reactiveVal> |
|
687 | -+ | ||
344 | +195x |
- # @description+ new_slices <- setdiff_teal_slices(slices, .self$all_slices()) |
|
688 | -+ | ||
345 | +195x |
- # Get the active filter values from the active filter selection of dataset from the filter panel.+ old_mapping <- attr(.self$all_slices(), "mapping") |
|
689 | -+ | ||
346 | +195x |
- #+ if (length(new_slices)) { |
|
690 | -+ | ||
347 | +6x |
- # @param dataset_name (character) The name of the dataset to get the filter values from.+ new_ids <- vapply(new_slices, `[[`, character(1L), "id") |
|
691 | -+ | ||
348 | +6x |
- # @param var_name (character) The name of the variable to get the filter values from.+ logger::log_debug(".slicesGlobal@slices_append: appending new slice(s): { new_ids }.") |
|
692 | -+ | ||
349 | +6x |
- #+ slices_ids <- vapply(.self$all_slices(), `[[`, character(1L), "id") |
|
693 | -+ | ||
350 | +6x |
- # @return The value of the active filter selection.+ lapply(new_slices, function(slice) { |
|
694 | +351 |
- get_active_filter_selection = function(dataset_name, var_name) {+ # In case the new state has the same id as an existing one, add a suffix |
|
695 | -! | +||
352 | +6x |
- checkmate::check_string(dataset_name)+ if (slice$id %in% slices_ids) { |
|
696 | -! | +||
353 | +1x |
- checkmate::check_string(var_name)+ slice$id <- utils::tail(make.unique(c(slices_ids, slice$id), sep = "_"), 1) |
|
697 | -! | +||
354 | +
- input_id_prefix <- sprintf(+ } |
||
698 | -! | +||
355 | +
- "%s-filters-%s-filter-%s_%s-inputs",+ }) |
||
699 | -! | +||
356 | +
- self$active_filters_ns(),+ |
||
700 | -! | +||
357 | +6x |
- dataset_name,+ new_slices_all <- c(.self$all_slices(), new_slices) |
|
701 | -! | +||
358 | +6x |
- dataset_name,+ attr(new_slices_all, "mapping") <- old_mapping |
|
702 | -! | +||
359 | +6x |
- var_name+ .self$all_slices(new_slices_all) |
|
703 | +360 |
- )+ } |
|
704 | +361 | ||
362 | +195x | +
+ invisible(.self)+ |
+ |
705 | +363 |
- # Find the type of filter (categorical or range)+ }) |
|
706 | -! | +||
364 | +
- supported_suffix <- c("selection", "selection_manual")+ }, |
||
707 | -! | +||
365 | +
- for (suffix in supported_suffix) {+ slices_get = function(module_label) { |
||
708 | -! | +||
366 | +289x |
- if (!is.null(self$get_html(sprintf("#%s-%s", input_id_prefix, suffix)))) {+ if (missing(module_label)) { |
|
709 | +367 | ! |
- return(self$get_value(input = sprintf("%s-%s", input_id_prefix, suffix)))- |
-
710 | -- |
- }- |
- |
711 | -- |
- }+ .self$all_slices() |
|
712 | +368 |
-
+ } else { |
|
713 | -! | +||
369 | +289x |
- NULL # If there are not any supported filters+ module_ids <- unlist(attr(.self$all_slices(), "mapping")[c(module_label, "global_filters")]) |
|
714 | -+ | ||
370 | +289x |
- },+ Filter( |
|
715 | -+ | ||
371 | +289x |
- # @description+ function(slice) slice$id %in% module_ids, |
|
716 | -+ | ||
372 | +289x |
- # Check if the page is stable without any `DOM` updates in the body of the app.+ .self$all_slices() |
|
717 | +373 |
- # This is achieved by blocing the R process by sleeping until the page is unchanged till the `stability_period`.+ ) |
|
718 | +374 |
- # @param stability_period (`numeric(1)`) The time in milliseconds to wait till the page to be stable.+ } |
|
719 | +375 |
- # @param check_interval (`numeric(1)`) The time in milliseconds to check for changes in the page.+ }, |
|
720 | +376 |
- # The stability check is reset when a change is detected in the page after sleeping for check_interval.+ slices_set = function(slices) { |
|
721 | -+ | ||
377 | +7x |
- wait_for_page_stability = function(stability_period = 2000, check_interval = 200) {+ shiny::isolate({ |
|
722 | -! | +||
378 | +7x |
- previous_content <- self$get_html("body")+ if (!is.teal_slices(slices)) { |
|
723 | +379 | ! |
- end_time <- Sys.time() + (stability_period / 1000)+ slices <- as.teal_slices(slices) |
724 | +380 | - - | -|
725 | -! | -
- repeat {+ } |
|
726 | -! | +||
381 | +7x |
- Sys.sleep(check_interval / 1000)+ .self$all_slices(slices) |
|
727 | -! | +||
382 | +7x |
- current_content <- self$get_html("body")+ invisible(.self) |
|
728 | +383 | - - | -|
729 | -! | -
- if (!identical(previous_content, current_content)) {+ }) |
|
730 | -! | +||
384 | +
- previous_content <- current_content+ }, |
||
731 | -! | +||
385 | +
- end_time <- Sys.time() + (stability_period / 1000)+ show = function() { |
||
732 | +386 | ! |
- } else if (Sys.time() >= end_time) {+ shiny::isolate(print(.self$all_slices())) |
733 | +387 | ! |
- break- |
-
734 | -- |
- }+ invisible(.self) |
|
735 | +388 |
- }+ } |
|
736 | +389 |
- }+ ) |
|
737 | +390 |
- )+ ) |
|
738 | +391 |
- )+ # todo: prevent any teal_slices attribute except mapping |
1 |
- setOldClass("teal_module")+ # FilteredData ------ |
||
2 |
- setOldClass("teal_modules")+ |
||
3 |
-
+ #' Drive a `teal` application |
||
4 |
- #' Create `teal_module` and `teal_modules` objects+ #' |
||
5 |
- #'+ #' Extension of the `shinytest2::AppDriver` class with methods for |
||
6 |
- #' @description+ #' driving a teal application for performing interactions for `shinytest2` tests. |
||
7 |
- #' `r lifecycle::badge("stable")`+ #' |
||
8 |
- #' Create a nested tab structure to embed modules in a `teal` application.+ #' @keywords internal |
||
10 |
- #' @details+ TealAppDriver <- R6::R6Class( # nolint: object_name. |
||
11 |
- #' `module()` creates an instance of a `teal_module` that can be placed in a `teal` application.+ "TealAppDriver", |
||
12 |
- #' `modules()` shapes the structure of a the application by organizing `teal_module` within the navigation panel.+ inherit = { |
||
13 |
- #' It wraps `teal_module` and `teal_modules` objects in a `teal_modules` object,+ if (!requireNamespace("shinytest2", quietly = TRUE)) { |
||
14 |
- #' which results in a nested structure corresponding to the nested tabs in the final application.+ stop("Please install 'shinytest2' package to use this class.") |
||
15 |
- #'+ } |
||
16 |
- #' Note that for `modules()` `label` comes after `...`, so it must be passed as a named argument,+ if (!requireNamespace("rvest", quietly = TRUE)) { |
||
17 |
- #' otherwise it will be captured by `...`.+ stop("Please install 'rvest' package to use this class.") |
||
18 |
- #'+ } |
||
19 |
- #' The labels `"global_filters"` and `"Report previewer"` are reserved+ shinytest2::AppDriver |
||
20 |
- #' because they are used by the `mapping` argument of [teal_slices()]+ }, |
||
21 |
- #' and the report previewer module [reporter_previewer_module()], respectively.+ # public methods ---- |
||
22 |
- #'+ public = list( |
||
23 |
- #' # Restricting datasets used by `teal_module`:+ #' @description |
||
24 |
- #' The `datanames` argument controls which datasets are used by the module’s server. These datasets,+ #' Initialize a `TealAppDriver` object for testing a `teal` application. |
||
25 |
- #' passed via server's `data` argument, are the only ones shown in the module's tab.+ #' |
||
26 |
- #'+ #' @param data,modules,filter,title,header,footer,landing_popup arguments passed to `init` |
||
27 |
- #' When `datanames` is set to `"all"`, all datasets in the data object are treated as relevant.+ #' @param timeout (`numeric`) Default number of milliseconds for any timeout or |
||
28 |
- #' However, this may include unnecessary datasets, such as:+ #' timeout_ parameter in the `TealAppDriver` class. |
||
29 |
- #' - Proxy variables for column modifications+ #' Defaults to 20s. |
||
30 |
- #' - Temporary datasets used to create final versions+ #' |
||
31 |
- #' - Connection objects+ #' See [`shinytest2::AppDriver`] `new` method for more details on how to change it |
||
32 |
- #'+ #' via options or environment variables. |
||
33 |
- #' To exclude irrelevant datasets, use the [set_datanames()] function to change `datanames` from+ #' @param load_timeout (`numeric`) How long to wait for the app to load, in ms. |
||
34 |
- #' `"all"` to specific names. Trying to modify non-`"all"` values with [set_datanames()] will result+ #' This includes the time to start R. Defaults to 100s. |
||
35 |
- #' in a warning. Datasets with names starting with . are ignored globally unless explicitly listed+ #' |
||
36 |
- #' in `datanames`.+ #' See [`shinytest2::AppDriver`] `new` method for more details on how to change it |
||
37 |
- #'+ #' via options or environment variables |
||
38 |
- #' # `datanames` with `transformers`+ #' @param ... Additional arguments to be passed to `shinytest2::AppDriver$new` |
||
39 |
- #' When transformers are specified, their `datanames` are added to the module’s `datanames`, which+ #' |
||
40 |
- #' changes the behavior as follows:+ #' |
||
41 |
- #' - If `module(datanames)` is `NULL` and the `transformers` have defined `datanames`, the sidebar+ #' @return Object of class `TealAppDriver` |
||
42 |
- #' will appear showing the `transformers`' datasets, instead of being hidden.+ initialize = function(data, |
||
43 |
- #' - If `module(datanames)` is set to specific values and any `transformer` has `datanames = "all"`,+ modules, |
||
44 |
- #' the module may receive extra datasets that could be unnecessary+ filter = teal_slices(), |
||
45 |
- #'+ title = build_app_title(), |
||
46 |
- #' @param label (`character(1)`) Label shown in the navigation item for the module or module group.+ header = tags$p(), |
||
47 |
- #' For `modules()` defaults to `"root"`. See `Details`.+ footer = tags$p(), |
||
48 |
- #' @param server (`function`) `shiny` module with following arguments:+ landing_popup = NULL, |
||
49 |
- #' - `id` - `teal` will set proper `shiny` namespace for this module (see [shiny::moduleServer()]).+ timeout = rlang::missing_arg(), |
||
50 |
- #' - `input`, `output`, `session` - (optional; not recommended) When provided, then [shiny::callModule()]+ load_timeout = rlang::missing_arg(), |
||
51 |
- #' will be used to call a module. From `shiny` 1.5.0, the recommended way is to use+ ...) { |
||
52 | -+ | ! |
- #' [shiny::moduleServer()] instead which doesn't require these arguments.+ private$data <- data |
53 | -+ | ! |
- #' - `data` (optional) When provided, the module will be called with `teal_data` object (i.e. a list of+ private$modules <- modules |
54 | -+ | ! |
- #' reactive (filtered) data specified in the `filters` argument) as the value of this argument.+ private$filter <- filter |
55 | -+ | ! |
- #' - `datasets` (optional) When provided, the module will be called with `FilteredData` object as the+ app <- init( |
56 | -+ | ! |
- #' value of this argument. (See [`teal.slice::FilteredData`]).+ data = data, |
57 | -+ | ! |
- #' - `reporter` (optional) When provided, the module will be called with `Reporter` object as the value+ modules = modules, |
58 | -+ | ! |
- #' of this argument. (See [`teal.reporter::Reporter`]).+ filter = filter, |
59 | -+ | ! |
- #' - `filter_panel_api` (optional) When provided, the module will be called with `FilterPanelAPI` object+ title = title, |
60 | -+ | ! |
- #' as the value of this argument. (See [`teal.slice::FilterPanelAPI`]).+ header = header, |
61 | -+ | ! |
- #' - `...` (optional) When provided, `server_args` elements will be passed to the module named argument+ footer = footer, |
62 | -+ | ! |
- #' or to the `...`.+ landing_popup = landing_popup, |
63 |
- #' @param ui (`function`) `shiny` UI module function with following arguments:+ ) |
||
64 |
- #' - `id` - `teal` will set proper `shiny` namespace for this module.+ |
||
65 |
- #' - `...` (optional) When provided, `ui_args` elements will be passed to the module named argument+ # Default timeout is hardcoded to 4s in shinytest2:::resolve_timeout |
||
66 |
- #' or to the `...`.+ # It must be set as parameter to the AppDriver |
||
67 | -+ | ! |
- #' @param filters (`character`) Deprecated. Use `datanames` instead.+ suppressWarnings( |
68 | -+ | ! |
- #' @param datanames (`character`) Names of the datasets relevant to the item.+ super$initialize( |
69 | -+ | ! |
- #' There are 2 reserved values that have specific behaviors:+ app_dir = shinyApp(app$ui, app$server), |
70 | -+ | ! |
- #' - The keyword `"all"` includes all datasets available in the data passed to the teal application.+ name = "teal", |
71 | -+ | ! |
- #' - `NULL` hides the sidebar panel completely.+ variant = shinytest2::platform_variant(), |
72 | -+ | ! |
- #' - If `transformers` are specified, their `datanames` are automatically added to this `datanames`+ timeout = rlang::maybe_missing(timeout, 20 * 1000), |
73 | -+ | ! |
- #' argument.+ load_timeout = rlang::maybe_missing(load_timeout, 100 * 1000), |
74 |
- #' @param server_args (named `list`) with additional arguments passed on to the server function.+ ... |
||
75 |
- #' @param ui_args (named `list`) with additional arguments passed on to the UI function.+ ) |
||
76 |
- #' @param x (`teal_module` or `teal_modules`) Object to format/print.+ ) |
||
77 |
- #' @param indent (`integer(1)`) Indention level; each nested element is indented one level more.+ |
||
78 |
- #' @param transformers (`list` of `teal_data_module`) that will be applied to transform the data.+ # Check for minimum version of Chrome that supports the tests |
||
79 |
- #' Each transform module UI will appear in the `teal`'s sidebar panel.+ # - Element.checkVisibility was added on 105 |
||
80 | -+ | ! |
- #' Transformers' `datanames` are added to the `datanames`. See [teal_transform_module()].+ chrome_version <- numeric_version( |
81 | -+ | ! |
- #'+ gsub( |
82 | -+ | ! |
- #' @param ...+ "[[:alnum:]_]+/", # Prefix that ends with forward slash |
83 |
- #' - For `modules()`: (`teal_module` or `teal_modules`) Objects to wrap into a tab.+ "", |
||
84 | -+ | ! |
- #' - For `format()` and `print()`: Arguments passed to other methods.+ self$get_chromote_session()$Browser$getVersion()$product |
85 |
- #'+ ), |
||
86 | -+ | ! |
- #' @return+ strict = FALSE |
87 |
- #' `module()` returns an object of class `teal_module`.+ ) |
||
88 |
- #'+ |
||
89 | -+ | ! |
- #' `modules()` returns a `teal_modules` object which contains following fields:+ required_version <- "121" |
90 |
- #' - `label`: taken from the `label` argument.+ |
||
91 | -+ | ! |
- #' - `children`: a list containing objects passed in `...`. List elements are named after+ testthat::skip_if( |
92 | -+ | ! |
- #' their `label` attribute converted to a valid `shiny` id.+ is.na(chrome_version), |
93 | -+ | ! |
- #'+ "Problem getting Chrome version, please contact the developers." |
94 |
- #' @name teal_modules+ ) |
||
95 | -+ | ! |
- #' @aliases teal_module+ testthat::skip_if( |
96 | -+ | ! |
- #'+ chrome_version < required_version, |
97 | -+ | ! |
- #' @examples+ sprintf( |
98 | -+ | ! |
- #' library(shiny)+ "Chrome version '%s' is not supported, please upgrade to '%s' or higher", |
99 | -+ | ! |
- #'+ chrome_version, |
100 | -+ | ! |
- #' module_1 <- module(+ required_version |
101 |
- #' label = "a module",+ ) |
||
102 |
- #' server = function(id, data) {+ ) |
||
103 |
- #' moduleServer(+ # end od check |
||
104 |
- #' id,+ |
||
105 | -+ | ! |
- #' module = function(input, output, session) {+ private$set_active_ns() |
106 | -+ | ! |
- #' output$data <- renderDataTable(data()[["iris"]])+ self$wait_for_idle() |
107 |
- #' }+ }, |
||
108 |
- #' )+ #' @description |
||
109 |
- #' },+ #' Append parent [`shinytest2::AppDriver`] `click` method with a call to `waif_for_idle()` method. |
||
110 |
- #' ui = function(id) {+ #' @param ... arguments passed to parent [`shinytest2::AppDriver`] `click()` method. |
||
111 |
- #' ns <- NS(id)+ click = function(...) { |
||
112 | -+ | ! |
- #' tagList(dataTableOutput(ns("data")))+ super$click(...) |
113 | -+ | ! |
- #' },+ private$wait_for_page_stability() |
114 |
- #' datanames = "all"+ }, |
||
115 |
- #' )+ #' @description |
||
116 |
- #'+ #' Check if the app has shiny errors. This checks for global shiny errors. |
||
117 |
- #' module_2 <- module(+ #' Note that any shiny errors dependent on shiny server render will only be captured after the teal module tab |
||
118 |
- #' label = "another module",+ #' is visited because shiny will not trigger server computations when the tab is invisible. |
||
119 |
- #' server = function(id) {+ #' So, navigate to the module tab you want to test before calling this function. |
||
120 |
- #' moduleServer(+ #' Although, this catches errors hidden in the other module tabs if they are already rendered. |
||
121 |
- #' id,+ expect_no_shiny_error = function() { |
||
122 | -+ | ! |
- #' module = function(input, output, session) {+ testthat::expect_null( |
123 | -+ | ! |
- #' output$text <- renderText("Another Module")+ self$get_html(".shiny-output-error:not(.shiny-output-error-validation)"), |
124 | -+ | ! |
- #' }+ info = "Shiny error is observed" |
125 |
- #' )+ ) |
||
126 |
- #' },+ }, |
||
127 |
- #' ui = function(id) {+ #' @description |
||
128 |
- #' ns <- NS(id)+ #' Check if the app has no validation errors. This checks for global shiny validation errors. |
||
129 |
- #' tagList(textOutput(ns("text")))+ expect_no_validation_error = function() { |
||
130 | -+ | ! |
- #' },+ testthat::expect_null( |
131 | -+ | ! |
- #' datanames = NULL+ self$get_html(".shiny-output-error-validation"), |
132 | -+ | ! |
- #' )+ info = "No validation error is observed" |
133 |
- #'+ ) |
||
134 |
- #' modules <- modules(+ }, |
||
135 |
- #' label = "modules",+ #' @description |
||
136 |
- #' modules(+ #' Check if the app has validation errors. This checks for global shiny validation errors. |
||
137 |
- #' label = "nested modules",+ expect_validation_error = function() { |
||
138 | -+ | ! |
- #' module_1+ testthat::expect_false( |
139 | -+ | ! |
- #' ),+ is.null(self$get_html(".shiny-output-error-validation")), |
140 | -+ | ! |
- #' module_2+ info = "Validation error is not observed" |
141 |
- #' )+ ) |
||
142 |
- #'+ }, |
||
143 |
- #' app <- init(+ #' @description |
||
144 |
- #' data = teal_data(iris = iris),+ #' Set the input in the `teal` app. |
||
145 |
- #' modules = modules+ #' |
||
146 |
- #' )+ #' @param input_id (character) The shiny input id with it's complete name space. |
||
147 |
- #'+ #' @param value The value to set the input to. |
||
148 |
- #' if (interactive()) {+ #' @param ... Additional arguments to be passed to `shinytest2::AppDriver$set_inputs` |
||
149 |
- #' shinyApp(app$ui, app$server)+ #' |
||
150 |
- #' }+ #' @return The `TealAppDriver` object invisibly. |
||
151 |
- #' @rdname teal_modules+ set_input = function(input_id, value, ...) { |
||
152 | -+ | ! |
- #' @export+ do.call( |
153 | -+ | ! |
- #'+ self$set_inputs, |
154 | -+ | ! |
- module <- function(label = "module",+ c(setNames(list(value), input_id), list(...)) |
155 |
- server = function(id, data, ...) moduleServer(id, function(input, output, session) NULL),+ ) |
||
156 | -+ | ! |
- ui = function(id, ...) tags$p(paste0("This module has no UI (id: ", id, " )")),+ invisible(self) |
157 |
- filters,+ }, |
||
158 |
- datanames = "all",+ #' @description |
||
159 |
- server_args = NULL,+ #' Navigate the teal tabs in the `teal` app. |
||
160 |
- ui_args = NULL,+ #' |
||
161 |
- transformers = list()) {+ #' @param tabs (character) Labels of tabs to navigate to. The order of the tabs is important, |
||
162 |
- # argument checking (independent)+ #' and it should start with the most parent level tab. |
||
163 |
- ## `label`+ #' Note: In case the teal tab group has duplicate names, the first tab will be selected, |
||
164 | -213x | +
- checkmate::assert_string(label)+ #' If you wish to select the second tab with the same name, use the suffix "_1". |
|
165 | -210x | +
- if (label == "global_filters") {+ #' If you wish to select the third tab with the same name, use the suffix "_2" and so on. |
|
166 | -1x | +
- stop(+ #' |
|
167 | -1x | +
- sprintf("module(label = \"%s\", ...\n ", label),+ #' @return The `TealAppDriver` object invisibly. |
|
168 | -1x | +
- "Label 'global_filters' is reserved in teal. Please change to something else.",+ navigate_teal_tab = function(tabs) { |
|
169 | -1x | +! |
- call. = FALSE+ checkmate::check_character(tabs, min.len = 1) |
170 | -+ | ! |
- )+ for (tab in tabs) { |
171 | -+ | ! |
- }+ self$set_input( |
172 | -209x | +! |
- if (label == "Report previewer") {+ "teal-teal_modules-active_tab", |
173 | ! |
- stop(+ get_unique_labels(tab), |
|
174 | ! |
- sprintf("module(label = \"%s\", ...\n ", label),+ wait_ = FALSE |
|
175 | -! | +
- "Label 'Report previewer' is reserved in teal. Please change to something else.",+ ) |
|
176 | -! | +
- call. = FALSE+ } |
|
177 | -+ | ! |
- )+ self$wait_for_idle() |
178 | -+ | ! |
- }+ private$set_active_ns() |
179 | -+ | ! |
-
+ invisible(self) |
180 |
- ## server+ }, |
||
181 | -209x | +
- checkmate::assert_function(server)+ #' @description |
|
182 | -209x | +
- server_formals <- names(formals(server))+ #' Get the active shiny name space for different components of the teal app. |
|
183 | -209x | +
- if (!(+ #' |
|
184 | -209x | +
- "id" %in% server_formals ||+ #' @return (`list`) The list of active shiny name space of the teal components. |
|
185 | -209x | +
- all(c("input", "output", "session") %in% server_formals)+ active_ns = function() { |
|
186 | -+ | ! |
- )) {+ if (identical(private$ns$module, character(0))) { |
187 | -2x | +! |
- stop(+ private$set_active_ns() |
188 | -2x | +
- "\nmodule() `server` argument requires a function with following arguments:",+ } |
|
189 | -2x | +! |
- "\n - id - `teal` will set proper `shiny` namespace for this module.",+ private$ns |
190 | -2x | +
- "\n - input, output, session (not recommended) - then `shiny::callModule` will be used to call a module.",+ }, |
|
191 | -2x | +
- "\n\nFollowing arguments can be used optionaly:",+ #' @description |
|
192 | -2x | +
- "\n - `data` - module will receive list of reactive (filtered) data specified in the `filters` argument",+ #' Get the active shiny name space for interacting with the module content. |
|
193 | -2x | +
- "\n - `datasets` - module will receive `FilteredData`. See `help(teal.slice::FilteredData)`",+ #' |
|
194 | -2x | +
- "\n - `reporter` - module will receive `Reporter`. See `help(teal.reporter::Reporter)`",+ #' @return (`string`) The active shiny name space of the component. |
|
195 | -2x | +
- "\n - `filter_panel_api` - module will receive `FilterPanelAPI`. (See [teal.slice::FilterPanelAPI]).",+ active_module_ns = function() { |
|
196 | -2x | +! |
- "\n - `...` server_args elements will be passed to the module named argument or to the `...`"+ if (identical(private$ns$module, character(0))) { |
197 | -+ | ! |
- )+ private$set_active_ns() |
198 |
- }+ } |
||
199 | -207x | +! |
- if ("datasets" %in% server_formals) {+ private$ns$module |
200 | -2x | +
- warning(+ }, |
|
201 | -2x | +
- sprintf("Called from module(label = \"%s\", ...)\n ", label),+ #' @description |
|
202 | -2x | +
- "`datasets` argument in the server is deprecated and will be removed in the next release. ",+ #' Get the active shiny name space bound with a custom `element` name. |
|
203 | -2x | +
- "Please use `data` instead.",+ #' |
|
204 | -2x | +
- call. = FALSE+ #' @param element `character(1)` custom element name. |
|
205 |
- )+ #' |
||
206 |
- }+ #' @return (`string`) The active shiny name space of the component bound with the input `element`. |
||
207 |
-
+ active_module_element = function(element) { |
||
208 | -+ | ! |
-
+ checkmate::assert_string(element) |
209 | -+ | ! |
- ## UI+ sprintf("#%s-%s", self$active_module_ns(), element) |
210 | -207x | +
- checkmate::assert_function(ui)+ }, |
|
211 | -207x | +
- ui_formals <- names(formals(ui))+ #' @description |
|
212 | -207x | +
- if (!"id" %in% ui_formals) {+ #' Get the text of the active shiny name space bound with a custom `element` name. |
|
213 | -1x | +
- stop(+ #' |
|
214 | -1x | +
- "\nmodule() `ui` argument requires a function with following arguments:",+ #' @param element `character(1)` the text of the custom element name. |
|
215 | -1x | +
- "\n - id - `teal` will set proper `shiny` namespace for this module.",+ #' |
|
216 | -1x | +
- "\n\nFollowing arguments can be used optionally:",+ #' @return (`string`) The text of the active shiny name space of the component bound with the input `element`. |
|
217 | -1x | +
- "\n - `...` ui_args elements will be passed to the module argument of the same name or to the `...`"+ active_module_element_text = function(element) { |
|
218 | -+ | ! |
- )+ checkmate::assert_string(element) |
219 | -+ | ! |
- }+ self$get_text(self$active_module_element(element)) |
220 | -206x | +
- if (any(c("data", "datasets") %in% ui_formals)) {+ }, |
|
221 | -2x | +
- stop(+ #' @description |
|
222 | -2x | +
- sprintf("Called from module(label = \"%s\", ...)\n ", label),+ #' Get the active shiny name space for interacting with the filter panel. |
|
223 | -2x | +
- "UI with `data` or `datasets` argument is no longer accepted.\n ",+ #' |
|
224 | -2x | +
- "If some UI inputs depend on data, please move the logic to your server instead.\n ",+ #' @return (`string`) The active shiny name space of the component. |
|
225 | -2x | +
- "Possible solutions are renderUI() or updateXyzInput() functions."+ active_filters_ns = function() { |
|
226 | -+ | ! |
- )+ if (identical(private$ns$filter_panel, character(0))) { |
227 | -+ | ! |
- }+ private$set_active_ns() |
228 |
-
+ } |
||
229 | -+ | ! |
-
+ private$ns$filter_panel |
230 |
- ## `filters`+ }, |
||
231 | -204x | +
- if (!missing(filters)) {+ #' @description |
|
232 | -! | +
- datanames <- filters+ #' Get the active shiny name space for interacting with the data-summary panel. |
|
233 | -! | +
- msg <-+ #' |
|
234 | -! | +
- "The `filters` argument is deprecated and will be removed in the next release. Please use `datanames` instead."+ #' @return (`string`) The active shiny name space of the data-summary component. |
|
235 | -! | +
- warning(msg)+ active_data_summary_ns = function() { |
|
236 | -+ | ! |
- }+ if (identical(private$ns$data_summary, character(0))) { |
237 | -+ | ! |
-
+ private$set_active_ns() |
238 |
- ## `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+ private$ns$data_summary |
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))+ #' @description |
|
242 | -12x | +
- datanames <- NULL+ #' Get the active shiny name space bound with a custom `element` name. |
|
243 |
- }+ #' |
||
244 | -204x | +
- checkmate::assert_character(datanames, min.len = 1, null.ok = TRUE, any.missing = FALSE)+ #' @param element `character(1)` custom element name. |
|
245 |
-
+ #' |
||
246 |
- ## `server_args`+ #' @return (`string`) The active shiny name space of the component bound with the input `element`. |
||
247 | -203x | +
- checkmate::assert_list(server_args, null.ok = TRUE, names = "named")+ active_data_summary_element = function(element) { |
|
248 | -201x | +! |
- srv_extra_args <- setdiff(names(server_args), server_formals)+ checkmate::assert_string(element) |
249 | -201x | +! |
- if (length(srv_extra_args) > 0 && !"..." %in% server_formals) {+ sprintf("#%s-%s", self$active_data_summary_ns(), element) |
250 | -1x | +
- stop(+ }, |
|
251 | -1x | +
- "\nFollowing `server_args` elements have no equivalent in the formals of the server:\n",+ #' @description |
|
252 | -1x | +
- paste(paste(" -", srv_extra_args), collapse = "\n"),+ #' Get the input from the module in the `teal` app. |
|
253 | -1x | +
- "\n\nUpdate the server arguments by including above or add `...`"+ #' This function will only access inputs from the name space of the current active teal module. |
|
254 |
- )+ #' |
||
255 |
- }+ #' @param input_id (character) The shiny input id to get the value from. |
||
256 |
-
+ #' |
||
257 |
- ## `ui_args`+ #' @return The value of the shiny input. |
||
258 | -200x | +
- checkmate::assert_list(ui_args, null.ok = TRUE, names = "named")+ get_active_module_input = function(input_id) { |
|
259 | -198x | +! |
- ui_extra_args <- setdiff(names(ui_args), ui_formals)+ checkmate::check_string(input_id) |
260 | -198x | +! |
- if (length(ui_extra_args) > 0 && !"..." %in% ui_formals) {+ self$get_value(input = sprintf("%s-%s", self$active_module_ns(), input_id)) |
261 | -1x | +
- stop(+ }, |
|
262 | -1x | +
- "\nFollowing `ui_args` elements have no equivalent in the formals of UI:\n",+ #' @description |
|
263 | -1x | +
- paste(paste(" -", ui_extra_args), collapse = "\n"),+ #' Get the output from the module in the `teal` app. |
|
264 | -1x | +
- "\n\nUpdate the UI arguments by including above or add `...`"+ #' This function will only access outputs from the name space of the current active teal module. |
|
265 |
- )+ #' |
||
266 |
- }+ #' @param output_id (character) The shiny output id to get the value from. |
||
267 |
-
+ #' |
||
268 |
- ## `transformers`+ #' @return The value of the shiny output. |
||
269 | -197x | +
- if (inherits(transformers, "teal_transform_module")) {+ get_active_module_output = function(output_id) { |
|
270 | -1x | +! |
- transformers <- list(transformers)+ checkmate::check_string(output_id) |
271 | -+ | ! |
- }+ self$get_value(output = sprintf("%s-%s", self$active_module_ns(), output_id)) |
272 | -197x | +
- checkmate::assert_list(transformers, types = "teal_transform_module")+ }, |
|
273 | -197x | +
- transformer_datanames <- unlist(lapply(transformers, attr, "datanames"))+ #' @description |
|
274 | -197x | +
- combined_datanames <- if (identical(datanames, "all")) {+ #' Get the output from the module's `teal.widgets::table_with_settings` or `DT::DTOutput` in the `teal` app. |
|
275 | -144x | +
- "all"+ #' This function will only access outputs from the name space of the current active teal module. |
|
276 |
- } else {+ #' |
||
277 | -53x | +
- union(datanames, transformer_datanames)+ #' @param table_id (`character(1)`) The id of the table in the active teal module's name space. |
|
278 |
- }+ #' @param which (integer) If there is more than one table, which should be extracted. |
||
279 |
-
+ #' By default it will look for a table that is built using `teal.widgets::table_with_settings`. |
||
280 | -197x | +
- structure(+ #' |
|
281 | -197x | +
- list(+ #' @return The data.frame with table contents. |
|
282 | -197x | +
- label = label,+ get_active_module_table_output = function(table_id, which = 1) { |
|
283 | -197x | +! |
- server = server,+ checkmate::check_number(which, lower = 1) |
284 | -197x | +! |
- ui = ui,+ checkmate::check_string(table_id) |
285 | -197x | +! |
- datanames = combined_datanames,+ table <- rvest::html_table( |
286 | -197x | +! |
- server_args = server_args,+ self$get_html_rvest(self$active_module_element(table_id)), |
287 | -197x | +! |
- ui_args = ui_args,+ fill = TRUE |
288 | -197x | +
- transformers = transformers+ ) |
|
289 | -+ | ! |
- ),+ if (length(table) == 0) { |
290 | -197x | +! |
- class = "teal_module"+ data.frame() |
291 |
- )+ } else { |
||
292 | -+ | ! |
- }+ table[[which]] |
293 |
-
+ } |
||
294 |
- #' @rdname teal_modules+ }, |
||
295 |
- #' @export+ #' @description |
||
296 |
- #'+ #' Get the output from the module's `teal.widgets::plot_with_settings` in the `teal` app. |
||
297 |
- modules <- function(..., label = "root") {+ #' This function will only access plots from the name space of the current active teal module. |
||
298 | -137x | +
- checkmate::assert_string(label)+ #' |
|
299 | -135x | +
- submodules <- list(...)+ #' @param plot_id (`character(1)`) The id of the plot in the active teal module's name space. |
|
300 | -135x | +
- if (any(vapply(submodules, is.character, FUN.VALUE = logical(1)))) {+ #' |
|
301 | -2x | +
- stop(+ #' @return The `src` attribute as `character(1)` vector. |
|
302 | -2x | +
- "The only character argument to modules() must be 'label' and it must be named, ",+ get_active_module_plot_output = function(plot_id) { |
|
303 | -2x | +! |
- "change modules('lab', ...) to modules(label = 'lab', ...)"+ checkmate::check_string(plot_id) |
304 | -+ | ! |
- )+ self$get_attr( |
305 | -+ | ! |
- }+ self$active_module_element(sprintf("%s-plot_main > img", plot_id)), |
306 | -+ | ! |
-
+ "src" |
307 | -133x | +
- checkmate::assert_list(submodules, min.len = 1, any.missing = FALSE, types = c("teal_module", "teal_modules"))+ ) |
|
308 |
- # name them so we can more easily access the children+ }, |
||
309 |
- # beware however that the label of the submodules should not be changed as it must be kept synced+ #' @description |
||
310 | -130x | +
- labels <- vapply(submodules, function(submodule) submodule$label, character(1))+ #' Set the input in the module in the `teal` app. |
|
311 | -130x | +
- names(submodules) <- get_unique_labels(labels)+ #' This function will only set inputs in the name space of the current active teal module. |
|
312 | -130x | +
- structure(+ #' |
|
313 | -130x | +
- list(+ #' @param input_id (character) The shiny input id to get the value from. |
|
314 | -130x | +
- label = label,+ #' @param value The value to set the input to. |
|
315 | -130x | +
- children = submodules+ #' @param ... Additional arguments to be passed to `shinytest2::AppDriver$set_inputs` |
|
316 |
- ),+ #'+ |
+ ||
317 | ++ |
+ #' @return The `TealAppDriver` object invisibly.+ |
+ |
318 | ++ |
+ set_active_module_input = function(input_id, value, ...) {+ |
+ |
319 | +! | +
+ checkmate::check_string(input_id)+ |
+ |
320 | +! | +
+ checkmate::check_string(value)+ |
+ |
321 | +! | +
+ self$set_input(+ |
+ |
322 | +! | +
+ sprintf("%s-%s", self$active_module_ns(), input_id),+ |
+ |
323 | +! | +
+ value,+ |
+ |
324 | ++ |
+ ...+ |
+ |
325 | ++ |
+ )+ |
+ |
326 | +! | +
+ dots <- rlang::list2(...)+ |
+ |
327 | +! | +
+ if (!isFALSE(dots[["wait"]])) self$wait_for_idle() # Default behavior is to wait+ |
+ |
328 | +! | +
+ invisible(self)+ |
+ |
329 | ++ |
+ },+ |
+ |
330 | ++ |
+ #' @description+ |
+ |
331 | ++ |
+ #' Get the active datasets that can be accessed via the filter panel of the current active teal module.+ |
+ |
332 | ++ |
+ get_active_filter_vars = function() {+ |
+ |
333 | +! | +
+ displayed_datasets_index <- self$is_visible(+ |
+ |
334 | +! | +
+ sprintf("#%s-filters-filter_active_vars_contents > span", self$active_filters_ns())+ |
+ |
335 | ++ |
+ )+ |
+ |
336 | ++ | + + | +|
337 | +! | +
+ available_datasets <- self$get_text(+ |
+ |
338 | +! | +
+ sprintf(+ |
+ |
339 | +! | +
+ "#%s-filters-filter_active_vars_contents .filter_panel_dataname",+ |
+ |
340 | +! | +
+ self$active_filters_ns()+ |
+ |
341 | ++ |
+ )+ |
+ |
342 | ++ |
+ )+ |
+ |
343 | ++ | + + | +|
344 | +! | +
+ available_datasets[displayed_datasets_index]+ |
+ |
345 | ++ |
+ },+ |
+ |
346 | ++ |
+ #' @description+ |
+ |
347 | ++ |
+ #' Get the active data summary table+ |
+ |
348 | ++ |
+ #' @return `data.frame`+ |
+ |
349 | ++ |
+ get_active_data_summary_table = function() {+ |
+ |
350 | +! | +
+ summary_table <- rvest::html_table(+ |
+ |
351 | +! | +
+ self$get_html_rvest(self$active_data_summary_element("table")),+ |
+ |
352 | +! | +
+ fill = TRUE+ |
+ |
353 | +! | +
+ )[[1]]+ |
+ |
354 | ++ | + + | +|
355 | +! | +
+ col_names <- unlist(summary_table[1, ], use.names = FALSE)+ |
+ |
356 | +! | +
+ summary_table <- summary_table[-1, ]+ |
+ |
357 | +! | +
+ colnames(summary_table) <- col_names+ |
+ |
358 | +! | +
+ if (nrow(summary_table) > 0) {+ |
+ |
359 | +! | +
+ summary_table+ |
+ |
360 | ++ |
+ } else {+ |
+ |
361 | +! | +
+ NULL+ |
+ |
362 | ++ |
+ }+ |
+ |
363 | ++ |
+ },+ |
+ |
364 | ++ |
+ #' @description+ |
+ |
365 | ++ |
+ #' Test if `DOM` elements are visible on the page with a JavaScript call.+ |
+ |
366 | ++ |
+ #' @param selector (`character(1)`) `CSS` selector to check visibility.+ |
+ |
367 | ++ |
+ #' A `CSS` id will return only one element if the UI is well formed.+ |
+ |
368 | ++ |
+ #' @param content_visibility_auto,opacity_property,visibility_property (`logical(1)`) See more information+ |
+ |
369 | ++ |
+ #' on <https://developer.mozilla.org/en-US/docs/Web/API/Element/checkVisibility>.+ |
+ |
370 | ++ |
+ #'+ |
+ |
371 | ++ |
+ #' @return Logical vector with all occurrences of the selector.+ |
+ |
372 | ++ |
+ is_visible = function(selector,+ |
+ |
373 | ++ |
+ content_visibility_auto = FALSE,+ |
+ |
374 | ++ |
+ opacity_property = FALSE,+ |
+ |
375 | ++ |
+ visibility_property = FALSE) {+ |
+ |
376 | +! | +
+ checkmate::assert_string(selector)+ |
+ |
377 | +! | +
+ checkmate::assert_flag(content_visibility_auto)+ |
+ |
378 | +! | +
+ checkmate::assert_flag(opacity_property)+ |
+ |
379 | +! | +
+ checkmate::assert_flag(visibility_property)+ |
+ |
380 | ++ | + + | +|
381 | +! | +
+ private$wait_for_page_stability()+ |
+ |
382 | ++ | + + | +|
383 | +! | +
+ 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 | ++ |
+ )+ |
+ |
387 | ++ | + + | +|
388 | +! | +
+ unlist(+ |
+ |
389 | +! | +
+ self$get_js(+ |
+ |
390 | +! | +
+ sprintf(+ |
+ |
391 | +! | +
+ "Array.from(document.querySelectorAll('%s')).map(el => el.checkVisibility({%s, %s, %s}))",+ |
+ |
392 | +! | +
+ selector,+ |
+ |
393 | ++ |
+ # Extra parameters+ |
+ |
394 | +! | +
+ sprintf("contentVisibilityAuto: %s", tolower(content_visibility_auto)),+ |
+ |
395 | +! | +
+ sprintf("opacityProperty: %s", tolower(opacity_property)),+ |
+ |
396 | +! | +
+ sprintf("visibilityProperty: %s", tolower(visibility_property))+ |
+ |
397 | ++ |
+ )+ |
+ |
398 | ++ |
+ )+ |
+ |
399 | ++ |
+ )+ |
+ |
400 | ++ |
+ },+ |
+ |
401 | ++ |
+ #' @description+ |
+ |
402 | ++ |
+ #' Get the active filter variables from a dataset in the `teal` app.+ |
+ |
403 | ++ |
+ #'+ |
+ |
404 | ++ |
+ #' @param dataset_name (character) The name of the dataset to get the filter variables from.+ |
+ |
405 | ++ |
+ #' If `NULL`, the filter variables for all the datasets will be returned in a list.+ |
+ |
406 | ++ |
+ get_active_data_filters = function(dataset_name = NULL) {+ |
+ |
407 | +! | +
+ checkmate::check_string(dataset_name, null.ok = TRUE)+ |
+ |
408 | +! | +
+ datasets <- self$get_active_filter_vars()+ |
+ |
409 | +! | +
+ checkmate::assert_subset(dataset_name, datasets)+ |
+ |
410 | +! | +
+ active_filters <- lapply(+ |
+ |
411 | +! | +
+ datasets,+ |
+ |
412 | +! | +
+ function(x) {+ |
+ |
413 | +! | +
+ var_names <- gsub(+ |
+ |
414 | +! | +
+ pattern = "\\s",+ |
+ |
415 | +! | +
+ replacement = "",+ |
+ |
416 | +! | +
+ self$get_text(+ |
+ |
417 | +! | +
+ sprintf(+ |
+ |
418 | +! | +
+ "#%s-filters-%s .filter-card-varname",+ |
+ |
419 | +! | +
+ self$active_filters_ns(),+ |
+ |
420 | +! | +
+ x+ |
+ |
421 | ++ |
+ )+ |
+ |
422 | ++ |
+ )+ |
+ |
423 | ++ |
+ )+ |
+ |
424 | +! | +
+ structure(+ |
+ |
425 | +! | +
+ lapply(var_names, private$get_active_filter_selection, dataset_name = x),+ |
+ |
426 | +! | +
+ names = var_names+ |
+ |
427 | ++ |
+ )+ |
+ |
428 | ++ |
+ }+ |
+ |
429 | ++ |
+ )+ |
+ |
430 | +! | +
+ names(active_filters) <- datasets+ |
+ |
431 | +! | +
+ if (is.null(dataset_name)) {+ |
+ |
432 | +! | +
+ return(active_filters)+ |
+ |
433 | ++ |
+ }+ |
+ |
434 | +! | +
+ active_filters[[dataset_name]]+ |
+ |
435 | ++ |
+ },+ |
+ |
436 | ++ |
+ #' @description+ |
+ |
437 | ++ |
+ #' Add a new variable from the dataset to be filtered.+ |
+ |
438 | ++ |
+ #'+ |
+ |
439 | ++ |
+ #' @param dataset_name (character) The name of the dataset to add the filter variable to.+ |
+ |
440 | ++ |
+ #' @param var_name (character) The name of the variable to add to the filter panel.+ |
+ |
441 | ++ |
+ #' @param ... Additional arguments to be passed to `shinytest2::AppDriver$set_inputs`+ |
+ |
442 | ++ |
+ #'+ |
+ |
443 | ++ |
+ #' @return The `TealAppDriver` object invisibly.+ |
+ |
444 | ++ |
+ add_filter_var = function(dataset_name, var_name, ...) {+ |
+ |
445 | +! | +
+ checkmate::check_string(dataset_name)+ |
+ |
446 | +! | +
+ checkmate::check_string(var_name)+ |
+ |
447 | +! | +
+ private$set_active_ns()+ |
+ |
448 | +! | +
+ self$click(+ |
+ |
449 | +! | +
+ selector = sprintf(+ |
+ |
450 | +! | +
+ "#%s-filters-%s-add_filter_icon",+ |
+ |
451 | +! | +
+ private$ns$filter_panel,+ |
+ |
452 | +! | +
+ dataset_name+ |
+ |
453 | ++ |
+ )+ |
+ |
454 | ++ |
+ )+ |
+ |
455 | +! | +
+ self$set_input(+ |
+ |
456 | +! | +
+ sprintf(+ |
+ |
457 | +! | +
+ "%s-filters-%s-%s-filter-var_to_add",+ |
+ |
458 | +! | +
+ private$ns$filter_panel,+ |
+ |
459 | +! | +
+ dataset_name,+ |
+ |
460 | +! | +
+ dataset_name+ |
+ |
461 | ++ |
+ ),+ |
+ |
462 | +! | +
+ var_name,+ |
+ |
463 | ++ |
+ ...+ |
+ |
464 | ++ |
+ )+ |
+ |
465 | +! | +
+ invisible(self)+ |
+ |
466 | ++ |
+ },+ |
+ |
467 | ++ |
+ #' @description+ |
+ |
468 | ++ |
+ #' Remove an active filter variable of a dataset from the active filter variables panel.+ |
+ |
469 | ++ |
+ #'+ |
+ |
470 | ++ |
+ #' @param dataset_name (character) The name of the dataset to remove the filter variable from.+ |
+ |
471 | ++ |
+ #' If `NULL`, all the filter variables will be removed.+ |
+ |
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 | ++ |
+ #'+ |
+ |
475 | ++ |
+ #' @return The `TealAppDriver` object invisibly.+ |
+ |
476 | ++ |
+ remove_filter_var = function(dataset_name = NULL, var_name = NULL) {+ |
+ |
477 | +! | +
+ checkmate::check_string(dataset_name, null.ok = TRUE)+ |
+ |
478 | +! | +
+ checkmate::check_string(var_name, null.ok = TRUE)+ |
+ |
479 | +! | +
+ if (is.null(dataset_name)) {+ |
+ |
480 | +! | +
+ remove_selector <- sprintf(+ |
+ |
481 | +! | +
+ "#%s-active-remove_all_filters",+ |
+ |
482 | +! | +
+ self$active_filters_ns()+ |
+ |
483 | ++ |
+ )+ |
+ |
484 | +! | +
+ } else if (is.null(var_name)) {+ |
+ |
485 | +! | +
+ remove_selector <- sprintf(+ |
+ |
486 | +! | +
+ "#%s-active-%s-remove_filters",+ |
+ |
487 | +! | +
+ self$active_filters_ns(),+ |
+ |
488 | +! | +
+ dataset_name+ |
+ |
489 | ++ |
+ )+ |
+ |
490 | ++ |
+ } else {+ |
+ |
491 | +! | +
+ remove_selector <- sprintf(+ |
+ |
492 | +! | +
+ "#%s-active-%s-filter-%s_%s-remove",+ |
+ |
493 | +! | +
+ self$active_filters_ns(),+ |
+ |
494 | +! | +
+ dataset_name,+ |
+ |
495 | +! | +
+ dataset_name,+ |
+ |
496 | +! | +
+ var_name+ |
+ |
497 | ++ |
+ )+ |
+ |
498 | ++ |
+ }+ |
+ |
499 | +! | +
+ self$click(+ |
+ |
500 | +! | +
+ selector = remove_selector+ |
+ |
501 | ++ |
+ )+ |
+ |
502 | +! | +
+ invisible(self)+ |
+ |
503 | ++ |
+ },+ |
+ |
504 | ++ |
+ #' @description+ |
+ |
505 | ++ |
+ #' Set the active filter values for a variable of a dataset in the active filter variable panel.+ |
+ |
506 | ++ |
+ #'+ |
+ |
507 | ++ |
+ #' @param dataset_name (character) The name of the dataset to set the filter value for.+ |
+ |
508 | ++ |
+ #' @param var_name (character) The name of the variable to set the filter value for.+ |
+ |
509 | ++ |
+ #' @param input The value to set the filter to.+ |
+ |
510 | ++ |
+ #' @param ... Additional arguments to be passed to `shinytest2::AppDriver$set_inputs`+ |
+ |
511 | ++ |
+ #'+ |
+ |
512 | ++ |
+ #' @return The `TealAppDriver` object invisibly.+ |
+ |
513 | ++ |
+ set_active_filter_selection = function(dataset_name,+ |
+ |
514 | ++ |
+ var_name,+ |
+ |
515 | ++ |
+ input,+ |
+ |
516 | ++ |
+ ...) {+ |
+ |
517 | +! | +
+ checkmate::check_string(dataset_name)+ |
+ |
518 | +! | +
+ checkmate::check_string(var_name)+ |
+ |
519 | +! | +
+ checkmate::check_string(input)+ |
+ |
520 | ++ | + + | +|
521 | +! | +
+ input_id_prefix <- sprintf(+ |
+ |
522 | +! | +
+ "%s-filters-%s-filter-%s_%s-inputs",+ |
+ |
523 | +! | +
+ self$active_filters_ns(),+ |
+ |
524 | +! | +
+ dataset_name,+ |
+ |
525 | +! | +
+ dataset_name,+ |
+ |
526 | +! | +
+ var_name+ |
+ |
527 | ++ |
+ )+ |
+ |
528 | ++ | + + | +|
529 | ++ |
+ # Find the type of filter (based on filter panel)+ |
+ |
530 | +! | +
+ supported_suffix <- c("selection", "selection_manual")+ |
+ |
531 | +! | +
+ slices_suffix <- supported_suffix[+ |
+ |
532 | +! | +
+ match(+ |
+ |
533 | +! | +
+ TRUE,+ |
+ |
534 | +! | +
+ vapply(+ |
+ |
535 | +! | +
+ supported_suffix,+ |
+ |
536 | +! | +
+ function(suffix) {+ |
+ |
537 | +! | +
+ !is.null(self$get_html(sprintf("#%s-%s", input_id_prefix, suffix)))+ |
+ |
538 | ++ |
+ },+ |
+ |
539 | +! | +
+ logical(1)+ |
+ |
540 | ++ |
+ )+ |
+ |
541 | ++ |
+ )+ |
+ |
542 | ++ |
+ ]+ |
+ |
543 | ++ | + + | +|
544 | ++ |
+ # Generate correct namespace+ |
+ |
545 | +! | +
+ slices_input_id <- sprintf(+ |
+ |
546 | +! | +
+ "%s-filters-%s-filter-%s_%s-inputs-%s",+ |
+ |
547 | +! | +
+ self$active_filters_ns(), |
|
317 | -130x | +||
548 | +! |
- class = "teal_modules"+ dataset_name, |
|
318 | -+ | ||
549 | +! |
- )+ dataset_name, |
|
319 | -+ | ||
550 | +! |
- }+ var_name, |
|
320 | -+ | ||
551 | +! |
-
+ slices_suffix |
|
321 | +552 |
- # printing methods ----+ ) |
|
322 | +553 | ||
323 | -+ | ||
554 | +! |
- #' @rdname teal_modules+ if (identical(slices_suffix, "selection_manual")) { |
|
324 | -+ | ||
555 | +! |
- #' @export+ checkmate::assert_numeric(input, len = 2) |
|
325 | +556 |
- format.teal_module <- function(x, indent = 0, ...) {+ |
|
326 | -3x | +||
557 | +! |
- paste0(paste(rep(" ", indent), collapse = ""), "+ ", x$label, "\n", collapse = "")+ dots <- rlang::list2(...) |
|
327 | -+ | ||
558 | +! |
- }+ checkmate::assert_choice(dots$priority_, formals(self$set_inputs)[["priority_"]], null.ok = TRUE) |
|
328 | -+ | ||
559 | +! |
-
+ checkmate::assert_flag(dots$wait_, null.ok = TRUE) |
|
329 | +560 | ||
330 | -- |
- #' @rdname teal_modules- |
- |
331 | -+ | ||
561 | +! |
- #' @export+ self$run_js( |
|
332 | -+ | ||
562 | +! |
- print.teal_module <- function(x, ...) {+ sprintf( |
|
333 | +563 | ! |
- cat(format(x, ...))+ "Shiny.setInputValue('%s:sw.numericRange', [%f, %f], {priority: '%s'})", |
334 | +564 | ! |
- invisible(x)+ slices_input_id, |
335 | -+ | ||
565 | +! |
- }+ input[[1]], |
|
336 | -+ | ||
566 | +! |
-
+ input[[2]], |
|
337 | -+ | ||
567 | +! |
-
+ priority_ = ifelse(is.null(dots$priority_), "input", dots$priority_) |
|
338 | +568 |
- #' @rdname teal_modules+ ) |
|
339 | +569 |
- #' @export+ ) |
|
340 | +570 |
- format.teal_modules <- function(x, indent = 0, ...) {+ |
|
341 | -1x | +||
571 | +! |
- paste(+ if (isTRUE(dots$wait_) || is.null(dots$wait_)) { |
|
342 | -1x | +||
572 | +! |
- c(+ self$wait_for_idle( |
|
343 | -1x | +||
573 | +! |
- paste0(rep(" ", indent), "+ ", x$label, "\n"),+ timeout = if (is.null(dots$timeout_)) rlang::missing_arg() else dots$timeout_ |
|
344 | -1x | +||
574 | +
- unlist(lapply(x$children, format, indent = indent + 1, ...))+ ) |
||
345 | +575 |
- ),+ } |
|
346 | -1x | +||
576 | +! |
- collapse = ""+ } else if (identical(slices_suffix, "selection")) { |
|
347 | -+ | ||
577 | +! |
- )+ self$set_input( |
|
348 | -+ | ||
578 | +! |
- }+ slices_input_id, |
|
349 | -+ | ||
579 | +! |
-
+ input, |
|
350 | +580 |
- #' @param modules (`teal_module` or `teal_modules`)+ ... |
|
351 | +581 |
- #' @rdname teal_modules+ ) |
|
352 | +582 |
- #' @examples+ } else { |
|
353 | -+ | ||
583 | +! |
- #' # change the module's datanames+ stop("Filter selection set not supported for this slice.") |
|
354 | +584 |
- #' set_datanames(module(datanames = "all"), "a")+ } |
|
355 | +585 |
- #'+ |
|
356 | -+ | ||
586 | +! |
- #' # change modules' datanames+ invisible(self) |
|
357 | +587 |
- #' set_datanames(+ }, |
|
358 | +588 |
- #' modules(+ #' @description |
|
359 | +589 |
- #' module(datanames = "all"),+ #' Extract `html` attribute (found by a `selector`). |
|
360 | +590 |
- #' module(datanames = "a")+ #' |
|
361 | +591 |
- #' ),+ #' @param selector (`character(1)`) specifying the selector to be used to get the content of a specific node. |
|
362 | +592 |
- #' "b"+ #' @param attribute (`character(1)`) name of an attribute to retrieve from a node specified by `selector`. |
|
363 | +593 |
- #' )+ #' |
|
364 | +594 |
- #' @export+ #' @return The `character` vector. |
|
365 | +595 |
- set_datanames <- function(modules, datanames) {+ get_attr = function(selector, attribute) { |
|
366 | +596 | ! |
- checkmate::assert_multi_class(modules, c("teal_modules", "teal_module"))+ rvest::html_attr( |
367 | +597 | ! |
- if (inherits(modules, "teal_modules")) {+ rvest::html_nodes(self$get_html_rvest("html"), selector), |
368 | +598 | ! |
- modules$children <- lapply(modules$children, set_datanames, datanames)+ attribute |
369 | +599 |
- } else {- |
- |
370 | -! | -
- if (identical(modules$datanames, "all")) {- |
- |
371 | -! | -
- modules$datanames <- datanames+ ) |
|
372 | +600 |
- } else {+ }, |
|
373 | -! | +||
601 | +
- warning(+ #' @description |
||
374 | -! | +||
602 | +
- "Not possible to modify datanames of the module ", modules$label,+ #' Wrapper around `get_html` that passes the output directly to `rvest::read_html`. |
||
375 | -! | +||
603 | +
- ". set_datanames() can only change datanames if it was set to \"all\".",+ #' |
||
376 | -! | +||
604 | +
- call. = FALSE+ #' @param selector `(character(1))` passed to `get_html`. |
||
377 | +605 |
- )+ #' |
|
378 | +606 |
- }+ #' @return An XML document. |
|
379 | +607 |
- }+ get_html_rvest = function(selector) { |
|
380 | +608 | ! |
- modules+ rvest::read_html(self$get_html(selector)) |
381 | +609 |
- }+ }, |
|
382 | +610 |
-
+ #' Wrapper around `get_url()` method that opens the app in the browser. |
|
383 | +611 |
- #' @rdname teal_modules+ #' |
|
384 | +612 |
- #' @export+ #' @return Nothing. Opens the underlying teal app in the browser. |
|
385 | +613 |
- print.teal_modules <- print.teal_module+ open_url = function() { |
|
386 | -+ | ||
614 | +! |
-
+ browseURL(self$get_url()) |
|
387 | +615 |
-
+ }, |
|
388 | +616 |
- # utilities ----+ #' @description |
|
389 | +617 |
- ## subset or modify modules ----+ #' Waits until a specified input, output, or export value. |
|
390 | +618 |
-
+ #' This function serves as a wrapper around the `wait_for_value` method, |
|
391 | +619 |
- #' Append a `teal_module` to `children` of a `teal_modules` object+ #' providing a more flexible interface for waiting on different types of values within the active module namespace. |
|
392 | +620 |
- #' @keywords internal+ #' @param input,output,export A name of an input, output, or export value. |
|
393 | +621 |
- #' @param modules (`teal_modules`)+ #' Only one of these parameters may be used. |
|
394 | +622 |
- #' @param module (`teal_module`) object to be appended onto the children of `modules`+ #' @param ... Must be empty. Allows for parameter expansion. |
|
395 | +623 |
- #' @return A `teal_modules` object with `module` appended.+ #' Parameter with additional value to passed in `wait_for_value`. |
|
396 | +624 |
- append_module <- function(modules, module) {- |
- |
397 | -8x | -
- checkmate::assert_class(modules, "teal_modules")- |
- |
398 | -6x | -
- checkmate::assert_class(module, "teal_module")+ wait_for_active_module_value = function(input = rlang::missing_arg(), |
|
399 | -4x | +||
625 | +
- modules$children <- c(modules$children, list(module))+ output = rlang::missing_arg(), |
||
400 | -4x | +||
626 | +
- labels <- vapply(modules$children, function(submodule) submodule$label, character(1))+ export = rlang::missing_arg(), |
||
401 | -4x | +||
627 | +
- names(modules$children) <- get_unique_labels(labels)+ ...) { |
||
402 | -4x | +||
628 | +! |
- modules+ ns <- shiny::NS(self$active_module_ns()) |
|
403 | +629 |
- }+ |
|
404 | -+ | ||
630 | +! |
-
+ if (!rlang::is_missing(input) && checkmate::test_string(input, min.chars = 1)) input <- ns(input) |
|
405 | -+ | ||
631 | +! |
- #' Extract/Remove module(s) of specific class+ if (!rlang::is_missing(output) && checkmate::test_string(output, min.chars = 1)) output <- ns(output) |
|
406 | -+ | ||
632 | +! |
- #'+ if (!rlang::is_missing(export) && checkmate::test_string(export, min.chars = 1)) export <- ns(export) |
|
407 | +633 |
- #' Given a `teal_module` or a `teal_modules`, return the elements of the structure according to `class`.+ |
|
408 | -+ | ||
634 | +! |
- #'+ self$wait_for_value( |
|
409 | -+ | ||
635 | +! |
- #' @param modules (`teal_modules`)+ input = input, |
|
410 | -+ | ||
636 | +! |
- #' @param class The class name of `teal_module` to be extracted or dropped.+ output = output, |
|
411 | -+ | ||
637 | +! |
- #' @keywords internal+ export = export, |
|
412 | +638 |
- #' @return+ ... |
|
413 | +639 |
- #' - For `extract_module`, a `teal_module` of class `class` or `teal_modules` containing modules of class `class`.+ ) |
|
414 | +640 |
- #' - For `drop_module`, the opposite, which is all `teal_modules` of class other than `class`.+ } |
|
415 | +641 |
- #' @rdname module_management+ ), |
|
416 | +642 |
- extract_module <- function(modules, class) {- |
- |
417 | -24x | -
- if (inherits(modules, class)) {- |
- |
418 | -! | -
- modules+ # private members ---- |
|
419 | -24x | +||
643 | +
- } else if (inherits(modules, "teal_module")) {+ private = list( |
||
420 | -13x | +||
644 | +
- NULL+ # private attributes ---- |
||
421 | -11x | +||
645 | +
- } else if (inherits(modules, "teal_modules")) {+ data = NULL, |
||
422 | -11x | +||
646 | +
- Filter(function(x) length(x) > 0L, lapply(modules$children, extract_module, class))+ modules = NULL, |
||
423 | +647 |
- }+ filter = teal_slices(), |
|
424 | +648 |
- }+ ns = list( |
|
425 | +649 |
-
+ module = character(0), |
|
426 | +650 |
- #' @keywords internal+ filter_panel = character(0) |
|
427 | +651 |
- #' @return `teal_modules`+ ), |
|
428 | +652 |
- #' @rdname module_management+ # private methods ---- |
|
429 | +653 |
- drop_module <- function(modules, class) {+ set_active_ns = function() { |
|
430 | +654 | ! |
- if (inherits(modules, class)) {+ all_inputs <- self$get_values()$input |
431 | +655 | ! |
- NULL+ active_tab_inputs <- all_inputs[grepl("-active_tab$", names(all_inputs))] |
432 | -! | +||
656 | +
- } else if (inherits(modules, "teal_module")) {+ |
||
433 | +657 | ! |
- modules+ tab_ns <- unlist(lapply(names(active_tab_inputs), function(name) { |
434 | +658 | ! |
- } else if (inherits(modules, "teal_modules")) {+ gsub( |
435 | +659 | ! |
- do.call(+ pattern = "-active_tab$", |
436 | +660 | ! |
- "modules",+ replacement = sprintf("-%s", active_tab_inputs[[name]]), |
437 | +661 | ! |
- c(Filter(function(x) length(x) > 0L, lapply(modules$children, drop_module, class)), label = modules$label)- |
-
438 | -- |
- )+ name |
|
439 | +662 |
- }+ ) |
|
440 | +663 |
- }+ })) |
|
441 | -+ | ||
664 | +! |
-
+ active_ns <- tab_ns[1] |
|
442 | -+ | ||
665 | +! |
- ## read modules ----+ if (length(tab_ns) > 1) { |
|
443 | -+ | ||
666 | +! |
-
+ for (i in 2:length(tab_ns)) { |
|
444 | -+ | ||
667 | +! |
- #' Does the object make use of the `arg`+ next_ns <- tab_ns[i] |
|
445 | -+ | ||
668 | +! |
- #'+ if (grepl(pattern = active_ns, next_ns)) { |
|
446 | -+ | ||
669 | +! |
- #' @param modules (`teal_module` or `teal_modules`) object+ active_ns <- next_ns |
|
447 | +670 |
- #' @param arg (`character(1)`) names of the arguments to be checked against formals of `teal` modules.+ } |
|
448 | +671 |
- #' @return `logical` whether the object makes use of `arg`.+ } |
|
449 | +672 |
- #' @rdname is_arg_used+ } |
|
450 | -+ | ||
673 | +! |
- #' @keywords internal+ private$ns$module <- sprintf("%s-%s", active_ns, "module") |
|
451 | +674 |
- is_arg_used <- function(modules, arg) {- |
- |
452 | -486x | -
- checkmate::assert_string(arg)- |
- |
453 | -483x | -
- if (inherits(modules, "teal_modules")) {+ |
|
454 | -18x | +||
675 | +! |
- any(unlist(lapply(modules$children, is_arg_used, arg)))+ components <- c("filter_panel", "data_summary") |
|
455 | -465x | +||
676 | +! |
- } else if (inherits(modules, "teal_module")) {+ for (component in components) { |
|
456 | -30x | +||
677 | +
- is_arg_used(modules$server, arg) || is_arg_used(modules$ui, arg)+ if ( |
||
457 | -435x | +||
678 | +! |
- } else if (is.function(modules)) {+ !is.null(self$get_html(sprintf("#%s-%s-panel", active_ns, component))) || |
|
458 | -433x | +||
679 | +! |
- isTRUE(arg %in% names(formals(modules)))+ !is.null(self$get_html(sprintf("#%s-%s-table", active_ns, component))) |
|
459 | +680 |
- } else {- |
- |
460 | -2x | -
- stop("is_arg_used function not implemented for this object")+ ) { |
|
461 | -+ | ||
681 | +! |
- }+ private$ns[[component]] <- sprintf("%s-%s", active_ns, component) |
|
462 | +682 |
- }+ } else { |
|
463 | -+ | ||
683 | +! |
-
+ private$ns[[component]] <- sprintf("%s-module_%s", active_ns, component) |
|
464 | +684 |
-
+ } |
|
465 | +685 |
- #' Get module depth+ } |
|
466 | +686 |
- #'+ }, |
|
467 | +687 |
- #' Depth starts at 0, so a single `teal.module` has depth 0.+ # @description |
|
468 | +688 |
- #' Nesting it increases overall depth by 1.+ # Get the active filter values from the active filter selection of dataset from the filter panel. |
|
469 | +689 |
- #'+ # |
|
470 | +690 |
- #' @inheritParams init+ # @param dataset_name (character) The name of the dataset to get the filter values from. |
|
471 | +691 |
- #' @param depth optional integer determining current depth level+ # @param var_name (character) The name of the variable to get the filter values from. |
|
472 | +692 |
- #'+ # |
|
473 | +693 |
- #' @return Depth level for given module.+ # @return The value of the active filter selection. |
|
474 | +694 |
- #' @keywords internal+ get_active_filter_selection = function(dataset_name, var_name) { |
|
475 | -+ | ||
695 | +! |
- modules_depth <- function(modules, depth = 0L) {+ checkmate::check_string(dataset_name) |
|
476 | -12x | +||
696 | +! |
- checkmate::assert_multi_class(modules, c("teal_module", "teal_modules"))+ checkmate::check_string(var_name) |
|
477 | -12x | +||
697 | +! |
- checkmate::assert_int(depth, lower = 0)+ input_id_prefix <- sprintf( |
|
478 | -11x | +||
698 | +! |
- if (inherits(modules, "teal_modules")) {+ "%s-filters-%s-filter-%s_%s-inputs", |
|
479 | -4x | +||
699 | +! |
- max(vapply(modules$children, modules_depth, integer(1), depth = depth + 1L))+ self$active_filters_ns(), |
|
480 | -+ | ||
700 | +! |
- } else {+ dataset_name, |
|
481 | -7x | +||
701 | +! |
- depth+ dataset_name, |
|
482 | -+ | ||
702 | +! |
- }+ var_name |
|
483 | +703 |
- }+ ) |
|
484 | +704 | ||
485 | +705 |
- #' Retrieve labels from `teal_modules`+ # Find the type of filter (categorical or range) |
|
486 | -+ | ||
706 | +! |
- #'+ supported_suffix <- c("selection", "selection_manual") |
|
487 | -+ | ||
707 | +! |
- #' @param modules (`teal_modules`)+ for (suffix in supported_suffix) { |
|
488 | -+ | ||
708 | +! |
- #' @return A `list` containing the labels of the modules. If the modules are nested,+ if (!is.null(self$get_html(sprintf("#%s-%s", input_id_prefix, suffix)))) { |
|
489 | -+ | ||
709 | +! |
- #' the function returns a nested `list` of labels.+ return(self$get_value(input = sprintf("%s-%s", input_id_prefix, suffix))) |
|
490 | +710 |
- #' @keywords internal+ } |
|
491 | +711 |
- module_labels <- function(modules) {- |
- |
492 | -189x | -
- if (inherits(modules, "teal_modules")) {- |
- |
493 | -82x | -
- lapply(modules$children, module_labels)+ } |
|
494 | +712 |
- } else {+ |
|
495 | -107x | +||
713 | +! |
- modules$label+ NULL # If there are not any supported filters |
|
496 | +714 |
- }+ }, |
|
497 | +715 |
- }+ # @description |
|
498 | +716 |
-
+ # Check if the page is stable without any `DOM` updates in the body of the app. |
|
499 | +717 |
- #' Retrieve `teal_bookmarkable` attribute from `teal_modules`+ # This is achieved by blocing the R process by sleeping until the page is unchanged till the `stability_period`. |
|
500 | +718 |
- #'+ # @param stability_period (`numeric(1)`) The time in milliseconds to wait till the page to be stable. |
|
501 | +719 |
- #' @param modules (`teal_modules` or `teal_module`) object+ # @param check_interval (`numeric(1)`) The time in milliseconds to check for changes in the page. |
|
502 | +720 |
- #' @return named list of the same structure as `modules` with `TRUE` or `FALSE` values indicating+ # The stability check is reset when a change is detected in the page after sleeping for check_interval. |
|
503 | +721 |
- #' whether the module is bookmarkable.+ wait_for_page_stability = function(stability_period = 2000, check_interval = 200) {+ |
+ |
722 | +! | +
+ previous_content <- self$get_html("body")+ |
+ |
723 | +! | +
+ end_time <- Sys.time() + (stability_period / 1000) |
|
504 | +724 |
- #' @keywords internal+ + |
+ |
725 | +! | +
+ repeat {+ |
+ |
726 | +! | +
+ Sys.sleep(check_interval / 1000)+ |
+ |
727 | +! | +
+ current_content <- self$get_html("body") |
|
505 | +728 |
- modules_bookmarkable <- function(modules) {+ |
|
506 | -189x | +||
729 | +! |
- checkmate::assert_multi_class(modules, c("teal_modules", "teal_module"))+ if (!identical(previous_content, current_content)) { |
|
507 | -189x | +||
730 | +! |
- if (inherits(modules, "teal_modules")) {+ previous_content <- current_content |
|
508 | -82x | +||
731 | +! |
- setNames(+ end_time <- Sys.time() + (stability_period / 1000) |
|
509 | -82x | +||
732 | +! |
- lapply(modules$children, modules_bookmarkable),+ } else if (Sys.time() >= end_time) { |
|
510 | -82x | +||
733 | +! |
- vapply(modules$children, `[[`, "label", FUN.VALUE = character(1))+ break |
|
511 | +734 |
- )+ } |
|
512 | +735 |
- } else {+ } |
|
513 | -107x | +||
736 | +
- attr(modules, "teal_bookmarkable", exact = TRUE)+ } |
||
514 | +737 |
- }+ ) |
|
515 | +738 |
- }+ ) |
1 |
- #' Landing popup module+ setOldClass("teal_module") |
||
2 |
- #'+ setOldClass("teal_modules") |
||
3 |
- #' @description Creates a landing welcome popup for `teal` applications.+ |
||
4 |
- #'+ #' Create `teal_module` and `teal_modules` objects |
||
5 |
- #' This module is used to display a popup dialog when the application starts.+ #' |
||
6 |
- #' The dialog blocks access to the application and must be closed with a button before the application can be viewed.+ #' @description |
||
7 |
- #'+ #' `r lifecycle::badge("stable")` |
||
8 |
- #' @param label (`character(1)`) Label of the module.+ #' Create a nested tab structure to embed modules in a `teal` application. |
||
9 |
- #' @param title (`character(1)`) Text to be displayed as popup title.+ #' |
||
10 |
- #' @param content (`character(1)`, `shiny.tag` or `shiny.tag.list`) with the content of the popup.+ #' @details |
||
11 |
- #' Passed to `...` of `shiny::modalDialog`. See examples.+ #' `module()` creates an instance of a `teal_module` that can be placed in a `teal` application. |
||
12 |
- #' @param buttons (`shiny.tag` or `shiny.tag.list`) Typically a `modalButton` or `actionButton`. See examples.+ #' `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 |
- #' @return A `teal_module` (extended with `teal_landing_module` class) to be used in `teal` applications.+ #' which results in a nested structure corresponding to the nested tabs in the final application. |
||
16 |
- #' @examples+ #' Note that for `modules()` `label` comes after `...`, so it must be passed as a named argument, |
||
17 |
- #' app1 <- init(+ #' otherwise it will be captured by `...`. |
||
18 |
- #' data = teal_data(iris = iris),+ #' |
||
19 |
- #' modules = modules(+ #' The labels `"global_filters"` and `"Report previewer"` are reserved |
||
20 |
- #' example_module()+ #' because they are used by the `mapping` argument of [teal_slices()] |
||
21 |
- #' ),+ #' and the report previewer module [reporter_previewer_module()], respectively. |
||
22 |
- #' landing_popup = landing_popup_module(+ #' |
||
23 |
- #' content = "A place for the welcome message or a disclaimer statement.",+ #' # Restricting datasets used by `teal_module`: |
||
24 |
- #' buttons = modalButton("Proceed")+ #' 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 |
- #' if (interactive()) {+ #' When `datanames` is set to `"all"`, all datasets in the data object are treated as relevant. |
||
28 |
- #' shinyApp(app1$ui, app1$server)+ #' However, this may include unnecessary datasets, such as: |
||
29 |
- #' }+ #' - Proxy variables for column modifications |
||
30 |
- #'+ #' - Temporary datasets used to create final versions |
||
31 |
- #' app2 <- init(+ #' - Connection objects |
||
32 |
- #' data = teal_data(iris = iris),+ #' |
||
33 |
- #' modules = modules(+ #' To exclude irrelevant datasets, use the [set_datanames()] function to change `datanames` from |
||
34 |
- #' example_module()+ #' `"all"` to specific names. Trying to modify non-`"all"` values with [set_datanames()] will result |
||
35 |
- #' ),+ #' in a warning. Datasets with names starting with . are ignored globally unless explicitly listed |
||
36 |
- #' landing_popup = landing_popup_module(+ #' in `datanames`. |
||
37 |
- #' title = "Welcome",+ #' |
||
38 |
- #' content = tags$b(+ #' # `datanames` with `transformers` |
||
39 |
- #' "A place for the welcome message or a disclaimer statement.",+ #' When transformers are specified, their `datanames` are added to the module’s `datanames`, which |
||
40 |
- #' style = "color: red;"+ #' changes the behavior as follows: |
||
41 |
- #' ),+ #' - If `module(datanames)` is `NULL` and the `transformers` have defined `datanames`, the sidebar |
||
42 |
- #' buttons = tagList(+ #' will appear showing the `transformers`' datasets, instead of being hidden. |
||
43 |
- #' modalButton("Proceed"),+ #' - If `module(datanames)` is set to specific values and any `transformer` has `datanames = "all"`, |
||
44 |
- #' actionButton("read", "Read more",+ #' the module may receive extra datasets that could be unnecessary |
||
45 |
- #' onclick = "window.open('http://google.com', '_blank')"+ #' |
||
46 |
- #' ),+ #' @param label (`character(1)`) Label shown in the navigation item for the module or module group. |
||
47 |
- #' actionButton("close", "Reject", onclick = "window.close()")+ #' For `modules()` defaults to `"root"`. See `Details`. |
||
48 |
- #' )+ #' @param server (`function`) `shiny` module with following arguments: |
||
49 |
- #' )- |
- ||
50 | -- |
- #' )- |
- |
51 | -- |
- #'- |
- |
52 | -- |
- #' if (interactive()) {- |
- |
53 | -- |
- #' shinyApp(app2$ui, app2$server)- |
- |
54 | -- |
- #' }- |
- |
55 | -- |
- #'- |
- |
56 | -- |
- #' @export- |
- |
57 | -- |
- landing_popup_module <- function(label = "Landing Popup",- |
- |
58 | -- |
- title = NULL,- |
- |
59 | -- |
- content = NULL,- |
- |
60 | -- |
- buttons = modalButton("Accept")) {- |
- |
61 | -! | -
- checkmate::assert_string(label)- |
- |
62 | -! | -
- checkmate::assert_string(title, null.ok = TRUE)- |
- |
63 | -! | -
- checkmate::assert_multi_class(- |
- |
64 | -! | -
- content,- |
- |
65 | -! | -
- classes = c("character", "shiny.tag", "shiny.tag.list", "html"), null.ok = TRUE- |
- |
66 | -- |
- )- |
- |
67 | -! | -
- checkmate::assert_multi_class(buttons, classes = c("shiny.tag", "shiny.tag.list"))- |
- |
68 | -- | - - | -|
69 | -! | -
- message("Initializing landing_popup_module")- |
- |
70 | -- | - - | -|
71 | -! | -
- module <- module(- |
- |
72 | -! | -
- label = label,- |
- |
73 | -! | -
- server = function(id) {- |
- |
74 | -! | -
- moduleServer(id, function(input, output, session) {- |
- |
75 | -! | -
- showModal(- |
- |
76 | -! | -
- modalDialog(- |
- |
77 | -! | -
- id = "landingpopup",- |
- |
78 | -! | -
- title = title,- |
- |
79 | -! | -
- content,- |
- |
80 | -! | -
- footer = buttons- |
- |
81 | -- |
- )- |
- |
82 | -- |
- )- |
- |
83 | -- |
- })- |
- |
84 | -- |
- }- |
- |
85 | -- |
- )- |
- |
86 | -! | -
- class(module) <- c("teal_module_landing", class(module))- |
- |
87 | -! | -
- module+ #' - `id` - `teal` will set proper `shiny` namespace for this module (see [shiny::moduleServer()]). |
|
88 | +50 |
- }+ #' - `input`, `output`, `session` - (optional; not recommended) When provided, then [shiny::callModule()] |
1 | +51 |
- #' Create a `teal` module for previewing a report+ #' will be used to call a module. From `shiny` 1.5.0, the recommended way is to use |
|
2 | +52 |
- #'+ #' [shiny::moduleServer()] instead which doesn't require these arguments. |
|
3 | +53 |
- #' @description `r lifecycle::badge("experimental")`+ #' - `data` (optional) When provided, the module will be called with `teal_data` object (i.e. a list of |
|
4 | +54 |
- #'+ #' reactive (filtered) data specified in the `filters` argument) as the value of this argument. |
|
5 | +55 |
- #' This function wraps [teal.reporter::reporter_previewer_ui()] and+ #' - `datasets` (optional) When provided, the module will be called with `FilteredData` object as the |
|
6 | +56 |
- #' [teal.reporter::reporter_previewer_srv()] into a `teal_module` to be+ #' value of this argument. (See [`teal.slice::FilteredData`]). |
|
7 | +57 |
- #' used in `teal` applications.+ #' - `reporter` (optional) When provided, the module will be called with `Reporter` object as the value |
|
8 | +58 |
- #'+ #' of this argument. (See [`teal.reporter::Reporter`]). |
|
9 | +59 |
- #' If you are creating a `teal` application using [init()] then this+ #' - `filter_panel_api` (optional) When provided, the module will be called with `FilterPanelAPI` object |
|
10 | +60 |
- #' module will be added to your application automatically if any of your `teal_modules`+ #' as the value of this argument. (See [`teal.slice::FilterPanelAPI`]). |
|
11 | +61 |
- #' support report generation.+ #' - `...` (optional) When provided, `server_args` elements will be passed to the module named argument |
|
12 | +62 |
- #'+ #' or to the `...`. |
|
13 | +63 |
- #' @inheritParams teal_modules+ #' @param ui (`function`) `shiny` UI module function with following arguments: |
|
14 | +64 |
- #' @param server_args (named `list`)+ #' - `id` - `teal` will set proper `shiny` namespace for this module. |
|
15 | +65 |
- #' Arguments passed to [teal.reporter::reporter_previewer_srv()].+ #' - `...` (optional) When provided, `ui_args` elements will be passed to the module named argument |
|
16 | +66 |
- #'+ #' or to the `...`. |
|
17 | +67 |
- #' @return+ #' @param filters (`character`) Deprecated. Use `datanames` instead. |
|
18 | +68 |
- #' `teal_module` (extended with `teal_module_previewer` class) containing the `teal.reporter` previewer functionality.+ #' @param datanames (`character`) Names of the datasets relevant to the item. |
|
19 | +69 |
- #'+ #' There are 2 reserved values that have specific behaviors: |
|
20 | +70 |
- #' @export+ #' - The keyword `"all"` includes all datasets available in the data passed to the teal application. |
|
21 | +71 |
- #'+ #' - `NULL` hides the sidebar panel completely. |
|
22 | +72 |
- reporter_previewer_module <- function(label = "Report previewer", server_args = list()) {+ #' - If `transformers` are specified, their `datanames` are automatically added to this `datanames` |
|
23 | -7x | +||
73 | +
- checkmate::assert_string(label)+ #' argument. |
||
24 | -5x | +||
74 | +
- checkmate::assert_list(server_args, names = "named")+ #' @param server_args (named `list`) with additional arguments passed on to the server function. |
||
25 | -5x | +||
75 | +
- checkmate::assert_true(all(names(server_args) %in% names(formals(teal.reporter::reporter_previewer_srv))))+ #' @param ui_args (named `list`) with additional arguments passed on to the UI function. |
||
26 | +76 |
-
+ #' @param x (`teal_module` or `teal_modules`) Object to format/print. |
|
27 | -3x | +||
77 | +
- message("Initializing reporter_previewer_module")+ #' @param indent (`integer(1)`) Indention level; each nested element is indented one level more. |
||
28 | +78 |
-
+ #' @param transformers (`list` of `teal_data_module`) that will be applied to transform the data. |
|
29 | -3x | +||
79 | +
- srv <- function(id, reporter, ...) {+ #' Each transform module UI will appear in the `teal`'s sidebar panel. |
||
30 | -! | +||
80 | +
- teal.reporter::reporter_previewer_srv(id, reporter, ...)+ #' Transformers' `datanames` are added to the `datanames`. See [teal_transform_module()]. |
||
31 | +81 |
- }+ #' |
|
32 | +82 |
-
+ #' @param ... |
|
33 | -3x | +||
83 | +
- ui <- function(id, ...) {+ #' - For `modules()`: (`teal_module` or `teal_modules`) Objects to wrap into a tab. |
||
34 | -! | +||
84 | +
- teal.reporter::reporter_previewer_ui(id, ...)+ #' - For `format()` and `print()`: Arguments passed to other methods. |
||
35 | +85 |
- }+ #' |
|
36 | +86 |
-
+ #' @return |
|
37 | -3x | +||
87 | +
- module <- module(+ #' `module()` returns an object of class `teal_module`. |
||
38 | -3x | +||
88 | +
- label = "temporary label",+ #' |
||
39 | -3x | +||
89 | +
- server = srv, ui = ui,+ #' `modules()` returns a `teal_modules` object which contains following fields: |
||
40 | -3x | +||
90 | +
- server_args = server_args, ui_args = list(), datanames = NULL+ #' - `label`: taken from the `label` argument. |
||
41 | +91 |
- )+ #' - `children`: a list containing objects passed in `...`. List elements are named after |
|
42 | +92 |
- # Module is created with a placeholder label and the label is changed later.+ #' their `label` attribute converted to a valid `shiny` id. |
|
43 | +93 |
- # This is to prevent another module being labeled "Report previewer".+ #' |
|
44 | -3x | +||
94 | +
- class(module) <- c(class(module), "teal_module_previewer")+ #' @name teal_modules |
||
45 | -3x | +||
95 | +
- module$label <- label+ #' @aliases teal_module |
||
46 | -3x | +||
96 | +
- attr(module, "teal_bookmarkable") <- TRUE+ #' |
||
47 | -3x | +||
97 | +
- module+ #' @examples |
||
48 | +98 |
- }+ #' library(shiny) |
1 | +99 |
- #' Calls all `modules`+ #' |
||
2 | +100 |
- #'+ #' module_1 <- module( |
||
3 | +101 |
- #' On the UI side each `teal_modules` is translated to a `tabsetPanel` and each `teal_module` is a+ #' label = "a module", |
||
4 | +102 |
- #' `tabPanel`. Both, UI and server are called recursively so that each tab is a separate module and+ #' server = function(id, data) { |
||
5 | +103 |
- #' reflect nested structure of `modules` argument.+ #' moduleServer( |
||
6 | +104 |
- #'+ #' id, |
||
7 | +105 |
- #' @name module_teal_module+ #' module = function(input, output, session) { |
||
8 | +106 |
- #'+ #' output$data <- renderDataTable(data()[["iris"]]) |
||
9 | +107 |
- #' @inheritParams module_teal+ #' } |
||
10 | +108 |
- #'+ #' ) |
||
11 | +109 |
- #' @param data_rv (`reactive` returning `teal_data`)+ #' }, |
||
12 | +110 |
- #'+ #' ui = function(id) { |
||
13 | +111 |
- #' @param slices_global (`reactiveVal` returning `modules_teal_slices`)+ #' ns <- NS(id) |
||
14 | +112 |
- #' see [`module_filter_manager`]+ #' tagList(dataTableOutput(ns("data"))) |
||
15 | +113 |
- #'+ #' }, |
||
16 | +114 |
- #' @param depth (`integer(1)`)+ #' datanames = "all" |
||
17 | +115 |
- #' number which helps to determine depth of the modules nesting.+ #' ) |
||
18 | +116 |
#' |
||
19 | +117 |
- #' @param datasets (`reactive` returning `FilteredData` or `NULL`)+ #' module_2 <- module( |
||
20 | +118 |
- #' When `datasets` is passed from the parent module (`srv_teal`) then `dataset` is a singleton+ #' label = "another module", |
||
21 | +119 |
- #' which implies in filter-panel to be "global". When `NULL` then filter-panel is "module-specific".+ #' server = function(id) { |
||
22 | +120 |
- #'+ #' moduleServer( |
||
23 | +121 |
- #' @param data_load_status (`reactive` returning `character`)+ #' id, |
||
24 | +122 |
- #' Determines action dependent on a data loading status:+ #' module = function(input, output, session) { |
||
25 | +123 |
- #' - `"ok"` when `teal_data` is returned from the data loading.+ #' output$text <- renderText("Another Module") |
||
26 | +124 |
- #' - `"teal_data_module failed"` when [teal_data_module()] didn't return `teal_data`. Disables tabs buttons.+ #' } |
||
27 | +125 |
- #' - `"external failed"` when a `reactive` passed to `srv_teal(data)` didn't return `teal_data`. Hides the whole tab+ #' ) |
||
28 | +126 |
- #' panel.+ #' }, |
||
29 | +127 |
- #'+ #' ui = function(id) { |
||
30 | +128 |
- #' @return+ #' ns <- NS(id) |
||
31 | +129 |
- #' output of currently active module.+ #' tagList(textOutput(ns("text"))) |
||
32 | +130 |
- #' - `srv_teal_module.teal_module` returns `reactiveVal` containing output of the called module.+ #' }, |
||
33 | +131 |
- #' - `srv_teal_module.teal_modules` returns output of module selected by `input$active_tab`.+ #' datanames = NULL |
||
34 | +132 | ++ |
+ #' )+ |
+ |
133 |
#' |
|||
35 | +134 |
- #' @keywords internal+ #' modules <- modules( |
||
36 | +135 |
- NULL+ #' label = "modules", |
||
37 | +136 |
-
+ #' modules( |
||
38 | +137 |
- #' @rdname module_teal_module+ #' label = "nested modules", |
||
39 | +138 |
- ui_teal_module <- function(id, modules, depth = 0L) {+ #' module_1 |
||
40 | -! | +|||
139 | +
- checkmate::assert_multi_class(modules, c("teal_modules", "teal_module", "shiny.tag"))+ #' ), |
|||
41 | -! | +|||
140 | +
- checkmate::assert_count(depth)+ #' module_2 |
|||
42 | -! | +|||
141 | +
- UseMethod("ui_teal_module", modules)+ #' ) |
|||
43 | +142 |
- }+ #' |
||
44 | +143 |
-
+ #' app <- init( |
||
45 | +144 |
- #' @rdname module_teal_module+ #' data = teal_data(iris = iris), |
||
46 | +145 |
- #' @export+ #' modules = modules |
||
47 | +146 |
- ui_teal_module.default <- function(id, modules, depth = 0L) {+ #' ) |
||
48 | -! | +|||
147 | +
- stop("Modules class not supported: ", paste(class(modules), collapse = " "))+ #' |
|||
49 | +148 |
- }+ #' if (interactive()) { |
||
50 | +149 |
-
+ #' shinyApp(app$ui, app$server) |
||
51 | +150 |
- #' @rdname module_teal_module+ #' } |
||
52 | +151 |
- #' @export+ #' @rdname teal_modules |
||
53 | +152 |
- ui_teal_module.teal_modules <- function(id, modules, depth = 0L) {+ #' @export |
||
54 | -! | +|||
153 | +
- ns <- NS(id)+ #' |
|||
55 | -! | +|||
154 | +
- tags$div(+ module <- function(label = "module", |
|||
56 | -! | +|||
155 | +
- id = ns("wrapper"),+ server = function(id, data, ...) moduleServer(id, function(input, output, session) NULL), |
|||
57 | -! | +|||
156 | +
- do.call(+ ui = function(id, ...) tags$p(paste0("This module has no UI (id: ", id, " )")), |
|||
58 | -! | +|||
157 | +
- tabsetPanel,+ filters, |
|||
59 | -! | +|||
158 | +
- c(+ datanames = "all", |
|||
60 | +159 |
- # by giving an id, we can reactively respond to tab changes+ server_args = NULL, |
||
61 | -! | +|||
160 | +
- list(+ ui_args = NULL, |
|||
62 | -! | +|||
161 | +
- id = ns("active_tab"),+ transformers = list()) { |
|||
63 | -! | +|||
162 | +
- type = if (modules$label == "root") "pills" else "tabs"+ # argument checking (independent) |
|||
64 | +163 |
- ),+ ## `label` |
||
65 | -! | +|||
164 | +213x |
- lapply(+ checkmate::assert_string(label) |
||
66 | -! | +|||
165 | +210x |
- names(modules$children),+ if (label == "global_filters") { |
||
67 | -! | +|||
166 | +1x |
- function(module_id) {+ stop( |
||
68 | -! | +|||
167 | +1x |
- module_label <- modules$children[[module_id]]$label+ sprintf("module(label = \"%s\", ...\n ", label), |
||
69 | -! | +|||
168 | +1x |
- if (is.null(module_label)) {+ "Label 'global_filters' is reserved in teal. Please change to something else.", |
||
70 | -! | +|||
169 | +1x |
- module_label <- icon("fas fa-database")+ call. = FALSE |
||
71 | +170 |
- }+ ) |
||
72 | -! | +|||
171 | +
- tabPanel(+ } |
|||
73 | -! | +|||
172 | +209x |
- title = module_label,+ if (label == "Report previewer") { |
||
74 | +173 | ! |
- value = module_id, # when clicked this tab value changes input$<tabset panel id>+ stop( |
|
75 | +174 | ! |
- ui_teal_module(+ sprintf("module(label = \"%s\", ...\n ", label), |
|
76 | +175 | ! |
- id = ns(module_id),+ "Label 'Report previewer' is reserved in teal. Please change to something else.", |
|
77 | +176 | ! |
- modules = modules$children[[module_id]],+ call. = FALSE |
|
78 | -! | +|||
177 | +
- depth = depth + 1L+ ) |
|||
79 | +178 |
- )+ } |
||
80 | +179 |
- )+ |
||
81 | +180 |
- }+ ## server |
||
82 | -+ | |||
181 | +209x |
- )+ checkmate::assert_function(server) |
||
83 | -+ | |||
182 | +209x |
- )+ server_formals <- names(formals(server)) |
||
84 | -+ | |||
183 | +209x |
- )+ if (!( |
||
85 | -+ | |||
184 | +209x |
- )+ "id" %in% server_formals || |
||
86 | -+ | |||
185 | +209x |
- }+ all(c("input", "output", "session") %in% server_formals) |
||
87 | +186 |
-
+ )) { |
||
88 | -+ | |||
187 | +2x |
- #' @rdname module_teal_module+ stop( |
||
89 | -+ | |||
188 | +2x |
- #' @export+ "\nmodule() `server` argument requires a function with following arguments:", |
||
90 | -+ | |||
189 | +2x |
- ui_teal_module.teal_module <- function(id, modules, depth = 0L) {+ "\n - id - `teal` will set proper `shiny` namespace for this module.", |
||
91 | -! | +|||
190 | +2x |
- ns <- NS(id)+ "\n - input, output, session (not recommended) - then `shiny::callModule` will be used to call a module.", |
||
92 | -! | +|||
191 | +2x |
- args <- c(list(id = ns("module")), modules$ui_args)+ "\n\nFollowing arguments can be used optionaly:", |
||
93 | -+ | |||
192 | +2x |
-
+ "\n - `data` - module will receive list of reactive (filtered) data specified in the `filters` argument", |
||
94 | -! | +|||
193 | +2x |
- ui_teal <- tagList(+ "\n - `datasets` - module will receive `FilteredData`. See `help(teal.slice::FilteredData)`", |
||
95 | -! | +|||
194 | +2x |
- div(+ "\n - `reporter` - module will receive `Reporter`. See `help(teal.reporter::Reporter)`", |
||
96 | -! | +|||
195 | +2x |
- id = ns("validate_datanames"),+ "\n - `filter_panel_api` - module will receive `FilterPanelAPI`. (See [teal.slice::FilterPanelAPI]).", |
||
97 | -! | +|||
196 | +2x |
- ui_validate_reactive_teal_data(ns("validate_datanames"))+ "\n - `...` server_args elements will be passed to the module named argument or to the `...`" |
||
98 | +197 |
- ),+ ) |
||
99 | -! | +|||
198 | +
- shinyjs::hidden(+ } |
|||
100 | -! | +|||
199 | +207x |
- tags$div(+ if ("datasets" %in% server_formals) { |
||
101 | -! | +|||
200 | +2x |
- id = ns("transformer_failure_info"),+ warning( |
||
102 | -! | +|||
201 | +2x |
- class = "teal_validated",+ sprintf("Called from module(label = \"%s\", ...)\n ", label), |
||
103 | -! | +|||
202 | +2x |
- div(+ "`datasets` argument in the server is deprecated and will be removed in the next release. ", |
||
104 | -! | +|||
203 | +2x |
- class = "teal-output-warning",+ "Please use `data` instead.", |
||
105 | -! | +|||
204 | +2x |
- "One of transformers failed. Please fix and continue."+ call. = FALSE |
||
106 | +205 |
- )+ ) |
||
107 | +206 |
- )+ } |
||
108 | +207 |
- ),- |
- ||
109 | -! | -
- tags$div(+ |
||
110 | -! | +|||
208 | +
- id = ns("teal_module_ui"),+ |
|||
111 | -! | +|||
209 | +
- do.call(modules$ui, args)+ ## UI |
|||
112 | -+ | |||
210 | +207x |
- )+ checkmate::assert_function(ui) |
||
113 | -+ | |||
211 | +207x |
- )+ ui_formals <- names(formals(ui)) |
||
114 | -+ | |||
212 | +207x |
-
+ if (!"id" %in% ui_formals) { |
||
115 | -! | +|||
213 | +1x |
- div(+ stop( |
||
116 | -! | +|||
214 | +1x |
- id = id,+ "\nmodule() `ui` argument requires a function with following arguments:", |
||
117 | -! | +|||
215 | +1x |
- class = "teal_module",+ "\n - id - `teal` will set proper `shiny` namespace for this module.", |
||
118 | -! | +|||
216 | +1x |
- uiOutput(ns("data_reactive"), inline = TRUE),+ "\n\nFollowing arguments can be used optionally:", |
||
119 | -! | +|||
217 | +1x |
- tagList(+ "\n - `...` ui_args elements will be passed to the module argument of the same name or to the `...`" |
||
120 | -! | +|||
218 | +
- if (depth >= 2L) tags$div(style = "mt-6"),+ ) |
|||
121 | -! | +|||
219 | +
- if (!is.null(modules$datanames)) {+ } |
|||
122 | -! | +|||
220 | +206x |
- fluidRow(+ if (any(c("data", "datasets") %in% ui_formals)) { |
||
123 | -! | +|||
221 | +2x |
- column(width = 9, ui_teal, class = "teal_primary_col"),+ stop( |
||
124 | -! | +|||
222 | +2x |
- column(+ sprintf("Called from module(label = \"%s\", ...)\n ", label), |
||
125 | -! | +|||
223 | +2x |
- width = 3,+ "UI with `data` or `datasets` argument is no longer accepted.\n ", |
||
126 | -! | +|||
224 | +2x |
- ui_data_summary(ns("data_summary")),+ "If some UI inputs depend on data, please move the logic to your server instead.\n ", |
||
127 | -! | +|||
225 | +2x |
- ui_filter_data(ns("filter_panel")),+ "Possible solutions are renderUI() or updateXyzInput() functions." |
||
128 | -! | +|||
226 | +
- ui_transform_data(ns("data_transform"), transformers = modules$transformers, class = "well"),+ ) |
|||
129 | -! | +|||
227 | +
- class = "teal_secondary_col"+ } |
|||
130 | +228 |
- )+ |
||
131 | +229 |
- )+ |
||
132 | +230 |
- } else {+ ## `filters` |
||
133 | -! | +|||
231 | +204x |
- div(+ if (!missing(filters)) { |
||
134 | +232 | ! |
- div(+ datanames <- filters |
|
135 | +233 | ! |
- class = "teal_validated",+ msg <- |
|
136 | +234 | ! |
- uiOutput(ns("data_input_error"))- |
- |
137 | -- |
- ),+ "The `filters` argument is deprecated and will be removed in the next release. Please use `datanames` instead." |
||
138 | +235 | ! |
- ui_teal- |
- |
139 | -- |
- )- |
- ||
140 | -- |
- }- |
- ||
141 | -- |
- )- |
- ||
142 | -- |
- )+ warning(msg) |
||
143 | +236 |
- }+ } |
||
144 | +237 | |||
145 | +238 |
- #' @rdname module_teal_module+ ## `datanames` (also including deprecated `filters`) |
||
146 | +239 |
- srv_teal_module <- function(id,+ # please note a race condition between datanames set when filters is not missing and data arg in server function |
||
147 | -+ | |||
240 | +204x |
- data_rv,+ if (!is.element("data", server_formals) && !is.null(datanames)) { |
||
148 | -+ | |||
241 | +12x |
- modules,+ message(sprintf("module \"%s\" server function takes no data so \"datanames\" will be ignored", label)) |
||
149 | -+ | |||
242 | +12x |
- datasets = NULL,+ datanames <- NULL |
||
150 | +243 |
- slices_global,+ } |
||
151 | -+ | |||
244 | +204x |
- reporter = teal.reporter::Reporter$new(),+ checkmate::assert_character(datanames, min.len = 1, null.ok = TRUE, any.missing = FALSE) |
||
152 | +245 |
- data_load_status = reactive("ok"),+ |
||
153 | +246 |
- is_active = reactive(TRUE)) {- |
- ||
154 | -189x | -
- checkmate::assert_string(id)+ ## `server_args` |
||
155 | -189x | +247 | +203x |
- assert_reactive(data_rv)+ checkmate::assert_list(server_args, null.ok = TRUE, names = "named") |
156 | -189x | +248 | +201x |
- checkmate::assert_multi_class(modules, c("teal_modules", "teal_module"))+ srv_extra_args <- setdiff(names(server_args), server_formals) |
157 | -189x | +249 | +201x |
- assert_reactive(datasets, null.ok = TRUE)+ if (length(srv_extra_args) > 0 && !"..." %in% server_formals) { |
158 | -189x | +250 | +1x |
- checkmate::assert_class(slices_global, ".slicesGlobal")+ stop( |
159 | -189x | +251 | +1x |
- checkmate::assert_class(reporter, "Reporter")+ "\nFollowing `server_args` elements have no equivalent in the formals of the server:\n", |
160 | -189x | +252 | +1x |
- assert_reactive(data_load_status)+ paste(paste(" -", srv_extra_args), collapse = "\n"), |
161 | -189x | +253 | +1x |
- UseMethod("srv_teal_module", modules)+ "\n\nUpdate the server arguments by including above or add `...`" |
162 | +254 |
- }+ ) |
||
163 | +255 |
-
+ } |
||
164 | +256 |
- #' @rdname module_teal_module+ |
||
165 | +257 |
- #' @export+ ## `ui_args` |
||
166 | -+ | |||
258 | +200x |
- srv_teal_module.default <- function(id,+ checkmate::assert_list(ui_args, null.ok = TRUE, names = "named") |
||
167 | -+ | |||
259 | +198x |
- data_rv,+ ui_extra_args <- setdiff(names(ui_args), ui_formals) |
||
168 | -+ | |||
260 | +198x |
- modules,+ if (length(ui_extra_args) > 0 && !"..." %in% ui_formals) { |
||
169 | -+ | |||
261 | +1x |
- datasets = NULL,+ stop( |
||
170 | -+ | |||
262 | +1x |
- slices_global,+ "\nFollowing `ui_args` elements have no equivalent in the formals of UI:\n", |
||
171 | -+ | |||
263 | +1x |
- reporter = teal.reporter::Reporter$new(),+ paste(paste(" -", ui_extra_args), collapse = "\n"), |
||
172 | -+ | |||
264 | +1x |
- data_load_status = reactive("ok"),+ "\n\nUpdate the UI arguments by including above or add `...`" |
||
173 | +265 |
- is_active = reactive(TRUE)) {- |
- ||
174 | -! | -
- stop("Modules class not supported: ", paste(class(modules), collapse = " "))+ ) |
||
175 | +266 |
- }+ } |
||
176 | +267 | |||
177 | -- |
- #' @rdname module_teal_module- |
- ||
178 | +268 |
- #' @export+ ## `transformers` |
||
179 | -+ | |||
269 | +197x |
- srv_teal_module.teal_modules <- function(id,+ if (inherits(transformers, "teal_transform_module")) { |
||
180 | -+ | |||
270 | +1x |
- data_rv,+ transformers <- list(transformers) |
||
181 | +271 |
- modules,+ } |
||
182 | -+ | |||
272 | +197x |
- datasets = NULL,+ checkmate::assert_list(transformers, types = "teal_transform_module") |
||
183 | -+ | |||
273 | +197x |
- slices_global,+ transformer_datanames <- unlist(lapply(transformers, attr, "datanames")) |
||
184 | -+ | |||
274 | +197x |
- reporter = teal.reporter::Reporter$new(),+ combined_datanames <- if (identical(datanames, "all")) { |
||
185 | -+ | |||
275 | +144x |
- data_load_status = reactive("ok"),+ "all" |
||
186 | +276 |
- is_active = reactive(TRUE)) {+ } else { |
||
187 | -82x | +277 | +53x |
- moduleServer(id = id, module = function(input, output, session) {+ union(datanames, transformer_datanames) |
188 | -82x | +|||
278 | +
- logger::log_debug("srv_teal_module.teal_modules initializing the module { deparse1(modules$label) }.")+ } |
|||
189 | +279 | |||
190 | -82x | +280 | +197x |
- observeEvent(data_load_status(), {+ structure( |
191 | -75x | +281 | +197x |
- tabs_selector <- sprintf("#%s li a", session$ns("active_tab"))+ list( |
192 | -75x | +282 | +197x |
- if (identical(data_load_status(), "ok")) {+ label = label, |
193 | -70x | +283 | +197x |
- logger::log_debug("srv_teal_module@1 enabling modules tabs.")+ server = server, |
194 | -70x | +284 | +197x |
- shinyjs::show("wrapper")+ ui = ui, |
195 | -70x | +285 | +197x |
- shinyjs::enable(selector = tabs_selector)+ datanames = combined_datanames, |
196 | -5x | +286 | +197x |
- } else if (identical(data_load_status(), "teal_data_module failed")) {+ server_args = server_args, |
197 | -5x | +287 | +197x |
- logger::log_debug("srv_teal_module@1 disabling modules tabs.")+ ui_args = ui_args, |
198 | -5x | -
- shinyjs::disable(selector = tabs_selector)- |
- ||
199 | -! | +288 | +197x |
- } else if (identical(data_load_status(), "external failed")) {+ transformers = transformers |
200 | -! | +|||
289 | +
- logger::log_debug("srv_teal_module@1 hiding modules tabs.")+ ), |
|||
201 | -! | +|||
290 | +197x |
- shinyjs::hide("wrapper")+ class = "teal_module" |
||
202 | +291 |
- }+ ) |
||
203 | +292 |
- })+ } |
||
204 | +293 | |||
205 | -82x | -
- modules_output <- sapply(- |
- ||
206 | -82x | -
- names(modules$children),- |
- ||
207 | -82x | -
- function(module_id) {- |
- ||
208 | -107x | -
- srv_teal_module(- |
- ||
209 | -107x | +|||
294 | +
- id = module_id,+ #' @rdname teal_modules |
|||
210 | -107x | +|||
295 | +
- data_rv = data_rv,+ #' @export |
|||
211 | -107x | +|||
296 | +
- modules = modules$children[[module_id]],+ #' |
|||
212 | -107x | +|||
297 | +
- datasets = datasets,+ modules <- function(..., label = "root") { |
|||
213 | -107x | +298 | +137x |
- slices_global = slices_global,+ checkmate::assert_string(label) |
214 | -107x | +299 | +135x |
- reporter = reporter,+ submodules <- list(...) |
215 | -107x | +300 | +135x |
- is_active = reactive(+ if (any(vapply(submodules, is.character, FUN.VALUE = logical(1)))) { |
216 | -107x | +301 | +2x |
- is_active() &&+ stop( |
217 | -107x | +302 | +2x |
- input$active_tab == module_id &&+ "The only character argument to modules() must be 'label' and it must be named, ", |
218 | -107x | +303 | +2x |
- identical(data_load_status(), "ok")+ "change modules('lab', ...) to modules(label = 'lab', ...)" |
219 | +304 |
- )+ ) |
||
220 | +305 |
- )+ } |
||
221 | +306 |
- },+ |
||
222 | -82x | +307 | +133x |
- simplify = FALSE+ checkmate::assert_list(submodules, min.len = 1, any.missing = FALSE, types = c("teal_module", "teal_modules")) |
223 | +308 |
- )+ # name them so we can more easily access the children |
||
224 | +309 |
-
+ # beware however that the label of the submodules should not be changed as it must be kept synced |
||
225 | -82x | +310 | +130x |
- modules_output+ labels <- vapply(submodules, function(submodule) submodule$label, character(1)) |
226 | -+ | |||
311 | +130x |
- })+ names(submodules) <- get_unique_labels(labels) |
||
227 | -+ | |||
312 | +130x |
- }+ structure( |
||
228 | -+ | |||
313 | +130x |
-
+ list( |
||
229 | -+ | |||
314 | +130x |
- #' @rdname module_teal_module+ label = label, |
||
230 | -+ | |||
315 | +130x |
- #' @export+ children = submodules |
||
231 | +316 |
- srv_teal_module.teal_module <- function(id,+ ), |
||
232 | -+ | |||
317 | +130x |
- data_rv,+ class = "teal_modules" |
||
233 | +318 |
- modules,+ ) |
||
234 | +319 |
- datasets = NULL,+ } |
||
235 | +320 |
- slices_global,+ |
||
236 | +321 |
- reporter = teal.reporter::Reporter$new(),+ # printing methods ---- |
||
237 | +322 |
- data_load_status = reactive("ok"),+ |
||
238 | +323 |
- is_active = reactive(TRUE)) {- |
- ||
239 | -107x | -
- logger::log_debug("srv_teal_module.teal_module initializing the module: { deparse1(modules$label) }.")- |
- ||
240 | -107x | -
- moduleServer(id = id, module = function(input, output, session) {+ #' @rdname teal_modules |
||
241 | -107x | +|||
324 | +
- module_out <- reactiveVal()+ #' @param is_last (`logical(1)`) Whether this is the last item in its parent's children list. |
|||
242 | +325 |
-
+ #' Affects the tree branch character used (L- vs |-) |
||
243 | -107x | +|||
326 | +
- active_datanames <- reactive({+ #' @param parent_prefix (`character(1)`) The prefix inherited from parent nodes, |
|||
244 | -84x | +|||
327 | +
- .resolve_module_datanames(data = data_rv(), modules = modules)+ #' used to maintain the tree structure in nested levels |
|||
245 | +328 |
- })+ #' @param is_root (`logical(1)`) Whether this is the root node of the tree. Only used in |
||
246 | -107x | +|||
329 | +
- if (is.null(datasets)) {+ #' format.teal_modules(). Determines whether to show "TEAL ROOT" header |
|||
247 | -20x | +|||
330 | +
- datasets <- eventReactive(data_rv(), {+ #' @param what (`character`) Specifies which metadata to display. |
|||
248 | -16x | +|||
331 | +
- req(inherits(data_rv(), "teal_data"))+ #' Possible values: "datasets", "properties", "ui_args", "server_args", "transformers" |
|||
249 | -16x | +|||
332 | +
- logger::log_debug("srv_teal_module@1 initializing module-specific FilteredData")+ #' @examples |
|||
250 | -16x | +|||
333 | +
- teal_data_to_filtered_data(data_rv(), datanames = active_datanames())+ #' mod <- module( |
|||
251 | +334 |
- })+ #' label = "My Custom Module", |
||
252 | +335 |
- }+ #' server = function(id, data, ...) {}, |
||
253 | +336 |
-
+ #' ui = function(id, ...) {}, |
||
254 | +337 |
- # manage module filters on the module level+ #' datanames = c("ADSL", "ADTTE"), |
||
255 | +338 |
- # important:+ #' transformers = list(), |
||
256 | +339 |
- # filter_manager_module_srv needs to be called before filter_panel_srv+ #' ui_args = list(a = 1, b = "b"), |
||
257 | +340 |
- # Because available_teal_slices is used in FilteredData$srv_available_slices (via srv_filter_panel)+ #' server_args = list(x = 5, y = list(p = 1)) |
||
258 | +341 |
- # and if it is not set, then it won't be available in the srv_filter_panel+ #' ) |
||
259 | -107x | +|||
342 | +
- srv_module_filter_manager(modules$label, module_fd = datasets, slices_global = slices_global)+ #' cat(format(mod)) |
|||
260 | +343 |
-
+ #' @export |
||
261 | -107x | +|||
344 | +
- call_once_when(is_active(), {+ format.teal_module <- function( |
|||
262 | -81x | +|||
345 | +
- filtered_teal_data <- srv_filter_data(+ x, indent = 0, is_last = FALSE, parent_prefix = "", |
|||
263 | -81x | +|||
346 | +
- "filter_panel",+ what = c("datasets", "properties", "ui_args", "server_args", "transformers"), ...) { |
|||
264 | -81x | +347 | +3x |
- datasets = datasets,+ empty_text <- "" |
265 | -81x | +348 | +3x |
- active_datanames = active_datanames,+ branch <- if (is_last) "L-" else "|-" |
266 | -81x | +349 | +3x |
- data_rv = data_rv,+ current_prefix <- paste0(parent_prefix, branch, " ") |
267 | -81x | +350 | +3x |
- is_active = is_active+ content_prefix <- paste0(parent_prefix, if (is_last) " " else "| ") |
268 | +351 |
- )- |
- ||
269 | -81x | -
- is_transformer_failed <- reactiveValues()- |
- ||
270 | -81x | -
- transformed_teal_data <- srv_transform_data(+ |
||
271 | -81x | +352 | +3x |
- "data_transform",+ format_list <- function(lst, empty = empty_text, label_width = 0) { |
272 | -81x | +353 | +6x |
- data = filtered_teal_data,+ if (is.null(lst) || length(lst) == 0) { |
273 | -81x | +354 | +6x |
- transformers = modules$transformers,+ empty |
274 | -81x | +|||
355 | +
- modules = modules,+ } else { |
|||
275 | -81x | +|||
356 | +! |
- is_transformer_failed = is_transformer_failed+ colon_space <- paste(rep(" ", label_width), collapse = "") |
||
276 | +357 |
- )- |
- ||
277 | -81x | -
- any_transformer_failed <- reactive({+ |
||
278 | -81x | +|||
358 | +! |
- any(unlist(reactiveValuesToList(is_transformer_failed)))+ first_item <- sprintf("%s (%s)", names(lst)[1], crayon::silver(class(lst[[1]])[1])) |
||
279 | -+ | |||
359 | +! |
- })+ rest_items <- if (length(lst) > 1) { |
||
280 | -+ | |||
360 | +! |
-
+ paste( |
||
281 | -81x | +|||
361 | +! |
- observeEvent(any_transformer_failed(), {+ vapply( |
||
282 | -81x | +|||
362 | +! |
- if (isTRUE(any_transformer_failed())) {+ names(lst)[-1], |
||
283 | -6x | +|||
363 | +! |
- shinyjs::hide("teal_module_ui")+ function(name) { |
||
284 | -6x | +|||
364 | +! |
- shinyjs::hide("validate_datanames")+ sprintf( |
||
285 | -6x | +|||
365 | +! |
- shinyjs::show("transformer_failure_info")+ "%s%s (%s)", |
||
286 | -+ | |||
366 | +! |
- } else {+ paste0(content_prefix, "| ", colon_space), |
||
287 | -75x | +|||
367 | +! |
- shinyjs::show("teal_module_ui")+ name, |
||
288 | -75x | +|||
368 | +! |
- shinyjs::show("validate_datanames")+ crayon::silver(class(lst[[name]])[1]) |
||
289 | -75x | +|||
369 | +
- shinyjs::hide("transformer_failure_info")+ ) |
|||
290 | +370 |
- }+ }, |
||
291 | -+ | |||
371 | +! |
- })+ character(1) |
||
292 | +372 |
-
+ ), |
||
293 | -81x | +|||
373 | +! |
- module_teal_data <- reactive({+ collapse = "\n" |
||
294 | -89x | +|||
374 | +
- req(inherits(transformed_teal_data(), "teal_data"))+ ) |
|||
295 | -83x | +|||
375 | +
- all_teal_data <- transformed_teal_data()+ } |
|||
296 | -83x | +|||
376 | +! |
- module_datanames <- .resolve_module_datanames(data = all_teal_data, modules = modules)+ if (length(lst) > 1) paste0(first_item, "\n", rest_items) else first_item |
||
297 | -83x | +|||
377 | +
- .subset_teal_data(all_teal_data, module_datanames)+ } |
|||
298 | +378 |
- })+ } |
||
299 | +379 | |||
300 | -81x | +380 | +3x |
- srv_validate_reactive_teal_data(+ bookmarkable <- isTRUE(attr(x, "teal_bookmarkable")) |
301 | -81x | +381 | +3x |
- "validate_datanames",+ reportable <- "reporter" %in% names(formals(x$server)) |
302 | -81x | +|||
382 | +
- data = module_teal_data,+ |
|||
303 | -81x | +383 | +3x |
- modules = modules+ transformers <- if (length(x$transformers) > 0) { |
304 | -+ | |||
384 | +! |
- )+ paste(sapply(x$transformers, function(t) attr(t, "label")), collapse = ", ") |
||
305 | +385 |
-
+ } else { |
||
306 | -81x | +386 | +3x |
- summary_table <- srv_data_summary("data_summary", module_teal_data)+ empty_text |
307 | +387 |
-
+ } |
||
308 | +388 |
- # Call modules.+ |
||
309 | -81x | +389 | +3x |
- if (!inherits(modules, "teal_module_previewer")) {+ output <- pasten(current_prefix, crayon::bgWhite(x$label)) |
310 | -81x | +|||
390 | +
- obs_module <- call_once_when(+ |
|||
311 | -81x | +391 | +3x |
- !is.null(module_teal_data()),+ if ("datasets" %in% what) { |
312 | -81x | +392 | +3x |
- ignoreNULL = TRUE,+ output <- paste0( |
313 | -81x | +393 | +3x |
- handlerExpr = {+ output, |
314 | -75x | +394 | +3x |
- module_out(.call_teal_module(modules, datasets, module_teal_data, reporter))+ content_prefix, "|- ", crayon::yellow("Datasets : "), paste(x$datanames, collapse = ", "), "\n" |
315 | +395 |
- }+ ) |
||
316 | +396 |
- )+ } |
||
317 | -+ | |||
397 | +3x |
- } else {+ if ("properties" %in% what) { |
||
318 | -+ | |||
398 | +3x |
- # Report previewer must be initiated on app start for report cards to be included in bookmarks.+ output <- paste0( |
||
319 | -+ | |||
399 | +3x |
- # When previewer is delayed, cards are bookmarked only if previewer has been initiated (visited).+ output, |
||
320 | -! | +|||
400 | +3x |
- module_out(.call_teal_module(modules, datasets, module_teal_data, reporter))+ content_prefix, "|- ", crayon::blue("Properties:"), "\n", |
||
321 | -+ | |||
401 | +3x |
- }+ content_prefix, "| |- ", crayon::cyan("Bookmarkable : "), bookmarkable, "\n", |
||
322 | -+ | |||
402 | +3x |
-
+ content_prefix, "| L- ", crayon::cyan("Reportable : "), reportable, "\n" |
||
323 | +403 |
- # todo: (feature request) add a ReporterCard to the reporter as an output from the teal_module+ ) |
||
324 | +404 |
- # how to determine if module returns a ReporterCard so that reportPreviewer is needed?+ } |
||
325 | -+ | |||
405 | +3x |
- # Should we insertUI of the ReportPreviewer then?+ if ("ui_args" %in% what) { |
||
326 | -+ | |||
406 | +3x |
- # What about attr(module, "reportable") - similar to attr(module, "bookmarkable")+ ui_args_formatted <- format_list(x$ui_args, label_width = 19) |
||
327 | -81x | +407 | +3x |
- if ("report" %in% names(module_out)) {+ output <- paste0( |
328 | -+ | |||
408 | +3x |
- # (reactively) add card to the reporter+ output, |
||
329 | -+ | |||
409 | +3x |
- }+ content_prefix, "|- ", crayon::green("UI Arguments : "), ui_args_formatted, "\n" |
||
330 | +410 |
- })+ ) |
||
331 | +411 |
-
+ } |
||
332 | -107x | +412 | +3x |
- module_out+ if ("server_args" %in% what) { |
333 | -+ | |||
413 | +3x |
- })+ server_args_formatted <- format_list(x$server_args, label_width = 19) |
||
334 | -+ | |||
414 | +3x |
- }+ output <- paste0( |
||
335 | -+ | |||
415 | +3x |
-
+ output, |
||
336 | -+ | |||
416 | +3x |
- # This function calls a module server function.+ content_prefix, "|- ", crayon::green("Server Arguments : "), server_args_formatted, "\n" |
||
337 | +417 |
- .call_teal_module <- function(modules, datasets, filtered_teal_data, reporter) {+ ) |
||
338 | +418 |
- # collect arguments to run teal_module+ } |
||
339 | -75x | +419 | +3x |
- args <- c(list(id = "module"), modules$server_args)+ if ("transformers" %in% what) { |
340 | -75x | +420 | +3x |
- if (is_arg_used(modules$server, "reporter")) {+ output <- paste0( |
341 | -1x | +421 | +3x |
- args <- c(args, list(reporter = reporter))+ output,+ |
+
422 | +3x | +
+ content_prefix, "L- ", crayon::magenta("Transformers : "), transformers, "\n" |
||
342 | +423 | ++ |
+ )+ |
+ |
424 |
} |
|||
343 | +425 | |||
344 | -75x | +426 | +3x |
- if (is_arg_used(modules$server, "datasets")) {+ output |
345 | -1x | +|||
427 | +
- args <- c(args, datasets = datasets())+ } |
|||
346 | -1x | +|||
428 | +
- warning("datasets argument is not reactive and therefore it won't be updated when data is refreshed.")+ |
|||
347 | +429 |
- }+ #' @rdname teal_modules |
||
348 | +430 |
-
+ #' @examples |
||
349 | -75x | +|||
431 | +
- if (is_arg_used(modules$server, "data")) {+ #' custom_module <- function( |
|||
350 | -71x | +|||
432 | +
- args <- c(args, data = list(filtered_teal_data))+ #' label = "label", ui_args = NULL, server_args = NULL, |
|||
351 | +433 |
- }+ #' datanames = "all", transformers = list(), bk = FALSE) { |
||
352 | +434 |
-
+ #' ans <- module( |
||
353 | -75x | +|||
435 | +
- if (is_arg_used(modules$server, "filter_panel_api")) {+ #' label, |
|||
354 | -1x | +|||
436 | +
- args <- c(args, filter_panel_api = teal.slice::FilterPanelAPI$new(datasets()))+ #' server = function(id, data, ...) {}, |
|||
355 | +437 |
- }+ #' ui = function(id, ...) { |
||
356 | +438 |
-
+ #' }, |
||
357 | -75x | +|||
439 | +
- if (is_arg_used(modules$server, "id")) {+ #' datanames = datanames, |
|||
358 | -75x | +|||
440 | +
- do.call(modules$server, args)+ #' transformers = transformers, |
|||
359 | +441 |
- } else {+ #' ui_args = ui_args, |
||
360 | -! | +|||
442 | +
- do.call(callModule, c(args, list(module = modules$server)))+ #' server_args = server_args |
|||
361 | +443 |
- }+ #' ) |
||
362 | +444 |
- }+ #' attr(ans, "teal_bookmarkable") <- bk |
||
363 | +445 |
-
+ #' ans |
||
364 | +446 |
- .resolve_module_datanames <- function(data, modules) {+ #' } |
||
365 | -167x | +|||
447 | +
- stopifnot("data_rv must be teal_data object." = inherits(data, "teal_data"))+ #' |
|||
366 | -167x | +|||
448 | +
- if (is.null(modules$datanames) || identical(modules$datanames, "all")) {+ #' dummy_transformer <- teal_transform_module( |
|||
367 | -135x | +|||
449 | +
- .topologically_sort_datanames(ls(teal.code::get_env(data)), teal.data::join_keys(data))+ #' label = "Dummy Transform", |
|||
368 | +450 |
- } else {+ #' ui = function(id) div("(does nothing)"), |
||
369 | -32x | +|||
451 | +
- intersect(+ #' server = function(id, data) { |
|||
370 | -32x | +|||
452 | +
- .include_parent_datanames(modules$datanames, teal.data::join_keys(data)),+ #' moduleServer(id, function(input, output, session) data) |
|||
371 | -32x | +|||
453 | +
- ls(teal.code::get_env(data))+ #' } |
|||
372 | +454 |
- )+ #' ) |
||
373 | +455 |
- }+ #' |
||
374 | +456 |
- }+ #' plot_transformer <- teal_transform_module( |
||
375 | +457 |
-
+ #' label = "Plot Settings", |
||
376 | +458 |
- #' Calls expression when condition is met+ #' ui = function(id) div("(does nothing)"), |
||
377 | +459 |
- #'+ #' server = function(id, data) { |
||
378 | +460 |
- #' Function postpones `handlerExpr` to the moment when `eventExpr` (condition) returns `TRUE`,+ #' moduleServer(id, function(input, output, session) data) |
||
379 | +461 |
- #' otherwise nothing happens.+ #' } |
||
380 | +462 |
- #' @param eventExpr A (quoted or unquoted) logical expression that represents the event;+ #' ) |
||
381 | +463 |
- #' this can be a simple reactive value like input$click, a call to a reactive expression+ #' |
||
382 | +464 |
- #' like dataset(), or even a complex expression inside curly braces.+ #' complete_modules <- modules( |
||
383 | +465 |
- #' @param ... additional arguments passed to `observeEvent` with the exception of `eventExpr` that is not allowed.+ #' custom_module( |
||
384 | +466 |
- #' @inheritParams shiny::observeEvent+ #' label = "Data Overview", |
||
385 | +467 |
- #'+ #' datanames = c("ADSL", "ADAE", "ADVS"), |
||
386 | +468 |
- #' @return An observer.+ #' ui_args = list( |
||
387 | +469 |
- #'+ #' view_type = "table", |
||
388 | +470 |
- #' @keywords internal+ #' page_size = 10, |
||
389 | +471 |
- call_once_when <- function(eventExpr, # nolint: object_name.+ #' filters = c("ARM", "SEX", "RACE") |
||
390 | +472 |
- handlerExpr, # nolint: object_name.+ #' ), |
||
391 | +473 |
- event.env = parent.frame(), # nolint: object_name.+ #' server_args = list( |
||
392 | +474 |
- handler.env = parent.frame(), # nolint: object_name.+ #' cache = TRUE, |
||
393 | +475 |
- ...) {+ #' debounce = 1000 |
||
394 | -188x | +|||
476 | +
- event_quo <- rlang::new_quosure(substitute(eventExpr), env = event.env)+ #' ), |
|||
395 | -188x | +|||
477 | ++ |
+ #' transformers = list(dummy_transformer),+ |
+ ||
478 | ++ |
+ #' bk = TRUE+ |
+ ||
479 | +
- handler_quo <- rlang::new_quosure(substitute(handlerExpr), env = handler.env)+ #' ), |
|||
396 | +480 |
-
+ #' modules( |
||
397 | +481 |
- # When `condExpr` is TRUE, then `handlerExpr` is evaluated once.+ #' label = "Nested 1", |
||
398 | -188x | +|||
482 | +
- activator <- reactive({+ #' custom_module( |
|||
399 | -188x | +|||
483 | +
- if (isTRUE(rlang::eval_tidy(event_quo))) {+ #' label = "Interactive Plots", |
|||
400 | -156x | +|||
484 | +
- TRUE+ #' datanames = c("ADSL", "ADVS"), |
|||
401 | +485 |
- }+ #' ui_args = list( |
||
402 | +486 |
- })+ #' plot_type = c("scatter", "box", "line"), |
||
403 | +487 |
-
+ #' height = 600, |
||
404 | -188x | +|||
488 | +
- observeEvent(+ #' width = 800, |
|||
405 | -188x | +|||
489 | +
- eventExpr = activator(),+ #' color_scheme = "viridis" |
|||
406 | -188x | +|||
490 | +
- once = TRUE,+ #' ), |
|||
407 | -188x | +|||
491 | +
- handlerExpr = rlang::eval_tidy(handler_quo),+ #' server_args = list( |
|||
408 | +492 |
- ...+ #' render_type = "svg", |
||
409 | +493 |
- )+ #' cache_plots = TRUE |
||
410 | +494 |
- }+ #' ), |
1 | +495 |
- #' Execute and validate `teal_data_module`+ #' transformers = list(dummy_transformer, plot_transformer), |
||
2 | +496 |
- #'+ #' bk = TRUE |
||
3 | +497 |
- #' This is a low level module to handle `teal_data_module` execution and validation.+ #' ), |
||
4 | +498 |
- #' [teal_transform_module()] inherits from [teal_data_module()] so it is handled by this module too.+ #' modules( |
||
5 | +499 |
- #' [srv_teal()] accepts various `data` objects and eventually they are all transformed to `reactive`+ #' label = "Nested 2", |
||
6 | +500 |
- #' [teal_data()] which is a standard data class in whole `teal` framework.+ #' custom_module( |
||
7 | +501 |
- #'+ #' label = "Summary Statistics", |
||
8 | +502 |
- #' @section data validation:+ #' datanames = "ADSL", |
||
9 | +503 |
- #'+ #' ui_args = list( |
||
10 | +504 |
- #' Executed [teal_data_module()] is validated and output is validated for consistency.+ #' stats = c("mean", "median", "sd", "range"), |
||
11 | +505 |
- #' Output `data` is invalid if:+ #' grouping = c("ARM", "SEX") |
||
12 | +506 |
- #' 1. [teal_data_module()] is invalid if server doesn't return `reactive`. **Immediately crashes an app!**+ #' ) |
||
13 | +507 |
- #' 2. `reactive` throws a `shiny.error` - happens when module creating [teal_data()] fails.+ #' ), |
||
14 | +508 |
- #' 3. `reactive` returns `qenv.error` - happens when [teal_data()] evaluates a failing code.+ #' modules( |
||
15 | +509 |
- #' 4. `reactive` object doesn't return [teal_data()].+ #' label = "Labeled nested modules", |
||
16 | +510 |
- #' 5. [teal_data()] object lacks any `datanames` specified in the `modules` argument.+ #' custom_module( |
||
17 | +511 |
- #'+ #' label = "Subgroup Analysis", |
||
18 | +512 |
- #' `teal` (observers in `srv_teal`) always waits to render an app until `reactive` `teal_data` is+ #' datanames = c("ADSL", "ADAE"), |
||
19 | +513 |
- #' returned. If error 2-4 occurs, relevant error message is displayed to the app user. Once the issue is+ #' ui_args = list( |
||
20 | +514 |
- #' resolved, the app will continue to run. `teal` guarantees that errors in data don't crash the app+ #' subgroups = c("AGE", "SEX", "RACE"), |
||
21 | +515 |
- #' (except error 1).+ #' analysis_type = "stratified" |
||
22 | +516 |
- #'+ #' ), |
||
23 | +517 |
- #' @param id (`character(1)`) Module id+ #' bk = TRUE |
||
24 | +518 |
- #' @param data (`reactive teal_data`)+ #' ) |
||
25 | +519 |
- #' @param data_module (`teal_data_module`)+ #' ), |
||
26 | +520 |
- #' @param modules (`teal_modules` or `teal_module`) For `datanames` validation purpose+ #' modules(custom_module(label = "Subgroup Analysis in non-labled modules")) |
||
27 | +521 |
- #' @param validate_shiny_silent_error (`logical`) If `TRUE`, then `shiny.silent.error` is validated and+ #' ) |
||
28 | +522 |
- #' @param is_transformer_failed (`reactiveValues`) contains `logical` flags named after each transformer.+ #' ), |
||
29 | +523 |
- #' Help to determine if any previous transformer failed, so that following transformers can be disabled+ #' custom_module("Non-nested module") |
||
30 | +524 |
- #' and display a generic failure message.+ #' ) |
||
31 | +525 |
#' |
||
32 | +526 |
- #' @return `reactive` `teal_data`+ #' cat(format(complete_modules)) |
||
33 | +527 |
- #'+ #' cat(format(complete_modules, what = c("ui_args", "server_args", "transformers"))) |
||
34 | +528 |
- #' @rdname module_teal_data+ #' @export |
||
35 | +529 |
- #' @name module_teal_data+ format.teal_modules <- function(x, indent = 0, is_root = TRUE, is_last = FALSE, parent_prefix = "", ...) { |
||
36 | -+ | |||
530 | +1x |
- #' @keywords internal+ if (is_root) { |
||
37 | -+ | |||
531 | +1x |
- NULL+ header <- pasten(crayon::bold("TEAL ROOT")) |
||
38 | -+ | |||
532 | +1x |
-
+ new_parent_prefix <- " " #' Initial indent for root level |
||
39 | +533 |
- #' @rdname module_teal_data+ } else { |
||
40 | -+ | |||
534 | +! |
- ui_teal_data <- function(id, data_module = function(id) NULL) {+ if (!is.null(x$label)) { |
||
41 | +535 | ! |
- checkmate::assert_string(id)+ branch <- if (is_last) "L-" else "|-" |
|
42 | +536 | ! |
- checkmate::assert_function(data_module, args = "id")+ header <- pasten(parent_prefix, branch, " ", crayon::bold(x$label)) |
|
43 | +537 | ! |
- ns <- NS(id)+ new_parent_prefix <- paste0(parent_prefix, if (is_last) " " else "| ") |
|
44 | +538 |
-
+ } else { |
||
45 | +539 | ! |
- shiny::tagList(+ header <- "" |
|
46 | +540 | ! |
- tags$div(id = ns("wrapper"), data_module(id = ns("data"))),+ new_parent_prefix <- parent_prefix |
|
47 | -! | +|||
541 | +
- ui_validate_reactive_teal_data(ns("validate"))+ } |
|||
48 | +542 |
- )+ } |
||
49 | +543 |
- }+ + |
+ ||
544 | +1x | +
+ if (length(x$children) > 0) {+ |
+ ||
545 | +1x | +
+ children_output <- character(0)+ |
+ ||
546 | +1x | +
+ n_children <- length(x$children) |
||
50 | +547 | |||
51 | -+ | |||
548 | +1x |
- #' @rdname module_teal_data+ for (i in seq_along(x$children)) {+ |
+ ||
549 | +3x | +
+ child <- x$children[[i]]+ |
+ ||
550 | +3x | +
+ is_last_child <- (i == n_children) |
||
52 | +551 |
- srv_teal_data <- function(id,+ + |
+ ||
552 | +3x | +
+ if (inherits(child, "teal_modules")) {+ |
+ ||
553 | +! | +
+ children_output <- c(+ |
+ ||
554 | +! | +
+ children_output,+ |
+ ||
555 | +! | +
+ format(child,+ |
+ ||
556 | +! | +
+ indent = indent,+ |
+ ||
557 | +! | +
+ is_root = FALSE,+ |
+ ||
558 | +! | +
+ is_last = is_last_child,+ |
+ ||
559 | +! | +
+ parent_prefix = new_parent_prefix, |
||
53 | +560 |
- data_module = function(id) NULL,+ ... |
||
54 | +561 |
- modules = NULL,+ ) |
||
55 | +562 |
- validate_shiny_silent_error = TRUE,+ ) |
||
56 | +563 |
- is_transformer_failed = reactiveValues()) {+ } else { |
||
57 | -20x | +564 | +3x |
- checkmate::assert_string(id)+ children_output <- c( |
58 | -20x | +565 | +3x |
- checkmate::assert_function(data_module, args = "id")+ children_output, |
59 | -20x | +566 | +3x |
- checkmate::assert_multi_class(modules, c("teal_modules", "teal_module"), null.ok = TRUE)+ format(child, |
60 | -20x | +567 | +3x |
- checkmate::assert_class(is_transformer_failed, "reactivevalues")+ indent = indent, |
61 | -+ | |||
568 | +3x |
-
+ is_last = is_last_child, |
||
62 | -20x | +569 | +3x |
- moduleServer(id, function(input, output, session) {+ parent_prefix = new_parent_prefix, |
63 | -20x | +|||
570 | +
- logger::log_debug("srv_teal_data initializing.")+ ... |
|||
64 | -20x | +|||
571 | +
- is_transformer_failed[[id]] <- FALSE+ ) |
|||
65 | -20x | +|||
572 | +
- data_out <- data_module(id = "data")+ ) |
|||
66 | -20x | +|||
573 | +
- data_handled <- reactive(tryCatch(data_out(), error = function(e) e))+ } |
|||
67 | -20x | +|||
574 | +
- observeEvent(data_handled(), {+ } |
|||
68 | -22x | +|||
575 | +
- if (!inherits(data_handled(), "teal_data")) {+ |
|||
69 | -6x | +576 | +1x |
- is_transformer_failed[[id]] <- TRUE+ paste0(header, paste(children_output, collapse = "")) |
70 | +577 |
- } else {+ } else { |
||
71 | -16x | +|||
578 | +! |
- is_transformer_failed[[id]] <- FALSE+ header |
||
72 | +579 |
- }+ } |
||
73 | +580 |
- })+ } |
||
74 | +581 | |||
75 | -20x | +|||
582 | +
- is_previous_failed <- reactive({+ #' @rdname teal_modules |
|||
76 | -20x | +|||
583 | +
- idx_this <- which(names(is_transformer_failed) == id)+ #' @export |
|||
77 | -20x | +|||
584 | +
- is_transformer_failed_list <- reactiveValuesToList(is_transformer_failed)+ print.teal_module <- function(x, ...) {+ |
+ |||
585 | +! | +
+ cat(format(x, ...))+ |
+ ||
586 | +! | +
+ invisible(x) |
||
78 | -20x | +|||
587 | +
- idx_failures <- which(unlist(is_transformer_failed_list))+ } |
|||
79 | -20x | +|||
588 | +
- any(idx_failures < idx_this)+ |
|||
80 | +589 |
- })+ #' @rdname teal_modules |
||
81 | +590 |
-
+ #' @export |
||
82 | -20x | +|||
591 | +
- observeEvent(is_previous_failed(), {+ print.teal_modules <- function(x, ...) { |
|||
83 | -20x | +|||
592 | +! |
- if (is_previous_failed()) {+ cat(format(x, ...)) |
||
84 | +593 | ! |
- shinyjs::disable("wrapper")+ invisible(x) |
|
85 | +594 |
- } else {+ } |
||
86 | -20x | +|||
595 | +
- shinyjs::enable("wrapper")+ |
|||
87 | +596 |
- }+ #' @param modules (`teal_module` or `teal_modules`) |
||
88 | +597 |
- })+ #' @rdname teal_modules |
||
89 | +598 |
-
+ #' @examples |
||
90 | -20x | +|||
599 | +
- srv_validate_reactive_teal_data(+ #' # change the module's datanames |
|||
91 | -20x | +|||
600 | +
- "validate",+ #' set_datanames(module(datanames = "all"), "a") |
|||
92 | -20x | +|||
601 | +
- data = data_handled,+ #' |
|||
93 | -20x | +|||
602 | +
- modules = modules,+ #' # change modules' datanames |
|||
94 | -20x | +|||
603 | +
- validate_shiny_silent_error = validate_shiny_silent_error,+ #' set_datanames( |
|||
95 | -20x | +|||
604 | +
- hide_validation_error = is_previous_failed+ #' modules( |
|||
96 | +605 |
- )+ #' module(datanames = "all"), |
||
97 | +606 |
- })+ #' module(datanames = "a") |
||
98 | +607 |
- }+ #' ), |
||
99 | +608 |
-
+ #' "b" |
||
100 | +609 |
- #' @rdname module_teal_data+ #' ) |
||
101 | +610 |
- ui_validate_reactive_teal_data <- function(id) {+ #' @export |
||
102 | -82x | +|||
611 | +
- ns <- NS(id)+ set_datanames <- function(modules, datanames) { |
|||
103 | -82x | +|||
612 | +! |
- tagList(+ checkmate::assert_multi_class(modules, c("teal_modules", "teal_module")) |
||
104 | -82x | +|||
613 | +! |
- div(+ if (inherits(modules, "teal_modules")) { |
||
105 | -82x | +|||
614 | +! |
- id = ns("validate_messages"),+ modules$children <- lapply(modules$children, set_datanames, datanames) |
||
106 | -82x | +|||
615 | +
- class = "teal_validated",+ } else { |
|||
107 | -82x | +|||
616 | +! |
- ui_validate_error(ns("silent_error")),+ if (identical(modules$datanames, "all")) { |
||
108 | -82x | +|||
617 | +! |
- ui_check_class_teal_data(ns("class_teal_data")),+ modules$datanames <- datanames |
||
109 | -82x | +|||
618 | +
- ui_check_shiny_warnings(ns("shiny_warnings"))+ } else { |
|||
110 | -+ | |||
619 | +! |
- ),+ warning( |
||
111 | -82x | +|||
620 | +! |
- div(+ "Not possible to modify datanames of the module ", modules$label, |
||
112 | -82x | +|||
621 | +! |
- class = "teal_validated",+ ". set_datanames() can only change datanames if it was set to \"all\".", |
||
113 | -82x | +|||
622 | +! |
- uiOutput(ns("previous_failed"))+ call. = FALSE |
||
114 | +623 |
- )+ ) |
||
115 | +624 |
- )+ } |
||
116 | +625 |
- }+ } |
||
117 | -+ | |||
626 | +! |
-
+ modules |
||
118 | +627 |
- #' @rdname module_teal_data+ } |
||
119 | +628 |
- srv_validate_reactive_teal_data <- function(id, # nolint: object_length+ |
||
120 | +629 |
- data,+ # utilities ---- |
||
121 | +630 |
- modules = NULL,+ ## subset or modify modules ---- |
||
122 | +631 |
- validate_shiny_silent_error = FALSE,+ |
||
123 | +632 |
- hide_validation_error = reactive(FALSE)) {+ #' Append a `teal_module` to `children` of a `teal_modules` object |
||
124 | -183x | +|||
633 | +
- checkmate::assert_string(id)+ #' @keywords internal |
|||
125 | -183x | +|||
634 | +
- checkmate::assert_multi_class(modules, c("teal_modules", "teal_module"), null.ok = TRUE)+ #' @param modules (`teal_modules`) |
|||
126 | -183x | +|||
635 | +
- checkmate::assert_flag(validate_shiny_silent_error)+ #' @param module (`teal_module`) object to be appended onto the children of `modules` |
|||
127 | +636 |
-
+ #' @return A `teal_modules` object with `module` appended. |
||
128 | -183x | +|||
637 | +
- moduleServer(id, function(input, output, session) {+ append_module <- function(modules, module) { |
|||
129 | -+ | |||
638 | +8x |
- # there is an empty reactive cycle on `init` and `data_rv` has `shiny.silent.error` class+ checkmate::assert_class(modules, "teal_modules") |
||
130 | -183x | +639 | +6x |
- srv_validate_error("silent_error", data, validate_shiny_silent_error)+ checkmate::assert_class(module, "teal_module") |
131 | -183x | +640 | +4x |
- srv_check_class_teal_data("class_teal_data", data)+ modules$children <- c(modules$children, list(module)) |
132 | -183x | +641 | +4x |
- srv_check_shiny_warnings("shiny_warnings", data, modules)+ labels <- vapply(modules$children, function(submodule) submodule$label, character(1)) |
133 | -183x | +642 | +4x |
- output$previous_failed <- renderUI({+ names(modules$children) <- get_unique_labels(labels) |
134 | -173x | +643 | +4x |
- if (hide_validation_error()) {+ modules |
135 | -! | +|||
644 | +
- shinyjs::hide("validate_messages")+ } |
|||
136 | -! | +|||
645 | +
- tags$div("One of previous transformers failed. Please fix and continue.", class = "teal-output-warning")+ |
|||
137 | +646 |
- } else {+ #' Extract/Remove module(s) of specific class |
||
138 | -173x | +|||
647 | +
- shinyjs::show("validate_messages")+ #' |
|||
139 | -173x | +|||
648 | +
- NULL+ #' Given a `teal_module` or a `teal_modules`, return the elements of the structure according to `class`. |
|||
140 | +649 |
- }+ #' |
||
141 | +650 |
- })+ #' @param modules (`teal_modules`) |
||
142 | +651 |
-
+ #' @param class The class name of `teal_module` to be extracted or dropped. |
||
143 | -183x | +|||
652 | +
- .trigger_on_success(data)+ #' @keywords internal |
|||
144 | +653 |
- })+ #' @return |
||
145 | +654 |
- }+ #' - For `extract_module`, a `teal_module` of class `class` or `teal_modules` containing modules of class `class`. |
||
146 | +655 |
-
+ #' - For `drop_module`, the opposite, which is all `teal_modules` of class other than `class`. |
||
147 | +656 |
- #' @keywords internal+ #' @rdname module_management |
||
148 | +657 |
- ui_validate_error <- function(id) {+ extract_module <- function(modules, class) { |
||
149 | -82x | +658 | +24x |
- ns <- NS(id)+ if (inherits(modules, class)) {+ |
+
659 | +! | +
+ modules |
||
150 | -82x | +660 | +24x |
- uiOutput(ns("message"))+ } 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)) |
||
151 | +664 | ++ |
+ }+ |
+ |
665 |
} |
|||
152 | +666 | |||
153 | +667 |
#' @keywords internal |
||
154 | +668 |
- srv_validate_error <- function(id, data, validate_shiny_silent_error) {+ #' @return `teal_modules` |
||
155 | -183x | +|||
669 | ++ |
+ #' @rdname module_management+ |
+ ||
670 | ++ |
+ drop_module <- function(modules, class) {+ |
+ ||
671 | +! | +
+ if (inherits(modules, class)) {+ |
+ ||
672 | +! |
- checkmate::assert_string(id)+ NULL |
||
156 | -183x | +|||
673 | +! |
- checkmate::assert_flag(validate_shiny_silent_error)+ } else if (inherits(modules, "teal_module")) { |
||
157 | -183x | +|||
674 | +! |
- moduleServer(id, function(input, output, session) {+ modules |
||
158 | -183x | +|||
675 | +! |
- output$message <- renderUI({+ } else if (inherits(modules, "teal_modules")) { |
||
159 | -186x | +|||
676 | +! |
- is_shiny_silent_error <- inherits(data(), "shiny.silent.error") && identical(data()$message, "")+ do.call( |
||
160 | -180x | +|||
677 | +! |
- if (inherits(data(), "qenv.error")) {+ "modules", |
||
161 | -2x | +|||
678 | +! |
- validate(+ c(Filter(function(x) length(x) > 0L, lapply(modules$children, drop_module, class)), label = modules$label) |
||
162 | -2x | +|||
679 | +
- need(+ ) |
|||
163 | -2x | +|||
680 | +
- FALSE,+ } |
|||
164 | -2x | +|||
681 | +
- paste(+ } |
|||
165 | -2x | +|||
682 | +
- "Error when executing the `data` module:",+ |
|||
166 | -2x | +|||
683 | +
- strip_style(paste(data()$message, collapse = "\n")),+ ## read modules ---- |
|||
167 | -2x | +|||
684 | +
- "\nCheck your inputs or contact app developer if error persists.",+ |
|||
168 | -2x | +|||
685 | +
- collapse = "\n"+ #' Does the object make use of the `arg` |
|||
169 | +686 |
- )+ #' |
||
170 | +687 |
- )+ #' @param modules (`teal_module` or `teal_modules`) object |
||
171 | +688 |
- )+ #' @param arg (`character(1)`) names of the arguments to be checked against formals of `teal` modules. |
||
172 | -178x | +|||
689 | +
- } else if (inherits(data(), "error")) {+ #' @return `logical` whether the object makes use of `arg`. |
|||
173 | -7x | +|||
690 | +
- if (is_shiny_silent_error && !validate_shiny_silent_error) {+ #' @rdname is_arg_used |
|||
174 | -1x | +|||
691 | +
- return(NULL)+ #' @keywords internal |
|||
175 | +692 |
- }+ is_arg_used <- function(modules, arg) { |
||
176 | -6x | +693 | +486x |
- validate(+ checkmate::assert_string(arg) |
177 | -6x | +694 | +483x |
- need(+ if (inherits(modules, "teal_modules")) { |
178 | -6x | +695 | +18x |
- FALSE,+ any(unlist(lapply(modules$children, is_arg_used, arg))) |
179 | -6x | +696 | +465x |
- sprintf(+ } else if (inherits(modules, "teal_module")) { |
180 | -6x | +697 | +30x |
- "Shiny error when executing the `data` module.\n%s\n%s",+ is_arg_used(modules$server, arg) || is_arg_used(modules$ui, arg) |
181 | -6x | +698 | +435x |
- data()$message,+ } else if (is.function(modules)) { |
182 | -6x | +699 | +433x |
- "Check your inputs or contact app developer if error persists."+ isTRUE(arg %in% names(formals(modules))) |
183 | +700 |
- )+ } else { |
||
184 | -+ | |||
701 | +2x |
- )+ stop("is_arg_used function not implemented for this object") |
||
185 | +702 |
- )+ } |
||
186 | +703 |
- }+ } |
||
187 | +704 |
- })+ |
||
188 | +705 |
- })+ |
||
189 | +706 |
- }+ #' Get module depth |
||
190 | +707 |
-
+ #' |
||
191 | +708 |
-
+ #' Depth starts at 0, so a single `teal.module` has depth 0. |
||
192 | +709 |
- #' @keywords internal+ #' Nesting it increases overall depth by 1. |
||
193 | +710 |
- ui_check_class_teal_data <- function(id) {+ #' |
||
194 | -82x | +|||
711 | +
- ns <- NS(id)+ #' @inheritParams init |
|||
195 | -82x | +|||
712 | +
- uiOutput(ns("message"))+ #' @param depth optional integer determining current depth level |
|||
196 | +713 |
- }+ #' |
||
197 | +714 |
-
+ #' @return Depth level for given module. |
||
198 | +715 |
#' @keywords internal |
||
199 | +716 |
- srv_check_class_teal_data <- function(id, data) {- |
- ||
200 | -183x | -
- checkmate::assert_string(id)- |
- ||
201 | -183x | -
- moduleServer(id, function(input, output, session) {- |
- ||
202 | -183x | -
- output$message <- renderUI({+ modules_depth <- function(modules, depth = 0L) { |
||
203 | -186x | +717 | +12x |
- validate(+ checkmate::assert_multi_class(modules, c("teal_module", "teal_modules")) |
204 | -186x | +718 | +12x |
- need(+ checkmate::assert_int(depth, lower = 0) |
205 | -186x | +719 | +11x |
- inherits(data(), c("teal_data", "error")),+ if (inherits(modules, "teal_modules")) { |
206 | -186x | -
- "Did not receive `teal_data` object. Cannot proceed further."- |
- ||
207 | -+ | 720 | +4x |
- )+ max(vapply(modules$children, modules_depth, integer(1), depth = depth + 1L)) |
208 | +721 |
- )+ } else { |
||
209 | -+ | |||
722 | +7x |
- })+ depth |
||
210 | +723 |
- })+ } |
||
211 | +724 |
} |
||
212 | +725 | |||
213 | +726 |
- #' @keywords internal+ #' Retrieve labels from `teal_modules` |
||
214 | +727 |
- ui_check_shiny_warnings <- function(id) {- |
- ||
215 | -82x | -
- ns <- NS(id)+ #' |
||
216 | -82x | +|||
728 | +
- uiOutput(NS(id, "message"))+ #' @param modules (`teal_modules`) |
|||
217 | +729 |
- }+ #' @return A `list` containing the labels of the modules. If the modules are nested, |
||
218 | +730 |
-
+ #' the function returns a nested `list` of labels. |
||
219 | +731 |
#' @keywords internal |
||
220 | +732 |
- srv_check_shiny_warnings <- function(id, data, modules) {- |
- ||
221 | -183x | -
- checkmate::assert_string(id)- |
- ||
222 | -183x | -
- moduleServer(id, function(input, output, session) {+ module_labels <- function(modules) { |
||
223 | -183x | +733 | +189x |
- output$message <- renderUI({+ if (inherits(modules, "teal_modules")) { |
224 | -186x | +734 | +82x |
- if (inherits(data(), "teal_data")) {+ lapply(modules$children, module_labels) |
225 | -169x | +|||
735 | +
- is_modules_ok <- check_modules_datanames_html(+ } else { |
|||
226 | -169x | +736 | +107x |
- modules = modules, datanames = ls(teal.code::get_env(data()))+ modules$label |
227 | +737 |
- )+ } |
||
228 | -169x | +|||
738 | +
- if (!isTRUE(is_modules_ok)) {+ } |
|||
229 | -15x | +|||
739 | +
- tags$div(is_modules_ok, class = "teal-output-warning")+ |
|||
230 | +740 |
- }+ #' Retrieve `teal_bookmarkable` attribute from `teal_modules` |
||
231 | +741 |
- }+ #' |
||
232 | +742 |
- })+ #' @param modules (`teal_modules` or `teal_module`) object |
||
233 | +743 |
- })+ #' @return named list of the same structure as `modules` with `TRUE` or `FALSE` values indicating |
||
234 | +744 |
- }+ #' whether the module is bookmarkable. |
||
235 | +745 |
-
+ #' @keywords internal |
||
236 | +746 |
- .trigger_on_success <- function(data) {+ modules_bookmarkable <- function(modules) { |
||
237 | -183x | +747 | +189x |
- out <- reactiveVal(NULL)+ checkmate::assert_multi_class(modules, c("teal_modules", "teal_module")) |
238 | -183x | +748 | +189x |
- observeEvent(data(), {+ if (inherits(modules, "teal_modules")) { |
239 | -180x | +749 | +82x |
- if (inherits(data(), "teal_data")) {+ setNames( |
240 | -169x | +750 | +82x |
- if (!identical(data(), out())) {+ lapply(modules$children, modules_bookmarkable), |
241 | -169x | +751 | +82x |
- out(data())+ vapply(modules$children, `[[`, "label", FUN.VALUE = character(1)) |
242 | +752 |
- }+ ) |
||
243 | +753 |
- }+ } else { |
||
244 | -+ | |||
754 | +107x |
- })+ attr(modules, "teal_bookmarkable", exact = TRUE) |
||
245 | +755 | - - | -||
246 | -183x | -
- out+ } |
||
247 | +756 |
}@@ -17213,2747 +18272,2657 @@ teal coverage - 59.99% |
1 |
- #' @title `TealReportCard`+ #' Validate that dataset has a minimum number of observations |
||
2 |
- #' @description `r lifecycle::badge("experimental")`+ #' |
||
3 |
- #' Child class of [`ReportCard`] that is used for `teal` specific applications.+ #' `r lifecycle::badge("stable")` |
||
4 |
- #' In addition to the parent methods, it supports rendering `teal` specific elements such as+ #' |
||
5 |
- #' the source code, the encodings panel content and the filter panel content as part of the+ #' This function is a wrapper for `shiny::validate`. |
||
6 |
- #' meta data.+ #' |
||
7 |
- #' @export+ #' @param x (`data.frame`) |
||
8 |
- #'+ #' @param min_nrow (`numeric(1)`) Minimum allowed number of rows in `x`. |
||
9 |
- TealReportCard <- R6::R6Class( # nolint: object_name.+ #' @param complete (`logical(1)`) Flag specifying whether to check only complete cases. Defaults to `FALSE`. |
||
10 |
- classname = "TealReportCard",+ #' @param allow_inf (`logical(1)`) Flag specifying whether to allow infinite values. Defaults to `TRUE`. |
||
11 |
- inherit = teal.reporter::ReportCard,+ #' @param msg (`character(1)`) Additional message to display alongside the default message. |
||
12 |
- public = list(+ #' |
||
13 |
- #' @description Appends the source code to the `content` meta data of this `TealReportCard`.+ #' @export |
||
14 |
- #'+ #' |
||
15 |
- #' @param src (`character(1)`) code as text.+ #' @examples |
||
16 |
- #' @param ... any `rmarkdown` `R` chunk parameter and its value.+ #' library(teal) |
||
17 |
- #' But `eval` parameter is always set to `FALSE`.+ #' ui <- fluidPage( |
||
18 |
- #' @return Object of class `TealReportCard`, invisibly.+ #' sliderInput("len", "Max Length of Sepal", |
||
19 |
- #' @examples+ #' min = 4.3, max = 7.9, value = 5 |
||
20 |
- #' card <- TealReportCard$new()$append_src(+ #' ), |
||
21 |
- #' "plot(iris)"+ #' plotOutput("plot") |
||
22 |
- #' )+ #' ) |
||
23 |
- #' card$get_content()[[1]]$get_content()+ #' |
||
24 |
- append_src = function(src, ...) {+ #' server <- function(input, output) { |
||
25 | -4x | +
- checkmate::assert_character(src, min.len = 0, max.len = 1)+ #' output$plot <- renderPlot({ |
|
26 | -4x | +
- params <- list(...)+ #' iris_df <- iris[iris$Sepal.Length <= input$len, ] |
|
27 | -4x | +
- params$eval <- FALSE+ #' validate_has_data( |
|
28 | -4x | +
- rblock <- RcodeBlock$new(src)+ #' iris_df, |
|
29 | -4x | +
- rblock$set_params(params)+ #' min_nrow = 10, |
|
30 | -4x | +
- self$append_content(rblock)+ #' complete = FALSE, |
|
31 | -4x | +
- self$append_metadata("SRC", src)+ #' msg = "Please adjust Max Length of Sepal" |
|
32 | -4x | +
- invisible(self)+ #' ) |
|
33 |
- },+ #' |
||
34 |
- #' @description Appends the filter state list to the `content` and `metadata` of this `TealReportCard`.+ #' hist(iris_df$Sepal.Length, breaks = 5) |
||
35 |
- #' If the filter state list has an attribute named `formatted`, it appends it to the card otherwise it uses+ #' }) |
||
36 |
- #' the default `yaml::as.yaml` to format the list.+ #' } |
||
37 |
- #' If the filter state list is empty, nothing is appended to the `content`.+ #' if (interactive()) { |
||
38 |
- #'+ #' shinyApp(ui, server) |
||
39 |
- #' @param fs (`teal_slices`) object returned from [teal_slices()] function.+ #' } |
||
40 |
- #' @return `self`, invisibly.+ #' |
||
41 |
- append_fs = function(fs) {+ validate_has_data <- function(x, |
||
42 | -5x | +
- checkmate::assert_class(fs, "teal_slices")+ min_nrow = NULL, |
|
43 | -4x | +
- self$append_text("Filter State", "header3")+ complete = FALSE, |
|
44 | -4x | +
- if (length(fs)) {+ allow_inf = TRUE, |
|
45 | -3x | +
- self$append_content(TealSlicesBlock$new(fs))+ msg = NULL) { |
|
46 | -+ | 17x |
- } else {+ checkmate::assert_string(msg, null.ok = TRUE) |
47 | -1x | +15x |
- self$append_text("No filters specified.")+ checkmate::assert_data_frame(x) |
48 | -+ | 15x |
- }+ if (!is.null(min_nrow)) { |
49 | -4x | +15x |
- invisible(self)+ if (complete) { |
50 | -+ | 5x |
- },+ complete_index <- stats::complete.cases(x) |
51 | -+ | 5x |
- #' @description Appends the encodings list to the `content` and `metadata` of this `TealReportCard`.+ validate(need( |
52 | -+ | 5x |
- #'+ sum(complete_index) > 0 && nrow(x[complete_index, , drop = FALSE]) >= min_nrow, |
53 | -+ | 5x |
- #' @param encodings (`list`) list of encodings selections of the `teal` app.+ paste(c(paste("Number of complete cases is less than:", min_nrow), msg), collapse = "\n") |
54 |
- #' @return `self`, invisibly.+ )) |
||
55 |
- #' @examples+ } else { |
||
56 | -+ | 10x |
- #' card <- TealReportCard$new()$append_encodings(list(variable1 = "X"))+ validate(need( |
57 | -+ | 10x |
- #' card$get_content()[[1]]$get_content()+ nrow(x) >= min_nrow, |
58 | -+ | 10x |
- #'+ paste( |
59 | -+ | 10x |
- append_encodings = function(encodings) {+ c(paste("Minimum number of records not met: >=", min_nrow, "records required."), msg), |
60 | -4x | +10x |
- checkmate::assert_list(encodings)+ collapse = "\n" |
61 | -4x | +
- self$append_text("Selected Options", "header3")+ ) |
|
62 | -4x | +
- if (requireNamespace("yaml", quietly = TRUE)) {+ )) |
|
63 | -4x | +
- self$append_text(yaml::as.yaml(encodings, handlers = list(+ } |
|
64 | -4x | +
- POSIXct = function(x) format(x, "%Y-%m-%d"),+ |
|
65 | -4x | +10x |
- POSIXlt = function(x) format(x, "%Y-%m-%d"),+ if (!allow_inf) { |
66 | -4x | +6x |
- Date = function(x) format(x, "%Y-%m-%d")+ validate(need( |
67 | -4x | +6x |
- )), "verbatim")+ all(vapply(x, function(col) !is.numeric(col) || !any(is.infinite(col)), logical(1))), |
68 | -+ | 6x |
- } else {+ "Dataframe contains Inf values which is not allowed." |
69 | -! | +
- stop("yaml package is required to format the encodings list")+ )) |
|
70 |
- }+ } |
||
71 | -4x | +
- self$append_metadata("Encodings", encodings)+ } |
|
72 | -4x | +
- invisible(self)+ } |
|
73 |
- }+ |
||
74 |
- ),+ #' Validate that dataset has unique rows for key variables |
||
75 |
- private = list(+ #' |
||
76 |
- dispatch_block = function(block_class) {+ #' `r lifecycle::badge("stable")` |
||
77 | -! | +
- eval(str2lang(block_class))+ #' |
|
78 |
- }+ #' This function is a wrapper for `shiny::validate`. |
||
79 |
- )+ #' |
||
80 |
- )+ #' @param x (`data.frame`) |
||
81 |
-
+ #' @param key (`character`) Vector of ID variables from `x` that identify unique records. |
||
82 |
- #' @title `TealSlicesBlock`+ #' |
||
83 |
- #' @docType class+ #' @export |
||
84 |
- #' @description+ #' |
||
85 |
- #' Specialized `TealSlicesBlock` block for managing filter panel content in reports.+ #' @examples |
||
86 |
- #' @keywords internal+ #' iris$id <- rep(1:50, times = 3) |
||
87 |
- TealSlicesBlock <- R6::R6Class( # nolint: object_name_linter.+ #' ui <- fluidPage( |
||
88 |
- classname = "TealSlicesBlock",+ #' selectInput( |
||
89 |
- inherit = teal.reporter:::TextBlock,+ #' inputId = "species", |
||
90 |
- public = list(+ #' label = "Select species", |
||
91 |
- #' @description Returns a `TealSlicesBlock` object.+ #' choices = c("setosa", "versicolor", "virginica"), |
||
92 |
- #'+ #' selected = "setosa", |
||
93 |
- #' @details Returns a `TealSlicesBlock` object with no content and no parameters.+ #' multiple = TRUE |
||
94 |
- #'+ #' ), |
||
95 |
- #' @param content (`teal_slices`) object returned from [teal_slices()] function.+ #' plotOutput("plot") |
||
96 |
- #' @param style (`character(1)`) string specifying style to apply.+ #' ) |
||
97 |
- #'+ #' server <- function(input, output) { |
||
98 |
- #' @return Object of class `TealSlicesBlock`, invisibly.+ #' output$plot <- renderPlot({ |
||
99 |
- #'+ #' iris_f <- iris[iris$Species %in% input$species, ] |
||
100 |
- initialize = function(content = teal_slices(), style = "verbatim") {+ #' validate_one_row_per_id(iris_f, key = c("id")) |
||
101 | -9x | +
- self$set_content(content)+ #' |
|
102 | -8x | +
- self$set_style(style)+ #' hist(iris_f$Sepal.Length, breaks = 5) |
|
103 | -8x | +
- invisible(self)+ #' }) |
|
104 |
- },+ #' } |
||
105 |
-
+ #' if (interactive()) { |
||
106 |
- #' @description Sets content of this `TealSlicesBlock`.+ #' shinyApp(ui, server) |
||
107 |
- #' Sets content as `YAML` text which represents a list generated from `teal_slices`.+ #' } |
||
108 |
- #' The list displays limited number of fields from `teal_slice` objects, but this list is+ #' |
||
109 |
- #' sufficient to conclude which filters were applied.+ validate_one_row_per_id <- function(x, key = c("USUBJID", "STUDYID")) { |
||
110 | -+ | ! |
- #' When `selected` field in `teal_slice` object is a range, then it is displayed as a "min"+ validate(need(!any(duplicated(x[key])), paste("Found more than one row per id."))) |
111 |
- #'+ } |
||
112 |
- #'+ |
||
113 |
- #' @param content (`teal_slices`) object returned from [teal_slices()] function.+ #' Validates that vector includes all expected values |
||
114 |
- #' @return `self`, invisibly.+ #' |
||
115 |
- set_content = function(content) {+ #' `r lifecycle::badge("stable")` |
||
116 | -9x | +
- checkmate::assert_class(content, "teal_slices")+ #' |
|
117 | -8x | +
- if (length(content) != 0) {+ #' This function is a wrapper for `shiny::validate`. |
|
118 | -6x | +
- states_list <- lapply(content, function(x) {+ #' |
|
119 | -6x | +
- x_list <- shiny::isolate(as.list(x))+ #' @param x Vector of values to test. |
|
120 | -6x | +
- if (+ #' @param choices Vector to test against. |
|
121 | -6x | +
- inherits(x_list$choices, c("integer", "numeric", "Date", "POSIXct", "POSIXlt")) &&+ #' @param msg (`character(1)`) Error message to display if some elements of `x` are not elements of `choices`. |
|
122 | -6x | +
- length(x_list$choices) == 2 &&+ #' |
|
123 | -6x | +
- length(x_list$selected) == 2+ #' @export |
|
124 |
- ) {+ #' |
||
125 | -! | +
- x_list$range <- paste(x_list$selected, collapse = " - ")+ #' @examples |
|
126 | -! | +
- x_list["selected"] <- NULL+ #' ui <- fluidPage( |
|
127 |
- }+ #' selectInput( |
||
128 | -6x | +
- if (!is.null(x_list$arg)) {+ #' "species", |
|
129 | -! | +
- x_list$arg <- if (x_list$arg == "subset") "Genes" else "Samples"+ #' "Select species", |
|
130 |
- }+ #' choices = c("setosa", "versicolor", "virginica", "unknown species"), |
||
131 |
-
+ #' selected = "setosa", |
||
132 | -6x | +
- x_list <- x_list[+ #' multiple = FALSE |
|
133 | -6x | +
- c("dataname", "varname", "experiment", "arg", "expr", "selected", "range", "keep_na", "keep_inf")+ #' ), |
|
134 |
- ]+ #' verbatimTextOutput("summary") |
||
135 | -6x | +
- names(x_list) <- c(+ #' ) |
|
136 | -6x | +
- "Dataset name", "Variable name", "Experiment", "Filtering by", "Applied expression",+ #' |
|
137 | -6x | +
- "Selected Values", "Selected range", "Include NA values", "Include Inf values"+ #' server <- function(input, output) { |
|
138 |
- )+ #' output$summary <- renderPrint({ |
||
139 |
-
+ #' validate_in(input$species, iris$Species, "Species does not exist.") |
||
140 | -6x | +
- Filter(Negate(is.null), x_list)+ #' nrow(iris[iris$Species == input$species, ]) |
|
141 |
- })+ #' }) |
||
142 |
-
+ #' } |
||
143 | -6x | +
- if (requireNamespace("yaml", quietly = TRUE)) {+ #' if (interactive()) { |
|
144 | -6x | +
- super$set_content(yaml::as.yaml(states_list))+ #' shinyApp(ui, server) |
|
145 |
- } else {+ #' } |
||
146 | -! | +
- stop("yaml package is required to format the filter state list")+ #' |
|
147 |
- }+ validate_in <- function(x, choices, msg) { |
||
148 | -+ | ! |
- }+ validate(need(length(x) > 0 && length(choices) > 0 && all(x %in% choices), msg)) |
149 | -8x | +
- private$teal_slices <- content+ } |
|
150 | -8x | +
- invisible(self)+ |
|
151 |
- },+ #' Validates that vector has length greater than 0 |
||
152 |
- #' @description Create the `TealSlicesBlock` from a list.+ #' |
||
153 |
- #'+ #' `r lifecycle::badge("stable")` |
||
154 |
- #' @param x (`named list`) with two fields `text` and `style`.+ #' |
||
155 |
- #' Use the `get_available_styles` method to get all possible styles.+ #' This function is a wrapper for `shiny::validate`. |
||
156 |
- #'+ #' |
||
157 |
- #' @return `self`, invisibly.+ #' @param x vector |
||
158 |
- #' @examples+ #' @param msg message to display |
||
159 |
- #' TealSlicesBlock <- getFromNamespace("TealSlicesBlock", "teal")+ #' |
||
160 |
- #' block <- TealSlicesBlock$new()+ #' @export |
||
161 |
- #' block$from_list(list(text = "sth", style = "default"))+ #' |
||
162 |
- #'+ #' @examples |
||
163 |
- from_list = function(x) {+ #' data <- data.frame( |
||
164 | -1x | +
- checkmate::assert_list(x)+ #' id = c(1:10, 11:20, 1:10), |
|
165 | -1x | +
- checkmate::assert_names(names(x), must.include = c("text", "style"))+ #' strata = rep(c("A", "B"), each = 15) |
|
166 | -1x | +
- super$set_content(x$text)+ #' ) |
|
167 | -1x | +
- super$set_style(x$style)+ #' ui <- fluidPage( |
|
168 | -1x | +
- invisible(self)+ #' selectInput("ref1", "Select strata1 to compare", |
|
169 |
- },+ #' choices = c("A", "B", "C"), selected = "A" |
||
170 |
- #' @description Convert the `TealSlicesBlock` to a list.+ #' ), |
||
171 |
- #'+ #' selectInput("ref2", "Select strata2 to compare", |
||
172 |
- #' @return `named list` with a text and style.+ #' choices = c("A", "B", "C"), selected = "B" |
||
173 |
- #' @examples+ #' ), |
||
174 |
- #' TealSlicesBlock <- getFromNamespace("TealSlicesBlock", "teal")+ #' verbatimTextOutput("arm_summary") |
||
175 |
- #' block <- TealSlicesBlock$new()+ #' ) |
||
176 |
- #' block$to_list()+ #' |
||
177 |
- #'+ #' server <- function(input, output) { |
||
178 |
- to_list = function() {+ #' output$arm_summary <- renderText({ |
||
179 | -2x | +
- content <- self$get_content()+ #' sample_1 <- data$id[data$strata == input$ref1] |
|
180 | -2x | +
- list(+ #' sample_2 <- data$id[data$strata == input$ref2] |
|
181 | -2x | +
- text = if (length(content)) content else "",+ #' |
|
182 | -2x | +
- style = self$get_style()+ #' validate_has_elements(sample_1, "No subjects in strata1.") |
|
183 |
- )+ #' validate_has_elements(sample_2, "No subjects in strata2.") |
||
184 |
- }+ #' |
||
185 |
- ),+ #' paste0( |
||
186 |
- private = list(+ #' "Number of samples in: strata1=", length(sample_1), |
||
187 |
- style = "verbatim",+ #' " comparions strata2=", length(sample_2) |
||
188 |
- teal_slices = NULL # teal_slices+ #' ) |
||
189 |
- )+ #' }) |
||
190 |
- )+ #' } |
1 | +191 |
- #' Generate lockfile for application's environment reproducibility+ #' if (interactive()) { |
|
2 | +192 |
- #'+ #' shinyApp(ui, server) |
|
3 | +193 |
- #' @param lockfile_path (`character`) path to the lockfile.+ #' } |
|
4 | +194 |
- #'+ validate_has_elements <- function(x, msg) { |
|
5 | -+ | ||
195 | +! |
- #' @section Different ways of creating lockfile:+ validate(need(length(x) > 0, msg)) |
|
6 | +196 |
- #' `teal` leverages [renv::snapshot()], which offers multiple methods for lockfile creation.+ } |
|
7 | +197 |
- #'+ |
|
8 | +198 |
- #' - **Working directory lockfile**: `teal`, by default, will create an `implicit` type lockfile that uses+ #' Validates no intersection between two vectors |
|
9 | +199 |
- #' `renv::dependencies()` to detect all R packages in the current project's working directory.+ #' |
|
10 | +200 |
- #' - **`DESCRIPTION`-based lockfile**: To generate a lockfile based on a `DESCRIPTION` file in your working+ #' `r lifecycle::badge("stable")` |
|
11 | +201 |
- #' directory, set `renv::settings$snapshot.type("explicit")`. The naming convention for `type` follows+ #' |
|
12 | +202 |
- #' `renv::snapshot()`. For the `"explicit"` type, refer to `renv::settings$package.dependency.fields()` for the+ #' This function is a wrapper for `shiny::validate`. |
|
13 | +203 |
- #' `DESCRIPTION` fields included in the lockfile.+ #' |
|
14 | +204 |
- #' - **Custom files-based lockfile**: To specify custom files as the basis for the lockfile, set+ #' @param x vector |
|
15 | +205 |
- #' `renv::settings$snapshot.type("custom")` and configure the `renv.snapshot.filter` option.+ #' @param y vector |
|
16 | +206 |
- #'+ #' @param msg (`character(1)`) message to display if `x` and `y` intersect |
|
17 | +207 |
- #' @section lockfile usage:+ #' |
|
18 | +208 |
- #' After creating the lockfile, you can restore the application's environment using `renv::restore()`.+ #' @export |
|
19 | +209 |
#' |
|
20 | +210 |
- #' @seealso [renv::snapshot()], [renv::restore()].+ #' @examples |
|
21 | +211 |
- #'+ #' data <- data.frame( |
|
22 | +212 |
- #' @return `NULL`+ #' id = c(1:10, 11:20, 1:10), |
|
23 | +213 |
- #'+ #' strata = rep(c("A", "B", "C"), each = 10) |
|
24 | +214 |
- #' @name module_teal_lockfile+ #' ) |
|
25 | +215 |
- #' @rdname module_teal_lockfile+ #' |
|
26 | +216 |
- #'+ #' ui <- fluidPage( |
|
27 | +217 |
- #' @keywords internal+ #' selectInput("ref1", "Select strata1 to compare", |
|
28 | +218 |
- NULL+ #' choices = c("A", "B", "C"), |
|
29 | +219 |
-
+ #' selected = "A" |
|
30 | +220 |
- #' @rdname module_teal_lockfile+ #' ), |
|
31 | +221 |
- ui_teal_lockfile <- function(id) {- |
- |
32 | -! | -
- ns <- NS(id)- |
- |
33 | -! | -
- shiny::tagList(- |
- |
34 | -! | -
- tags$span("", id = ns("lockFileStatus")),- |
- |
35 | -! | -
- shinyjs::disabled(downloadLink(ns("lockFileLink"), "Download lockfile"))+ #' selectInput("ref2", "Select strata2 to compare", |
|
36 | +222 |
- )+ #' choices = c("A", "B", "C"), |
|
37 | +223 |
- }+ #' selected = "B" |
|
38 | +224 |
-
+ #' ), |
|
39 | +225 |
- #' @rdname module_teal_lockfile+ #' verbatimTextOutput("summary") |
|
40 | +226 |
- srv_teal_lockfile <- function(id) {- |
- |
41 | -83x | -
- moduleServer(id, function(input, output, session) {- |
- |
42 | -83x | -
- logger::log_debug("Initialize srv_teal_lockfile.")- |
- |
43 | -83x | -
- enable_lockfile_download <- function() {- |
- |
44 | -! | -
- shinyjs::html("lockFileStatus", "Application lockfile ready.")- |
- |
45 | -! | -
- shinyjs::hide("lockFileStatus", anim = TRUE)- |
- |
46 | -! | -
- shinyjs::enable("lockFileLink")- |
- |
47 | -! | -
- output$lockFileLink <- shiny::downloadHandler(- |
- |
48 | -! | -
- filename = function() {+ #' ) |
|
49 | -! | +||
227 | +
- "renv.lock"+ #' |
||
50 | +228 |
- },+ #' server <- function(input, output) { |
|
51 | -! | +||
229 | +
- content = function(file) {+ #' output$summary <- renderText({ |
||
52 | -! | +||
230 | +
- file.copy(lockfile_path, file)+ #' sample_1 <- data$id[data$strata == input$ref1] |
||
53 | -! | +||
231 | +
- file+ #' sample_2 <- data$id[data$strata == input$ref2] |
||
54 | +232 |
- },+ #' |
|
55 | -! | +||
233 | +
- contentType = "application/json"+ #' validate_no_intersection( |
||
56 | +234 |
- )+ #' sample_1, sample_2, |
|
57 | +235 |
- }+ #' "subjects within strata1 and strata2 cannot overlap" |
|
58 | -83x | +||
236 | +
- disable_lockfile_download <- function() {+ #' ) |
||
59 | -! | +||
237 | +
- warning("Lockfile creation failed.", call. = FALSE)+ #' paste0( |
||
60 | -! | +||
238 | +
- shinyjs::html("lockFileStatus", "Lockfile creation failed.")+ #' "Number of subject in: reference treatment=", length(sample_1), |
||
61 | -! | +||
239 | +
- shinyjs::hide("lockFileLink")+ #' " comparions treatment=", length(sample_2) |
||
62 | +240 |
- }+ #' ) |
|
63 | +241 |
-
+ #' }) |
|
64 | -83x | +||
242 | +
- shiny::onStop(function() {+ #' } |
||
65 | -83x | +||
243 | +
- if (file.exists(lockfile_path) && !shiny::isRunning()) {+ #' if (interactive()) { |
||
66 | -1x | +||
244 | +
- logger::log_debug("Removing lockfile after shutting down the app")+ #' shinyApp(ui, server) |
||
67 | -1x | +||
245 | +
- file.remove(lockfile_path)+ #' } |
||
68 | +246 |
- }+ #' |
|
69 | +247 |
- })+ validate_no_intersection <- function(x, y, msg) {+ |
+ |
248 | +! | +
+ validate(need(length(intersect(x, y)) == 0, msg)) |
|
70 | +249 |
-
+ } |
|
71 | -83x | +||
250 | +
- lockfile_path <- "teal_app.lock"+ |
||
72 | -83x | +||
251 | +
- mode <- getOption("teal.lockfile.mode", default = "")+ |
||
73 | +252 |
-
+ #' Validates that dataset contains specific variable |
|
74 | -83x | +||
253 | +
- if (!(mode %in% c("auto", "enabled", "disabled"))) {+ #' |
||
75 | -! | +||
254 | +
- stop("'teal.lockfile.mode' option can only be one of \"auto\", \"disabled\" or \"disabled\". ")+ #' `r lifecycle::badge("stable")` |
||
76 | +255 |
- }+ #' |
|
77 | +256 |
-
+ #' This function is a wrapper for `shiny::validate`. |
|
78 | -83x | +||
257 | +
- if (mode == "disabled") {+ #' |
||
79 | -1x | +||
258 | +
- logger::log_debug("'teal.lockfile.mode' option is set to 'disabled'. Hiding lockfile download button.")+ #' @param data (`data.frame`) |
||
80 | -1x | +||
259 | +
- shinyjs::hide("lockFileLink")+ #' @param varname (`character(1)`) name of variable to check for in `data` |
||
81 | -1x | +||
260 | +
- return(NULL)+ #' @param msg (`character(1)`) message to display if `data` does not include `varname` |
||
82 | +261 |
- }+ #' |
|
83 | +262 |
-
+ #' @export |
|
84 | -82x | +||
263 | +
- if (file.exists(lockfile_path)) {+ #' |
||
85 | -! | +||
264 | +
- logger::log_debug("Lockfile has already been created for this app - skipping automatic creation.")+ #' @examples |
||
86 | -! | +||
265 | +
- enable_lockfile_download()+ #' data <- data.frame( |
||
87 | -! | +||
266 | +
- return(NULL)+ #' one = rep("a", length.out = 20), |
||
88 | +267 |
- }+ #' two = rep(c("a", "b"), length.out = 20) |
|
89 | +268 |
-
+ #' ) |
|
90 | -82x | +||
269 | +
- if (mode == "auto" && .is_disabled_lockfile_scenario()) {+ #' ui <- fluidPage( |
||
91 | -81x | +||
270 | +
- logger::log_debug(+ #' selectInput( |
||
92 | -81x | +||
271 | +
- "Automatic lockfile creation disabled. Execution scenario satisfies teal:::.is_disabled_lockfile_scenario()."+ #' "var", |
||
93 | +272 |
- )+ #' "Select variable", |
|
94 | -81x | +||
273 | +
- shinyjs::hide("lockFileLink")+ #' choices = c("one", "two", "three", "four"), |
||
95 | -81x | +||
274 | +
- return(NULL)+ #' selected = "one" |
||
96 | +275 |
- }+ #' ), |
|
97 | +276 |
-
+ #' verbatimTextOutput("summary") |
|
98 | -1x | +||
277 | +
- if (!.is_lockfile_deps_installed()) {+ #' ) |
||
99 | -! | +||
278 | +
- warning("Automatic lockfile creation disabled. `mirai` and `renv` packages must be installed.")+ #' |
||
100 | -! | +||
279 | +
- shinyjs::hide("lockFileLink")+ #' server <- function(input, output) { |
||
101 | -! | +||
280 | +
- return(NULL)+ #' output$summary <- renderText({ |
||
102 | +281 |
- }+ #' validate_has_variable(data, input$var) |
|
103 | +282 |
-
+ #' paste0("Selected treatment variables: ", paste(input$var, collapse = ", ")) |
|
104 | +283 |
- # - Will be run only if the lockfile doesn't exist (see the if-s above)+ #' }) |
|
105 | +284 |
- # - We render to the tempfile because the process might last after session is closed and we don't+ #' } |
|
106 | +285 |
- # want to make a "teal_app.renv" then. This is why we copy only during active session.+ #' if (interactive()) { |
|
107 | -1x | +||
286 | +
- process <- .teal_lockfile_process_invoke(lockfile_path)+ #' shinyApp(ui, server) |
||
108 | -1x | +||
287 | +
- observeEvent(process$status(), {+ #' } |
||
109 | -! | +||
288 | +
- if (process$status() %in% c("initial", "running")) {+ validate_has_variable <- function(data, varname, msg) { |
||
110 | +289 | ! |
- shinyjs::html("lockFileStatus", "Creating lockfile...")+ if (length(varname) != 0) { |
111 | +290 | ! |
- } else if (process$status() == "success") {+ has_vars <- varname %in% names(data) |
112 | -! | +||
291 | +
- result <- process$result()+ |
||
113 | +292 | ! |
- if (any(grepl("Lockfile written to", result$out))) {+ if (!all(has_vars)) { |
114 | +293 | ! |
- logger::log_debug("Lockfile containing { length(result$res$Packages) } packages created.")+ if (missing(msg)) { |
115 | +294 | ! |
- if (any(grepl("(WARNING|ERROR):", result$out))) {+ msg <- sprintf( |
116 | +295 | ! |
- warning("Lockfile created with warning(s) or error(s):", call. = FALSE)+ "%s does not have the required variables: %s.", |
117 | +296 | ! |
- for (i in result$out) {+ deparse(substitute(data)), |
118 | +297 | ! |
- warning(i, call. = FALSE)+ toString(varname[!has_vars]) |
119 | +298 |
- }+ ) |
|
120 | +299 |
- }+ } |
|
121 | +300 | ! |
- enable_lockfile_download()+ validate(need(FALSE, msg)) |
122 | +301 |
- } else {- |
- |
123 | -! | -
- disable_lockfile_download()+ } |
|
124 | +302 |
- }- |
- |
125 | -! | -
- } else if (process$status() == "error") {- |
- |
126 | -! | -
- disable_lockfile_download()+ } |
|
127 | +303 |
- }+ } |
|
128 | +304 |
- })+ |
|
129 | +305 |
-
+ #' Validate that variables has expected number of levels |
|
130 | -1x | +||
306 | +
- NULL+ #' |
||
131 | +307 |
- })+ #' `r lifecycle::badge("stable")` |
|
132 | +308 |
- }+ #' |
|
133 | +309 |
-
+ #' If the number of levels of `x` is less than `min_levels` |
|
134 | +310 |
- utils::globalVariables(c("opts", "sysenv", "libpaths", "wd", "lockfilepath", "run")) # needed for mirai call+ #' or greater than `max_levels` the validation will fail. |
|
135 | +311 |
- #' @rdname module_teal_lockfile+ #' This function is a wrapper for `shiny::validate`. |
|
136 | +312 |
- .teal_lockfile_process_invoke <- function(lockfile_path) {+ #' |
|
137 | -1x | +||
313 | +
- mirai_obj <- NULL+ #' @param x variable name. If `x` is not a factor, the unique values |
||
138 | -1x | +||
314 | +
- process <- shiny::ExtendedTask$new(function() {+ #' are treated as levels. |
||
139 | -1x | +||
315 | +
- m <- mirai::mirai(+ #' @param min_levels cutoff for minimum number of levels of `x` |
||
140 | +316 |
- {+ #' @param max_levels cutoff for maximum number of levels of `x` |
|
141 | -1x | +||
317 | +
- options(opts)+ #' @param var_name name of variable being validated for use in |
||
142 | -1x | +||
318 | +
- do.call(Sys.setenv, sysenv)+ #' validation message |
||
143 | -1x | +||
319 | +
- .libPaths(libpaths)+ #' |
||
144 | -1x | +||
320 | +
- setwd(wd)+ #' @export |
||
145 | -1x | +||
321 | +
- run(lockfile_path = lockfile_path)+ #' @examples |
||
146 | +322 |
- },+ #' data <- data.frame( |
|
147 | -1x | +||
323 | +
- run = .renv_snapshot,+ #' one = rep("a", length.out = 20), |
||
148 | -1x | +||
324 | +
- lockfile_path = lockfile_path,+ #' two = rep(c("a", "b"), length.out = 20), |
||
149 | -1x | +||
325 | +
- opts = options(),+ #' three = rep(c("a", "b", "c"), length.out = 20), |
||
150 | -1x | +||
326 | +
- libpaths = .libPaths(),+ #' four = rep(c("a", "b", "c", "d"), length.out = 20), |
||
151 | -1x | +||
327 | +
- sysenv = as.list(Sys.getenv()),+ #' stringsAsFactors = TRUE |
||
152 | -1x | +||
328 | +
- wd = getwd()+ #' ) |
||
153 | +329 |
- )+ #' ui <- fluidPage( |
|
154 | -1x | +||
330 | +
- mirai_obj <<- m+ #' selectInput( |
||
155 | -1x | +||
331 | +
- m+ #' "var", |
||
156 | +332 |
- })+ #' "Select variable", |
|
157 | +333 |
-
+ #' choices = c("one", "two", "three", "four"), |
|
158 | -1x | +||
334 | +
- shiny::onStop(function() {+ #' selected = "one" |
||
159 | -1x | +||
335 | +
- if (mirai::unresolved(mirai_obj)) {+ #' ), |
||
160 | -! | +||
336 | +
- logger::log_debug("Terminating a running lockfile process...")+ #' verbatimTextOutput("summary") |
||
161 | -! | +||
337 | +
- mirai::stop_mirai(mirai_obj) # this doesn't stop running - renv will be created even if session is closed+ #' ) |
||
162 | +338 |
- }+ #' |
|
163 | +339 |
- })+ #' server <- function(input, output) { |
|
164 | +340 |
-
+ #' output$summary <- renderText({ |
|
165 | -1x | +||
341 | +
- suppressWarnings({ # 'package:stats' may not be available when loading+ #' validate_n_levels(data[[input$var]], min_levels = 2, max_levels = 15, var_name = input$var) |
||
166 | -1x | +||
342 | +
- process$invoke()+ #' paste0( |
||
167 | +343 |
- })+ #' "Levels of selected treatment variable: ", |
|
168 | +344 |
-
+ #' paste(levels(data[[input$var]]), |
|
169 | -1x | +||
345 | +
- logger::log_debug("Lockfile creation started based on { getwd() }.")+ #' collapse = ", " |
||
170 | +346 |
-
+ #' ) |
|
171 | -1x | +||
347 | +
- process+ #' ) |
||
172 | +348 |
- }+ #' }) |
|
173 | +349 |
-
+ #' } |
|
174 | +350 |
- #' @rdname module_teal_lockfile+ #' if (interactive()) { |
|
175 | +351 |
- .renv_snapshot <- function(lockfile_path) {+ #' shinyApp(ui, server) |
|
176 | -1x | +||
352 | +
- out <- utils::capture.output(+ #' } |
||
177 | -1x | +||
353 | +
- res <- renv::snapshot(+ validate_n_levels <- function(x, min_levels = 1, max_levels = 12, var_name) { |
||
178 | -1x | +||
354 | +! |
- lockfile = lockfile_path,+ x_levels <- if (is.factor(x)) { |
|
179 | -1x | +||
355 | +! |
- prompt = FALSE,+ levels(x) |
|
180 | -1x | +||
356 | +
- force = TRUE,+ } else { |
||
181 | -1x | +||
357 | +! |
- type = renv::settings$snapshot.type() # see the section "Different ways of creating lockfile" above here+ unique(x) |
|
182 | +358 |
- )+ } |
|
183 | +359 |
- )+ |
|
184 | -+ | ||
360 | +! |
-
+ if (!is.null(min_levels) && !(is.null(max_levels))) { |
|
185 | -1x | +||
361 | +! |
- list(out = out, res = res)+ validate(need( |
|
186 | -+ | ||
362 | +! |
- }+ length(x_levels) >= min_levels && length(x_levels) <= max_levels, |
|
187 | -+ | ||
363 | +! |
-
+ sprintf(+ |
+ |
364 | +! | +
+ "%s variable needs minimum %s level(s) and maximum %s level(s).",+ |
+ |
365 | +! | +
+ var_name, min_levels, max_levels |
|
188 | +366 |
- #' @rdname module_teal_lockfile+ ) |
|
189 | +367 |
- .is_lockfile_deps_installed <- function() {+ )) |
|
190 | -1x | +||
368 | +! |
- requireNamespace("mirai", quietly = TRUE) && requireNamespace("renv", quietly = TRUE)+ } else if (!is.null(min_levels)) { |
|
191 | -+ | ||
369 | +! |
- }+ validate(need( |
|
192 | -+ | ||
370 | +! |
-
+ length(x_levels) >= min_levels, |
|
193 | -+ | ||
371 | +! |
- #' @rdname module_teal_lockfile+ sprintf("%s variable needs minimum %s levels(s)", var_name, min_levels) |
|
194 | +372 |
- .is_disabled_lockfile_scenario <- function() {+ )) |
|
195 | -81x | +||
373 | +! |
- identical(Sys.getenv("CALLR_IS_RUNNING"), "true") || # inside callr process+ } else if (!is.null(max_levels)) { |
|
196 | -81x | +||
374 | +! |
- identical(Sys.getenv("TESTTHAT"), "true") || # inside devtools::test+ validate(need( |
|
197 | -81x | +||
375 | +! |
- !identical(Sys.getenv("QUARTO_PROJECT_ROOT"), "") || # inside Quarto process+ length(x_levels) <= max_levels, |
|
198 | -+ | ||
376 | +! |
- (+ sprintf("%s variable needs maximum %s level(s)", var_name, max_levels) |
|
199 | -81x | +||
377 | +
- ("CheckExEnv" %in% search()) || any(c("_R_CHECK_TIMINGS_", "_R_CHECK_LICENSE_") %in% names(Sys.getenv()))+ )) |
||
200 | -81x | +||
378 | +
- ) # inside R CMD CHECK+ } |
||
201 | +379 |
}@@ -19962,28 +20931,28 @@ teal coverage - 59.99% |
1 |
- #' Data summary+ #' Filter state snapshot management |
||
2 |
- #' @description+ #' |
||
3 |
- #' Module and its utils to display the number of rows and subjects in the filtered and unfiltered data.+ #' Capture and restore snapshots of the global (app) filter state. |
||
5 |
- #' @details Handling different data classes:+ #' This module introduces snapshots: stored descriptions of the filter state of the entire application. |
||
6 |
- #' `get_filter_overview()` is a pseudo S3 method which has variants for:+ #' Snapshots allow the user to save the current filter state of the application for later use in the session, |
||
7 |
- #' - `array` (`data.frame`, `DataFrame`, `array`, `Matrix` and `SummarizedExperiment`): Method variant+ #' as well as to save it to file in order to share it with an app developer or other users, |
||
8 |
- #' can be applied to any two-dimensional objects on which [ncol()] can be used.+ #' who in turn can upload it to their own session. |
||
9 |
- #' - `MultiAssayExperiment`: for which summary contains counts for `colData` and all `experiments`.+ #' |
||
10 |
- #' - For other data types module displays data name with warning icon and no more details.+ #' The snapshot manager is accessed with the camera icon in the tabset bar. |
||
11 |
- #'+ #' At the beginning of a session it presents three icons: a camera, an upload, and an circular arrow. |
||
12 |
- #' Module includes also "Show/Hide unsupported" button to toggle rows of the summary table+ #' Clicking the camera captures a snapshot, clicking the upload adds a snapshot from a file |
||
13 |
- #' containing datasets where number of observations are not calculated.+ #' and applies the filter states therein, and clicking the arrow resets initial application state. |
||
14 |
- #'+ #' As snapshots are added, they will show up as rows in a table and each will have a select button and a save button. |
||
15 |
- #' @param id (`character(1)`) `shiny` module instance id.+ #' |
||
16 |
- #' @param teal_data (`reactive` returning `teal_data`)+ #' @section Server logic: |
||
17 |
- #'+ #' Snapshots are basically `teal_slices` objects, however, since each module is served by a separate instance |
||
18 |
- #' @name module_data_summary+ #' of `FilteredData` and these objects require shared state, `teal_slice` is a `reactiveVal` so `teal_slices` |
||
19 |
- #' @rdname module_data_summary+ #' cannot be stored as is. Therefore, `teal_slices` are reversibly converted to a list of lists representation |
||
20 |
- #' @keywords internal+ #' (attributes are maintained). |
||
21 |
- #' @return `NULL`.+ #' |
||
22 |
- NULL+ #' Snapshots are stored in a `reactiveVal` as a named list. |
||
23 |
-
+ #' The first snapshot is the initial state of the application and the user can add a snapshot whenever they see fit. |
||
24 |
- #' @rdname module_data_summary+ #' |
||
25 |
- ui_data_summary <- function(id) {+ #' For every snapshot except the initial one, a piece of UI is generated that contains |
||
26 | -! | +
- ns <- NS(id)+ #' the snapshot name, a select button to restore that snapshot, and a save button to save it to a file. |
|
27 | -! | +
- content_id <- ns("filters_overview_contents")+ #' The initial snapshot is restored by a separate "reset" button. |
|
28 | -! | +
- tags$div(+ #' It cannot be saved directly but a user is welcome to capture the initial state as a snapshot and save that. |
|
29 | -! | +
- id = id,+ #' |
|
30 | -! | +
- class = "well",+ #' @section Snapshot mechanics: |
|
31 | -! | +
- tags$div(+ #' When a snapshot is captured, the user is prompted to name it. |
|
32 | -! | +
- class = "row",+ #' Names are displayed as is but since they are used to create button ids, |
|
33 | -! | +
- tags$div(+ #' under the hood they are converted to syntactically valid strings. |
|
34 | -! | +
- class = "col-sm-9",+ #' New snapshot names are validated so that their valid versions are unique. |
|
35 | -! | +
- tags$label("Active Filter Summary", class = "text-primary mb-4")+ #' Leading and trailing white space is trimmed. |
|
36 |
- ),+ #' |
||
37 | -! | +
- tags$div(+ #' The module can read the global state of the application from `slices_global` and `mapping_matrix`. |
|
38 | -! | +
- class = "col-sm-3",+ #' The former provides a list of all existing `teal_slice`s and the latter says which slice is active in which module. |
|
39 | -! | +
- tags$i(+ #' Once a name has been accepted, `slices_global` is converted to a list of lists - a snapshot. |
|
40 | -! | +
- class = "remove pull-right fa fa-angle-down",+ #' The snapshot contains the `mapping` attribute of the initial application state |
|
41 | -! | +
- style = "cursor: pointer;",+ #' (or one that has been restored), which may not reflect the current one, |
|
42 | -! | +
- title = "fold/expand data summary panel",+ #' so `mapping_matrix` is transformed to obtain the current mapping, i.e. a list that, |
|
43 | -! | +
- onclick = sprintf("togglePanelItems(this, '%s', 'fa-angle-right', 'fa-angle-down');", content_id)+ #' when passed to the `mapping` argument of [teal_slices()], would result in the current mapping. |
|
44 |
- )+ #' This is substituted as the snapshot's `mapping` attribute and the snapshot is added to the snapshot list. |
||
45 |
- )+ #' |
||
46 |
- ),+ #' To restore app state, a snapshot is retrieved from storage and rebuilt into a `teal_slices` object. |
||
47 | -! | +
- tags$div(+ #' Then state of all `FilteredData` objects (provided in `datasets`) is cleared |
|
48 | -! | +
- id = content_id,+ #' and set anew according to the `mapping` attribute of the snapshot. |
|
49 | -! | +
- tags$div(+ #' The snapshot is then set as the current content of `slices_global`. |
|
50 | -! | +
- class = "teal_active_summary_filter_panel",+ #' |
|
51 | -! | +
- tableOutput(ns("table"))+ #' To save a snapshot, the snapshot is retrieved and reassembled just like for restoring, |
|
52 |
- )+ #' and then saved to file with [slices_store()]. |
||
53 |
- )+ #' |
||
54 |
- )+ #' When a snapshot is uploaded, it will first be added to storage just like a newly created one, |
||
55 |
- }+ #' and then used to restore app state much like a snapshot taken from storage. |
||
56 |
-
+ #' Upon clicking the upload icon the user will be prompted for a file to upload |
||
57 |
- #' @rdname module_data_summary+ #' and may choose to name the new snapshot. The name defaults to the name of the file (the extension is dropped) |
||
58 |
- srv_data_summary <- function(id, teal_data) {+ #' and normal naming rules apply. Loading the file yields a `teal_slices` object, |
||
59 | -81x | +
- assert_reactive(teal_data)+ #' which is disassembled for storage and used directly for restoring app state. |
|
60 | -81x | +
- moduleServer(+ #' |
|
61 | -81x | +
- id = id,+ #' @section Transferring snapshots: |
|
62 | -81x | +
- function(input, output, session) {+ #' Snapshots uploaded from disk should only be used in the same application they come from, |
|
63 | -81x | +
- logger::log_debug("srv_data_summary initializing")+ #' _i.e._ an application that uses the same data and the same modules. |
|
64 |
-
+ #' To ensure this is the case, `init` stamps `teal_slices` with an app id that is stored in the `app_id` attribute of |
||
65 | -81x | +
- summary_table <- reactive({+ #' a `teal_slices` object. When a snapshot is restored from file, its `app_id` is compared to that |
|
66 | -89x | +
- req(inherits(teal_data(), "teal_data"))+ #' of the current app state and only if the match is the snapshot admitted to the session. |
|
67 | -83x | +
- if (!length(ls(teal.code::get_env(teal_data())))) {+ #' |
|
68 | -2x | +
- return(NULL)+ #' @section Bookmarks: |
|
69 |
- }+ #' An `onBookmark` callback creates a snapshot of the current filter state. |
||
70 | -81x | +
- get_filter_overview_wrapper(teal_data)+ #' This is done on the app session, not the module session. |
|
71 |
- })+ #' (The snapshot will be retrieved by `module_teal` in order to set initial app state in a restored app.) |
||
72 |
-
+ #' Then that snapshot, and the previous snapshot history are dumped into the `values.rds` file in `<bookmark_dir>`. |
||
73 | -81x | +
- output$table <- renderUI({+ #' |
|
74 | -89x | +
- summary_table_out <- try(summary_table(), silent = TRUE)+ #' @param id (`character(1)`) `shiny` module instance id. |
|
75 | -89x | +
- if (inherits(summary_table_out, "try-error")) {+ #' @param slices_global (`reactiveVal`) that contains a `teal_slices` object |
|
76 |
- # Ignore silent shiny error+ #' containing all `teal_slice`s existing in the app, both active and inactive. |
||
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.")+ #' @return `list` containing the snapshot history, where each element is an unlisted `teal_slices` object. |
|
79 |
- }+ #' |
||
80 | -83x | +
- } else if (is.null(summary_table_out)) {+ #' @name module_snapshot_manager |
|
81 | -2x | +
- "no datasets to show"+ #' @rdname module_snapshot_manager |
|
82 |
- } else {+ #' |
||
83 | -81x | +
- is_unsupported <- apply(summary_table(), 1, function(x) all(is.na(x[-1])))+ #' @author Aleksander Chlebowski |
|
84 | -81x | +
- summary_table_out[is.na(summary_table_out)] <- ""+ #' @keywords internal |
|
85 | -81x | +
- body_html <- apply(+ NULL |
|
86 | -81x | +
- summary_table_out,+ |
|
87 | -81x | +
- 1,+ #' @rdname module_snapshot_manager |
|
88 | -81x | +
- function(x) {+ ui_snapshot_manager_panel <- function(id) { |
|
89 | -154x | +! |
- is_supported <- !all(x[-1] == "")+ ns <- NS(id) |
90 | -154x | +! |
- if (is_supported) {+ tags$button( |
91 | -147x | +! |
- tags$tr(+ id = ns("show_snapshot_manager"), |
92 | -147x | +! |
- tagList(+ class = "btn action-button wunder_bar_button", |
93 | -147x | +! |
- tags$td(x[1]),+ title = "View filter mapping", |
94 | -147x | +! |
- lapply(x[-1], tags$td)+ suppressMessages(icon("fas fa-camera")) |
95 |
- )+ ) |
||
96 |
- )+ } |
||
97 |
- }+ |
||
98 |
- }+ #' @rdname module_snapshot_manager |
||
99 |
- )+ srv_snapshot_manager_panel <- function(id, slices_global) { |
||
100 | -+ | 82x |
-
+ moduleServer(id, function(input, output, session) { |
101 | -81x | +82x |
- header_labels <- tools::toTitleCase(names(summary_table_out))+ logger::log_debug("srv_snapshot_manager_panel initializing") |
102 | -81x | +82x |
- header_labels[header_labels == "Dataname"] <- "Data Name"+ setBookmarkExclude(c("show_snapshot_manager")) |
103 | -81x | +82x |
- header_html <- tags$tr(tagList(lapply(header_labels, tags$td)))+ observeEvent(input$show_snapshot_manager, { |
104 | -+ | ! |
-
+ logger::log_debug("srv_snapshot_manager_panel@1 show_snapshot_manager button has been clicked.") |
105 | -81x | +! |
- table_html <- tags$table(+ showModal( |
106 | -81x | +! |
- class = "table custom-table",+ modalDialog( |
107 | -81x | +! |
- tags$thead(header_html),+ ui_snapshot_manager(session$ns("module")), |
108 | -81x | +! |
- tags$tbody(body_html)+ class = "snapshot_manager_modal", |
109 | -+ | ! |
- )+ size = "m", |
110 | -81x | +! |
- div(+ footer = NULL, |
111 | -81x | +! |
- table_html,+ easyClose = TRUE |
112 | -81x | +
- if (any(is_unsupported)) {+ ) |
|
113 | -7x | +
- p(+ ) |
|
114 | -7x | +
- class = c("pull-right", "float-right", "text-secondary"),+ }) |
|
115 | -7x | +82x |
- style = "font-size: 0.8em;",+ srv_snapshot_manager("module", slices_global = slices_global) |
116 | -7x | +
- sprintf("And %s more unfilterable object(s)", sum(is_unsupported)),+ }) |
|
117 | -7x | +
- icon(+ } |
|
118 | -7x | +
- name = "far fa-circle-question",+ |
|
119 | -7x | +
- title = paste(+ #' @rdname module_snapshot_manager |
|
120 | -7x | +
- sep = "",+ ui_snapshot_manager <- function(id) { |
|
121 | -7x | +! |
- collapse = "\n",+ ns <- NS(id) |
122 | -7x | +! |
- shQuote(summary_table()[is_unsupported, "dataname"]),+ tags$div( |
123 | -+ | ! |
- " (",+ class = "manager_content", |
124 | -7x | +! |
- vapply(+ tags$div( |
125 | -7x | +! |
- summary_table()[is_unsupported, "dataname"],+ class = "manager_table_row", |
126 | -7x | +! |
- function(x) class(teal_data()[[x]])[1],+ tags$span(tags$b("Snapshot manager")), |
127 | -7x | +! |
- character(1L)+ actionLink(ns("snapshot_add"), label = NULL, icon = icon("fas fa-camera"), title = "add snapshot"), |
128 | -+ | ! |
- ),+ actionLink(ns("snapshot_load"), label = NULL, icon = icon("fas fa-upload"), title = "upload snapshot"), |
129 | -+ | ! |
- ")"+ actionLink(ns("snapshot_reset"), label = NULL, icon = icon("fas fa-undo"), title = "reset initial state"), |
130 | -+ | ! |
- )+ NULL |
131 |
- )+ ), |
||
132 | -+ | ! |
- )+ uiOutput(ns("snapshot_list")) |
133 |
- }+ ) |
||
134 |
- )+ } |
||
135 |
- }+ |
||
136 |
- })+ #' @rdname module_snapshot_manager |
||
137 |
-
+ srv_snapshot_manager <- function(id, slices_global) { |
||
138 | -81x | +82x |
- NULL+ checkmate::assert_character(id) |
139 |
- }+ |
||
140 | -+ | 82x |
- )+ moduleServer(id, function(input, output, session) { |
141 | -+ | 82x |
- }+ logger::log_debug("srv_snapshot_manager initializing") |
143 |
- #' @rdname module_data_summary+ # Set up bookmarking callbacks ---- |
||
144 |
- get_filter_overview_wrapper <- function(teal_data) {+ # Register bookmark exclusions (all buttons and text fields). |
||
145 | -81x | +82x |
- datanames <- teal.data::datanames(teal_data())+ setBookmarkExclude(c( |
146 | -81x | +82x |
- joinkeys <- teal.data::join_keys(teal_data())+ "snapshot_add", "snapshot_load", "snapshot_reset", |
147 | -+ | 82x |
-
+ "snapshot_name_accept", "snaphot_file_accept", |
148 | -81x | +82x |
- current_data_objs <- sapply(+ "snapshot_name", "snapshot_file" |
149 | -81x | +
- datanames,+ )) |
|
150 | -81x | +
- function(name) teal.code::get_var(teal_data(), name),+ # Add snapshot history to bookmark. |
|
151 | -81x | +82x |
- simplify = FALSE+ session$onBookmark(function(state) { |
152 | -+ | ! |
- )+ logger::log_debug("srv_snapshot_manager@onBookmark: storing snapshot and bookmark history") |
153 | -81x | +! |
- initial_data_objs <- teal.code::get_var(teal_data(), ".raw_data")+ state$values$snapshot_history <- snapshot_history() # isolate this? |
154 |
-
+ }) |
||
155 | -81x | +
- out <- lapply(+ |
|
156 | -81x | +82x |
- datanames,+ ns <- session$ns |
157 | -81x | +
- function(dataname) {+ |
|
158 | -149x | +
- parent <- teal.data::parent(joinkeys, dataname)+ # Track global filter states ---- |
|
159 | -+ | 82x |
- # todo: what should we display for a parent dataset?+ snapshot_history <- reactiveVal({ |
160 |
- # - Obs and Subjects+ # Restore directly from bookmarked state, if applicable. |
||
161 | -+ | 82x |
- # - Obs only+ restoreValue( |
162 | -+ | 82x |
- # - Subjects only+ ns("snapshot_history"), |
163 | -+ | 82x |
- # todo (for later): summary table should be displayed in a way that child datasets+ list("Initial application state" = shiny::isolate(as.list(slices_global$all_slices(), recursive = TRUE))) |
164 |
- # are indented under their parent dataset to form a tree structure+ ) |
||
165 | -149x | +
- subject_keys <- if (length(parent) > 0) {+ }) |
|
166 | -7x | +
- names(joinkeys[dataname, parent])+ |
|
167 |
- } else {+ # Snapshot current application state ---- |
||
168 | -142x | +
- joinkeys[dataname, dataname]+ # Name snaphsot. |
|
169 | -+ | 82x |
- }+ observeEvent(input$snapshot_add, { |
170 | -149x | +! |
- get_filter_overview(+ logger::log_debug("srv_snapshot_manager: snapshot_add button clicked") |
171 | -149x | +! |
- current_data = current_data_objs[[dataname]],+ showModal( |
172 | -149x | +! |
- initial_data = initial_data_objs[[dataname]],+ modalDialog( |
173 | -149x | +! |
- dataname = dataname,+ textInput(ns("snapshot_name"), "Name the snapshot", width = "100%", placeholder = "Meaningful, unique name"), |
174 | -149x | +! |
- subject_keys = subject_keys+ footer = tagList( |
175 | -+ | ! |
- )+ actionButton(ns("snapshot_name_accept"), "Accept", icon = icon("far fa-thumbs-up")), |
176 | -+ | ! |
- }+ modalButton(label = "Cancel", icon = icon("far fa-thumbs-down")) |
177 |
- )+ ), |
||
178 | -+ | ! |
-
+ size = "s" |
179 | -81x | +
- do.call(.smart_rbind, out)+ ) |
|
180 |
- }+ ) |
||
181 |
-
+ }) |
||
182 |
-
+ # Store snaphsot. |
||
183 | -+ | 82x |
- #' @rdname module_data_summary+ observeEvent(input$snapshot_name_accept, { |
184 | -+ | ! |
- #' @param current_data (`object`) current object (after filtering and transforming).+ logger::log_debug("srv_snapshot_manager: snapshot_name_accept button clicked") |
185 | -+ | ! |
- #' @param initial_data (`object`) initial object.+ snapshot_name <- trimws(input$snapshot_name) |
186 | -+ | ! |
- #' @param dataname (`character(1)`)+ if (identical(snapshot_name, "")) { |
187 | -+ | ! |
- #' @param subject_keys (`character`) names of the columns which determine a single unique subjects+ logger::log_debug("srv_snapshot_manager: snapshot name rejected") |
188 | -+ | ! |
- get_filter_overview <- function(current_data, initial_data, dataname, subject_keys) {+ showNotification( |
189 | -154x | +! |
- if (inherits(current_data, c("data.frame", "DataFrame", "array", "Matrix", "SummarizedExperiment"))) {+ "Please name the snapshot.", |
190 | -146x | +! |
- get_filter_overview_array(current_data, initial_data, dataname, subject_keys)+ type = "message" |
191 | -8x | +
- } else if (inherits(current_data, "MultiAssayExperiment")) {+ ) |
|
192 | -1x | +! |
- get_filter_overview_MultiAssayExperiment(current_data, initial_data, dataname)+ updateTextInput(inputId = "snapshot_name", value = "", placeholder = "Meaningful, unique name") |
193 | -+ | ! |
- } else {+ } else if (is.element(make.names(snapshot_name), make.names(names(snapshot_history())))) { |
194 | -7x | +! |
- data.frame(dataname = dataname)+ logger::log_debug("srv_snapshot_manager: snapshot name rejected") |
195 | -+ | ! |
- }+ showNotification( |
196 | -+ | ! |
- }+ "This name is in conflict with other snapshot names. Please choose a different one.", |
197 | -+ | ! |
-
+ type = "message" |
198 |
- #' @rdname module_data_summary+ ) |
||
199 | -+ | ! |
- get_filter_overview_array <- function(current_data,+ updateTextInput(inputId = "snapshot_name", value = "", placeholder = "Meaningful, unique name") |
200 |
- initial_data,+ } else { |
||
201 | -+ | ! |
- dataname,+ logger::log_debug("srv_snapshot_manager: snapshot name accepted, adding snapshot") |
202 | -+ | ! |
- subject_keys) {+ snapshot <- as.list(slices_global$all_slices(), recursive = TRUE) |
203 | -146x | +! |
- if (length(subject_keys) == 0) {+ snapshot_update <- c(snapshot_history(), list(snapshot)) |
204 | -133x | +! |
- data.frame(+ names(snapshot_update)[length(snapshot_update)] <- snapshot_name |
205 | -133x | +! |
- dataname = dataname,+ snapshot_history(snapshot_update) |
206 | -133x | +! |
- obs = if (!is.null(initial_data)) {+ removeModal() |
207 | -124x | +
- sprintf("%s/%s", nrow(current_data), nrow(initial_data))+ # Reopen filter manager modal by clicking button in the main application. |
|
208 | -+ | ! |
- } else {+ shinyjs::click(id = "teal-wunder_bar-show_snapshot_manager", asis = TRUE) |
209 | -9x | +
- nrow(current_data)+ } |
|
210 |
- }+ }) |
||
211 |
- )+ |
||
212 |
- } else {+ # Upload a snapshot file ---- |
||
213 | -13x | +
- data.frame(+ # Select file. |
|
214 | -13x | +82x |
- dataname = dataname,+ observeEvent(input$snapshot_load, { |
215 | -13x | +! |
- obs = if (!is.null(initial_data)) {+ logger::log_debug("srv_snapshot_manager: snapshot_load button clicked") |
216 | -13x | +! |
- sprintf("%s/%s", nrow(current_data), nrow(initial_data))+ showModal( |
217 | -+ | ! |
- } else {+ modalDialog( |
218 | ! |
- nrow(current_data)+ fileInput(ns("snapshot_file"), "Choose snapshot file", accept = ".json", width = "100%"), |
|
219 | -+ | ! |
- },+ textInput( |
220 | -13x | +! |
- subjects = if (!is.null(initial_data)) {+ ns("snapshot_name"), |
221 | -13x | +! |
- sprintf("%s/%s", nrow(unique(current_data[subject_keys])), nrow(unique(initial_data[subject_keys])))+ "Name the snapshot (optional)", |
222 | -+ | ! |
- } else {+ width = "100%", |
223 | ! |
- nrow(unique(current_data[subject_keys]))+ placeholder = "Meaningful, unique name" |
|
224 |
- }+ ), |
||
225 | -+ | ! |
- )+ footer = tagList( |
226 | -+ | ! |
- }+ actionButton(ns("snaphot_file_accept"), "Accept", icon = icon("far fa-thumbs-up")), |
227 | -+ | ! |
- }+ modalButton(label = "Cancel", icon = icon("far fa-thumbs-down")) |
228 |
-
+ ) |
||
229 |
- #' @rdname module_data_summary+ ) |
||
230 |
- get_filter_overview_MultiAssayExperiment <- function(current_data, # nolint: object_length, object_name.+ ) |
||
231 |
- initial_data,+ }) |
||
232 |
- dataname) {+ # Store new snapshot to list and restore filter states. |
||
233 | -1x | +82x |
- experiment_names <- names(current_data)+ observeEvent(input$snaphot_file_accept, { |
234 | -1x | +! |
- mae_info <- data.frame(+ logger::log_debug("srv_snapshot_manager: snapshot_file_accept button clicked") |
235 | -1x | +! |
- dataname = dataname,+ snapshot_name <- trimws(input$snapshot_name) |
236 | -1x | +! |
- subjects = if (!is.null(initial_data)) {+ if (identical(snapshot_name, "")) { |
237 | ! |
- sprintf("%s/%s", nrow(current_data@colData), nrow(initial_data@colData))+ logger::log_debug("srv_snapshot_manager: no snapshot name provided, naming after file") |
|
238 | -+ | ! |
- } else {+ snapshot_name <- tools::file_path_sans_ext(input$snapshot_file$name) |
239 | -1x | +
- nrow(current_data@colData)+ } |
|
240 | -+ | ! |
- }+ if (is.element(make.names(snapshot_name), make.names(names(snapshot_history())))) { |
241 | -+ | ! |
- )+ logger::log_debug("srv_snapshot_manager: snapshot name rejected") |
242 | -+ | ! |
-
+ showNotification( |
243 | -1x | +! |
- experiment_obs_info <- do.call("rbind", lapply(+ "This name is in conflict with other snapshot names. Please choose a different one.", |
244 | -1x | +! |
- experiment_names,+ type = "message" |
245 | -1x | +
- function(experiment_name) {+ ) |
|
246 | -5x | +! |
- transform(+ updateTextInput(inputId = "snapshot_name", value = "", placeholder = "Meaningful, unique name") |
247 | -5x | +
- get_filter_overview(+ } else { |
|
248 | -5x | +
- current_data[[experiment_name]],+ # Restore snapshot and verify app compatibility. |
|
249 | -5x | +! |
- initial_data[[experiment_name]],+ logger::log_debug("srv_snapshot_manager: snapshot name accepted, loading snapshot") |
250 | -5x | +! |
- dataname = experiment_name,+ snapshot_state <- try(slices_restore(input$snapshot_file$datapath)) |
251 | -5x | +! |
- subject_keys = join_keys() # empty join keys+ if (!inherits(snapshot_state, "modules_teal_slices")) { |
252 | -+ | ! |
- ),+ logger::log_debug("srv_snapshot_manager: snapshot file corrupt") |
253 | -5x | +! |
- dataname = paste0(" - ", experiment_name)+ showNotification( |
254 | -+ | ! |
- )+ "File appears to be corrupt.", |
255 | -+ | ! |
- }+ type = "error" |
256 |
- ))+ ) |
||
257 | -+ | ! |
-
+ } else if (!identical(attr(snapshot_state, "app_id"), attr(slices_global$all_slices(), "app_id"))) { |
258 | -1x | +! |
- get_experiment_keys <- function(mae, experiment) {+ logger::log_debug("srv_snapshot_manager: snapshot not compatible with app") |
259 | -5x | +! |
- sample_subset <- mae@sampleMap[mae@sampleMap$colname %in% colnames(experiment), ]+ showNotification( |
260 | -5x | +! |
- length(unique(sample_subset$primary))+ "This snapshot file is not compatible with the app and cannot be loaded.", |
261 | -+ | ! |
- }+ type = "warning" |
262 |
-
+ ) |
||
263 | -1x | +
- experiment_subjects_info <- do.call("rbind", lapply(+ } else { |
|
264 | -1x | +
- experiment_names,+ # Add to snapshot history. |
|
265 | -1x | +! |
- function(experiment_name) {+ logger::log_debug("srv_snapshot_manager: snapshot loaded, adding to history") |
266 | -5x | +! |
- data.frame(+ snapshot <- as.list(slices_global$all_slices(), recursive = TRUE) |
267 | -5x | +! |
- subjects = if (!is.null(initial_data)) {+ snapshot_update <- c(snapshot_history(), list(snapshot)) |
268 | ! |
- sprintf(+ names(snapshot_update)[length(snapshot_update)] <- snapshot_name |
|
269 | ! |
- "%s/%s",+ snapshot_history(snapshot_update) |
|
270 | -! | +
- get_experiment_keys(current_data, current_data[[experiment_name]]),+ ### Begin simplified restore procedure. ### |
|
271 | ! |
- get_experiment_keys(current_data, initial_data[[experiment_name]])+ logger::log_debug("srv_snapshot_manager: restoring snapshot") |
|
272 | -+ | ! |
- )+ slices_global$slices_set(snapshot_state) |
273 | -+ | ! |
- } else {+ removeModal() |
274 | -5x | +
- get_experiment_keys(current_data, current_data[[experiment_name]])+ ### End simplified restore procedure. ### |
|
276 |
- )+ } |
||
277 |
- }+ }) |
||
278 |
- ))+ # Apply newly added snapshot. |
||
280 | -1x | +
- experiment_info <- cbind(experiment_obs_info, experiment_subjects_info)+ # Restore initial state ---- |
|
281 | -1x | +82x |
- .smart_rbind(mae_info, experiment_info)+ observeEvent(input$snapshot_reset, { |
282 | -+ | 2x |
- }+ logger::log_debug("srv_snapshot_manager: snapshot_reset button clicked, restoring snapshot") |
1 | -+ | |||
283 | +2x |
- #' `teal_data` utils+ s <- "Initial application state" |
||
2 | +284 |
- #'+ ### Begin restore procedure. ### |
||
3 | -+ | |||
285 | +2x |
- #' In `teal` we need to recreate the `teal_data` object due to two operations:+ snapshot <- snapshot_history()[[s]] |
||
4 | +286 |
- #' - we need to append filter-data code and objects which have been evaluated in `FilteredData` and+ # todo: as.teal_slices looses module-mapping if is not global |
||
5 | -+ | |||
287 | +2x |
- #' we want to avoid double-evaluation.+ snapshot_state <- as.teal_slices(snapshot) |
||
6 | -+ | |||
288 | +2x |
- #' - we need to subset `teal_data` to `datanames` used by the module, to shorten obtainable R-code+ slices_global$slices_set(snapshot_state) |
||
7 | -+ | |||
289 | +2x |
- #'+ removeModal() |
||
8 | +290 |
- #' Due to above recreation of `teal_data` object can't be done simply by using public+ ### End restore procedure. ### |
||
9 | +291 |
- #' `teal.code` and `teal.data` methods.+ }) |
||
10 | +292 |
- #'+ |
||
11 | +293 |
- #' @param data (`teal_data`)+ # Build snapshot table ---- |
||
12 | +294 |
- #' @param code (`character`) code to append to `data@code`+ # Create UI elements and server logic for the snapshot table. |
||
13 | +295 |
- #' @param objects (`list`) objects to append to `data@env`+ # Observers must be tracked to avoid duplication and excess reactivity. |
||
14 | +296 |
- #' @param datanames (`character`) names of the datasets+ # Remaining elements are tracked likewise for consistency and a slight speed margin. |
||
15 | -+ | |||
297 | +82x |
- #' @return modified `teal_data`+ observers <- reactiveValues() |
||
16 | -+ | |||
298 | +82x |
- #' @keywords internal+ handlers <- reactiveValues() |
||
17 | -+ | |||
299 | +82x |
- #' @name teal_data_utilities+ divs <- reactiveValues() |
||
18 | +300 |
- NULL+ + |
+ ||
301 | +82x | +
+ observeEvent(snapshot_history(), {+ |
+ ||
302 | +72x | +
+ logger::log_debug("srv_snapshot_manager: snapshot history modified, updating snapshot list")+ |
+ ||
303 | +72x | +
+ lapply(names(snapshot_history())[-1L], function(s) {+ |
+ ||
304 | +! | +
+ id_pickme <- sprintf("pickme_%s", make.names(s))+ |
+ ||
305 | +! | +
+ id_saveme <- sprintf("saveme_%s", make.names(s))+ |
+ ||
306 | +! | +
+ id_rowme <- sprintf("rowme_%s", make.names(s)) |
||
19 | +307 | |||
20 | +308 |
- #' @rdname teal_data_utilities+ # Observer for restoring snapshot. |
||
21 | -+ | |||
309 | +! |
- .append_evaluated_code <- function(data, code) {+ if (!is.element(id_pickme, names(observers))) { |
||
22 | -84x | +|||
310 | +! |
- checkmate::assert_class(data, "teal_data")+ observers[[id_pickme]] <- observeEvent(input[[id_pickme]], { |
||
23 | -84x | +|||
311 | +
- data@code <- c(data@code, code)+ ### Begin restore procedure. ### |
|||
24 | -84x | +|||
312 | +! |
- data@id <- c(data@id, max(data@id) + 1L + seq_along(code))+ snapshot <- snapshot_history()[[s]] |
||
25 | -84x | +|||
313 | +! |
- data@messages <- c(data@messages, rep("", length(code)))+ snapshot_state <- as.teal_slices(snapshot) |
||
26 | -84x | +|||
314 | +
- data@warnings <- c(data@warnings, rep("", length(code)))+ |
|||
27 | -84x | +|||
315 | +! |
- methods::validObject(data)+ slices_global$slices_set(snapshot_state) |
||
28 | -84x | +|||
316 | +! |
- data+ removeModal() |
||
29 | +317 |
- }+ ### End restore procedure. ### |
||
30 | +318 |
-
+ }) |
||
31 | +319 |
- #' @rdname teal_data_utilities+ } |
||
32 | +320 |
- .append_modified_data <- function(data, objects) {+ # Create handler for downloading snapshot. |
||
33 | -84x | +|||
321 | +! |
- checkmate::assert_class(data, "teal_data")+ if (!is.element(id_saveme, names(handlers))) { |
||
34 | -84x | +|||
322 | +! |
- checkmate::assert_class(objects, "list")+ output[[id_saveme]] <- downloadHandler( |
||
35 | -84x | +|||
323 | +! |
- new_env <- list2env(objects, parent = .GlobalEnv)+ filename = function() { |
||
36 | -84x | +|||
324 | +! |
- rlang::env_coalesce(new_env, teal.code::get_env(data))+ sprintf("teal_snapshot_%s_%s.json", s, Sys.Date()) |
||
37 | -84x | +|||
325 | +
- data@env <- new_env+ }, |
|||
38 | -84x | +|||
326 | +! |
- data+ content = function(file) {+ |
+ ||
327 | +! | +
+ snapshot <- snapshot_history()[[s]]+ |
+ ||
328 | +! | +
+ snapshot_state <- as.teal_slices(snapshot)+ |
+ ||
329 | +! | +
+ slices_store(tss = snapshot_state, file = file) |
||
39 | +330 |
- }+ } |
||
40 | +331 |
-
+ )+ |
+ ||
332 | +! | +
+ handlers[[id_saveme]] <- id_saveme |
||
41 | +333 |
- #' @rdname teal_data_utilities+ } |
||
42 | +334 |
- .subset_teal_data <- function(data, datanames) {+ # Create a row for the snapshot table. |
||
43 | -83x | +|||
335 | +! |
- checkmate::assert_class(data, "teal_data")+ if (!is.element(id_rowme, names(divs))) { |
||
44 | -83x | +|||
336 | +! |
- checkmate::assert_class(datanames, "character")+ divs[[id_rowme]] <- tags$div( |
||
45 | -83x | +|||
337 | +! |
- datanames_corrected <- intersect(datanames, ls(teal.code::get_env(data)))+ class = "manager_table_row", |
||
46 | -83x | +|||
338 | +! |
- datanames_corrected_with_raw <- c(datanames_corrected, ".raw_data")+ tags$span(tags$h5(s)), |
||
47 | -83x | +|||
339 | +! |
- if (!length(datanames_corrected)) {+ actionLink(inputId = ns(id_pickme), label = icon("far fa-circle-check"), title = "select"), |
||
48 | -2x | +|||
340 | +! |
- return(teal_data())+ downloadLink(outputId = ns(id_saveme), label = icon("far fa-save"), title = "save to file") |
||
49 | +341 |
- }+ ) |
||
50 | +342 | ++ |
+ }+ |
+ |
343 | ++ |
+ })+ |
+ ||
344 | ++ |
+ })+ |
+ ||
345 | ||||
346 | ++ |
+ # Create table to display list of snapshots and their actions.+ |
+ ||
51 | -81x | +347 | +82x |
- new_data <- do.call(+ output$snapshot_list <- renderUI({ |
52 | -81x | +348 | +72x |
- teal.data::teal_data,+ rows <- rev(reactiveValuesToList(divs)) |
53 | -81x | +349 | +72x |
- args = c(+ if (length(rows) == 0L) { |
54 | -81x | +350 | +72x |
- mget(x = datanames_corrected_with_raw, envir = teal.code::get_env(data)),+ tags$div( |
55 | -81x | +351 | +72x |
- list(+ class = "manager_placeholder", |
56 | -81x | +352 | +72x |
- code = teal.code::get_code(data, names = datanames_corrected_with_raw),+ "Snapshots will appear here." |
57 | -81x | +|||
353 | +
- join_keys = teal.data::join_keys(data)[datanames_corrected]+ ) |
|||
58 | +354 |
- )+ } else {+ |
+ ||
355 | +! | +
+ rows |
||
59 | +356 |
- )+ } |
||
60 | +357 |
- )+ }) |
||
61 | -81x | +|||
358 | +
- new_data@verified <- data@verified+ |
|||
62 | -81x | +359 | +82x |
- teal.data::datanames(new_data) <- datanames_corrected+ snapshot_history |
63 | -81x | +|||
360 | +
- new_data+ }) |
|||
64 | +361 |
}@@ -22396,14 +23464,14 @@ teal coverage - 59.99% |
1 |
- #' App state management.+ #' `teal` main module |
|||
4 |
- #' `r lifecycle::badge("experimental")`+ #' `r lifecycle::badge("stable")` |
|||
5 |
- #'+ #' Module to create a `teal` app. This module can be called directly instead of [init()] and |
|||
6 |
- #' Capture and restore the global (app) input state.+ #' included in your custom application. Please note that [init()] adds `reporter_previewer_module` |
|||
7 |
- #'+ #' automatically, which is not a case when calling `ui/srv_teal` directly. |
|||
8 |
- #' @details+ #' |
|||
9 |
- #' This module introduces bookmarks into `teal` apps: the `shiny` bookmarking mechanism becomes enabled+ #' @details |
|||
10 |
- #' and server-side bookmarks can be created.+ #' |
|||
11 |
- #'+ #' Module is responsible for creating the main `shiny` app layout and initializing all the necessary |
|||
12 |
- #' The bookmark manager presents a button with the bookmark icon and is placed in the tab-bar.+ #' components. This module establishes reactive connection between the input `data` and every other |
|||
13 |
- #' When clicked, the button creates a bookmark and opens a modal which displays the bookmark URL.+ #' component in the app. Reactive change of the `data` passed as an argument, reloads the app and |
|||
14 |
- #'+ #' possibly keeps all input settings the same so the user can continue where one left off. |
|||
15 |
- #' `teal` does not guarantee that all modules (`teal_module` objects) are bookmarkable.+ #' |
|||
16 |
- #' Those that are, have a `teal_bookmarkable` attribute set to `TRUE`. If any modules are not bookmarkable,+ #' ## data flow in `teal` application |
|||
17 |
- #' the bookmark manager modal displays a warning and the bookmark button displays a flag.+ #' |
|||
18 |
- #' In order to communicate that a external module is bookmarkable, the module developer+ #' This module supports multiple data inputs but eventually, they are all converted to `reactive` |
|||
19 |
- #' should set the `teal_bookmarkable` attribute to `TRUE`.+ #' returning `teal_data` in this module. On this `reactive teal_data` object several actions are |
|||
20 |
- #'+ #' performed: |
|||
21 |
- #' @section Server logic:+ #' - data loading in [`module_init_data`] |
|||
22 |
- #' A bookmark is a URL that contains the app address with a `/?_state_id_=<bookmark_dir>` suffix.+ #' - data filtering in [`module_filter_data`] |
|||
23 |
- #' `<bookmark_dir>` is a directory created on the server, where the state of the application is saved.+ #' - data transformation in [`module_transform_data`] |
|||
24 |
- #' Accessing the bookmark URL opens a new session of the app that starts in the previously saved state.+ #' |
|||
25 |
- #'+ #' ## Fallback on failure |
|||
26 |
- #' @section Note:+ #' |
|||
27 |
- #' To enable bookmarking use either:+ #' `teal` is designed in such way that app will never crash if the error is introduced in any |
|||
28 |
- #' - `shiny` app by using `shinyApp(..., enableBookmarking = "server")` (not supported in `shinytest2`)+ #' custom `shiny` module provided by app developer (e.g. [teal_data_module()], [teal_transform_module()]). |
|||
29 |
- #' - set `options(shiny.bookmarkStore = "server")` before running the app+ #' If any module returns a failing object, the app will halt the evaluation and display a warning message. |
|||
30 |
- #'+ #' App user should always have a chance to fix the improper input and continue without restarting the session. |
|||
32 |
- #' @inheritParams init+ #' @rdname module_teal |
|||
33 |
- #'+ #' @name module_teal |
|||
34 |
- #' @return Invisible `NULL`.+ #' |
|||
35 |
- #'+ #' @inheritParams module_init_data |
|||
36 |
- #' @aliases bookmark bookmark_manager bookmark_manager_module+ #' @inheritParams init |
|||
38 |
- #' @name module_bookmark_manager+ #' @return `NULL` invisibly |
|||
39 |
- #' @rdname module_bookmark_manager+ NULL |
|||
40 |
- #'+ |
|||
41 |
- #' @keywords internal+ #' @rdname module_teal |
|||
42 |
- #'+ #' @export |
|||
43 |
- NULL+ ui_teal <- function(id, |
|||
44 |
-
+ modules, |
|||
45 |
- #' @rdname module_bookmark_manager+ title = build_app_title(), |
|||
46 |
- ui_bookmark_panel <- function(id, modules) {+ header = tags$p(), |
|||
47 | -! | +
- ns <- NS(id)+ footer = tags$p()) { |
||
48 | -+ | ! |
-
+ checkmate::assert_character(id, max.len = 1, any.missing = FALSE) |
|
49 | ! |
- bookmark_option <- get_bookmarking_option()+ checkmate::assert( |
||
50 | ! |
- is_unbookmarkable <- need_bookmarking(modules)+ .var.name = "title", |
||
51 | ! |
- shinyOptions(bookmarkStore = bookmark_option)+ checkmate::check_string(title), |
||
52 | -+ | ! |
-
+ checkmate::check_multi_class(title, c("shiny.tag", "shiny.tag.list", "html")) |
|
53 |
- # Render bookmark warnings count+ ) |
|||
54 | ! |
- if (!all(is_unbookmarkable) && identical(bookmark_option, "server")) {- |
- ||
55 | -! | -
- tags$button(- |
- ||
56 | -! | -
- id = ns("do_bookmark"),- |
- ||
57 | -! | -
- class = "btn action-button wunder_bar_button bookmark_manager_button",- |
- ||
58 | -! | -
- title = "Add bookmark",- |
- ||
59 | -! | -
- tags$span(- |
- ||
60 | -! | -
- suppressMessages(icon("fas fa-bookmark")),- |
- ||
61 | -! | -
- if (any(is_unbookmarkable)) {- |
- ||
62 | -! | -
- tags$span(- |
- ||
63 | -! | -
- sum(is_unbookmarkable),- |
- ||
64 | -! | -
- class = "badge-warning badge-count text-white bg-danger"- |
- ||
65 | -- |
- )- |
- ||
66 | -- |
- }- |
- ||
67 | -- |
- )- |
- ||
68 | -- |
- )- |
- ||
69 | -- |
- }- |
- ||
70 | -- |
- }- |
- ||
71 | -- | - - | -||
72 | -- |
- #' @rdname module_bookmark_manager- |
- ||
73 | -- |
- srv_bookmark_panel <- function(id, modules) {- |
- ||
74 | -82x | -
- checkmate::assert_character(id)- |
- ||
75 | -82x | -
- checkmate::assert_class(modules, "teal_modules")- |
- ||
76 | -82x | -
- moduleServer(id, function(input, output, session) {- |
- ||
77 | -82x | -
- logger::log_debug("bookmark_manager_srv initializing")- |
- ||
78 | -82x | -
- ns <- session$ns- |
- ||
79 | -82x | -
- bookmark_option <- get_bookmarking_option()- |
- ||
80 | -82x | -
- is_unbookmarkable <- need_bookmarking(modules)- |
- ||
81 | -- | - - | -||
82 | -- |
- # Set up bookmarking callbacks ----- |
- ||
83 | -- |
- # 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 | -! | -
- logger::log_debug("bookmark_manager_srv@onBookmarked: bookmark button clicked, registering bookmark")- |
- ||
89 | -! | -
- modal_content <- if (bookmark_option != "server") {- |
- ||
90 | -! | -
- msg <- sprintf(- |
- ||
91 | -! | -
- "Bookmarking has been set to \"%s\".\n%s\n%s",- |
- ||
92 | -! | -
- bookmark_option,- |
- ||
93 | -! | -
- "Only server-side bookmarking is supported.",- |
- ||
94 | -! | -
- "Please contact your app developer."- |
- ||
95 | -- |
- )- |
- ||
96 | -! | -
- tags$div(- |
- ||
97 | -! | -
- tags$p(msg, class = "text-warning")- |
- ||
98 | -- |
- )- |
- ||
99 | -- |
- } else {+ checkmate::assert( |
||
100 | +55 | ! |
- tags$div(+ .var.name = "header", |
|
101 | +56 | ! |
- tags$span(+ checkmate::check_string(header), |
|
102 | +57 | ! |
- tags$pre(url)+ checkmate::check_multi_class(header, c("shiny.tag", "shiny.tag.list", "html")) |
|
103 | +58 |
- ),+ ) |
||
104 | +59 | ! |
- if (any(is_unbookmarkable)) {+ checkmate::assert( |
|
105 | +60 | ! |
- bkmb_summary <- rapply2(+ .var.name = "footer", |
|
106 | +61 | ! |
- modules_bookmarkable(modules),+ checkmate::check_string(footer), |
|
107 | +62 | ! |
- function(x) {+ checkmate::check_multi_class(footer, c("shiny.tag", "shiny.tag.list", "html")) |
|
108 | -! | +|||
63 | +
- if (isTRUE(x)) {+ ) |
|||
109 | -! | +|||
64 | +
- "\u2705" # check mark+ |
|||
110 | +65 | ! |
- } else if (isFALSE(x)) {+ if (is.character(title)) { |
|
111 | +66 | ! |
- "\u274C" # cross mark+ title <- build_app_title(title) |
|
112 | +67 |
- } else {+ } else { |
||
113 | +68 | ! |
- "\u2753" # question mark- |
- |
114 | -- |
- }+ validate_app_title_tag(title) |
||
115 | +69 |
- }+ } |
||
116 | +70 |
- )- |
- ||
117 | -! | -
- tags$div(+ |
||
118 | +71 | ! |
- tags$p(+ if (checkmate::test_string(header)) { |
|
119 | +72 | ! |
- icon("fas fa-exclamation-triangle"),+ header <- tags$p(header) |
|
120 | -! | +|||
73 | +
- "Some modules will not be restored when using this bookmark.",+ } |
|||
121 | -! | +|||
74 | +
- tags$br(),+ |
|||
122 | +75 | ! |
- "Check the list below to see which modules are not bookmarkable.",+ if (checkmate::test_string(footer)) { |
|
123 | +76 | ! |
- class = "text-warning"+ footer <- tags$p(footer) |
|
124 | +77 |
- ),- |
- ||
125 | -! | -
- tags$pre(yaml::as.yaml(bkmb_summary))+ } |
||
126 | +78 |
- )+ |
||
127 | -+ | |||
79 | +! |
- }+ ns <- NS(id) |
||
128 | +80 |
- )+ |
||
129 | +81 |
- }+ # show busy icon when `shiny` session is busy computing stuff |
||
130 | +82 |
-
+ # based on https://stackoverflow.com/questions/17325521/r-shiny-display-loading-message-while-function-is-running/22475216#22475216 # nolint: line_length. |
||
131 | +83 | ! |
- showModal(+ shiny_busy_message_panel <- conditionalPanel( |
|
132 | +84 | ! |
- modalDialog(+ condition = "(($('html').hasClass('shiny-busy')) && (document.getElementById('shiny-notification-panel') == null))", # nolint: line_length. |
|
133 | +85 | ! |
- id = ns("bookmark_modal"),+ tags$div( |
|
134 | +86 | ! |
- title = "Bookmarked teal app url",+ icon("arrows-rotate", class = "fa-spin", prefer_type = "solid"), |
|
135 | +87 | ! |
- modal_content,+ "Computing ...", |
|
136 | -! | +|||
88 | +
- easyClose = TRUE+ # CSS defined in `custom.css` |
|||
137 | -+ | |||
89 | +! |
- )+ class = "shinybusymessage" |
||
138 | +90 |
- )+ ) |
||
139 | +91 |
- })+ ) |
||
140 | +92 | |||
141 | -+ | |||
93 | +! |
- # manually trigger bookmarking because of the problems reported on windows with bookmarkButton in teal+ fluidPage( |
||
142 | -82x | +|||
94 | +! |
- observeEvent(input$do_bookmark, {+ id = id, |
||
143 | +95 | ! |
- logger::log_debug("bookmark_manager_srv@1 do_bookmark module clicked.")+ title = title, |
|
144 | +96 | ! |
- session$doBookmark()+ theme = get_teal_bs_theme(), |
|
145 | -+ | |||
97 | +! |
- })+ include_teal_css_js(), |
||
146 | -+ | |||
98 | +! |
-
+ tags$header(header), |
||
147 | -82x | +|||
99 | +! |
- invisible(NULL)+ tags$hr(class = "my-2"), |
||
148 | -+ | |||
100 | +! |
- })+ shiny_busy_message_panel, |
||
149 | -+ | |||
101 | +! |
- }+ tags$div( |
||
150 | -+ | |||
102 | +! |
-
+ id = ns("tabpanel_wrapper"), |
||
151 | -+ | |||
103 | +! |
-
+ class = "teal-body", |
||
152 | -+ | |||
104 | +! |
- #' @rdname module_bookmark_manager+ ui_teal_module(id = ns("teal_modules"), modules = modules) |
||
153 | +105 |
- get_bookmarking_option <- function() {+ ), |
||
154 | -82x | +|||
106 | +! |
- bookmark_option <- getShinyOption("bookmarkStore")+ tags$div( |
||
155 | -82x | +|||
107 | +! |
- if (is.null(bookmark_option) && identical(getOption("shiny.bookmarkStore"), "server")) {+ id = ns("options_buttons"), |
||
156 | +108 | ! |
- bookmark_option <- getOption("shiny.bookmarkStore")+ style = "position: absolute; right: 10px;", |
|
157 | -+ | |||
109 | +! |
- }+ ui_bookmark_panel(ns("bookmark_manager"), modules), |
||
158 | -82x | +|||
110 | +! |
- bookmark_option+ tags$button( |
||
159 | -+ | |||
111 | +! |
- }+ class = "btn action-button filter_hamburger", # see sidebar.css for style filter_hamburger |
||
160 | -+ | |||
112 | +! |
-
+ href = "javascript:void(0)", |
||
161 | -+ | |||
113 | +! |
- #' @rdname module_bookmark_manager+ onclick = sprintf("toggleFilterPanel('%s');", ns("tabpanel_wrapper")), |
||
162 | -+ | |||
114 | +! |
- need_bookmarking <- function(modules) {+ title = "Toggle filter panel", |
||
163 | -82x | +|||
115 | +! |
- unlist(rapply2(+ icon("fas fa-bars") |
||
164 | -82x | +|||
116 | +
- modules_bookmarkable(modules),+ ), |
|||
165 | -82x | +|||
117 | +! |
- Negate(isTRUE)+ ui_snapshot_manager_panel(ns("snapshot_manager_panel")), |
||
166 | -+ | |||
118 | +! |
- ))+ ui_filter_manager_panel(ns("filter_manager_panel")) |
||
167 | +119 |
- }+ ), |
||
168 | -+ | |||
120 | +! |
-
+ tags$script( |
||
169 | -+ | |||
121 | +! |
-
+ HTML( |
||
170 | -+ | |||
122 | +! |
- # utilities ----+ sprintf( |
||
171 | +123 |
-
+ " |
||
172 | -+ | |||
124 | +! |
- #' Restore value from bookmark.+ $(document).ready(function() { |
||
173 | -+ | |||
125 | +! |
- #'+ $('#%s').appendTo('#%s'); |
||
174 | +126 |
- #' Get value from bookmark or return default.+ }); |
||
175 | +127 |
- #'+ ", |
||
176 | -+ | |||
128 | +! |
- #' Bookmarks can store not only inputs but also arbitrary values.+ ns("options_buttons"), |
||
177 | -+ | |||
129 | +! |
- #' These values are stored by `onBookmark` callbacks and restored by `onBookmarked` callbacks,+ ns("teal_modules-active_tab") |
||
178 | +130 |
- #' and they are placed in the `values` environment in the `session$restoreContext` field.+ ) |
||
179 | +131 |
- #' Using `teal_data_module` makes it impossible to run the callbacks+ ) |
||
180 | +132 |
- #' because the app becomes ready before modules execute and callbacks are registered.+ ), |
||
181 | -+ | |||
133 | +! |
- #' In those cases the stored values can still be recovered from the `session` object directly.+ tags$hr(), |
||
182 | -+ | |||
134 | +! |
- #'+ tags$footer( |
||
183 | -+ | |||
135 | +! |
- #' Note that variable names in the `values` environment are prefixed with module name space names,+ tags$div( |
||
184 | -+ | |||
136 | +! |
- #' therefore, when using this function in modules, `value` must be run through the name space function.+ footer, |
||
185 | -+ | |||
137 | +! |
- #'+ teal.widgets::verbatim_popup_ui(ns("sessionInfo"), "Session Info", type = "link"), |
||
186 | -+ | |||
138 | +! |
- #' @param value (`character(1)`) name of value to restore+ br(), |
||
187 | -+ | |||
139 | +! |
- #' @param default fallback value+ ui_teal_lockfile(ns("lockfile")), |
||
188 | -+ | |||
140 | +! |
- #'+ textOutput(ns("identifier")) |
||
189 | +141 |
- #' @return+ ) |
||
190 | +142 |
- #' In an application restored from a server-side bookmark,+ ) |
||
191 | +143 |
- #' the variable specified by `value` from the `values` environment.+ ) |
||
192 | +144 |
- #' Otherwise `default`.+ } |
||
193 | +145 |
- #'+ |
||
194 | +146 |
- #' @keywords internal+ #' @rdname module_teal |
||
195 | +147 |
- #'+ #' @export |
||
196 | +148 |
- restoreValue <- function(value, default) { # nolint: object_name.+ srv_teal <- function(id, data, modules, filter = teal_slices()) { |
||
197 | -164x | +149 | +84x |
- checkmate::assert_character("value")+ checkmate::assert_character(id, max.len = 1, any.missing = FALSE) |
198 | -164x | +150 | +84x |
- session_default <- shiny::getDefaultReactiveDomain()+ checkmate::assert_multi_class(data, c("teal_data", "teal_data_module", "reactive")) |
199 | -164x | +151 | +83x |
- session_parent <- .subset2(session_default, "parent")+ checkmate::assert_class(modules, "teal_modules") |
200 | -164x | +152 | +83x |
- session <- if (is.null(session_parent)) session_default else session_parent+ checkmate::assert_class(filter, "teal_slices") |
201 | +153 | |||
202 | -164x | +154 | +83x |
- if (isTRUE(session$restoreContext$active) && exists(value, session$restoreContext$values, inherits = FALSE)) {+ moduleServer(id, function(input, output, session) { |
203 | -! | +|||
155 | +83x |
- session$restoreContext$values[[value]]+ logger::log_debug("srv_teal initializing.") |
||
204 | +156 |
- } else {+ |
||
205 | -164x | +157 | +83x |
- default+ if (getOption("teal.show_js_log", default = FALSE)) { |
206 | -+ | |||
158 | +! |
- }+ shinyjs::showLog() |
||
207 | +159 |
- }+ } |
||
208 | +160 | |||
209 | -+ | |||
161 | +83x |
- #' Compare bookmarks.+ srv_teal_lockfile("lockfile") |
||
210 | +162 |
- #'+ |
||
211 | -+ | |||
163 | +83x |
- #' Test if two bookmarks store identical state.+ output$identifier <- renderText( |
||
212 | -+ | |||
164 | +83x |
- #'+ paste0("Pid:", Sys.getpid(), " Token:", substr(session$token, 25, 32)) |
||
213 | +165 |
- #' `input` environments are compared one variable at a time and if not identical,+ ) |
||
214 | +166 |
- #' values in both bookmarks are reported. States of `datatable`s are stripped+ |
||
215 | -+ | |||
167 | +83x |
- #' of the `time` element before comparing because the time stamp is always different.+ teal.widgets::verbatim_popup_srv( |
||
216 | -+ | |||
168 | +83x |
- #' The contents themselves are not printed as they are large and the contents are not informative.+ "sessionInfo", |
||
217 | -+ | |||
169 | +83x |
- #' Elements present in one bookmark and absent in the other are also reported.+ verbatim_content = utils::capture.output(utils::sessionInfo()), |
||
218 | -+ | |||
170 | +83x |
- #' Differences are printed as messages.+ title = "SessionInfo" |
||
219 | +171 |
- #'+ ) |
||
220 | +172 |
- #' `values` environments are compared with `all.equal`.+ |
||
221 | +173 |
- #'+ # `JavaScript` code |
||
222 | -+ | |||
174 | +83x |
- #' @section How to use:+ run_js_files(files = "init.js") |
||
223 | +175 |
- #' Open an application, change relevant inputs (typically, all of them), and create a bookmark.+ |
||
224 | +176 |
- #' Then open that bookmark and immediately create a bookmark of that.+ # set timezone in shiny app |
||
225 | +177 |
- #' If restoring bookmarks occurred properly, the two bookmarks should store the same state.+ # timezone is set in the early beginning so it will be available also |
||
226 | +178 |
- #'+ # for `DDL` and all shiny modules |
||
227 | -+ | |||
179 | +83x |
- #'+ get_client_timezone(session$ns) |
||
228 | -+ | |||
180 | +83x |
- #' @param book1,book2 bookmark directories stored in `shiny_bookmarks/`;+ observeEvent( |
||
229 | -+ | |||
181 | +83x |
- #' default to the two most recently modified directories+ eventExpr = input$timezone, |
||
230 | -+ | |||
182 | +83x |
- #'+ once = TRUE, |
||
231 | -+ | |||
183 | +83x |
- #' @return+ handlerExpr = { |
||
232 | -+ | |||
184 | +! |
- #' Invisible `NULL` if bookmarks are identical or if there are no bookmarks to test.+ session$userData$timezone <- input$timezone |
||
233 | -+ | |||
185 | +! |
- #' `FALSE` if inconsistencies are detected.+ logger::log_debug("srv_teal@1 Timezone set to client's timezone: { input$timezone }.") |
||
234 | +186 |
- #'+ } |
||
235 | +187 |
- #' @keywords internal+ ) |
||
236 | +188 |
- #'+ |
||
237 | -+ | |||
189 | +83x |
- bookmarks_identical <- function(book1, book2) {+ data_pulled <- srv_init_data("data", data = data) |
||
238 | -! | +|||
190 | +82x |
- if (!dir.exists("shiny_bookmarks")) {+ data_validated <- srv_validate_reactive_teal_data( |
||
239 | -! | +|||
191 | +82x |
- message("no bookmark directory")+ "validate", |
||
240 | -! | +|||
192 | +82x |
- return(invisible(NULL))+ data = data_pulled, |
||
241 | -+ | |||
193 | +82x |
- }+ modules = modules,+ |
+ ||
194 | +82x | +
+ validate_shiny_silent_error = FALSE |
||
242 | +195 |
-
+ ) |
||
243 | -! | +|||
196 | +82x |
- ans <- TRUE+ data_rv <- reactive({ |
||
244 | -+ | |||
197 | +142x |
-
+ req(inherits(data_validated(), "teal_data")) |
||
245 | -! | +|||
198 | +70x |
- if (missing(book1) && missing(book2)) {+ is_filter_ok <- check_filter_datanames(filter, ls(teal.code::get_env(data_validated()))) |
||
246 | -! | +|||
199 | +70x |
- dirs <- list.dirs("shiny_bookmarks", recursive = FALSE)+ if (!isTRUE(is_filter_ok)) { |
||
247 | -! | +|||
200 | +2x |
- bookmarks_sorted <- basename(rev(dirs[order(file.mtime(dirs))]))+ showNotification( |
||
248 | -! | +|||
201 | +2x |
- if (length(bookmarks_sorted) < 2L) {+ "Some filters were not applied because of incompatibility with data. Contact app developer.", |
||
249 | -! | +|||
202 | +2x |
- message("no bookmarks to compare")+ type = "warning", |
||
250 | -! | +|||
203 | +2x |
- return(invisible(NULL))+ duration = 10 |
||
251 | +204 |
- }- |
- ||
252 | -! | -
- book1 <- bookmarks_sorted[2L]+ ) |
||
253 | -! | +|||
205 | +2x |
- book2 <- bookmarks_sorted[1L]+ warning(is_filter_ok) |
||
254 | +206 |
- } else {- |
- ||
255 | -! | -
- if (!dir.exists(file.path("shiny_bookmarks", book1))) stop(book1, " not found")+ } |
||
256 | -! | +|||
207 | +70x |
- if (!dir.exists(file.path("shiny_bookmarks", book2))) stop(book2, " not found")+ .add_signature_to_data(data_validated()) |
||
257 | +208 |
- }+ }) |
||
258 | +209 | |||
259 | -! | -
- book1_input <- readRDS(file.path("shiny_bookmarks", book1, "input.rds"))- |
- ||
260 | -! | +|||
210 | +82x |
- book2_input <- readRDS(file.path("shiny_bookmarks", book2, "input.rds"))+ data_load_status <- reactive({ |
||
261 | -+ | |||
211 | +75x |
-
+ if (inherits(data_pulled(), "teal_data")) { |
||
262 | -! | +|||
212 | +70x |
- elements_common <- intersect(names(book1_input), names(book2_input))+ "ok" |
||
263 | -! | +|||
213 | +
- dt_states <- grepl("_state$", elements_common)+ # todo: should we hide warnings on top for a data? |
|||
264 | -! | +|||
214 | +5x |
- if (any(dt_states)) {+ } else if (inherits(data, "teal_data_module")) { |
||
265 | -! | +|||
215 | +5x |
- for (el in elements_common[dt_states]) {+ "teal_data_module failed" |
||
266 | -! | +|||
216 | +
- book1_input[[el]][["time"]] <- NULL+ } else { |
|||
267 | +217 | ! |
- book2_input[[el]][["time"]] <- NULL+ "external failed" |
|
268 | +218 |
- }+ } |
||
269 | +219 |
- }+ }) |
||
270 | +220 | |||
271 | -! | +|||
221 | +82x |
- identicals <- mapply(identical, book1_input[elements_common], book2_input[elements_common])+ datasets_rv <- if (!isTRUE(attr(filter, "module_specific"))) { |
||
272 | -! | +|||
222 | +71x |
- non_identicals <- names(identicals[!identicals])+ eventReactive(data_rv(), { |
||
273 | -! | +|||
223 | +61x |
- compares <- sprintf("$ %s:\t%s --- %s", non_identicals, book1_input[non_identicals], book2_input[non_identicals])+ req(inherits(data_rv(), "teal_data")) |
||
274 | -! | +|||
224 | +61x |
- if (length(compares) != 0L) {+ logger::log_debug("srv_teal@1 initializing FilteredData") |
||
275 | -! | +|||
225 | +61x |
- message("common elements not identical: \n", paste(compares, collapse = "\n"))+ teal_data_to_filtered_data(data_rv()) |
||
276 | -! | +|||
226 | +
- ans <- FALSE+ }) |
|||
277 | +227 |
- }+ } |
||
278 | +228 | |||
279 | -! | +|||
229 | +82x |
- elements_boook1 <- setdiff(names(book1_input), names(book2_input))+ if (inherits(data, "teal_data_module")) { |
||
280 | -! | +|||
230 | +9x |
- if (length(elements_boook1) != 0L) {+ setBookmarkExclude(c("teal_modules-active_tab")) |
||
281 | -! | +|||
231 | +9x |
- dt_states <- grepl("_state$", elements_boook1)+ shiny::insertTab( |
||
282 | -! | +|||
232 | +9x |
- if (any(dt_states)) {+ inputId = "teal_modules-active_tab", |
||
283 | -! | +|||
233 | +9x |
- for (el in elements_boook1[dt_states]) {+ position = "before", |
||
284 | -! | +|||
234 | +9x |
- if (is.list(book1_input[[el]])) book1_input[[el]] <- "--- data table state ---"+ select = TRUE, |
||
285 | -+ | |||
235 | +9x |
- }+ tabPanel( |
||
286 | -+ | |||
236 | +9x |
- }+ title = icon("fas fa-database"), |
||
287 | -! | +|||
237 | +9x |
- excess1 <- sprintf("$ %s:\t%s", elements_boook1, book1_input[elements_boook1])+ value = "teal_data_module", |
||
288 | -! | +|||
238 | +9x |
- message("elements only in book1: \n", paste(excess1, collapse = "\n"))+ tags$div( |
||
289 | -! | +|||
239 | +9x |
- ans <- FALSE+ ui_init_data(session$ns("data")), |
||
290 | -+ | |||
240 | +9x |
- }+ ui_validate_reactive_teal_data(session$ns("validate")) |
||
291 | +241 |
-
+ ) |
||
292 | -! | +|||
242 | +
- elements_boook2 <- setdiff(names(book2_input), names(book1_input))+ ) |
|||
293 | -! | +|||
243 | +
- if (length(elements_boook2) != 0L) {+ ) |
|||
294 | -! | +|||
244 | +
- dt_states <- grepl("_state$", elements_boook1)+ |
|||
295 | -! | +|||
245 | +9x |
- if (any(dt_states)) {+ if (attr(data, "once")) { |
||
296 | -! | +|||
246 | +9x |
- for (el in elements_boook1[dt_states]) {+ observeEvent(data_rv(), once = TRUE, { |
||
297 | -! | +|||
247 | +4x |
- if (is.list(book2_input[[el]])) book2_input[[el]] <- "--- data table state ---"+ logger::log_debug("srv_teal@2 removing data tab.") |
||
298 | +248 |
- }+ # when once = TRUE we pull data once and then remove data tab |
||
299 | -+ | |||
249 | +4x |
- }+ removeTab("teal_modules-active_tab", target = "teal_data_module") |
||
300 | -! | +|||
250 | +
- excess2 <- sprintf("$ %s:\t%s", elements_boook2, book2_input[elements_boook2])+ }) |
|||
301 | -! | +|||
251 | +
- message("elements only in book2: \n", paste(excess2, collapse = "\n"))+ } |
|||
302 | -! | +|||
252 | +
- ans <- FALSE+ } else { |
|||
303 | +253 |
- }+ # when no teal_data_module then we want to display messages above tabsetPanel (because there is no data-tab) |
||
304 | -+ | |||
254 | +73x |
-
+ insertUI( |
||
305 | -! | +|||
255 | +73x |
- book1_values <- readRDS(file.path("shiny_bookmarks", book1, "values.rds"))+ selector = sprintf("#%s", session$ns("tabpanel_wrapper")), |
||
306 | -! | +|||
256 | +73x |
- book2_values <- readRDS(file.path("shiny_bookmarks", book2, "values.rds"))+ where = "beforeBegin", |
||
307 | -+ | |||
257 | +73x |
-
+ ui = tags$div(ui_validate_reactive_teal_data(session$ns("validate")), tags$br()) |
||
308 | -! | +|||
258 | +
- if (!isTRUE(all.equal(book1_values, book2_values))) {+ ) |
|||
309 | -! | +|||
259 | +
- message("different values detected")+ } |
|||
310 | -! | +|||
260 | +
- message("choices for numeric filters MAY be different, see RangeFilterState$set_choices")+ |
|||
311 | -! | +|||
261 | +82x |
- ans <- FALSE+ module_labels <- unlist(module_labels(modules), use.names = FALSE) |
||
312 | -+ | |||
262 | +82x |
- }+ slices_global <- methods::new(".slicesGlobal", filter, module_labels) |
||
313 | -+ | |||
263 | +82x |
-
+ modules_output <- srv_teal_module( |
||
314 | -! | +|||
264 | +82x |
- if (ans) message("perfect!")+ id = "teal_modules", |
||
315 | -! | +|||
265 | +82x |
- invisible(NULL)+ data_rv = data_rv, |
||
316 | -+ | |||
266 | +82x |
- }+ datasets = datasets_rv, |
||
317 | -+ | |||
267 | +82x |
-
+ modules = modules, |
||
318 | -+ | |||
268 | +82x |
-
+ slices_global = slices_global, |
||
319 | -+ | |||
269 | +82x |
- # Replacement for [base::rapply] which doesn't handle NULL values - skips the evaluation+ data_load_status = data_load_status |
||
320 | +270 |
- # of the function and returns NULL for given element.+ ) |
||
321 | -+ | |||
271 | +82x |
- rapply2 <- function(x, f) {+ mapping_table <- srv_filter_manager_panel("filter_manager_panel", slices_global = slices_global) |
||
322 | -189x | +272 | +82x |
- if (inherits(x, "list")) {+ snapshots <- srv_snapshot_manager_panel("snapshot_manager_panel", slices_global = slices_global) |
323 | +273 | 82x |
- lapply(x, rapply2, f = f)+ srv_bookmark_panel("bookmark_manager", modules) |
|
324 | +274 |
- } else {+ }) |
||
325 | -107x | +|||
275 | +
- f(x)+ |
|||
326 | -+ | |||
276 | +82x |
- }+ invisible(NULL) |
||
327 | +277 |
}@@ -24691,63 +25409,63 @@ teal coverage - 59.99% |
1 |
- #' Filter state snapshot management+ # This is the main function from teal to be used by the end-users. Although it delegates |
||
2 |
- #'+ # directly to `module_teal_with_splash.R`, we keep it in a separate file because its documentation is quite large |
||
3 |
- #' Capture and restore snapshots of the global (app) filter state.+ # and it is very end-user oriented. It may also perform more argument checking with more informative |
||
4 |
- #'+ # error messages. |
||
5 |
- #' This module introduces snapshots: stored descriptions of the filter state of the entire application.+ |
||
6 |
- #' Snapshots allow the user to save the current filter state of the application for later use in the session,+ #' Create the server and UI function for the `shiny` app |
||
7 |
- #' as well as to save it to file in order to share it with an app developer or other users,+ #' |
||
8 |
- #' who in turn can upload it to their own session.+ #' @description `r lifecycle::badge("stable")` |
||
10 |
- #' The snapshot manager is accessed with the camera icon in the tabset bar.+ #' End-users: This is the most important function for you to start a |
||
11 |
- #' At the beginning of a session it presents three icons: a camera, an upload, and an circular arrow.+ #' `teal` app that is composed of `teal` modules. |
||
12 |
- #' Clicking the camera captures a snapshot, clicking the upload adds a snapshot from a file+ #' |
||
13 |
- #' and applies the filter states therein, and clicking the arrow resets initial application state.+ #' @param data (`teal_data` or `teal_data_module`) |
||
14 |
- #' As snapshots are added, they will show up as rows in a table and each will have a select button and a save button.+ #' For constructing the data object, refer to [teal_data()] and [teal_data_module()]. |
||
15 |
- #'+ #' If `datanames` are not set for the `teal_data` object, defaults from the `teal_data` environment will be used. |
||
16 |
- #' @section Server logic:+ #' @param modules (`list` or `teal_modules` or `teal_module`) |
||
17 |
- #' Snapshots are basically `teal_slices` objects, however, since each module is served by a separate instance+ #' Nested list of `teal_modules` or `teal_module` objects or a single |
||
18 |
- #' of `FilteredData` and these objects require shared state, `teal_slice` is a `reactiveVal` so `teal_slices`+ #' `teal_modules` or `teal_module` object. These are the specific output modules which |
||
19 |
- #' cannot be stored as is. Therefore, `teal_slices` are reversibly converted to a list of lists representation+ #' will be displayed in the `teal` application. See [modules()] and [module()] for |
||
20 |
- #' (attributes are maintained).+ #' more details. |
||
21 |
- #'+ #' @param filter (`teal_slices`) Optionally, |
||
22 |
- #' Snapshots are stored in a `reactiveVal` as a named list.+ #' specifies the initial filter using [teal_slices()]. |
||
23 |
- #' The first snapshot is the initial state of the application and the user can add a snapshot whenever they see fit.+ #' @param title (`shiny.tag` or `character(1)`) Optionally, |
||
24 |
- #'+ #' the browser window title. Defaults to a title "teal app" with the icon of NEST. |
||
25 |
- #' For every snapshot except the initial one, a piece of UI is generated that contains+ #' Can be created using the `build_app_title()` or |
||
26 |
- #' the snapshot name, a select button to restore that snapshot, and a save button to save it to a file.+ #' by passing a valid `shiny.tag` which is a head tag with title and link tag. |
||
27 |
- #' The initial snapshot is restored by a separate "reset" button.+ #' @param header (`shiny.tag` or `character(1)`) Optionally, |
||
28 |
- #' It cannot be saved directly but a user is welcome to capture the initial state as a snapshot and save that.+ #' the header of the app. |
||
29 |
- #'+ #' @param footer (`shiny.tag` or `character(1)`) Optionally, |
||
30 |
- #' @section Snapshot mechanics:+ #' the footer of the app. |
||
31 |
- #' When a snapshot is captured, the user is prompted to name it.+ #' @param id (`character`) Optionally, |
||
32 |
- #' Names are displayed as is but since they are used to create button ids,+ #' a string specifying the `shiny` module id in cases it is used as a `shiny` module |
||
33 |
- #' under the hood they are converted to syntactically valid strings.+ #' rather than a standalone `shiny` app. This is a legacy feature. |
||
34 |
- #' New snapshot names are validated so that their valid versions are unique.+ #' @param landing_popup (`teal_module_landing`) Optionally, |
||
35 |
- #' Leading and trailing white space is trimmed.+ #' a `landing_popup_module` to show up as soon as the teal app is initialized. |
||
37 |
- #' The module can read the global state of the application from `slices_global` and `mapping_matrix`.+ #' @return Named list containing server and UI functions. |
||
38 |
- #' The former provides a list of all existing `teal_slice`s and the latter says which slice is active in which module.+ #' |
||
39 |
- #' Once a name has been accepted, `slices_global` is converted to a list of lists - a snapshot.+ #' @export |
||
40 |
- #' The snapshot contains the `mapping` attribute of the initial application state+ #' |
||
41 |
- #' (or one that has been restored), which may not reflect the current one,+ #' @include modules.R |
||
42 |
- #' so `mapping_matrix` is transformed to obtain the current mapping, i.e. a list that,+ #' |
||
43 |
- #' when passed to the `mapping` argument of [teal_slices()], would result in the current mapping.+ #' @examples |
||
44 |
- #' This is substituted as the snapshot's `mapping` attribute and the snapshot is added to the snapshot list.+ #' app <- init( |
||
45 |
- #'+ #' data = within( |
||
46 |
- #' To restore app state, a snapshot is retrieved from storage and rebuilt into a `teal_slices` object.+ #' teal_data(), |
||
47 |
- #' Then state of all `FilteredData` objects (provided in `datasets`) is cleared+ #' { |
||
48 |
- #' and set anew according to the `mapping` attribute of the snapshot.+ #' new_iris <- transform(iris, id = seq_len(nrow(iris))) |
||
49 |
- #' The snapshot is then set as the current content of `slices_global`.+ #' new_mtcars <- transform(mtcars, id = seq_len(nrow(mtcars))) |
||
50 |
- #'+ #' } |
||
51 |
- #' To save a snapshot, the snapshot is retrieved and reassembled just like for restoring,+ #' ), |
||
52 |
- #' and then saved to file with [slices_store()].+ #' modules = modules( |
||
53 |
- #'+ #' module( |
||
54 |
- #' When a snapshot is uploaded, it will first be added to storage just like a newly created one,+ #' label = "data source", |
||
55 |
- #' and then used to restore app state much like a snapshot taken from storage.+ #' server = function(input, output, session, data) {}, |
||
56 |
- #' Upon clicking the upload icon the user will be prompted for a file to upload+ #' ui = function(id, ...) tags$div(p("information about data source")), |
||
57 |
- #' and may choose to name the new snapshot. The name defaults to the name of the file (the extension is dropped)+ #' datanames = "all" |
||
58 |
- #' and normal naming rules apply. Loading the file yields a `teal_slices` object,+ #' ), |
||
59 |
- #' which is disassembled for storage and used directly for restoring app state.+ #' example_module(label = "example teal module"), |
||
60 |
- #'+ #' module( |
||
61 |
- #' @section Transferring snapshots:+ #' "Iris Sepal.Length histogram", |
||
62 |
- #' Snapshots uploaded from disk should only be used in the same application they come from,+ #' server = function(input, output, session, data) { |
||
63 |
- #' _i.e._ an application that uses the same data and the same modules.+ #' output$hist <- renderPlot( |
||
64 |
- #' To ensure this is the case, `init` stamps `teal_slices` with an app id that is stored in the `app_id` attribute of+ #' hist(data()[["new_iris"]]$Sepal.Length) |
||
65 |
- #' a `teal_slices` object. When a snapshot is restored from file, its `app_id` is compared to that+ #' ) |
||
66 |
- #' of the current app state and only if the match is the snapshot admitted to the session.+ #' }, |
||
67 |
- #'+ #' ui = function(id, ...) { |
||
68 |
- #' @section Bookmarks:+ #' ns <- NS(id) |
||
69 |
- #' An `onBookmark` callback creates a snapshot of the current filter state.+ #' plotOutput(ns("hist")) |
||
70 |
- #' This is done on the app session, not the module session.+ #' }, |
||
71 |
- #' (The snapshot will be retrieved by `module_teal` in order to set initial app state in a restored app.)+ #' datanames = "new_iris" |
||
72 |
- #' Then that snapshot, and the previous snapshot history are dumped into the `values.rds` file in `<bookmark_dir>`.+ #' ) |
||
73 |
- #'+ #' ), |
||
74 |
- #' @param id (`character(1)`) `shiny` module instance id.+ #' filter = teal_slices( |
||
75 |
- #' @param slices_global (`reactiveVal`) that contains a `teal_slices` object+ #' teal_slice(dataname = "new_iris", varname = "Species"), |
||
76 |
- #' containing all `teal_slice`s existing in the app, both active and inactive.+ #' teal_slice(dataname = "new_iris", varname = "Sepal.Length"), |
||
77 |
- #'+ #' teal_slice(dataname = "new_mtcars", varname = "cyl"), |
||
78 |
- #' @return `list` containing the snapshot history, where each element is an unlisted `teal_slices` object.+ #' exclude_varnames = list(new_iris = c("Sepal.Width", "Petal.Width")), |
||
79 |
- #'+ #' module_specific = TRUE, |
||
80 |
- #' @name module_snapshot_manager+ #' mapping = list( |
||
81 |
- #' @rdname module_snapshot_manager+ #' `example teal module` = "new_iris Species", |
||
82 |
- #'+ #' `Iris Sepal.Length histogram` = "new_iris Species", |
||
83 |
- #' @author Aleksander Chlebowski+ #' global_filters = "new_mtcars cyl" |
||
84 |
- #' @keywords internal+ #' ) |
||
85 |
- NULL+ #' ), |
||
86 |
-
+ #' title = "App title", |
||
87 |
- #' @rdname module_snapshot_manager+ #' header = tags$h1("Sample App"), |
||
88 |
- ui_snapshot_manager_panel <- function(id) {+ #' footer = tags$p("Sample footer") |
||
89 | -! | +
- ns <- NS(id)+ #' ) |
|
90 | -! | +
- tags$button(+ #' if (interactive()) { |
|
91 | -! | +
- id = ns("show_snapshot_manager"),+ #' shinyApp(app$ui, app$server) |
|
92 | -! | +
- class = "btn action-button wunder_bar_button",+ #' } |
|
93 | -! | +
- title = "View filter mapping",+ #' |
|
94 | -! | +
- suppressMessages(icon("fas fa-camera"))+ init <- function(data, |
|
95 |
- )+ modules, |
||
96 |
- }+ filter = teal_slices(), |
||
97 |
-
+ title = build_app_title(), |
||
98 |
- #' @rdname module_snapshot_manager+ header = tags$p(), |
||
99 |
- srv_snapshot_manager_panel <- function(id, slices_global) {+ footer = tags$p(), |
||
100 | -82x | +
- moduleServer(id, function(input, output, session) {+ id = character(0), |
|
101 | -82x | +
- logger::log_debug("srv_snapshot_manager_panel initializing")+ landing_popup = NULL) { |
|
102 | -82x | +12x |
- setBookmarkExclude(c("show_snapshot_manager"))+ logger::log_debug("init initializing teal app with: data ('{ class(data) }').") |
103 | -82x | +
- observeEvent(input$show_snapshot_manager, {+ |
|
104 | -! | +
- logger::log_debug("srv_snapshot_manager_panel@1 show_snapshot_manager button has been clicked.")+ # argument checking (independent) |
|
105 | -! | +
- showModal(+ ## `data` |
|
106 | -! | +12x |
- modalDialog(+ if (inherits(data, "TealData")) { |
107 | ! |
- ui_snapshot_manager(session$ns("module")),+ lifecycle::deprecate_stop( |
|
108 | ! |
- class = "snapshot_manager_modal",+ when = "0.15.0", |
|
109 | ! |
- size = "m",+ what = "init(data)", |
|
110 | ! |
- footer = NULL,+ paste( |
|
111 | ! |
- easyClose = TRUE+ "TealData is no longer supported. Use teal_data() instead.", |
|
112 | -+ | ! |
- )+ "Please follow migration instructions https://github.com/insightsengineering/teal/discussions/988." |
114 |
- })+ ) |
||
115 | -82x | +
- srv_snapshot_manager("module", slices_global = slices_global)+ } |
|
116 | -+ | 12x |
- })+ checkmate::assert_multi_class(data, c("teal_data", "teal_data_module")) |
117 | -+ | 12x |
- }+ checkmate::assert_class(landing_popup, "teal_module_landing", null.ok = TRUE) |
119 |
- #' @rdname module_snapshot_manager+ ## `modules` |
||
120 | -+ | 12x |
- ui_snapshot_manager <- function(id) {+ checkmate::assert( |
121 | -! | +12x |
- ns <- NS(id)+ .var.name = "modules", |
122 | -! | +12x |
- tags$div(+ checkmate::check_multi_class(modules, c("teal_modules", "teal_module")), |
123 | -! | +12x |
- class = "manager_content",+ checkmate::check_list(modules, min.len = 1, any.missing = FALSE, types = c("teal_module", "teal_modules")) |
124 | -! | +
- tags$div(+ ) |
|
125 | -! | +12x |
- class = "manager_table_row",+ if (inherits(modules, "teal_module")) { |
126 | -! | +1x |
- tags$span(tags$b("Snapshot manager")),+ modules <- list(modules) |
127 | -! | +
- actionLink(ns("snapshot_add"), label = NULL, icon = icon("fas fa-camera"), title = "add snapshot"),+ } |
|
128 | -! | +12x |
- actionLink(ns("snapshot_load"), label = NULL, icon = icon("fas fa-upload"), title = "upload snapshot"),+ if (checkmate::test_list(modules, min.len = 1, any.missing = FALSE, types = c("teal_module", "teal_modules"))) { |
129 | -! | +6x |
- actionLink(ns("snapshot_reset"), label = NULL, icon = icon("fas fa-undo"), title = "reset initial state"),+ modules <- do.call(teal::modules, modules) |
130 | -! | +
- NULL+ } |
|
131 |
- ),+ |
||
132 | -! | +
- uiOutput(ns("snapshot_list"))+ ## `filter` |
|
133 | -+ | 12x |
- )+ checkmate::assert_class(filter, "teal_slices") |
134 |
- }+ |
||
135 |
-
+ ## all other arguments |
||
136 | -+ | 11x |
- #' @rdname module_snapshot_manager+ checkmate::assert( |
137 | -+ | 11x |
- srv_snapshot_manager <- function(id, slices_global) {+ .var.name = "title", |
138 | -82x | +11x |
- checkmate::assert_character(id)+ checkmate::check_string(title), |
139 | -+ | 11x |
-
+ checkmate::check_multi_class(title, c("shiny.tag", "shiny.tag.list", "html")) |
140 | -82x | +
- moduleServer(id, function(input, output, session) {+ ) |
|
141 | -82x | +11x |
- logger::log_debug("srv_snapshot_manager initializing")+ checkmate::assert( |
142 | -+ | 11x |
-
+ .var.name = "header", |
143 | -+ | 11x |
- # Set up bookmarking callbacks ----+ checkmate::check_string(header), |
144 | -+ | 11x |
- # Register bookmark exclusions (all buttons and text fields).+ checkmate::check_multi_class(header, c("shiny.tag", "shiny.tag.list", "html")) |
145 | -82x | +
- setBookmarkExclude(c(+ ) |
|
146 | -82x | +11x |
- "snapshot_add", "snapshot_load", "snapshot_reset",+ checkmate::assert( |
147 | -82x | +11x |
- "snapshot_name_accept", "snaphot_file_accept",+ .var.name = "footer", |
148 | -82x | +11x |
- "snapshot_name", "snapshot_file"+ checkmate::check_string(footer), |
149 | -+ | 11x |
- ))+ checkmate::check_multi_class(footer, c("shiny.tag", "shiny.tag.list", "html")) |
150 |
- # Add snapshot history to bookmark.+ ) |
||
151 | -82x | +11x |
- session$onBookmark(function(state) {+ checkmate::assert_character(id, max.len = 1, any.missing = FALSE) |
152 | -! | +
- logger::log_debug("srv_snapshot_manager@onBookmark: storing snapshot and bookmark history")+ |
|
153 | -! | +
- state$values$snapshot_history <- snapshot_history() # isolate this?+ # log |
|
154 | -+ | 11x |
- })+ teal.logger::log_system_info() |
156 | -82x | +
- ns <- session$ns+ # argument transformations |
|
157 |
-
+ ## `modules` - landing module |
||
158 | -+ | 11x |
- # Track global filter states ----+ landing <- extract_module(modules, "teal_module_landing") |
159 | -82x | +11x |
- snapshot_history <- reactiveVal({+ if (length(landing) == 1L) { |
160 | -+ | ! |
- # Restore directly from bookmarked state, if applicable.+ landing_popup <- landing[[1L]] |
161 | -82x | +! |
- restoreValue(+ modules <- drop_module(modules, "teal_module_landing") |
162 | -82x | +! |
- ns("snapshot_history"),+ lifecycle::deprecate_soft( |
163 | -82x | +! |
- list("Initial application state" = shiny::isolate(as.list(slices_global$all_slices(), recursive = TRUE)))+ when = "0.15.3", |
164 | -+ | ! |
- )+ what = "landing_popup_module()", |
165 | -+ | ! |
- })+ details = paste( |
166 | -+ | ! |
-
+ "Pass `landing_popup_module` to the `landing_popup` argument of the `init` ", |
167 | -+ | ! |
- # Snapshot current application state ----+ "instead of wrapping it into `modules()` and passing to the `modules` argument" |
168 |
- # Name snaphsot.+ ) |
||
169 | -82x | +
- observeEvent(input$snapshot_add, {+ ) |
|
170 | -! | +11x |
- logger::log_debug("srv_snapshot_manager: snapshot_add button clicked")+ } else if (length(landing) > 1L) { |
171 | ! |
- showModal(+ stop("Only one `landing_popup_module` can be used.") |
|
172 | -! | +
- modalDialog(+ } |
|
173 | -! | +
- textInput(ns("snapshot_name"), "Name the snapshot", width = "100%", placeholder = "Meaningful, unique name"),+ |
|
174 | -! | +
- footer = tagList(+ ## `filter` - set app_id attribute unless present (when restoring bookmark) |
|
175 | -! | +11x |
- actionButton(ns("snapshot_name_accept"), "Accept", icon = icon("far fa-thumbs-up")),+ if (is.null(attr(filter, "app_id", exact = TRUE))) attr(filter, "app_id") <- create_app_id(data, modules) |
176 | -! | +
- modalButton(label = "Cancel", icon = icon("far fa-thumbs-down"))+ |
|
177 |
- ),+ ## `filter` - convert teal.slice::teal_slices to teal::teal_slices |
||
178 | -! | +11x |
- size = "s"+ filter <- as.teal_slices(as.list(filter)) |
179 |
- )+ |
||
180 |
- )+ # argument checking (interdependent) |
||
181 |
- })+ ## `filter` - `modules` |
||
182 | -+ | 11x |
- # Store snaphsot.+ if (isTRUE(attr(filter, "module_specific"))) { |
183 | -82x | +! |
- observeEvent(input$snapshot_name_accept, {+ module_names <- unlist(c(module_labels(modules), "global_filters")) |
184 | ! |
- logger::log_debug("srv_snapshot_manager: snapshot_name_accept button clicked")+ failed_mod_names <- setdiff(names(attr(filter, "mapping")), module_names) |
|
185 | ! |
- snapshot_name <- trimws(input$snapshot_name)+ if (length(failed_mod_names)) { |
|
186 | ! |
- if (identical(snapshot_name, "")) {+ stop( |
|
187 | ! |
- logger::log_debug("srv_snapshot_manager: snapshot name rejected")+ sprintf( |
|
188 | ! |
- showNotification(+ "Some module names in the mapping arguments don't match module labels.\n %s not in %s", |
|
189 | ! |
- "Please name the snapshot.",+ toString(failed_mod_names), |
|
190 | ! |
- type = "message"+ toString(unique(module_names)) |
|
192 | -! | +
- updateTextInput(inputId = "snapshot_name", value = "", placeholder = "Meaningful, unique name")+ ) |
|
193 | -! | +
- } else if (is.element(make.names(snapshot_name), make.names(names(snapshot_history())))) {+ } |
|
194 | -! | +
- logger::log_debug("srv_snapshot_manager: snapshot name rejected")+ |
|
195 | ! |
- showNotification(+ if (anyDuplicated(module_names)) { |
|
196 | -! | +
- "This name is in conflict with other snapshot names. Please choose a different one.",+ # In teal we are able to set nested modules with duplicated label. |
|
197 | -! | +
- type = "message"+ # Because mapping argument bases on the relationship between module-label and filter-id, |
|
198 |
- )+ # it is possible that module-label in mapping might refer to multiple teal_module (identified by the same label) |
||
199 | ! |
- updateTextInput(inputId = "snapshot_name", value = "", placeholder = "Meaningful, unique name")+ stop( |
|
200 | -+ | ! |
- } else {+ sprintf( |
201 | ! |
- logger::log_debug("srv_snapshot_manager: snapshot name accepted, adding snapshot")+ "Module labels should be unique when teal_slices(mapping = TRUE). Duplicated labels:\n%s ", |
|
202 | ! |
- snapshot <- as.list(slices_global$all_slices(), recursive = TRUE)+ toString(module_names[duplicated(module_names)]) |
|
203 | -! | +
- snapshot_update <- c(snapshot_history(), list(snapshot))+ ) |
|
204 | -! | +
- names(snapshot_update)[length(snapshot_update)] <- snapshot_name+ ) |
|
205 | -! | +
- snapshot_history(snapshot_update)+ } |
|
206 | -! | +
- removeModal()+ } |
|
207 |
- # Reopen filter manager modal by clicking button in the main application.+ |
||
208 | -! | +
- shinyjs::click(id = "teal-wunder_bar-show_snapshot_manager", asis = TRUE)+ ## `data` - `modules` |
|
209 | -+ | 11x |
- }+ if (inherits(data, "teal_data")) { |
210 | -+ | 10x |
- })+ if (length(ls(teal.code::get_env(data))) == 0) { |
211 | -+ | 1x |
-
+ stop("The environment of `data` is empty.") |
212 |
- # Upload a snapshot file ----+ } |
||
213 |
- # Select file.+ |
||
214 | -82x | +9x |
- observeEvent(input$snapshot_load, {+ is_modules_ok <- check_modules_datanames(modules, ls(teal.code::get_env(data))) |
215 | -! | +9x |
- logger::log_debug("srv_snapshot_manager: snapshot_load button clicked")+ if (!isTRUE(is_modules_ok) && length(unlist(extract_transformers(modules))) == 0) { |
216 | -! | +2x |
- showModal(+ warning(is_modules_ok, call. = FALSE) |
217 | -! | +
- modalDialog(+ } |
|
218 | -! | +
- fileInput(ns("snapshot_file"), "Choose snapshot file", accept = ".json", width = "100%"),+ |
|
219 | -! | +9x |
- textInput(+ is_filter_ok <- check_filter_datanames(filter, ls(teal.code::get_env(data))) |
220 | -! | +9x |
- ns("snapshot_name"),+ if (!isTRUE(is_filter_ok)) { |
221 | -! | +1x |
- "Name the snapshot (optional)",+ warning(is_filter_ok) |
222 | -! | +
- width = "100%",+ # we allow app to continue if applied filters are outside |
|
223 | -! | +
- placeholder = "Meaningful, unique name"+ # of possible data range |
|
224 |
- ),+ } |
||
225 | -! | +
- footer = tagList(+ } |
|
226 | -! | +
- actionButton(ns("snaphot_file_accept"), "Accept", icon = icon("far fa-thumbs-up")),+ |
|
227 | -! | +10x |
- modalButton(label = "Cancel", icon = icon("far fa-thumbs-down"))+ reporter <- teal.reporter::Reporter$new()$set_id(attr(filter, "app_id")) |
228 | -+ | 10x |
- )+ if (is_arg_used(modules, "reporter") && length(extract_module(modules, "teal_module_previewer")) == 0) { |
229 | -+ | ! |
- )+ modules <- append_module( |
230 | -+ | ! |
- )+ modules, |
231 | -+ | ! |
- })+ reporter_previewer_module(server_args = list(previewer_buttons = c("download", "reset"))) |
232 |
- # Store new snapshot to list and restore filter states.+ ) |
||
233 | -82x | +
- observeEvent(input$snaphot_file_accept, {+ } |
|
234 | -! | +
- logger::log_debug("srv_snapshot_manager: snapshot_file_accept button clicked")+ |
|
235 | -! | +10x |
- snapshot_name <- trimws(input$snapshot_name)+ ns <- NS(id) |
236 | -! | +
- if (identical(snapshot_name, "")) {+ # Note: UI must be a function to support bookmarking. |
|
237 | -! | +10x |
- logger::log_debug("srv_snapshot_manager: no snapshot name provided, naming after file")+ res <- list( |
238 | -! | +10x |
- snapshot_name <- tools::file_path_sans_ext(input$snapshot_file$name)+ ui = function(request) { |
239 | -+ | ! |
- }+ ui_teal( |
240 | ! |
- if (is.element(make.names(snapshot_name), make.names(names(snapshot_history())))) {+ id = ns("teal"), |
|
241 | ! |
- logger::log_debug("srv_snapshot_manager: snapshot name rejected")+ modules = modules, |
|
242 | ! |
- showNotification(+ title = title, |
|
243 | ! |
- "This name is in conflict with other snapshot names. Please choose a different one.",+ header = header, |
|
244 | ! |
- type = "message"+ footer = footer |
|
245 |
- )+ ) |
||
246 | -! | +
- updateTextInput(inputId = "snapshot_name", value = "", placeholder = "Meaningful, unique name")+ }, |
|
247 | -+ | 10x |
- } else {+ server = function(input, output, session) { |
248 | -+ | ! |
- # Restore snapshot and verify app compatibility.+ if (!is.null(landing_popup)) { |
249 | ! |
- logger::log_debug("srv_snapshot_manager: snapshot name accepted, loading snapshot")+ do.call(landing_popup$server, c(list(id = "landing_module_shiny_id"), landing_popup$server_args)) |
|
250 | -! | +
- snapshot_state <- try(slices_restore(input$snapshot_file$datapath))+ } |
|
251 | ! |
- if (!inherits(snapshot_state, "modules_teal_slices")) {+ srv_teal(id = ns("teal"), data = data, modules = modules, filter = deep_copy_filter(filter)) |
|
252 | -! | +
- logger::log_debug("srv_snapshot_manager: snapshot file corrupt")+ } |
|
253 | -! | +
- showNotification(+ ) |
|
254 | -! | +
- "File appears to be corrupt.",+ |
|
255 | -! | +10x |
- type = "error"+ logger::log_debug("init teal app has been initialized.") |
256 |
- )+ |
||
257 | -! | +10x |
- } else if (!identical(attr(snapshot_state, "app_id"), attr(slices_global$all_slices(), "app_id"))) {+ res |
258 | -! | +
- logger::log_debug("srv_snapshot_manager: snapshot not compatible with app")+ } |
|
259 | -! | +
1 | +
- showNotification(+ #' Filter panel module in teal |
|||
260 | -! | +|||
2 | +
- "This snapshot file is not compatible with the app and cannot be loaded.",+ #' |
|||
261 | -! | +|||
3 | +
- type = "warning"+ #' Creates filter panel module from `teal_data` object and returns `teal_data`. It is build in a way |
|||
262 | +4 |
- )+ #' that filter panel changes and anything what happens before (e.g. [`module_init_data`]) is triggering |
||
263 | +5 |
- } else {+ #' further reactive events only if something has changed and if the module is visible. Thanks to |
||
264 | +6 |
- # Add to snapshot history.+ #' this special implementation all modules' data are recalculated only for those modules which are |
||
265 | -! | +|||
7 | +
- logger::log_debug("srv_snapshot_manager: snapshot loaded, adding to history")+ #' currently displayed. |
|||
266 | -! | +|||
8 | +
- snapshot <- as.list(slices_global$all_slices(), recursive = TRUE)+ #' |
|||
267 | -! | +|||
9 | +
- snapshot_update <- c(snapshot_history(), list(snapshot))+ #' @return A `eventReactive` containing `teal_data` containing filtered objects and filter code. |
|||
268 | -! | +|||
10 | +
- names(snapshot_update)[length(snapshot_update)] <- snapshot_name+ #' `eventReactive` triggers only if all conditions are met: |
|||
269 | -! | +|||
11 | +
- snapshot_history(snapshot_update)+ #' - tab is selected (`is_active`) |
|||
270 | +12 |
- ### Begin simplified restore procedure. ###+ #' - when filters are changed (`get_filter_expr` is different than previous) |
||
271 | -! | +|||
13 | ++ |
+ #'+ |
+ ||
14 | ++ |
+ #' @inheritParams module_teal_module+ |
+ ||
15 | ++ |
+ #' @param active_datanames (`reactive` returning `character`) this module's data names+ |
+ ||
16 | ++ |
+ #' @name module_filter_data+ |
+ ||
17 | ++ |
+ #' @keywords internal+ |
+ ||
18 | ++ |
+ NULL+ |
+ ||
19 | ++ | + + | +||
20 | ++ |
+ #' @rdname module_filter_data+ |
+ ||
21 | +
- logger::log_debug("srv_snapshot_manager: restoring snapshot")+ ui_filter_data <- function(id) { |
|||
272 | +22 | ! |
- slices_global$slices_set(snapshot_state)+ ns <- shiny::NS(id) |
|
273 | +23 | ! |
- removeModal()+ uiOutput(ns("panel")) |
|
274 | +24 |
- ### End simplified restore procedure. ###+ } |
||
275 | +25 |
- }+ |
||
276 | +26 |
- }+ #' @rdname module_filter_data |
||
277 | +27 |
- })+ srv_filter_data <- function(id, datasets, active_datanames, data_rv, is_active) { |
||
278 | -+ | |||
28 | +81x |
- # Apply newly added snapshot.+ assert_reactive(datasets) |
||
279 | -+ | |||
29 | +81x |
-
+ moduleServer(id, function(input, output, session) {+ |
+ ||
30 | +81x | +
+ active_corrected <- reactive(intersect(active_datanames(), datasets()$datanames())) |
||
280 | +31 |
- # Restore initial state ----+ |
||
281 | -82x | +32 | +81x |
- observeEvent(input$snapshot_reset, {+ output$panel <- renderUI({ |
282 | -2x | +33 | +83x |
- logger::log_debug("srv_snapshot_manager: snapshot_reset button clicked, restoring snapshot")+ req(inherits(datasets(), "FilteredData")) |
283 | -2x | +34 | +83x |
- s <- "Initial application state"+ isolate({ |
284 | +35 |
- ### Begin restore procedure. ###- |
- ||
285 | -2x | -
- snapshot <- snapshot_history()[[s]]+ # render will be triggered only when FilteredData object changes (not when filters change) |
||
286 | +36 |
- # todo: as.teal_slices looses module-mapping if is not global+ # technically it means that teal_data_module needs to be refreshed |
||
287 | -2x | +37 | +83x |
- snapshot_state <- as.teal_slices(snapshot)+ logger::log_debug("srv_filter_panel rendering filter panel.") |
288 | -2x | +38 | +83x |
- slices_global$slices_set(snapshot_state)+ if (length(active_corrected())) { |
289 | -2x | +39 | +81x |
- removeModal()+ datasets()$srv_active("filters", active_datanames = active_corrected) |
290 | -+ | |||
40 | +81x |
- ### End restore procedure. ###+ datasets()$ui_active(session$ns("filters"), active_datanames = active_corrected) |
||
291 | +41 |
- })+ } |
||
292 | +42 |
-
+ }) |
||
293 | +43 |
- # Build snapshot table ----+ }) |
||
294 | +44 |
- # Create UI elements and server logic for the snapshot table.+ |
||
295 | -+ | |||
45 | +81x |
- # Observers must be tracked to avoid duplication and excess reactivity.+ trigger_data <- .observe_active_filter_changed(datasets, is_active, active_corrected, data_rv) |
||
296 | +46 |
- # Remaining elements are tracked likewise for consistency and a slight speed margin.+ |
||
297 | -82x | +47 | +81x |
- observers <- reactiveValues()+ eventReactive(trigger_data(), { |
298 | -82x | +48 | +84x |
- handlers <- reactiveValues()+ .make_filtered_teal_data(modules, data = data_rv(), datasets = datasets(), datanames = active_corrected()) |
299 | -82x | +|||
49 | +
- divs <- reactiveValues()+ }) |
|||
300 | +50 | ++ |
+ })+ |
+ |
51 | ++ |
+ }+ |
+ ||
52 | ||||
301 | -82x | +|||
53 | +
- observeEvent(snapshot_history(), {+ #' @rdname module_filter_data |
|||
302 | -72x | +|||
54 | +
- logger::log_debug("srv_snapshot_manager: snapshot history modified, updating snapshot list")+ .make_filtered_teal_data <- function(modules, data, datasets = NULL, datanames) { |
|||
303 | -72x | +55 | +84x |
- lapply(names(snapshot_history())[-1L], function(s) {+ data <- eval_code( |
304 | -! | +|||
56 | +84x |
- id_pickme <- sprintf("pickme_%s", make.names(s))+ data, |
||
305 | -! | +|||
57 | +84x |
- id_saveme <- sprintf("saveme_%s", make.names(s))+ paste0( |
||
306 | -! | +|||
58 | +84x |
- id_rowme <- sprintf("rowme_%s", make.names(s))+ ".raw_data <- list2env(list(", |
||
307 | -+ | |||
59 | +84x |
-
+ toString(sprintf("%1$s = %1$s", sapply(datanames, as.name))), |
||
308 | -+ | |||
60 | +84x |
- # Observer for restoring snapshot.+ "))\n", |
||
309 | -! | +|||
61 | +84x |
- if (!is.element(id_pickme, names(observers))) {+ "lockEnvironment(.raw_data) # @linksto .raw_data" # this is environment and it is shared by qenvs. CAN'T MODIFY! |
||
310 | -! | +|||
62 | +
- observers[[id_pickme]] <- observeEvent(input[[id_pickme]], {+ ) |
|||
311 | +63 |
- ### Begin restore procedure. ###+ ) |
||
312 | -! | +|||
64 | +84x |
- snapshot <- snapshot_history()[[s]]+ filtered_code <- .get_filter_expr(datasets = datasets, datanames = datanames) |
||
313 | -! | +|||
65 | +84x |
- snapshot_state <- as.teal_slices(snapshot)+ filtered_teal_data <- .append_evaluated_code(data, filtered_code) |
||
314 | -+ | |||
66 | +84x |
-
+ filtered_datasets <- sapply(datanames, function(x) datasets$get_data(x, filtered = TRUE), simplify = FALSE) |
||
315 | -! | +|||
67 | +84x |
- slices_global$slices_set(snapshot_state)+ filtered_teal_data <- .append_modified_data(filtered_teal_data, filtered_datasets) |
||
316 | -! | +|||
68 | +84x |
- removeModal()+ filtered_teal_data |
||
317 | +69 |
- ### End restore procedure. ###+ } |
||
318 | +70 |
- })+ |
||
319 | +71 |
- }+ #' @rdname module_filter_data |
||
320 | +72 |
- # Create handler for downloading snapshot.+ .observe_active_filter_changed <- function(datasets, is_active, active_datanames, data_rv) { |
||
321 | -! | +|||
73 | +81x |
- if (!is.element(id_saveme, names(handlers))) {+ previous_signature <- reactiveVal(NULL) |
||
322 | -! | +|||
74 | +81x |
- output[[id_saveme]] <- downloadHandler(+ filter_changed <- reactive({ |
||
323 | -! | +|||
75 | +185x |
- filename = function() {+ req(inherits(datasets(), "FilteredData")) |
||
324 | -! | +|||
76 | +185x |
- sprintf("teal_snapshot_%s_%s.json", s, Sys.Date())+ new_signature <- c( |
||
325 | -+ | |||
77 | +185x |
- },+ teal.code::get_code(data_rv()), |
||
326 | -! | +|||
78 | +185x |
- content = function(file) {+ .get_filter_expr(datasets = datasets(), datanames = active_datanames()) |
||
327 | -! | +|||
79 | +
- snapshot <- snapshot_history()[[s]]+ ) |
|||
328 | -! | +|||
80 | +185x |
- snapshot_state <- as.teal_slices(snapshot)+ if (!identical(previous_signature(), new_signature)) { |
||
329 | -! | +|||
81 | +89x |
- slices_store(tss = snapshot_state, file = file)+ previous_signature(new_signature) |
||
330 | -+ | |||
82 | +89x |
- }+ TRUE |
||
331 | +83 |
- )+ } else { |
||
332 | -! | +|||
84 | +96x |
- handlers[[id_saveme]] <- id_saveme+ FALSE |
||
333 | +85 |
- }+ } |
||
334 | +86 |
- # Create a row for the snapshot table.- |
- ||
335 | -! | -
- if (!is.element(id_rowme, names(divs))) {+ }) |
||
336 | -! | +|||
87 | +
- divs[[id_rowme]] <- tags$div(+ |
|||
337 | -! | +|||
88 | +81x |
- class = "manager_table_row",+ trigger_data <- reactiveVal(NULL) |
||
338 | -! | +|||
89 | +81x |
- tags$span(tags$h5(s)),+ observe({ |
||
339 | -! | +|||
90 | +198x |
- actionLink(inputId = ns(id_pickme), label = icon("far fa-circle-check"), title = "select"),+ if (isTRUE(is_active() && filter_changed())) { |
||
340 | -! | +|||
91 | +89x |
- downloadLink(outputId = ns(id_saveme), label = icon("far fa-save"), title = "save to file")+ isolate({ |
||
341 | -+ | |||
92 | +89x |
- )+ if (is.null(trigger_data())) { |
||
342 | -+ | |||
93 | +81x |
- }+ trigger_data(0) |
||
343 | +94 |
- })+ } else { |
||
344 | -+ | |||
95 | +8x |
- })+ trigger_data(trigger_data() + 1) |
||
345 | +96 |
-
+ } |
||
346 | +97 |
- # Create table to display list of snapshots and their actions.- |
- ||
347 | -82x | -
- output$snapshot_list <- renderUI({- |
- ||
348 | -72x | -
- rows <- rev(reactiveValuesToList(divs))+ }) |
||
349 | -72x | +|||
98 | +
- if (length(rows) == 0L) {+ } |
|||
350 | -72x | +|||
99 | +
- tags$div(+ }) |
|||
351 | -72x | +|||
100 | +
- class = "manager_placeholder",+ |
|||
352 | -72x | +101 | +81x |
- "Snapshots will appear here."+ trigger_data |
353 | +102 |
- )+ } |
||
354 | +103 |
- } else {+ |
||
355 | -! | +|||
104 | +
- rows+ #' @rdname module_filter_data |
|||
356 | +105 |
- }+ .get_filter_expr <- function(datasets, datanames) { |
||
357 | -+ | |||
106 | +269x |
- })+ if (length(datanames)) {+ |
+ ||
107 | +263x | +
+ teal.slice::get_filter_expr(datasets = datasets, datanames = datanames) |
||
358 | +108 |
-
+ } else { |
||
359 | -82x | +109 | +6x |
- snapshot_history+ NULL |
360 | +110 |
- })+ } |
||
361 | +111 |
}@@ -27224,6196 +28004,6496 @@ teal coverage - 59.99% |
1 |
- #' Filter panel module in teal+ #' Data summary |
|||
2 |
- #'+ #' @description |
|||
3 |
- #' Creates filter panel module from `teal_data` object and returns `teal_data`. It is build in a way+ #' Module and its utils to display the number of rows and subjects in the filtered and unfiltered data. |
|||
4 |
- #' that filter panel changes and anything what happens before (e.g. [`module_init_data`]) is triggering+ #' |
|||
5 |
- #' further reactive events only if something has changed and if the module is visible. Thanks to+ #' @details Handling different data classes: |
|||
6 |
- #' this special implementation all modules' data are recalculated only for those modules which are+ #' `get_filter_overview()` is a pseudo S3 method which has variants for: |
|||
7 |
- #' currently displayed.+ #' - `array` (`data.frame`, `DataFrame`, `array`, `Matrix` and `SummarizedExperiment`): Method variant |
|||
8 |
- #'+ #' can be applied to any two-dimensional objects on which [ncol()] can be used. |
|||
9 |
- #' @return A `eventReactive` containing `teal_data` containing filtered objects and filter code.+ #' - `MultiAssayExperiment`: for which summary contains counts for `colData` and all `experiments`. |
|||
10 |
- #' `eventReactive` triggers only if all conditions are met:+ #' - For other data types module displays data name with warning icon and no more details. |
|||
11 |
- #' - tab is selected (`is_active`)+ #' |
|||
12 |
- #' - when filters are changed (`get_filter_expr` is different than previous)+ #' Module includes also "Show/Hide unsupported" button to toggle rows of the summary table |
|||
13 |
- #'+ #' containing datasets where number of observations are not calculated. |
|||
14 |
- #' @inheritParams module_teal_module+ #' |
|||
15 |
- #' @param active_datanames (`reactive` returning `character`) this module's data names+ #' @param id (`character(1)`) `shiny` module instance id. |
|||
16 |
- #' @name module_filter_data+ #' @param teal_data (`reactive` returning `teal_data`) |
|||
17 |
- #' @keywords internal+ #' |
|||
18 |
- NULL+ #' @name module_data_summary |
|||
19 |
-
+ #' @rdname module_data_summary |
|||
20 |
- #' @rdname module_filter_data+ #' @keywords internal |
|||
21 |
- ui_filter_data <- function(id) {+ #' @return `NULL`. |
|||
22 | -! | +
- ns <- shiny::NS(id)+ NULL |
||
23 | -! | +
- uiOutput(ns("panel"))+ |
||
24 |
- }+ #' @rdname module_data_summary |
|||
25 |
-
+ ui_data_summary <- function(id) { |
|||
26 | -+ | ! |
- #' @rdname module_filter_data+ ns <- NS(id) |
|
27 | -+ | ! |
- srv_filter_data <- function(id, datasets, active_datanames, data_rv, is_active) {+ content_id <- ns("filters_overview_contents") |
|
28 | -81x | +! |
- assert_reactive(datasets)+ tags$div( |
|
29 | -81x | +! |
- moduleServer(id, function(input, output, session) {+ id = id, |
|
30 | -81x | +! |
- active_corrected <- reactive(intersect(active_datanames(), datasets()$datanames()))+ class = "well", |
|
31 | -+ | ! |
-
+ tags$div( |
|
32 | -81x | +! |
- output$panel <- renderUI({+ class = "row", |
|
33 | -83x | +! |
- req(inherits(datasets(), "FilteredData"))+ tags$div( |
|
34 | -83x | +! |
- isolate({+ class = "col-sm-9", |
|
35 | -+ | ! |
- # render will be triggered only when FilteredData object changes (not when filters change)+ tags$label("Active Filter Summary", class = "text-primary mb-4") |
|
36 |
- # technically it means that teal_data_module needs to be refreshed+ ), |
|||
37 | -83x | +! |
- logger::log_debug("srv_filter_panel rendering filter panel.")+ tags$div( |
|
38 | -83x | +! |
- if (length(active_corrected())) {+ class = "col-sm-3", |
|
39 | -81x | +! |
- datasets()$srv_active("filters", active_datanames = active_corrected)+ tags$i( |
|
40 | -81x | +! |
- datasets()$ui_active(session$ns("filters"), active_datanames = active_corrected)+ class = "remove pull-right fa fa-angle-down", |
|
41 | -+ | ! |
- }+ style = "cursor: pointer;", |
|
42 | -+ | ! |
- })+ title = "fold/expand data summary panel", |
|
43 | -+ | ! |
- })+ onclick = sprintf("togglePanelItems(this, '%s', 'fa-angle-right', 'fa-angle-down');", content_id) |
|
44 |
-
+ ) |
|||
45 | -81x | +
- trigger_data <- .observe_active_filter_changed(datasets, is_active, active_corrected, data_rv)+ ) |
||
46 |
-
+ ), |
|||
47 | -81x | +! |
- eventReactive(trigger_data(), {+ tags$div( |
|
48 | -84x | +! |
- .make_filtered_teal_data(modules, data = data_rv(), datasets = datasets(), datanames = active_corrected())+ id = content_id, |
|
49 | -+ | ! |
- })+ tags$div( |
|
50 | -+ | ! |
- })+ class = "teal_active_summary_filter_panel", |
|
51 | -+ | ! |
- }+ tableOutput(ns("table")) |
|
52 |
-
+ ) |
|||
53 |
- #' @rdname module_filter_data+ ) |
|||
54 |
- .make_filtered_teal_data <- function(modules, data, datasets = NULL, datanames) {+ ) |
|||
55 | -84x | +
- data <- eval_code(+ } |
||
56 | -84x | +
- data,+ |
||
57 | -84x | +
- paste0(+ #' @rdname module_data_summary |
||
58 | -84x | +
- ".raw_data <- list2env(list(",+ srv_data_summary <- function(id, teal_data) { |
||
59 | -84x | +81x |
- toString(sprintf("%1$s = %1$s", sapply(datanames, as.name))),+ assert_reactive(teal_data) |
|
60 | -84x | +81x |
- "))\n",+ moduleServer( |
|
61 | -84x | +81x |
- "lockEnvironment(.raw_data) # @linksto .raw_data" # this is environment and it is shared by qenvs. CAN'T MODIFY!+ id = id, |
|
62 | -+ | 81x |
- )+ function(input, output, session) { |
|
63 | -+ | 81x |
- )+ logger::log_debug("srv_data_summary initializing") |
|
64 | -84x | +
- filtered_code <- .get_filter_expr(datasets = datasets, datanames = datanames)+ |
||
65 | -84x | +81x |
- filtered_teal_data <- .append_evaluated_code(data, filtered_code)+ summary_table <- reactive({ |
|
66 | -84x | +89x |
- filtered_datasets <- sapply(datanames, function(x) datasets$get_data(x, filtered = TRUE), simplify = FALSE)+ req(inherits(teal_data(), "teal_data")) |
|
67 | -84x | +83x |
- filtered_teal_data <- .append_modified_data(filtered_teal_data, filtered_datasets)+ if (!length(ls(teal.code::get_env(teal_data())))) { |
|
68 | -84x | +2x |
- filtered_teal_data+ return(NULL) |
|
69 |
- }+ } |
|||
70 | -+ | 81x |
-
+ get_filter_overview_wrapper(teal_data) |
|
71 |
- #' @rdname module_filter_data+ }) |
|||
72 |
- .observe_active_filter_changed <- function(datasets, is_active, active_datanames, data_rv) {+ |
|||
73 | 81x |
- previous_signature <- reactiveVal(NULL)+ output$table <- renderUI({ |
||
74 | -81x | +89x |
- filter_changed <- reactive({+ summary_table_out <- try(summary_table(), silent = TRUE) |
|
75 | -185x | +89x |
- req(inherits(datasets(), "FilteredData"))+ if (inherits(summary_table_out, "try-error")) { |
|
76 | -185x | +
- new_signature <- c(+ # Ignore silent shiny error |
||
77 | -185x | +6x |
- teal.code::get_code(data_rv()),+ if (!inherits(attr(summary_table_out, "condition"), "shiny.silent.error")) { |
|
78 | -185x | +! |
- .get_filter_expr(datasets = datasets(), datanames = active_datanames())+ stop("Error occurred during data processing. See details in the main panel.") |
|
79 |
- )+ } |
|||
80 | -185x | +83x |
- if (!identical(previous_signature(), new_signature)) {+ } else if (is.null(summary_table_out)) { |
|
81 | -89x | +2x |
- previous_signature(new_signature)+ "no datasets to show" |
|
82 | -89x | +
- TRUE+ } else { |
||
83 | -+ | 81x |
- } else {+ is_unsupported <- apply(summary_table(), 1, function(x) all(is.na(x[-1]))) |
|
84 | -96x | +81x |
- FALSE+ summary_table_out[is.na(summary_table_out)] <- "" |
|
85 | -+ | 81x |
- }+ body_html <- apply( |
|
86 | -+ | 81x |
- })+ summary_table_out, |
|
87 | -+ | 81x |
-
+ 1, |
|
88 | 81x |
- trigger_data <- reactiveVal(NULL)+ function(x) { |
||
89 | -81x | +154x |
- observe({+ is_supported <- !all(x[-1] == "") |
|
90 | -198x | +154x |
- if (isTRUE(is_active() && filter_changed())) {+ if (is_supported) { |
|
91 | -89x | +147x |
- isolate({+ tags$tr( |
|
92 | -89x | +147x |
- if (is.null(trigger_data())) {+ tagList( |
|
93 | -81x | +147x |
- trigger_data(0)+ tags$td(x[1]), |
|
94 | -+ | 147x |
- } else {+ lapply(x[-1], tags$td) |
|
95 | -8x | +
- trigger_data(trigger_data() + 1)+ ) |
||
96 |
- }+ ) |
|||
97 |
- })+ } |
|||
98 |
- }+ } |
|||
99 |
- })+ )+ |
+ |||
100 | ++ | + + | +||
101 | +81x | +
+ header_labels <- tools::toTitleCase(names(summary_table_out))+ |
+ ||
102 | +81x | +
+ header_labels[header_labels == "Dataname"] <- "Data Name"+ |
+ ||
103 | +81x | +
+ header_html <- tags$tr(tagList(lapply(header_labels, tags$td))) |
||
100 | +104 | |||
101 | +105 | 81x |
- trigger_data+ table_html <- tags$table( |
|
102 | -+ | |||
106 | +81x |
- }+ class = "table custom-table", |
||
103 | -+ | |||
107 | +81x |
-
+ tags$thead(header_html), |
||
104 | -+ | |||
108 | +81x |
- #' @rdname module_filter_data+ tags$tbody(body_html) |
||
105 | +109 |
- .get_filter_expr <- function(datasets, datanames) {+ ) |
||
106 | -269x | +110 | +81x |
- if (length(datanames)) {+ div( |
107 | -263x | +111 | +81x |
- teal.slice::get_filter_expr(datasets = datasets, datanames = datanames)+ table_html, |
108 | -+ | |||
112 | +81x |
- } else {+ if (any(is_unsupported)) { |
||
109 | -6x | +113 | +7x |
- NULL+ p( |
110 | -+ | |||
114 | +7x |
- }+ class = c("pull-right", "float-right", "text-secondary"), |
||
111 | -+ | |||
115 | +7x |
- }+ style = "font-size: 0.8em;", |
1 | -+ | |||
116 | +7x |
- setOldClass("teal_data_module")+ sprintf("And %s more unfilterable object(s)", sum(is_unsupported)), |
||
2 | -+ | |||
117 | +7x |
-
+ icon( |
||
3 | -+ | |||
118 | +7x |
- #' Evaluate code on `teal_data_module`+ name = "far fa-circle-question", |
||
4 | -+ | |||
119 | +7x |
- #'+ title = paste( |
||
5 | -+ | |||
120 | +7x |
- #' @details+ sep = "", |
||
6 | -+ | |||
121 | +7x |
- #' `eval_code` evaluates given code in the environment of the `teal_data` object created by the `teal_data_module`.+ collapse = "\n", |
||
7 | -+ | |||
122 | +7x |
- #' The code is added to the `@code` slot of the `teal_data`.+ shQuote(summary_table()[is_unsupported, "dataname"]), |
||
8 | +123 |
- #'+ " (", |
||
9 | -+ | |||
124 | +7x |
- #' @param object (`teal_data_module`)+ vapply( |
||
10 | -+ | |||
125 | +7x |
- #' @inheritParams teal.code::eval_code+ summary_table()[is_unsupported, "dataname"], |
||
11 | -+ | |||
126 | +7x |
- #'+ function(x) class(teal_data()[[x]])[1], |
||
12 | -+ | |||
127 | +7x |
- #' @return+ character(1L) |
||
13 | +128 |
- #' `eval_code` returns a `teal_data_module` object with a delayed evaluation of `code` when the module is run.+ ), |
||
14 | +129 |
- #'+ ")" |
||
15 | +130 |
- #' @examples+ ) |
||
16 | +131 |
- #' eval_code(tdm, "dataset1 <- subset(dataset1, Species == 'virginica')")+ ) |
||
17 | +132 |
- #'+ ) |
||
18 | +133 |
- #' @include teal_data_module.R+ } |
||
19 | +134 |
- #' @name eval_code+ ) |
||
20 | +135 |
- #' @rdname teal_data_module+ } |
||
21 | +136 |
- #' @aliases eval_code,teal_data_module,character-method+ }) |
||
22 | +137 |
- #' @aliases eval_code,teal_data_module,language-method+ + |
+ ||
138 | +81x | +
+ NULL |
||
23 | +139 |
- #' @aliases eval_code,teal_data_module,expression-method+ } |
||
24 | +140 |
- #'+ ) |
||
25 | +141 |
- #' @importFrom methods setMethod+ } |
||
26 | +142 |
- #' @importMethodsFrom teal.code eval_code+ |
||
27 | +143 |
- #'+ #' @rdname module_data_summary |
||
28 | +144 |
- setMethod("eval_code", signature = c("teal_data_module", "character"), function(object, code) {+ get_filter_overview_wrapper <- function(teal_data) { |
||
29 | -9x | +145 | +81x |
- teal_data_module(+ datanames <- teal.data::datanames(teal_data()) |
30 | -9x | +146 | +81x |
- ui = function(id) {+ joinkeys <- teal.data::join_keys(teal_data()) |
31 | -1x | +|||
147 | +
- ns <- NS(id)+ |
|||
32 | -1x | +148 | +81x |
- object$ui(ns("mutate_inner"))+ current_data_objs <- sapply( |
33 | -+ | |||
149 | +81x |
- },+ datanames, |
||
34 | -9x | +150 | +81x |
- server = function(id) {+ function(name) teal.code::get_var(teal_data(), name), |
35 | -7x | +151 | +81x |
- moduleServer(id, function(input, output, session) {+ simplify = FALSE |
36 | -7x | +|||
152 | +
- teal_data_rv <- object$server("mutate_inner")+ ) |
|||
37 | -6x | +153 | +81x |
- td <- eventReactive(teal_data_rv(),+ initial_data_objs <- teal.code::get_var(teal_data(), ".raw_data") |
38 | +154 |
- {+ |
||
39 | -6x | +155 | +81x |
- if (inherits(teal_data_rv(), c("teal_data", "qenv.error"))) {+ out <- lapply( |
40 | -4x | +156 | +81x |
- eval_code(teal_data_rv(), code)+ datanames, |
41 | -+ | |||
157 | +81x |
- } else {+ function(dataname) { |
||
42 | -2x | +158 | +149x |
- teal_data_rv()+ parent <- teal.data::parent(joinkeys, dataname) |
43 | +159 |
- }+ # todo: what should we display for a parent dataset? |
||
44 | +160 |
- },+ # - Obs and Subjects |
||
45 | -6x | +|||
161 | +
- ignoreNULL = FALSE+ # - Obs only |
|||
46 | +162 |
- )+ # - Subjects only |
||
47 | -6x | +|||
163 | +
- td+ # todo (for later): summary table should be displayed in a way that child datasets |
|||
48 | +164 |
- })+ # are indented under their parent dataset to form a tree structure |
||
49 | -+ | |||
165 | +149x |
- }+ subject_keys <- if (length(parent) > 0) { |
||
50 | -+ | |||
166 | +7x |
- )+ names(joinkeys[dataname, parent]) |
||
51 | +167 |
- })+ } else { |
||
52 | -+ | |||
168 | +142x |
-
+ joinkeys[dataname, dataname] |
||
53 | +169 |
- setMethod("eval_code", signature = c("teal_data_module", "language"), function(object, code) {+ } |
||
54 | -1x | +170 | +149x |
- eval_code(object, code = paste(lang2calls(code), collapse = "\n"))+ get_filter_overview( |
55 | -+ | |||
171 | +149x |
- })+ current_data = current_data_objs[[dataname]], |
||
56 | -+ | |||
172 | +149x |
-
+ initial_data = initial_data_objs[[dataname]], |
||
57 | -+ | |||
173 | +149x |
- setMethod("eval_code", signature = c("teal_data_module", "expression"), function(object, code) {+ dataname = dataname, |
||
58 | -2x | +174 | +149x |
- eval_code(object, code = paste(lang2calls(code), collapse = "\n"))+ subject_keys = subject_keys |
59 | +175 |
- })+ ) |
1 | +176 |
- # This is the main function from teal to be used by the end-users. Although it delegates+ } |
||
2 | +177 |
- # directly to `module_teal_with_splash.R`, we keep it in a separate file because its documentation is quite large+ ) |
||
3 | +178 |
- # and it is very end-user oriented. It may also perform more argument checking with more informative+ + |
+ ||
179 | +81x | +
+ do.call(.smart_rbind, out) |
||
4 | +180 |
- # error messages.+ } |
||
5 | +181 | |||
6 | +182 |
- #' Create the server and UI function for the `shiny` app+ |
||
7 | +183 |
- #'+ #' @rdname module_data_summary |
||
8 | +184 |
- #' @description `r lifecycle::badge("stable")`+ #' @param current_data (`object`) current object (after filtering and transforming). |
||
9 | +185 |
- #'+ #' @param initial_data (`object`) initial object. |
||
10 | +186 |
- #' End-users: This is the most important function for you to start a+ #' @param dataname (`character(1)`) |
||
11 | +187 |
- #' `teal` app that is composed of `teal` modules.+ #' @param subject_keys (`character`) names of the columns which determine a single unique subjects |
||
12 | +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) |
||
13 | -+ | |||
191 | +8x |
- #' @param data (`teal_data` or `teal_data_module`)+ } else if (inherits(current_data, "MultiAssayExperiment")) { |
||
14 | -+ | |||
192 | +1x |
- #' For constructing the data object, refer to [teal_data()] and [teal_data_module()].+ get_filter_overview_MultiAssayExperiment(current_data, initial_data, dataname) |
||
15 | +193 |
- #' If `datanames` are not set for the `teal_data` object, defaults from the `teal_data` environment will be used.+ } else { |
||
16 | -+ | |||
194 | +7x |
- #' @param modules (`list` or `teal_modules` or `teal_module`)+ data.frame(dataname = dataname) |
||
17 | +195 |
- #' Nested list of `teal_modules` or `teal_module` objects or a single+ } |
||
18 | +196 |
- #' `teal_modules` or `teal_module` object. These are the specific output modules which+ } |
||
19 | +197 |
- #' will be displayed in the `teal` application. See [modules()] and [module()] for+ |
||
20 | +198 |
- #' more details.+ #' @rdname module_data_summary |
||
21 | +199 |
- #' @param filter (`teal_slices`) Optionally,+ get_filter_overview_array <- function(current_data, |
||
22 | +200 |
- #' specifies the initial filter using [teal_slices()].+ initial_data, |
||
23 | +201 |
- #' @param title (`shiny.tag` or `character(1)`) Optionally,+ dataname, |
||
24 | +202 |
- #' the browser window title. Defaults to a title "teal app" with the icon of NEST.+ subject_keys) { |
||
25 | -+ | |||
203 | +146x |
- #' Can be created using the `build_app_title()` or+ if (length(subject_keys) == 0) { |
||
26 | -+ | |||
204 | +133x |
- #' by passing a valid `shiny.tag` which is a head tag with title and link tag.+ data.frame( |
||
27 | -+ | |||
205 | +133x |
- #' @param header (`shiny.tag` or `character(1)`) Optionally,+ dataname = dataname, |
||
28 | -+ | |||
206 | +133x |
- #' the header of the app.+ obs = if (!is.null(initial_data)) { |
||
29 | -+ | |||
207 | +124x |
- #' @param footer (`shiny.tag` or `character(1)`) Optionally,+ sprintf("%s/%s", nrow(current_data), nrow(initial_data)) |
||
30 | +208 |
- #' the footer of the app.+ } else { |
||
31 | -+ | |||
209 | +9x |
- #' @param id (`character`) Optionally,+ nrow(current_data) |
||
32 | +210 |
- #' a string specifying the `shiny` module id in cases it is used as a `shiny` module+ } |
||
33 | +211 |
- #' rather than a standalone `shiny` app. This is a legacy feature.+ ) |
||
34 | +212 |
- #' @param landing_popup (`teal_module_landing`) Optionally,+ } else { |
||
35 | -+ | |||
213 | +13x |
- #' a `landing_popup_module` to show up as soon as the teal app is initialized.+ data.frame( |
||
36 | -+ | |||
214 | +13x |
- #'+ dataname = dataname, |
||
37 | -+ | |||
215 | +13x |
- #' @return Named list containing server and UI functions.+ obs = if (!is.null(initial_data)) { |
||
38 | -+ | |||
216 | +13x |
- #'+ sprintf("%s/%s", nrow(current_data), nrow(initial_data)) |
||
39 | +217 |
- #' @export+ } else { |
||
40 | -+ | |||
218 | +! |
- #'+ nrow(current_data) |
||
41 | +219 |
- #' @include modules.R+ }, |
||
42 | -+ | |||
220 | +13x |
- #'+ subjects = if (!is.null(initial_data)) { |
||
43 | -+ | |||
221 | +13x |
- #' @examples+ sprintf("%s/%s", nrow(unique(current_data[subject_keys])), nrow(unique(initial_data[subject_keys]))) |
||
44 | +222 |
- #' app <- init(+ } else { |
||
45 | -+ | |||
223 | +! |
- #' data = within(+ nrow(unique(current_data[subject_keys])) |
||
46 | +224 |
- #' teal_data(),+ } |
||
47 | +225 |
- #' {+ ) |
||
48 | +226 |
- #' new_iris <- transform(iris, id = seq_len(nrow(iris)))+ } |
||
49 | +227 |
- #' new_mtcars <- transform(mtcars, id = seq_len(nrow(mtcars)))+ } |
||
50 | +228 |
- #' }+ |
||
51 | +229 |
- #' ),+ #' @rdname module_data_summary |
||
52 | +230 |
- #' modules = modules(+ get_filter_overview_MultiAssayExperiment <- function(current_data, # nolint: object_length, object_name. |
||
53 | +231 |
- #' module(+ initial_data, |
||
54 | +232 |
- #' label = "data source",+ dataname) { |
||
55 | -+ | |||
233 | +1x |
- #' server = function(input, output, session, data) {},+ experiment_names <- names(current_data) |
||
56 | -+ | |||
234 | +1x |
- #' ui = function(id, ...) tags$div(p("information about data source")),+ mae_info <- data.frame( |
||
57 | -+ | |||
235 | +1x |
- #' datanames = "all"+ dataname = dataname, |
||
58 | -+ | |||
236 | +1x |
- #' ),+ subjects = if (!is.null(initial_data)) { |
||
59 | -+ | |||
237 | +! |
- #' example_module(label = "example teal module"),+ sprintf("%s/%s", nrow(current_data@colData), nrow(initial_data@colData)) |
||
60 | +238 |
- #' module(+ } else { |
||
61 | -+ | |||
239 | +1x |
- #' "Iris Sepal.Length histogram",+ nrow(current_data@colData) |
||
62 | +240 |
- #' server = function(input, output, session, data) {+ } |
||
63 | +241 |
- #' output$hist <- renderPlot(+ ) |
||
64 | +242 |
- #' hist(data()[["new_iris"]]$Sepal.Length)+ |
||
65 | -+ | |||
243 | +1x |
- #' )+ experiment_obs_info <- do.call("rbind", lapply( |
||
66 | -+ | |||
244 | +1x |
- #' },+ experiment_names, |
||
67 | -+ | |||
245 | +1x |
- #' ui = function(id, ...) {+ function(experiment_name) { |
||
68 | -+ | |||
246 | +5x |
- #' ns <- NS(id)+ transform( |
||
69 | -+ | |||
247 | +5x |
- #' plotOutput(ns("hist"))+ get_filter_overview( |
||
70 | -+ | |||
248 | +5x |
- #' },+ current_data[[experiment_name]], |
||
71 | -+ | |||
249 | +5x |
- #' datanames = "new_iris"+ initial_data[[experiment_name]], |
||
72 | -+ | |||
250 | +5x |
- #' )+ dataname = experiment_name, |
||
73 | -+ | |||
251 | +5x |
- #' ),+ subject_keys = join_keys() # empty join keys |
||
74 | +252 |
- #' filter = teal_slices(+ ), |
||
75 | -+ | |||
253 | +5x |
- #' teal_slice(dataname = "new_iris", varname = "Species"),+ dataname = paste0(" - ", experiment_name) |
||
76 | +254 |
- #' teal_slice(dataname = "new_iris", varname = "Sepal.Length"),+ ) |
||
77 | +255 |
- #' teal_slice(dataname = "new_mtcars", varname = "cyl"),+ } |
||
78 | +256 |
- #' exclude_varnames = list(new_iris = c("Sepal.Width", "Petal.Width")),+ )) |
||
79 | +257 |
- #' module_specific = TRUE,+ |
||
80 | -+ | |||
258 | +1x |
- #' mapping = list(+ get_experiment_keys <- function(mae, experiment) { |
||
81 | -+ | |||
259 | +5x |
- #' `example teal module` = "new_iris Species",+ sample_subset <- mae@sampleMap[mae@sampleMap$colname %in% colnames(experiment), ] |
||
82 | -+ | |||
260 | +5x |
- #' `Iris Sepal.Length histogram` = "new_iris Species",+ length(unique(sample_subset$primary)) |
||
83 | +261 |
- #' global_filters = "new_mtcars cyl"+ } |
||
84 | +262 |
- #' )+ |
||
85 | -+ | |||
263 | +1x |
- #' ),+ experiment_subjects_info <- do.call("rbind", lapply( |
||
86 | -+ | |||
264 | +1x |
- #' title = "App title",+ experiment_names, |
||
87 | -+ | |||
265 | +1x |
- #' header = tags$h1("Sample App"),+ function(experiment_name) { |
||
88 | -+ | |||
266 | +5x |
- #' footer = tags$p("Sample footer")+ data.frame( |
||
89 | -+ | |||
267 | +5x |
- #' )+ subjects = if (!is.null(initial_data)) { |
||
90 | -+ | |||
268 | +! |
- #' if (interactive()) {+ sprintf( |
||
91 | -+ | |||
269 | +! |
- #' shinyApp(app$ui, app$server)+ "%s/%s", |
||
92 | -+ | |||
270 | +! |
- #' }+ get_experiment_keys(current_data, current_data[[experiment_name]]), |
||
93 | -+ | |||
271 | +! |
- #'+ get_experiment_keys(current_data, initial_data[[experiment_name]]) |
||
94 | +272 |
- init <- function(data,+ ) |
||
95 | +273 |
- modules,+ } else { |
||
96 | -+ | |||
274 | +5x |
- filter = teal_slices(),+ get_experiment_keys(current_data, current_data[[experiment_name]]) |
||
97 | +275 |
- title = build_app_title(),+ } |
||
98 | +276 |
- header = tags$p(),+ ) |
||
99 | +277 |
- footer = tags$p(),+ } |
||
100 | +278 |
- id = character(0),+ )) |
||
101 | +279 |
- landing_popup = NULL) {+ |
||
102 | -12x | +280 | +1x |
- logger::log_debug("init initializing teal app with: data ('{ class(data) }').")+ experiment_info <- cbind(experiment_obs_info, experiment_subjects_info) |
103 | -+ | |||
281 | +1x |
-
+ .smart_rbind(mae_info, experiment_info) |
||
104 | +282 |
- # argument checking (independent)+ } |
105 | +1 |
- ## `data`+ #' App state management. |
||
106 | -12x | +|||
2 | +
- if (inherits(data, "TealData")) {+ #' |
|||
107 | -! | +|||
3 | +
- lifecycle::deprecate_stop(+ #' @description |
|||
108 | -! | +|||
4 | +
- when = "0.15.0",+ #' `r lifecycle::badge("experimental")` |
|||
109 | -! | +|||
5 | +
- what = "init(data)",+ #' |
|||
110 | -! | +|||
6 | +
- paste(+ #' Capture and restore the global (app) input state. |
|||
111 | -! | +|||
7 | +
- "TealData is no longer supported. Use teal_data() instead.",+ #' |
|||
112 | -! | +|||
8 | +
- "Please follow migration instructions https://github.com/insightsengineering/teal/discussions/988."+ #' @details |
|||
113 | +9 |
- )+ #' This module introduces bookmarks into `teal` apps: the `shiny` bookmarking mechanism becomes enabled |
||
114 | +10 |
- )+ #' and server-side bookmarks can be created. |
||
115 | +11 |
- }+ #' |
||
116 | -12x | +|||
12 | +
- checkmate::assert_multi_class(data, c("teal_data", "teal_data_module"))+ #' The bookmark manager presents a button with the bookmark icon and is placed in the tab-bar. |
|||
117 | -12x | +|||
13 | +
- checkmate::assert_class(landing_popup, "teal_module_landing", null.ok = TRUE)+ #' When clicked, the button creates a bookmark and opens a modal which displays the bookmark URL. |
|||
118 | +14 |
-
+ #' |
||
119 | +15 |
- ## `modules`+ #' `teal` does not guarantee that all modules (`teal_module` objects) are bookmarkable. |
||
120 | -12x | +|||
16 | +
- checkmate::assert(+ #' Those that are, have a `teal_bookmarkable` attribute set to `TRUE`. If any modules are not bookmarkable, |
|||
121 | -12x | +|||
17 | +
- .var.name = "modules",+ #' the bookmark manager modal displays a warning and the bookmark button displays a flag. |
|||
122 | -12x | +|||
18 | +
- checkmate::check_multi_class(modules, c("teal_modules", "teal_module")),+ #' In order to communicate that a external module is bookmarkable, the module developer |
|||
123 | -12x | +|||
19 | +
- checkmate::check_list(modules, min.len = 1, any.missing = FALSE, types = c("teal_module", "teal_modules"))+ #' should set the `teal_bookmarkable` attribute to `TRUE`. |
|||
124 | +20 |
- )+ #' |
||
125 | -12x | +|||
21 | +
- if (inherits(modules, "teal_module")) {+ #' @section Server logic: |
|||
126 | -1x | +|||
22 | +
- modules <- list(modules)+ #' A bookmark is a URL that contains the app address with a `/?_state_id_=<bookmark_dir>` suffix. |
|||
127 | +23 |
- }+ #' `<bookmark_dir>` is a directory created on the server, where the state of the application is saved. |
||
128 | -12x | +|||
24 | +
- if (checkmate::test_list(modules, min.len = 1, any.missing = FALSE, types = c("teal_module", "teal_modules"))) {+ #' Accessing the bookmark URL opens a new session of the app that starts in the previously saved state. |
|||
129 | -6x | +|||
25 | +
- modules <- do.call(teal::modules, modules)+ #' |
|||
130 | +26 |
- }+ #' @section Note: |
||
131 | +27 |
-
+ #' To enable bookmarking use either: |
||
132 | +28 |
- ## `filter`+ #' - `shiny` app by using `shinyApp(..., enableBookmarking = "server")` (not supported in `shinytest2`) |
||
133 | -12x | +|||
29 | +
- checkmate::assert_class(filter, "teal_slices")+ #' - set `options(shiny.bookmarkStore = "server")` before running the app |
|||
134 | +30 |
-
+ #' |
||
135 | +31 |
- ## all other arguments+ #' |
||
136 | -11x | +|||
32 | +
- checkmate::assert(+ #' @inheritParams init |
|||
137 | -11x | +|||
33 | +
- .var.name = "title",+ #' |
|||
138 | -11x | +|||
34 | +
- checkmate::check_string(title),+ #' @return Invisible `NULL`. |
|||
139 | -11x | +|||
35 | +
- checkmate::check_multi_class(title, c("shiny.tag", "shiny.tag.list", "html"))+ #' |
|||
140 | +36 |
- )+ #' @aliases bookmark bookmark_manager bookmark_manager_module |
||
141 | -11x | +|||
37 | +
- checkmate::assert(+ #' |
|||
142 | -11x | +|||
38 | +
- .var.name = "header",+ #' @name module_bookmark_manager |
|||
143 | -11x | +|||
39 | +
- checkmate::check_string(header),+ #' @rdname module_bookmark_manager |
|||
144 | -11x | +|||
40 | +
- checkmate::check_multi_class(header, c("shiny.tag", "shiny.tag.list", "html"))+ #' |
|||
145 | +41 |
- )+ #' @keywords internal |
||
146 | -11x | +|||
42 | +
- checkmate::assert(+ #' |
|||
147 | -11x | +|||
43 | +
- .var.name = "footer",+ NULL |
|||
148 | -11x | +|||
44 | +
- checkmate::check_string(footer),+ |
|||
149 | -11x | +|||
45 | +
- checkmate::check_multi_class(footer, c("shiny.tag", "shiny.tag.list", "html"))+ #' @rdname module_bookmark_manager |
|||
150 | +46 |
- )+ ui_bookmark_panel <- function(id, modules) { |
||
151 | -11x | +|||
47 | +! |
- checkmate::assert_character(id, max.len = 1, any.missing = FALSE)+ ns <- NS(id) |
||
152 | +48 | |||
153 | -+ | |||
49 | +! |
- # log+ bookmark_option <- get_bookmarking_option() |
||
154 | -11x | +|||
50 | +! |
- teal.logger::log_system_info()+ is_unbookmarkable <- need_bookmarking(modules)+ |
+ ||
51 | +! | +
+ shinyOptions(bookmarkStore = bookmark_option) |
||
155 | +52 | |||
156 | +53 |
- # argument transformations+ # Render bookmark warnings count |
||
157 | -+ | |||
54 | +! |
- ## `modules` - landing module+ if (!all(is_unbookmarkable) && identical(bookmark_option, "server")) { |
||
158 | -11x | +|||
55 | +! |
- landing <- extract_module(modules, "teal_module_landing")+ tags$button( |
||
159 | -11x | +|||
56 | +! |
- if (length(landing) == 1L) {+ id = ns("do_bookmark"), |
||
160 | +57 | ! |
- landing_popup <- landing[[1L]]+ class = "btn action-button wunder_bar_button bookmark_manager_button", |
|
161 | +58 | ! |
- modules <- drop_module(modules, "teal_module_landing")+ title = "Add bookmark", |
|
162 | +59 | ! |
- lifecycle::deprecate_soft(+ tags$span( |
|
163 | +60 | ! |
- when = "0.15.3",+ suppressMessages(icon("fas fa-bookmark")), |
|
164 | +61 | ! |
- what = "landing_popup_module()",+ if (any(is_unbookmarkable)) { |
|
165 | +62 | ! |
- details = paste(+ tags$span( |
|
166 | +63 | ! |
- "Pass `landing_popup_module` to the `landing_popup` argument of the `init` ",+ sum(is_unbookmarkable), |
|
167 | +64 | ! |
- "instead of wrapping it into `modules()` and passing to the `modules` argument"+ class = "badge-warning badge-count text-white bg-danger" |
|
168 | +65 | ++ |
+ )+ |
+ |
66 | ++ |
+ }+ |
+ ||
67 |
) |
|||
169 | +68 | ++ |
+ )+ |
+ |
69 | ++ |
+ }+ |
+ ||
70 | ++ |
+ }+ |
+ ||
71 | ++ | + + | +||
72 | ++ |
+ #' @rdname module_bookmark_manager+ |
+ ||
73 |
- )+ srv_bookmark_panel <- function(id, modules) {+ |
+ |||
74 | +82x | +
+ checkmate::assert_character(id) |
||
170 | -11x | +75 | +82x |
- } else if (length(landing) > 1L) {+ checkmate::assert_class(modules, "teal_modules") |
171 | -! | +|||
76 | +82x |
- stop("Only one `landing_popup_module` can be used.")+ moduleServer(id, function(input, output, session) { |
||
172 | -+ | |||
77 | +82x |
- }+ logger::log_debug("bookmark_manager_srv initializing") |
||
173 | -+ | |||
78 | +82x |
-
+ ns <- session$ns |
||
174 | -+ | |||
79 | +82x |
- ## `filter` - set app_id attribute unless present (when restoring bookmark)+ bookmark_option <- get_bookmarking_option() |
||
175 | -11x | +80 | +82x |
- if (is.null(attr(filter, "app_id", exact = TRUE))) attr(filter, "app_id") <- create_app_id(data, modules)+ is_unbookmarkable <- need_bookmarking(modules) |
176 | +81 | |||
177 | +82 |
- ## `filter` - convert teal.slice::teal_slices to teal::teal_slices- |
- ||
178 | -11x | -
- filter <- as.teal_slices(as.list(filter))+ # Set up bookmarking callbacks ---- |
||
179 | +83 |
-
+ # Register bookmark exclusions: do_bookmark button to avoid re-bookmarking |
||
180 | -+ | |||
84 | +82x |
- # argument checking (interdependent)+ setBookmarkExclude(c("do_bookmark")) |
||
181 | +85 |
- ## `filter` - `modules`+ # This bookmark can only be used on the app session. |
||
182 | -11x | +86 | +82x |
- if (isTRUE(attr(filter, "module_specific"))) {+ app_session <- .subset2(session, "parent") |
183 | -! | +|||
87 | +82x |
- module_names <- unlist(c(module_labels(modules), "global_filters"))+ app_session$onBookmarked(function(url) { |
||
184 | +88 | ! |
- failed_mod_names <- setdiff(names(attr(filter, "mapping")), module_names)+ logger::log_debug("bookmark_manager_srv@onBookmarked: bookmark button clicked, registering bookmark") |
|
185 | +89 | ! |
- if (length(failed_mod_names)) {+ modal_content <- if (bookmark_option != "server") { |
|
186 | +90 | ! |
- stop(+ msg <- sprintf( |
|
187 | +91 | ! |
- sprintf(+ "Bookmarking has been set to \"%s\".\n%s\n%s", |
|
188 | +92 | ! |
- "Some module names in the mapping arguments don't match module labels.\n %s not in %s",+ bookmark_option, |
|
189 | +93 | ! |
- toString(failed_mod_names),+ "Only server-side bookmarking is supported.", |
|
190 | +94 | ! |
- toString(unique(module_names))+ "Please contact your app developer." |
|
191 | +95 |
) |
||
192 | -+ | |||
96 | +! |
- )+ tags$div(+ |
+ ||
97 | +! | +
+ tags$p(msg, class = "text-warning") |
||
193 | +98 |
- }+ ) |
||
194 | +99 |
-
+ } else { |
||
195 | +100 | ! |
- if (anyDuplicated(module_names)) {+ tags$div( |
|
196 | -+ | |||
101 | +! |
- # In teal we are able to set nested modules with duplicated label.+ tags$span( |
||
197 | -+ | |||
102 | +! |
- # Because mapping argument bases on the relationship between module-label and filter-id,+ tags$pre(url) |
||
198 | +103 |
- # it is possible that module-label in mapping might refer to multiple teal_module (identified by the same label)+ ), |
||
199 | +104 | ! |
- stop(+ if (any(is_unbookmarkable)) { |
|
200 | +105 | ! |
- sprintf(+ bkmb_summary <- rapply2( |
|
201 | +106 | ! |
- "Module labels should be unique when teal_slices(mapping = TRUE). Duplicated labels:\n%s ",+ modules_bookmarkable(modules), |
|
202 | +107 | ! |
- toString(module_names[duplicated(module_names)])- |
- |
203 | -- |
- )+ function(x) { |
||
204 | -+ | |||
108 | +! |
- )+ if (isTRUE(x)) { |
||
205 | -+ | |||
109 | +! |
- }+ "\u2705" # check mark |
||
206 | -+ | |||
110 | +! |
- }+ } else if (isFALSE(x)) { |
||
207 | -+ | |||
111 | +! |
-
+ "\u274C" # cross mark |
||
208 | +112 |
- ## `data` - `modules`+ } else { |
||
209 | -11x | +|||
113 | +! |
- if (inherits(data, "teal_data")) {+ "\u2753" # question mark |
||
210 | -10x | +|||
114 | +
- if (length(ls(teal.code::get_env(data))) == 0) {+ } |
|||
211 | -1x | +|||
115 | +
- stop("The environment of `data` is empty.")+ } |
|||
212 | +116 |
- }+ ) |
||
213 | -+ | |||
117 | +! |
-
+ tags$div( |
||
214 | -9x | +|||
118 | +! |
- is_modules_ok <- check_modules_datanames(modules, ls(teal.code::get_env(data)))+ tags$p( |
||
215 | -9x | +|||
119 | +! |
- if (!isTRUE(is_modules_ok) && length(unlist(extract_transformers(modules))) == 0) {+ icon("fas fa-exclamation-triangle"), |
||
216 | -2x | +|||
120 | +! |
- warning(is_modules_ok, call. = FALSE)+ "Some modules will not be restored when using this bookmark.", |
||
217 | -+ | |||
121 | +! |
- }+ tags$br(), |
||
218 | -+ | |||
122 | +! |
-
+ "Check the list below to see which modules are not bookmarkable.", |
||
219 | -9x | +|||
123 | +! |
- is_filter_ok <- check_filter_datanames(filter, ls(teal.code::get_env(data)))+ class = "text-warning" |
||
220 | -9x | +|||
124 | +
- if (!isTRUE(is_filter_ok)) {+ ), |
|||
221 | -1x | +|||
125 | +! |
- warning(is_filter_ok)+ tags$pre(yaml::as.yaml(bkmb_summary)) |
||
222 | +126 |
- # we allow app to continue if applied filters are outside+ ) |
||
223 | +127 |
- # of possible data range+ } |
||
224 | +128 |
- }+ ) |
||
225 | +129 |
- }+ } |
||
226 | +130 | |||
227 | -10x | +|||
131 | +! |
- reporter <- teal.reporter::Reporter$new()$set_id(attr(filter, "app_id"))+ showModal( |
||
228 | -10x | +|||
132 | +! |
- if (is_arg_used(modules, "reporter") && length(extract_module(modules, "teal_module_previewer")) == 0) {+ modalDialog( |
||
229 | +133 | ! |
- modules <- append_module(+ id = ns("bookmark_modal"), |
|
230 | +134 | ! |
- modules,+ title = "Bookmarked teal app url", |
|
231 | +135 | ! |
- reporter_previewer_module(server_args = list(previewer_buttons = c("download", "reset")))+ modal_content, |
|
232 | -+ | |||
136 | +! |
- )+ easyClose = TRUE |
||
233 | +137 |
- }+ ) |
||
234 | +138 |
-
+ ) |
||
235 | -10x | +|||
139 | +
- ns <- NS(id)+ }) |
|||
236 | +140 |
- # Note: UI must be a function to support bookmarking.+ |
||
237 | -10x | +|||
141 | +
- res <- list(+ # manually trigger bookmarking because of the problems reported on windows with bookmarkButton in teal |
|||
238 | -10x | +142 | +82x |
- ui = function(request) {+ observeEvent(input$do_bookmark, { |
239 | +143 | ! |
- ui_teal(+ logger::log_debug("bookmark_manager_srv@1 do_bookmark module clicked.") |
|
240 | +144 | ! |
- id = ns("teal"),+ session$doBookmark() |
|
241 | -! | +|||
145 | +
- modules = modules,+ }) |
|||
242 | -! | +|||
146 | +
- title = title,+ |
|||
243 | -! | +|||
147 | +82x |
- header = header,+ invisible(NULL) |
||
244 | -! | +|||
148 | +
- footer = footer+ }) |
|||
245 | +149 |
- )+ } |
||
246 | +150 |
- },+ + |
+ ||
151 | ++ | + + | +||
152 | ++ |
+ #' @rdname module_bookmark_manager+ |
+ ||
153 | ++ |
+ get_bookmarking_option <- function() { |
||
247 | -10x | +154 | +82x |
- server = function(input, output, session) {+ bookmark_option <- getShinyOption("bookmarkStore") |
248 | -! | +|||
155 | +82x |
- if (!is.null(landing_popup)) {+ if (is.null(bookmark_option) && identical(getOption("shiny.bookmarkStore"), "server")) { |
||
249 | +156 | ! |
- do.call(landing_popup$server, c(list(id = "landing_module_shiny_id"), landing_popup$server_args))+ bookmark_option <- getOption("shiny.bookmarkStore") |
|
250 | +157 |
- }+ } |
||
251 | -! | +|||
158 | +82x |
- srv_teal(id = ns("teal"), data = data, modules = modules, filter = deep_copy_filter(filter))+ bookmark_option |
||
252 | +159 |
- }+ } |
||
253 | +160 |
- )+ |
||
254 | +161 |
-
+ #' @rdname module_bookmark_manager |
||
255 | -10x | +|||
162 | +
- logger::log_debug("init teal app has been initialized.")+ need_bookmarking <- function(modules) { |
|||
256 | -+ | |||
163 | +82x |
-
+ unlist(rapply2( |
||
257 | -10x | +164 | +82x |
- res+ modules_bookmarkable(modules), |
258 | -+ | |||
165 | +82x |
- }+ Negate(isTRUE) |
1 | +166 |
- #' Get client timezone+ )) |
||
2 | +167 |
- #'+ } |
||
3 | +168 |
- #' User timezone in the browser may be different to the one on the server.+ |
||
4 | +169 |
- #' This script can be run to register a `shiny` input which contains information about the timezone in the browser.+ |
||
5 | +170 |
- #'+ # utilities ---- |
||
6 | +171 |
- #' @param ns (`function`) namespace function passed from the `session` object in the `shiny` server.+ |
||
7 | +172 |
- #' For `shiny` modules this will allow for proper name spacing of the registered input.+ #' Restore value from bookmark. |
||
8 | +173 |
#' |
||
9 | +174 |
- #' @return `NULL`, invisibly.+ #' Get value from bookmark or return default. |
||
10 | +175 |
#' |
||
11 | +176 |
- #' @keywords internal+ #' Bookmarks can store not only inputs but also arbitrary values. |
||
12 | +177 |
- #'+ #' These values are stored by `onBookmark` callbacks and restored by `onBookmarked` callbacks, |
||
13 | +178 |
- get_client_timezone <- function(ns) {- |
- ||
14 | -83x | -
- script <- sprintf(+ #' and they are placed in the `values` environment in the `session$restoreContext` field. |
||
15 | -83x | +|||
179 | +
- "Shiny.setInputValue(`%s`, Intl.DateTimeFormat().resolvedOptions().timeZone)",+ #' Using `teal_data_module` makes it impossible to run the callbacks |
|||
16 | -83x | +|||
180 | +
- ns("timezone")+ #' because the app becomes ready before modules execute and callbacks are registered. |
|||
17 | +181 |
- )+ #' In those cases the stored values can still be recovered from the `session` object directly. |
||
18 | -83x | +|||
182 | +
- shinyjs::runjs(script) # function does not return anything+ #' |
|||
19 | -83x | +|||
183 | +
- invisible(NULL)+ #' Note that variable names in the `values` environment are prefixed with module name space names, |
|||
20 | +184 |
- }+ #' therefore, when using this function in modules, `value` must be run through the name space function. |
||
21 | +185 |
-
+ #' |
||
22 | +186 |
- #' Resolve the expected bootstrap theme+ #' @param value (`character(1)`) name of value to restore |
||
23 | +187 |
- #' @noRd+ #' @param default fallback value |
||
24 | +188 |
- #' @keywords internal+ #' |
||
25 | +189 |
- get_teal_bs_theme <- function() {+ #' @return |
||
26 | -4x | +|||
190 | +
- bs_theme <- getOption("teal.bs_theme")+ #' In an application restored from a server-side bookmark, |
|||
27 | +191 |
-
+ #' the variable specified by `value` from the `values` environment. |
||
28 | -4x | +|||
192 | +
- if (is.null(bs_theme)) {+ #' Otherwise `default`. |
|||
29 | -1x | +|||
193 | +
- return(NULL)+ #' |
|||
30 | +194 |
- }+ #' @keywords internal |
||
31 | +195 |
-
+ #' |
||
32 | -3x | +|||
196 | +
- if (!checkmate::test_class(bs_theme, "bs_theme")) {+ restoreValue <- function(value, default) { # nolint: object_name. |
|||
33 | -2x | +197 | +164x |
- warning(+ checkmate::assert_character("value") |
34 | -2x | +198 | +164x |
- "Assertion on 'teal.bs_theme' option value failed: ",+ session_default <- shiny::getDefaultReactiveDomain() |
35 | -2x | +199 | +164x |
- checkmate::check_class(bs_theme, "bs_theme"),+ session_parent <- .subset2(session_default, "parent") |
36 | -2x | +200 | +164x |
- ". The default Shiny Bootstrap theme will be used."+ session <- if (is.null(session_parent)) session_default else session_parent |
37 | +201 |
- )+ |
||
38 | -2x | +202 | +164x |
- return(NULL)+ if (isTRUE(session$restoreContext$active) && exists(value, session$restoreContext$values, inherits = FALSE)) { |
39 | -+ | |||
203 | +! |
- }+ session$restoreContext$values[[value]] |
||
40 | +204 |
-
+ } else { |
||
41 | -1x | +205 | +164x |
- bs_theme+ default |
42 | +206 |
- }+ } |
||
43 | +207 |
-
+ } |
||
44 | +208 |
- #' Return parentnames along with datanames.+ |
||
45 | +209 |
- #' @noRd+ #' Compare bookmarks. |
||
46 | +210 |
- #' @keywords internal+ #' |
||
47 | +211 |
- .include_parent_datanames <- function(datanames, join_keys) {+ #' Test if two bookmarks store identical state. |
||
48 | -167x | +|||
212 | +
- ordered_datanames <- datanames+ #' |
|||
49 | -167x | +|||
213 | +
- for (i in datanames) {+ #' `input` environments are compared one variable at a time and if not identical, |
|||
50 | -306x | +|||
214 | +
- parents <- character(0)+ #' values in both bookmarks are reported. States of `datatable`s are stripped |
|||
51 | -306x | +|||
215 | +
- while (length(i) > 0) {+ #' of the `time` element before comparing because the time stamp is always different. |
|||
52 | -319x | +|||
216 | +
- parent_i <- teal.data::parent(join_keys, i)+ #' The contents themselves are not printed as they are large and the contents are not informative. |
|||
53 | -319x | +|||
217 | +
- parents <- c(parent_i, parents)+ #' Elements present in one bookmark and absent in the other are also reported. |
|||
54 | -319x | +|||
218 | +
- i <- parent_i+ #' Differences are printed as messages. |
|||
55 | +219 |
- }+ #' |
||
56 | -306x | +|||
220 | +
- ordered_datanames <- c(parents, ordered_datanames)+ #' `values` environments are compared with `all.equal`. |
|||
57 | +221 |
- }+ #' |
||
58 | -167x | +|||
222 | +
- unique(ordered_datanames)+ #' @section How to use: |
|||
59 | +223 |
- }+ #' Open an application, change relevant inputs (typically, all of them), and create a bookmark. |
||
60 | +224 |
-
+ #' Then open that bookmark and immediately create a bookmark of that. |
||
61 | +225 |
- #' Return topologicaly sorted datanames+ #' If restoring bookmarks occurred properly, the two bookmarks should store the same state. |
||
62 | +226 |
- #' @noRd+ #' |
||
63 | +227 |
- #' @keywords internal+ #' |
||
64 | +228 |
- .topologically_sort_datanames <- function(datanames, join_keys) {+ #' @param book1,book2 bookmark directories stored in `shiny_bookmarks/`; |
||
65 | -135x | +|||
229 | +
- datanames_with_parents <- .include_parent_datanames(datanames, join_keys)+ #' default to the two most recently modified directories |
|||
66 | -135x | +|||
230 | +
- intersect(datanames, datanames_with_parents)+ #' |
|||
67 | +231 |
- }+ #' @return |
||
68 | +232 |
-
+ #' Invisible `NULL` if bookmarks are identical or if there are no bookmarks to test. |
||
69 | +233 |
- #' Create a `FilteredData`+ #' `FALSE` if inconsistencies are detected. |
||
70 | +234 |
#' |
||
71 | +235 |
- #' Create a `FilteredData` object from a `teal_data` object.+ #' @keywords internal |
||
72 | +236 |
#' |
||
73 | +237 |
- #' @param x (`teal_data`) object+ bookmarks_identical <- function(book1, book2) { |
||
74 | -+ | |||
238 | +! |
- #' @param datanames (`character`) vector of data set names to include; must be subset of `datanames(x)`+ if (!dir.exists("shiny_bookmarks")) { |
||
75 | -+ | |||
239 | +! |
- #' @return A `FilteredData` object.+ message("no bookmark directory") |
||
76 | -+ | |||
240 | +! |
- #' @keywords internal+ return(invisible(NULL)) |
||
77 | +241 |
- teal_data_to_filtered_data <- function(x, datanames = ls(teal.code::get_env(x))) {+ } |
||
78 | -78x | +|||
242 | +
- checkmate::assert_class(x, "teal_data")+ |
|||
79 | -78x | +|||
243 | +! |
- checkmate::assert_character(datanames, min.chars = 1L, any.missing = FALSE)+ ans <- TRUE |
||
80 | +244 |
- # Otherwise, FilteredData will be created in the modules' scope later+ |
||
81 | -78x | +|||
245 | +! |
- teal.slice::init_filtered_data(+ if (missing(book1) && missing(book2)) { |
||
82 | -78x | +|||
246 | +! |
- x = Filter(+ dirs <- list.dirs("shiny_bookmarks", recursive = FALSE) |
||
83 | -78x | +|||
247 | +! |
- length,+ bookmarks_sorted <- basename(rev(dirs[order(file.mtime(dirs))]))+ |
+ ||
248 | +! | +
+ if (length(bookmarks_sorted) < 2L) {+ |
+ ||
249 | +! | +
+ message("no bookmarks to compare") |
||
84 | -78x | +|||
250 | +! |
- sapply(datanames, function(dn) x[[dn]], simplify = FALSE)+ return(invisible(NULL)) |
||
85 | +251 |
- ),+ } |
||
86 | -78x | +|||
252 | +! |
- join_keys = teal.data::join_keys(x)+ book1 <- bookmarks_sorted[2L] |
||
87 | -+ | |||
253 | +! |
- )+ book2 <- bookmarks_sorted[1L] |
||
88 | +254 |
- }+ } else { |
||
89 | -+ | |||
255 | +! |
-
+ if (!dir.exists(file.path("shiny_bookmarks", book1))) stop(book1, " not found") |
||
90 | -+ | |||
256 | +! |
-
+ if (!dir.exists(file.path("shiny_bookmarks", book2))) stop(book2, " not found") |
||
91 | +257 |
- #' Template function for `TealReportCard` creation and customization+ } |
||
92 | +258 |
- #'+ |
||
93 | -+ | |||
259 | +! |
- #' This function generates a report card with a title,+ book1_input <- readRDS(file.path("shiny_bookmarks", book1, "input.rds")) |
||
94 | -+ | |||
260 | +! |
- #' an optional description, and the option to append the filter state list.+ book2_input <- readRDS(file.path("shiny_bookmarks", book2, "input.rds")) |
||
95 | +261 |
- #'+ |
||
96 | -+ | |||
262 | +! |
- #' @param title (`character(1)`) title of the card (unless overwritten by label)+ elements_common <- intersect(names(book1_input), names(book2_input)) |
||
97 | -+ | |||
263 | +! |
- #' @param label (`character(1)`) label provided by the user when adding the card+ dt_states <- grepl("_state$", elements_common) |
||
98 | -+ | |||
264 | +! |
- #' @param description (`character(1)`) optional, additional description+ if (any(dt_states)) { |
||
99 | -+ | |||
265 | +! |
- #' @param with_filter (`logical(1)`) flag indicating to add filter state+ for (el in elements_common[dt_states]) { |
||
100 | -+ | |||
266 | +! |
- #' @param filter_panel_api (`FilterPanelAPI`) object with API that allows the generation+ book1_input[[el]][["time"]] <- NULL |
||
101 | -+ | |||
267 | +! |
- #' of the filter state in the report+ book2_input[[el]][["time"]] <- NULL |
||
102 | +268 |
- #'+ } |
||
103 | +269 |
- #' @return (`TealReportCard`) populated with a title, description and filter state.+ } |
||
104 | +270 |
- #'+ |
||
105 | -+ | |||
271 | +! |
- #' @export+ identicals <- mapply(identical, book1_input[elements_common], book2_input[elements_common]) |
||
106 | -+ | |||
272 | +! |
- report_card_template <- function(title, label, description = NULL, with_filter, filter_panel_api) {+ non_identicals <- names(identicals[!identicals]) |
||
107 | -2x | +|||
273 | +! |
- checkmate::assert_string(title)+ compares <- sprintf("$ %s:\t%s --- %s", non_identicals, book1_input[non_identicals], book2_input[non_identicals]) |
||
108 | -2x | +|||
274 | +! |
- checkmate::assert_string(label)+ if (length(compares) != 0L) { |
||
109 | -2x | +|||
275 | +! |
- checkmate::assert_string(description, null.ok = TRUE)+ message("common elements not identical: \n", paste(compares, collapse = "\n")) |
||
110 | -2x | +|||
276 | +! |
- checkmate::assert_flag(with_filter)+ ans <- FALSE |
||
111 | -2x | +|||
277 | +
- checkmate::assert_class(filter_panel_api, classes = "FilterPanelAPI")+ } |
|||
112 | +278 | |||
113 | -2x | -
- card <- teal::TealReportCard$new()- |
- ||
114 | -2x | +|||
279 | +! |
- title <- if (label == "") title else label+ elements_boook1 <- setdiff(names(book1_input), names(book2_input)) |
||
115 | -2x | +|||
280 | +! |
- card$set_name(title)+ if (length(elements_boook1) != 0L) { |
||
116 | -2x | +|||
281 | +! |
- card$append_text(title, "header2")+ dt_states <- grepl("_state$", elements_boook1) |
||
117 | -1x | +|||
282 | +! |
- if (!is.null(description)) card$append_text(description, "header3")+ if (any(dt_states)) { |
||
118 | -1x | +|||
283 | +! |
- if (with_filter) card$append_fs(filter_panel_api$get_filter_state())+ for (el in elements_boook1[dt_states]) { |
||
119 | -2x | +|||
284 | +! |
- card+ if (is.list(book1_input[[el]])) book1_input[[el]] <- "--- data table state ---" |
||
120 | +285 |
- }+ } |
||
121 | +286 |
-
+ } |
||
122 | -+ | |||
287 | +! |
-
+ excess1 <- sprintf("$ %s:\t%s", elements_boook1, book1_input[elements_boook1]) |
||
123 | -+ | |||
288 | +! |
- #' Check `datanames` in modules+ message("elements only in book1: \n", paste(excess1, collapse = "\n")) |
||
124 | -+ | |||
289 | +! |
- #'+ ans <- FALSE |
||
125 | +290 |
- #' These functions check if specified `datanames` in modules match those in the data object,+ } |
||
126 | +291 |
- #' returning error messages or `TRUE` for successful validation. Two functions return error message+ |
||
127 | -+ | |||
292 | +! |
- #' in different forms:+ elements_boook2 <- setdiff(names(book2_input), names(book1_input)) |
||
128 | -+ | |||
293 | +! |
- #' - `check_modules_datanames` returns `character(1)` for basic assertion usage+ if (length(elements_boook2) != 0L) { |
||
129 | -+ | |||
294 | +! |
- #' - `check_modules_datanames_html` returns `shiny.tag.list` to display it in the app.+ dt_states <- grepl("_state$", elements_boook1) |
||
130 | -+ | |||
295 | +! |
- #'+ if (any(dt_states)) { |
||
131 | -+ | |||
296 | +! |
- #' @param modules (`teal_modules`) object+ for (el in elements_boook1[dt_states]) { |
||
132 | -+ | |||
297 | +! |
- #' @param datanames (`character`) names of datasets available in the `data` object+ if (is.list(book2_input[[el]])) book2_input[[el]] <- "--- data table state ---" |
||
133 | +298 |
- #'+ } |
||
134 | +299 |
- #' @return `TRUE` if validation passes, otherwise `character(1)` or `shiny.tag.list`+ } |
||
135 | -+ | |||
300 | +! |
- #' @keywords internal+ excess2 <- sprintf("$ %s:\t%s", elements_boook2, book2_input[elements_boook2]) |
||
136 | -+ | |||
301 | +! |
- check_modules_datanames <- function(modules, datanames) {+ message("elements only in book2: \n", paste(excess2, collapse = "\n")) |
||
137 | -9x | +|||
302 | +! |
- out <- check_modules_datanames_html(modules, datanames)+ ans <- FALSE |
||
138 | -9x | +|||
303 | +
- if (inherits(out, "shiny.tag.list")) {+ } |
|||
139 | -3x | +|||
304 | +
- out_with_ticks <- gsub("<code>|</code>", "`", toString(out))+ |
|||
140 | -3x | +|||
305 | +! |
- out_text <- gsub("<[^<>]+>", "", toString(out_with_ticks))+ book1_values <- readRDS(file.path("shiny_bookmarks", book1, "values.rds")) |
||
141 | -3x | +|||
306 | +! |
- trimws(gsub("[[:space:]]+", " ", out_text))+ book2_values <- readRDS(file.path("shiny_bookmarks", book2, "values.rds")) |
||
142 | +307 |
- } else {- |
- ||
143 | -6x | -
- out+ |
||
144 | -+ | |||
308 | +! |
- }+ if (!isTRUE(all.equal(book1_values, book2_values))) { |
||
145 | -+ | |||
309 | +! |
- }+ message("different values detected") |
||
146 | -+ | |||
310 | +! |
-
+ message("choices for numeric filters MAY be different, see RangeFilterState$set_choices") |
||
147 | -+ | |||
311 | +! |
- #' @rdname check_modules_datanames+ ans <- FALSE |
||
148 | +312 |
- check_modules_datanames_html <- function(modules,+ } |
||
149 | +313 |
- datanames) {+ |
||
150 | -178x | +|||
314 | +! |
- check_datanames <- check_modules_datanames_recursive(modules, datanames)+ if (ans) message("perfect!") |
||
151 | -178x | +|||
315 | +! |
- show_module_info <- inherits(modules, "teal_modules") # used in two contexts - module and app+ invisible(NULL) |
||
152 | -178x | +|||
316 | +
- if (!length(check_datanames)) {+ } |
|||
153 | -160x | +|||
317 | +
- return(TRUE)+ |
|||
154 | +318 |
- }+ |
||
155 | -18x | +|||
319 | +
- shiny::tagList(+ # Replacement for [base::rapply] which doesn't handle NULL values - skips the evaluation |
|||
156 | -18x | +|||
320 | +
- lapply(+ # of the function and returns NULL for given element. |
|||
157 | -18x | +|||
321 | +
- check_datanames,+ rapply2 <- function(x, f) { |
|||
158 | -18x | +322 | +189x |
- function(mod) {+ if (inherits(x, "list")) { |
159 | -18x | +323 | +82x |
- tagList(+ lapply(x, rapply2, f = f) |
160 | -18x | +|||
324 | +
- tags$span(+ } else { |
|||
161 | -18x | +325 | +107x |
- tags$span(if (length(mod$missing_datanames) == 1) "Dataset" else "Datasets"),+ f(x) |
162 | -18x | +|||
326 | +
- to_html_code_list(mod$missing_datanames),+ } |
|||
163 | -18x | +|||
327 | +
- tags$span(+ } |
|||
164 | -18x | +
1 | +
- paste0(+ #' Generate lockfile for application's environment reproducibility |
|||
165 | -18x | +|||
2 | +
- if (length(mod$missing_datanames) > 1) "are missing" else "is missing",+ #' |
|||
166 | -18x | +|||
3 | +
- if (show_module_info) sprintf(" for module '%s'.", mod$label) else "."+ #' @param lockfile_path (`character`) path to the lockfile. |
|||
167 | +4 |
- )+ #' |
||
168 | +5 |
- )+ #' @section Different ways of creating lockfile: |
||
169 | +6 |
- ),+ #' `teal` leverages [renv::snapshot()], which offers multiple methods for lockfile creation. |
||
170 | -18x | +|||
7 | +
- if (length(datanames) >= 1) {+ #' |
|||
171 | -16x | +|||
8 | +
- tagList(+ #' - **Working directory lockfile**: `teal`, by default, will create an `implicit` type lockfile that uses |
|||
172 | -16x | +|||
9 | +
- tags$span(if (length(datanames) == 1) "Dataset" else "Datasets"),+ #' `renv::dependencies()` to detect all R packages in the current project's working directory. |
|||
173 | -16x | +|||
10 | +
- tags$span("available in data:"),+ #' - **`DESCRIPTION`-based lockfile**: To generate a lockfile based on a `DESCRIPTION` file in your working |
|||
174 | -16x | +|||
11 | +
- tagList(+ #' directory, set `renv::settings$snapshot.type("explicit")`. The naming convention for `type` follows |
|||
175 | -16x | +|||
12 | +
- tags$span(+ #' `renv::snapshot()`. For the `"explicit"` type, refer to `renv::settings$package.dependency.fields()` for the |
|||
176 | -16x | +|||
13 | +
- to_html_code_list(datanames),+ #' `DESCRIPTION` fields included in the lockfile. |
|||
177 | -16x | +|||
14 | +
- tags$span(".", .noWS = "outside"),+ #' - **Custom files-based lockfile**: To specify custom files as the basis for the lockfile, set |
|||
178 | -16x | +|||
15 | +
- .noWS = c("outside")+ #' `renv::settings$snapshot.type("custom")` and configure the `renv.snapshot.filter` option. |
|||
179 | +16 |
- )+ #' |
||
180 | +17 |
- )+ #' @section lockfile usage: |
||
181 | +18 |
- )+ #' After creating the lockfile, you can restore the application's environment using `renv::restore()`. |
||
182 | +19 |
- } else {+ #' |
||
183 | -2x | +|||
20 | +
- tags$span("No datasets are available in data.")+ #' @seealso [renv::snapshot()], [renv::restore()]. |
|||
184 | +21 |
- },+ #' |
||
185 | -18x | +|||
22 | +
- tags$br(.noWS = "before")+ #' @return `NULL` |
|||
186 | +23 |
- )+ #' |
||
187 | +24 |
- }+ #' @name module_teal_lockfile |
||
188 | +25 |
- )+ #' @rdname module_teal_lockfile |
||
189 | +26 |
- )+ #' |
||
190 | +27 |
- }+ #' @keywords internal |
||
191 | +28 |
-
+ NULL |
||
192 | +29 |
- #' Recursively checks modules and returns list for every datanames mismatch between module and data+ |
||
193 | +30 |
- #' @noRd+ #' @rdname module_teal_lockfile |
||
194 | +31 |
- check_modules_datanames_recursive <- function(modules, datanames) { # nolint: object_name_length+ ui_teal_lockfile <- function(id) { |
||
195 | -277x | +|||
32 | +! |
- checkmate::assert_multi_class(modules, c("teal_module", "teal_modules"))+ ns <- NS(id) |
||
196 | -277x | +|||
33 | +! |
- checkmate::assert_character(datanames)+ shiny::tagList( |
||
197 | -277x | +|||
34 | +! |
- if (inherits(modules, "teal_modules")) {+ tags$span("", id = ns("lockFileStatus")), |
||
198 | -79x | +|||
35 | +! |
- unlist(+ shinyjs::disabled(downloadLink(ns("lockFileLink"), "Download lockfile")) |
||
199 | -79x | +|||
36 | +
- lapply(modules$children, check_modules_datanames_recursive, datanames = datanames),+ ) |
|||
200 | -79x | +|||
37 | +
- recursive = FALSE+ } |
|||
201 | +38 |
- )+ |
||
202 | +39 |
- } else {+ #' @rdname module_teal_lockfile |
||
203 | -198x | +|||
40 | +
- missing_datanames <- setdiff(modules$datanames, c("all", datanames))+ srv_teal_lockfile <- function(id) { |
|||
204 | -198x | +41 | +83x |
- if (length(missing_datanames)) {+ moduleServer(id, function(input, output, session) { |
205 | -18x | +42 | +83x |
- list(list(+ logger::log_debug("Initialize srv_teal_lockfile.") |
206 | -18x | +43 | +83x |
- label = modules$label,+ enable_lockfile_download <- function() { |
207 | -18x | +|||
44 | +! |
- missing_datanames = missing_datanames+ shinyjs::html("lockFileStatus", "Application lockfile ready.") |
||
208 | -+ | |||
45 | +! |
- ))+ shinyjs::hide("lockFileStatus", anim = TRUE) |
||
209 | -+ | |||
46 | +! |
- }+ shinyjs::enable("lockFileLink") |
||
210 | -+ | |||
47 | +! |
- }+ output$lockFileLink <- shiny::downloadHandler( |
||
211 | -+ | |||
48 | +! |
- }+ filename = function() {+ |
+ ||
49 | +! | +
+ "renv.lock" |
||
212 | +50 |
-
+ },+ |
+ ||
51 | +! | +
+ content = function(file) {+ |
+ ||
52 | +! | +
+ file.copy(lockfile_path, file)+ |
+ ||
53 | +! | +
+ file |
||
213 | +54 |
- #' Convert character vector to html code separated with commas and "and"+ },+ |
+ ||
55 | +! | +
+ contentType = "application/json" |
||
214 | +56 |
- #' @noRd+ ) |
||
215 | +57 |
- to_html_code_list <- function(x) {+ } |
||
216 | -34x | +58 | +83x |
- checkmate::assert_character(x)+ disable_lockfile_download <- function() { |
217 | -34x | +|||
59 | +! |
- do.call(+ warning("Lockfile creation failed.", call. = FALSE) |
||
218 | -34x | +|||
60 | +! |
- tagList,+ shinyjs::html("lockFileStatus", "Lockfile creation failed.") |
||
219 | -34x | +|||
61 | +! |
- lapply(seq_along(x), function(.ix) {+ shinyjs::hide("lockFileLink")+ |
+ ||
62 | ++ |
+ }+ |
+ ||
63 | ++ | + | ||
220 | -47x | +64 | +83x |
- tagList(+ shiny::onStop(function() { |
221 | -47x | +65 | +83x |
- tags$code(x[.ix]),+ if (file.exists(lockfile_path) && !shiny::isRunning()) { |
222 | -47x | +66 | +1x |
- if (.ix != length(x)) {+ logger::log_debug("Removing lockfile after shutting down the app") |
223 | +67 | 1x |
- if (.ix == length(x) - 1) tags$span(" and ") else tags$span(", ", .noWS = "before")+ file.remove(lockfile_path) |
|
224 | +68 |
- }+ } |
||
225 | +69 |
- )+ }) |
||
226 | +70 |
- })+ + |
+ ||
71 | +83x | +
+ lockfile_path <- "teal_app.lock"+ |
+ ||
72 | +83x | +
+ mode <- getOption("teal.lockfile.mode", default = "") |
||
227 | +73 |
- )+ + |
+ ||
74 | +83x | +
+ if (!(mode %in% c("auto", "enabled", "disabled"))) {+ |
+ ||
75 | +! | +
+ stop("'teal.lockfile.mode' option can only be one of \"auto\", \"disabled\" or \"disabled\". ") |
||
228 | +76 |
- }+ } |
||
229 | +77 | |||
230 | -+ | |||
78 | +83x |
-
+ if (mode == "disabled") { |
||
231 | -+ | |||
79 | +1x |
- #' Check `datanames` in filters+ logger::log_debug("'teal.lockfile.mode' option is set to 'disabled'. Hiding lockfile download button.") |
||
232 | -+ | |||
80 | +1x |
- #'+ shinyjs::hide("lockFileLink") |
||
233 | -+ | |||
81 | +1x |
- #' This function checks whether `datanames` in filters correspond to those in `data`,+ return(NULL) |
||
234 | +82 |
- #' returning character vector with error messages or `TRUE` if all checks pass.+ } |
||
235 | +83 |
- #'+ |
||
236 | -+ | |||
84 | +82x |
- #' @param filters (`teal_slices`) object+ if (file.exists(lockfile_path)) { |
||
237 | -+ | |||
85 | +! |
- #' @param datanames (`character`) names of datasets available in the `data` object+ logger::log_debug("Lockfile has already been created for this app - skipping automatic creation.") |
||
238 | -+ | |||
86 | +! |
- #'+ enable_lockfile_download() |
||
239 | -+ | |||
87 | +! |
- #' @return A `character(1)` containing error message or TRUE if validation passes.+ return(NULL) |
||
240 | +88 |
- #' @keywords internal+ } |
||
241 | +89 |
- check_filter_datanames <- function(filters, datanames) {+ |
||
242 | -79x | +90 | +82x |
- checkmate::assert_class(filters, "teal_slices")+ if (mode == "auto" && .is_disabled_lockfile_scenario()) { |
243 | -79x | +91 | +81x |
- checkmate::assert_character(datanames)+ logger::log_debug( |
244 | -+ | |||
92 | +81x |
-
+ "Automatic lockfile creation disabled. Execution scenario satisfies teal:::.is_disabled_lockfile_scenario()." |
||
245 | +93 |
- # check teal_slices against datanames- |
- ||
246 | -79x | -
- out <- unlist(sapply(+ ) |
||
247 | -79x | +94 | +81x |
- filters, function(filter) {+ shinyjs::hide("lockFileLink") |
248 | -24x | +95 | +81x |
- dataname <- shiny::isolate(filter$dataname)+ return(NULL) |
249 | -24x | +|||
96 | +
- if (!dataname %in% datanames) {+ } |
|||
250 | -3x | +|||
97 | +
- sprintf(+ |
|||
251 | -3x | +98 | +1x |
- "- Filter '%s' refers to dataname not available in 'data':\n %s not in (%s)",+ if (!.is_lockfile_deps_installed()) { |
252 | -3x | +|||
99 | +! |
- shiny::isolate(filter$id),+ warning("Automatic lockfile creation disabled. `mirai` and `renv` packages must be installed.") |
||
253 | -3x | +|||
100 | +! |
- dQuote(dataname, q = FALSE),+ shinyjs::hide("lockFileLink") |
||
254 | -3x | +|||
101 | +! |
- toString(dQuote(datanames, q = FALSE))+ return(NULL) |
||
255 | +102 |
- )+ } |
||
256 | +103 |
- }+ |
||
257 | +104 |
- }+ # - Will be run only if the lockfile doesn't exist (see the if-s above) |
||
258 | +105 |
- ))+ # - We render to the tempfile because the process might last after session is closed and we don't |
||
259 | +106 |
-
+ # want to make a "teal_app.renv" then. This is why we copy only during active session. |
||
260 | -+ | |||
107 | +1x |
-
+ process <- .teal_lockfile_process_invoke(lockfile_path) |
||
261 | -79x | +108 | +1x |
- if (length(out)) {+ observeEvent(process$status(), { |
262 | -3x | +|||
109 | +! |
- paste(out, collapse = "\n")+ if (process$status() %in% c("initial", "running")) { |
||
263 | -+ | |||
110 | +! |
- } else {+ shinyjs::html("lockFileStatus", "Creating lockfile...") |
||
264 | -76x | +|||
111 | +! |
- TRUE+ } else if (process$status() == "success") { |
||
265 | -+ | |||
112 | +! |
- }+ result <- process$result() |
||
266 | -+ | |||
113 | +! |
- }+ if (any(grepl("Lockfile written to", result$out))) { |
||
267 | -+ | |||
114 | +! |
-
+ logger::log_debug("Lockfile containing { length(result$res$Packages) } packages created.") |
||
268 | -+ | |||
115 | +! |
- #' Function for validating the title parameter of `teal::init`+ if (any(grepl("(WARNING|ERROR):", result$out))) { |
||
269 | -+ | |||
116 | +! |
- #'+ warning("Lockfile created with warning(s) or error(s):", call. = FALSE) |
||
270 | -+ | |||
117 | +! |
- #' Checks if the input of the title from `teal::init` will create a valid title and favicon tag.+ for (i in result$out) { |
||
271 | -+ | |||
118 | +! |
- #' @param shiny_tag (`shiny.tag`) Object to validate for a valid title.+ warning(i, call. = FALSE) |
||
272 | +119 |
- #' @keywords internal+ } |
||
273 | +120 |
- validate_app_title_tag <- function(shiny_tag) {+ } |
||
274 | -7x | +|||
121 | +! |
- checkmate::assert_class(shiny_tag, "shiny.tag")+ enable_lockfile_download() |
||
275 | -7x | +|||
122 | +
- checkmate::assert_true(shiny_tag$name == "head")+ } else { |
|||
276 | -6x | +|||
123 | +! |
- child_names <- vapply(shiny_tag$children, `[[`, character(1L), "name")+ disable_lockfile_download() |
||
277 | -6x | +|||
124 | +
- checkmate::assert_subset(c("title", "link"), child_names, .var.name = "child tags")+ } |
|||
278 | -4x | +|||
125 | +! |
- rel_attr <- shiny_tag$children[[which(child_names == "link")]]$attribs$rel+ } else if (process$status() == "error") { |
||
279 | -4x | +|||
126 | +! |
- checkmate::assert_subset(+ disable_lockfile_download() |
||
280 | -4x | +|||
127 | +
- rel_attr,+ } |
|||
281 | -4x | +|||
128 | +
- c("icon", "shortcut icon"),+ }) |
|||
282 | -4x | +|||
129 | +
- .var.name = "Link tag's rel attribute",+ |
|||
283 | -4x | +130 | +1x |
- empty.ok = FALSE+ NULL |
284 | +131 |
- )+ }) |
||
285 | +132 |
} |
||
286 | +133 | |||
287 | +134 |
- #' Build app title with favicon+ utils::globalVariables(c("opts", "sysenv", "libpaths", "wd", "lockfilepath", "run")) # needed for mirai call |
||
288 | +135 |
- #'+ #' @rdname module_teal_lockfile |
||
289 | +136 |
- #' A helper function to create the browser title along with a logo.+ .teal_lockfile_process_invoke <- function(lockfile_path) { |
||
290 | -+ | |||
137 | +1x |
- #'+ mirai_obj <- NULL |
||
291 | -+ | |||
138 | +1x |
- #' @param title (`character`) The browser title for the `teal` app.+ process <- shiny::ExtendedTask$new(function() { |
||
292 | -+ | |||
139 | +1x |
- #' @param favicon (`character`) The path for the icon for the title.+ m <- mirai::mirai( |
||
293 | +140 |
- #' The image/icon path can be remote or the static path accessible by `shiny`, like the `www/`+ { |
||
294 | -+ | |||
141 | +1x |
- #'+ options(opts) |
||
295 | -+ | |||
142 | +1x |
- #' @return A `shiny.tag` containing the element that adds the title and logo to the `shiny` app.+ do.call(Sys.setenv, sysenv) |
||
296 | -+ | |||
143 | +1x |
- #' @export+ .libPaths(libpaths) |
||
297 | -+ | |||
144 | +1x |
- build_app_title <- function(+ setwd(wd) |
||
298 | -+ | |||
145 | +1x |
- title = "teal app",+ run(lockfile_path = lockfile_path) |
||
299 | +146 |
- favicon = "https://raw.githubusercontent.com/insightsengineering/hex-stickers/main/PNG/nest.png") {+ }, |
||
300 | -13x | +147 | +1x |
- checkmate::assert_string(title, null.ok = TRUE)+ run = .renv_snapshot, |
301 | -13x | +148 | +1x |
- checkmate::assert_string(favicon, null.ok = TRUE)+ lockfile_path = lockfile_path, |
302 | -13x | +149 | +1x |
- tags$head(+ opts = options(), |
303 | -13x | +150 | +1x |
- tags$title(title),+ libpaths = .libPaths(), |
304 | -13x | +151 | +1x |
- tags$link(+ sysenv = as.list(Sys.getenv()), |
305 | -13x | +152 | +1x |
- rel = "icon",+ wd = getwd()+ |
+
153 | ++ |
+ ) |
||
306 | -13x | +154 | +1x |
- href = favicon,+ mirai_obj <<- m |
307 | -13x | +155 | +1x |
- sizes = "any"+ m |
308 | +156 |
- )+ }) |
||
309 | +157 |
- )+ |
||
310 | -+ | |||
158 | +1x |
- }+ shiny::onStop(function() { |
||
311 | -+ | |||
159 | +1x |
-
+ if (mirai::unresolved(mirai_obj)) { |
||
312 | -+ | |||
160 | +! |
- #' Application ID+ logger::log_debug("Terminating a running lockfile process...") |
||
313 | -+ | |||
161 | +! |
- #'+ mirai::stop_mirai(mirai_obj) # this doesn't stop running - renv will be created even if session is closed |
||
314 | +162 |
- #' Creates App ID used to match filter snapshots to application.+ } |
||
315 | +163 |
- #'+ }) |
||
316 | +164 |
- #' Calculate app ID that will be used to stamp filter state snapshots.+ |
||
317 | -+ | |||
165 | +1x |
- #' App ID is a hash of the app's data and modules.+ suppressWarnings({ # 'package:stats' may not be available when loading |
||
318 | -+ | |||
166 | +1x |
- #' See "transferring snapshots" section in ?snapshot.+ process$invoke() |
||
319 | +167 |
- #'+ }) |
||
320 | +168 |
- #' @param data (`teal_data` or `teal_data_module`) as accepted by `init`+ |
||
321 | -+ | |||
169 | +1x |
- #' @param modules (`teal_modules`) object as accepted by `init`+ logger::log_debug("Lockfile creation started based on { getwd() }.") |
||
322 | +170 |
- #'+ |
||
323 | -+ | |||
171 | +1x |
- #' @return A single character string.+ process |
||
324 | +172 |
- #'+ } |
||
325 | +173 |
- #' @keywords internal+ |
||
326 | +174 |
- create_app_id <- function(data, modules) {+ #' @rdname module_teal_lockfile |
||
327 | -21x | +|||
175 | +
- checkmate::assert_multi_class(data, c("teal_data", "teal_data_module"))+ .renv_snapshot <- function(lockfile_path) { |
|||
328 | -20x | +176 | +1x |
- checkmate::assert_class(modules, "teal_modules")+ out <- utils::capture.output( |
329 | -+ | |||
177 | +1x |
-
+ res <- renv::snapshot( |
||
330 | -19x | +178 | +1x |
- data <- if (inherits(data, "teal_data")) {+ lockfile = lockfile_path, |
331 | -17x | +179 | +1x |
- as.list(teal.code::get_env(data))+ prompt = FALSE, |
332 | -19x | +180 | +1x |
- } else if (inherits(data, "teal_data_module")) {+ force = TRUE, |
333 | -2x | +181 | +1x |
- deparse1(body(data$server))+ type = renv::settings$snapshot.type() # see the section "Different ways of creating lockfile" above here |
334 | +182 |
- }+ ) |
||
335 | -19x | +|||
183 | +
- modules <- lapply(modules, defunction)+ ) |
|||
336 | +184 | |||
337 | -19x | +185 | +1x |
- rlang::hash(list(data = data, modules = modules))+ list(out = out, res = res) |
338 | +186 |
} |
||
339 | +187 | |||
340 | +188 |
- #' Go through list and extract bodies of encountered functions as string, recursively.+ #' @rdname module_teal_lockfile |
||
341 | +189 |
- #' @keywords internal+ .is_lockfile_deps_installed <- function() {+ |
+ ||
190 | +1x | +
+ requireNamespace("mirai", quietly = TRUE) && requireNamespace("renv", quietly = TRUE) |
||
342 | +191 |
- #' @noRd+ } |
||
343 | +192 |
- defunction <- function(x) {+ |
||
344 | -229x | +|||
193 | +
- if (is.list(x)) {+ #' @rdname module_teal_lockfile+ |
+ |||
194 | ++ |
+ .is_disabled_lockfile_scenario <- function() { |
||
345 | -67x | +195 | +81x |
- lapply(x, defunction)+ identical(Sys.getenv("CALLR_IS_RUNNING"), "true") || # inside callr process |
346 | -162x | +196 | +81x |
- } else if (is.function(x)) {+ identical(Sys.getenv("TESTTHAT"), "true") || # inside devtools::test |
347 | -50x | +197 | +81x |
- deparse1(body(x))+ !identical(Sys.getenv("QUARTO_PROJECT_ROOT"), "") || # inside Quarto process |
348 | +198 |
- } else {+ ( |
||
349 | -112x | +199 | +81x |
- x+ ("CheckExEnv" %in% search()) || any(c("_R_CHECK_TIMINGS_", "_R_CHECK_LICENSE_") %in% names(Sys.getenv())) |
350 | -+ | |||
200 | +81x |
- }+ ) # inside R CMD CHECK |
||
351 | +201 |
} |
352 | +1 |
-
+ #' An example `teal` module |
|
353 | +2 |
- #' Get unique labels+ #' |
|
354 | +3 |
- #'+ #' `r lifecycle::badge("experimental")` |
|
355 | +4 |
- #' Get unique labels for the modules to avoid namespace conflicts.+ #' |
|
356 | +5 |
- #'+ #' @inheritParams teal_modules |
|
357 | +6 |
- #' @param labels (`character`) vector of labels+ #' @return A `teal` module which can be included in the `modules` argument to [init()]. |
|
358 | +7 |
- #'+ #' @examples |
|
359 | +8 |
- #' @return (`character`) vector of unique labels+ #' app <- init( |
|
360 | +9 |
- #'+ #' data = teal_data(IRIS = iris, MTCARS = mtcars), |
|
361 | +10 |
- #' @keywords internal+ #' modules = example_module() |
|
362 | +11 |
- get_unique_labels <- function(labels) {+ #' ) |
|
363 | -215x | +||
12 | +
- make.unique(gsub("[^[:alnum:]]", "_", tolower(labels)), sep = "_")+ #' if (interactive()) { |
||
364 | +13 |
- }+ #' shinyApp(app$ui, app$server) |
|
365 | +14 |
-
+ #' } |
|
366 | +15 |
- #' Remove ANSI escape sequences from a string+ #' @export |
|
367 | +16 |
- #' @noRd+ example_module <- function(label = "example teal module", datanames = "all", transformers = list()) { |
|
368 | -+ | ||
17 | +38x |
- strip_style <- function(string) {+ checkmate::assert_string(label) |
|
369 | +18 | +38x | +
+ ans <- module(+ |
+
19 | +38x | +
+ label,+ |
+ |
20 | +38x | +
+ server = function(id, data) {+ |
+ |
21 | 2x |
- checkmate::assert_string(string)+ checkmate::assert_class(isolate(data()), "teal_data") |
|
370 | -+ | ||
22 | +2x |
-
+ moduleServer(id, function(input, output, session) { |
|
371 | +23 | 2x |
- gsub(+ datanames_rv <- reactive(ls(teal.code::get_env((req(data()))))) |
372 | +24 | 2x |
- "(?:(?:\\x{001b}\\[)|\\x{009b})(?:(?:[0-9]{1,3})?(?:(?:;[0-9]{0,3})*)?[A-M|f-m])|\\x{001b}[A-M]",+ observeEvent(datanames_rv(), {+ |
+
25 | +2x | +
+ selected <- input$dataname+ |
+ |
26 | +2x | +
+ if (identical(selected, "")) {+ |
+ |
27 | +! | +
+ selected <- restoreInput(session$ns("dataname"), NULL)+ |
+ |
28 | +2x | +
+ } else if (isFALSE(selected %in% datanames_rv())) {+ |
+ |
29 | +! | +
+ selected <- datanames_rv()[1] |
|
373 | +30 |
- "",+ } |
|
374 | +31 | 2x |
- string,+ updateSelectInput( |
375 | +32 | 2x |
- perl = TRUE,+ session = session, |
376 | +33 | 2x |
- useBytes = TRUE+ inputId = "dataname",+ |
+
34 | +2x | +
+ choices = datanames_rv(),+ |
+ |
35 | +2x | +
+ selected = selected |
|
377 | +36 |
- )+ ) |
|
378 | +37 |
- }+ }) |
|
379 | +38 | ||
39 | +2x | +
+ output$text <- renderPrint({+ |
+ |
40 | +2x | +
+ req(input$dataname)+ |
+ |
41 | +! | +
+ data()[[input$dataname]]+ |
+ |
380 | +42 |
- #' Convert character list to human readable html with commas and "and"+ }) |
|
381 | +43 |
- #' @noRd+ + |
+ |
44 | +2x | +
+ teal.widgets::verbatim_popup_srv(+ |
+ |
45 | +2x | +
+ id = "rcode",+ |
+ |
46 | +2x | +
+ verbatim_content = reactive(teal.code::get_code(data())), |
|
382 | -+ | ||
47 | +2x |
- paste_datanames_character <- function(x,+ title = "Example Code" |
|
383 | +48 |
- tags = list(span = shiny::tags$span, code = shiny::tags$code),+ ) |
|
384 | +49 |
- tagList = shiny::tagList) { # nolint: object_name.+ }) |
|
385 | -! | +||
50 | +
- checkmate::assert_character(x)+ }, |
||
386 | -! | +||
51 | +38x |
- do.call(+ ui = function(id) { |
|
387 | +52 | ! |
- tagList,+ ns <- NS(id) |
388 | +53 | ! |
- lapply(seq_along(x), function(.ix) {+ teal.widgets::standard_layout( |
389 | +54 | ! |
- tagList(+ output = verbatimTextOutput(ns("text")), |
390 | +55 | ! |
- tags$code(x[.ix]),+ encoding = tags$div( |
391 | +56 | ! |
- if (.ix != length(x)) {+ selectInput(ns("dataname"), "Choose a dataset", choices = NULL), |
392 | +57 | ! |
- tags$span(ifelse(.ix == length(x) - 1, " and ", ", "))+ teal.widgets::verbatim_popup_ui(ns("rcode"), "Show R code") |
393 | +58 |
- }+ ) |
|
394 | +59 |
) |
|
395 | +60 |
- })+ }, |
|
396 | -+ | ||
61 | +38x |
- )+ datanames = datanames, |
|
397 | -+ | ||
62 | +38x |
- }+ transformers = transformers |
|
398 | +63 |
-
+ ) |
|
399 | -+ | ||
64 | +38x |
- #' Build datanames error string for error message+ attr(ans, "teal_bookmarkable") <- TRUE |
|
400 | -+ | ||
65 | +38x |
- #'+ ans |
|
401 | +66 |
- #' tags and tagList are overwritten in arguments allowing to create strings for+ } |
402 | +1 |
- #' logging purposes+ #' Create a `teal` module for previewing a report |
||
403 | +2 |
- #' @noRd+ #' |
||
404 | +3 |
- build_datanames_error_message <- function(label = NULL,+ #' @description `r lifecycle::badge("experimental")` |
||
405 | +4 |
- datanames,+ #' |
||
406 | +5 |
- extra_datanames,+ #' This function wraps [teal.reporter::reporter_previewer_ui()] and |
||
407 | +6 |
- tags = list(span = shiny::tags$span, code = shiny::tags$code),+ #' [teal.reporter::reporter_previewer_srv()] into a `teal_module` to be |
||
408 | +7 |
- tagList = shiny::tagList) { # nolint: object_name.- |
- ||
409 | -! | -
- tags$span(- |
- ||
410 | -! | -
- tags$span(ifelse(length(extra_datanames) > 1, "Datasets", "Dataset")),- |
- ||
411 | -! | -
- paste_datanames_character(extra_datanames, tags, tagList),- |
- ||
412 | -! | -
- tags$span(- |
- ||
413 | -! | -
- paste0(- |
- ||
414 | -! | -
- ifelse(length(extra_datanames) > 1, "are missing", "is missing"),+ #' used in `teal` applications. |
||
415 | -! | +|||
8 | +
- ifelse(is.null(label), ".", sprintf(" for tab '%s'.", label))+ #' |
|||
416 | +9 |
- )+ #' If you are creating a `teal` application using [init()] then this |
||
417 | +10 |
- ),+ #' module will be added to your application automatically if any of your `teal_modules` |
||
418 | -! | +|||
11 | +
- if (length(datanames) >= 1) {+ #' support report generation. |
|||
419 | -! | +|||
12 | +
- tagList(+ #' |
|||
420 | -! | +|||
13 | +
- tags$span(ifelse(length(datanames) > 1, "Datasets", "Dataset")),+ #' @inheritParams teal_modules |
|||
421 | -! | +|||
14 | +
- tags$span("available in data:"),+ #' @param server_args (named `list`) |
|||
422 | -! | +|||
15 | +
- tagList(+ #' Arguments passed to [teal.reporter::reporter_previewer_srv()]. |
|||
423 | -! | +|||
16 | +
- tags$span(+ #' |
|||
424 | -! | +|||
17 | +
- paste_datanames_character(datanames, tags, tagList),+ #' @return |
|||
425 | -! | +|||
18 | +
- tags$span(".", .noWS = "outside"),+ #' `teal_module` (extended with `teal_module_previewer` class) containing the `teal.reporter` previewer functionality. |
|||
426 | -! | +|||
19 | +
- .noWS = c("outside")+ #' |
|||
427 | +20 |
- )+ #' @export |
||
428 | +21 |
- )+ #' |
||
429 | +22 |
- )+ reporter_previewer_module <- function(label = "Report previewer", server_args = list()) { |
||
430 | -+ | |||
23 | +7x |
- } else {+ checkmate::assert_string(label) |
||
431 | -! | +|||
24 | +5x |
- tags$span("No datasets are available in data.")+ checkmate::assert_list(server_args, names = "named") |
||
432 | -+ | |||
25 | +5x |
- }+ checkmate::assert_true(all(names(server_args) %in% names(formals(teal.reporter::reporter_previewer_srv)))) |
||
433 | +26 |
- )+ |
||
434 | -+ | |||
27 | +3x |
- }+ message("Initializing reporter_previewer_module") |
||
435 | +28 | |||
436 | -+ | |||
29 | +3x |
- #' Smart `rbind`+ srv <- function(id, reporter, ...) { |
||
437 | -+ | |||
30 | +! |
- #'+ teal.reporter::reporter_previewer_srv(id, reporter, ...) |
||
438 | +31 |
- #' Combine `data.frame` objects which have different columns+ } |
||
439 | +32 |
- #'+ |
||
440 | -+ | |||
33 | +3x |
- #' @param ... (`data.frame`)+ ui <- function(id, ...) {+ |
+ ||
34 | +! | +
+ teal.reporter::reporter_previewer_ui(id, ...) |
||
441 | +35 |
- #' @keywords internal+ } |
||
442 | +36 |
- .smart_rbind <- function(...) {+ |
||
443 | -82x | +37 | +3x |
- dots <- list(...)+ module <- module( |
444 | -82x | +38 | +3x |
- checkmate::assert_list(dots, "data.frame", .var.name = "...")+ label = "temporary label", |
445 | -82x | +39 | +3x |
- Reduce(+ server = srv, ui = ui, |
446 | -82x | +40 | +3x |
- x = dots,+ server_args = server_args, ui_args = list(), datanames = NULL |
447 | -82x | +|||
41 | +
- function(x, y) {+ ) |
|||
448 | -69x | +|||
42 | +
- all_columns <- union(colnames(x), colnames(y))+ # Module is created with a placeholder label and the label is changed later. |
|||
449 | -69x | +|||
43 | +
- x[setdiff(all_columns, colnames(x))] <- NA+ # This is to prevent another module being labeled "Report previewer". |
|||
450 | -69x | +44 | +3x |
- y[setdiff(all_columns, colnames(y))] <- NA+ class(module) <- c(class(module), "teal_module_previewer") |
451 | -69x | +45 | +3x |
- rbind(x, y)+ module$label <- label |
452 | -+ | |||
46 | +3x |
- }+ attr(module, "teal_bookmarkable") <- TRUE |
||
453 | -+ | |||
47 | +3x |
- )+ module |
||
454 | +48 |
}@@ -33422,14 +34502,14 @@ teal coverage - 59.99% |
1 |
- #' An example `teal` module+ #' Data Module for teal |
||
3 |
- #' `r lifecycle::badge("experimental")`+ #' This module manages the `data` argument for `srv_teal`. The `teal` framework uses [teal_data()], |
||
4 |
- #'+ #' which can be provided in various ways: |
||
5 |
- #' @inheritParams teal_modules+ #' 1. Directly as a [teal.data::teal_data()] object. This will automatically convert it into a `reactive` `teal_data`. |
||
6 |
- #' @return A `teal` module which can be included in the `modules` argument to [init()].+ #' 2. As a `reactive` object that returns a [teal.data::teal_data()] object. |
||
7 |
- #' @examples+ #' |
||
8 |
- #' app <- init(+ #' @details |
||
9 |
- #' data = teal_data(IRIS = iris, MTCARS = mtcars),+ #' ## Reactive `teal_data`: |
||
10 |
- #' modules = example_module()+ #' |
||
11 |
- #' )+ #' The data in the application can be reactively updated, prompting [srv_teal()] to rebuild the |
||
12 |
- #' if (interactive()) {+ #' content accordingly. There are two methods for creating interactive `teal_data`: |
||
13 |
- #' shinyApp(app$ui, app$server)+ #' 1. Using a `reactive` object provided from outside the `teal` application. In this scenario, |
||
14 |
- #' }+ #' reactivity is controlled by an external module, and `srv_teal` responds to changes. |
||
15 |
- #' @export+ #' 2. Using [teal_data_module()], which is embedded within the `teal` application, allowing data to |
||
16 |
- example_module <- function(label = "example teal module", datanames = "all", transformers = list()) {+ #' be resubmitted by the user as needed. |
||
17 | -38x | +
- checkmate::assert_string(label)+ #' |
|
18 | -38x | +
- ans <- module(+ #' Since the server of [teal_data_module()] must return a `reactive` `teal_data` object, both |
|
19 | -38x | +
- label,+ #' methods (1 and 2) produce the same reactive behavior within a `teal` application. The distinction |
|
20 | -38x | +
- server = function(id, data) {+ #' lies in data control: the first method involves external control, while the second method |
|
21 | -2x | +
- checkmate::assert_class(isolate(data()), "teal_data")+ #' involves control from a custom module within the app. |
|
22 | -2x | +
- moduleServer(id, function(input, output, session) {+ #' |
|
23 | -2x | +
- datanames_rv <- reactive(ls(teal.code::get_env((req(data())))))+ #' For more details, see [`module_teal_data`]. |
|
24 | -2x | +
- observeEvent(datanames_rv(), {+ #' |
|
25 | -2x | +
- selected <- input$dataname+ #' @inheritParams init |
|
26 | -2x | +
- if (identical(selected, "")) {+ #' |
|
27 | -! | +
- selected <- restoreInput(session$ns("dataname"), NULL)+ #' @param data (`teal_data`, `teal_data_module`, or `reactive` returning `teal_data`) |
|
28 | -2x | +
- } else if (isFALSE(selected %in% datanames_rv())) {+ #' The data which application will depend on. |
|
29 | -! | +
- selected <- datanames_rv()[1]+ #' |
|
30 |
- }+ #' @return A `reactive` object that returns: |
||
31 | -2x | +
- updateSelectInput(+ #' Output of the `data`. If `data` fails then returned error is handled (after [tryCatch()]) so that |
|
32 | -2x | +
- session = session,+ #' rest of the application can respond to this respectively. |
|
33 | -2x | +
- inputId = "dataname",+ #' |
|
34 | -2x | +
- choices = datanames_rv(),+ #' @rdname module_init_data |
|
35 | -2x | +
- selected = selected+ #' @name module_init_data |
|
36 |
- )+ #' @keywords internal |
||
37 |
- })+ NULL |
||
39 | -2x | +
- output$text <- renderPrint({+ #' @rdname module_init_data |
|
40 | -2x | +
- req(input$dataname)+ ui_init_data <- function(id) { |
|
41 | -! | +9x |
- data()[[input$dataname]]+ ns <- shiny::NS(id) |
42 | -+ | 9x |
- })+ shiny::div( |
43 | -+ | 9x |
-
+ id = ns("content"), |
44 | -2x | +9x |
- teal.widgets::verbatim_popup_srv(+ style = "display: inline-block; width: 100%;", |
45 | -2x | +9x |
- id = "rcode",+ uiOutput(ns("data")) |
46 | -2x | +
- verbatim_content = reactive(teal.code::get_code(data())),+ ) |
|
47 | -2x | +
- title = "Example Code"+ } |
|
48 |
- )+ |
||
49 |
- })+ #' @rdname module_init_data |
||
50 |
- },+ srv_init_data <- function(id, data) { |
||
51 | -38x | +83x |
- ui = function(id) {+ checkmate::assert_character(id, max.len = 1, any.missing = FALSE) |
52 | -! | +83x |
- ns <- NS(id)+ checkmate::assert_multi_class(data, c("teal_data", "teal_data_module", "reactive")) |
53 | -! | +
- teal.widgets::standard_layout(+ |
|
54 | -! | +83x |
- output = verbatimTextOutput(ns("text")),+ moduleServer(id, function(input, output, session) { |
55 | -! | +83x |
- encoding = tags$div(+ logger::log_debug("srv_data initializing.") |
56 | -! | +
- selectInput(ns("dataname"), "Choose a dataset", choices = NULL),+ # data_rv contains teal_data object |
|
57 | -! | +
- teal.widgets::verbatim_popup_ui(ns("rcode"), "Show R code")+ # either passed to teal::init or returned from teal_data_module |
|
58 | -+ | 83x |
- )+ data_out <- if (inherits(data, "teal_data_module")) { |
59 | -+ | 10x |
- )+ output$data <- renderUI(data$ui(id = session$ns("teal_data_module"))) |
60 | -+ | 10x |
- },+ data$server("teal_data_module") |
61 | -38x | +83x |
- datanames = datanames,+ } else if (inherits(data, "teal_data")) { |
62 | -38x | +43x |
- transformers = transformers+ reactiveVal(data) |
63 | -+ | 83x |
- )+ } else if (test_reactive(data)) { |
64 | -38x | +30x |
- attr(ans, "teal_bookmarkable") <- TRUE+ data |
65 | -38x | +
- ans+ } |
|
66 |
- }+ |
1 | -+ | |||
67 | +82x |
- #' Store and restore `teal_slices` object+ data_handled <- reactive({ |
||
2 | -+ | |||
68 | +75x |
- #'+ tryCatch(data_out(), error = function(e) e) |
||
3 | +69 |
- #' Functions that write a `teal_slices` object to a file in the `JSON` format,+ }) |
||
4 | +70 |
- #' and also restore the object from disk.+ |
||
5 | +71 |
- #'+ # We want to exclude teal_data_module elements from bookmarking as they might have some secrets |
||
6 | -+ | |||
72 | +82x |
- #' Date and date time objects are stored in the following formats:+ observeEvent(data_handled(), { |
||
7 | -+ | |||
73 | +75x |
- #'+ if (inherits(data_handled(), "teal_data")) { |
||
8 | -+ | |||
74 | +70x |
- #' - `Date` class is converted to the `"ISO8601"` standard (`YYYY-MM-DD`).+ app_session <- .subset2(shiny::getDefaultReactiveDomain(), "parent") |
||
9 | -+ | |||
75 | +70x |
- #' - `POSIX*t` classes are converted to character by using+ setBookmarkExclude( |
||
10 | -+ | |||
76 | +70x |
- #' `format.POSIX*t(usetz = TRUE, tz = "UTC")` (`YYYY-MM-DD HH:MM:SS UTC`, where+ session$ns( |
||
11 | -+ | |||
77 | +70x |
- #' `UTC` is the `Coordinated Universal Time` timezone short-code).+ grep( |
||
12 | -+ | |||
78 | +70x |
- #'+ pattern = "teal_data_module-",+ |
+ ||
79 | +70x | +
+ x = names(reactiveValuesToList(input)),+ |
+ ||
80 | +70x | +
+ value = TRUE |
||
13 | +81 |
- #' This format is assumed during `slices_restore`. All `POSIX*t` objects in+ ) |
||
14 | +82 |
- #' `selected` or `choices` fields of `teal_slice` objects are always printed in+ ),+ |
+ ||
83 | +70x | +
+ session = app_session |
||
15 | +84 |
- #' `UTC` timezone as well.+ ) |
||
16 | +85 |
- #'+ } |
||
17 | +86 |
- #' @param tss (`teal_slices`) object to be stored.+ }) |
||
18 | +87 |
- #' @param file (`character(1)`) file path where `teal_slices` object will be+ + |
+ ||
88 | +82x | +
+ data_handled |
||
19 | +89 |
- #' saved and restored. The file extension should be `".json"`.+ }) |
||
20 | +90 |
- #'+ } |
||
21 | +91 |
- #' @return `slices_store` returns `NULL`, invisibly.+ |
||
22 | +92 |
- #'+ #' Adds signature protection to the `datanames` in the data |
||
23 | +93 |
- #' @seealso [teal_slices()]+ #' @param data (`teal_data`) |
||
24 | +94 |
- #'+ #' @return `teal_data` with additional code that has signature of the `datanames` |
||
25 | +95 |
#' @keywords internal |
||
26 | +96 |
- #'+ .add_signature_to_data <- function(data) { |
||
27 | -+ | |||
97 | +70x |
- slices_store <- function(tss, file) {+ hashes <- .get_hashes_code(data) |
||
28 | -9x | +98 | +70x |
- checkmate::assert_class(tss, "teal_slices")+ tdata <- do.call( |
29 | -9x | +99 | +70x |
- checkmate::assert_path_for_output(file, overwrite = TRUE, extension = "json")+ teal.data::teal_data,+ |
+
100 | +70x | +
+ c(+ |
+ ||
101 | +70x | +
+ list(code = trimws(c(teal.code::get_code(data), hashes), which = "right")),+ |
+ ||
102 | +70x | +
+ list(join_keys = teal.data::join_keys(data)),+ |
+ ||
103 | +70x | +
+ sapply(+ |
+ ||
104 | +70x | +
+ ls(teal.code::get_env(data)),+ |
+ ||
105 | +70x | +
+ teal.code::get_var,+ |
+ ||
106 | +70x | +
+ object = data,+ |
+ ||
107 | +70x | +
+ simplify = FALSE |
||
30 | +108 |
-
+ ) |
||
31 | -9x | +|||
109 | +
- cat(format(tss, trim_lines = FALSE), "\n", file = file)+ ) |
|||
32 | +110 |
- }+ ) |
||
33 | +111 | |||
112 | +70x | +
+ tdata@verified <- data@verified+ |
+ ||
113 | +70x | +
+ tdata+ |
+ ||
34 | +114 |
- #' @rdname slices_store+ } |
||
35 | +115 | ++ | + + | +|
116 |
- #' @return `slices_restore` returns a `teal_slices` object restored from the file.+ #' Get code that tests the integrity of the reproducible data |
|||
36 | +117 |
- #' @keywords internal+ #' |
||
37 | +118 |
- slices_restore <- function(file) {+ #' @param data (`teal_data`) object holding the data |
||
38 | -9x | +|||
119 | +
- checkmate::assert_file_exists(file, access = "r", extension = "json")+ #' @param datanames (`character`) names of `datasets` |
|||
39 | +120 |
-
+ #' |
||
40 | -9x | +|||
121 | +
- tss_json <- jsonlite::fromJSON(file, simplifyDataFrame = FALSE)+ #' @return A character vector with the code lines. |
|||
41 | -9x | +|||
122 | +
- tss_json$slices <-+ #' @keywords internal |
|||
42 | -9x | +|||
123 | +
- lapply(tss_json$slices, function(slice) {+ #' |
|||
43 | -9x | +|||
124 | +
- for (field in c("selected", "choices")) {+ .get_hashes_code <- function(data, datanames = ls(teal.code::get_env(data))) { |
|||
44 | -18x | +125 | +70x |
- if (!is.null(slice[[field]])) {+ vapply( |
45 | -12x | +126 | +70x |
- if (length(slice[[field]]) > 0) {+ datanames, |
46 | -9x | +127 | +70x |
- date_partial_regex <- "^[0-9]{4}-[0-9]{2}-[0-9]{2}"+ function(dataname, datasets) { |
47 | -9x | +128 | +125x |
- time_stamp_regex <- paste0(date_partial_regex, "\\s[0-9]{2}:[0-9]{2}:[0-9]{2}\\sUTC$")+ x <- data[[dataname]] |
48 | +129 | |||
49 | -9x | +130 | +125x |
- slice[[field]] <-+ code <- if (is.function(x) && !is.primitive(x)) { |
50 | -9x | +131 | +6x |
- if (all(grepl(paste0(date_partial_regex, "$"), slice[[field]]))) {+ x <- deparse1(x) |
51 | -3x | +132 | +6x |
- as.Date(slice[[field]])+ bquote(rlang::hash(deparse1(.(as.name(dataname))))) |
52 | -9x | +|||
133 | +
- } else if (all(grepl(time_stamp_regex, slice[[field]]))) {+ } else { |
|||
53 | -3x | +134 | +119x |
- as.POSIXct(slice[[field]], tz = "UTC")+ bquote(rlang::hash(.(as.name(dataname)))) |
54 | +135 |
- } else {+ } |
||
55 | -3x | +136 | +125x |
- slice[[field]]+ sprintf( |
56 | -+ | |||
137 | +125x |
- }+ "stopifnot(%s == %s) # @linksto %s", |
||
57 | -+ | |||
138 | +125x |
- } else {+ deparse1(code), |
||
58 | -3x | +139 | +125x |
- slice[[field]] <- character(0)+ deparse1(rlang::hash(x)), |
59 | -+ | |||
140 | +125x |
- }+ dataname |
||
60 | +141 |
- }+ ) |
||
61 | +142 |
- }+ }, |
||
62 | -9x | -
- slice- |
- ||
63 | -- |
- })- |
- ||
64 | -+ | 143 | +70x |
-
+ character(1L), |
65 | -9x | +144 | +70x |
- tss_elements <- lapply(tss_json$slices, as.teal_slice)+ USE.NAMES = TRUE |
66 | +145 | - - | -||
67 | -9x | -
- do.call(teal_slices, c(tss_elements, tss_json$attributes))+ ) |
||
68 | +146 |
}@@ -34372,14 +35530,14 @@ teal coverage - 59.99% |
1 |
- #' `teal` main module+ #' Calls all `modules` |
|||
3 |
- #' @description+ #' On the UI side each `teal_modules` is translated to a `tabsetPanel` and each `teal_module` is a |
|||
4 |
- #' `r lifecycle::badge("stable")`+ #' `tabPanel`. Both, UI and server are called recursively so that each tab is a separate module and |
|||
5 |
- #' Module to create a `teal` app. This module can be called directly instead of [init()] and+ #' reflect nested structure of `modules` argument. |
|||
6 |
- #' included in your custom application. Please note that [init()] adds `reporter_previewer_module`+ #' |
|||
7 |
- #' automatically, which is not a case when calling `ui/srv_teal` directly.+ #' @name module_teal_module |
|||
9 |
- #' @details+ #' @inheritParams module_teal |
|||
11 |
- #' Module is responsible for creating the main `shiny` app layout and initializing all the necessary+ #' @param data_rv (`reactive` returning `teal_data`) |
|||
12 |
- #' components. This module establishes reactive connection between the input `data` and every other+ #' |
|||
13 |
- #' component in the app. Reactive change of the `data` passed as an argument, reloads the app and+ #' @param slices_global (`reactiveVal` returning `modules_teal_slices`) |
|||
14 |
- #' possibly keeps all input settings the same so the user can continue where one left off.+ #' see [`module_filter_manager`] |
|||
16 |
- #' ## data flow in `teal` application+ #' @param depth (`integer(1)`) |
|||
17 |
- #'+ #' number which helps to determine depth of the modules nesting. |
|||
18 |
- #' This module supports multiple data inputs but eventually, they are all converted to `reactive`+ #' |
|||
19 |
- #' returning `teal_data` in this module. On this `reactive teal_data` object several actions are+ #' @param datasets (`reactive` returning `FilteredData` or `NULL`) |
|||
20 |
- #' performed:+ #' When `datasets` is passed from the parent module (`srv_teal`) then `dataset` is a singleton |
|||
21 |
- #' - data loading in [`module_init_data`]+ #' which implies in filter-panel to be "global". When `NULL` then filter-panel is "module-specific". |
|||
22 |
- #' - data filtering in [`module_filter_data`]+ #' |
|||
23 |
- #' - data transformation in [`module_transform_data`]+ #' @param data_load_status (`reactive` returning `character`) |
|||
24 |
- #'+ #' Determines action dependent on a data loading status: |
|||
25 |
- #' ## Fallback on failure+ #' - `"ok"` when `teal_data` is returned from the data loading. |
|||
26 |
- #'+ #' - `"teal_data_module failed"` when [teal_data_module()] didn't return `teal_data`. Disables tabs buttons. |
|||
27 |
- #' `teal` is designed in such way that app will never crash if the error is introduced in any+ #' - `"external failed"` when a `reactive` passed to `srv_teal(data)` didn't return `teal_data`. Hides the whole tab |
|||
28 |
- #' custom `shiny` module provided by app developer (e.g. [teal_data_module()], [teal_transform_module()]).+ #' panel. |
|||
29 |
- #' If any module returns a failing object, the app will halt the evaluation and display a warning message.+ #' |
|||
30 |
- #' App user should always have a chance to fix the improper input and continue without restarting the session.+ #' @return |
|||
31 |
- #'+ #' output of currently active module. |
|||
32 |
- #' @rdname module_teal+ #' - `srv_teal_module.teal_module` returns `reactiveVal` containing output of the called module. |
|||
33 |
- #' @name module_teal+ #' - `srv_teal_module.teal_modules` returns output of module selected by `input$active_tab`. |
|||
35 |
- #' @inheritParams module_init_data+ #' @keywords internal |
|||
36 |
- #' @inheritParams init+ NULL |
|||
37 |
- #'+ |
|||
38 |
- #' @return `NULL` invisibly+ #' @rdname module_teal_module |
|||
39 |
- NULL+ ui_teal_module <- function(id, modules, depth = 0L) { |
|||
40 | -+ | ! |
-
+ checkmate::assert_multi_class(modules, c("teal_modules", "teal_module", "shiny.tag")) |
|
41 | -+ | ! |
- #' @rdname module_teal+ checkmate::assert_count(depth) |
|
42 | -+ | ! |
- #' @export+ UseMethod("ui_teal_module", modules) |
|
43 |
- ui_teal <- function(id,+ } |
|||
44 |
- modules,+ |
|||
45 |
- title = build_app_title(),+ #' @rdname module_teal_module |
|||
46 |
- header = tags$p(),+ #' @export |
|||
47 |
- footer = tags$p()) {+ ui_teal_module.default <- function(id, modules, depth = 0L) { |
|||
48 | ! |
- checkmate::assert_character(id, max.len = 1, any.missing = FALSE)+ stop("Modules class not supported: ", paste(class(modules), collapse = " ")) |
||
49 | -! | +
- checkmate::assert(+ } |
||
50 | -! | +
- .var.name = "title",+ |
||
51 | -! | +
- checkmate::check_string(title),+ #' @rdname module_teal_module |
||
52 | -! | +
- checkmate::check_multi_class(title, c("shiny.tag", "shiny.tag.list", "html"))+ #' @export |
||
53 |
- )+ ui_teal_module.teal_modules <- function(id, modules, depth = 0L) { |
|||
54 | ! |
- checkmate::assert(+ ns <- NS(id) |
||
55 | ! |
- .var.name = "header",+ tags$div( |
||
56 | ! |
- checkmate::check_string(header),+ id = ns("wrapper"), |
||
57 | ! |
- checkmate::check_multi_class(header, c("shiny.tag", "shiny.tag.list", "html"))+ do.call( |
||
58 | -+ | ! |
- )+ tabsetPanel, |
|
59 | ! |
- checkmate::assert(+ c( |
||
60 | -! | +
- .var.name = "footer",+ # by giving an id, we can reactively respond to tab changes |
||
61 | ! |
- checkmate::check_string(footer),+ list( |
||
62 | ! |
- checkmate::check_multi_class(footer, c("shiny.tag", "shiny.tag.list", "html"))+ id = ns("active_tab"), |
||
63 | -+ | ! |
- )+ type = if (modules$label == "root") "pills" else "tabs" |
|
64 |
-
+ ), |
|||
65 | ! |
- if (is.character(title)) {+ lapply( |
||
66 | ! |
- title <- build_app_title(title)+ names(modules$children), |
||
67 | -+ | ! |
- } else {+ function(module_id) { |
|
68 | ! |
- validate_app_title_tag(title)+ module_label <- modules$children[[module_id]]$label |
||
69 | -+ | ! |
- }+ if (is.null(module_label)) { |
|
70 | -+ | ! |
-
+ module_label <- icon("fas fa-database") |
|
71 | -! | +
- if (checkmate::test_string(header)) {+ } |
||
72 | ! |
- header <- tags$p(header)+ tabPanel( |
||
73 | -+ | ! |
- }+ title = module_label, |
|
74 | -+ | ! |
-
+ value = module_id, # when clicked this tab value changes input$<tabset panel id> |
|
75 | ! |
- if (checkmate::test_string(footer)) {+ ui_teal_module( |
||
76 | ! |
- footer <- tags$p(footer)+ id = ns(module_id), |
||
77 | -+ | ! |
- }+ modules = modules$children[[module_id]], |
|
78 | -+ | ! |
-
+ depth = depth + 1L |
|
79 | -! | +
- ns <- NS(id)+ ) |
||
80 |
-
+ ) |
|||
81 |
- # show busy icon when `shiny` session is busy computing stuff+ } |
|||
82 |
- # based on https://stackoverflow.com/questions/17325521/r-shiny-display-loading-message-while-function-is-running/22475216#22475216 # nolint: line_length.+ ) |
|||
83 | -! | +
- shiny_busy_message_panel <- conditionalPanel(+ ) |
||
84 | -! | +
- condition = "(($('html').hasClass('shiny-busy')) && (document.getElementById('shiny-notification-panel') == null))", # nolint: line_length.+ ) |
||
85 | -! | +
- tags$div(+ ) |
||
86 | -! | +
- icon("arrows-rotate", class = "fa-spin", prefer_type = "solid"),+ } |
||
87 | -! | +
- "Computing ...",+ |
||
88 |
- # CSS defined in `custom.css`+ #' @rdname module_teal_module |
|||
89 | -! | +
- class = "shinybusymessage"+ #' @export |
||
90 |
- )+ ui_teal_module.teal_module <- function(id, modules, depth = 0L) { |
|||
91 | -+ | ! |
- )+ ns <- NS(id) |
|
92 | -+ | ! |
-
+ args <- c(list(id = ns("module")), modules$ui_args) |
|
93 | -! | +
- fluidPage(+ |
||
94 | ! |
- id = id,+ ui_teal <- tagList( |
||
95 | ! |
- title = title,+ div( |
||
96 | ! |
- theme = get_teal_bs_theme(),+ id = ns("validate_datanames"), |
||
97 | ! |
- include_teal_css_js(),+ ui_validate_reactive_teal_data(ns("validate_datanames")) |
||
98 | -! | +
- tags$header(header),+ ), |
||
99 | ! |
- tags$hr(class = "my-2"),+ shinyjs::hidden( |
||
100 | ! |
- shiny_busy_message_panel,+ tags$div( |
||
101 | ! |
- tags$div(+ id = ns("transformer_failure_info"), |
||
102 | ! |
- id = ns("tabpanel_wrapper"),+ class = "teal_validated", |
||
103 | ! |
- class = "teal-body",+ div( |
||
104 | ! |
- ui_teal_module(id = ns("teal_modules"), modules = modules)+ class = "teal-output-warning", |
||
105 | -+ | ! |
- ),+ "One of transformers failed. Please fix and continue." |
|
106 | -! | +
- tags$div(+ ) |
||
107 | -! | +
- id = ns("options_buttons"),+ ) |
||
108 | -! | +
- style = "position: absolute; right: 10px;",+ ), |
||
109 | ! |
- ui_bookmark_panel(ns("bookmark_manager"), modules),+ tags$div( |
||
110 | ! |
- tags$button(+ id = ns("teal_module_ui"), |
||
111 | ! |
- class = "btn action-button filter_hamburger", # see sidebar.css for style filter_hamburger+ do.call(modules$ui, args) |
||
112 | -! | +
- href = "javascript:void(0)",+ ) |
||
113 | -! | +
- onclick = sprintf("toggleFilterPanel('%s');", ns("tabpanel_wrapper")),+ ) |
||
114 | -! | +
- title = "Toggle filter panel",+ |
||
115 | ! |
- icon("fas fa-bars")+ div( |
||
116 | -+ | ! |
- ),+ id = id, |
|
117 | ! |
- ui_snapshot_manager_panel(ns("snapshot_manager_panel")),+ class = "teal_module", |
||
118 | ! |
- ui_filter_manager_panel(ns("filter_manager_panel"))+ uiOutput(ns("data_reactive"), inline = TRUE), |
||
119 | -+ | ! |
- ),+ tagList( |
|
120 | ! |
- tags$script(+ if (depth >= 2L) tags$div(style = "mt-6"), |
||
121 | ! |
- HTML(+ if (!is.null(modules$datanames)) { |
||
122 | ! |
- sprintf(+ fluidRow( |
||
123 | -+ | ! |
- "+ column(width = 9, ui_teal, class = "teal_primary_col"), |
|
124 | ! |
- $(document).ready(function() {+ column( |
||
125 | ! |
- $('#%s').appendTo('#%s');+ width = 3, |
||
126 | -+ | ! |
- });+ ui_data_summary(ns("data_summary")), |
|
127 | -+ | ! |
- ",+ ui_filter_data(ns("filter_panel")), |
|
128 | ! |
- ns("options_buttons"),+ ui_transform_data(ns("data_transform"), transformers = modules$transformers, class = "well"), |
||
129 | ! |
- ns("teal_modules-active_tab")+ class = "teal_secondary_col" |
||
130 |
- )+ ) |
|||
131 |
- )+ ) |
|||
132 |
- ),+ } else { |
|||
133 | ! |
- tags$hr(),+ div( |
||
134 | ! |
- tags$footer(+ div( |
||
135 | ! |
- tags$div(+ class = "teal_validated", |
||
136 | ! |
- footer,+ uiOutput(ns("data_input_error")) |
||
137 | -! | +
- teal.widgets::verbatim_popup_ui(ns("sessionInfo"), "Session Info", type = "link"),+ ), |
||
138 | ! |
- br(),+ ui_teal |
||
139 | -! | +
- ui_teal_lockfile(ns("lockfile")),+ ) |
||
140 | -! | +
- textOutput(ns("identifier"))+ } |
||
141 |
- )+ ) |
|||
142 |
- )+ ) |
|||
143 |
- )+ } |
|||
144 |
- }+ |
|||
145 |
-
+ #' @rdname module_teal_module |
|||
146 |
- #' @rdname module_teal+ srv_teal_module <- function(id, |
|||
147 |
- #' @export+ data_rv, |
|||
148 |
- srv_teal <- function(id, data, modules, filter = teal_slices()) {+ modules, |
|||
149 | -84x | +
- checkmate::assert_character(id, max.len = 1, any.missing = FALSE)+ datasets = NULL, |
||
150 | -84x | +
- checkmate::assert_multi_class(data, c("teal_data", "teal_data_module", "reactive"))+ slices_global, |
||
151 | -83x | +
- checkmate::assert_class(modules, "teal_modules")+ reporter = teal.reporter::Reporter$new(), |
||
152 | -83x | +
- checkmate::assert_class(filter, "teal_slices")+ data_load_status = reactive("ok"), |
||
153 |
-
+ is_active = reactive(TRUE)) { |
|||
154 | -83x | +189x |
- moduleServer(id, function(input, output, session) {+ checkmate::assert_string(id) |
|
155 | -83x | +189x |
- logger::log_debug("srv_teal initializing.")+ assert_reactive(data_rv) |
|
156 | -+ | 189x |
-
+ checkmate::assert_multi_class(modules, c("teal_modules", "teal_module")) |
|
157 | -83x | +189x |
- if (getOption("teal.show_js_log", default = FALSE)) {+ assert_reactive(datasets, null.ok = TRUE) |
|
158 | -! | +189x |
- shinyjs::showLog()+ checkmate::assert_class(slices_global, ".slicesGlobal") |
|
159 | -+ | 189x |
- }+ checkmate::assert_class(reporter, "Reporter") |
|
160 | -+ | 189x |
-
+ assert_reactive(data_load_status) |
|
161 | -83x | +189x |
- srv_teal_lockfile("lockfile")+ UseMethod("srv_teal_module", modules) |
|
162 |
-
+ } |
|||
163 | -83x | +
- output$identifier <- renderText(+ |
||
164 | -83x | +
- paste0("Pid:", Sys.getpid(), " Token:", substr(session$token, 25, 32))+ #' @rdname module_teal_module |
||
165 |
- )+ #' @export |
|||
166 |
-
+ srv_teal_module.default <- function(id, |
|||
167 | -83x | +
- teal.widgets::verbatim_popup_srv(+ data_rv, |
||
168 | -83x | +
- "sessionInfo",+ modules, |
||
169 | -83x | +
- verbatim_content = utils::capture.output(utils::sessionInfo()),+ datasets = NULL, |
||
170 | -83x | +
- title = "SessionInfo"+ slices_global, |
||
171 |
- )+ reporter = teal.reporter::Reporter$new(), |
|||
172 |
-
+ data_load_status = reactive("ok"), |
|||
173 |
- # `JavaScript` code+ is_active = reactive(TRUE)) { |
|||
174 | -83x | +! |
- run_js_files(files = "init.js")+ stop("Modules class not supported: ", paste(class(modules), collapse = " ")) |
|
175 |
-
+ } |
|||
176 |
- # set timezone in shiny app+ |
|||
177 |
- # timezone is set in the early beginning so it will be available also+ #' @rdname module_teal_module |
|||
178 |
- # for `DDL` and all shiny modules+ #' @export |
|||
179 | -83x | +
- get_client_timezone(session$ns)+ srv_teal_module.teal_modules <- function(id, |
||
180 | -83x | +
- observeEvent(+ data_rv, |
||
181 | -83x | +
- eventExpr = input$timezone,+ modules, |
||
182 | -83x | +
- once = TRUE,+ datasets = NULL, |
||
183 | -83x | +
- handlerExpr = {+ slices_global, |
||
184 | -! | +
- session$userData$timezone <- input$timezone+ reporter = teal.reporter::Reporter$new(), |
||
185 | -! | +
- logger::log_debug("srv_teal@1 Timezone set to client's timezone: { input$timezone }.")+ data_load_status = reactive("ok"), |
||
186 |
- }+ is_active = reactive(TRUE)) { |
|||
187 | -+ | 82x |
- )+ moduleServer(id = id, module = function(input, output, session) { |
|
188 | -+ | 82x |
-
+ logger::log_debug("srv_teal_module.teal_modules initializing the module { deparse1(modules$label) }.") |
|
189 | -83x | +
- data_pulled <- srv_init_data("data", data = data)+ |
||
190 | 82x |
- data_validated <- srv_validate_reactive_teal_data(+ observeEvent(data_load_status(), { |
||
191 | -82x | +75x |
- "validate",+ tabs_selector <- sprintf("#%s li a", session$ns("active_tab")) |
|
192 | -82x | +75x |
- data = data_pulled,+ if (identical(data_load_status(), "ok")) { |
|
193 | -82x | +70x |
- modules = modules,+ logger::log_debug("srv_teal_module@1 enabling modules tabs.") |
|
194 | -82x | +70x |
- validate_shiny_silent_error = FALSE+ shinyjs::show("wrapper") |
|
195 | -+ | 70x |
- )+ shinyjs::enable(selector = tabs_selector) |
|
196 | -82x | +5x |
- data_rv <- reactive({+ } else if (identical(data_load_status(), "teal_data_module failed")) { |
|
197 | -142x | +5x |
- req(inherits(data_validated(), "teal_data"))+ logger::log_debug("srv_teal_module@1 disabling modules tabs.") |
|
198 | -70x | +5x |
- is_filter_ok <- check_filter_datanames(filter, ls(teal.code::get_env(data_validated())))+ shinyjs::disable(selector = tabs_selector) |
|
199 | -70x | +! |
- if (!isTRUE(is_filter_ok)) {+ } else if (identical(data_load_status(), "external failed")) { |
|
200 | -2x | +! |
- showNotification(+ logger::log_debug("srv_teal_module@1 hiding modules tabs.") |
|
201 | -2x | +! |
- "Some filters were not applied because of incompatibility with data. Contact app developer.",+ shinyjs::hide("wrapper") |
|
202 | -2x | +
- type = "warning",+ } |
||
203 | -2x | +
- duration = 10+ }) |
||
204 |
- )+ |
|||
205 | -2x | +82x |
- warning(is_filter_ok)+ modules_output <- sapply( |
|
206 | -+ | 82x |
- }+ names(modules$children), |
|
207 | -70x | +82x |
- .add_signature_to_data(data_validated())+ function(module_id) { |
|
208 | -+ | 107x |
- })+ srv_teal_module( |
|
209 | -+ | 107x |
-
+ id = module_id, |
|
210 | -82x | +107x |
- data_load_status <- reactive({+ data_rv = data_rv, |
|
211 | -75x | +107x |
- if (inherits(data_pulled(), "teal_data")) {+ modules = modules$children[[module_id]], |
|
212 | -70x | +107x |
- "ok"+ datasets = datasets, |
|
213 | -+ | 107x |
- # todo: should we hide warnings on top for a data?+ slices_global = slices_global, |
|
214 | -5x | +107x |
- } else if (inherits(data, "teal_data_module")) {+ reporter = reporter, |
|
215 | -5x | +107x |
- "teal_data_module failed"+ is_active = reactive( |
|
216 | -+ | 107x |
- } else {+ is_active() && |
|
217 | -! | +107x |
- "external failed"+ input$active_tab == module_id && |
|
218 | -+ | 107x |
- }+ identical(data_load_status(), "ok") |
|
219 |
- })+ ) |
|||
220 |
-
+ ) |
|||
221 | -82x | +
- datasets_rv <- if (!isTRUE(attr(filter, "module_specific"))) {+ }, |
||
222 | -71x | +82x |
- eventReactive(data_rv(), {+ simplify = FALSE |
|
223 | -61x | +
- req(inherits(data_rv(), "teal_data"))+ ) |
||
224 | -61x | +
- logger::log_debug("srv_teal@1 initializing FilteredData")+ |
||
225 | -61x | +82x |
- teal_data_to_filtered_data(data_rv())+ modules_output |
|
226 |
- })+ }) |
|||
227 |
- }+ } |
|||
229 | -82x | +
- if (inherits(data, "teal_data_module")) {+ #' @rdname module_teal_module |
||
230 | -9x | +
- setBookmarkExclude(c("teal_modules-active_tab"))+ #' @export |
||
231 | -9x | +
- shiny::insertTab(+ srv_teal_module.teal_module <- function(id, |
||
232 | -9x | +
- inputId = "teal_modules-active_tab",+ data_rv, |
||
233 | -9x | +
- position = "before",+ modules, |
||
234 | -9x | +
- select = TRUE,+ datasets = NULL, |
||
235 | -9x | +
- tabPanel(+ slices_global, |
||
236 | -9x | +
- title = icon("fas fa-database"),+ reporter = teal.reporter::Reporter$new(), |
||
237 | -9x | +
- value = "teal_data_module",+ data_load_status = reactive("ok"), |
||
238 | -9x | +
- tags$div(+ is_active = reactive(TRUE)) { |
||
239 | -9x | +107x |
- ui_init_data(session$ns("data")),+ logger::log_debug("srv_teal_module.teal_module initializing the module: { deparse1(modules$label) }.") |
|
240 | -9x | +107x |
- ui_validate_reactive_teal_data(session$ns("validate"))+ moduleServer(id = id, module = function(input, output, session) { |
|
241 | -+ | 107x |
- )+ module_out <- reactiveVal() |
|
242 |
- )+ |
|||
243 | -+ | 107x |
- )+ active_datanames <- reactive({ |
|
244 | -+ | 84x |
-
+ .resolve_module_datanames(data = data_rv(), modules = modules) |
|
245 | -9x | +
- if (attr(data, "once")) {+ }) |
||
246 | -9x | +107x |
- observeEvent(data_rv(), once = TRUE, {+ if (is.null(datasets)) { |
|
247 | -4x | +20x |
- logger::log_debug("srv_teal@2 removing data tab.")+ datasets <- eventReactive(data_rv(), { |
|
248 | -+ | 16x |
- # when once = TRUE we pull data once and then remove data tab+ req(inherits(data_rv(), "teal_data")) |
|
249 | -4x | +16x |
- removeTab("teal_modules-active_tab", target = "teal_data_module")+ logger::log_debug("srv_teal_module@1 initializing module-specific FilteredData") |
|
250 | -+ | 16x |
- })+ teal_data_to_filtered_data(data_rv(), datanames = active_datanames()) |
|
251 |
- }+ }) |
|||
252 |
- } else {+ } |
|||
253 |
- # when no teal_data_module then we want to display messages above tabsetPanel (because there is no data-tab)+ |
|||
254 | -73x | +
- insertUI(+ # manage module filters on the module level |
||
255 | -73x | +
- selector = sprintf("#%s", session$ns("tabpanel_wrapper")),+ # important: |
||
256 | -73x | +
- where = "beforeBegin",+ # filter_manager_module_srv needs to be called before filter_panel_srv |
||
257 | -73x | +
- ui = tags$div(ui_validate_reactive_teal_data(session$ns("validate")), tags$br())+ # Because available_teal_slices is used in FilteredData$srv_available_slices (via srv_filter_panel) |
||
258 |
- )+ # and if it is not set, then it won't be available in the srv_filter_panel |
|||
259 | -+ | 107x |
- }+ srv_module_filter_manager(modules$label, module_fd = datasets, slices_global = slices_global) |
|
261 | -82x | +107x |
- module_labels <- unlist(module_labels(modules), use.names = FALSE)+ call_once_when(is_active(), { |
|
262 | -82x | +81x |
- slices_global <- methods::new(".slicesGlobal", filter, module_labels)+ filtered_teal_data <- srv_filter_data( |
|
263 | -82x | +81x |
- modules_output <- srv_teal_module(+ "filter_panel", |
|
264 | -82x | +81x |
- id = "teal_modules",+ datasets = datasets, |
|
265 | -82x | +81x |
- data_rv = data_rv,+ active_datanames = active_datanames, |
|
266 | -82x | +81x |
- datasets = datasets_rv,+ data_rv = data_rv, |
|
267 | -82x | +81x |
- modules = modules,+ is_active = is_active |
|
268 | -82x | +
- slices_global = slices_global,+ ) |
||
269 | -82x | +81x |
- data_load_status = data_load_status+ is_transformer_failed <- reactiveValues() |
|
270 | -+ | 81x |
- )+ transformed_teal_data <- srv_transform_data( |
|
271 | -82x | +81x |
- mapping_table <- srv_filter_manager_panel("filter_manager_panel", slices_global = slices_global)+ "data_transform", |
|
272 | -82x | +81x |
- snapshots <- srv_snapshot_manager_panel("snapshot_manager_panel", slices_global = slices_global)+ data = filtered_teal_data, |
|
273 | -82x | +81x |
- srv_bookmark_panel("bookmark_manager", modules)+ transformers = modules$transformers, |
|
274 | -- |
- })- |
- ||
275 | -+ | 81x |
-
+ modules = modules, |
|
276 | -82x | +275 | +81x |
- invisible(NULL)+ is_transformer_failed = is_transformer_failed |
277 | +276 |
- }+ ) |
1 | -+ | |||
277 | +81x |
- #' Module to transform `reactive` `teal_data`+ any_transformer_failed <- reactive({ |
||
2 | -+ | |||
278 | +81x |
- #'+ any(unlist(reactiveValuesToList(is_transformer_failed))) |
||
3 | +279 |
- #' Module calls multiple [`module_teal_data`] in sequence so that `reactive teal_data` output+ }) |
||
4 | +280 |
- #' from one module is handed over to the following module's input.+ |
||
5 | -+ | |||
281 | +81x |
- #'+ observeEvent(any_transformer_failed(), { |
||
6 | -+ | |||
282 | +81x |
- #' @inheritParams module_teal_data+ if (isTRUE(any_transformer_failed())) { |
||
7 | -+ | |||
283 | +6x |
- #' @inheritParams teal_modules+ shinyjs::hide("teal_module_ui") |
||
8 | -+ | |||
284 | +6x |
- #' @return `reactive` `teal_data`+ shinyjs::hide("validate_datanames") |
||
9 | -+ | |||
285 | +6x |
- #'+ shinyjs::show("transformer_failure_info") |
||
10 | +286 |
- #'+ } else { |
||
11 | -+ | |||
287 | +75x |
- #' @name module_transform_data+ shinyjs::show("teal_module_ui") |
||
12 | -+ | |||
288 | +75x |
- #' @keywords internal+ shinyjs::show("validate_datanames") |
||
13 | -+ | |||
289 | +75x |
- NULL+ shinyjs::hide("transformer_failure_info") |
||
14 | +290 |
-
+ } |
||
15 | +291 |
- #' @rdname module_transform_data+ }) |
||
16 | +292 |
- ui_transform_data <- function(id, transformers = list(), class = "well") {- |
- ||
17 | -! | -
- checkmate::assert_string(id)+ |
||
18 | -! | +|||
293 | +81x |
- checkmate::assert_list(transformers, "teal_transform_module")+ module_teal_data <- reactive({ |
||
19 | -+ | |||
294 | +89x |
-
+ req(inherits(transformed_teal_data(), "teal_data")) |
||
20 | -! | +|||
295 | +83x |
- ns <- NS(id)+ all_teal_data <- transformed_teal_data() |
||
21 | -! | +|||
296 | +83x |
- labels <- lapply(transformers, function(x) attr(x, "label"))+ module_datanames <- .resolve_module_datanames(data = all_teal_data, modules = modules) |
||
22 | -! | +|||
297 | +83x |
- ids <- get_unique_labels(labels)+ .subset_teal_data(all_teal_data, module_datanames) |
||
23 | -! | +|||
298 | +
- names(transformers) <- ids+ }) |
|||
24 | +299 | |||
25 | -! | -
- lapply(- |
- ||
26 | -! | -
- names(transformers),- |
- ||
27 | -! | +|||
300 | +81x |
- function(name) {+ srv_validate_reactive_teal_data( |
||
28 | -! | +|||
301 | +81x |
- data_mod <- transformers[[name]]+ "validate_datanames", |
||
29 | -! | +|||
302 | +81x |
- wrapper_id <- ns(sprintf("wrapper_%s", name))+ data = module_teal_data, |
||
30 | -! | +|||
303 | +81x |
- div( # todo: accordion?+ modules = modules |
||
31 | +304 |
- # class .teal_validated changes the color of the boarder on error in ui_validate_reactive_teal_data+ ) |
||
32 | +305 |
- # For details see tealValidate.js file.+ |
||
33 | -! | +|||
306 | +81x |
- class = c(class, "teal_validated"),+ summary_table <- srv_data_summary("data_summary", module_teal_data) |
||
34 | -! | +|||
307 | +
- title = attr(data_mod, "label"),+ |
|||
35 | -! | +|||
308 | +
- tags$span(+ # Call modules. |
|||
36 | -! | +|||
309 | +81x |
- class = "text-primary mb-4",+ if (!inherits(modules, "teal_module_previewer")) { |
||
37 | -! | +|||
310 | +81x |
- icon("fas fa-square-pen"),+ obs_module <- call_once_when( |
||
38 | -! | +|||
311 | +81x |
- attr(data_mod, "label")+ !is.null(module_teal_data()), |
||
39 | -+ | |||
312 | +81x |
- ),+ ignoreNULL = TRUE, |
||
40 | -! | +|||
313 | +81x |
- tags$i(+ handlerExpr = { |
||
41 | -! | +|||
314 | +75x |
- class = "remove pull-right fa fa-angle-down",+ module_out(.call_teal_module(modules, datasets, module_teal_data, reporter)) |
||
42 | -! | +|||
315 | +
- style = "cursor: pointer;",+ } |
|||
43 | -! | +|||
316 | +
- title = "fold/expand transform panel",+ ) |
|||
44 | -! | +|||
317 | +
- onclick = sprintf("togglePanelItems(this, '%s', 'fa-angle-right', 'fa-angle-down');", wrapper_id)+ } else { |
|||
45 | +318 |
- ),+ # Report previewer must be initiated on app start for report cards to be included in bookmarks. |
||
46 | -! | +|||
319 | +
- div(+ # When previewer is delayed, cards are bookmarked only if previewer has been initiated (visited). |
|||
47 | +320 | ! |
- id = wrapper_id,+ module_out(.call_teal_module(modules, datasets, module_teal_data, reporter)) |
|
48 | -! | +|||
321 | +
- ui_teal_data(id = ns(name), data_module = transformers[[name]]$ui)+ } |
|||
49 | +322 |
- )+ |
||
50 | +323 |
- )+ # todo: (feature request) add a ReporterCard to the reporter as an output from the teal_module |
||
51 | +324 |
- }+ # how to determine if module returns a ReporterCard so that reportPreviewer is needed? |
||
52 | +325 |
- )+ # Should we insertUI of the ReportPreviewer then? |
||
53 | +326 |
- }+ # What about attr(module, "reportable") - similar to attr(module, "bookmarkable")+ |
+ ||
327 | +81x | +
+ if ("report" %in% names(module_out)) { |
||
54 | +328 |
-
+ # (reactively) add card to the reporter |
||
55 | +329 |
- #' @rdname module_transform_data+ } |
||
56 | +330 |
- srv_transform_data <- function(id, data, transformers = list(), modules, is_transformer_failed = reactiveValues()) {+ }) |
||
57 | -81x | +|||
331 | +
- checkmate::assert_string(id)+ |
|||
58 | -81x | +332 | +107x |
- assert_reactive(data)+ module_out |
59 | -81x | +|||
333 | +
- checkmate::assert_list(transformers, "teal_transform_module")+ }) |
|||
60 | -81x | +|||
334 | +
- checkmate::assert_class(modules, "teal_module")+ } |
|||
61 | -81x | +|||
335 | +
- labels <- lapply(transformers, function(x) attr(x, "label"))+ |
|||
62 | -81x | +|||
336 | +
- ids <- get_unique_labels(labels)+ # This function calls a module server function. |
|||
63 | -81x | +|||
337 | +
- names(transformers) <- ids+ .call_teal_module <- function(modules, datasets, filtered_teal_data, reporter) { |
|||
64 | -81x | +|||
338 | +
- moduleServer(id, function(input, output, session) {+ # collect arguments to run teal_module |
|||
65 | -81x | +339 | +75x |
- logger::log_debug("srv_teal_data_modules initializing.")+ args <- c(list(id = "module"), modules$server_args) |
66 | -81x | +340 | +75x |
- Reduce(+ if (is_arg_used(modules$server, "reporter")) { |
67 | -81x | +341 | +1x |
- function(previous_result, name) {+ args <- c(args, list(reporter = reporter)) |
68 | -20x | +|||
342 | +
- srv_teal_data(+ } |
|||
69 | -20x | +|||
343 | +
- id = name,+ |
|||
70 | -20x | +344 | +75x |
- data_module = function(id) transformers[[name]]$server(id, previous_result),+ if (is_arg_used(modules$server, "datasets")) { |
71 | -20x | +345 | +1x |
- modules = modules,+ args <- c(args, datasets = datasets()) |
72 | -20x | +346 | +1x |
- is_transformer_failed = is_transformer_failed+ warning("datasets argument is not reactive and therefore it won't be updated when data is refreshed.") |
73 | +347 |
- )+ } |
||
74 | +348 |
- },+ |
||
75 | -81x | +349 | +75x |
- x = names(transformers),+ if (is_arg_used(modules$server, "data")) { |
76 | -81x | +350 | +71x |
- init = data+ args <- c(args, data = list(filtered_teal_data)) |
77 | +351 |
- )+ } |
||
78 | +352 |
- })+ |
||
79 | -+ | |||
353 | +75x |
- }+ if (is_arg_used(modules$server, "filter_panel_api")) { |
1 | -+ | |||
354 | +1x |
- #' Data Module for teal+ args <- c(args, filter_panel_api = teal.slice::FilterPanelAPI$new(datasets())) |
||
2 | +355 |
- #'+ } |
||
3 | +356 |
- #' This module manages the `data` argument for `srv_teal`. The `teal` framework uses [teal_data()],+ |
||
4 | -+ | |||
357 | +75x |
- #' which can be provided in various ways:+ if (is_arg_used(modules$server, "id")) { |
||
5 | -+ | |||
358 | +75x |
- #' 1. Directly as a [teal.data::teal_data()] object. This will automatically convert it into a `reactive` `teal_data`.+ do.call(modules$server, args) |
||
6 | +359 |
- #' 2. As a `reactive` object that returns a [teal.data::teal_data()] object.+ } else { |
||
7 | -+ | |||
360 | +! |
- #'+ do.call(callModule, c(args, list(module = modules$server))) |
||
8 | +361 |
- #' @details+ } |
||
9 | +362 |
- #' ## Reactive `teal_data`:+ } |
||
10 | +363 |
- #'+ |
||
11 | +364 |
- #' The data in the application can be reactively updated, prompting [srv_teal()] to rebuild the+ .resolve_module_datanames <- function(data, modules) { |
||
12 | -+ | |||
365 | +167x |
- #' content accordingly. There are two methods for creating interactive `teal_data`:+ stopifnot("data_rv must be teal_data object." = inherits(data, "teal_data")) |
||
13 | -+ | |||
366 | +167x |
- #' 1. Using a `reactive` object provided from outside the `teal` application. In this scenario,+ if (is.null(modules$datanames) || identical(modules$datanames, "all")) { |
||
14 | -+ | |||
367 | +135x |
- #' reactivity is controlled by an external module, and `srv_teal` responds to changes.+ .topologically_sort_datanames(ls(teal.code::get_env(data)), teal.data::join_keys(data)) |
||
15 | +368 |
- #' 2. Using [teal_data_module()], which is embedded within the `teal` application, allowing data to+ } else { |
||
16 | -+ | |||
369 | +32x |
- #' be resubmitted by the user as needed.+ intersect( |
||
17 | -+ | |||
370 | +32x |
- #'+ .include_parent_datanames(modules$datanames, teal.data::join_keys(data)), |
||
18 | -+ | |||
371 | +32x |
- #' Since the server of [teal_data_module()] must return a `reactive` `teal_data` object, both+ ls(teal.code::get_env(data)) |
||
19 | +372 |
- #' methods (1 and 2) produce the same reactive behavior within a `teal` application. The distinction+ ) |
||
20 | +373 |
- #' lies in data control: the first method involves external control, while the second method+ } |
||
21 | +374 |
- #' involves control from a custom module within the app.+ } |
||
22 | +375 |
- #'+ |
||
23 | +376 |
- #' For more details, see [`module_teal_data`].+ #' Calls expression when condition is met |
||
24 | +377 |
#' |
||
25 | -- |
- #' @inheritParams init- |
- ||
26 | +378 |
- #'+ #' Function postpones `handlerExpr` to the moment when `eventExpr` (condition) returns `TRUE`, |
||
27 | +379 |
- #' @param data (`teal_data`, `teal_data_module`, or `reactive` returning `teal_data`)+ #' otherwise nothing happens. |
||
28 | +380 |
- #' The data which application will depend on.+ #' @param eventExpr A (quoted or unquoted) logical expression that represents the event; |
||
29 | +381 |
- #'+ #' this can be a simple reactive value like input$click, a call to a reactive expression |
||
30 | +382 |
- #' @return A `reactive` object that returns:+ #' like dataset(), or even a complex expression inside curly braces. |
||
31 | +383 |
- #' Output of the `data`. If `data` fails then returned error is handled (after [tryCatch()]) so that+ #' @param ... additional arguments passed to `observeEvent` with the exception of `eventExpr` that is not allowed. |
||
32 | +384 |
- #' rest of the application can respond to this respectively.+ #' @inheritParams shiny::observeEvent |
||
33 | +385 |
#' |
||
34 | +386 |
- #' @rdname module_init_data+ #' @return An observer. |
||
35 | +387 |
- #' @name module_init_data+ #' |
||
36 | +388 |
#' @keywords internal |
||
37 | +389 |
- NULL+ call_once_when <- function(eventExpr, # nolint: object_name. |
||
38 | +390 |
-
+ handlerExpr, # nolint: object_name. |
||
39 | +391 |
- #' @rdname module_init_data+ event.env = parent.frame(), # nolint: object_name. |
||
40 | +392 |
- ui_init_data <- function(id) {- |
- ||
41 | -9x | -
- ns <- shiny::NS(id)- |
- ||
42 | -9x | -
- shiny::div(- |
- ||
43 | -9x | -
- id = ns("content"),- |
- ||
44 | -9x | -
- style = "display: inline-block; width: 100%;",- |
- ||
45 | -9x | -
- uiOutput(ns("data"))+ handler.env = parent.frame(), # nolint: object_name. |
||
46 | +393 |
- )+ ...) { |
||
47 | -+ | |||
394 | +188x |
- }+ event_quo <- rlang::new_quosure(substitute(eventExpr), env = event.env) |
||
48 | -+ | |||
395 | +188x |
-
+ handler_quo <- rlang::new_quosure(substitute(handlerExpr), env = handler.env) |
||
49 | +396 |
- #' @rdname module_init_data+ |
||
50 | +397 |
- srv_init_data <- function(id, data) {+ # When `condExpr` is TRUE, then `handlerExpr` is evaluated once. |
||
51 | -83x | +398 | +188x |
- checkmate::assert_character(id, max.len = 1, any.missing = FALSE)+ activator <- reactive({ |
52 | -83x | -
- checkmate::assert_multi_class(data, c("teal_data", "teal_data_module", "reactive"))- |
- ||
53 | -+ | 399 | +188x |
-
+ if (isTRUE(rlang::eval_tidy(event_quo))) { |
54 | -83x | +400 | +156x |
- moduleServer(id, function(input, output, session) {+ TRUE |
55 | -83x | +|||
401 | +
- logger::log_debug("srv_data initializing.")+ } |
|||
56 | +402 |
- # data_rv contains teal_data object+ }) |
||
57 | +403 |
- # either passed to teal::init or returned from teal_data_module+ |
||
58 | -83x | +404 | +188x |
- data_out <- if (inherits(data, "teal_data_module")) {+ observeEvent( |
59 | -10x | +405 | +188x |
- output$data <- renderUI(data$ui(id = session$ns("teal_data_module")))+ eventExpr = activator(), |
60 | -10x | +406 | +188x |
- data$server("teal_data_module")+ once = TRUE, |
61 | -83x | +407 | +188x |
- } else if (inherits(data, "teal_data")) {+ handlerExpr = rlang::eval_tidy(handler_quo), |
62 | -43x | +|||
408 | +
- reactiveVal(data)+ ... |
|||
63 | -83x | +|||
409 | +
- } else if (test_reactive(data)) {+ ) |
|||
64 | -30x | +|||
410 | +
- data+ } |
65 | +1 |
- }+ #' Landing popup module |
||||
66 | +2 |
-
+ #' |
||||
67 | -82x | +|||||
3 | +
- data_handled <- reactive({+ #' @description Creates a landing welcome popup for `teal` applications. |
|||||
68 | -75x | +|||||
4 | +
- tryCatch(data_out(), error = function(e) e)+ #' |
|||||
69 | +5 |
- })+ #' This module is used to display a popup dialog when the application starts. |
||||
70 | +6 |
-
+ #' The dialog blocks access to the application and must be closed with a button before the application can be viewed. |
||||
71 | +7 |
- # We want to exclude teal_data_module elements from bookmarking as they might have some secrets+ #' |
||||
72 | -82x | +|||||
8 | +
- observeEvent(data_handled(), {+ #' @param label (`character(1)`) Label of the module. |
|||||
73 | -75x | +|||||
9 | +
- if (inherits(data_handled(), "teal_data")) {+ #' @param title (`character(1)`) Text to be displayed as popup title. |
|||||
74 | -70x | +|||||
10 | +
- app_session <- .subset2(shiny::getDefaultReactiveDomain(), "parent")+ #' @param content (`character(1)`, `shiny.tag` or `shiny.tag.list`) with the content of the popup. |
|||||
75 | -70x | +|||||
11 | +
- setBookmarkExclude(+ #' Passed to `...` of `shiny::modalDialog`. See examples. |
|||||
76 | -70x | +|||||
12 | +
- session$ns(+ #' @param buttons (`shiny.tag` or `shiny.tag.list`) Typically a `modalButton` or `actionButton`. See examples. |
|||||
77 | -70x | +|||||
13 | +
- grep(+ #' |
|||||
78 | -70x | +|||||
14 | +
- pattern = "teal_data_module-",+ #' @return A `teal_module` (extended with `teal_landing_module` class) to be used in `teal` applications. |
|||||
79 | -70x | +|||||
15 | +
- x = names(reactiveValuesToList(input)),+ #' |
|||||
80 | -70x | +|||||
16 | +
- value = TRUE+ #' @examples |
|||||
81 | +17 |
- )+ #' app1 <- init( |
||||
82 | +18 |
- ),+ #' data = teal_data(iris = iris), |
||||
83 | -70x | +|||||
19 | +
- session = app_session+ #' modules = modules( |
|||||
84 | +20 |
- )+ #' example_module() |
||||
85 | +21 |
- }+ #' ), |
||||
86 | +22 |
- })+ #' landing_popup = landing_popup_module( |
||||
87 | +23 |
-
+ #' content = "A place for the welcome message or a disclaimer statement.", |
||||
88 | -82x | +|||||
24 | +
- data_handled+ #' buttons = modalButton("Proceed") |
|||||
89 | +25 |
- })+ #' ) |
||||
90 | +26 |
- }+ #' ) |
||||
91 | +27 |
-
+ #' if (interactive()) { |
||||
92 | +28 |
- #' Adds signature protection to the `datanames` in the data+ #' shinyApp(app1$ui, app1$server) |
||||
93 | +29 |
- #' @param data (`teal_data`)+ #' } |
||||
94 | +30 |
- #' @return `teal_data` with additional code that has signature of the `datanames`+ #' |
||||
95 | +31 |
- #' @keywords internal+ #' app2 <- init( |
||||
96 | +32 |
- .add_signature_to_data <- function(data) {+ #' data = teal_data(iris = iris), |
||||
97 | -70x | +|||||
33 | +
- hashes <- .get_hashes_code(data)+ #' modules = modules( |
|||||
98 | -70x | +|||||
34 | +
- tdata <- do.call(+ #' example_module() |
|||||
99 | -70x | +|||||
35 | +
- teal.data::teal_data,+ #' ), |
|||||
100 | -70x | +|||||
36 | +
- c(+ #' landing_popup = landing_popup_module( |
|||||
101 | -70x | +|||||
37 | +
- list(code = trimws(c(teal.code::get_code(data), hashes), which = "right")),+ #' title = "Welcome", |
|||||
102 | -70x | +|||||
38 | +
- list(join_keys = teal.data::join_keys(data)),+ #' content = tags$b( |
|||||
103 | -70x | +|||||
39 | +
- sapply(+ #' "A place for the welcome message or a disclaimer statement.", |
|||||
104 | -70x | +|||||
40 | +
- ls(teal.code::get_env(data)),+ #' style = "color: red;" |
|||||
105 | -70x | +|||||
41 | +
- teal.code::get_var,+ #' ), |
|||||
106 | -70x | +|||||
42 | +
- object = data,+ #' buttons = tagList( |
|||||
107 | -70x | +|||||
43 | +
- simplify = FALSE+ #' modalButton("Proceed"), |
|||||
108 | +44 |
- )+ #' actionButton("read", "Read more", |
||||
109 | +45 |
- )+ #' onclick = "window.open('http://google.com', '_blank')" |
||||
110 | +46 |
- )+ #' ), |
||||
111 | +47 |
-
+ #' actionButton("close", "Reject", onclick = "window.close()") |
||||
112 | -70x | +|||||
48 | +
- tdata@verified <- data@verified+ #' ) |
|||||
113 | -70x | +|||||
49 | +
- tdata+ #' ) |
|||||
114 | +50 |
- }+ #' ) |
||||
115 | +51 |
-
+ #' |
||||
116 | +52 |
- #' Get code that tests the integrity of the reproducible data+ #' if (interactive()) { |
||||
117 | +53 |
- #'+ #' shinyApp(app2$ui, app2$server) |
||||
118 | +54 |
- #' @param data (`teal_data`) object holding the data+ #' } |
||||
119 | +55 |
- #' @param datanames (`character`) names of `datasets`+ #' |
||||
120 | +56 |
- #'+ #' @export |
||||
121 | +57 |
- #' @return A character vector with the code lines.+ landing_popup_module <- function(label = "Landing Popup", |
||||
122 | +58 |
- #' @keywords internal+ title = NULL, |
||||
123 | +59 |
- #'+ content = NULL, |
||||
124 | +60 |
- .get_hashes_code <- function(data, datanames = ls(teal.code::get_env(data))) {+ buttons = modalButton("Accept")) { |
||||
125 | -70x | +|||||
61 | +! |
- vapply(+ checkmate::assert_string(label) |
||||
126 | -70x | +|||||
62 | +! |
- datanames,+ checkmate::assert_string(title, null.ok = TRUE) |
||||
127 | -70x | +|||||
63 | +! |
- function(dataname, datasets) {+ checkmate::assert_multi_class( |
||||
128 | -125x | +|||||
64 | +! | +
+ content,+ |
+ ||||
65 | +! | +
+ classes = c("character", "shiny.tag", "shiny.tag.list", "html"), null.ok = TRUE+ |
+ ||||
66 | ++ |
+ )+ |
+ ||||
67 | +! | +
+ checkmate::assert_multi_class(buttons, classes = c("shiny.tag", "shiny.tag.list"))+ |
+ ||||
68 | ++ | + + | +||||
69 | +! |
- x <- data[[dataname]]+ message("Initializing landing_popup_module") |
||||
129 | +70 | |||||
130 | -125x | -
- code <- if (is.function(x) && !is.primitive(x)) {- |
- ||||
131 | -6x | +|||||
71 | +! |
- x <- deparse1(x)+ module <- module( |
||||
132 | -6x | +|||||
72 | +! |
- bquote(rlang::hash(deparse1(.(as.name(dataname)))))+ label = label, |
||||
133 | -+ | |||||
73 | +! |
- } else {+ server = function(id) { |
||||
134 | -119x | +|||||
74 | +! |
- bquote(rlang::hash(.(as.name(dataname))))+ moduleServer(id, function(input, output, session) { |
||||
135 | -+ | |||||
75 | +! |
- }+ showModal( |
||||
136 | -125x | +|||||
76 | +! |
- sprintf(+ modalDialog( |
||||
137 | -125x | +|||||
77 | +! |
- "stopifnot(%s == %s) # @linksto %s",+ id = "landingpopup", |
||||
138 | -125x | +|||||
78 | +! |
- deparse1(code),+ title = title, |
||||
139 | -125x | +|||||
79 | +! |
- deparse1(rlang::hash(x)),+ content, |
||||
140 | -125x | +|||||
80 | +! |
- dataname+ footer = buttons |
||||
141 | +81 |
- )+ ) |
||||
142 | +82 |
- },+ ) |
||||
143 | -70x | +|||||
83 | +
- character(1L),+ }) |
|||||
144 | -70x | +|||||
84 | +
- USE.NAMES = TRUE+ } |
|||||
145 | +85 |
) |
||||
86 | +! | +
+ class(module) <- c("teal_module_landing", class(module))+ |
+ ||||
87 | +! | +
+ module+ |
+ ||||
146 | +88 |
}@@ -38443,4406 +39567,4852 @@ teal coverage - 59.99% | 77 | ! |
- shinyjs::useShinyjs(),+ shinyjs::useShinyjs(),+ |
+ |
78 | +! | +
+ include_css_files(),+ |
+ ||||
79 | ++ |
+ # init.js is executed from the server+ |
+ ||||
80 | +! | +
+ include_js_files(except = "init.js"),+ |
+ ||||
81 | +! | +
+ shinyjs::hidden(icon("fas fa-gear")), # add hidden icon to load font-awesome css for icons+ |
+ ||||
82 | ++ |
+ )+ |
+ ||||
83 | ++ |
+ }+ |
+
1 | ++ |
+ #' Send input validation messages to output+ |
+ |
2 | ++ |
+ #'+ |
+ |
3 | ++ |
+ #' Captures messages from `InputValidator` objects and collates them+ |
+ |
4 | ++ |
+ #' into one message passed to `validate`.+ |
+ |
5 | ++ |
+ #'+ |
+ |
6 | ++ |
+ #' `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 | ++ |
+ #' of the output element.+ |
+ |
9 | ++ |
+ #' `shinyvalidate::InputValidator` allows to validate input elements+ |
+ |
10 | ++ |
+ #' and to display specific messages in their respective input widgets.+ |
+ |
11 | ++ |
+ #' `validate_inputs` provides a hybrid solution.+ |
+ |
12 | ++ |
+ #' 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 | ++ |
+ #' This way the input `validator` messages are repeated in the output.+ |
+ |
15 | ++ |
+ #'+ |
+ |
16 | ++ |
+ #' The `...` argument accepts any number of `InputValidator` objects+ |
+ |
17 | ++ |
+ #' or a nested list of such objects.+ |
+ |
18 | ++ |
+ #' If `validators` are passed directly, all their messages are printed together+ |
+ |
19 | ++ |
+ #' under one (optional) header message specified by `header`. If a list is passed,+ |
+ |
20 | ++ |
+ #' messages are grouped by `validator`. The list's names are used as headers+ |
+ |
21 | ++ |
+ #' for their respective message groups.+ |
+ |
22 | ++ |
+ #' If neither of the nested list elements is named, a header message is taken from `header`.+ |
+ |
23 | ++ |
+ #'+ |
+ |
24 | ++ |
+ #' @param ... either any number of `InputValidator` objects+ |
+ |
25 | ++ |
+ #' or an optionally named, possibly nested `list` of `InputValidator`+ |
+ |
26 | ++ |
+ #' objects, see `Details`+ |
+ |
27 | ++ |
+ #' @param header (`character(1)`) generic validation message; set to NULL to omit+ |
+ |
28 | ++ |
+ #'+ |
+ |
29 | ++ |
+ #' @return+ |
+ |
30 | ++ |
+ #' Returns NULL if the final validation call passes and a `shiny.silent.error` if it fails.+ |
+ |
31 | ++ |
+ #'+ |
+ |
32 | ++ |
+ #' @seealso [`shinyvalidate::InputValidator`], [`shiny::validate`]+ |
+ |
33 | ++ |
+ #'+ |
+ |
34 | ++ |
+ #' @examplesIf require("shinyvalidate")+ |
+ |
35 | ++ |
+ #' library(shiny)+ |
+ |
36 | ++ |
+ #' library(shinyvalidate)+ |
+ |
37 | ++ |
+ #'+ |
+ |
38 | ++ |
+ #' ui <- fluidPage(+ |
+ |
39 | ++ |
+ #' selectInput("method", "validation method", c("sequential", "combined", "grouped")),+ |
+ |
40 | ++ |
+ #' sidebarLayout(+ |
+ |
41 | ++ |
+ #' sidebarPanel(+ |
+ |
42 | ++ |
+ #' selectInput("letter", "select a letter:", c(letters[1:3], LETTERS[4:6])),+ |
+ |
43 | ++ |
+ #' selectInput("number", "select a number:", 1:6),+ |
+ |
44 | ++ |
+ #' tags$br(),+ |
+ |
45 | ++ |
+ #' selectInput("color", "select a color:",+ |
+ |
46 | ++ |
+ #' c("black", "indianred2", "springgreen2", "cornflowerblue"),+ |
+ |
47 | ++ |
+ #' multiple = TRUE+ |
+ |
48 | ++ |
+ #' ), |
|
78 | -! | +||
49 | +
- include_css_files(),+ #' sliderInput("size", "select point size:", |
||
79 | +50 |
- # init.js is executed from the server+ #' min = 0.1, max = 4, value = 0.25 |
|
80 | -! | +||
51 | +
- include_js_files(except = "init.js"),+ #' ) |
||
81 | -! | +||
52 | +
- shinyjs::hidden(icon("fas fa-gear")), # add hidden icon to load font-awesome css for icons+ #' ), |
||
82 | +53 |
- )+ #' mainPanel(plotOutput("plot")) |
|
83 | +54 |
- }+ #' ) |
1 | +55 |
- #' Create a `tdata` object+ #' ) |
|
2 | +56 |
#' |
|
3 | +57 |
- #' @description `r lifecycle::badge("superseded")`+ #' server <- function(input, output) { |
|
4 | +58 |
- #'+ #' # set up input validation |
|
5 | +59 |
- #' Recent changes in `teal` cause modules to fail because modules expect a `tdata` object+ #' iv <- InputValidator$new() |
|
6 | +60 |
- #' to be passed to the `data` argument but instead they receive a `teal_data` object,+ #' iv$add_rule("letter", sv_in_set(LETTERS, "choose a capital letter")) |
|
7 | +61 |
- #' which is additionally wrapped in a reactive expression in the server functions.+ #' iv$add_rule("number", function(x) { |
|
8 | +62 |
- #' In order to easily adapt such modules without a proper refactor,+ #' if (as.integer(x) %% 2L == 1L) "choose an even number" |
|
9 | +63 |
- #' use this function to downgrade the `data` argument.+ #' }) |
|
10 | +64 |
- #'+ #' iv$enable() |
|
11 | +65 |
- #' @name tdata+ #' # more input validation |
|
12 | +66 |
- #' @param ... ignored+ #' iv_par <- InputValidator$new() |
|
13 | +67 |
- #' @return nothing+ #' iv_par$add_rule("color", sv_required(message = "choose a color")) |
|
14 | +68 |
- NULL+ #' iv_par$add_rule("color", function(x) { |
|
15 | +69 |
-
+ #' if (length(x) > 1L) "choose only one color" |
|
16 | +70 |
- #' @rdname tdata+ #' }) |
|
17 | +71 |
- #' @export+ #' iv_par$add_rule( |
|
18 | +72 |
- new_tdata <- function(...) {+ #' "size", |
|
19 | -! | +||
73 | +
- .deprecate_tdata_msg()+ #' sv_between( |
||
20 | +74 |
- }+ #' left = 0.5, right = 3, |
|
21 | +75 |
-
+ #' message_fmt = "choose a value between {left} and {right}" |
|
22 | +76 |
- #' @rdname tdata+ #' ) |
|
23 | +77 |
- #' @export+ #' ) |
|
24 | +78 |
- tdata2env <- function(...) {+ #' iv_par$enable() |
|
25 | -! | +||
79 | +
- .deprecate_tdata_msg()+ #' |
||
26 | +80 |
- }+ #' output$plot <- renderPlot({ |
|
27 | +81 |
-
+ #' # validate output |
|
28 | +82 |
- #' @rdname tdata+ #' switch(input[["method"]], |
|
29 | +83 |
- #' @export+ #' "sequential" = { |
|
30 | +84 |
- get_code_tdata <- function(...) {+ #' validate_inputs(iv) |
|
31 | -! | +||
85 | +
- .deprecate_tdata_msg()+ #' validate_inputs(iv_par, header = "Set proper graphical parameters") |
||
32 | +86 |
- }+ #' }, |
|
33 | +87 |
-
+ #' "combined" = validate_inputs(iv, iv_par), |
|
34 | +88 |
- #' @rdname tdata+ #' "grouped" = validate_inputs(list( |
|
35 | +89 |
- #' @export+ #' "Some inputs require attention" = iv, |
|
36 | +90 |
- join_keys.tdata <- function(...) {+ #' "Set proper graphical parameters" = iv_par |
|
37 | -! | +||
91 | +
- .deprecate_tdata_msg()+ #' )) |
||
38 | +92 |
- }+ #' ) |
|
39 | +93 |
-
+ #' |
|
40 | +94 |
- #' @rdname tdata+ #' plot(faithful$eruptions ~ faithful$waiting, |
|
41 | +95 |
- #' @export+ #' las = 1, pch = 16, |
|
42 | +96 |
- get_metadata <- function(...) {+ #' col = input[["color"]], cex = input[["size"]] |
|
43 | -! | +||
97 | +
- .deprecate_tdata_msg()+ #' ) |
||
44 | +98 |
- }+ #' }) |
|
45 | +99 |
-
+ #' } |
|
46 | +100 |
- #' @rdname tdata+ #' |
|
47 | +101 |
- #' @export+ #' if (interactive()) { |
|
48 | +102 |
- as_tdata <- function(...) {+ #' shinyApp(ui, server) |
|
49 | -! | +||
103 | +
- .deprecate_tdata_msg()+ #' } |
||
50 | +104 |
- }+ #' |
|
51 | +105 |
-
+ #' @export |
|
52 | +106 |
-
+ #' |
|
53 | +107 |
- .deprecate_tdata_msg <- function() {+ validate_inputs <- function(..., header = "Some inputs require attention") { |
|
54 | -! | +||
108 | +36x |
- lifecycle::deprecate_stop(+ dots <- list(...) |
|
55 | -! | +||
109 | +2x |
- when = "0.16",+ if (!is_validators(dots)) stop("validate_inputs accepts validators or a list thereof") |
|
56 | -! | +||
110 | +
- what = "tdata()",+ |
||
57 | -! | +||
111 | +34x |
- details = paste(+ messages <- extract_validator(dots, header) |
|
58 | -! | +||
112 | +34x |
- "tdata has been removed in favour of `teal_data`.\n",+ failings <- if (!any_names(dots)) { |
|
59 | -! | +||
113 | +29x |
- "Please follow migration instructions https://github.com/insightsengineering/teal/discussions/987."+ add_header(messages, header) |
|
60 | +114 |
- )+ } else {+ |
+ |
115 | +5x | +
+ unlist(messages) |
|
61 | +116 |
- )+ } |
|
62 | +117 | ++ | + + | +
118 | +34x | +
+ shiny::validate(shiny::need(is.null(failings), failings))+ |
+ |
119 |
} |
1 | +120 |
- #' Validate that dataset has a minimum number of observations+ |
||
2 | +121 |
- #'+ ### internal functions |
||
3 | +122 |
- #' `r lifecycle::badge("stable")`+ |
||
4 | +123 |
- #'+ #' @noRd |
||
5 | +124 |
- #' This function is a wrapper for `shiny::validate`.+ #' @keywords internal |
||
6 | +125 |
- #'+ # recursive object type test |
||
7 | +126 |
- #' @param x (`data.frame`)+ # returns logical of length 1 |
||
8 | +127 |
- #' @param min_nrow (`numeric(1)`) Minimum allowed number of rows in `x`.+ is_validators <- function(x) {+ |
+ ||
128 | +118x | +
+ all(if (is.list(x)) unlist(lapply(x, is_validators)) else inherits(x, "InputValidator")) |
||
9 | +129 |
- #' @param complete (`logical(1)`) Flag specifying whether to check only complete cases. Defaults to `FALSE`.+ } |
||
10 | +130 |
- #' @param allow_inf (`logical(1)`) Flag specifying whether to allow infinite values. Defaults to `TRUE`.+ |
||
11 | +131 |
- #' @param msg (`character(1)`) Additional message to display alongside the default message.+ #' @noRd |
||
12 | +132 |
- #'+ #' @keywords internal |
||
13 | +133 |
- #' @export+ # test if an InputValidator object is enabled |
||
14 | +134 |
- #'+ # returns logical of length 1 |
||
15 | +135 |
- #' @examples+ # official method requested at https://github.com/rstudio/shinyvalidate/issues/64 |
||
16 | +136 |
- #' library(teal)+ validator_enabled <- function(x) {+ |
+ ||
137 | +49x | +
+ x$.__enclos_env__$private$enabled |
||
17 | +138 |
- #' ui <- fluidPage(+ } |
||
18 | +139 |
- #' sliderInput("len", "Max Length of Sepal",+ |
||
19 | +140 |
- #' min = 4.3, max = 7.9, value = 5+ #' Recursively extract messages from validator list |
||
20 | +141 |
- #' ),+ #' @return A character vector or a list of character vectors, possibly nested and named. |
||
21 | +142 |
- #' plotOutput("plot")+ #' @noRd |
||
22 | +143 |
- #' )+ #' @keywords internal |
||
23 | +144 |
- #'+ extract_validator <- function(iv, header) {+ |
+ ||
145 | +113x | +
+ if (inherits(iv, "InputValidator")) {+ |
+ ||
146 | +49x | +
+ add_header(gather_messages(iv), header) |
||
24 | +147 |
- #' server <- function(input, output) {+ } 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) |
||
25 | +150 |
- #' output$plot <- renderPlot({+ } |
||
26 | +151 |
- #' iris_df <- iris[iris$Sepal.Length <= input$len, ]+ } |
||
27 | +152 |
- #' validate_has_data(+ |
||
28 | +153 |
- #' iris_df,+ #' Collate failing messages from validator. |
||
29 | +154 |
- #' min_nrow = 10,+ #' @return `list` |
||
30 | +155 |
- #' complete = FALSE,+ #' @noRd |
||
31 | +156 |
- #' msg = "Please adjust Max Length of Sepal"+ #' @keywords internal |
||
32 | +157 |
- #' )+ gather_messages <- function(iv) { |
||
33 | -+ | |||
158 | +49x |
- #'+ if (validator_enabled(iv)) { |
||
34 | -+ | |||
159 | +46x |
- #' hist(iris_df$Sepal.Length, breaks = 5)+ status <- iv$validate() |
||
35 | -+ | |||
160 | +46x |
- #' })+ failing_inputs <- Filter(Negate(is.null), status) |
||
36 | -+ | |||
161 | +46x |
- #' }+ unique(lapply(failing_inputs, function(x) x[["message"]])) |
||
37 | +162 |
- #' if (interactive()) {+ } else { |
||
38 | -+ | |||
163 | +3x |
- #' shinyApp(ui, server)+ warning("Validator is disabled and will be omitted.") |
||
39 | -+ | |||
164 | +3x |
- #' }+ list() |
||
40 | +165 |
- #'+ } |
||
41 | +166 |
- validate_has_data <- function(x,+ } |
||
42 | +167 |
- min_nrow = NULL,+ |
||
43 | +168 |
- complete = FALSE,+ #' Add optional header to failing messages |
||
44 | +169 |
- allow_inf = TRUE,+ #' @noRd |
||
45 | +170 |
- msg = NULL) {+ #' @keywords internal |
||
46 | -17x | +|||
171 | +
- checkmate::assert_string(msg, null.ok = TRUE)+ add_header <- function(messages, header = "") { |
|||
47 | -15x | +172 | +78x |
- checkmate::assert_data_frame(x)+ ans <- unlist(messages) |
48 | -15x | +173 | +78x |
- if (!is.null(min_nrow)) {+ if (length(ans) != 0L && isTRUE(nchar(header) > 0L)) { |
49 | -15x | +174 | +31x |
- if (complete) {+ ans <- c(paste0(header, "\n"), ans, "\n") |
50 | -5x | +|||
175 | +
- complete_index <- stats::complete.cases(x)+ } |
|||
51 | -5x | +176 | +78x |
- validate(need(+ ans |
52 | -5x | +|||
177 | +
- sum(complete_index) > 0 && nrow(x[complete_index, , drop = FALSE]) >= min_nrow,+ } |
|||
53 | -5x | +|||
178 | +
- paste(c(paste("Number of complete cases is less than:", min_nrow), msg), collapse = "\n")+ |
|||
54 | +179 |
- ))+ #' Recursively check if the object contains a named list |
||
55 | +180 |
- } else {+ #' @noRd |
||
56 | -10x | +|||
181 | +
- validate(need(+ #' @keywords internal |
|||
57 | -10x | +|||
182 | +
- nrow(x) >= min_nrow,+ any_names <- function(x) { |
|||
58 | -10x | +183 | +103x |
- paste(+ any( |
59 | -10x | +184 | +103x |
- c(paste("Minimum number of records not met: >=", min_nrow, "records required."), msg),+ if (is.list(x)) { |
60 | -10x | +185 | +58x |
- collapse = "\n"+ if (!is.null(names(x)) && any(names(x) != "")) TRUE else unlist(lapply(x, any_names)) |
61 | +186 |
- )+ } else { |
||
62 | -+ | |||
187 | +40x |
- ))+ FALSE |
||
63 | +188 |
} |
||
64 | +189 |
-
+ ) |
||
65 | -10x | +|||
190 | +
- if (!allow_inf) {+ } |
|||
66 | -6x | +
1 | +
- validate(need(+ #' Create a `tdata` object |
||
67 | -6x | +||
2 | +
- all(vapply(x, function(col) !is.numeric(col) || !any(is.infinite(col)), logical(1))),+ #' |
||
68 | -6x | +||
3 | +
- "Dataframe contains Inf values which is not allowed."+ #' @description `r lifecycle::badge("superseded")` |
||
69 | +4 |
- ))+ #' |
|
70 | +5 |
- }+ #' Recent changes in `teal` cause modules to fail because modules expect a `tdata` object |
|
71 | +6 |
- }+ #' to be passed to the `data` argument but instead they receive a `teal_data` object, |
|
72 | +7 |
- }+ #' which is additionally wrapped in a reactive expression in the server functions. |
|
73 | +8 |
-
+ #' In order to easily adapt such modules without a proper refactor, |
|
74 | +9 |
- #' Validate that dataset has unique rows for key variables+ #' use this function to downgrade the `data` argument. |
|
75 | +10 |
#' |
|
76 | +11 |
- #' `r lifecycle::badge("stable")`+ #' @name tdata |
|
77 | +12 |
- #'+ #' @param ... ignored |
|
78 | +13 |
- #' This function is a wrapper for `shiny::validate`.+ #' @return nothing |
|
79 | +14 |
- #'+ NULL |
|
80 | +15 |
- #' @param x (`data.frame`)+ |
|
81 | +16 |
- #' @param key (`character`) Vector of ID variables from `x` that identify unique records.+ #' @rdname tdata |
|
82 | +17 |
- #'+ #' @export |
|
83 | +18 |
- #' @export+ new_tdata <- function(...) { |
|
84 | -+ | ||
19 | +! |
- #'+ .deprecate_tdata_msg() |
|
85 | +20 |
- #' @examples+ } |
|
86 | +21 |
- #' iris$id <- rep(1:50, times = 3)+ |
|
87 | +22 |
- #' ui <- fluidPage(+ #' @rdname tdata |
|
88 | +23 |
- #' selectInput(+ #' @export |
|
89 | +24 |
- #' inputId = "species",+ tdata2env <- function(...) {+ |
+ |
25 | +! | +
+ .deprecate_tdata_msg() |
|
90 | +26 |
- #' label = "Select species",+ } |
|
91 | +27 |
- #' choices = c("setosa", "versicolor", "virginica"),+ |
|
92 | +28 |
- #' selected = "setosa",+ #' @rdname tdata |
|
93 | +29 |
- #' multiple = TRUE+ #' @export |
|
94 | +30 |
- #' ),+ get_code_tdata <- function(...) {+ |
+ |
31 | +! | +
+ .deprecate_tdata_msg() |
|
95 | +32 |
- #' plotOutput("plot")+ } |
|
96 | +33 |
- #' )+ |
|
97 | +34 |
- #' server <- function(input, output) {+ #' @rdname tdata |
|
98 | +35 |
- #' output$plot <- renderPlot({+ #' @export |
|
99 | +36 |
- #' iris_f <- iris[iris$Species %in% input$species, ]+ join_keys.tdata <- function(...) {+ |
+ |
37 | +! | +
+ .deprecate_tdata_msg() |
|
100 | +38 |
- #' validate_one_row_per_id(iris_f, key = c("id"))+ } |
|
101 | +39 |
- #'+ |
|
102 | +40 |
- #' hist(iris_f$Sepal.Length, breaks = 5)+ #' @rdname tdata |
|
103 | +41 |
- #' })+ #' @export |
|
104 | +42 |
- #' }+ get_metadata <- function(...) {+ |
+ |
43 | +! | +
+ .deprecate_tdata_msg() |
|
105 | +44 |
- #' if (interactive()) {+ } |
|
106 | +45 |
- #' shinyApp(ui, server)+ |
|
107 | +46 |
- #' }+ #' @rdname tdata |
|
108 | +47 |
- #'+ #' @export |
|
109 | +48 |
- validate_one_row_per_id <- function(x, key = c("USUBJID", "STUDYID")) {+ as_tdata <- function(...) { |
|
110 | +49 | ! |
- validate(need(!any(duplicated(x[key])), paste("Found more than one row per id.")))+ .deprecate_tdata_msg() |
111 | +50 |
} |
|
112 | +51 | ||
113 | +52 |
- #' Validates that vector includes all expected values+ |
|
114 | +53 |
- #'+ .deprecate_tdata_msg <- function() { |
|
115 | -+ | ||
54 | +! |
- #' `r lifecycle::badge("stable")`+ lifecycle::deprecate_stop(+ |
+ |
55 | +! | +
+ when = "0.16",+ |
+ |
56 | +! | +
+ what = "tdata()",+ |
+ |
57 | +! | +
+ details = paste(+ |
+ |
58 | +! | +
+ "tdata has been removed in favour of `teal_data`.\n",+ |
+ |
59 | +! | +
+ "Please follow migration instructions https://github.com/insightsengineering/teal/discussions/987." |
|
116 | +60 |
- #'+ ) |
|
117 | +61 |
- #' This function is a wrapper for `shiny::validate`.+ ) |
|
118 | +62 |
- #'+ } |
119 | +1 |
- #' @param x Vector of values to test.+ #' @title `TealReportCard` |
|
120 | +2 |
- #' @param choices Vector to test against.+ #' @description `r lifecycle::badge("experimental")` |
|
121 | +3 |
- #' @param msg (`character(1)`) Error message to display if some elements of `x` are not elements of `choices`.+ #' Child class of [`ReportCard`] that is used for `teal` specific applications. |
|
122 | +4 |
- #'+ #' In addition to the parent methods, it supports rendering `teal` specific elements such as |
|
123 | +5 |
- #' @export+ #' the source code, the encodings panel content and the filter panel content as part of the |
|
124 | +6 |
- #'+ #' meta data. |
|
125 | +7 |
- #' @examples+ #' @export |
|
126 | +8 |
- #' ui <- fluidPage(+ #' |
|
127 | +9 |
- #' selectInput(+ TealReportCard <- R6::R6Class( # nolint: object_name. |
|
128 | +10 |
- #' "species",+ classname = "TealReportCard", |
|
129 | +11 |
- #' "Select species",+ inherit = teal.reporter::ReportCard, |
|
130 | +12 |
- #' choices = c("setosa", "versicolor", "virginica", "unknown species"),+ public = list( |
|
131 | +13 |
- #' selected = "setosa",+ #' @description Appends the source code to the `content` meta data of this `TealReportCard`. |
|
132 | +14 |
- #' multiple = FALSE+ #' |
|
133 | +15 |
- #' ),+ #' @param src (`character(1)`) code as text. |
|
134 | +16 |
- #' verbatimTextOutput("summary")+ #' @param ... any `rmarkdown` `R` chunk parameter and its value. |
|
135 | +17 |
- #' )+ #' But `eval` parameter is always set to `FALSE`. |
|
136 | +18 |
- #'+ #' @return Object of class `TealReportCard`, invisibly. |
|
137 | +19 |
- #' server <- function(input, output) {+ #' @examples |
|
138 | +20 |
- #' output$summary <- renderPrint({+ #' card <- TealReportCard$new()$append_src( |
|
139 | +21 |
- #' validate_in(input$species, iris$Species, "Species does not exist.")+ #' "plot(iris)" |
|
140 | +22 |
- #' nrow(iris[iris$Species == input$species, ])+ #' ) |
|
141 | +23 |
- #' })+ #' card$get_content()[[1]]$get_content() |
|
142 | +24 |
- #' }+ append_src = function(src, ...) { |
|
143 | -+ | ||
25 | +4x |
- #' if (interactive()) {+ checkmate::assert_character(src, min.len = 0, max.len = 1) |
|
144 | -+ | ||
26 | +4x |
- #' shinyApp(ui, server)+ params <- list(...) |
|
145 | -+ | ||
27 | +4x |
- #' }+ params$eval <- FALSE |
|
146 | -+ | ||
28 | +4x |
- #'+ rblock <- RcodeBlock$new(src) |
|
147 | -+ | ||
29 | +4x |
- validate_in <- function(x, choices, msg) {+ rblock$set_params(params) |
|
148 | -! | +||
30 | +4x |
- validate(need(length(x) > 0 && length(choices) > 0 && all(x %in% choices), msg))+ self$append_content(rblock) |
|
149 | -+ | ||
31 | +4x |
- }+ self$append_metadata("SRC", src) |
|
150 | -+ | ||
32 | +4x |
-
+ invisible(self) |
|
151 | +33 |
- #' Validates that vector has length greater than 0+ }, |
|
152 | +34 |
- #'+ #' @description Appends the filter state list to the `content` and `metadata` of this `TealReportCard`. |
|
153 | +35 |
- #' `r lifecycle::badge("stable")`+ #' If the filter state list has an attribute named `formatted`, it appends it to the card otherwise it uses |
|
154 | +36 |
- #'+ #' the default `yaml::as.yaml` to format the list. |
|
155 | +37 |
- #' This function is a wrapper for `shiny::validate`.+ #' If the filter state list is empty, nothing is appended to the `content`. |
|
156 | +38 |
- #'+ #' |
|
157 | +39 |
- #' @param x vector+ #' @param fs (`teal_slices`) object returned from [teal_slices()] function. |
|
158 | +40 |
- #' @param msg message to display+ #' @return `self`, invisibly. |
|
159 | +41 |
- #'+ append_fs = function(fs) { |
|
160 | -+ | ||
42 | +5x |
- #' @export+ checkmate::assert_class(fs, "teal_slices") |
|
161 | -+ | ||
43 | +4x |
- #'+ self$append_text("Filter State", "header3") |
|
162 | -+ | ||
44 | +4x |
- #' @examples+ if (length(fs)) { |
|
163 | -+ | ||
45 | +3x |
- #' data <- data.frame(+ self$append_content(TealSlicesBlock$new(fs)) |
|
164 | +46 |
- #' id = c(1:10, 11:20, 1:10),+ } else { |
|
165 | -+ | ||
47 | +1x |
- #' strata = rep(c("A", "B"), each = 15)+ self$append_text("No filters specified.") |
|
166 | +48 |
- #' )+ } |
|
167 | -+ | ||
49 | +4x |
- #' ui <- fluidPage(+ invisible(self) |
|
168 | +50 |
- #' selectInput("ref1", "Select strata1 to compare",+ }, |
|
169 | +51 |
- #' choices = c("A", "B", "C"), selected = "A"+ #' @description Appends the encodings list to the `content` and `metadata` of this `TealReportCard`. |
|
170 | +52 |
- #' ),+ #' |
|
171 | +53 |
- #' selectInput("ref2", "Select strata2 to compare",+ #' @param encodings (`list`) list of encodings selections of the `teal` app. |
|
172 | +54 |
- #' choices = c("A", "B", "C"), selected = "B"+ #' @return `self`, invisibly. |
|
173 | +55 |
- #' ),+ #' @examples |
|
174 | +56 |
- #' verbatimTextOutput("arm_summary")+ #' card <- TealReportCard$new()$append_encodings(list(variable1 = "X")) |
|
175 | +57 |
- #' )+ #' card$get_content()[[1]]$get_content() |
|
176 | +58 |
- #'+ #' |
|
177 | +59 |
- #' server <- function(input, output) {+ append_encodings = function(encodings) { |
|
178 | -+ | ||
60 | +4x |
- #' output$arm_summary <- renderText({+ checkmate::assert_list(encodings) |
|
179 | -+ | ||
61 | +4x |
- #' sample_1 <- data$id[data$strata == input$ref1]+ self$append_text("Selected Options", "header3") |
|
180 | -+ | ||
62 | +4x |
- #' sample_2 <- data$id[data$strata == input$ref2]+ if (requireNamespace("yaml", quietly = TRUE)) { |
|
181 | -+ | ||
63 | +4x |
- #'+ self$append_text(yaml::as.yaml(encodings, handlers = list( |
|
182 | -+ | ||
64 | +4x |
- #' validate_has_elements(sample_1, "No subjects in strata1.")+ POSIXct = function(x) format(x, "%Y-%m-%d"), |
|
183 | -+ | ||
65 | +4x |
- #' validate_has_elements(sample_2, "No subjects in strata2.")+ POSIXlt = function(x) format(x, "%Y-%m-%d"), |
|
184 | -+ | ||
66 | +4x |
- #'+ Date = function(x) format(x, "%Y-%m-%d") |
|
185 | -+ | ||
67 | +4x |
- #' paste0(+ )), "verbatim") |
|
186 | +68 |
- #' "Number of samples in: strata1=", length(sample_1),+ } else { |
|
187 | -+ | ||
69 | +! |
- #' " comparions strata2=", length(sample_2)+ stop("yaml package is required to format the encodings list") |
|
188 | +70 |
- #' )+ } |
|
189 | -+ | ||
71 | +4x |
- #' })+ self$append_metadata("Encodings", encodings) |
|
190 | -+ | ||
72 | +4x |
- #' }+ invisible(self) |
|
191 | +73 |
- #' if (interactive()) {+ } |
|
192 | +74 |
- #' shinyApp(ui, server)+ ), |
|
193 | +75 |
- #' }+ private = list( |
|
194 | +76 |
- validate_has_elements <- function(x, msg) {+ dispatch_block = function(block_class) { |
|
195 | +77 | ! |
- validate(need(length(x) > 0, msg))- |
-
196 | -- |
- }+ eval(str2lang(block_class)) |
|
197 | +78 |
-
+ } |
|
198 | +79 |
- #' Validates no intersection between two vectors+ ) |
|
199 | +80 |
- #'+ ) |
|
200 | +81 |
- #' `r lifecycle::badge("stable")`+ |
|
201 | +82 |
- #'+ #' @title `TealSlicesBlock` |
|
202 | +83 |
- #' This function is a wrapper for `shiny::validate`.+ #' @docType class |
|
203 | +84 |
- #'+ #' @description |
|
204 | +85 |
- #' @param x vector+ #' Specialized `TealSlicesBlock` block for managing filter panel content in reports. |
|
205 | +86 |
- #' @param y vector+ #' @keywords internal |
|
206 | +87 |
- #' @param msg (`character(1)`) message to display if `x` and `y` intersect+ TealSlicesBlock <- R6::R6Class( # nolint: object_name_linter. |
|
207 | +88 |
- #'+ classname = "TealSlicesBlock", |
|
208 | +89 |
- #' @export+ inherit = teal.reporter:::TextBlock, |
|
209 | +90 |
- #'+ public = list( |
|
210 | +91 |
- #' @examples+ #' @description Returns a `TealSlicesBlock` object. |
|
211 | +92 |
- #' data <- data.frame(+ #' |
|
212 | +93 |
- #' id = c(1:10, 11:20, 1:10),+ #' @details Returns a `TealSlicesBlock` object with no content and no parameters. |
|
213 | +94 |
- #' strata = rep(c("A", "B", "C"), each = 10)+ #' |
|
214 | +95 |
- #' )+ #' @param content (`teal_slices`) object returned from [teal_slices()] function. |
|
215 | +96 |
- #'+ #' @param style (`character(1)`) string specifying style to apply. |
|
216 | +97 |
- #' ui <- fluidPage(+ #' |
|
217 | +98 |
- #' selectInput("ref1", "Select strata1 to compare",+ #' @return Object of class `TealSlicesBlock`, invisibly. |
|
218 | +99 |
- #' choices = c("A", "B", "C"),+ #' |
|
219 | +100 |
- #' selected = "A"+ initialize = function(content = teal_slices(), style = "verbatim") { |
|
220 | -+ | ||
101 | +9x |
- #' ),+ self$set_content(content) |
|
221 | -+ | ||
102 | +8x |
- #' selectInput("ref2", "Select strata2 to compare",+ self$set_style(style) |
|
222 | -+ | ||
103 | +8x |
- #' choices = c("A", "B", "C"),+ invisible(self) |
|
223 | +104 |
- #' selected = "B"+ }, |
|
224 | +105 |
- #' ),+ |
|
225 | +106 |
- #' verbatimTextOutput("summary")+ #' @description Sets content of this `TealSlicesBlock`. |
|
226 | +107 |
- #' )+ #' Sets content as `YAML` text which represents a list generated from `teal_slices`. |
|
227 | +108 |
- #'+ #' The list displays limited number of fields from `teal_slice` objects, but this list is |
|
228 | +109 |
- #' server <- function(input, output) {+ #' sufficient to conclude which filters were applied. |
|
229 | +110 |
- #' output$summary <- renderText({+ #' When `selected` field in `teal_slice` object is a range, then it is displayed as a "min" |
|
230 | +111 |
- #' sample_1 <- data$id[data$strata == input$ref1]+ #' |
|
231 | +112 |
- #' sample_2 <- data$id[data$strata == input$ref2]+ #' |
|
232 | +113 |
- #'+ #' @param content (`teal_slices`) object returned from [teal_slices()] function. |
|
233 | +114 |
- #' validate_no_intersection(+ #' @return `self`, invisibly. |
|
234 | +115 |
- #' sample_1, sample_2,+ set_content = function(content) { |
|
235 | -+ | ||
116 | +9x |
- #' "subjects within strata1 and strata2 cannot overlap"+ checkmate::assert_class(content, "teal_slices") |
|
236 | -+ | ||
117 | +8x |
- #' )+ if (length(content) != 0) { |
|
237 | -+ | ||
118 | +6x |
- #' paste0(+ states_list <- lapply(content, function(x) { |
|
238 | -+ | ||
119 | +6x |
- #' "Number of subject in: reference treatment=", length(sample_1),+ x_list <- shiny::isolate(as.list(x)) |
|
239 | -+ | ||
120 | +6x |
- #' " comparions treatment=", length(sample_2)+ if ( |
|
240 | -+ | ||
121 | +6x |
- #' )+ inherits(x_list$choices, c("integer", "numeric", "Date", "POSIXct", "POSIXlt")) && |
|
241 | -+ | ||
122 | +6x |
- #' })+ length(x_list$choices) == 2 && |
|
242 | -+ | ||
123 | +6x |
- #' }+ length(x_list$selected) == 2 |
|
243 | +124 |
- #' if (interactive()) {+ ) { |
|
244 | -+ | ||
125 | +! |
- #' shinyApp(ui, server)+ x_list$range <- paste(x_list$selected, collapse = " - ") |
|
245 | -+ | ||
126 | +! |
- #' }+ x_list["selected"] <- NULL |
|
246 | +127 |
- #'+ } |
|
247 | -+ | ||
128 | +6x |
- validate_no_intersection <- function(x, y, msg) {+ if (!is.null(x_list$arg)) { |
|
248 | +129 | ! |
- validate(need(length(intersect(x, y)) == 0, msg))+ x_list$arg <- if (x_list$arg == "subset") "Genes" else "Samples" |
249 | +130 |
- }+ } |
|
250 | +131 | ||
251 | -+ | ||
132 | +6x |
-
+ x_list <- x_list[ |
|
252 | -+ | ||
133 | +6x |
- #' Validates that dataset contains specific variable+ c("dataname", "varname", "experiment", "arg", "expr", "selected", "range", "keep_na", "keep_inf") |
|
253 | +134 |
- #'+ ] |
|
254 | -+ | ||
135 | +6x |
- #' `r lifecycle::badge("stable")`+ names(x_list) <- c( |
|
255 | -+ | ||
136 | +6x |
- #'+ "Dataset name", "Variable name", "Experiment", "Filtering by", "Applied expression", |
|
256 | -+ | ||
137 | +6x |
- #' This function is a wrapper for `shiny::validate`.+ "Selected Values", "Selected range", "Include NA values", "Include Inf values" |
|
257 | +138 |
- #'+ ) |
|
258 | +139 |
- #' @param data (`data.frame`)+ |
|
259 | -+ | ||
140 | +6x |
- #' @param varname (`character(1)`) name of variable to check for in `data`+ Filter(Negate(is.null), x_list) |
|
260 | +141 |
- #' @param msg (`character(1)`) message to display if `data` does not include `varname`+ }) |
|
261 | +142 |
- #'+ |
|
262 | -+ | ||
143 | +6x |
- #' @export+ if (requireNamespace("yaml", quietly = TRUE)) { |
|
263 | -+ | ||
144 | +6x |
- #'+ super$set_content(yaml::as.yaml(states_list)) |
|
264 | +145 |
- #' @examples+ } else { |
|
265 | -+ | ||
146 | +! |
- #' data <- data.frame(+ stop("yaml package is required to format the filter state list") |
|
266 | +147 |
- #' one = rep("a", length.out = 20),+ } |
|
267 | +148 |
- #' two = rep(c("a", "b"), length.out = 20)+ } |
|
268 | -+ | ||
149 | +8x |
- #' )+ private$teal_slices <- content |
|
269 | -+ | ||
150 | +8x |
- #' ui <- fluidPage(+ invisible(self) |
|
270 | +151 |
- #' selectInput(+ }, |
|
271 | +152 |
- #' "var",+ #' @description Create the `TealSlicesBlock` from a list. |
|
272 | +153 |
- #' "Select variable",+ #' |
|
273 | +154 |
- #' choices = c("one", "two", "three", "four"),+ #' @param x (`named list`) with two fields `text` and `style`. |
|
274 | +155 |
- #' selected = "one"+ #' Use the `get_available_styles` method to get all possible styles. |
|
275 | +156 |
- #' ),+ #' |
|
276 | +157 |
- #' verbatimTextOutput("summary")+ #' @return `self`, invisibly. |
|
277 | +158 |
- #' )+ #' @examples |
|
278 | +159 |
- #'+ #' TealSlicesBlock <- getFromNamespace("TealSlicesBlock", "teal") |
|
279 | +160 |
- #' server <- function(input, output) {+ #' block <- TealSlicesBlock$new() |
|
280 | +161 |
- #' output$summary <- renderText({+ #' block$from_list(list(text = "sth", style = "default")) |
|
281 | +162 |
- #' validate_has_variable(data, input$var)+ #' |
|
282 | +163 |
- #' paste0("Selected treatment variables: ", paste(input$var, collapse = ", "))+ from_list = function(x) { |
|
283 | -+ | ||
164 | +1x |
- #' })+ checkmate::assert_list(x) |
|
284 | -+ | ||
165 | +1x |
- #' }+ checkmate::assert_names(names(x), must.include = c("text", "style")) |
|
285 | -+ | ||
166 | +1x |
- #' if (interactive()) {+ super$set_content(x$text) |
|
286 | -+ | ||
167 | +1x |
- #' shinyApp(ui, server)+ super$set_style(x$style) |
|
287 | -+ | ||
168 | +1x |
- #' }+ invisible(self) |
|
288 | +169 |
- validate_has_variable <- function(data, varname, msg) {+ }, |
|
289 | -! | +||
170 | +
- if (length(varname) != 0) {+ #' @description Convert the `TealSlicesBlock` to a list. |
||
290 | -! | +||
171 | +
- has_vars <- varname %in% names(data)+ #' |
||
291 | +172 |
-
+ #' @return `named list` with a text and style. |
|
292 | -! | +||
173 | +
- if (!all(has_vars)) {+ #' @examples |
||
293 | -! | +||
174 | +
- if (missing(msg)) {+ #' TealSlicesBlock <- getFromNamespace("TealSlicesBlock", "teal") |
||
294 | -! | +||
175 | +
- msg <- sprintf(+ #' block <- TealSlicesBlock$new() |
||
295 | -! | +||
176 | +
- "%s does not have the required variables: %s.",+ #' block$to_list() |
||
296 | -! | +||
177 | +
- deparse(substitute(data)),+ #' |
||
297 | -! | +||
178 | +
- toString(varname[!has_vars])+ to_list = function() { |
||
298 | -+ | ||
179 | +2x |
- )+ content <- self$get_content() |
|
299 | -+ | ||
180 | +2x |
- }+ list( |
|
300 | -! | +||
181 | +2x |
- validate(need(FALSE, msg))+ text = if (length(content)) content else "", |
|
301 | -+ | ||
182 | +2x |
- }+ style = self$get_style() |
|
302 | +183 |
- }+ ) |
|
303 | +184 |
- }+ } |
|
304 | +185 |
-
+ ), |
|
305 | +186 |
- #' Validate that variables has expected number of levels+ private = list( |
|
306 | +187 |
- #'+ style = "verbatim", |
|
307 | +188 |
- #' `r lifecycle::badge("stable")`+ teal_slices = NULL # teal_slices |
|
308 | +189 |
- #'+ ) |
|
309 | +190 |
- #' If the number of levels of `x` is less than `min_levels`+ ) |
310 | +1 |
- #' or greater than `max_levels` the validation will fail.+ #' Data module for `teal` applications |
|
311 | +2 |
- #' This function is a wrapper for `shiny::validate`.+ #' |
|
312 | +3 |
- #'+ #' @description |
|
313 | +4 |
- #' @param x variable name. If `x` is not a factor, the unique values+ #' `r lifecycle::badge("experimental")` |
|
314 | +5 |
- #' are treated as levels.+ #' |
|
315 | +6 |
- #' @param min_levels cutoff for minimum number of levels of `x`+ #' Create a `teal_data_module` object and evaluate code on it with history tracking. |
|
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+ #' @details |
|
318 | +9 |
- #' validation message+ #' `teal_data_module` creates a `shiny` module to interactively supply or modify data in a `teal` application. |
|
319 | +10 |
- #'+ #' The module allows for running any code (creation _and_ some modification) after the app starts or reloads. |
|
320 | +11 |
- #' @export+ #' The body of the server function will be run in the app rather than in the global environment. |
|
321 | +12 |
- #' @examples+ #' This means it will be run every time the app starts, so use sparingly. |
|
322 | +13 |
- #' data <- data.frame(+ #' |
|
323 | +14 |
- #' one = rep("a", length.out = 20),+ #' Pass this module instead of a `teal_data` object in a call to [init()]. |
|
324 | +15 |
- #' two = rep(c("a", "b"), length.out = 20),+ #' Note that the server function must always return a `teal_data` object wrapped in a reactive expression. |
|
325 | +16 |
- #' three = rep(c("a", "b", "c"), length.out = 20),+ #' |
|
326 | +17 |
- #' four = rep(c("a", "b", "c", "d"), length.out = 20),+ #' See vignette `vignette("data-as-shiny-module", package = "teal")` for more details. |
|
327 | +18 |
- #' stringsAsFactors = TRUE+ #' |
|
328 | +19 |
- #' )+ #' @param ui (`function(id)`) |
|
329 | +20 |
- #' ui <- fluidPage(+ #' `shiny` module UI function; must only take `id` argument |
|
330 | +21 |
- #' selectInput(+ #' @param server (`function(id)`) |
|
331 | +22 |
- #' "var",+ #' `shiny` module server function; must only take `id` argument; |
|
332 | +23 |
- #' "Select variable",+ #' must return reactive expression containing `teal_data` object |
|
333 | +24 |
- #' choices = c("one", "two", "three", "four"),+ #' @param label (`character(1)`) Label of the module. |
|
334 | +25 |
- #' selected = "one"+ #' @param once (`logical(1)`) |
|
335 | +26 |
- #' ),+ #' If `TRUE`, the data module will be shown only once and will disappear after successful data loading. |
|
336 | +27 |
- #' verbatimTextOutput("summary")+ #' App user will no longer be able to interact with this module anymore. |
|
337 | +28 |
- #' )+ #' If `FALSE`, the data module can be reused multiple times. |
|
338 | +29 |
- #'+ #' App user will be able to interact and change the data output from the module multiple times. |
|
339 | +30 |
- #' server <- function(input, output) {+ #' |
|
340 | +31 |
- #' output$summary <- renderText({+ #' @return |
|
341 | +32 |
- #' validate_n_levels(data[[input$var]], min_levels = 2, max_levels = 15, var_name = input$var)+ #' `teal_data_module` returns a list of class `teal_data_module` containing two elements, `ui` and |
|
342 | +33 |
- #' paste0(+ #' `server` provided via arguments. |
|
343 | +34 |
- #' "Levels of selected treatment variable: ",+ #' |
|
344 | +35 |
- #' paste(levels(data[[input$var]]),+ #' @examples |
|
345 | +36 |
- #' collapse = ", "+ #' tdm <- teal_data_module( |
|
346 | +37 |
- #' )+ #' ui = function(id) { |
|
347 | +38 |
- #' )+ #' ns <- NS(id) |
|
348 | +39 |
- #' })+ #' actionButton(ns("submit"), label = "Load data") |
|
349 | +40 |
- #' }+ #' }, |
|
350 | +41 |
- #' if (interactive()) {+ #' server = function(id) { |
|
351 | +42 |
- #' shinyApp(ui, server)+ #' moduleServer(id, function(input, output, session) { |
|
352 | +43 |
- #' }+ #' eventReactive(input$submit, { |
|
353 | +44 |
- validate_n_levels <- function(x, min_levels = 1, max_levels = 12, var_name) {+ #' data <- within( |
|
354 | -! | +||
45 | +
- x_levels <- if (is.factor(x)) {+ #' teal_data(), |
||
355 | -! | +||
46 | +
- levels(x)+ #' { |
||
356 | +47 |
- } else {+ #' dataset1 <- iris |
|
357 | -! | +||
48 | +
- unique(x)+ #' dataset2 <- mtcars |
||
358 | +49 |
- }+ #' } |
|
359 | +50 |
-
+ #' ) |
|
360 | -! | +||
51 | +
- if (!is.null(min_levels) && !(is.null(max_levels))) {+ #' datanames(data) <- c("dataset1", "dataset2") |
||
361 | -! | +||
52 | +
- validate(need(+ #' |
||
362 | -! | +||
53 | +
- length(x_levels) >= min_levels && length(x_levels) <= max_levels,+ #' data |
||
363 | -! | +||
54 | +
- sprintf(+ #' }) |
||
364 | -! | +||
55 | +
- "%s variable needs minimum %s level(s) and maximum %s level(s).",+ #' }) |
||
365 | -! | +||
56 | +
- var_name, min_levels, max_levels+ #' } |
||
366 | +57 |
- )+ #' ) |
|
367 | +58 |
- ))+ #' |
|
368 | -! | +||
59 | +
- } else if (!is.null(min_levels)) {+ #' @name teal_data_module |
||
369 | -! | +||
60 | +
- validate(need(+ #' @seealso [`teal.data::teal_data-class`], [teal.code::qenv()] |
||
370 | -! | +||
61 | +
- length(x_levels) >= min_levels,+ #' |
||
371 | -! | +||
62 | +
- sprintf("%s variable needs minimum %s levels(s)", var_name, min_levels)+ #' @export |
||
372 | +63 |
- ))+ teal_data_module <- function(ui, server, label = "data module", once = TRUE) { |
|
373 | -! | +||
64 | +33x |
- } else if (!is.null(max_levels)) {+ checkmate::assert_function(ui, args = "id", nargs = 1) |
|
374 | -! | +||
65 | +32x |
- validate(need(+ checkmate::assert_function(server, args = "id", nargs = 1) |
|
375 | -! | +||
66 | +30x |
- length(x_levels) <= max_levels,+ checkmate::assert_string(label) |
|
376 | -! | +||
67 | +30x |
- sprintf("%s variable needs maximum %s level(s)", var_name, max_levels)+ checkmate::assert_flag(once) |
|
377 | -+ | ||
68 | +30x |
- ))+ structure( |
|
378 | -+ | ||
69 | +30x |
- }+ list( |
|
379 | -+ | ||
70 | +30x |
- }+ ui = ui, |
1 | -+ | |||
71 | +30x |
- #' Filter settings for `teal` applications+ server = function(id) { |
||
2 | -+ | |||
72 | +23x |
- #'+ data_out <- server(id) |
||
3 | -+ | |||
73 | +22x |
- #' Specify initial filter states and filtering settings for a `teal` app.+ decorate_err_msg( |
||
4 | -+ | |||
74 | +22x |
- #'+ assert_reactive(data_out), |
||
5 | -+ | |||
75 | +22x |
- #' Produces a `teal_slices` object.+ pre = sprintf("From: 'teal_data_module()':\nA 'teal_data_module' with \"%s\" label:", label), |
||
6 | -+ | |||
76 | +22x |
- #' The `teal_slice` components will specify filter states that will be active when the app starts.+ post = "Please make sure that this module returns a 'reactive` object containing 'teal_data' class of object." # nolint: line_length_linter. |
||
7 | +77 |
- #' Attributes (created with the named arguments) will configure the way the app applies filters.+ ) |
||
8 | +78 |
- #' See argument descriptions for details.+ } |
||
9 | +79 |
- #'+ ), |
||
10 | -+ | |||
80 | +30x |
- #' @inheritParams teal.slice::teal_slices+ label = label, |
||
11 | -+ | |||
81 | +30x |
- #'+ class = "teal_data_module", |
||
12 | -+ | |||
82 | +30x |
- #' @param module_specific (`logical(1)`) optional,+ once = once |
||
13 | +83 |
- #' - `FALSE` (default) when one filter panel applied to all modules.+ ) |
||
14 | +84 |
- #' All filters will be shared by all modules.+ } |
||
15 | +85 |
- #' - `TRUE` when filter panel module-specific.+ |
||
16 | +86 |
- #' Modules can have different set of filters specified - see `mapping` argument.+ #' Data module for `teal` transformers. |
||
17 | +87 |
- #' @param mapping `r lifecycle::badge("experimental")`+ #' |
||
18 | +88 |
- #' _This is a new feature. Do kindly share your opinions on+ #' @description |
||
19 | +89 |
- #' [`teal`'s GitHub repository](https://github.com/insightsengineering/teal/)._+ #' `r lifecycle::badge("experimental")` |
||
20 | +90 |
#' |
||
21 | +91 |
- #' (named `list`) specifies which filters will be active in which modules on app start.+ #' Create a `teal_data_module` object for custom transformation of data for pre-processing |
||
22 | +92 |
- #' Elements should contain character vector of `teal_slice` `id`s (see [`teal.slice::teal_slice`]).+ #' before passing the data into the module. |
||
23 | +93 |
- #' Names of the list should correspond to `teal_module` `label` set in [module()] function.+ #' |
||
24 | +94 |
- #' - `id`s listed under `"global_filters` will be active in all modules.+ #' @details |
||
25 | +95 |
- #' - If missing, all filters will be applied to all modules.+ #' `teal_transform_module` creates a [`teal_data_module`] object to transform data in a `teal` |
||
26 | +96 |
- #' - If empty list, all filters will be available to all modules but will start inactive.+ #' application. This transformation happens after the data has passed through the filtering activity |
||
27 | +97 |
- #' - If `module_specific` is `FALSE`, only `global_filters` will be active on start.+ #' in teal. The transformed data is then sent to the server of the [teal_module()]. |
||
28 | +98 |
- #' @param app_id (`character(1)`)+ #' |
||
29 | +99 |
- #' For internal use only, do not set manually.+ #' See vignette `vignette("data-transform-as-shiny-module", package = "teal")` for more details. |
||
30 | +100 |
- #' Added by `init` so that a `teal_slices` can be matched to the app in which it was used.+ #' |
||
31 | +101 |
- #' Used for verifying snapshots uploaded from file. See `snapshot`.+ #' |
||
32 | +102 |
- #'+ #' @inheritParams teal_data_module |
||
33 | +103 |
- #' @param x (`list`) of lists to convert to `teal_slices`+ #' @param server (`function(id, data)`) |
||
34 | +104 |
- #'+ #' `shiny` module server function; that takes `id` and `data` argument, |
||
35 | +105 |
- #' @return+ #' where the `id` is the module id and `data` is the reactive `teal_data` input. |
||
36 | +106 |
- #' A `teal_slices` object.+ #' The server function must return reactive expression containing `teal_data` object. |
||
37 | +107 |
#' |
||
38 | +108 |
- #' @seealso [`teal.slice::teal_slices`], [`teal.slice::teal_slice`], [slices_store()]+ #' The server function definition should not use `eventReactive` as it may lead to |
||
39 | +109 |
- #'+ #' unexpected behavior. |
||
40 | +110 |
- #' @examples+ #' See `vignettes("data-transform-as-shiny-module")` for more information. |
||
41 | +111 |
- #' filter <- teal_slices(+ #' @param datanames (`character`) |
||
42 | +112 |
- #' teal_slice(dataname = "iris", varname = "Species", id = "species"),+ #' Names of the datasets that are relevant for this module to evaluate. If set to `character(0)` |
||
43 | +113 |
- #' teal_slice(dataname = "iris", varname = "Sepal.Length", id = "sepal_length"),+ #' then module would receive [modules()] `datanames`. |
||
44 | +114 |
- #' teal_slice(+ #' @examples |
||
45 | +115 |
- #' dataname = "iris", id = "long_petals", title = "Long petals", expr = "Petal.Length > 5"+ #' my_transformers <- list( |
||
46 | +116 |
- #' ),+ #' teal_transform_module( |
||
47 | +117 |
- #' teal_slice(dataname = "mtcars", varname = "mpg", id = "mtcars_mpg"),+ #' label = "Custom transform for iris", |
||
48 | +118 |
- #' mapping = list(+ #' datanames = "iris", |
||
49 | +119 |
- #' module1 = c("species", "sepal_length"),+ #' ui = function(id) { |
||
50 | +120 |
- #' module2 = c("mtcars_mpg"),+ #' ns <- NS(id) |
||
51 | +121 |
- #' global_filters = "long_petals"+ #' tags$div( |
||
52 | +122 |
- #' )+ #' numericInput(ns("n_rows"), "Subset n rows", value = 6, min = 1, max = 150, step = 1) |
||
53 | +123 |
- #' )+ #' ) |
||
54 | +124 |
- #'+ #' }, |
||
55 | +125 |
- #' app <- init(+ #' server = function(id, data) { |
||
56 | +126 |
- #' data = teal_data(iris = iris, mtcars = mtcars),+ #' moduleServer(id, function(input, output, session) { |
||
57 | +127 |
- #' modules = list(+ #' reactive({ |
||
58 | +128 |
- #' module("module1"),+ #' within(data(), |
||
59 | +129 |
- #' module("module2")+ #' { |
||
60 | +130 |
- #' ),+ #' iris <- head(iris, num_rows) |
||
61 | +131 |
- #' filter = filter+ #' }, |
||
62 | +132 |
- #' )+ #' num_rows = input$n_rows |
||
63 | +133 |
- #'+ #' ) |
||
64 | +134 |
- #' if (interactive()) {+ #' }) |
||
65 | +135 |
- #' shinyApp(app$ui, app$server)+ #' }) |
||
66 | +136 |
- #' }+ #' } |
||
67 | +137 |
- #'+ #' ) |
||
68 | +138 |
- #' @export+ #' ) |
||
69 | +139 |
- teal_slices <- function(...,+ #' |
||
70 | +140 |
- exclude_varnames = NULL,+ #' @name teal_transform_module |
||
71 | +141 |
- include_varnames = NULL,+ #' |
||
72 | +142 |
- count_type = NULL,+ #' @export |
||
73 | +143 |
- allow_add = TRUE,+ teal_transform_module <- function(ui = function(id) NULL, |
||
74 | +144 |
- module_specific = FALSE,+ server = function(id, data) data, |
||
75 | +145 |
- mapping,+ label = "transform module", |
||
76 | +146 |
- app_id = NULL) {+ datanames = character(0)) { |
||
77 | -161x | +147 | +20x |
- shiny::isolate({+ checkmate::assert_function(ui, args = "id", nargs = 1) |
78 | -161x | +148 | +20x |
- checkmate::assert_flag(allow_add)+ checkmate::assert_function(server, args = c("id", "data"), nargs = 2) |
79 | -161x | +149 | +20x |
- checkmate::assert_flag(module_specific)+ checkmate::assert_string(label) |
80 | -51x | +150 | +20x |
- if (!missing(mapping)) checkmate::assert_list(mapping, types = c("character", "NULL"), names = "named")+ checkmate::assert_character(datanames) |
81 | -158x | +151 | +20x |
- checkmate::assert_string(app_id, null.ok = TRUE)+ if (identical(datanames, "all")) { |
82 | -+ | |||
152 | +1x |
-
+ stop( |
||
83 | -158x | +153 | +1x |
- slices <- list(...)+ "teal_transform_module can't have datanames property equal to 'all'. Set `datanames = character(0)` instead.", |
84 | -158x | +154 | +1x |
- all_slice_id <- vapply(slices, `[[`, character(1L), "id")+ call. = FALSE |
85 | +155 |
-
+ ) |
||
86 | -158x | +|||
156 | +
- if (missing(mapping)) {+ } |
|||
87 | -110x | +157 | +19x |
- mapping <- if (length(all_slice_id)) {+ structure( |
88 | -26x | -
- list(global_filters = all_slice_id)- |
- ||
89 | -+ | 158 | +19x |
- } else {+ list( |
90 | -84x | +159 | +19x |
- list()+ ui = ui, |
91 | -+ | |||
160 | +19x |
- }+ server = function(id, data) { |
||
92 | -+ | |||
161 | +20x |
- }+ data_out <- server(id, data) |
||
93 | +162 | |||
94 | -158x | -
- if (!module_specific) {- |
- ||
95 | -139x | -
- mapping[setdiff(names(mapping), "global_filters")] <- NULL- |
- ||
96 | -+ | 163 | +20x |
- }+ if (inherits(data_out, "reactive.event")) { |
97 | +164 |
-
+ # This warning message partially detects when `eventReactive` is used in `data_module`. |
||
98 | -158x | +165 | +1x |
- failed_slice_id <- setdiff(unlist(mapping), all_slice_id)+ warning( |
99 | -158x | +166 | +1x |
- if (length(failed_slice_id)) {+ "teal_transform_module() ", |
100 | +167 | 1x |
- stop(sprintf(+ "Using eventReactive in teal_transform module server code should be avoided as it ", |
|
101 | +168 | 1x |
- "Filters in mapping don't match any available filter.\n %s not in %s",+ "may lead to unexpected behavior. See the vignettes for more information ", |
|
102 | +169 | 1x |
- toString(failed_slice_id),+ "(`vignette(\"data-transform-as-shiny-module\", package = \"teal\")`).", |
|
103 | +170 | 1x |
- toString(all_slice_id)+ call. = FALSE |
|
104 | +171 |
- ))+ ) |
||
105 | +172 |
- }+ } |
||
106 | +173 | |||
107 | -157x | -
- tss <- teal.slice::teal_slices(- |
- ||
108 | -- |
- ...,- |
- ||
109 | -157x | +174 | +20x |
- exclude_varnames = exclude_varnames,+ decorate_err_msg( |
110 | -157x | +175 | +20x |
- include_varnames = include_varnames,+ assert_reactive(data_out), |
111 | -157x | +176 | +20x |
- count_type = count_type,+ pre = sprintf("From: 'teal_transform_module()':\nA 'teal_transform_module' with \"%s\" label:", label), |
112 | -157x | +177 | +20x |
- allow_add = allow_add+ post = "Please make sure that this module returns a 'reactive` object containing 'teal_data' class of object." # nolint: line_length_linter. |
113 | +178 |
- )+ ) |
||
114 | -157x | +|||
179 | +
- attr(tss, "mapping") <- mapping+ } |
|||
115 | -157x | +|||
180 | +
- attr(tss, "module_specific") <- module_specific+ ), |
|||
116 | -157x | +181 | +19x |
- attr(tss, "app_id") <- app_id+ label = label, |
117 | -157x | +182 | +19x |
- class(tss) <- c("modules_teal_slices", class(tss))+ datanames = datanames, |
118 | -157x | +183 | +19x |
- tss+ class = c("teal_transform_module", "teal_data_module") |
119 | +184 |
- })+ ) |
||
120 | +185 |
} |
||
121 | +186 | |||
122 | +187 | |||
123 | +188 |
- #' @rdname teal_slices+ #' Extract all `transformers` from `modules`. |
||
124 | +189 |
- #' @export+ #' |
||
125 | +190 |
- #' @keywords internal+ #' @param modules `teal_modules` or `teal_module` |
||
126 | +191 |
- #'+ #' @return A list of `teal_transform_module` nested in the same way as input `modules`. |
||
127 | +192 |
- as.teal_slices <- function(x) { # nolint: object_name.- |
- ||
128 | -13x | -
- checkmate::assert_list(x)- |
- ||
129 | -13x | -
- lapply(x, checkmate::assert_list, names = "named", .var.name = "list element")+ #' @keywords internal |
||
130 | +193 |
-
+ extract_transformers <- function(modules) {+ |
+ ||
194 | +6x | +
+ if (inherits(modules, "teal_module")) { |
||
131 | -13x | +195 | +3x |
- attrs <- attributes(unclass(x))+ modules$transformers |
132 | -13x | +196 | +3x |
- ans <- lapply(x, function(x) if (is.teal_slice(x)) x else as.teal_slice(x))+ } else if (inherits(modules, "teal_modules")) { |
133 | -13x | +197 | +3x |
- do.call(teal_slices, c(ans, attrs))+ lapply(modules$children, extract_transformers) |
134 | +198 |
- }+ } |
||
135 | +199 |
-
+ } |
136 | +1 |
-
+ .onLoad <- function(libname, pkgname) { |
|
137 | +2 |
- #' @rdname teal_slices+ # adapted from https://github.com/r-lib/devtools/blob/master/R/zzz.R |
|
138 | +3 |
- #' @export+ |
|
139 | -+ | ||
4 | +! |
- #' @keywords internal+ teal_default_options <- list( |
|
140 | -+ | ||
5 | +! |
- #'+ teal.show_js_log = FALSE, |
|
141 | -+ | ||
6 | +! |
- c.teal_slices <- function(...) {+ teal.lockfile.mode = "auto", |
|
142 | -6x | +||
7 | +! |
- x <- list(...)+ shiny.sanitize.errors = FALSE |
|
143 | -6x | +||
8 | +
- checkmate::assert_true(all(vapply(x, is.teal_slices, logical(1L))), .var.name = "all arguments are teal_slices")+ ) |
||
144 | +9 | ||
145 | -6x | +||
10 | +! |
- all_attributes <- lapply(x, attributes)+ op <- options() |
|
146 | -6x | +||
11 | +! |
- all_attributes <- coalesce_r(all_attributes)+ toset <- !(names(teal_default_options) %in% names(op)) |
|
147 | -6x | +||
12 | +! |
- all_attributes <- all_attributes[names(all_attributes) != "class"]+ if (any(toset)) options(teal_default_options[toset]) |
|
148 | +13 | ||
149 | -6x | -
- do.call(- |
- |
150 | -6x | -
- teal_slices,- |
- |
151 | -6x | +||
14 | +
- c(+ # Set up the teal logger instance |
||
152 | -6x | +||
15 | +! |
- unique(unlist(x, recursive = FALSE)),+ teal.logger::register_logger("teal") |
|
153 | -6x | +||
16 | +! |
- all_attributes+ teal.logger::register_handlers("teal") |
|
154 | +17 |
- )+ |
|
155 | -+ | ||
18 | +! |
- )+ invisible() |
|
156 | +19 |
} |
|
157 | +20 | ||
158 | +21 |
-
+ .onAttach <- function(libname, pkgname) { |
|
159 | -+ | ||
22 | +2x |
- #' Deep copy `teal_slices`+ packageStartupMessage( |
|
160 | -+ | ||
23 | +2x |
- #'+ "\nYou are using teal version ", |
|
161 | +24 |
- #' it's important to create a new copy of `teal_slices` when+ # `system.file` uses the `shim` of `system.file` by `teal` |
|
162 | +25 |
- #' starting a new `shiny` session. Otherwise, object will be shared+ # we avoid `desc` dependency here to get the version |
|
163 | -+ | ||
26 | +2x |
- #' by multiple users as it is created in global environment before+ read.dcf(system.file("DESCRIPTION", package = "teal"))[, "Version"] |
|
164 | +27 |
- #' `shiny` session starts.+ ) |
|
165 | +28 |
- #' @param filter (`teal_slices`)+ } |
|
166 | +29 |
- #' @return `teal_slices`+ |
|
167 | +30 |
- #' @keywords internal+ # This one is here because setdiff_teal_slice should not be exported from teal.slice. |
|
168 | +31 |
- deep_copy_filter <- function(filter) {- |
- |
169 | -1x | -
- checkmate::assert_class(filter, "teal_slices")+ setdiff_teal_slices <- getFromNamespace("setdiff_teal_slices", "teal.slice") |
|
170 | -1x | +||
32 | +
- shiny::isolate({+ # This one is here because it is needed by c.teal_slices but we don't want it exported from teal.slice. |
||
171 | -1x | +||
33 | +
- filter_copy <- lapply(filter, function(slice) {+ coalesce_r <- getFromNamespace("coalesce_r", "teal.slice") |
||
172 | -2x | +||
34 | +
- teal.slice::as.teal_slice(as.list(slice))+ # all *Block objects are private in teal.reporter |
||
173 | +35 |
- })+ RcodeBlock <- getFromNamespace("RcodeBlock", "teal.reporter") # nolint: object_name. |
|
174 | -1x | +||
36 | +
- attributes(filter_copy) <- attributes(filter)+ |
||
175 | -1x | +||
37 | +
- filter_copy+ # Use non-exported function(s) from teal.code |
||
176 | +38 |
- })+ # This one is here because lang2calls should not be exported from teal.code |
|
177 | +39 |
- }+ lang2calls <- getFromNamespace("lang2calls", "teal.code") |
1 |
- #' Data module for `teal` applications+ #' Store and restore `teal_slices` object |
||
3 |
- #' @description+ #' Functions that write a `teal_slices` object to a file in the `JSON` format, |
||
4 |
- #' `r lifecycle::badge("experimental")`+ #' and also restore the object from disk. |
||
6 |
- #' Create a `teal_data_module` object and evaluate code on it with history tracking.+ #' Date and date time objects are stored in the following formats: |
||
8 |
- #' @details+ #' - `Date` class is converted to the `"ISO8601"` standard (`YYYY-MM-DD`). |
||
9 |
- #' `teal_data_module` creates a `shiny` module to interactively supply or modify data in a `teal` application.+ #' - `POSIX*t` classes are converted to character by using |
||
10 |
- #' The module allows for running any code (creation _and_ some modification) after the app starts or reloads.+ #' `format.POSIX*t(usetz = TRUE, tz = "UTC")` (`YYYY-MM-DD HH:MM:SS UTC`, where |
||
11 |
- #' The body of the server function will be run in the app rather than in the global environment.+ #' `UTC` is the `Coordinated Universal Time` timezone short-code). |
||
12 |
- #' This means it will be run every time the app starts, so use sparingly.+ #' |
||
13 |
- #'+ #' This format is assumed during `slices_restore`. All `POSIX*t` objects in |
||
14 |
- #' Pass this module instead of a `teal_data` object in a call to [init()].+ #' `selected` or `choices` fields of `teal_slice` objects are always printed in |
||
15 |
- #' Note that the server function must always return a `teal_data` object wrapped in a reactive expression.+ #' `UTC` timezone as well. |
||
17 |
- #' See vignette `vignette("data-as-shiny-module", package = "teal")` for more details.+ #' @param tss (`teal_slices`) object to be stored. |
||
18 |
- #'+ #' @param file (`character(1)`) file path where `teal_slices` object will be |
||
19 |
- #' @param ui (`function(id)`)+ #' saved and restored. The file extension should be `".json"`. |
||
20 |
- #' `shiny` module UI function; must only take `id` argument+ #' |
||
21 |
- #' @param server (`function(id)`)+ #' @return `slices_store` returns `NULL`, invisibly. |
||
22 |
- #' `shiny` module server function; must only take `id` argument;+ #' |
||
23 |
- #' must return reactive expression containing `teal_data` object+ #' @seealso [teal_slices()] |
||
24 |
- #' @param label (`character(1)`) Label of the module.+ #' |
||
25 |
- #' @param once (`logical(1)`)+ #' @keywords internal |
||
26 |
- #' If `TRUE`, the data module will be shown only once and will disappear after successful data loading.+ #' |
||
27 |
- #' App user will no longer be able to interact with this module anymore.+ slices_store <- function(tss, file) { |
||
28 | -+ | 9x |
- #' If `FALSE`, the data module can be reused multiple times.+ checkmate::assert_class(tss, "teal_slices") |
29 | -+ | 9x |
- #' App user will be able to interact and change the data output from the module multiple times.+ checkmate::assert_path_for_output(file, overwrite = TRUE, extension = "json") |
30 |
- #'+ |
||
31 | -+ | 9x |
- #' @return+ cat(format(tss, trim_lines = FALSE), "\n", file = file) |
32 |
- #' `teal_data_module` returns a list of class `teal_data_module` containing two elements, `ui` and+ } |
||
33 |
- #' `server` provided via arguments.+ |
||
34 |
- #'+ #' @rdname slices_store |
||
35 |
- #' @examples+ #' @return `slices_restore` returns a `teal_slices` object restored from the file. |
||
36 |
- #' tdm <- teal_data_module(+ #' @keywords internal |
||
37 |
- #' ui = function(id) {+ slices_restore <- function(file) {+ |
+ ||
38 | +9x | +
+ checkmate::assert_file_exists(file, access = "r", extension = "json")+ |
+ |
39 | ++ | + + | +|
40 | +9x | +
+ tss_json <- jsonlite::fromJSON(file, simplifyDataFrame = FALSE)+ |
+ |
41 | +9x | +
+ tss_json$slices <-+ |
+ |
42 | +9x | +
+ lapply(tss_json$slices, function(slice) {+ |
+ |
43 | +9x | +
+ for (field in c("selected", "choices")) {+ |
+ |
44 | +18x | +
+ if (!is.null(slice[[field]])) {+ |
+ |
45 | +12x | +
+ if (length(slice[[field]]) > 0) {+ |
+ |
46 | +9x | +
+ date_partial_regex <- "^[0-9]{4}-[0-9]{2}-[0-9]{2}"+ |
+ |
47 | +9x | +
+ time_stamp_regex <- paste0(date_partial_regex, "\\s[0-9]{2}:[0-9]{2}:[0-9]{2}\\sUTC$")+ |
+ |
48 | ++ | + + | +|
49 | +9x | +
+ slice[[field]] <-+ |
+ |
50 | +9x | +
+ if (all(grepl(paste0(date_partial_regex, "$"), slice[[field]]))) {+ |
+ |
51 | +3x | +
+ as.Date(slice[[field]])+ |
+ |
52 | +9x | +
+ } else if (all(grepl(time_stamp_regex, slice[[field]]))) {+ |
+ |
53 | +3x | +
+ as.POSIXct(slice[[field]], tz = "UTC")+ |
+ |
54 | ++ |
+ } else {+ |
+ |
55 | +3x | +
+ slice[[field]]+ |
+ |
56 | ++ |
+ }+ |
+ |
57 | ++ |
+ } else {+ |
+ |
58 | +3x | +
+ slice[[field]] <- character(0) |
|
38 | +59 |
- #' ns <- NS(id)+ } |
|
39 | +60 |
- #' actionButton(ns("submit"), label = "Load data")+ } |
|
40 | +61 |
- #' },+ } |
|
41 | -+ | ||
62 | +9x |
- #' server = function(id) {+ slice |
|
42 | +63 |
- #' moduleServer(id, function(input, output, session) {+ }) |
|
43 | +64 |
- #' eventReactive(input$submit, {+ |
|
44 | -+ | ||
65 | +9x |
- #' data <- within(+ tss_elements <- lapply(tss_json$slices, as.teal_slice) |
|
45 | +66 |
- #' teal_data(),+ |
|
46 | -+ | ||
67 | +9x |
- #' {+ do.call(teal_slices, c(tss_elements, tss_json$attributes)) |
|
47 | +68 |
- #' dataset1 <- iris+ } |
48 | +1 |
- #' dataset2 <- mtcars+ #' Module to transform `reactive` `teal_data` |
|
49 | +2 |
- #' }+ #' |
|
50 | +3 |
- #' )+ #' Module calls multiple [`module_teal_data`] in sequence so that `reactive teal_data` output |
|
51 | +4 |
- #' datanames(data) <- c("dataset1", "dataset2")+ #' from one module is handed over to the following module's input. |
|
52 | +5 |
#' |
|
53 | +6 |
- #' data+ #' @inheritParams module_teal_data |
|
54 | +7 |
- #' })+ #' @inheritParams teal_modules |
|
55 | +8 |
- #' })+ #' @return `reactive` `teal_data` |
|
56 | +9 |
- #' }+ #' |
|
57 | +10 |
- #' )+ #' |
|
58 | +11 |
- #'+ #' @name module_transform_data |
|
59 | +12 |
- #' @name teal_data_module+ #' @keywords internal |
|
60 | +13 |
- #' @seealso [`teal.data::teal_data-class`], [teal.code::qenv()]+ NULL |
|
61 | +14 |
- #'+ |
|
62 | +15 |
- #' @export+ #' @rdname module_transform_data |
|
63 | +16 |
- teal_data_module <- function(ui, server, label = "data module", once = TRUE) {+ ui_transform_data <- function(id, transformers = list(), class = "well") { |
|
64 | -33x | +||
17 | +! |
- checkmate::assert_function(ui, args = "id", nargs = 1)+ checkmate::assert_string(id) |
|
65 | -32x | +||
18 | +! |
- checkmate::assert_function(server, args = "id", nargs = 1)+ checkmate::assert_list(transformers, "teal_transform_module") |
|
66 | -30x | +||
19 | +
- checkmate::assert_string(label)+ |
||
67 | -30x | +||
20 | +! |
- checkmate::assert_flag(once)+ ns <- NS(id) |
|
68 | -30x | +||
21 | +! |
- structure(+ labels <- lapply(transformers, function(x) attr(x, "label")) |
|
69 | -30x | +||
22 | +! |
- list(+ ids <- get_unique_labels(labels) |
|
70 | -30x | +||
23 | +! |
- ui = ui,+ names(transformers) <- ids |
|
71 | -30x | +||
24 | +
- server = function(id) {+ |
||
72 | -23x | +||
25 | +! |
- data_out <- server(id)+ lapply( |
|
73 | -22x | +||
26 | +! |
- decorate_err_msg(+ names(transformers), |
|
74 | -22x | +||
27 | +! |
- assert_reactive(data_out),+ function(name) { |
|
75 | -22x | +||
28 | +! |
- pre = sprintf("From: 'teal_data_module()':\nA 'teal_data_module' with \"%s\" label:", label),+ data_mod <- transformers[[name]] |
|
76 | -22x | +||
29 | +! |
- post = "Please make sure that this module returns a 'reactive` object containing 'teal_data' class of object." # nolint: line_length_linter.+ wrapper_id <- ns(sprintf("wrapper_%s", name)) |
|
77 | -+ | ||
30 | +! |
- )+ div( # todo: accordion? |
|
78 | +31 |
- }+ # class .teal_validated changes the color of the boarder on error in ui_validate_reactive_teal_data |
|
79 | +32 |
- ),+ # For details see tealValidate.js file. |
|
80 | -30x | +||
33 | +! |
- label = label,+ class = c(class, "teal_validated"), |
|
81 | -30x | +||
34 | +! |
- class = "teal_data_module",+ title = attr(data_mod, "label"), |
|
82 | -30x | +||
35 | +! |
- once = once+ tags$span( |
|
83 | -+ | ||
36 | +! |
- )+ class = "text-primary mb-4", |
|
84 | -+ | ||
37 | +! |
- }+ icon("fas fa-square-pen"), |
|
85 | -+ | ||
38 | +! |
-
+ attr(data_mod, "label") |
|
86 | +39 |
- #' Data module for `teal` transformers.+ ), |
|
87 | -+ | ||
40 | +! |
- #'+ tags$i( |
|
88 | -+ | ||
41 | +! |
- #' @description+ class = "remove pull-right fa fa-angle-down", |
|
89 | -+ | ||
42 | +! |
- #' `r lifecycle::badge("experimental")`+ style = "cursor: pointer;", |
|
90 | -+ | ||
43 | +! |
- #'+ title = "fold/expand transform panel", |
|
91 | -+ | ||
44 | +! |
- #' Create a `teal_data_module` object for custom transformation of data for pre-processing+ onclick = sprintf("togglePanelItems(this, '%s', 'fa-angle-right', 'fa-angle-down');", wrapper_id) |
|
92 | +45 |
- #' before passing the data into the module.+ ), |
|
93 | -+ | ||
46 | +! |
- #'+ div( |
|
94 | -+ | ||
47 | +! |
- #' @details+ id = wrapper_id, |
|
95 | -+ | ||
48 | +! |
- #' `teal_transform_module` creates a [`teal_data_module`] object to transform data in a `teal`+ ui_teal_data(id = ns(name), data_module = transformers[[name]]$ui) |
|
96 | +49 |
- #' application. This transformation happens after the data has passed through the filtering activity+ ) |
|
97 | +50 |
- #' in teal. The transformed data is then sent to the server of the [teal_module()].+ ) |
|
98 | +51 |
- #'+ } |
|
99 | +52 |
- #' See vignette `vignette("data-transform-as-shiny-module", package = "teal")` for more details.+ ) |
|
100 | +53 |
- #'+ } |
|
101 | +54 |
- #'+ |
|
102 | +55 |
- #' @inheritParams teal_data_module+ #' @rdname module_transform_data |
|
103 | +56 |
- #' @param server (`function(id, data)`)+ srv_transform_data <- function(id, data, transformers = list(), modules, is_transformer_failed = reactiveValues()) { |
|
104 | -+ | ||
57 | +81x |
- #' `shiny` module server function; that takes `id` and `data` argument,+ checkmate::assert_string(id) |
|
105 | -+ | ||
58 | +81x |
- #' where the `id` is the module id and `data` is the reactive `teal_data` input.+ assert_reactive(data) |
|
106 | -+ | ||
59 | +81x |
- #' The server function must return reactive expression containing `teal_data` object.+ checkmate::assert_list(transformers, "teal_transform_module") |
|
107 | -+ | ||
60 | +81x |
- #'+ checkmate::assert_class(modules, "teal_module") |
|
108 | -+ | ||
61 | +81x |
- #' The server function definition should not use `eventReactive` as it may lead to+ labels <- lapply(transformers, function(x) attr(x, "label")) |
|
109 | -+ | ||
62 | +81x |
- #' unexpected behavior.+ ids <- get_unique_labels(labels) |
|
110 | -+ | ||
63 | +81x |
- #' See `vignettes("data-transform-as-shiny-module")` for more information.+ names(transformers) <- ids |
|
111 | -+ | ||
64 | +81x |
- #' @param datanames (`character`)+ moduleServer(id, function(input, output, session) { |
|
112 | -+ | ||
65 | +81x |
- #' Names of the datasets that are relevant for this module to evaluate. If set to `character(0)`+ logger::log_debug("srv_teal_data_modules initializing.") |
|
113 | -+ | ||
66 | +81x |
- #' then module would receive [modules()] `datanames`.+ Reduce( |
|
114 | -+ | ||
67 | +81x | +
+ function(previous_result, name) {+ |
+ |
68 | +20x | +
+ srv_teal_data(+ |
+ |
69 | +20x | +
+ id = name,+ |
+ |
70 | +20x | +
+ data_module = function(id) transformers[[name]]$server(id, previous_result),+ |
+ |
71 | +20x | +
+ modules = modules,+ |
+ |
72 | +20x |
- #' @examples+ is_transformer_failed = is_transformer_failed |
|
115 | +73 |
- #' my_transformers <- list(+ ) |
|
116 | +74 |
- #' teal_transform_module(+ }, |
|
117 | -+ | ||
75 | +81x |
- #' label = "Custom transform for iris",+ x = names(transformers), |
|
118 | -+ | ||
76 | +81x |
- #' datanames = "iris",+ init = data |
|
119 | +77 |
- #' ui = function(id) {+ ) |
|
120 | +78 |
- #' ns <- NS(id)+ }) |
|
121 | +79 |
- #' tags$div(+ } |
122 | +1 |
- #' numericInput(ns("n_rows"), "Subset n rows", value = 6, min = 1, max = 150, step = 1)+ #' Filter settings for `teal` applications |
|
123 | +2 |
- #' )+ #' |
|
124 | +3 |
- #' },+ #' Specify initial filter states and filtering settings for a `teal` app. |
|
125 | +4 |
- #' server = function(id, data) {+ #' |
|
126 | +5 |
- #' moduleServer(id, function(input, output, session) {+ #' Produces a `teal_slices` object. |
|
127 | +6 |
- #' reactive({+ #' The `teal_slice` components will specify filter states that will be active when the app starts. |
|
128 | +7 |
- #' within(data(),+ #' Attributes (created with the named arguments) will configure the way the app applies filters. |
|
129 | +8 |
- #' {+ #' See argument descriptions for details. |
|
130 | +9 |
- #' iris <- head(iris, num_rows)+ #' |
|
131 | +10 |
- #' },+ #' @inheritParams teal.slice::teal_slices |
|
132 | +11 |
- #' num_rows = input$n_rows+ #' |
|
133 | +12 |
- #' )+ #' @param module_specific (`logical(1)`) optional, |
|
134 | +13 |
- #' })+ #' - `FALSE` (default) when one filter panel applied to all modules. |
|
135 | +14 |
- #' })+ #' All filters will be shared by all modules. |
|
136 | +15 |
- #' }+ #' - `TRUE` when filter panel module-specific. |
|
137 | +16 |
- #' )+ #' Modules can have different set of filters specified - see `mapping` argument. |
|
138 | +17 |
- #' )+ #' @param mapping `r lifecycle::badge("experimental")` |
|
139 | +18 |
- #'+ #' _This is a new feature. Do kindly share your opinions on |
|
140 | +19 |
- #' @name teal_transform_module+ #' [`teal`'s GitHub repository](https://github.com/insightsengineering/teal/)._ |
|
141 | +20 |
#' |
|
142 | +21 |
- #' @export+ #' (named `list`) specifies which filters will be active in which modules on app start. |
|
143 | +22 |
- teal_transform_module <- function(ui = function(id) NULL,+ #' Elements should contain character vector of `teal_slice` `id`s (see [`teal.slice::teal_slice`]). |
|
144 | +23 |
- server = function(id, data) data,+ #' Names of the list should correspond to `teal_module` `label` set in [module()] function. |
|
145 | +24 |
- label = "transform module",+ #' - `id`s listed under `"global_filters` will be active in all modules. |
|
146 | +25 |
- datanames = character(0)) {- |
- |
147 | -20x | -
- checkmate::assert_function(ui, args = "id", nargs = 1)- |
- |
148 | -20x | -
- checkmate::assert_function(server, args = c("id", "data"), nargs = 2)- |
- |
149 | -20x | -
- checkmate::assert_string(label)- |
- |
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.",- |
- |
154 | -1x | -
- call. = FALSE+ #' - If missing, all filters will be applied to all modules. |
|
155 | +26 |
- )+ #' - If empty list, all filters will be available to all modules but will start inactive. |
|
156 | +27 |
- }- |
- |
157 | -19x | -
- structure(- |
- |
158 | -19x | -
- list(- |
- |
159 | -19x | -
- ui = ui,- |
- |
160 | -19x | -
- server = function(id, data) {- |
- |
161 | -20x | -
- data_out <- server(id, data)+ #' - If `module_specific` is `FALSE`, only `global_filters` will be active on start. |
|
162 | +28 | - - | -|
163 | -20x | -
- if (inherits(data_out, "reactive.event")) {+ #' @param app_id (`character(1)`) |
|
164 | +29 |
- # This warning message partially detects when `eventReactive` is used in `data_module`.- |
- |
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 ",- |
- |
169 | -1x | -
- "(`vignette(\"data-transform-as-shiny-module\", package = \"teal\")`).",- |
- |
170 | -1x | -
- call. = FALSE+ #' For internal use only, do not set manually. |
|
171 | +30 |
- )+ #' Added by `init` so that a `teal_slices` can be matched to the app in which it was used. |
|
172 | +31 |
- }+ #' Used for verifying snapshots uploaded from file. See `snapshot`. |
|
173 | +32 |
-
+ #' |
|
174 | -20x | +||
33 | +
- decorate_err_msg(+ #' @param x (`list`) of lists to convert to `teal_slices` |
||
175 | -20x | +||
34 | +
- assert_reactive(data_out),+ #' |
||
176 | -20x | +||
35 | +
- pre = sprintf("From: 'teal_transform_module()':\nA 'teal_transform_module' with \"%s\" label:", label),+ #' @return |
||
177 | -20x | +||
36 | +
- post = "Please make sure that this module returns a 'reactive` object containing 'teal_data' class of object." # nolint: line_length_linter.+ #' A `teal_slices` object. |
||
178 | +37 |
- )+ #' |
|
179 | +38 |
- }+ #' @seealso [`teal.slice::teal_slices`], [`teal.slice::teal_slice`], [slices_store()] |
|
180 | +39 |
- ),+ #' |
|
181 | -19x | +||
40 | +
- label = label,+ #' @examples |
||
182 | -19x | +||
41 | +
- datanames = datanames,+ #' filter <- teal_slices( |
||
183 | -19x | +||
42 | +
- class = c("teal_transform_module", "teal_data_module")+ #' teal_slice(dataname = "iris", varname = "Species", id = "species"), |
||
184 | +43 |
- )+ #' teal_slice(dataname = "iris", varname = "Sepal.Length", id = "sepal_length"), |
|
185 | +44 |
- }+ #' teal_slice( |
|
186 | +45 |
-
+ #' dataname = "iris", id = "long_petals", title = "Long petals", expr = "Petal.Length > 5" |
|
187 | +46 |
-
+ #' ), |
|
188 | +47 |
- #' Extract all `transformers` from `modules`.+ #' teal_slice(dataname = "mtcars", varname = "mpg", id = "mtcars_mpg"), |
|
189 | +48 |
- #'+ #' mapping = list( |
|
190 | +49 |
- #' @param modules `teal_modules` or `teal_module`+ #' module1 = c("species", "sepal_length"), |
|
191 | +50 |
- #' @return A list of `teal_transform_module` nested in the same way as input `modules`.+ #' module2 = c("mtcars_mpg"), |
|
192 | +51 |
- #' @keywords internal+ #' global_filters = "long_petals" |
|
193 | +52 |
- extract_transformers <- function(modules) {+ #' ) |
|
194 | -6x | +||
53 | +
- if (inherits(modules, "teal_module")) {+ #' ) |
||
195 | -3x | +||
54 | +
- modules$transformers+ #' |
||
196 | -3x | +||
55 | +
- } else if (inherits(modules, "teal_modules")) {+ #' app <- init( |
||
197 | -3x | +||
56 | +
- lapply(modules$children, extract_transformers)+ #' data = teal_data(iris = iris, mtcars = mtcars), |
||
198 | +57 |
- }+ #' modules = list( |
|
199 | +58 |
- }+ #' module("module1"), |
1 | +59 |
- #' Send input validation messages to output+ #' module("module2") |
||
2 | +60 |
- #'+ #' ), |
||
3 | +61 |
- #' Captures messages from `InputValidator` objects and collates them+ #' filter = filter |
||
4 | +62 |
- #' into one message passed to `validate`.+ #' ) |
||
5 | +63 |
#' |
||
6 | +64 |
- #' `shiny::validate` is used to withhold rendering of an output element until+ #' if (interactive()) { |
||
7 | +65 |
- #' certain conditions are met and to print a validation message in place+ #' shinyApp(app$ui, app$server) |
||
8 | +66 |
- #' of the output element.+ #' } |
||
9 | +67 |
- #' `shinyvalidate::InputValidator` allows to validate input elements+ #' |
||
10 | +68 |
- #' and to display specific messages in their respective input widgets.+ #' @export |
||
11 | +69 |
- #' `validate_inputs` provides a hybrid solution.+ teal_slices <- function(..., |
||
12 | +70 |
- #' Given an `InputValidator` object, messages corresponding to inputs that fail validation+ exclude_varnames = NULL, |
||
13 | +71 |
- #' are extracted and placed in one validation message that is passed to a `validate`/`need` call.+ include_varnames = NULL, |
||
14 | +72 |
- #' This way the input `validator` messages are repeated in the output.+ count_type = NULL, |
||
15 | +73 |
- #'+ allow_add = TRUE, |
||
16 | +74 |
- #' The `...` argument accepts any number of `InputValidator` objects+ module_specific = FALSE, |
||
17 | +75 |
- #' or a nested list of such objects.+ mapping, |
||
18 | +76 |
- #' If `validators` are passed directly, all their messages are printed together+ app_id = NULL) { |
||
19 | -+ | |||
77 | +161x |
- #' under one (optional) header message specified by `header`. If a list is passed,+ shiny::isolate({ |
||
20 | -+ | |||
78 | +161x |
- #' messages are grouped by `validator`. The list's names are used as headers+ checkmate::assert_flag(allow_add) |
||
21 | -+ | |||
79 | +161x |
- #' for their respective message groups.+ checkmate::assert_flag(module_specific) |
||
22 | -+ | |||
80 | +51x |
- #' If neither of the nested list elements is named, a header message is taken from `header`.+ if (!missing(mapping)) checkmate::assert_list(mapping, types = c("character", "NULL"), names = "named") |
||
23 | -+ | |||
81 | +158x |
- #'+ checkmate::assert_string(app_id, null.ok = TRUE) |
||
24 | +82 |
- #' @param ... either any number of `InputValidator` objects+ |
||
25 | -+ | |||
83 | +158x |
- #' or an optionally named, possibly nested `list` of `InputValidator`+ slices <- list(...) |
||
26 | -+ | |||
84 | +158x |
- #' objects, see `Details`+ all_slice_id <- vapply(slices, `[[`, character(1L), "id") |
||
27 | +85 |
- #' @param header (`character(1)`) generic validation message; set to NULL to omit+ |
||
28 | -+ | |||
86 | +158x |
- #'+ if (missing(mapping)) { |
||
29 | -+ | |||
87 | +110x |
- #' @return+ mapping <- if (length(all_slice_id)) { |
||
30 | -+ | |||
88 | +26x |
- #' Returns NULL if the final validation call passes and a `shiny.silent.error` if it fails.+ list(global_filters = all_slice_id) |
||
31 | +89 |
- #'+ } else { |
||
32 | -+ | |||
90 | +84x |
- #' @seealso [`shinyvalidate::InputValidator`], [`shiny::validate`]+ list() |
||
33 | +91 |
- #'+ } |
||
34 | +92 |
- #' @examplesIf require("shinyvalidate")+ } |
||
35 | +93 |
- #' library(shiny)+ |
||
36 | -+ | |||
94 | +158x |
- #' library(shinyvalidate)+ if (!module_specific) { |
||
37 | -+ | |||
95 | +139x |
- #'+ mapping[setdiff(names(mapping), "global_filters")] <- NULL |
||
38 | +96 |
- #' ui <- fluidPage(+ } |
||
39 | +97 |
- #' selectInput("method", "validation method", c("sequential", "combined", "grouped")),+ |
||
40 | -+ | |||
98 | +158x |
- #' sidebarLayout(+ failed_slice_id <- setdiff(unlist(mapping), all_slice_id) |
||
41 | -+ | |||
99 | +158x |
- #' sidebarPanel(+ if (length(failed_slice_id)) { |
||
42 | -+ | |||
100 | +1x |
- #' selectInput("letter", "select a letter:", c(letters[1:3], LETTERS[4:6])),+ stop(sprintf( |
||
43 | -+ | |||
101 | +1x |
- #' selectInput("number", "select a number:", 1:6),+ "Filters in mapping don't match any available filter.\n %s not in %s", |
||
44 | -+ | |||
102 | +1x |
- #' tags$br(),+ toString(failed_slice_id), |
||
45 | -+ | |||
103 | +1x |
- #' selectInput("color", "select a color:",+ toString(all_slice_id) |
||
46 | +104 |
- #' c("black", "indianred2", "springgreen2", "cornflowerblue"),+ )) |
||
47 | +105 |
- #' multiple = TRUE+ } |
||
48 | +106 |
- #' ),+ |
||
49 | -+ | |||
107 | +157x |
- #' sliderInput("size", "select point size:",+ tss <- teal.slice::teal_slices( |
||
50 | +108 |
- #' min = 0.1, max = 4, value = 0.25+ ..., |
||
51 | -+ | |||
109 | +157x |
- #' )+ exclude_varnames = exclude_varnames, |
||
52 | -+ | |||
110 | +157x |
- #' ),+ include_varnames = include_varnames, |
||
53 | -+ | |||
111 | +157x |
- #' mainPanel(plotOutput("plot"))+ count_type = count_type, |
||
54 | -+ | |||
112 | +157x |
- #' )+ allow_add = allow_add |
||
55 | +113 |
- #' )+ ) |
||
56 | -+ | |||
114 | +157x |
- #'+ attr(tss, "mapping") <- mapping |
||
57 | -+ | |||
115 | +157x |
- #' server <- function(input, output) {+ attr(tss, "module_specific") <- module_specific |
||
58 | -+ | |||
116 | +157x |
- #' # set up input validation+ attr(tss, "app_id") <- app_id |
||
59 | -+ | |||
117 | +157x |
- #' iv <- InputValidator$new()+ class(tss) <- c("modules_teal_slices", class(tss)) |
||
60 | -+ | |||
118 | +157x |
- #' iv$add_rule("letter", sv_in_set(LETTERS, "choose a capital letter"))+ tss |
||
61 | +119 |
- #' iv$add_rule("number", function(x) {+ }) |
||
62 | +120 |
- #' if (as.integer(x) %% 2L == 1L) "choose an even number"+ } |
||
63 | +121 |
- #' })+ |
||
64 | +122 |
- #' iv$enable()+ |
||
65 | +123 |
- #' # more input validation+ #' @rdname teal_slices |
||
66 | +124 |
- #' iv_par <- InputValidator$new()+ #' @export |
||
67 | +125 |
- #' iv_par$add_rule("color", sv_required(message = "choose a color"))+ #' @keywords internal |
||
68 | +126 |
- #' iv_par$add_rule("color", function(x) {+ #' |
||
69 | +127 |
- #' if (length(x) > 1L) "choose only one color"+ as.teal_slices <- function(x) { # nolint: object_name. |
||
70 | -+ | |||
128 | +13x |
- #' })+ checkmate::assert_list(x) |
||
71 | -+ | |||
129 | +13x |
- #' iv_par$add_rule(+ lapply(x, checkmate::assert_list, names = "named", .var.name = "list element") |
||
72 | +130 |
- #' "size",+ |
||
73 | -+ | |||
131 | +13x |
- #' sv_between(+ attrs <- attributes(unclass(x)) |
||
74 | -+ | |||
132 | +13x |
- #' left = 0.5, right = 3,+ ans <- lapply(x, function(x) if (is.teal_slice(x)) x else as.teal_slice(x)) |
||
75 | -+ | |||
133 | +13x |
- #' message_fmt = "choose a value between {left} and {right}"+ do.call(teal_slices, c(ans, attrs)) |
||
76 | +134 |
- #' )+ } |
||
77 | +135 |
- #' )+ |
||
78 | +136 |
- #' iv_par$enable()+ |
||
79 | +137 |
- #'+ #' @rdname teal_slices |
||
80 | +138 |
- #' output$plot <- renderPlot({+ #' @export |
||
81 | +139 |
- #' # validate output+ #' @keywords internal |
||
82 | +140 |
- #' switch(input[["method"]],+ #' |
||
83 | +141 |
- #' "sequential" = {+ c.teal_slices <- function(...) { |
||
84 | -+ | |||
142 | +6x |
- #' validate_inputs(iv)+ x <- list(...) |
||
85 | -+ | |||
143 | +6x |
- #' validate_inputs(iv_par, header = "Set proper graphical parameters")+ checkmate::assert_true(all(vapply(x, is.teal_slices, logical(1L))), .var.name = "all arguments are teal_slices") |
||
86 | +144 |
- #' },+ |
||
87 | -+ | |||
145 | +6x |
- #' "combined" = validate_inputs(iv, iv_par),+ all_attributes <- lapply(x, attributes) |
||
88 | -+ | |||
146 | +6x |
- #' "grouped" = validate_inputs(list(+ all_attributes <- coalesce_r(all_attributes) |
||
89 | -+ | |||
147 | +6x |
- #' "Some inputs require attention" = iv,+ all_attributes <- all_attributes[names(all_attributes) != "class"] |
||
90 | +148 |
- #' "Set proper graphical parameters" = iv_par+ |
||
91 | -+ | |||
149 | +6x |
- #' ))+ do.call( |
||
92 | -+ | |||
150 | +6x |
- #' )+ teal_slices, |
||
93 | -+ | |||
151 | +6x |
- #'+ c( |
||
94 | -+ | |||
152 | +6x |
- #' plot(faithful$eruptions ~ faithful$waiting,+ unique(unlist(x, recursive = FALSE)), |
||
95 | -+ | |||
153 | +6x |
- #' las = 1, pch = 16,+ all_attributes |
||
96 | +154 |
- #' col = input[["color"]], cex = input[["size"]]+ ) |
||
97 | +155 |
- #' )+ ) |
||
98 | +156 |
- #' })+ } |
||
99 | +157 |
- #' }+ |
||
100 | +158 |
- #'+ |
||
101 | +159 |
- #' if (interactive()) {+ #' Deep copy `teal_slices` |
||
102 | +160 |
- #' shinyApp(ui, server)+ #' |
||
103 | +161 |
- #' }+ #' it's important to create a new copy of `teal_slices` when |
||
104 | +162 |
- #'+ #' starting a new `shiny` session. Otherwise, object will be shared |
||
105 | +163 |
- #' @export+ #' by multiple users as it is created in global environment before |
||
106 | +164 |
- #'+ #' `shiny` session starts. |
||
107 | +165 |
- validate_inputs <- function(..., header = "Some inputs require attention") {+ #' @param filter (`teal_slices`) |
||
108 | -36x | +|||
166 | +
- dots <- list(...)+ #' @return `teal_slices` |
|||
109 | -2x | +|||
167 | +
- if (!is_validators(dots)) stop("validate_inputs accepts validators or a list thereof")+ #' @keywords internal |
|||
110 | +168 |
-
+ deep_copy_filter <- function(filter) { |
||
111 | -34x | +169 | +1x |
- messages <- extract_validator(dots, header)+ checkmate::assert_class(filter, "teal_slices") |
112 | -34x | +170 | +1x |
- failings <- if (!any_names(dots)) {+ shiny::isolate({ |
113 | -29x | -
- add_header(messages, header)- |
- ||
114 | -+ | 171 | +1x |
- } else {+ filter_copy <- lapply(filter, function(slice) { |
115 | -5x | +172 | +2x |
- unlist(messages)+ teal.slice::as.teal_slice(as.list(slice)) |
116 | +173 |
- }+ }) |
||
117 | -+ | |||
174 | +1x |
-
+ attributes(filter_copy) <- attributes(filter) |
||
118 | -34x | +175 | +1x |
- shiny::validate(shiny::need(is.null(failings), failings))+ filter_copy |
119 | +176 |
- }+ }) |
||
120 | +177 |
-
+ } |
121 | +1 |
- ### internal functions+ #' `teal_data` utils |
||
122 | +2 |
-
+ #' |
||
123 | +3 |
- #' @noRd+ #' In `teal` we need to recreate the `teal_data` object due to two operations: |
||
124 | +4 |
- #' @keywords internal+ #' - we need to append filter-data code and objects which have been evaluated in `FilteredData` and |
||
125 | +5 |
- # recursive object type test+ #' we want to avoid double-evaluation. |
||
126 | +6 |
- # returns logical of length 1+ #' - we need to subset `teal_data` to `datanames` used by the module, to shorten obtainable R-code |
||
127 | +7 |
- is_validators <- function(x) {- |
- ||
128 | -118x | -
- all(if (is.list(x)) unlist(lapply(x, is_validators)) else inherits(x, "InputValidator"))+ #' |
||
129 | +8 |
- }+ #' Due to above recreation of `teal_data` object can't be done simply by using public |
||
130 | +9 |
-
+ #' `teal.code` and `teal.data` methods. |
||
131 | +10 |
- #' @noRd+ #' |
||
132 | +11 |
- #' @keywords internal+ #' @param data (`teal_data`) |
||
133 | +12 |
- # test if an InputValidator object is enabled+ #' @param code (`character`) code to append to `data@code` |
||
134 | +13 |
- # returns logical of length 1+ #' @param objects (`list`) objects to append to `data@env` |
||
135 | +14 |
- # official method requested at https://github.com/rstudio/shinyvalidate/issues/64+ #' @param datanames (`character`) names of the datasets |
||
136 | +15 |
- validator_enabled <- function(x) {- |
- ||
137 | -49x | -
- x$.__enclos_env__$private$enabled+ #' @return modified `teal_data` |
||
138 | +16 |
- }+ #' @keywords internal |
||
139 | +17 |
-
+ #' @name teal_data_utilities |
||
140 | +18 |
- #' Recursively extract messages from validator list+ NULL |
||
141 | +19 |
- #' @return A character vector or a list of character vectors, possibly nested and named.+ |
||
142 | +20 |
- #' @noRd+ #' @rdname teal_data_utilities |
||
143 | +21 |
- #' @keywords internal+ .append_evaluated_code <- function(data, code) { |
||
144 | -+ | |||
22 | +84x |
- extract_validator <- function(iv, header) {+ checkmate::assert_class(data, "teal_data") |
||
145 | -113x | +23 | +84x |
- if (inherits(iv, "InputValidator")) {+ data@code <- c(data@code, code) |
146 | -49x | +24 | +84x |
- add_header(gather_messages(iv), header)+ data@id <- c(data@id, max(data@id) + 1L + seq_along(code)) |
147 | -+ | |||
25 | +84x |
- } else {+ data@messages <- c(data@messages, rep("", length(code))) |
||
148 | -58x | +26 | +84x |
- if (is.null(names(iv))) names(iv) <- rep("", length(iv))+ data@warnings <- c(data@warnings, rep("", length(code))) |
149 | -64x | +27 | +84x |
- mapply(extract_validator, iv = iv, header = names(iv), SIMPLIFY = FALSE)+ methods::validObject(data) |
150 | -+ | |||
28 | +84x |
- }+ data |
||
151 | +29 |
} |
||
152 | +30 | |||
153 | -- |
- #' Collate failing messages from validator.- |
- ||
154 | -- |
- #' @return `list`- |
- ||
155 | -- |
- #' @noRd- |
- ||
156 | +31 |
- #' @keywords internal+ #' @rdname teal_data_utilities |
||
157 | +32 |
- gather_messages <- function(iv) {+ .append_modified_data <- function(data, objects) { |
||
158 | -49x | +33 | +84x |
- if (validator_enabled(iv)) {+ checkmate::assert_class(data, "teal_data") |
159 | -46x | +34 | +84x |
- status <- iv$validate()+ checkmate::assert_class(objects, "list") |
160 | -46x | +35 | +84x |
- failing_inputs <- Filter(Negate(is.null), status)+ new_env <- list2env(objects, parent = .GlobalEnv) |
161 | -46x | -
- unique(lapply(failing_inputs, function(x) x[["message"]]))- |
- ||
162 | -+ | 36 | +84x |
- } else {+ rlang::env_coalesce(new_env, teal.code::get_env(data)) |
163 | -3x | +37 | +84x |
- warning("Validator is disabled and will be omitted.")+ data@env <- new_env |
164 | -3x | -
- list()- |
- ||
165 | -+ | 38 | +84x |
- }+ data |
166 | +39 |
} |
||
167 | +40 | |||
168 | -- |
- #' Add optional header to failing messages- |
- ||
169 | +41 |
- #' @noRd+ #' @rdname teal_data_utilities |
||
170 | +42 |
- #' @keywords internal+ .subset_teal_data <- function(data, datanames) { |
||
171 | -+ | |||
43 | +83x |
- add_header <- function(messages, header = "") {+ checkmate::assert_class(data, "teal_data") |
||
172 | -78x | +44 | +83x |
- ans <- unlist(messages)+ checkmate::assert_class(datanames, "character") |
173 | -78x | +45 | +83x |
- if (length(ans) != 0L && isTRUE(nchar(header) > 0L)) {+ datanames_corrected <- intersect(datanames, ls(teal.code::get_env(data))) |
174 | -31x | +46 | +83x |
- ans <- c(paste0(header, "\n"), ans, "\n")+ datanames_corrected_with_raw <- c(datanames_corrected, ".raw_data") |
175 | -+ | |||
47 | +83x |
- }+ if (!length(datanames_corrected)) { |
||
176 | -78x | +48 | +2x |
- ans+ return(teal_data()) |
177 | +49 |
- }+ } |
||
178 | +50 | |||
179 | -+ | |||
51 | +81x |
- #' Recursively check if the object contains a named list+ new_data <- do.call( |
||
180 | -+ | |||
52 | +81x |
- #' @noRd+ teal.data::teal_data, |
||
181 | -+ | |||
53 | +81x |
- #' @keywords internal+ args = c( |
||
182 | -+ | |||
54 | +81x |
- any_names <- function(x) {+ mget(x = datanames_corrected_with_raw, envir = teal.code::get_env(data)), |
||
183 | -103x | +55 | +81x |
- any(+ list( |
184 | -103x | +56 | +81x |
- if (is.list(x)) {+ code = teal.code::get_code(data, names = datanames_corrected_with_raw), |
185 | -58x | +57 | +81x |
- if (!is.null(names(x)) && any(names(x) != "")) TRUE else unlist(lapply(x, any_names))+ join_keys = teal.data::join_keys(data)[datanames_corrected] |
186 | +58 |
- } else {- |
- ||
187 | -40x | -
- FALSE+ ) |
||
188 | +59 |
- }+ ) |
||
189 | +60 |
) |
||
61 | +81x | +
+ new_data@verified <- data@verified+ |
+ ||
62 | +81x | +
+ teal.data::datanames(new_data) <- datanames_corrected+ |
+ ||
63 | +81x | +
+ new_data+ |
+ ||
190 | +64 |
}@@ -45772,77 +47347,77 @@ teal coverage - 59.99% |
1 |
- #' Evaluate expression on `teal_data_module`+ setOldClass("teal_data_module") |
|||
2 |
- #'+ |
|||
3 |
- #' @details+ #' Evaluate code on `teal_data_module` |
|||
4 |
- #' `within` is a convenience function for evaluating inline code inside the environment of a `teal_data_module`.+ #' |
|||
5 |
- #' It accepts only inline expressions (both simple and compound) and allows for injecting values into `expr` through+ #' @details |
|||
6 |
- #' the `...` argument: as `name:value` pairs are passed to `...`, `name` in `expr` will be replaced with `value.`+ #' `eval_code` evaluates given code in the environment of the `teal_data` object created by the `teal_data_module`. |
|||
7 |
- #'+ #' The code is added to the `@code` slot of the `teal_data`. |
|||
8 |
- #' @param data (`teal_data_module`) object+ #' |
|||
9 |
- #' @param expr (`expression`) to evaluate. Must be inline code. See+ #' @param object (`teal_data_module`) |
|||
10 |
- #' @param ... See `Details`.+ #' @inheritParams teal.code::eval_code |
|||
13 |
- #' `within` returns a `teal_data_module` object with a delayed evaluation of `expr` when the module is run.+ #' `eval_code` returns a `teal_data_module` object with a delayed evaluation of `code` when the module is run. |
|||
16 |
- #' within(tdm, dataset1 <- subset(dataset1, Species == "virginica"))+ #' eval_code(tdm, "dataset1 <- subset(dataset1, Species == 'virginica')") |
|||
18 |
- #' # use additional parameter for expression value substitution.+ #' @include teal_data_module.R |
|||
19 |
- #' valid_species <- "versicolor"+ #' @name eval_code |
|||
20 |
- #' within(tdm, dataset1 <- subset(dataset1, Species %in% species), species = valid_species)+ #' @rdname teal_data_module |
|||
21 |
- #' @include teal_data_module.R+ #' @aliases eval_code,teal_data_module,character-method |
|||
22 |
- #' @name within+ #' @aliases eval_code,teal_data_module,language-method |
|||
23 |
- #' @rdname teal_data_module+ #' @aliases eval_code,teal_data_module,expression-method |
|||
25 |
- #' @export+ #' @importFrom methods setMethod |
|||
26 |
- #'+ #' @importMethodsFrom teal.code eval_code |
|||
27 |
- within.teal_data_module <- function(data, expr, ...) {+ #' |
|||
28 | -2x | +
- expr <- substitute(expr)+ setMethod("eval_code", signature = c("teal_data_module", "character"), function(object, code) { |
||
29 | -2x | +9x |
- extras <- list(...)+ teal_data_module( |
|
30 | +9x | +
+ ui = function(id) {+ |
+ ||
31 | +1x | +
+ ns <- NS(id)+ |
+ ||
32 | +1x | +
+ object$ui(ns("mutate_inner"))+ |
+ ||
33 |
-
+ },+ |
+ |||
34 | +9x | +
+ server = function(id) {+ |
+ ||
35 | +7x | +
+ moduleServer(id, function(input, output, session) {+ |
+ ||
36 | +7x | +
+ teal_data_rv <- object$server("mutate_inner")+ |
+ ||
37 | +6x | +
+ td <- eventReactive(teal_data_rv(), |
||
31 | +38 |
- # Add braces for consistency.+ { |
||
32 | -2x | +39 | +6x |
- if (!identical(as.list(expr)[[1L]], as.symbol("{"))) {+ if (inherits(teal_data_rv(), c("teal_data", "qenv.error"))) { |
33 | +40 | +4x | +
+ eval_code(teal_data_rv(), code)+ |
+ |
41 | ++ |
+ } else {+ |
+ ||
42 | 2x |
- expr <- call("{", expr)+ teal_data_rv() |
||
34 | +43 |
- }+ } |
||
35 | +44 |
-
+ }, |
||
36 | -2x | +45 | +6x |
- calls <- as.list(expr)[-1]+ ignoreNULL = FALSE |
37 | +46 | ++ |
+ )+ |
+ |
47 | +6x | +
+ td+ |
+ ||
48 | ++ |
+ })+ |
+ ||
49 | ++ |
+ }+ |
+ ||
50 | ++ |
+ )+ |
+ ||
51 | ++ |
+ })+ |
+ ||
52 | ||||
38 | +53 |
- # Inject extra values into expressions.+ setMethod("eval_code", signature = c("teal_data_module", "language"), function(object, code) { |
||
39 | -2x | +54 | +1x |
- calls <- lapply(calls, function(x) do.call(substitute, list(x, env = extras)))+ eval_code(object, code = paste(lang2calls(code), collapse = "\n")) |
40 | +55 | ++ |
+ })+ |
+ |
56 | ||||
57 | ++ |
+ setMethod("eval_code", signature = c("teal_data_module", "expression"), function(object, code) {+ |
+ ||
41 | +58 | 2x |
- eval_code(object = data, code = as.expression(calls))+ eval_code(object, code = paste(lang2calls(code), collapse = "\n")) |
|
42 | +59 |
- }+ }) |
1 |
- #' Show `R` code modal+ #' Evaluate expression on `teal_data_module` |
||
3 |
- #' @description `r lifecycle::badge("deprecated")`+ #' @details |
||
4 |
- #'+ #' `within` is a convenience function for evaluating inline code inside the environment of a `teal_data_module`. |
||
5 |
- #' Use the [shiny::showModal()] function to show the `R` code inside.+ #' It accepts only inline expressions (both simple and compound) and allows for injecting values into `expr` through |
||
6 |
- #'+ #' the `...` argument: as `name:value` pairs are passed to `...`, `name` in `expr` will be replaced with `value.` |
||
7 |
- #' @param title (`character(1)`)+ #' |
||
8 |
- #' Title of the modal, displayed in the first comment of the `R` code.+ #' @param data (`teal_data_module`) object |
||
9 |
- #' @param rcode (`character`)+ #' @param expr (`expression`) to evaluate. Must be inline code. See |
||
10 |
- #' vector with `R` code to show inside the modal.+ #' @param ... See `Details`. |
||
11 |
- #' @param session (`ShinySession`) optional+ #' |
||
12 |
- #' `shiny` session object, defaults to [shiny::getDefaultReactiveDomain()].+ #' @return |
||
13 |
- #'+ #' `within` returns a `teal_data_module` object with a delayed evaluation of `expr` when the module is run. |
||
14 |
- #' @references [shiny::showModal()]+ #' |
||
15 |
- #' @export+ #' @examples |
||
16 |
- show_rcode_modal <- function(title = NULL, rcode, session = getDefaultReactiveDomain()) {+ #' within(tdm, dataset1 <- subset(dataset1, Species == "virginica")) |
||
17 | -! | +
- lifecycle::deprecate_soft(+ #' |
|
18 | -! | +
- when = "0.16",+ #' # use additional parameter for expression value substitution. |
|
19 | -! | +
- what = "show_rcode_modal()",+ #' valid_species <- "versicolor" |
|
20 | -! | +
- details = "This function will be removed in the next release."+ #' within(tdm, dataset1 <- subset(dataset1, Species %in% species), species = valid_species) |
|
21 |
- )+ #' @include teal_data_module.R |
||
22 |
-
+ #' @name within |
||
23 | -! | +
- rcode <- paste(rcode, collapse = "\n")+ #' @rdname teal_data_module |
|
24 |
-
+ #' |
||
25 | -! | +
- ns <- session$ns+ #' @export |
|
26 | -! | +
- showModal(modalDialog(+ #' |
|
27 | -! | +
- tagList(+ within.teal_data_module <- function(data, expr, ...) { |
|
28 | -! | +2x |
- tags$div(+ expr <- substitute(expr) |
29 | -! | +2x |
- actionButton(ns("copyRCode"), "Copy to Clipboard", `data-clipboard-target` = paste0("#", ns("r_code"))),+ extras <- list(...) |
30 | -! | +
- modalButton("Dismiss"),+ |
|
31 | -! | +
- style = "mb-4"+ # Add braces for consistency. |
|
32 | -+ | 2x |
- ),+ if (!identical(as.list(expr)[[1L]], as.symbol("{"))) { |
33 | -! | +2x |
- tags$div(tags$pre(id = ns("r_code"), rcode)),+ expr <- call("{", expr) |
34 |
- ),+ } |
||
35 | -! | +
- title = title,+ |
|
36 | -! | +2x |
- footer = tagList(+ calls <- as.list(expr)[-1] |
37 | -! | +
- actionButton(ns("copyRCode"), "Copy to Clipboard", `data-clipboard-target` = paste0("#", ns("r_code"))),+ |
|
38 | -! | +
- modalButton("Dismiss")+ # Inject extra values into expressions. |
|
39 | -+ | 2x |
- ),+ calls <- lapply(calls, function(x) do.call(substitute, list(x, env = extras))) |
40 | -! | +
- size = "l",+ |
|
41 | -! | +2x |
- easyClose = TRUE+ eval_code(object = data, code = as.expression(calls)) |
42 | - |
- ))- |
- |
43 | -
} |
@@ -46658,293 +48345,363 @@
1 |
- .onLoad <- function(libname, pkgname) {+ #' Check that argument is reactive. |
||
2 |
- # adapted from https://github.com/r-lib/devtools/blob/master/R/zzz.R+ #' |
||
3 |
-
+ #' @inherit checkmate::check_class params return |
||
4 | -! | +
- teal_default_options <- list(+ #' |
|
5 | -! | +
- teal.show_js_log = FALSE,+ #' @keywords internal |
|
6 | -! | +
- teal.lockfile.mode = "auto",+ check_reactive <- function(x, null.ok = FALSE) { # nolint: object_name_linter. |
|
7 | -! | +990x |
- shiny.sanitize.errors = FALSE+ if (!isTRUE(checkmate::test_class(x, classes = "reactive", null.ok = null.ok))) { |
8 | -+ | 4x |
- )+ cl <- class(x) |
9 | -+ | 4x |
-
+ return(sprintf( |
10 | -! | +4x |
- op <- options()+ "Must be a reactive (i.e. inherit from 'reactive' class) but has class%s '%s'", |
11 | -! | +4x |
- toset <- !(names(teal_default_options) %in% names(op))+ if (length(cl) > 1L) "es" else "", |
12 | -! | +4x |
- if (any(toset)) options(teal_default_options[toset])+ paste0(cl, collapse = "','") |
13 |
-
+ )) |
||
14 |
- # Set up the teal logger instance+ } |
||
15 | -! | +986x |
- teal.logger::register_logger("teal")+ return(TRUE) |
16 | -! | +
- teal.logger::register_handlers("teal")+ } |
|
17 |
-
+ #' @rdname check_reactive |
||
18 | -! | +
- invisible()+ test_reactive <- function(x, null.ok = FALSE) { # nolint: object_name_linter. |
|
19 | -+ | 30x |
- }+ isTRUE(check_reactive(x, null.ok = null.ok)) |
20 |
-
+ } |
||
21 |
- .onAttach <- function(libname, pkgname) {+ #' @rdname check_reactive |
||
22 | -2x | +
- packageStartupMessage(+ assert_reactive <- checkmate::makeAssertionFunction(check_reactive) |
|
23 | -2x | +
- "\nYou are using teal version ",+ |
|
24 |
- # `system.file` uses the `shim` of `system.file` by `teal`+ #' Capture error and decorate error message. |
||
25 |
- # we avoid `desc` dependency here to get the version+ #' |
||
26 | -2x | +
- read.dcf(system.file("DESCRIPTION", package = "teal"))[, "Version"]+ #' @param x object to evaluate |
|
27 |
- )+ #' @param pre (`character(1)`) A string to prepend to error message |
||
28 |
- }+ #' @param post (`character(1)`) A string to append to error message |
||
29 |
-
+ #' |
||
30 |
- # This one is here because setdiff_teal_slice should not be exported from teal.slice.+ #' @return `x` if no error, otherwise throws error with decorated message |
||
31 |
- setdiff_teal_slices <- getFromNamespace("setdiff_teal_slices", "teal.slice")+ #' |
||
32 |
- # This one is here because it is needed by c.teal_slices but we don't want it exported from teal.slice.+ #' @keywords internal |
||
33 |
- coalesce_r <- getFromNamespace("coalesce_r", "teal.slice")+ decorate_err_msg <- function(x, pre = character(0), post = character(0)) { |
||
34 | -+ | 41x |
- # all *Block objects are private in teal.reporter+ tryCatch( |
35 | -+ | 41x |
- RcodeBlock <- getFromNamespace("RcodeBlock", "teal.reporter") # nolint: object_name.+ x, |
36 | +41x | +
+ error = function(e) {+ |
+ |
37 | +2x | +
+ stop(+ |
+ |
38 | +2x | +
+ "\n",+ |
+ |
39 | +2x | +
+ pre,+ |
+ |
40 | +2x | +
+ "\n",+ |
+ |
41 | +2x | +
+ e$message,+ |
+ |
42 | +2x | +
+ "\n",+ |
+ |
43 | +2x | +
+ post,+ |
+ |
44 | +2x | +
+ call. = FALSE+ |
+ |
45 |
-
+ ) |
||
37 | +46 |
- # Use non-exported function(s) from teal.code+ } |
|
38 | +47 |
- # This one is here because lang2calls should not be exported from teal.code+ )+ |
+ |
48 | +39x | +
+ x |
|
39 | +49 |
- lang2calls <- getFromNamespace("lang2calls", "teal.code")+ } |
1 |
- #' Check that argument is reactive.+ #' Show `R` code modal |
||
3 |
- #' @inherit checkmate::check_class params return+ #' @description `r lifecycle::badge("deprecated")` |
||
5 |
- #' @keywords internal+ #' Use the [shiny::showModal()] function to show the `R` code inside. |
||
6 |
- check_reactive <- function(x, null.ok = FALSE) { # nolint: object_name_linter.+ #' |
||
7 | -990x | +
- if (!isTRUE(checkmate::test_class(x, classes = "reactive", null.ok = null.ok))) {+ #' @param title (`character(1)`) |
|
8 | -4x | +
- cl <- class(x)+ #' Title of the modal, displayed in the first comment of the `R` code. |
|
9 | -4x | +
- return(sprintf(+ #' @param rcode (`character`) |
|
10 | -4x | +
- "Must be a reactive (i.e. inherit from 'reactive' class) but has class%s '%s'",+ #' vector with `R` code to show inside the modal. |
|
11 | -4x | +
- if (length(cl) > 1L) "es" else "",+ #' @param session (`ShinySession`) optional |
|
12 | -4x | +
- paste0(cl, collapse = "','")+ #' `shiny` session object, defaults to [shiny::getDefaultReactiveDomain()]. |
|
13 |
- ))+ #' |
||
14 |
- }+ #' @references [shiny::showModal()] |
||
15 | -986x | +
- return(TRUE)+ #' @export |
|
16 |
- }+ show_rcode_modal <- function(title = NULL, rcode, session = getDefaultReactiveDomain()) { |
||
17 | -+ | ! |
- #' @rdname check_reactive+ lifecycle::deprecate_soft( |
18 | -+ | ! |
- test_reactive <- function(x, null.ok = FALSE) { # nolint: object_name_linter.+ when = "0.16", |
19 | -30x | +! |
- isTRUE(check_reactive(x, null.ok = null.ok))+ what = "show_rcode_modal()", |
20 | -+ | ! |
- }+ details = "This function will be removed in the next release." |
21 |
- #' @rdname check_reactive+ ) |
||
22 |
- assert_reactive <- checkmate::makeAssertionFunction(check_reactive)+ |
||
23 | -+ | ! |
-
+ rcode <- paste(rcode, collapse = "\n") |
24 |
- #' Capture error and decorate error message.+ |
||
25 | -+ | ! |
- #'+ ns <- session$ns |
26 | -+ | ! |
- #' @param x object to evaluate+ showModal(modalDialog( |
27 | -+ | ! |
- #' @param pre (`character(1)`) A string to prepend to error message+ tagList( |
28 | -+ | ! |
- #' @param post (`character(1)`) A string to append to error message+ tags$div( |
29 | -+ | ! |
- #'+ actionButton(ns("copyRCode"), "Copy to Clipboard", `data-clipboard-target` = paste0("#", ns("r_code"))), |
30 | -+ | ! |
- #' @return `x` if no error, otherwise throws error with decorated message+ modalButton("Dismiss"), |
31 | -+ | ! |
- #'+ style = "mb-4" |
32 |
- #' @keywords internal+ ), |
||
33 | -+ | ! |
- decorate_err_msg <- function(x, pre = character(0), post = character(0)) {+ tags$div(tags$pre(id = ns("r_code"), rcode)), |
34 | -41x | +
- tryCatch(+ ), |
|
35 | -41x | +! |
- x,+ title = title, |
36 | -41x | +! |
- error = function(e) {+ footer = tagList( |
37 | -2x | +! |
- stop(+ actionButton(ns("copyRCode"), "Copy to Clipboard", `data-clipboard-target` = paste0("#", ns("r_code"))), |
38 | -2x | +! |
- "\n",+ modalButton("Dismiss") |
39 | -2x | +
- pre,+ ), |
|
40 | -2x | +! |
- "\n",+ size = "l", |
41 | -2x | -
- e$message,- |
- |
42 | -2x | -
- "\n",- |
- |
43 | -2x | -
- post,- |
- |
44 | -2x | -
- call. = FALSE- |
- |
45 | -- |
- )- |
- |
46 | -+ | ! |
- }+ easyClose = TRUE |
47 | +42 |
- )- |
- |
48 | -39x | -
- x+ )) |
|
49 | +43 |
} |