-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathresources.qmd
1335 lines (1130 loc) · 41.5 KB
/
resources.qmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Resources {#sec-resources}
```{r}
#| eval: true
#| echo: false
#| include: false
source("_common.R")
```
```{r}
#| label: co_box_tldr
#| echo: false
#| results: asis
#| eval: true
co_box(
color = "b",
look = "default", hsize = "1.05", size = "1.0",
header = "TLDR: Adding external files/resources", fold = TRUE,
contents = "
<br>
- The **`inst/`** folder is used to store files/resources that are available when your package is installed (i.e., this folder *'will be copied recursively to the installation directory.'*)\n
- **`system.file()`** is the 'file path accessor' function we can use to locate files in the installed version of our app-package\n
- Use **`addResourcePath()`** with **`system.file()`** and **`inst/`** to include external files in your application.\n
**Workflow:** for a file located in `inst/www/file.png`:\n
\`\`\`r
# add path to app
addResourcePath('www', system.file('www', package = 'pkg'))
# use path without 'inst/' prefix in UI
img(src = 'www/shiny.png')
\`\`\`
"
)
```
---
In this chapter, we'll cover how to include external resources (i.e., the images, CSS styling, JavaScript files, etc. previously served from the `www/` folder) in an app-package.
```{r}
#| label: shinypak_apps
#| echo: false
#| results: asis
#| eval: true
shinypak_apps(regex = "09", branch = "09.1_www")
```
When we launch our app, we see the Shiny logo (`shiny.png`) in the `www/` folder is not being loaded into the UI:
```{r}
#| eval: false
#| code-fold: false
launch_app(run = 'p')
```
Shiny's internal functions previously automatically handled serving the contents of `www/`.[^load-support] Now that we’ve converted our application into a package, we’ll need to tell the application where to find these resources explicitly.[^external-common-problem]
![`www/shiny.png` is not visible when we launch the app](images/external_initial_launch_app.png){width='100%' fig-align='center'}
[^load-support]: "*The `www/` folder is a special one for Shiny. Resources your app may link to, such as images—or in this case, scripts—are placed in the `www/` folder. Shiny then knows to make these files available for access from the web browser.*" - [Shiny documentation](https://shiny.posit.co/r/articles/build/css/#other-methods)
[^external-common-problem]: This is a common problem developers encounter when converting shiny app into app-packages. See [this popular thread](https://community.rstudio.com/t/shiny-app-as-a-package-directory-structure-and-www-folder/135323/8) on Posit Community.
## Package files {.unnumbered}
While developing, we get used to accessing and interacting with our package files from the **Files** pane or **Explorer** window:
:::{.panel-tabset}
### RStudio ![](images/rstudio-icon.png){height=20}
!['Source' files for `sap` in **Files** pane](images/external_files_pane.png){width='80%'}
### Positron ![](images/positron.png){height=20}
!['Source' files for `sap` in **Explorer** window](images/external_positron_explorer_pane.png){width='80%'}
:::
However, as noted in the [data](data.qmd) chapter, the aren't the files in our *installed* package. We can use `system.file()` and `fs::dir_tree()` to print a folder tree of our *installed* package files:
::: {layout="[50, 50]"}
::: {style="font-size: 0.90em;"}
```{verbatim}
sap/
├── DESCRIPTION
├── NAMESPACE
├── R
│ ├── data.R
│ ├── display_type.R
│ ├── mod_scatter_display.R
│ ├── mod_var_input.R
│ ├── launch_app.R
│ ├── movies_server.R
│ ├── movies_ui.R
│ └── scatter_plot.R
├── README.md
├── app.R
├── data
│ ├── movies.RData
│ └── movies.rda
├── inst
│ └── extdata
│ └── movies.fst
├── man
│ ├── display_type.Rd
│ ├── mod_scatter_display_server.Rd
│ ├── mod_scatter_display_ui.Rd
│ ├── mod_var_input_server.Rd
│ ├── mod_var_input_ui.Rd
│ ├── movies.Rd
│ ├── launch_app.Rd
│ ├── movies_server.Rd
│ ├── movies_ui.Rd
│ └── scatter_plot.Rd
├── sap.Rproj
└── www
└── shiny.png
```
:::
::: {style="font-size: 0.90em;"}
```{verbatim}
sap/
├── DESCRIPTION # <1>
├── INDEX
├── Meta # <2>
│ ├── Rd.rds
│ ├── data.rds
│ ├── features.rds
│ ├── hsearch.rds
│ ├── links.rds
│ ├── nsInfo.rds
│ └── package.rds # <2>
├── NAMESPACE # <3>
├── R # <4>
│ ├── sap
│ ├── sap.rdb
│ └── sap.rdx # <4>
├── data # <5>
│ ├── Rdata.rdb
│ ├── Rdata.rds
│ └── Rdata.rdx # <5>
├── extdata # <6>
│ └── movies.fst
├── help # <7>
│ ├── AnIndex
│ ├── aliases.rds
│ ├── sap.rdb
│ ├── sap.rdx
│ └── paths.rds # <7>
└── html # <8>
├── 00Index.html
└── R.css # <8>
```
1. `DESCRIPTION` is in *both* source and installed versions, and format remains unchanged.
2. Metadata files, such as `data.rds` and `package.rds`, are created in the `Meta/` directory
3. `NAMESPACE` is in *both* source and installed versions, and format remains unchanged.
4. R code in the `R/` directory is byte-compiled for improved performance, stored in `.rdb` and `.rdx` files.
5. Datasets in the `data/` directory are serialized into a lazyload database and stored as `.rdb` and `.rdx` files in the `R/` directory.
6. The `extdata/` folder is in *both* source and installed versions, and the `movies.fst` file remains unchanged.
7. `.Rd` files are processed into binary help files
8. HTML and styling for help index
:::
:::
Very few of the source folders and files we’ve been working with remain in the installed version of our package. An exception is the `movies.fst` file (stored in `inst/extdata/`). Hopefully seeing these two folder trees side-by-side demystifies what `devtools::install()` does.
When we want to add non-R package files to our app (like the `shiny.png` logo), we store these files in the `inst/`folder and access them with `system.file()`.[^inst-r-pkgs]
[^inst-r-pkgs]: Read more about sub-directories to avoid in `inst/` in [R Packages, 2ed](https://r-pkgs.org/misc.html#sec-misc-inst).
> "*The contents of the `inst/` subdirectory will be copied recursively to the installation directory. Subdirectories of `inst/` should not interfere with those used by R (currently, `R/`, `data/`, `demo/`, `exec/`, `libs/`, `man/`, `help/`, `html/` and `Meta/`, and earlier versions used `latex/`, `R-ex/`).*" - [Writing R extensions, Package subdirectories](https://cran.r-project.org/doc/manuals/r-release/R-exts.html#Package-subdirectories)
```{r}
#| label: co_box_install
#| echo: false
#| results: asis
#| eval: true
#| include: true
co_box(
color = "b", fold = TRUE,
look = "default", hsize = "1.15", size = "1.10",
header = "Other Uses of the `inst/` folder",
contents = "
I found exploring the structure of the `inst/` folder in other packages incredibly helpful in understanding how to use this directory for package development. For example, the `inst/examples/` folder in the [`shiny` package](https://github.com/rstudio/shiny) holds a variety of Shiny apps:
\`\`\` sh
/path/to/install/Library/R/x86_64/4.2/library/shiny/examples/
├── 01_hello
│ ├── DESCRIPTION
│ ├── Readme.md
│ └── app.R
├── 02_text
│ ├── DESCRIPTION
│ ├── Readme.md
│ └── app.R
├── 03_reactivity
│ ├── DESCRIPTION
│ ├── Readme.md
│ └── app.R
├── 04_mpg
│ ├── DESCRIPTION
│ ├── Readme.md
│ └── app.R
├── 05_sliders
│ ├── DESCRIPTION
│ ├── Readme.md
│ └── app.R
├── 06_tabsets
│ ├── DESCRIPTION
│ ├── Readme.md
│ └── app.R
├── 07_widgets
│ ├── DESCRIPTION
│ ├── Readme.md
│ └── app.R
├── 09_upload
│ ├── DESCRIPTION
│ ├── Readme.md
│ └── app.R
├── 10_download
│ ├── DESCRIPTION
│ ├── Readme.md
│ └── app.R
└── 11_timer
├── DESCRIPTION
├── Readme.md
└── app.R
\`\`\`
These files are used in [`shiny::runExample()`](https://github.com/rstudio/shiny/blob/9a35b01e23fe9e95e69aeb3624554b58c7a2b74f/R/runapp.R#L477)):
\`\`\` r
shiny::runExample(example = '11_timer')
\`\`\`
")
```
## Image files {#sec-resources-image-files}
To include the contents of `www/` in our app-package, we’ll need to move `www/` into `inst/`, and then access its contents with `system.file()`.[^inst-view]
[^inst-view]: The key takeaway here is that the `inst/` subfolders and files are available *unchanged* in the installed version (with the `inst/` folder omitted.).
### [`system.file()`]{style="font-size: 0.95em;"}
We used `system.file()` in the [Data chapter](data.qmd) (see @sec-data-system-file) to access the `movies.fst` file in `inst/extdata/`. `system.file()` gives us access to the package files _on installation_ (i.e., the files we saw in the folder tree above).
```{r}
#| eval: false
#| code-fold: show
#| code-summary: 'system.file() is accessing movies.fst from the installed location'
fst::read_fst(
path = system.file("extdata/", "movies.fst",
package = "sap")
)
```
In essence, `movies.fst` has ‘source’ package and ‘installed’ locations.
#### Source package files {.unnumbered}
```{bash}
#| eval: false
#| code-fold: false
inst/ # <1>
└── extdata/
└── movies.fst # <1>
```
1. What we see
#### Installed package files {.unnumbered}
```{bash}
#| eval: false
#| code-fold: false
└── extdata/ # <1>
└── movies.fst # <1>
```
1. What R sees
### [`addResourcePath()`]{style="font-size: 0.95em;"} {#sec-resources-add-resource-path}
The `addResourcePath()` function will add a “*directory of static resources to Shiny’s web server.*”[^add-resource-path-4] In `sap`, we want to add the `www` directory, which includes the `shiny.png` file.
[^add-resource-path-4]: You can read more about adding external resources in the [documentation for `addResourcePath()`](https://shiny.posit.co/r/reference/shiny/latest/resourcepaths).
:::{layout="[10,-1, 10]" layout-valign="top"}
#### [Current `www` location]{style="font-size: 0.95em;"} {.unnumbered}
``` sh
├── inst
│ └── extdata
│ └── movies.fst
└── www
└── shiny.png
```
#### [New `www` location]{style="font-size: 0.95em;"} {.unnumbered}
``` sh
inst/
├── extdata/
│ └── movies.fst
└── www/
└── shiny.png
```
:::
In `R/movies_ui.R`, we’ll include the `addResourcePath()` at the top of the `tagList()` and reference the image in `img()` using only the subfolder in the path:
```{r}
#| eval: false
#| code-fold: show
#| code-summary: 'show/hide movies_ui()'
movies_ui <- function() {
addResourcePath(
prefix = "www", # <1>
directoryPath = system.file("www", package = "sap") # <2>
)
tagList(
bslib::page_fillable(
h1("Movie Reviews"),
bslib::layout_sidebar(
sidebar =
bslib::sidebar(
title = tags$h4("Sidebar inputs"),
img(
src = "www/shiny.png", # <3>
height = 60,
width = 55,
style = "margin:10px 10px"
),
mod_var_input_ui("vars")
),
bslib::card(
full_screen = TRUE,
bslib::card_header(
tags$h4("Scatter Plot")
),
mod_scatter_display_ui("plot"),
bslib::card_footer(
tags$blockquote(
tags$em(
tags$p(
"The data for this application comes from the ",
tags$a("Building web applications with Shiny",
href = "https://rstudio-education.github.io/shiny-course/"
),
"tutorial"
)
)
)
)
)
)
)
)
}
```
1. Prefix (or folder name) of installed location
2. Path to installed package files
3. Reference to installed package image file
The application includes the image file after loading, documenting, and installing our package:
```{r}
#| label: hot_key_load_all_00
#| echo: false
#| results: asis
#| eval: true
hot_key("all")
```
```{r}
#| eval: false
#| code-fold: false
library(sap)
launch_app(run = 'p')
```
![`inst/www` accessible with `addResourcePath()`](images/external_www_launch_app.png){width='100%' fig-align='center'}
We can also use `inst/` to store alternate image files and configure the UI to display a different layout. This method ensures our app has the exact same functionality, but a different UI layout.[^layouts-git]
[^layouts-git]: As the development of your application progresses, you can (and should) keep different versions of your application in separate Git branches. But I've also found using the `inst/` folder for those early stages of developing is helpful.
```{r}
#| label: co_box_bslib
#| echo: false
#| results: asis
#| eval: true
co_box(
color = "o",
look = "default", hsize = "1.10", size = "1.05",
header = "Dependency watch!",
contents = "
`bslib` is a dependency of `shiny`, so we don't need to import this with `usethis::use_package()` (see output from `pak::pkg_deps_tree('shiny')` below)
\`\`\`sh
shiny 1.9.1 ✨
├─httpuv 1.6.15 ✨🔧
│ ├─later 1.3.2 ✨🔧
│ │ ├─Rcpp 1.0.13 ✨🔧
│ │ └─rlang 1.1.4 ✨🔧
│ ├─promises 1.3.0 ✨🔧
│ │ ├─fastmap 1.2.0 ✨🔧
│ │ ├─later
│ │ ├─magrittr 2.0.3 ✨🔧
│ │ ├─R6 2.5.1 ✨
│ │ ├─Rcpp
│ │ └─rlang
│ ├─R6
│ └─Rcpp
├─mime 0.12 ✨🔧
├─jsonlite 1.8.8 ✨🔧
├─xtable 1.8-4 ✨
├─fontawesome 0.5.2 ✨
│ ├─rlang
│ └─htmltools 0.5.8.1 ✨🔧
│ ├─base64enc 0.1-3 ✨🔧
│ ├─digest 0.6.36 ✨🔧
│ ├─fastmap
│ └─rlang
├─htmltools
├─R6
├─sourcetools 0.1.7-1 ✨🔧
├─later
├─promises
├─crayon 1.5.3 ✨
├─rlang
├─fastmap
├─withr 3.0.1 ✨
├─commonmark 1.9.1 ✨🔧
├─glue 1.7.0 ✨🔧
├─bslib 0.8.0 ✨
│ ├─base64enc
│ ├─cachem 1.1.0 ✨🔧
│ │ ├─rlang
│ │ └─fastmap
│ ├─fastmap
│ ├─htmltools
│ ├─jquerylib 0.1.4 ✨
│ │ └─htmltools
│ ├─jsonlite
│ ├─lifecycle 1.0.4 ✨
│ │ ├─cli 3.6.3 ✨🔧
│ │ ├─glue
│ │ └─rlang
│ ├─memoise 2.0.1 ✨
│ │ ├─rlang
│ │ └─cachem
│ ├─mime
│ ├─rlang
│ └─sass 0.4.9 ✨🔧
│ ├─fs 1.6.4 ✨🔧
│ ├─rlang
│ ├─htmltools
│ ├─R6
│ └─rappdirs 0.3.3 ✨🔧
├─cachem
└─lifecycle
Key: ✨ new | 🔧 compile
\`\`\`
",
fold = TRUE
)
```
The updated `movies_ui()` function below has an optional [`bslib`](https://rstudio.github.io/bslib/index.html) argument that will change the layout an display an alternate image (stored in `inst/www/bootstrap.png`).
```{r}
#| eval: false
#| code-fold: show
#| code-summary: 'show/hide updated movies_ui()'
#' User Interface for the Movies Review Application
#'
#' Creates the user interface (UI) for the Movies Review application, which
#' allows users to create customizable scatter plots based on movie data.
#'
#' @param bslib View bslib logo?
#'
#' @return A Shiny `tagList` object containing the UI elements.
#'
#' @section Details:
#' The interface is built using [`bslib`](https://rstudio.github.io/bslib/)
#' - **Page (fillable)**: [`bslib::page_fillable()`](https://rstudio.github.io/bslib/reference/page_fillable.html)
#' displays the app title.
#' - **Sidebar**: [`bslib::layout_sidebar()`](https://rstudio.github.io/bslib/reference/sidebar.html)
#' includes a logo and the variable
#' selection module.
#' ([`mod_var_input_ui`]).
#' - **Card**: [`bslib::card()`](https://rstudio.github.io/bslib/reference/card.html)
#' displays the scatter plot module
#' ([`mod_scatter_display_ui`]).
#'
#' @seealso
#' - [`movies_server()`] for the server logic of the app.
#' - [`mod_var_input_ui()`] and [`mod_scatter_display_ui()`] for the modules
#' included in the UI.
#'
#' @family **Application Components**
#'
#' @examples
#' if (interactive()) {
#' shiny::shinyApp(ui = movies_ui(), server = movies_server)
#' }
#'
#' @export
movies_ui <- function(bslib = FALSE) {
addResourcePath( # <1>
prefix = 'www',
directoryPath = system.file('www', package = 'sap')) # <1>
if (isFALSE(bslib)) {
tagList( # <2>
bslib::page_fillable(
h1("Movie Reviews"),
bslib::layout_sidebar(
sidebar =
bslib::sidebar(
title = tags$h4("Sidebar inputs"),
img(
src = "www/shiny.png",
height = 60,
width = 55,
style = "margin:10px 10px"
),
mod_var_input_ui("vars")
),
bslib::card(
full_screen = TRUE,
bslib::card_header(
tags$h4("Scatter Plot")
),
bslib::card_body(fillable = TRUE,
mod_scatter_display_ui("plot")
),
bslib::card_footer(
tags$blockquote(
tags$em(
tags$p(
"The data for this application comes from the ",
tags$a("Building web applications with Shiny",
href = "https://rstudio-education.github.io/shiny-course/"
),
"tutorial"
)
)
)
)
)
)
)
) # <2>
} else {
tagList( # <3>
bslib::page_fillable(
title = "Movie Reviews (bslib)",
theme = bslib::bs_theme(
bg = "#101010",
fg = "#F6F5F5",
primary = "#EE6F57",
secondary = "#32E0C4",
success = "#FF4B5C",
base_font = sass::font_google("Ubuntu"),
heading_font = sass::font_google("Ubuntu")
),
bslib::layout_sidebar(
sidebar = bslib::sidebar(
open = TRUE,
mod_var_input_ui("vars")
),
bslib::card(
full_screen = TRUE,
bslib::card_header(
img(src = "www/bootstrap.png", # <4>
height = 80,
width = 100,
style = "margin:10px 10px")
),
bslib::card_body(fillable = TRUE,
mod_scatter_display_ui("plot")
)
)
)
)
) # <3>
}
}
```
1. Include `inst/www` resources
2. Original `bslib` layout
3. New `bslib` layout
4. Reference to alternate image (in `inst/www/bootstrap.png`)
The new `bslib` argument in our updated `moves_ui()` function toggles between the two UI options. We should also add an `app` argument to `launch_app()` to handle the two UI options:
```{r}
#| label: rd-launch-app-bslib
#| eval: false
#| code-fold: show
#| code-summary: 'show/hide updated launch_app()'
#' Movies app standalone function
#'
#' Wrapper function for `shinyApp()`
#'
#' @param app which app to run. Options are:
#' * `"movies"` = Default app
#' * `"bslib"` = Alternative `bslib` layout
#' @param options arguments to pass to `options()`
#' @param run where to launch app:
#' * `p` = launch in viewer pane
#' * `b` = launch in external browser
#' * `w` = launch in window
#' @param ... arguments passed to UI
#'
#' @return shiny app
#'
#' @seealso [mod_var_input_ui()], [mod_var_input_server()], [mod_scatter_display_ui()], [mod_scatter_display_server()]
#'
#'
#' @export
#'
#' @import shiny
#'
launch_app <- function(app = "movies", options = list(), run = "p", ...) {
if (interactive()) {
display_type(run = run)
}
if (app == "bslib") {
shinyApp(
ui = movies_ui(bslib = TRUE),
server = movies_server,
options = options
)
} else {
shinyApp(
ui = movies_ui(...),
server = movies_server,
options = options
)
}
}
```
Now we can load, document, and build the package and confirm `app = "bslib"` works:
```{r}
#| label: dev_key_load_all_01
#| echo: false
#| results: asis
#| eval: true
hot_key("all")
```
```{r}
#| eval: false
#| code-fold: false
launch_app(app = 'bslib')
```
This alternate version of `launch_app()` uses the same modules and utility functions as the previous versions but when `app = "bslib"`, the app displays the alternate UI layout:
![`inst/www/bootstrap.png` image from `movies_ui()`](images/external_bslib_launch_app.png){width='100%' fig-align='center'}
The `inst/` folder is a versatile tool for storing various files needed in our application (logos or images, CSS styling, JavaScript functions, HTML, etc.). The example above was simple, but using `inst/` to hold resources for alternate UIs that can be displayed with a single argument is handy for demoing versions for stakeholders.
## Data files {#sec-resources-inst-dev}
It is not uncommon to develop an application that can handle data from multiple sources. In these situations, we can sometimes store the alternative data files in the `inst/` folder.[^external-data]
[^external-data]: We covered external data in @sec-data-inst-extdata.
### A [`tidy-movies`]{style="font-size: 0.95em;"} app
We'll create an alternative application in `sap` that uses a tidy version of the [`ggplot2movies` data](https://cran.r-project.org/web/packages/ggplot2movies/index.html), which we create using a function stored in the [`data-raw/tidy_movies.R`](https://github.com/mjfrigaard/sap/blob/09.2_inst-tidy-movies/data-raw/tidy_movies.R) file.[^raw-data]
```{r}
#| include: false
#| eval: false
#| code-fold: true
#| code-summary: 'show/hide data-raw/tidy_movies.R'
## code to prepare the `tidy_movies` dataset goes here
# load packages --------------------
library(fst)
make_tidy_ggp2_movies <- function(movies_data_url) {
movies_data <- read.csv(file = movies_data_url)
# specify genre columns
genre_cols <- c(
"Action", "Animation",
"Comedy", "Drama",
"Documentary", "Romance",
"Short"
)
# calculate row sum for genres
movies_data$genre_count <- rowSums(movies_data[, genre_cols])
# create aggregate 'genres' for multiple categories
movies_data$genres <- apply(
X = movies_data[, genre_cols],
MARGIN = 1,
FUN = function(row) {
genres <- names(row[row == 1])
if (length(genres) > 0) {
return(paste(genres, collapse = ", "))
} else {
return(NA)
}
}
)
# format variables
movies_data$genre_count <- as.integer(movies_data$genre_count)
movies_data$genre <- ifelse(test = movies_data$genre_count > 1,
yes = "Multiple genres",
no = movies_data$genres
)
movies_data$genre <- as.factor(movies_data$genre)
movies_data$mpaa <- factor(movies_data$mpaa,
levels = c("G", "PG", "PG-13", "R", "NC-17"),
labels = c("G", "PG", "PG-13", "R", "NC-17")
)
# reduce columns to only those in graph
movies_data[, c(
"title", "year", "length", "budget",
"rating", "votes", "mpaa", "genre_count",
"genres", "genre"
)]
}
tidy_movies <- make_tidy_ggp2_movies("https://raw.githubusercontent.com/hadley/ggplot2movies/master/data-raw/movies.csv")
# save to inst/tidy-data/
fst::write_fst(x = tidy_movies, path = "inst/tidy-data/tidy_movies.fst")
```
[^raw-data]: We covered the `data-raw/` folder in the [Data chapter](data.qmd), and you can read more about it [here in R packages, 2ed](https://r-pkgs.org/data.html#sec-data-data-raw.)
We can place the application modules, UI, and server functions in [`inst/tidy-movies/R`](https://github.com/mjfrigaard/sap/tree/09.3_inst-dev/inst/tidy-movies/R):
```{bash}
#| eval: false
#| code-fold: false
inst
├── extdata
│ └── movies.fst
├── tidy-movies # <1>
│ ├── R # <2>
│ │ ├── devServer.R
│ │ ├── devUI.R
│ │ ├── dev_mod_scatter.R
│ │ └── dev_mod_vars.R # <2>
│ ├── app.R # <3>
│ ├── imdb.png # <4>
│ └── tidy_movies.fst # <5>
└── www
├── bootstrap.png
└── shiny.png
5 directories, 10 files
```
1. Tidy movies app folder
2. App ui, server, and modules
3. Launch `tidy-movies` app
4. Alternate image/logo
5. Alternate data
All of the functions from `sap` are available in the `tidy-movies/` app with explicit namespacing (i.e., `sap::fun()`):
1. `dev_mod_vars_ui()` contains choices for the columns in the `tidy_movies` data, but there's no need to rewrite the `mod_var_input_server()` function.[^export-modules]
2. The `dev_mode_scatter` module functions have been rewritten to add functionality for importing the `tidy_movies.fst` data file and an option to removing missing values from the graph.
3. [`inst/tidy-data/app.R`](https://github.com/mjfrigaard/sap/blob/09.3_inst-dev/inst/tidy-data/app.R) contains a call to `shinyApp()` and any other packages we'll need to launch the application. The data and alternative image file can be placed in the root folder (with the `app.R` file):
[^export-modules]: This requires exporting `mod_var_input_server()` with `@export` in the `R/` folder.
### Launching [`tidy-movies`]{style="font-size: 0.95em;"} {#sec-resources-tidy-movies-launch}
Finally, we'll launch the `tidy_movies` data app with the `app` argument in our standalone function. This conditional argument is similar to the `app = "bslib"` option, but we use `shinyAppDir()` to launch the app stored in `inst/tidy-movies` (which we locate with `system.file()`).
```{r}
#| eval: false
#| code-fold: show
#| code-summary: 'show/hide R/launch_app.R'
#' Launch the Movies Review Application
#'
#' Starts the Movies Review Shiny application, which provides a customizable
#' scatter plot interface for analyzing movie data.
#'
#' @param app which app to run. Options are:
#' * `"movies"` = Default app
#' * `"bslib"` = Alternative `bslib` layout
#' * `"ggp2"` = `ggplot2movies` (tidy) data app.
#' @param options arguments to pass to `options()`
#' @param run where to launch app:
#' * `p` = launch in viewer pane
#' * `b` = launch in external browser
#' * `w` = launch in window
#' @param ... arguments passed to UI
#'
#' @return A **Shiny application** object.
#'
#' @section Details:
#' The application uses:
#' - **UI**: Defined in [`movies_ui()`].
#' - **Server Logic**: Defined in [`movies_server()`].
#'
#' @seealso
#' - [`movies_ui()`] for the user interface.
#' - [`movies_server()`] for the server logic.
#'
#' @family **Standalone Application**
#'
#' @details
#' See the [ggplot2movies](https://github.com/hadley/ggplot2movies) package.
#'
#'
#' @examples
#' if (interactive()) {
#' launch_app()
#' }
#'
#' @export
#'
#' @import shiny
#'
launch_app <- function(app = "movies", options = list(), run = "p", ...) {
if (interactive()) {
display_type(run = run)
}
if (app == "bslib") {
shinyApp(
ui = movies_ui(bslib = TRUE),
server = movies_server,
options = options
)
} else if (app == "ggp2") {
shinyAppDir(
appDir = system.file("tidy-movies",
package = "sap"
),
options = options
)
} else {
shinyApp(
ui = movies_ui(...),
server = movies_server,
options = options
)
}
}
```
<br>
After loading, documenting, and installing, we’ll run the tidy `ggplot2movies::movies` data app:
```{r}
#| label: dev_key_load_all_02
#| echo: false
#| results: asis
#| eval: true
hot_key("all")
```
```{r}
#| code-fold: false
#| eval: false
launch_app(app = 'ggp2')
```
![`inst/tidy-movies/` app with `dev_movies_ui()`](images/external_ggp2_launch_app.png){width='100%' fig-align='center'}
```{r}
#| label: co_box_themes_colors
#| echo: false
#| results: asis
#| eval: true
co_box(
color = "g",
look = "default", hsize = "1.10", size = "1.05",
header = "Using colors and themes",
contents = "Using different colors and themes for alternative applications can be a quick and easy way to differentiate the versions of your application.")
```
## Quarto apps {#sec-resources-inst-quarto}
Shiny apps can also be built inside [Quarto documents](https://quarto.org/docs/interactive/shiny/), in which case we could also use the `inst/` folder to store and load resources (images, CSS, etc.).
The `inst/quarto/` folder contains a Quarto version of our movies app:
```{bash}
#| eval: false
#| code-fold: false
inst/quarto
├── _quarto.yml
├── index.qmd
└── www
├── quarto.png
└── styles.scss
1 directory, 4 files
```
The `_quarto.yml` file contains project metadata for the app[^proj-yaml], and the `www/` folder contains an image file and a CSS file.
```yml
title: "Quarto Movies App"
format:
html:
embed-resources: true
```
[^proj-yaml]: Read more about the `_quarto.yml` configuration file in the [Quarto documentation.](https://quarto.org/docs/projects/quarto-projects.html#project-metadata)
### Shiny documents
In `index.qmd`, we can specify `server: shiny` in the YAML header to let Quarto know we want the document to be interactive:
:::{style='font-size: 0.90em;'}
```yml
---
title: Quarto Movies App
format:
html:
page-layout: full
embed-resources: true
theme:
- united
- www/styles.scss
server: shiny
---
```
:::
The other options we've included in our YAML header are [`page-layout`](https://quarto.org/docs/output-formats/page-layout.html#page-layout) (for customizing the layout of each element), [`embed-resources`](https://quarto.org/docs/output-formats/html-publishing.html#standalone-html) (to create a standalone HTML document), and [`theme`](https://quarto.org/docs/output-formats/html-themes.html) (we're using a Bootstrap 5 theme with custom CSS).
To set up our Quarto/Shiny app, we should include a code chunk with `context: setup` near the top of the document. We can use the image files in `inst/quarto/www` by adding a call to `addResourcePath()` in the `setup` chunk:
{{< include _quarto_setup.qmd >}}
Note the `context: setup` chunk includes options and themes (I'm using the [`thematic` package](https://rstudio.github.io/thematic/) to set a theme for the `ggplot2` graph in our app).
Using `page-layout: full` in the YAML header lets us use a variety of `panel` options for each code chunk. For example, we'll place the variable input module in a code chunk with the `input` option,[^export-mod-var-input-ui] the display module with the `center` option,[^export-mod-scatter-display-ui] and the data/Quarto attribution in the `fill` option.[^page-layout]
[^export-mod-var-input-ui]: This requires exporting `mod_var_input_ui()` with `@export` in the `R/` folder.
[^export-mod-scatter-display-ui]: This requires exporting `mod_scatter_display_ui()` with `@export` in the `R/` folder.
[^page-layout]: Read more about `page-layout` in the [Quarto documentation](https://quarto.org/docs/output-formats/page-layout.html#page-layout)
{{< include _quarto_panel.qmd >}}
The `context: setup` and `panel` option code chunks will execute when the document is rendered. However, any code chunk with `context: server` will execute when the document is _served_ (not when it is rendered).[^export-server-module-funs]
[^export-server-module-funs]: This requires exporting `mod_var_input_server()` and `mod_scatter_display_server()` with `@export` in the `R/` folder.
{{< include _quarto_server.qmd >}}
These chunks are run in separate R sessions, meaning we cannot access variables created in the first chunk within the second and vice versa (similar to to the `movies_ui()`, and `movies_server.R()`).
To render our Quarto Shiny app, we can use the **Run Document**/**Preview** button or running the following commands in the **Terminal**:
```sh
quarto serve /<path>/<to>/sap/inst/quarto/index.qmd