-
Notifications
You must be signed in to change notification settings - Fork 0
/
my-rhino-app.qmd
1694 lines (1366 loc) · 48.6 KB
/
my-rhino-app.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
---
title: "Shiny frameworks (part 5, `rhino`)"
author: "Martin Frigaard"
date: "2023-03-03"
categories: [shiny, code, packages]
image: "image.png"
toc: true
toc-depth: 5
toc-title: 'Contents'
toc-location: "left"
fig-align: center
code-link: true
fontsize: '10'
callout-icon: false
freeze: true
execute:
echo: true
warning: false
eval: false
---
```{r}
#| label: utils
#| eval: true
#| echo: false
#| include: false
library(kableExtra)
co_box <- function(color, header, contents = "Your text") {
class <- switch(color,
b = "note",
g = "tip",
r = "important",
o = "caution",
stop("Invalid `type`", call. = FALSE)
)
switch(color,
b = cat(paste0(
"\n",
":::: {.callout-", class, " collapse='false'}", "\n\n",
"## ", header, "\n\n",
"::: {style='font-size: 0.90em; color: #696969;'}\n\n",
contents, "\n\n",
"::: \n\n",
"::::", "\n"
)),
g = cat(paste0(
"\n",
":::: {.callout-", class, " collapse='true'}", "\n\n",
"## ", header, "\n\n",
"::: {style='font-size: 0.90em; color: #696969;'}\n\n",
contents, "\n\n",
"::: \n\n",
"::::", "\n"
)),
o = cat(paste0(
"\n",
":::: {.callout-", class, " collapse='false'}", "\n\n",
"## ", header, "\n\n",
"::: {style='font-size: 0.90em; color: #696969;'}\n\n",
contents, "\n\n",
"::: \n\n",
"::::", "\n"
)),
r = cat(paste0(
"\n",
":::: {.callout-", class, " collapse='false'}", "\n\n",
"## ", header, "\n\n",
"::: {style='font-size: 0.90em; color: #696969;'}\n\n",
contents, "\n\n",
"::: \n\n",
"::::", "\n"
)),
stop("Invalid `type`", call. = FALSE)
)
}
# roxy_ns_df -----
roxy_ns_df <- data.frame(
check.names = FALSE,
`roxygen2 tag` = c("@importFrom", "@import", "@export"),
`NAMESPACE directive` = c(
"importFrom() : import selected object from another NAMESPACE",
"import(): import all objects from another package’s NAMESPACE.",
"export() : export the function, method, generic, or class so it’s available outside of the package (in the NAMESPACE)"
),
DESCRIPTION = c("Imports:", "Imports:", "Nothing")
)
# box_use_df -----
box_use_df <- data.frame(
check.names = FALSE,
`Inside box::use()` = c(
"box::use(
pkg
)",
"box::use(
p = pkg
)",
"box::use(
pkg = pkg[foo, bar]
)",
"box::use(
pkg[my_foo = foo, ...]
)"
),
Action = c(
"imports 'pkg', does not attach any function names",
"imports 'pkg' with alias ('p'), does not attach any function names",
"imports 'pkg' and attaches the function names 'pkg::foo()' and 'pkg::bar()'",
"imports 'pkg' with alias for 'foo' ('my_foo') and attaches all exported function names"
)
)
```
<!--
https://mjfrigaard.github.io/posts/vanilla-shiny/
https://mjfrigaard.github.io/posts/my-pkg-app/
https://mjfrigaard.github.io/posts/my-golem-app/
https://mjfrigaard.github.io/posts/my-leprechaun-app/
https://mjfrigaard.github.io/posts/my-rhino-app/
-->
This is the fifth and final post on creating shiny apps with various frameworks. In this post, I'll build a *'high quality, enterprise-grade'* shiny app using the [`rhino`](https://appsilon.github.io/rhino/index.html) package and framework.
```{r}
#| label: co_box_dev
#| echo: false
#| results: asis
#| eval: true
co_box(color = "r", header = "ALERT!", "**This post is currently under development. Thank you for your patience.**")
```
## Framework comparisons
This series has focused on the following technical areas: **Start**, **Build**, and **Use**.
- **Start** covers the steps required to begin building a shiny app with the framework (from the console and IDE), and any additional packages or dependencies.
- **Build** covers the development process, which includes writing and storing code, data, external resources (like CSS or JavaScript), testing, etc.
- **Use** shows how developers can launch their application using the given framework/package locally (i.e., within the RStudio (Posit) IDE), common workflow tips, and any points I found confusing.
+ In part one, I built a 'minimal' shiny app ([`VanillaApp`](https://mjfrigaard.github.io/posts/vanilla-shiny/))
+ In part two, I structured the shiny application as an R package using [`usethis`](https://usethis.r-lib.org/) and [`devtools`](https://devtools.r-lib.org/), [`myPkgApp`](https://mjfrigaard.github.io/posts/my-pkg-app/).
+ In part three, I used the popular [`golem` framework](https://thinkr-open.github.io/golem/), [`myGolemApp`](https://mjfrigaard.github.io/posts/my-golem-app/).
+ In part four, I created a shiny app using the [`leprechaun` package](https://leprechaun.opifex.org/#/) and framework, [`myLeprechaunApp`](https://mjfrigaard.github.io/posts/my-leprechaun-app/)
The GitHub repo with all shiny app setups is [here](https://github.com/mjfrigaard/shiny-app-setups).
<br>
# `myRhinoApp`
`rhino` is a package developed by [Appsilon](https://appsilon.com/) (yes, [`shinyconf` Appsilon](https://shinyconf.appsilon.com/)) for "*Build[ing] high quality, enterprise-grade Shiny apps at speed.*"
`rhino` differs from the previous frameworks and methods in a couple important ways. First, a `rhino` application **is not an R package**. Instead, `rhino` shiny apps rely on [`box`](https://klmr.me/box/) for managing importing dependencies (instead of the `DESCRIPTION` and `NAMESPACE`). Second, `rhino` requires [node.js](https://www.wikiwand.com/en/Node.js), open-source JavaScript runtime environment.
## Start
To create a new rhino application, select **Project** > **New Project** > **New Directory**, and **Shiny Application using rhino**
The **New Project Wizard** will require a *Directory name* and *subdirectory*. I've also left *Github Actions CI* selected (the default)
::: {#fig-rhino-setup .column}
![](rhino-setup.png){height="100%" width="100%" fig-align="center"}
`myRhinoApp`
:::
::: {style="font-size: 0.80em;"}
*Click __Code__ to see output*
:::
::: {style="font-size: 0.80em;"}
```{bash}
#| label: startup-rhino
#| code-fold: true
* Initializing project ...
* Discovering package dependencies ... Done!
* Copying packages into the cache ... Done!
The following package(s) will be updated in the lockfile:
# CRAN ===============================
- R.cache [* -> 0.16.0]
- R.methodsS3 [* -> 1.8.2]
< < < < < < < OMITTED > > > > > > > >
- xtable [* -> 1.8-4]
- yaml [* -> 2.3.7]
# GitHub =============================
- box [* -> klmr/box@dev]
The version of R recorded in the lockfile will be updated:
- R [*] -> [4.2.2]
* Lockfile written to '~/projects/myRhinoApp/renv.lock'.
✔ Initialized renv.
✔ Application structure created.
✔ Unit tests structure created.
✔ E2E tests structure created.
✔ Github Actions CI added.
```
:::
This initializes the new `rhino` app by opening the `.Rproj` file in RStudio.
If I wanted to create the `myRhinoApp` application from the console, I would use the following:
::: {style="font-size: 0.80em;"}
```{r}
#| label: init-rhino
#| code-fold: false
install.packages("rhino")
rhino::init("/Users/mjfrigaard/projects/myRhinoApp")
```
:::
::: {style="font-size: 0.80em;"}
*Click __Code__ to see output*
:::
::: {style="font-size: 0.80em;"}
```{bash}
#| label: rhino-init-output
#| code-fold: true
✔ Rproj file created.
* Initializing project ...
* Discovering package dependencies ... Done!
* Copying packages into the cache ... Done!
The following package(s) will be updated in the lockfile:
# CRAN ===============================
- R.cache [* -> 0.16.0]
- R.methodsS3 [* -> 1.8.2]
< < < < < < < OMITTED > > > > > > > >
- xtable [* -> 1.8-4]
- yaml [* -> 2.3.7]
# GitHub =============================
- box [* -> klmr/box@dev]
The version of R recorded in the lockfile will be updated:
- R [*] -> [4.2.2]
* Lockfile written to '~/projects/myRhinoApp/renv.lock'.
✔ Initialized renv.
✔ Application structure created.
✔ Unit tests structure created.
✔ E2E tests structure created.
✔ Github Actions CI added.
```
:::
```{r}
#| label: co_box_output
#| echo: false
#| results: asis
#| eval: true
co_box(color = "b", header = "What's the difference?", contents = "Both methods create the same structure, using `rhino::init()` will not automatically open the new rhino application project file (`~/projects/myRhinoApp/myRhinoApp.Rproj`), so I have to navigate to this file and open it.")
```
The initial folder structure for a new rhino app is below:
::: {style="font-size: 0.80em;"}
```{bash}
#| label: rhino-initial-tree
#| code-fold: false
myRhinoApp/
├── app/
│ ├── js
│ │ └── index.js
│ ├── logic
│ │ └── __init__.R
│ ├── main.R
│ ├── static
│ │ └── favicon.ico
│ ├── styles
│ │ └── main.scss
│ └── view
│ └── __init__.R
├── app.R
├── config.yml
├── dependencies.R
├── myRhinoApp.Rproj
├── renv/
│ ├── activate.R
│ ├── library
│ │ └── R-4.2
│ ├── sandbox
│ │ └── R-4.2
│ └── settings.dcf
├── renv.lock
├── rhino.yml
└── tests/
├── cypress
│ └── integration
├── cypress.json
└── testthat
└── test-main.R
16 directories, 16 files
```
:::
The `rhino` package website has [excellent documentation on their app structure philosophy](https://appsilon.github.io/rhino/articles/explanation/application-structure.html), and it's worth reading through this before getting started. I'll do my best to summarize the application's files below:
### `app/`
The `app/` folder contains the primary folder and files for my application.
- `app/` includes the following files and sub-folders:
::: {style="font-size: 0.80em;"}
```{bash}
#| label: rhino-initial-app
#| code-fold: false
app/
├── js/
│ └── index.js
├── logic/
│ └── __init__.R
├── main.R
├── static/
│ └── favicon.ico
├── styles/
│ └── main.scss
└── view/
└── __init__.R
6 directories, 6 files
```
:::
- `js/`: the `js` folder initially contains a blank `index.js` script
- `logic/`: the `logic` folder contains [*code independent from Shiny*](https://appsilon.github.io/rhino/articles/explanation/application-structure.html#logic)
- `logic/__init__.R` is originally blank, but provides a link to the website section on project structure
::: {style="font-size: 0.80em;"}
```{r}
#| label: rhino-initial-logic-init
#| code-fold: false
# Logic: application code independent from Shiny.
# https://go.appsilon.com/rhino-project-structure
```
:::
- `static/`: the `static/` folder will contain external resources (like JavaScript files) and is similar to the sub-folders in `inst/` from `golem` and `leprechaun`.
- Use these file in the UI with:
::: {style="font-size: 0.80em;"}
```{r}
#| label: rhino-statis-ui-call
#| code-fold: false
tags$script(src = "static/js/app.min.js")
```
:::
- `styles/`: the `styles/` folder will hold custom styles (CSS and HTML) in the `styles/main.css` file (which is initially blank)
- `view/`: the `view/` folder holds the [*code which describes the user interface of your application and relies upon the reactive capabilities of Shiny.*](https://appsilon.github.io/rhino/articles/explanation/application-structure.html#view)
- `view/__init__.R` is also intially blank, but provides a link to the website section on project structure
::: {style="font-size: 0.80em;"}
```{r}
#| label: rhino-initial-view-init
#| code-fold: false
# View: Shiny modules and related code.
# https://go.appsilon.com/rhino-project-structure
```
:::
- `main.R`: the `main.R` file contains the *actual* application code (this is where I'll make edits).
- `app/main.R` contains the code for the application I see when I run `rhino::app()`
::: {style="font-size: 0.80em;"}
*Click __Code__ to see `app/main.R`*
:::
::: {style="font-size: 0.80em;"}
```{r}
#| label: rhino-initial-main
#| code-fold: show
box::use(
shiny[bootstrapPage, moduleServer, NS, renderText, tags, textOutput],
)
#' @export
ui <- function(id) {
ns <- NS(id)
bootstrapPage(
tags$h3(
textOutput(ns("message"))
)
)
}
#' @export
server <- function(id) {
moduleServer(id, function(input, output, session) {
output$message <- renderText("Hello!")
})
}
```
:::
<br>
```{r}
#| label: box_co_box
#| echo: false
#| eval: true
#| results: asis
co_box(color = "r", header = "`box::use()`?", contents = "If `box`'s syntax looks strange--don't worry! It looked strange to me too at first. But it's actually something special with those `roxygen2` tags. I'll cover it more in the **Build** section below.")
```
### `app.R`
- `app.R` is the file that will run my application and contains the `rhino::app()` function.
::: {style="font-size: 0.95em; color: #E74A2F;"}
**Do not edit this file!**
:::
::: {style="font-size: 0.80em;"}
```{r}
#| label: rhino-app-initial
#| code-fold: false
# Rhino / shinyApp entrypoint. Do not edit.
rhino::app()
```
:::
- `rhino` has a 'minimal `app.R`' [philosophy](https://appsilon.github.io/rhino/articles/explanation/application-structure.html#minimal-app-r), and the call to `rhino::app()` [performs multiple operations](https://appsilon.github.io/rhino/reference/app.html) beyond `shiny::runApp()`
### `config.yml`
- `config.yml` is a YAML file that follows the [`config` package](https://rstudio.github.io/config/) format. This file initially contains two calls to `Sys.getenv()`:
::: {style="font-size: 0.80em;"}
``` YAML
default:
rhino_log_level: !expr Sys.getenv("RHINO_LOG_LEVEL", "INFO")
rhino_log_file: !expr Sys.getenv("RHINO_LOG_FILE", NA)
```
:::
- Read more about how to use `config.yml` in the **Environments** section of the [How to: Manage secrets and environments](https://appsilon.github.io/rhino/articles/how-to/manage-secrets-and-environments.html?#environments) vignette.
### `dependencies.R`
- `dependencies.R` is an `.R` script that contains any other packages used by the application. Using this file is covered in the [Manage Dependencies vignette](https://appsilon.github.io/rhino/articles/how-to/manage-r-dependencies.html) on the package website, and I've covered `renv` in the [first application (`VanillaShiny`)](https://mjfrigaard.github.io/posts/vanilla-shiny/#renv).
- As I can see from the note in the comments, the dependencies will be tracked using `packrat` in rsconnect.
::: {style="font-size: 0.80em;"}
```{r}
#| label: rhino-depends
#| code-fold: false
# This file allows packrat (used by rsconnect during deployment)
# to pick up dependencies.
library(rhino)
```
:::
- I know I'll be using `ggplot2` and `stringr` in this application, so I'll load those there.
::: {style="font-size: 0.80em;"}
```{r}
#| label: new-rhino-depends
#| code-fold: false
# This file allows packrat (used by rsconnect during deployment)
# to pick up dependencies.
library(rhino)
library(ggplot2)
library(stringr)
```
:::
- Now I `install` and take a snapshot with `renv`:
::: {style="font-size: 0.80em;"}
```{r}
#| label: snapshot-renv-depends
#| code-fold: false
renv::install(c("ggplot2", "stringr"))
renv::snapshot()
```
:::
### `renv/`
- The `renv/` folder contains the R version and packages used to build the application:
- `renv.lock` is the lock file and contains the packages and R version used in the application.
::: {style="font-size: 0.80em;"}
```{bash}
#| label: rhino-renv
#| code-fold: false
myRhinoApp/
├── renv/
│ ├── activate.R
│ ├── library/
│ │ └── R-4.2
│ │ └── x86_64-apple-darwin17.0
│ ├── sandbox/
│ │ └── R-4.2
│ │ └── x86_64-apple-darwin17.0
│ └── settings.dcf
└── renv.lock
```
:::
- Read more about [getting started with `renv`](https://rstudio.github.io/renv/articles/renv.html) and using [`renv` in package development](https://rstudio.github.io/renv/articles/packages.html)
### `rhino.yml`
- `rhino.yml` is the configuration file and contains options for setting how Sass is built or for importing from another application structure to `rhino`.
- the code below showcases the optional arguments (and is not included in the application)
::: {style="font-size: 0.80em;"}
``` YAML
sass: string # required | one of: "node", "r"
legacy_entrypoint: string # optional | one of: "app_dir", "source", "box_top_level"
```
:::
- Read more about `rhino.yml` in the [Explanation: Configuring Rhino - rhino.yml](https://appsilon.github.io/rhino/articles/explanation/rhino-yml.html) vignette.
### `tests/`
- `tests/` contains two sub-folders, `cypress/` and `testthat/`:
::: {style="font-size: 0.80em;"}
```{bash}
tests/
├── cypress/
│ └── integration/
│ └── app.spec.js
├── cypress.json
└── testthat/
└── test-main.R
```
:::
#### `cypress/`
- `tests/cypress/` holds folders for using the [Cypress web and component testing framework](https://www.cypress.io/).
- This is also covered in the ['Use `shinttest2` vignette'](https://appsilon.github.io/rhino/articles/how-to/use-shinytest2.html).
::: {style="font-size: 0.80em;"}
```bash
tests/
├── cypress/
│ └── integration/
│ └── app.spec.js
└── cypress.json
```
:::
#### `testthat/`
- `tests/testthat/` contains the architecture for writing tests with [testthat](https://testthat.r-lib.org/)
- `rhino` also has a helper function for running all tests in the `testthat/` folder ([`rhino::test_r()`](https://appsilon.github.io/rhino/reference/test_r.html))
::: {style="font-size: 0.80em;"}
```bash
tests/
└── testthat/
└── test-main.R
```
:::
## Build
Unlike the previous applications in this series, `rhino` applications don't use the `NAMESPACE` and `DESCRIPTION` to manage dependencies. Instead, they use the `box` modules to explicitly import packages and functions
### `box`
::: {layout-ncol=1}
![](box-logo.png){width=1in fig-align="right"}
:::
`rhino` apps use [`box`](https://klmr.me/box/index.html) to create modules, which is handy, because it's specifically designed for writing "*reusable, composable and modular R code*"
**Quick refresher:** if I'm building a shiny app,
- I install dependencies using `install.packages('<package>')` (or `renv::install('<package>')`)
- When I want to use an installed package, I run `library(<package>)`, which loads the package namespace '*and attach[es] it on the search list*' (or I can use `<package>::<function>`)
- If the application gets converted into an R package, I track these dependencies using `roxygen2` tags `@importFrom` or `@import` (which are converted into `NAMESPACE` directives)
- I also include them in the `DESCRIPTION` under `Imports:`
So, I run `library(<package>)` to load the entire package namespace when I want to use a function, but it's recommended I use `@importFrom` to *specify* the package functions if I'm developing my own R package.
Put another way,
*"If I only need one or two items from a package, why am I loading* **everything** *in the namespace with `library()`?"*
This is where [`box`](https://klmr.me/box/index.html) comes in--it's designed to *'completely replace the base R `library` and `require` functions'*.
[`box`](https://klmr.me/box/index.html) handles dependencies by *'writing modular code'* and is perhaps best summarized in the following quote from [The Zen of Python](https://peps.python.org/pep-0020/) (also on the [package website](https://klmr.me/box/index.html#why-box))
> '*explicit is better than implicit.*'
A `box` module is essentially just an R script in a folder. However, in `box::use()`, instead of loading packages and functions using `library()` or `::`, I can **encapsulate and explicitly import packages and functions** in these R scripts using the syntax `package[function]`.
- The module below imports the `foo()` and `bar()` functions from the `pkg` package in the `mod.R` file (in the `box/` folder)
::: {style="font-size: 0.80em;"}
``` r
# contents of box/mod.R
#' @export
box::use(
pkg[foo, bar]
)
```
:::
- I can now access `foo()` and `bar()` from `mod.R` using `box::use(box/mod)`:
::: {style="font-size: 0.80em;"}
``` r
# using contents of box/mod.R
box::use(
box/mod
)
```
:::
#### `box` modules
Here is a quick example:
- Below I attempt to use `tidyverse`s `tidyverse_logo()` function
::: {style="font-size: 0.80em;"}
```{r}
#| label: tidyverse_logo_test
#| echo: true
#| eval: true
#| error: true
tidyverse_logo()
```
:::
- The error is expected, because `dplyr` has been installed, but hasn't been loaded.
- In a `box` module, I import the `tidyverse_logo()` from `tidyverse` (without using `library()` or `::`), by creating a `logo.R` file in a `tidy` folder. In `logo.R`, I include `box::use()` and the following code:
- I also include `#' @export` on the preceding line:
::: {style="font-size: 0.80em;"}
```{r}
#| label: box_tidy
#| eval: false
# contents of tidy/logo.R
#' @export
box::use(
tidyverse[tidyverse_logo]
)
```
:::
- Note I did not have to use `tidyverse::tidyverse_logo()`
- To use this module, I call `box::use(tidy/logo)`, which loads `logo` into the environment.
::: {style="font-size: 0.80em;"}
```{r}
#| label: box_use_tidy_logo
#| eval: false
box::use(tidy/logo)
ls(logo)
```
```bash
<module: tidy/logo>
```
:::
- I can use `ls()` on `logo` to return the imported names.
::: {style="font-size: 0.80em;"}
```{r}
#| label: ls_logo
#| eval: false
ls(logo)
```
```bash
[1] "tidyverse_logo"
```
:::
- To use the `tidyverse_logo()` function, I use `$`:
::: {style="font-size: 0.80em;"}
```{r}
#| label: logo_tidyverse_logo
#| eval: false
logo$tidyverse_logo()
```
```bash
⬢ __ _ __ . ⬡ ⬢ .
/ /_(_)__/ /_ ___ _____ _______ ___
/ __/ / _ / // / |/ / -_) __(_-</ -_)
\__/_/\_,_/\_, /|___/\__/_/ /___/\__/
⬢ . /___/ ⬡ . ⬢
```
:::
- Note that `tidyverse_logo()` is still not loaded *outside* the `logo` module
::: {style="font-size: 0.80em;"}
```{r}
#| label: tidyverse_logo_retest
#| eval: true
#| error: true
tidyverse_logo()
```
:::
I can also include (or wrap) `box::use()` inside custom functions, and then call these when I've imported the module:
- `tidy/plogo.R` imports `tidyverse_logo()` *inside* a custom function, `print_logo()`
- Note that to use a packages/functions from a module, you must include `#' @export` from `roxygen2` (in the line above):
::: {style="font-size: 0.80em;"}
```{r}
#| label: plogo_tidyverse_logo
#| eval: false
# contents of tidy/plogo.R
#' prints tidyverse logo
#' @export
print_logo <- function() {
# import pkg[fun] inside function
box::use(
tidyverse[tidyverse_logo]
)
# use fun
tidyverse_logo()
}
```
:::
- I load the module into the environment with `box::use(path/to/module)`
::: {style="font-size: 0.80em;"}
```{r}
#| label: use_plogo
#| eval: false
# use tidy/plogo
box::use(tidy/plogo)
plogo
```
``` bash
<module: tidy/plogo>
```
:::
- I can use the `print_logo()` function the same way I used `tidyverse_logo()` in the `logo` module.
::: {style="font-size: 0.80em;"}
```{r}
#| label: run_print_logo
#| eval: false
# access print_logo() with $
plogo$print_logo()
```
```bash
⬢ __ _ __ . ⬡ ⬢ .
/ /_(_)__/ /_ ___ _____ _______ ___
/ __/ / _ / // / |/ / -_) __(_-</ -_)
\__/_/\_,_/\_, /|___/\__/_/ /___/\__/
⬢ . /___/ ⬡ . ⬢
```
:::
- Also note `print_logo()` doesn't exist outside the `plogo` module:
::: {style="font-size: 0.80em;"}
```{r}
#| label: check_plogo
#| eval: true
#| error: true
print_logo()
```
:::
- This is what is meant by *encapsulation*
`box` modules can also import functions and packages using aliases.
- The example below (`tidy/tidy_logo.R`) exports `tidyverse_logo()` as `tidy_logo()` and `print_logo()`
- Both the contents of `box::use()` and `print_logo()` need the `#' @export` tag
::: {style="font-size: 0.80em;"}
```{r}
#| label: module_tidy_logo
#| eval: false
# contents of tidy/tidy_logo.R
#' import alias tidyverse logo
#' @export
box::use(
tidyverse[tidy_logo = tidyverse_logo]
)
#' prints tidyverse logo
#' @export
print_logo <- function() {
# use fun alias
tidy_logo()
}
```
:::
- After I load the module with `box::use()`, I can see both functions in `tidy_logo` using `ls()`
::: {style="font-size: 0.80em;"}
```{r}
#| label: ls_tidy_logo
#| eval: false
box::use(tidy/tidy_logo)
ls(tidy_logo)
```
```bash
[1] "print_logo" "tidy_logo"
```
:::
- If I compare both functions, I find they are identical:
::: {style="font-size: 0.80em;"}
```{r}
#| label: identical_tidy_logo
#| eval: false
identical(
x = tidy_logo$print_logo(),
y = tidy_logo$tidy_logo()
)
```
```bash
[1] TRUE
```
:::
There are multiple methods for importing packages and functions with `box`. The table below list a few of these options:
::: {style="font-size: 0.60em;"}
```{r}
#| label: co_box_box_use
#| echo: false
#| eval: true
#| results: asis
co_box(
color = "b",
header = "**`box::use()` options**",
contents = kable_styling(
kable_input = knitr::kable(box_use_df,
align = c("l", "l", "r"),
bootstrap_options = c("striped", "hover", "condensed", "responsive")
)
)
)
```
:::
::: {style="font-size: 0.85em; color: [#E74A2F;"}
*These options are also listed on the [package website](https://klmr.me/box/index.html)*
:::
This has been a very brief overview of `box`, so I **highly recommend** consulting the [`box` website](https://klmr.me/box/index.html) and vignettes (especially ["the hierarchy of module environments"](https://klmr.me/box/articles/mod-env-hierarchy.html)). The `rhino` website also has a great overview on using [`box` with shiny apps](https://appsilon.github.io/rhino/articles/explanation/box-modules.html) (I also have a collection of `box` module examples in this [repo](https://github.com/mjfrigaard/rbox/blob/main/boxes.md).)
### Modules
Now that I've covered a bit on how `box` modules work, I am going to create the *application* modules. New modules should be created in the `app/view/` folder.
The first module we'll create is the `app/view/inputs.R` module for collecting the user inputs
- The code below is placed in `app/view/inputs.R`
::: {style="font-size: 0.80em;"}
*Click __Code__ to see `app/view/inputs.R`*
:::
::: {style="font-size: 0.80em;"}
```{r}
#| label: inputs_module
#| eval: false
#| code-fold: true
# app/view/inputs.R
# define module functions
box::use(
shiny[
NS, tagList, selectInput, h3,
sliderInput, textInput, moduleServer, reactive
],
)
#' input values UI
#' @export
ui <- function(id) {
ns <- NS(id)
tagList(
selectInput(
inputId = ns("y"),
label = "Y-axis:",
choices = c(
"IMDB rating" = "imdb_rating",
"IMDB number of votes" = "imdb_num_votes",
"Critics Score" = "critics_score",
"Audience Score" = "audience_score",
"Runtime" = "runtime"
),
selected = "audience_score"
),
selectInput(
inputId = ns("x"),
label = "X-axis:",
choices = c(
"IMDB rating" = "imdb_rating",
"IMDB number of votes" = "imdb_num_votes",
"Critics Score" = "critics_score",
"Audience Score" = "audience_score",
"Runtime" = "runtime"
),
selected = "imdb_rating"
),
selectInput(
inputId = ns("z"),
label = "Color by:",
choices = c(
"Title Type" = "title_type",
"Genre" = "genre",
"MPAA Rating" = "mpaa_rating",
"Critics Rating" = "critics_rating",
"Audience Rating" = "audience_rating"
),
selected = "mpaa_rating"
),
sliderInput(
inputId = ns("alpha"),
label = "Alpha:",
min = 0, max = 1, step = 0.1,
value = 0.5
),
sliderInput(