diff --git a/coverage-report/index.html b/coverage-report/index.html index c9d9e0cb0..4908c4e3a 100644 --- a/coverage-report/index.html +++ b/coverage-report/index.html @@ -95,7 +95,7 @@ font-size: 11px; }
1 |
- #' `teal` main module+ #' Filter state snapshot management |
||
3 |
- #' @description+ #' Capture and restore snapshots of the global (app) filter state. |
||
4 |
- #' `r lifecycle::badge("stable")`+ #' |
||
5 |
- #' Module to create a `teal` app. This module can be called directly instead of [init()] and+ #' This module introduces snapshots: stored descriptions of the filter state of the entire application. |
||
6 |
- #' included in your custom application. Please note that [init()] adds `reporter_previewer_module`+ #' Snapshots allow the user to save the current filter state of the application for later use in the session, |
||
7 |
- #' automatically, which is not a case when calling `ui/srv_teal` directly.+ #' 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. |
||
9 |
- #' @details+ #' |
||
10 |
- #'+ #' The snapshot manager is accessed with the camera icon in the tabset bar. |
||
11 |
- #' Module is responsible for creating the main `shiny` app layout and initializing all the necessary+ #' At the beginning of a session it presents three icons: a camera, an upload, and an circular arrow. |
||
12 |
- #' components. This module establishes reactive connection between the input `data` and every other+ #' Clicking the camera captures a snapshot, clicking the upload adds a snapshot from a file |
||
13 |
- #' component in the app. Reactive change of the `data` passed as an argument, reloads the app and+ #' and applies the filter states therein, and clicking the arrow resets initial application state. |
||
14 |
- #' possibly keeps all input settings the same so the user can continue where one left off.+ #' As snapshots are added, they will show up as rows in a table and each will have a select button and a save button. |
||
16 |
- #' ## data flow in `teal` application+ #' @section Server logic: |
||
17 |
- #'+ #' Snapshots are basically `teal_slices` objects, however, since each module is served by a separate instance |
||
18 |
- #' This module supports multiple data inputs but eventually, they are all converted to `reactive`+ #' of `FilteredData` and these objects require shared state, `teal_slice` is a `reactiveVal` so `teal_slices` |
||
19 |
- #' returning `teal_data` in this module. On this `reactive teal_data` object several actions are+ #' cannot be stored as is. Therefore, `teal_slices` are reversibly converted to a list of lists representation |
||
20 |
- #' performed:+ #' (attributes are maintained). |
||
21 |
- #' - data loading in [`module_init_data`]+ #' |
||
22 |
- #' - data filtering in [`module_filter_data`]+ #' Snapshots are stored in a `reactiveVal` as a named list. |
||
23 |
- #' - data transformation in [`module_transform_data`]+ #' The first snapshot is the initial state of the application and the user can add a snapshot whenever they see fit. |
||
25 |
- #' ## Fallback on failure+ #' For every snapshot except the initial one, a piece of UI is generated that contains |
||
26 |
- #'+ #' the snapshot name, a select button to restore that snapshot, and a save button to save it to a file. |
||
27 |
- #' `teal` is designed in such way that app will never crash if the error is introduced in any+ #' The initial snapshot is restored by a separate "reset" button. |
||
28 |
- #' custom `shiny` module provided by app developer (e.g. [teal_data_module()], [teal_transform_module()]).+ #' It cannot be saved directly but a user is welcome to capture the initial state as a snapshot and save that. |
||
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.+ #' @section Snapshot mechanics: |
||
31 |
- #'+ #' When a snapshot is captured, the user is prompted to name it. |
||
32 |
- #' @rdname module_teal+ #' Names are displayed as is but since they are used to create button ids, |
||
33 |
- #' @name module_teal+ #' under the hood they are converted to syntactically valid strings. |
||
34 |
- #'+ #' New snapshot names are validated so that their valid versions are unique. |
||
35 |
- #' @inheritParams module_init_data+ #' Leading and trailing white space is trimmed. |
||
36 |
- #' @inheritParams init+ #' |
||
37 |
- #'+ #' The module can read the global state of the application from `slices_global` and `mapping_matrix`. |
||
38 |
- #' @return `NULL` invisibly+ #' The former provides a list of all existing `teal_slice`s and the latter says which slice is active in which module. |
||
39 |
- NULL+ #' Once a name has been accepted, `slices_global` is converted to a list of lists - a snapshot. |
||
40 |
-
+ #' The snapshot contains the `mapping` attribute of the initial application state |
||
41 |
- #' @rdname module_teal+ #' (or one that has been restored), which may not reflect the current one, |
||
42 |
- #' @export+ #' so `mapping_matrix` is transformed to obtain the current mapping, i.e. a list that, |
||
43 |
- ui_teal <- function(id,+ #' when passed to the `mapping` argument of [teal_slices()], would result in the current mapping. |
||
44 |
- modules,+ #' This is substituted as the snapshot's `mapping` attribute and the snapshot is added to the snapshot list. |
||
45 |
- title = build_app_title(),+ #' |
||
46 |
- header = tags$p(),+ #' To restore app state, a snapshot is retrieved from storage and rebuilt into a `teal_slices` object. |
||
47 |
- footer = tags$p()) {+ #' Then state of all `FilteredData` objects (provided in `datasets`) is cleared |
||
48 | -! | +
- checkmate::assert_character(id, max.len = 1, any.missing = FALSE)+ #' and set anew according to the `mapping` attribute of the snapshot. |
|
49 | -! | +
- checkmate::assert(+ #' The snapshot is then set as the current content of `slices_global`. |
|
50 | -! | +
- .var.name = "title",+ #' |
|
51 | -! | +
- checkmate::check_string(title),+ #' To save a snapshot, the snapshot is retrieved and reassembled just like for restoring, |
|
52 | -! | +
- checkmate::check_multi_class(title, c("shiny.tag", "shiny.tag.list", "html"))+ #' and then saved to file with [slices_store()]. |
|
53 |
- )+ #' |
||
54 | -! | +
- checkmate::assert(+ #' When a snapshot is uploaded, it will first be added to storage just like a newly created one, |
|
55 | -! | +
- .var.name = "header",+ #' and then used to restore app state much like a snapshot taken from storage. |
|
56 | -! | +
- checkmate::check_string(header),+ #' Upon clicking the upload icon the user will be prompted for a file to upload |
|
57 | -! | +
- checkmate::check_multi_class(header, c("shiny.tag", "shiny.tag.list", "html"))+ #' and may choose to name the new snapshot. The name defaults to the name of the file (the extension is dropped) |
|
58 |
- )+ #' and normal naming rules apply. Loading the file yields a `teal_slices` object, |
||
59 | -! | +
- checkmate::assert(+ #' which is disassembled for storage and used directly for restoring app state. |
|
60 | -! | +
- .var.name = "footer",+ #' |
|
61 | -! | +
- checkmate::check_string(footer),+ #' @section Transferring snapshots: |
|
62 | -! | +
- checkmate::check_multi_class(footer, c("shiny.tag", "shiny.tag.list", "html"))+ #' Snapshots uploaded from disk should only be used in the same application they come from, |
|
63 |
- )+ #' _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 | -! | +
- if (is.character(title)) {+ #' a `teal_slices` object. When a snapshot is restored from file, its `app_id` is compared to that |
|
66 | -! | +
- title <- build_app_title(title)+ #' of the current app state and only if the match is the snapshot admitted to the session. |
|
67 |
- } else {+ #' |
||
68 | -! | +
- validate_app_title_tag(title)+ #' @section Bookmarks: |
|
69 |
- }+ #' An `onBookmark` callback creates a snapshot of the current filter state. |
||
70 |
-
+ #' This is done on the app session, not the module session. |
||
71 | -! | +
- if (checkmate::test_string(header)) {+ #' (The snapshot will be retrieved by `module_teal` in order to set initial app state in a restored app.) |
|
72 | -! | +
- header <- tags$p(header)+ #' 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. |
||
75 | -! | +
- if (checkmate::test_string(footer)) {+ #' @param slices_global (`reactiveVal`) that contains a `teal_slices` object |
|
76 | -! | +
- footer <- tags$p(footer)+ #' containing all `teal_slice`s existing in the app, both active and inactive. |
|
77 |
- }+ #' |
||
78 |
-
+ #' @return `list` containing the snapshot history, where each element is an unlisted `teal_slices` object. |
||
79 | -! | +
- ns <- NS(id)+ #' |
|
80 |
-
+ #' @name module_snapshot_manager |
||
81 |
- # show busy icon when `shiny` session is busy computing stuff+ #' @rdname module_snapshot_manager |
||
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(+ #' @author Aleksander Chlebowski |
|
84 | -! | +
- condition = "(($('html').hasClass('shiny-busy')) && (document.getElementById('shiny-notification-panel') == null))", # nolint: line_length.+ #' @keywords internal |
|
85 | -! | +
- tags$div(+ NULL |
|
86 | -! | +
- icon("arrows-rotate", class = "fa-spin", prefer_type = "solid"),+ |
|
87 | -! | +
- "Computing ...",+ #' @rdname module_snapshot_manager |
|
88 |
- # CSS defined in `custom.css`+ ui_snapshot_manager_panel <- function(id) { |
||
89 | ! |
- class = "shinybusymessage"+ ns <- NS(id) |
|
90 | -+ | ! |
- )+ tags$button( |
91 | -+ | ! |
- )+ id = ns("show_snapshot_manager"), |
92 | -+ | ! |
-
+ class = "btn action-button wunder_bar_button", |
93 | ! |
- fluidPage(+ title = "View filter mapping", |
|
94 | ! |
- id = id,+ suppressMessages(icon("fas fa-camera")) |
|
95 | -! | +
- title = title,+ ) |
|
96 | -! | +
- theme = get_teal_bs_theme(),+ } |
|
97 | -! | +
- include_teal_css_js(),+ |
|
98 | -! | +
- tags$header(header),+ #' @rdname module_snapshot_manager |
|
99 | -! | +
- tags$hr(class = "my-2"),+ srv_snapshot_manager_panel <- function(id, slices_global) { |
|
100 | -! | +87x |
- shiny_busy_message_panel,+ moduleServer(id, function(input, output, session) { |
101 | -! | +87x |
- tags$div(+ logger::log_debug("srv_snapshot_manager_panel initializing") |
102 | -! | +87x |
- id = ns("tabpanel_wrapper"),+ setBookmarkExclude(c("show_snapshot_manager")) |
103 | -! | +87x |
- class = "teal-body",+ observeEvent(input$show_snapshot_manager, { |
104 | ! |
- ui_teal_module(id = ns("teal_modules"), modules = modules)+ logger::log_debug("srv_snapshot_manager_panel@1 show_snapshot_manager button has been clicked.") |
|
105 | -+ | ! |
- ),+ showModal( |
106 | ! |
- tags$div(+ modalDialog( |
|
107 | ! |
- id = ns("options_buttons"),+ ui_snapshot_manager(session$ns("module")), |
|
108 | ! |
- style = "position: absolute; right: 10px;",+ class = "snapshot_manager_modal", |
|
109 | ! |
- ui_bookmark_panel(ns("bookmark_manager"), modules),+ size = "m", |
|
110 | ! |
- tags$button(+ footer = NULL, |
|
111 | ! |
- class = "btn action-button filter_hamburger", # see sidebar.css for style filter_hamburger+ easyClose = TRUE |
|
112 | -! | +
- href = "javascript:void(0)",+ ) |
|
113 | -! | +
- onclick = sprintf("toggleFilterPanel('%s');", ns("tabpanel_wrapper")),+ ) |
|
114 | -! | +
- title = "Toggle filter panel",+ }) |
|
115 | -! | +87x |
- icon("fas fa-bars")+ srv_snapshot_manager("module", slices_global = slices_global) |
116 |
- ),+ }) |
||
117 | -! | +
- ui_snapshot_manager_panel(ns("snapshot_manager_panel")),+ } |
|
118 | -! | +
- ui_filter_manager_panel(ns("filter_manager_panel"))+ |
|
119 |
- ),+ #' @rdname module_snapshot_manager |
||
120 | -! | +
- tags$script(+ ui_snapshot_manager <- function(id) { |
|
121 | ! |
- HTML(+ ns <- NS(id) |
|
122 | ! |
- sprintf(+ tags$div( |
|
123 | -+ | ! |
- "+ class = "manager_content", |
124 | ! |
- $(document).ready(function() {+ tags$div( |
|
125 | ! |
- $('#%s').appendTo('#%s');+ class = "manager_table_row", |
|
126 | -+ | ! |
- });+ tags$span(tags$b("Snapshot manager")), |
127 | -+ | ! |
- ",+ actionLink(ns("snapshot_add"), label = NULL, icon = icon("fas fa-camera"), title = "add snapshot"), |
128 | ! |
- ns("options_buttons"),+ actionLink(ns("snapshot_load"), label = NULL, icon = icon("fas fa-upload"), title = "upload snapshot"), |
|
129 | ! |
- ns("teal_modules-active_tab")+ actionLink(ns("snapshot_reset"), label = NULL, icon = icon("fas fa-undo"), title = "reset initial state"), |
|
130 | -+ | ! |
- )+ NULL |
131 |
- )+ ), |
||
132 | -+ | ! |
- ),+ uiOutput(ns("snapshot_list")) |
133 | -! | +
- tags$hr(),+ ) |
|
134 | -! | +
- tags$footer(+ } |
|
135 | -! | +
- tags$div(+ |
|
136 | -! | +
- footer,+ #' @rdname module_snapshot_manager |
|
137 | -! | +
- teal.widgets::verbatim_popup_ui(ns("sessionInfo"), "Session Info", type = "link"),+ srv_snapshot_manager <- function(id, slices_global) { |
|
138 | -! | +87x |
- br(),+ checkmate::assert_character(id) |
139 | -! | +
- ui_teal_lockfile(ns("lockfile")),+ |
|
140 | -! | +87x |
- textOutput(ns("identifier"))+ moduleServer(id, function(input, output, session) { |
141 | -+ | 87x |
- )+ logger::log_debug("srv_snapshot_manager initializing") |
142 |
- )+ |
||
143 |
- )+ # Set up bookmarking callbacks ---- |
||
144 |
- }+ # Register bookmark exclusions (all buttons and text fields). |
||
145 | -+ | 87x |
-
+ setBookmarkExclude(c( |
146 | -+ | 87x |
- #' @rdname module_teal+ "snapshot_add", "snapshot_load", "snapshot_reset", |
147 | -+ | 87x |
- #' @export+ "snapshot_name_accept", "snaphot_file_accept", |
148 | -+ | 87x |
- srv_teal <- function(id, data, modules, filter = teal_slices()) {+ "snapshot_name", "snapshot_file" |
149 | -89x | +
- checkmate::assert_character(id, max.len = 1, any.missing = FALSE)+ )) |
|
150 | -89x | +
- checkmate::assert_multi_class(data, c("teal_data", "teal_data_module", "reactive"))+ # Add snapshot history to bookmark. |
|
151 | -88x | +87x |
- checkmate::assert_class(modules, "teal_modules")+ session$onBookmark(function(state) { |
152 | -88x | +! |
- checkmate::assert_class(filter, "teal_slices")+ logger::log_debug("srv_snapshot_manager@onBookmark: storing snapshot and bookmark history") |
153 | -+ | ! |
-
+ state$values$snapshot_history <- snapshot_history() # isolate this? |
154 | -88x | +
- moduleServer(id, function(input, output, session) {+ }) |
|
155 | -88x | +
- logger::log_debug("srv_teal initializing.")+ |
|
156 | -+ | 87x |
-
+ ns <- session$ns |
157 | -88x | +
- if (getOption("teal.show_js_log", default = FALSE)) {+ |
|
158 | -! | +
- shinyjs::showLog()+ # Track global filter states ---- |
|
159 | -+ | 87x |
- }+ snapshot_history <- reactiveVal({ |
160 |
-
+ # Restore directly from bookmarked state, if applicable. |
||
161 | -88x | +87x |
- srv_teal_lockfile("lockfile")+ restoreValue( |
162 | -+ | 87x |
-
+ ns("snapshot_history"), |
163 | -88x | +87x |
- output$identifier <- renderText(+ list("Initial application state" = shiny::isolate(as.list(slices_global$all_slices(), recursive = TRUE))) |
164 | -88x | +
- paste0("Pid:", Sys.getpid(), " Token:", substr(session$token, 25, 32))+ ) |
|
165 |
- )+ }) |
||
167 | -88x | +
- teal.widgets::verbatim_popup_srv(+ # Snapshot current application state ---- |
|
168 | -88x | +
- "sessionInfo",+ # Name snaphsot. |
|
169 | -88x | +87x |
- verbatim_content = utils::capture.output(utils::sessionInfo()),+ observeEvent(input$snapshot_add, { |
170 | -88x | +! |
- title = "SessionInfo"+ logger::log_debug("srv_snapshot_manager: snapshot_add button clicked") |
171 | -+ | ! |
- )+ showModal( |
172 | -+ | ! |
-
+ modalDialog( |
173 | -+ | ! |
- # `JavaScript` code+ textInput(ns("snapshot_name"), "Name the snapshot", width = "100%", placeholder = "Meaningful, unique name"), |
174 | -88x | +! |
- run_js_files(files = "init.js")+ footer = tagList( |
175 | -+ | ! |
-
+ actionButton(ns("snapshot_name_accept"), "Accept", icon = icon("far fa-thumbs-up")), |
176 | -+ | ! |
- # set timezone in shiny app+ modalButton(label = "Cancel", icon = icon("far fa-thumbs-down")) |
177 |
- # timezone is set in the early beginning so it will be available also+ ), |
||
178 | -+ | ! |
- # for `DDL` and all shiny modules+ size = "s" |
179 | -88x | +
- get_client_timezone(session$ns)+ ) |
|
180 | -88x | +
- observeEvent(+ ) |
|
181 | -88x | +
- eventExpr = input$timezone,+ }) |
|
182 | -88x | +
- once = TRUE,+ # Store snaphsot. |
|
183 | -88x | +87x |
- handlerExpr = {+ observeEvent(input$snapshot_name_accept, { |
184 | ! |
- session$userData$timezone <- input$timezone+ logger::log_debug("srv_snapshot_manager: snapshot_name_accept button clicked") |
|
185 | ! |
- logger::log_debug("srv_teal@1 Timezone set to client's timezone: { input$timezone }.")+ snapshot_name <- trimws(input$snapshot_name) |
|
186 | -+ | ! |
- }+ if (identical(snapshot_name, "")) { |
187 | -+ | ! |
- )+ logger::log_debug("srv_snapshot_manager: snapshot name rejected") |
188 | -+ | ! |
-
+ showNotification( |
189 | -88x | +! |
- data_handled <- srv_init_data("data", data = data)+ "Please name the snapshot.", |
190 | -+ | ! |
-
+ type = "message" |
191 | -87x | +
- validate_ui <- tags$div(+ ) |
|
192 | -87x | +! |
- id = session$ns("validate_messages"),+ updateTextInput(inputId = "snapshot_name", value = "", placeholder = "Meaningful, unique name") |
193 | -87x | +! |
- class = "teal_validated",+ } else if (is.element(make.names(snapshot_name), make.names(names(snapshot_history())))) { |
194 | -87x | +! |
- ui_check_class_teal_data(session$ns("class_teal_data")),+ logger::log_debug("srv_snapshot_manager: snapshot name rejected") |
195 | -87x | +! |
- ui_validate_error(session$ns("silent_error")),+ showNotification( |
196 | -87x | +! |
- ui_check_module_datanames(session$ns("datanames_warning"))+ "This name is in conflict with other snapshot names. Please choose a different one.", |
197 | -+ | ! |
- )+ type = "message" |
198 | -87x | +
- srv_check_class_teal_data("class_teal_data", data_handled)+ ) |
|
199 | -87x | +! |
- srv_validate_error("silent_error", data_handled, validate_shiny_silent_error = FALSE)+ updateTextInput(inputId = "snapshot_name", value = "", placeholder = "Meaningful, unique name") |
200 | -87x | +
- srv_check_module_datanames("datanames_warning", data_handled, modules)+ } else { |
|
201 | -+ | ! |
-
+ logger::log_debug("srv_snapshot_manager: snapshot name accepted, adding snapshot") |
202 | -87x | +! |
- data_validated <- .trigger_on_success(data_handled)+ snapshot <- as.list(slices_global$all_slices(), recursive = TRUE) |
203 | -+ | ! |
-
+ snapshot_update <- c(snapshot_history(), list(snapshot)) |
204 | -87x | +! |
- data_signatured <- reactive({+ names(snapshot_update)[length(snapshot_update)] <- snapshot_name |
205 | -152x | +! |
- req(inherits(data_validated(), "teal_data"))+ snapshot_history(snapshot_update) |
206 | -75x | +! |
- is_filter_ok <- check_filter_datanames(filter, names(data_validated()))+ removeModal() |
207 | -75x | +
- if (!isTRUE(is_filter_ok)) {+ # Reopen filter manager modal by clicking button in the main application. |
|
208 | -2x | +! |
- showNotification(+ shinyjs::click(id = "teal-wunder_bar-show_snapshot_manager", asis = TRUE) |
209 | -2x | +
- "Some filters were not applied because of incompatibility with data. Contact app developer.",+ } |
|
210 | -2x | +
- type = "warning",+ }) |
|
211 | -2x | +
- duration = 10+ |
|
212 |
- )+ # Upload a snapshot file ---- |
||
213 | -2x | +
- warning(is_filter_ok)+ # Select file. |
|
214 | -+ | 87x |
- }+ observeEvent(input$snapshot_load, { |
215 | -75x | +! |
- .add_signature_to_data(data_validated())+ logger::log_debug("srv_snapshot_manager: snapshot_load button clicked") |
216 | -+ | ! |
- })+ showModal( |
217 | -+ | ! |
-
+ modalDialog( |
218 | -87x | +! |
- data_load_status <- reactive({+ fileInput(ns("snapshot_file"), "Choose snapshot file", accept = ".json", width = "100%"), |
219 | -80x | +! |
- if (inherits(data_handled(), "teal_data")) {+ textInput( |
220 | -75x | +! |
- "ok"+ ns("snapshot_name"), |
221 | -5x | +! |
- } else if (inherits(data, "teal_data_module")) {+ "Name the snapshot (optional)", |
222 | -5x | +! |
- "teal_data_module failed"+ width = "100%", |
223 | -+ | ! |
- } else {+ placeholder = "Meaningful, unique name" |
224 | -! | +
- "external failed"+ ), |
|
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 | -87x | +
- datasets_rv <- if (!isTRUE(attr(filter, "module_specific"))) {+ ) |
|
229 | -76x | +
- eventReactive(data_signatured(), {+ ) |
|
230 | -66x | +
- req(inherits(data_signatured(), "teal_data"))+ ) |
|
231 | -66x | +
- logger::log_debug("srv_teal@1 initializing FilteredData")+ }) |
|
232 | -66x | +
- teal_data_to_filtered_data(data_signatured())+ # Store new snapshot to list and restore filter states. |
|
233 | -+ | 87x |
- })+ observeEvent(input$snaphot_file_accept, { |
234 | -+ | ! |
- }+ logger::log_debug("srv_snapshot_manager: snapshot_file_accept button clicked") |
235 | -+ | ! |
-
+ snapshot_name <- trimws(input$snapshot_name) |
236 | -+ | ! |
-
+ if (identical(snapshot_name, "")) { |
237 | -+ | ! |
-
+ logger::log_debug("srv_snapshot_manager: no snapshot name provided, naming after file") |
238 | -87x | +! |
- if (inherits(data, "teal_data_module")) {+ snapshot_name <- tools::file_path_sans_ext(input$snapshot_file$name) |
239 | -9x | +
- setBookmarkExclude(c("teal_modules-active_tab"))+ } |
|
240 | -9x | +! |
- shiny::insertTab(+ if (is.element(make.names(snapshot_name), make.names(names(snapshot_history())))) { |
241 | -9x | +! |
- inputId = "teal_modules-active_tab",+ logger::log_debug("srv_snapshot_manager: snapshot name rejected") |
242 | -9x | +! |
- position = "before",+ showNotification( |
243 | -9x | +! |
- select = TRUE,+ "This name is in conflict with other snapshot names. Please choose a different one.", |
244 | -9x | +! |
- tabPanel(+ type = "message" |
245 | -9x | +
- title = icon("fas fa-database"),+ ) |
|
246 | -9x | +! |
- value = "teal_data_module",+ updateTextInput(inputId = "snapshot_name", value = "", placeholder = "Meaningful, unique name") |
247 | -9x | +
- tags$div(+ } else { |
|
248 | -9x | +
- ui_init_data(session$ns("data")),+ # Restore snapshot and verify app compatibility. |
|
249 | -9x | +! |
- validate_ui+ logger::log_debug("srv_snapshot_manager: snapshot name accepted, loading snapshot") |
250 | -+ | ! |
- )+ snapshot_state <- try(slices_restore(input$snapshot_file$datapath)) |
251 | -+ | ! |
- )+ if (!inherits(snapshot_state, "modules_teal_slices")) { |
252 | -+ | ! |
- )+ logger::log_debug("srv_snapshot_manager: snapshot file corrupt") |
253 | -+ | ! |
-
+ showNotification( |
254 | -9x | +! |
- if (attr(data, "once")) {+ "File appears to be corrupt.", |
255 | -9x | +! |
- observeEvent(data_signatured(), once = TRUE, {+ type = "error" |
256 | -4x | +
- logger::log_debug("srv_teal@2 removing data tab.")+ ) |
|
257 | -+ | ! |
- # when once = TRUE we pull data once and then remove data tab+ } else if (!identical(attr(snapshot_state, "app_id"), attr(slices_global$all_slices(), "app_id"))) { |
258 | -4x | +! |
- removeTab("teal_modules-active_tab", target = "teal_data_module")+ logger::log_debug("srv_snapshot_manager: snapshot not compatible with app") |
259 | -+ | ! |
- })+ showNotification( |
260 | -+ | ! |
- }+ "This snapshot file is not compatible with the app and cannot be loaded.", |
261 | -+ | ! |
- } else {+ type = "warning" |
262 |
- # when no teal_data_module then we want to display messages above tabsetPanel (because there is no data-tab)+ ) |
||
263 | -78x | +
- insertUI(+ } else { |
|
264 | -78x | +
- selector = sprintf("#%s", session$ns("tabpanel_wrapper")),+ # Add to snapshot history. |
|
265 | -78x | +! |
- where = "beforeBegin",+ logger::log_debug("srv_snapshot_manager: snapshot loaded, adding to history") |
266 | -78x | +! |
- ui = tags$div(validate_ui, tags$br())+ snapshot <- as.list(slices_global$all_slices(), recursive = TRUE) |
267 | -+ | ! |
- )+ snapshot_update <- c(snapshot_history(), list(snapshot)) |
268 | -+ | ! |
- }+ names(snapshot_update)[length(snapshot_update)] <- snapshot_name |
269 | -+ | ! |
-
+ snapshot_history(snapshot_update) |
270 | -87x | +
- module_labels <- unlist(module_labels(modules), use.names = FALSE)+ ### Begin simplified restore procedure. ### |
|
271 | -87x | +! |
- slices_global <- methods::new(".slicesGlobal", filter, module_labels)+ logger::log_debug("srv_snapshot_manager: restoring snapshot") |
272 | -87x | +! |
- modules_output <- srv_teal_module(+ slices_global$slices_set(snapshot_state) |
273 | -87x | +! |
- id = "teal_modules",+ removeModal() |
274 | -87x | +
- data = data_signatured,+ ### End simplified restore procedure. ### |
|
275 | -87x | +
- datasets = datasets_rv,+ } |
|
276 | -87x | +
- modules = modules,+ } |
|
277 | -87x | +
- slices_global = slices_global,+ }) |
|
278 | -87x | +
- data_load_status = data_load_status+ # Apply newly added snapshot. |
|
279 |
- )+ |
||
280 | -87x | +
- mapping_table <- srv_filter_manager_panel("filter_manager_panel", slices_global = slices_global)+ # Restore initial state ---- |
|
281 | 87x |
- snapshots <- srv_snapshot_manager_panel("snapshot_manager_panel", slices_global = slices_global)+ observeEvent(input$snapshot_reset, { |
|
282 | -87x | +2x |
- srv_bookmark_panel("bookmark_manager", modules)+ logger::log_debug("srv_snapshot_manager: snapshot_reset button clicked, restoring snapshot") |
283 | -+ | 2x |
- })+ s <- "Initial application state" |
284 |
-
+ ### Begin restore procedure. ### |
||
285 | -87x | +2x |
- invisible(NULL)+ snapshot <- snapshot_history()[[s]] |
286 | -+ | 2x |
- }+ snapshot_state <- as.teal_slices(snapshot) |
1 | -+ | ||
287 | +2x |
- #' Calls all `modules`+ slices_global$slices_set(snapshot_state) |
|
2 | -+ | ||
288 | +2x |
- #'+ removeModal() |
|
3 | +289 |
- #' On the UI side each `teal_modules` is translated to a `tabsetPanel` and each `teal_module` is a+ ### End restore procedure. ### |
|
4 | +290 |
- #' `tabPanel`. Both, UI and server are called recursively so that each tab is a separate module and+ }) |
|
5 | +291 |
- #' reflect nested structure of `modules` argument.+ |
|
6 | +292 |
- #'+ # Build snapshot table ---- |
|
7 | +293 |
- #' @name module_teal_module+ # Create UI elements and server logic for the snapshot table. |
|
8 | +294 |
- #'+ # Observers must be tracked to avoid duplication and excess reactivity. |
|
9 | +295 |
- #' @inheritParams module_teal+ # Remaining elements are tracked likewise for consistency and a slight speed margin. |
|
10 | -+ | ||
296 | +87x |
- #'+ observers <- reactiveValues() |
|
11 | -+ | ||
297 | +87x |
- #' @param data (`reactive` returning `teal_data`)+ handlers <- reactiveValues() |
|
12 | -+ | ||
298 | +87x |
- #'+ divs <- reactiveValues() |
|
13 | +299 |
- #' @param slices_global (`reactiveVal` returning `modules_teal_slices`)+ |
|
14 | -+ | ||
300 | +87x |
- #' see [`module_filter_manager`]+ observeEvent(snapshot_history(), { |
|
15 | -+ | ||
301 | +77x |
- #'+ logger::log_debug("srv_snapshot_manager: snapshot history modified, updating snapshot list") |
|
16 | -+ | ||
302 | +77x |
- #' @param depth (`integer(1)`)+ lapply(names(snapshot_history())[-1L], function(s) { |
|
17 | -+ | ||
303 | +! |
- #' number which helps to determine depth of the modules nesting.+ id_pickme <- sprintf("pickme_%s", make.names(s)) |
|
18 | -+ | ||
304 | +! |
- #'+ id_saveme <- sprintf("saveme_%s", make.names(s)) |
|
19 | -+ | ||
305 | +! |
- #' @param datasets (`reactive` returning `FilteredData` or `NULL`)+ id_rowme <- sprintf("rowme_%s", make.names(s)) |
|
20 | +306 |
- #' When `datasets` is passed from the parent module (`srv_teal`) then `dataset` is a singleton+ |
|
21 | +307 |
- #' which implies in filter-panel to be "global". When `NULL` then filter-panel is "module-specific".+ # Observer for restoring snapshot. |
|
22 | -+ | ||
308 | +! |
- #'+ if (!is.element(id_pickme, names(observers))) { |
|
23 | -+ | ||
309 | +! |
- #' @param data_load_status (`reactive` returning `character`)+ observers[[id_pickme]] <- observeEvent(input[[id_pickme]], { |
|
24 | +310 |
- #' Determines action dependent on a data loading status:+ ### Begin restore procedure. ### |
|
25 | -+ | ||
311 | +! |
- #' - `"ok"` when `teal_data` is returned from the data loading.+ snapshot <- snapshot_history()[[s]] |
|
26 | -+ | ||
312 | +! |
- #' - `"teal_data_module failed"` when [teal_data_module()] didn't return `teal_data`. Disables tabs buttons.+ snapshot_state <- as.teal_slices(snapshot) |
|
27 | +313 |
- #' - `"external failed"` when a `reactive` passed to `srv_teal(data)` didn't return `teal_data`. Hides the whole tab+ |
|
28 | -+ | ||
314 | +! |
- #' panel.+ slices_global$slices_set(snapshot_state) |
|
29 | -+ | ||
315 | +! |
- #'+ removeModal() |
|
30 | +316 |
- #' @return+ ### End restore procedure. ### |
|
31 | +317 |
- #' output of currently active module.+ }) |
|
32 | +318 |
- #' - `srv_teal_module.teal_module` returns `reactiveVal` containing output of the called module.+ } |
|
33 | +319 |
- #' - `srv_teal_module.teal_modules` returns output of module selected by `input$active_tab`.+ # Create handler for downloading snapshot. |
|
34 | -+ | ||
320 | +! |
- #'+ if (!is.element(id_saveme, names(handlers))) { |
|
35 | -+ | ||
321 | +! |
- #' @keywords internal- |
- |
36 | -- |
- NULL+ output[[id_saveme]] <- downloadHandler( |
|
37 | -+ | ||
322 | +! |
-
+ filename = function() { |
|
38 | -+ | ||
323 | +! |
- #' @rdname module_teal_module+ sprintf("teal_snapshot_%s_%s.json", s, Sys.Date()) |
|
39 | +324 |
- ui_teal_module <- function(id, modules, depth = 0L) {+ }, |
|
40 | +325 | ! |
- checkmate::assert_multi_class(modules, c("teal_modules", "teal_module", "shiny.tag"))+ content = function(file) { |
41 | +326 | ! |
- checkmate::assert_count(depth)+ snapshot <- snapshot_history()[[s]] |
42 | +327 | ! |
- UseMethod("ui_teal_module", modules)- |
-
43 | -- |
- }- |
- |
44 | -- |
-
+ snapshot_state <- as.teal_slices(snapshot) |
|
45 | -+ | ||
328 | +! |
- #' @rdname module_teal_module+ slices_store(tss = snapshot_state, file = file) |
|
46 | +329 |
- #' @export+ } |
|
47 | +330 |
- ui_teal_module.default <- function(id, modules, depth = 0L) {+ ) |
|
48 | +331 | ! |
- stop("Modules class not supported: ", paste(class(modules), collapse = " "))- |
-
49 | -- |
- }- |
- |
50 | -- |
-
+ handlers[[id_saveme]] <- id_saveme |
|
51 | +332 |
- #' @rdname module_teal_module+ } |
|
52 | +333 |
- #' @export+ # Create a row for the snapshot table. |
|
53 | -+ | ||
334 | +! |
- ui_teal_module.teal_modules <- function(id, modules, depth = 0L) {+ if (!is.element(id_rowme, names(divs))) { |
|
54 | +335 | ! |
- ns <- NS(id)+ divs[[id_rowme]] <- tags$div( |
55 | +336 | ! |
- tags$div(+ class = "manager_table_row", |
56 | +337 | ! |
- id = ns("wrapper"),+ tags$span(tags$h5(s)), |
57 | +338 | ! |
- do.call(+ actionLink(inputId = ns(id_pickme), label = icon("far fa-circle-check"), title = "select"), |
58 | +339 | ! |
- tabsetPanel,+ downloadLink(outputId = ns(id_saveme), label = icon("far fa-save"), title = "save to file") |
59 | -! | +||
340 | +
- c(+ ) |
||
60 | +341 |
- # by giving an id, we can reactively respond to tab changes+ } |
|
61 | -! | +||
342 | +
- list(+ }) |
||
62 | -! | +||
343 | +
- id = ns("active_tab"),+ }) |
||
63 | -! | +||
344 | +
- type = if (modules$label == "root") "pills" else "tabs"+ |
||
64 | +345 |
- ),+ # Create table to display list of snapshots and their actions. |
|
65 | -! | +||
346 | +87x |
- lapply(+ output$snapshot_list <- renderUI({ |
|
66 | -! | +||
347 | +77x |
- names(modules$children),+ rows <- rev(reactiveValuesToList(divs)) |
|
67 | -! | +||
348 | +77x |
- function(module_id) {+ if (length(rows) == 0L) { |
|
68 | -! | +||
349 | +77x |
- module_label <- modules$children[[module_id]]$label+ tags$div( |
|
69 | -! | +||
350 | +77x |
- if (is.null(module_label)) {+ class = "manager_placeholder", |
|
70 | -! | +||
351 | +77x |
- module_label <- icon("fas fa-database")+ "Snapshots will appear here." |
|
71 | +352 |
- }+ ) |
|
72 | -! | +||
353 | +
- tabPanel(+ } else { |
||
73 | +354 | ! |
- title = module_label,+ rows |
74 | -! | +||
355 | +
- value = module_id, # when clicked this tab value changes input$<tabset panel id>+ } |
||
75 | -! | +||
356 | +
- ui_teal_module(+ }) |
||
76 | -! | +||
357 | +
- id = ns(module_id),+ |
||
77 | -! | +||
358 | +87x |
- modules = modules$children[[module_id]],+ snapshot_history |
|
78 | -! | +||
359 | +
- depth = depth + 1L+ }) |
||
79 | +360 |
- )+ } |
80 | +1 |
- )+ #' Filter panel module in teal |
||
81 | +2 |
- }+ #' |
||
82 | +3 |
- )+ #' Creates filter panel module from `teal_data` object and returns `teal_data`. It is build in a way |
||
83 | +4 |
- )+ #' that filter panel changes and anything what happens before (e.g. [`module_init_data`]) is triggering |
||
84 | +5 |
- )+ #' further reactive events only if something has changed and if the module is visible. Thanks to |
||
85 | +6 |
- )+ #' this special implementation all modules' data are recalculated only for those modules which are |
||
86 | +7 |
- }+ #' currently displayed. |
||
87 | +8 |
-
+ #' |
||
88 | +9 |
- #' @rdname module_teal_module+ #' @return A `eventReactive` containing `teal_data` containing filtered objects and filter code. |
||
89 | +10 |
- #' @export+ #' `eventReactive` triggers only if all conditions are met: |
||
90 | +11 |
- ui_teal_module.teal_module <- function(id, modules, depth = 0L) {+ #' - tab is selected (`is_active`) |
||
91 | -! | +|||
12 | +
- ns <- NS(id)+ #' - when filters are changed (`get_filter_expr` is different than previous) |
|||
92 | -! | +|||
13 | +
- args <- c(list(id = ns("module")), modules$ui_args)+ #' |
|||
93 | +14 |
-
+ #' @inheritParams module_teal_module |
||
94 | -! | +|||
15 | +
- ui_teal <- tagList(+ #' @param active_datanames (`reactive` returning `character`) this module's data names |
|||
95 | -! | +|||
16 | +
- shinyjs::hidden(+ #' @name module_filter_data |
|||
96 | -! | +|||
17 | +
- tags$div(+ #' @keywords internal |
|||
97 | -! | +|||
18 | +
- id = ns("transform_failure_info"),+ NULL |
|||
98 | -! | +|||
19 | +
- class = "teal_validated",+ |
|||
99 | -! | +|||
20 | +
- div(+ #' @rdname module_filter_data+ |
+ |||
21 | ++ |
+ ui_filter_data <- function(id) { |
||
100 | +22 | ! |
- class = "teal-output-warning",+ ns <- shiny::NS(id) |
|
101 | +23 | ! |
- "One of transformators failed. Please check its inputs."+ uiOutput(ns("panel")) |
|
102 | +24 |
- )+ } |
||
103 | +25 |
- )+ |
||
104 | +26 |
- ),+ #' @rdname module_filter_data |
||
105 | -! | +|||
27 | +
- tags$div(+ srv_filter_data <- function(id, datasets, active_datanames, data, is_active) { |
|||
106 | -! | +|||
28 | +86x |
- id = ns("teal_module_ui"),+ assert_reactive(datasets) |
||
107 | -! | +|||
29 | +86x |
- tags$div(+ moduleServer(id, function(input, output, session) { |
||
108 | -! | +|||
30 | +86x |
- class = "teal_validated",+ active_corrected <- reactive(intersect(active_datanames(), datasets()$datanames())) |
||
109 | -! | +|||
31 | +
- ui_check_module_datanames(ns("validate_datanames"))+ |
|||
110 | -+ | |||
32 | +86x |
- ),+ output$panel <- renderUI({ |
||
111 | -! | +|||
33 | +88x |
- do.call(modules$ui, args)+ req(inherits(datasets(), "FilteredData")) |
||
112 | -+ | |||
34 | +88x |
- )+ isolate({ |
||
113 | +35 |
- )+ # render will be triggered only when FilteredData object changes (not when filters change) |
||
114 | +36 |
-
+ # technically it means that teal_data_module needs to be refreshed |
||
115 | -! | +|||
37 | +88x |
- div(+ logger::log_debug("srv_filter_panel rendering filter panel.") |
||
116 | -! | +|||
38 | +88x |
- id = id,+ if (length(active_corrected())) { |
||
117 | -! | +|||
39 | +86x |
- class = "teal_module",+ datasets()$srv_active("filters", active_datanames = active_corrected) |
||
118 | -! | +|||
40 | +86x |
- uiOutput(ns("data_reactive"), inline = TRUE),+ datasets()$ui_active(session$ns("filters"), active_datanames = active_corrected) |
||
119 | -! | +|||
41 | +
- tagList(+ } |
|||
120 | -! | +|||
42 | +
- if (depth >= 2L) tags$div(style = "mt-6"),+ }) |
|||
121 | -! | +|||
43 | +
- if (!is.null(modules$datanames)) {+ }) |
|||
122 | -! | +|||
44 | +
- fluidRow(+ |
|||
123 | -! | +|||
45 | +86x |
- column(width = 9, ui_teal, class = "teal_primary_col"),+ trigger_data <- .observe_active_filter_changed(datasets, is_active, active_corrected, data) |
||
124 | -! | +|||
46 | +
- column(+ |
|||
125 | -! | +|||
47 | +86x |
- width = 3,+ eventReactive(trigger_data(), { |
||
126 | -! | +|||
48 | +89x |
- ui_data_summary(ns("data_summary")),+ .make_filtered_teal_data(modules, data = data(), datasets = datasets(), datanames = active_corrected()) |
||
127 | -! | +|||
49 | +
- ui_filter_data(ns("filter_panel")),+ }) |
|||
128 | -! | +|||
50 | +
- ui_transform_teal_data(ns("data_transform"), transformators = modules$transformators, class = "well"),+ }) |
|||
129 | -! | +|||
51 | +
- class = "teal_secondary_col"+ } |
|||
130 | +52 |
- )+ |
||
131 | +53 |
- )+ #' @rdname module_filter_data |
||
132 | +54 |
- } else {+ .make_filtered_teal_data <- function(modules, data, datasets = NULL, datanames) { |
||
133 | -! | +|||
55 | +89x |
- ui_teal+ data <- eval_code( |
||
134 | -+ | |||
56 | +89x |
- }+ data,+ |
+ ||
57 | +89x | +
+ paste0(+ |
+ ||
58 | +89x | +
+ ".raw_data <- list2env(list(",+ |
+ ||
59 | +89x | +
+ toString(sprintf("%1$s = %1$s", sapply(datanames, as.name))),+ |
+ ||
60 | +89x | +
+ "))\n",+ |
+ ||
61 | +89x | +
+ "lockEnvironment(.raw_data) # @linksto .raw_data" # this is environment and it is shared by qenvs. CAN'T MODIFY! |
||
135 | +62 |
) |
||
136 | +63 |
) |
||
64 | +89x | +
+ filtered_code <- .get_filter_expr(datasets = datasets, datanames = datanames)+ |
+ ||
65 | +89x | +
+ filtered_teal_data <- .append_evaluated_code(data, filtered_code)+ |
+ ||
66 | +89x | +
+ filtered_datasets <- sapply(datanames, function(x) datasets$get_data(x, filtered = TRUE), simplify = FALSE)+ |
+ ||
67 | +89x | +
+ filtered_teal_data <- .append_modified_data(filtered_teal_data, filtered_datasets)+ |
+ ||
68 | +89x | +
+ filtered_teal_data+ |
+ ||
137 | +69 |
} |
||
138 | +70 | |||
139 | +71 |
- #' @rdname module_teal_module+ #' @rdname module_filter_data |
||
140 | +72 |
- srv_teal_module <- function(id,+ .observe_active_filter_changed <- function(datasets, is_active, active_datanames, data) { |
||
141 | -+ | |||
73 | +86x |
- data,+ previous_signature <- reactiveVal(NULL) |
||
142 | -+ | |||
74 | +86x |
- modules,+ filter_changed <- reactive({+ |
+ ||
75 | +195x | +
+ req(inherits(datasets(), "FilteredData"))+ |
+ ||
76 | +195x | +
+ new_signature <- c(+ |
+ ||
77 | +195x | +
+ teal.code::get_code(data()),+ |
+ ||
78 | +195x | +
+ .get_filter_expr(datasets = datasets(), datanames = active_datanames()) |
||
143 | +79 |
- datasets = NULL,+ )+ |
+ ||
80 | +195x | +
+ if (!identical(previous_signature(), new_signature)) {+ |
+ ||
81 | +94x | +
+ previous_signature(new_signature)+ |
+ ||
82 | +94x | +
+ TRUE |
||
144 | +83 |
- slices_global,+ } else {+ |
+ ||
84 | +101x | +
+ FALSE |
||
145 | +85 |
- reporter = teal.reporter::Reporter$new(),+ } |
||
146 | +86 |
- data_load_status = reactive("ok"),+ }) |
||
147 | +87 |
- is_active = reactive(TRUE)) {+ |
||
148 | -199x | +88 | +86x |
- checkmate::assert_string(id)+ trigger_data <- reactiveVal(NULL) |
149 | -199x | +89 | +86x |
- assert_reactive(data)+ observe({ |
150 | -199x | +90 | +208x |
- checkmate::assert_multi_class(modules, c("teal_modules", "teal_module"))+ if (isTRUE(is_active() && filter_changed())) { |
151 | -199x | +91 | +94x |
- assert_reactive(datasets, null.ok = TRUE)+ isolate({ |
152 | -199x | +92 | +94x |
- checkmate::assert_class(slices_global, ".slicesGlobal")+ if (is.null(trigger_data())) { |
153 | -199x | +93 | +86x |
- checkmate::assert_class(reporter, "Reporter")+ trigger_data(0) |
154 | -199x | +|||
94 | +
- assert_reactive(data_load_status)+ } else { |
|||
155 | -199x | +95 | +8x |
- UseMethod("srv_teal_module", modules)+ trigger_data(trigger_data() + 1) |
156 | +96 |
- }+ } |
||
157 | +97 |
-
+ }) |
||
158 | +98 |
- #' @rdname module_teal_module+ } |
||
159 | +99 |
- #' @export+ }) |
||
160 | +100 |
- srv_teal_module.default <- function(id,+ |
||
161 | -+ | |||
101 | +86x |
- data,+ trigger_data |
||
162 | +102 |
- modules,+ } |
||
163 | +103 |
- datasets = NULL,+ |
||
164 | +104 |
- slices_global,+ #' @rdname module_filter_data |
||
165 | +105 |
- reporter = teal.reporter::Reporter$new(),+ .get_filter_expr <- function(datasets, datanames) { |
||
166 | -+ | |||
106 | +284x |
- data_load_status = reactive("ok"),+ if (length(datanames)) {+ |
+ ||
107 | +278x | +
+ teal.slice::get_filter_expr(datasets = datasets, datanames = datanames) |
||
167 | +108 |
- is_active = reactive(TRUE)) {+ } else { |
||
168 | -! | +|||
109 | +6x |
- stop("Modules class not supported: ", paste(class(modules), collapse = " "))+ NULL |
||
169 | +110 |
- }+ } |
||
170 | +111 |
-
+ } |
171 | +1 |
- #' @rdname module_teal_module+ #' Get client timezone |
||
172 | +2 |
- #' @export+ #' |
||
173 | +3 |
- srv_teal_module.teal_modules <- function(id,+ #' User timezone in the browser may be different to the one on the server. |
||
174 | +4 |
- data,+ #' This script can be run to register a `shiny` input which contains information about the timezone in the browser. |
||
175 | +5 |
- modules,+ #' |
||
176 | +6 |
- datasets = NULL,+ #' @param ns (`function`) namespace function passed from the `session` object in the `shiny` server. |
||
177 | +7 |
- slices_global,+ #' For `shiny` modules this will allow for proper name spacing of the registered input. |
||
178 | +8 |
- reporter = teal.reporter::Reporter$new(),+ #' |
||
179 | +9 |
- data_load_status = reactive("ok"),+ #' @return `NULL`, invisibly. |
||
180 | +10 |
- is_active = reactive(TRUE)) {+ #' |
||
181 | -87x | +|||
11 | +
- moduleServer(id = id, module = function(input, output, session) {+ #' @keywords internal |
|||
182 | -87x | +|||
12 | +
- logger::log_debug("srv_teal_module.teal_modules initializing the module { deparse1(modules$label) }.")+ #' |
|||
183 | +13 |
-
+ get_client_timezone <- function(ns) { |
||
184 | -87x | +14 | +88x |
- observeEvent(data_load_status(), {+ script <- sprintf( |
185 | -80x | +15 | +88x |
- tabs_selector <- sprintf("#%s li a", session$ns("active_tab"))+ "Shiny.setInputValue(`%s`, Intl.DateTimeFormat().resolvedOptions().timeZone)", |
186 | -80x | -
- if (identical(data_load_status(), "ok")) {- |
- ||
187 | -75x | +16 | +88x |
- logger::log_debug("srv_teal_module@1 enabling modules tabs.")+ ns("timezone") |
188 | -75x | +|||
17 | +
- shinyjs::show("wrapper")+ ) |
|||
189 | -75x | +18 | +88x |
- shinyjs::enable(selector = tabs_selector)+ shinyjs::runjs(script) # function does not return anything |
190 | -5x | +19 | +88x |
- } else if (identical(data_load_status(), "teal_data_module failed")) {+ invisible(NULL) |
191 | -5x | +|||
20 | +
- logger::log_debug("srv_teal_module@1 disabling modules tabs.")+ } |
|||
192 | -5x | +|||
21 | +
- shinyjs::disable(selector = tabs_selector)+ |
|||
193 | -! | +|||
22 | +
- } else if (identical(data_load_status(), "external failed")) {+ #' Resolve the expected bootstrap theme |
|||
194 | -! | +|||
23 | +
- logger::log_debug("srv_teal_module@1 hiding modules tabs.")+ #' @noRd |
|||
195 | -! | +|||
24 | +
- shinyjs::hide("wrapper")+ #' @keywords internal |
|||
196 | +25 |
- }+ get_teal_bs_theme <- function() { |
||
197 | -+ | |||
26 | +4x |
- })+ bs_theme <- getOption("teal.bs_theme") |
||
198 | +27 | |||
199 | -87x | +28 | +4x |
- modules_output <- sapply(+ if (is.null(bs_theme)) { |
200 | -87x | +29 | +1x |
- names(modules$children),+ return(NULL) |
201 | -87x | +|||
30 | +
- function(module_id) {+ } |
|||
202 | -112x | +|||
31 | +
- srv_teal_module(+ |
|||
203 | -112x | +32 | +3x |
- id = module_id,+ if (!checkmate::test_class(bs_theme, "bs_theme")) { |
204 | -112x | +33 | +2x |
- data = data,+ warning( |
205 | -112x | +34 | +2x |
- modules = modules$children[[module_id]],+ "Assertion on 'teal.bs_theme' option value failed: ", |
206 | -112x | +35 | +2x |
- datasets = datasets,+ checkmate::check_class(bs_theme, "bs_theme"), |
207 | -112x | +36 | +2x |
- slices_global = slices_global,+ ". The default Shiny Bootstrap theme will be used." |
208 | -112x | +|||
37 | +
- reporter = reporter,+ ) |
|||
209 | -112x | +38 | +2x |
- is_active = reactive(+ return(NULL) |
210 | -112x | +|||
39 | +
- is_active() &&+ } |
|||
211 | -112x | +|||
40 | +
- input$active_tab == module_id &&+ |
|||
212 | -112x | +41 | +1x |
- identical(data_load_status(), "ok")+ bs_theme |
213 | +42 |
- )+ } |
||
214 | +43 |
- )+ |
||
215 | +44 |
- },+ #' Return parentnames along with datanames. |
||
216 | -87x | +|||
45 | +
- simplify = FALSE+ #' @noRd |
|||
217 | +46 |
- )+ #' @keywords internal |
||
218 | +47 |
-
+ .include_parent_datanames <- function(datanames, join_keys) { |
||
219 | -87x | +48 | +32x |
- modules_output+ ordered_datanames <- datanames |
220 | -+ | |||
49 | +32x |
- })+ for (current in datanames) { |
||
221 | -+ | |||
50 | +62x |
- }+ parents <- character(0L) |
||
222 | -+ | |||
51 | +62x |
-
+ while (length(current) > 0) {+ |
+ ||
52 | +64x | +
+ current <- teal.data::parent(join_keys, current)+ |
+ ||
53 | +64x | +
+ parents <- c(current, parents) |
||
223 | +54 |
- #' @rdname module_teal_module+ }+ |
+ ||
55 | +62x | +
+ ordered_datanames <- c(parents, ordered_datanames) |
||
224 | +56 |
- #' @export+ } |
||
225 | +57 |
- srv_teal_module.teal_module <- function(id,+ + |
+ ||
58 | +32x | +
+ unique(ordered_datanames) |
||
226 | +59 |
- data,+ } |
||
227 | +60 |
- modules,+ |
||
228 | +61 |
- datasets = NULL,+ #' Create a `FilteredData` |
||
229 | +62 |
- slices_global,+ #' |
||
230 | +63 |
- reporter = teal.reporter::Reporter$new(),+ #' Create a `FilteredData` object from a `teal_data` object. |
||
231 | +64 |
- data_load_status = reactive("ok"),+ #' |
||
232 | +65 |
- is_active = reactive(TRUE)) {+ #' @param x (`teal_data`) object |
||
233 | -112x | +|||
66 | +
- logger::log_debug("srv_teal_module.teal_module initializing the module: { deparse1(modules$label) }.")+ #' @param datanames (`character`) vector of data set names to include; must be subset of `names(x)` |
|||
234 | -112x | +|||
67 | +
- moduleServer(id = id, module = function(input, output, session) {+ #' @return A `FilteredData` object. |
|||
235 | -112x | +|||
68 | +
- module_out <- reactiveVal()+ #' @keywords internal |
|||
236 | +69 |
-
+ teal_data_to_filtered_data <- function(x, datanames = names(x)) { |
||
237 | -112x | +70 | +83x |
- active_datanames <- reactive({+ checkmate::assert_class(x, "teal_data") |
238 | -89x | +71 | +83x |
- .resolve_module_datanames(data = data(), modules = modules)+ checkmate::assert_character(datanames, min.chars = 1L, any.missing = FALSE) |
239 | +72 |
- })+ # Otherwise, FilteredData will be created in the modules' scope later |
||
240 | -112x | +73 | +83x |
- if (is.null(datasets)) {+ teal.slice::init_filtered_data( |
241 | -20x | +74 | +83x |
- datasets <- eventReactive(data(), {+ x = Filter(length, sapply(datanames, function(dn) x[[dn]], simplify = FALSE)), |
242 | -16x | +75 | +83x |
- req(inherits(data(), "teal_data"))+ join_keys = teal.data::join_keys(x) |
243 | -16x | +|||
76 | +
- logger::log_debug("srv_teal_module@1 initializing module-specific FilteredData")+ ) |
|||
244 | -16x | +|||
77 | +
- teal_data_to_filtered_data(data(), datanames = active_datanames())+ } |
|||
245 | +78 |
- })+ |
||
246 | +79 |
- }+ |
||
247 | +80 |
-
+ #' Template function for `TealReportCard` creation and customization |
||
248 | +81 |
- # manage module filters on the module level+ #' |
||
249 | +82 |
- # important:+ #' This function generates a report card with a title, |
||
250 | +83 |
- # filter_manager_module_srv needs to be called before filter_panel_srv+ #' an optional description, and the option to append the filter state list. |
||
251 | +84 |
- # Because available_teal_slices is used in FilteredData$srv_available_slices (via srv_filter_panel)+ #' |
||
252 | +85 |
- # and if it is not set, then it won't be available in the srv_filter_panel+ #' @param title (`character(1)`) title of the card (unless overwritten by label) |
||
253 | -112x | +|||
86 | +
- srv_module_filter_manager(modules$label, module_fd = datasets, slices_global = slices_global)+ #' @param label (`character(1)`) label provided by the user when adding the card |
|||
254 | +87 |
-
+ #' @param description (`character(1)`) optional, additional description |
||
255 | -112x | +|||
88 | +
- call_once_when(is_active(), {+ #' @param with_filter (`logical(1)`) flag indicating to add filter state |
|||
256 | -86x | +|||
89 | +
- filtered_teal_data <- srv_filter_data(+ #' @param filter_panel_api (`FilterPanelAPI`) object with API that allows the generation |
|||
257 | -86x | +|||
90 | +
- "filter_panel",+ #' of the filter state in the report |
|||
258 | -86x | +|||
91 | +
- datasets = datasets,+ #' |
|||
259 | -86x | +|||
92 | +
- active_datanames = active_datanames,+ #' @return (`TealReportCard`) populated with a title, description and filter state. |
|||
260 | -86x | +|||
93 | +
- data = data,+ #' |
|||
261 | -86x | +|||
94 | +
- is_active = is_active+ #' @export |
|||
262 | +95 |
- )+ report_card_template <- function(title, label, description = NULL, with_filter, filter_panel_api) { |
||
263 | -86x | +96 | +2x |
- is_transform_failed <- reactiveValues()+ checkmate::assert_string(title) |
264 | -86x | +97 | +2x |
- transformed_teal_data <- srv_transform_teal_data(+ checkmate::assert_string(label) |
265 | -86x | +98 | +2x |
- "data_transform",+ checkmate::assert_string(description, null.ok = TRUE) |
266 | -86x | +99 | +2x |
- data = filtered_teal_data,+ checkmate::assert_flag(with_filter) |
267 | -86x | +100 | +2x |
- transformators = modules$transformators,+ checkmate::assert_class(filter_panel_api, classes = "FilterPanelAPI") |
268 | -86x | +|||
101 | +
- modules = modules,+ |
|||
269 | -86x | +102 | +2x |
- is_transform_failed = is_transform_failed+ card <- teal::TealReportCard$new() |
270 | -+ | |||
103 | +2x |
- )+ title <- if (label == "") title else label |
||
271 | -86x | +104 | +2x |
- any_transform_failed <- reactive({+ card$set_name(title) |
272 | -86x | +105 | +2x |
- any(unlist(reactiveValuesToList(is_transform_failed)))+ card$append_text(title, "header2") |
273 | -+ | |||
106 | +1x |
- })+ if (!is.null(description)) card$append_text(description, "header3") |
||
274 | -+ | |||
107 | +1x |
-
+ if (with_filter) card$append_fs(filter_panel_api$get_filter_state()) |
||
275 | -86x | +108 | +2x |
- observeEvent(any_transform_failed(), {+ card |
276 | -86x | +|||
109 | +
- if (isTRUE(any_transform_failed())) {+ } |
|||
277 | -6x | +|||
110 | +
- shinyjs::hide("teal_module_ui")+ |
|||
278 | -6x | +|||
111 | +
- shinyjs::show("transform_failure_info")+ |
|||
279 | +112 |
- } else {+ #' Check `datanames` in modules |
||
280 | -80x | +|||
113 | +
- shinyjs::show("teal_module_ui")+ #' |
|||
281 | -80x | +|||
114 | +
- shinyjs::hide("transform_failure_info")+ #' These functions check if specified `datanames` in modules match those in the data object, |
|||
282 | +115 |
- }+ #' returning error messages or `TRUE` for successful validation. Two functions return error message |
||
283 | +116 |
- })+ #' in different forms: |
||
284 | +117 |
-
+ #' - `check_modules_datanames` returns `character(1)` for basic assertion usage |
||
285 | -86x | +|||
118 | +
- module_teal_data <- reactive({+ #' - `check_modules_datanames_html` returns `shiny.tag.list` to display it in the app. |
|||
286 | -94x | +|||
119 | +
- req(inherits(transformed_teal_data(), "teal_data"))+ #' |
|||
287 | -88x | +|||
120 | +
- all_teal_data <- transformed_teal_data()+ #' @param modules (`teal_modules`) object |
|||
288 | -88x | +|||
121 | +
- module_datanames <- .resolve_module_datanames(data = all_teal_data, modules = modules)+ #' @param datanames (`character`) names of datasets available in the `data` object |
|||
289 | -88x | +|||
122 | +
- all_teal_data[c(module_datanames, ".raw_data")]+ #' |
|||
290 | +123 |
- })+ #' @return `TRUE` if validation passes, otherwise `character(1)` or `shiny.tag.list` |
||
291 | +124 |
-
+ #' @keywords internal+ |
+ ||
125 | ++ |
+ check_modules_datanames <- function(modules, datanames) { |
||
292 | -86x | +126 | +11x |
- srv_check_module_datanames(+ out <- check_modules_datanames_html(modules, datanames) |
293 | -86x | +127 | +11x |
- "validate_datanames",+ if (inherits(out, "shiny.tag.list")) { |
294 | -86x | +128 | +5x |
- data = module_teal_data,+ out_with_ticks <- gsub("<code>|</code>", "`", toString(out)) |
295 | -86x | +129 | +5x |
- modules = modules+ out_text <- gsub("<[^<>]+>", "", toString(out_with_ticks)) |
296 | -+ | |||
130 | +5x |
- )+ trimws(gsub("[[:space:]]+", " ", out_text)) |
||
297 | +131 |
-
+ } else { |
||
298 | -86x | +132 | +6x |
- summary_table <- srv_data_summary("data_summary", module_teal_data)+ out |
299 | +133 |
-
+ } |
||
300 | +134 |
- # Call modules.+ } |
||
301 | -86x | +|||
135 | +
- if (!inherits(modules, "teal_module_previewer")) {+ |
|||
302 | -86x | +|||
136 | +
- obs_module <- call_once_when(+ #' @rdname check_modules_datanames |
|||
303 | -86x | +|||
137 | +
- !is.null(module_teal_data()),+ check_reserved_datanames <- function(datanames) { |
|||
304 | -86x | +138 | +190x |
- ignoreNULL = TRUE,+ reserved_datanames <- datanames[datanames %in% c("all", ".raw_data")] |
305 | -86x | +139 | +190x |
- handlerExpr = {+ if (length(reserved_datanames) == 0L) { |
306 | -80x | +140 | +184x |
- module_out(.call_teal_module(modules, datasets, module_teal_data, reporter))+ return(NULL) |
307 | +141 |
- }+ } |
||
308 | +142 |
- )+ |
||
309 | -+ | |||
143 | +6x |
- } else {+ tags$span( |
||
310 | -+ | |||
144 | +6x |
- # Report previewer must be initiated on app start for report cards to be included in bookmarks.+ to_html_code_list(reserved_datanames), |
||
311 | -+ | |||
145 | +6x |
- # When previewer is delayed, cards are bookmarked only if previewer has been initiated (visited).+ sprintf( |
||
312 | -! | +|||
146 | +6x |
- module_out(.call_teal_module(modules, datasets, module_teal_data, reporter))+ "%s reserved for internal use. Please avoid using %s as %s.", |
||
313 | -+ | |||
147 | +6x |
- }+ pluralize(reserved_datanames, "is", "are"), |
||
314 | -+ | |||
148 | +6x |
- })+ pluralize(reserved_datanames, "it", "them"), |
||
315 | -+ | |||
149 | +6x |
-
+ pluralize(reserved_datanames, "a dataset name", "dataset names") |
||
316 | -112x | +|||
150 | +
- module_out+ ) |
|||
317 | +151 |
- })+ ) |
||
318 | +152 |
} |
||
319 | +153 | |||
320 | +154 |
- # This function calls a module server function.+ #' @rdname check_modules_datanames |
||
321 | +155 |
- .call_teal_module <- function(modules, datasets, data, reporter) {+ check_modules_datanames_html <- function(modules, datanames) { |
||
322 | -80x | +156 | +190x |
- assert_reactive(data)+ check_datanames <- check_modules_datanames_recursive(modules, datanames) |
323 | -+ | |||
157 | +190x |
-
+ show_module_info <- inherits(modules, "teal_modules") # used in two contexts - module and app |
||
324 | +158 |
- # collect arguments to run teal_module+ |
||
325 | -80x | +159 | +190x |
- args <- c(list(id = "module"), modules$server_args)+ reserved_datanames <- check_reserved_datanames(datanames)+ |
+
160 | ++ | + | ||
326 | -80x | +161 | +190x |
- if (is_arg_used(modules$server, "reporter")) {+ if (!length(check_datanames)) { |
327 | -1x | +162 | +172x |
- args <- c(args, list(reporter = reporter))+ out <- if (is.null(reserved_datanames)) { |
328 | -+ | |||
163 | +166x |
- }+ TRUE |
||
329 | +164 |
-
+ } else { |
||
330 | -80x | +165 | +6x |
- if (is_arg_used(modules$server, "datasets")) {+ shiny::tagList(reserved_datanames) |
331 | -1x | +|||
166 | +
- args <- c(args, datasets = datasets())+ } |
|||
332 | -1x | +167 | +172x |
- warning("datasets argument is not reactive and therefore it won't be updated when data is refreshed.")+ return(out) |
333 | +168 |
} |
||
334 | -+ | |||
169 | +18x |
-
+ shiny::tagList( |
||
335 | -80x | +170 | +18x |
- if (is_arg_used(modules$server, "data")) {+ reserved_datanames, |
336 | -76x | +171 | +18x |
- args <- c(args, data = list(data))+ lapply( |
337 | -+ | |||
172 | +18x |
- }+ check_datanames, |
||
338 | -+ | |||
173 | +18x |
-
+ function(mod) { |
||
339 | -80x | +174 | +18x |
- if (is_arg_used(modules$server, "filter_panel_api")) {+ tagList( |
340 | -1x | +175 | +18x |
- args <- c(args, filter_panel_api = teal.slice::FilterPanelAPI$new(datasets()))+ tags$span( |
341 | -+ | |||
176 | +18x |
- }+ tags$span(pluralize(mod$missing_datanames, "Dataset")), |
||
342 | -+ | |||
177 | +18x |
-
+ to_html_code_list(mod$missing_datanames), |
||
343 | -80x | +178 | +18x |
- if (is_arg_used(modules$server, "id")) {+ tags$span( |
344 | -80x | +179 | +18x |
- do.call(modules$server, args)+ sprintf( |
345 | -+ | |||
180 | +18x |
- } else {+ "%s missing%s.", |
||
346 | -! | +|||
181 | +18x |
- do.call(callModule, c(args, list(module = modules$server)))+ pluralize(mod$missing_datanames, "is", "are"), |
||
347 | -+ | |||
182 | +18x |
- }+ if (show_module_info) sprintf(" for module '%s'", mod$label) else "" |
||
348 | +183 |
- }+ ) |
||
349 | +184 |
-
+ ) |
||
350 | +185 |
- .resolve_module_datanames <- function(data, modules) {+ ), |
||
351 | -177x | +186 | +18x |
- stopifnot("data must be teal_data object." = inherits(data, "teal_data"))+ if (length(datanames) >= 1) { |
352 | -177x | +187 | +16x |
- if (is.null(modules$datanames) || identical(modules$datanames, "all")) {+ tagList( |
353 | -145x | -
- names(data)- |
- ||
354 | -+ | 188 | +16x |
- } else {+ tags$span(pluralize(datanames, "Dataset")), |
355 | -32x | +189 | +16x |
- intersect(+ tags$span("available in data:"), |
356 | -32x | +190 | +16x |
- names(data), # Keep topological order from teal.data::names()+ tagList( |
357 | -32x | -
- .include_parent_datanames(modules$datanames, teal.data::join_keys(data))- |
- ||
358 | -- |
- )- |
- ||
359 | -- |
- }- |
- ||
360 | -+ | 191 | +16x |
- }+ tags$span( |
361 | -+ | |||
192 | +16x |
-
+ to_html_code_list(datanames), |
||
362 | -+ | |||
193 | +16x |
- #' Calls expression when condition is met+ tags$span(".", .noWS = "outside"), |
||
363 | -+ | |||
194 | +16x |
- #'+ .noWS = c("outside") |
||
364 | +195 |
- #' Function postpones `handlerExpr` to the moment when `eventExpr` (condition) returns `TRUE`,+ ) |
||
365 | +196 |
- #' otherwise nothing happens.+ ) |
||
366 | +197 |
- #' @param eventExpr A (quoted or unquoted) logical expression that represents the event;+ ) |
||
367 | +198 |
- #' this can be a simple reactive value like input$click, a call to a reactive expression+ } else { |
||
368 | -+ | |||
199 | +2x |
- #' like dataset(), or even a complex expression inside curly braces.+ tags$span("No datasets are available in data.") |
||
369 | +200 |
- #' @param ... additional arguments passed to `observeEvent` with the exception of `eventExpr` that is not allowed.+ }, |
||
370 | -+ | |||
201 | +18x |
- #' @inheritParams shiny::observeEvent+ tags$br(.noWS = "before") |
||
371 | +202 |
- #'+ ) |
||
372 | +203 |
- #' @return An observer.+ } |
||
373 | +204 |
- #'+ ) |
||
374 | +205 |
- #' @keywords internal+ ) |
||
375 | +206 |
- call_once_when <- function(eventExpr, # nolint: object_name.+ } |
||
376 | +207 |
- handlerExpr, # nolint: object_name.+ |
||
377 | +208 |
- event.env = parent.frame(), # nolint: object_name.+ #' Recursively checks modules and returns list for every datanames mismatch between module and data |
||
378 | +209 |
- handler.env = parent.frame(), # nolint: object_name.+ #' @noRd |
||
379 | +210 |
- ...) {+ check_modules_datanames_recursive <- function(modules, datanames) { # nolint: object_name_length |
||
380 | -198x | +211 | +296x |
- event_quo <- rlang::new_quosure(substitute(eventExpr), env = event.env)+ checkmate::assert_multi_class(modules, c("teal_module", "teal_modules")) |
381 | -198x | -
- handler_quo <- rlang::new_quosure(substitute(handlerExpr), env = handler.env)- |
- ||
382 | -+ | 212 | +296x |
-
+ checkmate::assert_character(datanames) |
383 | -+ | |||
213 | +296x |
- # When `condExpr` is TRUE, then `handlerExpr` is evaluated once.+ if (inherits(modules, "teal_modules")) { |
||
384 | -198x | +214 | +86x |
- activator <- reactive({+ unlist( |
385 | -198x | +215 | +86x |
- if (isTRUE(rlang::eval_tidy(event_quo))) {+ lapply(modules$children, check_modules_datanames_recursive, datanames = datanames), |
386 | -166x | +216 | +86x |
- TRUE+ recursive = FALSE |
387 | +217 |
- }+ ) |
||
388 | +218 |
- })+ } else { |
||
389 | -+ | |||
219 | +210x |
-
+ missing_datanames <- setdiff(modules$datanames, c("all", datanames)) |
||
390 | -198x | +220 | +210x |
- observeEvent(+ if (length(missing_datanames)) { |
391 | -198x | +221 | +18x |
- eventExpr = activator(),+ list(list( |
392 | -198x | +222 | +18x |
- once = TRUE,+ label = modules$label, |
393 | -198x | +223 | +18x |
- handlerExpr = rlang::eval_tidy(handler_quo),+ missing_datanames = missing_datanames |
394 | +224 |
- ...+ )) |
||
395 | +225 |
- )+ } |
||
396 | +226 |
- }+ } |
1 | +227 |
- #' Filter state snapshot management+ } |
||
2 | +228 |
- #'+ |
||
3 | +229 |
- #' Capture and restore snapshots of the global (app) filter state.+ #' Convert character vector to html code separated with commas and "and" |
||
4 | +230 |
- #'+ #' @noRd |
||
5 | +231 |
- #' This module introduces snapshots: stored descriptions of the filter state of the entire application.+ to_html_code_list <- function(x) { |
||
6 | -+ | |||
232 | +40x |
- #' Snapshots allow the user to save the current filter state of the application for later use in the session,+ checkmate::assert_character(x) |
||
7 | -+ | |||
233 | +40x |
- #' as well as to save it to file in order to share it with an app developer or other users,+ do.call( |
||
8 | -+ | |||
234 | +40x |
- #' who in turn can upload it to their own session.+ tagList, |
||
9 | -+ | |||
235 | +40x |
- #'+ lapply(seq_along(x), function(.ix) { |
||
10 | -+ | |||
236 | +56x |
- #' The snapshot manager is accessed with the camera icon in the tabset bar.+ tagList( |
||
11 | -+ | |||
237 | +56x |
- #' At the beginning of a session it presents three icons: a camera, an upload, and an circular arrow.+ tags$code(x[.ix]), |
||
12 | -+ | |||
238 | +56x |
- #' Clicking the camera captures a snapshot, clicking the upload adds a snapshot from a file+ if (.ix != length(x)) {+ |
+ ||
239 | +1x | +
+ if (.ix == length(x) - 1) tags$span(" and ") else tags$span(", ", .noWS = "before") |
||
13 | +240 |
- #' and applies the filter states therein, and clicking the arrow resets initial application state.+ } |
||
14 | +241 |
- #' 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 | +242 |
- #'+ }) |
||
16 | +243 |
- #' @section Server logic:+ ) |
||
17 | +244 |
- #' Snapshots are basically `teal_slices` objects, however, since each module is served by a separate instance+ } |
||
18 | +245 |
- #' of `FilteredData` and these objects require shared state, `teal_slice` is a `reactiveVal` so `teal_slices`+ |
||
19 | +246 |
- #' cannot be stored as is. Therefore, `teal_slices` are reversibly converted to a list of lists representation+ |
||
20 | +247 |
- #' (attributes are maintained).+ #' Check `datanames` in filters |
||
21 | +248 |
#' |
||
22 | +249 |
- #' Snapshots are stored in a `reactiveVal` as a named list.+ #' This function checks whether `datanames` in filters correspond to those in `data`, |
||
23 | +250 |
- #' The first snapshot is the initial state of the application and the user can add a snapshot whenever they see fit.+ #' returning character vector with error messages or `TRUE` if all checks pass. |
||
24 | +251 |
#' |
||
25 | +252 |
- #' For every snapshot except the initial one, a piece of UI is generated that contains+ #' @param filters (`teal_slices`) object |
||
26 | +253 |
- #' the snapshot name, a select button to restore that snapshot, and a save button to save it to a file.+ #' @param datanames (`character`) names of datasets available in the `data` object |
||
27 | +254 |
- #' The initial snapshot is restored by a separate "reset" button.+ #' |
||
28 | +255 |
- #' It cannot be saved directly but a user is welcome to capture the initial state as a snapshot and save that.+ #' @return A `character(1)` containing error message or TRUE if validation passes. |
||
29 | +256 |
- #'+ #' @keywords internal |
||
30 | +257 |
- #' @section Snapshot mechanics:+ check_filter_datanames <- function(filters, datanames) { |
||
31 | -+ | |||
258 | +86x |
- #' When a snapshot is captured, the user is prompted to name it.+ checkmate::assert_class(filters, "teal_slices") |
||
32 | -+ | |||
259 | +86x |
- #' Names are displayed as is but since they are used to create button ids,+ checkmate::assert_character(datanames) |
||
33 | +260 |
- #' under the hood they are converted to syntactically valid strings.+ |
||
34 | +261 |
- #' New snapshot names are validated so that their valid versions are unique.+ # check teal_slices against datanames |
||
35 | -+ | |||
262 | +86x |
- #' Leading and trailing white space is trimmed.+ out <- unlist(sapply( |
||
36 | -+ | |||
263 | +86x |
- #'+ filters, function(filter) { |
||
37 | -+ | |||
264 | +24x |
- #' The module can read the global state of the application from `slices_global` and `mapping_matrix`.+ dataname <- shiny::isolate(filter$dataname) |
||
38 | -+ | |||
265 | +24x |
- #' The former provides a list of all existing `teal_slice`s and the latter says which slice is active in which module.+ if (!dataname %in% datanames) { |
||
39 | -+ | |||
266 | +3x |
- #' Once a name has been accepted, `slices_global` is converted to a list of lists - a snapshot.+ sprintf( |
||
40 | -- |
- #' The snapshot contains the `mapping` attribute of the initial application state+ | ||
267 | +3x | +
+ "- Filter '%s' refers to dataname not available in 'data':\n %s not in (%s)", |
||
41 | -+ | |||
268 | +3x |
- #' (or one that has been restored), which may not reflect the current one,+ shiny::isolate(filter$id), |
||
42 | -+ | |||
269 | +3x |
- #' so `mapping_matrix` is transformed to obtain the current mapping, i.e. a list that,+ dQuote(dataname, q = FALSE), |
||
43 | -+ | |||
270 | +3x |
- #' when passed to the `mapping` argument of [teal_slices()], would result in the current mapping.+ toString(dQuote(datanames, q = FALSE)) |
||
44 | +271 |
- #' This is substituted as the snapshot's `mapping` attribute and the snapshot is added to the snapshot list.+ ) |
||
45 | +272 |
- #'+ } |
||
46 | +273 |
- #' To restore app state, a snapshot is retrieved from storage and rebuilt into a `teal_slices` object.+ } |
||
47 | +274 |
- #' Then state of all `FilteredData` objects (provided in `datasets`) is cleared+ )) |
||
48 | +275 |
- #' and set anew according to the `mapping` attribute of the snapshot.+ |
||
49 | +276 |
- #' The snapshot is then set as the current content of `slices_global`.+ |
||
50 | -+ | |||
277 | +86x |
- #'+ if (length(out)) { |
||
51 | -+ | |||
278 | +3x |
- #' To save a snapshot, the snapshot is retrieved and reassembled just like for restoring,+ paste(out, collapse = "\n") |
||
52 | +279 |
- #' and then saved to file with [slices_store()].+ } else { |
||
53 | -+ | |||
280 | +83x |
- #'+ TRUE |
||
54 | +281 |
- #' When a snapshot is uploaded, it will first be added to storage just like a newly created one,+ } |
||
55 | +282 |
- #' and then used to restore app state much like a snapshot taken from storage.+ } |
||
56 | +283 |
- #' Upon clicking the upload icon the user will be prompted for a file to upload+ |
||
57 | +284 |
- #' and may choose to name the new snapshot. The name defaults to the name of the file (the extension is dropped)+ #' Function for validating the title parameter of `teal::init` |
||
58 | +285 |
- #' and normal naming rules apply. Loading the file yields a `teal_slices` object,+ #' |
||
59 | +286 |
- #' which is disassembled for storage and used directly for restoring app state.+ #' Checks if the input of the title from `teal::init` will create a valid title and favicon tag. |
||
60 | +287 |
- #'+ #' @param shiny_tag (`shiny.tag`) Object to validate for a valid title. |
||
61 | +288 |
- #' @section Transferring snapshots:+ #' @keywords internal |
||
62 | +289 |
- #' Snapshots uploaded from disk should only be used in the same application they come from,+ validate_app_title_tag <- function(shiny_tag) { |
||
63 | -+ | |||
290 | +7x |
- #' _i.e._ an application that uses the same data and the same modules.+ checkmate::assert_class(shiny_tag, "shiny.tag") |
||
64 | -+ | |||
291 | +7x |
- #' To ensure this is the case, `init` stamps `teal_slices` with an app id that is stored in the `app_id` attribute of+ checkmate::assert_true(shiny_tag$name == "head") |
||
65 | -+ | |||
292 | +6x |
- #' a `teal_slices` object. When a snapshot is restored from file, its `app_id` is compared to that+ child_names <- vapply(shiny_tag$children, `[[`, character(1L), "name") |
||
66 | -+ | |||
293 | +6x |
- #' of the current app state and only if the match is the snapshot admitted to the session.+ checkmate::assert_subset(c("title", "link"), child_names, .var.name = "child tags") |
||
67 | -+ | |||
294 | +4x |
- #'+ rel_attr <- shiny_tag$children[[which(child_names == "link")]]$attribs$rel |
||
68 | -+ | |||
295 | +4x |
- #' @section Bookmarks:+ checkmate::assert_subset( |
||
69 | -+ | |||
296 | +4x |
- #' An `onBookmark` callback creates a snapshot of the current filter state.+ rel_attr, |
||
70 | -+ | |||
297 | +4x |
- #' This is done on the app session, not the module session.+ c("icon", "shortcut icon"), |
||
71 | -+ | |||
298 | +4x |
- #' (The snapshot will be retrieved by `module_teal` in order to set initial app state in a restored app.)+ .var.name = "Link tag's rel attribute", |
||
72 | -+ | |||
299 | +4x |
- #' Then that snapshot, and the previous snapshot history are dumped into the `values.rds` file in `<bookmark_dir>`.+ empty.ok = FALSE |
||
73 | +300 |
- #'+ ) |
||
74 | +301 |
- #' @param id (`character(1)`) `shiny` module instance id.+ } |
||
75 | +302 |
- #' @param slices_global (`reactiveVal`) that contains a `teal_slices` object+ |
||
76 | +303 |
- #' containing all `teal_slice`s existing in the app, both active and inactive.+ #' Build app title with favicon |
||
77 | +304 |
#' |
||
78 | +305 |
- #' @return `list` containing the snapshot history, where each element is an unlisted `teal_slices` object.+ #' A helper function to create the browser title along with a logo. |
||
79 | +306 |
#' |
||
80 | +307 |
- #' @name module_snapshot_manager+ #' @param title (`character`) The browser title for the `teal` app. |
||
81 | +308 |
- #' @rdname module_snapshot_manager+ #' @param favicon (`character`) The path for the icon for the title. |
||
82 | +309 |
- #'+ #' The image/icon path can be remote or the static path accessible by `shiny`, like the `www/` |
||
83 | +310 |
- #' @author Aleksander Chlebowski+ #' |
||
84 | +311 |
- #' @keywords internal+ #' @return A `shiny.tag` containing the element that adds the title and logo to the `shiny` app. |
||
85 | +312 |
- NULL+ #' @export |
||
86 | +313 |
-
+ build_app_title <- function( |
||
87 | +314 |
- #' @rdname module_snapshot_manager+ title = "teal app", |
||
88 | +315 |
- ui_snapshot_manager_panel <- function(id) {+ favicon = "https://raw.githubusercontent.com/insightsengineering/hex-stickers/main/PNG/nest.png") { |
||
89 | -! | +|||
316 | +15x |
- ns <- NS(id)+ checkmate::assert_string(title, null.ok = TRUE) |
||
90 | -! | +|||
317 | +15x |
- tags$button(+ checkmate::assert_string(favicon, null.ok = TRUE) |
||
91 | -! | +|||
318 | +15x |
- id = ns("show_snapshot_manager"),+ tags$head( |
||
92 | -! | +|||
319 | +15x |
- class = "btn action-button wunder_bar_button",+ tags$title(title), |
||
93 | -! | +|||
320 | +15x |
- title = "View filter mapping",+ tags$link( |
||
94 | -! | +|||
321 | +15x |
- suppressMessages(icon("fas fa-camera"))+ rel = "icon", |
||
95 | -+ | |||
322 | +15x |
- )+ href = favicon,+ |
+ ||
323 | +15x | +
+ sizes = "any" |
||
96 | +324 |
- }+ ) |
||
97 | +325 |
-
+ ) |
||
98 | +326 |
- #' @rdname module_snapshot_manager+ } |
||
99 | +327 |
- srv_snapshot_manager_panel <- function(id, slices_global) {+ |
||
100 | -87x | +|||
328 | +
- moduleServer(id, function(input, output, session) {+ #' Application ID |
|||
101 | -87x | +|||
329 | +
- logger::log_debug("srv_snapshot_manager_panel initializing")+ #' |
|||
102 | -87x | +|||
330 | +
- setBookmarkExclude(c("show_snapshot_manager"))+ #' Creates App ID used to match filter snapshots to application. |
|||
103 | -87x | +|||
331 | +
- observeEvent(input$show_snapshot_manager, {+ #' |
|||
104 | -! | +|||
332 | +
- logger::log_debug("srv_snapshot_manager_panel@1 show_snapshot_manager button has been clicked.")+ #' Calculate app ID that will be used to stamp filter state snapshots. |
|||
105 | -! | +|||
333 | +
- showModal(+ #' App ID is a hash of the app's data and modules. |
|||
106 | -! | +|||
334 | +
- modalDialog(+ #' See "transferring snapshots" section in ?snapshot. |
|||
107 | -! | +|||
335 | +
- ui_snapshot_manager(session$ns("module")),+ #' |
|||
108 | -! | +|||
336 | +
- class = "snapshot_manager_modal",+ #' @param data (`teal_data` or `teal_data_module`) as accepted by `init` |
|||
109 | -! | +|||
337 | +
- size = "m",+ #' @param modules (`teal_modules`) object as accepted by `init` |
|||
110 | -! | +|||
338 | +
- footer = NULL,+ #' |
|||
111 | -! | +|||
339 | +
- easyClose = TRUE+ #' @return A single character string. |
|||
112 | +340 |
- )+ #' |
||
113 | +341 |
- )+ #' @keywords internal |
||
114 | +342 |
- })+ create_app_id <- function(data, modules) { |
||
115 | -87x | +343 | +23x |
- srv_snapshot_manager("module", slices_global = slices_global)+ checkmate::assert_multi_class(data, c("teal_data", "teal_data_module")) |
116 | -+ | |||
344 | +22x |
- })+ checkmate::assert_class(modules, "teal_modules") |
||
117 | +345 |
- }+ |
||
118 | -+ | |||
346 | +21x |
-
+ data <- if (inherits(data, "teal_data")) { |
||
119 | -+ | |||
347 | +19x |
- #' @rdname module_snapshot_manager+ as.list(data) |
||
120 | -+ | |||
348 | +21x |
- ui_snapshot_manager <- function(id) {+ } else if (inherits(data, "teal_data_module")) { |
||
121 | -! | +|||
349 | +2x |
- ns <- NS(id)+ deparse1(body(data$server)) |
||
122 | -! | +|||
350 | +
- tags$div(+ } |
|||
123 | -! | +|||
351 | +21x |
- class = "manager_content",+ modules <- lapply(modules, defunction) |
||
124 | -! | -
- tags$div(- |
- ||
125 | -! | -
- class = "manager_table_row",- |
- ||
126 | -! | -
- tags$span(tags$b("Snapshot manager")),- |
- ||
127 | -! | -
- 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 | -! | +|||
352 | +
- actionLink(ns("snapshot_reset"), label = NULL, icon = icon("fas fa-undo"), title = "reset initial state"),+ |
|||
130 | -! | +|||
353 | +21x |
- NULL+ rlang::hash(list(data = data, modules = modules)) |
||
131 | +354 |
- ),- |
- ||
132 | -! | -
- uiOutput(ns("snapshot_list"))+ } |
||
133 | +355 |
- )+ |
||
134 | +356 |
- }+ #' Go through list and extract bodies of encountered functions as string, recursively. |
||
135 | +357 |
-
+ #' @keywords internal |
||
136 | +358 |
- #' @rdname module_snapshot_manager+ #' @noRd |
||
137 | +359 |
- srv_snapshot_manager <- function(id, slices_global) {+ defunction <- function(x) { |
||
138 | -87x | +360 | +297x |
- checkmate::assert_character(id)+ if (is.list(x)) { |
139 | -+ | |||
361 | +121x |
-
+ lapply(x, defunction) |
||
140 | -87x | +362 | +176x |
- moduleServer(id, function(input, output, session) {+ } else if (is.function(x)) { |
141 | -87x | +363 | +54x |
- logger::log_debug("srv_snapshot_manager initializing")+ deparse1(body(x)) |
142 | +364 |
-
+ } else {+ |
+ ||
365 | +122x | +
+ x |
||
143 | +366 |
- # Set up bookmarking callbacks ----+ } |
||
144 | +367 |
- # Register bookmark exclusions (all buttons and text fields).+ } |
||
145 | -87x | +|||
368 | +
- setBookmarkExclude(c(+ |
|||
146 | -87x | +|||
369 | +
- "snapshot_add", "snapshot_load", "snapshot_reset",+ #' Get unique labels |
|||
147 | -87x | +|||
370 | +
- "snapshot_name_accept", "snaphot_file_accept",+ #' |
|||
148 | -87x | +|||
371 | +
- "snapshot_name", "snapshot_file"+ #' Get unique labels for the modules to avoid namespace conflicts. |
|||
149 | +372 |
- ))+ #' |
||
150 | +373 |
- # Add snapshot history to bookmark.+ #' @param labels (`character`) vector of labels |
||
151 | -87x | +|||
374 | +
- session$onBookmark(function(state) {+ #' |
|||
152 | -! | +|||
375 | +
- logger::log_debug("srv_snapshot_manager@onBookmark: storing snapshot and bookmark history")+ #' @return (`character`) vector of unique labels |
|||
153 | -! | +|||
376 | +
- state$values$snapshot_history <- snapshot_history() # isolate this?+ #' |
|||
154 | +377 |
- })+ #' @keywords internal |
||
155 | +378 |
-
+ get_unique_labels <- function(labels) { |
||
156 | -87x | +379 | +141x |
- ns <- session$ns+ make.unique(gsub("[^[:alnum:]]", "_", tolower(labels)), sep = "_") |
157 | +380 |
-
+ } |
||
158 | +381 |
- # Track global filter states ----- |
- ||
159 | -87x | -
- snapshot_history <- reactiveVal({+ |
||
160 | +382 |
- # Restore directly from bookmarked state, if applicable.+ #' @keywords internal |
||
161 | -87x | +|||
383 | +
- restoreValue(+ #' @noRd |
|||
162 | -87x | +384 | +4x |
- ns("snapshot_history"),+ pasten <- function(...) paste0(..., "\n") |
163 | -87x | +|||
385 | +
- list("Initial application state" = shiny::isolate(as.list(slices_global$all_slices(), recursive = TRUE)))+ |
|||
164 | +386 |
- )+ #' Convert character list to human readable html with commas and "and" |
||
165 | +387 |
- })+ #' @noRd |
||
166 | +388 |
-
+ paste_datanames_character <- function(x, |
||
167 | +389 |
- # Snapshot current application state ----+ tags = list(span = shiny::tags$span, code = shiny::tags$code), |
||
168 | +390 |
- # Name snaphsot.+ tagList = shiny::tagList) { # nolint: object_name. |
||
169 | -87x | +|||
391 | +! |
- observeEvent(input$snapshot_add, {+ checkmate::assert_character(x) |
||
170 | +392 | ! |
- logger::log_debug("srv_snapshot_manager: snapshot_add button clicked")+ do.call( |
|
171 | +393 | ! |
- showModal(+ tagList, |
|
172 | +394 | ! |
- modalDialog(+ lapply(seq_along(x), function(.ix) { |
|
173 | +395 | ! |
- textInput(ns("snapshot_name"), "Name the snapshot", width = "100%", placeholder = "Meaningful, unique name"),+ tagList( |
|
174 | +396 | ! |
- footer = tagList(+ tags$code(x[.ix]), |
|
175 | +397 | ! |
- actionButton(ns("snapshot_name_accept"), "Accept", icon = icon("far fa-thumbs-up")),+ if (.ix != length(x)) { |
|
176 | +398 | ! |
- modalButton(label = "Cancel", icon = icon("far fa-thumbs-down"))+ tags$span(if (.ix == length(x) - 1) " and " else ", ") |
|
177 | +399 |
- ),+ } |
||
178 | -! | +|||
400 | +
- size = "s"+ ) |
|||
179 | +401 |
- )+ }) |
||
180 | +402 |
- )+ ) |
||
181 | +403 |
- })+ } |
||
182 | +404 |
- # Store snaphsot.+ |
||
183 | -87x | +|||
405 | +
- observeEvent(input$snapshot_name_accept, {+ #' Build datanames error string for error message |
|||
184 | -! | +|||
406 | +
- logger::log_debug("srv_snapshot_manager: snapshot_name_accept button clicked")+ #' |
|||
185 | -! | +|||
407 | +
- snapshot_name <- trimws(input$snapshot_name)+ #' tags and tagList are overwritten in arguments allowing to create strings for |
|||
186 | -! | +|||
408 | +
- if (identical(snapshot_name, "")) {+ #' logging purposes |
|||
187 | -! | +|||
409 | +
- logger::log_debug("srv_snapshot_manager: snapshot name rejected")+ #' @noRd |
|||
188 | -! | +|||
410 | +
- showNotification(+ build_datanames_error_message <- function(label = NULL, |
|||
189 | -! | +|||
411 | +
- "Please name the snapshot.",+ datanames, |
|||
190 | -! | +|||
412 | +
- type = "message"+ extra_datanames, |
|||
191 | +413 |
- )+ tags = list(span = shiny::tags$span, code = shiny::tags$code),+ |
+ ||
414 | ++ |
+ tagList = shiny::tagList) { # nolint: object_name. |
||
192 | +415 | ! |
- updateTextInput(inputId = "snapshot_name", value = "", placeholder = "Meaningful, unique name")+ tags$span( |
|
193 | +416 | ! |
- } else if (is.element(make.names(snapshot_name), make.names(names(snapshot_history())))) {+ tags$span(pluralize(extra_datanames, "Dataset")), |
|
194 | +417 | ! |
- logger::log_debug("srv_snapshot_manager: snapshot name rejected")+ paste_datanames_character(extra_datanames, tags, tagList), |
|
195 | +418 | ! |
- showNotification(+ tags$span( |
|
196 | +419 | ! |
- "This name is in conflict with other snapshot names. Please choose a different one.",+ sprintf( |
|
197 | +420 | ! |
- type = "message"+ "%s missing%s", |
|
198 | -+ | |||
421 | +! |
- )+ pluralize(extra_datanames, "is", "are"), |
||
199 | +422 | ! |
- updateTextInput(inputId = "snapshot_name", value = "", placeholder = "Meaningful, unique name")+ if (is.null(label)) "" else sprintf(" for tab '%s'", label) |
|
200 | +423 |
- } else {+ )+ |
+ ||
424 | ++ |
+ ), |
||
201 | +425 | ! |
- logger::log_debug("srv_snapshot_manager: snapshot name accepted, adding snapshot")+ if (length(datanames) >= 1) { |
|
202 | +426 | ! |
- snapshot <- as.list(slices_global$all_slices(), recursive = TRUE)+ tagList( |
|
203 | +427 | ! |
- snapshot_update <- c(snapshot_history(), list(snapshot))+ tags$span(pluralize(datanames, "Dataset")), |
|
204 | +428 | ! |
- names(snapshot_update)[length(snapshot_update)] <- snapshot_name+ tags$span("available in data:"), |
|
205 | +429 | ! |
- snapshot_history(snapshot_update)+ tagList( |
|
206 | +430 | ! |
- removeModal()+ tags$span( |
|
207 | -+ | |||
431 | +! |
- # Reopen filter manager modal by clicking button in the main application.+ paste_datanames_character(datanames, tags, tagList), |
||
208 | +432 | ! |
- shinyjs::click(id = "teal-wunder_bar-show_snapshot_manager", asis = TRUE)+ tags$span(".", .noWS = "outside"), |
|
209 | -+ | |||
433 | +! |
- }+ .noWS = c("outside") |
||
210 | +434 |
- })+ ) |
||
211 | +435 |
-
+ ) |
||
212 | +436 |
- # Upload a snapshot file ----+ ) |
||
213 | +437 |
- # Select file.+ } else { |
||
214 | -87x | +|||
438 | +! |
- observeEvent(input$snapshot_load, {+ tags$span("No datasets are available in data.") |
||
215 | -! | +|||
439 | +
- logger::log_debug("srv_snapshot_manager: snapshot_load button clicked")+ } |
|||
216 | -! | +|||
440 | +
- showModal(+ ) |
|||
217 | -! | +|||
441 | +
- modalDialog(+ } |
|||
218 | -! | +|||
442 | +
- fileInput(ns("snapshot_file"), "Choose snapshot file", accept = ".json", width = "100%"),+ |
|||
219 | -! | +|||
443 | +
- textInput(+ #' Smart `rbind` |
|||
220 | -! | +|||
444 | +
- ns("snapshot_name"),+ #' |
|||
221 | -! | +|||
445 | +
- "Name the snapshot (optional)",+ #' Combine `data.frame` objects which have different columns |
|||
222 | -! | +|||
446 | +
- width = "100%",+ #' |
|||
223 | -! | +|||
447 | +
- placeholder = "Meaningful, unique name"+ #' @param ... (`data.frame`) |
|||
224 | +448 |
- ),+ #' @keywords internal |
||
225 | -! | +|||
449 | +
- footer = tagList(+ .smart_rbind <- function(...) { |
|||
226 | -! | +|||
450 | +89x |
- actionButton(ns("snaphot_file_accept"), "Accept", icon = icon("far fa-thumbs-up")),+ dots <- list(...) |
||
227 | -! | +|||
451 | +89x |
- modalButton(label = "Cancel", icon = icon("far fa-thumbs-down"))+ checkmate::assert_list(dots, "data.frame", .var.name = "...")+ |
+ ||
452 | +89x | +
+ Reduce(+ |
+ ||
453 | +89x | +
+ x = dots,+ |
+ ||
454 | +89x | +
+ function(x, y) {+ |
+ ||
455 | +72x | +
+ all_columns <- union(colnames(x), colnames(y))+ |
+ ||
456 | +72x | +
+ x[setdiff(all_columns, colnames(x))] <- NA+ |
+ ||
457 | +72x | +
+ y[setdiff(all_columns, colnames(y))] <- NA+ |
+ ||
458 | +72x | +
+ rbind(x, y) |
||
228 | +459 |
- )+ } |
||
229 | +460 |
- )+ ) |
||
230 | +461 |
- )+ } |
||
231 | +462 |
- })+ |
||
232 | +463 |
- # Store new snapshot to list and restore filter states.+ #' Pluralize a word depending on the size of the input+ |
+ ||
464 | ++ |
+ #'+ |
+ ||
465 | ++ |
+ #' @param x (`object`) to check length for plural.+ |
+ ||
466 | ++ |
+ #' @param singular (`character`) singular form of the word.+ |
+ ||
467 | ++ |
+ #' @param plural (optional `character`) plural form of the word. If not given an "s"+ |
+ ||
468 | ++ |
+ #' is added to the singular form.+ |
+ ||
469 | ++ |
+ #'+ |
+ ||
470 | ++ |
+ #' @return A `character` that correctly represents the size of the `x` argument.+ |
+ ||
471 | ++ |
+ #' @keywords internal+ |
+ ||
472 | ++ |
+ pluralize <- function(x, singular, plural = NULL) { |
||
233 | -87x | +473 | +70x |
- observeEvent(input$snaphot_file_accept, {+ checkmate::assert_string(singular) |
234 | -! | +|||
474 | +70x |
- logger::log_debug("srv_snapshot_manager: snapshot_file_accept button clicked")+ checkmate::assert_string(plural, null.ok = TRUE) |
||
235 | -! | +|||
475 | +70x |
- snapshot_name <- trimws(input$snapshot_name)+ if (length(x) == 1L) { # Zero length object should use plural form. |
||
236 | -! | +|||
476 | +42x |
- if (identical(snapshot_name, "")) {+ singular |
||
237 | -! | +|||
477 | +
- logger::log_debug("srv_snapshot_manager: no snapshot name provided, naming after file")+ } else { |
|||
238 | -! | +|||
478 | +28x |
- snapshot_name <- tools::file_path_sans_ext(input$snapshot_file$name)+ if (is.null(plural)) {+ |
+ ||
479 | +12x | +
+ sprintf("%ss", singular) |
||
239 | +480 |
- }+ } else { |
||
240 | -! | +|||
481 | +16x |
- if (is.element(make.names(snapshot_name), make.names(names(snapshot_history())))) {+ plural |
||
241 | -! | +|||
482 | +
- logger::log_debug("srv_snapshot_manager: snapshot name rejected")+ } |
|||
242 | -! | +|||
483 | +
- showNotification(+ } |
|||
243 | -! | +|||
484 | +
- "This name is in conflict with other snapshot names. Please choose a different one.",+ } |
|||
244 | -! | +
1 | +
- type = "message"+ setOldClass("teal_module") |
||
245 | +2 |
- )+ setOldClass("teal_modules") |
|
246 | -! | +||
3 | +
- updateTextInput(inputId = "snapshot_name", value = "", placeholder = "Meaningful, unique name")+ |
||
247 | +4 |
- } else {+ #' Create `teal_module` and `teal_modules` objects |
|
248 | +5 |
- # Restore snapshot and verify app compatibility.+ #' |
|
249 | -! | +||
6 | +
- logger::log_debug("srv_snapshot_manager: snapshot name accepted, loading snapshot")+ #' @description |
||
250 | -! | +||
7 | +
- snapshot_state <- try(slices_restore(input$snapshot_file$datapath))+ #' `r lifecycle::badge("stable")` |
||
251 | -! | +||
8 | +
- if (!inherits(snapshot_state, "modules_teal_slices")) {+ #' Create a nested tab structure to embed modules in a `teal` application. |
||
252 | -! | +||
9 | +
- logger::log_debug("srv_snapshot_manager: snapshot file corrupt")+ #' |
||
253 | -! | +||
10 | +
- showNotification(+ #' @details |
||
254 | -! | +||
11 | +
- "File appears to be corrupt.",+ #' `module()` creates an instance of a `teal_module` that can be placed in a `teal` application. |
||
255 | -! | +||
12 | +
- type = "error"+ #' `modules()` shapes the structure of a the application by organizing `teal_module` within the navigation panel. |
||
256 | +13 |
- )+ #' It wraps `teal_module` and `teal_modules` objects in a `teal_modules` object, |
|
257 | -! | +||
14 | +
- } else if (!identical(attr(snapshot_state, "app_id"), attr(slices_global$all_slices(), "app_id"))) {+ #' which results in a nested structure corresponding to the nested tabs in the final application. |
||
258 | -! | +||
15 | +
- logger::log_debug("srv_snapshot_manager: snapshot not compatible with app")+ #' |
||
259 | -! | +||
16 | +
- showNotification(+ #' Note that for `modules()` `label` comes after `...`, so it must be passed as a named argument, |
||
260 | -! | +||
17 | +
- "This snapshot file is not compatible with the app and cannot be loaded.",+ #' otherwise it will be captured by `...`. |
||
261 | -! | +||
18 | +
- type = "warning"+ #' |
||
262 | +19 |
- )+ #' The labels `"global_filters"` and `"Report previewer"` are reserved |
|
263 | +20 |
- } else {+ #' because they are used by the `mapping` argument of [teal_slices()] |
|
264 | +21 |
- # Add to snapshot history.+ #' and the report previewer module [reporter_previewer_module()], respectively. |
|
265 | -! | +||
22 | +
- logger::log_debug("srv_snapshot_manager: snapshot loaded, adding to history")+ #' |
||
266 | -! | +||
23 | +
- snapshot <- as.list(slices_global$all_slices(), recursive = TRUE)+ #' # Restricting datasets used by `teal_module`: |
||
267 | -! | +||
24 | +
- snapshot_update <- c(snapshot_history(), list(snapshot))+ #' The `datanames` argument controls which datasets are used by the module’s server. These datasets, |
||
268 | -! | +||
25 | +
- names(snapshot_update)[length(snapshot_update)] <- snapshot_name+ #' passed via server's `data` argument, are the only ones shown in the module's tab. |
||
269 | -! | +||
26 | +
- snapshot_history(snapshot_update)+ #' |
||
270 | +27 |
- ### Begin simplified restore procedure. ###+ #' When `datanames` is set to `"all"`, all datasets in the data object are treated as relevant. |
|
271 | -! | +||
28 | +
- logger::log_debug("srv_snapshot_manager: restoring snapshot")+ #' However, this may include unnecessary datasets, such as: |
||
272 | -! | +||
29 | +
- slices_global$slices_set(snapshot_state)+ #' - Proxy variables for column modifications |
||
273 | -! | +||
30 | +
- removeModal()+ #' - Temporary datasets used to create final versions |
||
274 | +31 |
- ### End simplified restore procedure. ###+ #' - Connection objects |
|
275 | +32 |
- }+ #' |
|
276 | +33 |
- }+ #' To exclude irrelevant datasets, use the [set_datanames()] function to change `datanames` from |
|
277 | +34 |
- })+ #' `"all"` to specific names. Trying to modify non-`"all"` values with [set_datanames()] will result |
|
278 | +35 |
- # Apply newly added snapshot.+ #' in a warning. Datasets with names starting with . are ignored globally unless explicitly listed |
|
279 | +36 |
-
+ #' in `datanames`. |
|
280 | +37 |
- # Restore initial state ----+ #' |
|
281 | -87x | +||
38 | +
- observeEvent(input$snapshot_reset, {+ #' # `datanames` with `transformators` |
||
282 | -2x | +||
39 | +
- logger::log_debug("srv_snapshot_manager: snapshot_reset button clicked, restoring snapshot")+ #' When transformators are specified, their `datanames` are added to the module’s `datanames`, which |
||
283 | -2x | +||
40 | +
- s <- "Initial application state"+ #' changes the behavior as follows: |
||
284 | +41 |
- ### Begin restore procedure. ###+ #' - If `module(datanames)` is `NULL` and the `transformators` have defined `datanames`, the sidebar |
|
285 | -2x | +||
42 | +
- snapshot <- snapshot_history()[[s]]+ #' will appear showing the `transformators`' datasets, instead of being hidden. |
||
286 | -2x | +||
43 | +
- snapshot_state <- as.teal_slices(snapshot)+ #' - If `module(datanames)` is set to specific values and any `transformator` has `datanames = "all"`, |
||
287 | -2x | +||
44 | +
- slices_global$slices_set(snapshot_state)+ #' the module may receive extra datasets that could be unnecessary |
||
288 | -2x | +||
45 | +
- removeModal()+ #'+ |
+ ||
46 | ++ |
+ #' @param label (`character(1)`) Label shown in the navigation item for the module or module group.+ |
+ |
47 | ++ |
+ #' For `modules()` defaults to `"root"`. See `Details`.+ |
+ |
48 | ++ |
+ #' @param server (`function`) `shiny` module with following arguments:+ |
+ |
49 | ++ |
+ #' - `id` - `teal` will set proper `shiny` namespace for this module (see [shiny::moduleServer()]).+ |
+ |
50 | ++ |
+ #' - `input`, `output`, `session` - (optional; not recommended) When provided, then [shiny::callModule()]+ |
+ |
51 | ++ |
+ #' will be used to call a module. From `shiny` 1.5.0, the recommended way is to use+ |
+ |
52 | ++ |
+ #' [shiny::moduleServer()] instead which doesn't require these arguments.+ |
+ |
53 | ++ |
+ #' - `data` (optional) When provided, the module will be called with `teal_data` object (i.e. a list of+ |
+ |
54 | ++ |
+ #' reactive (filtered) data specified in the `filters` argument) as the value of this argument.+ |
+ |
55 | ++ |
+ #' - `datasets` (optional) When provided, the module will be called with `FilteredData` object as the+ |
+ |
56 | ++ |
+ #' value of this argument. (See [`teal.slice::FilteredData`]).+ |
+ |
57 | ++ |
+ #' - `reporter` (optional) When provided, the module will be called with `Reporter` object as the value+ |
+ |
58 | ++ |
+ #' of this argument. (See [`teal.reporter::Reporter`]).+ |
+ |
59 | ++ |
+ #' - `filter_panel_api` (optional) When provided, the module will be called with `FilterPanelAPI` object+ |
+ |
60 | ++ |
+ #' as the value of this argument. (See [`teal.slice::FilterPanelAPI`]).+ |
+ |
61 | ++ |
+ #' - `...` (optional) When provided, `server_args` elements will be passed to the module named argument+ |
+ |
62 | ++ |
+ #' or to the `...`.+ |
+ |
63 | ++ |
+ #' @param ui (`function`) `shiny` UI module function with following arguments:+ |
+ |
64 | ++ |
+ #' - `id` - `teal` will set proper `shiny` namespace for this module.+ |
+ |
65 | ++ |
+ #' - `...` (optional) When provided, `ui_args` elements will be passed to the module named argument+ |
+ |
66 | ++ |
+ #' or to the `...`.+ |
+ |
67 | ++ |
+ #' @param filters (`character`) Deprecated. Use `datanames` instead.+ |
+ |
68 | ++ |
+ #' @param datanames (`character`) Names of the datasets relevant to the item.+ |
+ |
69 | ++ |
+ #' There are 2 reserved values that have specific behaviors:+ |
+ |
70 | ++ |
+ #' - The keyword `"all"` includes all datasets available in the data passed to the teal application.+ |
+ |
71 | ++ |
+ #' - `NULL` hides the sidebar panel completely.+ |
+ |
72 | ++ |
+ #' - If `transformators` are specified, their `datanames` are automatically added to this `datanames`+ |
+ |
73 | ++ |
+ #' argument.+ |
+ |
74 | ++ |
+ #' @param server_args (named `list`) with additional arguments passed on to the server function.+ |
+ |
75 | ++ |
+ #' @param ui_args (named `list`) with additional arguments passed on to the UI function.+ |
+ |
76 | ++ |
+ #' @param x (`teal_module` or `teal_modules`) Object to format/print.+ |
+ |
77 | ++ |
+ #' @param transformators (`list` of `teal_transform_module`) that will be applied to transformator module's data input.+ |
+ |
78 | ++ |
+ #'+ |
+ |
79 | ++ |
+ #'+ |
+ |
80 | ++ |
+ #' @param ...+ |
+ |
81 | ++ |
+ #' - For `modules()`: (`teal_module` or `teal_modules`) Objects to wrap into a tab.+ |
+ |
82 | ++ |
+ #' - For `format()` and `print()`: Arguments passed to other methods.+ |
+ |
83 | ++ |
+ #'+ |
+ |
84 | ++ |
+ #' @return |
|
289 | +85 |
- ### End restore procedure. ###+ #' `module()` returns an object of class `teal_module`. |
|
290 | +86 |
- })+ #' |
|
291 | +87 |
-
+ #' `modules()` returns a `teal_modules` object which contains following fields: |
|
292 | +88 |
- # Build snapshot table ----+ #' - `label`: taken from the `label` argument. |
|
293 | +89 |
- # Create UI elements and server logic for the snapshot table.+ #' - `children`: a list containing objects passed in `...`. List elements are named after |
|
294 | +90 |
- # Observers must be tracked to avoid duplication and excess reactivity.+ #' their `label` attribute converted to a valid `shiny` id. |
|
295 | +91 |
- # Remaining elements are tracked likewise for consistency and a slight speed margin.+ #' |
|
296 | -87x | +||
92 | +
- observers <- reactiveValues()+ #' @name teal_modules |
||
297 | -87x | +||
93 | +
- handlers <- reactiveValues()+ #' @aliases teal_module |
||
298 | -87x | +||
94 | +
- divs <- reactiveValues()+ #' |
||
299 | +95 |
-
+ #' @examples |
|
300 | -87x | +||
96 | +
- observeEvent(snapshot_history(), {+ #' library(shiny) |
||
301 | -77x | +||
97 | +
- logger::log_debug("srv_snapshot_manager: snapshot history modified, updating snapshot list")+ #' |
||
302 | -77x | +||
98 | +
- lapply(names(snapshot_history())[-1L], function(s) {+ #' module_1 <- module( |
||
303 | -! | +||
99 | +
- id_pickme <- sprintf("pickme_%s", make.names(s))+ #' label = "a module", |
||
304 | -! | +||
100 | +
- id_saveme <- sprintf("saveme_%s", make.names(s))+ #' server = function(id, data) { |
||
305 | -! | +||
101 | +
- id_rowme <- sprintf("rowme_%s", make.names(s))+ #' moduleServer( |
||
306 | +102 |
-
+ #' id, |
|
307 | +103 |
- # Observer for restoring snapshot.+ #' module = function(input, output, session) { |
|
308 | -! | +||
104 | +
- if (!is.element(id_pickme, names(observers))) {+ #' output$data <- renderDataTable(data()[["iris"]]) |
||
309 | -! | +||
105 | +
- observers[[id_pickme]] <- observeEvent(input[[id_pickme]], {+ #' } |
||
310 | +106 |
- ### Begin restore procedure. ###+ #' ) |
|
311 | -! | +||
107 | +
- snapshot <- snapshot_history()[[s]]+ #' }, |
||
312 | -! | +||
108 | +
- snapshot_state <- as.teal_slices(snapshot)+ #' ui = function(id) { |
||
313 | +109 |
-
+ #' ns <- NS(id) |
|
314 | -! | +||
110 | +
- slices_global$slices_set(snapshot_state)+ #' tagList(dataTableOutput(ns("data"))) |
||
315 | -! | +||
111 | +
- removeModal()+ #' }, |
||
316 | +112 |
- ### End restore procedure. ###+ #' datanames = "all" |
|
317 | +113 |
- })+ #' ) |
|
318 | +114 |
- }+ #' |
|
319 | +115 |
- # Create handler for downloading snapshot.+ #' module_2 <- module( |
|
320 | -! | +||
116 | +
- if (!is.element(id_saveme, names(handlers))) {+ #' label = "another module", |
||
321 | -! | +||
117 | +
- output[[id_saveme]] <- downloadHandler(+ #' server = function(id) { |
||
322 | -! | +||
118 | +
- filename = function() {+ #' moduleServer( |
||
323 | -! | +||
119 | +
- sprintf("teal_snapshot_%s_%s.json", s, Sys.Date())+ #' id, |
||
324 | +120 |
- },+ #' module = function(input, output, session) { |
|
325 | -! | +||
121 | +
- content = function(file) {+ #' output$text <- renderText("Another Module") |
||
326 | -! | +||
122 | +
- snapshot <- snapshot_history()[[s]]+ #' } |
||
327 | -! | +||
123 | +
- snapshot_state <- as.teal_slices(snapshot)+ #' ) |
||
328 | -! | +||
124 | +
- slices_store(tss = snapshot_state, file = file)+ #' }, |
||
329 | +125 |
- }+ #' ui = function(id) { |
|
330 | +126 |
- )+ #' ns <- NS(id) |
|
331 | -! | +||
127 | +
- handlers[[id_saveme]] <- id_saveme+ #' tagList(textOutput(ns("text"))) |
||
332 | +128 |
- }+ #' }, |
|
333 | +129 |
- # Create a row for the snapshot table.+ #' datanames = NULL |
|
334 | -! | +||
130 | +
- if (!is.element(id_rowme, names(divs))) {+ #' ) |
||
335 | -! | +||
131 | +
- divs[[id_rowme]] <- tags$div(+ #' |
||
336 | -! | +||
132 | +
- class = "manager_table_row",+ #' modules <- modules( |
||
337 | -! | +||
133 | +
- tags$span(tags$h5(s)),+ #' label = "modules", |
||
338 | -! | +||
134 | +
- actionLink(inputId = ns(id_pickme), label = icon("far fa-circle-check"), title = "select"),+ #' modules( |
||
339 | -! | +||
135 | +
- downloadLink(outputId = ns(id_saveme), label = icon("far fa-save"), title = "save to file")+ #' label = "nested modules", |
||
340 | +136 |
- )+ #' module_1 |
|
341 | +137 |
- }+ #' ), |
|
342 | +138 |
- })+ #' module_2 |
|
343 | +139 |
- })+ #' ) |
|
344 | +140 |
-
+ #' |
|
345 | +141 |
- # Create table to display list of snapshots and their actions.+ #' app <- init( |
|
346 | -87x | +||
142 | +
- output$snapshot_list <- renderUI({+ #' data = teal_data(iris = iris), |
||
347 | -77x | +||
143 | +
- rows <- rev(reactiveValuesToList(divs))+ #' modules = modules |
||
348 | -77x | +||
144 | +
- if (length(rows) == 0L) {+ #' ) |
||
349 | -77x | +||
145 | +
- tags$div(+ #' |
||
350 | -77x | +||
146 | +
- class = "manager_placeholder",+ #' if (interactive()) { |
||
351 | -77x | +||
147 | +
- "Snapshots will appear here."+ #' shinyApp(app$ui, app$server) |
||
352 | +148 |
- )+ #' } |
|
353 | +149 |
- } else {+ #' @rdname teal_modules |
|
354 | -! | +||
150 | +
- rows+ #' @export |
||
355 | +151 |
- }+ #' |
|
356 | +152 |
- })+ module <- function(label = "module", |
|
357 | +153 |
-
+ server = function(id, data, ...) moduleServer(id, function(input, output, session) NULL), |
|
358 | -87x | +||
154 | +
- snapshot_history+ ui = function(id, ...) tags$p(paste0("This module has no UI (id: ", id, " )")), |
||
359 | +155 |
- })+ filters, |
|
360 | +156 |
- }+ datanames = "all", |
1 | +157 |
- #' @title `TealReportCard`+ server_args = NULL, |
||
2 | +158 |
- #' @description `r lifecycle::badge("experimental")`+ ui_args = NULL, |
||
3 | +159 |
- #' Child class of [`teal.reporter::ReportCard`] that is used for `teal` specific applications.+ transformators = list()) { |
||
4 | +160 |
- #' In addition to the parent methods, it supports rendering `teal` specific elements such as+ # argument checking (independent) |
||
5 | +161 |
- #' the source code, the encodings panel content and the filter panel content as part of the+ ## `label` |
||
6 | -+ | |||
162 | +220x |
- #' meta data.+ checkmate::assert_string(label) |
||
7 | -+ | |||
163 | +217x |
- #' @export+ if (label == "global_filters") {+ |
+ ||
164 | +1x | +
+ stop(+ |
+ ||
165 | +1x | +
+ sprintf("module(label = \"%s\", ...\n ", label),+ |
+ ||
166 | +1x | +
+ "Label 'global_filters' is reserved in teal. Please change to something else.",+ |
+ ||
167 | +1x | +
+ call. = FALSE |
||
8 | +168 |
- #'+ ) |
||
9 | +169 |
- TealReportCard <- R6::R6Class( # nolint: object_name.+ } |
||
10 | -+ | |||
170 | +216x |
- classname = "TealReportCard",+ if (label == "Report previewer") { |
||
11 | -+ | |||
171 | +! |
- inherit = teal.reporter::ReportCard,+ stop( |
||
12 | -+ | |||
172 | +! |
- public = list(+ sprintf("module(label = \"%s\", ...\n ", label), |
||
13 | -+ | |||
173 | +! |
- #' @description Appends the source code to the `content` meta data of this `TealReportCard`.+ "Label 'Report previewer' is reserved in teal. Please change to something else.", |
||
14 | -+ | |||
174 | +! |
- #'+ call. = FALSE |
||
15 | +175 |
- #' @param src (`character(1)`) code as text.+ ) |
||
16 | +176 |
- #' @param ... any `rmarkdown` `R` chunk parameter and its value.+ } |
||
17 | +177 |
- #' But `eval` parameter is always set to `FALSE`.+ |
||
18 | +178 |
- #' @return Object of class `TealReportCard`, invisibly.+ ## server |
||
19 | -+ | |||
179 | +216x |
- #' @examples+ checkmate::assert_function(server) |
||
20 | -+ | |||
180 | +216x |
- #' card <- TealReportCard$new()$append_src(+ server_formals <- names(formals(server)) |
||
21 | -+ | |||
181 | +216x |
- #' "plot(iris)"+ if (!( |
||
22 | -+ | |||
182 | +216x |
- #' )+ "id" %in% server_formals || |
||
23 | -+ | |||
183 | +216x |
- #' card$get_content()[[1]]$get_content()+ all(c("input", "output", "session") %in% server_formals) |
||
24 | +184 |
- append_src = function(src, ...) {+ )) { |
||
25 | -4x | +185 | +2x |
- checkmate::assert_character(src, min.len = 0, max.len = 1)+ stop( |
26 | -4x | +186 | +2x |
- params <- list(...)+ "\nmodule() `server` argument requires a function with following arguments:", |
27 | -4x | +187 | +2x |
- params$eval <- FALSE+ "\n - id - `teal` will set proper `shiny` namespace for this module.", |
28 | -4x | +188 | +2x |
- rblock <- RcodeBlock$new(src)+ "\n - input, output, session (not recommended) - then `shiny::callModule` will be used to call a module.", |
29 | -4x | +189 | +2x |
- rblock$set_params(params)+ "\n\nFollowing arguments can be used optionaly:", |
30 | -4x | +190 | +2x |
- self$append_content(rblock)+ "\n - `data` - module will receive list of reactive (filtered) data specified in the `filters` argument", |
31 | -4x | +191 | +2x |
- self$append_metadata("SRC", src)+ "\n - `datasets` - module will receive `FilteredData`. See `help(teal.slice::FilteredData)`", |
32 | -4x | -
- invisible(self)- |
- ||
33 | -+ | 192 | +2x |
- },+ "\n - `reporter` - module will receive `Reporter`. See `help(teal.reporter::Reporter)`", |
34 | -+ | |||
193 | +2x |
- #' @description Appends the filter state list to the `content` and `metadata` of this `TealReportCard`.+ "\n - `filter_panel_api` - module will receive `FilterPanelAPI`. (See [teal.slice::FilterPanelAPI]).", |
||
35 | -+ | |||
194 | +2x |
- #' If the filter state list has an attribute named `formatted`, it appends it to the card otherwise it uses+ "\n - `...` server_args elements will be passed to the module named argument or to the `...`" |
||
36 | +195 |
- #' the default `yaml::as.yaml` to format the list.+ ) |
||
37 | +196 |
- #' If the filter state list is empty, nothing is appended to the `content`.+ } |
||
38 | +197 |
- #'+ |
||
39 | -+ | |||
198 | +214x |
- #' @param fs (`teal_slices`) object returned from [teal_slices()] function.+ if ("datasets" %in% server_formals) { |
||
40 | -+ | |||
199 | +2x |
- #' @return `self`, invisibly.+ warning( |
||
41 | -+ | |||
200 | +2x |
- append_fs = function(fs) {+ sprintf("Called from module(label = \"%s\", ...)\n ", label), |
||
42 | -5x | +201 | +2x |
- checkmate::assert_class(fs, "teal_slices")+ "`datasets` argument in the server is deprecated and will be removed in the next release. ", |
43 | -4x | +202 | +2x |
- self$append_text("Filter State", "header3")+ "Please use `data` instead.", |
44 | -4x | +203 | +2x |
- if (length(fs)) {+ call. = FALSE |
45 | -3x | +|||
204 | +
- self$append_content(TealSlicesBlock$new(fs))+ ) |
|||
46 | +205 |
- } else {+ } |
||
47 | -1x | +|||
206 | +
- self$append_text("No filters specified.")+ |
|||
48 | +207 |
- }+ ## UI |
||
49 | -4x | +208 | +214x |
- invisible(self)+ checkmate::assert_function(ui) |
50 | -+ | |||
209 | +214x |
- },+ ui_formals <- names(formals(ui)) |
||
51 | -+ | |||
210 | +214x |
- #' @description Appends the encodings list to the `content` and `metadata` of this `TealReportCard`.+ if (!"id" %in% ui_formals) { |
||
52 | -+ | |||
211 | +1x |
- #'+ stop( |
||
53 | -+ | |||
212 | +1x |
- #' @param encodings (`list`) list of encodings selections of the `teal` app.+ "\nmodule() `ui` argument requires a function with following arguments:", |
||
54 | -+ | |||
213 | +1x |
- #' @return `self`, invisibly.+ "\n - id - `teal` will set proper `shiny` namespace for this module.", |
||
55 | -+ | |||
214 | +1x |
- #' @examples+ "\n\nFollowing arguments can be used optionally:", |
||
56 | -+ | |||
215 | +1x |
- #' card <- TealReportCard$new()$append_encodings(list(variable1 = "X"))+ "\n - `...` ui_args elements will be passed to the module argument of the same name or to the `...`" |
||
57 | +216 |
- #' card$get_content()[[1]]$get_content()+ ) |
||
58 | +217 |
- #'+ } |
||
59 | +218 |
- append_encodings = function(encodings) {- |
- ||
60 | -4x | -
- checkmate::assert_list(encodings)+ |
||
61 | -4x | +219 | +213x |
- self$append_text("Selected Options", "header3")+ if (any(c("data", "datasets") %in% ui_formals)) { |
62 | -4x | +220 | +2x |
- if (requireNamespace("yaml", quietly = TRUE)) {+ stop( |
63 | -4x | +221 | +2x |
- self$append_text(yaml::as.yaml(encodings, handlers = list(+ sprintf("Called from module(label = \"%s\", ...)\n ", label), |
64 | -4x | +222 | +2x |
- POSIXct = function(x) format(x, "%Y-%m-%d"),+ "UI with `data` or `datasets` argument is no longer accepted.\n ", |
65 | -4x | +223 | +2x |
- POSIXlt = function(x) format(x, "%Y-%m-%d"),+ "If some UI inputs depend on data, please move the logic to your server instead.\n ", |
66 | -4x | +224 | +2x |
- Date = function(x) format(x, "%Y-%m-%d")+ "Possible solutions are renderUI() or updateXyzInput() functions." |
67 | -4x | +|||
225 | +
- )), "verbatim")+ ) |
|||
68 | +226 |
- } else {+ } |
||
69 | -! | +|||
227 | +
- stop("yaml package is required to format the encodings list")+ |
|||
70 | +228 |
- }+ ## `filters` |
||
71 | -4x | +229 | +211x |
- self$append_metadata("Encodings", encodings)+ if (!missing(filters)) { |
72 | -4x | +|||
230 | +! |
- invisible(self)+ datanames <- filters |
||
73 | -+ | |||
231 | +! |
- }+ msg <- |
||
74 | -+ | |||
232 | +! |
- ),+ "The `filters` argument is deprecated and will be removed in the next release. Please use `datanames` instead." |
||
75 | -+ | |||
233 | +! |
- private = list(+ warning(msg) |
||
76 | +234 |
- dispatch_block = function(block_class) {+ } |
||
77 | -! | +|||
235 | +
- eval(str2lang(block_class))+ |
|||
78 | +236 |
- }+ ## `datanames` (also including deprecated `filters`) |
||
79 | +237 |
- )+ # please note a race condition between datanames set when filters is not missing and data arg in server function |
||
80 | -+ | |||
238 | +211x |
- )+ if (!is.element("data", server_formals) && !is.null(datanames)) { |
||
81 | -+ | |||
239 | +12x |
-
+ message(sprintf("module \"%s\" server function takes no data so \"datanames\" will be ignored", label)) |
||
82 | -+ | |||
240 | +12x |
- #' @title `TealSlicesBlock`+ datanames <- NULL |
||
83 | +241 |
- #' @docType class+ } |
||
84 | -+ | |||
242 | +211x |
- #' @description+ checkmate::assert_character(datanames, min.len = 1, null.ok = TRUE, any.missing = FALSE) |
||
85 | +243 |
- #' Specialized `TealSlicesBlock` block for managing filter panel content in reports.+ |
||
86 | +244 |
- #' @keywords internal+ ## `server_args` |
||
87 | -+ | |||
245 | +210x |
- TealSlicesBlock <- R6::R6Class( # nolint: object_name_linter.+ checkmate::assert_list(server_args, null.ok = TRUE, names = "named")+ |
+ ||
246 | +208x | +
+ srv_extra_args <- setdiff(names(server_args), server_formals) |
||
88 | -+ | |||
247 | +208x |
- classname = "TealSlicesBlock",+ if (length(srv_extra_args) > 0 && !"..." %in% server_formals) { |
||
89 | -+ | |||
248 | +1x |
- inherit = teal.reporter:::TextBlock,+ stop( |
||
90 | -+ | |||
249 | +1x |
- public = list(+ "\nFollowing `server_args` elements have no equivalent in the formals of the server:\n", |
||
91 | -+ | |||
250 | +1x |
- #' @description Returns a `TealSlicesBlock` object.+ paste(paste(" -", srv_extra_args), collapse = "\n"), |
||
92 | -+ | |||
251 | +1x |
- #'+ "\n\nUpdate the server arguments by including above or add `...`" |
||
93 | +252 |
- #' @details Returns a `TealSlicesBlock` object with no content and no parameters.+ ) |
||
94 | +253 |
- #'+ } |
||
95 | +254 |
- #' @param content (`teal_slices`) object returned from [teal_slices()] function.+ |
||
96 | +255 |
- #' @param style (`character(1)`) string specifying style to apply.+ ## `ui_args` |
||
97 | -+ | |||
256 | +207x |
- #'+ checkmate::assert_list(ui_args, null.ok = TRUE, names = "named") |
||
98 | -+ | |||
257 | +205x |
- #' @return Object of class `TealSlicesBlock`, invisibly.+ ui_extra_args <- setdiff(names(ui_args), ui_formals) |
||
99 | -+ | |||
258 | +205x |
- #'+ if (length(ui_extra_args) > 0 && !"..." %in% ui_formals) { |
||
100 | -+ | |||
259 | +1x |
- initialize = function(content = teal_slices(), style = "verbatim") {+ stop( |
||
101 | -9x | +260 | +1x |
- self$set_content(content)+ "\nFollowing `ui_args` elements have no equivalent in the formals of UI:\n", |
102 | -8x | +261 | +1x |
- self$set_style(style)+ paste(paste(" -", ui_extra_args), collapse = "\n"), |
103 | -8x | +262 | +1x |
- invisible(self)+ "\n\nUpdate the UI arguments by including above or add `...`" |
104 | +263 |
- },+ ) |
||
105 | +264 |
-
+ } |
||
106 | +265 |
- #' @description Sets content of this `TealSlicesBlock`.+ |
||
107 | +266 |
- #' Sets content as `YAML` text which represents a list generated from `teal_slices`.+ ## `transformators` |
||
108 | -+ | |||
267 | +204x |
- #' The list displays limited number of fields from `teal_slice` objects, but this list is+ if (inherits(transformators, "teal_transform_module")) { |
||
109 | -+ | |||
268 | +1x |
- #' sufficient to conclude which filters were applied.+ transformators <- list(transformators) |
||
110 | +269 |
- #' When `selected` field in `teal_slice` object is a range, then it is displayed as a "min"+ } |
||
111 | -+ | |||
270 | +204x |
- #'+ checkmate::assert_list(transformators, types = "teal_transform_module") |
||
112 | -+ | |||
271 | +204x |
- #'+ transform_datanames <- unlist(lapply(transformators, attr, "datanames"))+ |
+ ||
272 | +204x | +
+ combined_datanames <- if (identical(datanames, "all")) {+ |
+ ||
273 | +151x | +
+ "all" |
||
113 | +274 |
- #' @param content (`teal_slices`) object returned from [teal_slices()] function.+ } else {+ |
+ ||
275 | +53x | +
+ union(datanames, transform_datanames) |
||
114 | +276 |
- #' @return `self`, invisibly.+ } |
||
115 | +277 |
- set_content = function(content) {+ |
||
116 | -9x | +278 | +204x |
- checkmate::assert_class(content, "teal_slices")+ structure( |
117 | -8x | +279 | +204x |
- if (length(content) != 0) {+ list( |
118 | -6x | +280 | +204x |
- states_list <- lapply(content, function(x) {+ label = label, |
119 | -6x | +281 | +204x |
- x_list <- shiny::isolate(as.list(x))+ server = server, |
120 | -6x | +282 | +204x |
- if (+ ui = ui, |
121 | -6x | +283 | +204x |
- inherits(x_list$choices, c("integer", "numeric", "Date", "POSIXct", "POSIXlt")) &&+ datanames = combined_datanames, |
122 | -6x | +284 | +204x |
- length(x_list$choices) == 2 &&+ server_args = server_args, |
123 | -6x | +285 | +204x |
- length(x_list$selected) == 2+ ui_args = ui_args,+ |
+
286 | +204x | +
+ transformators = transformators |
||
124 | +287 |
- ) {+ ), |
||
125 | -! | +|||
288 | +204x |
- x_list$range <- paste(x_list$selected, collapse = " - ")+ class = "teal_module" |
||
126 | -! | +|||
289 | +
- x_list["selected"] <- NULL+ ) |
|||
127 | +290 |
- }+ } |
||
128 | -6x | +|||
291 | +
- if (!is.null(x_list$arg)) {+ |
|||
129 | -! | +|||
292 | +
- x_list$arg <- if (x_list$arg == "subset") "Genes" else "Samples"+ #' @rdname teal_modules |
|||
130 | +293 |
- }+ #' @export |
||
131 | +294 |
-
+ #' |
||
132 | -6x | +|||
295 | +
- x_list <- x_list[+ modules <- function(..., label = "root") { |
|||
133 | -6x | +296 | +144x |
- c("dataname", "varname", "experiment", "arg", "expr", "selected", "range", "keep_na", "keep_inf")+ checkmate::assert_string(label) |
134 | -+ | |||
297 | +142x |
- ]+ submodules <- list(...) |
||
135 | -6x | +298 | +142x |
- names(x_list) <- c(+ if (any(vapply(submodules, is.character, FUN.VALUE = logical(1)))) { |
136 | -6x | +299 | +2x |
- "Dataset name", "Variable name", "Experiment", "Filtering by", "Applied expression",+ stop( |
137 | -6x | +300 | +2x |
- "Selected Values", "Selected range", "Include NA values", "Include Inf values"+ "The only character argument to modules() must be 'label' and it must be named, ", |
138 | -+ | |||
301 | +2x |
- )+ "change modules('lab', ...) to modules(label = 'lab', ...)" |
||
139 | +302 | - - | -||
140 | -6x | -
- Filter(Negate(is.null), x_list)+ ) |
||
141 | +303 |
- })+ } |
||
142 | +304 | |||
143 | -6x | +305 | +140x |
- if (requireNamespace("yaml", quietly = TRUE)) {+ checkmate::assert_list(submodules, min.len = 1, any.missing = FALSE, types = c("teal_module", "teal_modules")) |
144 | -6x | +|||
306 | +
- super$set_content(yaml::as.yaml(states_list))+ # name them so we can more easily access the children |
|||
145 | +307 |
- } else {+ # beware however that the label of the submodules should not be changed as it must be kept synced |
||
146 | -! | +|||
308 | +137x |
- stop("yaml package is required to format the filter state list")+ labels <- vapply(submodules, function(submodule) submodule$label, character(1)) |
||
147 | -+ | |||
309 | +137x |
- }+ names(submodules) <- get_unique_labels(labels) |
||
148 | -+ | |||
310 | +137x |
- }+ structure( |
||
149 | -8x | +311 | +137x |
- private$teal_slices <- content+ list( |
150 | -8x | +312 | +137x |
- invisible(self)+ label = label, |
151 | -+ | |||
313 | +137x |
- },+ children = submodules |
||
152 | +314 |
- #' @description Create the `TealSlicesBlock` from a list.+ ), |
||
153 | -+ | |||
315 | +137x |
- #'+ class = "teal_modules" |
||
154 | +316 |
- #' @param x (`named list`) with two fields `text` and `style`.+ ) |
||
155 | +317 |
- #' Use the `get_available_styles` method to get all possible styles.+ } |
||
156 | +318 |
- #'+ |
||
157 | +319 |
- #' @return `self`, invisibly.+ # printing methods ---- |
||
158 | +320 |
- #' @examples+ |
||
159 | +321 |
- #' TealSlicesBlock <- getFromNamespace("TealSlicesBlock", "teal")+ #' @rdname teal_modules |
||
160 | +322 |
- #' block <- TealSlicesBlock$new()+ #' @param is_last (`logical(1)`) Whether this is the last item in its parent's children list. |
||
161 | +323 |
- #' block$from_list(list(text = "sth", style = "default"))+ #' Affects the tree branch character used (L- vs |-) |
||
162 | +324 |
- #'+ #' @param parent_prefix (`character(1)`) The prefix inherited from parent nodes, |
||
163 | +325 |
- from_list = function(x) {- |
- ||
164 | -1x | -
- checkmate::assert_list(x)- |
- ||
165 | -1x | -
- checkmate::assert_names(names(x), must.include = c("text", "style"))- |
- ||
166 | -1x | -
- super$set_content(x$text)- |
- ||
167 | -1x | -
- super$set_style(x$style)- |
- ||
168 | -1x | -
- invisible(self)+ #' used to maintain the tree structure in nested levels |
||
169 | +326 |
- },+ #' @param is_root (`logical(1)`) Whether this is the root node of the tree. Only used in |
||
170 | +327 |
- #' @description Convert the `TealSlicesBlock` to a list.+ #' format.teal_modules(). Determines whether to show "TEAL ROOT" header |
||
171 | +328 |
- #'+ #' @param what (`character`) Specifies which metadata to display. |
||
172 | +329 |
- #' @return `named list` with a text and style.+ #' Possible values: "datasets", "properties", "ui_args", "server_args", "transformators" |
||
173 | +330 |
- #' @examples+ #' @examples |
||
174 | +331 |
- #' TealSlicesBlock <- getFromNamespace("TealSlicesBlock", "teal")+ #' mod <- module( |
||
175 | +332 |
- #' block <- TealSlicesBlock$new()+ #' label = "My Custom Module", |
||
176 | +333 |
- #' block$to_list()+ #' server = function(id, data, ...) {}, |
||
177 | +334 |
- #'+ #' ui = function(id, ...) {}, |
||
178 | +335 |
- to_list = function() {+ #' datanames = c("ADSL", "ADTTE"), |
||
179 | -2x | +|||
336 | +
- content <- self$get_content()+ #' transformators = list(), |
|||
180 | -2x | +|||
337 | +
- list(+ #' ui_args = list(a = 1, b = "b"), |
|||
181 | -2x | +|||
338 | +
- text = if (length(content)) content else "",+ #' server_args = list(x = 5, y = list(p = 1)) |
|||
182 | -2x | +|||
339 | +
- style = self$get_style()+ #' ) |
|||
183 | +340 |
- )+ #' cat(format(mod)) |
||
184 | +341 |
- }+ #' @export |
||
185 | +342 |
- ),+ format.teal_module <- function(x, |
||
186 | +343 |
- private = list(+ is_last = FALSE, |
||
187 | +344 |
- style = "verbatim",+ parent_prefix = "", |
||
188 | +345 |
- teal_slices = NULL # teal_slices+ what = c("datasets", "properties", "ui_args", "server_args", "transformators"), |
||
189 | +346 |
- )+ ...) { |
||
190 | -+ | |||
347 | +3x |
- )+ empty_text <- "" |
1 | -+ | ||
348 | +3x |
- #' Send input validation messages to output+ branch <- if (is_last) "L-" else "|-" |
|
2 | -+ | ||
349 | +3x |
- #'+ current_prefix <- paste0(parent_prefix, branch, " ") |
|
3 | -+ | ||
350 | +3x |
- #' Captures messages from `InputValidator` objects and collates them+ content_prefix <- paste0(parent_prefix, if (is_last) " " else "| ") |
|
4 | +351 |
- #' into one message passed to `validate`.+ |
|
5 | -+ | ||
352 | +3x |
- #'+ format_list <- function(lst, empty = empty_text, label_width = 0) { |
|
6 | -+ | ||
353 | +6x |
- #' `shiny::validate` is used to withhold rendering of an output element until+ if (is.null(lst) || length(lst) == 0) { |
|
7 | -+ | ||
354 | +6x |
- #' certain conditions are met and to print a validation message in place+ empty |
|
8 | +355 |
- #' of the output element.+ } else { |
|
9 | -+ | ||
356 | +! |
- #' `shinyvalidate::InputValidator` allows to validate input elements+ colon_space <- paste(rep(" ", label_width), collapse = "") |
|
10 | +357 |
- #' and to display specific messages in their respective input widgets.+ |
|
11 | -+ | ||
358 | +! |
- #' `validate_inputs` provides a hybrid solution.+ first_item <- sprintf("%s (%s)", names(lst)[1], cli::col_silver(class(lst[[1]])[1])) |
|
12 | -+ | ||
359 | +! |
- #' Given an `InputValidator` object, messages corresponding to inputs that fail validation+ rest_items <- if (length(lst) > 1) { |
|
13 | -+ | ||
360 | +! |
- #' are extracted and placed in one validation message that is passed to a `validate`/`need` call.+ paste( |
|
14 | -+ | ||
361 | +! |
- #' This way the input `validator` messages are repeated in the output.+ vapply( |
|
15 | -+ | ||
362 | +! |
- #'+ names(lst)[-1], |
|
16 | -+ | ||
363 | +! |
- #' The `...` argument accepts any number of `InputValidator` objects+ function(name) { |
|
17 | -+ | ||
364 | +! |
- #' or a nested list of such objects.+ sprintf( |
|
18 | -+ | ||
365 | +! |
- #' If `validators` are passed directly, all their messages are printed together+ "%s%s (%s)", |
|
19 | -+ | ||
366 | +! |
- #' under one (optional) header message specified by `header`. If a list is passed,+ paste0(content_prefix, "| ", colon_space), |
|
20 | -+ | ||
367 | +! |
- #' messages are grouped by `validator`. The list's names are used as headers+ name, |
|
21 | -+ | ||
368 | +! |
- #' for their respective message groups.+ cli::col_silver(class(lst[[name]])[1]) |
|
22 | +369 |
- #' If neither of the nested list elements is named, a header message is taken from `header`.+ ) |
|
23 | +370 |
- #'+ }, |
|
24 | -+ | ||
371 | +! |
- #' @param ... either any number of `InputValidator` objects+ character(1) |
|
25 | +372 |
- #' or an optionally named, possibly nested `list` of `InputValidator`+ ), |
|
26 | -+ | ||
373 | +! |
- #' objects, see `Details`+ collapse = "\n" |
|
27 | +374 |
- #' @param header (`character(1)`) generic validation message; set to NULL to omit+ ) |
|
28 | +375 |
- #'+ } |
|
29 | -+ | ||
376 | +! |
- #' @return+ if (length(lst) > 1) paste0(first_item, "\n", rest_items) else first_item |
|
30 | +377 |
- #' Returns NULL if the final validation call passes and a `shiny.silent.error` if it fails.+ } |
|
31 | +378 |
- #'+ } |
|
32 | +379 |
- #' @seealso [`shinyvalidate::InputValidator`], [`shiny::validate`]+ |
|
33 | -+ | ||
380 | +3x |
- #'+ bookmarkable <- isTRUE(attr(x, "teal_bookmarkable")) |
|
34 | -+ | ||
381 | +3x |
- #' @examplesIf require("shinyvalidate")+ reportable <- "reporter" %in% names(formals(x$server)) |
|
35 | +382 |
- #' library(shiny)+ |
|
36 | -+ | ||
383 | +3x |
- #' library(shinyvalidate)+ transformators <- if (length(x$transformators) > 0) { |
|
37 | -+ | ||
384 | +! |
- #'+ paste(sapply(x$transformators, function(t) attr(t, "label")), collapse = ", ") |
|
38 | +385 |
- #' ui <- fluidPage(+ } else { |
|
39 | -+ | ||
386 | +3x |
- #' selectInput("method", "validation method", c("sequential", "combined", "grouped")),+ empty_text |
|
40 | +387 |
- #' sidebarLayout(+ } |
|
41 | +388 |
- #' sidebarPanel(+ |
|
42 | -+ | ||
389 | +3x |
- #' selectInput("letter", "select a letter:", c(letters[1:3], LETTERS[4:6])),+ output <- pasten(current_prefix, cli::bg_white(cli::col_black(x$label))) |
|
43 | +390 |
- #' selectInput("number", "select a number:", 1:6),+ |
|
44 | -+ | ||
391 | +3x |
- #' tags$br(),+ if ("datasets" %in% what) { |
|
45 | -+ | ||
392 | +3x |
- #' selectInput("color", "select a color:",+ output <- paste0( |
|
46 | -+ | ||
393 | +3x |
- #' c("black", "indianred2", "springgreen2", "cornflowerblue"),+ output, |
|
47 | -+ | ||
394 | +3x |
- #' multiple = TRUE+ content_prefix, "|- ", cli::col_yellow("Datasets : "), paste(x$datanames, collapse = ", "), "\n" |
|
48 | +395 |
- #' ),+ ) |
|
49 | +396 |
- #' sliderInput("size", "select point size:",+ } |
|
50 | -+ | ||
397 | +3x |
- #' min = 0.1, max = 4, value = 0.25+ if ("properties" %in% what) { |
|
51 | -+ | ||
398 | +3x |
- #' )+ output <- paste0( |
|
52 | -+ | ||
399 | +3x |
- #' ),+ output, |
|
53 | -+ | ||
400 | +3x |
- #' mainPanel(plotOutput("plot"))+ content_prefix, "|- ", cli::col_blue("Properties:"), "\n", |
|
54 | -+ | ||
401 | +3x |
- #' )+ content_prefix, "| |- ", cli::col_cyan("Bookmarkable : "), bookmarkable, "\n", |
|
55 | -+ | ||
402 | +3x |
- #' )+ content_prefix, "| L- ", cli::col_cyan("Reportable : "), reportable, "\n" |
|
56 | +403 |
- #'+ ) |
|
57 | +404 |
- #' server <- function(input, output) {+ } |
|
58 | -+ | ||
405 | +3x |
- #' # set up input validation+ if ("ui_args" %in% what) { |
|
59 | -+ | ||
406 | +3x |
- #' iv <- InputValidator$new()+ ui_args_formatted <- format_list(x$ui_args, label_width = 19) |
|
60 | -+ | ||
407 | +3x |
- #' iv$add_rule("letter", sv_in_set(LETTERS, "choose a capital letter"))+ output <- paste0( |
|
61 | -+ | ||
408 | +3x |
- #' iv$add_rule("number", function(x) {+ output, |
|
62 | -+ | ||
409 | +3x |
- #' if (as.integer(x) %% 2L == 1L) "choose an even number"+ content_prefix, "|- ", cli::col_green("UI Arguments : "), ui_args_formatted, "\n" |
|
63 | +410 |
- #' })+ ) |
|
64 | +411 |
- #' iv$enable()+ } |
|
65 | -+ | ||
412 | +3x |
- #' # more input validation+ if ("server_args" %in% what) { |
|
66 | -+ | ||
413 | +3x |
- #' iv_par <- InputValidator$new()+ server_args_formatted <- format_list(x$server_args, label_width = 19) |
|
67 | -+ | ||
414 | +3x |
- #' iv_par$add_rule("color", sv_required(message = "choose a color"))+ output <- paste0( |
|
68 | -+ | ||
415 | +3x |
- #' iv_par$add_rule("color", function(x) {+ output, |
|
69 | -+ | ||
416 | +3x |
- #' if (length(x) > 1L) "choose only one color"+ content_prefix, "|- ", cli::col_green("Server Arguments : "), server_args_formatted, "\n" |
|
70 | +417 |
- #' })+ ) |
|
71 | +418 |
- #' iv_par$add_rule(+ } |
|
72 | -+ | ||
419 | +3x |
- #' "size",+ if ("transformators" %in% what) { |
|
73 | -+ | ||
420 | +3x |
- #' sv_between(+ output <- paste0( |
|
74 | -+ | ||
421 | +3x |
- #' left = 0.5, right = 3,+ output, |
|
75 | -+ | ||
422 | +3x |
- #' message_fmt = "choose a value between {left} and {right}"+ content_prefix, "L- ", cli::col_magenta("Transformators : "), transformators, "\n" |
|
76 | +423 |
- #' )+ ) |
|
77 | +424 |
- #' )+ } |
|
78 | +425 |
- #' iv_par$enable()+ |
|
79 | -+ | ||
426 | +3x |
- #'+ output |
|
80 | +427 |
- #' output$plot <- renderPlot({+ } |
|
81 | +428 |
- #' # validate output+ |
|
82 | +429 |
- #' switch(input[["method"]],+ #' @rdname teal_modules |
|
83 | +430 |
- #' "sequential" = {+ #' @examples |
|
84 | +431 |
- #' validate_inputs(iv)+ #' custom_module <- function( |
|
85 | +432 |
- #' validate_inputs(iv_par, header = "Set proper graphical parameters")+ #' label = "label", ui_args = NULL, server_args = NULL, |
|
86 | +433 |
- #' },+ #' datanames = "all", transformators = list(), bk = FALSE) { |
|
87 | +434 |
- #' "combined" = validate_inputs(iv, iv_par),+ #' ans <- module( |
|
88 | +435 |
- #' "grouped" = validate_inputs(list(+ #' label, |
|
89 | +436 |
- #' "Some inputs require attention" = iv,+ #' server = function(id, data, ...) {}, |
|
90 | +437 |
- #' "Set proper graphical parameters" = iv_par+ #' ui = function(id, ...) { |
|
91 | +438 |
- #' ))+ #' }, |
|
92 | +439 |
- #' )+ #' datanames = datanames, |
|
93 | +440 |
- #'+ #' transformators = transformators, |
|
94 | +441 |
- #' plot(faithful$eruptions ~ faithful$waiting,+ #' ui_args = ui_args, |
|
95 | +442 |
- #' las = 1, pch = 16,+ #' server_args = server_args |
|
96 | +443 |
- #' col = input[["color"]], cex = input[["size"]]+ #' ) |
|
97 | +444 |
- #' )+ #' attr(ans, "teal_bookmarkable") <- bk |
|
98 | +445 |
- #' })+ #' ans |
|
99 | +446 |
#' } |
|
100 | +447 |
#' |
|
101 | +448 |
- #' if (interactive()) {+ #' dummy_transformator <- teal_transform_module( |
|
102 | +449 |
- #' shinyApp(ui, server)+ #' label = "Dummy Transform", |
|
103 | +450 |
- #' }+ #' ui = function(id) div("(does nothing)"), |
|
104 | +451 |
- #'+ #' server = function(id, data) { |
|
105 | +452 |
- #' @export+ #' moduleServer(id, function(input, output, session) data) |
|
106 | +453 |
- #'+ #' } |
|
107 | +454 |
- validate_inputs <- function(..., header = "Some inputs require attention") {- |
- |
108 | -36x | -
- dots <- list(...)- |
- |
109 | -2x | -
- if (!is_validators(dots)) stop("validate_inputs accepts validators or a list thereof")+ #' ) |
|
110 | +455 | - - | -|
111 | -34x | -
- messages <- extract_validator(dots, header)- |
- |
112 | -34x | -
- failings <- if (!any_names(dots)) {- |
- |
113 | -29x | -
- add_header(messages, header)+ #' |
|
114 | +456 |
- } else {- |
- |
115 | -5x | -
- unlist(messages)+ #' plot_transformator <- teal_transform_module( |
|
116 | +457 |
- }+ #' label = "Plot Settings", |
|
117 | +458 | - - | -|
118 | -34x | -
- shiny::validate(shiny::need(is.null(failings), failings))+ #' ui = function(id) div("(does nothing)"), |
|
119 | +459 |
- }+ #' server = function(id, data) { |
|
120 | +460 |
-
+ #' moduleServer(id, function(input, output, session) data) |
|
121 | +461 |
- ### internal functions+ #' } |
|
122 | +462 |
-
+ #' ) |
|
123 | +463 |
- #' @noRd+ #' |
|
124 | +464 |
- #' @keywords internal+ #' complete_modules <- modules( |
|
125 | +465 |
- # recursive object type test+ #' custom_module( |
|
126 | +466 |
- # returns logical of length 1+ #' label = "Data Overview", |
|
127 | +467 |
- is_validators <- function(x) {- |
- |
128 | -118x | -
- all(if (is.list(x)) unlist(lapply(x, is_validators)) else inherits(x, "InputValidator"))+ #' datanames = c("ADSL", "ADAE", "ADVS"), |
|
129 | +468 |
- }+ #' ui_args = list( |
|
130 | +469 |
-
+ #' view_type = "table", |
|
131 | +470 |
- #' @noRd+ #' page_size = 10, |
|
132 | +471 |
- #' @keywords internal+ #' filters = c("ARM", "SEX", "RACE") |
|
133 | +472 |
- # test if an InputValidator object is enabled+ #' ), |
|
134 | +473 |
- # returns logical of length 1+ #' server_args = list( |
|
135 | +474 |
- # official method requested at https://github.com/rstudio/shinyvalidate/issues/64+ #' cache = TRUE, |
|
136 | +475 |
- validator_enabled <- function(x) {- |
- |
137 | -49x | -
- x$.__enclos_env__$private$enabled+ #' debounce = 1000 |
|
138 | +476 |
- }+ #' ), |
|
139 | +477 |
-
+ #' transformators = list(dummy_transformator), |
|
140 | +478 |
- #' Recursively extract messages from validator list+ #' bk = TRUE |
|
141 | +479 |
- #' @return A character vector or a list of character vectors, possibly nested and named.+ #' ), |
|
142 | +480 |
- #' @noRd+ #' modules( |
|
143 | +481 |
- #' @keywords internal+ #' label = "Nested 1", |
|
144 | +482 |
- extract_validator <- function(iv, header) {- |
- |
145 | -113x | -
- if (inherits(iv, "InputValidator")) {- |
- |
146 | -49x | -
- add_header(gather_messages(iv), header)+ #' custom_module( |
|
147 | +483 |
- } 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)+ #' label = "Interactive Plots", |
|
150 | +484 |
- }+ #' datanames = c("ADSL", "ADVS"), |
|
151 | +485 |
- }+ #' ui_args = list( |
|
152 | +486 |
-
+ #' plot_type = c("scatter", "box", "line"), |
|
153 | +487 |
- #' Collate failing messages from validator.+ #' height = 600, |
|
154 | +488 |
- #' @return `list`+ #' width = 800, |
|
155 | +489 |
- #' @noRd+ #' color_scheme = "viridis" |
|
156 | +490 |
- #' @keywords internal+ #' ), |
|
157 | +491 |
- gather_messages <- function(iv) {- |
- |
158 | -49x | -
- if (validator_enabled(iv)) {- |
- |
159 | -46x | -
- status <- iv$validate()- |
- |
160 | -46x | -
- failing_inputs <- Filter(Negate(is.null), status)- |
- |
161 | -46x | -
- unique(lapply(failing_inputs, function(x) x[["message"]]))+ #' server_args = list( |
|
162 | +492 |
- } else {+ #' render_type = "svg", |
|
163 | -3x | +||
493 | +
- warning("Validator is disabled and will be omitted.")+ #' cache_plots = TRUE |
||
164 | -3x | +||
494 | +
- list()+ #' ), |
||
165 | +495 |
- }+ #' transformators = list(dummy_transformator, plot_transformator), |
|
166 | +496 |
- }+ #' bk = TRUE |
|
167 | +497 |
-
+ #' ), |
|
168 | +498 |
- #' Add optional header to failing messages+ #' modules( |
|
169 | +499 |
- #' @noRd+ #' label = "Nested 2", |
|
170 | +500 |
- #' @keywords internal+ #' custom_module( |
|
171 | +501 |
- add_header <- function(messages, header = "") {+ #' label = "Summary Statistics", |
|
172 | -78x | +||
502 | +
- ans <- unlist(messages)+ #' datanames = "ADSL", |
||
173 | -78x | +||
503 | +
- if (length(ans) != 0L && isTRUE(nchar(header) > 0L)) {+ #' ui_args = list( |
||
174 | -31x | +||
504 | +
- ans <- c(paste0(header, "\n"), ans, "\n")+ #' stats = c("mean", "median", "sd", "range"), |
||
175 | +505 |
- }+ #' grouping = c("ARM", "SEX") |
|
176 | -78x | +||
506 | +
- ans+ #' ) |
||
177 | +507 |
- }+ #' ), |
|
178 | +508 |
-
+ #' modules( |
|
179 | +509 |
- #' Recursively check if the object contains a named list+ #' label = "Labeled nested modules", |
|
180 | +510 |
- #' @noRd+ #' custom_module( |
|
181 | +511 |
- #' @keywords internal+ #' label = "Subgroup Analysis", |
|
182 | +512 |
- any_names <- function(x) {+ #' datanames = c("ADSL", "ADAE"), |
|
183 | -103x | +||
513 | +
- any(+ #' ui_args = list( |
||
184 | -103x | +||
514 | +
- if (is.list(x)) {+ #' subgroups = c("AGE", "SEX", "RACE"), |
||
185 | -58x | +||
515 | +
- if (!is.null(names(x)) && any(names(x) != "")) TRUE else unlist(lapply(x, any_names))+ #' analysis_type = "stratified" |
||
186 | +516 |
- } else {+ #' ), |
|
187 | -40x | +||
517 | +
- FALSE+ #' bk = TRUE |
||
188 | +518 |
- }+ #' ) |
|
189 | +519 |
- )+ #' ), |
|
190 | +520 |
- }+ #' modules(custom_module(label = "Subgroup Analysis in non-labled modules")) |
1 | +521 |
- #' Manage multiple `FilteredData` objects+ #' ) |
||
2 | +522 |
- #'+ #' ), |
||
3 | +523 |
- #' @description+ #' custom_module("Non-nested module") |
||
4 | +524 |
- #' Oversee filter states across the entire application.+ #' ) |
||
5 | +525 |
#' |
||
6 | +526 |
- #' @section Slices global:+ #' cat(format(complete_modules)) |
||
7 | +527 |
- #' The key role in maintaining the module-specific filter states is played by the `.slicesGlobal`+ #' cat(format(complete_modules, what = c("ui_args", "server_args", "transformators"))) |
||
8 | +528 |
- #' object. It is a reference class that holds the following fields:+ #' @export |
||
9 | +529 |
- #' - `all_slices` (`reactiveVal`) - reactive value containing all filters registered in an app.+ format.teal_modules <- function(x, is_root = TRUE, is_last = FALSE, parent_prefix = "", ...) { |
||
10 | -+ | |||
530 | +1x |
- #' - `module_slices_api` (`reactiveValues`) - reactive field containing references to each modules'+ if (is_root) { |
||
11 | -+ | |||
531 | +1x |
- #' `FilteredData` object methods. At this moment it is used only in `srv_filter_manager` to display+ header <- pasten(cli::style_bold("TEAL ROOT")) |
||
12 | -+ | |||
532 | +1x |
- #' the filter states in a table combining informations from `all_slices` and from+ new_parent_prefix <- " " #' Initial indent for root level |
||
13 | +533 |
- #' `FilteredData$get_available_teal_slices()`.+ } else { |
||
14 | -+ | |||
534 | +! |
- #'+ if (!is.null(x$label)) { |
||
15 | -+ | |||
535 | +! |
- #' During a session only new filters are added to `all_slices` unless [`module_snapshot_manager`] is+ branch <- if (is_last) "L-" else "|-" |
||
16 | -+ | |||
536 | +! |
- #' used to restore previous state. Filters from `all_slices` can be activated or deactivated in a+ header <- pasten(parent_prefix, branch, " ", cli::style_bold(x$label)) |
||
17 | -+ | |||
537 | +! |
- #' module which is linked (both ways) by `attr(, "mapping")` so that:+ new_parent_prefix <- paste0(parent_prefix, if (is_last) " " else "| ") |
||
18 | +538 |
- #' - If module's filter is added or removed in its `FilteredData` object, this information is passed+ } else { |
||
19 | -+ | |||
539 | +! |
- #' to `SlicesGlobal` which updates `attr(, "mapping")` accordingly.+ header <- "" |
||
20 | -+ | |||
540 | +! |
- #' - When mapping changes in a `SlicesGlobal`, filters are set or removed from module's+ new_parent_prefix <- parent_prefix |
||
21 | +541 |
- #' `FilteredData`.+ } |
||
22 | +542 |
- #'+ } |
||
23 | +543 |
- #' @section Filter manager:+ |
||
24 | -+ | |||
544 | +1x |
- #' Filter-manager is split into two parts:+ if (length(x$children) > 0) { |
||
25 | -+ | |||
545 | +1x |
- #' 1. `ui/srv_filter_manager_panel` - Called once for the whole app. This module observes changes in+ children_output <- character(0) |
||
26 | -+ | |||
546 | +1x |
- #' the filters in `slices_global` and displays them in a table utilizing information from `mapping`:+ n_children <- length(x$children) |
||
27 | +547 |
- #' - (`TRUE`) - filter is active in the module+ |
||
28 | -+ | |||
548 | +1x |
- #' - (`FALSE`) - filter is inactive in the module+ for (i in seq_along(x$children)) { |
||
29 | -+ | |||
549 | +3x |
- #' - (`NA`) - filter is not available in the module+ child <- x$children[[i]] |
||
30 | -+ | |||
550 | +3x |
- #' 2. `ui/srv_module_filter_manager` - Called once for each `teal_module`. Handling filter states+ is_last_child <- (i == n_children) |
||
31 | +551 |
- #' for of single module and keeping module `FilteredData` consistent with `slices_global`, so that+ |
||
32 | -+ | |||
552 | +3x |
- #' local filters are always reflected in the `slices_global` and its mapping and vice versa.+ if (inherits(child, "teal_modules")) { |
||
33 | -+ | |||
553 | +! |
- #'+ children_output <- c( |
||
34 | -+ | |||
554 | +! |
- #'+ children_output, |
||
35 | -+ | |||
555 | +! |
- #' @param id (`character(1)`)+ format(child, |
||
36 | -+ | |||
556 | +! |
- #' `shiny` module instance id.+ is_root = FALSE, |
||
37 | -+ | |||
557 | +! |
- #'+ is_last = is_last_child, |
||
38 | -+ | |||
558 | +! |
- #' @param slices_global (`reactiveVal`)+ parent_prefix = new_parent_prefix, |
||
39 | +559 |
- #' containing `teal_slices`.+ ... |
||
40 | +560 |
- #'+ ) |
||
41 | +561 |
- #' @param module_fd (`FilteredData`)+ ) |
||
42 | +562 |
- #' Object containing the data to be filtered in a single `teal` module.+ } else { |
||
43 | -+ | |||
563 | +3x |
- #'+ children_output <- c( |
||
44 | -+ | |||
564 | +3x |
- #' @return+ children_output, |
||
45 | -+ | |||
565 | +3x |
- #' Module returns a `slices_global` (`reactiveVal`) containing a `teal_slices` object with mapping.+ format(child, |
||
46 | -+ | |||
566 | +3x |
- #'+ is_last = is_last_child, |
||
47 | -+ | |||
567 | +3x |
- #' @encoding UTF-8+ parent_prefix = new_parent_prefix, |
||
48 | +568 |
- #'+ ... |
||
49 | +569 |
- #' @name module_filter_manager+ ) |
||
50 | +570 |
- #' @rdname module_filter_manager+ ) |
||
51 | +571 |
- #'+ } |
||
52 | +572 |
- NULL+ } |
||
53 | +573 | |||
54 | -+ | |||
574 | +1x |
- #' @rdname module_filter_manager+ paste0(header, paste(children_output, collapse = "")) |
||
55 | +575 |
- ui_filter_manager_panel <- function(id) {+ } else { |
||
56 | +576 | ! |
- ns <- NS(id)+ header |
|
57 | -! | +|||
577 | +
- tags$button(+ } |
|||
58 | -! | +|||
578 | +
- id = ns("show_filter_manager"),+ } |
|||
59 | -! | +|||
579 | +
- class = "btn action-button wunder_bar_button",+ |
|||
60 | -! | +|||
580 | +
- title = "View filter mapping",+ #' @rdname teal_modules+ |
+ |||
581 | ++ |
+ #' @export+ |
+ ||
582 | ++ |
+ print.teal_module <- function(x, ...) { |
||
61 | +583 | ! |
- suppressMessages(icon("fas fa-grip"))+ cat(format(x, ...)) |
|
62 | -+ | |||
584 | +! |
- )+ invisible(x) |
||
63 | +585 |
} |
||
64 | +586 | |||
65 | +587 |
- #' @rdname module_filter_manager+ #' @rdname teal_modules |
||
66 | +588 |
- #' @keywords internal+ #' @export |
||
67 | +589 |
- srv_filter_manager_panel <- function(id, slices_global) {- |
- ||
68 | -87x | -
- checkmate::assert_string(id)- |
- ||
69 | -87x | -
- checkmate::assert_class(slices_global, ".slicesGlobal")+ print.teal_modules <- function(x, ...) { |
||
70 | -87x | +|||
590 | +! |
- moduleServer(id, function(input, output, session) {+ cat(format(x, ...)) |
||
71 | -87x | +|||
591 | +! |
- setBookmarkExclude(c("show_filter_manager"))+ invisible(x) |
||
72 | -87x | +|||
592 | +
- observeEvent(input$show_filter_manager, {+ } |
|||
73 | -! | +|||
593 | +
- logger::log_debug("srv_filter_manager_panel@1 show_filter_manager button has been clicked.")+ |
|||
74 | -! | +|||
594 | +
- showModal(+ #' @param modules (`teal_module` or `teal_modules`) |
|||
75 | -! | +|||
595 | +
- modalDialog(+ #' @rdname teal_modules |
|||
76 | -! | +|||
596 | +
- ui_filter_manager(session$ns("filter_manager")),+ #' @examples |
|||
77 | -! | +|||
597 | +
- class = "filter_manager_modal",+ #' # change the module's datanames |
|||
78 | -! | +|||
598 | +
- size = "l",+ #' set_datanames(module(datanames = "all"), "a") |
|||
79 | -! | +|||
599 | +
- footer = NULL,+ #' |
|||
80 | -! | +|||
600 | +
- easyClose = TRUE+ #' # change modules' datanames |
|||
81 | +601 |
- )+ #' set_datanames( |
||
82 | +602 |
- )+ #' modules( |
||
83 | +603 |
- })+ #' module(datanames = "all"), |
||
84 | -87x | +|||
604 | +
- srv_filter_manager("filter_manager", slices_global = slices_global)+ #' module(datanames = "a") |
|||
85 | +605 |
- })+ #' ), |
||
86 | +606 |
- }+ #' "b" |
||
87 | +607 |
-
+ #' ) |
||
88 | +608 |
- #' @rdname module_filter_manager+ #' @export |
||
89 | +609 |
- ui_filter_manager <- function(id) {+ set_datanames <- function(modules, datanames) { |
||
90 | +610 | ! |
- ns <- NS(id)+ checkmate::assert_multi_class(modules, c("teal_modules", "teal_module")) |
|
91 | +611 | ! |
- actionButton(ns("filter_manager"), NULL, icon = icon("fas fa-filter"))+ if (inherits(modules, "teal_modules")) { |
|
92 | +612 | ! |
- tags$div(+ modules$children <- lapply(modules$children, set_datanames, datanames)+ |
+ |
613 | ++ |
+ } else { |
||
93 | +614 | ! |
- class = "filter_manager_content",+ if (identical(modules$datanames, "all")) { |
|
94 | +615 | ! |
- tableOutput(ns("slices_table"))+ modules$datanames <- datanames |
|
95 | +616 |
- )+ } else { |
||
96 | -+ | |||
617 | +! |
- }+ warning( |
||
97 | -+ | |||
618 | +! |
-
+ "Not possible to modify datanames of the module ", modules$label, |
||
98 | -+ | |||
619 | +! |
- #' @rdname module_filter_manager+ ". set_datanames() can only change datanames if it was set to \"all\".", |
||
99 | -+ | |||
620 | +! |
- srv_filter_manager <- function(id, slices_global) {+ call. = FALSE |
||
100 | -87x | +|||
621 | +
- checkmate::assert_string(id)+ ) |
|||
101 | -87x | +|||
622 | +
- checkmate::assert_class(slices_global, ".slicesGlobal")+ } |
|||
102 | +623 |
-
+ } |
||
103 | -87x | +|||
624 | +! |
- moduleServer(id, function(input, output, session) {+ modules |
||
104 | -87x | +|||
625 | +
- logger::log_debug("filter_manager_srv initializing.")+ } |
|||
105 | +626 | |||
106 | +627 |
- # Bookmark slices global with mapping.+ # utilities ---- |
||
107 | -87x | +|||
628 | +
- session$onBookmark(function(state) {+ ## subset or modify modules ---- |
|||
108 | -! | +|||
629 | +
- logger::log_debug("filter_manager_srv@onBookmark: storing filter state")+ |
|||
109 | -! | +|||
630 | +
- state$values$filter_state_on_bookmark <- as.list(+ #' Append a `teal_module` to `children` of a `teal_modules` object |
|||
110 | -! | +|||
631 | +
- slices_global$all_slices(),+ #' @keywords internal |
|||
111 | -! | +|||
632 | +
- recursive = TRUE+ #' @param modules (`teal_modules`) |
|||
112 | +633 |
- )+ #' @param module (`teal_module`) object to be appended onto the children of `modules` |
||
113 | +634 |
- })+ #' @return A `teal_modules` object with `module` appended. |
||
114 | +635 |
-
+ append_module <- function(modules, module) { |
||
115 | -87x | +636 | +8x |
- bookmarked_slices <- restoreValue(session$ns("filter_state_on_bookmark"), NULL)+ checkmate::assert_class(modules, "teal_modules") |
116 | -87x | -
- if (!is.null(bookmarked_slices)) {- |
- ||
117 | -! | +637 | +6x |
- logger::log_debug("filter_manager_srv: restoring filter state from bookmark.")+ checkmate::assert_class(module, "teal_module") |
118 | -! | +|||
638 | +4x |
- slices_global$slices_set(bookmarked_slices)+ modules$children <- c(modules$children, list(module)) |
||
119 | -+ | |||
639 | +4x |
- }+ labels <- vapply(modules$children, function(submodule) submodule$label, character(1)) |
||
120 | -+ | |||
640 | +4x |
-
+ names(modules$children) <- get_unique_labels(labels) |
||
121 | -87x | +641 | +4x |
- mapping_table <- reactive({+ modules |
122 | +642 |
- # We want this to be reactive on slices_global$all_slices() only as get_available_teal_slices()+ } |
||
123 | +643 |
- # is dependent on slices_global$all_slices().+ |
||
124 | -96x | +|||
644 | +
- module_labels <- setdiff(+ #' Extract/Remove module(s) of specific class |
|||
125 | -96x | +|||
645 | +
- names(attr(slices_global$all_slices(), "mapping")),+ #' |
|||
126 | -96x | +|||
646 | +
- "Report previewer"+ #' Given a `teal_module` or a `teal_modules`, return the elements of the structure according to `class`. |
|||
127 | +647 |
- )+ #' |
||
128 | -96x | +|||
648 | +
- isolate({+ #' @param modules (`teal_modules`) |
|||
129 | -96x | +|||
649 | +
- mm <- as.data.frame(+ #' @param class The class name of `teal_module` to be extracted or dropped. |
|||
130 | -96x | +|||
650 | +
- sapply(+ #' @keywords internal |
|||
131 | -96x | +|||
651 | +
- module_labels,+ #' @return |
|||
132 | -96x | +|||
652 | +
- simplify = FALSE,+ #' - For `extract_module`, a `teal_module` of class `class` or `teal_modules` containing modules of class `class`. |
|||
133 | -96x | +|||
653 | +
- function(module_label) {+ #' - For `drop_module`, the opposite, which is all `teal_modules` of class other than `class`. |
|||
134 | -109x | +|||
654 | +
- available_slices <- slices_global$module_slices_api[[module_label]]$get_available_teal_slices()+ #' @rdname module_management |
|||
135 | -101x | +|||
655 | +
- global_ids <- sapply(slices_global$all_slices(), `[[`, "id", simplify = FALSE)+ extract_module <- function(modules, class) { |
|||
136 | -101x | +656 | +28x |
- module_ids <- sapply(slices_global$slices_get(module_label), `[[`, "id", simplify = FALSE)+ if (inherits(modules, class)) { |
137 | -101x | +|||
657 | +! |
- allowed_ids <- vapply(available_slices, `[[`, character(1L), "id")+ modules |
||
138 | -101x | +658 | +28x |
- active_ids <- global_ids %in% module_ids+ } else if (inherits(modules, "teal_module")) { |
139 | -101x | -
- setNames(nm = global_ids, ifelse(global_ids %in% allowed_ids, active_ids, NA))- |
- ||
140 | -+ | 659 | +15x |
- }+ NULL |
141 | -+ | |||
660 | +13x |
- ),+ } else if (inherits(modules, "teal_modules")) { |
||
142 | -96x | +661 | +13x |
- check.names = FALSE+ Filter(function(x) length(x) > 0L, lapply(modules$children, extract_module, class)) |
143 | +662 |
- )+ } |
||
144 | -88x | +|||
663 | +
- colnames(mm)[colnames(mm) == "global_filters"] <- "Global filters"+ } |
|||
145 | +664 | |||
146 | -88x | +|||
665 | +
- mm+ #' @keywords internal |
|||
147 | +666 |
- })+ #' @return `teal_modules` |
||
148 | +667 |
- })+ #' @rdname module_management |
||
149 | +668 |
-
+ drop_module <- function(modules, class) { |
||
150 | -87x | +|||
669 | +! |
- output$slices_table <- renderTable(+ if (inherits(modules, class)) { |
||
151 | -87x | +|||
670 | +! |
- expr = {+ NULL |
||
152 | -96x | +|||
671 | +! |
- logger::log_debug("filter_manager_srv@1 rendering slices_table.")+ } else if (inherits(modules, "teal_module")) { |
||
153 | -96x | +|||
672 | +! |
- mm <- mapping_table()+ modules |
||
154 | -+ | |||
673 | +! |
-
+ } else if (inherits(modules, "teal_modules")) { |
||
155 | -+ | |||
674 | +! |
- # Display logical values as UTF characters.+ do.call( |
||
156 | -88x | +|||
675 | +! |
- mm[] <- lapply(mm, ifelse, yes = intToUtf8(9989), no = intToUtf8(10060))+ "modules", |
||
157 | -88x | +|||
676 | +! |
- mm[] <- lapply(mm, function(x) ifelse(is.na(x), intToUtf8(128306), x))+ c(Filter(function(x) length(x) > 0L, lapply(modules$children, drop_module, class)), label = modules$label) |
||
158 | +677 |
-
+ ) |
||
159 | +678 |
- # Display placeholder if no filters defined.- |
- ||
160 | -88x | -
- if (nrow(mm) == 0L) {- |
- ||
161 | -64x | -
- mm <- data.frame(`Filter manager` = "No filters specified.", check.names = FALSE)+ } |
||
162 | -64x | +|||
679 | +
- rownames(mm) <- ""+ } |
|||
163 | +680 |
- }+ |
||
164 | -88x | +|||
681 | +
- mm+ ## read modules ---- |
|||
165 | +682 |
- },+ |
||
166 | -87x | +|||
683 | +
- rownames = TRUE+ #' Does the object make use of the `arg` |
|||
167 | +684 |
- )+ #' |
||
168 | +685 |
-
+ #' @param modules (`teal_module` or `teal_modules`) object |
||
169 | -87x | +|||
686 | +
- mapping_table # for testing purpose+ #' @param arg (`character(1)`) names of the arguments to be checked against formals of `teal` modules. |
|||
170 | +687 |
- })+ #' @return `logical` whether the object makes use of `arg`. |
||
171 | +688 |
- }+ #' @rdname is_arg_used |
||
172 | +689 |
-
+ #' @keywords internal |
||
173 | +690 |
- #' @rdname module_filter_manager+ is_arg_used <- function(modules, arg) { |
||
174 | -+ | |||
691 | +519x |
- srv_module_filter_manager <- function(id, module_fd, slices_global) {+ checkmate::assert_string(arg) |
||
175 | -112x | +692 | +516x |
- checkmate::assert_string(id)+ if (inherits(modules, "teal_modules")) { |
176 | -112x | +693 | +20x |
- assert_reactive(module_fd)+ any(unlist(lapply(modules$children, is_arg_used, arg))) |
177 | -112x | +694 | +496x |
- checkmate::assert_class(slices_global, ".slicesGlobal")+ } else if (inherits(modules, "teal_module")) { |
178 | -+ | |||
695 | +32x |
-
+ is_arg_used(modules$server, arg) || is_arg_used(modules$ui, arg) |
||
179 | -112x | +696 | +464x |
- moduleServer(id, function(input, output, session) {+ } else if (is.function(modules)) { |
180 | -112x | +697 | +462x |
- logger::log_debug("srv_module_filter_manager initializing for module: { id }.")+ isTRUE(arg %in% names(formals(modules))) |
181 | +698 |
- # Track filter global and local states.+ } else { |
||
182 | -112x | +699 | +2x |
- slices_global_module <- reactive({+ stop("is_arg_used function not implemented for this object") |
183 | -201x | +|||
700 | +
- slices_global$slices_get(module_label = id)+ } |
|||
184 | +701 |
- })+ } |
||
185 | -112x | +|||
702 | +
- slices_module <- reactive(req(module_fd())$get_filter_state())+ |
|||
186 | +703 | |||
187 | -112x | +|||
704 | +
- module_fd_previous <- reactiveVal(NULL)+ #' Get module depth |
|||
188 | +705 |
-
+ #' |
||
189 | +706 |
- # Set (reactively) available filters for the module.+ #' Depth starts at 0, so a single `teal.module` has depth 0. |
||
190 | -112x | +|||
707 | +
- obs1 <- observeEvent(module_fd(), priority = 1, {+ #' Nesting it increases overall depth by 1. |
|||
191 | -93x | +|||
708 | +
- logger::log_debug("srv_module_filter_manager@1 setting initial slices for module: { id }.")+ #' |
|||
192 | +709 |
- # Filters relevant for the module in module-specific app.+ #' @inheritParams init |
||
193 | -93x | +|||
710 | +
- slices <- slices_global_module()+ #' @param depth optional integer determining current depth level |
|||
194 | +711 |
-
+ #' |
||
195 | +712 |
- # Clean up previous filter states and refresh cache of previous module_fd with current+ #' @return Depth level for given module.+ |
+ ||
713 | ++ |
+ #' @keywords internal+ |
+ ||
714 | ++ |
+ modules_depth <- function(modules, depth = 0L) { |
||
196 | -3x | +715 | +12x |
- if (!is.null(module_fd_previous())) module_fd_previous()$finalize()+ checkmate::assert_multi_class(modules, c("teal_module", "teal_modules")) |
197 | -93x | +716 | +12x |
- module_fd_previous(module_fd())+ checkmate::assert_int(depth, lower = 0) |
198 | -+ | |||
717 | +11x |
-
+ if (inherits(modules, "teal_modules")) {+ |
+ ||
718 | +4x | +
+ max(vapply(modules$children, modules_depth, integer(1), depth = depth + 1L)) |
||
199 | +719 |
- # Setting filter states from slices_global:+ } else {+ |
+ ||
720 | +7x | +
+ depth |
||
200 | +721 |
- # 1. when app initializes slices_global set to initial filters (specified by app developer)+ } |
||
201 | +722 |
- # 2. when data reinitializes slices_global reflects latest filter states+ } |
||
202 | +723 | |||
203 | -93x | +|||
724 | +
- module_fd()$set_filter_state(slices)+ #' Retrieve labels from `teal_modules` |
|||
204 | +725 |
-
+ #' |
||
205 | +726 |
- # irrelevant filters are discarded in FilteredData$set_available_teal_slices+ #' @param modules (`teal_modules`) |
||
206 | +727 |
- # it means we don't need to subset slices_global$all_slices() from filters refering to irrelevant datasets+ #' @return A `list` containing the labels of the modules. If the modules are nested, |
||
207 | -93x | +|||
728 | +
- module_fd()$set_available_teal_slices(slices_global$all_slices)+ #' the function returns a nested `list` of labels. |
|||
208 | +729 |
-
+ #' @keywords internal |
||
209 | +730 |
- # this needed in filter_manager_srv+ module_labels <- function(modules) { |
||
210 | -93x | +731 | +199x |
- slices_global$module_slices_api_set(+ if (inherits(modules, "teal_modules")) { |
211 | -93x | +732 | +87x |
- id,+ lapply(modules$children, module_labels) |
212 | -93x | +|||
733 | +
- list(+ } else { |
|||
213 | -93x | +734 | +112x |
- get_available_teal_slices = module_fd()$get_available_teal_slices(),+ modules$label |
214 | -93x | +|||
735 | +
- set_filter_state = module_fd()$set_filter_state, # for testing purpose+ } |
|||
215 | -93x | +|||
736 | +
- get_filter_state = module_fd()$get_filter_state # for testing purpose+ } |
|||
216 | +737 |
- )+ |
||
217 | +738 |
- )+ #' Retrieve `teal_bookmarkable` attribute from `teal_modules` |
||
218 | +739 |
- })+ #' |
||
219 | +740 |
-
+ #' @param modules (`teal_modules` or `teal_module`) object |
||
220 | +741 |
- # Update global state and mapping matrix when module filters change.+ #' @return named list of the same structure as `modules` with `TRUE` or `FALSE` values indicating |
||
221 | -112x | +|||
742 | +
- obs2 <- observeEvent(slices_module(), priority = 0, {+ #' whether the module is bookmarkable.+ |
+ |||
743 | ++ |
+ #' @keywords internal+ |
+ ||
744 | ++ |
+ modules_bookmarkable <- function(modules) { |
||
222 | -113x | +745 | +199x | +
+ checkmate::assert_multi_class(modules, c("teal_modules", "teal_module"))+ |
+
746 | +199x |
- this_slices <- slices_module()+ if (inherits(modules, "teal_modules")) { |
||
223 | -113x | +747 | +87x |
- slices_global$slices_append(this_slices) # append new slices to the all_slices list+ setNames( |
224 | -113x | +748 | +87x |
- mapping_elem <- setNames(nm = id, list(vapply(this_slices, `[[`, character(1L), "id")))+ lapply(modules$children, modules_bookmarkable), |
225 | -113x | +749 | +87x |
- slices_global$slices_active(mapping_elem)+ vapply(modules$children, `[[`, "label", FUN.VALUE = character(1)) |
226 | +750 |
- })+ ) |
||
227 | +751 |
-
+ } else { |
||
228 | +752 | 112x |
- obs3 <- observeEvent(slices_global_module(), {- |
- |
229 | -135x | -
- global_vs_module <- setdiff_teal_slices(slices_global_module(), slices_module())- |
- ||
230 | -135x | -
- module_vs_global <- setdiff_teal_slices(slices_module(), slices_global_module())+ attr(modules, "teal_bookmarkable", exact = TRUE) |
||
231 | -126x | +|||
753 | +
- if (length(global_vs_module) || length(module_vs_global)) {+ } |
|||
232 | +754 |
- # Comment: (Nota Bene) Normally new filters for a module are added through module-filter-panel, and slices+ } |
233 | +1 |
- # global are updated automatically so slices_module -> slices_global_module are equal.+ #' Data summary |
||
234 | +2 |
- # this if is valid only when a change is made on the global level so the change needs to be propagated down+ #' @description |
||
235 | +3 |
- # to the module (for example through snapshot manager). If it happens both slices are different+ #' Module and its utils to display the number of rows and subjects in the filtered and unfiltered data. |
||
236 | -13x | +|||
4 | +
- logger::log_debug("srv_module_filter_manager@3 (N.B.) global state has changed for a module:{ id }.")+ #' |
|||
237 | -13x | +|||
5 | +
- module_fd()$clear_filter_states()+ #' @details Handling different data classes: |
|||
238 | -13x | +|||
6 | +
- module_fd()$set_filter_state(slices_global_module())+ #' `get_filter_overview()` is a pseudo S3 method which has variants for: |
|||
239 | +7 |
- }+ #' - `array` (`data.frame`, `DataFrame`, `array`, `Matrix` and `SummarizedExperiment`): Method variant |
||
240 | +8 |
- })+ #' can be applied to any two-dimensional objects on which [ncol()] can be used. |
||
241 | +9 |
-
+ #' - `MultiAssayExperiment`: for which summary contains counts for `colData` and all `experiments`. |
||
242 | -112x | +|||
10 | +
- slices_module # returned for testing purpose+ #' - For other data types module displays data name with warning icon and no more details. |
|||
243 | +11 |
- })+ #' |
||
244 | +12 |
- }+ #' Module includes also "Show/Hide unsupported" button to toggle rows of the summary table |
||
245 | +13 |
-
+ #' containing datasets where number of observations are not calculated. |
||
246 | +14 |
- #' @importFrom shiny reactiveVal reactiveValues+ #' |
||
247 | +15 |
- methods::setOldClass("reactiveVal")+ #' @param id (`character(1)`) `shiny` module instance id. |
||
248 | +16 |
- methods::setOldClass("reactivevalues")+ #' @param teal_data (`reactive` returning `teal_data`) |
||
249 | +17 |
-
+ #' |
||
250 | +18 |
- #' @importFrom methods new+ #' @name module_data_summary |
||
251 | +19 |
- #' @rdname module_filter_manager+ #' @rdname module_data_summary |
||
252 | +20 |
- .slicesGlobal <- methods::setRefClass(".slicesGlobal", # nolint: object_name.+ #' @keywords internal |
||
253 | +21 |
- fields = list(+ #' @return `NULL`. |
||
254 | +22 |
- all_slices = "reactiveVal",+ NULL |
||
255 | +23 |
- module_slices_api = "reactivevalues"+ |
||
256 | +24 |
- ),+ #' @rdname module_data_summary |
||
257 | +25 |
- methods = list(+ ui_data_summary <- function(id) { |
||
258 | -+ | |||
26 | +! |
- initialize = function(slices = teal_slices(), module_labels) {+ ns <- NS(id) |
||
259 | -87x | +|||
27 | +! |
- shiny::isolate({+ content_id <- ns("filters_overview_contents") |
||
260 | -87x | +|||
28 | +! |
- checkmate::assert_class(slices, "teal_slices")+ tags$div( |
||
261 | -+ | |||
29 | +! |
- # needed on init to not mix "global_filters" with module-specific-slots+ id = id, |
||
262 | -87x | +|||
30 | +! |
- if (isTRUE(attr(slices, "module_specific"))) {+ class = "well", |
||
263 | -11x | +|||
31 | +! |
- old_mapping <- attr(slices, "mapping")+ tags$div( |
||
264 | -11x | +|||
32 | +! |
- new_mapping <- sapply(module_labels, simplify = FALSE, function(module_label) {+ class = "row", |
||
265 | -20x | +|||
33 | +! |
- unique(unlist(old_mapping[c(module_label, "global_filters")]))+ tags$div( |
||
266 | -+ | |||
34 | +! |
- })+ class = "col-sm-9", |
||
267 | -11x | +|||
35 | +! |
- attr(slices, "mapping") <- new_mapping+ tags$label("Active Filter Summary", class = "text-primary mb-4") |
||
268 | +36 |
- }+ ), |
||
269 | -87x | +|||
37 | +! |
- .self$all_slices <<- shiny::reactiveVal(slices)+ tags$div( |
||
270 | -87x | +|||
38 | +! |
- .self$module_slices_api <<- shiny::reactiveValues()+ class = "col-sm-3", |
||
271 | -87x | +|||
39 | +! |
- .self$slices_append(slices)+ tags$i( |
||
272 | -87x | +|||
40 | +! |
- .self$slices_active(attr(slices, "mapping"))+ class = "remove pull-right fa fa-angle-down", |
||
273 | -87x | +|||
41 | +! |
- invisible(.self)+ style = "cursor: pointer;", |
||
274 | -+ | |||
42 | +! |
- })+ title = "fold/expand data summary panel", |
||
275 | -+ | |||
43 | +! |
- },+ onclick = sprintf("togglePanelItems(this, '%s', 'fa-angle-right', 'fa-angle-down');", content_id) |
||
276 | +44 |
- is_module_specific = function() {- |
- ||
277 | -296x | -
- isTRUE(attr(.self$all_slices(), "module_specific"))+ ) |
||
278 | +45 |
- },+ ) |
||
279 | +46 |
- module_slices_api_set = function(module_label, functions_list) {+ ), |
||
280 | -93x | +|||
47 | +! |
- shiny::isolate({+ tags$div( |
||
281 | -93x | +|||
48 | +! |
- if (!.self$is_module_specific()) {+ id = content_id, |
||
282 | -77x | +|||
49 | +! |
- module_label <- "global_filters"+ tags$div( |
||
283 | -+ | |||
50 | +! |
- }+ class = "teal_active_summary_filter_panel", |
||
284 | -93x | +|||
51 | +! |
- if (!identical(.self$module_slices_api[[module_label]], functions_list)) {+ tableOutput(ns("table")) |
||
285 | -93x | +|||
52 | +
- .self$module_slices_api[[module_label]] <- functions_list+ ) |
|||
286 | +53 |
- }+ ) |
||
287 | -93x | +|||
54 | +
- invisible(.self)+ ) |
|||
288 | +55 |
- })+ } |
||
289 | +56 |
- },+ |
||
290 | +57 |
- slices_deactivate_all = function(module_label) {+ #' @rdname module_data_summary |
||
291 | -! | +|||
58 | +
- shiny::isolate({+ srv_data_summary <- function(id, data) { |
|||
292 | -! | +|||
59 | +86x |
- new_slices <- .self$all_slices()+ assert_reactive(data) |
||
293 | -! | +|||
60 | +86x |
- old_mapping <- attr(new_slices, "mapping")+ moduleServer( |
||
294 | -+ | |||
61 | +86x |
-
+ id = id, |
||
295 | -! | +|||
62 | +86x |
- new_mapping <- if (.self$is_module_specific()) {+ function(input, output, session) { |
||
296 | -! | +|||
63 | +86x |
- new_module_mapping <- setNames(nm = module_label, list(character(0)))+ logger::log_debug("srv_data_summary initializing") |
||
297 | -! | +|||
64 | +
- modifyList(old_mapping, new_module_mapping)+ |
|||
298 | -! | +|||
65 | +86x |
- } else if (missing(module_label)) {+ summary_table <- reactive({ |
||
299 | -! | +|||
66 | +94x |
- lapply(+ req(inherits(data(), "teal_data")) |
||
300 | -! | +|||
67 | +88x |
- attr(.self$all_slices(), "mapping"),+ if (!length(data())) { |
||
301 | +68 | ! |
- function(x) character(0)- |
- |
302 | -- |
- )+ return(NULL) |
||
303 | +69 |
- } else {- |
- ||
304 | -! | -
- old_mapping[[module_label]] <- character(0)+ } |
||
305 | -! | +|||
70 | +88x |
- old_mapping+ get_filter_overview_wrapper(data) |
||
306 | +71 |
- }+ }) |
||
307 | +72 | |||
308 | -! | +|||
73 | +86x |
- if (!identical(new_mapping, old_mapping)) {+ output$table <- renderUI({ |
||
309 | -! | +|||
74 | +94x |
- logger::log_debug(".slicesGlobal@slices_deactivate_all: deactivating all slices.")+ summary_table_out <- try(summary_table(), silent = TRUE) |
||
310 | -! | +|||
75 | +94x |
- attr(new_slices, "mapping") <- new_mapping+ if (inherits(summary_table_out, "try-error")) { |
||
311 | -! | +|||
76 | +
- .self$all_slices(new_slices)+ # Ignore silent shiny error |
|||
312 | -+ | |||
77 | +6x |
- }+ if (!inherits(attr(summary_table_out, "condition"), "shiny.silent.error")) { |
||
313 | +78 | ! |
- invisible(.self)+ stop("Error occurred during data processing. See details in the main panel.") |
|
314 | +79 |
- })+ } |
||
315 | -+ | |||
80 | +88x |
- },+ } else if (is.null(summary_table_out)) { |
||
316 | -+ | |||
81 | +2x |
- slices_active = function(mapping_elem) {+ "no datasets to show" |
||
317 | -203x | +|||
82 | +
- shiny::isolate({+ } else { |
|||
318 | -203x | +83 | +86x |
- if (.self$is_module_specific()) {+ is_unsupported <- apply(summary_table(), 1, function(x) all(is.na(x[-1]))) |
319 | -36x | +84 | +86x |
- new_mapping <- modifyList(attr(.self$all_slices(), "mapping"), mapping_elem)+ summary_table_out[is.na(summary_table_out)] <- "" |
320 | -+ | |||
85 | +86x |
- } else {+ body_html <- apply( |
||
321 | -167x | +86 | +86x |
- new_mapping <- setNames(nm = "global_filters", list(unique(unlist(mapping_elem))))+ summary_table_out, |
322 | -+ | |||
87 | +86x |
- }+ 1, |
||
323 | -+ | |||
88 | +86x |
-
+ function(x) { |
||
324 | -203x | +89 | +162x |
- if (!identical(new_mapping, attr(.self$all_slices(), "mapping"))) {+ is_supported <- !all(x[-1] == "") |
325 | -146x | +90 | +162x |
- mapping_modules <- toString(names(new_mapping))+ if (is_supported) { |
326 | -146x | +91 | +153x |
- logger::log_debug(".slicesGlobal@slices_active: changing mapping for module(s): { mapping_modules }.")+ tags$tr( |
327 | -146x | +92 | +153x |
- new_slices <- .self$all_slices()+ tagList( |
328 | -146x | +93 | +153x |
- attr(new_slices, "mapping") <- new_mapping+ tags$td(x[1]), |
329 | -146x | +94 | +153x |
- .self$all_slices(new_slices)+ lapply(x[-1], tags$td) |
330 | +95 |
- }+ ) |
||
331 | +96 |
-
+ ) |
||
332 | -203x | +|||
97 | +
- invisible(.self)+ } |
|||
333 | +98 |
- })+ } |
||
334 | +99 |
- },+ ) |
||
335 | +100 |
- # - only new filters are appended to the $all_slices+ |
||
336 | -+ | |||
101 | +86x |
- # - mapping is not updated here+ header_labels <- tools::toTitleCase(names(summary_table_out))+ |
+ ||
102 | +86x | +
+ header_labels[header_labels == "Dataname"] <- "Data Name"+ |
+ ||
103 | +86x | +
+ header_html <- tags$tr(tagList(lapply(header_labels, tags$td))) |
||
337 | +104 |
- slices_append = function(slices, activate = FALSE) {+ |
||
338 | -203x | +105 | +86x |
- shiny::isolate({+ table_html <- tags$table( |
339 | -203x | +106 | +86x |
- if (!is.teal_slices(slices)) {+ class = "table custom-table", |
340 | -! | +|||
107 | +86x |
- slices <- as.teal_slices(slices)+ tags$thead(header_html), |
||
341 | -+ | |||
108 | +86x |
- }+ tags$tbody(body_html) |
||
342 | +109 |
-
+ ) |
||
343 | -+ | |||
110 | +86x |
- # to make sure that we don't unnecessary trigger $all_slices <reactiveVal>+ div( |
||
344 | -203x | +111 | +86x |
- new_slices <- setdiff_teal_slices(slices, .self$all_slices())+ table_html, |
345 | -203x | +112 | +86x |
- old_mapping <- attr(.self$all_slices(), "mapping")+ if (any(is_unsupported)) { |
346 | -203x | +113 | +9x |
- if (length(new_slices)) {+ p( |
347 | -6x | +114 | +9x |
- new_ids <- vapply(new_slices, `[[`, character(1L), "id")+ class = c("pull-right", "float-right", "text-secondary"), |
348 | -6x | +115 | +9x |
- logger::log_debug(".slicesGlobal@slices_append: appending new slice(s): { new_ids }.")+ style = "font-size: 0.8em;", |
349 | -6x | +116 | +9x |
- slices_ids <- vapply(.self$all_slices(), `[[`, character(1L), "id")+ sprintf("And %s more unfilterable object(s)", sum(is_unsupported)), |
350 | -6x | +117 | +9x |
- lapply(new_slices, function(slice) {+ icon( |
351 | -+ | |||
118 | +9x |
- # In case the new state has the same id as an existing one, add a suffix+ name = "far fa-circle-question", |
||
352 | -6x | +119 | +9x |
- if (slice$id %in% slices_ids) {+ title = paste( |
353 | -1x | +120 | +9x |
- slice$id <- utils::tail(make.unique(c(slices_ids, slice$id), sep = "_"), 1)+ sep = "", |
354 | -+ | |||
121 | +9x |
- }+ collapse = "\n", |
||
355 | -+ | |||
122 | +9x |
- })+ shQuote(summary_table()[is_unsupported, "dataname"]), |
||
356 | +123 |
-
+ " (", |
||
357 | -6x | +124 | +9x |
- new_slices_all <- c(.self$all_slices(), new_slices)+ vapply( |
358 | -6x | +125 | +9x |
- attr(new_slices_all, "mapping") <- old_mapping+ summary_table()[is_unsupported, "dataname"], |
359 | -6x | +126 | +9x |
- .self$all_slices(new_slices_all)+ function(x) class(data()[[x]])[1],+ |
+
127 | +9x | +
+ character(1L) |
||
360 | +128 |
- }+ ), |
||
361 | +129 |
-
+ ")" |
||
362 | -203x | +|||
130 | +
- invisible(.self)+ ) |
|||
363 | +131 |
- })+ ) |
||
364 | +132 |
- },+ ) |
||
365 | +133 |
- slices_get = function(module_label) {+ } |
||
366 | -302x | +|||
134 | +
- if (missing(module_label)) {+ ) |
|||
367 | -! | +|||
135 | +
- .self$all_slices()+ } |
|||
368 | +136 |
- } else {+ }) |
||
369 | -302x | +|||
137 | +
- module_ids <- unlist(attr(.self$all_slices(), "mapping")[c(module_label, "global_filters")])+ |
|||
370 | -302x | +138 | +86x |
- Filter(+ NULL |
371 | -302x | +|||
139 | +
- function(slice) slice$id %in% module_ids,+ } |
|||
372 | -302x | +|||
140 | +
- .self$all_slices()+ ) |
|||
373 | +141 |
- )+ } |
||
374 | +142 |
- }+ |
||
375 | +143 |
- },+ #' @rdname module_data_summary |
||
376 | +144 |
- slices_set = function(slices) {+ get_filter_overview_wrapper <- function(teal_data) { |
||
377 | -7x | +|||
145 | +
- shiny::isolate({+ # Sort datanames in topological order |
|||
378 | -7x | +146 | +88x |
- if (!is.teal_slices(slices)) {+ datanames <- names(teal_data()) |
379 | -! | +|||
147 | +88x |
- slices <- as.teal_slices(slices)+ joinkeys <- teal.data::join_keys(teal_data()) |
||
380 | +148 |
- }+ |
||
381 | -7x | +149 | +88x |
- .self$all_slices(slices)+ current_data_objs <- sapply( |
382 | -7x | +150 | +88x |
- invisible(.self)+ datanames,+ |
+
151 | +88x | +
+ function(name) teal_data()[[name]],+ |
+ ||
152 | +88x | +
+ simplify = FALSE |
||
383 | +153 |
- })+ ) |
||
384 | -+ | |||
154 | +88x |
- },+ initial_data_objs <- teal_data()[[".raw_data"]] |
||
385 | +155 |
- show = function() {+ |
||
386 | -! | +|||
156 | +88x |
- shiny::isolate(print(.self$all_slices()))+ out <- lapply( |
||
387 | -! | +|||
157 | +88x |
- invisible(.self)+ datanames, |
||
388 | -+ | |||
158 | +88x |
- }+ function(dataname) { |
||
389 | -+ | |||
159 | +157x |
- )+ parent <- teal.data::parent(joinkeys, dataname) |
||
390 | -+ | |||
160 | +157x |
- )+ subject_keys <- if (length(parent) > 0) { |
1 | -+ | ||
161 | +8x |
- #' Execute and validate `teal_data_module`+ names(joinkeys[dataname, parent]) |
|
2 | +162 |
- #'+ } else { |
|
3 | -+ | ||
163 | +149x |
- #' This is a low level module to handle `teal_data_module` execution and validation.+ joinkeys[dataname, dataname] |
|
4 | +164 |
- #' [teal_transform_module()] inherits from [teal_data_module()] so it is handled by this module too.+ } |
|
5 | -+ | ||
165 | +157x |
- #' [srv_teal()] accepts various `data` objects and eventually they are all transformed to `reactive`+ get_filter_overview( |
|
6 | -+ | ||
166 | +157x |
- #' [teal.data::teal_data()] which is a standard data class in whole `teal` framework.+ current_data = current_data_objs[[dataname]], |
|
7 | -+ | ||
167 | +157x |
- #'+ initial_data = initial_data_objs[[dataname]], |
|
8 | -+ | ||
168 | +157x |
- #' @section data validation:+ dataname = dataname, |
|
9 | -+ | ||
169 | +157x |
- #'+ subject_keys = subject_keys |
|
10 | +170 |
- #' Executed [teal_data_module()] is validated and output is validated for consistency.+ ) |
|
11 | +171 |
- #' Output `data` is invalid if:+ } |
|
12 | +172 |
- #' 1. [teal_data_module()] is invalid if server doesn't return `reactive`. **Immediately crashes an app!**+ ) |
|
13 | +173 |
- #' 2. `reactive` throws a `shiny.error` - happens when module creating [teal.data::teal_data()] fails.+ |
|
14 | -+ | ||
174 | +88x |
- #' 3. `reactive` returns `qenv.error` - happens when [teal.data::teal_data()] evaluates a failing code.+ do.call(.smart_rbind, out) |
|
15 | +175 |
- #' 4. `reactive` object doesn't return [teal.data::teal_data()].+ } |
|
16 | +176 |
- #' 5. [teal.data::teal_data()] object lacks any `datanames` specified in the `modules` argument.+ |
|
17 | +177 |
- #'+ |
|
18 | +178 |
- #' `teal` (observers in `srv_teal`) always waits to render an app until `reactive` `teal_data` is+ #' @rdname module_data_summary |
|
19 | +179 |
- #' returned. If error 2-4 occurs, relevant error message is displayed to the app user. Once the issue is+ #' @param current_data (`object`) current object (after filtering and transforming). |
|
20 | +180 |
- #' resolved, the app will continue to run. `teal` guarantees that errors in data don't crash the app+ #' @param initial_data (`object`) initial object. |
|
21 | +181 |
- #' (except error 1).+ #' @param dataname (`character(1)`) |
|
22 | +182 |
- #'+ #' @param subject_keys (`character`) names of the columns which determine a single unique subjects |
|
23 | +183 |
- #' @param id (`character(1)`) Module id+ get_filter_overview <- function(current_data, initial_data, dataname, subject_keys) { |
|
24 | -+ | ||
184 | +162x |
- #' @param data (`reactive teal_data`)+ if (inherits(current_data, c("data.frame", "DataFrame", "array", "Matrix", "SummarizedExperiment"))) { |
|
25 | -+ | ||
185 | +152x |
- #' @param data_module (`teal_data_module`)+ get_filter_overview_array(current_data, initial_data, dataname, subject_keys) |
|
26 | -+ | ||
186 | +10x |
- #' @param modules (`teal_modules` or `teal_module`) For `datanames` validation purpose+ } else if (inherits(current_data, "MultiAssayExperiment")) { |
|
27 | -+ | ||
187 | +1x |
- #' @param validate_shiny_silent_error (`logical`) If `TRUE`, then `shiny.silent.error` is validated and+ get_filter_overview_MultiAssayExperiment(current_data, initial_data, dataname) |
|
28 | +188 |
- #' @param is_transform_failed (`reactiveValues`) contains `logical` flags named after each transformator.+ } else { |
|
29 | -+ | ||
189 | +9x |
- #' Help to determine if any previous transformator failed, so that following transformators can be disabled+ data.frame(dataname = dataname) |
|
30 | +190 |
- #' and display a generic failure message.+ } |
|
31 | +191 |
- #'+ } |
|
32 | +192 |
- #' @return `reactive` `teal_data`+ |
|
33 | +193 |
- #'+ #' @rdname module_data_summary |
|
34 | +194 |
- #' @rdname module_teal_data+ get_filter_overview_array <- function(current_data, |
|
35 | +195 |
- #' @name module_teal_data+ initial_data, |
|
36 | +196 |
- #' @keywords internal+ dataname, |
|
37 | +197 |
- NULL+ subject_keys) { |
|
38 | -+ | ||
198 | +152x |
-
+ if (length(subject_keys) == 0) { |
|
39 | -+ | ||
199 | +138x |
- #' @rdname module_teal_data+ data.frame( |
|
40 | -+ | ||
200 | +138x |
- #' @aliases ui_teal_data+ dataname = dataname, |
|
41 | -+ | ||
201 | +138x |
- #' @note+ obs = if (!is.null(initial_data)) { |
|
42 | -+ | ||
202 | +127x |
- #' `ui_teal_data_module` was renamed from `ui_teal_data`.+ sprintf("%s/%s", nrow(current_data), nrow(initial_data)) |
|
43 | +203 |
- ui_teal_data_module <- function(id, data_module = function(id) NULL) {+ } else { |
|
44 | -! | +||
204 | +11x |
- checkmate::assert_string(id)+ nrow(current_data) |
|
45 | -! | +||
205 | +
- checkmate::assert_function(data_module, args = "id")+ } |
||
46 | -! | +||
206 | +
- ns <- NS(id)+ ) |
||
47 | +207 |
-
+ } else { |
|
48 | -! | +||
208 | +14x |
- shiny::tagList(+ data.frame( |
|
49 | -! | +||
209 | +14x |
- tags$div(id = ns("wrapper"), data_module(id = ns("data"))),+ dataname = dataname, |
|
50 | -! | +||
210 | +14x |
- ui_validate_reactive_teal_data(ns("validate"))+ obs = if (!is.null(initial_data)) { |
|
51 | -+ | ||
211 | +13x |
- )+ sprintf("%s/%s", nrow(current_data), nrow(initial_data)) |
|
52 | +212 |
- }+ } else { |
|
53 | -+ | ||
213 | +1x |
-
+ nrow(current_data) |
|
54 | +214 |
- #' @rdname module_teal_data+ }, |
|
55 | -+ | ||
215 | +14x |
- #' @aliases srv_teal_data+ subjects = if (!is.null(initial_data)) { |
|
56 | -+ | ||
216 | +13x |
- #' @note+ sprintf("%s/%s", nrow(unique(current_data[subject_keys])), nrow(unique(initial_data[subject_keys]))) |
|
57 | +217 |
- #' `srv_teal_data_module` was renamed from `srv_teal_data`.+ } else { |
|
58 | -+ | ||
218 | +1x |
- srv_teal_data_module <- function(id,+ nrow(unique(current_data[subject_keys])) |
|
59 | +219 |
- data_module = function(id) NULL,+ } |
|
60 | +220 |
- modules = NULL,+ ) |
|
61 | +221 |
- validate_shiny_silent_error = TRUE,+ } |
|
62 | +222 |
- is_transform_failed = reactiveValues()) {- |
- |
63 | -! | -
- checkmate::assert_string(id)- |
- |
64 | -! | -
- checkmate::assert_function(data_module, args = "id")- |
- |
65 | -! | -
- checkmate::assert_multi_class(modules, c("teal_modules", "teal_module"), null.ok = TRUE)+ } |
|
66 | -! | +||
223 | +
- checkmate::assert_class(is_transform_failed, "reactivevalues")+ |
||
67 | +224 |
-
+ #' @rdname module_data_summary |
|
68 | -! | +||
225 | +
- moduleServer(id, function(input, output, session) {+ get_filter_overview_MultiAssayExperiment <- function(current_data, # nolint: object_length, object_name. |
||
69 | -! | +||
226 | +
- logger::log_debug("srv_teal_data_module initializing.")+ initial_data, |
||
70 | -! | +||
227 | +
- is_transform_failed[[id]] <- FALSE+ dataname) { |
||
71 | -! | +||
228 | +1x |
- module_out <- data_module(id = "data")+ experiment_names <- names(current_data) |
|
72 | -! | +||
229 | +1x |
- try_module_out <- reactive(tryCatch(module_out(), error = function(e) e))+ mae_info <- data.frame( |
|
73 | -! | +||
230 | +1x |
- observeEvent(try_module_out(), {+ dataname = dataname, |
- |
74 | -! | +||
231 | +1x |
- if (!inherits(try_module_out(), "teal_data")) {+ subjects = if (!is.null(initial_data)) { |
|
75 | +232 | ! |
- is_transform_failed[[id]] <- TRUE+ sprintf("%s/%s", nrow(current_data@colData), nrow(initial_data@colData)) |
76 | +233 |
- } else {+ } else { |
|
77 | -! | +||
234 | +1x |
- is_transform_failed[[id]] <- FALSE+ nrow(current_data@colData) |
|
78 | +235 |
- }+ } |
|
79 | +236 |
- })+ ) |
|
80 | +237 | ||
81 | -! | -
- is_previous_failed <- reactive({- |
- |
82 | -! | +||
238 | +1x |
- idx_this <- which(names(is_transform_failed) == id)+ experiment_obs_info <- do.call("rbind", lapply( |
|
83 | -! | +||
239 | +1x |
- is_transform_failed_list <- reactiveValuesToList(is_transform_failed)+ experiment_names, |
|
84 | -! | +||
240 | +1x |
- idx_failures <- which(unlist(is_transform_failed_list))+ function(experiment_name) { |
|
85 | -! | +||
241 | +5x |
- any(idx_failures < idx_this)+ transform( |
|
86 | -+ | ||
242 | +5x |
- })+ get_filter_overview( |
|
87 | -+ | ||
243 | +5x |
-
+ current_data[[experiment_name]], |
|
88 | -! | +||
244 | +5x |
- observeEvent(is_previous_failed(), {+ initial_data[[experiment_name]], |
|
89 | -! | +||
245 | +5x |
- if (is_previous_failed()) {+ dataname = experiment_name, |
|
90 | -! | +||
246 | +5x |
- shinyjs::disable("wrapper")+ subject_keys = join_keys() # empty join keys |
|
91 | +247 |
- } else {+ ), |
|
92 | -! | +||
248 | +5x |
- shinyjs::enable("wrapper")+ dataname = paste0(" - ", experiment_name) |
|
93 | +249 |
- }+ ) |
|
94 | +250 |
- })+ } |
|
95 | +251 | - - | -|
96 | -! | -
- srv_validate_reactive_teal_data(- |
- |
97 | -! | -
- "validate",- |
- |
98 | -! | -
- data = try_module_out,- |
- |
99 | -! | -
- modules = modules,+ )) |
|
100 | -! | +||
252 | +
- validate_shiny_silent_error = validate_shiny_silent_error,+ |
||
101 | -! | +||
253 | +1x |
- hide_validation_error = is_previous_failed+ get_experiment_keys <- function(mae, experiment) { |
|
102 | -+ | ||
254 | +5x |
- )+ sample_subset <- mae@sampleMap[mae@sampleMap$colname %in% colnames(experiment), ] |
|
103 | -+ | ||
255 | +5x |
- })+ length(unique(sample_subset$primary)) |
|
104 | +256 |
- }+ } |
|
105 | +257 | ||
106 | -- |
- #' @rdname module_teal_data- |
- |
107 | -+ | ||
258 | +1x |
- ui_validate_reactive_teal_data <- function(id) {+ experiment_subjects_info <- do.call("rbind", lapply( |
|
108 | -! | +||
259 | +1x |
- ns <- NS(id)+ experiment_names, |
|
109 | -! | +||
260 | +1x |
- tagList(+ function(experiment_name) { |
|
110 | -! | +||
261 | +5x |
- div(+ data.frame( |
|
111 | -! | +||
262 | +5x |
- id = ns("validate_messages"),+ subjects = if (!is.null(initial_data)) { |
|
112 | +263 | ! |
- class = "teal_validated",+ sprintf( |
113 | +264 | ! |
- ui_validate_error(ns("silent_error")),+ "%s/%s", |
114 | +265 | ! |
- ui_check_class_teal_data(ns("class_teal_data")),+ get_experiment_keys(current_data, current_data[[experiment_name]]), |
115 | +266 | ! |
- ui_check_module_datanames(ns("shiny_warnings"))+ get_experiment_keys(current_data, initial_data[[experiment_name]]) |
116 | +267 |
- ),+ ) |
|
117 | -! | +||
268 | +
- div(+ } else { |
||
118 | -! | +||
269 | +5x |
- class = "teal_validated",+ get_experiment_keys(current_data, current_data[[experiment_name]]) |
|
119 | -! | +||
270 | +
- uiOutput(ns("previous_failed"))+ } |
||
120 | +271 |
- )+ ) |
|
121 | +272 |
- )+ } |
|
122 | +273 |
- }+ )) |
|
123 | +274 | ||
124 | -+ | ||
275 | +1x |
- #' @rdname module_teal_data+ experiment_info <- cbind(experiment_obs_info, experiment_subjects_info) |
|
125 | -+ | ||
276 | +1x |
- srv_validate_reactive_teal_data <- function(id, # nolint: object_length+ .smart_rbind(mae_info, experiment_info) |
|
126 | +277 |
- data,+ } |
127 | +1 |
- modules = NULL,+ #' Generate lockfile for application's environment reproducibility |
||
128 | +2 |
- validate_shiny_silent_error = FALSE,+ #' |
||
129 | +3 |
- hide_validation_error = reactive(FALSE)) {- |
- ||
130 | -! | -
- checkmate::assert_string(id)- |
- ||
131 | -! | -
- checkmate::assert_multi_class(modules, c("teal_modules", "teal_module"), null.ok = TRUE)- |
- ||
132 | -! | -
- checkmate::assert_flag(validate_shiny_silent_error)+ #' @param lockfile_path (`character`) path to the lockfile. |
||
133 | +4 |
-
+ #' |
||
134 | -! | +|||
5 | +
- moduleServer(id, function(input, output, session) {+ #' @section Different ways of creating lockfile: |
|||
135 | +6 |
- # there is an empty reactive cycle on `init` and `data` has `shiny.silent.error` class+ #' `teal` leverages [renv::snapshot()], which offers multiple methods for lockfile creation. |
||
136 | -! | +|||
7 | +
- srv_validate_error("silent_error", data, validate_shiny_silent_error)+ #' |
|||
137 | -! | +|||
8 | +
- srv_check_class_teal_data("class_teal_data", data)+ #' - **Working directory lockfile**: `teal`, by default, will create an `implicit` type lockfile that uses |
|||
138 | -! | +|||
9 | +
- srv_check_module_datanames("shiny_warnings", data, modules)+ #' `renv::dependencies()` to detect all R packages in the current project's working directory. |
|||
139 | -! | +|||
10 | +
- output$previous_failed <- renderUI({+ #' - **`DESCRIPTION`-based lockfile**: To generate a lockfile based on a `DESCRIPTION` file in your working |
|||
140 | -! | +|||
11 | +
- if (hide_validation_error()) {+ #' directory, set `renv::settings$snapshot.type("explicit")`. The naming convention for `type` follows |
|||
141 | -! | +|||
12 | +
- shinyjs::hide("validate_messages")+ #' `renv::snapshot()`. For the `"explicit"` type, refer to `renv::settings$package.dependency.fields()` for the |
|||
142 | -! | +|||
13 | +
- tags$div("One of previous transformators failed. Please check its inputs.", class = "teal-output-warning")+ #' `DESCRIPTION` fields included in the lockfile. |
|||
143 | +14 |
- } else {+ #' - **Custom files-based lockfile**: To specify custom files as the basis for the lockfile, set |
||
144 | -! | +|||
15 | +
- shinyjs::show("validate_messages")+ #' `renv::settings$snapshot.type("custom")` and configure the `renv.snapshot.filter` option. |
|||
145 | -! | +|||
16 | +
- NULL+ #' |
|||
146 | +17 |
- }+ #' @section lockfile usage: |
||
147 | +18 |
- })+ #' After creating the lockfile, you can restore the application's environment using `renv::restore()`. |
||
148 | +19 |
-
+ #' |
||
149 | -! | +|||
20 | +
- .trigger_on_success(data)+ #' @seealso [renv::snapshot()], [renv::restore()]. |
|||
150 | +21 |
- })+ #' |
||
151 | +22 |
- }+ #' @return `NULL` |
||
152 | +23 |
-
+ #' |
||
153 | +24 |
- #' @keywords internal+ #' @name module_teal_lockfile |
||
154 | +25 |
- ui_validate_error <- function(id) {+ #' @rdname module_teal_lockfile |
||
155 | -116x | +|||
26 | +
- ns <- NS(id)+ #' |
|||
156 | -116x | +|||
27 | +
- uiOutput(ns("message"))+ #' @keywords internal |
|||
157 | +28 |
- }+ NULL |
||
158 | +29 | |||
159 | +30 |
- #' @keywords internal+ #' @rdname module_teal_lockfile |
||
160 | +31 |
- srv_validate_error <- function(id, data, validate_shiny_silent_error) {+ ui_teal_lockfile <- function(id) { |
||
161 | -113x | +|||
32 | +! |
- checkmate::assert_string(id)+ ns <- NS(id) |
||
162 | -113x | +|||
33 | +! |
- checkmate::assert_flag(validate_shiny_silent_error)+ shiny::tagList( |
||
163 | -113x | +|||
34 | +! |
- moduleServer(id, function(input, output, session) {+ tags$span("", id = ns("lockFileStatus")), |
||
164 | -113x | +|||
35 | +! |
- output$message <- renderUI({+ shinyjs::disabled(downloadLink(ns("lockFileLink"), "Download lockfile")) |
||
165 | -112x | +|||
36 | +
- is_shiny_silent_error <- inherits(data(), "shiny.silent.error") && identical(data()$message, "")+ ) |
|||
166 | -112x | +|||
37 | +
- if (inherits(data(), "qenv.error")) {+ } |
|||
167 | -2x | +|||
38 | +
- validate(+ |
|||
168 | -2x | +|||
39 | +
- need(+ #' @rdname module_teal_lockfile |
|||
169 | -2x | +|||
40 | +
- FALSE,+ srv_teal_lockfile <- function(id) { |
|||
170 | -2x | +41 | +88x |
- paste(+ moduleServer(id, function(input, output, session) { |
171 | -2x | +42 | +88x |
- "Error when executing the `data` module:",+ logger::log_debug("Initialize srv_teal_lockfile.") |
172 | -2x | +43 | +88x |
- strip_style(paste(data()$message, collapse = "\n")),+ enable_lockfile_download <- function() { |
173 | -2x | +|||
44 | +! |
- "\nCheck your inputs or contact app developer if error persists.",+ shinyjs::html("lockFileStatus", "Application lockfile ready.") |
||
174 | -2x | +|||
45 | +! |
- collapse = "\n"+ shinyjs::hide("lockFileStatus", anim = TRUE) |
||
175 | -+ | |||
46 | +! |
- )+ shinyjs::enable("lockFileLink") |
||
176 | -+ | |||
47 | +! |
- )+ output$lockFileLink <- shiny::downloadHandler( |
||
177 | -+ | |||
48 | +! |
- )+ filename = function() { |
||
178 | -110x | +|||
49 | +! |
- } else if (inherits(data(), "error")) {+ "renv.lock" |
||
179 | -11x | +|||
50 | +
- if (is_shiny_silent_error && !validate_shiny_silent_error) {+ }, |
|||
180 | -4x | +|||
51 | +! |
- return(NULL)+ content = function(file) { |
||
181 | -+ | |||
52 | +! |
- }+ file.copy(lockfile_path, file) |
||
182 | -7x | +|||
53 | +! |
- validate(+ file |
||
183 | -7x | +|||
54 | +
- need(+ }, |
|||
184 | -7x | +|||
55 | +! |
- FALSE,+ contentType = "application/json" |
||
185 | -7x | +|||
56 | +
- sprintf(+ ) |
|||
186 | -7x | +|||
57 | +
- "Shiny error when executing the `data` module.\n%s\n%s",+ } |
|||
187 | -7x | +58 | +88x |
- data()$message,+ disable_lockfile_download <- function() { |
188 | -7x | +|||
59 | +! |
- "Check your inputs or contact app developer if error persists."+ warning("Lockfile creation failed.", call. = FALSE) |
||
189 | -+ | |||
60 | +! |
- )+ shinyjs::html("lockFileStatus", "Lockfile creation failed.") |
||
190 | -+ | |||
61 | +! |
- )+ shinyjs::hide("lockFileLink") |
||
191 | +62 |
- )+ } |
||
192 | +63 |
- }+ |
||
193 | -+ | |||
64 | +88x |
- })+ shiny::onStop(function() { |
||
194 | -+ | |||
65 | +88x |
- })+ if (file.exists(lockfile_path) && !shiny::isRunning()) { |
||
195 | -+ | |||
66 | +1x |
- }+ logger::log_debug("Removing lockfile after shutting down the app") |
||
196 | -+ | |||
67 | +1x |
-
+ file.remove(lockfile_path) |
||
197 | +68 |
-
+ } |
||
198 | +69 |
- #' @keywords internal+ }) |
||
199 | +70 |
- ui_check_class_teal_data <- function(id) {+ |
||
200 | -116x | +71 | +88x |
- ns <- NS(id)+ lockfile_path <- "teal_app.lock" |
201 | -116x | +72 | +88x |
- uiOutput(ns("message"))+ mode <- getOption("teal.lockfile.mode", default = "") |
202 | +73 |
- }+ |
||
203 | -+ | |||
74 | +88x |
-
+ if (!(mode %in% c("auto", "enabled", "disabled"))) { |
||
204 | -+ | |||
75 | +! |
- #' @keywords internal+ stop("'teal.lockfile.mode' option can only be one of \"auto\", \"disabled\" or \"disabled\". ") |
||
205 | +76 |
- srv_check_class_teal_data <- function(id, data) {- |
- ||
206 | -113x | -
- checkmate::assert_string(id)- |
- ||
207 | -113x | -
- moduleServer(id, function(input, output, session) {+ } |
||
208 | -113x | +|||
77 | +
- output$message <- renderUI({+ |
|||
209 | -112x | +78 | +88x |
- validate(+ if (mode == "disabled") { |
210 | -112x | +79 | +1x |
- need(+ logger::log_debug("'teal.lockfile.mode' option is set to 'disabled'. Hiding lockfile download button.") |
211 | -112x | +80 | +1x |
- inherits(data(), c("teal_data", "error")),+ shinyjs::hide("lockFileLink") |
212 | -112x | +81 | +1x |
- "Did not receive `teal_data` object. Cannot proceed further."+ return(NULL) |
213 | +82 |
- )+ } |
||
214 | +83 |
- )+ |
||
215 | -+ | |||
84 | +87x |
- })+ if (file.exists(lockfile_path)) { |
||
216 | -+ | |||
85 | +! |
- })+ logger::log_debug("Lockfile has already been created for this app - skipping automatic creation.") |
||
217 | -+ | |||
86 | +! |
- }+ enable_lockfile_download() |
||
218 | -+ | |||
87 | +! |
-
+ return(NULL) |
||
219 | +88 |
- #' @keywords internal+ } |
||
220 | +89 |
- ui_check_module_datanames <- function(id) {+ |
||
221 | -116x | +90 | +87x |
- ns <- NS(id)+ if (mode == "auto" && .is_disabled_lockfile_scenario()) { |
222 | -116x | +91 | +86x |
- uiOutput(NS(id, "message"))+ logger::log_debug( |
223 | -+ | |||
92 | +86x |
- }+ "Automatic lockfile creation disabled. Execution scenario satisfies teal:::.is_disabled_lockfile_scenario()." |
||
224 | +93 |
-
+ ) |
||
225 | -+ | |||
94 | +86x |
- #' @keywords internal+ shinyjs::hide("lockFileLink") |
||
226 | -+ | |||
95 | +86x |
- srv_check_module_datanames <- function(id, data, modules) {+ return(NULL) |
||
227 | -193x | +|||
96 | +
- checkmate::assert_string(id)+ } |
|||
228 | -193x | +|||
97 | +
- moduleServer(id, function(input, output, session) {+ |
|||
229 | -193x | +98 | +1x |
- output$message <- renderUI({+ if (!.is_lockfile_deps_installed()) { |
230 | -196x | +|||
99 | +! |
- if (inherits(data(), "teal_data")) {+ warning("Automatic lockfile creation disabled. `mirai` and `renv` packages must be installed.") |
||
231 | -179x | +|||
100 | +! |
- is_modules_ok <- check_modules_datanames_html(+ shinyjs::hide("lockFileLink") |
||
232 | -179x | +|||
101 | +! |
- modules = modules, datanames = names(data())+ return(NULL) |
||
233 | +102 |
- )+ } |
||
234 | -179x | +|||
103 | +
- if (!isTRUE(is_modules_ok)) {+ |
|||
235 | -19x | +|||
104 | +
- tags$div(is_modules_ok, class = "teal-output-warning")+ # - Will be run only if the lockfile doesn't exist (see the if-s above) |
|||
236 | +105 |
- }+ # - We render to the tempfile because the process might last after session is closed and we don't |
||
237 | +106 |
- }+ # want to make a "teal_app.renv" then. This is why we copy only during active session. |
||
238 | -+ | |||
107 | +1x |
- })+ process <- .teal_lockfile_process_invoke(lockfile_path) |
||
239 | -+ | |||
108 | +1x |
- })+ observeEvent(process$status(), { |
||
240 | -+ | |||
109 | +! |
- }+ if (process$status() %in% c("initial", "running")) { |
||
241 | -+ | |||
110 | +! |
-
+ shinyjs::html("lockFileStatus", "Creating lockfile...") |
||
242 | -+ | |||
111 | +! |
- .trigger_on_success <- function(data) {+ } else if (process$status() == "success") { |
||
243 | -113x | +|||
112 | +! |
- out <- reactiveVal(NULL)+ result <- process$result() |
||
244 | -113x | +|||
113 | +! |
- observeEvent(data(), {+ if (any(grepl("Lockfile written to", result$out))) { |
||
245 | -112x | +|||
114 | +! |
- if (inherits(data(), "teal_data")) {+ logger::log_debug("Lockfile containing { length(result$res$Packages) } packages created.") |
||
246 | -97x | +|||
115 | +! |
- if (!identical(data(), out())) {+ if (any(grepl("(WARNING|ERROR):", result$out))) { |
||
247 | -97x | +|||
116 | +! |
- out(data())+ warning("Lockfile created with warning(s) or error(s):", call. = FALSE) |
||
248 | -+ | |||
117 | +! |
- }+ for (i in result$out) { |
||
249 | -+ | |||
118 | +! |
- }+ warning(i, call. = FALSE) |
||
250 | +119 |
- })+ } |
||
251 | +120 |
-
+ } |
||
252 | -113x | +|||
121 | +! |
- out+ enable_lockfile_download() |
||
253 | +122 |
- }+ } else { |
1 | -+ | ||
123 | +! |
- #' Data module for `teal` transformations and output customization+ disable_lockfile_download() |
|
2 | +124 |
- #'+ } |
|
3 | -+ | ||
125 | +! |
- #' @description+ } else if (process$status() == "error") { |
|
4 | -+ | ||
126 | +! |
- #' `r lifecycle::badge("experimental")`+ disable_lockfile_download() |
|
5 | +127 |
- #'+ } |
|
6 | +128 |
- #' `teal_transform_module` provides a `shiny` module that enables data transformations within a `teal` application+ }) |
|
7 | +129 |
- #' and allows for customization of outputs generated by modules.+ |
|
8 | -+ | ||
130 | +1x |
- #'+ NULL |
|
9 | +131 |
- #' # Transforming Module Inputs in `teal`+ }) |
|
10 | +132 |
- #'+ } |
|
11 | +133 |
- #' Data transformations occur after data has been filtered in `teal`.+ |
|
12 | +134 |
- #' The transformed data is then passed to the `server` of [`teal_module()`] and managed by `teal`'s internal processes.+ utils::globalVariables(c("opts", "sysenv", "libpaths", "wd", "lockfilepath", "run")) # needed for mirai call |
|
13 | +135 |
- #' The primary advantage of `teal_transform_module` over custom modules is in its error handling, where all warnings and+ #' @rdname module_teal_lockfile |
|
14 | +136 |
- #' errors are managed by `teal`, allowing developers to focus on transformation logic.+ .teal_lockfile_process_invoke <- function(lockfile_path) { |
|
15 | -+ | ||
137 | +1x |
- #'+ mirai_obj <- NULL |
|
16 | -+ | ||
138 | +1x |
- #' For more details, see the vignette: `vignette("data-transform-as-shiny-module", package = "teal")`.+ process <- shiny::ExtendedTask$new(function() { |
|
17 | -+ | ||
139 | +1x |
- #'+ m <- mirai::mirai( |
|
18 | +140 |
- #' # Customizing Module Outputs+ { |
|
19 | -+ | ||
141 | +1x |
- #'+ options(opts) |
|
20 | -+ | ||
142 | +1x |
- #' `teal_transform_module` also allows developers to modify any object created within [`teal.data::teal_data`].+ do.call(Sys.setenv, sysenv) |
|
21 | -+ | ||
143 | +1x |
- #' This means you can use it to customize not only datasets but also tables, listings, and graphs.+ .libPaths(libpaths) |
|
22 | -+ | ||
144 | +1x |
- #' Some [`teal_modules`] permit developers to inject custom `shiny` modules to enhance displayed outputs.+ setwd(wd) |
|
23 | -+ | ||
145 | +1x |
- #' To manage these `decorators` within your module, use [`ui_transform_teal_data()`] and [`srv_transform_teal_data()`].+ run(lockfile_path = lockfile_path) |
|
24 | +146 |
- #' (For further guidance on managing decorators, refer to `ui_args` and `srv_args` in the vignette documentation.)+ }, |
|
25 | -+ | ||
147 | +1x |
- #'+ run = .renv_snapshot, |
|
26 | -+ | ||
148 | +1x |
- #' See the vignette `vignette("decorate-modules-output", package = "teal")` for additional examples.+ lockfile_path = lockfile_path, |
|
27 | -+ | ||
149 | +1x |
- #'+ opts = options(), |
|
28 | -+ | ||
150 | +1x |
- #' # `server` as a language+ libpaths = .libPaths(), |
|
29 | -+ | ||
151 | +1x |
- #'+ sysenv = as.list(Sys.getenv()), |
|
30 | -+ | ||
152 | +1x |
- #' The `server` function in `teal_transform_module` must return a reactive [`teal.data::teal_data`] object.+ wd = getwd() |
|
31 | +153 |
- #' For simple transformations without complex reactivity, the `server` function might look like this:s+ ) |
|
32 | -+ | ||
154 | +1x |
- #'+ mirai_obj <<- m |
|
33 | -+ | ||
155 | +1x |
- #' ```+ m |
|
34 | +156 |
- #' function(id, data) {+ }) |
|
35 | +157 |
- #' moduleServer(id, function(input, output, session) {+ |
|
36 | -+ | ||
158 | +1x |
- #' reactive({+ shiny::onStop(function() { |
|
37 | -+ | ||
159 | +1x |
- #' within(+ if (mirai::unresolved(mirai_obj)) { |
|
38 | -+ | ||
160 | +! |
- #' data(),+ logger::log_debug("Terminating a running lockfile process...") |
|
39 | -+ | ||
161 | +! |
- #' expr = x <- subset(x, col == level),+ mirai::stop_mirai(mirai_obj) # this doesn't stop running - renv will be created even if session is closed |
|
40 | +162 |
- #' level = input$level+ } |
|
41 | +163 |
- #' )+ }) |
|
42 | +164 |
- #' })+ |
|
43 | -+ | ||
165 | +1x |
- #' })+ suppressWarnings({ # 'package:stats' may not be available when loading |
|
44 | -+ | ||
166 | +1x |
- #' }+ process$invoke() |
|
45 | +167 |
- #' ```+ }) |
|
46 | +168 |
- #'+ |
|
47 | -+ | ||
169 | +1x |
- #' The example above can be simplified using `make_teal_transform_server`, where `level` is automatically matched to the+ logger::log_debug("Lockfile creation started based on { getwd() }.") |
|
48 | +170 |
- #' corresponding `input` parameter:+ |
|
49 | -+ | ||
171 | +1x |
- #'+ process |
|
50 | +172 |
- #' ```+ } |
|
51 | +173 |
- #' make_teal_transform_server(expr = expression(x <- subset(x, col == level)))+ |
|
52 | +174 |
- #' ```+ #' @rdname module_teal_lockfile |
|
53 | +175 |
- #' @inheritParams teal_data_module+ .renv_snapshot <- function(lockfile_path) { |
|
54 | -+ | ||
176 | +1x |
- #' @param server (`function(id, data)` or `expression`)+ out <- utils::capture.output( |
|
55 | -+ | ||
177 | +1x |
- #' A `shiny` module server function that takes `id` and `data` as arguments, where `id` is the module id and `data`+ res <- renv::snapshot( |
|
56 | -+ | ||
178 | +1x | +
+ lockfile = lockfile_path,+ |
+ |
179 | +1x | +
+ prompt = FALSE,+ |
+ |
180 | +1x |
- #' is the reactive `teal_data` input. The `server` function must return a reactive expression containing a `teal_data`+ force = TRUE, |
|
57 | -+ | ||
181 | +1x |
- #' object. For simplified syntax, use [`make_teal_transform_server()`].+ type = renv::settings$snapshot.type() # see the section "Different ways of creating lockfile" above here |
|
58 | +182 |
- #' @param datanames (`character`)+ ) |
|
59 | +183 |
- #' Specifies the names of datasets relevant to the module. Only filters for the specified `datanames` will be displayed+ ) |
|
60 | +184 |
- #' in the filter panel. The keyword `"all"` can be used to display filters for all datasets. `datanames` are+ |
|
61 | -+ | ||
185 | +1x |
- #' automatically appended to the [`modules()`] `datanames`.+ list(out = out, res = res) |
|
62 | +186 |
- #'+ } |
|
63 | +187 |
- #'+ |
|
64 | +188 |
- #' @examples+ #' @rdname module_teal_lockfile |
|
65 | +189 |
- #' data_transformators <- list(+ .is_lockfile_deps_installed <- function() { |
|
66 | -+ | ||
190 | +1x |
- #' teal_transform_module(+ requireNamespace("mirai", quietly = TRUE) && requireNamespace("renv", quietly = TRUE) |
|
67 | +191 |
- #' label = "Static transformator for iris",+ } |
|
68 | +192 |
- #' datanames = "iris",+ |
|
69 | +193 |
- #' server = function(id, data) {+ #' @rdname module_teal_lockfile |
|
70 | +194 |
- #' moduleServer(id, function(input, output, session) {+ .is_disabled_lockfile_scenario <- function() { |
|
71 | -+ | ||
195 | +86x |
- #' reactive({+ identical(Sys.getenv("CALLR_IS_RUNNING"), "true") || # inside callr process |
|
72 | -+ | ||
196 | +86x |
- #' within(data(), {+ identical(Sys.getenv("TESTTHAT"), "true") || # inside devtools::test |
|
73 | -+ | ||
197 | +86x |
- #' iris <- head(iris, 5)+ !identical(Sys.getenv("QUARTO_PROJECT_ROOT"), "") || # inside Quarto process |
|
74 | +198 |
- #' })+ ( |
|
75 | -+ | ||
199 | +86x |
- #' })+ ("CheckExEnv" %in% search()) || any(c("_R_CHECK_TIMINGS_", "_R_CHECK_LICENSE_") %in% names(Sys.getenv())) |
|
76 | -+ | ||
200 | +86x |
- #' })+ ) # inside R CMD CHECK |
|
77 | +201 |
- #' }+ } |
78 | +1 |
- #' ),+ #' Data Module for teal |
||
79 | +2 |
- #' teal_transform_module(+ #' |
||
80 | +3 |
- #' label = "Interactive transformator for iris",+ #' This module manages the `data` argument for `srv_teal`. The `teal` framework uses [teal.data::teal_data()], |
||
81 | +4 |
- #' datanames = "iris",+ #' which can be provided in various ways: |
||
82 | +5 |
- #' ui = function(id) {+ #' 1. Directly as a [teal.data::teal_data()] object. This will automatically convert it into a `reactive` `teal_data`. |
||
83 | +6 |
- #' ns <- NS(id)+ #' 2. As a `reactive` object that returns a [teal.data::teal_data()] object. |
||
84 | +7 |
- #' tags$div(+ #' |
||
85 | +8 |
- #' numericInput(ns("n_cols"), "Show n columns", value = 5, min = 1, max = 5, step = 1)+ #' @details |
||
86 | +9 |
- #' )+ #' ## Reactive `teal_data`: |
||
87 | +10 |
- #' },+ #' |
||
88 | +11 |
- #' server = function(id, data) {+ #' The data in the application can be reactively updated, prompting [srv_teal()] to rebuild the |
||
89 | +12 |
- #' moduleServer(id, function(input, output, session) {+ #' content accordingly. There are two methods for creating interactive `teal_data`: |
||
90 | +13 |
- #' reactive({+ #' 1. Using a `reactive` object provided from outside the `teal` application. In this scenario, |
||
91 | +14 |
- #' within(data(),+ #' reactivity is controlled by an external module, and `srv_teal` responds to changes. |
||
92 | +15 |
- #' {+ #' 2. Using [teal_data_module()], which is embedded within the `teal` application, allowing data to |
||
93 | +16 |
- #' iris <- iris[, 1:n_cols]+ #' be resubmitted by the user as needed. |
||
94 | +17 |
- #' },+ #' |
||
95 | +18 |
- #' n_cols = input$n_cols+ #' Since the server of [teal_data_module()] must return a `reactive` `teal_data` object, both |
||
96 | +19 |
- #' )+ #' methods (1 and 2) produce the same reactive behavior within a `teal` application. The distinction |
||
97 | +20 |
- #' })+ #' lies in data control: the first method involves external control, while the second method |
||
98 | +21 |
- #' })+ #' involves control from a custom module within the app. |
||
99 | +22 |
- #' }+ #' |
||
100 | +23 |
- #' )+ #' For more details, see [`module_teal_data`]. |
||
101 | +24 |
- #' )+ #' |
||
102 | +25 |
- #'+ #' @inheritParams init |
||
103 | +26 |
- #' output_decorator <- teal_transform_module(+ #' |
||
104 | +27 |
- #' server = make_teal_transform_server(+ #' @param data (`teal_data`, `teal_data_module`, or `reactive` returning `teal_data`) |
||
105 | +28 |
- #' expression(+ #' The data which application will depend on. |
||
106 | +29 |
- #' object <- rev(object)+ #' |
||
107 | +30 |
- #' )+ #' @return A `reactive` object that returns: |
||
108 | +31 |
- #' )+ #' Output of the `data`. If `data` fails then returned error is handled (after [tryCatch()]) so that |
||
109 | +32 |
- #' )+ #' rest of the application can respond to this respectively. |
||
110 | +33 |
#' |
||
111 | +34 |
- #' app <- init(+ #' @rdname module_init_data |
||
112 | +35 |
- #' data = teal_data(iris = iris),+ #' @name module_init_data |
||
113 | +36 |
- #' modules = example_module(+ #' @keywords internal |
||
114 | +37 |
- #' transformators = data_transformators,+ NULL |
||
115 | +38 |
- #' decorators = list(output_decorator)+ |
||
116 | +39 |
- #' )+ #' @rdname module_init_data |
||
117 | +40 |
- #' )+ ui_init_data <- function(id) { |
||
118 | -+ | |||
41 | +9x |
- #' if (interactive()) {+ ns <- shiny::NS(id) |
||
119 | -+ | |||
42 | +9x |
- #' shinyApp(app$ui, app$server)+ shiny::div( |
||
120 | -+ | |||
43 | +9x |
- #' }+ id = ns("content"), |
||
121 | -+ | |||
44 | +9x |
- #'+ style = "display: inline-block; width: 100%;", |
||
122 | -+ | |||
45 | +9x |
- #' @name teal_transform_module+ uiOutput(ns("data")) |
||
123 | +46 |
- #'+ ) |
||
124 | +47 |
- #' @export+ } |
||
125 | +48 |
- teal_transform_module <- function(ui = NULL,+ |
||
126 | +49 |
- server = function(id, data) data,+ #' @rdname module_init_data |
||
127 | +50 |
- label = "transform module",+ srv_init_data <- function(id, data) { |
||
128 | -+ | |||
51 | +88x |
- datanames = "all") {+ checkmate::assert_character(id, max.len = 1, any.missing = FALSE) |
||
129 | -25x | +52 | +88x |
- structure(+ checkmate::assert_multi_class(data, c("teal_data", "teal_data_module", "reactive")) |
130 | -25x | +|||
53 | +
- list(+ |
|||
131 | -25x | +54 | +88x |
- ui = ui,+ moduleServer(id, function(input, output, session) { |
132 | -25x | +55 | +88x |
- server = function(id, data) {+ logger::log_debug("srv_data initializing.") |
133 | -26x | +56 | +88x |
- data_out <- server(id, data)+ data_out <- if (inherits(data, "teal_data_module")) { |
134 | -+ | |||
57 | +10x |
-
+ output$data <- renderUI(data$ui(id = session$ns("teal_data_module"))) |
||
135 | -26x | +58 | +10x |
- if (inherits(data_out, "reactive.event")) {+ data$server("teal_data_module") |
136 | -+ | |||
59 | +88x |
- # This warning message partially detects when `eventReactive` is used in `data_module`.+ } else if (inherits(data, "teal_data")) { |
||
137 | -1x | +60 | +48x |
- warning(+ reactiveVal(data) |
138 | -1x | +61 | +88x |
- "teal_transform_module() ",+ } else if (test_reactive(data)) { |
139 | -1x | +62 | +30x |
- "Using eventReactive in teal_transform module server code should be avoided as it ",+ data |
140 | -1x | +|||
63 | +
- "may lead to unexpected behavior. See the vignettes for more information ",+ } |
|||
141 | -1x | +|||
64 | +
- "(`vignette(\"data-transform-as-shiny-module\", package = \"teal\")`).",+ |
|||
142 | -1x | +65 | +87x |
- call. = FALSE+ data_handled <- reactive({ |
143 | -+ | |||
66 | +80x |
- )+ tryCatch(data_out(), error = function(e) e) |
||
144 | +67 |
- }+ }) |
||
145 | +68 | |||
146 | +69 |
-
+ # We want to exclude teal_data_module elements from bookmarking as they might have some secrets |
||
147 | -26x | +70 | +87x |
- decorate_err_msg(+ observeEvent(data_handled(), { |
148 | -26x | +71 | +80x |
- assert_reactive(data_out),+ if (inherits(data_handled(), "teal_data")) { |
149 | -26x | +72 | +75x |
- pre = sprintf("From: 'teal_transform_module()':\nA 'teal_transform_module' with \"%s\" label:", label),+ app_session <- .subset2(shiny::getDefaultReactiveDomain(), "parent") |
150 | -26x | -
- post = "Please make sure that this module returns a 'reactive` object containing 'teal_data' class of object." # nolint: line_length_linter.- |
- ||
151 | -+ | 73 | +75x |
- )+ setBookmarkExclude( |
152 | -+ | |||
74 | +75x |
- }+ session$ns( |
||
153 | -+ | |||
75 | +75x |
- ),+ grep( |
||
154 | -25x | +|||
76 | +75x |
- label = label,+ pattern = "teal_data_module-", |
||
155 | -25x | +77 | +75x |
- datanames = datanames,+ x = names(reactiveValuesToList(input)), |
156 | -25x | +78 | +75x |
- class = c("teal_transform_module", "teal_data_module")+ value = TRUE |
157 | +79 |
- )+ ) |
||
158 | +80 |
- }+ ), |
||
159 | -+ | |||
81 | +75x |
-
+ session = app_session |
||
160 | +82 |
- #' Make teal_transform_module's server+ ) |
||
161 | +83 |
- #'+ } |
||
162 | +84 |
- #' A factory function to simplify creation of a [`teal_transform_module`]'s server. Specified `expr`+ }) |
||
163 | +85 |
- #' is wrapped in a shiny module function and output can be passed to the `server` argument in+ |
||
164 | -+ | |||
86 | +87x |
- #' [teal_transform_module()] call. Such a server function can be linked with ui and values from the+ data_handled |
||
165 | +87 |
- #' inputs can be used in the expression. Object names specified in the expression will be substituted+ }) |
||
166 | +88 |
- #' with the value of the respective input (matched by the name) - for example in+ } |
||
167 | +89 |
- #' `expression(graph <- graph + ggtitle(title))` object `title` will be replaced with the value of+ |
||
168 | +90 |
- #' `input$title`.+ #' Adds signature protection to the `datanames` in the data |
||
169 | +91 |
- #' @param expr (`language`)+ #' @param data (`teal_data`) |
||
170 | +92 |
- #' An R call which will be evaluated within [`teal.data::teal_data`] environment.+ #' @return `teal_data` with additional code that has signature of the `datanames` |
||
171 | +93 |
- #' @return `function(id, data)` returning `shiny` module+ #' @keywords internal |
||
172 | +94 |
- #' @examples+ .add_signature_to_data <- function(data) { |
||
173 | -+ | |||
95 | +75x |
- #'+ hashes <- .get_hashes_code(data) |
||
174 | -+ | |||
96 | +75x |
- #' trim_iris <- teal_transform_module(+ tdata <- do.call( |
||
175 | -+ | |||
97 | +75x |
- #' label = "Simplified interactive transformator for iris",+ teal.data::teal_data, |
||
176 | -+ | |||
98 | +75x |
- #' datanames = "iris",+ c( |
||
177 | -+ | |||
99 | +75x |
- #' ui = function(id) {+ list(code = trimws(c(teal.code::get_code(data), hashes), which = "right")), |
||
178 | -+ | |||
100 | +75x |
- #' ns <- NS(id)+ list(join_keys = teal.data::join_keys(data)), |
||
179 | -+ | |||
101 | +75x |
- #' numericInput(ns("n_rows"), "Subset n rows", value = 6, min = 1, max = 150, step = 1)+ sapply( |
||
180 | -+ | |||
102 | +75x |
- #' },+ names(data), |
||
181 | -+ | |||
103 | +75x |
- #' server = make_teal_transform_server(expression(iris <- head(iris, n_rows)))+ teal.code::get_var, |
||
182 | -+ | |||
104 | +75x |
- #' )+ object = data, |
||
183 | -+ | |||
105 | +75x |
- #'+ simplify = FALSE |
||
184 | +106 |
- #' app <- init(+ ) |
||
185 | +107 |
- #' data = teal_data(iris = iris),+ ) |
||
186 | +108 |
- #' modules = example_module(transformators = trim_iris)+ ) |
||
187 | +109 |
- #' )+ + |
+ ||
110 | +75x | +
+ tdata@verified <- data@verified+ |
+ ||
111 | +75x | +
+ tdata |
||
188 | +112 |
- #' if (interactive()) {+ } |
||
189 | +113 |
- #' shinyApp(app$ui, app$server)+ |
||
190 | +114 |
- #' }+ #' Get code that tests the integrity of the reproducible data |
||
191 | +115 |
#' |
||
192 | +116 |
- #' @export+ #' @param data (`teal_data`) object holding the data |
||
193 | +117 |
- make_teal_transform_server <- function(expr) {+ #' @param datanames (`character`) names of `datasets` |
||
194 | -3x | +|||
118 | +
- if (is.call(expr)) {+ #' |
|||
195 | -1x | +|||
119 | +
- expr <- as.expression(expr)+ #' @return A character vector with the code lines. |
|||
196 | +120 |
- }+ #' @keywords internal |
||
197 | -3x | +|||
121 | +
- checkmate::assert_multi_class(expr, c("call", "expression"))+ #' |
|||
198 | +122 |
-
+ .get_hashes_code <- function(data, datanames = names(data)) { |
||
199 | -3x | +123 | +75x |
- function(id, data) {+ vapply( |
200 | -3x | +124 | +75x |
- moduleServer(id, function(input, output, session) {+ datanames, |
201 | -3x | +125 | +75x |
- list_env <- reactive(+ function(dataname, datasets) { |
202 | -3x | -
- lapply(rlang::set_names(names(input)), function(x) input[[x]])- |
- ||
203 | -+ | 126 | +133x |
- )+ x <- data[[dataname]] |
204 | +127 | |||
205 | -3x | +128 | +133x |
- reactive({+ code <- if (is.function(x) && !is.primitive(x)) { |
206 | -4x | +129 | +6x |
- call_with_inputs <- lapply(expr, function(x) {+ x <- deparse1(x) |
207 | -4x | +130 | +6x |
- do.call(what = substitute, args = list(expr = x, env = list_env()))+ bquote(rlang::hash(deparse1(.(as.name(dataname))))) |
208 | +131 |
- })+ } else { |
||
209 | -4x | -
- eval_code(object = data(), code = as.expression(call_with_inputs))- |
- ||
210 | -- |
- })- |
- ||
211 | -- |
- })- |
- ||
212 | -+ | 132 | +127x |
- }+ bquote(rlang::hash(.(as.name(dataname)))) |
213 | +133 |
- }+ } |
||
214 | -+ | |||
134 | +133x |
-
+ sprintf( |
||
215 | -+ | |||
135 | +133x |
- #' Extract all `transformators` from `modules`.+ "stopifnot(%s == %s) # @linksto %s", |
||
216 | -+ | |||
136 | +133x |
- #'+ deparse1(code), |
||
217 | -+ | |||
137 | +133x |
- #' @param modules `teal_modules` or `teal_module`+ deparse1(rlang::hash(x)), |
||
218 | -+ | |||
138 | +133x |
- #' @return A list of `teal_transform_module` nested in the same way as input `modules`.+ dataname |
||
219 | +139 |
- #' @keywords internal+ ) |
||
220 | +140 |
- extract_transformators <- function(modules) {- |
- ||
221 | -10x | -
- if (inherits(modules, "teal_module")) {- |
- ||
222 | -5x | -
- modules$transformators+ }, |
||
223 | -5x | +141 | +75x |
- } else if (inherits(modules, "teal_modules")) {+ character(1L), |
224 | -5x | +142 | +75x |
- lapply(modules$children, extract_transformators)+ USE.NAMES = TRUE |
225 | +143 |
- }+ ) |
||
226 | +144 |
}@@ -16197,14 +16471,14 @@ teal coverage - 60.12% |
1 |
- #' An example `teal` module+ #' Manage multiple `FilteredData` objects |
|||
3 |
- #' `r lifecycle::badge("experimental")`+ #' @description |
|||
4 |
- #'+ #' Oversee filter states across the entire application. |
|||
5 |
- #' This module creates an object called `object` that can be modified with decorators.+ #' |
|||
6 |
- #' The `object` is determined by what's selected in `Choose a dataset` input in UI.+ #' @section Slices global: |
|||
7 |
- #' The object can be anything that can be handled by `renderPrint()`.+ #' The key role in maintaining the module-specific filter states is played by the `.slicesGlobal` |
|||
8 |
- #' See the `vignette("decorate-modules-output", package = "teal")` or [`teal_transform_module`]+ #' object. It is a reference class that holds the following fields: |
|||
9 |
- #' to read more about decorators.+ #' - `all_slices` (`reactiveVal`) - reactive value containing all filters registered in an app. |
|||
10 |
- #'+ #' - `module_slices_api` (`reactiveValues`) - reactive field containing references to each modules' |
|||
11 |
- #' @inheritParams teal_modules+ #' `FilteredData` object methods. At this moment it is used only in `srv_filter_manager` to display |
|||
12 |
- #' @param decorators `r lifecycle::badge("experimental")` (`list` of `teal_transform_module` or `NULL`) optional,+ #' the filter states in a table combining informations from `all_slices` and from |
|||
13 |
- #' if not `NULL`, decorator for tables or plots included in the module.+ #' `FilteredData$get_available_teal_slices()`. |
|||
15 |
- #' @return A `teal` module which can be included in the `modules` argument to [init()].+ #' During a session only new filters are added to `all_slices` unless [`module_snapshot_manager`] is |
|||
16 |
- #' @examples+ #' used to restore previous state. Filters from `all_slices` can be activated or deactivated in a |
|||
17 |
- #' app <- init(+ #' module which is linked (both ways) by `attr(, "mapping")` so that: |
|||
18 |
- #' data = teal_data(IRIS = iris, MTCARS = mtcars),+ #' - If module's filter is added or removed in its `FilteredData` object, this information is passed |
|||
19 |
- #' modules = example_module()+ #' to `SlicesGlobal` which updates `attr(, "mapping")` accordingly. |
|||
20 |
- #' )+ #' - When mapping changes in a `SlicesGlobal`, filters are set or removed from module's |
|||
21 |
- #' if (interactive()) {+ #' `FilteredData`. |
|||
22 |
- #' shinyApp(app$ui, app$server)+ #' |
|||
23 |
- #' }+ #' @section Filter manager: |
|||
24 |
- #' @export+ #' Filter-manager is split into two parts: |
|||
25 |
- example_module <- function(label = "example teal module",+ #' 1. `ui/srv_filter_manager_panel` - Called once for the whole app. This module observes changes in |
|||
26 |
- datanames = "all",+ #' the filters in `slices_global` and displays them in a table utilizing information from `mapping`: |
|||
27 |
- transformators = list(),+ #' - (`TRUE`) - filter is active in the module |
|||
28 |
- decorators = NULL) {+ #' - (`FALSE`) - filter is inactive in the module |
|||
29 | -43x | +
- checkmate::assert_string(label)+ #' - (`NA`) - filter is not available in the module |
||
30 | -43x | +
- checkmate::assert_list(decorators, "teal_transform_module", null.ok = TRUE)+ #' 2. `ui/srv_module_filter_manager` - Called once for each `teal_module`. Handling filter states |
||
31 |
-
+ #' for of single module and keeping module `FilteredData` consistent with `slices_global`, so that |
|||
32 | -43x | +
- ans <- module(+ #' local filters are always reflected in the `slices_global` and its mapping and vice versa. |
||
33 | -43x | +
- label,+ #' |
||
34 | -43x | +
- server = function(id, data, decorators) {+ #' |
||
35 | -5x | +
- checkmate::assert_class(isolate(data()), "teal_data")+ #' @param id (`character(1)`) |
||
36 | -5x | +
- moduleServer(id, function(input, output, session) {+ #' `shiny` module instance id. |
||
37 | -5x | +
- datanames_rv <- reactive(names(req(data())))+ #' |
||
38 | -5x | +
- observeEvent(datanames_rv(), {+ #' @param slices_global (`reactiveVal`) |
||
39 | -5x | +
- selected <- input$dataname+ #' containing `teal_slices`. |
||
40 | -5x | +
- if (identical(selected, "")) {+ #' |
||
41 | -! | +
- selected <- restoreInput(session$ns("dataname"), NULL)+ #' @param module_fd (`FilteredData`) |
||
42 | -5x | +
- } else if (isFALSE(selected %in% datanames_rv())) {+ #' Object containing the data to be filtered in a single `teal` module. |
||
43 | -! | +
- selected <- datanames_rv()[1]+ #' |
||
44 |
- }+ #' @return |
|||
45 | -5x | +
- updateSelectInput(+ #' Module returns a `slices_global` (`reactiveVal`) containing a `teal_slices` object with mapping. |
||
46 | -5x | +
- session = session,+ #' |
||
47 | -5x | +
- inputId = "dataname",+ #' @encoding UTF-8 |
||
48 | -5x | +
- choices = datanames_rv(),+ #' |
||
49 | -5x | +
- selected = selected+ #' @name module_filter_manager |
||
50 |
- )+ #' @rdname module_filter_manager |
|||
51 |
- })+ #' |
|||
52 |
-
+ NULL |
|||
53 | -5x | +
- table_data <- reactive({+ |
||
54 | -8x | +
- req(input$dataname)+ #' @rdname module_filter_manager |
||
55 | -3x | +
- within(data(),+ ui_filter_manager_panel <- function(id) { |
||
56 | -+ | ! |
- {+ ns <- NS(id) |
|
57 | -3x | +! |
- object <- dataname+ tags$button( |
|
58 | -+ | ! |
- },+ id = ns("show_filter_manager"), |
|
59 | -3x | +! |
- dataname = as.name(input$dataname)+ class = "btn action-button wunder_bar_button", |
|
60 | -+ | ! |
- )+ title = "View filter mapping", |
|
61 | -+ | ! |
- })+ suppressMessages(icon("fas fa-grip")) |
|
62 |
-
+ ) |
|||
63 | -5x | +
- table_data_decorated_no_print <- srv_transform_teal_data(+ } |
||
64 | -5x | +
- "decorate",+ |
||
65 | -5x | +
- data = table_data,+ #' @rdname module_filter_manager |
||
66 | -5x | +
- transformators = decorators+ #' @keywords internal |
||
67 |
- )+ srv_filter_manager_panel <- function(id, slices_global) { |
|||
68 | -5x | +87x |
- table_data_decorated <- reactive(within(req(table_data_decorated_no_print()), expr = object))+ checkmate::assert_string(id) |
|
69 | -+ | 87x |
-
+ checkmate::assert_class(slices_global, ".slicesGlobal") |
|
70 | -5x | +87x |
- output$text <- renderPrint({+ moduleServer(id, function(input, output, session) { |
|
71 | -9x | +87x |
- req(table_data()) # Ensure original errors from module are displayed+ setBookmarkExclude(c("show_filter_manager")) |
|
72 | -4x | +87x |
- table_data_decorated()[["object"]]+ observeEvent(input$show_filter_manager, { |
|
73 | -- |
- })- |
- ||
74 | -- | - - | -||
75 | -5x | -
- teal.widgets::verbatim_popup_srv(- |
- ||
76 | -5x | -
- id = "rcode",- |
- ||
77 | -5x | -
- verbatim_content = reactive(teal.code::get_code(req(table_data_decorated()))),- |
- ||
78 | -5x | -
- title = "Example Code"- |
- ||
79 | -- |
- )- |
- ||
80 | -- | - - | -||
81 | -5x | -
- table_data_decorated- |
- ||
82 | -- |
- })- |
- ||
83 | -- |
- },- |
- ||
84 | -43x | +! |
- ui = function(id, decorators) {+ logger::log_debug("srv_filter_manager_panel@1 show_filter_manager button has been clicked.") |
|
85 | +74 | ! |
- ns <- NS(id)+ showModal( |
|
86 | +75 | ! |
- teal.widgets::standard_layout(+ modalDialog( |
|
87 | +76 | ! |
- output = verbatimTextOutput(ns("text")),+ ui_filter_manager(session$ns("filter_manager")), |
|
88 | +77 | ! |
- encoding = tags$div(+ class = "filter_manager_modal", |
|
89 | +78 | ! |
- selectInput(ns("dataname"), "Choose a dataset", choices = NULL),+ size = "l", |
|
90 | +79 | ! |
- ui_transform_teal_data(ns("decorate"), transformators = decorators),+ footer = NULL, |
|
91 | +80 | ! |
- teal.widgets::verbatim_popup_ui(ns("rcode"), "Show R code")+ easyClose = TRUE |
|
92 | +81 |
) |
||
93 | +82 |
) |
||
94 | +83 |
- },- |
- ||
95 | -43x | -
- ui_args = list(decorators = decorators),- |
- ||
96 | -43x | -
- server_args = list(decorators = decorators),- |
- ||
97 | -43x | -
- datanames = datanames,+ }) |
||
98 | -43x | +84 | +87x |
- transformators = transformators+ srv_filter_manager("filter_manager", slices_global = slices_global) |
99 | +85 |
- )- |
- ||
100 | -43x | -
- attr(ans, "teal_bookmarkable") <- TRUE- |
- ||
101 | -43x | -
- ans+ }) |
||
102 | +86 |
} |
1 | +87 |
- #' Get client timezone+ |
||
2 | +88 |
- #'+ #' @rdname module_filter_manager |
||
3 | +89 |
- #' User timezone in the browser may be different to the one on the server.+ ui_filter_manager <- function(id) { |
||
4 | -+ | |||
90 | +! |
- #' This script can be run to register a `shiny` input which contains information about the timezone in the browser.+ ns <- NS(id) |
||
5 | -+ | |||
91 | +! |
- #'+ actionButton(ns("filter_manager"), NULL, icon = icon("fas fa-filter")) |
||
6 | -+ | |||
92 | +! |
- #' @param ns (`function`) namespace function passed from the `session` object in the `shiny` server.+ tags$div( |
||
7 | -+ | |||
93 | +! |
- #' For `shiny` modules this will allow for proper name spacing of the registered input.+ class = "filter_manager_content", |
||
8 | -+ | |||
94 | +! |
- #'+ tableOutput(ns("slices_table")) |
||
9 | +95 |
- #' @return `NULL`, invisibly.+ ) |
||
10 | +96 |
- #'+ } |
||
11 | +97 |
- #' @keywords internal+ |
||
12 | +98 |
- #'+ #' @rdname module_filter_manager |
||
13 | +99 |
- get_client_timezone <- function(ns) {- |
- ||
14 | -88x | -
- script <- sprintf(+ srv_filter_manager <- function(id, slices_global) { |
||
15 | -88x | +100 | +87x |
- "Shiny.setInputValue(`%s`, Intl.DateTimeFormat().resolvedOptions().timeZone)",+ checkmate::assert_string(id) |
16 | -88x | +101 | +87x |
- ns("timezone")+ checkmate::assert_class(slices_global, ".slicesGlobal") |
17 | +102 |
- )+ |
||
18 | -88x | +103 | +87x |
- shinyjs::runjs(script) # function does not return anything+ moduleServer(id, function(input, output, session) { |
19 | -88x | -
- invisible(NULL)- |
- ||
20 | -+ | 104 | +87x |
- }+ logger::log_debug("filter_manager_srv initializing.") |
21 | +105 | |||
22 | -- |
- #' Resolve the expected bootstrap theme- |
- ||
23 | +106 |
- #' @noRd+ # Bookmark slices global with mapping. |
||
24 | -+ | |||
107 | +87x |
- #' @keywords internal+ session$onBookmark(function(state) { |
||
25 | -+ | |||
108 | +! |
- get_teal_bs_theme <- function() {+ logger::log_debug("filter_manager_srv@onBookmark: storing filter state") |
||
26 | -4x | +|||
109 | +! |
- bs_theme <- getOption("teal.bs_theme")+ state$values$filter_state_on_bookmark <- as.list( |
||
27 | -+ | |||
110 | +! |
-
+ slices_global$all_slices(), |
||
28 | -4x | +|||
111 | +! |
- if (is.null(bs_theme)) {+ recursive = TRUE |
||
29 | -1x | +|||
112 | +
- return(NULL)+ ) |
|||
30 | +113 |
- }+ }) |
||
31 | +114 | |||
32 | -3x | +115 | +87x |
- if (!checkmate::test_class(bs_theme, "bs_theme")) {+ bookmarked_slices <- restoreValue(session$ns("filter_state_on_bookmark"), NULL) |
33 | -2x | +116 | +87x |
- warning(+ if (!is.null(bookmarked_slices)) { |
34 | -2x | +|||
117 | +! |
- "Assertion on 'teal.bs_theme' option value failed: ",+ logger::log_debug("filter_manager_srv: restoring filter state from bookmark.") |
||
35 | -2x | +|||
118 | +! |
- checkmate::check_class(bs_theme, "bs_theme"),+ slices_global$slices_set(bookmarked_slices) |
||
36 | -2x | +|||
119 | +
- ". The default Shiny Bootstrap theme will be used."+ } |
|||
37 | +120 |
- )+ |
||
38 | -2x | +121 | +87x |
- return(NULL)+ mapping_table <- reactive({ |
39 | +122 |
- }+ # We want this to be reactive on slices_global$all_slices() only as get_available_teal_slices() |
||
40 | +123 |
-
+ # is dependent on slices_global$all_slices(). |
||
41 | -1x | +124 | +96x |
- bs_theme+ module_labels <- setdiff( |
42 | -+ | |||
125 | +96x |
- }+ names(attr(slices_global$all_slices(), "mapping")), |
||
43 | -+ | |||
126 | +96x |
-
+ "Report previewer" |
||
44 | +127 |
- #' Return parentnames along with datanames.+ ) |
||
45 | -+ | |||
128 | +96x |
- #' @noRd+ isolate({ |
||
46 | -+ | |||
129 | +96x |
- #' @keywords internal+ mm <- as.data.frame( |
||
47 | -+ | |||
130 | +96x |
- .include_parent_datanames <- function(datanames, join_keys) {+ sapply( |
||
48 | -32x | +131 | +96x |
- ordered_datanames <- datanames+ module_labels, |
49 | -32x | +132 | +96x |
- for (current in datanames) {+ simplify = FALSE, |
50 | -62x | +133 | +96x |
- parents <- character(0L)+ function(module_label) { |
51 | -62x | +134 | +109x |
- while (length(current) > 0) {+ available_slices <- slices_global$module_slices_api[[module_label]]$get_available_teal_slices() |
52 | -64x | +135 | +101x |
- current <- teal.data::parent(join_keys, current)+ global_ids <- sapply(slices_global$all_slices(), `[[`, "id", simplify = FALSE) |
53 | -64x | +136 | +101x |
- parents <- c(current, parents)+ module_ids <- sapply(slices_global$slices_get(module_label), `[[`, "id", simplify = FALSE) |
54 | -+ | |||
137 | +101x |
- }+ allowed_ids <- vapply(available_slices, `[[`, character(1L), "id") |
||
55 | -62x | +138 | +101x |
- ordered_datanames <- c(parents, ordered_datanames)+ active_ids <- global_ids %in% module_ids |
56 | -+ | |||
139 | +101x |
- }+ setNames(nm = global_ids, ifelse(global_ids %in% allowed_ids, active_ids, NA)) |
||
57 | +140 | - - | -||
58 | -32x | -
- unique(ordered_datanames)+ } |
||
59 | +141 |
- }+ ), |
||
60 | -+ | |||
142 | +96x |
-
+ check.names = FALSE |
||
61 | +143 |
- #' Create a `FilteredData`+ ) |
||
62 | -+ | |||
144 | +88x |
- #'+ colnames(mm)[colnames(mm) == "global_filters"] <- "Global filters" |
||
63 | +145 |
- #' Create a `FilteredData` object from a `teal_data` object.+ |
||
64 | -+ | |||
146 | +88x |
- #'+ mm |
||
65 | +147 |
- #' @param x (`teal_data`) object+ }) |
||
66 | +148 |
- #' @param datanames (`character`) vector of data set names to include; must be subset of `names(x)`+ }) |
||
67 | +149 |
- #' @return A `FilteredData` object.+ |
||
68 | -+ | |||
150 | +87x |
- #' @keywords internal+ output$slices_table <- renderTable( |
||
69 | -+ | |||
151 | +87x |
- teal_data_to_filtered_data <- function(x, datanames = names(x)) {+ expr = { |
||
70 | -83x | +152 | +96x |
- checkmate::assert_class(x, "teal_data")+ logger::log_debug("filter_manager_srv@1 rendering slices_table.") |
71 | -83x | +153 | +96x |
- checkmate::assert_character(datanames, min.chars = 1L, any.missing = FALSE)+ mm <- mapping_table() |
72 | +154 |
- # Otherwise, FilteredData will be created in the modules' scope later+ |
||
73 | -83x | +|||
155 | +
- teal.slice::init_filtered_data(+ # Display logical values as UTF characters. |
|||
74 | -83x | +156 | +88x |
- x = Filter(length, sapply(datanames, function(dn) x[[dn]], simplify = FALSE)),+ mm[] <- lapply(mm, ifelse, yes = intToUtf8(9989), no = intToUtf8(10060)) |
75 | -83x | +157 | +88x |
- join_keys = teal.data::join_keys(x)+ mm[] <- lapply(mm, function(x) ifelse(is.na(x), intToUtf8(128306), x)) |
76 | +158 |
- )+ |
||
77 | +159 |
- }+ # Display placeholder if no filters defined. |
||
78 | -+ | |||
160 | +88x |
-
+ if (nrow(mm) == 0L) { |
||
79 | -+ | |||
161 | +64x |
-
+ mm <- data.frame(`Filter manager` = "No filters specified.", check.names = FALSE) |
||
80 | -+ | |||
162 | +64x |
- #' Template function for `TealReportCard` creation and customization+ rownames(mm) <- "" |
||
81 | +163 |
- #'+ } |
||
82 | -+ | |||
164 | +88x |
- #' This function generates a report card with a title,+ mm |
||
83 | +165 |
- #' an optional description, and the option to append the filter state list.+ }, |
||
84 | -+ | |||
166 | +87x |
- #'+ rownames = TRUE |
||
85 | +167 |
- #' @param title (`character(1)`) title of the card (unless overwritten by label)+ ) |
||
86 | +168 |
- #' @param label (`character(1)`) label provided by the user when adding the card+ |
||
87 | -+ | |||
169 | +87x |
- #' @param description (`character(1)`) optional, additional description+ mapping_table # for testing purpose |
||
88 | +170 |
- #' @param with_filter (`logical(1)`) flag indicating to add filter state+ }) |
||
89 | +171 |
- #' @param filter_panel_api (`FilterPanelAPI`) object with API that allows the generation+ } |
||
90 | +172 |
- #' of the filter state in the report+ |
||
91 | +173 |
- #'+ #' @rdname module_filter_manager |
||
92 | +174 |
- #' @return (`TealReportCard`) populated with a title, description and filter state.+ srv_module_filter_manager <- function(id, module_fd, slices_global) { |
||
93 | -+ | |||
175 | +112x |
- #'+ checkmate::assert_string(id) |
||
94 | -+ | |||
176 | +112x |
- #' @export+ assert_reactive(module_fd)+ |
+ ||
177 | +112x | +
+ checkmate::assert_class(slices_global, ".slicesGlobal") |
||
95 | +178 |
- report_card_template <- function(title, label, description = NULL, with_filter, filter_panel_api) {+ |
||
96 | -2x | +179 | +112x |
- checkmate::assert_string(title)+ moduleServer(id, function(input, output, session) { |
97 | -2x | +180 | +112x |
- checkmate::assert_string(label)+ logger::log_debug("srv_module_filter_manager initializing for module: { id }.") |
98 | -2x | +|||
181 | +
- checkmate::assert_string(description, null.ok = TRUE)+ # Track filter global and local states. |
|||
99 | -2x | +182 | +112x |
- checkmate::assert_flag(with_filter)+ slices_global_module <- reactive({ |
100 | -2x | +183 | +201x |
- checkmate::assert_class(filter_panel_api, classes = "FilterPanelAPI")+ slices_global$slices_get(module_label = id) |
101 | +184 |
-
+ }) |
||
102 | -2x | +185 | +112x |
- card <- teal::TealReportCard$new()+ slices_module <- reactive(req(module_fd())$get_filter_state()) |
103 | -2x | +|||
186 | +
- title <- if (label == "") title else label+ |
|||
104 | -2x | +187 | +112x |
- card$set_name(title)+ module_fd_previous <- reactiveVal(NULL) |
105 | -2x | +|||
188 | +
- card$append_text(title, "header2")+ |
|||
106 | -1x | +|||
189 | +
- if (!is.null(description)) card$append_text(description, "header3")+ # Set (reactively) available filters for the module. |
|||
107 | -1x | +190 | +112x |
- if (with_filter) card$append_fs(filter_panel_api$get_filter_state())+ obs1 <- observeEvent(module_fd(), priority = 1, { |
108 | -2x | +191 | +93x |
- card+ logger::log_debug("srv_module_filter_manager@1 setting initial slices for module: { id }.") |
109 | +192 |
- }+ # Filters relevant for the module in module-specific app. |
||
110 | -+ | |||
193 | +93x |
-
+ slices <- slices_global_module() |
||
111 | +194 | |||
112 | +195 |
- #' Check `datanames` in modules+ # Clean up previous filter states and refresh cache of previous module_fd with current |
||
113 | -+ | |||
196 | +3x |
- #'+ if (!is.null(module_fd_previous())) module_fd_previous()$finalize() |
||
114 | -+ | |||
197 | +93x |
- #' These functions check if specified `datanames` in modules match those in the data object,+ module_fd_previous(module_fd()) |
||
115 | +198 |
- #' returning error messages or `TRUE` for successful validation. Two functions return error message+ |
||
116 | +199 |
- #' in different forms:+ # Setting filter states from slices_global: |
||
117 | +200 |
- #' - `check_modules_datanames` returns `character(1)` for basic assertion usage+ # 1. when app initializes slices_global set to initial filters (specified by app developer) |
||
118 | +201 |
- #' - `check_modules_datanames_html` returns `shiny.tag.list` to display it in the app.+ # 2. when data reinitializes slices_global reflects latest filter states |
||
119 | +202 |
- #'+ |
||
120 | -+ | |||
203 | +93x |
- #' @param modules (`teal_modules`) object+ module_fd()$set_filter_state(slices) |
||
121 | +204 |
- #' @param datanames (`character`) names of datasets available in the `data` object+ |
||
122 | +205 |
- #'+ # irrelevant filters are discarded in FilteredData$set_available_teal_slices |
||
123 | +206 |
- #' @return `TRUE` if validation passes, otherwise `character(1)` or `shiny.tag.list`+ # it means we don't need to subset slices_global$all_slices() from filters refering to irrelevant datasets+ |
+ ||
207 | +93x | +
+ module_fd()$set_available_teal_slices(slices_global$all_slices) |
||
124 | +208 |
- #' @keywords internal+ |
||
125 | +209 |
- check_modules_datanames <- function(modules, datanames) {+ # this needed in filter_manager_srv |
||
126 | -11x | +210 | +93x |
- out <- check_modules_datanames_html(modules, datanames)+ slices_global$module_slices_api_set( |
127 | -11x | +211 | +93x |
- if (inherits(out, "shiny.tag.list")) {+ id, |
128 | -5x | +212 | +93x |
- out_with_ticks <- gsub("<code>|</code>", "`", toString(out))+ list( |
129 | -5x | +213 | +93x |
- out_text <- gsub("<[^<>]+>", "", toString(out_with_ticks))+ get_available_teal_slices = module_fd()$get_available_teal_slices(), |
130 | -5x | +214 | +93x |
- trimws(gsub("[[:space:]]+", " ", out_text))+ set_filter_state = module_fd()$set_filter_state, # for testing purpose |
131 | -+ | |||
215 | +93x |
- } else {+ get_filter_state = module_fd()$get_filter_state # for testing purpose |
||
132 | -6x | +|||
216 | +
- out+ ) |
|||
133 | +217 |
- }+ ) |
||
134 | +218 |
- }+ }) |
||
135 | +219 | |||
136 | +220 |
- #' @rdname check_modules_datanames+ # Update global state and mapping matrix when module filters change. |
||
137 | -+ | |||
221 | +112x |
- check_reserved_datanames <- function(datanames) {+ obs2 <- observeEvent(slices_module(), priority = 0, { |
||
138 | -190x | +222 | +113x |
- reserved_datanames <- datanames[datanames %in% c("all", ".raw_data")]+ this_slices <- slices_module() |
139 | -190x | +223 | +113x |
- if (length(reserved_datanames) == 0L) {+ slices_global$slices_append(this_slices) # append new slices to the all_slices list |
140 | -184x | +224 | +113x |
- return(NULL)+ mapping_elem <- setNames(nm = id, list(vapply(this_slices, `[[`, character(1L), "id")))+ |
+
225 | +113x | +
+ slices_global$slices_active(mapping_elem) |
||
141 | +226 |
- }+ }) |
||
142 | +227 | |||
143 | -6x | +228 | +112x |
- tags$span(+ obs3 <- observeEvent(slices_global_module(), { |
144 | -6x | +229 | +135x |
- to_html_code_list(reserved_datanames),+ global_vs_module <- setdiff_teal_slices(slices_global_module(), slices_module()) |
145 | -6x | +230 | +135x |
- sprintf(+ module_vs_global <- setdiff_teal_slices(slices_module(), slices_global_module()) |
146 | -6x | +231 | +126x |
- "%s reserved for internal use. Please avoid using %s as %s.",+ if (length(global_vs_module) || length(module_vs_global)) { |
147 | -6x | +|||
232 | +
- pluralize(reserved_datanames, "is", "are"),+ # Comment: (Nota Bene) Normally new filters for a module are added through module-filter-panel, and slices |
|||
148 | -6x | +|||
233 | +
- pluralize(reserved_datanames, "it", "them"),+ # global are updated automatically so slices_module -> slices_global_module are equal. |
|||
149 | -6x | +|||
234 | +
- pluralize(reserved_datanames, "a dataset name", "dataset names")+ # this if is valid only when a change is made on the global level so the change needs to be propagated down |
|||
150 | +235 |
- )+ # to the module (for example through snapshot manager). If it happens both slices are different |
||
151 | -+ | |||
236 | +13x |
- )+ logger::log_debug("srv_module_filter_manager@3 (N.B.) global state has changed for a module:{ id }.") |
||
152 | -+ | |||
237 | +13x |
- }+ module_fd()$clear_filter_states() |
||
153 | -+ | |||
238 | +13x |
-
+ module_fd()$set_filter_state(slices_global_module()) |
||
154 | +239 |
- #' @rdname check_modules_datanames+ } |
||
155 | +240 |
- check_modules_datanames_html <- function(modules, datanames) {+ }) |
||
156 | -190x | +|||
241 | +
- check_datanames <- check_modules_datanames_recursive(modules, datanames)+ |
|||
157 | -190x | +242 | +112x |
- show_module_info <- inherits(modules, "teal_modules") # used in two contexts - module and app+ slices_module # returned for testing purpose |
158 | +243 |
-
+ }) |
||
159 | -190x | +|||
244 | +
- reserved_datanames <- check_reserved_datanames(datanames)+ } |
|||
160 | +245 | |||
161 | -190x | +|||
246 | +
- if (!length(check_datanames)) {+ #' @importFrom shiny reactiveVal reactiveValues |
|||
162 | -172x | +|||
247 | +
- out <- if (is.null(reserved_datanames)) {+ methods::setOldClass("reactiveVal") |
|||
163 | -166x | +|||
248 | +
- TRUE+ methods::setOldClass("reactivevalues") |
|||
164 | +249 |
- } else {+ |
||
165 | -6x | +|||
250 | +
- shiny::tagList(reserved_datanames)+ #' @importFrom methods new |
|||
166 | +251 |
- }+ #' @rdname module_filter_manager |
||
167 | -172x | +|||
252 | +
- return(out)+ .slicesGlobal <- methods::setRefClass(".slicesGlobal", # nolint: object_name. |
|||
168 | +253 |
- }+ fields = list( |
||
169 | -18x | +|||
254 | +
- shiny::tagList(+ all_slices = "reactiveVal", |
|||
170 | -18x | +|||
255 | +
- reserved_datanames,+ module_slices_api = "reactivevalues" |
|||
171 | -18x | +|||
256 | +
- lapply(+ ), |
|||
172 | -18x | +|||
257 | +
- check_datanames,+ methods = list( |
|||
173 | -18x | +|||
258 | +
- function(mod) {+ initialize = function(slices = teal_slices(), module_labels) { |
|||
174 | -18x | +259 | +87x |
- tagList(+ shiny::isolate({ |
175 | -18x | +260 | +87x |
- tags$span(+ checkmate::assert_class(slices, "teal_slices") |
176 | -18x | +|||
261 | +
- tags$span(pluralize(mod$missing_datanames, "Dataset")),+ # needed on init to not mix "global_filters" with module-specific-slots |
|||
177 | -18x | +262 | +87x |
- to_html_code_list(mod$missing_datanames),+ if (isTRUE(attr(slices, "module_specific"))) { |
178 | -18x | +263 | +11x |
- tags$span(+ old_mapping <- attr(slices, "mapping") |
179 | -18x | +264 | +11x |
- sprintf(+ new_mapping <- sapply(module_labels, simplify = FALSE, function(module_label) { |
180 | -18x | +265 | +20x |
- "%s missing%s.",+ unique(unlist(old_mapping[c(module_label, "global_filters")])) |
181 | -18x | +|||
266 | +
- pluralize(mod$missing_datanames, "is", "are"),+ }) |
|||
182 | -18x | +267 | +11x |
- if (show_module_info) sprintf(" for module '%s'", mod$label) else ""+ attr(slices, "mapping") <- new_mapping |
183 | +268 |
- )+ } |
||
184 | -+ | |||
269 | +87x |
- )+ .self$all_slices <<- shiny::reactiveVal(slices) |
||
185 | -+ | |||
270 | +87x |
- ),+ .self$module_slices_api <<- shiny::reactiveValues() |
||
186 | -18x | +271 | +87x |
- if (length(datanames) >= 1) {+ .self$slices_append(slices) |
187 | -16x | +272 | +87x |
- tagList(+ .self$slices_active(attr(slices, "mapping")) |
188 | -16x | +273 | +87x |
- tags$span(pluralize(datanames, "Dataset")),+ invisible(.self) |
189 | -16x | +|||
274 | +
- tags$span("available in data:"),+ }) |
|||
190 | -16x | +|||
275 | +
- tagList(+ },+ |
+ |||
276 | ++ |
+ is_module_specific = function() { |
||
191 | -16x | +277 | +296x |
- tags$span(+ isTRUE(attr(.self$all_slices(), "module_specific")) |
192 | -16x | +|||
278 | +
- to_html_code_list(datanames),+ }, |
|||
193 | -16x | +|||
279 | +
- tags$span(".", .noWS = "outside"),+ module_slices_api_set = function(module_label, functions_list) { |
|||
194 | -16x | +280 | +93x |
- .noWS = c("outside")+ shiny::isolate({ |
195 | -+ | |||
281 | +93x |
- )+ if (!.self$is_module_specific()) { |
||
196 | -+ | |||
282 | +77x |
- )+ module_label <- "global_filters" |
||
197 | +283 |
- )+ } |
||
198 | -+ | |||
284 | +93x |
- } else {+ if (!identical(.self$module_slices_api[[module_label]], functions_list)) { |
||
199 | -2x | +285 | +93x |
- tags$span("No datasets are available in data.")+ .self$module_slices_api[[module_label]] <- functions_list |
200 | +286 |
- },+ } |
||
201 | -18x | +287 | +93x |
- tags$br(.noWS = "before")+ invisible(.self) |
202 | +288 |
- )+ }) |
||
203 | +289 |
- }+ }, |
||
204 | +290 |
- )+ slices_deactivate_all = function(module_label) { |
||
205 | -+ | |||
291 | +! |
- )+ shiny::isolate({ |
||
206 | -+ | |||
292 | +! |
- }+ new_slices <- .self$all_slices() |
||
207 | -+ | |||
293 | +! |
-
+ old_mapping <- attr(new_slices, "mapping") |
||
208 | +294 |
- #' Recursively checks modules and returns list for every datanames mismatch between module and data+ |
||
209 | -+ | |||
295 | +! |
- #' @noRd+ new_mapping <- if (.self$is_module_specific()) { |
||
210 | -+ | |||
296 | +! |
- check_modules_datanames_recursive <- function(modules, datanames) { # nolint: object_name_length+ new_module_mapping <- setNames(nm = module_label, list(character(0))) |
||
211 | -296x | +|||
297 | +! |
- checkmate::assert_multi_class(modules, c("teal_module", "teal_modules"))+ modifyList(old_mapping, new_module_mapping) |
||
212 | -296x | +|||
298 | +! |
- checkmate::assert_character(datanames)+ } else if (missing(module_label)) { |
||
213 | -296x | +|||
299 | +! |
- if (inherits(modules, "teal_modules")) {+ lapply( |
||
214 | -86x | +|||
300 | +! |
- unlist(+ attr(.self$all_slices(), "mapping"), |
||
215 | -86x | +|||
301 | +! |
- lapply(modules$children, check_modules_datanames_recursive, datanames = datanames),+ function(x) character(0) |
||
216 | -86x | +|||
302 | +
- recursive = FALSE+ ) |
|||
217 | +303 |
- )+ } else {+ |
+ ||
304 | +! | +
+ old_mapping[[module_label]] <- character(0)+ |
+ ||
305 | +! | +
+ old_mapping |
||
218 | +306 |
- } else {+ } |
||
219 | -210x | +|||
307 | +
- missing_datanames <- setdiff(modules$datanames, c("all", datanames))+ |
|||
220 | -210x | +|||
308 | +! |
- if (length(missing_datanames)) {+ if (!identical(new_mapping, old_mapping)) { |
||
221 | -18x | +|||
309 | +! |
- list(list(+ logger::log_debug(".slicesGlobal@slices_deactivate_all: deactivating all slices.") |
||
222 | -18x | +|||
310 | +! |
- label = modules$label,+ attr(new_slices, "mapping") <- new_mapping |
||
223 | -18x | +|||
311 | +! |
- missing_datanames = missing_datanames+ .self$all_slices(new_slices) |
||
224 | +312 |
- ))+ } |
||
225 | -+ | |||
313 | +! |
- }+ invisible(.self) |
||
226 | +314 |
- }+ }) |
||
227 | +315 |
- }+ }, |
||
228 | +316 |
-
+ slices_active = function(mapping_elem) { |
||
229 | -+ | |||
317 | +203x |
- #' Convert character vector to html code separated with commas and "and"+ shiny::isolate({ |
||
230 | -+ | |||
318 | +203x |
- #' @noRd+ if (.self$is_module_specific()) {+ |
+ ||
319 | +36x | +
+ new_mapping <- modifyList(attr(.self$all_slices(), "mapping"), mapping_elem) |
||
231 | +320 |
- to_html_code_list <- function(x) {+ } else { |
||
232 | -40x | +321 | +167x |
- checkmate::assert_character(x)+ new_mapping <- setNames(nm = "global_filters", list(unique(unlist(mapping_elem)))) |
233 | -40x | +|||
322 | +
- do.call(+ }+ |
+ |||
323 | ++ | + | ||
234 | -40x | +324 | +203x |
- tagList,+ if (!identical(new_mapping, attr(.self$all_slices(), "mapping"))) { |
235 | -40x | +325 | +146x |
- lapply(seq_along(x), function(.ix) {+ mapping_modules <- toString(names(new_mapping)) |
236 | -56x | +326 | +146x |
- tagList(+ logger::log_debug(".slicesGlobal@slices_active: changing mapping for module(s): { mapping_modules }.") |
237 | -56x | +327 | +146x |
- tags$code(x[.ix]),+ new_slices <- .self$all_slices() |
238 | -56x | +328 | +146x |
- if (.ix != length(x)) {+ attr(new_slices, "mapping") <- new_mapping |
239 | -1x | +329 | +146x |
- if (.ix == length(x) - 1) tags$span(" and ") else tags$span(", ", .noWS = "before")+ .self$all_slices(new_slices) |
240 | +330 |
} |
||
241 | +331 |
- )+ |
||
242 | -+ | |||
332 | +203x |
- })+ invisible(.self) |
||
243 | +333 |
- )+ }) |
||
244 | +334 |
- }+ }, |
||
245 | +335 |
-
+ # - only new filters are appended to the $all_slices |
||
246 | +336 |
-
+ # - mapping is not updated here |
||
247 | +337 |
- #' Check `datanames` in filters+ slices_append = function(slices, activate = FALSE) { |
||
248 | -+ | |||
338 | +203x |
- #'+ shiny::isolate({ |
||
249 | -+ | |||
339 | +203x |
- #' This function checks whether `datanames` in filters correspond to those in `data`,+ if (!is.teal_slices(slices)) { |
||
250 | -+ | |||
340 | +! |
- #' returning character vector with error messages or `TRUE` if all checks pass.+ slices <- as.teal_slices(slices) |
||
251 | +341 |
- #'+ } |
||
252 | +342 |
- #' @param filters (`teal_slices`) object+ |
||
253 | +343 |
- #' @param datanames (`character`) names of datasets available in the `data` object+ # to make sure that we don't unnecessary trigger $all_slices <reactiveVal> |
||
254 | -+ | |||
344 | +203x |
- #'+ new_slices <- setdiff_teal_slices(slices, .self$all_slices()) |
||
255 | -+ | |||
345 | +203x |
- #' @return A `character(1)` containing error message or TRUE if validation passes.+ old_mapping <- attr(.self$all_slices(), "mapping") |
||
256 | -+ | |||
346 | +203x |
- #' @keywords internal+ if (length(new_slices)) { |
||
257 | -+ | |||
347 | +6x |
- check_filter_datanames <- function(filters, datanames) {+ new_ids <- vapply(new_slices, `[[`, character(1L), "id") |
||
258 | -86x | +348 | +6x |
- checkmate::assert_class(filters, "teal_slices")+ logger::log_debug(".slicesGlobal@slices_append: appending new slice(s): { new_ids }.") |
259 | -86x | +349 | +6x |
- checkmate::assert_character(datanames)+ slices_ids <- vapply(.self$all_slices(), `[[`, character(1L), "id") |
260 | -+ | |||
350 | +6x |
-
+ lapply(new_slices, function(slice) { |
||
261 | +351 |
- # check teal_slices against datanames- |
- ||
262 | -86x | -
- out <- unlist(sapply(+ # In case the new state has the same id as an existing one, add a suffix |
||
263 | -86x | +352 | +6x |
- filters, function(filter) {+ if (slice$id %in% slices_ids) { |
264 | -24x | +353 | +1x |
- dataname <- shiny::isolate(filter$dataname)+ slice$id <- utils::tail(make.unique(c(slices_ids, slice$id), sep = "_"), 1) |
265 | -24x | +|||
354 | +
- if (!dataname %in% datanames) {+ } |
|||
266 | -3x | +|||
355 | +
- sprintf(+ }) |
|||
267 | -3x | +|||
356 | +
- "- Filter '%s' refers to dataname not available in 'data':\n %s not in (%s)",+ |
|||
268 | -3x | +357 | +6x |
- shiny::isolate(filter$id),+ new_slices_all <- c(.self$all_slices(), new_slices) |
269 | -3x | +358 | +6x |
- dQuote(dataname, q = FALSE),+ attr(new_slices_all, "mapping") <- old_mapping |
270 | -3x | +359 | +6x |
- toString(dQuote(datanames, q = FALSE))+ .self$all_slices(new_slices_all) |
271 | +360 |
- )+ } |
||
272 | +361 |
- }+ |
||
273 | -+ | |||
362 | +203x |
- }+ invisible(.self) |
||
274 | +363 |
- ))+ }) |
||
275 | +364 |
-
+ }, |
||
276 | +365 |
-
+ slices_get = function(module_label) { |
||
277 | -86x | +366 | +302x |
- if (length(out)) {+ if (missing(module_label)) { |
278 | -3x | +|||
367 | +! |
- paste(out, collapse = "\n")+ .self$all_slices() |
||
279 | +368 |
- } else {+ } else { |
||
280 | -83x | -
- TRUE- |
- ||
281 | -+ | 369 | +302x |
- }+ module_ids <- unlist(attr(.self$all_slices(), "mapping")[c(module_label, "global_filters")]) |
282 | -+ | |||
370 | +302x |
- }+ Filter( |
||
283 | -+ | |||
371 | +302x |
-
+ function(slice) slice$id %in% module_ids, |
||
284 | -+ | |||
372 | +302x |
- #' Function for validating the title parameter of `teal::init`+ .self$all_slices() |
||
285 | +373 |
- #'+ ) |
||
286 | +374 |
- #' Checks if the input of the title from `teal::init` will create a valid title and favicon tag.+ } |
||
287 | +375 |
- #' @param shiny_tag (`shiny.tag`) Object to validate for a valid title.+ }, |
||
288 | +376 |
- #' @keywords internal+ slices_set = function(slices) { |
||
289 | -+ | |||
377 | +7x |
- validate_app_title_tag <- function(shiny_tag) {+ shiny::isolate({ |
||
290 | +378 | 7x |
- checkmate::assert_class(shiny_tag, "shiny.tag")+ if (!is.teal_slices(slices)) { |
|
291 | -7x | +|||
379 | +! |
- checkmate::assert_true(shiny_tag$name == "head")+ slices <- as.teal_slices(slices) |
||
292 | -6x | +|||
380 | +
- child_names <- vapply(shiny_tag$children, `[[`, character(1L), "name")+ } |
|||
293 | -6x | +381 | +7x |
- checkmate::assert_subset(c("title", "link"), child_names, .var.name = "child tags")+ .self$all_slices(slices) |
294 | -4x | +382 | +7x |
- rel_attr <- shiny_tag$children[[which(child_names == "link")]]$attribs$rel+ invisible(.self) |
295 | -4x | +|||
383 | +
- checkmate::assert_subset(+ }) |
|||
296 | -4x | +|||
384 | +
- rel_attr,+ }, |
|||
297 | -4x | +|||
385 | +
- c("icon", "shortcut icon"),+ show = function() { |
|||
298 | -4x | +|||
386 | +! |
- .var.name = "Link tag's rel attribute",+ shiny::isolate(print(.self$all_slices())) |
||
299 | -4x | +|||
387 | +! |
- empty.ok = FALSE+ invisible(.self) |
||
300 | +388 |
- )+ } |
||
301 | +389 |
- }+ ) |
||
302 | +390 |
-
+ ) |
303 | +1 |
- #' Build app title with favicon+ #' An example `teal` module |
||
304 | +2 |
#' |
||
305 | +3 |
- #' A helper function to create the browser title along with a logo.+ #' `r lifecycle::badge("experimental")` |
||
306 | +4 |
#' |
||
307 | +5 |
- #' @param title (`character`) The browser title for the `teal` app.+ #' This module creates an object called `object` that can be modified with decorators. |
||
308 | +6 |
- #' @param favicon (`character`) The path for the icon for the title.+ #' The `object` is determined by what's selected in `Choose a dataset` input in UI. |
||
309 | +7 |
- #' The image/icon path can be remote or the static path accessible by `shiny`, like the `www/`+ #' The object can be anything that can be handled by `renderPrint()`. |
||
310 | +8 |
- #'+ #' See the `vignette("decorate-modules-output", package = "teal")` or [`teal_transform_module`] |
||
311 | +9 |
- #' @return A `shiny.tag` containing the element that adds the title and logo to the `shiny` app.+ #' to read more about decorators. |
||
312 | +10 |
- #' @export+ #' |
||
313 | +11 |
- build_app_title <- function(+ #' @inheritParams teal_modules |
||
314 | +12 |
- title = "teal app",+ #' @param decorators `r lifecycle::badge("experimental")` (`list` of `teal_transform_module` or `NULL`) optional, |
||
315 | +13 |
- favicon = "https://raw.githubusercontent.com/insightsengineering/hex-stickers/main/PNG/nest.png") {+ #' if not `NULL`, decorator for tables or plots included in the module. |
||
316 | -15x | +|||
14 | +
- checkmate::assert_string(title, null.ok = TRUE)+ #' |
|||
317 | -15x | +|||
15 | +
- checkmate::assert_string(favicon, null.ok = TRUE)+ #' @return A `teal` module which can be included in the `modules` argument to [init()]. |
|||
318 | -15x | +|||
16 | +
- tags$head(+ #' @examples |
|||
319 | -15x | +|||
17 | +
- tags$title(title),+ #' app <- init( |
|||
320 | -15x | +|||
18 | +
- tags$link(+ #' data = teal_data(IRIS = iris, MTCARS = mtcars), |
|||
321 | -15x | +|||
19 | +
- rel = "icon",+ #' modules = example_module() |
|||
322 | -15x | +|||
20 | +
- href = favicon,+ #' ) |
|||
323 | -15x | +|||
21 | +
- sizes = "any"+ #' if (interactive()) { |
|||
324 | +22 |
- )+ #' shinyApp(app$ui, app$server) |
||
325 | +23 |
- )+ #' } |
||
326 | +24 |
- }+ #' @export |
||
327 | +25 |
-
+ example_module <- function(label = "example teal module", |
||
328 | +26 |
- #' Application ID+ datanames = "all", |
||
329 | +27 |
- #'+ transformators = list(), |
||
330 | +28 |
- #' Creates App ID used to match filter snapshots to application.+ decorators = NULL) { |
||
331 | -+ | |||
29 | +43x |
- #'+ checkmate::assert_string(label) |
||
332 | -+ | |||
30 | +43x |
- #' Calculate app ID that will be used to stamp filter state snapshots.+ checkmate::assert_list(decorators, "teal_transform_module", null.ok = TRUE) |
||
333 | +31 |
- #' App ID is a hash of the app's data and modules.+ |
||
334 | -+ | |||
32 | +43x |
- #' See "transferring snapshots" section in ?snapshot.+ ans <- module( |
||
335 | -+ | |||
33 | +43x |
- #'+ label, |
||
336 | -+ | |||
34 | +43x |
- #' @param data (`teal_data` or `teal_data_module`) as accepted by `init`+ server = function(id, data, decorators) { |
||
337 | -+ | |||
35 | +5x |
- #' @param modules (`teal_modules`) object as accepted by `init`+ checkmate::assert_class(isolate(data()), "teal_data") |
||
338 | -+ | |||
36 | +5x |
- #'+ moduleServer(id, function(input, output, session) { |
||
339 | -+ | |||
37 | +5x |
- #' @return A single character string.+ datanames_rv <- reactive(names(req(data()))) |
||
340 | -+ | |||
38 | +5x |
- #'+ observeEvent(datanames_rv(), { |
||
341 | -+ | |||
39 | +5x |
- #' @keywords internal+ selected <- input$dataname+ |
+ ||
40 | +5x | +
+ if (identical(selected, "")) {+ |
+ ||
41 | +! | +
+ selected <- restoreInput(session$ns("dataname"), NULL)+ |
+ ||
42 | +5x | +
+ } else if (isFALSE(selected %in% datanames_rv())) {+ |
+ ||
43 | +! | +
+ selected <- datanames_rv()[1] |
||
342 | +44 |
- create_app_id <- function(data, modules) {+ } |
||
343 | -23x | +45 | +5x |
- checkmate::assert_multi_class(data, c("teal_data", "teal_data_module"))+ updateSelectInput( |
344 | -22x | +46 | +5x | +
+ session = session,+ |
+
47 | +5x | +
+ inputId = "dataname",+ |
+ ||
48 | +5x | +
+ choices = datanames_rv(),+ |
+ ||
49 | +5x | +
+ selected = selected+ |
+ ||
50 | +
- checkmate::assert_class(modules, "teal_modules")+ ) |
|||
345 | +51 |
-
+ }) |
||
346 | -21x | +|||
52 | +
- data <- if (inherits(data, "teal_data")) {+ |
|||
347 | -19x | +53 | +5x |
- as.list(data)+ table_data <- reactive({ |
348 | -21x | +54 | +8x |
- } else if (inherits(data, "teal_data_module")) {+ req(input$dataname) |
349 | -2x | +55 | +3x |
- deparse1(body(data$server))+ within(data(), |
350 | +56 |
- }+ { |
||
351 | -21x | +57 | +3x |
- modules <- lapply(modules, defunction)+ object <- dataname |
352 | +58 |
-
+ }, |
||
353 | -21x | -
- rlang::hash(list(data = data, modules = modules))- |
- ||
354 | -+ | 59 | +3x |
- }+ dataname = as.name(input$dataname) |
355 | +60 |
-
+ ) |
||
356 | +61 |
- #' Go through list and extract bodies of encountered functions as string, recursively.+ }) |
||
357 | +62 |
- #' @keywords internal+ |
||
358 | -+ | |||
63 | +5x |
- #' @noRd+ table_data_decorated_no_print <- srv_transform_teal_data( |
||
359 | -+ | |||
64 | +5x |
- defunction <- function(x) {+ "decorate", |
||
360 | -297x | +65 | +5x |
- if (is.list(x)) {+ data = table_data, |
361 | -121x | +66 | +5x |
- lapply(x, defunction)+ transformators = decorators |
362 | -176x | +|||
67 | +
- } else if (is.function(x)) {+ ) |
|||
363 | -54x | +68 | +5x |
- deparse1(body(x))+ table_data_decorated <- reactive(within(req(table_data_decorated_no_print()), expr = object)) |
364 | +69 |
- } else {+ |
||
365 | -122x | +70 | +5x |
- x+ output$text <- renderPrint({ |
366 | -+ | |||
71 | +9x |
- }+ req(table_data()) # Ensure original errors from module are displayed |
||
367 | -+ | |||
72 | +4x |
- }+ table_data_decorated()[["object"]] |
||
368 | +73 |
-
+ }) |
||
369 | +74 |
- #' Get unique labels+ |
||
370 | -+ | |||
75 | +5x |
- #'+ teal.widgets::verbatim_popup_srv( |
||
371 | -+ | |||
76 | +5x |
- #' Get unique labels for the modules to avoid namespace conflicts.+ id = "rcode", |
||
372 | -+ | |||
77 | +5x |
- #'+ verbatim_content = reactive(teal.code::get_code(req(table_data_decorated()))), |
||
373 | -+ | |||
78 | +5x |
- #' @param labels (`character`) vector of labels+ title = "Example Code" |
||
374 | +79 |
- #'+ ) |
||
375 | +80 |
- #' @return (`character`) vector of unique labels+ |
||
376 | -+ | |||
81 | +5x |
- #'+ table_data_decorated |
||
377 | +82 |
- #' @keywords internal+ }) |
||
378 | +83 |
- get_unique_labels <- function(labels) {+ }, |
||
379 | -141x | +84 | +43x |
- make.unique(gsub("[^[:alnum:]]", "_", tolower(labels)), sep = "_")+ ui = function(id, decorators) { |
380 | -+ | |||
85 | +! |
- }+ ns <- NS(id) |
||
381 | -+ | |||
86 | +! |
-
+ teal.widgets::standard_layout( |
||
382 | -+ | |||
87 | +! |
- #' Remove ANSI escape sequences from a string+ output = verbatimTextOutput(ns("text")), |
||
383 | -+ | |||
88 | +! |
- #' @noRd+ encoding = tags$div( |
||
384 | -+ | |||
89 | +! |
- strip_style <- function(string) {+ selectInput(ns("dataname"), "Choose a dataset", choices = NULL), |
||
385 | -2x | +|||
90 | +! |
- checkmate::assert_string(string)+ ui_transform_teal_data(ns("decorate"), transformators = decorators), |
||
386 | -+ | |||
91 | +! |
-
+ teal.widgets::verbatim_popup_ui(ns("rcode"), "Show R code") |
||
387 | -2x | +|||
92 | +
- gsub(+ ) |
|||
388 | -2x | +|||
93 | +
- "(?:(?:\\x{001b}\\[)|\\x{009b})(?:(?:[0-9]{1,3})?(?:(?:;[0-9]{0,3})*)?[A-M|f-m])|\\x{001b}[A-M]",+ ) |
|||
389 | +94 |
- "",+ }, |
||
390 | -2x | +95 | +43x |
- string,+ ui_args = list(decorators = decorators), |
391 | -2x | +96 | +43x |
- perl = TRUE,+ server_args = list(decorators = decorators), |
392 | -2x | +97 | +43x |
- useBytes = TRUE+ datanames = datanames, |
393 | -+ | |||
98 | +43x |
- )+ transformators = transformators |
||
394 | +99 |
- }+ ) |
||
395 | -+ | |||
100 | +43x |
-
+ attr(ans, "teal_bookmarkable") <- TRUE |
||
396 | -+ | |||
101 | +43x |
- #' @keywords internal+ ans |
||
397 | +102 |
- #' @noRd+ } |
||
398 | -4x | +
1 | +
- pasten <- function(...) paste0(..., "\n")+ setOldClass("teal_data_module") |
||
399 | +2 | ||
400 | +3 |
- #' Convert character list to human readable html with commas and "and"+ #' Evaluate code on `teal_data_module` |
|
401 | +4 |
- #' @noRd+ #' |
|
402 | +5 |
- paste_datanames_character <- function(x,+ #' @details |
|
403 | +6 |
- tags = list(span = shiny::tags$span, code = shiny::tags$code),+ #' `eval_code` evaluates given code in the environment of the `teal_data` object created by the `teal_data_module`. |
|
404 | +7 |
- tagList = shiny::tagList) { # nolint: object_name.- |
- |
405 | -! | -
- checkmate::assert_character(x)- |
- |
406 | -! | -
- do.call(- |
- |
407 | -! | -
- tagList,- |
- |
408 | -! | -
- lapply(seq_along(x), function(.ix) {- |
- |
409 | -! | -
- tagList(- |
- |
410 | -! | -
- tags$code(x[.ix]),+ #' The code is added to the `@code` slot of the `teal_data`. |
|
411 | -! | +||
8 | +
- if (.ix != length(x)) {+ #' |
||
412 | -! | +||
9 | +
- tags$span(if (.ix == length(x) - 1) " and " else ", ")+ #' @param object (`teal_data_module`) |
||
413 | +10 |
- }+ #' @inheritParams teal.code::eval_code |
|
414 | +11 |
- )+ #' |
|
415 | +12 |
- })+ #' @return |
|
416 | +13 |
- )+ #' `eval_code` returns a `teal_data_module` object with a delayed evaluation of `code` when the module is run. |
|
417 | +14 |
- }+ #' |
|
418 | +15 |
-
+ #' @examples |
|
419 | +16 |
- #' Build datanames error string for error message+ #' eval_code(tdm, "dataset1 <- subset(dataset1, Species == 'virginica')") |
|
420 | +17 |
#' |
|
421 | +18 |
- #' tags and tagList are overwritten in arguments allowing to create strings for+ #' @include teal_data_module.R |
|
422 | +19 |
- #' logging purposes+ #' @name eval_code |
|
423 | +20 |
- #' @noRd+ #' @rdname teal_data_module |
|
424 | +21 |
- build_datanames_error_message <- function(label = NULL,+ #' @aliases eval_code,teal_data_module,character-method |
|
425 | +22 |
- datanames,+ #' @aliases eval_code,teal_data_module,language-method |
|
426 | +23 |
- extra_datanames,+ #' @aliases eval_code,teal_data_module,expression-method |
|
427 | +24 |
- tags = list(span = shiny::tags$span, code = shiny::tags$code),+ #' |
|
428 | +25 |
- tagList = shiny::tagList) { # nolint: object_name.- |
- |
429 | -! | -
- tags$span(- |
- |
430 | -! | -
- tags$span(pluralize(extra_datanames, "Dataset")),+ #' @importFrom methods setMethod |
|
431 | -! | +||
26 | +
- paste_datanames_character(extra_datanames, tags, tagList),+ #' @importMethodsFrom teal.code eval_code |
||
432 | -! | +||
27 | +
- tags$span(+ #' |
||
433 | -! | +||
28 | +
- sprintf(+ setMethod("eval_code", signature = c("teal_data_module", "character"), function(object, code) { |
||
434 | -! | +||
29 | +9x |
- "%s missing%s",+ teal_data_module( |
|
435 | -! | +||
30 | +9x |
- pluralize(extra_datanames, "is", "are"),+ ui = function(id) { |
|
436 | -! | +||
31 | +1x |
- if (is.null(label)) "" else sprintf(" for tab '%s'", label)+ ns <- NS(id) |
|
437 | -+ | ||
32 | +1x |
- )+ object$ui(ns("mutate_inner")) |
|
438 | +33 |
- ),+ }, |
|
439 | -! | +||
34 | +9x |
- if (length(datanames) >= 1) {+ server = function(id) { |
|
440 | -! | +||
35 | +7x |
- tagList(+ moduleServer(id, function(input, output, session) { |
|
441 | -! | +||
36 | +7x |
- tags$span(pluralize(datanames, "Dataset")),+ data <- object$server("mutate_inner") |
|
442 | -! | +||
37 | +6x |
- tags$span("available in data:"),+ td <- eventReactive(data(), |
|
443 | -! | +||
38 | +
- tagList(+ { |
||
444 | -! | +||
39 | +6x |
- tags$span(+ if (inherits(data(), c("teal_data", "qenv.error"))) { |
|
445 | -! | +||
40 | +4x |
- paste_datanames_character(datanames, tags, tagList),+ eval_code(data(), code) |
|
446 | -! | +||
41 | +
- tags$span(".", .noWS = "outside"),+ } else { |
||
447 | -! | +||
42 | +2x |
- .noWS = c("outside")+ data() |
|
448 | +43 |
- )+ } |
|
449 | +44 |
- )+ }, |
|
450 | -+ | ||
45 | +6x |
- )+ ignoreNULL = FALSE |
|
451 | +46 |
- } else {+ ) |
|
452 | -! | +||
47 | +6x |
- tags$span("No datasets are available in data.")+ td |
|
453 | +48 | ++ |
+ })+ |
+
49 |
} |
||
454 | +50 |
) |
|
455 | +51 |
- }+ }) |
|
456 | +52 | ||
457 | +53 |
- #' Smart `rbind`+ setMethod("eval_code", signature = c("teal_data_module", "language"), function(object, code) { |
|
458 | -+ | ||
54 | +1x |
- #'+ eval_code(object, code = paste(lang2calls(code), collapse = "\n")) |
|
459 | +55 |
- #' Combine `data.frame` objects which have different columns+ }) |
|
460 | +56 |
- #'+ |
|
461 | +57 |
- #' @param ... (`data.frame`)+ setMethod("eval_code", signature = c("teal_data_module", "expression"), function(object, code) { |
|
462 | -+ | ||
58 | +2x |
- #' @keywords internal+ eval_code(object, code = paste(lang2calls(code), collapse = "\n")) |
|
463 | +59 |
- .smart_rbind <- function(...) {+ }) |
|
464 | -89x | +
1 | +
- dots <- list(...)+ #' Filter settings for `teal` applications |
||
465 | -89x | +||
2 | +
- checkmate::assert_list(dots, "data.frame", .var.name = "...")+ #' |
||
466 | -89x | +||
3 | +
- Reduce(+ #' Specify initial filter states and filtering settings for a `teal` app. |
||
467 | -89x | +||
4 | +
- x = dots,+ #' |
||
468 | -89x | +||
5 | +
- function(x, y) {+ #' Produces a `teal_slices` object. |
||
469 | -72x | +||
6 | +
- all_columns <- union(colnames(x), colnames(y))+ #' The `teal_slice` components will specify filter states that will be active when the app starts. |
||
470 | -72x | +||
7 | +
- x[setdiff(all_columns, colnames(x))] <- NA+ #' Attributes (created with the named arguments) will configure the way the app applies filters. |
||
471 | -72x | +||
8 | +
- y[setdiff(all_columns, colnames(y))] <- NA+ #' See argument descriptions for details. |
||
472 | -72x | +||
9 | +
- rbind(x, y)+ #' |
||
473 | +10 |
- }+ #' @inheritParams teal.slice::teal_slices |
|
474 | +11 |
- )+ #' |
|
475 | +12 |
- }+ #' @param module_specific (`logical(1)`) optional, |
|
476 | +13 |
-
+ #' - `FALSE` (default) when one filter panel applied to all modules. |
|
477 | +14 |
- #' Pluralize a word depending on the size of the input+ #' All filters will be shared by all modules. |
|
478 | +15 |
- #'+ #' - `TRUE` when filter panel module-specific. |
|
479 | +16 |
- #' @param x (`object`) to check length for plural.+ #' Modules can have different set of filters specified - see `mapping` argument. |
|
480 | +17 |
- #' @param singular (`character`) singular form of the word.+ #' @param mapping `r lifecycle::badge("experimental")` |
|
481 | +18 |
- #' @param plural (optional `character`) plural form of the word. If not given an "s"+ #' _This is a new feature. Do kindly share your opinions on |
|
482 | +19 |
- #' is added to the singular form.+ #' [`teal`'s GitHub repository](https://github.com/insightsengineering/teal/)._ |
|
483 | +20 |
#' |
|
484 | +21 |
- #' @return A `character` that correctly represents the size of the `x` argument.+ #' (named `list`) specifies which filters will be active in which modules on app start. |
|
485 | +22 |
- #' @keywords internal+ #' Elements should contain character vector of `teal_slice` `id`s (see [`teal.slice::teal_slice`]). |
|
486 | +23 |
- pluralize <- function(x, singular, plural = NULL) {+ #' Names of the list should correspond to `teal_module` `label` set in [module()] function. |
|
487 | -70x | +||
24 | +
- checkmate::assert_string(singular)+ #' - `id`s listed under `"global_filters` will be active in all modules. |
||
488 | -70x | +||
25 | +
- checkmate::assert_string(plural, null.ok = TRUE)+ #' - If missing, all filters will be applied to all modules. |
||
489 | -70x | +||
26 | +
- if (length(x) == 1L) { # Zero length object should use plural form.+ #' - If empty list, all filters will be available to all modules but will start inactive. |
||
490 | -42x | +||
27 | +
- singular+ #' - If `module_specific` is `FALSE`, only `global_filters` will be active on start. |
||
491 | +28 |
- } else {+ #' @param app_id (`character(1)`) |
|
492 | -28x | +||
29 | +
- if (is.null(plural)) {+ #' For internal use only, do not set manually. |
||
493 | -12x | +||
30 | +
- sprintf("%ss", singular)+ #' Added by `init` so that a `teal_slices` can be matched to the app in which it was used. |
||
494 | +31 |
- } else {+ #' Used for verifying snapshots uploaded from file. See `snapshot`. |
|
495 | -16x | +||
32 | +
- plural+ #' |
||
496 | +33 |
- }+ #' @param x (`list`) of lists to convert to `teal_slices` |
|
497 | +34 |
- }+ #' |
|
498 | +35 |
- }+ #' @return |
1 | +36 |
- #' Data Module for teal+ #' A `teal_slices` object. |
||
2 | +37 |
#' |
||
3 | +38 |
- #' This module manages the `data` argument for `srv_teal`. The `teal` framework uses [teal.data::teal_data()],+ #' @seealso [`teal.slice::teal_slices`], [`teal.slice::teal_slice`], [slices_store()] |
||
4 | +39 |
- #' which can be provided in various ways:+ #' |
||
5 | +40 |
- #' 1. Directly as a [teal.data::teal_data()] object. This will automatically convert it into a `reactive` `teal_data`.+ #' @examples |
||
6 | +41 |
- #' 2. As a `reactive` object that returns a [teal.data::teal_data()] object.+ #' filter <- teal_slices( |
||
7 | +42 |
- #'+ #' teal_slice(dataname = "iris", varname = "Species", id = "species"), |
||
8 | +43 |
- #' @details+ #' teal_slice(dataname = "iris", varname = "Sepal.Length", id = "sepal_length"), |
||
9 | +44 |
- #' ## Reactive `teal_data`:+ #' teal_slice( |
||
10 | +45 |
- #'+ #' dataname = "iris", id = "long_petals", title = "Long petals", expr = "Petal.Length > 5" |
||
11 | +46 |
- #' The data in the application can be reactively updated, prompting [srv_teal()] to rebuild the+ #' ), |
||
12 | +47 |
- #' content accordingly. There are two methods for creating interactive `teal_data`:+ #' teal_slice(dataname = "mtcars", varname = "mpg", id = "mtcars_mpg"), |
||
13 | +48 |
- #' 1. Using a `reactive` object provided from outside the `teal` application. In this scenario,+ #' mapping = list( |
||
14 | +49 |
- #' reactivity is controlled by an external module, and `srv_teal` responds to changes.+ #' module1 = c("species", "sepal_length"), |
||
15 | +50 |
- #' 2. Using [teal_data_module()], which is embedded within the `teal` application, allowing data to+ #' module2 = c("mtcars_mpg"), |
||
16 | +51 |
- #' be resubmitted by the user as needed.+ #' global_filters = "long_petals" |
||
17 | +52 |
- #'+ #' ) |
||
18 | +53 |
- #' Since the server of [teal_data_module()] must return a `reactive` `teal_data` object, both+ #' ) |
||
19 | +54 |
- #' methods (1 and 2) produce the same reactive behavior within a `teal` application. The distinction+ #' |
||
20 | +55 |
- #' lies in data control: the first method involves external control, while the second method+ #' app <- init( |
||
21 | +56 |
- #' involves control from a custom module within the app.+ #' data = teal_data(iris = iris, mtcars = mtcars), |
||
22 | +57 |
- #'+ #' modules = list( |
||
23 | +58 |
- #' For more details, see [`module_teal_data`].+ #' module("module1"), |
||
24 | +59 |
- #'+ #' module("module2")+ |
+ ||
60 | ++ |
+ #' ), |
||
25 | +61 |
- #' @inheritParams init+ #' filter = filter |
||
26 | +62 |
- #'+ #' ) |
||
27 | +63 |
- #' @param data (`teal_data`, `teal_data_module`, or `reactive` returning `teal_data`)+ #' |
||
28 | +64 |
- #' The data which application will depend on.+ #' if (interactive()) { |
||
29 | +65 |
- #'+ #' shinyApp(app$ui, app$server) |
||
30 | +66 |
- #' @return A `reactive` object that returns:+ #' } |
||
31 | +67 |
- #' Output of the `data`. If `data` fails then returned error is handled (after [tryCatch()]) so that+ #' |
||
32 | +68 |
- #' rest of the application can respond to this respectively.+ #' @export |
||
33 | +69 |
- #'+ teal_slices <- function(..., |
||
34 | +70 |
- #' @rdname module_init_data+ exclude_varnames = NULL, |
||
35 | +71 |
- #' @name module_init_data+ include_varnames = NULL, |
||
36 | +72 |
- #' @keywords internal+ count_type = NULL, |
||
37 | +73 |
- NULL+ allow_add = TRUE, |
||
38 | +74 |
-
+ module_specific = FALSE, |
||
39 | +75 |
- #' @rdname module_init_data+ mapping, |
||
40 | +76 |
- ui_init_data <- function(id) {+ app_id = NULL) { |
||
41 | -9x | +77 | +170x |
- ns <- shiny::NS(id)+ shiny::isolate({ |
42 | -9x | +78 | +170x |
- shiny::div(+ checkmate::assert_flag(allow_add) |
43 | -9x | +79 | +170x |
- id = ns("content"),+ checkmate::assert_flag(module_specific) |
44 | -9x | +80 | +53x |
- style = "display: inline-block; width: 100%;",+ if (!missing(mapping)) checkmate::assert_list(mapping, types = c("character", "NULL"), names = "named") |
45 | -9x | +81 | +167x |
- uiOutput(ns("data"))+ checkmate::assert_string(app_id, null.ok = TRUE) |
46 | +82 |
- )+ |
||
47 | -+ | |||
83 | +167x |
- }+ slices <- list(...) |
||
48 | -+ | |||
84 | +167x |
-
+ all_slice_id <- vapply(slices, `[[`, character(1L), "id") |
||
49 | +85 |
- #' @rdname module_init_data+ |
||
50 | -+ | |||
86 | +167x |
- srv_init_data <- function(id, data) {+ if (missing(mapping)) { |
||
51 | -88x | +87 | +117x |
- checkmate::assert_character(id, max.len = 1, any.missing = FALSE)+ mapping <- if (length(all_slice_id)) { |
52 | -88x | +88 | +26x |
- checkmate::assert_multi_class(data, c("teal_data", "teal_data_module", "reactive"))+ list(global_filters = all_slice_id) |
53 | +89 |
-
+ } else { |
||
54 | -88x | +90 | +91x |
- moduleServer(id, function(input, output, session) {+ list() |
55 | -88x | +|||
91 | +
- logger::log_debug("srv_data initializing.")+ } |
|||
56 | -88x | +|||
92 | +
- data_out <- if (inherits(data, "teal_data_module")) {+ } |
|||
57 | -10x | +|||
93 | +
- output$data <- renderUI(data$ui(id = session$ns("teal_data_module")))+ |
|||
58 | -10x | +94 | +167x |
- data$server("teal_data_module")+ if (!module_specific) { |
59 | -88x | +95 | +148x |
- } else if (inherits(data, "teal_data")) {+ mapping[setdiff(names(mapping), "global_filters")] <- NULL |
60 | -48x | +|||
96 | +
- reactiveVal(data)+ }+ |
+ |||
97 | ++ | + | ||
61 | -88x | +98 | +167x |
- } else if (test_reactive(data)) {+ failed_slice_id <- setdiff(unlist(mapping), all_slice_id) |
62 | -30x | +99 | +167x |
- data+ if (length(failed_slice_id)) { |
63 | -+ | |||
100 | +1x |
- }+ stop(sprintf( |
||
64 | -+ | |||
101 | +1x |
-
+ "Filters in mapping don't match any available filter.\n %s not in %s", |
||
65 | -87x | +102 | +1x |
- data_handled <- reactive({+ toString(failed_slice_id), |
66 | -80x | +103 | +1x |
- tryCatch(data_out(), error = function(e) e)+ toString(all_slice_id) |
67 | +104 |
- })+ )) |
||
68 | +105 |
-
+ } |
||
69 | +106 |
- # We want to exclude teal_data_module elements from bookmarking as they might have some secrets+ |
||
70 | -87x | +107 | +166x |
- observeEvent(data_handled(), {+ tss <- teal.slice::teal_slices( |
71 | -80x | +|||
108 | +
- if (inherits(data_handled(), "teal_data")) {+ ..., |
|||
72 | -75x | +109 | +166x |
- app_session <- .subset2(shiny::getDefaultReactiveDomain(), "parent")+ exclude_varnames = exclude_varnames, |
73 | -75x | +110 | +166x |
- setBookmarkExclude(+ include_varnames = include_varnames, |
74 | -75x | +111 | +166x |
- session$ns(+ count_type = count_type, |
75 | -75x | +112 | +166x |
- grep(+ allow_add = allow_add |
76 | -75x | +|||
113 | +
- pattern = "teal_data_module-",+ ) |
|||
77 | -75x | +114 | +166x |
- x = names(reactiveValuesToList(input)),+ attr(tss, "mapping") <- mapping |
78 | -75x | +115 | +166x |
- value = TRUE+ attr(tss, "module_specific") <- module_specific |
79 | -+ | |||
116 | +166x |
- )+ attr(tss, "app_id") <- app_id |
||
80 | -+ | |||
117 | +166x |
- ),+ class(tss) <- c("modules_teal_slices", class(tss)) |
||
81 | -75x | +118 | +166x |
- session = app_session+ tss |
82 | +119 |
- )+ }) |
||
83 | +120 |
- }+ } |
||
84 | +121 |
- })+ |
||
85 | +122 | |||
86 | -87x | -
- data_handled- |
- ||
87 | +123 |
- })+ #' @rdname teal_slices |
||
88 | +124 |
- }+ #' @export |
||
89 | +125 |
-
+ #' @keywords internal |
||
90 | +126 |
- #' Adds signature protection to the `datanames` in the data+ #' |
||
91 | +127 |
- #' @param data (`teal_data`)+ as.teal_slices <- function(x) { # nolint: object_name. |
||
92 | -+ | |||
128 | +15x |
- #' @return `teal_data` with additional code that has signature of the `datanames`+ checkmate::assert_list(x) |
||
93 | -+ | |||
129 | +15x |
- #' @keywords internal+ lapply(x, checkmate::assert_list, names = "named", .var.name = "list element") |
||
94 | +130 |
- .add_signature_to_data <- function(data) {+ |
||
95 | -75x | +131 | +15x |
- hashes <- .get_hashes_code(data)+ attrs <- attributes(unclass(x)) |
96 | -75x | +132 | +15x |
- tdata <- do.call(+ ans <- lapply(x, function(x) if (is.teal_slice(x)) x else as.teal_slice(x)) |
97 | -75x | +133 | +15x |
- teal.data::teal_data,+ do.call(teal_slices, c(ans, attrs)) |
98 | -75x | +|||
134 | +
- c(+ } |
|||
99 | -75x | +|||
135 | +
- list(code = trimws(c(teal.code::get_code(data), hashes), which = "right")),+ |
|||
100 | -75x | +|||
136 | +
- list(join_keys = teal.data::join_keys(data)),+ |
|||
101 | -75x | +|||
137 | +
- sapply(+ #' @rdname teal_slices |
|||
102 | -75x | +|||
138 | +
- names(data),+ #' @export |
|||
103 | -75x | +|||
139 | +
- teal.code::get_var,+ #' @keywords internal+ |
+ |||
140 | ++ |
+ #'+ |
+ ||
141 | ++ |
+ c.teal_slices <- function(...) { |
||
104 | -75x | +142 | +6x |
- object = data,+ x <- list(...) |
105 | -75x | +143 | +6x |
- simplify = FALSE+ checkmate::assert_true(all(vapply(x, is.teal_slices, logical(1L))), .var.name = "all arguments are teal_slices") |
106 | +144 |
- )+ |
||
107 | -+ | |||
145 | +6x |
- )+ all_attributes <- lapply(x, attributes) |
||
108 | -+ | |||
146 | +6x |
- )+ all_attributes <- coalesce_r(all_attributes)+ |
+ ||
147 | +6x | +
+ all_attributes <- all_attributes[names(all_attributes) != "class"] |
||
109 | +148 | |||
110 | -75x | +149 | +6x |
- tdata@verified <- data@verified+ do.call( |
111 | -75x | +150 | +6x |
- tdata+ teal_slices, |
112 | -+ | |||
151 | +6x |
- }+ c( |
||
113 | -+ | |||
152 | +6x |
-
+ unique(unlist(x, recursive = FALSE)), |
||
114 | -+ | |||
153 | +6x |
- #' Get code that tests the integrity of the reproducible data+ all_attributes |
||
115 | +154 |
- #'+ ) |
||
116 | +155 |
- #' @param data (`teal_data`) object holding the data+ ) |
||
117 | +156 |
- #' @param datanames (`character`) names of `datasets`+ } |
||
118 | +157 |
- #'+ |
||
119 | +158 |
- #' @return A character vector with the code lines.+ |
||
120 | +159 |
- #' @keywords internal+ #' Deep copy `teal_slices` |
||
121 | +160 |
#' |
||
122 | +161 |
- .get_hashes_code <- function(data, datanames = names(data)) {- |
- ||
123 | -75x | -
- vapply(- |
- ||
124 | -75x | -
- datanames,- |
- ||
125 | -75x | -
- function(dataname, datasets) {- |
- ||
126 | -133x | -
- x <- data[[dataname]]+ #' it's important to create a new copy of `teal_slices` when |
||
127 | +162 | - - | -||
128 | -133x | -
- code <- if (is.function(x) && !is.primitive(x)) {+ #' starting a new `shiny` session. Otherwise, object will be shared |
||
129 | -6x | +|||
163 | +
- x <- deparse1(x)+ #' by multiple users as it is created in global environment before |
|||
130 | -6x | +|||
164 | +
- bquote(rlang::hash(deparse1(.(as.name(dataname)))))+ #' `shiny` session starts. |
|||
131 | +165 |
- } else {+ #' @param filter (`teal_slices`) |
||
132 | -127x | +|||
166 | +
- bquote(rlang::hash(.(as.name(dataname))))+ #' @return `teal_slices` |
|||
133 | +167 |
- }+ #' @keywords internal |
||
134 | -133x | +|||
168 | +
- sprintf(+ deep_copy_filter <- function(filter) { |
|||
135 | -133x | +169 | +1x |
- "stopifnot(%s == %s) # @linksto %s",+ checkmate::assert_class(filter, "teal_slices") |
136 | -133x | +170 | +1x |
- deparse1(code),+ shiny::isolate({ |
137 | -133x | +171 | +1x |
- deparse1(rlang::hash(x)),+ filter_copy <- lapply(filter, function(slice) { |
138 | -133x | -
- dataname- |
- ||
139 | -+ | 172 | +2x |
- )+ teal.slice::as.teal_slice(as.list(slice)) |
140 | +173 |
- },+ }) |
||
141 | -75x | +174 | +1x |
- character(1L),+ attributes(filter_copy) <- attributes(filter) |
142 | -75x | +175 | +1x |
- USE.NAMES = TRUE+ filter_copy |
143 | +176 |
- )+ }) |
||
144 | +177 |
}@@ -21423,49 +21591,49 @@ teal coverage - 60.12% |
1 |
- # This is the main function from teal to be used by the end-users. Although it delegates+ #' Execute and validate `teal_data_module` |
||
2 |
- # directly to `module_teal_with_splash.R`, we keep it in a separate file because its documentation is quite large+ #' |
||
3 |
- # and it is very end-user oriented. It may also perform more argument checking with more informative+ #' This is a low level module to handle `teal_data_module` execution and validation. |
||
4 |
- # error messages.+ #' [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 |
- #' Create the server and UI function for the `shiny` app+ #' [teal.data::teal_data()] which is a standard data class in whole `teal` framework. |
||
8 |
- #' @description `r lifecycle::badge("stable")`+ #' @section data validation: |
||
10 |
- #' End-users: This is the most important function for you to start a+ #' Executed [teal_data_module()] is validated and output is validated for consistency. |
||
11 |
- #' `teal` app that is composed of `teal` modules.+ #' Output `data` is invalid if: |
||
12 |
- #'+ #' 1. [teal_data_module()] is invalid if server doesn't return `reactive`. **Immediately crashes an app!** |
||
13 |
- #' @param data (`teal_data` or `teal_data_module`)+ #' 2. `reactive` throws a `shiny.error` - happens when module creating [teal.data::teal_data()] fails. |
||
14 |
- #' For constructing the data object, refer to [teal.data::teal_data()] and [teal_data_module()].+ #' 3. `reactive` returns `qenv.error` - happens when [teal.data::teal_data()] evaluates a failing code. |
||
15 |
- #' If `datanames` are not set for the `teal_data` object, defaults from the `teal_data` environment will be used.+ #' 4. `reactive` object doesn't return [teal.data::teal_data()]. |
||
16 |
- #' @param modules (`list` or `teal_modules` or `teal_module`)+ #' 5. [teal.data::teal_data()] object lacks any `datanames` specified in the `modules` argument. |
||
17 |
- #' Nested list of `teal_modules` or `teal_module` objects or a single+ #' |
||
18 |
- #' `teal_modules` or `teal_module` object. These are the specific output modules which+ #' `teal` (observers in `srv_teal`) always waits to render an app until `reactive` `teal_data` is |
||
19 |
- #' will be displayed in the `teal` application. See [modules()] and [module()] for+ #' returned. If error 2-4 occurs, relevant error message is displayed to the app user. Once the issue is |
||
20 |
- #' more details.+ #' resolved, the app will continue to run. `teal` guarantees that errors in data don't crash the app |
||
21 |
- #' @param filter (`teal_slices`) Optionally,+ #' (except error 1). |
||
22 |
- #' specifies the initial filter using [teal_slices()].+ #' |
||
23 |
- #' @param title (`shiny.tag` or `character(1)`) Optionally,+ #' @param id (`character(1)`) Module id |
||
24 |
- #' the browser window title. Defaults to a title "teal app" with the icon of NEST.+ #' @param data (`reactive teal_data`) |
||
25 |
- #' Can be created using the `build_app_title()` or+ #' @param data_module (`teal_data_module`) |
||
26 |
- #' by passing a valid `shiny.tag` which is a head tag with title and link tag.+ #' @param modules (`teal_modules` or `teal_module`) For `datanames` validation purpose |
||
27 |
- #' @param header (`shiny.tag` or `character(1)`) Optionally,+ #' @param validate_shiny_silent_error (`logical`) If `TRUE`, then `shiny.silent.error` is validated and |
||
28 |
- #' the header of the app.+ #' @param is_transform_failed (`reactiveValues`) contains `logical` flags named after each transformator. |
||
29 |
- #' @param footer (`shiny.tag` or `character(1)`) Optionally,+ #' Help to determine if any previous transformator failed, so that following transformators can be disabled |
||
30 |
- #' the footer of the app.+ #' and display a generic failure message. |
||
31 |
- #' @param id (`character`) Optionally,+ #' |
||
32 |
- #' a string specifying the `shiny` module id in cases it is used as a `shiny` module+ #' @return `reactive` `teal_data` |
||
33 |
- #' rather than a standalone `shiny` app. This is a legacy feature.+ #' |
||
34 |
- #' @param landing_popup (`teal_module_landing`) Optionally,+ #' @rdname module_teal_data |
||
35 |
- #' a `landing_popup_module` to show up as soon as the teal app is initialized.+ #' @name module_teal_data |
||
36 |
- #'+ #' @keywords internal |
||
37 |
- #' @return Named list containing server and UI functions.+ NULL |
||
38 |
- #'+ |
||
39 |
- #' @export+ #' @rdname module_teal_data |
||
40 |
- #'+ #' @aliases ui_teal_data |
||
41 |
- #' @include modules.R+ #' @note |
||
42 |
- #'+ #' `ui_teal_data_module` was renamed from `ui_teal_data`. |
||
43 |
- #' @examples+ ui_teal_data_module <- function(id, data_module = function(id) NULL) { |
||
44 | -+ | ! |
- #' app <- init(+ checkmate::assert_string(id) |
45 | -+ | ! |
- #' data = within(+ checkmate::assert_function(data_module, args = "id") |
46 | -+ | ! |
- #' teal_data(),+ ns <- NS(id) |
47 |
- #' {+ |
||
48 | -+ | ! |
- #' new_iris <- transform(iris, id = seq_len(nrow(iris)))+ shiny::tagList( |
49 | -+ | ! |
- #' new_mtcars <- transform(mtcars, id = seq_len(nrow(mtcars)))+ tags$div(id = ns("wrapper"), data_module(id = ns("data"))), |
50 | -+ | ! |
- #' }+ ui_validate_reactive_teal_data(ns("validate")) |
51 |
- #' ),+ ) |
||
52 |
- #' modules = modules(+ } |
||
53 |
- #' module(+ |
||
54 |
- #' label = "data source",+ #' @rdname module_teal_data |
||
55 |
- #' server = function(input, output, session, data) {},+ #' @aliases srv_teal_data |
||
56 |
- #' ui = function(id, ...) tags$div(p("information about data source")),+ #' @note |
||
57 |
- #' datanames = "all"+ #' `srv_teal_data_module` was renamed from `srv_teal_data`. |
||
58 |
- #' ),+ srv_teal_data_module <- function(id, |
||
59 |
- #' example_module(label = "example teal module"),+ data_module = function(id) NULL, |
||
60 |
- #' module(+ modules = NULL, |
||
61 |
- #' "Iris Sepal.Length histogram",+ validate_shiny_silent_error = TRUE, |
||
62 |
- #' server = function(input, output, session, data) {+ is_transform_failed = reactiveValues()) { |
||
63 | -+ | ! |
- #' output$hist <- renderPlot(+ checkmate::assert_string(id) |
64 | -+ | ! |
- #' hist(data()[["new_iris"]]$Sepal.Length)+ checkmate::assert_function(data_module, args = "id") |
65 | -+ | ! |
- #' )+ checkmate::assert_multi_class(modules, c("teal_modules", "teal_module"), null.ok = TRUE) |
66 | -+ | ! |
- #' },+ checkmate::assert_class(is_transform_failed, "reactivevalues") |
67 |
- #' ui = function(id, ...) {+ |
||
68 | -+ | ! |
- #' ns <- NS(id)+ moduleServer(id, function(input, output, session) { |
69 | -+ | ! |
- #' plotOutput(ns("hist"))+ logger::log_debug("srv_teal_data_module initializing.") |
70 | -+ | ! |
- #' },+ is_transform_failed[[id]] <- FALSE |
71 | -+ | ! |
- #' datanames = "new_iris"+ module_out <- data_module(id = "data") |
72 | -+ | ! |
- #' )+ try_module_out <- reactive(tryCatch(module_out(), error = function(e) e)) |
73 | -+ | ! |
- #' ),+ observeEvent(try_module_out(), { |
74 | -+ | ! |
- #' filter = teal_slices(+ if (!inherits(try_module_out(), "teal_data")) { |
75 | -+ | ! |
- #' teal_slice(dataname = "new_iris", varname = "Species"),+ is_transform_failed[[id]] <- TRUE |
76 |
- #' teal_slice(dataname = "new_iris", varname = "Sepal.Length"),+ } else { |
||
77 | -+ | ! |
- #' teal_slice(dataname = "new_mtcars", varname = "cyl"),+ is_transform_failed[[id]] <- FALSE |
78 |
- #' exclude_varnames = list(new_iris = c("Sepal.Width", "Petal.Width")),+ } |
||
79 |
- #' module_specific = TRUE,+ }) |
||
80 |
- #' mapping = list(+ |
||
81 | -+ | ! |
- #' `example teal module` = "new_iris Species",+ is_previous_failed <- reactive({ |
82 | -+ | ! |
- #' `Iris Sepal.Length histogram` = "new_iris Species",+ idx_this <- which(names(is_transform_failed) == id) |
83 | -+ | ! |
- #' global_filters = "new_mtcars cyl"+ is_transform_failed_list <- reactiveValuesToList(is_transform_failed) |
84 | -+ | ! |
- #' )+ idx_failures <- which(unlist(is_transform_failed_list)) |
85 | -+ | ! |
- #' ),+ any(idx_failures < idx_this) |
86 |
- #' title = "App title",+ }) |
||
87 |
- #' header = tags$h1("Sample App"),+ |
||
88 | -+ | ! |
- #' footer = tags$p("Sample footer")+ observeEvent(is_previous_failed(), { |
89 | -+ | ! |
- #' )+ if (is_previous_failed()) { |
90 | -+ | ! |
- #' if (interactive()) {+ shinyjs::disable("wrapper") |
91 |
- #' shinyApp(app$ui, app$server)+ } else { |
||
92 | -+ | ! |
- #' }+ shinyjs::enable("wrapper") |
93 |
- #'+ } |
||
94 |
- init <- function(data,+ }) |
||
95 |
- modules,+ |
||
96 | -+ | ! |
- filter = teal_slices(),+ srv_validate_reactive_teal_data( |
97 | -+ | ! |
- title = build_app_title(),+ "validate", |
98 | -+ | ! |
- header = tags$p(),+ data = try_module_out, |
99 | -+ | ! |
- footer = tags$p(),+ modules = modules, |
100 | -+ | ! |
- id = character(0),+ validate_shiny_silent_error = validate_shiny_silent_error, |
101 | -+ | ! |
- landing_popup = NULL) {+ hide_validation_error = is_previous_failed |
102 | -14x | +
- logger::log_debug("init initializing teal app with: data ('{ class(data) }').")+ ) |
|
103 |
-
+ }) |
||
104 |
- # argument checking (independent)+ } |
||
105 |
- ## `data`+ |
||
106 | -14x | +
- checkmate::assert_multi_class(data, c("teal_data", "teal_data_module"))+ #' @rdname module_teal_data |
|
107 | -14x | +
- checkmate::assert_class(landing_popup, "teal_module_landing", null.ok = TRUE)+ ui_validate_reactive_teal_data <- function(id) { |
|
108 | -+ | ! |
-
+ ns <- NS(id) |
109 | -+ | ! |
- ## `modules`+ tagList( |
110 | -14x | +! |
- checkmate::assert(+ div( |
111 | -14x | +! |
- .var.name = "modules",+ id = ns("validate_messages"), |
112 | -14x | +! |
- checkmate::check_multi_class(modules, c("teal_modules", "teal_module")),+ class = "teal_validated", |
113 | -14x | +! |
- checkmate::check_list(modules, min.len = 1, any.missing = FALSE, types = c("teal_module", "teal_modules"))+ ui_validate_error(ns("silent_error")), |
114 | -+ | ! |
- )+ ui_check_class_teal_data(ns("class_teal_data")), |
115 | -14x | +! |
- if (inherits(modules, "teal_module")) {+ ui_check_module_datanames(ns("shiny_warnings")) |
116 | -1x | +
- modules <- list(modules)+ ), |
|
117 | -+ | ! |
- }+ div( |
118 | -14x | +! |
- if (checkmate::test_list(modules, min.len = 1, any.missing = FALSE, types = c("teal_module", "teal_modules"))) {+ class = "teal_validated", |
119 | -8x | +! |
- modules <- do.call(teal::modules, modules)+ uiOutput(ns("previous_failed")) |
120 |
- }+ ) |
||
121 |
-
+ ) |
||
122 |
- ## `filter`+ } |
||
123 | -14x | +
- checkmate::assert_class(filter, "teal_slices")+ |
|
124 |
-
+ #' @rdname module_teal_data |
||
125 |
- ## all other arguments+ srv_validate_reactive_teal_data <- function(id, # nolint: object_length |
||
126 | -13x | +
- checkmate::assert(+ data, |
|
127 | -13x | +
- .var.name = "title",+ modules = NULL, |
|
128 | -13x | +
- checkmate::check_string(title),+ validate_shiny_silent_error = FALSE, |
|
129 | -13x | +
- checkmate::check_multi_class(title, c("shiny.tag", "shiny.tag.list", "html"))+ hide_validation_error = reactive(FALSE)) { |
|
130 | -+ | ! |
- )+ checkmate::assert_string(id) |
131 | -13x | +! |
- checkmate::assert(+ checkmate::assert_multi_class(modules, c("teal_modules", "teal_module"), null.ok = TRUE) |
132 | -13x | +! |
- .var.name = "header",+ checkmate::assert_flag(validate_shiny_silent_error) |
133 | -13x | +
- checkmate::check_string(header),+ |
|
134 | -13x | +! |
- checkmate::check_multi_class(header, c("shiny.tag", "shiny.tag.list", "html"))+ moduleServer(id, function(input, output, session) { |
135 |
- )+ # there is an empty reactive cycle on `init` and `data` has `shiny.silent.error` class |
||
136 | -13x | +! |
- checkmate::assert(+ srv_validate_error("silent_error", data, validate_shiny_silent_error) |
137 | -13x | +! |
- .var.name = "footer",+ srv_check_class_teal_data("class_teal_data", data) |
138 | -13x | +! |
- checkmate::check_string(footer),+ srv_check_module_datanames("shiny_warnings", data, modules) |
139 | -13x | +! |
- checkmate::check_multi_class(footer, c("shiny.tag", "shiny.tag.list", "html"))+ output$previous_failed <- renderUI({ |
140 | -+ | ! |
- )+ if (hide_validation_error()) { |
141 | -13x | +! |
- checkmate::assert_character(id, max.len = 1, any.missing = FALSE)+ shinyjs::hide("validate_messages") |
142 | -+ | ! |
-
+ tags$div("One of previous transformators failed. Please check its inputs.", class = "teal-output-warning") |
143 |
- # log+ } else { |
||
144 | -13x | +! |
- teal.logger::log_system_info()+ shinyjs::show("validate_messages") |
145 | -+ | ! |
-
+ NULL |
146 |
- # argument transformations+ } |
||
147 |
- ## `modules` - landing module+ }) |
||
148 | -13x | +
- landing <- extract_module(modules, "teal_module_landing")+ |
|
149 | -13x | +! |
- if (length(landing) == 1L) {+ .trigger_on_success(data) |
150 | -! | +
- landing_popup <- landing[[1L]]+ }) |
|
151 | -! | +
- modules <- drop_module(modules, "teal_module_landing")+ } |
|
152 | -! | +
- lifecycle::deprecate_soft(+ |
|
153 | -! | +
- when = "0.15.3",+ #' @keywords internal |
|
154 | -! | +
- what = "landing_popup_module()",+ ui_validate_error <- function(id) { |
|
155 | -! | +116x |
- details = paste(+ ns <- NS(id) |
156 | -! | +116x |
- "Pass `landing_popup_module` to the `landing_popup` argument of the `init` ",+ uiOutput(ns("message")) |
157 | -! | +
- "instead of wrapping it into `modules()` and passing to the `modules` argument"+ } |
|
158 |
- )+ |
||
159 |
- )+ #' @keywords internal |
||
160 | -13x | +
- } else if (length(landing) > 1L) {+ srv_validate_error <- function(id, data, validate_shiny_silent_error) { |
|
161 | -! | +113x |
- stop("Only one `landing_popup_module` can be used.")+ checkmate::assert_string(id) |
162 | -+ | 113x |
- }+ checkmate::assert_flag(validate_shiny_silent_error) |
163 | -+ | 113x |
-
+ moduleServer(id, function(input, output, session) { |
164 | -+ | 113x |
- ## `filter` - set app_id attribute unless present (when restoring bookmark)+ output$message <- renderUI({ |
165 | -13x | +112x |
- if (is.null(attr(filter, "app_id", exact = TRUE))) attr(filter, "app_id") <- create_app_id(data, modules)+ is_shiny_silent_error <- inherits(data(), "shiny.silent.error") && identical(data()$message, "") |
166 | -+ | 112x |
-
+ if (inherits(data(), "qenv.error")) { |
167 | -+ | 2x |
- ## `filter` - convert teal.slice::teal_slices to teal::teal_slices+ validate( |
168 | -13x | +2x |
- filter <- as.teal_slices(as.list(filter))+ need( |
169 | -+ | 2x |
-
+ FALSE, |
170 | -+ | 2x |
- # argument checking (interdependent)+ paste( |
171 | -+ | 2x |
- ## `filter` - `modules`+ "Error when executing the `data` module:", |
172 | -13x | +2x |
- if (isTRUE(attr(filter, "module_specific"))) {+ cli::ansi_strip(paste(data()$message, collapse = "\n")), |
173 | -! | +2x |
- module_names <- unlist(c(module_labels(modules), "global_filters"))+ "\nCheck your inputs or contact app developer if error persists.", |
174 | -! | +2x |
- failed_mod_names <- setdiff(names(attr(filter, "mapping")), module_names)+ collapse = "\n" |
175 | -! | +
- if (length(failed_mod_names)) {+ ) |
|
176 | -! | +
- stop(+ ) |
|
177 | -! | +
- sprintf(+ ) |
|
178 | -! | +110x |
- "Some module names in the mapping arguments don't match module labels.\n %s not in %s",+ } else if (inherits(data(), "error")) { |
179 | -! | +11x |
- toString(failed_mod_names),+ if (is_shiny_silent_error && !validate_shiny_silent_error) { |
180 | -! | +4x |
- toString(unique(module_names))+ return(NULL) |
181 |
- )+ } |
||
182 | -+ | 7x |
- )+ validate( |
183 | -+ | 7x |
- }+ need( |
184 | -+ | 7x |
-
+ FALSE, |
185 | -! | +7x |
- if (anyDuplicated(module_names)) {+ sprintf( |
186 | -+ | 7x |
- # In teal we are able to set nested modules with duplicated label.+ "Shiny error when executing the `data` module.\n%s\n%s", |
187 | -+ | 7x |
- # Because mapping argument bases on the relationship between module-label and filter-id,+ data()$message, |
188 | -+ | 7x |
- # it is possible that module-label in mapping might refer to multiple teal_module (identified by the same label)+ "Check your inputs or contact app developer if error persists." |
189 | -! | +
- stop(+ ) |
|
190 | -! | +
- sprintf(+ ) |
|
191 | -! | +
- "Module labels should be unique when teal_slices(mapping = TRUE). Duplicated labels:\n%s ",+ ) |
|
192 | -! | +
- toString(module_names[duplicated(module_names)])+ } |
|
193 |
- )+ }) |
||
194 |
- )+ }) |
||
195 |
- }+ } |
||
196 |
- }+ |
||
198 |
- ## `data` - `modules`+ #' @keywords internal |
||
199 | -13x | +
- if (inherits(data, "teal_data")) {+ ui_check_class_teal_data <- function(id) { |
|
200 | -12x | +116x |
- if (length(data) == 0) {+ ns <- NS(id) |
201 | -1x | +116x |
- stop("The environment of `data` is empty.")+ uiOutput(ns("message")) |
202 |
- }+ } |
||
204 | -11x | +
- is_modules_ok <- check_modules_datanames(modules, names(data))+ #' @keywords internal |
|
205 | -11x | +
- if (!isTRUE(is_modules_ok) && length(unlist(extract_transformators(modules))) == 0) {+ srv_check_class_teal_data <- function(id, data) { |
|
206 | -4x | +113x |
- warning(is_modules_ok, call. = FALSE)+ checkmate::assert_string(id) |
207 | -+ | 113x |
- }+ moduleServer(id, function(input, output, session) { |
208 | -+ | 113x |
-
+ output$message <- renderUI({ |
209 | -11x | +112x |
- is_filter_ok <- check_filter_datanames(filter, names(data))+ validate( |
210 | -11x | +112x |
- if (!isTRUE(is_filter_ok)) {+ need( |
211 | -1x | +112x |
- warning(is_filter_ok)+ inherits(data(), c("teal_data", "error")), |
212 | -+ | 112x |
- # we allow app to continue if applied filters are outside+ "Did not receive `teal_data` object. Cannot proceed further." |
213 |
- # of possible data range+ ) |
||
214 |
- }+ ) |
||
215 |
- }+ }) |
||
216 |
-
+ }) |
||
217 | -12x | +
- reporter <- teal.reporter::Reporter$new()$set_id(attr(filter, "app_id"))+ } |
|
218 | -12x | +
- if (is_arg_used(modules, "reporter") && length(extract_module(modules, "teal_module_previewer")) == 0) {+ |
|
219 | -! | +
- modules <- append_module(+ #' @keywords internal |
|
220 | -! | +
- modules,+ ui_check_module_datanames <- function(id) { |
|
221 | -! | +116x |
- reporter_previewer_module(server_args = list(previewer_buttons = c("download", "reset")))+ ns <- NS(id) |
222 | -+ | 116x |
- )+ uiOutput(NS(id, "message")) |
223 |
- }+ } |
||
225 | -12x | +
- ns <- NS(id)+ #' @keywords internal |
|
226 |
- # Note: UI must be a function to support bookmarking.+ srv_check_module_datanames <- function(id, data, modules) { |
||
227 | -12x | +193x |
- res <- list(+ checkmate::assert_string(id) |
228 | -12x | +193x |
- ui = function(request) {+ moduleServer(id, function(input, output, session) { |
229 | -! | +193x |
- ui_teal(+ output$message <- renderUI({ |
230 | -! | +196x |
- id = ns("teal"),+ if (inherits(data(), "teal_data")) { |
231 | -! | +179x |
- modules = modules,+ is_modules_ok <- check_modules_datanames_html( |
232 | -! | +179x |
- title = title,+ modules = modules, datanames = names(data()) |
233 | -! | +
- header = header,+ ) |
|
234 | -! | +179x |
- footer = footer+ if (!isTRUE(is_modules_ok)) { |
235 | -+ | 19x |
- )+ tags$div(is_modules_ok, class = "teal-output-warning") |
236 |
- },+ } |
||
237 | -12x | +
- server = function(input, output, session) {+ } |
|
238 | -! | +
- if (!is.null(landing_popup)) {+ }) |
|
239 | -! | +
- do.call(landing_popup$server, c(list(id = "landing_module_shiny_id"), landing_popup$server_args))+ }) |
|
240 |
- }+ } |
||
241 | -! | +
- srv_teal(id = ns("teal"), data = data, modules = modules, filter = deep_copy_filter(filter))+ |
|
242 |
- }+ .trigger_on_success <- function(data) { |
||
243 | -+ | 113x |
- )+ out <- reactiveVal(NULL) |
244 | -+ | 113x |
-
+ observeEvent(data(), { |
245 | -12x | +112x |
- logger::log_debug("init teal app has been initialized.")+ if (inherits(data(), "teal_data")) { |
246 | -+ | 97x |
-
+ if (!identical(data(), out())) { |
247 | -12x | +97x |
- res+ out(data()) |
248 | + |
+ }+ |
+ |
249 | ++ |
+ }+ |
+ |
250 | ++ |
+ })+ |
+ |
251 | ++ | + + | +|
252 | +113x | +
+ out+ |
+ |
253 | +
} |
@@ -23165,35 +23368,35 @@
1 |
- setOldClass("teal_module")+ #' App state management. |
|||
2 |
- setOldClass("teal_modules")+ #' |
|||
3 |
-
+ #' @description |
|||
4 |
- #' Create `teal_module` and `teal_modules` objects+ #' `r lifecycle::badge("experimental")` |
|||
6 |
- #' @description+ #' Capture and restore the global (app) input state. |
|||
7 |
- #' `r lifecycle::badge("stable")`+ #' |
|||
8 |
- #' Create a nested tab structure to embed modules in a `teal` application.+ #' @details |
|||
9 |
- #'+ #' This module introduces bookmarks into `teal` apps: the `shiny` bookmarking mechanism becomes enabled |
|||
10 |
- #' @details+ #' and server-side bookmarks can be created. |
|||
11 |
- #' `module()` creates an instance of a `teal_module` that can be placed in a `teal` application.+ #' |
|||
12 |
- #' `modules()` shapes the structure of a the application by organizing `teal_module` within the navigation panel.+ #' The bookmark manager presents a button with the bookmark icon and is placed in the tab-bar. |
|||
13 |
- #' It wraps `teal_module` and `teal_modules` objects in a `teal_modules` object,+ #' When clicked, the button creates a bookmark and opens a modal which displays the bookmark URL. |
|||
14 |
- #' which results in a nested structure corresponding to the nested tabs in the final application.+ #' |
|||
15 |
- #'+ #' `teal` does not guarantee that all modules (`teal_module` objects) are bookmarkable. |
|||
16 |
- #' Note that for `modules()` `label` comes after `...`, so it must be passed as a named argument,+ #' Those that are, have a `teal_bookmarkable` attribute set to `TRUE`. If any modules are not bookmarkable, |
|||
17 |
- #' otherwise it will be captured by `...`.+ #' 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 |
|||
19 |
- #' The labels `"global_filters"` and `"Report previewer"` are reserved+ #' should set the `teal_bookmarkable` attribute to `TRUE`. |
|||
20 |
- #' because they are used by the `mapping` argument of [teal_slices()]+ #' |
|||
21 |
- #' and the report previewer module [reporter_previewer_module()], respectively.+ #' @section Server logic: |
|||
22 |
- #'+ #' A bookmark is a URL that contains the app address with a `/?_state_id_=<bookmark_dir>` suffix. |
|||
23 |
- #' # Restricting datasets used by `teal_module`:+ #' `<bookmark_dir>` is a directory created on the server, where the state of the application is saved. |
|||
24 |
- #' The `datanames` argument controls which datasets are used by the module’s server. These datasets,+ #' Accessing the bookmark URL opens a new session of the app that starts in the previously saved state. |
|||
25 |
- #' passed via server's `data` argument, are the only ones shown in the module's tab.+ #' |
|||
26 |
- #'+ #' @section Note: |
|||
27 |
- #' When `datanames` is set to `"all"`, all datasets in the data object are treated as relevant.+ #' To enable bookmarking use either: |
|||
28 |
- #' However, this may include unnecessary datasets, such as:+ #' - `shiny` app by using `shinyApp(..., enableBookmarking = "server")` (not supported in `shinytest2`) |
|||
29 |
- #' - Proxy variables for column modifications+ #' - set `options(shiny.bookmarkStore = "server")` before running the app |
|||
30 |
- #' - Temporary datasets used to create final versions+ #' |
|||
31 |
- #' - Connection objects+ #' |
|||
32 |
- #'+ #' @inheritParams init |
|||
33 |
- #' To exclude irrelevant datasets, use the [set_datanames()] function to change `datanames` from+ #' |
|||
34 |
- #' `"all"` to specific names. Trying to modify non-`"all"` values with [set_datanames()] will result+ #' @return Invisible `NULL`. |
|||
35 |
- #' in a warning. Datasets with names starting with . are ignored globally unless explicitly listed+ #' |
|||
36 |
- #' in `datanames`.+ #' @aliases bookmark bookmark_manager bookmark_manager_module |
|||
38 |
- #' # `datanames` with `transformators`+ #' @name module_bookmark_manager |
|||
39 |
- #' When transformators are specified, their `datanames` are added to the module’s `datanames`, which+ #' @rdname module_bookmark_manager |
|||
40 |
- #' changes the behavior as follows:+ #' |
|||
41 |
- #' - If `module(datanames)` is `NULL` and the `transformators` have defined `datanames`, the sidebar+ #' @keywords internal |
|||
42 |
- #' will appear showing the `transformators`' datasets, instead of being hidden.+ #' |
|||
43 |
- #' - If `module(datanames)` is set to specific values and any `transformator` has `datanames = "all"`,+ NULL |
|||
44 |
- #' the module may receive extra datasets that could be unnecessary+ |
|||
45 |
- #'+ #' @rdname module_bookmark_manager |
|||
46 |
- #' @param label (`character(1)`) Label shown in the navigation item for the module or module group.+ ui_bookmark_panel <- function(id, modules) { |
|||
47 | -+ | ! |
- #' For `modules()` defaults to `"root"`. See `Details`.+ ns <- NS(id) |
|
48 |
- #' @param server (`function`) `shiny` module with following arguments:+ |
|||
49 | -+ | ! |
- #' - `id` - `teal` will set proper `shiny` namespace for this module (see [shiny::moduleServer()]).+ bookmark_option <- get_bookmarking_option() |
|
50 | -+ | ! |
- #' - `input`, `output`, `session` - (optional; not recommended) When provided, then [shiny::callModule()]+ is_unbookmarkable <- need_bookmarking(modules) |
|
51 | -+ | ! |
- #' will be used to call a module. From `shiny` 1.5.0, the recommended way is to use+ shinyOptions(bookmarkStore = bookmark_option) |
|
52 |
- #' [shiny::moduleServer()] instead which doesn't require these arguments.+ |
|||
53 |
- #' - `data` (optional) When provided, the module will be called with `teal_data` object (i.e. a list of+ # Render bookmark warnings count |
|||
54 | -+ | ! |
- #' reactive (filtered) data specified in the `filters` argument) as the value of this argument.+ if (!all(is_unbookmarkable) && identical(bookmark_option, "server")) { |
|
55 | -+ | ! |
- #' - `datasets` (optional) When provided, the module will be called with `FilteredData` object as the+ tags$button( |
|
56 | -+ | ! |
- #' value of this argument. (See [`teal.slice::FilteredData`]).+ id = ns("do_bookmark"), |
|
57 | -+ | ! |
- #' - `reporter` (optional) When provided, the module will be called with `Reporter` object as the value+ class = "btn action-button wunder_bar_button bookmark_manager_button", |
|
58 | -+ | ! |
- #' of this argument. (See [`teal.reporter::Reporter`]).+ title = "Add bookmark", |
|
59 | -+ | ! |
- #' - `filter_panel_api` (optional) When provided, the module will be called with `FilterPanelAPI` object+ tags$span( |
|
60 | -+ | ! |
- #' as the value of this argument. (See [`teal.slice::FilterPanelAPI`]).+ suppressMessages(icon("fas fa-bookmark")), |
|
61 | -+ | ! |
- #' - `...` (optional) When provided, `server_args` elements will be passed to the module named argument+ if (any(is_unbookmarkable)) { |
|
62 | -+ | ! |
- #' or to the `...`.+ tags$span( |
|
63 | -+ | ! |
- #' @param ui (`function`) `shiny` UI module function with following arguments:+ sum(is_unbookmarkable), |
|
64 | -+ | ! |
- #' - `id` - `teal` will set proper `shiny` namespace for this module.+ class = "badge-warning badge-count text-white bg-danger" |
|
65 |
- #' - `...` (optional) When provided, `ui_args` elements will be passed to the module named argument+ ) |
|||
66 |
- #' or to the `...`.+ } |
|||
67 |
- #' @param filters (`character`) Deprecated. Use `datanames` instead.+ ) |
|||
68 |
- #' @param datanames (`character`) Names of the datasets relevant to the item.+ ) |
|||
69 |
- #' There are 2 reserved values that have specific behaviors:+ } |
|||
70 |
- #' - The keyword `"all"` includes all datasets available in the data passed to the teal application.+ } |
|||
71 |
- #' - `NULL` hides the sidebar panel completely.+ |
|||
72 |
- #' - If `transformators` are specified, their `datanames` are automatically added to this `datanames`+ #' @rdname module_bookmark_manager |
|||
73 |
- #' argument.+ srv_bookmark_panel <- function(id, modules) { |
|||
74 | -+ | 87x |
- #' @param server_args (named `list`) with additional arguments passed on to the server function.+ checkmate::assert_character(id) |
|
75 | -+ | 87x |
- #' @param ui_args (named `list`) with additional arguments passed on to the UI function.+ checkmate::assert_class(modules, "teal_modules") |
|
76 | -+ | 87x |
- #' @param x (`teal_module` or `teal_modules`) Object to format/print.+ moduleServer(id, function(input, output, session) { |
|
77 | -+ | 87x |
- #' @param transformators (`list` of `teal_transform_module`) that will be applied to transformator module's data input.+ logger::log_debug("bookmark_manager_srv initializing") |
|
78 | -+ | 87x |
- #'+ ns <- session$ns |
|
79 | -+ | 87x |
- #'+ bookmark_option <- get_bookmarking_option() |
|
80 | -+ | 87x |
- #' @param ...+ is_unbookmarkable <- need_bookmarking(modules) |
|
81 |
- #' - For `modules()`: (`teal_module` or `teal_modules`) Objects to wrap into a tab.+ |
|||
82 |
- #' - For `format()` and `print()`: Arguments passed to other methods.+ # Set up bookmarking callbacks ---- |
|||
83 |
- #'+ # Register bookmark exclusions: do_bookmark button to avoid re-bookmarking |
|||
84 | -+ | 87x |
- #' @return+ setBookmarkExclude(c("do_bookmark")) |
|
85 |
- #' `module()` returns an object of class `teal_module`.+ # This bookmark can only be used on the app session. |
|||
86 | -+ | 87x |
- #'+ app_session <- .subset2(session, "parent") |
|
87 | -+ | 87x |
- #' `modules()` returns a `teal_modules` object which contains following fields:+ app_session$onBookmarked(function(url) { |
|
88 | -+ | ! |
- #' - `label`: taken from the `label` argument.+ logger::log_debug("bookmark_manager_srv@onBookmarked: bookmark button clicked, registering bookmark") |
|
89 | -+ | ! |
- #' - `children`: a list containing objects passed in `...`. List elements are named after+ modal_content <- if (bookmark_option != "server") { |
|
90 | -+ | ! |
- #' their `label` attribute converted to a valid `shiny` id.+ msg <- sprintf( |
|
91 | -+ | ! |
- #'+ "Bookmarking has been set to \"%s\".\n%s\n%s", |
|
92 | -+ | ! |
- #' @name teal_modules+ bookmark_option, |
|
93 | -+ | ! |
- #' @aliases teal_module+ "Only server-side bookmarking is supported.", |
|
94 | -+ | ! |
- #'+ "Please contact your app developer." |
|
95 |
- #' @examples+ ) |
|||
96 | -+ | ! |
- #' library(shiny)+ tags$div( |
|
97 | -+ | ! |
- #'+ tags$p(msg, class = "text-warning") |
|
98 |
- #' module_1 <- module(+ ) |
|||
99 |
- #' label = "a module",+ } else { |
|||
100 | -+ | ! |
- #' server = function(id, data) {+ tags$div( |
|
101 | -+ | ! |
- #' moduleServer(+ tags$span( |
|
102 | -+ | ! |
- #' id,+ tags$pre(url) |
|
103 |
- #' module = function(input, output, session) {+ ), |
|||
104 | -+ | ! |
- #' output$data <- renderDataTable(data()[["iris"]])+ if (any(is_unbookmarkable)) { |
|
105 | -+ | ! |
- #' }+ bkmb_summary <- rapply2( |
|
106 | -+ | ! |
- #' )+ modules_bookmarkable(modules), |
|
107 | -+ | ! |
- #' },+ function(x) { |
|
108 | -+ | ! |
- #' ui = function(id) {+ if (isTRUE(x)) { |
|
109 | -+ | ! |
- #' ns <- NS(id)+ "\u2705" # check mark |
|
110 | -+ | ! |
- #' tagList(dataTableOutput(ns("data")))+ } else if (isFALSE(x)) { |
|
111 | -+ | ! |
- #' },+ "\u274C" # cross mark |
|
112 |
- #' datanames = "all"+ } else { |
|||
113 | -+ | ! |
- #' )+ "\u2753" # question mark |
|
114 |
- #'+ } |
|||
115 |
- #' module_2 <- module(+ } |
|||
116 |
- #' label = "another module",+ ) |
|||
117 | -+ | ! |
- #' server = function(id) {+ tags$div( |
|
118 | -+ | ! |
- #' moduleServer(+ tags$p( |
|
119 | -+ | ! |
- #' id,+ icon("fas fa-exclamation-triangle"), |
|
120 | -+ | ! |
- #' module = function(input, output, session) {+ "Some modules will not be restored when using this bookmark.", |
|
121 | -+ | ! |
- #' output$text <- renderText("Another Module")+ tags$br(), |
|
122 | -+ | ! |
- #' }+ "Check the list below to see which modules are not bookmarkable.", |
|
123 | -+ | ! |
- #' )+ class = "text-warning" |
|
124 |
- #' },+ ), |
|||
125 | -+ | ! |
- #' ui = function(id) {+ tags$pre(yaml::as.yaml(bkmb_summary)) |
|
126 |
- #' ns <- NS(id)+ ) |
|||
127 |
- #' tagList(textOutput(ns("text")))+ } |
|||
128 |
- #' },+ ) |
|||
129 |
- #' datanames = NULL+ } |
|||
130 |
- #' )+ |
|||
131 | -+ | ! |
- #'+ showModal( |
|
132 | -+ | ! |
- #' modules <- modules(+ modalDialog( |
|
133 | -+ | ! |
- #' label = "modules",+ id = ns("bookmark_modal"), |
|
134 | -+ | ! |
- #' modules(+ title = "Bookmarked teal app url", |
|
135 | -+ | ! |
- #' label = "nested modules",+ modal_content, |
|
136 | -+ | ! |
- #' module_1+ easyClose = TRUE |
|
137 |
- #' ),+ ) |
|||
138 |
- #' module_2+ ) |
|||
139 |
- #' )+ }) |
|||
140 |
- #'+ |
|||
141 |
- #' app <- init(+ # manually trigger bookmarking because of the problems reported on windows with bookmarkButton in teal |
|||
142 | -+ | 87x |
- #' data = teal_data(iris = iris),+ observeEvent(input$do_bookmark, { |
|
143 | -+ | ! |
- #' modules = modules+ logger::log_debug("bookmark_manager_srv@1 do_bookmark module clicked.") |
|
144 | -+ | ! |
- #' )+ session$doBookmark() |
|
145 |
- #'+ }) |
|||
146 |
- #' if (interactive()) {+ |
|||
147 | -+ | 87x |
- #' shinyApp(app$ui, app$server)+ invisible(NULL) |
|
148 |
- #' }+ }) |
|||
149 |
- #' @rdname teal_modules+ } |
|||
150 |
- #' @export+ |
|||
151 |
- #'+ |
|||
152 |
- module <- function(label = "module",+ #' @rdname module_bookmark_manager |
|||
153 |
- server = function(id, data, ...) moduleServer(id, function(input, output, session) NULL),+ get_bookmarking_option <- function() { |
|||
154 | -+ | 87x |
- ui = function(id, ...) tags$p(paste0("This module has no UI (id: ", id, " )")),+ bookmark_option <- getShinyOption("bookmarkStore") |
|
155 | -+ | 87x |
- filters,+ if (is.null(bookmark_option) && identical(getOption("shiny.bookmarkStore"), "server")) { |
|
156 | -+ | ! |
- datanames = "all",+ bookmark_option <- getOption("shiny.bookmarkStore") |
|
157 |
- server_args = NULL,+ } |
|||
158 | -+ | 87x |
- ui_args = NULL,+ bookmark_option |
|
159 |
- transformators = list()) {+ } |
|||
160 |
- # argument checking (independent)+ |
|||
161 |
- ## `label`+ #' @rdname module_bookmark_manager |
|||
162 | -220x | +
- checkmate::assert_string(label)+ need_bookmarking <- function(modules) { |
||
163 | -217x | +87x |
- if (label == "global_filters") {+ unlist(rapply2( |
|
164 | -1x | +87x |
- stop(+ modules_bookmarkable(modules), |
|
165 | -1x | +87x |
- sprintf("module(label = \"%s\", ...\n ", label),+ Negate(isTRUE) |
|
166 | -1x | +
- "Label 'global_filters' is reserved in teal. Please change to something else.",+ )) |
||
167 | -1x | +
- call. = FALSE+ } |
||
168 |
- )+ |
|||
169 |
- }+ |
|||
170 | -216x | +
- if (label == "Report previewer") {+ # utilities ---- |
||
171 | -! | +
- stop(+ |
||
172 | -! | +
- sprintf("module(label = \"%s\", ...\n ", label),+ #' Restore value from bookmark. |
||
173 | -! | +
- "Label 'Report previewer' is reserved in teal. Please change to something else.",+ #' |
||
174 | -! | +
- call. = FALSE+ #' Get value from bookmark or return default. |
||
175 |
- )+ #' |
|||
176 |
- }+ #' Bookmarks can store not only inputs but also arbitrary values. |
|||
177 |
-
+ #' These values are stored by `onBookmark` callbacks and restored by `onBookmarked` callbacks, |
|||
178 |
- ## server+ #' and they are placed in the `values` environment in the `session$restoreContext` field. |
|||
179 | -216x | +
- checkmate::assert_function(server)+ #' Using `teal_data_module` makes it impossible to run the callbacks |
||
180 | -216x | +
- server_formals <- names(formals(server))+ #' because the app becomes ready before modules execute and callbacks are registered. |
||
181 | -216x | +
- if (!(+ #' In those cases the stored values can still be recovered from the `session` object directly. |
||
182 | -216x | +
- "id" %in% server_formals ||+ #' |
||
183 | -216x | +
- all(c("input", "output", "session") %in% server_formals)+ #' Note that variable names in the `values` environment are prefixed with module name space names, |
||
184 |
- )) {+ #' therefore, when using this function in modules, `value` must be run through the name space function. |
|||
185 | -2x | +
- stop(+ #' |
||
186 | -2x | +
- "\nmodule() `server` argument requires a function with following arguments:",+ #' @param value (`character(1)`) name of value to restore |
||
187 | -2x | +
- "\n - id - `teal` will set proper `shiny` namespace for this module.",+ #' @param default fallback value |
||
188 | -2x | +
- "\n - input, output, session (not recommended) - then `shiny::callModule` will be used to call a module.",+ #' |
||
189 | -2x | +
- "\n\nFollowing arguments can be used optionaly:",+ #' @return |
||
190 | -2x | +
- "\n - `data` - module will receive list of reactive (filtered) data specified in the `filters` argument",+ #' In an application restored from a server-side bookmark, |
||
191 | -2x | +
- "\n - `datasets` - module will receive `FilteredData`. See `help(teal.slice::FilteredData)`",+ #' the variable specified by `value` from the `values` environment. |
||
192 | -2x | +
- "\n - `reporter` - module will receive `Reporter`. See `help(teal.reporter::Reporter)`",+ #' Otherwise `default`. |
||
193 | -2x | +
- "\n - `filter_panel_api` - module will receive `FilterPanelAPI`. (See [teal.slice::FilterPanelAPI]).",+ #' |
||
194 | -2x | +
- "\n - `...` server_args elements will be passed to the module named argument or to the `...`"+ #' @keywords internal |
||
195 |
- )+ #' |
|||
196 |
- }+ restoreValue <- function(value, default) { # nolint: object_name. |
|||
197 | -+ | 174x |
-
+ checkmate::assert_character("value") |
|
198 | -214x | +174x |
- if ("datasets" %in% server_formals) {+ session_default <- shiny::getDefaultReactiveDomain() |
|
199 | -2x | +174x |
- warning(+ session_parent <- .subset2(session_default, "parent") |
|
200 | -2x | +174x |
- sprintf("Called from module(label = \"%s\", ...)\n ", label),+ session <- if (is.null(session_parent)) session_default else session_parent |
|
201 | -2x | +
- "`datasets` argument in the server is deprecated and will be removed in the next release. ",+ |
||
202 | -2x | +174x |
- "Please use `data` instead.",+ if (isTRUE(session$restoreContext$active) && exists(value, session$restoreContext$values, inherits = FALSE)) { |
|
203 | -2x | +! |
- call. = FALSE+ session$restoreContext$values[[value]] |
|
204 |
- )+ } else { |
|||
205 | -+ | 174x |
- }+ default |
|
206 |
-
+ } |
|||
207 |
- ## UI+ } |
|||
208 | -214x | +
- checkmate::assert_function(ui)+ |
||
209 | -214x | +
- ui_formals <- names(formals(ui))+ #' Compare bookmarks. |
||
210 | -214x | +
- if (!"id" %in% ui_formals) {+ #' |
||
211 | -1x | +
- stop(+ #' Test if two bookmarks store identical state. |
||
212 | -1x | +
- "\nmodule() `ui` argument requires a function with following arguments:",+ #' |
||
213 | -1x | +
- "\n - id - `teal` will set proper `shiny` namespace for this module.",+ #' `input` environments are compared one variable at a time and if not identical, |
||
214 | -1x | +
- "\n\nFollowing arguments can be used optionally:",+ #' values in both bookmarks are reported. States of `datatable`s are stripped |
||
215 | -1x | +
- "\n - `...` ui_args elements will be passed to the module argument of the same name or to the `...`"+ #' of the `time` element before comparing because the time stamp is always different. |
||
216 |
- )+ #' The contents themselves are not printed as they are large and the contents are not informative. |
|||
217 |
- }+ #' Elements present in one bookmark and absent in the other are also reported. |
|||
218 |
-
+ #' Differences are printed as messages. |
|||
219 | -213x | +
- if (any(c("data", "datasets") %in% ui_formals)) {+ #' |
||
220 | -2x | +
- stop(+ #' `values` environments are compared with `all.equal`. |
||
221 | -2x | +
- sprintf("Called from module(label = \"%s\", ...)\n ", label),+ #' |
||
222 | -2x | +
- "UI with `data` or `datasets` argument is no longer accepted.\n ",+ #' @section How to use: |
||
223 | -2x | +
- "If some UI inputs depend on data, please move the logic to your server instead.\n ",+ #' Open an application, change relevant inputs (typically, all of them), and create a bookmark. |
||
224 | -2x | +
- "Possible solutions are renderUI() or updateXyzInput() functions."+ #' Then open that bookmark and immediately create a bookmark of that. |
||
225 |
- )+ #' If restoring bookmarks occurred properly, the two bookmarks should store the same state. |
|||
226 |
- }+ #' |
|||
227 |
-
+ #' |
|||
228 |
- ## `filters`+ #' @param book1,book2 bookmark directories stored in `shiny_bookmarks/`; |
|||
229 | -211x | +
- if (!missing(filters)) {+ #' default to the two most recently modified directories |
||
230 | -! | +
- datanames <- filters+ #' |
||
231 | -! | +
- msg <-+ #' @return |
||
232 | -! | +
- "The `filters` argument is deprecated and will be removed in the next release. Please use `datanames` instead."+ #' Invisible `NULL` if bookmarks are identical or if there are no bookmarks to test. |
||
233 | -! | +
- warning(msg)+ #' `FALSE` if inconsistencies are detected. |
||
234 |
- }+ #' |
|||
235 |
-
+ #' @keywords internal |
|||
236 |
- ## `datanames` (also including deprecated `filters`)+ #' |
|||
237 |
- # please note a race condition between datanames set when filters is not missing and data arg in server function+ bookmarks_identical <- function(book1, book2) { |
|||
238 | -211x | +! |
- if (!is.element("data", server_formals) && !is.null(datanames)) {+ if (!dir.exists("shiny_bookmarks")) { |
|
239 | -12x | +! |
- message(sprintf("module \"%s\" server function takes no data so \"datanames\" will be ignored", label))+ message("no bookmark directory") |
|
240 | -12x | +! |
- datanames <- NULL+ return(invisible(NULL)) |
|
242 | -211x | +
- checkmate::assert_character(datanames, min.len = 1, null.ok = TRUE, any.missing = FALSE)+ |
||
243 | -+ | ! |
-
+ ans <- TRUE |
|
244 |
- ## `server_args`+ |
|||
245 | -210x | +! |
- checkmate::assert_list(server_args, null.ok = TRUE, names = "named")+ if (missing(book1) && missing(book2)) { |
|
246 | -208x | +! |
- srv_extra_args <- setdiff(names(server_args), server_formals)+ dirs <- list.dirs("shiny_bookmarks", recursive = FALSE) |
|
247 | -208x | +! |
- if (length(srv_extra_args) > 0 && !"..." %in% server_formals) {+ bookmarks_sorted <- basename(rev(dirs[order(file.mtime(dirs))])) |
|
248 | -1x | +! |
- stop(+ if (length(bookmarks_sorted) < 2L) { |
|
249 | -1x | +! |
- "\nFollowing `server_args` elements have no equivalent in the formals of the server:\n",+ message("no bookmarks to compare") |
|
250 | -1x | +! |
- paste(paste(" -", srv_extra_args), collapse = "\n"),+ return(invisible(NULL)) |
|
251 | -1x | +
- "\n\nUpdate the server arguments by including above or add `...`"+ } |
||
252 | -+ | ! |
- )+ book1 <- bookmarks_sorted[2L] |
|
253 | -+ | ! |
- }+ book2 <- bookmarks_sorted[1L] |
|
254 |
-
+ } else { |
|||
255 | -+ | ! |
- ## `ui_args`+ if (!dir.exists(file.path("shiny_bookmarks", book1))) stop(book1, " not found") |
|
256 | -207x | +! |
- checkmate::assert_list(ui_args, null.ok = TRUE, names = "named")+ if (!dir.exists(file.path("shiny_bookmarks", book2))) stop(book2, " not found") |
|
257 | -205x | +
- ui_extra_args <- setdiff(names(ui_args), ui_formals)+ } |
||
258 | -205x | +
- if (length(ui_extra_args) > 0 && !"..." %in% ui_formals) {+ |
||
259 | -1x | +! |
- stop(+ book1_input <- readRDS(file.path("shiny_bookmarks", book1, "input.rds")) |
|
260 | -1x | +! |
- "\nFollowing `ui_args` elements have no equivalent in the formals of UI:\n",+ book2_input <- readRDS(file.path("shiny_bookmarks", book2, "input.rds")) |
|
261 | -1x | +
- paste(paste(" -", ui_extra_args), collapse = "\n"),+ |
||
262 | -1x | +! |
- "\n\nUpdate the UI arguments by including above or add `...`"+ elements_common <- intersect(names(book1_input), names(book2_input)) |
|
263 | +! | +
+ dt_states <- grepl("_state$", elements_common)+ |
+ ||
264 | +! | +
+ if (any(dt_states)) {+ |
+ ||
265 | +! | +
+ for (el in elements_common[dt_states]) {+ |
+ ||
266 | +! | +
+ book1_input[[el]][["time"]] <- NULL+ |
+ ||
267 | +! | +
+ book2_input[[el]][["time"]] <- NULL+ |
+ ||
268 |
- )+ } |
|||
264 | +269 |
} |
||
265 | +270 | ++ | + + | +|
271 | +! | +
+ identicals <- mapply(identical, book1_input[elements_common], book2_input[elements_common])+ |
+ ||
272 | +! | +
+ non_identicals <- names(identicals[!identicals])+ |
+ ||
273 | +! | +
+ compares <- sprintf("$ %s:\t%s --- %s", non_identicals, book1_input[non_identicals], book2_input[non_identicals])+ |
+ ||
274 | +! | +
+ if (length(compares) != 0L) {+ |
+ ||
275 | +! | +
+ message("common elements not identical: \n", paste(compares, collapse = "\n"))+ |
+ ||
276 | +! | +
+ ans <- FALSE+ |
+ ||
277 | ++ |
+ }+ |
+ ||
278 | ||||
279 | +! | +
+ elements_boook1 <- setdiff(names(book1_input), names(book2_input))+ |
+ ||
280 | +! | +
+ if (length(elements_boook1) != 0L) {+ |
+ ||
281 | +! | +
+ dt_states <- grepl("_state$", elements_boook1)+ |
+ ||
282 | +! | +
+ if (any(dt_states)) {+ |
+ ||
283 | +! | +
+ for (el in elements_boook1[dt_states]) {+ |
+ ||
284 | +! | +
+ if (is.list(book1_input[[el]])) book1_input[[el]] <- "--- data table state ---"+ |
+ ||
266 | +285 |
- ## `transformators`+ }+ |
+ ||
286 | ++ |
+ }+ |
+ ||
287 | +! | +
+ excess1 <- sprintf("$ %s:\t%s", elements_boook1, book1_input[elements_boook1])+ |
+ ||
288 | +! | +
+ message("elements only in book1: \n", paste(excess1, collapse = "\n"))+ |
+ ||
289 | +! | +
+ ans <- FALSE+ |
+ ||
290 | ++ |
+ }+ |
+ ||
291 | ++ | + + | +||
292 | +! | +
+ elements_boook2 <- setdiff(names(book2_input), names(book1_input))+ |
+ ||
293 | +! | +
+ if (length(elements_boook2) != 0L) { |
||
267 | -204x | +|||
294 | +! |
- if (inherits(transformators, "teal_transform_module")) {+ dt_states <- grepl("_state$", elements_boook1) |
||
268 | -1x | +|||
295 | +! |
- transformators <- list(transformators)+ if (any(dt_states)) { |
||
269 | -+ | |||
296 | +! |
- }+ for (el in elements_boook1[dt_states]) { |
||
270 | -204x | +|||
297 | +! |
- checkmate::assert_list(transformators, types = "teal_transform_module")+ if (is.list(book2_input[[el]])) book2_input[[el]] <- "--- data table state ---" |
||
271 | -204x | +|||
298 | +
- transform_datanames <- unlist(lapply(transformators, attr, "datanames"))+ } |
|||
272 | -204x | +|||
299 | +
- combined_datanames <- if (identical(datanames, "all")) {+ } |
|||
273 | -151x | +|||
300 | +! |
- "all"+ excess2 <- sprintf("$ %s:\t%s", elements_boook2, book2_input[elements_boook2]) |
||
274 | -+ | |||
301 | +! |
- } else {+ message("elements only in book2: \n", paste(excess2, collapse = "\n")) |
||
275 | -53x | +|||
302 | +! |
- union(datanames, transform_datanames)+ ans <- FALSE |
||
276 | +303 |
} |
||
277 | +304 | |||
278 | -204x | -
- structure(- |
- ||
279 | -204x | +|||
305 | +! |
- list(+ book1_values <- readRDS(file.path("shiny_bookmarks", book1, "values.rds")) |
||
280 | -204x | +|||
306 | +! |
- label = label,+ book2_values <- readRDS(file.path("shiny_bookmarks", book2, "values.rds")) |
||
281 | -204x | +|||
307 | +
- server = server,+ |
|||
282 | -204x | +|||
308 | +! |
- ui = ui,+ if (!isTRUE(all.equal(book1_values, book2_values))) { |
||
283 | -204x | +|||
309 | +! |
- datanames = combined_datanames,+ message("different values detected") |
||
284 | -204x | +|||
310 | +! |
- server_args = server_args,+ message("choices for numeric filters MAY be different, see RangeFilterState$set_choices") |
||
285 | -204x | +|||
311 | +! |
- ui_args = ui_args,+ ans <- FALSE |
||
286 | -204x | +|||
312 | +
- transformators = transformators+ } |
|||
287 | +313 |
- ),+ |
||
288 | -204x | +|||
314 | +! |
- class = "teal_module"+ if (ans) message("perfect!") |
||
289 | -+ | |||
315 | +! |
- )+ invisible(NULL) |
||
290 | +316 |
} |
||
291 | +317 | |||
292 | +318 |
- #' @rdname teal_modules+ |
||
293 | +319 |
- #' @export+ # Replacement for [base::rapply] which doesn't handle NULL values - skips the evaluation |
||
294 | +320 |
- #'+ # of the function and returns NULL for given element. |
||
295 | +321 |
- modules <- function(..., label = "root") {- |
- ||
296 | -144x | -
- checkmate::assert_string(label)- |
- ||
297 | -142x | -
- submodules <- list(...)+ rapply2 <- function(x, f) { |
||
298 | -142x | +322 | +199x |
- if (any(vapply(submodules, is.character, FUN.VALUE = logical(1)))) {+ if (inherits(x, "list")) { |
299 | -2x | +323 | +87x |
- stop(+ lapply(x, rapply2, f = f) |
300 | -2x | +|||
324 | +
- "The only character argument to modules() must be 'label' and it must be named, ",+ } else { |
|||
301 | -2x | +325 | +112x |
- "change modules('lab', ...) to modules(label = 'lab', ...)"+ f(x) |
302 | +326 |
- )+ } |
||
303 | +327 |
- }+ } |
304 | +1 | - - | -||
305 | -140x | -
- checkmate::assert_list(submodules, min.len = 1, any.missing = FALSE, types = c("teal_module", "teal_modules"))+ #' `teal` main module |
||
306 | +2 |
- # name them so we can more easily access the children+ #' |
||
307 | +3 |
- # beware however that the label of the submodules should not be changed as it must be kept synced- |
- ||
308 | -137x | -
- labels <- vapply(submodules, function(submodule) submodule$label, character(1))+ #' @description |
||
309 | -137x | +|||
4 | +
- names(submodules) <- get_unique_labels(labels)+ #' `r lifecycle::badge("stable")` |
|||
310 | -137x | +|||
5 | +
- structure(+ #' Module to create a `teal` app. This module can be called directly instead of [init()] and |
|||
311 | -137x | +|||
6 | +
- list(+ #' included in your custom application. Please note that [init()] adds `reporter_previewer_module` |
|||
312 | -137x | +|||
7 | +
- label = label,+ #' automatically, which is not a case when calling `ui/srv_teal` directly. |
|||
313 | -137x | +|||
8 | +
- children = submodules+ #' |
|||
314 | +9 |
- ),+ #' @details |
||
315 | -137x | +|||
10 | +
- class = "teal_modules"+ #' |
|||
316 | +11 |
- )+ #' Module is responsible for creating the main `shiny` app layout and initializing all the necessary |
||
317 | +12 |
- }+ #' components. This module establishes reactive connection between the input `data` and every other |
||
318 | +13 |
-
+ #' component in the app. Reactive change of the `data` passed as an argument, reloads the app and |
||
319 | +14 |
- # printing methods ----+ #' possibly keeps all input settings the same so the user can continue where one left off. |
||
320 | +15 |
-
+ #' |
||
321 | +16 |
- #' @rdname teal_modules+ #' ## data flow in `teal` application |
||
322 | +17 |
- #' @param is_last (`logical(1)`) Whether this is the last item in its parent's children list.+ #' |
||
323 | +18 |
- #' Affects the tree branch character used (L- vs |-)+ #' This module supports multiple data inputs but eventually, they are all converted to `reactive` |
||
324 | +19 |
- #' @param parent_prefix (`character(1)`) The prefix inherited from parent nodes,+ #' returning `teal_data` in this module. On this `reactive teal_data` object several actions are |
||
325 | +20 |
- #' used to maintain the tree structure in nested levels+ #' performed: |
||
326 | +21 |
- #' @param is_root (`logical(1)`) Whether this is the root node of the tree. Only used in+ #' - data loading in [`module_init_data`] |
||
327 | +22 |
- #' format.teal_modules(). Determines whether to show "TEAL ROOT" header+ #' - data filtering in [`module_filter_data`] |
||
328 | +23 |
- #' @param what (`character`) Specifies which metadata to display.+ #' - data transformation in [`module_transform_data`] |
||
329 | +24 |
- #' Possible values: "datasets", "properties", "ui_args", "server_args", "transformators"+ #' |
||
330 | +25 |
- #' @examples+ #' ## Fallback on failure |
||
331 | +26 |
- #' mod <- module(+ #' |
||
332 | +27 |
- #' label = "My Custom Module",+ #' `teal` is designed in such way that app will never crash if the error is introduced in any |
||
333 | +28 |
- #' server = function(id, data, ...) {},+ #' custom `shiny` module provided by app developer (e.g. [teal_data_module()], [teal_transform_module()]). |
||
334 | +29 |
- #' ui = function(id, ...) {},+ #' If any module returns a failing object, the app will halt the evaluation and display a warning message. |
||
335 | +30 |
- #' datanames = c("ADSL", "ADTTE"),+ #' App user should always have a chance to fix the improper input and continue without restarting the session. |
||
336 | +31 |
- #' transformators = list(),+ #' |
||
337 | +32 |
- #' ui_args = list(a = 1, b = "b"),+ #' @rdname module_teal |
||
338 | +33 |
- #' server_args = list(x = 5, y = list(p = 1))+ #' @name module_teal |
||
339 | +34 |
- #' )+ #' |
||
340 | +35 |
- #' cat(format(mod))+ #' @inheritParams module_init_data |
||
341 | +36 |
- #' @export+ #' @inheritParams init |
||
342 | +37 |
- format.teal_module <- function(+ #' |
||
343 | +38 |
- x, is_last = FALSE, parent_prefix = "",+ #' @return `NULL` invisibly |
||
344 | +39 |
- what = c("datasets", "properties", "ui_args", "server_args", "transformators"), ...) {+ NULL |
||
345 | -3x | +|||
40 | +
- empty_text <- ""+ |
|||
346 | -3x | +|||
41 | +
- branch <- if (is_last) "L-" else "|-"+ #' @rdname module_teal |
|||
347 | -3x | +|||
42 | +
- current_prefix <- paste0(parent_prefix, branch, " ")+ #' @export |
|||
348 | -3x | +|||
43 | +
- content_prefix <- paste0(parent_prefix, if (is_last) " " else "| ")+ ui_teal <- function(id, |
|||
349 | +44 |
-
+ modules, |
||
350 | -3x | +|||
45 | +
- format_list <- function(lst, empty = empty_text, label_width = 0) {+ title = build_app_title(), |
|||
351 | -6x | +|||
46 | +
- if (is.null(lst) || length(lst) == 0) {+ header = tags$p(), |
|||
352 | -6x | +|||
47 | +
- empty+ footer = tags$p()) { |
|||
353 | -+ | |||
48 | +! |
- } else {+ checkmate::assert_character(id, max.len = 1, any.missing = FALSE) |
||
354 | +49 | ! |
- colon_space <- paste(rep(" ", label_width), collapse = "")+ checkmate::assert( |
|
355 | -+ | |||
50 | +! |
-
+ .var.name = "title", |
||
356 | +51 | ! |
- first_item <- sprintf("%s (%s)", names(lst)[1], crayon::silver(class(lst[[1]])[1]))+ checkmate::check_string(title), |
|
357 | +52 | ! |
- rest_items <- if (length(lst) > 1) {+ checkmate::check_multi_class(title, c("shiny.tag", "shiny.tag.list", "html")) |
|
358 | -! | +|||
53 | +
- paste(+ ) |
|||
359 | +54 | ! |
- vapply(+ checkmate::assert( |
|
360 | +55 | ! |
- names(lst)[-1],+ .var.name = "header", |
|
361 | +56 | ! |
- function(name) {+ checkmate::check_string(header), |
|
362 | +57 | ! |
- sprintf(+ checkmate::check_multi_class(header, c("shiny.tag", "shiny.tag.list", "html"))+ |
+ |
58 | ++ |
+ ) |
||
363 | +59 | ! |
- "%s%s (%s)",+ checkmate::assert( |
|
364 | +60 | ! |
- paste0(content_prefix, "| ", colon_space),+ .var.name = "footer", |
|
365 | +61 | ! |
- name,+ checkmate::check_string(footer), |
|
366 | +62 | ! |
- crayon::silver(class(lst[[name]])[1])+ checkmate::check_multi_class(footer, c("shiny.tag", "shiny.tag.list", "html")) |
|
367 | +63 |
- )+ ) |
||
368 | +64 |
- },+ |
||
369 | +65 | ! |
- character(1)+ if (is.character(title)) {+ |
+ |
66 | +! | +
+ title <- build_app_title(title) |
||
370 | +67 |
- ),+ } else { |
||
371 | +68 | ! |
- collapse = "\n"+ validate_app_title_tag(title) |
|
372 | +69 |
- )+ } |
||
373 | +70 |
- }+ |
||
374 | +71 | ! |
- if (length(lst) > 1) paste0(first_item, "\n", rest_items) else first_item+ if (checkmate::test_string(header)) { |
|
375 | -+ | |||
72 | +! |
- }+ header <- tags$p(header) |
||
376 | +73 |
} |
||
377 | +74 | |||
378 | -3x | +|||
75 | +! |
- bookmarkable <- isTRUE(attr(x, "teal_bookmarkable"))+ if (checkmate::test_string(footer)) { |
||
379 | -3x | +|||
76 | +! |
- reportable <- "reporter" %in% names(formals(x$server))+ footer <- tags$p(footer) |
||
380 | +77 |
-
+ } |
||
381 | -3x | +|||
78 | +
- transformators <- if (length(x$transformators) > 0) {+ |
|||
382 | +79 | ! |
- paste(sapply(x$transformators, function(t) attr(t, "label")), collapse = ", ")+ ns <- NS(id) |
|
383 | +80 |
- } else {+ |
||
384 | -3x | +|||
81 | +
- empty_text+ # show busy icon when `shiny` session is busy computing stuff |
|||
385 | +82 |
- }+ # based on https://stackoverflow.com/questions/17325521/r-shiny-display-loading-message-while-function-is-running/22475216#22475216 # nolint: line_length. |
||
386 | -+ | |||
83 | +! |
-
+ shiny_busy_message_panel <- conditionalPanel( |
||
387 | -3x | +|||
84 | +! |
- output <- pasten(current_prefix, crayon::bgWhite(x$label))+ condition = "(($('html').hasClass('shiny-busy')) && (document.getElementById('shiny-notification-panel') == null))", # nolint: line_length. |
||
388 | -+ | |||
85 | +! |
-
+ tags$div( |
||
389 | -3x | +|||
86 | +! |
- if ("datasets" %in% what) {+ icon("arrows-rotate", class = "fa-spin", prefer_type = "solid"), |
||
390 | -3x | +|||
87 | +! |
- output <- paste0(+ "Computing ...", |
||
391 | -3x | +|||
88 | +
- output,+ # CSS defined in `custom.css` |
|||
392 | -3x | +|||
89 | +! |
- content_prefix, "|- ", crayon::yellow("Datasets : "), paste(x$datanames, collapse = ", "), "\n"+ class = "shinybusymessage" |
||
393 | +90 |
) |
||
394 | +91 |
- }- |
- ||
395 | -3x | -
- if ("properties" %in% what) {+ ) |
||
396 | -3x | +|||
92 | +
- output <- paste0(+ |
|||
397 | -3x | +|||
93 | +! |
- output,+ fluidPage( |
||
398 | -3x | +|||
94 | +! |
- content_prefix, "|- ", crayon::blue("Properties:"), "\n",+ id = id, |
||
399 | -3x | +|||
95 | +! |
- content_prefix, "| |- ", crayon::cyan("Bookmarkable : "), bookmarkable, "\n",+ title = title, |
||
400 | -3x | +|||
96 | +! |
- content_prefix, "| L- ", crayon::cyan("Reportable : "), reportable, "\n"+ theme = get_teal_bs_theme(), |
||
401 | -+ | |||
97 | +! |
- )+ include_teal_css_js(), |
||
402 | -+ | |||
98 | +! |
- }+ tags$header(header), |
||
403 | -3x | +|||
99 | +! |
- if ("ui_args" %in% what) {+ tags$hr(class = "my-2"), |
||
404 | -3x | +|||
100 | +! |
- ui_args_formatted <- format_list(x$ui_args, label_width = 19)+ shiny_busy_message_panel, |
||
405 | -3x | +|||
101 | +! |
- output <- paste0(+ tags$div( |
||
406 | -3x | +|||
102 | +! |
- output,+ id = ns("tabpanel_wrapper"), |
||
407 | -3x | +|||
103 | +! |
- content_prefix, "|- ", crayon::green("UI Arguments : "), ui_args_formatted, "\n"+ class = "teal-body", |
||
408 | -+ | |||
104 | +! |
- )+ ui_teal_module(id = ns("teal_modules"), modules = modules) |
||
409 | +105 |
- }- |
- ||
410 | -3x | -
- if ("server_args" %in% what) {- |
- ||
411 | -3x | -
- server_args_formatted <- format_list(x$server_args, label_width = 19)- |
- ||
412 | -3x | -
- output <- paste0(+ ), |
||
413 | -3x | +|||
106 | +! |
- output,+ tags$div( |
||
414 | -3x | +|||
107 | +! |
- content_prefix, "|- ", crayon::green("Server Arguments : "), server_args_formatted, "\n"+ id = ns("options_buttons"), |
||
415 | -+ | |||
108 | +! |
- )+ style = "position: absolute; right: 10px;", |
||
416 | -+ | |||
109 | +! |
- }+ ui_bookmark_panel(ns("bookmark_manager"), modules), |
||
417 | -3x | +|||
110 | +! |
- if ("transformators" %in% what) {+ tags$button( |
||
418 | -3x | +|||
111 | +! |
- output <- paste0(+ class = "btn action-button filter_hamburger", # see sidebar.css for style filter_hamburger |
||
419 | -3x | +|||
112 | +! |
- output,+ href = "javascript:void(0)", |
||
420 | -3x | +|||
113 | +! |
- content_prefix, "L- ", crayon::magenta("Transformators : "), transformators, "\n"+ onclick = sprintf("toggleFilterPanel('%s');", ns("tabpanel_wrapper")), |
||
421 | -+ | |||
114 | +! |
- )+ title = "Toggle filter panel", |
||
422 | -+ | |||
115 | +! |
- }+ icon("fas fa-bars") |
||
423 | +116 | - - | -||
424 | -3x | -
- output+ ), |
||
425 | -+ | |||
117 | +! |
- }+ ui_snapshot_manager_panel(ns("snapshot_manager_panel")), |
||
426 | -+ | |||
118 | +! |
-
+ ui_filter_manager_panel(ns("filter_manager_panel")) |
||
427 | +119 |
- #' @rdname teal_modules+ ), |
||
428 | -+ | |||
120 | +! |
- #' @examples+ tags$script( |
||
429 | -+ | |||
121 | +! |
- #' custom_module <- function(+ HTML( |
||
430 | -+ | |||
122 | +! |
- #' label = "label", ui_args = NULL, server_args = NULL,+ sprintf( |
||
431 | +123 |
- #' datanames = "all", transformators = list(), bk = FALSE) {+ " |
||
432 | -+ | |||
124 | +! |
- #' ans <- module(+ $(document).ready(function() { |
||
433 | -+ | |||
125 | +! |
- #' label,+ $('#%s').appendTo('#%s'); |
||
434 | +126 |
- #' server = function(id, data, ...) {},+ }); |
||
435 | +127 |
- #' ui = function(id, ...) {+ ", |
||
436 | -+ | |||
128 | +! |
- #' },+ ns("options_buttons"), |
||
437 | -+ | |||
129 | +! |
- #' datanames = datanames,+ ns("teal_modules-active_tab") |
||
438 | +130 |
- #' transformators = transformators,+ ) |
||
439 | +131 |
- #' ui_args = ui_args,+ ) |
||
440 | +132 |
- #' server_args = server_args+ ), |
||
441 | -+ | |||
133 | +! |
- #' )+ tags$hr(), |
||
442 | -+ | |||
134 | +! |
- #' attr(ans, "teal_bookmarkable") <- bk+ tags$footer( |
||
443 | -+ | |||
135 | +! |
- #' ans+ tags$div( |
||
444 | -+ | |||
136 | +! |
- #' }+ footer, |
||
445 | -+ | |||
137 | +! |
- #'+ teal.widgets::verbatim_popup_ui(ns("sessionInfo"), "Session Info", type = "link"), |
||
446 | -+ | |||
138 | +! |
- #' dummy_transformator <- teal_transform_module(+ br(), |
||
447 | -+ | |||
139 | +! |
- #' label = "Dummy Transform",+ ui_teal_lockfile(ns("lockfile")), |
||
448 | -+ | |||
140 | +! |
- #' ui = function(id) div("(does nothing)"),+ textOutput(ns("identifier")) |
||
449 | +141 |
- #' server = function(id, data) {+ ) |
||
450 | +142 |
- #' moduleServer(id, function(input, output, session) data)+ ) |
||
451 | +143 |
- #' }+ ) |
||
452 | +144 |
- #' )+ } |
||
453 | +145 |
- #'+ |
||
454 | +146 |
- #' plot_transformator <- teal_transform_module(+ #' @rdname module_teal |
||
455 | +147 |
- #' label = "Plot Settings",+ #' @export |
||
456 | +148 |
- #' ui = function(id) div("(does nothing)"),+ srv_teal <- function(id, data, modules, filter = teal_slices()) { |
||
457 | -+ | |||
149 | +89x |
- #' server = function(id, data) {+ checkmate::assert_character(id, max.len = 1, any.missing = FALSE) |
||
458 | -+ | |||
150 | +89x |
- #' moduleServer(id, function(input, output, session) data)+ checkmate::assert_multi_class(data, c("teal_data", "teal_data_module", "reactive")) |
||
459 | -+ | |||
151 | +88x |
- #' }+ checkmate::assert_class(modules, "teal_modules") |
||
460 | -+ | |||
152 | +88x |
- #' )+ checkmate::assert_class(filter, "teal_slices") |
||
461 | +153 |
- #'+ |
||
462 | -+ | |||
154 | +88x |
- #' complete_modules <- modules(+ moduleServer(id, function(input, output, session) { |
||
463 | -+ | |||
155 | +88x |
- #' custom_module(+ logger::log_debug("srv_teal initializing.") |
||
464 | +156 |
- #' label = "Data Overview",+ |
||
465 | -+ | |||
157 | +88x |
- #' datanames = c("ADSL", "ADAE", "ADVS"),+ if (getOption("teal.show_js_log", default = FALSE)) { |
||
466 | -+ | |||
158 | +! |
- #' ui_args = list(+ shinyjs::showLog() |
||
467 | +159 |
- #' view_type = "table",+ } |
||
468 | +160 |
- #' page_size = 10,+ |
||
469 | -+ | |||
161 | +88x |
- #' filters = c("ARM", "SEX", "RACE")+ srv_teal_lockfile("lockfile") |
||
470 | +162 |
- #' ),+ |
||
471 | -+ | |||
163 | +88x |
- #' server_args = list(+ output$identifier <- renderText( |
||
472 | -+ | |||
164 | +88x |
- #' cache = TRUE,+ paste0("Pid:", Sys.getpid(), " Token:", substr(session$token, 25, 32)) |
||
473 | +165 |
- #' debounce = 1000+ ) |
||
474 | +166 |
- #' ),+ |
||
475 | -+ | |||
167 | +88x |
- #' transformators = list(dummy_transformator),+ teal.widgets::verbatim_popup_srv( |
||
476 | -+ | |||
168 | +88x |
- #' bk = TRUE+ "sessionInfo", |
||
477 | -+ | |||
169 | +88x |
- #' ),+ verbatim_content = utils::capture.output(utils::sessionInfo()), |
||
478 | -+ | |||
170 | +88x |
- #' modules(+ title = "SessionInfo" |
||
479 | +171 |
- #' label = "Nested 1",+ ) |
||
480 | +172 |
- #' custom_module(+ |
||
481 | +173 |
- #' label = "Interactive Plots",+ # `JavaScript` code |
||
482 | -+ | |||
174 | +88x |
- #' datanames = c("ADSL", "ADVS"),+ run_js_files(files = "init.js") |
||
483 | +175 |
- #' ui_args = list(+ |
||
484 | +176 |
- #' plot_type = c("scatter", "box", "line"),+ # set timezone in shiny app |
||
485 | +177 |
- #' height = 600,+ # timezone is set in the early beginning so it will be available also |
||
486 | +178 |
- #' width = 800,+ # for `DDL` and all shiny modules |
||
487 | -+ | |||
179 | +88x |
- #' color_scheme = "viridis"+ get_client_timezone(session$ns) |
||
488 | -+ | |||
180 | +88x |
- #' ),+ observeEvent( |
||
489 | -+ | |||
181 | +88x |
- #' server_args = list(+ eventExpr = input$timezone, |
||
490 | -+ | |||
182 | +88x |
- #' render_type = "svg",+ once = TRUE, |
||
491 | -+ | |||
183 | +88x |
- #' cache_plots = TRUE+ handlerExpr = { |
||
492 | -+ | |||
184 | +! |
- #' ),+ session$userData$timezone <- input$timezone |
||
493 | -+ | |||
185 | +! |
- #' transformators = list(dummy_transformator, plot_transformator),+ logger::log_debug("srv_teal@1 Timezone set to client's timezone: { input$timezone }.") |
||
494 | +186 |
- #' bk = TRUE+ } |
||
495 | +187 |
- #' ),+ ) |
||
496 | +188 |
- #' modules(+ |
||
497 | -+ | |||
189 | +88x |
- #' label = "Nested 2",+ data_handled <- srv_init_data("data", data = data) |
||
498 | +190 |
- #' custom_module(+ |
||
499 | -+ | |||
191 | +87x |
- #' label = "Summary Statistics",+ validate_ui <- tags$div( |
||
500 | -+ | |||
192 | +87x |
- #' datanames = "ADSL",+ id = session$ns("validate_messages"), |
||
501 | -+ | |||
193 | +87x |
- #' ui_args = list(+ class = "teal_validated", |
||
502 | -+ | |||
194 | +87x |
- #' stats = c("mean", "median", "sd", "range"),+ ui_check_class_teal_data(session$ns("class_teal_data")), |
||
503 | -+ | |||
195 | +87x |
- #' grouping = c("ARM", "SEX")+ ui_validate_error(session$ns("silent_error")), |
||
504 | -+ | |||
196 | +87x |
- #' )+ ui_check_module_datanames(session$ns("datanames_warning")) |
||
505 | +197 |
- #' ),+ ) |
||
506 | -+ | |||
198 | +87x |
- #' modules(+ srv_check_class_teal_data("class_teal_data", data_handled) |
||
507 | -+ | |||
199 | +87x |
- #' label = "Labeled nested modules",+ srv_validate_error("silent_error", data_handled, validate_shiny_silent_error = FALSE) |
||
508 | -+ | |||
200 | +87x |
- #' custom_module(+ srv_check_module_datanames("datanames_warning", data_handled, modules) |
||
509 | +201 |
- #' label = "Subgroup Analysis",+ |
||
510 | -+ | |||
202 | +87x |
- #' datanames = c("ADSL", "ADAE"),+ data_validated <- .trigger_on_success(data_handled) |
||
511 | +203 |
- #' ui_args = list(+ |
||
512 | -+ | |||
204 | +87x |
- #' subgroups = c("AGE", "SEX", "RACE"),+ data_signatured <- reactive({ |
||
513 | -+ | |||
205 | +152x |
- #' analysis_type = "stratified"+ req(inherits(data_validated(), "teal_data")) |
||
514 | -+ | |||
206 | +75x |
- #' ),+ is_filter_ok <- check_filter_datanames(filter, names(data_validated())) |
||
515 | -+ | |||
207 | +75x |
- #' bk = TRUE+ if (!isTRUE(is_filter_ok)) { |
||
516 | -+ | |||
208 | +2x |
- #' )+ showNotification( |
||
517 | -+ | |||
209 | +2x |
- #' ),+ "Some filters were not applied because of incompatibility with data. Contact app developer.", |
||
518 | -+ | |||
210 | +2x |
- #' modules(custom_module(label = "Subgroup Analysis in non-labled modules"))+ type = "warning", |
||
519 | -+ | |||
211 | +2x |
- #' )+ duration = 10 |
||
520 | +212 |
- #' ),+ ) |
||
521 | -+ | |||
213 | +2x |
- #' custom_module("Non-nested module")+ warning(is_filter_ok) |
||
522 | +214 |
- #' )+ } |
||
523 | -+ | |||
215 | +75x |
- #'+ .add_signature_to_data(data_validated()) |
||
524 | +216 |
- #' cat(format(complete_modules))+ }) |
||
525 | +217 |
- #' cat(format(complete_modules, what = c("ui_args", "server_args", "transformators")))+ |
||
526 | -+ | |||
218 | +87x |
- #' @export+ data_load_status <- reactive({ |
||
527 | -+ | |||
219 | +80x |
- format.teal_modules <- function(x, is_root = TRUE, is_last = FALSE, parent_prefix = "", ...) {+ if (inherits(data_handled(), "teal_data")) { |
||
528 | -1x | +220 | +75x |
- if (is_root) {+ "ok" |
529 | -1x | +221 | +5x |
- header <- pasten(crayon::bold("TEAL ROOT"))+ } else if (inherits(data, "teal_data_module")) { |
530 | -1x | +222 | +5x |
- new_parent_prefix <- " " #' Initial indent for root level+ "teal_data_module failed" |
531 | +223 |
- } else {+ } else { |
||
532 | +224 | ! |
- if (!is.null(x$label)) {+ "external failed" |
|
533 | -! | +|||
225 | +
- branch <- if (is_last) "L-" else "|-"+ } |
|||
534 | -! | +|||
226 | +
- header <- pasten(parent_prefix, branch, " ", crayon::bold(x$label))+ }) |
|||
535 | -! | +|||
227 | +
- new_parent_prefix <- paste0(parent_prefix, if (is_last) " " else "| ")+ |
|||
536 | -+ | |||
228 | +87x |
- } else {+ datasets_rv <- if (!isTRUE(attr(filter, "module_specific"))) { |
||
537 | -! | +|||
229 | +76x |
- header <- ""+ eventReactive(data_signatured(), { |
||
538 | -! | +|||
230 | +66x |
- new_parent_prefix <- parent_prefix+ req(inherits(data_signatured(), "teal_data")) |
||
539 | -+ | |||
231 | +66x |
- }+ logger::log_debug("srv_teal@1 initializing FilteredData") |
||
540 | -+ | |||
232 | +66x |
- }+ teal_data_to_filtered_data(data_signatured()) |
||
541 | +233 |
-
+ }) |
||
542 | -1x | +|||
234 | +
- if (length(x$children) > 0) {+ } |
|||
543 | -1x | +|||
235 | +
- children_output <- character(0)+ |
|||
544 | -1x | +|||
236 | +
- n_children <- length(x$children)+ |
|||
545 | +237 | |||
546 | -1x | +238 | +87x |
- for (i in seq_along(x$children)) {+ if (inherits(data, "teal_data_module")) { |
547 | -3x | +239 | +9x |
- child <- x$children[[i]]+ setBookmarkExclude(c("teal_modules-active_tab")) |
548 | -3x | +240 | +9x |
- is_last_child <- (i == n_children)+ shiny::insertTab( |
549 | -+ | |||
241 | +9x |
-
+ inputId = "teal_modules-active_tab", |
||
550 | -3x | +242 | +9x |
- if (inherits(child, "teal_modules")) {+ position = "before", |
551 | -! | +|||
243 | +9x |
- children_output <- c(+ select = TRUE, |
||
552 | -! | +|||
244 | +9x |
- children_output,+ tabPanel( |
||
553 | -! | +|||
245 | +9x |
- format(child,+ title = icon("fas fa-database"), |
||
554 | -! | +|||
246 | +9x |
- is_root = FALSE,+ value = "teal_data_module", |
||
555 | -! | +|||
247 | +9x |
- is_last = is_last_child,+ tags$div( |
||
556 | -! | +|||
248 | +9x |
- parent_prefix = new_parent_prefix,+ ui_init_data(session$ns("data")), |
||
557 | -+ | |||
249 | +9x |
- ...+ validate_ui |
||
558 | +250 |
) |
||
559 | +251 |
) |
||
560 | +252 |
- } else {- |
- ||
561 | -3x | -
- children_output <- c(+ ) |
||
562 | -3x | +|||
253 | +
- children_output,+ |
|||
563 | -3x | +254 | +9x |
- format(child,+ if (attr(data, "once")) { |
564 | -3x | +255 | +9x |
- is_last = is_last_child,+ observeEvent(data_signatured(), once = TRUE, { |
565 | -3x | +256 | +4x |
- parent_prefix = new_parent_prefix,+ logger::log_debug("srv_teal@2 removing data tab.") |
566 | +257 |
- ...+ # when once = TRUE we pull data once and then remove data tab |
||
567 | -+ | |||
258 | +4x |
- )+ removeTab("teal_modules-active_tab", target = "teal_data_module") |
||
568 | +259 |
- )+ }) |
||
569 | +260 |
} |
||
570 | +261 |
- }+ } else { |
||
571 | +262 |
-
+ # when no teal_data_module then we want to display messages above tabsetPanel (because there is no data-tab) |
||
572 | -1x | +263 | +78x |
- paste0(header, paste(children_output, collapse = ""))+ insertUI( |
573 | -+ | |||
264 | +78x |
- } else {+ selector = sprintf("#%s", session$ns("tabpanel_wrapper")), |
||
574 | -! | +|||
265 | +78x |
- header+ where = "beforeBegin",+ |
+ ||
266 | +78x | +
+ ui = tags$div(validate_ui, tags$br()) |
||
575 | +267 |
- }+ ) |
||
576 | +268 |
- }+ } |
||
577 | +269 | |||
578 | -+ | |||
270 | +87x |
- #' @rdname teal_modules+ module_labels <- unlist(module_labels(modules), use.names = FALSE) |
||
579 | -+ | |||
271 | +87x |
- #' @export+ slices_global <- methods::new(".slicesGlobal", filter, module_labels) |
||
580 | -+ | |||
272 | +87x |
- print.teal_module <- function(x, ...) {+ modules_output <- srv_teal_module( |
||
581 | -! | +|||
273 | +87x |
- cat(format(x, ...))+ id = "teal_modules", |
||
582 | -! | +|||
274 | +87x |
- invisible(x)+ data = data_signatured, |
||
583 | -+ | |||
275 | +87x |
- }+ datasets = datasets_rv, |
||
584 | -+ | |||
276 | +87x |
-
+ modules = modules, |
||
585 | -+ | |||
277 | +87x |
- #' @rdname teal_modules+ slices_global = slices_global, |
||
586 | -+ | |||
278 | +87x |
- #' @export+ data_load_status = data_load_status |
||
587 | +279 |
- print.teal_modules <- function(x, ...) {+ ) |
||
588 | -! | +|||
280 | +87x |
- cat(format(x, ...))+ mapping_table <- srv_filter_manager_panel("filter_manager_panel", slices_global = slices_global) |
||
589 | -! | +|||
281 | +87x |
- invisible(x)+ snapshots <- srv_snapshot_manager_panel("snapshot_manager_panel", slices_global = slices_global)+ |
+ ||
282 | +87x | +
+ srv_bookmark_panel("bookmark_manager", modules) |
||
590 | +283 |
- }+ }) |
||
591 | +284 | |||
592 | -+ | |||
285 | +87x |
- #' @param modules (`teal_module` or `teal_modules`)+ invisible(NULL) |
||
593 | +286 |
- #' @rdname teal_modules+ } |
594 | +1 |
- #' @examples+ # FilteredData ------ |
|
595 | +2 |
- #' # change the module's datanames+ |
|
596 | +3 |
- #' set_datanames(module(datanames = "all"), "a")+ #' Drive a `teal` application |
|
597 | +4 |
#' |
|
598 | +5 |
- #' # change modules' datanames+ #' Extension of the `shinytest2::AppDriver` class with methods for |
|
599 | +6 |
- #' set_datanames(+ #' driving a teal application for performing interactions for `shinytest2` tests. |
|
600 | +7 |
- #' modules(+ #' |
|
601 | +8 |
- #' module(datanames = "all"),+ #' @keywords internal |
|
602 | +9 |
- #' module(datanames = "a")+ #' |
|
603 | +10 |
- #' ),+ TealAppDriver <- R6::R6Class( # nolint: object_name. |
|
604 | +11 |
- #' "b"+ "TealAppDriver", |
|
605 | +12 |
- #' )+ inherit = { |
|
606 | +13 |
- #' @export+ if (!requireNamespace("shinytest2", quietly = TRUE)) { |
|
607 | +14 |
- set_datanames <- function(modules, datanames) {- |
- |
608 | -! | -
- checkmate::assert_multi_class(modules, c("teal_modules", "teal_module"))- |
- |
609 | -! | -
- if (inherits(modules, "teal_modules")) {- |
- |
610 | -! | -
- modules$children <- lapply(modules$children, set_datanames, datanames)+ stop("Please install 'shinytest2' package to use this class.") |
|
611 | +15 |
- } else {- |
- |
612 | -! | -
- if (identical(modules$datanames, "all")) {- |
- |
613 | -! | -
- modules$datanames <- datanames+ } |
|
614 | +16 |
- } else {- |
- |
615 | -! | -
- warning(- |
- |
616 | -! | -
- "Not possible to modify datanames of the module ", modules$label,+ if (!requireNamespace("rvest", quietly = TRUE)) { |
|
617 | -! | +||
17 | +
- ". set_datanames() can only change datanames if it was set to \"all\".",+ stop("Please install 'rvest' package to use this class.") |
||
618 | -! | +||
18 | +
- call. = FALSE+ } |
||
619 | +19 |
- )+ shinytest2::AppDriver |
|
620 | +20 |
- }+ }, |
|
621 | +21 |
- }+ # public methods ---- |
|
622 | -! | +||
22 | +
- modules+ public = list( |
||
623 | +23 |
- }+ #' @description |
|
624 | +24 |
-
+ #' Initialize a `TealAppDriver` object for testing a `teal` application. |
|
625 | +25 |
- # utilities ----+ #' |
|
626 | +26 |
- ## subset or modify modules ----+ #' @param data,modules,filter,title,header,footer,landing_popup arguments passed to `init` |
|
627 | +27 |
-
+ #' @param timeout (`numeric`) Default number of milliseconds for any timeout or |
|
628 | +28 |
- #' Append a `teal_module` to `children` of a `teal_modules` object+ #' timeout_ parameter in the `TealAppDriver` class. |
|
629 | +29 |
- #' @keywords internal+ #' Defaults to 20s. |
|
630 | +30 |
- #' @param modules (`teal_modules`)+ #' |
|
631 | +31 |
- #' @param module (`teal_module`) object to be appended onto the children of `modules`+ #' See [`shinytest2::AppDriver`] `new` method for more details on how to change it |
|
632 | +32 |
- #' @return A `teal_modules` object with `module` appended.+ #' via options or environment variables. |
|
633 | +33 |
- append_module <- function(modules, module) {+ #' @param load_timeout (`numeric`) How long to wait for the app to load, in ms. |
|
634 | -8x | +||
34 | +
- checkmate::assert_class(modules, "teal_modules")+ #' This includes the time to start R. Defaults to 100s. |
||
635 | -6x | +||
35 | +
- checkmate::assert_class(module, "teal_module")+ #' |
||
636 | -4x | +||
36 | +
- modules$children <- c(modules$children, list(module))+ #' See [`shinytest2::AppDriver`] `new` method for more details on how to change it |
||
637 | -4x | +||
37 | +
- labels <- vapply(modules$children, function(submodule) submodule$label, character(1))+ #' via options or environment variables |
||
638 | -4x | +||
38 | +
- names(modules$children) <- get_unique_labels(labels)+ #' @param ... Additional arguments to be passed to `shinytest2::AppDriver$new` |
||
639 | -4x | +||
39 | +
- modules+ #' |
||
640 | +40 |
- }+ #' |
|
641 | +41 |
-
+ #' @return Object of class `TealAppDriver` |
|
642 | +42 |
- #' Extract/Remove module(s) of specific class+ initialize = function(data, |
|
643 | +43 |
- #'+ modules, |
|
644 | +44 |
- #' Given a `teal_module` or a `teal_modules`, return the elements of the structure according to `class`.+ filter = teal_slices(), |
|
645 | +45 |
- #'+ title = build_app_title(), |
|
646 | +46 |
- #' @param modules (`teal_modules`)+ header = tags$p(), |
|
647 | +47 |
- #' @param class The class name of `teal_module` to be extracted or dropped.+ footer = tags$p(), |
|
648 | +48 |
- #' @keywords internal+ landing_popup = NULL, |
|
649 | +49 |
- #' @return+ timeout = rlang::missing_arg(), |
|
650 | +50 |
- #' - For `extract_module`, a `teal_module` of class `class` or `teal_modules` containing modules of class `class`.+ load_timeout = rlang::missing_arg(), |
|
651 | +51 |
- #' - For `drop_module`, the opposite, which is all `teal_modules` of class other than `class`.+ ...) { |
|
652 | -+ | ||
52 | +! |
- #' @rdname module_management+ private$data <- data |
|
653 | -+ | ||
53 | +! |
- extract_module <- function(modules, class) {+ private$modules <- modules |
|
654 | -28x | +||
54 | +! |
- if (inherits(modules, class)) {+ private$filter <- filter |
|
655 | +55 | ! |
- modules+ app <- init( |
656 | -28x | +||
56 | +! |
- } else if (inherits(modules, "teal_module")) {+ data = data, |
|
657 | -15x | +||
57 | +! |
- NULL+ modules = modules, |
|
658 | -13x | +||
58 | +! |
- } else if (inherits(modules, "teal_modules")) {+ filter = filter, |
|
659 | -13x | +||
59 | +! |
- Filter(function(x) length(x) > 0L, lapply(modules$children, extract_module, class))+ title = title, |
|
660 | -+ | ||
60 | +! |
- }+ header = header, |
|
661 | -+ | ||
61 | +! |
- }+ footer = footer, |
|
662 | -+ | ||
62 | +! |
-
+ landing_popup = landing_popup, |
|
663 | +63 |
- #' @keywords internal+ ) |
|
664 | +64 |
- #' @return `teal_modules`+ |
|
665 | +65 |
- #' @rdname module_management+ # Default timeout is hardcoded to 4s in shinytest2:::resolve_timeout |
|
666 | +66 |
- drop_module <- function(modules, class) {+ # It must be set as parameter to the AppDriver |
|
667 | +67 | ! |
- if (inherits(modules, class)) {+ suppressWarnings( |
668 | +68 | ! |
- NULL+ super$initialize( |
669 | +69 | ! |
- } else if (inherits(modules, "teal_module")) {+ app_dir = shinyApp(app$ui, app$server), |
670 | +70 | ! |
- modules+ name = "teal", |
671 | +71 | ! |
- } else if (inherits(modules, "teal_modules")) {+ variant = shinytest2::platform_variant(), |
672 | +72 | ! |
- do.call(+ timeout = rlang::maybe_missing(timeout, 20 * 1000), |
673 | +73 | ! |
- "modules",+ load_timeout = rlang::maybe_missing(load_timeout, 100 * 1000), |
674 | -! | +||
74 | +
- c(Filter(function(x) length(x) > 0L, lapply(modules$children, drop_module, class)), label = modules$label)+ ... |
||
675 | +75 |
- )+ ) |
|
676 | +76 |
- }+ ) |
|
677 | +77 |
- }+ |
|
678 | +78 |
-
+ # Check for minimum version of Chrome that supports the tests |
|
679 | +79 |
- ## read modules ----+ # - Element.checkVisibility was added on 105+ |
+ |
80 | +! | +
+ chrome_version <- numeric_version(+ |
+ |
81 | +! | +
+ gsub(+ |
+ |
82 | +! | +
+ "[[:alnum:]_]+/", # Prefix that ends with forward slash |
|
680 | +83 |
-
+ "",+ |
+ |
84 | +! | +
+ self$get_chromote_session()$Browser$getVersion()$product |
|
681 | +85 |
- #' Does the object make use of the `arg`+ ),+ |
+ |
86 | +! | +
+ strict = FALSE |
|
682 | +87 |
- #'+ ) |
|
683 | +88 |
- #' @param modules (`teal_module` or `teal_modules`) object+ + |
+ |
89 | +! | +
+ required_version <- "121" |
|
684 | +90 |
- #' @param arg (`character(1)`) names of the arguments to be checked against formals of `teal` modules.+ + |
+ |
91 | +! | +
+ testthat::skip_if(+ |
+ |
92 | +! | +
+ is.na(chrome_version), |
|
685 | -+ | ||
93 | +! |
- #' @return `logical` whether the object makes use of `arg`.+ "Problem getting Chrome version, please contact the developers." |
|
686 | +94 |
- #' @rdname is_arg_used+ ) |
|
687 | -+ | ||
95 | +! |
- #' @keywords internal+ testthat::skip_if( |
|
688 | -+ | ||
96 | +! |
- is_arg_used <- function(modules, arg) {+ chrome_version < required_version, |
|
689 | -519x | +||
97 | +! |
- checkmate::assert_string(arg)+ sprintf( |
|
690 | -516x | +||
98 | +! |
- if (inherits(modules, "teal_modules")) {+ "Chrome version '%s' is not supported, please upgrade to '%s' or higher", |
|
691 | -20x | +||
99 | +! |
- any(unlist(lapply(modules$children, is_arg_used, arg)))+ chrome_version, |
|
692 | -496x | +||
100 | +! |
- } else if (inherits(modules, "teal_module")) {+ required_version |
|
693 | -32x | +||
101 | +
- is_arg_used(modules$server, arg) || is_arg_used(modules$ui, arg)+ ) |
||
694 | -464x | +||
102 | +
- } else if (is.function(modules)) {+ ) |
||
695 | -462x | +||
103 | +
- isTRUE(arg %in% names(formals(modules)))+ # end od check |
||
696 | +104 |
- } else {+ |
|
697 | -2x | +||
105 | +! |
- stop("is_arg_used function not implemented for this object")+ private$set_active_ns() |
|
698 | -+ | ||
106 | +! |
- }+ self$wait_for_idle() |
|
699 | +107 |
- }+ }, |
|
700 | +108 |
-
+ #' @description |
|
701 | +109 |
-
+ #' Append parent [`shinytest2::AppDriver`] `click` method with a call to `waif_for_idle()` method. |
|
702 | +110 |
- #' Get module depth+ #' @param ... arguments passed to parent [`shinytest2::AppDriver`] `click()` method. |
|
703 | +111 |
- #'+ click = function(...) { |
|
704 | -+ | ||
112 | +! |
- #' Depth starts at 0, so a single `teal.module` has depth 0.+ super$click(...) |
|
705 | -+ | ||
113 | +! |
- #' Nesting it increases overall depth by 1.+ private$wait_for_page_stability() |
|
706 | +114 |
- #'+ }, |
|
707 | +115 |
- #' @inheritParams init+ #' @description |
|
708 | +116 |
- #' @param depth optional integer determining current depth level+ #' Check if the app has shiny errors. This checks for global shiny errors. |
|
709 | +117 |
- #'+ #' Note that any shiny errors dependent on shiny server render will only be captured after the teal module tab |
|
710 | +118 |
- #' @return Depth level for given module.+ #' is visited because shiny will not trigger server computations when the tab is invisible. |
|
711 | +119 |
- #' @keywords internal+ #' So, navigate to the module tab you want to test before calling this function. |
|
712 | +120 |
- modules_depth <- function(modules, depth = 0L) {+ #' Although, this catches errors hidden in the other module tabs if they are already rendered. |
|
713 | -12x | +||
121 | +
- checkmate::assert_multi_class(modules, c("teal_module", "teal_modules"))+ expect_no_shiny_error = function() { |
||
714 | -12x | +||
122 | +! |
- checkmate::assert_int(depth, lower = 0)+ testthat::expect_null( |
|
715 | -11x | +||
123 | +! |
- if (inherits(modules, "teal_modules")) {+ self$get_html(".shiny-output-error:not(.shiny-output-error-validation)"), |
|
716 | -4x | +||
124 | +! |
- max(vapply(modules$children, modules_depth, integer(1), depth = depth + 1L))+ info = "Shiny error is observed" |
|
717 | +125 |
- } else {+ ) |
|
718 | -7x | +||
126 | +
- depth+ }, |
||
719 | +127 |
- }+ #' @description |
|
720 | +128 |
- }+ #' Check if the app has no validation errors. This checks for global shiny validation errors. |
|
721 | +129 |
-
+ expect_no_validation_error = function() { |
|
722 | -+ | ||
130 | +! |
- #' Retrieve labels from `teal_modules`+ testthat::expect_null( |
|
723 | -+ | ||
131 | +! |
- #'+ self$get_html(".shiny-output-error-validation"),+ |
+ |
132 | +! | +
+ info = "No validation error is observed" |
|
724 | +133 |
- #' @param modules (`teal_modules`)+ ) |
|
725 | +134 |
- #' @return A `list` containing the labels of the modules. If the modules are nested,+ }, |
|
726 | +135 |
- #' the function returns a nested `list` of labels.+ #' @description |
|
727 | +136 |
- #' @keywords internal+ #' Check if the app has validation errors. This checks for global shiny validation errors. |
|
728 | +137 |
- module_labels <- function(modules) {+ expect_validation_error = function() { |
|
729 | -199x | +||
138 | +! |
- if (inherits(modules, "teal_modules")) {+ testthat::expect_false( |
|
730 | -87x | +||
139 | +! |
- lapply(modules$children, module_labels)+ is.null(self$get_html(".shiny-output-error-validation")), |
|
731 | -+ | ||
140 | +! |
- } else {+ info = "Validation error is not observed" |
|
732 | -112x | +||
141 | +
- modules$label+ ) |
||
733 | +142 |
- }+ }, |
|
734 | +143 |
- }+ #' @description |
|
735 | +144 |
-
+ #' Set the input in the `teal` app. |
|
736 | +145 |
- #' Retrieve `teal_bookmarkable` attribute from `teal_modules`+ #' |
|
737 | +146 |
- #'+ #' @param input_id (character) The shiny input id with it's complete name space. |
|
738 | +147 |
- #' @param modules (`teal_modules` or `teal_module`) object+ #' @param value The value to set the input to. |
|
739 | +148 |
- #' @return named list of the same structure as `modules` with `TRUE` or `FALSE` values indicating+ #' @param ... Additional arguments to be passed to `shinytest2::AppDriver$set_inputs` |
|
740 | +149 |
- #' whether the module is bookmarkable.+ #' |
|
741 | +150 |
- #' @keywords internal+ #' @return The `TealAppDriver` object invisibly. |
|
742 | +151 |
- modules_bookmarkable <- function(modules) {+ set_input = function(input_id, value, ...) { |
|
743 | -199x | +||
152 | +! |
- checkmate::assert_multi_class(modules, c("teal_modules", "teal_module"))+ do.call( |
|
744 | -199x | +||
153 | +! |
- if (inherits(modules, "teal_modules")) {+ self$set_inputs, |
|
745 | -87x | +||
154 | +! |
- setNames(+ c(setNames(list(value), input_id), list(...)) |
|
746 | -87x | +||
155 | +
- lapply(modules$children, modules_bookmarkable),+ ) |
||
747 | -87x | +||
156 | +! |
- vapply(modules$children, `[[`, "label", FUN.VALUE = character(1))+ invisible(self) |
|
748 | +157 |
- )+ }, |
|
749 | +158 |
- } else {+ #' @description |
|
750 | -112x | +||
159 | +
- attr(modules, "teal_bookmarkable", exact = TRUE)+ #' Navigate the teal tabs in the `teal` app. |
||
751 | +160 |
- }+ #' |
|
752 | +161 |
- }+ #' @param tabs (character) Labels of tabs to navigate to. The order of the tabs is important, |
1 | +162 |
- # FilteredData ------+ #' and it should start with the most parent level tab. |
||
2 | +163 |
-
+ #' Note: In case the teal tab group has duplicate names, the first tab will be selected, |
||
3 | +164 |
- #' Drive a `teal` application+ #' If you wish to select the second tab with the same name, use the suffix "_1". |
||
4 | +165 |
- #'+ #' If you wish to select the third tab with the same name, use the suffix "_2" and so on. |
||
5 | +166 |
- #' Extension of the `shinytest2::AppDriver` class with methods for+ #' |
||
6 | +167 |
- #' driving a teal application for performing interactions for `shinytest2` tests.+ #' @return The `TealAppDriver` object invisibly. |
||
7 | +168 |
- #'+ navigate_teal_tab = function(tabs) { |
||
8 | -+ | |||
169 | +! |
- #' @keywords internal+ checkmate::check_character(tabs, min.len = 1) |
||
9 | -+ | |||
170 | +! |
- #'+ for (tab in tabs) { |
||
10 | -+ | |||
171 | +! |
- TealAppDriver <- R6::R6Class( # nolint: object_name.+ self$set_input( |
||
11 | -+ | |||
172 | +! |
- "TealAppDriver",+ "teal-teal_modules-active_tab",+ |
+ ||
173 | +! | +
+ get_unique_labels(tab),+ |
+ ||
174 | +! | +
+ wait_ = FALSE |
||
12 | +175 |
- inherit = {+ ) |
||
13 | +176 |
- if (!requireNamespace("shinytest2", quietly = TRUE)) {+ }+ |
+ ||
177 | +! | +
+ self$wait_for_idle()+ |
+ ||
178 | +! | +
+ private$set_active_ns()+ |
+ ||
179 | +! | +
+ invisible(self) |
||
14 | +180 |
- stop("Please install 'shinytest2' package to use this class.")+ }, |
||
15 | +181 |
- }+ #' @description |
||
16 | +182 |
- if (!requireNamespace("rvest", quietly = TRUE)) {+ #' Get the active shiny name space for different components of the teal app. |
||
17 | +183 |
- stop("Please install 'rvest' package to use this class.")+ #' |
||
18 | +184 |
- }+ #' @return (`list`) The list of active shiny name space of the teal components. |
||
19 | +185 |
- shinytest2::AppDriver+ active_ns = function() { |
||
20 | -+ | |||
186 | +! |
- },+ if (identical(private$ns$module, character(0))) { |
||
21 | -+ | |||
187 | +! |
- # public methods ----+ private$set_active_ns() |
||
22 | +188 |
- public = list(+ } |
||
23 | -+ | |||
189 | +! |
- #' @description+ private$ns |
||
24 | +190 |
- #' Initialize a `TealAppDriver` object for testing a `teal` application.+ }, |
||
25 | +191 |
- #'+ #' @description |
||
26 | +192 |
- #' @param data,modules,filter,title,header,footer,landing_popup arguments passed to `init`+ #' Get the active shiny name space for interacting with the module content. |
||
27 | +193 |
- #' @param timeout (`numeric`) Default number of milliseconds for any timeout or+ #' |
||
28 | +194 |
- #' timeout_ parameter in the `TealAppDriver` class.+ #' @return (`string`) The active shiny name space of the component. |
||
29 | +195 |
- #' Defaults to 20s.+ active_module_ns = function() { |
||
30 | -+ | |||
196 | +! |
- #'+ if (identical(private$ns$module, character(0))) { |
||
31 | -+ | |||
197 | +! |
- #' See [`shinytest2::AppDriver`] `new` method for more details on how to change it+ private$set_active_ns() |
||
32 | +198 |
- #' via options or environment variables.+ } |
||
33 | -+ | |||
199 | +! |
- #' @param load_timeout (`numeric`) How long to wait for the app to load, in ms.+ private$ns$module |
||
34 | +200 |
- #' This includes the time to start R. Defaults to 100s.+ }, |
||
35 | +201 |
- #'+ #' @description |
||
36 | +202 |
- #' See [`shinytest2::AppDriver`] `new` method for more details on how to change it+ #' Get the active shiny name space bound with a custom `element` name. |
||
37 | +203 |
- #' via options or environment variables+ #' |
||
38 | +204 |
- #' @param ... Additional arguments to be passed to `shinytest2::AppDriver$new`+ #' @param element `character(1)` custom element name. |
||
39 | +205 |
#' |
||
40 | +206 |
- #'+ #' @return (`string`) The active shiny name space of the component bound with the input `element`. |
||
41 | +207 |
- #' @return Object of class `TealAppDriver`+ active_module_element = function(element) { |
||
42 | -+ | |||
208 | +! |
- initialize = function(data,+ checkmate::assert_string(element) |
||
43 | -+ | |||
209 | +! |
- modules,+ sprintf("#%s-%s", self$active_module_ns(), element) |
||
44 | +210 |
- filter = teal_slices(),+ }, |
||
45 | +211 |
- title = build_app_title(),+ #' @description |
||
46 | +212 |
- header = tags$p(),+ #' Get the text of the active shiny name space bound with a custom `element` name. |
||
47 | +213 |
- footer = tags$p(),+ #' |
||
48 | +214 |
- landing_popup = NULL,+ #' @param element `character(1)` the text of the custom element name. |
||
49 | +215 |
- timeout = rlang::missing_arg(),+ #' |
||
50 | +216 |
- load_timeout = rlang::missing_arg(),+ #' @return (`string`) The text of the active shiny name space of the component bound with the input `element`. |
||
51 | +217 |
- ...) {+ active_module_element_text = function(element) { |
||
52 | +218 | ! |
- private$data <- data+ checkmate::assert_string(element) |
|
53 | +219 | ! |
- private$modules <- modules+ self$get_text(self$active_module_element(element)) |
|
54 | -! | +|||
220 | +
- private$filter <- filter+ }, |
|||
55 | -! | +|||
221 | +
- app <- init(+ #' @description |
|||
56 | -! | +|||
222 | +
- data = data,+ #' Get the active shiny name space for interacting with the filter panel. |
|||
57 | -! | +|||
223 | +
- modules = modules,+ #' |
|||
58 | -! | +|||
224 | +
- filter = filter,+ #' @return (`string`) The active shiny name space of the component. |
|||
59 | -! | +|||
225 | +
- title = title,+ active_filters_ns = function() { |
|||
60 | +226 | ! |
- header = header,+ if (identical(private$ns$filter_panel, character(0))) { |
|
61 | +227 | ! |
- footer = footer,+ private$set_active_ns()+ |
+ |
228 | ++ |
+ } |
||
62 | +229 | ! |
- landing_popup = landing_popup,+ private$ns$filter_panel |
|
63 | +230 |
- )+ }, |
||
64 | +231 |
-
+ #' @description |
||
65 | +232 |
- # Default timeout is hardcoded to 4s in shinytest2:::resolve_timeout+ #' Get the active shiny name space for interacting with the data-summary panel. |
||
66 | +233 |
- # It must be set as parameter to the AppDriver+ #' |
||
67 | -! | +|||
234 | +
- suppressWarnings(+ #' @return (`string`) The active shiny name space of the data-summary component. |
|||
68 | -! | +|||
235 | +
- super$initialize(+ active_data_summary_ns = function() { |
|||
69 | +236 | ! |
- app_dir = shinyApp(app$ui, app$server),+ if (identical(private$ns$data_summary, character(0))) { |
|
70 | +237 | ! |
- name = "teal",+ private$set_active_ns() |
|
71 | -! | +|||
238 | +
- variant = shinytest2::platform_variant(),+ } |
|||
72 | +239 | ! |
- timeout = rlang::maybe_missing(timeout, 20 * 1000),+ private$ns$data_summary |
|
73 | -! | +|||
240 | +
- load_timeout = rlang::maybe_missing(load_timeout, 100 * 1000),+ }, |
|||
74 | +241 |
- ...+ #' @description |
||
75 | +242 |
- )+ #' Get the active shiny name space bound with a custom `element` name. |
||
76 | +243 |
- )+ #' |
||
77 | +244 |
-
+ #' @param element `character(1)` custom element name. |
||
78 | +245 |
- # Check for minimum version of Chrome that supports the tests+ #' |
||
79 | +246 |
- # - Element.checkVisibility was added on 105+ #' @return (`string`) The active shiny name space of the component bound with the input `element`. |
||
80 | -! | +|||
247 | +
- chrome_version <- numeric_version(+ active_data_summary_element = function(element) { |
|||
81 | +248 | ! |
- gsub(+ checkmate::assert_string(element) |
|
82 | +249 | ! |
- "[[:alnum:]_]+/", # Prefix that ends with forward slash+ sprintf("#%s-%s", self$active_data_summary_ns(), element) |
|
83 | +250 |
- "",- |
- ||
84 | -! | -
- self$get_chromote_session()$Browser$getVersion()$product+ }, |
||
85 | +251 |
- ),- |
- ||
86 | -! | -
- strict = FALSE+ #' @description |
||
87 | +252 |
- )+ #' Get the input from the module in the `teal` app. |
||
88 | +253 | - - | -||
89 | -! | -
- required_version <- "121"+ #' This function will only access inputs from the name space of the current active teal module. |
||
90 | +254 | - - | -||
91 | -! | -
- testthat::skip_if(- |
- ||
92 | -! | -
- is.na(chrome_version),- |
- ||
93 | -! | -
- "Problem getting Chrome version, please contact the developers."+ #' |
||
94 | +255 |
- )- |
- ||
95 | -! | -
- testthat::skip_if(+ #' @param input_id (character) The shiny input id to get the value from. |
||
96 | -! | +|||
256 | +
- chrome_version < required_version,+ #' |
|||
97 | -! | +|||
257 | +
- sprintf(+ #' @return The value of the shiny input. |
|||
98 | -! | +|||
258 | +
- "Chrome version '%s' is not supported, please upgrade to '%s' or higher",+ get_active_module_input = function(input_id) { |
|||
99 | +259 | ! |
- chrome_version,+ checkmate::check_string(input_id) |
|
100 | +260 | ! |
- required_version+ self$get_value(input = sprintf("%s-%s", self$active_module_ns(), input_id)) |
|
101 | +261 |
- )+ }, |
||
102 | +262 |
- )+ #' @description |
||
103 | +263 |
- # end od check+ #' Get the output from the module in the `teal` app. |
||
104 | +264 | - - | -||
105 | -! | -
- private$set_active_ns()- |
- ||
106 | -! | -
- self$wait_for_idle()+ #' This function will only access outputs from the name space of the current active teal module. |
||
107 | +265 |
- },+ #' |
||
108 | +266 |
- #' @description+ #' @param output_id (character) The shiny output id to get the value from. |
||
109 | +267 |
- #' Append parent [`shinytest2::AppDriver`] `click` method with a call to `waif_for_idle()` method.+ #' |
||
110 | +268 |
- #' @param ... arguments passed to parent [`shinytest2::AppDriver`] `click()` method.+ #' @return The value of the shiny output. |
||
111 | +269 |
- click = function(...) {+ get_active_module_output = function(output_id) { |
||
112 | +270 | ! |
- super$click(...)+ checkmate::check_string(output_id) |
|
113 | +271 | ! |
- private$wait_for_page_stability()+ self$get_value(output = sprintf("%s-%s", self$active_module_ns(), output_id)) |
|
114 | +272 |
}, |
||
115 | +273 |
#' @description |
||
116 | +274 |
- #' Check if the app has shiny errors. This checks for global shiny errors.+ #' Get the output from the module's `teal.widgets::table_with_settings` or `DT::DTOutput` in the `teal` app. |
||
117 | +275 |
- #' Note that any shiny errors dependent on shiny server render will only be captured after the teal module tab+ #' This function will only access outputs from the name space of the current active teal module. |
||
118 | +276 |
- #' is visited because shiny will not trigger server computations when the tab is invisible.+ #' |
||
119 | +277 |
- #' So, navigate to the module tab you want to test before calling this function.+ #' @param table_id (`character(1)`) The id of the table in the active teal module's name space. |
||
120 | +278 |
- #' Although, this catches errors hidden in the other module tabs if they are already rendered.+ #' @param which (integer) If there is more than one table, which should be extracted. |
||
121 | +279 |
- expect_no_shiny_error = function() {- |
- ||
122 | -! | -
- testthat::expect_null(- |
- ||
123 | -! | -
- self$get_html(".shiny-output-error:not(.shiny-output-error-validation)"),- |
- ||
124 | -! | -
- info = "Shiny error is observed"+ #' By default it will look for a table that is built using `teal.widgets::table_with_settings`. |
||
125 | +280 |
- )+ #' |
||
126 | +281 |
- },+ #' @return The data.frame with table contents. |
||
127 | +282 |
- #' @description+ get_active_module_table_output = function(table_id, which = 1) { |
||
128 | -+ | |||
283 | +! |
- #' Check if the app has no validation errors. This checks for global shiny validation errors.+ checkmate::check_number(which, lower = 1) |
||
129 | -+ | |||
284 | +! |
- expect_no_validation_error = function() {+ checkmate::check_string(table_id) |
||
130 | +285 | ! |
- testthat::expect_null(+ table <- rvest::html_table( |
|
131 | +286 | ! |
- self$get_html(".shiny-output-error-validation"),+ self$get_html_rvest(self$active_module_element(table_id)), |
|
132 | +287 | ! |
- info = "No validation error is observed"+ fill = TRUE |
|
133 | +288 |
) |
||
134 | -- |
- },- |
- ||
135 | -- |
- #' @description- |
- ||
136 | -- |
- #' Check if the app has validation errors. This checks for global shiny validation errors.- |
- ||
137 | -+ | |||
289 | +! |
- expect_validation_error = function() {+ if (length(table) == 0) { |
||
138 | +290 | ! |
- testthat::expect_false(+ data.frame() |
|
139 | -! | +|||
291 | +
- is.null(self$get_html(".shiny-output-error-validation")),+ } else { |
|||
140 | +292 | ! |
- info = "Validation error is not observed"+ table[[which]] |
|
141 | +293 |
- )+ } |
||
142 | +294 |
}, |
||
143 | +295 |
#' @description |
||
144 | -- |
- #' Set the input in the `teal` app.- |
- ||
145 | +296 |
- #'+ #' Get the output from the module's `teal.widgets::plot_with_settings` in the `teal` app. |
||
146 | +297 |
- #' @param input_id (character) The shiny input id with it's complete name space.+ #' This function will only access plots from the name space of the current active teal module. |
||
147 | +298 |
- #' @param value The value to set the input to.+ #' |
||
148 | +299 |
- #' @param ... Additional arguments to be passed to `shinytest2::AppDriver$set_inputs`+ #' @param plot_id (`character(1)`) The id of the plot in the active teal module's name space. |
||
149 | +300 |
#' |
||
150 | +301 |
- #' @return The `TealAppDriver` object invisibly.+ #' @return The `src` attribute as `character(1)` vector. |
||
151 | +302 |
- set_input = function(input_id, value, ...) {+ get_active_module_plot_output = function(plot_id) { |
||
152 | +303 | ! |
- do.call(+ checkmate::check_string(plot_id) |
|
153 | +304 | ! |
- self$set_inputs,+ self$get_attr( |
|
154 | +305 | ! |
- c(setNames(list(value), input_id), list(...))- |
- |
155 | -- |
- )+ self$active_module_element(sprintf("%s-plot_main > img", plot_id)), |
||
156 | +306 | ! |
- invisible(self)+ "src" |
|
157 | +307 |
- },+ ) |
||
158 | +308 |
- #' @description+ }, |
||
159 | +309 |
- #' Navigate the teal tabs in the `teal` app.+ #' @description |
||
160 | +310 |
- #'+ #' Set the input in the module in the `teal` app. |
||
161 | +311 |
- #' @param tabs (character) Labels of tabs to navigate to. The order of the tabs is important,+ #' This function will only set inputs in the name space of the current active teal module. |
||
162 | +312 |
- #' and it should start with the most parent level tab.+ #' |
||
163 | +313 |
- #' Note: In case the teal tab group has duplicate names, the first tab will be selected,+ #' @param input_id (character) The shiny input id to get the value from. |
||
164 | +314 |
- #' If you wish to select the second tab with the same name, use the suffix "_1".+ #' @param value The value to set the input to. |
||
165 | +315 |
- #' If you wish to select the third tab with the same name, use the suffix "_2" and so on.+ #' @param ... Additional arguments to be passed to `shinytest2::AppDriver$set_inputs` |
||
166 | +316 |
#' |
||
167 | +317 |
#' @return The `TealAppDriver` object invisibly. |
||
168 | +318 |
- navigate_teal_tab = function(tabs) {- |
- ||
169 | -! | -
- checkmate::check_character(tabs, min.len = 1)+ set_active_module_input = function(input_id, value, ...) { |
||
170 | +319 | ! |
- for (tab in tabs) {+ checkmate::check_string(input_id) |
|
171 | +320 | ! |
- self$set_input(+ checkmate::check_string(value) |
|
172 | +321 | ! |
- "teal-teal_modules-active_tab",+ self$set_input( |
|
173 | +322 | ! |
- get_unique_labels(tab),+ sprintf("%s-%s", self$active_module_ns(), input_id), |
|
174 | +323 | ! |
- wait_ = FALSE+ value, |
|
175 | +324 |
- )+ ... |
||
176 | +325 |
- }+ ) |
||
177 | +326 | ! |
- self$wait_for_idle()+ dots <- rlang::list2(...) |
|
178 | +327 | ! |
- private$set_active_ns()+ if (!isFALSE(dots[["wait"]])) self$wait_for_idle() # Default behavior is to wait |
|
179 | +328 | ! |
invisible(self) |
|
180 | +329 |
}, |
||
181 | +330 |
#' @description |
||
182 | -- |
- #' Get the active shiny name space for different components of the teal app.- |
- ||
183 | -- |
- #'- |
- ||
184 | +331 |
- #' @return (`list`) The list of active shiny name space of the teal components.+ #' Get the active datasets that can be accessed via the filter panel of the current active teal module. |
||
185 | +332 |
- active_ns = function() {- |
- ||
186 | -! | -
- if (identical(private$ns$module, character(0))) {+ get_active_filter_vars = function() { |
||
187 | +333 | ! |
- private$set_active_ns()- |
- |
188 | -- |
- }+ displayed_datasets_index <- self$is_visible( |
||
189 | +334 | ! |
- private$ns- |
- |
190 | -- |
- },- |
- ||
191 | -- |
- #' @description+ sprintf("#%s-filters-filter_active_vars_contents > span", self$active_filters_ns()) |
||
192 | +335 |
- #' Get the active shiny name space for interacting with the module content.+ ) |
||
193 | +336 |
- #'+ |
||
194 | -+ | |||
337 | +! |
- #' @return (`string`) The active shiny name space of the component.+ available_datasets <- self$get_text( |
||
195 | -+ | |||
338 | +! |
- active_module_ns = function() {+ sprintf( |
||
196 | +339 | ! |
- if (identical(private$ns$module, character(0))) {+ "#%s-filters-filter_active_vars_contents .filter_panel_dataname", |
|
197 | +340 | ! |
- private$set_active_ns()+ self$active_filters_ns() |
|
198 | +341 |
- }- |
- ||
199 | -! | -
- private$ns$module+ ) |
||
200 | +342 |
- },+ ) |
||
201 | +343 |
- #' @description+ |
||
202 | -+ | |||
344 | +! |
- #' Get the active shiny name space bound with a custom `element` name.+ available_datasets[displayed_datasets_index] |
||
203 | +345 |
- #'+ }, |
||
204 | +346 |
- #' @param element `character(1)` custom element name.+ #' @description |
||
205 | +347 |
- #'+ #' Get the active data summary table |
||
206 | +348 |
- #' @return (`string`) The active shiny name space of the component bound with the input `element`.+ #' @return `data.frame` |
||
207 | +349 |
- active_module_element = function(element) {+ get_active_data_summary_table = function() { |
||
208 | +350 | ! |
- checkmate::assert_string(element)+ summary_table <- rvest::html_table( |
|
209 | +351 | ! |
- sprintf("#%s-%s", self$active_module_ns(), element)- |
- |
210 | -- |
- },- |
- ||
211 | -- |
- #' @description+ self$get_html_rvest(self$active_data_summary_element("table")), |
||
212 | -+ | |||
352 | +! |
- #' Get the text of the active shiny name space bound with a custom `element` name.+ fill = TRUE |
||
213 | -+ | |||
353 | +! |
- #'+ )[[1]] |
||
214 | +354 |
- #' @param element `character(1)` the text of the custom element name.+ |
||
215 | -+ | |||
355 | +! |
- #'+ col_names <- unlist(summary_table[1, ], use.names = FALSE) |
||
216 | -+ | |||
356 | +! |
- #' @return (`string`) The text of the active shiny name space of the component bound with the input `element`.+ summary_table <- summary_table[-1, ] |
||
217 | -+ | |||
357 | +! |
- active_module_element_text = function(element) {+ colnames(summary_table) <- col_names |
||
218 | +358 | ! |
- checkmate::assert_string(element)+ if (nrow(summary_table) > 0) { |
|
219 | +359 | ! |
- self$get_text(self$active_module_element(element))+ summary_table |
|
220 | +360 |
- },+ } else { |
||
221 | -+ | |||
361 | +! |
- #' @description+ NULL |
||
222 | +362 |
- #' Get the active shiny name space for interacting with the filter panel.+ } |
||
223 | +363 |
- #'+ }, |
||
224 | +364 |
- #' @return (`string`) The active shiny name space of the component.+ #' @description |
||
225 | +365 |
- active_filters_ns = function() {+ #' Test if `DOM` elements are visible on the page with a JavaScript call. |
||
226 | -! | +|||
366 | +
- if (identical(private$ns$filter_panel, character(0))) {+ #' @param selector (`character(1)`) `CSS` selector to check visibility. |
|||
227 | -! | +|||
367 | +
- private$set_active_ns()+ #' A `CSS` id will return only one element if the UI is well formed. |
|||
228 | +368 |
- }+ #' @param content_visibility_auto,opacity_property,visibility_property (`logical(1)`) See more information |
||
229 | -! | +|||
369 | +
- private$ns$filter_panel+ #' on <https://developer.mozilla.org/en-US/docs/Web/API/Element/checkVisibility>. |
|||
230 | +370 |
- },+ #' |
||
231 | +371 |
- #' @description+ #' @return Logical vector with all occurrences of the selector. |
||
232 | +372 |
- #' Get the active shiny name space for interacting with the data-summary panel.+ is_visible = function(selector, |
||
233 | +373 |
- #'+ content_visibility_auto = FALSE, |
||
234 | +374 |
- #' @return (`string`) The active shiny name space of the data-summary component.+ opacity_property = FALSE, |
||
235 | +375 |
- active_data_summary_ns = function() {+ visibility_property = FALSE) { |
||
236 | +376 | ! |
- if (identical(private$ns$data_summary, character(0))) {+ checkmate::assert_string(selector) |
|
237 | +377 | ! |
- private$set_active_ns()+ checkmate::assert_flag(content_visibility_auto) |
|
238 | -+ | |||
378 | +! |
- }+ checkmate::assert_flag(opacity_property) |
||
239 | +379 | ! |
- private$ns$data_summary+ checkmate::assert_flag(visibility_property) |
|
240 | +380 |
- },+ |
||
241 | -+ | |||
381 | +! |
- #' @description+ private$wait_for_page_stability() |
||
242 | +382 |
- #' Get the active shiny name space bound with a custom `element` name.+ |
||
243 | -+ | |||
383 | +! |
- #'+ testthat::skip_if_not( |
||
244 | -+ | |||
384 | +! |
- #' @param element `character(1)` custom element name.+ self$get_js("typeof Element.prototype.checkVisibility === 'function'"), |
||
245 | -+ | |||
385 | +! |
- #'+ "Element.prototype.checkVisibility is not supported in the current browser." |
||
246 | +386 |
- #' @return (`string`) The active shiny name space of the component bound with the input `element`.+ ) |
||
247 | +387 |
- active_data_summary_element = function(element) {+ |
||
248 | +388 | ! |
- checkmate::assert_string(element)+ unlist( |
|
249 | +389 | ! |
- sprintf("#%s-%s", self$active_data_summary_ns(), element)+ self$get_js( |
|
250 | -+ | |||
390 | +! |
- },+ sprintf( |
||
251 | -+ | |||
391 | +! |
- #' @description+ "Array.from(document.querySelectorAll('%s')).map(el => el.checkVisibility({%s, %s, %s}))", |
||
252 | -+ | |||
392 | +! |
- #' Get the input from the module in the `teal` app.+ selector, |
||
253 | +393 |
- #' This function will only access inputs from the name space of the current active teal module.+ # Extra parameters |
||
254 | -+ | |||
394 | +! |
- #'+ sprintf("contentVisibilityAuto: %s", tolower(content_visibility_auto)), |
||
255 | -+ | |||
395 | +! |
- #' @param input_id (character) The shiny input id to get the value from.+ sprintf("opacityProperty: %s", tolower(opacity_property)), |
||
256 | -+ | |||
396 | +! |
- #'+ sprintf("visibilityProperty: %s", tolower(visibility_property)) |
||
257 | +397 |
- #' @return The value of the shiny input.+ ) |
||
258 | +398 |
- get_active_module_input = function(input_id) {- |
- ||
259 | -! | -
- checkmate::check_string(input_id)+ ) |
||
260 | -! | +|||
399 | +
- self$get_value(input = sprintf("%s-%s", self$active_module_ns(), input_id))+ ) |
|||
261 | +400 |
}, |
||
262 | +401 |
#' @description |
||
263 | +402 |
- #' Get the output from the module in the `teal` app.+ #' Get the active filter variables from a dataset in the `teal` app. |
||
264 | +403 |
- #' This function will only access outputs from the name space of the current active teal module.+ #' |
||
265 | +404 |
- #'+ #' @param dataset_name (character) The name of the dataset to get the filter variables from. |
||
266 | +405 |
- #' @param output_id (character) The shiny output id to get the value from.+ #' If `NULL`, the filter variables for all the datasets will be returned in a list. |
||
267 | +406 |
- #'+ get_active_data_filters = function(dataset_name = NULL) { |
||
268 | -+ | |||
407 | +! |
- #' @return The value of the shiny output.+ checkmate::check_string(dataset_name, null.ok = TRUE) |
||
269 | -+ | |||
408 | +! |
- get_active_module_output = function(output_id) {+ datasets <- self$get_active_filter_vars() |
||
270 | +409 | ! |
- checkmate::check_string(output_id)+ checkmate::assert_subset(dataset_name, datasets) |
|
271 | +410 | ! |
- self$get_value(output = sprintf("%s-%s", self$active_module_ns(), output_id))+ active_filters <- lapply( |
|
272 | -+ | |||
411 | +! |
- },+ datasets, |
||
273 | -+ | |||
412 | +! |
- #' @description+ function(x) { |
||
274 | -+ | |||
413 | +! |
- #' Get the output from the module's `teal.widgets::table_with_settings` or `DT::DTOutput` in the `teal` app.+ var_names <- gsub( |
||
275 | -+ | |||
414 | +! |
- #' This function will only access outputs from the name space of the current active teal module.+ pattern = "\\s", |
||
276 | -+ | |||
415 | +! |
- #'+ replacement = "", |
||
277 | -+ | |||
416 | +! |
- #' @param table_id (`character(1)`) The id of the table in the active teal module's name space.+ self$get_text( |
||
278 | -+ | |||
417 | +! |
- #' @param which (integer) If there is more than one table, which should be extracted.+ sprintf( |
||
279 | -+ | |||
418 | +! |
- #' By default it will look for a table that is built using `teal.widgets::table_with_settings`.+ "#%s-filters-%s .filter-card-varname",+ |
+ ||
419 | +! | +
+ self$active_filters_ns(),+ |
+ ||
420 | +! | +
+ x |
||
280 | +421 |
- #'+ ) |
||
281 | +422 |
- #' @return The data.frame with table contents.+ ) |
||
282 | +423 |
- get_active_module_table_output = function(table_id, which = 1) {+ ) |
||
283 | +424 | ! |
- checkmate::check_number(which, lower = 1)+ structure( |
|
284 | +425 | ! |
- checkmate::check_string(table_id)+ lapply(var_names, private$get_active_filter_selection, dataset_name = x), |
|
285 | +426 | ! |
- table <- rvest::html_table(+ names = var_names |
|
286 | -! | +|||
427 | +
- self$get_html_rvest(self$active_module_element(table_id)),+ ) |
|||
287 | -! | +|||
428 | +
- fill = TRUE+ } |
|||
288 | +429 |
) |
||
289 | +430 | ! |
- if (length(table) == 0) {+ names(active_filters) <- datasets |
|
290 | +431 | ! |
- data.frame()+ if (is.null(dataset_name)) {+ |
+ |
432 | +! | +
+ return(active_filters) |
||
291 | +433 |
- } else {+ } |
||
292 | +434 | ! |
- table[[which]]+ active_filters[[dataset_name]] |
|
293 | +435 |
- }+ }, |
||
294 | +436 |
- },+ #' @description |
||
295 | +437 |
- #' @description+ #' Add a new variable from the dataset to be filtered. |
||
296 | +438 |
- #' Get the output from the module's `teal.widgets::plot_with_settings` in the `teal` app.+ #' |
||
297 | +439 |
- #' This function will only access plots from the name space of the current active teal module.+ #' @param dataset_name (character) The name of the dataset to add the filter variable to. |
||
298 | +440 |
- #'+ #' @param var_name (character) The name of the variable to add to the filter panel. |
||
299 | +441 |
- #' @param plot_id (`character(1)`) The id of the plot in the active teal module's name space.+ #' @param ... Additional arguments to be passed to `shinytest2::AppDriver$set_inputs` |
||
300 | +442 |
#' |
||
301 | +443 |
- #' @return The `src` attribute as `character(1)` vector.+ #' @return The `TealAppDriver` object invisibly. |
||
302 | +444 |
- get_active_module_plot_output = function(plot_id) {+ add_filter_var = function(dataset_name, var_name, ...) { |
||
303 | +445 | ! |
- checkmate::check_string(plot_id)+ checkmate::check_string(dataset_name) |
|
304 | +446 | ! |
- self$get_attr(+ checkmate::check_string(var_name) |
|
305 | +447 | ! |
- self$active_module_element(sprintf("%s-plot_main > img", plot_id)),+ private$set_active_ns() |
|
306 | +448 | ! |
- "src"- |
- |
307 | -- |
- )- |
- ||
308 | -- |
- },- |
- ||
309 | -- |
- #' @description- |
- ||
310 | -- |
- #' Set the input in the module in the `teal` app.+ self$click( |
||
311 | -+ | |||
449 | +! |
- #' This function will only set inputs in the name space of the current active teal module.+ selector = sprintf( |
||
312 | -+ | |||
450 | +! |
- #'+ "#%s-filters-%s-add_filter_icon", |
||
313 | -+ | |||
451 | +! |
- #' @param input_id (character) The shiny input id to get the value from.+ private$ns$filter_panel, |
||
314 | -+ | |||
452 | +! |
- #' @param value The value to set the input to.+ dataset_name |
||
315 | +453 |
- #' @param ... Additional arguments to be passed to `shinytest2::AppDriver$set_inputs`+ ) |
||
316 | +454 |
- #'+ ) |
||
317 | -+ | |||
455 | +! |
- #' @return The `TealAppDriver` object invisibly.+ self$set_input( |
||
318 | -+ | |||
456 | +! |
- set_active_module_input = function(input_id, value, ...) {+ sprintf( |
||
319 | +457 | ! |
- checkmate::check_string(input_id)+ "%s-filters-%s-%s-filter-var_to_add", |
|
320 | +458 | ! |
- checkmate::check_string(value)+ private$ns$filter_panel, |
|
321 | +459 | ! |
- self$set_input(+ dataset_name, |
|
322 | +460 | ! |
- sprintf("%s-%s", self$active_module_ns(), input_id),+ dataset_name+ |
+ |
461 | ++ |
+ ), |
||
323 | +462 | ! |
- value,+ var_name, |
|
324 | +463 |
... |
||
325 | +464 |
) |
||
326 | +465 | ! |
- dots <- rlang::list2(...)+ invisible(self) |
|
327 | -! | +|||
466 | +
- if (!isFALSE(dots[["wait"]])) self$wait_for_idle() # Default behavior is to wait+ }, |
|||
328 | -! | +|||
467 | +
- invisible(self)+ #' @description |
|||
329 | +468 |
- },+ #' Remove an active filter variable of a dataset from the active filter variables panel. |
||
330 | +469 |
- #' @description+ #' |
||
331 | +470 |
- #' Get the active datasets that can be accessed via the filter panel of the current active teal module.+ #' @param dataset_name (character) The name of the dataset to remove the filter variable from. |
||
332 | +471 |
- get_active_filter_vars = function() {+ #' If `NULL`, all the filter variables will be removed. |
||
333 | -! | +|||
472 | +
- displayed_datasets_index <- self$is_visible(+ #' @param var_name (character) The name of the variable to remove from the filter panel. |
|||
334 | -! | +|||
473 | +
- sprintf("#%s-filters-filter_active_vars_contents > span", self$active_filters_ns())+ #' If `NULL`, all the filter variables of the dataset will be removed. |
|||
335 | +474 |
- )+ #' |
||
336 | +475 |
-
+ #' @return The `TealAppDriver` object invisibly.+ |
+ ||
476 | ++ |
+ remove_filter_var = function(dataset_name = NULL, var_name = NULL) { |
||
337 | +477 | ! |
- available_datasets <- self$get_text(+ checkmate::check_string(dataset_name, null.ok = TRUE) |
|
338 | +478 | ! |
- sprintf(+ checkmate::check_string(var_name, null.ok = TRUE) |
|
339 | +479 | ! |
- "#%s-filters-filter_active_vars_contents .filter_panel_dataname",+ if (is.null(dataset_name)) { |
|
340 | +480 | ! |
- self$active_filters_ns()+ remove_selector <- sprintf( |
|
341 | -+ | |||
481 | +! |
- )+ "#%s-active-remove_all_filters", |
||
342 | -+ | |||
482 | +! |
- )+ self$active_filters_ns() |
||
343 | +483 |
-
+ ) |
||
344 | +484 | ! |
- available_datasets[displayed_datasets_index]+ } else if (is.null(var_name)) { |
|
345 | -+ | |||
485 | +! |
- },+ remove_selector <- sprintf( |
||
346 | -+ | |||
486 | +! |
- #' @description+ "#%s-active-%s-remove_filters", |
||
347 | -+ | |||
487 | +! |
- #' Get the active data summary table+ self$active_filters_ns(),+ |
+ ||
488 | +! | +
+ dataset_name |
||
348 | +489 |
- #' @return `data.frame`+ ) |
||
349 | +490 |
- get_active_data_summary_table = function() {+ } else { |
||
350 | +491 | ! |
- summary_table <- rvest::html_table(+ remove_selector <- sprintf( |
|
351 | +492 | ! |
- self$get_html_rvest(self$active_data_summary_element("table")),+ "#%s-active-%s-filter-%s_%s-remove", |
|
352 | +493 | ! |
- fill = TRUE+ self$active_filters_ns(), |
|
353 | +494 | ! |
- )[[1]]+ dataset_name, |
|
354 | -+ | |||
495 | +! |
-
+ dataset_name, |
||
355 | +496 | ! |
- col_names <- unlist(summary_table[1, ], use.names = FALSE)+ var_name |
|
356 | -! | +|||
497 | +
- summary_table <- summary_table[-1, ]+ ) |
|||
357 | -! | +|||
498 | +
- colnames(summary_table) <- col_names+ } |
|||
358 | +499 | ! |
- if (nrow(summary_table) > 0) {+ self$click( |
|
359 | +500 | ! |
- summary_table+ selector = remove_selector |
|
360 | +501 |
- } else {+ ) |
||
361 | +502 | ! |
- NULL+ invisible(self) |
|
362 | +503 |
- }+ }, |
||
363 | +504 |
- },+ #' @description |
||
364 | +505 |
- #' @description+ #' Set the active filter values for a variable of a dataset in the active filter variable panel. |
||
365 | +506 |
- #' Test if `DOM` elements are visible on the page with a JavaScript call.+ #' |
||
366 | +507 |
- #' @param selector (`character(1)`) `CSS` selector to check visibility.+ #' @param dataset_name (character) The name of the dataset to set the filter value for. |
||
367 | +508 |
- #' A `CSS` id will return only one element if the UI is well formed.+ #' @param var_name (character) The name of the variable to set the filter value for. |
||
368 | +509 |
- #' @param content_visibility_auto,opacity_property,visibility_property (`logical(1)`) See more information+ #' @param input The value to set the filter to. |
||
369 | +510 |
- #' on <https://developer.mozilla.org/en-US/docs/Web/API/Element/checkVisibility>.+ #' @param ... Additional arguments to be passed to `shinytest2::AppDriver$set_inputs` |
||
370 | +511 |
#' |
||
371 | +512 |
- #' @return Logical vector with all occurrences of the selector.+ #' @return The `TealAppDriver` object invisibly. |
||
372 | +513 |
- is_visible = function(selector,+ set_active_filter_selection = function(dataset_name, |
||
373 | +514 |
- content_visibility_auto = FALSE,+ var_name, |
||
374 | +515 |
- opacity_property = FALSE,+ input, |
||
375 | +516 |
- visibility_property = FALSE) {- |
- ||
376 | -! | -
- checkmate::assert_string(selector)+ ...) { |
||
377 | +517 | ! |
- checkmate::assert_flag(content_visibility_auto)+ checkmate::check_string(dataset_name) |
|
378 | +518 | ! |
- checkmate::assert_flag(opacity_property)+ checkmate::check_string(var_name) |
|
379 | +519 | ! |
- checkmate::assert_flag(visibility_property)+ checkmate::check_string(input) |
|
380 | +520 | |||
381 | +521 | ! |
- private$wait_for_page_stability()+ input_id_prefix <- sprintf( |
|
382 | -+ | |||
522 | +! |
-
+ "%s-filters-%s-filter-%s_%s-inputs", |
||
383 | +523 | ! |
- testthat::skip_if_not(+ self$active_filters_ns(), |
|
384 | +524 | ! |
- self$get_js("typeof Element.prototype.checkVisibility === 'function'"),+ dataset_name, |
|
385 | +525 | ! |
- "Element.prototype.checkVisibility is not supported in the current browser."+ dataset_name,+ |
+ |
526 | +! | +
+ var_name |
||
386 | +527 |
) |
||
387 | +528 | |||
529 | ++ |
+ # Find the type of filter (based on filter panel)+ |
+ ||
388 | +530 | ! |
- unlist(+ supported_suffix <- c("selection", "selection_manual") |
|
389 | +531 | ! |
- self$get_js(+ slices_suffix <- supported_suffix[ |
|
390 | +532 | ! |
- sprintf(+ match( |
|
391 | +533 | ! |
- "Array.from(document.querySelectorAll('%s')).map(el => el.checkVisibility({%s, %s, %s}))",+ TRUE, |
|
392 | +534 | ! |
- selector,+ vapply( |
|
393 | -+ | |||
535 | +! |
- # Extra parameters+ supported_suffix, |
||
394 | +536 | ! |
- sprintf("contentVisibilityAuto: %s", tolower(content_visibility_auto)),+ function(suffix) { |
|
395 | +537 | ! |
- sprintf("opacityProperty: %s", tolower(opacity_property)),+ !is.null(self$get_html(sprintf("#%s-%s", input_id_prefix, suffix)))+ |
+ |
538 | ++ |
+ }, |
||
396 | +539 | ! |
- sprintf("visibilityProperty: %s", tolower(visibility_property))+ logical(1) |
|
397 | +540 |
) |
||
398 | +541 |
) |
||
399 | +542 |
- )+ ] |
||
400 | +543 |
- },+ |
||
401 | +544 |
- #' @description+ # Generate correct namespace |
||
402 | -+ | |||
545 | +! |
- #' Get the active filter variables from a dataset in the `teal` app.+ slices_input_id <- sprintf( |
||
403 | -+ | |||
546 | +! |
- #'+ "%s-filters-%s-filter-%s_%s-inputs-%s",+ |
+ ||
547 | +! | +
+ self$active_filters_ns(),+ |
+ ||
548 | +! | +
+ dataset_name,+ |
+ ||
549 | +! | +
+ dataset_name,+ |
+ ||
550 | +! | +
+ var_name, |
||
404 | -+ | |||
551 | +! |
- #' @param dataset_name (character) The name of the dataset to get the filter variables from.+ slices_suffix |
||
405 | +552 |
- #' If `NULL`, the filter variables for all the datasets will be returned in a list.+ ) |
||
406 | +553 |
- get_active_data_filters = function(dataset_name = NULL) {+ |
||
407 | +554 | ! |
- checkmate::check_string(dataset_name, null.ok = TRUE)+ if (identical(slices_suffix, "selection_manual")) { |
|
408 | +555 | ! |
- datasets <- self$get_active_filter_vars()+ checkmate::assert_numeric(input, len = 2) |
|
409 | -! | +|||
556 | +
- checkmate::assert_subset(dataset_name, datasets)+ |
|||
410 | +557 | ! |
- active_filters <- lapply(+ dots <- rlang::list2(...) |
|
411 | +558 | ! |
- datasets,+ checkmate::assert_choice(dots$priority_, formals(self$set_inputs)[["priority_"]], null.ok = TRUE) |
|
412 | +559 | ! |
- function(x) {+ checkmate::assert_flag(dots$wait_, null.ok = TRUE) |
|
413 | -! | +|||
560 | +
- var_names <- gsub(+ |
|||
414 | +561 | ! |
- pattern = "\\s",+ self$run_js( |
|
415 | +562 | ! |
- replacement = "",+ sprintf( |
|
416 | +563 | ! |
- self$get_text(+ "Shiny.setInputValue('%s:sw.numericRange', [%f, %f], {priority: '%s'})", |
|
417 | +564 | ! |
- sprintf(+ slices_input_id, |
|
418 | +565 | ! |
- "#%s-filters-%s .filter-card-varname",+ input[[1]], |
|
419 | +566 | ! |
- self$active_filters_ns(),+ input[[2]], |
|
420 | +567 | ! |
- x+ priority_ = ifelse(is.null(dots$priority_), "input", dots$priority_) |
|
421 | +568 |
- )+ ) |
||
422 | +569 |
- )+ ) |
||
423 | +570 |
- )+ |
||
424 | +571 | ! |
- structure(+ if (isTRUE(dots$wait_) || is.null(dots$wait_)) { |
|
425 | +572 | ! |
- lapply(var_names, private$get_active_filter_selection, dataset_name = x),+ self$wait_for_idle( |
|
426 | +573 | ! |
- names = var_names+ timeout = if (is.null(dots$timeout_)) rlang::missing_arg() else dots$timeout_ |
|
427 | +574 |
) |
||
428 | +575 |
} |
||
429 | -+ | |||
576 | +! |
- )+ } else if (identical(slices_suffix, "selection")) { |
||
430 | +577 | ! |
- names(active_filters) <- datasets+ self$set_input( |
|
431 | +578 | ! |
- if (is.null(dataset_name)) {+ slices_input_id, |
|
432 | +579 | ! |
- return(active_filters)+ input, |
|
433 | +580 |
- }+ ... |
||
434 | -! | +|||
581 | +
- active_filters[[dataset_name]]+ ) |
|||
435 | +582 |
- },+ } else {+ |
+ ||
583 | +! | +
+ stop("Filter selection set not supported for this slice.") |
||
436 | +584 |
- #' @description+ } |
||
437 | +585 |
- #' Add a new variable from the dataset to be filtered.+ + |
+ ||
586 | +! | +
+ invisible(self) |
||
438 | +587 |
- #'+ }, |
||
439 | +588 |
- #' @param dataset_name (character) The name of the dataset to add the filter variable to.+ #' @description |
||
440 | +589 |
- #' @param var_name (character) The name of the variable to add to the filter panel.+ #' Extract `html` attribute (found by a `selector`). |
||
441 | +590 |
- #' @param ... Additional arguments to be passed to `shinytest2::AppDriver$set_inputs`+ #' |
||
442 | +591 |
- #'+ #' @param selector (`character(1)`) specifying the selector to be used to get the content of a specific node. |
||
443 | +592 |
- #' @return The `TealAppDriver` object invisibly.+ #' @param attribute (`character(1)`) name of an attribute to retrieve from a node specified by `selector`. |
||
444 | +593 |
- add_filter_var = function(dataset_name, var_name, ...) {+ #' |
||
445 | -! | +|||
594 | +
- checkmate::check_string(dataset_name)+ #' @return The `character` vector. |
|||
446 | -! | +|||
595 | +
- checkmate::check_string(var_name)+ get_attr = function(selector, attribute) { |
|||
447 | +596 | ! |
- private$set_active_ns()+ rvest::html_attr( |
|
448 | +597 | ! |
- self$click(+ rvest::html_nodes(self$get_html_rvest("html"), selector), |
|
449 | +598 | ! |
- selector = sprintf(+ attribute |
|
450 | -! | +|||
599 | +
- "#%s-filters-%s-add_filter_icon",+ ) |
|||
451 | -! | +|||
600 | +
- private$ns$filter_panel,+ }, |
|||
452 | -! | +|||
601 | +
- dataset_name+ #' @description |
|||
453 | +602 |
- )+ #' Wrapper around `get_html` that passes the output directly to `rvest::read_html`. |
||
454 | +603 |
- )+ #' |
||
455 | -! | +|||
604 | +
- self$set_input(+ #' @param selector `(character(1))` passed to `get_html`. |
|||
456 | -! | +|||
605 | +
- sprintf(+ #' |
|||
457 | -! | +|||
606 | +
- "%s-filters-%s-%s-filter-var_to_add",+ #' @return An XML document. |
|||
458 | -! | +|||
607 | +
- private$ns$filter_panel,+ get_html_rvest = function(selector) { |
|||
459 | +608 | ! |
- dataset_name,+ rvest::read_html(self$get_html(selector)) |
|
460 | -! | +|||
609 | +
- dataset_name+ }, |
|||
461 | +610 |
- ),+ #' Wrapper around `get_url()` method that opens the app in the browser. |
||
462 | -! | +|||
611 | +
- var_name,+ #' |
|||
463 | +612 |
- ...+ #' @return Nothing. Opens the underlying teal app in the browser. |
||
464 | +613 |
- )+ open_url = function() { |
||
465 | +614 | ! |
- invisible(self)+ browseURL(self$get_url()) |
|
466 | +615 |
}, |
||
467 | +616 |
#' @description |
||
468 | +617 |
- #' Remove an active filter variable of a dataset from the active filter variables panel.+ #' Waits until a specified input, output, or export value. |
||
469 | +618 |
- #'+ #' This function serves as a wrapper around the `wait_for_value` method, |
||
470 | +619 |
- #' @param dataset_name (character) The name of the dataset to remove the filter variable from.+ #' providing a more flexible interface for waiting on different types of values within the active module namespace. |
||
471 | +620 |
- #' If `NULL`, all the filter variables will be removed.+ #' @param input,output,export A name of an input, output, or export value. |
||
472 | +621 |
- #' @param var_name (character) The name of the variable to remove from the filter panel.+ #' Only one of these parameters may be used. |
||
473 | +622 |
- #' If `NULL`, all the filter variables of the dataset will be removed.+ #' @param ... Must be empty. Allows for parameter expansion. |
||
474 | +623 |
- #'+ #' Parameter with additional value to passed in `wait_for_value`. |
||
475 | +624 |
- #' @return The `TealAppDriver` object invisibly.+ wait_for_active_module_value = function(input = rlang::missing_arg(), |
||
476 | +625 |
- 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()+ output = rlang::missing_arg(), |
||
483 | +626 |
- )- |
- ||
484 | -! | -
- } else if (is.null(var_name)) {- |
- ||
485 | -! | -
- remove_selector <- sprintf(- |
- ||
486 | -! | -
- "#%s-active-%s-remove_filters",+ export = rlang::missing_arg(), |
||
487 | -! | +|||
627 | +
- self$active_filters_ns(),+ ...) { |
|||
488 | +628 | ! |
- dataset_name- |
- |
489 | -- |
- )+ ns <- shiny::NS(self$active_module_ns()) |
||
490 | +629 |
- } else {+ |
||
491 | +630 | ! |
- remove_selector <- sprintf(+ if (!rlang::is_missing(input) && checkmate::test_string(input, min.chars = 1)) input <- ns(input) |
|
492 | +631 | ! |
- "#%s-active-%s-filter-%s_%s-remove",+ if (!rlang::is_missing(output) && checkmate::test_string(output, min.chars = 1)) output <- ns(output) |
|
493 | +632 | ! |
- self$active_filters_ns(),+ if (!rlang::is_missing(export) && checkmate::test_string(export, min.chars = 1)) export <- ns(export) |
|
494 | -! | +|||
633 | +
- dataset_name,+ |
|||
495 | +634 | ! |
- dataset_name,+ self$wait_for_value( |
|
496 | +635 | ! |
- var_name- |
- |
497 | -- |
- )- |
- ||
498 | -- |
- }+ input = input, |
||
499 | +636 | ! |
- self$click(+ output = output, |
|
500 | +637 | ! |
- selector = remove_selector+ export = export, |
|
501 | -- |
- )- |
- ||
502 | -! | +638 | +
- invisible(self)+ ... |
|
503 | +639 |
- },+ ) |
||
504 | +640 |
- #' @description+ } |
||
505 | +641 |
- #' Set the active filter values for a variable of a dataset in the active filter variable panel.+ ), |
||
506 | +642 |
- #'+ # private members ---- |
||
507 | +643 |
- #' @param dataset_name (character) The name of the dataset to set the filter value for.+ private = list( |
||
508 | +644 |
- #' @param var_name (character) The name of the variable to set the filter value for.+ # private attributes ---- |
||
509 | +645 |
- #' @param input The value to set the filter to.+ data = NULL, |
||
510 | +646 |
- #' @param ... Additional arguments to be passed to `shinytest2::AppDriver$set_inputs`+ modules = NULL, |
||
511 | +647 |
- #'+ filter = teal_slices(), |
||
512 | +648 |
- #' @return The `TealAppDriver` object invisibly.+ ns = list( |
||
513 | +649 |
- set_active_filter_selection = function(dataset_name,+ module = character(0), |
||
514 | +650 |
- var_name,+ filter_panel = character(0) |
||
515 | +651 |
- input,+ ), |
||
516 | +652 |
- ...) {+ # private methods ---- |
||
517 | -! | +|||
653 | +
- checkmate::check_string(dataset_name)+ set_active_ns = function() { |
|||
518 | +654 | ! |
- checkmate::check_string(var_name)+ all_inputs <- self$get_values()$input |
|
519 | +655 | ! |
- checkmate::check_string(input)+ active_tab_inputs <- all_inputs[grepl("-active_tab$", names(all_inputs))] |
|
520 | +656 | |||
521 | -! | -
- input_id_prefix <- sprintf(- |
- ||
522 | +657 | ! |
- "%s-filters-%s-filter-%s_%s-inputs",+ tab_ns <- unlist(lapply(names(active_tab_inputs), function(name) { |
|
523 | +658 | ! |
- self$active_filters_ns(),+ gsub( |
|
524 | +659 | ! |
- dataset_name,+ pattern = "-active_tab$", |
|
525 | +660 | ! |
- dataset_name,+ replacement = sprintf("-%s", active_tab_inputs[[name]]), |
|
526 | +661 | ! |
- var_name- |
- |
527 | -- |
- )+ name |
||
528 | +662 |
-
+ ) |
||
529 | +663 |
- # Find the type of filter (based on filter panel)+ })) |
||
530 | +664 | ! |
- supported_suffix <- c("selection", "selection_manual")+ active_ns <- tab_ns[1] |
|
531 | +665 | ! |
- slices_suffix <- supported_suffix[+ if (length(tab_ns) > 1) { |
|
532 | +666 | ! |
- match(+ for (i in 2:length(tab_ns)) { |
|
533 | +667 | ! |
- TRUE,+ next_ns <- tab_ns[i] |
|
534 | +668 | ! |
- vapply(+ if (grepl(pattern = active_ns, next_ns)) { |
|
535 | +669 | ! |
- supported_suffix,+ active_ns <- next_ns |
|
536 | -! | +|||
670 | +
- function(suffix) {+ } |
|||
537 | -! | +|||
671 | +
- !is.null(self$get_html(sprintf("#%s-%s", input_id_prefix, suffix)))+ } |
|||
538 | +672 |
- },+ } |
||
539 | +673 | ! |
- logical(1)- |
- |
540 | -- |
- )+ private$ns$module <- sprintf("%s-%s", active_ns, "module") |
||
541 | +674 |
- )+ |
||
542 | -+ | |||
675 | +! |
- ]+ components <- c("filter_panel", "data_summary") |
||
543 | -+ | |||
676 | +! |
-
+ for (component in components) { |
||
544 | +677 |
- # Generate correct namespace+ if ( |
||
545 | +678 | ! |
- slices_input_id <- sprintf(+ !is.null(self$get_html(sprintf("#%s-%s-panel", active_ns, component))) || |
|
546 | +679 | ! |
- "%s-filters-%s-filter-%s_%s-inputs-%s",+ !is.null(self$get_html(sprintf("#%s-%s-table", active_ns, component))) |
|
547 | -! | +|||
680 | +
- self$active_filters_ns(),+ ) { |
|||
548 | +681 | ! |
- dataset_name,+ private$ns[[component]] <- sprintf("%s-%s", active_ns, component) |
|
549 | -! | +|||
682 | +
- dataset_name,+ } else { |
|||
550 | +683 | ! |
- var_name,+ private$ns[[component]] <- sprintf("%s-module_%s", active_ns, component) |
|
551 | -! | +|||
684 | +
- slices_suffix+ } |
|||
552 | +685 |
- )+ } |
||
553 | +686 |
-
+ }, |
||
554 | -! | +|||
687 | +
- if (identical(slices_suffix, "selection_manual")) {+ # @description |
|||
555 | -! | +|||
688 | +
- checkmate::assert_numeric(input, len = 2)+ # Get the active filter values from the active filter selection of dataset from the filter panel. |
|||
556 | +689 |
-
+ # |
||
557 | -! | +|||
690 | +
- dots <- rlang::list2(...)+ # @param dataset_name (character) The name of the dataset to get the filter values from. |
|||
558 | -! | +|||
691 | +
- checkmate::assert_choice(dots$priority_, formals(self$set_inputs)[["priority_"]], null.ok = TRUE)+ # @param var_name (character) The name of the variable to get the filter values from. |
|||
559 | -! | +|||
692 | +
- checkmate::assert_flag(dots$wait_, null.ok = TRUE)+ # |
|||
560 | +693 |
-
+ # @return The value of the active filter selection. |
||
561 | -! | +|||
694 | +
- self$run_js(+ get_active_filter_selection = function(dataset_name, var_name) { |
|||
562 | +695 | ! |
- sprintf(+ checkmate::check_string(dataset_name) |
|
563 | +696 | ! |
- "Shiny.setInputValue('%s:sw.numericRange', [%f, %f], {priority: '%s'})",+ checkmate::check_string(var_name) |
|
564 | +697 | ! |
- slices_input_id,+ input_id_prefix <- sprintf( |
|
565 | +698 | ! |
- input[[1]],+ "%s-filters-%s-filter-%s_%s-inputs", |
|
566 | +699 | ! |
- input[[2]],+ self$active_filters_ns(), |
|
567 | +700 | ! |
- priority_ = ifelse(is.null(dots$priority_), "input", dots$priority_)- |
- |
568 | -- |
- )- |
- ||
569 | -- |
- )- |
- ||
570 | -- |
-
+ dataset_name, |
||
571 | +701 | ! |
- if (isTRUE(dots$wait_) || is.null(dots$wait_)) {+ dataset_name, |
|
572 | +702 | ! |
- self$wait_for_idle(+ var_name |
|
573 | -! | +|||
703 | +
- timeout = if (is.null(dots$timeout_)) rlang::missing_arg() else dots$timeout_+ ) |
|||
574 | +704 |
- )+ |
||
575 | +705 |
- }+ # Find the type of filter (categorical or range) |
||
576 | +706 | ! |
- } else if (identical(slices_suffix, "selection")) {+ supported_suffix <- c("selection", "selection_manual") |
|
577 | +707 | ! |
- self$set_input(+ for (suffix in supported_suffix) { |
|
578 | +708 | ! |
- slices_input_id,+ if (!is.null(self$get_html(sprintf("#%s-%s", input_id_prefix, suffix)))) { |
|
579 | +709 | ! |
- input,+ return(self$get_value(input = sprintf("%s-%s", input_id_prefix, suffix))) |
|
580 | +710 |
- ...+ } |
||
581 | +711 |
- )+ } |
||
582 | +712 |
- } else {+ |
||
583 | +713 | ! |
- stop("Filter selection set not supported for this slice.")+ NULL # If there are not any supported filters |
|
584 | +714 |
- }+ }, |
||
585 | +715 |
-
+ # @description |
||
586 | -! | +|||
716 | +
- invisible(self)+ # Check if the page is stable without any `DOM` updates in the body of the app. |
|||
587 | +717 |
- },+ # This is achieved by blocing the R process by sleeping until the page is unchanged till the `stability_period`. |
||
588 | +718 |
- #' @description+ # @param stability_period (`numeric(1)`) The time in milliseconds to wait till the page to be stable. |
||
589 | +719 |
- #' Extract `html` attribute (found by a `selector`).+ # @param check_interval (`numeric(1)`) The time in milliseconds to check for changes in the page. |
||
590 | +720 |
- #'+ # The stability check is reset when a change is detected in the page after sleeping for check_interval. |
||
591 | +721 |
- #' @param selector (`character(1)`) specifying the selector to be used to get the content of a specific node.+ wait_for_page_stability = function(stability_period = 2000, check_interval = 200) { |
||
592 | -+ | |||
722 | +! |
- #' @param attribute (`character(1)`) name of an attribute to retrieve from a node specified by `selector`.+ previous_content <- self$get_html("body") |
||
593 | -+ | |||
723 | +! |
- #'+ end_time <- Sys.time() + (stability_period / 1000) |
||
594 | +724 |
- #' @return The `character` vector.+ + |
+ ||
725 | +! | +
+ repeat {+ |
+ ||
726 | +! | +
+ Sys.sleep(check_interval / 1000)+ |
+ ||
727 | +! | +
+ current_content <- self$get_html("body") |
||
595 | +728 |
- get_attr = function(selector, attribute) {+ |
||
596 | +729 | ! |
- rvest::html_attr(+ if (!identical(previous_content, current_content)) { |
|
597 | +730 | ! |
- rvest::html_nodes(self$get_html_rvest("html"), selector),+ previous_content <- current_content |
|
598 | +731 | ! |
- attribute+ end_time <- Sys.time() + (stability_period / 1000) |
|
599 | -+ | |||
732 | +! |
- )+ } else if (Sys.time() >= end_time) { |
||
600 | -+ | |||
733 | +! |
- },+ break |
||
601 | +734 |
- #' @description+ } |
||
602 | +735 |
- #' Wrapper around `get_html` that passes the output directly to `rvest::read_html`.+ } |
||
603 | +736 |
- #'+ } |
||
604 | +737 |
- #' @param selector `(character(1))` passed to `get_html`.+ ) |
||
605 | +738 |
- #'+ ) |
606 | +1 |
- #' @return An XML document.+ #' Create a `teal` module for previewing a report |
|
607 | +2 |
- get_html_rvest = function(selector) {- |
- |
608 | -! | -
- rvest::read_html(self$get_html(selector))+ #' |
|
609 | +3 |
- },+ #' @description `r lifecycle::badge("experimental")` |
|
610 | +4 |
- #' Wrapper around `get_url()` method that opens the app in the browser.+ #' |
|
611 | +5 |
- #'+ #' This function wraps [teal.reporter::reporter_previewer_ui()] and |
|
612 | +6 |
- #' @return Nothing. Opens the underlying teal app in the browser.+ #' [teal.reporter::reporter_previewer_srv()] into a `teal_module` to be |
|
613 | +7 |
- open_url = function() {- |
- |
614 | -! | -
- browseURL(self$get_url())+ #' used in `teal` applications. |
|
615 | +8 |
- },+ #' |
|
616 | +9 |
- #' @description+ #' If you are creating a `teal` application using [init()] then this |
|
617 | +10 |
- #' Waits until a specified input, output, or export value.+ #' module will be added to your application automatically if any of your `teal_modules` |
|
618 | +11 |
- #' This function serves as a wrapper around the `wait_for_value` method,+ #' support report generation. |
|
619 | +12 |
- #' providing a more flexible interface for waiting on different types of values within the active module namespace.+ #' |
|
620 | +13 |
- #' @param input,output,export A name of an input, output, or export value.+ #' @inheritParams teal_modules |
|
621 | +14 |
- #' Only one of these parameters may be used.+ #' @param server_args (named `list`) |
|
622 | +15 |
- #' @param ... Must be empty. Allows for parameter expansion.+ #' Arguments passed to [teal.reporter::reporter_previewer_srv()]. |
|
623 | +16 |
- #' Parameter with additional value to passed in `wait_for_value`.+ #' |
|
624 | +17 |
- wait_for_active_module_value = function(input = rlang::missing_arg(),+ #' @return |
|
625 | +18 |
- output = rlang::missing_arg(),+ #' `teal_module` (extended with `teal_module_previewer` class) containing the `teal.reporter` previewer functionality. |
|
626 | +19 |
- export = rlang::missing_arg(),+ #' |
|
627 | +20 |
- ...) {+ #' @export |
|
628 | -! | +||
21 | +
- ns <- shiny::NS(self$active_module_ns())+ #' |
||
629 | +22 |
-
+ reporter_previewer_module <- function(label = "Report previewer", server_args = list()) { |
|
630 | -! | +||
23 | +7x |
- if (!rlang::is_missing(input) && checkmate::test_string(input, min.chars = 1)) input <- ns(input)+ checkmate::assert_string(label) |
|
631 | -! | +||
24 | +5x |
- if (!rlang::is_missing(output) && checkmate::test_string(output, min.chars = 1)) output <- ns(output)+ checkmate::assert_list(server_args, names = "named") |
|
632 | -! | +||
25 | +5x |
- if (!rlang::is_missing(export) && checkmate::test_string(export, min.chars = 1)) export <- ns(export)+ checkmate::assert_true(all(names(server_args) %in% names(formals(teal.reporter::reporter_previewer_srv)))) |
|
633 | +26 | ||
634 | -! | +||
27 | +3x |
- self$wait_for_value(+ message("Initializing reporter_previewer_module") |
|
635 | -! | +||
28 | +
- input = input,+ |
||
636 | -! | +||
29 | +3x |
- output = output,+ srv <- function(id, reporter, ...) { |
|
637 | +30 | ! |
- export = export,- |
-
638 | -- |
- ...+ teal.reporter::reporter_previewer_srv(id, reporter, ...) |
|
639 | +31 |
- )+ } |
|
640 | +32 |
- }+ |
|
641 | -+ | ||
33 | +3x |
- ),+ ui <- function(id, ...) { |
|
642 | -+ | ||
34 | +! |
- # private members ----+ teal.reporter::reporter_previewer_ui(id, ...) |
|
643 | +35 |
- private = list(+ } |
|
644 | +36 |
- # private attributes ----+ |
|
645 | -+ | ||
37 | +3x |
- data = NULL,+ module <- module( |
|
646 | -+ | ||
38 | +3x |
- modules = NULL,+ label = "temporary label", |
|
647 | -+ | ||
39 | +3x |
- filter = teal_slices(),+ server = srv, ui = ui, |
|
648 | -+ | ||
40 | +3x |
- ns = list(+ server_args = server_args, ui_args = list(), datanames = NULL |
|
649 | +41 |
- module = character(0),+ ) |
|
650 | +42 |
- filter_panel = character(0)+ # Module is created with a placeholder label and the label is changed later. |
|
651 | +43 |
- ),+ # This is to prevent another module being labeled "Report previewer". |
|
652 | -+ | ||
44 | +3x |
- # private methods ----+ class(module) <- c(class(module), "teal_module_previewer") |
|
653 | -+ | ||
45 | +3x |
- set_active_ns = function() {+ module$label <- label |
|
654 | -! | +||
46 | +3x |
- all_inputs <- self$get_values()$input+ attr(module, "teal_bookmarkable") <- TRUE |
|
655 | -! | +||
47 | +3x |
- active_tab_inputs <- all_inputs[grepl("-active_tab$", names(all_inputs))]+ module |
|
656 | +48 | - - | -|
657 | -! | -
- tab_ns <- unlist(lapply(names(active_tab_inputs), function(name) {- |
- |
658 | -! | -
- gsub(- |
- |
659 | -! | -
- pattern = "-active_tab$",- |
- |
660 | -! | -
- replacement = sprintf("-%s", active_tab_inputs[[name]]),- |
- |
661 | -! | -
- name+ } |
662 | +1 |
- )+ # This is the main function from teal to be used by the end-users. Although it delegates |
|
663 | +2 |
- }))- |
- |
664 | -! | -
- active_ns <- tab_ns[1]+ # directly to `module_teal_with_splash.R`, we keep it in a separate file because its documentation is quite large |
|
665 | -! | +||
3 | +
- if (length(tab_ns) > 1) {+ # and it is very end-user oriented. It may also perform more argument checking with more informative |
||
666 | -! | +||
4 | +
- for (i in 2:length(tab_ns)) {+ # error messages. |
||
667 | -! | +||
5 | +
- next_ns <- tab_ns[i]+ |
||
668 | -! | +||
6 | +
- if (grepl(pattern = active_ns, next_ns)) {+ #' Create the server and UI function for the `shiny` app |
||
669 | -! | +||
7 | +
- active_ns <- next_ns+ #' |
||
670 | +8 |
- }+ #' @description `r lifecycle::badge("stable")` |
|
671 | +9 |
- }+ #' |
|
672 | +10 |
- }+ #' End-users: This is the most important function for you to start a |
|
673 | -! | +||
11 | +
- private$ns$module <- sprintf("%s-%s", active_ns, "module")+ #' `teal` app that is composed of `teal` modules. |
||
674 | +12 |
-
+ #' |
|
675 | -! | +||
13 | +
- components <- c("filter_panel", "data_summary")+ #' @param data (`teal_data` or `teal_data_module`) |
||
676 | -! | +||
14 | +
- for (component in components) {+ #' For constructing the data object, refer to [teal.data::teal_data()] and [teal_data_module()]. |
||
677 | +15 |
- if (+ #' If `datanames` are not set for the `teal_data` object, defaults from the `teal_data` environment will be used. |
|
678 | -! | +||
16 | +
- !is.null(self$get_html(sprintf("#%s-%s-panel", active_ns, component))) ||+ #' @param modules (`list` or `teal_modules` or `teal_module`) |
||
679 | -! | +||
17 | +
- !is.null(self$get_html(sprintf("#%s-%s-table", active_ns, component)))+ #' Nested list of `teal_modules` or `teal_module` objects or a single |
||
680 | +18 |
- ) {+ #' `teal_modules` or `teal_module` object. These are the specific output modules which |
|
681 | -! | +||
19 | +
- private$ns[[component]] <- sprintf("%s-%s", active_ns, component)+ #' will be displayed in the `teal` application. See [modules()] and [module()] for |
||
682 | +20 |
- } else {+ #' more details. |
|
683 | -! | +||
21 | +
- private$ns[[component]] <- sprintf("%s-module_%s", active_ns, component)+ #' @param filter (`teal_slices`) Optionally, |
||
684 | +22 |
- }+ #' specifies the initial filter using [teal_slices()]. |
|
685 | +23 |
- }+ #' @param title (`shiny.tag` or `character(1)`) Optionally, |
|
686 | +24 |
- },+ #' the browser window title. Defaults to a title "teal app" with the icon of NEST. |
|
687 | +25 |
- # @description+ #' Can be created using the `build_app_title()` or |
|
688 | +26 |
- # Get the active filter values from the active filter selection of dataset from the filter panel.+ #' by passing a valid `shiny.tag` which is a head tag with title and link tag. |
|
689 | +27 |
- #+ #' @param header (`shiny.tag` or `character(1)`) Optionally, |
|
690 | +28 |
- # @param dataset_name (character) The name of the dataset to get the filter values from.+ #' the header of the app. |
|
691 | +29 |
- # @param var_name (character) The name of the variable to get the filter values from.+ #' @param footer (`shiny.tag` or `character(1)`) Optionally, |
|
692 | +30 |
- #+ #' the footer of the app. |
|
693 | +31 |
- # @return The value of the active filter selection.+ #' @param id (`character`) Optionally, |
|
694 | +32 |
- get_active_filter_selection = function(dataset_name, var_name) {+ #' a string specifying the `shiny` module id in cases it is used as a `shiny` module |
|
695 | -! | +||
33 | +
- checkmate::check_string(dataset_name)+ #' rather than a standalone `shiny` app. This is a legacy feature. |
||
696 | -! | +||
34 | +
- checkmate::check_string(var_name)+ #' @param landing_popup (`teal_module_landing`) Optionally, |
||
697 | -! | +||
35 | +
- input_id_prefix <- sprintf(+ #' a `landing_popup_module` to show up as soon as the teal app is initialized. |
||
698 | -! | +||
36 | +
- "%s-filters-%s-filter-%s_%s-inputs",+ #' |
||
699 | -! | +||
37 | +
- self$active_filters_ns(),+ #' @return Named list containing server and UI functions. |
||
700 | -! | +||
38 | +
- dataset_name,+ #' |
||
701 | -! | +||
39 | +
- dataset_name,+ #' @export |
||
702 | -! | +||
40 | +
- var_name+ #' |
||
703 | +41 |
- )+ #' @include modules.R |
|
704 | +42 |
-
+ #' |
|
705 | +43 |
- # Find the type of filter (categorical or range)+ #' @examples |
|
706 | -! | +||
44 | +
- supported_suffix <- c("selection", "selection_manual")+ #' app <- init( |
||
707 | -! | +||
45 | +
- for (suffix in supported_suffix) {+ #' data = within( |
||
708 | -! | +||
46 | +
- if (!is.null(self$get_html(sprintf("#%s-%s", input_id_prefix, suffix)))) {+ #' teal_data(), |
||
709 | -! | +||
47 | +
- return(self$get_value(input = sprintf("%s-%s", input_id_prefix, suffix)))+ #' { |
||
710 | +48 |
- }+ #' new_iris <- transform(iris, id = seq_len(nrow(iris))) |
|
711 | +49 |
- }+ #' new_mtcars <- transform(mtcars, id = seq_len(nrow(mtcars))) |
|
712 | +50 |
-
+ #' } |
|
713 | -! | +||
51 | +
- NULL # If there are not any supported filters+ #' ), |
||
714 | +52 |
- },+ #' modules = modules( |
|
715 | +53 |
- # @description+ #' module( |
|
716 | +54 |
- # Check if the page is stable without any `DOM` updates in the body of the app.+ #' label = "data source", |
|
717 | +55 |
- # This is achieved by blocing the R process by sleeping until the page is unchanged till the `stability_period`.+ #' server = function(input, output, session, data) {}, |
|
718 | +56 |
- # @param stability_period (`numeric(1)`) The time in milliseconds to wait till the page to be stable.+ #' ui = function(id, ...) tags$div(p("information about data source")), |
|
719 | +57 |
- # @param check_interval (`numeric(1)`) The time in milliseconds to check for changes in the page.+ #' datanames = "all" |
|
720 | +58 |
- # The stability check is reset when a change is detected in the page after sleeping for check_interval.+ #' ), |
|
721 | +59 |
- wait_for_page_stability = function(stability_period = 2000, check_interval = 200) {+ #' example_module(label = "example teal module"), |
|
722 | -! | +||
60 | +
- previous_content <- self$get_html("body")+ #' module( |
||
723 | -! | +||
61 | +
- end_time <- Sys.time() + (stability_period / 1000)+ #' "Iris Sepal.Length histogram", |
||
724 | +62 |
-
+ #' server = function(input, output, session, data) { |
|
725 | -! | +||
63 | +
- repeat {+ #' output$hist <- renderPlot( |
||
726 | -! | +||
64 | +
- Sys.sleep(check_interval / 1000)+ #' hist(data()[["new_iris"]]$Sepal.Length) |
||
727 | -! | +||
65 | +
- current_content <- self$get_html("body")+ #' ) |
||
728 | +66 |
-
+ #' }, |
|
729 | -! | +||
67 | +
- if (!identical(previous_content, current_content)) {+ #' ui = function(id, ...) { |
||
730 | -! | +||
68 | +
- previous_content <- current_content+ #' ns <- NS(id) |
||
731 | -! | +||
69 | +
- end_time <- Sys.time() + (stability_period / 1000)+ #' plotOutput(ns("hist")) |
||
732 | -! | +||
70 | +
- } else if (Sys.time() >= end_time) {+ #' }, |
||
733 | -! | +||
71 | +
- break+ #' datanames = "new_iris" |
||
734 | +72 |
- }+ #' ) |
|
735 | +73 |
- }+ #' ), |
|
736 | +74 |
- }+ #' filter = teal_slices( |
|
737 | +75 |
- )+ #' teal_slice(dataname = "new_iris", varname = "Species"), |
|
738 | +76 |
- )+ #' teal_slice(dataname = "new_iris", varname = "Sepal.Length"), |
1 | +77 |
- #' Landing popup module+ #' teal_slice(dataname = "new_mtcars", varname = "cyl"), |
|
2 | +78 |
- #'+ #' exclude_varnames = list(new_iris = c("Sepal.Width", "Petal.Width")), |
|
3 | +79 |
- #' @description Creates a landing welcome popup for `teal` applications.+ #' module_specific = TRUE, |
|
4 | +80 |
- #'+ #' mapping = list( |
|
5 | +81 |
- #' This module is used to display a popup dialog when the application starts.+ #' `example teal module` = "new_iris Species", |
|
6 | +82 |
- #' The dialog blocks access to the application and must be closed with a button before the application can be viewed.+ #' `Iris Sepal.Length histogram` = "new_iris Species", |
|
7 | +83 |
- #'+ #' global_filters = "new_mtcars cyl" |
|
8 | +84 |
- #' @param label (`character(1)`) Label of the module.+ #' ) |
|
9 | +85 |
- #' @param title (`character(1)`) Text to be displayed as popup title.+ #' ), |
|
10 | +86 |
- #' @param content (`character(1)`, `shiny.tag` or `shiny.tag.list`) with the content of the popup.+ #' title = "App title", |
|
11 | +87 |
- #' Passed to `...` of `shiny::modalDialog`. See examples.+ #' header = tags$h1("Sample App"), |
|
12 | +88 |
- #' @param buttons (`shiny.tag` or `shiny.tag.list`) Typically a `modalButton` or `actionButton`. See examples.+ #' footer = tags$p("Sample footer") |
|
13 | +89 |
- #'+ #' ) |
|
14 | +90 |
- #' @return A `teal_module` (extended with `teal_landing_module` class) to be used in `teal` applications.+ #' if (interactive()) { |
|
15 | +91 |
- #'+ #' shinyApp(app$ui, app$server) |
|
16 | +92 |
- #' @examples+ #' } |
|
17 | +93 |
- #' app1 <- init(+ #' |
|
18 | +94 |
- #' data = teal_data(iris = iris),+ init <- function(data, |
|
19 | +95 |
- #' modules = modules(+ modules, |
|
20 | +96 |
- #' example_module()+ filter = teal_slices(), |
|
21 | +97 |
- #' ),+ title = build_app_title(), |
|
22 | +98 |
- #' landing_popup = landing_popup_module(+ header = tags$p(), |
|
23 | +99 |
- #' content = "A place for the welcome message or a disclaimer statement.",+ footer = tags$p(), |
|
24 | +100 |
- #' buttons = modalButton("Proceed")+ id = character(0), |
|
25 | +101 |
- #' )+ landing_popup = NULL) { |
|
26 | -+ | ||
102 | +14x |
- #' )+ logger::log_debug("init initializing teal app with: data ('{ class(data) }').") |
|
27 | +103 |
- #' if (interactive()) {+ |
|
28 | +104 |
- #' shinyApp(app1$ui, app1$server)+ # argument checking (independent) |
|
29 | +105 |
- #' }+ ## `data` |
|
30 | -+ | ||
106 | +14x |
- #'+ checkmate::assert_multi_class(data, c("teal_data", "teal_data_module")) |
|
31 | -+ | ||
107 | +14x |
- #' app2 <- init(+ checkmate::assert_class(landing_popup, "teal_module_landing", null.ok = TRUE) |
|
32 | +108 |
- #' data = teal_data(iris = iris),+ |
|
33 | +109 |
- #' modules = modules(+ ## `modules` |
|
34 | -+ | ||
110 | +14x |
- #' example_module()+ checkmate::assert( |
|
35 | -+ | ||
111 | +14x |
- #' ),+ .var.name = "modules", |
|
36 | -+ | ||
112 | +14x |
- #' landing_popup = landing_popup_module(+ checkmate::check_multi_class(modules, c("teal_modules", "teal_module")), |
|
37 | -+ | ||
113 | +14x |
- #' title = "Welcome",+ checkmate::check_list(modules, min.len = 1, any.missing = FALSE, types = c("teal_module", "teal_modules")) |
|
38 | +114 |
- #' content = tags$b(+ ) |
|
39 | -+ | ||
115 | +14x |
- #' "A place for the welcome message or a disclaimer statement.",+ if (inherits(modules, "teal_module")) { |
|
40 | -+ | ||
116 | +1x |
- #' style = "color: red;"+ modules <- list(modules) |
|
41 | +117 |
- #' ),+ } |
|
42 | -+ | ||
118 | +14x |
- #' buttons = tagList(+ if (checkmate::test_list(modules, min.len = 1, any.missing = FALSE, types = c("teal_module", "teal_modules"))) { |
|
43 | -+ | ||
119 | +8x |
- #' modalButton("Proceed"),+ modules <- do.call(teal::modules, modules) |
|
44 | +120 |
- #' actionButton("read", "Read more",+ } |
|
45 | +121 |
- #' onclick = "window.open('http://google.com', '_blank')"+ |
|
46 | +122 |
- #' ),+ ## `filter` |
|
47 | -+ | ||
123 | +14x |
- #' actionButton("close", "Reject", onclick = "window.close()")+ checkmate::assert_class(filter, "teal_slices") |
|
48 | +124 |
- #' )+ |
|
49 | +125 |
- #' )+ ## all other arguments |
|
50 | -+ | ||
126 | +13x |
- #' )+ checkmate::assert( |
|
51 | -+ | ||
127 | +13x |
- #'+ .var.name = "title", |
|
52 | -+ | ||
128 | +13x |
- #' if (interactive()) {+ checkmate::check_string(title), |
|
53 | -+ | ||
129 | +13x |
- #' shinyApp(app2$ui, app2$server)+ checkmate::check_multi_class(title, c("shiny.tag", "shiny.tag.list", "html")) |
|
54 | +130 |
- #' }+ ) |
|
55 | -+ | ||
131 | +13x |
- #'+ checkmate::assert( |
|
56 | -+ | ||
132 | +13x |
- #' @export+ .var.name = "header", |
|
57 | -+ | ||
133 | +13x |
- landing_popup_module <- function(label = "Landing Popup",+ checkmate::check_string(header), |
|
58 | -+ | ||
134 | +13x |
- title = NULL,+ checkmate::check_multi_class(header, c("shiny.tag", "shiny.tag.list", "html")) |
|
59 | +135 |
- content = NULL,+ ) |
|
60 | -+ | ||
136 | +13x |
- buttons = modalButton("Accept")) {+ checkmate::assert( |
|
61 | -! | +||
137 | +13x |
- checkmate::assert_string(label)+ .var.name = "footer", |
|
62 | -! | +||
138 | +13x |
- checkmate::assert_string(title, null.ok = TRUE)+ checkmate::check_string(footer), |
|
63 | -! | +||
139 | +13x |
- checkmate::assert_multi_class(+ checkmate::check_multi_class(footer, c("shiny.tag", "shiny.tag.list", "html")) |
|
64 | -! | +||
140 | +
- content,+ ) |
||
65 | -! | +||
141 | +13x |
- classes = c("character", "shiny.tag", "shiny.tag.list", "html"), null.ok = TRUE+ checkmate::assert_character(id, max.len = 1, any.missing = FALSE) |
|
66 | +142 |
- )+ |
|
67 | -! | +||
143 | +
- checkmate::assert_multi_class(buttons, classes = c("shiny.tag", "shiny.tag.list"))+ # log+ |
+ ||
144 | +13x | +
+ teal.logger::log_system_info() |
|
68 | +145 | ||
69 | -! | +||
146 | +
- message("Initializing landing_popup_module")+ # argument transformations |
||
70 | +147 |
-
+ ## `modules` - landing module |
|
71 | -! | +||
148 | +13x |
- module <- module(+ landing <- extract_module(modules, "teal_module_landing") |
|
72 | -! | +||
149 | +13x |
- label = label,+ if (length(landing) == 1L) { |
|
73 | +150 | ! |
- server = function(id) {+ landing_popup <- landing[[1L]] |
74 | +151 | ! |
- moduleServer(id, function(input, output, session) {+ modules <- drop_module(modules, "teal_module_landing") |
75 | +152 | ! |
- showModal(+ lifecycle::deprecate_soft( |
76 | +153 | ! |
- modalDialog(+ when = "0.15.3", |
77 | +154 | ! |
- id = "landingpopup",+ what = "landing_popup_module()", |
78 | +155 | ! |
- title = title,+ details = paste( |
79 | +156 | ! |
- content,+ "Pass `landing_popup_module` to the `landing_popup` argument of the `init` ", |
80 | +157 | ! |
- footer = buttons+ "instead of wrapping it into `modules()` and passing to the `modules` argument" |
81 | +158 |
- )+ ) |
|
82 | +159 |
- )+ ) |
|
83 | -+ | ||
160 | +13x |
- })+ } else if (length(landing) > 1L) {+ |
+ |
161 | +! | +
+ stop("Only one `landing_popup_module` can be used.") |
|
84 | +162 |
- }+ } |
|
85 | +163 |
- )+ |
|
86 | -! | +||
164 | +
- class(module) <- c("teal_module_landing", class(module))+ ## `filter` - set app_id attribute unless present (when restoring bookmark) |
||
87 | -! | +||
165 | +13x |
- module+ if (is.null(attr(filter, "app_id", exact = TRUE))) attr(filter, "app_id") <- create_app_id(data, modules) |
|
88 | +166 |
- }+ |
1 | +167 |
- #' App state management.+ ## `filter` - convert teal.slice::teal_slices to teal::teal_slices |
||
2 | -+ | |||
168 | +13x |
- #'+ filter <- as.teal_slices(as.list(filter)) |
||
3 | +169 |
- #' @description+ |
||
4 | +170 |
- #' `r lifecycle::badge("experimental")`+ # argument checking (interdependent) |
||
5 | +171 |
- #'+ ## `filter` - `modules` |
||
6 | -+ | |||
172 | +13x |
- #' Capture and restore the global (app) input state.+ if (isTRUE(attr(filter, "module_specific"))) { |
||
7 | -+ | |||
173 | +! |
- #'+ module_names <- unlist(c(module_labels(modules), "global_filters")) |
||
8 | -+ | |||
174 | +! |
- #' @details+ failed_mod_names <- setdiff(names(attr(filter, "mapping")), module_names) |
||
9 | -+ | |||
175 | +! |
- #' This module introduces bookmarks into `teal` apps: the `shiny` bookmarking mechanism becomes enabled+ if (length(failed_mod_names)) { |
||
10 | -+ | |||
176 | +! |
- #' and server-side bookmarks can be created.+ stop( |
||
11 | -+ | |||
177 | +! |
- #'+ sprintf( |
||
12 | -+ | |||
178 | +! |
- #' The bookmark manager presents a button with the bookmark icon and is placed in the tab-bar.+ "Some module names in the mapping arguments don't match module labels.\n %s not in %s", |
||
13 | -+ | |||
179 | +! |
- #' When clicked, the button creates a bookmark and opens a modal which displays the bookmark URL.+ toString(failed_mod_names), |
||
14 | -+ | |||
180 | +! |
- #'+ toString(unique(module_names)) |
||
15 | +181 |
- #' `teal` does not guarantee that all modules (`teal_module` objects) are bookmarkable.+ ) |
||
16 | +182 |
- #' Those that are, have a `teal_bookmarkable` attribute set to `TRUE`. If any modules are not bookmarkable,+ ) |
||
17 | +183 |
- #' the bookmark manager modal displays a warning and the bookmark button displays a flag.+ } |
||
18 | +184 |
- #' In order to communicate that a external module is bookmarkable, the module developer+ |
||
19 | -+ | |||
185 | +! |
- #' should set the `teal_bookmarkable` attribute to `TRUE`.+ if (anyDuplicated(module_names)) { |
||
20 | +186 |
- #'+ # In teal we are able to set nested modules with duplicated label. |
||
21 | +187 |
- #' @section Server logic:+ # Because mapping argument bases on the relationship between module-label and filter-id, |
||
22 | +188 |
- #' A bookmark is a URL that contains the app address with a `/?_state_id_=<bookmark_dir>` suffix.+ # it is possible that module-label in mapping might refer to multiple teal_module (identified by the same label) |
||
23 | -+ | |||
189 | +! |
- #' `<bookmark_dir>` is a directory created on the server, where the state of the application is saved.+ stop( |
||
24 | -+ | |||
190 | +! |
- #' Accessing the bookmark URL opens a new session of the app that starts in the previously saved state.+ sprintf( |
||
25 | -+ | |||
191 | +! |
- #'+ "Module labels should be unique when teal_slices(mapping = TRUE). Duplicated labels:\n%s ", |
||
26 | -+ | |||
192 | +! |
- #' @section Note:+ toString(module_names[duplicated(module_names)]) |
||
27 | +193 |
- #' To enable bookmarking use either:+ ) |
||
28 | +194 |
- #' - `shiny` app by using `shinyApp(..., enableBookmarking = "server")` (not supported in `shinytest2`)+ ) |
||
29 | +195 |
- #' - set `options(shiny.bookmarkStore = "server")` before running the app+ } |
||
30 | +196 |
- #'+ } |
||
31 | +197 |
- #'+ |
||
32 | +198 |
- #' @inheritParams init+ ## `data` - `modules` |
||
33 | -+ | |||
199 | +13x |
- #'+ if (inherits(data, "teal_data")) {+ |
+ ||
200 | +12x | +
+ if (length(data) == 0) {+ |
+ ||
201 | +1x | +
+ stop("The environment of `data` is empty.") |
||
34 | +202 |
- #' @return Invisible `NULL`.+ } |
||
35 | +203 |
- #'+ + |
+ ||
204 | +11x | +
+ is_modules_ok <- check_modules_datanames(modules, names(data))+ |
+ ||
205 | +11x | +
+ if (!isTRUE(is_modules_ok) && length(unlist(extract_transformators(modules))) == 0) { |
||
36 | -+ | |||
206 | +4x |
- #' @aliases bookmark bookmark_manager bookmark_manager_module+ warning(is_modules_ok, call. = FALSE) |
||
37 | +207 |
- #'+ } |
||
38 | +208 |
- #' @name module_bookmark_manager+ |
||
39 | -+ | |||
209 | +11x |
- #' @rdname module_bookmark_manager+ is_filter_ok <- check_filter_datanames(filter, names(data)) |
||
40 | -+ | |||
210 | +11x |
- #'+ if (!isTRUE(is_filter_ok)) { |
||
41 | -+ | |||
211 | +1x |
- #' @keywords internal+ warning(is_filter_ok) |
||
42 | +212 |
- #'+ # we allow app to continue if applied filters are outside |
||
43 | +213 |
- NULL+ # of possible data range |
||
44 | +214 |
-
+ } |
||
45 | +215 |
- #' @rdname module_bookmark_manager+ } |
||
46 | +216 |
- ui_bookmark_panel <- function(id, modules) {+ |
||
47 | -! | +|||
217 | +12x |
- ns <- NS(id)+ reporter <- teal.reporter::Reporter$new()$set_id(attr(filter, "app_id")) |
||
48 | -+ | |||
218 | +12x |
-
+ if (is_arg_used(modules, "reporter") && length(extract_module(modules, "teal_module_previewer")) == 0) { |
||
49 | +219 | ! |
- bookmark_option <- get_bookmarking_option()+ modules <- append_module( |
|
50 | +220 | ! |
- is_unbookmarkable <- need_bookmarking(modules)+ modules, |
|
51 | +221 | ! |
- shinyOptions(bookmarkStore = bookmark_option)+ reporter_previewer_module(server_args = list(previewer_buttons = c("download", "reset"))) |
|
52 | +222 |
-
+ ) |
||
53 | +223 |
- # Render bookmark warnings count+ } |
||
54 | -! | +|||
224 | +
- if (!all(is_unbookmarkable) && identical(bookmark_option, "server")) {+ |
|||
55 | -! | +|||
225 | +12x |
- tags$button(+ ns <- NS(id) |
||
56 | -! | +|||
226 | +
- id = ns("do_bookmark"),+ # Note: UI must be a function to support bookmarking. |
|||
57 | -! | +|||
227 | +12x |
- class = "btn action-button wunder_bar_button bookmark_manager_button",+ res <- list( |
||
58 | -! | +|||
228 | +12x |
- title = "Add bookmark",+ ui = function(request) { |
||
59 | +229 | ! |
- tags$span(+ ui_teal( |
|
60 | +230 | ! |
- suppressMessages(icon("fas fa-bookmark")),+ id = ns("teal"), |
|
61 | +231 | ! |
- if (any(is_unbookmarkable)) {+ modules = modules, |
|
62 | +232 | ! |
- tags$span(+ title = title, |
|
63 | +233 | ! |
- sum(is_unbookmarkable),+ header = header, |
|
64 | +234 | ! |
- class = "badge-warning badge-count text-white bg-danger"+ footer = footer |
|
65 | +235 |
- )+ ) |
||
66 | +236 |
- }+ }, |
||
67 | -+ | |||
237 | +12x |
- )+ server = function(input, output, session) { |
||
68 | -+ | |||
238 | +! |
- )+ if (!is.null(landing_popup)) { |
||
69 | -+ | |||
239 | +! |
- }+ do.call(landing_popup$server, c(list(id = "landing_module_shiny_id"), landing_popup$server_args)) |
||
70 | +240 |
- }+ }+ |
+ ||
241 | +! | +
+ srv_teal(id = ns("teal"), data = data, modules = modules, filter = deep_copy_filter(filter)) |
||
71 | +242 |
-
+ } |
||
72 | +243 |
- #' @rdname module_bookmark_manager+ ) |
||
73 | +244 |
- srv_bookmark_panel <- function(id, modules) {+ |
||
74 | -87x | +245 | +12x |
- checkmate::assert_character(id)+ logger::log_debug("init teal app has been initialized.") |
75 | -87x | +|||
246 | +
- checkmate::assert_class(modules, "teal_modules")+ |
|||
76 | -87x | +247 | +12x |
- moduleServer(id, function(input, output, session) {+ res |
77 | -87x | +|||
248 | +
- logger::log_debug("bookmark_manager_srv initializing")+ } |
|||
78 | -87x | +
1 | +
- ns <- session$ns+ #' Calls all `modules` |
|||
79 | -87x | +|||
2 | +
- bookmark_option <- get_bookmarking_option()+ #' |
|||
80 | -87x | +|||
3 | +
- is_unbookmarkable <- need_bookmarking(modules)+ #' On the UI side each `teal_modules` is translated to a `tabsetPanel` and each `teal_module` is a |
|||
81 | +4 |
-
+ #' `tabPanel`. Both, UI and server are called recursively so that each tab is a separate module and |
||
82 | +5 |
- # Set up bookmarking callbacks ----+ #' reflect nested structure of `modules` argument. |
||
83 | +6 |
- # Register bookmark exclusions: do_bookmark button to avoid re-bookmarking+ #' |
||
84 | -87x | +|||
7 | +
- setBookmarkExclude(c("do_bookmark"))+ #' @name module_teal_module |
|||
85 | +8 |
- # This bookmark can only be used on the app session.+ #' |
||
86 | -87x | +|||
9 | +
- app_session <- .subset2(session, "parent")+ #' @inheritParams module_teal |
|||
87 | -87x | +|||
10 | +
- app_session$onBookmarked(function(url) {+ #' |
|||
88 | -! | +|||
11 | +
- logger::log_debug("bookmark_manager_srv@onBookmarked: bookmark button clicked, registering bookmark")+ #' @param data (`reactive` returning `teal_data`) |
|||
89 | -! | +|||
12 | +
- modal_content <- if (bookmark_option != "server") {+ #' |
|||
90 | -! | +|||
13 | +
- msg <- sprintf(+ #' @param slices_global (`reactiveVal` returning `modules_teal_slices`) |
|||
91 | -! | +|||
14 | +
- "Bookmarking has been set to \"%s\".\n%s\n%s",+ #' see [`module_filter_manager`] |
|||
92 | -! | +|||
15 | +
- bookmark_option,+ #' |
|||
93 | -! | +|||
16 | +
- "Only server-side bookmarking is supported.",+ #' @param depth (`integer(1)`) |
|||
94 | -! | +|||
17 | +
- "Please contact your app developer."+ #' number which helps to determine depth of the modules nesting. |
|||
95 | +18 |
- )+ #' |
||
96 | -! | +|||
19 | +
- tags$div(+ #' @param datasets (`reactive` returning `FilteredData` or `NULL`) |
|||
97 | -! | +|||
20 | +
- tags$p(msg, class = "text-warning")+ #' When `datasets` is passed from the parent module (`srv_teal`) then `dataset` is a singleton |
|||
98 | +21 |
- )+ #' which implies in filter-panel to be "global". When `NULL` then filter-panel is "module-specific". |
||
99 | +22 |
- } else {+ #' |
||
100 | -! | +|||
23 | +
- tags$div(+ #' @param data_load_status (`reactive` returning `character`) |
|||
101 | -! | +|||
24 | +
- tags$span(+ #' Determines action dependent on a data loading status: |
|||
102 | -! | +|||
25 | +
- tags$pre(url)+ #' - `"ok"` when `teal_data` is returned from the data loading. |
|||
103 | +26 |
- ),+ #' - `"teal_data_module failed"` when [teal_data_module()] didn't return `teal_data`. Disables tabs buttons. |
||
104 | -! | +|||
27 | +
- if (any(is_unbookmarkable)) {+ #' - `"external failed"` when a `reactive` passed to `srv_teal(data)` didn't return `teal_data`. Hides the whole tab |
|||
105 | -! | +|||
28 | +
- bkmb_summary <- rapply2(+ #' panel. |
|||
106 | -! | +|||
29 | +
- modules_bookmarkable(modules),+ #' |
|||
107 | -! | +|||
30 | +
- function(x) {+ #' @return |
|||
108 | -! | +|||
31 | +
- if (isTRUE(x)) {+ #' output of currently active module. |
|||
109 | -! | +|||
32 | +
- "\u2705" # check mark+ #' - `srv_teal_module.teal_module` returns `reactiveVal` containing output of the called module. |
|||
110 | -! | +|||
33 | +
- } else if (isFALSE(x)) {+ #' - `srv_teal_module.teal_modules` returns output of module selected by `input$active_tab`. |
|||
111 | -! | +|||
34 | +
- "\u274C" # cross mark+ #' |
|||
112 | +35 |
- } else {+ #' @keywords internal |
||
113 | -! | +|||
36 | +
- "\u2753" # question mark+ NULL |
|||
114 | +37 |
- }+ |
||
115 | +38 |
- }+ #' @rdname module_teal_module |
||
116 | +39 |
- )+ ui_teal_module <- function(id, modules, depth = 0L) { |
||
117 | +40 | ! |
- tags$div(+ checkmate::assert_multi_class(modules, c("teal_modules", "teal_module", "shiny.tag")) |
|
118 | +41 | ! |
- tags$p(+ checkmate::assert_count(depth) |
|
119 | +42 | ! |
- icon("fas fa-exclamation-triangle"),+ UseMethod("ui_teal_module", modules) |
|
120 | -! | +|||
43 | +
- "Some modules will not be restored when using this bookmark.",+ } |
|||
121 | -! | +|||
44 | +
- tags$br(),+ |
|||
122 | -! | +|||
45 | +
- "Check the list below to see which modules are not bookmarkable.",+ #' @rdname module_teal_module |
|||
123 | -! | +|||
46 | +
- class = "text-warning"+ #' @export |
|||
124 | +47 |
- ),+ ui_teal_module.default <- function(id, modules, depth = 0L) { |
||
125 | +48 | ! |
- tags$pre(yaml::as.yaml(bkmb_summary))+ stop("Modules class not supported: ", paste(class(modules), collapse = " ")) |
|
126 | +49 |
- )+ } |
||
127 | +50 |
- }+ |
||
128 | +51 |
- )+ #' @rdname module_teal_module |
||
129 | +52 |
- }+ #' @export |
||
130 | +53 |
-
+ ui_teal_module.teal_modules <- function(id, modules, depth = 0L) { |
||
131 | +54 | ! |
- showModal(+ ns <- NS(id) |
|
132 | +55 | ! |
- modalDialog(+ tags$div( |
|
133 | +56 | ! |
- id = ns("bookmark_modal"),+ id = ns("wrapper"), |
|
134 | +57 | ! |
- title = "Bookmarked teal app url",+ do.call( |
|
135 | +58 | ! |
- modal_content,+ tabsetPanel, |
|
136 | +59 | ! |
- easyClose = TRUE+ c( |
|
137 | +60 |
- )+ # by giving an id, we can reactively respond to tab changes |
||
138 | -+ | |||
61 | +! |
- )+ list( |
||
139 | -+ | |||
62 | +! |
- })+ id = ns("active_tab"), |
||
140 | -+ | |||
63 | +! |
-
+ type = if (modules$label == "root") "pills" else "tabs" |
||
141 | +64 |
- # manually trigger bookmarking because of the problems reported on windows with bookmarkButton in teal- |
- ||
142 | -87x | -
- observeEvent(input$do_bookmark, {+ ), |
||
143 | +65 | ! |
- logger::log_debug("bookmark_manager_srv@1 do_bookmark module clicked.")+ lapply( |
|
144 | +66 | ! |
- session$doBookmark()+ names(modules$children), |
|
145 | -+ | |||
67 | +! |
- })+ function(module_id) { |
||
146 | -+ | |||
68 | +! |
-
+ module_label <- modules$children[[module_id]]$label |
||
147 | -87x | +|||
69 | +! |
- invisible(NULL)+ if (is.null(module_label)) { |
||
148 | -+ | |||
70 | +! |
- })+ module_label <- icon("fas fa-database") |
||
149 | +71 |
- }+ } |
||
150 | -+ | |||
72 | +! |
-
+ tabPanel( |
||
151 | -+ | |||
73 | +! |
-
+ title = module_label, |
||
152 | -+ | |||
74 | +! |
- #' @rdname module_bookmark_manager+ value = module_id, # when clicked this tab value changes input$<tabset panel id> |
||
153 | -+ | |||
75 | +! |
- get_bookmarking_option <- function() {+ ui_teal_module( |
||
154 | -87x | +|||
76 | +! |
- bookmark_option <- getShinyOption("bookmarkStore")+ id = ns(module_id), |
||
155 | -87x | +|||
77 | +! |
- if (is.null(bookmark_option) && identical(getOption("shiny.bookmarkStore"), "server")) {+ modules = modules$children[[module_id]], |
||
156 | +78 | ! |
- bookmark_option <- getOption("shiny.bookmarkStore")+ depth = depth + 1L |
|
157 | +79 |
- }- |
- ||
158 | -87x | -
- bookmark_option+ ) |
||
159 | +80 |
- }+ ) |
||
160 | +81 |
-
+ } |
||
161 | +82 |
- #' @rdname module_bookmark_manager+ ) |
||
162 | +83 |
- need_bookmarking <- function(modules) {- |
- ||
163 | -87x | -
- unlist(rapply2(- |
- ||
164 | -87x | -
- modules_bookmarkable(modules),- |
- ||
165 | -87x | -
- Negate(isTRUE)+ ) |
||
166 | +84 |
- ))+ ) |
||
167 | +85 |
- }+ ) |
||
168 | +86 |
-
+ } |
||
169 | +87 | |||
170 | +88 |
- # utilities ----+ #' @rdname module_teal_module |
||
171 | +89 |
-
+ #' @export |
||
172 | +90 |
- #' Restore value from bookmark.+ ui_teal_module.teal_module <- function(id, modules, depth = 0L) { |
||
173 | -+ | |||
91 | +! |
- #'+ ns <- NS(id) |
||
174 | -+ | |||
92 | +! |
- #' Get value from bookmark or return default.+ args <- c(list(id = ns("module")), modules$ui_args) |
||
175 | +93 |
- #'+ |
||
176 | -+ | |||
94 | +! |
- #' Bookmarks can store not only inputs but also arbitrary values.+ ui_teal <- tagList( |
||
177 | -+ | |||
95 | +! |
- #' These values are stored by `onBookmark` callbacks and restored by `onBookmarked` callbacks,+ shinyjs::hidden( |
||
178 | -+ | |||
96 | +! |
- #' and they are placed in the `values` environment in the `session$restoreContext` field.+ tags$div( |
||
179 | -+ | |||
97 | +! |
- #' Using `teal_data_module` makes it impossible to run the callbacks+ id = ns("transform_failure_info"), |
||
180 | -+ | |||
98 | +! |
- #' because the app becomes ready before modules execute and callbacks are registered.+ class = "teal_validated", |
||
181 | -+ | |||
99 | +! |
- #' In those cases the stored values can still be recovered from the `session` object directly.+ div( |
||
182 | -+ | |||
100 | +! |
- #'+ class = "teal-output-warning", |
||
183 | -+ | |||
101 | +! |
- #' Note that variable names in the `values` environment are prefixed with module name space names,+ "One of transformators failed. Please check its inputs." |
||
184 | +102 |
- #' therefore, when using this function in modules, `value` must be run through the name space function.+ ) |
||
185 | +103 |
- #'+ ) |
||
186 | +104 |
- #' @param value (`character(1)`) name of value to restore+ ), |
||
187 | -+ | |||
105 | +! |
- #' @param default fallback value+ tags$div( |
||
188 | -+ | |||
106 | +! |
- #'+ id = ns("teal_module_ui"), |
||
189 | -+ | |||
107 | +! |
- #' @return+ tags$div( |
||
190 | -+ | |||
108 | +! |
- #' In an application restored from a server-side bookmark,+ class = "teal_validated", |
||
191 | -+ | |||
109 | +! |
- #' the variable specified by `value` from the `values` environment.+ ui_check_module_datanames(ns("validate_datanames")) |
||
192 | +110 |
- #' Otherwise `default`.+ ), |
||
193 | -+ | |||
111 | +! |
- #'+ do.call(modules$ui, args) |
||
194 | +112 |
- #' @keywords internal+ ) |
||
195 | +113 |
- #'+ ) |
||
196 | +114 |
- restoreValue <- function(value, default) { # nolint: object_name.- |
- ||
197 | -174x | -
- checkmate::assert_character("value")- |
- ||
198 | -174x | -
- session_default <- shiny::getDefaultReactiveDomain()- |
- ||
199 | -174x | -
- session_parent <- .subset2(session_default, "parent")- |
- ||
200 | -174x | -
- session <- if (is.null(session_parent)) session_default else session_parent+ |
||
201 | -+ | |||
115 | +! |
-
+ div( |
||
202 | -174x | +|||
116 | +! |
- if (isTRUE(session$restoreContext$active) && exists(value, session$restoreContext$values, inherits = FALSE)) {+ id = id, |
||
203 | +117 | ! |
- session$restoreContext$values[[value]]+ class = "teal_module", |
|
204 | -+ | |||
118 | +! |
- } else {+ uiOutput(ns("data_reactive"), inline = TRUE), |
||
205 | -174x | +|||
119 | +! |
- default+ tagList( |
||
206 | -+ | |||
120 | +! |
- }+ if (depth >= 2L) tags$div(style = "mt-6"), |
||
207 | -+ | |||
121 | +! |
- }+ if (!is.null(modules$datanames)) { |
||
208 | -+ | |||
122 | +! |
-
+ fluidRow( |
||
209 | -+ | |||
123 | +! |
- #' Compare bookmarks.+ column(width = 9, ui_teal, class = "teal_primary_col"), |
||
210 | -+ | |||
124 | +! |
- #'+ column( |
||
211 | -+ | |||
125 | +! |
- #' Test if two bookmarks store identical state.+ width = 3, |
||
212 | -+ | |||
126 | +! |
- #'+ ui_data_summary(ns("data_summary")), |
||
213 | -+ | |||
127 | +! |
- #' `input` environments are compared one variable at a time and if not identical,+ ui_filter_data(ns("filter_panel")), |
||
214 | -+ | |||
128 | +! |
- #' values in both bookmarks are reported. States of `datatable`s are stripped+ ui_transform_teal_data(ns("data_transform"), transformators = modules$transformators, class = "well"), |
||
215 | -+ | |||
129 | +! |
- #' of the `time` element before comparing because the time stamp is always different.+ class = "teal_secondary_col" |
||
216 | +130 |
- #' The contents themselves are not printed as they are large and the contents are not informative.+ ) |
||
217 | +131 |
- #' Elements present in one bookmark and absent in the other are also reported.+ ) |
||
218 | +132 |
- #' Differences are printed as messages.+ } else { |
||
219 | -+ | |||
133 | +! |
- #'+ ui_teal |
||
220 | +134 |
- #' `values` environments are compared with `all.equal`.+ } |
||
221 | +135 |
- #'+ ) |
||
222 | +136 |
- #' @section How to use:+ ) |
||
223 | +137 |
- #' Open an application, change relevant inputs (typically, all of them), and create a bookmark.+ } |
||
224 | +138 |
- #' Then open that bookmark and immediately create a bookmark of that.+ |
||
225 | +139 |
- #' If restoring bookmarks occurred properly, the two bookmarks should store the same state.+ #' @rdname module_teal_module |
||
226 | +140 |
- #'+ srv_teal_module <- function(id, |
||
227 | +141 |
- #'+ data, |
||
228 | +142 |
- #' @param book1,book2 bookmark directories stored in `shiny_bookmarks/`;+ modules, |
||
229 | +143 |
- #' default to the two most recently modified directories+ datasets = NULL, |
||
230 | +144 |
- #'+ slices_global, |
||
231 | +145 |
- #' @return+ reporter = teal.reporter::Reporter$new(), |
||
232 | +146 |
- #' Invisible `NULL` if bookmarks are identical or if there are no bookmarks to test.+ data_load_status = reactive("ok"), |
||
233 | +147 |
- #' `FALSE` if inconsistencies are detected.+ is_active = reactive(TRUE)) { |
||
234 | -+ | |||
148 | +199x |
- #'+ checkmate::assert_string(id) |
||
235 | -+ | |||
149 | +199x |
- #' @keywords internal+ assert_reactive(data) |
||
236 | -+ | |||
150 | +199x |
- #'+ checkmate::assert_multi_class(modules, c("teal_modules", "teal_module")) |
||
237 | -+ | |||
151 | +199x |
- bookmarks_identical <- function(book1, book2) {+ assert_reactive(datasets, null.ok = TRUE) |
||
238 | -! | +|||
152 | +199x |
- if (!dir.exists("shiny_bookmarks")) {+ checkmate::assert_class(slices_global, ".slicesGlobal") |
||
239 | -! | +|||
153 | +199x |
- message("no bookmark directory")+ checkmate::assert_class(reporter, "Reporter") |
||
240 | -! | +|||
154 | +199x |
- return(invisible(NULL))+ assert_reactive(data_load_status) |
||
241 | -+ | |||
155 | +199x |
- }+ UseMethod("srv_teal_module", modules) |
||
242 | +156 | - - | -||
243 | -! | -
- ans <- TRUE+ } |
||
244 | +157 | |||
245 | -! | -
- if (missing(book1) && missing(book2)) {- |
- ||
246 | -! | +|||
158 | +
- dirs <- list.dirs("shiny_bookmarks", recursive = FALSE)+ #' @rdname module_teal_module |
|||
247 | -! | +|||
159 | +
- bookmarks_sorted <- basename(rev(dirs[order(file.mtime(dirs))]))+ #' @export |
|||
248 | -! | +|||
160 | +
- if (length(bookmarks_sorted) < 2L) {+ srv_teal_module.default <- function(id, |
|||
249 | -! | +|||
161 | +
- message("no bookmarks to compare")+ data, |
|||
250 | -! | +|||
162 | +
- return(invisible(NULL))+ modules, |
|||
251 | +163 |
- }+ datasets = NULL, |
||
252 | -! | +|||
164 | +
- book1 <- bookmarks_sorted[2L]+ slices_global, |
|||
253 | -! | +|||
165 | +
- book2 <- bookmarks_sorted[1L]+ reporter = teal.reporter::Reporter$new(), |
|||
254 | +166 |
- } else {+ data_load_status = reactive("ok"), |
||
255 | -! | +|||
167 | +
- if (!dir.exists(file.path("shiny_bookmarks", book1))) stop(book1, " not found")+ is_active = reactive(TRUE)) { |
|||
256 | +168 | ! |
- if (!dir.exists(file.path("shiny_bookmarks", book2))) stop(book2, " not found")+ stop("Modules class not supported: ", paste(class(modules), collapse = " ")) |
|
257 | +169 |
- }+ } |
||
258 | +170 | |||
259 | -! | -
- book1_input <- readRDS(file.path("shiny_bookmarks", book1, "input.rds"))- |
- ||
260 | -! | +|||
171 | +
- book2_input <- readRDS(file.path("shiny_bookmarks", book2, "input.rds"))+ #' @rdname module_teal_module |
|||
261 | +172 |
-
+ #' @export |
||
262 | -! | +|||
173 | +
- elements_common <- intersect(names(book1_input), names(book2_input))+ srv_teal_module.teal_modules <- function(id, |
|||
263 | -! | +|||
174 | +
- dt_states <- grepl("_state$", elements_common)+ data, |
|||
264 | -! | +|||
175 | +
- if (any(dt_states)) {+ modules, |
|||
265 | -! | +|||
176 | +
- for (el in elements_common[dt_states]) {+ datasets = NULL, |
|||
266 | -! | +|||
177 | +
- book1_input[[el]][["time"]] <- NULL+ slices_global, |
|||
267 | -! | +|||
178 | +
- book2_input[[el]][["time"]] <- NULL+ reporter = teal.reporter::Reporter$new(), |
|||
268 | +179 |
- }+ data_load_status = reactive("ok"), |
||
269 | +180 |
- }+ is_active = reactive(TRUE)) { |
||
270 | -+ | |||
181 | +87x |
-
+ moduleServer(id = id, module = function(input, output, session) { |
||
271 | -! | +|||
182 | +87x |
- identicals <- mapply(identical, book1_input[elements_common], book2_input[elements_common])+ logger::log_debug("srv_teal_module.teal_modules initializing the module { deparse1(modules$label) }.") |
||
272 | -! | +|||
183 | +
- non_identicals <- names(identicals[!identicals])+ |
|||
273 | -! | +|||
184 | +87x |
- compares <- sprintf("$ %s:\t%s --- %s", non_identicals, book1_input[non_identicals], book2_input[non_identicals])+ observeEvent(data_load_status(), { |
||
274 | -! | +|||
185 | +80x |
- if (length(compares) != 0L) {+ tabs_selector <- sprintf("#%s li a", session$ns("active_tab")) |
||
275 | -! | +|||
186 | +80x |
- message("common elements not identical: \n", paste(compares, collapse = "\n"))+ if (identical(data_load_status(), "ok")) { |
||
276 | -! | +|||
187 | +75x |
- ans <- FALSE+ logger::log_debug("srv_teal_module@1 enabling modules tabs.") |
||
277 | -+ | |||
188 | +75x |
- }+ shinyjs::show("wrapper") |
||
278 | -+ | |||
189 | +75x |
-
+ shinyjs::enable(selector = tabs_selector) |
||
279 | -! | +|||
190 | +5x |
- elements_boook1 <- setdiff(names(book1_input), names(book2_input))+ } else if (identical(data_load_status(), "teal_data_module failed")) { |
||
280 | -! | +|||
191 | +5x |
- if (length(elements_boook1) != 0L) {+ logger::log_debug("srv_teal_module@1 disabling modules tabs.") |
||
281 | -! | +|||
192 | +5x |
- dt_states <- grepl("_state$", elements_boook1)+ shinyjs::disable(selector = tabs_selector) |
||
282 | +193 | ! |
- if (any(dt_states)) {+ } else if (identical(data_load_status(), "external failed")) { |
|
283 | +194 | ! |
- for (el in elements_boook1[dt_states]) {+ logger::log_debug("srv_teal_module@1 hiding modules tabs.") |
|
284 | +195 | ! |
- if (is.list(book1_input[[el]])) book1_input[[el]] <- "--- data table state ---"+ shinyjs::hide("wrapper") |
|
285 | +196 |
} |
||
286 | +197 |
- }+ }) |
||
287 | -! | +|||
198 | +
- excess1 <- sprintf("$ %s:\t%s", elements_boook1, book1_input[elements_boook1])+ |
|||
288 | -! | +|||
199 | +87x |
- message("elements only in book1: \n", paste(excess1, collapse = "\n"))+ modules_output <- sapply( |
||
289 | -! | +|||
200 | +87x |
- ans <- FALSE+ names(modules$children), |
||
290 | -+ | |||
201 | +87x |
- }+ function(module_id) { |
||
291 | -+ | |||
202 | +112x |
-
+ srv_teal_module( |
||
292 | -! | +|||
203 | +112x |
- elements_boook2 <- setdiff(names(book2_input), names(book1_input))+ id = module_id, |
||
293 | -! | +|||
204 | +112x |
- if (length(elements_boook2) != 0L) {+ data = data, |
||
294 | -! | +|||
205 | +112x |
- dt_states <- grepl("_state$", elements_boook1)+ modules = modules$children[[module_id]], |
||
295 | -! | +|||
206 | +112x |
- if (any(dt_states)) {+ datasets = datasets, |
||
296 | -! | +|||
207 | +112x |
- for (el in elements_boook1[dt_states]) {+ slices_global = slices_global, |
||
297 | -! | +|||
208 | +112x |
- if (is.list(book2_input[[el]])) book2_input[[el]] <- "--- data table state ---"+ reporter = reporter, |
||
298 | -+ | |||
209 | +112x |
- }+ is_active = reactive( |
||
299 | -+ | |||
210 | +112x |
- }+ is_active() && |
||
300 | -! | +|||
211 | +112x |
- excess2 <- sprintf("$ %s:\t%s", elements_boook2, book2_input[elements_boook2])+ input$active_tab == module_id && |
||
301 | -! | +|||
212 | +112x |
- message("elements only in book2: \n", paste(excess2, collapse = "\n"))+ identical(data_load_status(), "ok") |
||
302 | -! | +|||
213 | +
- ans <- FALSE+ ) |
|||
303 | +214 |
- }+ ) |
||
304 | +215 |
-
+ }, |
||
305 | -! | +|||
216 | +87x |
- book1_values <- readRDS(file.path("shiny_bookmarks", book1, "values.rds"))+ simplify = FALSE |
||
306 | -! | +|||
217 | +
- book2_values <- readRDS(file.path("shiny_bookmarks", book2, "values.rds"))+ ) |
|||
307 | +218 | |||
308 | -! | +|||
219 | +87x |
- if (!isTRUE(all.equal(book1_values, book2_values))) {+ modules_output |
||
309 | -! | +|||
220 | +
- message("different values detected")+ }) |
|||
310 | -! | +|||
221 | +
- message("choices for numeric filters MAY be different, see RangeFilterState$set_choices")+ } |
|||
311 | -! | +|||
222 | +
- ans <- FALSE+ |
|||
312 | +223 |
- }+ #' @rdname module_teal_module |
||
313 | +224 |
-
+ #' @export |
||
314 | -! | +|||
225 | +
- if (ans) message("perfect!")+ srv_teal_module.teal_module <- function(id, |
|||
315 | -! | +|||
226 | +
- invisible(NULL)+ data, |
|||
316 | +227 |
- }+ modules, |
||
317 | +228 |
-
+ datasets = NULL, |
||
318 | +229 |
-
+ slices_global, |
||
319 | +230 |
- # Replacement for [base::rapply] which doesn't handle NULL values - skips the evaluation+ reporter = teal.reporter::Reporter$new(), |
||
320 | +231 |
- # of the function and returns NULL for given element.+ data_load_status = reactive("ok"), |
||
321 | +232 |
- rapply2 <- function(x, f) {+ is_active = reactive(TRUE)) { |
||
322 | -199x | +233 | +112x |
- if (inherits(x, "list")) {+ logger::log_debug("srv_teal_module.teal_module initializing the module: { deparse1(modules$label) }.") |
323 | -87x | +234 | +112x |
- lapply(x, rapply2, f = f)+ moduleServer(id = id, module = function(input, output, session) {+ |
+
235 | +112x | +
+ module_out <- reactiveVal() |
||
324 | +236 |
- } else {+ |
||
325 | +237 | 112x |
- f(x)+ active_datanames <- reactive({ |
|
326 | -+ | |||
238 | +89x |
- }+ .resolve_module_datanames(data = data(), modules = modules) |
||
327 | +239 |
- }+ }) |
1 | -+ | |||
240 | +112x |
- #' Validate that dataset has a minimum number of observations+ if (is.null(datasets)) { |
||
2 | -+ | |||
241 | +20x |
- #'+ datasets <- eventReactive(data(), { |
||
3 | -+ | |||
242 | +16x |
- #' `r lifecycle::badge("stable")`+ req(inherits(data(), "teal_data")) |
||
4 | -+ | |||
243 | +16x |
- #'+ logger::log_debug("srv_teal_module@1 initializing module-specific FilteredData") |
||
5 | -+ | |||
244 | +16x |
- #' This function is a wrapper for `shiny::validate`.+ teal_data_to_filtered_data(data(), datanames = active_datanames()) |
||
6 | +245 |
- #'+ }) |
||
7 | +246 |
- #' @param x (`data.frame`)+ } |
||
8 | +247 |
- #' @param min_nrow (`numeric(1)`) Minimum allowed number of rows in `x`.+ |
||
9 | +248 |
- #' @param complete (`logical(1)`) Flag specifying whether to check only complete cases. Defaults to `FALSE`.+ # manage module filters on the module level |
||
10 | +249 |
- #' @param allow_inf (`logical(1)`) Flag specifying whether to allow infinite values. Defaults to `TRUE`.+ # important: |
||
11 | +250 |
- #' @param msg (`character(1)`) Additional message to display alongside the default message.+ # filter_manager_module_srv needs to be called before filter_panel_srv |
||
12 | +251 |
- #'+ # Because available_teal_slices is used in FilteredData$srv_available_slices (via srv_filter_panel) |
||
13 | +252 |
- #' @export+ # and if it is not set, then it won't be available in the srv_filter_panel |
||
14 | -+ | |||
253 | +112x |
- #'+ srv_module_filter_manager(modules$label, module_fd = datasets, slices_global = slices_global) |
||
15 | +254 |
- #' @examples+ |
||
16 | -+ | |||
255 | +112x |
- #' library(teal)+ call_once_when(is_active(), { |
||
17 | -+ | |||
256 | +86x |
- #' ui <- fluidPage(+ filtered_teal_data <- srv_filter_data( |
||
18 | -+ | |||
257 | +86x |
- #' sliderInput("len", "Max Length of Sepal",+ "filter_panel", |
||
19 | -+ | |||
258 | +86x |
- #' min = 4.3, max = 7.9, value = 5+ datasets = datasets, |
||
20 | -+ | |||
259 | +86x |
- #' ),+ active_datanames = active_datanames, |
||
21 | -+ | |||
260 | +86x |
- #' plotOutput("plot")+ data = data, |
||
22 | -+ | |||
261 | +86x |
- #' )+ is_active = is_active |
||
23 | +262 |
- #'+ ) |
||
24 | -+ | |||
263 | +86x |
- #' server <- function(input, output) {+ is_transform_failed <- reactiveValues() |
||
25 | -+ | |||
264 | +86x |
- #' output$plot <- renderPlot({+ transformed_teal_data <- srv_transform_teal_data( |
||
26 | -+ | |||
265 | +86x |
- #' iris_df <- iris[iris$Sepal.Length <= input$len, ]+ "data_transform",+ |
+ ||
266 | +86x | +
+ data = filtered_teal_data,+ |
+ ||
267 | +86x | +
+ transformators = modules$transformators,+ |
+ ||
268 | +86x | +
+ modules = modules,+ |
+ ||
269 | +86x | +
+ is_transform_failed = is_transform_failed |
||
27 | +270 |
- #' validate_has_data(+ )+ |
+ ||
271 | +86x | +
+ any_transform_failed <- reactive({+ |
+ ||
272 | +86x | +
+ any(unlist(reactiveValuesToList(is_transform_failed))) |
||
28 | +273 |
- #' iris_df,+ }) |
||
29 | +274 |
- #' min_nrow = 10,+ |
||
30 | -+ | |||
275 | +86x |
- #' complete = FALSE,+ observeEvent(any_transform_failed(), { |
||
31 | -+ | |||
276 | +86x |
- #' msg = "Please adjust Max Length of Sepal"+ if (isTRUE(any_transform_failed())) { |
||
32 | -+ | |||
277 | +6x |
- #' )+ shinyjs::hide("teal_module_ui") |
||
33 | -+ | |||
278 | +6x |
- #'+ shinyjs::show("transform_failure_info") |
||
34 | +279 |
- #' hist(iris_df$Sepal.Length, breaks = 5)+ } else { |
||
35 | -+ | |||
280 | +80x |
- #' })+ shinyjs::show("teal_module_ui") |
||
36 | -+ | |||
281 | +80x |
- #' }+ shinyjs::hide("transform_failure_info") |
||
37 | +282 |
- #' if (interactive()) {+ } |
||
38 | +283 |
- #' shinyApp(ui, server)+ }) |
||
39 | +284 |
- #' }+ |
||
40 | -+ | |||
285 | +86x |
- #'+ module_teal_data <- reactive({ |
||
41 | -+ | |||
286 | +94x |
- validate_has_data <- function(x,+ req(inherits(transformed_teal_data(), "teal_data")) |
||
42 | -+ | |||
287 | +88x |
- min_nrow = NULL,+ all_teal_data <- transformed_teal_data() |
||
43 | -+ | |||
288 | +88x |
- complete = FALSE,+ module_datanames <- .resolve_module_datanames(data = all_teal_data, modules = modules) |
||
44 | -+ | |||
289 | +88x |
- allow_inf = TRUE,+ all_teal_data[c(module_datanames, ".raw_data")] |
||
45 | +290 |
- msg = NULL) {+ }) |
||
46 | -17x | +|||
291 | +
- checkmate::assert_string(msg, null.ok = TRUE)+ |
|||
47 | -15x | +292 | +86x |
- checkmate::assert_data_frame(x)+ srv_check_module_datanames( |
48 | -15x | +293 | +86x |
- if (!is.null(min_nrow)) {+ "validate_datanames", |
49 | -15x | +294 | +86x |
- if (complete) {+ data = module_teal_data, |
50 | -5x | +295 | +86x |
- complete_index <- stats::complete.cases(x)+ modules = modules |
51 | -5x | +|||
296 | +
- validate(need(+ ) |
|||
52 | -5x | +|||
297 | +
- sum(complete_index) > 0 && nrow(x[complete_index, , drop = FALSE]) >= min_nrow,+ |
|||
53 | -5x | +298 | +86x |
- paste(c(paste("Number of complete cases is less than:", min_nrow), msg), collapse = "\n")+ summary_table <- srv_data_summary("data_summary", module_teal_data) |
54 | +299 |
- ))+ |
||
55 | +300 |
- } else {+ # Call modules. |
||
56 | -10x | +301 | +86x |
- validate(need(+ if (!inherits(modules, "teal_module_previewer")) { |
57 | -10x | +302 | +86x |
- nrow(x) >= min_nrow,+ obs_module <- call_once_when( |
58 | -10x | +303 | +86x |
- paste(+ !is.null(module_teal_data()), |
59 | -10x | +304 | +86x |
- c(paste("Minimum number of records not met: >=", min_nrow, "records required."), msg),+ ignoreNULL = TRUE, |
60 | -10x | +305 | +86x |
- collapse = "\n"+ handlerExpr = { |
61 | -+ | |||
306 | +80x |
- )+ module_out(.call_teal_module(modules, datasets, module_teal_data, reporter)) |
||
62 | +307 |
- ))+ } |
||
63 | +308 |
- }+ ) |
||
64 | +309 |
-
+ } else { |
||
65 | -10x | +|||
310 | +
- if (!allow_inf) {+ # Report previewer must be initiated on app start for report cards to be included in bookmarks. |
|||
66 | -6x | +|||
311 | +
- validate(need(+ # When previewer is delayed, cards are bookmarked only if previewer has been initiated (visited). |
|||
67 | -6x | +|||
312 | +! |
- all(vapply(x, function(col) !is.numeric(col) || !any(is.infinite(col)), logical(1))),+ module_out(.call_teal_module(modules, datasets, module_teal_data, reporter)) |
||
68 | -6x | +|||
313 | +
- "Dataframe contains Inf values which is not allowed."+ } |
|||
69 | +314 |
- ))+ }) |
||
70 | +315 |
- }+ + |
+ ||
316 | +112x | +
+ module_out |
||
71 | +317 |
- }+ }) |
||
72 | +318 |
} |
||
73 | +319 | |||
74 | +320 |
- #' Validate that dataset has unique rows for key variables+ # This function calls a module server function. |
||
75 | +321 |
- #'+ .call_teal_module <- function(modules, datasets, data, reporter) { |
||
76 | -+ | |||
322 | +80x |
- #' `r lifecycle::badge("stable")`+ assert_reactive(data) |
||
77 | +323 |
- #'+ |
||
78 | +324 |
- #' This function is a wrapper for `shiny::validate`.+ # collect arguments to run teal_module |
||
79 | -+ | |||
325 | +80x |
- #'+ args <- c(list(id = "module"), modules$server_args) |
||
80 | -+ | |||
326 | +80x |
- #' @param x (`data.frame`)+ if (is_arg_used(modules$server, "reporter")) { |
||
81 | -+ | |||
327 | +1x |
- #' @param key (`character`) Vector of ID variables from `x` that identify unique records.+ args <- c(args, list(reporter = reporter)) |
||
82 | +328 |
- #'+ } |
||
83 | +329 |
- #' @export+ |
||
84 | -+ | |||
330 | +80x |
- #'+ if (is_arg_used(modules$server, "datasets")) { |
||
85 | -+ | |||
331 | +1x |
- #' @examples+ args <- c(args, datasets = datasets()) |
||
86 | -+ | |||
332 | +1x |
- #' iris$id <- rep(1:50, times = 3)+ warning("datasets argument is not reactive and therefore it won't be updated when data is refreshed.") |
||
87 | +333 |
- #' ui <- fluidPage(+ } |
||
88 | +334 |
- #' selectInput(+ |
||
89 | -+ | |||
335 | +80x |
- #' inputId = "species",+ if (is_arg_used(modules$server, "data")) { |
||
90 | -+ | |||
336 | +76x |
- #' label = "Select species",+ args <- c(args, data = list(data)) |
||
91 | +337 |
- #' choices = c("setosa", "versicolor", "virginica"),+ } |
||
92 | +338 |
- #' selected = "setosa",+ |
||
93 | -+ | |||
339 | +80x |
- #' multiple = TRUE+ if (is_arg_used(modules$server, "filter_panel_api")) { |
||
94 | -+ | |||
340 | +1x |
- #' ),+ args <- c(args, filter_panel_api = teal.slice::FilterPanelAPI$new(datasets())) |
||
95 | +341 |
- #' plotOutput("plot")+ } |
||
96 | +342 |
- #' )+ |
||
97 | -+ | |||
343 | +80x |
- #' server <- function(input, output) {+ if (is_arg_used(modules$server, "id")) { |
||
98 | -+ | |||
344 | +80x |
- #' output$plot <- renderPlot({+ do.call(modules$server, args) |
||
99 | +345 |
- #' iris_f <- iris[iris$Species %in% input$species, ]+ } else { |
||
100 | -+ | |||
346 | +! |
- #' validate_one_row_per_id(iris_f, key = c("id"))+ do.call(callModule, c(args, list(module = modules$server))) |
||
101 | +347 |
- #'+ } |
||
102 | +348 |
- #' hist(iris_f$Sepal.Length, breaks = 5)+ } |
||
103 | +349 |
- #' })+ |
||
104 | +350 |
- #' }+ .resolve_module_datanames <- function(data, modules) { |
||
105 | -+ | |||
351 | +177x |
- #' if (interactive()) {+ stopifnot("data must be teal_data object." = inherits(data, "teal_data")) |
||
106 | -+ | |||
352 | +177x |
- #' shinyApp(ui, server)+ if (is.null(modules$datanames) || identical(modules$datanames, "all")) { |
||
107 | -+ | |||
353 | +145x |
- #' }+ names(data) |
||
108 | +354 |
- #'+ } else {+ |
+ ||
355 | +32x | +
+ intersect(+ |
+ ||
356 | +32x | +
+ names(data), # Keep topological order from teal.data::names()+ |
+ ||
357 | +32x | +
+ .include_parent_datanames(modules$datanames, teal.data::join_keys(data)) |
||
109 | +358 |
- validate_one_row_per_id <- function(x, key = c("USUBJID", "STUDYID")) {+ ) |
||
110 | -! | +|||
359 | +
- validate(need(!any(duplicated(x[key])), paste("Found more than one row per id.")))+ } |
|||
111 | +360 |
} |
||
112 | +361 | |||
113 | +362 |
- #' Validates that vector includes all expected values+ #' Calls expression when condition is met |
||
114 | +363 |
#' |
||
115 | +364 |
- #' `r lifecycle::badge("stable")`+ #' Function postpones `handlerExpr` to the moment when `eventExpr` (condition) returns `TRUE`, |
||
116 | +365 |
- #'+ #' otherwise nothing happens. |
||
117 | +366 |
- #' This function is a wrapper for `shiny::validate`.+ #' @param eventExpr A (quoted or unquoted) logical expression that represents the event; |
||
118 | +367 |
- #'+ #' this can be a simple reactive value like input$click, a call to a reactive expression |
||
119 | +368 |
- #' @param x Vector of values to test.+ #' like dataset(), or even a complex expression inside curly braces. |
||
120 | +369 |
- #' @param choices Vector to test against.+ #' @param ... additional arguments passed to `observeEvent` with the exception of `eventExpr` that is not allowed. |
||
121 | +370 |
- #' @param msg (`character(1)`) Error message to display if some elements of `x` are not elements of `choices`.+ #' @inheritParams shiny::observeEvent |
||
122 | +371 |
#' |
||
123 | +372 |
- #' @export+ #' @return An observer. |
||
124 | +373 |
#' |
||
125 | +374 |
- #' @examples+ #' @keywords internal |
||
126 | +375 |
- #' ui <- fluidPage(+ call_once_when <- function(eventExpr, # nolint: object_name. |
||
127 | +376 |
- #' selectInput(+ handlerExpr, # nolint: object_name. |
||
128 | +377 |
- #' "species",+ event.env = parent.frame(), # nolint: object_name. |
||
129 | +378 |
- #' "Select species",+ handler.env = parent.frame(), # nolint: object_name. |
||
130 | +379 |
- #' choices = c("setosa", "versicolor", "virginica", "unknown species"),+ ...) { |
||
131 | -+ | |||
380 | +198x |
- #' selected = "setosa",+ event_quo <- rlang::new_quosure(substitute(eventExpr), env = event.env) |
||
132 | -+ | |||
381 | +198x |
- #' multiple = FALSE+ handler_quo <- rlang::new_quosure(substitute(handlerExpr), env = handler.env) |
||
133 | +382 |
- #' ),+ |
||
134 | +383 |
- #' verbatimTextOutput("summary")+ # When `condExpr` is TRUE, then `handlerExpr` is evaluated once. |
||
135 | -+ | |||
384 | +198x |
- #' )+ activator <- reactive({ |
||
136 | -+ | |||
385 | +198x |
- #'+ if (isTRUE(rlang::eval_tidy(event_quo))) { |
||
137 | -+ | |||
386 | +166x |
- #' server <- function(input, output) {+ TRUE |
||
138 | +387 |
- #' output$summary <- renderPrint({+ } |
||
139 | +388 |
- #' validate_in(input$species, iris$Species, "Species does not exist.")+ }) |
||
140 | +389 |
- #' nrow(iris[iris$Species == input$species, ])+ |
||
141 | -+ | |||
390 | +198x |
- #' })+ observeEvent( |
||
142 | -+ | |||
391 | +198x |
- #' }+ eventExpr = activator(), |
||
143 | -+ | |||
392 | +198x |
- #' if (interactive()) {+ once = TRUE, |
||
144 | -+ | |||
393 | +198x |
- #' shinyApp(ui, server)+ handlerExpr = rlang::eval_tidy(handler_quo), |
||
145 | +394 |
- #' }+ ... |
||
146 | +395 |
- #'+ ) |
||
147 | +396 |
- validate_in <- function(x, choices, msg) {+ } |
||
148 | -! | +
1 | +
- validate(need(length(x) > 0 && length(choices) > 0 && all(x %in% choices), msg))+ #' Validate that dataset has a minimum number of observations |
||
149 | +2 |
- }+ #' |
|
150 | +3 |
-
+ #' `r lifecycle::badge("stable")` |
|
151 | +4 |
- #' Validates that vector has length greater than 0+ #' |
|
152 | +5 |
- #'+ #' This function is a wrapper for `shiny::validate`. |
|
153 | +6 |
- #' `r lifecycle::badge("stable")`+ #' |
|
154 | +7 |
- #'+ #' @param x (`data.frame`) |
|
155 | +8 |
- #' This function is a wrapper for `shiny::validate`.+ #' @param min_nrow (`numeric(1)`) Minimum allowed number of rows in `x`. |
|
156 | +9 |
- #'+ #' @param complete (`logical(1)`) Flag specifying whether to check only complete cases. Defaults to `FALSE`. |
|
157 | +10 |
- #' @param x vector+ #' @param allow_inf (`logical(1)`) Flag specifying whether to allow infinite values. Defaults to `TRUE`. |
|
158 | +11 |
- #' @param msg message to display+ #' @param msg (`character(1)`) Additional message to display alongside the default message. |
|
159 | +12 |
#' |
|
160 | +13 |
#' @export |
|
161 | +14 |
#' |
|
162 | +15 |
#' @examples |
|
163 | +16 |
- #' data <- data.frame(+ #' library(teal) |
|
164 | +17 |
- #' id = c(1:10, 11:20, 1:10),+ #' ui <- fluidPage( |
|
165 | +18 |
- #' strata = rep(c("A", "B"), each = 15)+ #' sliderInput("len", "Max Length of Sepal", |
|
166 | +19 |
- #' )+ #' min = 4.3, max = 7.9, value = 5 |
|
167 | +20 |
- #' ui <- fluidPage(+ #' ), |
|
168 | +21 |
- #' selectInput("ref1", "Select strata1 to compare",+ #' plotOutput("plot") |
|
169 | +22 |
- #' choices = c("A", "B", "C"), selected = "A"+ #' ) |
|
170 | +23 |
- #' ),+ #' |
|
171 | +24 |
- #' selectInput("ref2", "Select strata2 to compare",+ #' server <- function(input, output) { |
|
172 | +25 |
- #' choices = c("A", "B", "C"), selected = "B"+ #' output$plot <- renderPlot({ |
|
173 | +26 |
- #' ),+ #' iris_df <- iris[iris$Sepal.Length <= input$len, ] |
|
174 | +27 |
- #' verbatimTextOutput("arm_summary")+ #' validate_has_data( |
|
175 | +28 |
- #' )+ #' iris_df, |
|
176 | +29 |
- #'+ #' min_nrow = 10, |
|
177 | +30 |
- #' server <- function(input, output) {+ #' complete = FALSE, |
|
178 | +31 |
- #' output$arm_summary <- renderText({+ #' msg = "Please adjust Max Length of Sepal" |
|
179 | +32 |
- #' sample_1 <- data$id[data$strata == input$ref1]+ #' ) |
|
180 | +33 |
- #' sample_2 <- data$id[data$strata == input$ref2]+ #' |
|
181 | +34 |
- #'+ #' hist(iris_df$Sepal.Length, breaks = 5) |
|
182 | +35 |
- #' validate_has_elements(sample_1, "No subjects in strata1.")+ #' }) |
|
183 | +36 |
- #' validate_has_elements(sample_2, "No subjects in strata2.")+ #' } |
|
184 | +37 |
- #'+ #' if (interactive()) { |
|
185 | +38 |
- #' paste0(+ #' shinyApp(ui, server) |
|
186 | +39 |
- #' "Number of samples in: strata1=", length(sample_1),+ #' } |
|
187 | +40 |
- #' " comparions strata2=", length(sample_2)+ #' |
|
188 | +41 |
- #' )+ validate_has_data <- function(x, |
|
189 | +42 |
- #' })+ min_nrow = NULL, |
|
190 | +43 |
- #' }+ complete = FALSE, |
|
191 | +44 |
- #' if (interactive()) {+ allow_inf = TRUE, |
|
192 | +45 |
- #' shinyApp(ui, server)+ msg = NULL) { |
|
193 | -+ | ||
46 | +17x |
- #' }+ checkmate::assert_string(msg, null.ok = TRUE) |
|
194 | -+ | ||
47 | +15x |
- validate_has_elements <- function(x, msg) {+ checkmate::assert_data_frame(x) |
|
195 | -! | +||
48 | +15x |
- validate(need(length(x) > 0, msg))+ if (!is.null(min_nrow)) { |
|
196 | -+ | ||
49 | +15x |
- }+ if (complete) { |
|
197 | -+ | ||
50 | +5x |
-
+ complete_index <- stats::complete.cases(x) |
|
198 | -+ | ||
51 | +5x |
- #' Validates no intersection between two vectors+ validate(need( |
|
199 | -+ | ||
52 | +5x |
- #'+ sum(complete_index) > 0 && nrow(x[complete_index, , drop = FALSE]) >= min_nrow, |
|
200 | -+ | ||
53 | +5x |
- #' `r lifecycle::badge("stable")`+ paste(c(paste("Number of complete cases is less than:", min_nrow), msg), collapse = "\n") |
|
201 | +54 |
- #'+ )) |
|
202 | +55 |
- #' This function is a wrapper for `shiny::validate`.+ } else {+ |
+ |
56 | +10x | +
+ validate(need(+ |
+ |
57 | +10x | +
+ nrow(x) >= min_nrow,+ |
+ |
58 | +10x | +
+ paste(+ |
+ |
59 | +10x | +
+ c(paste("Minimum number of records not met: >=", min_nrow, "records required."), msg),+ |
+ |
60 | +10x | +
+ collapse = "\n" |
|
203 | +61 |
- #'+ ) |
|
204 | +62 |
- #' @param x vector+ )) |
|
205 | +63 |
- #' @param y vector+ } |
|
206 | +64 |
- #' @param msg (`character(1)`) message to display if `x` and `y` intersect+ + |
+ |
65 | +10x | +
+ if (!allow_inf) {+ |
+ |
66 | +6x | +
+ validate(need(+ |
+ |
67 | +6x | +
+ all(vapply(x, function(col) !is.numeric(col) || !any(is.infinite(col)), logical(1))),+ |
+ |
68 | +6x | +
+ "Dataframe contains Inf values which is not allowed." |
|
207 | +69 |
- #'+ )) |
|
208 | +70 |
- #' @export+ } |
|
209 | +71 |
- #'+ } |
|
210 | +72 |
- #' @examples+ } |
|
211 | +73 |
- #' data <- data.frame(+ |
|
212 | +74 |
- #' id = c(1:10, 11:20, 1:10),+ #' Validate that dataset has unique rows for key variables |
|
213 | +75 |
- #' strata = rep(c("A", "B", "C"), each = 10)+ #' |
|
214 | +76 |
- #' )+ #' `r lifecycle::badge("stable")` |
|
215 | +77 |
#' |
|
216 | +78 |
- #' ui <- fluidPage(+ #' This function is a wrapper for `shiny::validate`. |
|
217 | +79 |
- #' selectInput("ref1", "Select strata1 to compare",+ #' |
|
218 | +80 |
- #' choices = c("A", "B", "C"),+ #' @param x (`data.frame`) |
|
219 | +81 |
- #' selected = "A"+ #' @param key (`character`) Vector of ID variables from `x` that identify unique records. |
|
220 | +82 |
- #' ),+ #' |
|
221 | +83 |
- #' selectInput("ref2", "Select strata2 to compare",+ #' @export |
|
222 | +84 |
- #' choices = c("A", "B", "C"),+ #' |
|
223 | +85 |
- #' selected = "B"+ #' @examples |
|
224 | +86 |
- #' ),+ #' iris$id <- rep(1:50, times = 3) |
|
225 | +87 |
- #' verbatimTextOutput("summary")+ #' ui <- fluidPage( |
|
226 | +88 |
- #' )+ #' selectInput( |
|
227 | +89 |
- #'+ #' inputId = "species", |
|
228 | +90 |
- #' server <- function(input, output) {+ #' label = "Select species", |
|
229 | +91 |
- #' output$summary <- renderText({+ #' choices = c("setosa", "versicolor", "virginica"), |
|
230 | +92 |
- #' sample_1 <- data$id[data$strata == input$ref1]+ #' selected = "setosa", |
|
231 | +93 |
- #' sample_2 <- data$id[data$strata == input$ref2]+ #' multiple = TRUE |
|
232 | +94 |
- #'+ #' ), |
|
233 | +95 |
- #' validate_no_intersection(+ #' plotOutput("plot") |
|
234 | +96 |
- #' sample_1, sample_2,+ #' ) |
|
235 | +97 |
- #' "subjects within strata1 and strata2 cannot overlap"+ #' server <- function(input, output) { |
|
236 | +98 |
- #' )+ #' output$plot <- renderPlot({ |
|
237 | +99 |
- #' paste0(+ #' iris_f <- iris[iris$Species %in% input$species, ] |
|
238 | +100 |
- #' "Number of subject in: reference treatment=", length(sample_1),+ #' validate_one_row_per_id(iris_f, key = c("id")) |
|
239 | +101 |
- #' " comparions treatment=", length(sample_2)+ #' |
|
240 | +102 |
- #' )+ #' hist(iris_f$Sepal.Length, breaks = 5) |
|
241 | +103 |
#' }) |
|
242 | +104 |
#' } |
|
243 | +105 |
#' if (interactive()) { |
|
244 | +106 |
#' shinyApp(ui, server) |
|
245 | +107 |
#' } |
|
246 | +108 |
#' |
|
247 | +109 |
- validate_no_intersection <- function(x, y, msg) {+ validate_one_row_per_id <- function(x, key = c("USUBJID", "STUDYID")) { |
|
248 | +110 | ! |
- validate(need(length(intersect(x, y)) == 0, msg))+ validate(need(!any(duplicated(x[key])), paste("Found more than one row per id."))) |
249 | +111 |
} |
|
250 | -- | - - | -|
251 | +112 | ||
252 | +113 |
- #' Validates that dataset contains specific variable+ #' Validates that vector includes all expected values |
|
253 | +114 |
#' |
|
254 | +115 |
#' `r lifecycle::badge("stable")` |
|
255 | +116 |
#' |
|
256 | +117 |
#' This function is a wrapper for `shiny::validate`. |
|
257 | +118 |
#' |
|
258 | +119 |
- #' @param data (`data.frame`)+ #' @param x Vector of values to test. |
|
259 | +120 |
- #' @param varname (`character(1)`) name of variable to check for in `data`+ #' @param choices Vector to test against. |
|
260 | +121 |
- #' @param msg (`character(1)`) message to display if `data` does not include `varname`+ #' @param msg (`character(1)`) Error message to display if some elements of `x` are not elements of `choices`. |
|
261 | +122 |
#' |
|
262 | +123 |
#' @export |
|
263 | +124 |
#' |
|
264 | +125 |
#' @examples |
|
265 | -- |
- #' data <- data.frame(- |
- |
266 | -- |
- #' one = rep("a", length.out = 20),- |
- |
267 | -- |
- #' two = rep(c("a", "b"), length.out = 20)- |
- |
268 | +126 |
- #' )+ #' ui <- fluidPage( |
|
269 | +127 |
- #' ui <- fluidPage(+ #' selectInput( |
|
270 | +128 |
- #' selectInput(+ #' "species", |
|
271 | +129 |
- #' "var",+ #' "Select species", |
|
272 | +130 |
- #' "Select variable",+ #' choices = c("setosa", "versicolor", "virginica", "unknown species"), |
|
273 | +131 |
- #' choices = c("one", "two", "three", "four"),+ #' selected = "setosa", |
|
274 | +132 |
- #' selected = "one"+ #' multiple = FALSE |
|
275 | +133 |
#' ), |
|
276 | +134 |
#' verbatimTextOutput("summary") |
|
277 | +135 |
#' ) |
|
278 | +136 |
#' |
|
279 | +137 |
#' server <- function(input, output) { |
|
280 | +138 |
- #' output$summary <- renderText({+ #' output$summary <- renderPrint({ |
|
281 | +139 |
- #' validate_has_variable(data, input$var)+ #' validate_in(input$species, iris$Species, "Species does not exist.") |
|
282 | +140 |
- #' paste0("Selected treatment variables: ", paste(input$var, collapse = ", "))+ #' nrow(iris[iris$Species == input$species, ]) |
|
283 | +141 |
#' }) |
|
284 | +142 |
#' } |
|
285 | +143 |
#' if (interactive()) { |
|
286 | +144 |
#' shinyApp(ui, server) |
|
287 | +145 |
#' } |
|
288 | -- |
- validate_has_variable <- function(data, varname, msg) {- |
- |
289 | -! | -
- if (length(varname) != 0) {- |
- |
290 | -! | -
- has_vars <- varname %in% names(data)- |
- |
291 | -- | - - | -|
292 | -! | -
- if (!all(has_vars)) {- |
- |
293 | -! | -
- if (missing(msg)) {- |
- |
294 | -! | -
- msg <- sprintf(- |
- |
295 | -! | -
- "%s does not have the required variables: %s.",- |
- |
296 | -! | -
- deparse(substitute(data)),- |
- |
297 | -! | -
- toString(varname[!has_vars])- |
- |
298 | +146 |
- )+ #' |
|
299 | +147 |
- }+ validate_in <- function(x, choices, msg) { |
|
300 | +148 | ! |
- validate(need(FALSE, msg))- |
-
301 | -- |
- }- |
- |
302 | -- |
- }+ validate(need(length(x) > 0 && length(choices) > 0 && all(x %in% choices), msg)) |
|
303 | +149 |
} |
|
304 | +150 | ||
305 | +151 |
- #' Validate that variables has expected number of levels+ #' Validates that vector has length greater than 0 |
|
306 | +152 |
#' |
|
307 | +153 |
#' `r lifecycle::badge("stable")` |
|
308 | +154 |
#' |
|
309 | -- |
- #' If the number of levels of `x` is less than `min_levels`- |
- |
310 | -- |
- #' or greater than `max_levels` the validation will fail.- |
- |
311 | +155 |
#' This function is a wrapper for `shiny::validate`. |
|
312 | +156 |
#' |
|
313 | -- |
- #' @param x variable name. If `x` is not a factor, the unique values- |
- |
314 | -- |
- #' are treated as levels.- |
- |
315 | +157 |
- #' @param min_levels cutoff for minimum number of levels of `x`+ #' @param x vector |
|
316 | +158 |
- #' @param max_levels cutoff for maximum number of levels of `x`+ #' @param msg message to display |
|
317 | +159 |
- #' @param var_name name of variable being validated for use in+ #' |
|
318 | +160 |
- #' validation message+ #' @export |
|
319 | +161 |
#' |
|
320 | -- |
- #' @export- |
- |
321 | +162 |
#' @examples |
|
322 | +163 |
#' data <- data.frame( |
|
323 | -- |
- #' one = rep("a", length.out = 20),- |
- |
324 | -- |
- #' two = rep(c("a", "b"), length.out = 20),- |
- |
325 | -- |
- #' three = rep(c("a", "b", "c"), length.out = 20),- |
- |
326 | +164 |
- #' four = rep(c("a", "b", "c", "d"), length.out = 20),+ #' id = c(1:10, 11:20, 1:10), |
|
327 | +165 |
- #' stringsAsFactors = TRUE+ #' strata = rep(c("A", "B"), each = 15) |
|
328 | +166 |
#' ) |
|
329 | +167 |
#' ui <- fluidPage( |
|
330 | +168 |
- #' selectInput(+ #' selectInput("ref1", "Select strata1 to compare", |
|
331 | +169 |
- #' "var",+ #' choices = c("A", "B", "C"), selected = "A" |
|
332 | +170 |
- #' "Select variable",+ #' ), |
|
333 | +171 |
- #' choices = c("one", "two", "three", "four"),+ #' selectInput("ref2", "Select strata2 to compare", |
|
334 | +172 |
- #' selected = "one"+ #' choices = c("A", "B", "C"), selected = "B" |
|
335 | +173 |
#' ), |
|
336 | +174 |
- #' verbatimTextOutput("summary")+ #' verbatimTextOutput("arm_summary") |
|
337 | +175 |
#' ) |
|
338 | +176 |
#' |
|
339 | +177 |
#' server <- function(input, output) { |
|
340 | +178 |
- #' output$summary <- renderText({+ #' output$arm_summary <- renderText({ |
|
341 | +179 |
- #' validate_n_levels(data[[input$var]], min_levels = 2, max_levels = 15, var_name = input$var)+ #' sample_1 <- data$id[data$strata == input$ref1] |
|
342 | +180 |
- #' paste0(+ #' sample_2 <- data$id[data$strata == input$ref2] |
|
343 | +181 |
- #' "Levels of selected treatment variable: ",+ #' |
|
344 | +182 |
- #' paste(levels(data[[input$var]]),+ #' validate_has_elements(sample_1, "No subjects in strata1.") |
|
345 | +183 |
- #' collapse = ", "+ #' validate_has_elements(sample_2, "No subjects in strata2.") |
|
346 | +184 |
- #' )+ #' |
|
347 | +185 |
- #' )+ #' paste0( |
|
348 | +186 |
- #' })+ #' "Number of samples in: strata1=", length(sample_1), |
|
349 | +187 |
- #' }+ #' " comparions strata2=", length(sample_2) |
|
350 | +188 |
- #' if (interactive()) {+ #' ) |
|
351 | +189 |
- #' shinyApp(ui, server)+ #' }) |
|
352 | +190 |
#' } |
|
353 | +191 |
- validate_n_levels <- function(x, min_levels = 1, max_levels = 12, var_name) {+ #' if (interactive()) { |
|
354 | -! | +||
192 | +
- x_levels <- if (is.factor(x)) {+ #' shinyApp(ui, server) |
||
355 | -! | +||
193 | +
- levels(x)+ #' } |
||
356 | +194 |
- } else {+ validate_has_elements <- function(x, msg) { |
|
357 | +195 | ! |
- unique(x)+ validate(need(length(x) > 0, msg)) |
358 | +196 |
- }+ } |
|
359 | +197 | ||
360 | -! | -
- if (!is.null(min_levels) && !(is.null(max_levels))) {- |
- |
361 | -! | -
- validate(need(- |
- |
362 | -! | +||
198 | +
- length(x_levels) >= min_levels && length(x_levels) <= max_levels,+ #' Validates no intersection between two vectors |
||
363 | -! | +||
199 | +
- sprintf(+ #' |
||
364 | -! | +||
200 | +
- "%s variable needs minimum %s level(s) and maximum %s level(s).",+ #' `r lifecycle::badge("stable")` |
||
365 | -! | +||
201 | +
- var_name, min_levels, max_levels+ #' |
||
366 | +202 |
- )+ #' This function is a wrapper for `shiny::validate`. |
|
367 | +203 |
- ))+ #' |
|
368 | -! | +||
204 | +
- } else if (!is.null(min_levels)) {+ #' @param x vector |
||
369 | -! | +||
205 | +
- validate(need(+ #' @param y vector |
||
370 | -! | +||
206 | +
- length(x_levels) >= min_levels,+ #' @param msg (`character(1)`) message to display if `x` and `y` intersect |
||
371 | -! | +||
207 | +
- sprintf("%s variable needs minimum %s levels(s)", var_name, min_levels)+ #' |
||
372 | +208 |
- ))+ #' @export |
|
373 | -! | +||
209 | +
- } else if (!is.null(max_levels)) {+ #' |
||
374 | -! | +||
210 | +
- validate(need(+ #' @examples |
||
375 | -! | +||
211 | +
- length(x_levels) <= max_levels,+ #' data <- data.frame( |
||
376 | -! | +||
212 | +
- sprintf("%s variable needs maximum %s level(s)", var_name, max_levels)+ #' id = c(1:10, 11:20, 1:10), |
||
377 | +213 |
- ))+ #' strata = rep(c("A", "B", "C"), each = 10) |
|
378 | +214 |
- }+ #' ) |
|
379 | +215 |
- }+ #' |
1 | +216 |
- #' Data summary+ #' ui <- fluidPage( |
|
2 | +217 |
- #' @description+ #' selectInput("ref1", "Select strata1 to compare", |
|
3 | +218 |
- #' Module and its utils to display the number of rows and subjects in the filtered and unfiltered data.+ #' choices = c("A", "B", "C"), |
|
4 | +219 |
- #'+ #' selected = "A" |
|
5 | +220 |
- #' @details Handling different data classes:+ #' ), |
|
6 | +221 |
- #' `get_filter_overview()` is a pseudo S3 method which has variants for:+ #' selectInput("ref2", "Select strata2 to compare", |
|
7 | +222 |
- #' - `array` (`data.frame`, `DataFrame`, `array`, `Matrix` and `SummarizedExperiment`): Method variant+ #' choices = c("A", "B", "C"), |
|
8 | +223 |
- #' can be applied to any two-dimensional objects on which [ncol()] can be used.+ #' selected = "B" |
|
9 | +224 |
- #' - `MultiAssayExperiment`: for which summary contains counts for `colData` and all `experiments`.+ #' ), |
|
10 | +225 |
- #' - For other data types module displays data name with warning icon and no more details.+ #' verbatimTextOutput("summary") |
|
11 | +226 |
- #'+ #' ) |
|
12 | +227 |
- #' Module includes also "Show/Hide unsupported" button to toggle rows of the summary table+ #' |
|
13 | +228 |
- #' containing datasets where number of observations are not calculated.+ #' server <- function(input, output) { |
|
14 | +229 |
- #'+ #' output$summary <- renderText({ |
|
15 | +230 |
- #' @param id (`character(1)`) `shiny` module instance id.+ #' sample_1 <- data$id[data$strata == input$ref1] |
|
16 | +231 |
- #' @param teal_data (`reactive` returning `teal_data`)+ #' sample_2 <- data$id[data$strata == input$ref2] |
|
17 | +232 |
#' |
|
18 | +233 |
- #' @name module_data_summary+ #' validate_no_intersection( |
|
19 | +234 |
- #' @rdname module_data_summary+ #' sample_1, sample_2, |
|
20 | +235 |
- #' @keywords internal+ #' "subjects within strata1 and strata2 cannot overlap" |
|
21 | +236 |
- #' @return `NULL`.+ #' ) |
|
22 | +237 |
- NULL+ #' paste0( |
|
23 | +238 |
-
+ #' "Number of subject in: reference treatment=", length(sample_1), |
|
24 | +239 |
- #' @rdname module_data_summary+ #' " comparions treatment=", length(sample_2) |
|
25 | +240 |
- ui_data_summary <- function(id) {+ #' ) |
|
26 | -! | +||
241 | +
- ns <- NS(id)+ #' }) |
||
27 | -! | +||
242 | +
- content_id <- ns("filters_overview_contents")+ #' } |
||
28 | -! | +||
243 | +
- tags$div(+ #' if (interactive()) { |
||
29 | -! | +||
244 | +
- id = id,+ #' shinyApp(ui, server) |
||
30 | -! | +||
245 | +
- class = "well",+ #' } |
||
31 | -! | +||
246 | +
- tags$div(+ #' |
||
32 | -! | +||
247 | +
- class = "row",+ validate_no_intersection <- function(x, y, msg) { |
||
33 | +248 | ! |
- tags$div(+ validate(need(length(intersect(x, y)) == 0, msg)) |
34 | -! | +||
249 | +
- class = "col-sm-9",+ } |
||
35 | -! | +||
250 | +
- tags$label("Active Filter Summary", class = "text-primary mb-4")+ |
||
36 | +251 |
- ),+ |
|
37 | -! | +||
252 | +
- tags$div(+ #' Validates that dataset contains specific variable |
||
38 | -! | +||
253 | +
- class = "col-sm-3",+ #' |
||
39 | -! | +||
254 | +
- tags$i(+ #' `r lifecycle::badge("stable")` |
||
40 | -! | +||
255 | +
- class = "remove pull-right fa fa-angle-down",+ #' |
||
41 | -! | +||
256 | +
- style = "cursor: pointer;",+ #' This function is a wrapper for `shiny::validate`. |
||
42 | -! | +||
257 | +
- title = "fold/expand data summary panel",+ #' |
||
43 | -! | +||
258 | +
- onclick = sprintf("togglePanelItems(this, '%s', 'fa-angle-right', 'fa-angle-down');", content_id)+ #' @param data (`data.frame`) |
||
44 | +259 |
- )+ #' @param varname (`character(1)`) name of variable to check for in `data` |
|
45 | +260 |
- )+ #' @param msg (`character(1)`) message to display if `data` does not include `varname` |
|
46 | +261 |
- ),+ #' |
|
47 | -! | +||
262 | +
- tags$div(+ #' @export |
||
48 | -! | +||
263 | +
- id = content_id,+ #' |
||
49 | -! | +||
264 | +
- tags$div(+ #' @examples |
||
50 | -! | +||
265 | +
- class = "teal_active_summary_filter_panel",+ #' data <- data.frame( |
||
51 | -! | +||
266 | +
- tableOutput(ns("table"))+ #' one = rep("a", length.out = 20), |
||
52 | +267 |
- )+ #' two = rep(c("a", "b"), length.out = 20) |
|
53 | +268 |
- )+ #' ) |
|
54 | +269 |
- )+ #' ui <- fluidPage( |
|
55 | +270 |
- }+ #' selectInput( |
|
56 | +271 |
-
+ #' "var", |
|
57 | +272 |
- #' @rdname module_data_summary+ #' "Select variable", |
|
58 | +273 |
- srv_data_summary <- function(id, data) {+ #' choices = c("one", "two", "three", "four"), |
|
59 | -86x | +||
274 | +
- assert_reactive(data)+ #' selected = "one" |
||
60 | -86x | +||
275 | +
- moduleServer(+ #' ), |
||
61 | -86x | +||
276 | +
- id = id,+ #' verbatimTextOutput("summary") |
||
62 | -86x | +||
277 | +
- function(input, output, session) {+ #' ) |
||
63 | -86x | +||
278 | +
- logger::log_debug("srv_data_summary initializing")+ #' |
||
64 | +279 |
-
+ #' server <- function(input, output) { |
|
65 | -86x | +||
280 | +
- summary_table <- reactive({+ #' output$summary <- renderText({ |
||
66 | -94x | +||
281 | +
- req(inherits(data(), "teal_data"))+ #' validate_has_variable(data, input$var) |
||
67 | -88x | +||
282 | +
- if (!length(data())) {+ #' paste0("Selected treatment variables: ", paste(input$var, collapse = ", ")) |
||
68 | -! | +||
283 | +
- return(NULL)+ #' }) |
||
69 | +284 |
- }+ #' } |
|
70 | -88x | +||
285 | +
- get_filter_overview_wrapper(data)+ #' if (interactive()) { |
||
71 | +286 |
- })+ #' shinyApp(ui, server) |
|
72 | +287 |
-
+ #' } |
|
73 | -86x | +||
288 | +
- output$table <- renderUI({+ validate_has_variable <- function(data, varname, msg) { |
||
74 | -94x | +||
289 | +! |
- summary_table_out <- try(summary_table(), silent = TRUE)+ if (length(varname) != 0) { |
|
75 | -94x | +||
290 | +! |
- if (inherits(summary_table_out, "try-error")) {+ has_vars <- varname %in% names(data) |
|
76 | +291 |
- # Ignore silent shiny error+ |
|
77 | -6x | +||
292 | +! |
- if (!inherits(attr(summary_table_out, "condition"), "shiny.silent.error")) {+ if (!all(has_vars)) { |
|
78 | +293 | ! |
- stop("Error occurred during data processing. See details in the main panel.")+ if (missing(msg)) { |
79 | -+ | ||
294 | +! |
- }+ msg <- sprintf( |
|
80 | -88x | +||
295 | +! |
- } else if (is.null(summary_table_out)) {+ "%s does not have the required variables: %s.", |
|
81 | -2x | +||
296 | +! |
- "no datasets to show"+ deparse(substitute(data)),+ |
+ |
297 | +! | +
+ toString(varname[!has_vars]) |
|
82 | +298 |
- } else {+ ) |
|
83 | -86x | +||
299 | +
- is_unsupported <- apply(summary_table(), 1, function(x) all(is.na(x[-1])))+ } |
||
84 | -86x | +||
300 | +! |
- summary_table_out[is.na(summary_table_out)] <- ""+ validate(need(FALSE, msg)) |
|
85 | -86x | +||
301 | +
- body_html <- apply(+ } |
||
86 | -86x | +||
302 | +
- summary_table_out,+ } |
||
87 | -86x | +||
303 | +
- 1,+ } |
||
88 | -86x | +||
304 | +
- function(x) {+ |
||
89 | -162x | +||
305 | +
- is_supported <- !all(x[-1] == "")+ #' Validate that variables has expected number of levels |
||
90 | -162x | +||
306 | +
- if (is_supported) {+ #' |
||
91 | -153x | +||
307 | +
- tags$tr(+ #' `r lifecycle::badge("stable")` |
||
92 | -153x | +||
308 | +
- tagList(+ #' |
||
93 | -153x | +||
309 | +
- tags$td(x[1]),+ #' If the number of levels of `x` is less than `min_levels` |
||
94 | -153x | +||
310 | +
- lapply(x[-1], tags$td)+ #' or greater than `max_levels` the validation will fail. |
||
95 | +311 |
- )+ #' This function is a wrapper for `shiny::validate`. |
|
96 | +312 |
- )+ #' |
|
97 | +313 |
- }+ #' @param x variable name. If `x` is not a factor, the unique values |
|
98 | +314 |
- }+ #' are treated as levels. |
|
99 | +315 |
- )+ #' @param min_levels cutoff for minimum number of levels of `x` |
|
100 | +316 |
-
+ #' @param max_levels cutoff for maximum number of levels of `x` |
|
101 | -86x | +||
317 | +
- header_labels <- tools::toTitleCase(names(summary_table_out))+ #' @param var_name name of variable being validated for use in |
||
102 | -86x | +||
318 | +
- header_labels[header_labels == "Dataname"] <- "Data Name"+ #' validation message |
||
103 | -86x | +||
319 | +
- header_html <- tags$tr(tagList(lapply(header_labels, tags$td)))+ #' |
||
104 | +320 |
-
+ #' @export |
|
105 | -86x | +||
321 | +
- table_html <- tags$table(+ #' @examples |
||
106 | -86x | +||
322 | +
- class = "table custom-table",+ #' data <- data.frame( |
||
107 | -86x | +||
323 | +
- tags$thead(header_html),+ #' one = rep("a", length.out = 20), |
||
108 | -86x | +||
324 | +
- tags$tbody(body_html)+ #' two = rep(c("a", "b"), length.out = 20), |
||
109 | +325 |
- )+ #' three = rep(c("a", "b", "c"), length.out = 20), |
|
110 | -86x | +||
326 | +
- div(+ #' four = rep(c("a", "b", "c", "d"), length.out = 20), |
||
111 | -86x | +||
327 | +
- table_html,+ #' stringsAsFactors = TRUE |
||
112 | -86x | +||
328 | +
- if (any(is_unsupported)) {+ #' ) |
||
113 | -9x | +||
329 | +
- p(+ #' ui <- fluidPage( |
||
114 | -9x | +||
330 | +
- class = c("pull-right", "float-right", "text-secondary"),+ #' selectInput( |
||
115 | -9x | +||
331 | +
- style = "font-size: 0.8em;",+ #' "var", |
||
116 | -9x | +||
332 | +
- sprintf("And %s more unfilterable object(s)", sum(is_unsupported)),+ #' "Select variable", |
||
117 | -9x | +||
333 | +
- icon(+ #' choices = c("one", "two", "three", "four"), |
||
118 | -9x | +||
334 | +
- name = "far fa-circle-question",+ #' selected = "one" |
||
119 | -9x | +||
335 | +
- title = paste(+ #' ), |
||
120 | -9x | +||
336 | +
- sep = "",+ #' verbatimTextOutput("summary") |
||
121 | -9x | +||
337 | +
- collapse = "\n",+ #' ) |
||
122 | -9x | +||
338 | +
- shQuote(summary_table()[is_unsupported, "dataname"]),+ #' |
||
123 | +339 |
- " (",+ #' server <- function(input, output) { |
|
124 | -9x | +||
340 | +
- vapply(+ #' output$summary <- renderText({ |
||
125 | -9x | +||
341 | +
- summary_table()[is_unsupported, "dataname"],+ #' validate_n_levels(data[[input$var]], min_levels = 2, max_levels = 15, var_name = input$var) |
||
126 | -9x | +||
342 | +
- function(x) class(data()[[x]])[1],+ #' paste0( |
||
127 | -9x | +||
343 | +
- character(1L)+ #' "Levels of selected treatment variable: ", |
||
128 | +344 |
- ),+ #' paste(levels(data[[input$var]]), |
|
129 | +345 |
- ")"+ #' collapse = ", " |
|
130 | +346 |
- )+ #' ) |
|
131 | +347 |
- )+ #' ) |
|
132 | +348 |
- )+ #' }) |
|
133 | +349 |
- }+ #' } |
|
134 | +350 |
- )+ #' if (interactive()) { |
|
135 | +351 |
- }+ #' shinyApp(ui, server) |
|
136 | +352 |
- })+ #' } |
|
137 | +353 |
-
+ validate_n_levels <- function(x, min_levels = 1, max_levels = 12, var_name) { |
|
138 | -86x | +||
354 | +! |
- NULL+ x_levels <- if (is.factor(x)) { |
|
139 | -+ | ||
355 | +! |
- }+ levels(x) |
|
140 | +356 |
- )+ } else {+ |
+ |
357 | +! | +
+ unique(x) |
|
141 | +358 |
- }+ } |
|
142 | +359 | ||
143 | -+ | ||
360 | +! |
- #' @rdname module_data_summary+ if (!is.null(min_levels) && !(is.null(max_levels))) { |
|
144 | -+ | ||
361 | +! |
- get_filter_overview_wrapper <- function(teal_data) {+ validate(need( |
|
145 | -+ | ||
362 | +! |
- # Sort datanames in topological order+ length(x_levels) >= min_levels && length(x_levels) <= max_levels, |
|
146 | -88x | +||
363 | +! |
- datanames <- names(teal_data())+ sprintf( |
|
147 | -88x | +||
364 | +! |
- joinkeys <- teal.data::join_keys(teal_data())+ "%s variable needs minimum %s level(s) and maximum %s level(s).",+ |
+ |
365 | +! | +
+ var_name, min_levels, max_levels |
|
148 | +366 |
-
+ ) |
|
149 | -88x | +||
367 | +
- current_data_objs <- sapply(+ )) |
||
150 | -88x | +||
368 | +! |
- datanames,+ } else if (!is.null(min_levels)) { |
|
151 | -88x | +||
369 | +! |
- function(name) teal_data()[[name]],+ validate(need( |
|
152 | -88x | +||
370 | +! |
- simplify = FALSE+ length(x_levels) >= min_levels,+ |
+ |
371 | +! | +
+ sprintf("%s variable needs minimum %s levels(s)", var_name, min_levels) |
|
153 | +372 |
- )+ )) |
|
154 | -88x | +||
373 | +! |
- initial_data_objs <- teal_data()[[".raw_data"]]+ } else if (!is.null(max_levels)) { |
|
155 | -+ | ||
374 | +! |
-
+ validate(need( |
|
156 | -88x | +||
375 | +! |
- out <- lapply(+ length(x_levels) <= max_levels, |
|
157 | -88x | +||
376 | +! |
- datanames,+ sprintf("%s variable needs maximum %s level(s)", var_name, max_levels) |
|
158 | -88x | +||
377 | +
- function(dataname) {+ )) |
||
159 | -157x | +||
378 | +
- parent <- teal.data::parent(joinkeys, dataname)+ } |
||
160 | -157x | +||
379 | +
- subject_keys <- if (length(parent) > 0) {+ } |
||
161 | -8x | +
1 | +
- names(joinkeys[dataname, parent])+ #' Data module for `teal` transformations and output customization |
||
162 | +2 |
- } else {+ #' |
|
163 | -149x | +||
3 | +
- joinkeys[dataname, dataname]+ #' @description |
||
164 | +4 |
- }+ #' `r lifecycle::badge("experimental")` |
|
165 | -157x | +||
5 | +
- get_filter_overview(+ #' |
||
166 | -157x | +||
6 | +
- current_data = current_data_objs[[dataname]],+ #' `teal_transform_module` provides a `shiny` module that enables data transformations within a `teal` application |
||
167 | -157x | +||
7 | +
- initial_data = initial_data_objs[[dataname]],+ #' and allows for customization of outputs generated by modules. |
||
168 | -157x | +||
8 | +
- dataname = dataname,+ #' |
||
169 | -157x | +||
9 | +
- subject_keys = subject_keys+ #' # Transforming Module Inputs in `teal` |
||
170 | +10 |
- )+ #' |
|
171 | +11 |
- }+ #' Data transformations occur after data has been filtered in `teal`. |
|
172 | +12 |
- )+ #' The transformed data is then passed to the `server` of [`teal_module()`] and managed by `teal`'s internal processes. |
|
173 | +13 |
-
+ #' The primary advantage of `teal_transform_module` over custom modules is in its error handling, where all warnings and |
|
174 | -88x | +||
14 | +
- do.call(.smart_rbind, out)+ #' errors are managed by `teal`, allowing developers to focus on transformation logic. |
||
175 | +15 |
- }+ #' |
|
176 | +16 |
-
+ #' For more details, see the vignette: `vignette("data-transform-as-shiny-module", package = "teal")`. |
|
177 | +17 |
-
+ #' |
|
178 | +18 |
- #' @rdname module_data_summary+ #' # Customizing Module Outputs |
|
179 | +19 |
- #' @param current_data (`object`) current object (after filtering and transforming).+ #' |
|
180 | +20 |
- #' @param initial_data (`object`) initial object.+ #' `teal_transform_module` also allows developers to modify any object created within [`teal.data::teal_data`]. |
|
181 | +21 |
- #' @param dataname (`character(1)`)+ #' This means you can use it to customize not only datasets but also tables, listings, and graphs. |
|
182 | +22 |
- #' @param subject_keys (`character`) names of the columns which determine a single unique subjects+ #' Some [`teal_modules`] permit developers to inject custom `shiny` modules to enhance displayed outputs. |
|
183 | +23 |
- get_filter_overview <- function(current_data, initial_data, dataname, subject_keys) {+ #' To manage these `decorators` within your module, use [`ui_transform_teal_data()`] and [`srv_transform_teal_data()`]. |
|
184 | -162x | +||
24 | +
- if (inherits(current_data, c("data.frame", "DataFrame", "array", "Matrix", "SummarizedExperiment"))) {+ #' (For further guidance on managing decorators, refer to `ui_args` and `srv_args` in the vignette documentation.) |
||
185 | -152x | +||
25 | +
- get_filter_overview_array(current_data, initial_data, dataname, subject_keys)+ #' |
||
186 | -10x | +||
26 | +
- } else if (inherits(current_data, "MultiAssayExperiment")) {+ #' See the vignette `vignette("decorate-modules-output", package = "teal")` for additional examples. |
||
187 | -1x | +||
27 | +
- get_filter_overview_MultiAssayExperiment(current_data, initial_data, dataname)+ #' |
||
188 | +28 |
- } else {+ #' # `server` as a language |
|
189 | -9x | +||
29 | +
- data.frame(dataname = dataname)+ #' |
||
190 | +30 |
- }+ #' The `server` function in `teal_transform_module` must return a reactive [`teal.data::teal_data`] object. |
|
191 | +31 |
- }+ #' For simple transformations without complex reactivity, the `server` function might look like this:s |
|
192 | +32 |
-
+ #' |
|
193 | +33 |
- #' @rdname module_data_summary+ #' ``` |
|
194 | +34 |
- get_filter_overview_array <- function(current_data,+ #' function(id, data) { |
|
195 | +35 |
- initial_data,+ #' moduleServer(id, function(input, output, session) { |
|
196 | +36 |
- dataname,+ #' reactive({ |
|
197 | +37 |
- subject_keys) {+ #' within( |
|
198 | -152x | +||
38 | +
- if (length(subject_keys) == 0) {+ #' data(), |
||
199 | -138x | +||
39 | +
- data.frame(+ #' expr = x <- subset(x, col == level), |
||
200 | -138x | +||
40 | +
- dataname = dataname,+ #' level = input$level |
||
201 | -138x | +||
41 | +
- obs = if (!is.null(initial_data)) {+ #' ) |
||
202 | -127x | +||
42 | +
- sprintf("%s/%s", nrow(current_data), nrow(initial_data))+ #' }) |
||
203 | +43 |
- } else {+ #' }) |
|
204 | -11x | +||
44 | ++ |
+ #' }+ |
+ |
45 | ++ |
+ #' ```+ |
+ |
46 | +
- nrow(current_data)+ #' |
||
205 | +47 |
- }+ #' The example above can be simplified using `make_teal_transform_server`, where `level` is automatically matched to the |
|
206 | +48 |
- )+ #' corresponding `input` parameter: |
|
207 | +49 |
- } else {+ #' |
|
208 | -14x | +||
50 | +
- data.frame(+ #' ``` |
||
209 | -14x | +||
51 | +
- dataname = dataname,+ #' make_teal_transform_server(expr = expression(x <- subset(x, col == level))) |
||
210 | -14x | +||
52 | +
- obs = if (!is.null(initial_data)) {+ #' ``` |
||
211 | -13x | +||
53 | +
- sprintf("%s/%s", nrow(current_data), nrow(initial_data))+ #' @inheritParams teal_data_module |
||
212 | +54 |
- } else {+ #' @param server (`function(id, data)` or `expression`) |
|
213 | -1x | +||
55 | +
- nrow(current_data)+ #' A `shiny` module server function that takes `id` and `data` as arguments, where `id` is the module id and `data` |
||
214 | +56 |
- },+ #' is the reactive `teal_data` input. The `server` function must return a reactive expression containing a `teal_data` |
|
215 | -14x | +||
57 | +
- subjects = if (!is.null(initial_data)) {+ #' object. For simplified syntax, use [`make_teal_transform_server()`]. |
||
216 | -13x | +||
58 | +
- sprintf("%s/%s", nrow(unique(current_data[subject_keys])), nrow(unique(initial_data[subject_keys])))+ #' @param datanames (`character`) |
||
217 | +59 |
- } else {+ #' Specifies the names of datasets relevant to the module. Only filters for the specified `datanames` will be displayed |
|
218 | -1x | +||
60 | +
- nrow(unique(current_data[subject_keys]))+ #' in the filter panel. The keyword `"all"` can be used to display filters for all datasets. `datanames` are |
||
219 | +61 |
- }+ #' automatically appended to the [`modules()`] `datanames`. |
|
220 | +62 |
- )+ #' |
|
221 | +63 |
- }+ #' |
|
222 | +64 |
- }+ #' @examples |
|
223 | +65 |
-
+ #' data_transformators <- list( |
|
224 | +66 |
- #' @rdname module_data_summary+ #' teal_transform_module( |
|
225 | +67 |
- get_filter_overview_MultiAssayExperiment <- function(current_data, # nolint: object_length, object_name.+ #' label = "Static transformator for iris", |
|
226 | +68 |
- initial_data,+ #' datanames = "iris", |
|
227 | +69 |
- dataname) {+ #' server = function(id, data) { |
|
228 | -1x | +||
70 | +
- experiment_names <- names(current_data)+ #' moduleServer(id, function(input, output, session) { |
||
229 | -1x | +||
71 | +
- mae_info <- data.frame(+ #' reactive({ |
||
230 | -1x | +||
72 | +
- dataname = dataname,+ #' within(data(), { |
||
231 | -1x | +||
73 | +
- subjects = if (!is.null(initial_data)) {+ #' iris <- head(iris, 5) |
||
232 | -! | +||
74 | +
- sprintf("%s/%s", nrow(current_data@colData), nrow(initial_data@colData))+ #' }) |
||
233 | +75 |
- } else {+ #' }) |
|
234 | -1x | +||
76 | +
- nrow(current_data@colData)+ #' }) |
||
235 | +77 |
- }+ #' } |
|
236 | +78 |
- )+ #' ), |
|
237 | +79 |
-
+ #' teal_transform_module( |
|
238 | -1x | +||
80 | +
- experiment_obs_info <- do.call("rbind", lapply(+ #' label = "Interactive transformator for iris", |
||
239 | -1x | +||
81 | +
- experiment_names,+ #' datanames = "iris", |
||
240 | -1x | +||
82 | +
- function(experiment_name) {+ #' ui = function(id) { |
||
241 | -5x | +||
83 | +
- transform(+ #' ns <- NS(id) |
||
242 | -5x | +||
84 | +
- get_filter_overview(+ #' tags$div( |
||
243 | -5x | +||
85 | +
- current_data[[experiment_name]],+ #' numericInput(ns("n_cols"), "Show n columns", value = 5, min = 1, max = 5, step = 1) |
||
244 | -5x | +||
86 | +
- initial_data[[experiment_name]],+ #' ) |
||
245 | -5x | +||
87 | +
- dataname = experiment_name,+ #' }, |
||
246 | -5x | +||
88 | +
- subject_keys = join_keys() # empty join keys+ #' server = function(id, data) { |
||
247 | +89 |
- ),+ #' moduleServer(id, function(input, output, session) { |
|
248 | -5x | +||
90 | +
- dataname = paste0(" - ", experiment_name)+ #' reactive({ |
||
249 | +91 |
- )+ #' within(data(), |
|
250 | +92 |
- }+ #' { |
|
251 | +93 |
- ))+ #' iris <- iris[, 1:n_cols] |
|
252 | +94 |
-
+ #' }, |
|
253 | -1x | +||
95 | +
- get_experiment_keys <- function(mae, experiment) {+ #' n_cols = input$n_cols |
||
254 | -5x | +||
96 | +
- sample_subset <- mae@sampleMap[mae@sampleMap$colname %in% colnames(experiment), ]+ #' ) |
||
255 | -5x | +||
97 | +
- length(unique(sample_subset$primary))+ #' }) |
||
256 | +98 |
- }+ #' }) |
|
257 | +99 |
-
+ #' } |
|
258 | -1x | +||
100 | +
- experiment_subjects_info <- do.call("rbind", lapply(+ #' ) |
||
259 | -1x | +||
101 | +
- experiment_names,+ #' ) |
||
260 | -1x | +||
102 | +
- function(experiment_name) {+ #' |
||
261 | -5x | +||
103 | +
- data.frame(+ #' output_decorator <- teal_transform_module( |
||
262 | -5x | +||
104 | +
- subjects = if (!is.null(initial_data)) {+ #' server = make_teal_transform_server( |
||
263 | -! | +||
105 | +
- sprintf(+ #' expression( |
||
264 | -! | +||
106 | +
- "%s/%s",+ #' object <- rev(object) |
||
265 | -! | +||
107 | +
- get_experiment_keys(current_data, current_data[[experiment_name]]),+ #' ) |
||
266 | -! | +||
108 | +
- get_experiment_keys(current_data, initial_data[[experiment_name]])+ #' ) |
||
267 | +109 |
- )+ #' ) |
|
268 | +110 |
- } else {+ #' |
|
269 | -5x | +||
111 | +
- get_experiment_keys(current_data, current_data[[experiment_name]])+ #' app <- init( |
||
270 | +112 |
- }+ #' data = teal_data(iris = iris), |
|
271 | +113 |
- )+ #' modules = example_module( |
|
272 | +114 |
- }+ #' transformators = data_transformators, |
|
273 | +115 |
- ))+ #' decorators = list(output_decorator) |
|
274 | +116 |
-
+ #' ) |
|
275 | -1x | +||
117 | +
- experiment_info <- cbind(experiment_obs_info, experiment_subjects_info)+ #' ) |
||
276 | -1x | +||
118 | +
- .smart_rbind(mae_info, experiment_info)+ #' if (interactive()) { |
||
277 | +119 |
- }+ #' shinyApp(app$ui, app$server) |
1 | +120 |
- #' Filter panel module in teal+ #' } |
||
2 | +121 |
#' |
||
3 | +122 |
- #' Creates filter panel module from `teal_data` object and returns `teal_data`. It is build in a way+ #' @name teal_transform_module |
||
4 | +123 |
- #' that filter panel changes and anything what happens before (e.g. [`module_init_data`]) is triggering+ #' |
||
5 | +124 |
- #' further reactive events only if something has changed and if the module is visible. Thanks to+ #' @export |
||
6 | +125 |
- #' this special implementation all modules' data are recalculated only for those modules which are+ teal_transform_module <- function(ui = NULL, |
||
7 | +126 |
- #' currently displayed.+ server = function(id, data) data, |
||
8 | +127 |
- #'+ label = "transform module", |
||
9 | +128 |
- #' @return A `eventReactive` containing `teal_data` containing filtered objects and filter code.+ datanames = "all") { |
||
10 | -+ | |||
129 | +25x |
- #' `eventReactive` triggers only if all conditions are met:+ structure( |
||
11 | -+ | |||
130 | +25x |
- #' - tab is selected (`is_active`)+ list( |
||
12 | -+ | |||
131 | +25x |
- #' - when filters are changed (`get_filter_expr` is different than previous)+ ui = ui, |
||
13 | -+ | |||
132 | +25x |
- #'+ server = function(id, data) { |
||
14 | -+ | |||
133 | +26x |
- #' @inheritParams module_teal_module+ data_out <- server(id, data) |
||
15 | +134 |
- #' @param active_datanames (`reactive` returning `character`) this module's data names+ |
||
16 | -+ | |||
135 | +26x |
- #' @name module_filter_data+ if (inherits(data_out, "reactive.event")) { |
||
17 | +136 |
- #' @keywords internal+ # This warning message partially detects when `eventReactive` is used in `data_module`. |
||
18 | -+ | |||
137 | +1x |
- NULL+ warning( |
||
19 | -+ | |||
138 | +1x |
-
+ "teal_transform_module() ", |
||
20 | -+ | |||
139 | +1x |
- #' @rdname module_filter_data+ "Using eventReactive in teal_transform module server code should be avoided as it ", |
||
21 | -+ | |||
140 | +1x |
- ui_filter_data <- function(id) {+ "may lead to unexpected behavior. See the vignettes for more information ", |
||
22 | -! | +|||
141 | +1x |
- ns <- shiny::NS(id)+ "(`vignette(\"data-transform-as-shiny-module\", package = \"teal\")`).", |
||
23 | -! | +|||
142 | +1x |
- uiOutput(ns("panel"))+ call. = FALSE |
||
24 | +143 |
- }+ ) |
||
25 | +144 |
-
+ } |
||
26 | +145 |
- #' @rdname module_filter_data+ |
||
27 | +146 |
- srv_filter_data <- function(id, datasets, active_datanames, data, is_active) {- |
- ||
28 | -86x | -
- assert_reactive(datasets)+ |
||
29 | -86x | +147 | +26x |
- moduleServer(id, function(input, output, session) {+ decorate_err_msg( |
30 | -86x | -
- active_corrected <- reactive(intersect(active_datanames(), datasets()$datanames()))- |
- ||
31 | -+ | 148 | +26x |
-
+ assert_reactive(data_out), |
32 | -86x | +149 | +26x |
- output$panel <- renderUI({+ pre = sprintf("From: 'teal_transform_module()':\nA 'teal_transform_module' with \"%s\" label:", label), |
33 | -88x | +150 | +26x |
- req(inherits(datasets(), "FilteredData"))+ post = "Please make sure that this module returns a 'reactive` object containing 'teal_data' class of object." # nolint: line_length_linter. |
34 | -88x | +|||
151 | +
- isolate({+ ) |
|||
35 | +152 |
- # render will be triggered only when FilteredData object changes (not when filters change)+ } |
||
36 | +153 |
- # technically it means that teal_data_module needs to be refreshed+ ), |
||
37 | -88x | +154 | +25x |
- logger::log_debug("srv_filter_panel rendering filter panel.")+ label = label, |
38 | -88x | +155 | +25x |
- if (length(active_corrected())) {+ datanames = datanames, |
39 | -86x | +156 | +25x |
- datasets()$srv_active("filters", active_datanames = active_corrected)+ class = c("teal_transform_module", "teal_data_module") |
40 | -86x | +|||
157 | +
- datasets()$ui_active(session$ns("filters"), active_datanames = active_corrected)+ ) |
|||
41 | +158 |
- }+ } |
||
42 | +159 |
- })+ |
||
43 | +160 |
- })+ #' Make teal_transform_module's server |
||
44 | +161 |
-
+ #' |
||
45 | -86x | +|||
162 | +
- trigger_data <- .observe_active_filter_changed(datasets, is_active, active_corrected, data)+ #' A factory function to simplify creation of a [`teal_transform_module`]'s server. Specified `expr` |
|||
46 | +163 |
-
+ #' is wrapped in a shiny module function and output can be passed to the `server` argument in |
||
47 | -86x | +|||
164 | +
- eventReactive(trigger_data(), {+ #' [teal_transform_module()] call. Such a server function can be linked with ui and values from the |
|||
48 | -89x | +|||
165 | +
- .make_filtered_teal_data(modules, data = data(), datasets = datasets(), datanames = active_corrected())+ #' inputs can be used in the expression. Object names specified in the expression will be substituted |
|||
49 | +166 |
- })+ #' with the value of the respective input (matched by the name) - for example in |
||
50 | +167 |
- })+ #' `expression(graph <- graph + ggtitle(title))` object `title` will be replaced with the value of |
||
51 | +168 |
- }+ #' `input$title`. |
||
52 | +169 |
-
+ #' @param expr (`language`) |
||
53 | +170 |
- #' @rdname module_filter_data+ #' An R call which will be evaluated within [`teal.data::teal_data`] environment. |
||
54 | +171 |
- .make_filtered_teal_data <- function(modules, data, datasets = NULL, datanames) {+ #' @return `function(id, data)` returning `shiny` module |
||
55 | -89x | +|||
172 | +
- data <- eval_code(+ #' @examples |
|||
56 | -89x | +|||
173 | +
- data,+ #' |
|||
57 | -89x | +|||
174 | +
- paste0(+ #' trim_iris <- teal_transform_module( |
|||
58 | -89x | +|||
175 | +
- ".raw_data <- list2env(list(",+ #' label = "Simplified interactive transformator for iris", |
|||
59 | -89x | +|||
176 | +
- toString(sprintf("%1$s = %1$s", sapply(datanames, as.name))),+ #' datanames = "iris", |
|||
60 | -89x | +|||
177 | +
- "))\n",+ #' ui = function(id) { |
|||
61 | -89x | +|||
178 | +
- "lockEnvironment(.raw_data) # @linksto .raw_data" # this is environment and it is shared by qenvs. CAN'T MODIFY!+ #' ns <- NS(id) |
|||
62 | +179 |
- )+ #' numericInput(ns("n_rows"), "Subset n rows", value = 6, min = 1, max = 150, step = 1) |
||
63 | +180 |
- )+ #' }, |
||
64 | -89x | +|||
181 | +
- filtered_code <- .get_filter_expr(datasets = datasets, datanames = datanames)+ #' server = make_teal_transform_server(expression(iris <- head(iris, n_rows))) |
|||
65 | -89x | +|||
182 | +
- filtered_teal_data <- .append_evaluated_code(data, filtered_code)+ #' ) |
|||
66 | -89x | +|||
183 | +
- filtered_datasets <- sapply(datanames, function(x) datasets$get_data(x, filtered = TRUE), simplify = FALSE)+ #' |
|||
67 | -89x | +|||
184 | +
- filtered_teal_data <- .append_modified_data(filtered_teal_data, filtered_datasets)+ #' app <- init( |
|||
68 | -89x | +|||
185 | +
- filtered_teal_data+ #' data = teal_data(iris = iris), |
|||
69 | +186 |
- }+ #' modules = example_module(transformators = trim_iris) |
||
70 | +187 |
-
+ #' ) |
||
71 | +188 |
- #' @rdname module_filter_data+ #' if (interactive()) { |
||
72 | +189 |
- .observe_active_filter_changed <- function(datasets, is_active, active_datanames, data) {+ #' shinyApp(app$ui, app$server) |
||
73 | -86x | +|||
190 | +
- previous_signature <- reactiveVal(NULL)+ #' } |
|||
74 | -86x | +|||
191 | +
- filter_changed <- reactive({+ #' |
|||
75 | -195x | +|||
192 | +
- req(inherits(datasets(), "FilteredData"))+ #' @export |
|||
76 | -195x | +|||
193 | +
- new_signature <- c(+ make_teal_transform_server <- function(expr) { |
|||
77 | -195x | +194 | +3x |
- teal.code::get_code(data()),+ if (is.call(expr)) { |
78 | -195x | +195 | +1x |
- .get_filter_expr(datasets = datasets(), datanames = active_datanames())+ expr <- as.expression(expr) |
79 | +196 |
- )+ } |
||
80 | -195x | +197 | +3x |
- if (!identical(previous_signature(), new_signature)) {+ checkmate::assert_multi_class(expr, c("call", "expression")) |
81 | -94x | +|||
198 | +
- previous_signature(new_signature)+ |
|||
82 | -94x | +199 | +3x |
- TRUE+ function(id, data) { |
83 | -+ | |||
200 | +3x |
- } else {+ moduleServer(id, function(input, output, session) { |
||
84 | -101x | +201 | +3x |
- FALSE+ list_env <- reactive( |
85 | -+ | |||
202 | +3x |
- }+ lapply(rlang::set_names(names(input)), function(x) input[[x]]) |
||
86 | +203 |
- })+ ) |
||
87 | +204 | |||
88 | -86x | -
- trigger_data <- reactiveVal(NULL)- |
- ||
89 | -86x | -
- observe({- |
- ||
90 | -208x | -
- if (isTRUE(is_active() && filter_changed())) {- |
- ||
91 | -94x | +205 | +3x |
- isolate({+ reactive({ |
92 | -94x | +206 | +4x |
- if (is.null(trigger_data())) {+ call_with_inputs <- lapply(expr, function(x) { |
93 | -86x | +207 | +4x |
- trigger_data(0)+ do.call(what = substitute, args = list(expr = x, env = list_env())) |
94 | +208 |
- } else {+ }) |
||
95 | -8x | +209 | +4x |
- trigger_data(trigger_data() + 1)+ eval_code(object = data(), code = as.expression(call_with_inputs)) |
96 | +210 |
- }+ }) |
||
97 | +211 |
- })+ }) |
||
98 | +212 |
- }+ } |
||
99 | +213 |
- })+ } |
||
100 | +214 | |||
101 | -86x | +|||
215 | +
- trigger_data+ #' Extract all `transformators` from `modules`. |
|||
102 | +216 |
- }+ #' |
||
103 | +217 |
-
+ #' @param modules `teal_modules` or `teal_module` |
||
104 | +218 |
- #' @rdname module_filter_data+ #' @return A list of `teal_transform_module` nested in the same way as input `modules`. |
||
105 | +219 |
- .get_filter_expr <- function(datasets, datanames) {+ #' @keywords internal+ |
+ ||
220 | ++ |
+ extract_transformators <- function(modules) { |
||
106 | -284x | +221 | +10x |
- if (length(datanames)) {+ if (inherits(modules, "teal_module")) { |
107 | -278x | +222 | +5x |
- teal.slice::get_filter_expr(datasets = datasets, datanames = datanames)+ modules$transformators |
108 | -+ | |||
223 | +5x |
- } else {+ } else if (inherits(modules, "teal_modules")) { |
||
109 | -6x | +224 | +5x |
- NULL+ lapply(modules$children, extract_transformators) |
110 | +225 |
} |
||
111 | +226 |
}@@ -41911,3787 +41952,3970 @@ teal coverage - 60.12% |
1 |
- #' Data module for `teal` applications+ #' @title `TealReportCard` |
||
2 |
- #'+ #' @description `r lifecycle::badge("experimental")` |
||
3 |
- #' @description+ #' Child class of [`teal.reporter::ReportCard`] that is used for `teal` specific applications. |
||
4 |
- #' `r lifecycle::badge("experimental")`+ #' 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 |
||
6 |
- #' Create a `teal_data_module` object and evaluate code on it with history tracking.+ #' meta data. |
||
7 |
- #'+ #' @export |
||
8 |
- #' @details+ #' |
||
9 |
- #' `teal_data_module` creates a `shiny` module to interactively supply or modify data in a `teal` application.+ TealReportCard <- R6::R6Class( # nolint: object_name. |
||
10 |
- #' The module allows for running any code (creation _and_ some modification) after the app starts or reloads.+ classname = "TealReportCard", |
||
11 |
- #' The body of the server function will be run in the app rather than in the global environment.+ inherit = teal.reporter::ReportCard, |
||
12 |
- #' This means it will be run every time the app starts, so use sparingly.+ public = list( |
||
13 |
- #'+ #' @description Appends the source code to the `content` meta data of this `TealReportCard`. |
||
14 |
- #' Pass this module instead of a `teal_data` object in a call to [init()].+ #' |
||
15 |
- #' Note that the server function must always return a `teal_data` object wrapped in a reactive expression.+ #' @param src (`character(1)`) code as text. |
||
16 |
- #'+ #' @param ... any `rmarkdown` `R` chunk parameter and its value. |
||
17 |
- #' See vignette `vignette("data-as-shiny-module", package = "teal")` for more details.+ #' But `eval` parameter is always set to `FALSE`. |
||
18 |
- #'+ #' @return Object of class `TealReportCard`, invisibly. |
||
19 |
- #' @param ui (`function(id)`)+ #' @examples |
||
20 |
- #' `shiny` module UI function; must only take `id` argument+ #' card <- TealReportCard$new()$append_src( |
||
21 |
- #' @param server (`function(id)`)+ #' "plot(iris)" |
||
22 |
- #' `shiny` module server function; must only take `id` argument;+ #' ) |
||
23 |
- #' must return reactive expression containing `teal_data` object+ #' card$get_content()[[1]]$get_content() |
||
24 |
- #' @param label (`character(1)`) Label of the module.+ append_src = function(src, ...) { |
||
25 | -+ | 4x |
- #' @param once (`logical(1)`)+ checkmate::assert_character(src, min.len = 0, max.len = 1) |
26 | -+ | 4x |
- #' If `TRUE`, the data module will be shown only once and will disappear after successful data loading.+ params <- list(...) |
27 | -+ | 4x |
- #' App user will no longer be able to interact with this module anymore.+ params$eval <- FALSE |
28 | -+ | 4x |
- #' If `FALSE`, the data module can be reused multiple times.+ rblock <- RcodeBlock$new(src) |
29 | -+ | 4x |
- #' App user will be able to interact and change the data output from the module multiple times.+ rblock$set_params(params) |
30 | -+ | 4x |
- #'+ self$append_content(rblock) |
31 | -+ | 4x |
- #' @return+ self$append_metadata("SRC", src) |
32 | -+ | 4x |
- #' `teal_data_module` returns a list of class `teal_data_module` containing two elements, `ui` and+ invisible(self) |
33 |
- #' `server` provided via arguments.+ }, |
||
34 |
- #'+ #' @description Appends the filter state list to the `content` and `metadata` of this `TealReportCard`. |
||
35 |
- #' @examples+ #' If the filter state list has an attribute named `formatted`, it appends it to the card otherwise it uses |
||
36 |
- #' tdm <- teal_data_module(+ #' the default `yaml::as.yaml` to format the list. |
||
37 |
- #' ui = function(id) {+ #' If the filter state list is empty, nothing is appended to the `content`. |
||
38 |
- #' ns <- NS(id)+ #' |
||
39 |
- #' actionButton(ns("submit"), label = "Load data")+ #' @param fs (`teal_slices`) object returned from [teal_slices()] function. |
||
40 |
- #' },+ #' @return `self`, invisibly. |
||
41 |
- #' server = function(id) {+ append_fs = function(fs) { |
||
42 | -+ | 5x |
- #' moduleServer(id, function(input, output, session) {+ checkmate::assert_class(fs, "teal_slices") |
43 | -+ | 4x |
- #' eventReactive(input$submit, {+ self$append_text("Filter State", "header3") |
44 | -+ | 4x |
- #' data <- within(+ if (length(fs)) { |
45 | -+ | 3x |
- #' teal_data(),+ self$append_content(TealSlicesBlock$new(fs)) |
46 |
- #' {+ } else { |
||
47 | -+ | 1x |
- #' dataset1 <- iris+ self$append_text("No filters specified.") |
48 |
- #' dataset2 <- mtcars+ } |
||
49 | -+ | 4x |
- #' }+ invisible(self) |
50 |
- #' )+ }, |
||
51 |
- #'+ #' @description Appends the encodings list to the `content` and `metadata` of this `TealReportCard`. |
||
52 |
- #' data+ #' |
||
53 |
- #' })+ #' @param encodings (`list`) list of encodings selections of the `teal` app. |
||
54 |
- #' })+ #' @return `self`, invisibly. |
||
55 |
- #' }+ #' @examples |
||
56 |
- #' )+ #' card <- TealReportCard$new()$append_encodings(list(variable1 = "X")) |
||
57 |
- #'+ #' card$get_content()[[1]]$get_content() |
||
58 |
- #' @name teal_data_module+ #' |
||
59 |
- #' @seealso [`teal.data::teal_data-class`], [teal.code::qenv()]+ append_encodings = function(encodings) { |
||
60 | -+ | 4x |
- #'+ checkmate::assert_list(encodings) |
61 | -+ | 4x |
- #' @export+ self$append_text("Selected Options", "header3") |
62 | -+ | 4x |
- teal_data_module <- function(ui, server, label = "data module", once = TRUE) {+ if (requireNamespace("yaml", quietly = TRUE)) { |
63 | -33x | +4x |
- checkmate::assert_function(ui, args = "id", nargs = 1)+ self$append_text(yaml::as.yaml(encodings, handlers = list( |
64 | -32x | +4x |
- checkmate::assert_function(server, args = "id", nargs = 1)+ POSIXct = function(x) format(x, "%Y-%m-%d"), |
65 | -30x | +4x |
- checkmate::assert_string(label)+ POSIXlt = function(x) format(x, "%Y-%m-%d"), |
66 | -30x | +4x |
- checkmate::assert_flag(once)+ Date = function(x) format(x, "%Y-%m-%d") |
67 | -30x | +4x |
- structure(+ )), "verbatim") |
68 | -30x | +
- list(+ } else { |
|
69 | -30x | +! |
- ui = ui,+ stop("yaml package is required to format the encodings list") |
70 | -30x | +
- server = function(id) {+ } |
|
71 | -23x | +4x |
- data_out <- server(id)+ self$append_metadata("Encodings", encodings) |
72 | -22x | +4x |
- decorate_err_msg(+ invisible(self) |
73 | -22x | +
- assert_reactive(data_out),+ } |
|
74 | -22x | +
- pre = sprintf("From: 'teal_data_module()':\nA 'teal_data_module' with \"%s\" label:", label),+ ), |
|
75 | -22x | +
- post = "Please make sure that this module returns a 'reactive` object containing 'teal_data' class of object." # nolint: line_length_linter.+ private = list( |
|
76 |
- )+ dispatch_block = function(block_class) { |
||
77 | -+ | ! |
- }+ eval(str2lang(block_class)) |
78 |
- ),+ } |
||
79 | -30x | +
- label = label,+ ) |
|
80 | -30x | +
- class = "teal_data_module",+ ) |
|
81 | -30x | +
- once = once+ |
|
82 |
- )+ #' @title `TealSlicesBlock` |
||
83 |
- }+ #' @docType class |
1 | +84 |
- #' Generate lockfile for application's environment reproducibility+ #' @description+ |
+ ||
85 | ++ |
+ #' Specialized `TealSlicesBlock` block for managing filter panel content in reports.+ |
+ ||
86 | ++ |
+ #' @keywords internal+ |
+ ||
87 | ++ |
+ TealSlicesBlock <- R6::R6Class( # nolint: object_name_linter.+ |
+ ||
88 | ++ |
+ classname = "TealSlicesBlock",+ |
+ ||
89 | ++ |
+ inherit = teal.reporter:::TextBlock,+ |
+ ||
90 | ++ |
+ public = list(+ |
+ ||
91 | ++ |
+ #' @description Returns a `TealSlicesBlock` object.+ |
+ ||
92 | ++ |
+ #'+ |
+ ||
93 | ++ |
+ #' @details Returns a `TealSlicesBlock` object with no content and no parameters.+ |
+ ||
94 | ++ |
+ #'+ |
+ ||
95 | ++ |
+ #' @param content (`teal_slices`) object returned from [teal_slices()] function.+ |
+ ||
96 | ++ |
+ #' @param style (`character(1)`) string specifying style to apply.+ |
+ ||
97 | ++ |
+ #'+ |
+ ||
98 | ++ |
+ #' @return Object of class `TealSlicesBlock`, invisibly.+ |
+ ||
99 | ++ |
+ #'+ |
+ ||
100 | ++ |
+ initialize = function(content = teal_slices(), style = "verbatim") {+ |
+ ||
101 | +9x | +
+ self$set_content(content)+ |
+ ||
102 | +8x | +
+ self$set_style(style)+ |
+ ||
103 | +8x | +
+ invisible(self) |
||
2 | +104 |
- #'+ }, |
||
3 | +105 |
- #' @param lockfile_path (`character`) path to the lockfile.+ |
||
4 | +106 |
- #'+ #' @description Sets content of this `TealSlicesBlock`. |
||
5 | +107 |
- #' @section Different ways of creating lockfile:+ #' Sets content as `YAML` text which represents a list generated from `teal_slices`. |
||
6 | +108 |
- #' `teal` leverages [renv::snapshot()], which offers multiple methods for lockfile creation.+ #' The list displays limited number of fields from `teal_slice` objects, but this list is |
||
7 | +109 |
- #'+ #' sufficient to conclude which filters were applied. |
||
8 | +110 |
- #' - **Working directory lockfile**: `teal`, by default, will create an `implicit` type lockfile that uses+ #' When `selected` field in `teal_slice` object is a range, then it is displayed as a "min" |
||
9 | +111 |
- #' `renv::dependencies()` to detect all R packages in the current project's working directory.+ #' |
||
10 | +112 |
- #' - **`DESCRIPTION`-based lockfile**: To generate a lockfile based on a `DESCRIPTION` file in your working+ #' |
||
11 | +113 |
- #' directory, set `renv::settings$snapshot.type("explicit")`. The naming convention for `type` follows+ #' @param content (`teal_slices`) object returned from [teal_slices()] function. |
||
12 | +114 |
- #' `renv::snapshot()`. For the `"explicit"` type, refer to `renv::settings$package.dependency.fields()` for the+ #' @return `self`, invisibly. |
||
13 | +115 |
- #' `DESCRIPTION` fields included in the lockfile.+ set_content = function(content) { |
||
14 | -+ | |||
116 | +9x |
- #' - **Custom files-based lockfile**: To specify custom files as the basis for the lockfile, set+ checkmate::assert_class(content, "teal_slices") |
||
15 | -+ | |||
117 | +8x |
- #' `renv::settings$snapshot.type("custom")` and configure the `renv.snapshot.filter` option.+ if (length(content) != 0) { |
||
16 | -+ | |||
118 | +6x |
- #'+ states_list <- lapply(content, function(x) { |
||
17 | -+ | |||
119 | +6x |
- #' @section lockfile usage:+ x_list <- shiny::isolate(as.list(x)) |
||
18 | -+ | |||
120 | +6x |
- #' After creating the lockfile, you can restore the application's environment using `renv::restore()`.+ if ( |
||
19 | -+ | |||
121 | +6x |
- #'+ inherits(x_list$choices, c("integer", "numeric", "Date", "POSIXct", "POSIXlt")) && |
||
20 | -+ | |||
122 | +6x |
- #' @seealso [renv::snapshot()], [renv::restore()].+ length(x_list$choices) == 2 && |
||
21 | -+ | |||
123 | +6x |
- #'+ length(x_list$selected) == 2 |
||
22 | +124 |
- #' @return `NULL`+ ) { |
||
23 | -+ | |||
125 | +! |
- #'+ x_list$range <- paste(x_list$selected, collapse = " - ") |
||
24 | -+ | |||
126 | +! |
- #' @name module_teal_lockfile+ x_list["selected"] <- NULL |
||
25 | +127 |
- #' @rdname module_teal_lockfile+ } |
||
26 | -+ | |||
128 | +6x |
- #'+ if (!is.null(x_list$arg)) { |
||
27 | -+ | |||
129 | +! |
- #' @keywords internal+ x_list$arg <- if (x_list$arg == "subset") "Genes" else "Samples" |
||
28 | +130 |
- NULL+ } |
||
29 | +131 | |||
30 | -+ | |||
132 | +6x |
- #' @rdname module_teal_lockfile+ x_list <- x_list[ |
||
31 | -+ | |||
133 | +6x |
- ui_teal_lockfile <- function(id) {+ c("dataname", "varname", "experiment", "arg", "expr", "selected", "range", "keep_na", "keep_inf") |
||
32 | -! | +|||
134 | +
- ns <- NS(id)+ ] |
|||
33 | -! | +|||
135 | +6x |
- shiny::tagList(+ names(x_list) <- c( |
||
34 | -! | +|||
136 | +6x |
- tags$span("", id = ns("lockFileStatus")),+ "Dataset name", "Variable name", "Experiment", "Filtering by", "Applied expression", |
||
35 | -! | +|||
137 | +6x |
- shinyjs::disabled(downloadLink(ns("lockFileLink"), "Download lockfile"))+ "Selected Values", "Selected range", "Include NA values", "Include Inf values" |
||
36 | +138 |
- )+ ) |
||
37 | +139 |
- }+ |
||
38 | -+ | |||
140 | +6x |
-
+ Filter(Negate(is.null), x_list) |
||
39 | +141 |
- #' @rdname module_teal_lockfile+ }) |
||
40 | +142 |
- srv_teal_lockfile <- function(id) {- |
- ||
41 | -88x | -
- moduleServer(id, function(input, output, session) {+ |
||
42 | -88x | +143 | +6x |
- logger::log_debug("Initialize srv_teal_lockfile.")+ if (requireNamespace("yaml", quietly = TRUE)) { |
43 | -88x | +144 | +6x |
- enable_lockfile_download <- function() {+ super$set_content(yaml::as.yaml(states_list)) |
44 | -! | +|||
145 | +
- shinyjs::html("lockFileStatus", "Application lockfile ready.")+ } else { |
|||
45 | +146 | ! |
- shinyjs::hide("lockFileStatus", anim = TRUE)+ stop("yaml package is required to format the filter state list") |
|
46 | -! | +|||
147 | +
- shinyjs::enable("lockFileLink")+ } |
|||
47 | -! | +|||
148 | +
- output$lockFileLink <- shiny::downloadHandler(+ } |
|||
48 | -! | +|||
149 | +8x |
- filename = function() {+ private$teal_slices <- content |
||
49 | -! | +|||
150 | +8x |
- "renv.lock"+ invisible(self) |
||
50 | +151 |
- },+ }, |
||
51 | -! | +|||
152 | +
- content = function(file) {+ #' @description Create the `TealSlicesBlock` from a list. |
|||
52 | -! | +|||
153 | +
- file.copy(lockfile_path, file)+ #' |
|||
53 | -! | +|||
154 | +
- file+ #' @param x (`named list`) with two fields `text` and `style`. |
|||
54 | +155 |
- },+ #' Use the `get_available_styles` method to get all possible styles. |
||
55 | -! | +|||
156 | +
- contentType = "application/json"+ #' |
|||
56 | +157 |
- )+ #' @return `self`, invisibly. |
||
57 | +158 |
- }+ #' @examples |
||
58 | -88x | +|||
159 | +
- disable_lockfile_download <- function() {+ #' TealSlicesBlock <- getFromNamespace("TealSlicesBlock", "teal") |
|||
59 | -! | +|||
160 | +
- warning("Lockfile creation failed.", call. = FALSE)+ #' block <- TealSlicesBlock$new() |
|||
60 | -! | +|||
161 | +
- shinyjs::html("lockFileStatus", "Lockfile creation failed.")+ #' block$from_list(list(text = "sth", style = "default")) |
|||
61 | -! | +|||
162 | +
- shinyjs::hide("lockFileLink")+ #' |
|||
62 | +163 |
- }+ from_list = function(x) { |
||
63 | -+ | |||
164 | +1x |
-
+ checkmate::assert_list(x) |
||
64 | -88x | +165 | +1x |
- shiny::onStop(function() {+ checkmate::assert_names(names(x), must.include = c("text", "style")) |
65 | -88x | +166 | +1x |
- if (file.exists(lockfile_path) && !shiny::isRunning()) {+ super$set_content(x$text) |
66 | +167 | 1x |
- logger::log_debug("Removing lockfile after shutting down the app")+ super$set_style(x$style) |
|
67 | +168 | 1x |
- file.remove(lockfile_path)+ invisible(self) |
|
68 | +169 |
- }+ }, |
||
69 | +170 |
- })+ #' @description Convert the `TealSlicesBlock` to a list. |
||
70 | +171 |
-
+ #' |
||
71 | -88x | +|||
172 | +
- lockfile_path <- "teal_app.lock"+ #' @return `named list` with a text and style. |
|||
72 | -88x | +|||
173 | +
- mode <- getOption("teal.lockfile.mode", default = "")+ #' @examples |
|||
73 | +174 |
-
+ #' TealSlicesBlock <- getFromNamespace("TealSlicesBlock", "teal") |
||
74 | -88x | +|||
175 | +
- if (!(mode %in% c("auto", "enabled", "disabled"))) {+ #' block <- TealSlicesBlock$new() |
|||
75 | -! | +|||
176 | +
- stop("'teal.lockfile.mode' option can only be one of \"auto\", \"disabled\" or \"disabled\". ")+ #' block$to_list() |
|||
76 | +177 |
- }+ #' |
||
77 | +178 |
-
+ to_list = function() { |
||
78 | -88x | +179 | +2x |
- if (mode == "disabled") {+ content <- self$get_content() |
79 | -1x | +180 | +2x |
- logger::log_debug("'teal.lockfile.mode' option is set to 'disabled'. Hiding lockfile download button.")+ list( |
80 | -1x | +181 | +2x |
- shinyjs::hide("lockFileLink")+ text = if (length(content)) content else "", |
81 | -1x | +182 | +2x |
- return(NULL)+ style = self$get_style() |
82 | +183 | ++ |
+ )+ |
+ |
184 |
} |
|||
83 | +185 |
-
+ ), |
||
84 | -87x | +|||
186 | +
- if (file.exists(lockfile_path)) {+ private = list( |
|||
85 | -! | +|||
187 | +
- logger::log_debug("Lockfile has already been created for this app - skipping automatic creation.")+ style = "verbatim", |
|||
86 | -! | +|||
188 | +
- enable_lockfile_download()+ teal_slices = NULL # teal_slices |
|||
87 | -! | +|||
189 | +
- return(NULL)+ ) |
|||
88 | +190 |
- }+ ) |
89 | +1 |
-
+ #' Module to transform `reactive` `teal_data` |
||
90 | -87x | +|||
2 | +
- if (mode == "auto" && .is_disabled_lockfile_scenario()) {+ #' |
|||
91 | -86x | +|||
3 | +
- logger::log_debug(+ #' Module calls [teal_transform_module()] in sequence so that `reactive teal_data` output |
|||
92 | -86x | +|||
4 | +
- "Automatic lockfile creation disabled. Execution scenario satisfies teal:::.is_disabled_lockfile_scenario()."+ #' from one module is handed over to the following module's input. |
|||
93 | +5 |
- )+ #' |
||
94 | -86x | +|||
6 | +
- shinyjs::hide("lockFileLink")+ #' @inheritParams module_teal_data |
|||
95 | -86x | +|||
7 | +
- return(NULL)+ #' @inheritParams teal_modules |
|||
96 | +8 |
- }+ #' @param class (character(1)) CSS class to be added in the `div` wrapper tag. |
||
97 | +9 | |||
98 | -1x | -
- if (!.is_lockfile_deps_installed()) {- |
- ||
99 | -! | +|||
10 | +
- warning("Automatic lockfile creation disabled. `mirai` and `renv` packages must be installed.")+ #' @return `reactive` `teal_data` |
|||
100 | -! | +|||
11 | +
- shinyjs::hide("lockFileLink")+ #' |
|||
101 | -! | +|||
12 | +
- return(NULL)+ #' @name module_transform_data |
|||
102 | +13 |
- }+ NULL |
||
103 | +14 | |||
104 | +15 |
- # - Will be run only if the lockfile doesn't exist (see the if-s above)+ #' @export |
||
105 | +16 |
- # - We render to the tempfile because the process might last after session is closed and we don't+ #' @rdname module_transform_data |
||
106 | +17 |
- # want to make a "teal_app.renv" then. This is why we copy only during active session.+ ui_transform_teal_data <- function(id, transformators, class = "well") { |
||
107 | +18 | 1x |
- process <- .teal_lockfile_process_invoke(lockfile_path)+ checkmate::assert_string(id) |
|
108 | +19 | 1x |
- observeEvent(process$status(), {+ if (length(transformators) == 0L) { |
|
109 | +20 | ! |
- if (process$status() %in% c("initial", "running")) {+ return(NULL) |
|
110 | -! | +|||
21 | +
- shinyjs::html("lockFileStatus", "Creating lockfile...")+ } |
|||
111 | -! | +|||
22 | +1x |
- } else if (process$status() == "success") {+ if (inherits(transformators, "teal_transform_module")) { |
||
112 | -! | +|||
23 | +1x |
- result <- process$result()+ transformators <- list(transformators) |
||
113 | -! | +|||
24 | +
- if (any(grepl("Lockfile written to", result$out))) {+ } |
|||
114 | -! | +|||
25 | +1x |
- logger::log_debug("Lockfile containing { length(result$res$Packages) } packages created.")+ checkmate::assert_list(transformators, "teal_transform_module") |
||
115 | -! | +|||
26 | +1x |
- if (any(grepl("(WARNING|ERROR):", result$out))) {+ names(transformators) <- sprintf("transform_%d", seq_len(length(transformators))) |
||
116 | -! | +|||
27 | +
- warning("Lockfile created with warning(s) or error(s):", call. = FALSE)+ |
|||
117 | -! | +|||
28 | +1x |
- for (i in result$out) {+ lapply( |
||
118 | -! | +|||
29 | +1x |
- warning(i, call. = FALSE)+ names(transformators), |
||
119 | -+ | |||
30 | +1x |
- }+ function(name) { |
||
120 | -+ | |||
31 | +1x |
- }+ child_id <- NS(id, name) |
||
121 | -! | +|||
32 | +1x |
- enable_lockfile_download()+ ns <- NS(child_id)+ |
+ ||
33 | +1x | +
+ data_mod <- transformators[[name]]+ |
+ ||
34 | +1x | +
+ transform_wrapper_id <- ns(sprintf("wrapper_%s", name)) |
||
122 | +35 |
- } else {+ |
||
123 | -! | +|||
36 | +1x |
- disable_lockfile_download()+ display_fun <- if (is.null(data_mod$ui)) shinyjs::hidden else function(x) x |
||
124 | +37 |
- }+ |
||
125 | -! | +|||
38 | +1x |
- } else if (process$status() == "error") {+ display_fun( |
||
126 | -! | +|||
39 | +1x |
- disable_lockfile_download()+ div( |
||
127 | +40 |
- }+ # class .teal_validated changes the color of the boarder on error in ui_validate_reactive_teal_data |
||
128 | +41 |
- })+ # For details see tealValidate.js file. |
||
129 | -+ | |||
42 | +1x |
-
+ id = ns("wrapper"), |
||
130 | +43 | 1x |
- NULL+ class = c(class, "teal_validated"), |
|
131 | -+ | |||
44 | +1x |
- })+ title = attr(data_mod, "label"), |
||
132 | -+ | |||
45 | +1x |
- }+ tags$span( |
||
133 | -+ | |||
46 | +1x |
-
+ class = "text-primary mb-4", |
||
134 | -+ | |||
47 | +1x |
- utils::globalVariables(c("opts", "sysenv", "libpaths", "wd", "lockfilepath", "run")) # needed for mirai call+ icon("fas fa-square-pen"), |
||
135 | -+ | |||
48 | +1x |
- #' @rdname module_teal_lockfile+ attr(data_mod, "label") |
||
136 | +49 |
- .teal_lockfile_process_invoke <- function(lockfile_path) {+ ), |
||
137 | +50 | 1x |
- mirai_obj <- NULL+ tags$i( |
|
138 | +51 | 1x |
- process <- shiny::ExtendedTask$new(function() {+ class = "remove pull-right fa fa-angle-down", |
|
139 | +52 | 1x |
- m <- mirai::mirai(+ style = "cursor: pointer;", |
|
140 | -+ | |||
53 | +1x |
- {+ title = "fold/expand transformator panel", |
||
141 | +54 | 1x |
- options(opts)+ onclick = sprintf("togglePanelItems(this, '%s', 'fa-angle-right', 'fa-angle-down');", transform_wrapper_id) |
|
142 | -1x | +|||
55 | +
- do.call(Sys.setenv, sysenv)+ ), |
|||
143 | +56 | 1x |
- .libPaths(libpaths)+ tags$div( |
|
144 | +57 | 1x |
- setwd(wd)+ id = transform_wrapper_id, |
|
145 | +58 | 1x |
- run(lockfile_path = lockfile_path)+ if (is.null(data_mod$ui)) {+ |
+ |
59 | +! | +
+ return(NULL) |
||
146 | +60 |
- },+ } else { |
||
147 | +61 | 1x |
- run = .renv_snapshot,+ data_mod$ui(id = ns("transform")) |
|
148 | -1x | +|||
62 | +
- lockfile_path = lockfile_path,+ }, |
|||
149 | +63 | 1x |
- opts = options(),+ div( |
|
150 | +64 | 1x |
- libpaths = .libPaths(),+ id = ns("validate_messages"), |
|
151 | +65 | 1x |
- sysenv = as.list(Sys.getenv()),+ class = "teal_validated", |
|
152 | +66 | 1x |
- wd = getwd()+ uiOutput(ns("error_wrapper")) |
|
153 | +67 |
- )+ ) |
||
154 | -1x | +|||
68 | +
- mirai_obj <<- m+ ) |
|||
155 | -1x | +|||
69 | +
- m+ ) |
|||
156 | +70 |
- })+ ) |
||
157 | +71 |
-
+ } |
||
158 | -1x | +|||
72 | +
- shiny::onStop(function() {+ ) |
|||
159 | -1x | +|||
73 | +
- if (mirai::unresolved(mirai_obj)) {+ } |
|||
160 | -! | +|||
74 | +
- logger::log_debug("Terminating a running lockfile process...")+ |
|||
161 | -! | +|||
75 | +
- mirai::stop_mirai(mirai_obj) # this doesn't stop running - renv will be created even if session is closed+ #' @export |
|||
162 | +76 |
- }+ #' @rdname module_transform_data |
||
163 | +77 |
- })+ srv_transform_teal_data <- function(id, data, transformators, modules = NULL, is_transform_failed = reactiveValues()) {+ |
+ ||
78 | +94x | +
+ checkmate::assert_string(id)+ |
+ ||
79 | +94x | +
+ assert_reactive(data) |
||
164 | -+ | |||
80 | +94x |
-
+ checkmate::assert_class(modules, "teal_module", null.ok = TRUE) |
||
165 | -1x | +81 | +94x |
- suppressWarnings({ # 'package:stats' may not be available when loading+ if (length(transformators) == 0L) { |
166 | -1x | +82 | +71x |
- process$invoke()+ return(data) |
167 | +83 |
- })+ } |
||
168 | -+ | |||
84 | +23x |
-
+ if (inherits(transformators, "teal_transform_module")) { |
||
169 | -1x | +85 | +3x |
- logger::log_debug("Lockfile creation started based on { getwd() }.")+ transformators <- list(transformators) |
170 | +86 |
-
+ } |
||
171 | -1x | +87 | +23x |
- process+ checkmate::assert_list(transformators, "teal_transform_module", null.ok = TRUE) |
172 | -+ | |||
88 | +23x |
- }+ names(transformators) <- sprintf("transform_%d", seq_len(length(transformators))) |
||
173 | +89 | |||
174 | -+ | |||
90 | +23x |
- #' @rdname module_teal_lockfile+ moduleServer(id, function(input, output, session) { |
||
175 | -+ | |||
91 | +23x |
- .renv_snapshot <- function(lockfile_path) {+ module_output <- Reduce( |
||
176 | -1x | +92 | +23x |
- out <- utils::capture.output(+ function(data_previous, name) { |
177 | -1x | +93 | +26x |
- res <- renv::snapshot(+ moduleServer(name, function(input, output, session) { |
178 | -1x | +94 | +26x |
- lockfile = lockfile_path,+ logger::log_debug("srv_transform_teal_data initializing for { name }.") |
179 | -1x | +95 | +26x |
- prompt = FALSE,+ is_transform_failed[[name]] <- FALSE |
180 | -1x | +96 | +26x |
- force = TRUE,+ data_out <- transformators[[name]]$server("transform", data = data_previous) |
181 | -1x | +97 | +26x |
- type = renv::settings$snapshot.type() # see the section "Different ways of creating lockfile" above here+ data_handled <- reactive(tryCatch(data_out(), error = function(e) e)) |
182 | -+ | |||
98 | +26x |
- )+ observeEvent(data_handled(), { |
||
183 | -+ | |||
99 | +32x |
- )+ if (inherits(data_handled(), "teal_data")) {+ |
+ ||
100 | +22x | +
+ is_transform_failed[[name]] <- FALSE |
||
184 | +101 |
-
+ } else { |
||
185 | -1x | +102 | +10x |
- list(out = out, res = res)+ is_transform_failed[[name]] <- TRUE |
186 | +103 |
- }+ } |
||
187 | +104 |
-
+ }) |
||
188 | +105 |
- #' @rdname module_teal_lockfile+ |
||
189 | -+ | |||
106 | +26x |
- .is_lockfile_deps_installed <- function() {+ is_previous_failed <- reactive({ |
||
190 | -1x | +107 | +29x |
- requireNamespace("mirai", quietly = TRUE) && requireNamespace("renv", quietly = TRUE)+ idx_this <- which(names(is_transform_failed) == name) |
191 | -+ | |||
108 | +29x |
- }+ is_transform_failed_list <- reactiveValuesToList(is_transform_failed) |
||
192 | -+ | |||
109 | +29x |
-
+ idx_failures <- which(unlist(is_transform_failed_list)) |
||
193 | -+ | |||
110 | +29x |
- #' @rdname module_teal_lockfile+ any(idx_failures < idx_this) |
||
194 | +111 |
- .is_disabled_lockfile_scenario <- function() {+ }) |
||
195 | -86x | +|||
112 | +
- identical(Sys.getenv("CALLR_IS_RUNNING"), "true") || # inside callr process+ |
|||
196 | -86x | +113 | +26x |
- identical(Sys.getenv("TESTTHAT"), "true") || # inside devtools::test+ srv_validate_error("silent_error", data_handled, validate_shiny_silent_error = FALSE) |
197 | -86x | -
- !identical(Sys.getenv("QUARTO_PROJECT_ROOT"), "") || # inside Quarto process- |
- ||
198 | -+ | 114 | +26x |
- (+ srv_check_class_teal_data("class_teal_data", data_handled) |
199 | -86x | +115 | +26x |
- ("CheckExEnv" %in% search()) || any(c("_R_CHECK_TIMINGS_", "_R_CHECK_LICENSE_") %in% names(Sys.getenv()))+ if (!is.null(modules)) { |
200 | -86x | -
- ) # inside R CMD CHECK- |
- ||
201 | -+ | 116 | +20x |
- }+ srv_check_module_datanames("datanames_warning", data_handled, modules) |
1 | +117 |
- #' Module to transform `reactive` `teal_data`+ } |
||
2 | +118 |
- #'+ |
||
3 | +119 |
- #' Module calls [teal_transform_module()] in sequence so that `reactive teal_data` output+ # When there is no UI (`ui = NULL`) it should still show the errors |
||
4 | -+ | |||
120 | +26x |
- #' from one module is handed over to the following module's input.+ observe({ |
||
5 | -+ | |||
121 | +32x |
- #'+ if (!inherits(data_handled(), "teal_data") && !is_previous_failed()) { |
||
6 | -+ | |||
122 | +10x |
- #' @inheritParams module_teal_data+ shinyjs::show("wrapper") |
||
7 | +123 |
- #' @inheritParams teal_modules+ } |
||
8 | +124 |
- #' @param class (character(1)) CSS class to be added in the `div` wrapper tag.+ }) |
||
9 | +125 | |||
10 | -+ | |||
126 | +26x |
- #' @return `reactive` `teal_data`+ transform_wrapper_id <- sprintf("wrapper_%s", name) |
||
11 | -+ | |||
127 | +26x |
- #'+ output$error_wrapper <- renderUI({ |
||
12 | -+ | |||
128 | +29x |
- #' @name module_transform_data+ if (is_previous_failed()) { |
||
13 | -+ | |||
129 | +! |
- NULL+ shinyjs::disable(transform_wrapper_id) |
||
14 | -+ | |||
130 | +! |
-
+ tags$div("One of previous transformators failed. Please check its inputs.", class = "teal-output-warning") |
||
15 | +131 |
- #' @export+ } else { |
||
16 | -+ | |||
132 | +29x |
- #' @rdname module_transform_data+ shinyjs::enable(transform_wrapper_id) |
||
17 | -+ | |||
133 | +29x |
- ui_transform_teal_data <- function(id, transformators, class = "well") {+ shiny::tagList( |
||
18 | -1x | +134 | +29x |
- checkmate::assert_string(id)+ ui_validate_error(session$ns("silent_error")), |
19 | -1x | +135 | +29x |
- if (length(transformators) == 0L) {+ ui_check_class_teal_data(session$ns("class_teal_data")), |
20 | -! | +|||
136 | +29x |
- return(NULL)+ ui_check_module_datanames(session$ns("datanames_warning")) |
||
21 | +137 |
- }+ ) |
||
22 | -1x | +|||
138 | +
- if (inherits(transformators, "teal_transform_module")) {+ } |
|||
23 | -1x | +|||
139 | +
- transformators <- list(transformators)+ }) |
|||
24 | +140 |
- }+ |
||
25 | -1x | +141 | +26x |
- checkmate::assert_list(transformators, "teal_transform_module")+ .trigger_on_success(data_handled) |
26 | -1x | +|||
142 | +
- names(transformators) <- sprintf("transform_%d", seq_len(length(transformators)))+ }) |
|||
27 | +143 |
-
+ }, |
||
28 | -1x | +144 | +23x |
- lapply(+ x = names(transformators), |
29 | -1x | +145 | +23x |
- names(transformators),+ init = data |
30 | -1x | +|||
146 | +
- function(name) {+ ) |
|||
31 | -1x | +147 | +23x |
- child_id <- NS(id, name)+ module_output |
32 | -1x | +|||
148 | +
- ns <- NS(child_id)+ }) |
|||
33 | -1x | +|||
149 | +
- data_mod <- transformators[[name]]+ } |
|||
34 | -1x | +
1 | +
- transform_wrapper_id <- ns(sprintf("wrapper_%s", name))+ #' `teal_data` utils |
|||
35 | +2 |
-
+ #' |
||
36 | -1x | +|||
3 | +
- display_fun <- if (is.null(data_mod$ui)) shinyjs::hidden else function(x) x+ #' In `teal` we need to recreate the `teal_data` object due to two operations: |
|||
37 | +4 |
-
+ #' - we need to append filter-data code and objects which have been evaluated in `FilteredData` and |
||
38 | -1x | +|||
5 | +
- display_fun(+ #' we want to avoid double-evaluation. |
|||
39 | -1x | +|||
6 | ++ |
+ #' - we need to subset `teal_data` to `datanames` used by the module, to shorten obtainable R-code+ |
+ ||
7 | +
- div(+ #' |
|||
40 | +8 |
- # class .teal_validated changes the color of the boarder on error in ui_validate_reactive_teal_data+ #' Due to above recreation of `teal_data` object can't be done simply by using public |
||
41 | +9 |
- # For details see tealValidate.js file.+ #' `teal.code` and `teal.data` methods. |
||
42 | -1x | +|||
10 | +
- id = ns("wrapper"),+ #' |
|||
43 | -1x | +|||
11 | +
- class = c(class, "teal_validated"),+ #' @param data (`teal_data`) |
|||
44 | -1x | +|||
12 | +
- title = attr(data_mod, "label"),+ #' @param code (`character`) code to append to the object's code slot. |
|||
45 | -1x | +|||
13 | +
- tags$span(+ #' @param objects (`list`) objects to append to object's environment. |
|||
46 | -1x | +|||
14 | +
- class = "text-primary mb-4",+ #' @return modified `teal_data` |
|||
47 | -1x | +|||
15 | +
- icon("fas fa-square-pen"),+ #' @keywords internal |
|||
48 | -1x | +|||
16 | +
- attr(data_mod, "label")+ #' @name teal_data_utilities |
|||
49 | +17 |
- ),+ NULL |
||
50 | -1x | +|||
18 | +
- tags$i(+ |
|||
51 | -1x | +|||
19 | +
- class = "remove pull-right fa fa-angle-down",+ #' @rdname teal_data_utilities |
|||
52 | -1x | +|||
20 | +
- style = "cursor: pointer;",+ .append_evaluated_code <- function(data, code) { |
|||
53 | -1x | +21 | +89x |
- title = "fold/expand transformator panel",+ checkmate::assert_class(data, "teal_data") |
54 | -1x | +22 | +89x |
- onclick = sprintf("togglePanelItems(this, '%s', 'fa-angle-right', 'fa-angle-down');", transform_wrapper_id)+ data@code <- c(data@code, code2list(code)) |
55 | -+ | |||
23 | +89x |
- ),+ methods::validObject(data) |
||
56 | -1x | +24 | +89x |
- tags$div(+ data |
57 | -1x | +|||
25 | +
- id = transform_wrapper_id,+ } |
|||
58 | -1x | +|||
26 | +
- if (is.null(data_mod$ui)) {+ |
|||
59 | -! | +|||
27 | +
- return(NULL)+ #' @rdname teal_data_utilities |
|||
60 | +28 |
- } else {+ .append_modified_data <- function(data, objects) { |
||
61 | -1x | +29 | +89x |
- data_mod$ui(id = ns("transform"))+ checkmate::assert_class(data, "teal_data") |
62 | -+ | |||
30 | +89x |
- },+ checkmate::assert_class(objects, "list") |
||
63 | -1x | +31 | +89x |
- div(+ new_env <- list2env(objects, parent = .GlobalEnv) |
64 | -1x | +32 | +89x |
- id = ns("validate_messages"),+ rlang::env_coalesce(new_env, as.environment(data)) |
65 | -1x | +33 | +89x |
- class = "teal_validated",+ data@.xData <- new_env |
66 | -1x | +34 | +89x |
- uiOutput(ns("error_wrapper"))+ data |
67 | +35 |
- )+ } |
68 | +1 |
- )+ #' Send input validation messages to output |
|
69 | +2 |
- )+ #' |
|
70 | +3 |
- )+ #' Captures messages from `InputValidator` objects and collates them |
|
71 | +4 |
- }+ #' into one message passed to `validate`. |
|
72 | +5 |
- )+ #' |
|
73 | +6 |
- }+ #' `shiny::validate` is used to withhold rendering of an output element until |
|
74 | +7 |
-
+ #' certain conditions are met and to print a validation message in place |
|
75 | +8 |
- #' @export+ #' of the output element. |
|
76 | +9 |
- #' @rdname module_transform_data+ #' `shinyvalidate::InputValidator` allows to validate input elements |
|
77 | +10 |
- srv_transform_teal_data <- function(id, data, transformators, modules = NULL, is_transform_failed = reactiveValues()) {- |
- |
78 | -94x | -
- checkmate::assert_string(id)- |
- |
79 | -94x | -
- assert_reactive(data)- |
- |
80 | -94x | -
- checkmate::assert_class(modules, "teal_module", null.ok = TRUE)- |
- |
81 | -94x | -
- if (length(transformators) == 0L) {- |
- |
82 | -71x | -
- return(data)+ #' and to display specific messages in their respective input widgets. |
|
83 | +11 |
- }+ #' `validate_inputs` provides a hybrid solution. |
|
84 | -23x | +||
12 | +
- if (inherits(transformators, "teal_transform_module")) {+ #' Given an `InputValidator` object, messages corresponding to inputs that fail validation |
||
85 | -3x | +||
13 | +
- transformators <- list(transformators)+ #' are extracted and placed in one validation message that is passed to a `validate`/`need` call. |
||
86 | +14 |
- }+ #' This way the input `validator` messages are repeated in the output. |
|
87 | -23x | +||
15 | +
- checkmate::assert_list(transformators, "teal_transform_module", null.ok = TRUE)+ #' |
||
88 | -23x | +||
16 | +
- names(transformators) <- sprintf("transform_%d", seq_len(length(transformators)))+ #' The `...` argument accepts any number of `InputValidator` objects |
||
89 | +17 |
-
+ #' or a nested list of such objects. |
|
90 | -23x | +||
18 | +
- moduleServer(id, function(input, output, session) {+ #' If `validators` are passed directly, all their messages are printed together |
||
91 | -23x | +||
19 | +
- module_output <- Reduce(+ #' under one (optional) header message specified by `header`. If a list is passed, |
||
92 | -23x | +||
20 | +
- function(data_previous, name) {+ #' messages are grouped by `validator`. The list's names are used as headers |
||
93 | -26x | +||
21 | +
- moduleServer(name, function(input, output, session) {+ #' for their respective message groups. |
||
94 | -26x | +||
22 | +
- logger::log_debug("srv_transform_teal_data initializing for { name }.")+ #' If neither of the nested list elements is named, a header message is taken from `header`. |
||
95 | -26x | +||
23 | +
- is_transform_failed[[name]] <- FALSE+ #' |
||
96 | -26x | +||
24 | +
- data_out <- transformators[[name]]$server("transform", data = data_previous)+ #' @param ... either any number of `InputValidator` objects |
||
97 | -26x | +||
25 | +
- data_handled <- reactive(tryCatch(data_out(), error = function(e) e))+ #' or an optionally named, possibly nested `list` of `InputValidator` |
||
98 | -26x | +||
26 | +
- observeEvent(data_handled(), {+ #' objects, see `Details` |
||
99 | -32x | +||
27 | +
- if (inherits(data_handled(), "teal_data")) {+ #' @param header (`character(1)`) generic validation message; set to NULL to omit |
||
100 | -22x | +||
28 | +
- is_transform_failed[[name]] <- FALSE+ #' |
||
101 | +29 |
- } else {+ #' @return |
|
102 | -10x | +||
30 | +
- is_transform_failed[[name]] <- TRUE+ #' Returns NULL if the final validation call passes and a `shiny.silent.error` if it fails. |
||
103 | +31 |
- }+ #' |
|
104 | +32 |
- })+ #' @seealso [`shinyvalidate::InputValidator`], [`shiny::validate`] |
|
105 | +33 |
-
+ #' |
|
106 | -26x | +||
34 | +
- is_previous_failed <- reactive({+ #' @examplesIf require("shinyvalidate") |
||
107 | -29x | +||
35 | +
- idx_this <- which(names(is_transform_failed) == name)+ #' library(shiny) |
||
108 | -29x | +||
36 | +
- is_transform_failed_list <- reactiveValuesToList(is_transform_failed)+ #' library(shinyvalidate) |
||
109 | -29x | +||
37 | +
- idx_failures <- which(unlist(is_transform_failed_list))+ #' |
||
110 | -29x | +||
38 | +
- any(idx_failures < idx_this)+ #' ui <- fluidPage( |
||
111 | +39 |
- })+ #' selectInput("method", "validation method", c("sequential", "combined", "grouped")), |
|
112 | +40 |
-
+ #' sidebarLayout( |
|
113 | -26x | +||
41 | +
- srv_validate_error("silent_error", data_handled, validate_shiny_silent_error = FALSE)+ #' sidebarPanel( |
||
114 | -26x | +||
42 | +
- srv_check_class_teal_data("class_teal_data", data_handled)+ #' selectInput("letter", "select a letter:", c(letters[1:3], LETTERS[4:6])), |
||
115 | -26x | +||
43 | +
- if (!is.null(modules)) {+ #' selectInput("number", "select a number:", 1:6), |
||
116 | -20x | +||
44 | +
- srv_check_module_datanames("datanames_warning", data_handled, modules)+ #' tags$br(), |
||
117 | +45 |
- }+ #' selectInput("color", "select a color:", |
|
118 | +46 |
-
+ #' c("black", "indianred2", "springgreen2", "cornflowerblue"), |
|
119 | +47 |
- # When there is no UI (`ui = NULL`) it should still show the errors+ #' multiple = TRUE |
|
120 | -26x | +||
48 | +
- observe({+ #' ), |
||
121 | -32x | +||
49 | +
- if (!inherits(data_handled(), "teal_data") && !is_previous_failed()) {+ #' sliderInput("size", "select point size:", |
||
122 | -10x | +||
50 | +
- shinyjs::show("wrapper")+ #' min = 0.1, max = 4, value = 0.25 |
||
123 | +51 |
- }+ #' ) |
|
124 | +52 |
- })+ #' ), |
|
125 | +53 |
-
+ #' mainPanel(plotOutput("plot")) |
|
126 | -26x | +||
54 | +
- transform_wrapper_id <- sprintf("wrapper_%s", name)+ #' ) |
||
127 | -26x | +||
55 | +
- output$error_wrapper <- renderUI({+ #' ) |
||
128 | -29x | +||
56 | +
- if (is_previous_failed()) {+ #' |
||
129 | -! | +||
57 | +
- shinyjs::disable(transform_wrapper_id)+ #' server <- function(input, output) { |
||
130 | -! | +||
58 | +
- tags$div("One of previous transformators failed. Please check its inputs.", class = "teal-output-warning")+ #' # set up input validation |
||
131 | +59 |
- } else {+ #' iv <- InputValidator$new() |
|
132 | -29x | +||
60 | +
- shinyjs::enable(transform_wrapper_id)+ #' iv$add_rule("letter", sv_in_set(LETTERS, "choose a capital letter")) |
||
133 | -29x | +||
61 | +
- shiny::tagList(+ #' iv$add_rule("number", function(x) { |
||
134 | -29x | +||
62 | +
- ui_validate_error(session$ns("silent_error")),+ #' if (as.integer(x) %% 2L == 1L) "choose an even number" |
||
135 | -29x | +||
63 | +
- ui_check_class_teal_data(session$ns("class_teal_data")),+ #' }) |
||
136 | -29x | +||
64 | +
- ui_check_module_datanames(session$ns("datanames_warning"))+ #' iv$enable() |
||
137 | +65 |
- )+ #' # more input validation |
|
138 | +66 |
- }+ #' iv_par <- InputValidator$new() |
|
139 | +67 |
- })+ #' iv_par$add_rule("color", sv_required(message = "choose a color")) |
|
140 | +68 |
-
+ #' iv_par$add_rule("color", function(x) { |
|
141 | -26x | +||
69 | +
- .trigger_on_success(data_handled)+ #' if (length(x) > 1L) "choose only one color" |
||
142 | +70 |
- })+ #' }) |
|
143 | +71 |
- },+ #' iv_par$add_rule( |
|
144 | -23x | +||
72 | +
- x = names(transformators),+ #' "size", |
||
145 | -23x | +||
73 | +
- init = data+ #' sv_between( |
||
146 | +74 |
- )+ #' left = 0.5, right = 3, |
|
147 | -23x | +||
75 | +
- module_output+ #' message_fmt = "choose a value between {left} and {right}" |
||
148 | +76 |
- })+ #' ) |
|
149 | +77 |
- }+ #' ) |
1 | +78 |
- #' Create a `tdata` object+ #' iv_par$enable() |
|
2 | +79 |
#' |
|
3 | +80 |
- #' @description `r lifecycle::badge("superseded")`+ #' output$plot <- renderPlot({ |
|
4 | +81 |
- #'+ #' # validate output |
|
5 | +82 |
- #' Recent changes in `teal` cause modules to fail because modules expect a `tdata` object+ #' switch(input[["method"]], |
|
6 | +83 |
- #' to be passed to the `data` argument but instead they receive a `teal_data` object,+ #' "sequential" = { |
|
7 | +84 |
- #' which is additionally wrapped in a reactive expression in the server functions.+ #' validate_inputs(iv) |
|
8 | +85 |
- #' In order to easily adapt such modules without a proper refactor,+ #' validate_inputs(iv_par, header = "Set proper graphical parameters") |
|
9 | +86 |
- #' use this function to downgrade the `data` argument.+ #' }, |
|
10 | +87 |
- #'+ #' "combined" = validate_inputs(iv, iv_par), |
|
11 | +88 |
- #' @name tdata+ #' "grouped" = validate_inputs(list( |
|
12 | +89 |
- #' @param ... ignored+ #' "Some inputs require attention" = iv, |
|
13 | +90 |
- #' @return nothing+ #' "Set proper graphical parameters" = iv_par |
|
14 | +91 |
- NULL+ #' )) |
|
15 | +92 |
-
+ #' ) |
|
16 | +93 |
- #' @rdname tdata+ #' |
|
17 | +94 |
- #' @export+ #' plot(faithful$eruptions ~ faithful$waiting, |
|
18 | +95 |
- new_tdata <- function(...) {+ #' las = 1, pch = 16, |
|
19 | -! | +||
96 | +
- .deprecate_tdata_msg()+ #' col = input[["color"]], cex = input[["size"]] |
||
20 | +97 |
- }+ #' ) |
|
21 | +98 |
-
+ #' }) |
|
22 | +99 |
- #' @rdname tdata+ #' } |
|
23 | +100 |
- #' @export+ #' |
|
24 | +101 |
- tdata2env <- function(...) {+ #' if (interactive()) { |
|
25 | -! | +||
102 | +
- .deprecate_tdata_msg()+ #' shinyApp(ui, server) |
||
26 | +103 |
- }+ #' } |
|
27 | +104 |
-
+ #' |
|
28 | +105 |
- #' @rdname tdata+ #' @export |
|
29 | +106 |
- #' @export+ #' |
|
30 | +107 |
- get_code_tdata <- function(...) {+ validate_inputs <- function(..., header = "Some inputs require attention") { |
|
31 | -! | +||
108 | +36x |
- .deprecate_tdata_msg()+ dots <- list(...) |
|
32 | -+ | ||
109 | +2x |
- }+ if (!is_validators(dots)) stop("validate_inputs accepts validators or a list thereof") |
|
33 | +110 | ||
111 | +34x | +
+ messages <- extract_validator(dots, header)+ |
+ |
112 | +34x | +
+ failings <- if (!any_names(dots)) {+ |
+ |
113 | +29x | +
+ add_header(messages, header)+ |
+ |
34 | +114 |
- #' @rdname tdata+ } else {+ |
+ |
115 | +5x | +
+ unlist(messages) |
|
35 | +116 |
- #' @export+ } |
|
36 | +117 |
- join_keys.tdata <- function(...) {+ |
|
37 | -! | +||
118 | +34x |
- .deprecate_tdata_msg()+ shiny::validate(shiny::need(is.null(failings), failings)) |
|
38 | +119 |
} |
|
39 | +120 | ||
40 | +121 |
- #' @rdname tdata+ ### internal functions |
|
41 | +122 |
- #' @export+ |
|
42 | +123 |
- get_metadata <- function(...) {+ #' @noRd |
|
43 | -! | +||
124 | +
- .deprecate_tdata_msg()+ #' @keywords internal |
||
44 | +125 |
- }+ # recursive object type test |
|
45 | +126 |
-
+ # returns logical of length 1 |
|
46 | +127 |
- #' @rdname tdata+ is_validators <- function(x) { |
|
47 | -+ | ||
128 | +118x |
- #' @export+ all(if (is.list(x)) unlist(lapply(x, is_validators)) else inherits(x, "InputValidator")) |
|
48 | +129 |
- as_tdata <- function(...) {+ } |
|
49 | -! | +||
130 | +
- .deprecate_tdata_msg()+ |
||
50 | +131 |
- }+ #' @noRd |
|
51 | +132 |
-
+ #' @keywords internal |
|
52 | +133 |
-
+ # test if an InputValidator object is enabled |
|
53 | +134 |
- .deprecate_tdata_msg <- function() {+ # returns logical of length 1 |
|
54 | -! | +||
135 | +
- lifecycle::deprecate_stop(+ # official method requested at https://github.com/rstudio/shinyvalidate/issues/64 |
||
55 | -! | +||
136 | +
- when = "0.16",+ validator_enabled <- function(x) { |
||
56 | -! | +||
137 | +49x |
- what = "tdata()",+ x$.__enclos_env__$private$enabled |
|
57 | -! | +||
138 | +
- details = paste(+ } |
||
58 | -! | +||
139 | +
- "tdata has been removed in favour of `teal_data`.\n",+ |
||
59 | -! | +||
140 | +
- "Please follow migration instructions https://github.com/insightsengineering/teal/discussions/987."+ #' Recursively extract messages from validator list |
||
60 | +141 |
- )+ #' @return A character vector or a list of character vectors, possibly nested and named. |
|
61 | +142 |
- )+ #' @noRd |
|
62 | +143 |
- }+ #' @keywords internal |
1 | +144 |
- #' Evaluate expression on `teal_data_module`+ extract_validator <- function(iv, header) { |
||
2 | -+ | |||
145 | +113x |
- #'+ if (inherits(iv, "InputValidator")) { |
||
3 | -+ | |||
146 | +49x |
- #' @details+ add_header(gather_messages(iv), header) |
||
4 | +147 |
- #' `within` is a convenience function for evaluating inline code inside the environment of a `teal_data_module`.+ } else { |
||
5 | -+ | |||
148 | +58x |
- #' It accepts only inline expressions (both simple and compound) and allows for injecting values into `expr` through+ if (is.null(names(iv))) names(iv) <- rep("", length(iv)) |
||
6 | -+ | |||
149 | +64x |
- #' the `...` argument: as `name:value` pairs are passed to `...`, `name` in `expr` will be replaced with `value.`+ mapply(extract_validator, iv = iv, header = names(iv), SIMPLIFY = FALSE) |
||
7 | +150 |
- #'+ } |
||
8 | +151 |
- #' @param data (`teal_data_module`) object+ } |
||
9 | +152 |
- #' @param expr (`expression`) to evaluate. Must be inline code. See [within()]+ |
||
10 | +153 |
- #' @param ... See `Details`.+ #' Collate failing messages from validator. |
||
11 | +154 |
- #'+ #' @return `list` |
||
12 | +155 |
- #' @return+ #' @noRd |
||
13 | +156 |
- #' `within` returns a `teal_data_module` object with a delayed evaluation of `expr` when the module is run.+ #' @keywords internal |
||
14 | +157 |
- #'+ gather_messages <- function(iv) { |
||
15 | -+ | |||
158 | +49x |
- #' @examples+ if (validator_enabled(iv)) { |
||
16 | -+ | |||
159 | +46x |
- #' within(tdm, dataset1 <- subset(dataset1, Species == "virginica"))+ status <- iv$validate() |
||
17 | -+ | |||
160 | +46x |
- #'+ failing_inputs <- Filter(Negate(is.null), status) |
||
18 | -+ | |||
161 | +46x |
- #' # use additional parameter for expression value substitution.+ unique(lapply(failing_inputs, function(x) x[["message"]])) |
||
19 | +162 |
- #' valid_species <- "versicolor"+ } else { |
||
20 | -+ | |||
163 | +3x |
- #' within(tdm, dataset1 <- subset(dataset1, Species %in% species), species = valid_species)+ warning("Validator is disabled and will be omitted.")+ |
+ ||
164 | +3x | +
+ list() |
||
21 | +165 |
- #' @include teal_data_module.R+ } |
||
22 | +166 |
- #' @name within+ } |
||
23 | +167 |
- #' @rdname teal_data_module+ |
||
24 | +168 |
- #'+ #' Add optional header to failing messages |
||
25 | +169 |
- #' @export+ #' @noRd |
||
26 | +170 |
- #'+ #' @keywords internal |
||
27 | +171 |
- within.teal_data_module <- function(data, expr, ...) {+ add_header <- function(messages, header = "") { |
||
28 | -2x | +172 | +78x |
- expr <- substitute(expr)+ ans <- unlist(messages) |
29 | -2x | +173 | +78x |
- extras <- list(...)+ if (length(ans) != 0L && isTRUE(nchar(header) > 0L)) { |
30 | -+ | |||
174 | +31x |
-
+ ans <- c(paste0(header, "\n"), ans, "\n") |
||
31 | +175 |
- # Add braces for consistency.+ } |
||
32 | -2x | +176 | +78x |
- if (!identical(as.list(expr)[[1L]], as.symbol("{"))) {+ ans |
33 | -2x | +|||
177 | +
- expr <- call("{", expr)+ } |
|||
34 | +178 |
- }+ |
||
35 | +179 |
-
+ #' Recursively check if the object contains a named list |
||
36 | -2x | +|||
180 | +
- calls <- as.list(expr)[-1]+ #' @noRd |
|||
37 | +181 |
-
+ #' @keywords internal |
||
38 | +182 |
- # Inject extra values into expressions.+ any_names <- function(x) { |
||
39 | -2x | +183 | +103x |
- calls <- lapply(calls, function(x) do.call(substitute, list(x, env = extras)))+ any(+ |
+
184 | +103x | +
+ if (is.list(x)) {+ |
+ ||
185 | +58x | +
+ if (!is.null(names(x)) && any(names(x) != "")) TRUE else unlist(lapply(x, any_names)) |
||
40 | +186 |
-
+ } else { |
||
41 | -2x | +187 | +40x |
- eval_code(object = data, code = as.expression(calls))+ FALSE |
42 | +188 | ++ |
+ }+ |
+ |
189 | ++ |
+ )+ |
+ ||
190 |
}@@ -46335,14 +46559,14 @@ teal coverage - 60.12% |
1 |
- #' Filter settings for `teal` applications+ #' Evaluate expression on `teal_data_module` |
||
3 |
- #' Specify initial filter states and filtering settings for a `teal` app.+ #' @details |
||
4 |
- #'+ #' `within` is a convenience function for evaluating inline code inside the environment of a `teal_data_module`. |
||
5 |
- #' Produces a `teal_slices` object.+ #' It accepts only inline expressions (both simple and compound) and allows for injecting values into `expr` through |
||
6 |
- #' The `teal_slice` components will specify filter states that will be active when the app starts.+ #' the `...` argument: as `name:value` pairs are passed to `...`, `name` in `expr` will be replaced with `value.` |
||
7 |
- #' Attributes (created with the named arguments) will configure the way the app applies filters.+ #' |
||
8 |
- #' See argument descriptions for details.+ #' @param data (`teal_data_module`) object |
||
9 |
- #'+ #' @param expr (`expression`) to evaluate. Must be inline code. See [within()] |
||
10 |
- #' @inheritParams teal.slice::teal_slices+ #' @param ... See `Details`. |
||
12 |
- #' @param module_specific (`logical(1)`) optional,+ #' @return |
||
13 |
- #' - `FALSE` (default) when one filter panel applied to all modules.+ #' `within` returns a `teal_data_module` object with a delayed evaluation of `expr` when the module is run. |
||
14 |
- #' All filters will be shared by all modules.+ #' |
||
15 |
- #' - `TRUE` when filter panel module-specific.+ #' @examples |
||
16 |
- #' Modules can have different set of filters specified - see `mapping` argument.+ #' within(tdm, dataset1 <- subset(dataset1, Species == "virginica")) |
||
17 |
- #' @param mapping `r lifecycle::badge("experimental")`+ #' |
||
18 |
- #' _This is a new feature. Do kindly share your opinions on+ #' # use additional parameter for expression value substitution. |
||
19 |
- #' [`teal`'s GitHub repository](https://github.com/insightsengineering/teal/)._+ #' valid_species <- "versicolor" |
||
20 |
- #'+ #' within(tdm, dataset1 <- subset(dataset1, Species %in% species), species = valid_species) |
||
21 |
- #' (named `list`) specifies which filters will be active in which modules on app start.+ #' @include teal_data_module.R |
||
22 |
- #' Elements should contain character vector of `teal_slice` `id`s (see [`teal.slice::teal_slice`]).+ #' @name within |
||
23 |
- #' Names of the list should correspond to `teal_module` `label` set in [module()] function.+ #' @rdname teal_data_module |
||
24 |
- #' - `id`s listed under `"global_filters` will be active in all modules.+ #' |
||
25 |
- #' - If missing, all filters will be applied to all modules.+ #' @export |
||
26 |
- #' - If empty list, all filters will be available to all modules but will start inactive.+ #' |
||
27 |
- #' - If `module_specific` is `FALSE`, only `global_filters` will be active on start.+ within.teal_data_module <- function(data, expr, ...) { |
||
28 | -+ | 2x |
- #' @param app_id (`character(1)`)+ expr <- substitute(expr) |
29 | -+ | 2x |
- #' For internal use only, do not set manually.+ extras <- list(...) |
30 |
- #' Added by `init` so that a `teal_slices` can be matched to the app in which it was used.+ |
||
31 |
- #' Used for verifying snapshots uploaded from file. See `snapshot`.+ # Add braces for consistency. |
||
32 | -+ | 2x |
- #'+ if (!identical(as.list(expr)[[1L]], as.symbol("{"))) { |
33 | -+ | 2x |
- #' @param x (`list`) of lists to convert to `teal_slices`+ expr <- call("{", expr) |
34 |
- #'+ } |
||
35 |
- #' @return+ |
||
36 | -+ | 2x |
- #' A `teal_slices` object.+ calls <- as.list(expr)[-1] |
37 |
- #'+ |
||
38 |
- #' @seealso [`teal.slice::teal_slices`], [`teal.slice::teal_slice`], [slices_store()]+ # Inject extra values into expressions. |
||
39 | -+ | 2x |
- #'+ calls <- lapply(calls, function(x) do.call(substitute, list(x, env = extras))) |
40 |
- #' @examples+ |
||
41 | -+ | 2x |
- #' filter <- teal_slices(+ eval_code(object = data, code = as.expression(calls)) |
42 |
- #' teal_slice(dataname = "iris", varname = "Species", id = "species"),- |
- ||
43 | -- |
- #' teal_slice(dataname = "iris", varname = "Sepal.Length", id = "sepal_length"),+ } |
44 | +1 |
- #' teal_slice(+ #' Create a `tdata` object |
|
45 | +2 |
- #' dataname = "iris", id = "long_petals", title = "Long petals", expr = "Petal.Length > 5"+ #' |
|
46 | +3 |
- #' ),+ #' @description `r lifecycle::badge("superseded")` |
|
47 | +4 |
- #' teal_slice(dataname = "mtcars", varname = "mpg", id = "mtcars_mpg"),+ #' |
|
48 | +5 |
- #' mapping = list(+ #' Recent changes in `teal` cause modules to fail because modules expect a `tdata` object |
|
49 | +6 |
- #' module1 = c("species", "sepal_length"),+ #' to be passed to the `data` argument but instead they receive a `teal_data` object, |
|
50 | +7 |
- #' module2 = c("mtcars_mpg"),+ #' which is additionally wrapped in a reactive expression in the server functions. |
|
51 | +8 |
- #' global_filters = "long_petals"+ #' In order to easily adapt such modules without a proper refactor, |
|
52 | +9 |
- #' )+ #' use this function to downgrade the `data` argument. |
|
53 | +10 |
- #' )+ #' |
|
54 | +11 |
- #'+ #' @name tdata |
|
55 | +12 |
- #' app <- init(+ #' @param ... ignored |
|
56 | +13 |
- #' data = teal_data(iris = iris, mtcars = mtcars),+ #' @return nothing |
|
57 | +14 |
- #' modules = list(+ NULL |
|
58 | +15 |
- #' module("module1"),+ |
|
59 | +16 |
- #' module("module2")+ #' @rdname tdata |
|
60 | +17 |
- #' ),+ #' @export |
|
61 | +18 |
- #' filter = filter+ new_tdata <- function(...) { |
|
62 | -+ | ||
19 | +! |
- #' )+ .deprecate_tdata_msg() |
|
63 | +20 |
- #'+ } |
|
64 | +21 |
- #' if (interactive()) {+ |
|
65 | +22 |
- #' shinyApp(app$ui, app$server)+ #' @rdname tdata |
|
66 | +23 |
- #' }+ #' @export |
|
67 | +24 |
- #'+ tdata2env <- function(...) { |
|
68 | -+ | ||
25 | +! |
- #' @export+ .deprecate_tdata_msg() |
|
69 | +26 |
- teal_slices <- function(...,+ } |
|
70 | +27 |
- exclude_varnames = NULL,+ |
|
71 | +28 |
- include_varnames = NULL,+ #' @rdname tdata |
|
72 | +29 |
- count_type = NULL,+ #' @export |
|
73 | +30 |
- allow_add = TRUE,+ get_code_tdata <- function(...) { |
|
74 | -+ | ||
31 | +! |
- module_specific = FALSE,+ .deprecate_tdata_msg() |
|
75 | +32 |
- mapping,+ } |
|
76 | +33 |
- app_id = NULL) {+ |
|
77 | -170x | +||
34 | +
- shiny::isolate({+ #' @rdname tdata |
||
78 | -170x | +||
35 | +
- checkmate::assert_flag(allow_add)+ #' @export |
||
79 | -170x | +||
36 | +
- checkmate::assert_flag(module_specific)+ join_keys.tdata <- function(...) { |
||
80 | -53x | +||
37 | +! |
- if (!missing(mapping)) checkmate::assert_list(mapping, types = c("character", "NULL"), names = "named")+ .deprecate_tdata_msg() |
|
81 | -167x | +||
38 | +
- checkmate::assert_string(app_id, null.ok = TRUE)+ } |
||
82 | +39 | ||
83 | -167x | -
- slices <- list(...)- |
- |
84 | -167x | -
- all_slice_id <- vapply(slices, `[[`, character(1L), "id")- |
- |
85 | +40 |
-
+ #' @rdname tdata |
|
86 | -167x | +||
41 | +
- if (missing(mapping)) {+ #' @export |
||
87 | -117x | +||
42 | +
- mapping <- if (length(all_slice_id)) {+ get_metadata <- function(...) { |
||
88 | -26x | +||
43 | +! |
- list(global_filters = all_slice_id)+ .deprecate_tdata_msg() |
|
89 | +44 |
- } else {+ } |
|
90 | -91x | +||
45 | +
- list()+ |
||
91 | +46 |
- }+ #' @rdname tdata |
|
92 | +47 |
- }+ #' @export |
|
93 | +48 |
-
+ as_tdata <- function(...) { |
|
94 | -167x | +||
49 | +! |
- if (!module_specific) {+ .deprecate_tdata_msg() |
|
95 | -148x | +||
50 | +
- mapping[setdiff(names(mapping), "global_filters")] <- NULL+ } |
||
96 | +51 |
- }+ |
|
97 | +52 | ||
98 | -167x | +||
53 | +
- failed_slice_id <- setdiff(unlist(mapping), all_slice_id)+ .deprecate_tdata_msg <- function() { |
||
99 | -167x | +||
54 | +! |
- if (length(failed_slice_id)) {+ lifecycle::deprecate_stop( |
|
100 | -1x | +||
55 | +! |
- stop(sprintf(+ when = "0.16", |
|
101 | -1x | +||
56 | +! |
- "Filters in mapping don't match any available filter.\n %s not in %s",+ what = "tdata()", |
|
102 | -1x | +||
57 | +! |
- toString(failed_slice_id),+ details = paste( |
|
103 | -1x | +||
58 | +! |
- toString(all_slice_id)+ "tdata has been removed in favour of `teal_data`.\n",+ |
+ |
59 | +! | +
+ "Please follow migration instructions https://github.com/insightsengineering/teal/discussions/987." |
|
104 | +60 |
- ))+ ) |
|
105 | +61 |
- }+ ) |
|
106 | +62 |
-
+ } |
|
107 | -166x | +
1 | +
- tss <- teal.slice::teal_slices(+ #' Generates library calls from current session info |
|||
108 | +2 |
- ...,+ #' |
||
109 | -166x | +|||
3 | +
- exclude_varnames = exclude_varnames,+ #' Function to create multiple library calls out of current session info to ensure reproducible code works. |
|||
110 | -166x | +|||
4 | +
- include_varnames = include_varnames,+ #' |
|||
111 | -166x | +|||
5 | +
- count_type = count_type,+ #' @return Character vector of `library(<package>)` calls. |
|||
112 | -166x | +|||
6 | +
- allow_add = allow_add+ #' @keywords internal |
|||
113 | +7 |
- )+ get_rcode_libraries <- function() { |
||
114 | -166x | +8 | +1x |
- attr(tss, "mapping") <- mapping+ libraries <- vapply( |
115 | -166x | +9 | +1x |
- attr(tss, "module_specific") <- module_specific+ utils::sessionInfo()$otherPkgs, |
116 | -166x | +10 | +1x |
- attr(tss, "app_id") <- app_id+ function(x) { |
117 | -166x | +11 | +15x |
- class(tss) <- c("modules_teal_slices", class(tss))+ paste0("library(", x$Package, ")")+ |
+
12 | ++ |
+ }, |
||
118 | -166x | +13 | +1x |
- tss+ character(1) |
119 | +14 |
- })+ ) |
||
120 | -+ | |||
15 | +1x |
- }+ paste0(paste0(rev(libraries), sep = "\n"), collapse = "") |
||
121 | +16 |
-
+ } |
||
122 | +17 | |||
123 | +18 |
- #' @rdname teal_slices+ |
||
124 | +19 |
- #' @export+ #' @noRd |
||
125 | +20 |
#' @keywords internal |
||
126 | +21 |
- #'+ get_rcode_str_install <- function() { |
||
127 | -+ | |||
22 | +5x |
- as.teal_slices <- function(x) { # nolint: object_name.+ code_string <- getOption("teal.load_nest_code") |
||
128 | -15x | +23 | +5x |
- checkmate::assert_list(x)+ if (is.character(code_string)) { |
129 | -15x | +24 | +2x |
- lapply(x, checkmate::assert_list, names = "named", .var.name = "list element")+ code_string |
130 | +25 | - - | -||
131 | -15x | -
- attrs <- attributes(unclass(x))+ } else { |
||
132 | -15x | +26 | +3x |
- ans <- lapply(x, function(x) if (is.teal_slice(x)) x else as.teal_slice(x))+ "# Add any code to install/load your NEST environment here\n" |
133 | -15x | +|||
27 | +
- do.call(teal_slices, c(ans, attrs))+ } |
|||
134 | +28 |
} |
135 | +1 |
-
+ #' Include `CSS` files from `/inst/css/` package directory to application header |
|
136 | +2 |
-
+ #' |
|
137 | +3 |
- #' @rdname teal_slices+ #' `system.file` should not be used to access files in other packages, it does |
|
138 | +4 |
- #' @export+ #' not work with `devtools`. Therefore, we redefine this method in each package |
|
139 | +5 |
- #' @keywords internal+ #' as needed. Thus, we do not export this method. |
|
140 | +6 |
#' |
|
141 | +7 |
- c.teal_slices <- function(...) {- |
- |
142 | -6x | -
- x <- list(...)- |
- |
143 | -6x | -
- checkmate::assert_true(all(vapply(x, is.teal_slices, logical(1L))), .var.name = "all arguments are teal_slices")+ #' @param pattern (`character`) pattern of files to be included |
|
144 | +8 |
-
+ #' |
|
145 | -6x | +||
9 | +
- all_attributes <- lapply(x, attributes)+ #' @return HTML code that includes `CSS` files. |
||
146 | -6x | +||
10 | +
- all_attributes <- coalesce_r(all_attributes)+ #' @keywords internal |
||
147 | -6x | +||
11 | +
- all_attributes <- all_attributes[names(all_attributes) != "class"]+ include_css_files <- function(pattern = "*") { |
||
148 | -+ | ||
12 | +! |
-
+ css_files <- list.files( |
|
149 | -6x | +||
13 | +! |
- do.call(+ system.file("css", package = "teal", mustWork = TRUE), |
|
150 | -6x | +||
14 | +! |
- teal_slices,+ pattern = pattern, full.names = TRUE |
|
151 | -6x | +||
15 | +
- c(+ ) |
||
152 | -6x | +||
16 | +
- unique(unlist(x, recursive = FALSE)),+ |
||
153 | -6x | +||
17 | +! |
- all_attributes+ singleton( |
|
154 | -+ | ||
18 | +! |
- )+ tags$head(lapply(css_files, includeCSS)) |
|
155 | +19 |
) |
|
156 | +20 |
} |
|
157 | +21 | ||
158 | +22 |
-
+ #' Include `JS` files from `/inst/js/` package directory to application header |
|
159 | +23 |
- #' Deep copy `teal_slices`+ #' |
|
160 | +24 |
- #'+ #' `system.file` should not be used to access files in other packages, it does |
|
161 | +25 |
- #' it's important to create a new copy of `teal_slices` when+ #' not work with `devtools`. Therefore, we redefine this method in each package |
|
162 | +26 |
- #' starting a new `shiny` session. Otherwise, object will be shared+ #' as needed. Thus, we do not export this method |
|
163 | +27 |
- #' by multiple users as it is created in global environment before+ #' |
|
164 | +28 |
- #' `shiny` session starts.+ #' @param pattern (`character`) pattern of files to be included, passed to `system.file` |
|
165 | +29 |
- #' @param filter (`teal_slices`)+ #' @param except (`character`) vector of basename filenames to be excluded |
|
166 | +30 |
- #' @return `teal_slices`+ #' |
|
167 | +31 |
- #' @keywords internal+ #' @return HTML code that includes `JS` files. |
|
168 | +32 |
- deep_copy_filter <- function(filter) {+ #' @keywords internal |
|
169 | -1x | +||
33 | +
- checkmate::assert_class(filter, "teal_slices")+ include_js_files <- function(pattern = NULL, except = NULL) { |
||
170 | -1x | +||
34 | +! |
- shiny::isolate({+ checkmate::assert_character(except, min.len = 1, any.missing = FALSE, null.ok = TRUE) |
|
171 | -1x | +||
35 | +! |
- filter_copy <- lapply(filter, function(slice) {+ js_files <- list.files(system.file("js", package = "teal", mustWork = TRUE), pattern = pattern, full.names = TRUE) |
|
172 | -2x | +||
36 | +! |
- teal.slice::as.teal_slice(as.list(slice))+ js_files <- js_files[!(basename(js_files) %in% except)] # no-op if except is NULL |
|
173 | +37 |
- })+ |
|
174 | -1x | +||
38 | +! |
- attributes(filter_copy) <- attributes(filter)+ singleton(lapply(js_files, includeScript)) |
|
175 | -1x | +||
39 | +
- filter_copy+ } |
||
176 | +40 |
- })+ |
|
177 | +41 |
- }+ #' Run `JS` file from `/inst/js/` package directory |
1 | +42 |
- #' `teal_data` utils+ #' |
|
2 | +43 |
- #'+ #' This is triggered from the server to execute on the client |
|
3 | +44 |
- #' In `teal` we need to recreate the `teal_data` object due to two operations:+ #' rather than triggered directly on the client. |
|
4 | +45 |
- #' - we need to append filter-data code and objects which have been evaluated in `FilteredData` and+ #' Unlike `include_js_files` which includes `JavaScript` functions, |
|
5 | +46 |
- #' we want to avoid double-evaluation.+ #' the `run_js` actually executes `JavaScript` functions. |
|
6 | +47 |
- #' - we need to subset `teal_data` to `datanames` used by the module, to shorten obtainable R-code+ #' |
|
7 | +48 |
- #'+ #' `system.file` should not be used to access files in other packages, it does |
|
8 | +49 |
- #' Due to above recreation of `teal_data` object can't be done simply by using public+ #' not work with `devtools`. Therefore, we redefine this method in each package |
|
9 | +50 |
- #' `teal.code` and `teal.data` methods.+ #' as needed. Thus, we do not export this method. |
|
10 | +51 |
#' |
|
11 | +52 |
- #' @param data (`teal_data`)+ #' @param files (`character`) vector of filenames. |
|
12 | +53 |
- #' @param code (`character`) code to append to the object's code slot.+ #' |
|
13 | +54 |
- #' @param objects (`list`) objects to append to object's environment.+ #' @return `NULL`, invisibly. |
|
14 | +55 |
- #' @return modified `teal_data`+ #' @keywords internal |
|
15 | +56 |
- #' @keywords internal+ run_js_files <- function(files) {+ |
+ |
57 | +88x | +
+ checkmate::assert_character(files, min.len = 1, any.missing = FALSE)+ |
+ |
58 | +88x | +
+ lapply(files, function(file) {+ |
+ |
59 | +88x | +
+ shinyjs::runjs(paste0(readLines(system.file("js", file, package = "teal", mustWork = TRUE)), collapse = "\n")) |
|
16 | +60 |
- #' @name teal_data_utilities+ })+ |
+ |
61 | +88x | +
+ invisible(NULL) |
|
17 | +62 |
- NULL+ } |
|
18 | +63 | ||
19 | +64 |
- #' @rdname teal_data_utilities+ #' Code to include `teal` `CSS` and `JavaScript` files |
|
20 | +65 |
- .append_evaluated_code <- function(data, code) {+ #' |
|
21 | -89x | +||
66 | +
- checkmate::assert_class(data, "teal_data")+ #' This is useful when you want to use the same `JavaScript` and `CSS` files that are |
||
22 | -89x | +||
67 | +
- data@code <- c(data@code, code2list(code))+ #' used with the `teal` application. |
||
23 | -89x | +||
68 | +
- methods::validObject(data)+ #' This is also useful for running standalone modules in `teal` with the correct |
||
24 | -89x | +||
69 | +
- data+ #' styles. |
||
25 | +70 |
- }+ #' Also initializes `shinyjs` so you can use it. |
|
26 | +71 |
-
+ #' |
|
27 | +72 |
- #' @rdname teal_data_utilities+ #' Simply add `include_teal_css_js()` as one of the UI elements. |
|
28 | +73 |
- .append_modified_data <- function(data, objects) {+ #' @return A `shiny.tag.list`. |
|
29 | -89x | +||
74 | +
- checkmate::assert_class(data, "teal_data")+ #' @keywords internal |
||
30 | -89x | +||
75 | +
- checkmate::assert_class(objects, "list")+ include_teal_css_js <- function() { |
||
31 | -89x | +||
76 | +! |
- new_env <- list2env(objects, parent = .GlobalEnv)+ tagList( |
|
32 | -89x | +||
77 | +! |
- rlang::env_coalesce(new_env, as.environment(data))+ shinyjs::useShinyjs(), |
|
33 | -89x | +||
78 | +! |
- data@.xData <- new_env+ include_css_files(), |
|
34 | -89x | +||
79 | +
- data+ # 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 |
|
35 | +82 | ++ |
+ )+ |
+
83 |
}@@ -47831,14 +48088,14 @@ teal coverage - 60.12% |
1 |
- #' UI and server modules of `teal`+ #' Store and restore `teal_slices` object |
||
3 |
- #' @description `r lifecycle::badge("deprecated")`+ #' Functions that write a `teal_slices` object to a file in the `JSON` format, |
||
4 |
- #' Please use [`module_teal`] instead.+ #' and also restore the object from disk. |
||
6 |
- #' @inheritParams ui_teal+ #' Date and date time objects are stored in the following formats: |
||
7 |
- #' @inheritParams srv_teal+ #' |
||
8 |
- #'+ #' - `Date` class is converted to the `"ISO8601"` standard (`YYYY-MM-DD`). |
||
9 |
- #' @return+ #' - `POSIX*t` classes are converted to character by using |
||
10 |
- #' Returns a `reactive` expression containing a `teal_data` object when data is loaded or `NULL` when it is not.+ #' `format.POSIX*t(usetz = TRUE, tz = "UTC")` (`YYYY-MM-DD HH:MM:SS UTC`, where |
||
11 |
- #' @name module_teal_with_splash+ #' `UTC` is the `Coordinated Universal Time` timezone short-code). |
||
13 |
- NULL+ #' This format is assumed during `slices_restore`. All `POSIX*t` objects in |
||
14 |
-
+ #' `selected` or `choices` fields of `teal_slice` objects are always printed in |
||
15 |
- #' @export+ #' `UTC` timezone as well. |
||
16 |
- #' @rdname module_teal_with_splash+ #' |
||
17 |
- ui_teal_with_splash <- function(id,+ #' @param tss (`teal_slices`) object to be stored. |
||
18 |
- data,+ #' @param file (`character(1)`) file path where `teal_slices` object will be |
||
19 |
- title = build_app_title(),+ #' saved and restored. The file extension should be `".json"`. |
||
20 |
- header = tags$p(),+ #' |
||
21 |
- footer = tags$p()) {+ #' @return `slices_store` returns `NULL`, invisibly. |
||
22 | -! | +
- lifecycle::deprecate_soft(+ #' |
|
23 | -! | +
- when = "0.16",+ #' @seealso [teal_slices()] |
|
24 | -! | +
- what = "ui_teal_with_splash()",+ #' |
|
25 | -! | +
- details = "Deprecated, please use `ui_teal` instead"+ #' @keywords internal |
|
26 |
- )+ #' |
||
27 | -! | +
- ui_teal(id = id, title = title, header = header, footer = footer)+ slices_store <- function(tss, file) { |
|
28 | -+ | 9x |
- }+ checkmate::assert_class(tss, "teal_slices") |
29 | -+ | 9x |
-
+ checkmate::assert_path_for_output(file, overwrite = TRUE, extension = "json") |
30 |
- #' @export+ |
||
31 | -+ | 9x |
- #' @rdname module_teal_with_splash+ cat(format(tss, trim_lines = FALSE), "\n", file = file) |
32 |
- srv_teal_with_splash <- function(id, data, modules, filter = teal_slices()) {+ } |
||
33 | -! | +
- lifecycle::deprecate_soft(+ |
|
34 | -! | +
- when = "0.16",+ #' @rdname slices_store |
|
35 | -! | +
- what = "srv_teal_with_splash()",+ #' @return `slices_restore` returns a `teal_slices` object restored from the file. |
|
36 | -! | +
- details = "Deprecated, please use `srv_teal` instead"+ #' @keywords internal |
|
37 |
- )+ slices_restore <- function(file) { |
||
38 | -! | +9x |
- srv_teal(id = id, data = data, modules = modules, filter = filter)+ checkmate::assert_file_exists(file, access = "r", extension = "json") |
39 |
- }+ |
1 | -+ | |||
40 | +9x |
- #' Generates library calls from current session info+ tss_json <- jsonlite::fromJSON(file, simplifyDataFrame = FALSE) |
||
2 | -+ | |||
41 | +9x | +
+ tss_json$slices <-+ |
+ ||
42 | +9x | +
+ lapply(tss_json$slices, function(slice) {+ |
+ ||
43 | +9x |
- #'+ for (field in c("selected", "choices")) { |
||
3 | -+ | |||
44 | +18x |
- #' Function to create multiple library calls out of current session info to ensure reproducible code works.+ if (!is.null(slice[[field]])) { |
||
4 | -+ | |||
45 | +12x |
- #'+ if (length(slice[[field]]) > 0) { |
||
5 | -+ | |||
46 | +9x |
- #' @return Character vector of `library(<package>)` calls.+ date_partial_regex <- "^[0-9]{4}-[0-9]{2}-[0-9]{2}" |
||
6 | -+ | |||
47 | +9x |
- #' @keywords internal+ time_stamp_regex <- paste0(date_partial_regex, "\\s[0-9]{2}:[0-9]{2}:[0-9]{2}\\sUTC$") |
||
7 | +48 |
- get_rcode_libraries <- function() {+ |
||
8 | -1x | +49 | +9x |
- libraries <- vapply(+ slice[[field]] <- |
9 | -1x | +50 | +9x |
- utils::sessionInfo()$otherPkgs,+ if (all(grepl(paste0(date_partial_regex, "$"), slice[[field]]))) { |
10 | -1x | +51 | +3x |
- function(x) {+ as.Date(slice[[field]]) |
11 | -15x | -
- paste0("library(", x$Package, ")")- |
- ||
12 | -+ | 52 | +9x |
- },+ } else if (all(grepl(time_stamp_regex, slice[[field]]))) { |
13 | -1x | +53 | +3x |
- character(1)+ as.POSIXct(slice[[field]], tz = "UTC") |
14 | +54 |
- )+ } else { |
||
15 | -1x | +55 | +3x |
- paste0(paste0(rev(libraries), sep = "\n"), collapse = "")+ slice[[field]] |
16 | +56 |
- }+ } |
||
17 | +57 |
-
+ } else { |
||
18 | -+ | |||
58 | +3x |
-
+ slice[[field]] <- character(0) |
||
19 | +59 |
- #' @noRd+ } |
||
20 | +60 |
- #' @keywords internal+ } |
||
21 | +61 |
- get_rcode_str_install <- function() {- |
- ||
22 | -5x | -
- code_string <- getOption("teal.load_nest_code")+ } |
||
23 | -5x | +62 | +9x |
- if (is.character(code_string)) {+ slice |
24 | -2x | +|||
63 | +
- code_string+ }) |
|||
25 | +64 |
- } else {+ |
||
26 | -3x | +65 | +9x |
- "# Add any code to install/load your NEST environment here\n"+ tss_elements <- lapply(tss_json$slices, as.teal_slice) |
27 | +66 |
- }+ + |
+ ||
67 | +9x | +
+ do.call(teal_slices, c(tss_elements, tss_json$attributes)) |
||
28 | +68 |
}@@ -48312,14 +48570,14 @@ teal coverage - 60.12% |
1 |
- #' Include `CSS` files from `/inst/css/` package directory to application header+ #' Show `R` code modal |
||
3 |
- #' `system.file` should not be used to access files in other packages, it does+ #' @description `r lifecycle::badge("deprecated")` |
||
4 |
- #' not work with `devtools`. Therefore, we redefine this method in each package+ #' |
||
5 |
- #' as needed. Thus, we do not export this method.+ #' Use the [shiny::showModal()] function to show the `R` code inside. |
||
7 |
- #' @param pattern (`character`) pattern of files to be included+ #' @param title (`character(1)`) |
||
8 |
- #'+ #' Title of the modal, displayed in the first comment of the `R` code. |
||
9 |
- #' @return HTML code that includes `CSS` files.+ #' @param rcode (`character`) |
||
10 |
- #' @keywords internal+ #' vector with `R` code to show inside the modal. |
||
11 |
- include_css_files <- function(pattern = "*") {+ #' @param session (`ShinySession`) optional |
||
12 | -! | +
- css_files <- list.files(+ #' `shiny` session object, defaults to [shiny::getDefaultReactiveDomain()]. |
|
13 | -! | +
- system.file("css", package = "teal", mustWork = TRUE),+ #' |
|
14 | -! | +
- pattern = pattern, full.names = TRUE+ #' @references [shiny::showModal()] |
|
15 |
- )+ #' @export |
||
16 |
-
+ show_rcode_modal <- function(title = NULL, rcode, session = getDefaultReactiveDomain()) { |
||
17 | ! |
- singleton(+ lifecycle::deprecate_soft( |
|
18 | ! |
- tags$head(lapply(css_files, includeCSS))+ when = "0.16", |
|
19 | -+ | ! |
- )+ what = "show_rcode_modal()", |
20 | -+ | ! |
- }+ details = "This function will be removed in the next release." |
21 |
-
+ ) |
||
22 |
- #' Include `JS` files from `/inst/js/` package directory to application header+ |
||
23 | -+ | ! |
- #'+ rcode <- paste(rcode, collapse = "\n") |
24 |
- #' `system.file` should not be used to access files in other packages, it does+ |
||
25 | -+ | ! |
- #' not work with `devtools`. Therefore, we redefine this method in each package+ ns <- session$ns |
26 | -+ | ! |
- #' as needed. Thus, we do not export this method+ showModal(modalDialog( |
27 | -+ | ! |
- #'+ tagList( |
28 | -+ | ! |
- #' @param pattern (`character`) pattern of files to be included, passed to `system.file`+ tags$div( |
29 | -+ | ! |
- #' @param except (`character`) vector of basename filenames to be excluded+ actionButton(ns("copyRCode"), "Copy to Clipboard", `data-clipboard-target` = paste0("#", ns("r_code"))), |
30 | -+ | ! |
- #'+ modalButton("Dismiss"), |
31 | -+ | ! |
- #' @return HTML code that includes `JS` files.+ style = "mb-4" |
32 |
- #' @keywords internal+ ), |
||
33 | -+ | ! |
- include_js_files <- function(pattern = NULL, except = NULL) {+ tags$div(tags$pre(id = ns("r_code"), rcode)), |
34 | -! | +
- checkmate::assert_character(except, min.len = 1, any.missing = FALSE, null.ok = TRUE)+ ), |
|
35 | ! |
- js_files <- list.files(system.file("js", package = "teal", mustWork = TRUE), pattern = pattern, full.names = TRUE)+ title = title, |
|
36 | ! |
- js_files <- js_files[!(basename(js_files) %in% except)] # no-op if except is NULL+ footer = tagList( |
|
37 | -+ | ! |
-
+ actionButton(ns("copyRCode"), "Copy to Clipboard", `data-clipboard-target` = paste0("#", ns("r_code"))), |
38 | ! |
- singleton(lapply(js_files, includeScript))+ modalButton("Dismiss") |
|
39 |
- }+ ), |
||
40 | -+ | ! |
-
+ size = "l", |
41 | -+ | ! |
- #' Run `JS` file from `/inst/js/` package directory+ easyClose = TRUE |
42 |
- #'+ )) |
||
43 |
- #' This is triggered from the server to execute on the client+ } |
44 | +1 |
- #' rather than triggered directly on the client.+ #' Data module for `teal` applications |
|
45 | +2 |
- #' Unlike `include_js_files` which includes `JavaScript` functions,+ #' |
|
46 | +3 |
- #' the `run_js` actually executes `JavaScript` functions.+ #' @description |
|
47 | +4 |
- #'+ #' `r lifecycle::badge("experimental")` |
|
48 | +5 |
- #' `system.file` should not be used to access files in other packages, it does+ #' |
|
49 | +6 |
- #' not work with `devtools`. Therefore, we redefine this method in each package+ #' Create a `teal_data_module` object and evaluate code on it with history tracking. |
|
50 | +7 |
- #' as needed. Thus, we do not export this method.+ #' |
|
51 | +8 |
- #'+ #' @details |
|
52 | +9 |
- #' @param files (`character`) vector of filenames.+ #' `teal_data_module` creates a `shiny` module to interactively supply or modify data in a `teal` application. |
|
53 | +10 |
- #'+ #' The module allows for running any code (creation _and_ some modification) after the app starts or reloads. |
|
54 | +11 |
- #' @return `NULL`, invisibly.+ #' The body of the server function will be run in the app rather than in the global environment. |
|
55 | +12 |
- #' @keywords internal+ #' This means it will be run every time the app starts, so use sparingly. |
|
56 | +13 |
- run_js_files <- function(files) {- |
- |
57 | -88x | -
- checkmate::assert_character(files, min.len = 1, any.missing = FALSE)- |
- |
58 | -88x | -
- lapply(files, function(file) {- |
- |
59 | -88x | -
- shinyjs::runjs(paste0(readLines(system.file("js", file, package = "teal", mustWork = TRUE)), collapse = "\n"))+ #' |
|
60 | +14 |
- })- |
- |
61 | -88x | -
- invisible(NULL)+ #' Pass this module instead of a `teal_data` object in a call to [init()]. |
|
62 | +15 |
- }+ #' Note that the server function must always return a `teal_data` object wrapped in a reactive expression. |
|
63 | +16 |
-
+ #' |
|
64 | +17 |
- #' Code to include `teal` `CSS` and `JavaScript` files+ #' See vignette `vignette("data-as-shiny-module", package = "teal")` for more details. |
|
65 | +18 |
#' |
|
66 | +19 |
- #' This is useful when you want to use the same `JavaScript` and `CSS` files that are+ #' @param ui (`function(id)`) |
|
67 | +20 |
- #' used with the `teal` application.+ #' `shiny` module UI function; must only take `id` argument |
|
68 | +21 |
- #' This is also useful for running standalone modules in `teal` with the correct+ #' @param server (`function(id)`) |
|
69 | +22 |
- #' styles.+ #' `shiny` module server function; must only take `id` argument; |
|
70 | +23 |
- #' Also initializes `shinyjs` so you can use it.+ #' must return reactive expression containing `teal_data` object |
|
71 | +24 |
- #'+ #' @param label (`character(1)`) Label of the module. |
|
72 | +25 |
- #' Simply add `include_teal_css_js()` as one of the UI elements.+ #' @param once (`logical(1)`) |
|
73 | +26 |
- #' @return A `shiny.tag.list`.+ #' If `TRUE`, the data module will be shown only once and will disappear after successful data loading. |
|
74 | +27 |
- #' @keywords internal+ #' App user will no longer be able to interact with this module anymore. |
|
75 | +28 |
- include_teal_css_js <- function() {+ #' If `FALSE`, the data module can be reused multiple times. |
|
76 | -! | +||
29 | +
- tagList(+ #' App user will be able to interact and change the data output from the module multiple times. |
||
77 | -! | +||
30 | +
- shinyjs::useShinyjs(),+ #' |
||
78 | -! | +||
31 | +
- include_css_files(),+ #' @return |
||
79 | +32 |
- # init.js is executed from the server+ #' `teal_data_module` returns a list of class `teal_data_module` containing two elements, `ui` and |
|
80 | -! | +||
33 | +
- include_js_files(except = "init.js"),+ #' `server` provided via arguments. |
||
81 | -! | +||
34 | +
- shinyjs::hidden(icon("fas fa-gear")), # add hidden icon to load font-awesome css for icons+ #' |
||
82 | +35 |
- )+ #' @examples |
|
83 | +36 |
- }+ #' tdm <- teal_data_module( |
1 | +37 |
- #' Create a `teal` module for previewing a report+ #' ui = function(id) { |
||
2 | +38 |
- #'+ #' ns <- NS(id) |
||
3 | +39 |
- #' @description `r lifecycle::badge("experimental")`+ #' actionButton(ns("submit"), label = "Load data") |
||
4 | +40 |
- #'+ #' }, |
||
5 | +41 |
- #' This function wraps [teal.reporter::reporter_previewer_ui()] and+ #' server = function(id) { |
||
6 | +42 |
- #' [teal.reporter::reporter_previewer_srv()] into a `teal_module` to be+ #' moduleServer(id, function(input, output, session) { |
||
7 | +43 |
- #' used in `teal` applications.+ #' eventReactive(input$submit, { |
||
8 | +44 |
- #'+ #' data <- within( |
||
9 | +45 |
- #' If you are creating a `teal` application using [init()] then this+ #' teal_data(), |
||
10 | +46 |
- #' module will be added to your application automatically if any of your `teal_modules`+ #' { |
||
11 | +47 |
- #' support report generation.+ #' dataset1 <- iris |
||
12 | +48 |
- #'+ #' dataset2 <- mtcars |
||
13 | +49 |
- #' @inheritParams teal_modules+ #' } |
||
14 | +50 |
- #' @param server_args (named `list`)+ #' ) |
||
15 | +51 |
- #' Arguments passed to [teal.reporter::reporter_previewer_srv()].+ #' |
||
16 | +52 |
- #'+ #' data |
||
17 | +53 |
- #' @return+ #' }) |
||
18 | +54 |
- #' `teal_module` (extended with `teal_module_previewer` class) containing the `teal.reporter` previewer functionality.+ #' }) |
||
19 | +55 |
- #'+ #' } |
||
20 | +56 |
- #' @export+ #' ) |
||
21 | +57 |
#' |
||
22 | +58 |
- reporter_previewer_module <- function(label = "Report previewer", server_args = list()) {+ #' @name teal_data_module |
||
23 | -7x | +|||
59 | +
- checkmate::assert_string(label)+ #' @seealso [`teal.data::teal_data-class`], [teal.code::qenv()] |
|||
24 | -5x | +|||
60 | +
- checkmate::assert_list(server_args, names = "named")+ #' |
|||
25 | -5x | +|||
61 | +
- checkmate::assert_true(all(names(server_args) %in% names(formals(teal.reporter::reporter_previewer_srv))))+ #' @export |
|||
26 | +62 |
-
+ teal_data_module <- function(ui, server, label = "data module", once = TRUE) { |
||
27 | -3x | -
- message("Initializing reporter_previewer_module")- |
- ||
28 | -+ | 63 | +33x |
-
+ checkmate::assert_function(ui, args = "id", nargs = 1) |
29 | -3x | +64 | +32x |
- srv <- function(id, reporter, ...) {+ checkmate::assert_function(server, args = "id", nargs = 1) |
30 | -! | +|||
65 | +30x |
- teal.reporter::reporter_previewer_srv(id, reporter, ...)+ checkmate::assert_string(label) |
||
31 | -+ | |||
66 | +30x |
- }+ checkmate::assert_flag(once) |
||
32 | -+ | |||
67 | +30x |
-
+ structure( |
||
33 | -3x | +68 | +30x |
- ui <- function(id, ...) {+ list( |
34 | -! | +|||
69 | +30x |
- teal.reporter::reporter_previewer_ui(id, ...)+ ui = ui, |
||
35 | -+ | |||
70 | +30x |
- }+ server = function(id) { |
||
36 | -+ | |||
71 | +23x |
-
+ data_out <- server(id) |
||
37 | -3x | +72 | +22x |
- module <- module(+ decorate_err_msg( |
38 | -3x | +73 | +22x |
- label = "temporary label",+ assert_reactive(data_out), |
39 | -3x | +74 | +22x |
- server = srv, ui = ui,+ pre = sprintf("From: 'teal_data_module()':\nA 'teal_data_module' with \"%s\" label:", label), |
40 | -3x | +75 | +22x |
- server_args = server_args, ui_args = list(), datanames = NULL+ post = "Please make sure that this module returns a 'reactive` object containing 'teal_data' class of object." # nolint: line_length_linter. |
41 | +76 |
- )+ ) |
||
42 | +77 |
- # Module is created with a placeholder label and the label is changed later.+ } |
||
43 | +78 |
- # This is to prevent another module being labeled "Report previewer".+ ), |
||
44 | -3x | +79 | +30x |
- class(module) <- c(class(module), "teal_module_previewer")+ label = label, |
45 | -3x | +80 | +30x |
- module$label <- label+ class = "teal_data_module", |
46 | -3x | +81 | +30x |
- attr(module, "teal_bookmarkable") <- TRUE+ once = once |
47 | -3x | +|||
82 | +
- module+ ) |
|||
48 | +83 |
}@@ -49241,56 +49464,56 @@ teal coverage - 60.12% |
1 |
- setOldClass("teal_data_module")+ #' UI and server modules of `teal` |
||
2 |
-
+ #' |
||
3 |
- #' Evaluate code on `teal_data_module`+ #' @description `r lifecycle::badge("deprecated")` |
||
4 |
- #'+ #' Please use [`module_teal`] instead. |
||
5 |
- #' @details+ #' |
||
6 |
- #' `eval_code` evaluates given code in the environment of the `teal_data` object created by the `teal_data_module`.+ #' @inheritParams ui_teal |
||
7 |
- #' The code is added to the `@code` slot of the `teal_data`.+ #' @inheritParams srv_teal |
||
9 |
- #' @param object (`teal_data_module`)+ #' @return |
||
10 |
- #' @inheritParams teal.code::eval_code+ #' Returns a `reactive` expression containing a `teal_data` object when data is loaded or `NULL` when it is not. |
||
11 |
- #'+ #' @name module_teal_with_splash |
||
12 |
- #' @return+ #' |
||
13 |
- #' `eval_code` returns a `teal_data_module` object with a delayed evaluation of `code` when the module is run.+ NULL |
||
14 |
- #'+ |
||
15 |
- #' @examples+ #' @export |
||
16 |
- #' eval_code(tdm, "dataset1 <- subset(dataset1, Species == 'virginica')")+ #' @rdname module_teal_with_splash |
||
17 |
- #'+ ui_teal_with_splash <- function(id, |
||
18 |
- #' @include teal_data_module.R+ data, |
||
19 |
- #' @name eval_code+ title = build_app_title(), |
||
20 |
- #' @rdname teal_data_module+ header = tags$p(), |
||
21 |
- #' @aliases eval_code,teal_data_module,character-method+ footer = tags$p()) { |
||
22 | -+ | ! |
- #' @aliases eval_code,teal_data_module,language-method+ lifecycle::deprecate_soft( |
23 | -+ | ! |
- #' @aliases eval_code,teal_data_module,expression-method+ when = "0.16", |
24 | -+ | ! |
- #'+ what = "ui_teal_with_splash()", |
25 | -+ | ! |
- #' @importFrom methods setMethod+ details = "Deprecated, please use `ui_teal` instead" |
26 |
- #' @importMethodsFrom teal.code eval_code+ ) |
||
27 | -+ | ! |
- #'+ ui_teal(id = id, title = title, header = header, footer = footer) |
28 |
- setMethod("eval_code", signature = c("teal_data_module", "character"), function(object, code) {- |
- ||
29 | -9x | -
- 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 | -
- data <- object$server("mutate_inner")- |
- |
37 | -6x | -
- td <- eventReactive(data(),- |
- |
38 | -- |
- {- |
- |
39 | -6x | -
- if (inherits(data(), c("teal_data", "qenv.error"))) {- |
- |
40 | -4x | -
- eval_code(data(), code)- |
- |
41 | -- |
- } else {- |
- |
42 | -2x | -
- data()- |
- |
43 | -- |
- }- |
- |
44 | -- |
- },- |
- |
45 | -6x | -
- ignoreNULL = FALSE- |
- |
46 | -- |
- )- |
- |
47 | -6x | -
- td- |
- |
48 | -- |
- })+ } |
|
49 | +29 |
- }+ |
|
50 | +30 |
- )+ #' @export |
|
51 | +31 |
- })+ #' @rdname module_teal_with_splash |
|
52 | +32 |
-
+ srv_teal_with_splash <- function(id, data, modules, filter = teal_slices()) { |
|
53 | -+ | ||
33 | +! |
- setMethod("eval_code", signature = c("teal_data_module", "language"), function(object, code) {+ lifecycle::deprecate_soft( |
|
54 | -1x | +||
34 | +! |
- eval_code(object, code = paste(lang2calls(code), collapse = "\n"))- |
- |
55 | -+ | ||
35 | +! |
- })+ what = "srv_teal_with_splash()", |
|
56 | -+ | ||
36 | +! |
-
+ details = "Deprecated, please use `srv_teal` instead" |
|
57 | +37 |
- setMethod("eval_code", signature = c("teal_data_module", "expression"), function(object, code) {+ ) |
|
58 | -2x | +||
38 | +! |
- eval_code(object, code = paste(lang2calls(code), collapse = "\n"))+ srv_teal(id = id, data = data, modules = modules, filter = filter) |
|
59 | +39 |
- })+ } |
1 |
- #' Store and restore `teal_slices` object+ #' Landing popup module |
||
3 |
- #' Functions that write a `teal_slices` object to a file in the `JSON` format,+ #' @description Creates a landing welcome popup for `teal` applications. |
||
4 |
- #' and also restore the object from disk.+ #' |
||
5 |
- #'+ #' This module is used to display a popup dialog when the application starts. |
||
6 |
- #' Date and date time objects are stored in the following formats:+ #' The dialog blocks access to the application and must be closed with a button before the application can be viewed. |
||
8 |
- #' - `Date` class is converted to the `"ISO8601"` standard (`YYYY-MM-DD`).+ #' @param label (`character(1)`) Label of the module. |
||
9 |
- #' - `POSIX*t` classes are converted to character by using+ #' @param title (`character(1)`) Text to be displayed as popup title. |
||
10 |
- #' `format.POSIX*t(usetz = TRUE, tz = "UTC")` (`YYYY-MM-DD HH:MM:SS UTC`, where+ #' @param content (`character(1)`, `shiny.tag` or `shiny.tag.list`) with the content of the popup. |
||
11 |
- #' `UTC` is the `Coordinated Universal Time` timezone short-code).+ #' Passed to `...` of `shiny::modalDialog`. See examples. |
||
12 |
- #'+ #' @param buttons (`shiny.tag` or `shiny.tag.list`) Typically a `modalButton` or `actionButton`. See examples. |
||
13 |
- #' This format is assumed during `slices_restore`. All `POSIX*t` objects in+ #' |
||
14 |
- #' `selected` or `choices` fields of `teal_slice` objects are always printed in+ #' @return A `teal_module` (extended with `teal_landing_module` class) to be used in `teal` applications. |
||
15 |
- #' `UTC` timezone as well.+ #' |
||
16 |
- #'+ #' @examples |
||
17 |
- #' @param tss (`teal_slices`) object to be stored.+ #' app1 <- init( |
||
18 |
- #' @param file (`character(1)`) file path where `teal_slices` object will be+ #' data = teal_data(iris = iris), |
||
19 |
- #' saved and restored. The file extension should be `".json"`.+ #' modules = modules( |
||
20 |
- #'+ #' example_module() |
||
21 |
- #' @return `slices_store` returns `NULL`, invisibly.+ #' ), |
||
22 |
- #'+ #' landing_popup = landing_popup_module( |
||
23 |
- #' @seealso [teal_slices()]+ #' content = "A place for the welcome message or a disclaimer statement.", |
||
24 |
- #'+ #' buttons = modalButton("Proceed") |
||
25 |
- #' @keywords internal+ #' ) |
||
26 |
- #'+ #' ) |
||
27 |
- slices_store <- function(tss, file) {+ #' if (interactive()) { |
||
28 | -9x | +
- checkmate::assert_class(tss, "teal_slices")+ #' shinyApp(app1$ui, app1$server) |
|
29 | -9x | +
- checkmate::assert_path_for_output(file, overwrite = TRUE, extension = "json")+ #' } |
|
30 |
-
+ #' |
||
31 | -9x | +
- cat(format(tss, trim_lines = FALSE), "\n", file = file)+ #' app2 <- init( |
|
32 |
- }+ #' data = teal_data(iris = iris), |
||
33 |
-
+ #' modules = modules( |
||
34 |
- #' @rdname slices_store+ #' example_module() |
||
35 |
- #' @return `slices_restore` returns a `teal_slices` object restored from the file.+ #' ), |
||
36 |
- #' @keywords internal+ #' landing_popup = landing_popup_module( |
||
37 |
- slices_restore <- function(file) {- |
- ||
38 | -9x | -
- checkmate::assert_file_exists(file, access = "r", extension = "json")+ #' title = "Welcome", |
|
39 | +38 | - - | -|
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$")+ #' content = tags$b( |
|
48 | +39 | - - | -|
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")+ #' "A place for the welcome message or a disclaimer statement.", |
|
54 | +40 |
- } else {- |
- |
55 | -3x | -
- slice[[field]]+ #' style = "color: red;" |
|
56 | +41 |
- }+ #' ), |
|
57 | +42 |
- } else {- |
- |
58 | -3x | -
- slice[[field]] <- character(0)+ #' buttons = tagList( |
|
59 | +43 |
- }+ #' modalButton("Proceed"), |
|
60 | +44 |
- }+ #' actionButton("read", "Read more", |
|
61 | +45 |
- }- |
- |
62 | -9x | -
- slice+ #' onclick = "window.open('http://google.com', '_blank')" |
|
63 | +46 |
- })+ #' ), |
|
64 | +47 | - - | -|
65 | -9x | -
- tss_elements <- lapply(tss_json$slices, as.teal_slice)+ #' actionButton("close", "Reject", onclick = "window.close()") |
|
66 | +48 | - - | -|
67 | -9x | -
- do.call(teal_slices, c(tss_elements, tss_json$attributes))+ #' ) |
|
68 | +49 |
- }+ #' ) |
1 | +50 |
- #' Show `R` code modal+ #' ) |
|
2 | +51 |
#' |
|
3 | +52 |
- #' @description `r lifecycle::badge("deprecated")`+ #' if (interactive()) { |
|
4 | +53 |
- #'+ #' shinyApp(app2$ui, app2$server) |
|
5 | +54 |
- #' Use the [shiny::showModal()] function to show the `R` code inside.+ #' } |
|
6 | +55 |
#' |
|
7 | -- |
- #' @param title (`character(1)`)- |
- |
8 | -- |
- #' Title of the modal, displayed in the first comment of the `R` code.- |
- |
9 | -- |
- #' @param rcode (`character`)- |
- |
10 | -- |
- #' vector with `R` code to show inside the modal.- |
- |
11 | +56 |
- #' @param session (`ShinySession`) optional+ #' @export |
|
12 | +57 |
- #' `shiny` session object, defaults to [shiny::getDefaultReactiveDomain()].+ landing_popup_module <- function(label = "Landing Popup", |
|
13 | +58 |
- #'+ title = NULL, |
|
14 | +59 |
- #' @references [shiny::showModal()]+ content = NULL, |
|
15 | +60 |
- #' @export+ buttons = modalButton("Accept")) { |
|
16 | -+ | ||
61 | +! |
- show_rcode_modal <- function(title = NULL, rcode, session = getDefaultReactiveDomain()) {+ checkmate::assert_string(label) |
|
17 | +62 | ! |
- lifecycle::deprecate_soft(+ checkmate::assert_string(title, null.ok = TRUE) |
18 | +63 | ! |
- when = "0.16",+ checkmate::assert_multi_class( |
19 | +64 | ! |
- what = "show_rcode_modal()",+ content, |
20 | +65 | ! |
- details = "This function will be removed in the next release."+ classes = c("character", "shiny.tag", "shiny.tag.list", "html"), null.ok = TRUE |
21 | +66 |
) |
|
67 | +! | +
+ checkmate::assert_multi_class(buttons, classes = c("shiny.tag", "shiny.tag.list"))+ |
+ |
22 | +68 | ||
23 | +69 | ! |
- rcode <- paste(rcode, collapse = "\n")+ message("Initializing landing_popup_module") |
24 | +70 | ||
25 | +71 | ! |
- ns <- session$ns+ module <- module( |
26 | +72 | ! |
- showModal(modalDialog(+ label = label, |
27 | +73 | ! |
- tagList(+ server = function(id) { |
28 | +74 | ! |
- tags$div(+ moduleServer(id, function(input, output, session) { |
29 | +75 | ! |
- actionButton(ns("copyRCode"), "Copy to Clipboard", `data-clipboard-target` = paste0("#", ns("r_code"))),+ showModal( |
30 | +76 | ! |
- modalButton("Dismiss"),+ modalDialog( |
31 | +77 | ! |
- style = "mb-4"- |
-
32 | -- |
- ),+ id = "landingpopup", |
|
33 | +78 | ! |
- tags$div(tags$pre(id = ns("r_code"), rcode)),+ title = title, |
34 | -+ | ||
79 | +! |
- ),+ content, |
|
35 | +80 | ! |
- title = title,+ footer = buttons |
36 | -! | +||
81 | +
- footer = tagList(+ ) |
||
37 | -! | +||
82 | +
- actionButton(ns("copyRCode"), "Copy to Clipboard", `data-clipboard-target` = paste0("#", ns("r_code"))),+ ) |
||
38 | -! | +||
83 | +
- modalButton("Dismiss")+ }) |
||
39 | +84 |
- ),+ } |
|
40 | -! | +||
85 | +
- size = "l",+ ) |
||
41 | +86 | ! |
- easyClose = TRUE+ class(module) <- c("teal_module_landing", class(module)) |
42 | -+ | ||
87 | +! |
- ))+ module |
|
43 | +88 |
} |