Debian Codegraph @

inst/examples-shiny/brand.yml/app.R

raw
1 rlang::check_installed("shiny", version = "1.8.1")
2 rlang::check_installed("bslib", version = "0.8.0.9000")
3 rlang::check_installed("future")
4 rlang::check_installed("ggplot2")
5 rlang::check_installed("markdown")
6
7 library(shiny)
8 library(bslib)
9 library(ggplot2)
10
11 library(future)
12 plan(multisession)
13
14 options(
15 bslib.color_contrast_warnings = FALSE
16 # shiny.autoreload.pattern = "_brand[.]yml|app[.]R|[.]s?css" ## TODO: Enable after fixing autoreload
17 )
18
19 theme_brand <- bs_theme()
20
21 brand <- attr(theme_brand, "brand")
22 BRAND_PATH <- brand$path %||% "_brand.yml"
23
24 theme_set(theme_minimal())
25
26 if (requireNamespace("thematic", quietly = TRUE)) {
27 base_font <- bslib:::brand_pluck(brand, "typography", "base", "family")
28 if (!is.null(base_font)) {
29 # TODO: Update plot fonts dynamically
30 thematic::thematic_shiny(font = base_font)
31 } else {
32 thematic::thematic_shiny()
33 }
34 }
35
36 use_download_button <- FALSE
37
38 # ---- For hosted demo, delete if local ----
39 is_app_hosted <-
40 Sys.getenv("R_CONFIG_ACTIVE") %in%
41 c("shinylive", "shinyapps", "rsconnect", "rstudio_cloud")
42 is_app_packaged <-
43 getwd() == system.file("examples-shiny/brand.yml", package = "bslib")
44 use_download_button <- is_app_hosted || is_app_packaged
45
46 if (bslib:::brand_has(brand, "typography", "fonts")) {
47 tryCatch(
48 {
49 if (brand$typography$fonts[[2]]$files[[1]]$path == "Monda.ttf") {
50 if (!file.exists("Monda.ttf")) {
51 download.file(
52 "https://github.com/google/fonts/raw/48db77e32954f6f5e65a7122ecbe8a2093c4f5d7/ofl/monda/Monda%5Bwght%5D.ttf",
53 "Monda.ttf"
54 )
55 download.file(
56 "https://github.com/google/fonts/raw/48db77e32954f6f5e65a7122ecbe8a2093c4f5d7/ofl/monda/OFL.txt",
57 "Monda-OFL.txt"
58 )
59 }
60 }
61 },
62 error = function(err) {}
63 )
64 }
65 # ---- For hosted demo, delete if local ----
66
67 ui <- page_navbar(
68 theme = bs_add_rules(theme_brand, sass::sass_file("_colors.scss")),
69 title = tagList(
70 uiOutput("brand_icon", inline = TRUE),
71 uiOutput("brand_name", inline = TRUE)
72 ),
73 window_title = "brand.yml Demo",
74 fillable = TRUE,
75
76 sidebar = sidebar(
77 id = "sidebar_editor",
78 position = "right",
79 open = "closed",
80 width = "40%",
81 bg = "var(--bs-dark)",
82 fg = "var(--bs-light)",
83 `data-bs-theme` = "dark",
84
85 card(
86 card_header(
87 class = "text-bg-secondary hstack",
88 div("Edit", code("brand.yml")),
89 div(
90 class = "ms-auto",
91 tooltip(
92 tags$a(
93 class = "btn btn-link p-0",
94 href = "https://posit-dev.github.io/brand-yml/brand/",
95 target = "_blank",
96 bsicons::bs_icon(
97 "question-square-fill",
98 title = "About brand.yml",
99 size = "1.25rem"
100 )
101 ),
102 "About brand.yml"
103 )
104 )
105 ),
106 htmltools::tagAppendAttributes(
107 textAreaInput(
108 "txt_brand_yml",
109 label = NULL,
110 value = if (!is.null(brand)) {
111 paste(readLines(brand$path, warn = FALSE), collapse = "\n")
112 },
113 width = "100%",
114 height = "80%",
115 rows = 20
116 ),
117 class = "font-monospace",
118 .cssSelector = "textarea"
119 ),
120 card_body(
121 padding = 0,
122 div(
123 id = "editor_brand_yml",
124 style = "overflow: auto;",
125 as_fill_item()
126 )
127 )
128 ),
129
130 tags$script(
131 type = "module",
132 HTML(
133 '
134 import { basicEditor } from "https://esm.sh/[email protected]/setups";
135 import "https://esm.sh/[email protected]/prism/languages/yaml";
136
137 const shinyInput = document.getElementById("txt_brand_yml");
138
139 function initBrandEditor() {
140 if (typeof Shiny.setInputValue !== "function") {
141 setTimeout(initBrandEditor, 100);
142 return;
143 }
144 window.brandEditor = basicEditor(
145 "#editor_brand_yml",
146 {
147 language: "yml",
148 theme: "github-dark",
149 value: shinyInput.value,
150 onUpdate: (value) => {
151 Shiny.setInputValue("txt_brand_yml", value);
152 },
153 },
154 () => shinyInput.parentElement.parentElement.remove()
155 );
156 }
157
158 initBrandEditor();
159 '
160 )
161 ),
162
163 tags$style(
164 HTML(
165 '
166 .bslib-sidebar-layout .sidebar-title { margin-bottom: 0 }
167 #sidebar_editor .sidebar-content { height: max(600px, 100%) }'
168 )
169 ),
170
171 if (use_download_button) {
172 shiny::downloadButton(
173 "download",
174 label = span(
175 "Download",
176 code("_brand.yml", style = "color: currentColor"),
177 "file"
178 ),
179 class = "btn-outline-light"
180 )
181 } else {
182 actionButton(
183 "save",
184 label = span(
185 "Save",
186 code("_brand.yml", style = "color: currentColor"),
187 "file"
188 ),
189 class = "btn-outline-light"
190 )
191 }
192 ),
193
194 nav_panel(
195 "Input Output Demo",
196 value = "dashboard",
197 layout_sidebar(
198 sidebar = sidebar(
199 sliderInput("slider1", "Numeric Slider Input", 0, 11, 11),
200 numericInput("numeric1", "Numeric Input Widget", 30),
201 dateInput("date1", "Date Input Component", value = "2024-01-01"),
202 input_switch("switch1", "Binary Switch Input", value = TRUE),
203 radioButtons(
204 "radio1",
205 "Radio Button Group",
206 choices = c("Option A", "Option B", "Option C", "Option D")
207 ),
208 actionButton("action1", "Action Button")
209 ),
210 shiny::useBusyIndicators(),
211 layout_column_wrap(
212 value_box(
213 title = "Metric 1",
214 value = "100",
215 theme = "primary",
216 id = "value_box_one"
217 ),
218 value_box(
219 title = "Metric 2",
220 value = "200",
221 theme = "secondary",
222 id = "value_box_two"
223 ),
224 value_box(
225 title = "Metric 3",
226 value = "300",
227 theme = "info",
228 id = "value_box_three"
229 )
230 ),
231 card(
232 card_header("Plot Output"),
233 plotOutput("out_plot")
234 ),
235 card(
236 card_header("Text Output"),
237 verbatimTextOutput("out_text")
238 )
239 )
240 ),
241
242 nav_panel(
243 "Widget Gallery",
244 layout_column_wrap(
245 width = 300,
246 heights_equal = "row",
247 card(
248 card_header("Button Variants"),
249 actionButton("btn_default", "Default"),
250 actionButton("btn_primary", "Primary", class = "btn-primary"),
251 actionButton("btn_secondary", "Secondary", class = "btn-secondary"),
252 actionButton("btn_success", "Success", class = "btn-success"),
253 actionButton("btn_danger", "Danger", class = "btn-danger"),
254 actionButton("btn_warning", "Warning", class = "btn-warning"),
255 actionButton("btn_info", "Info", class = "btn-info")
256 ),
257 card(
258 card_header("Radio Button Examples"),
259 radioButtons(
260 "radio2",
261 "Standard Radio Group",
262 choices = c("Selection 1", "Selection 2", "Selection 3")
263 ),
264 radioButtons(
265 "radio3",
266 "Inline Radio Group",
267 choices = c("Option 1", "Option 2", "Option 3"),
268 inline = TRUE
269 )
270 ),
271 card(
272 card_header("Checkbox Examples"),
273 checkboxGroupInput(
274 "check1",
275 "Standard Checkbox Group",
276 choices = c("Item 1", "Item 2", "Item 3")
277 ),
278 checkboxGroupInput(
279 "check2",
280 "Inline Checkbox Group",
281 choices = c("Choice A", "Choice B", "Choice C"),
282 inline = TRUE
283 )
284 ),
285 card(
286 card_header("Select Input Widgets"),
287 selectizeInput(
288 "select1",
289 "Selectize Input",
290 choices = c("Selection A", "Selection B", "Selection C")
291 ),
292 selectInput(
293 "select2",
294 "Multiple Select Input",
295 choices = c("Item X", "Item Y", "Item Z"),
296 multiple = TRUE
297 )
298 ),
299 card(
300 card_header("Text Input Widgets"),
301 textInput("text1", "Text Input"),
302 textAreaInput(
303 "textarea1",
304 "Text Area Input",
305 value = "Default text content for the text area widget"
306 ),
307 passwordInput("password1", "Password Input")
308 )
309 )
310 ),
311
312 nav_panel(
313 "Colors",
314 div(
315 class = "container-sm overflow-y-auto",
316 uiOutput("ui_colors")
317 )
318 ),
319
320 nav_panel(
321 "Documentation",
322 div(
323 class = "container-sm overflow-y-auto",
324 if (FALSE) library(markdown), # for shinyapps.io
325 includeMarkdown("documentation.md")
326 )
327 ),
328
329 nav_spacer(),
330 nav_item(input_dark_mode(id = "color_mode")),
331 nav_item(
332 actionLink(
333 "show_editor",
334 bsicons::bs_icon(
335 "pencil-fill",
336 size = "1rem",
337 title = "Show/hide editor"
338 ),
339 class = "nav-link"
340 )
341 ),
342 )
343
344 errors <- rlang::new_environment()
345
346 error_notification <- function(context) {
347 function(err) {
348 time <- as.character(Sys.time())
349
350 msg <- conditionMessage(err)
351 # Strip ANSI color sequences from error messages
352 msg <- gsub(
353 pattern = "\u001b\\[.*?m",
354 replacement = "",
355 msg
356 )
357 # Wrap at 40 characters
358 msg <- paste(strwrap(msg, width = 60), collapse = "\n")
359
360 err_id <- rlang::hash(list(time, msg))
361 assign(err_id, list(message = msg, context = context), envir = errors)
362
363 showNotification(
364 markdown(context),
365 action = tags$button(
366 class = "btn btn-outline-danger pull-right",
367 onclick = sprintf(
368 "event.preventDefault(); Shiny.setInputValue('show_error', '%s')",
369 err_id
370 ),
371 "Show details"
372 ),
373 duration = 10,
374 type = "error",
375 id = err_id
376 )
377 }
378 }
379
380 server <- function(input, output, session) {
381 brand_yml_text <- debounce(reactive(input$txt_brand_yml), 1000)
382 brand_yml <- reactiveVal()
383
384 observeEvent(input$show_editor, sidebar_toggle("sidebar_editor"))
385
386 observeEvent(input$show_error, {
387 req(input$show_error)
388 err <- get0(input$show_error, errors)
389
390 if (is.null(err)) {
391 message("Could not find error with id ", input$show_error)
392 return()
393 }
394
395 removeNotification(input$show_error)
396 rm(list = input$show_error, envir = errors)
397
398 showModal(
399 modalDialog(
400 size = "l",
401 easyClose = TRUE,
402 markdown(err$context),
403 pre(err$message)
404 )
405 )
406 })
407
408 observeEvent(brand_yml_text(), {
409 req(brand_yml_text())
410
411 tryCatch(
412 {
413 b <- yaml::yaml.load(brand_yml_text())
414 b$path <- normalizePath(BRAND_PATH, mustWork = FALSE)
415 brand_yml(b)
416 },
417 error = error_notification(
418 "Could not parse `_brand.yml` file. Check for syntax errors."
419 )
420 )
421 })
422
423 observeEvent(brand_yml(), {
424 req(brand_yml())
425
426 tryCatch(
427 {
428 theme <- bs_theme(brand = brand_yml())
429 theme <- bs_add_rules(theme, sass::sass_file("_colors.scss"))
430 session$setCurrentTheme(theme)
431 },
432 error = error_notification(
433 "Could not compile branded theme. Please check your `_brand.yml` file."
434 )
435 )
436 })
437
438 output$brand_name <- renderUI({
439 brand_name <-
440 bslib:::brand_pluck(brand_yml(), "meta", "name", "short") %||%
441 bslib:::brand_pluck(brand_yml(), "meta", "name")
442
443 if (rlang::is_string(brand_name)) brand_name else "brand.yml Demo"
444 })
445
446 output$brand_icon <- renderUI({
447 brand <- brand_yml()
448
449 logo <-
450 bslib:::brand_pluck(brand, "logo", "small") %||%
451 bslib:::brand_pluck(brand, "logo")
452
453 req(rlang::is_string(logo))
454
455 logo_path <- file.path(dirname(BRAND_PATH), logo)
456 if (file.exists(logo_path)) {
457 img(
458 src = base64enc::dataURI(
459 file = logo_path,
460 mime = mime::guess_type(logo_path)
461 ),
462 height = 30
463 )
464 }
465 })
466
467 observeEvent(input$save, {
468 validate(
469 need(input$txt_brand_yml, "_brand.yml file contents cannot be empty.")
470 )
471
472 tryCatch(
473 {
474 writeLines(input$txt_brand_yml, BRAND_PATH)
475 showNotification(markdown("Saved `_brand.yml`!"))
476 },
477 error = error_notification("Could not save `_brand.yml`.")
478 )
479 })
480
481 output$download <- downloadHandler(
482 filename = "_brand.yml",
483 content = function(file) {
484 validate(
485 need(input$txt_brand_yml, "_brand.yml file contents cannot be empty.")
486 )
487 writeLines(input$txt_brand_yml, file)
488 }
489 )
490
491 PlotTask <- ExtendedTask$new(function(x_max, y_factor) {
492 x <- seq(0, x_max, length.out = 100)
493 y <- sin(x) * y_factor
494
495 future({
496 Sys.sleep(3)
497
498 df <- data.frame(x = x, y = y)
499
500 ggplot(df, aes(x = x, y = y)) +
501 geom_col(width = 1, position = "identity") +
502 labs(title = "Sine Wave Output", x = "", y = "")
503 })
504 })
505
506 observe({
507 x_max <- debounce(reactive(input$numeric1), 500)()
508 y_factor <- debounce(reactive(input$slider1), 500)()
509
510 PlotTask$invoke(x_max = x_max, y_factor = y_factor)
511 })
512
513 output$out_plot <- renderPlot({
514 PlotTask$result()
515 })
516
517 output$out_text <- renderText({
518 "example_function <- function() {\n return(\"Function output text\")\n}"
519 })
520
521 output$ui_colors <- renderUI({
522 bootstrap_colors <- c(
523 "blue",
524 "indigo",
525 "purple",
526 "pink",
527 "red",
528 "orange",
529 "yellow",
530 "green",
531 "teal",
532 "cyan"
533 )
534 colors <- c("gray", bootstrap_colors)
535
536 tagList(
537 layout_columns(
538 col_widths = 3,
539 class = "font-monospace",
540 !!!lapply(
541 c(
542 "primary",
543 "secondary",
544 "dark",
545 "light",
546 "info",
547 "success",
548 "warning",
549 "danger"
550 ),
551 function(color) {
552 div(
553 color,
554 class = paste0("p-3 mb-2 position-relative text-bg-", color)
555 )
556 }
557 )
558 ),
559 layout_columns(
560 col_widths = 3,
561 class = "font-monospace",
562 !!!lapply(
563 c("black", "white", "foreground", "background"),
564 function(color) {
565 div(
566 color,
567 class = paste0("p-3 mb-2 position-relative bd-", color)
568 )
569 }
570 )
571 ),
572 layout_column_wrap(
573 width = 200,
574 !!!lapply(colors, function(color) {
575 if (!color %in% c("white", "black")) {
576 div(
577 class = "mb-3",
578 div(
579 color,
580 class = paste0("p-3 mb-2 position-relative bd-", color, "-500")
581 ),
582 lapply(seq(100, 900, 100), function(r) {
583 div(
584 paste0(color, "-", r),
585 class = paste0("p-3 bd-", color, "-", r)
586 )
587 })
588 )
589 }
590 })
591 )
592 )
593 })
594 }
595
596 shinyApp(ui, server)