-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlaunch.qmd
903 lines (649 loc) · 30.5 KB
/
launch.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
# Launch {#sec-launch}
```{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.10", size = "1.05",
header = "TLDR: Launching your app", fold = TRUE,
contents = "
**Launching Apps:**
- **`shinyApp()`**: can be bundled in a standalone app function to store an app-package\n
- Also useful for quick prototyping or if an app is in a single `.R` script\n
- Returns a shiny app object (helpful with testing)\n
- **`runApp()`**: versatile function that can launch apps in multiple formats/locations\n
- A directory with a `server.R` and `ui.R`, or a single `app.R` file`\n
- An app object created by `shinyApp()`\n
- **`shinyAppDir()`**: useful if you need launch a Shiny app programmatically from a directory.\n
"
)
```
---
This chapter covers the differences between `shinyApp()`, `runApp()`, and `shinyAppDir()`, what should go in an `app.R` file, and other options for launching an app (or apps) from within an app-package.
```{r}
#| label: co_box_positron_version
#| echo: false
#| results: asis
#| eval: true
co_box(
color = "b",
look = "simple",
hsize = "1.10",
size = "1.05",
header = "![](images/positron.png){height=20} Positron Version",
fold = TRUE,
contents = "At the time of this writing, the [2024.09.0-1](https://github.com/posit-dev/positron/releases/tag/2024.09.0-1) pre-release of Positron was available for testing."
)
```
During development, we have a variety of options for launching applications. Both RStudio ![](images/rstudio-icon.png){height=20} and Positron ![](images/positron.png){height=20} offer a single-click button to run our application the top of the **Source** pane/**Editor**. We can also launch the app by calling the standalone app function in the **Console**. Below we'll cover what happens behind the scenes when we click on these icons.
```{r}
#| label: shinypak_apps
#| echo: false
#| results: asis
#| eval: true
shinypak_apps(regex = "08", branch = "08_launch")
```
## Running apps
In the current branch of `sap`, the `app.R` file contains a call to `launch_app()`, which loads the package and passes the UI and server functions to `shinyApp()`.
```{r}
#| label: co_box_terminology
#| echo: false
#| results: asis
#| eval: true
co_box(
color = "b",
look = "default",
fold = FALSE,
hsize = "1.10",
size = "1.05",
header = "'Launch' vs. 'Run'",
contents = "
I'll be using the term 'launch' to differentiate successfully displaying the application locally (either in the IDE window, viewer pane, or browser) from clicking on the **Run App**/**Run Shiny App** button or calling the `runApp()` function."
)
```
```{r}
#| label: git_margin_box_06.2_pkg-imports
#| echo: false
#| results: asis
#| eval: true
git_margin_box(
contents = "standard",
fig_pw = '75%',
branch = "06.2_pkg-imports",
repo = 'sap')
```
As we can see in the image below, this places the **Run App** icon in RStudio's ![](images/rstudio-icon.png){height=20} **Source** pane. In Positron ![](images/positron.png){height=20}, the `app.R` file displays the **Run Shiny App**.
::: {.panel-tabset}
### RStudio ![](images/rstudio-icon.png){height=20}
![](images/launch_run_app_from_imports.png){width=100%}
### Positron ![](images/positron.png){height=20}
![](images/launch_positron_run_app.png){width=100%}
:::
Clicking on either **Run App**/**Run Shiny App** buttons calls `runApp()` and launches our application, but with a `loadSupport()` warning.
The section below will cover the `loadSupport()` warning and why it appears when using the **Run App**/**Run Shiny App** buttons in RStudio ![](images/rstudio-icon.png){height=20} and Positron ![](images/positron.png){height=20}.
### [`loadSupport()`]{style="font-size: 0.95em; font-weight: bold;"} warnings
```{r}
#| label: co_box_load_support_warn
#| echo: false
#| results: asis
#| eval: true
co_box(
color = "r",
look = "default",
hsize = "1.10",
size = "1.05",
fold = FALSE,
header = "loadSupport() warning",
contents = "
<br>
![](images/launch_loadsupport_error_run_app.png){width=100%}
The warning in the **Console** is telling us `loadSupport()` has detected that `sap` is a package, but it's still sourcing the `R/` subdirectory.[^load-support-shiny-chap]
[^load-support-shiny-chap]: If you recall, we covered the [`loadSupport()`](https://shiny.posit.co/r/reference/shiny/1.5.0/loadsupport) function in [Chapter 2](shiny.qmd).
")
```
::: {.panel-tabset}
### RStudio ![](images/rstudio-icon.png){height=20}
As noted above, clicking **Run App** in RStudio ![](images/rstudio-icon.png){height=20} calls `runApp()` and launches our application with a `loadSupport()` warning printed in the **Console**.
![Clicking **Run App** in RStudio calls `runApp()` and displays the `loadSupport()` warning](images/launch_loadsupport_error.png){width=100%}
### Positron ![](images/positron.png){height=20}
In Positron ![](images/positron.png){height=20}, clicking on the **Run Shiny App** button launches the application with a slightly different process than RStudio ![](images/rstudio-icon.png){height=20}:
![Clicking **Run Shiny App** in Positron calls `runApp()` and displays the `loadSupport()` warning](images/launch_positron_Run_Shiny_App.png){width=100%}
1. A new Shiny terminal process is started with the `--devmode` option
2. `runApp()` is called with the *full* path to our `app.R` file and a `port` argument[^positron-browser]
3. The `loadSupport()` warning is displayed in the Terminal
[^positron-browser]: I've displayed the application in the browser clicking on the ![](images/launch_positron_shiny_popout.png){height=20} 'Open the current URL in the default browser' icon.
:::
-------------------------------------------------
It's important to note that we also see the `loadSupport()` warning if we bypass the **Run App**/**Run Shiny App** buttons and call `shiny::runApp()` directly in the **Console**:
::: {.panel-tabset}
### RStudio ![](images/rstudio-icon.png){height=20}
![Calling `runApp()` directly in RStudio's **Console** displays the `loadSupport()` warning](images/launch_rstudio_runApp.png)
### Positron ![](images/positron.png){height=20}
![Calling `runApp()` directly in Positron's **Console** displays the `loadSupport()` warning](images/launch_positron_runApp.png){width=100%}
:::
-------------------------------------------------
[*What's with the warning?*]{style="font-size: 1.15em; font-weight: bold;"}
In the [Shiny chapter](shiny.qmd) we learned `loadSupport()` is called automatically when an application is run with `runApp()`. Specifically, `loadSupport()`
> "*loads any top-level supporting .R files in the `R/` directory adjacent to the `app.R`/`server.R`/`ui.R` files*" [^shiny-loadsupport]
[^shiny-loadsupport]: `loadSupport()` does this by sourcing the files in [alphabetical order](https://shiny.posit.co/r/reference/shiny/1.7.3/loadsupport).
Behind the scenes, `runApp()` is called by *both* **Run App/Run Shiny App** buttons, which then automatically calls `loadSupport()`. This is why if we pass our standalone app function to the **Console** (*which uses `shinyApp()`, not `runApp()`*), the warning disappears:
::: {.panel-tabset}
### RStudio ![](images/rstudio-icon.png){height=20}
![No `loadSupport()` warning in RStudio](images/launch_launch_app_call_rs.png){fig-align='center'}
### Positron ![](images/positron.png){height=20}
![No `loadSupport()` warning in Positron](images/launch_launch_app_call_positron.png){fig-align='center'}
:::
-------------------------------------------------
The examples above demonstrate the differences between calling `shinyApp()` and `runApp()`, and the tension between calling a standalone app function from an R package vs. sourcing the `app.R` file in a Shiny project.
### [`--devmode`]{style="font-weight: bold;"}
As we saw above, clicking **Run Shiny App** in Positron ![](images/positron.png){height=20} will launch the application in [`devmode`](https://shiny.posit.co/r/reference/shiny/latest/devmode.html),[^devmode-exp] which is controlled by the script below:
[^devmode-exp]: [`devmode`](https://shiny.posit.co/r/reference/shiny/latest/devmode.html) is an experimental option with multiple settings.
```{r}
#| eval: false
#| code-fold: true
#| code-summary: "show/hide Positron's runShinyApp.R script"
usage <- "Usage: Rscript runShinyApp.R <path> <port> [--devmode]"
args <- commandArgs(trailingOnly = TRUE) # <1>
if (length(args) < 2) {
stop(usage)
}
path <- args[1]
port <- as.integer(args[2])
stopifnot(is.integer(port))
devmode <- "--devmode" %in% args # <2>
if (devmode) {
shiny::devmode()
} else {
options(shiny.autoreload = TRUE)
}
message("Running Shiny app")
message("-----------------")
message(sprintf('shiny::runApp(%s, port = %d)\n', deparse(path), port))
shiny::runApp(path, port = port, launch.browser = FALSE) # <3>
```
1. `commandArgs(trailingOnly = TRUE)` retrieves the arguments passed to the script, excluding the default arguments used when R starts.
2. `devmode <- "--devmode" %in% args` checks if the `--devmode` flag is present among the arguments. If it is, `devmode` is set to `TRUE`
3. Lastly, the script runs the Shiny app using `runApp()` (with the specified `path` and `port`), and `launch.browser = FALSE` ensures the app is not automatically opened in a web browser.
Shiny `devmode` will display *something like* the following messages the first time your application is launched using the **Run Shiny App** button in Positron ![](images/positron.png){height=20}:
```{bash}
#| eval: false
#| code-fold: true
#| code-summary: 'show/hide devmode options'
shiny devmode - Using full shiny javascript file. To use the minified version, call `options(shiny.minified = TRUE)`
This message is displayed once every 8 hours.
shiny devmode - Turning off caching of Sass -> CSS compilation. To turn caching on, call `options(sass.cache = TRUE)`
This message is displayed once every 8 hours.
shiny devmode - Disabling the use of bslib precompiled themes. To be able to use precompiled themes, call `options(bslib.precompiled = TRUE)`
This message is displayed once every 8 hours.
shiny devmode - Enabling warnings about low color contrasts found inside `bslib::bs_theme()`. To suppress these warnings, set `options(bslib.color_contrast_warnings = FALSE)`
This message is displayed once every 8 hours.
```
## Shiny launch functions
<!-- https://rtask.thinkr.fr/shinyapp-runapp-shinyappdir-difference/ -->
In the following sections, we'll compare `shinyApp()`, `shinyAppDir()`, and `runApp()` to determine which one to use in `R/launch_app.R` and the `app.R` file. As we've seen, the **Run App**/**Run Shiny App** buttons call `runApp()`, even when we have a call to `shinyApp()` in the `app.R` file. This might make you wonder,
["*Why even include a call to `shinyApp()` if the app is being launched with `runApp()`?*"]{style="font-size: 1.05em; font-weight: bold;"}
Let's review what happens when we call `shinyApp()`.
### [`shinyApp()`]{style="font-size: 0.95em; font-weight: bold;"} {#sec-launch-shiny-app}
One of the key features of `shinyApp()` is the creation of the `shiny.appobj` (a `shiny` app object):
```{r}
#| eval: false
#| code-fold: false
app <- shinyApp(ui = movies_ui,
server = movies_server)
str(app)
```
If we look at the structure of the returned object from `shinyApp()`, we see the `shiny.appobj` includes the `appDir` under `appOptions`:
``` sh
List of 5
$ httpHandler :function (req)
$ serverFuncSource:function ()
$ onStart : NULL
$ options : list()
$ appOptions :List of 2
..$ appDir : chr "/path/to/sap" # <1>
..$ bookmarkStore: NULL
- attr(*, "class")= chr "shiny.appobj" # <2>
```
1. `appDir` is the first argument of `runApp()`
2. A shiny app object
This is why `runApp()` works with any `.R` file creating a shiny app object.
:::: {.callout-note collapse="true" appearance="default" title='shinyApp()'}
::: {style='font-size: 1.05em; color: #696969;'}
:::{layout="[45,55]" layout-valign="center"}
[`shinyApp()`]{style="font-size: 0.95em"}: Creates and launches an app defined inline within the call itself (or with UI and server functions passed as arguments).
``` r
shinyApp(
ui = fluidPage(
# UI elements
),
server = function(input, output) {
# Server logic
}
)
```
:::
:::
::::
### [`shinyAppDir()`]{style="font-size: 0.95em; font-weight: bold;"} {#sec-launch-shiny-app-dir}
`shinyAppDir()` is similar to `shinyApp()`, but is designed to use a "*path to directory that contains a Shiny app.*"
In practice, we can use `shinyAppDir()` with a returned object from `shinyApp()`:
```{r}
#| eval: false
#| code-fold: false
app <- shinyApp(
ui = movies_ui,
server = movies_server
)
app$appOptions$appDir
```
``` sh
[1] "path/to/sap"
```
This path can be passed to the `appDir` argument (along with any Shiny `options`).
```{r}
#| eval: false
#| code-fold: false
shinyAppDir(
appDir = app$appOptions$appDir,
options(test.mode = TRUE)
)
```
:::: {.callout-note collapse="true" appearance="default" title='shinyAppDir()'}
::: {style='font-size: 1.05em; color: #696969;'}
:::{layout="[45,55]" layout-valign="center"}
[`shinyAppDir()`]{style="font-size: 0.95em"}: Launches an app from a directory (with an `app.R` or `ui.R`/`server.R` files).
``` r
shinyAppDir(
appDir = "path/to/app/",
options = list())
```
:::
:::
::::
### [`runApp()`]{style="font-size: 0.95em; font-weight: bold;"} {#sec-launch-run-app}
The reason we're able to call `runApp()` in the **Console** to launch both applications above is because it's very versatile:
:::{layout="[45,55]" layout-valign="center"}
#### [`runApp()`]{style="font-size: 0.85em"} {.unnumbered}
Can launch apps from `ui.R`/`server.R`, `app.R` or directory:
#### {.unnumbered}
``` r
# In console
runApp()
```
:::
:::{layout="[45,55]" layout-valign="center"}
Works with a path to an `.R` file that creates a `shiny.appobj`:[^launch-run-app-shiny-examples]
[^launch-run-app-shiny-examples]: Shiny's examples are run [using `runApp()`](https://github.com/rstudio/shiny/blob/9ebcbf8a2dec7045f609624d5f339e9a3e29de5f/R/runapp.R#L436)
``` r
runApp(appDir = "path/to/sap")
```
:::
:::{layout="[45,55]" layout-valign="center"}
Can also use a `shiny.appobj` directly:
``` r
app <- shinyApp(
ui = movies_ui,
server = movies_server)
runApp(appDir = app)
```
:::
This final method does not produce the `loadSupport()` warning because a Shiny object (`shiny.appobj`) has already been created, and `runApp()` is essentially calling `print(app)` in the **Console**.
:::: {.callout-note collapse="true" appearance="default" title="runApp()"}
::: {style='font-size: 1.05em; color: #696969;'}
:::{layout="[45,55]" layout-valign="center"}
[`runApp()`]{style="font-size: 0.95em"}: A generalized way to launch your app--it can run apps defined inline, or from a directory.
``` r
runApp(
appDir = "path/to/app/",
test.mode = TRUE/FALSE)
```
:::
:::
::::
#### Recap {.unnumbered}
1. `shinyApp()` is typically used to create apps within an interactive R session
2. `shinyAppDir()` runs a Shiny app stored in a directory (containing an `app.R` file (or `ui.R` and `server.R` files)
3. `runApp()` also launches apps in a directory, but it's versatility makes it suitable for running apps in various formats, either defined inline or in separate directories.[^shiny-app-launchers]
[^shiny-app-launchers]: It's worthwhile to read the documentation on [`shinyApp()`, `shinyAppDir()`](https://shiny.posit.co/r/reference/shiny/0.14/shinyapp), and [`runApp()`](https://shiny.posit.co/r/reference/shiny/1.7.4/runapp).
## Standalone function
I tend to name the standalone app function `launch_app()` and include the options covered below (none of these are required, though).
```{r}
#| label: git_box_08_launch-app
#| echo: false
#| results: asis
#| eval: true
git_margin_box(
contents = "launch",
fig_pw = '75%',
branch = "08_launch-app",
repo = 'sap')
```
### App launching options
`shinyApp()` or `shinyAppDir()` both have an `options` argument, so we should make this available in `launch_app()`. For example, one of the Shiny options we could include in our standalone app function is `test.mode`:
> '*Should the application be launched in test mode? This is only used for recording or running automated tests. Defaults to the `shiny.testmode` option, or `FALSE` if the option is not set.*'
The `test.mode` option lets us [export values from our application]((https://shiny.posit.co/r/reference/shiny/1.0.2/exporttestvalues)) when we're running tests (which we'll cover in-depth in the [Tests](@sec-tests) section).
We'll make `options` an argument that defaults to an empty `list()` in `launch_app()`:
```{r}
#| eval: false
#| code-fold: false
launch_app <- function(options = list()) {
shinyApp(
ui = movies_ui(), # <1>
server = movies_server, # <1>
options = options # <2>
)
}
```
1. Build the shiny app object with `movies_ui` and `movies_server`
2. Include `options` list
### Where to launch?
I've written a `display_type()` helper function to 1) check if the application is being run in RStudio and, if so, 2) control where the Shiny app is launched. The `run` argument in `display_type()` takes the following options:
- `"p"` = **Viewer Pane**
- `"w"` = **IDE Window**
- `"b"` = **External browser**
The option to access configuration is `shiny.launch.browser`:[^launch-shiny.launch.browser]
[^launch-shiny.launch.browser]: The `shiny.launch.browser` options are covered in [this blog post by Garrick Aden-Buie](https://www.garrickadenbuie.com/blog/shiny-tip-option-where-to-run/), and I've combined them into a `run` argument in `launch_app()`
```{r}
#| eval: false
#| code-fold: false
#' Shiny app display mode helper
#'
#' @param run where to launch app:
#' * `"p"` = launch in viewer pane
#' * `"b"` = launch in external browser
#' * `"w"` = launch in window (default)
#'
#' @return notification of `shinyViewerType` option
#'
#' @export
#'
display_type <- function(run = "w") {
if (interactive()) {
if (Sys.getenv("RSTUDIO") == "1") { #<1>
switch( #<2>
run,
p = options(shiny.launch.browser = .rs.invokeShinyPaneViewer),
b = options(shiny.launch.browser = .rs.invokeShinyWindowExternal),
w = options(shiny.launch.browser = .rs.invokeShinyWindowViewer),
NULL = options(shiny.launch.browser = NULL)
) #<2>
environment <- "RStudio"
shinyViewerType <- getOption('shiny.launch.browser') |>
attributes() |>
unlist() |>
unname()
cli::cli_alert_info("App running in {environment}") #<3>
cli::cli_alert_info("shinyViewerType set to {shinyViewerType}") #<4>
} else {
environment <- "RStudio"
cli::cli_alert_info("App not running in {environment}")
}
} else {
cli::cli_alert_info("App not running in interactive session")
}
}
```
1. Detect IDE
2. Set option
3. Print IDE
4. Print option
```{r}
#| label: co_box_cli_dependency
#| echo: false
#| results: asis
#| eval: true
co_box(
color = "o",
look = "default", hsize = "1.10", size = "1.05",
fold = TRUE,
header = "New dependency!",
contents = "
The `cli` package is imported as part the `devtools`/`usethis` workflow but we want to add it the `Imports` field of the `DESCRIPTION` with `usethis::use_package('cli')`.
"
)
```
### An updated [`launch_app()`]{style="font-size: 0.90em"} {#sec-launch-standalone-app-function}
The `display_type()` and `options` list have been added to `launch_app()`:
```{r}
#| eval: false
#| code-fold: false
launch_app <- function(options = list(), run = "p") {
display_type(run = run) # <1>
shinyApp(
ui = movies_ui(),
server = movies_server,
options = options # <2>
) # <3>
}
```
1. Set `shinyViewerType` option with `display_type()`
2. Pass options
3. Launch app
After loading, documenting, and installing our package, we can see the documentation for our updated `launch_app()` function in RStudio ![](images/rstudio-icon.png){height=20} and Positron ![](images/positron.png){height=20}:
```{r}
#| label: dev_key_all_00
#| echo: false
#| results: asis
#| eval: true
hot_key("all")
```
:::{layout="[40,60]" layout-valign="top"}
![Standalone app function in RStudio](images/launch_standalone_rstudio.png){width='100%'}
![Standalone app function in Positron](images/launch_standalone_positron.png){width='100%'}
:::
In RStudio ![](images/rstudio-icon.png){height=20}, we will confirm the app is launching without the `loadSupport()` warning, the message is printing to the **Console** from the `run` argument, and `test.mode` are implemented correctly.
We also want to confirm `launch_app()` works in Positron ![](images/positron.png){height=20}:
::: {.panel-tabset}
### ![](images/rstudio-icon.png){height=20} `launch_app()`
![`launch_app()` launches the app in the Window](images/launch_launch_app_fun_window.png){width=100%}
### ![](images/rstudio-icon.png){height=20} `launch_app()` args
![The updated `launch_app()` function launches the application in the Viewer](images/launch_launch_app_args.png){width=100%}
### ![](images/positron.png){height=20} `launch_app()`
![The updated `launch_app()` function in Positron](images/launch_launch_app_args_positron.png){width=100%}
:::
When we're confident our standalone app function is working, we'll write the `app.R` file.
## The [`app.R`]{style="font-size: 1.10em; font-weight: bold;"} file {#sec-launch-app-dot-r}
The `app.R` file should contain any options or settings that we would use during development. There are multiple ways to launch an application from `app.R`, so I encourage you to explore the options below to find a method that works for your workflow/environment.
### Is this an interactive session?
The first condition we'll check to see if there is a "*[human operator to interact with](https://stat.ethz.ch/R-manual/R-devel/library/base/help/interactive.html)*" with `base::interactive()`:
```{r}
#| eval: false
#| code-fold: false
if (!interactive()) {
} else {
}
```
You have probably seen control flow like this in `shiny` help file examples (like `flowLayout()` below):
:::{#fig-launch_if_interactive_examples}
![`if (interactive())` in `flowLayout()` example](images/launch_if_interactive_examples.png){#fig-launch_if_interactive_examples width=100%}
Running examples 'interactively' let's us see the app demo beneath the code
:::
Adding `if` and `interactive()` will allow our `app.R` file distinguish between 1) launching apps from a RStudio/Positron session (i.e., during development) and 2) deploying apps (i.e., like publishing the application on Posit Connect).
#### Non-interactive sessions
If the session is non-interactive, we'll divert all regular output to the standard error stream. The `sink()` function *"diverts R output to a connection"*, so the code below sends the output that would normally print to the console to the where error messages are written.
```{r}
#| eval: false
#| code-fold: false
if (!interactive()) {
sink(stderr(), type = "output")
} else {
}
```
This is useful in a non-interactive settings if we want to re-direct the error output for the console text-mode connection.
`tryCatch()` is used for 'catching conditions' during the execution of an expression (`expr = `):
```{r}
#| eval: false
#| code-fold: false
if (!interactive()) {
sink(stderr(), type = "output")
tryCatch(expr = {
library(sap)
}, error = function(e) {
pkgload::load_all()
})
} else {
}
```
In this case, if `library(sap)` throws an error, the function specified after `error =` is executed (i.e., `pkgload::load_all()`).[^launch-pkgload-load_all]
[^launch-pkgload-load_all]: `pkgload` is part of the [conscious uncoupling](https://www.tidyverse.org/blog/2018/10/devtools-2-0-0/) of the `devtools` package we learned about back in [Chapter 6](dependencies.qmd).
Written this way, in a non-interactive R session, `app.R` will re-direct the error output and attempt to load and attach `sap`, and if this fails, `app.R` will attempt to load all the files in the `R/` folder.
#### Interactive sessions
If the session ***is*** interactive, we want `app.R` to load all the code in the `R/` folder with `pkgload::load_all()` before launching our app with `launch_app()` (and a few optional arguments).
```{r}
#| eval: false
#| code-fold: false
if (!interactive()) {
sink(stderr(), type = "output")
tryCatch(
expr = {
library(sap)
},
error = function(e) {
pkgload::load_all()
}
)
} else {
pkgload::load_all()
}
sap::launch_app(
options = list(test.mode = TRUE), run = 'p')
```
`pkgload::load_all()` is the function that's called when we run `devtools::load_all()` (or use [<kbd>Ctrl/Cmd</kbd> + <kbd>Shift</kbd> + <kbd>L</kbd>]{style="font-weight: bold; font-size: 0.75em"}), and this is somewhat analogous to running `library(sap)`
```{r}
#| label: co_box_pkgload
#| echo: false
#| results: asis
#| eval: true
co_box(
color = "o",
look = "default", hsize = "1.10", size = "1.05",
fold = TRUE,
header = "New dependency!",
contents = "
The `pkgload` package is imported as part the `devtools`/`usethis` workflow, otherwise we'd want to add it the `Imports` field of the `DESCRIPTION` with `usethis::use_package('pkgload')`.
"
)
```
#### Dealing with [`loadSupport()`]{style="font-size: 0.95em; font-weight: bold;"}
The [`withr` package](https://withr.r-lib.org/) is designed to '*run code with safely and temporarily modified global state*', and it comes in handy when launching shiny apps. For example, I want to turn off the `loadSupport()` behavior when launching the app from `app.R`.[^launch-r-folder]
[^launch-r-folder]: You can read more about the `shiny.autoload.r` option and `loadSupport()` in [this article](https://shiny.posit.co/r/articles/build/app-formats/index.html#the-r-directory)
We can use `withr::with_options()` to accomplish this using the following `new` and `code` arguments
1. `new`: a named list of the *new options and their values*
2. `code`: the '*Code to execute in the temporary environment*
We'll place the `withr::with_options()` at the top of `app.R` and pass `shiny.autoload.r = FALSE` to the `new` argument (the contents of our `app.R` are passed into the `code` argument).
```{r}
#| eval: false
#| code-fold: false
withr::with_options(new = list(shiny.autoload.r = FALSE), code = { # <1>
if (!interactive()) { # <2>
sink(stderr(), type = "output")
tryCatch(
expr = {
library(sap)
},
error = function(e) {
pkgload::load_all()
}
) # <2>
} else { # <3>
pkgload::load_all()
} # <3>
sap::launch_app( # <4>
options = list(test.mode = TRUE), run = 'p') # <4>
})
```
1. Turn off `loadSupport()`
2. Define non-interactive behaviors
3. Define interactive behaviors
4. Launch app (with options)
Now that we've updated the `app.R` to account for the app-package structure, we'll load, document, and install `sap` and send it's contents to the **Console**:
```{r}
#| label: dev_key_all_01
#| echo: false
#| results: asis
#| eval: true
hot_key("all")
```
```{r}
#| label: co_box_withr
#| echo: false
#| results: asis
#| eval: true
co_box(
color = "o",
look = "default", hsize = "1.10", size = "1.05",
fold = TRUE,
header = "New dependency!",
contents = "
The `withr` package is imported as part the `devtools`/`usethis` workflow, otherwise we'd want to add it the `Imports` field of the `DESCRIPTION` with `usethis::use_package('withr')`.
"
)
```
### Updated [`app.R`]{style="font-size: 0.90em"}
When we send the contents of `app.R` to the **Console**, the `loadSupport()` options are applied before running the app:
::: {.panel-tabset}
### RStudio ![](images/rstudio-icon.png){height=20}
![Sending `app.R` to RStudio's **Console**](images/launch_app_dot_r.png){width=100%}
### Positron ![](images/positron.png){height=20}
![Sending `app.R` to Positron's **Console**](images/launch_positron_app_dot_r.png){width=100%}
:::
```{r}
#| label: co_box_disable_autoload
#| echo: false
#| results: asis
#| eval: true
co_box(
color = "g",
look = "default", hsize = "1.10", size = "1.05",
fold = TRUE,
header = "`R/_disable_autoload.R`",
contents = "
In the documentation for `loadSupport()`, you'll find a second option for removing the `R/` directory sourcing behavior: placing a `_disable_autoload.R` file in the `R/` directory (this is also one of the behaviors of the [`golem` framework](https://github.com/ThinkR-open/golem/blob/365a5cc303b189973abab0dd375c64be79bcf74a/R/disable_autoload.R), which we will cover in the following chapters).
Both methods work--this chapter demonstrates a way to remove the `loadSupport()` warning without having to add this file.
"
)
```
## Recap {.unnumbered}
This chapter has covered some options for launching your app within your app-package. We went over what to include in the standalone app function and the `app.R` file, the differences between `shinyApp()`, `shinyAppDir()` and `runApp()`, but it's worth exploring these topics further (especially if you plan on having more than one apps in your package).
```{r}
#| label: co_box_app_recap
#| echo: false
#| results: asis
#| eval: true
co_box(
color = "g",
header = "Recap: launching your app",
look = "default", hsize = "1.10", size = "1.05",
fold = FALSE,
contents = "
**`shinyApp()`**:
- `shinyApp()` doesn't care about file structure, so it's useful for quick prototyping or if the app is in a single `.R` script. It's also more portable because you can share your app with a single `.R` script.
- It's possible to bundle `shinyApp()` in a wrapper function to integrate within an R package (like we've done with `launch_app()`).
- `shinyApp()` returns a shiny app object, which can be useful if you want to explore the app structure programmatically (i.e., testing).
**`shinyAppDir()`**:
- `shinyAppDir()` launches an app from a directory, and is useful if an app is spread across multiple files and folders.
**`runApp()`**
- `runApp()` a more generalized way to launch an app. It works with:
- apps contained in a directory (i.e., `runApp('path/to/app')`
- apps in separate `ui.R` and `server.R` files (or a single `app.R` file)
- a shiny app object (passed to the `appDir` argument).
- Clicking on **Run App** will run the application with `runApp()` if is detects a file (or files) that creates a shiny object.
"
)
```
In the following chapter, we're going to cover where to put non-standard R package files that are common to Shiny apps (`images`, `.css`/`.scss` file, etc.).
```{r}
#| label: git_contrib_box
#| echo: false
#| results: asis
#| eval: true
git_contrib_box()
```