-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdebug_apps.qmd
1163 lines (956 loc) · 32.5 KB
/
debug_apps.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
# Debugging apps {#sec-debug-apps}
```{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 = "{width='8%'}TLDR: Debugging apps",
fold = TRUE,
contents = "
"
)
```
In the previous chapters we demonstrated how to:
1. Wrapping the call to `browser()` in an `observe()` scope for interactive debugging
2. Capturing and printing reactive inputs in the UI with `reactiveValuesToList()`, `verbatimTextOutput()`, and `renderPrint()`
This chapter covers using abstract syntax trees to help understand the structure of an application's modules, and how to use the two previously described debugging methods to understand bugs and errors.
```{r}
#| label: shinypak_apps
#| echo: false
#| results: asis
#| eval: true
shinypak_apps(regex = "12", branch = "12.1_debug-mods")
```
## Abstract syntax trees {#sec-debug-apps-abstract-syntax-trees}
Shiny app-packages can quickly become a complex and intertwined web of functions: utility functions, modules, user interface (UI) elements, server logic, etc. Before we jump into debugging modules, we'll revisit their function and purpose by considering the following description of namespaces from the [`NS()` function documentation](https://shiny.posit.co/r/reference/shiny/latest/ns.html):
> "*a namespace is to an ID as a directory is to a file.*"
To visualize the hierarchical relationship between the functions in our app, we'll use abstract syntax trees (`ast()`) from the `lobstr` package.[^debug-lobstr]
[^debug-lobstr]: Create abstract syntax trees with the [`ast()` function](https://lobstr.r-lib.org/reference/ast.html) and read the *Code is a tree* section in [Advanced R, 2ed.](https://adv-r.hadley.nz/meta-big-picture.html#code-tree)
:::{layout="[50,50]" layout-valign="top"}
For example, `launch_app()` calls the `display_type()` utility function, then `movies_ui()` and `movies_server()`:
```{r}
#| eval: true
#| include: true
#| echo: false
lobstr::ast(
launch_app(
display_type(),
movies_ui(),
movies_server()
)
)
```
:::
:::{layout="[50,50]" layout-valign="top"}
`movies_ui()` and `movies_server()` call their respective UI and server module functions:
```{r}
#| eval: true
#| include: true
#| echo: false
lobstr::ast(
launch_app(
display_type(),
movies_ui(
mod_var_input_ui(),
mod_scatter_display_ui()
),
movies_server(
mod_var_input_server(),
mod_scatter_display_server()
)
)
)
```
:::
:::{layout="[50,50]" layout-valign="top"}
And `mod_scatter_display_server()` calls the `scatter_plot()` utility function:
```{r}
#| eval: true
#| include: true
#| echo: false
lobstr::ast(
launch_app(
display_type(),
movies_ui(
mod_var_input_ui(),
mod_scatter_display_ui()
),
movies_server(
mod_var_input_server(),
mod_scatter_display_server(
scatter_plot()
)
)
)
)
```
:::
Abstract folder trees can be used to help construct a simplified call stack for applications (especially if we are using multiple utility functions or nested modules).
## Debugging modules {#sec-debug-apps-modules}
In this branch of `sap`, the inputs has been split into two separate modules: variable inputs and aesthetic inputs. The variable input module collects and returns the selected columns from the `movies` data, and the aesthetics input module collects and returns the alpha, point size, and (optional) graph title.
This updates our abstract syntax tree to the following:
```{r}
#| eval: true
#| include: true
#| echo: false
lobstr::ast(
launch_app(
display_type(),
movies_ui(
mod_var_input_ui(),
mod_aes_input_ui(),
mod_scatter_display_ui()
),
movies_server(
mod_var_input_server(),
mod_aes_input_server(),
mod_scatter_display_server(
scatter_plot()
)
)
)
)
```
### Input modules {#sec-debug-apps-input-modules}
The diagram below illustrates the changes to the variable input module.
```{=html}
<style>
.codeStyle span:not(.nodeLabel) {
font-family: monospace;
font-size: 1.5em;
font-weight: bold;
color: #9753b8 !important;
background-color: #f6f6f6;
padding: 0.2em;
}
</style>
```
```{mermaid}
%%| fig-align: center
%%| fig-cap: 'Variable Inputs modules'
%%{init: {'theme': 'neutral', 'themeVariables': { 'fontFamily': 'monospace', "fontSize":"16px"}}}%%
flowchart TD
User(["User"])
mod_var_input_ui["<strong>mod_var_input_ui()</strong>"]
mod_aes_input_ui["<strong>mod_aes_input_ui()</strong>"]
subgraph mod_var_input_server["<strong>mod_var_input_server()</strong>"]
VarReactives[/"input$x<br>input$y<br>input$z"/]
end
subgraph mod_aes_input_server["<strong>mod_aes_input_server()</strong>"]
AesReactives[/"input$alpha<br>input$size<br>input$plot_title"/]
end
selected_vars[/"selected variables"/]
selected_aes[/"selected aesthetics"/]
User --> |"<em>Selects X, Y, and Color...</em>"|mod_var_input_ui
User --> |"<em>Selects Size, Alpha and optional Title...</em>"|mod_aes_input_ui
mod_var_input_ui --> |"<em>Collects<br>variables...</em>"|mod_var_input_server
mod_aes_input_ui --> |"<em>Collects aesthetics...</em>"|mod_aes_input_server
VarReactives --> selected_vars
AesReactives --> selected_aes
style mod_var_input_ui stroke-width:2px,rx:3,ry:3
style mod_aes_input_ui stroke-width:2px,rx:3,ry:3
style mod_var_input_server stroke-width:2px,rx:3,ry:3
style mod_aes_input_server stroke-width:2px,rx:3,ry:3
style VarReactives font-size: 14px
style AesReactives font-size: 14px
```
**`mod_var_input_ui()`**: Our variable input module will now only collect the x, y, and color variables from the `movies` data.
```{r}
#| eval: false
#| code-fold: show
#| code-summary: 'show/hide R/mod_var_input.R'
mod_var_input_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"
)
)
}
mod_var_input_server <- function(id) {
moduleServer(id, function(input, output, session) {
return(
reactive({
list(
"y" = input$y, # <1>
"x" = input$x, # <2>
"z" = input$z # <3>
)
})
)
})
}
```
1. Returned x axis variable
2. Returned y axis variable
3. Returned color variable
**`mod_aes_input_ui()`**: The new aesthetic input module will collect the alpha, size, and optional plot title values.
```{r}
#| eval: false
#| code-fold: show
#| code-summary: 'show/hide R/mod_aes_input.R'
mod_aes_input_ui <- function(id) {
ns <- NS(id)
tagList(
sliderInput(
inputId = ns("alpha"),
label = "Alpha:",
min = 0, max = 1, step = 0.1,
value = 0.5
),
sliderInput(
inputId = ns("size"),
label = "Size:",
min = 0, max = 5,
value = 2
),
textInput(
inputId = ns("x"),
label = "Plot title",
placeholder = "Enter plot title"
)
)
}
mod_aes_input_server <- function(id) {
moduleServer(id, function(input, output, session) {
return(
reactive({
list(
"alpha" = input$alpha, # <1>
"size" = input$size, # <2>
"plot_title" = input$x # <3>
)
})
)
})
}
```
1. Returned alpha aesthetic
2. Returned size aesthetic
3. Returned plot title
Each module will have a dedicated namespace inside the `movies_ui()` and `movies_server()` functions, but this requires a minor adjustment to the `mod_scatter_display_server()` and `movies_server()` functions:
**`mod_scatter_display_server()`**: We need to adjust the function arguments and the creation of the `inputs()` reactive:
```{r}
#| eval: false
#| code-fold: show
#| code-summary: 'show/hide mod_scatter_display_server()'
mod_scatter_display_server <- function(id, var_inputs, aes_inputs) { # <1>
moduleServer(id, function(input, output, session) {
inputs <- reactive({
plot_title <- tools::toTitleCase(aes_inputs()$plot_title) # <2>
list(
x = var_inputs()$x, # <4>
y = var_inputs()$y,
z = var_inputs()$z, # <4>
alpha = aes_inputs()$alpha, # <3>
size = aes_inputs()$size,
plot_title = plot_title # <3>
)
})
output$scatterplot <- renderPlot({
plot <- scatter_plot(
# data --------------------
df = movies,
x_var = inputs()$x,
y_var = inputs()$y,
col_var = inputs()$z,
alpha_var = inputs()$alpha,
size_var = inputs()$size
)
plot +
ggplot2::labs(
title = inputs()$plot_title,
x = stringr::str_replace_all(tools::toTitleCase(inputs()$x), "_", " "),
y = stringr::str_replace_all(tools::toTitleCase(inputs()$y), "_", " ")
) +
ggplot2::theme_minimal() +
ggplot2::theme(legend.position = "bottom")
})
})
}
```
1. Add function argument for aesthetics
2. Optional title input
3. Alpha and size inputs
4. Variable reactive inputs
**`movies_server()`**: We now have two reactive variables: the `selected_vars` and `selected_aes`:
```{r}
movies_server <- function(input, output, session) {
selected_vars <- mod_var_input_server("vars") # <1>
selected_aes <- mod_aes_input_server("aes") # <2>
mod_scatter_display_server("plot",
var_inputs = selected_vars, # <3>
aes_inputs = selected_aes) # <4>
}
```
1. Collected variable inputs
2. Collected aesthetic inputs
3. Variable input argument for graph display
4. Aesthetic input argument for graph display
The diagram below illustrates the changes to the functions above:
```{=html}
<style>
.codeStyle span:not(.nodeLabel) {
font-family: monospace;
font-size: 1.5em;
font-weight: bold;
color: #9753b8 !important;
background-color: #f6f6f6;
padding: 0.2em;
}
</style>
```
```{mermaid}
%%| fig-align: center
%%| fig-cap: 'Variable and aesthetic input modules'
%%{init: {'theme': 'neutral', 'themeVariables': { 'fontFamily': 'monospace', "fontSize":"16px"}}}%%
flowchart TD
User(["User"])
mod_var_input_ui["<strong>mod_var_input_ui()</strong>"]
mod_aes_input_ui["<strong>mod_aes_input_ui()</strong>"]
mod_scatter_display_ui["<strong>mod_scatter_display_ui</strong>"]
subgraph mod_scatter_display_server["<strong>mod_scatter_display_server()</strong>"]
var_inputs[\"var_inputs"\]
aes_inputs[\"aes_inputs"\]
inputs[/"inputs()"/]
scatter_plot("scatter_plot()")
end
subgraph mod_var_input_server["<strong>mod_var_input_server()</strong>"]
VarReactives[/"input$x<br>input$y<br>input$z"/]
end
subgraph mod_aes_input_server["<strong>mod_aes_input_server()</strong>"]
AesReactives[/"input$alpha<br>input$size<br>input$plot_title"/]
end
selected_vars[/"selected variables"/]
selected_aes[/"selected aesthetics"/]
User --> |"<em>Selects X, Y, and Color...</em>"|mod_var_input_ui
User --> |"<em>Selects Size, Alpha and optional Title...</em>"|mod_aes_input_ui
mod_var_input_ui --> |"<em>Collects<br>variables...</em>"|mod_var_input_server
mod_aes_input_ui --> |"<em>Collects aesthetics...</em>"|mod_aes_input_server
VarReactives --> selected_vars
AesReactives --> selected_aes
selected_vars -->|"<em>Input argument for...</em>"|var_inputs
selected_aes -->|"<em>Input argument for...</em>"|aes_inputs
var_inputs & aes_inputs --> inputs --> scatter_plot
scatter_plot -->|"<em>Renders plot...</em>"|mod_scatter_display_ui
mod_scatter_display_ui -->|"<em>Displays output...</em>"|Display(["Graph"])
style mod_scatter_display_ui font-size:12px,stroke-width:2px,rx:3,ry:3
style mod_scatter_display_server font-size:12px,stroke-width:2px,rx:3,ry:3
style mod_var_input_server font-size:13px,stroke-width:2px,rx:3,ry:3
style mod_var_input_ui font-size:13px,stroke-width:2px,rx:3,ry:3
style mod_aes_input_server font-size:13px,stroke-width:2px,rx:3,ry:3
style mod_aes_input_ui font-size:13px,stroke-width:2px,rx:3,ry:3
style scatter_plot stroke-width:2px,rx:10,ry:10
style VarReactives font-size: 14px
style AesReactives font-size: 14px
```
Uncoupling the input modules will make it easier to independently modify and debug their corresponding graph elements.
## UI function debugging {#sec-debug-ui}
In [`mod_var_input_ui()`](https://github.com/mjfrigaard/sap/blob/12.1_debug-mods/R/mod_var_input.R) and [`mod_aes_input_ui()`](https://github.com/mjfrigaard/sap/blob/12.1_debug-mods/R/mod_aes_input.R), the `NS()` function is used to encapsulate input IDs within a namespace.
We will place a `verbatimTextOutput()` in both UI module functions:[^review-chp-11]
```{r}
#| eval: false
#| code-fold: false
mod_var_input_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"
),
strong( #<1>
code("var_input"),
"module reactive ",
code("inputs")
), #<1>
verbatimTextOutput(ns("vals")) #<2>
)
}
```
1. Optional label
2. Include the `ns()` for the `inputId`
```{r}
#| eval: false
#| code-fold: false
mod_aes_input_ui <- function(id) {
ns <- NS(id)
tagList(
sliderInput(
inputId = ns("alpha"),
label = "Alpha:",
min = 0, max = 1, step = 0.1,
value = 0.5
),
sliderInput(
inputId = ns("size"),
label = "Size:",
min = 0, max = 5,
value = 2
),
textInput(
inputId = ns("x"),
label = "Plot title",
placeholder = "Enter plot title"
),
strong( #<1>
code("aes_input"),
"module reactive ",
code("inputs")
), #<1>
verbatimTextOutput(ns("vals")) #<2>
)
}
```
1. Optional label
2. Include the `ns()` for the `inputId`
## Server function debugging {#sec-debug-server}
In the corresponding server functions, we'll capture the reactive values and print the list using `lobstr::tree()`:[^review-chp-11]
[^review-chp-11]: We covered using `reactiveValuesToList()`, `renderPrint()` and `verbatimTextOutput()` in @sec-print-debug-reactive-values-to-list.
```{r}
#| eval: false
#| code-fold: false
mod_var_input_server <- function(id) {
moduleServer(id, function(input, output, session) {
observe({
output$vals <- renderPrint({ #<2>
all_vals <- reactiveValuesToList(input, #<1>
all.names = TRUE) #<3>
lobstr::tree(all_vals) #<4>
})
}) |>
bindEvent(c(input$x, input$y, input$x)) #<5>
return(
reactive({
list(
"y" = input$y,
"x" = input$x,
"z" = input$z
)
})
)
})
}
```
1. Collect reactive values in module
2. Print these values to the UI
3. Include all reactive objects
4. Visualize using `lobstr::tree()`
5. Bind to inputs
```{r}
#| eval: false
#| code-fold: false
mod_aes_input_server <- function(id) {
moduleServer(id, function(input, output, session) {
observe({
output$vals <- renderPrint({ #<2>
all_vals <- reactiveValuesToList(input, #<1>
all.names = TRUE) #<3>
lobstr::tree(all_vals) #<4>
})
}) |>
bindEvent(c(input$alpha, input$size, input$x)) #<5>
return(
reactive({
list(
"alpha" = input$alpha,
"size" = input$size,
"plot_title" = input$x
)
})
)
})
}
```
1. Collect reactive values in module
2. Print these values to the UI
3. Include all reactive objects
4. Visualize using `lobstr::tree()`
5. Bind to inputs
We see the following in the sidebar after loading, documenting, installing and launching our app;
```{r}
#| label: hot_key_01
#| echo: false
#| results: asis
#| eval: true
hot_key(fun = "all")
```
:::{layout="[50,50]" layout-valign="top"}
Reactive values for the variable input module:
{fig-align='center'}
:::
:::{layout="[50,50]" layout-valign="top"}
Reactive values for the aesthetic input module:
{fig-align='center'}
:::
In the variable and aesthetic module namespaces, `NS()` ensures all the inputs are unique *within the module* (even when multiple modules are used in the same application).
```{bash}
#| eval: false
#| code-fold: false
<list>
├─y: "audience_score"
├─x: "imdb_rating"
└─z: "mpaa_rating"
```
You probably noticed that I've renamed the `inputId` for the plot title to `x`, but we avoid any namespace collisions because each ID is stored safely within a module.
```{bash}
#| eval: false
#| code-fold: false
<list>
├─alpha: 0.5
├─size: 2
└─x: ""
```
**This encapsulation is similar to how a directory provides a distinct context for files, preventing naming conflicts within a file system.**
If we repeat this method in [`movies_ui()`](https://github.com/mjfrigaard/sap/blob/12_debug-apps/R/movies_ui.R) and [`movies_server()`](https://github.com/mjfrigaard/sap/blob/12_debug-apps/R/movies_server.R):
```{r}
#| eval: false
#| code-fold: show
#| code-summary: 'show/hide movies_ui()'
movies_ui <- function(bslib = FALSE) {
addResourcePath(
prefix = 'www',
directoryPath = system.file('www/', package = 'sap'))
if (isFALSE(bslib)) {
tagList(
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"),
mod_aes_input_ui("aes")
),
bslib::card(
full_screen = TRUE,
bslib::card_header(
tags$h4("Scatter Plot")
),
bslib::card_body(fillable = TRUE,
strong( # <1>
code("movies_server()"),
"reactive values"
), # <1>
verbatimTextOutput(outputId = "vals"), # <1>
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"
)
)
)
)
)
)
)
)
} else {
tagList(
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(
mod_var_input_ui("vars"),
mod_aes_input_ui("aes")
),
bslib::card(
full_screen = TRUE,
bslib::card_header(
tags$img(
src = "www/bootstrap.png",
height = 80,
width = 100,
style = "margin:10px 10px"
)
),
bslib::card_body(
strong( # <2>
code("movies_server()"),
"reactive values"
),
verbatimTextOutput(outputId = "vals"), # <2>
mod_scatter_display_ui("plot")
)
)
)
)
)
}
}
```
1. Label and output for printed reactive values
2. Label and output for printed reactive values (`bslib` UI option)
```{r}
#| eval: false
#| code-fold: show
#| code-summary: 'show/hide movies_server()'
movies_server <- function(input, output, session) {
output$vals <- renderPrint({ #<2>
app_vals <- reactiveValuesToList(x = input, #<1>
all.names = TRUE) #<1>
lobstr::tree(app_vals) #<3>
})
selected_vars <- mod_var_input_server("vars")
selected_aes <- mod_aes_input_server("aes")
mod_scatter_display_server("plot",
var_inputs = selected_vars,
aes_inputs = selected_aes)
}
```
1. Capture reactive values
2. Render reactive values
3. Print list as folder tree
Load the package and run the app:
```{r}
#| label: hot_key_02
#| echo: false
#| results: asis
#| eval: true
hot_key(fun = "all")
```
The printed output from `movies_ui()` and` movies_server()` is prefixed with the namespace (i.e., `vars-` or `aes-`), reflecting the hierarchical organization of the input IDs, **much like file paths in a directory structure**.
{width='100%' fig-align='center'}
By using `reactiveValuesToList()` and `lobstr::tree()` in combination with `verbatimTextOutput()` and `renderPrint()`, we are effectively debugging and inspecting the module’s reactive inputs.
```{bash}
#| eval: false
#| code-fold: false
<list>
├─vars-y: "audience_score"
├─vars-x: "imdb_rating"
├─vars-z: "mpaa_rating"
├─aes-alpha: 0.5
├─aes-size: 2
└─aes-x: ""
```
Capturing and rendering reactive values in the UI gives us the benefits of print debugging while our Shiny app is running. When it's combined with `observe()` and `browser()`, we can get a direct view of the application state and the program flow at specific execution points.
```{r}
#| label: git_box_12.1
#| echo: false
#| results: asis
#| eval: true
git_margin_box(
contents = "launch",
fig_pw = '65%',
branch = "12.1_debug-mods",
repo = 'sap')
```
## Module communication {#sec-debug-apps-module-comms}
When we load, document, install and view the application in this branch we find an error with the graph display:
{width='100%' fig-align='center'}
The call stack (printed to the **Console**) displays the following information:
```{bash}
#| eval: false
#| code-fold: false
Warning: Error in tools::toTitleCase: 'text' must be a character vector
208: stop
207: tools::toTitleCase
206: <reactive>
204: .func
201: contextFunc
200: env$runWith
189: ctx$run
188: self$.updateValue
186: inputs
178: renderPlot
176: func
136: drawPlot
122: <reactive:plotObj>
102: drawReactive
89: renderFunc
88: output$plot-scatterplot
3: runApp
2: print.shiny.appobj
1: <Anonymous>
```
The output in the **Console** is helpful (we know the error is coming from the `tools::toTitleCase()` function), but we need to narrow it down because we're using this function in multiple places.
To use the interactive debugger, we'll add `browser()` and `observe()` in the `movies_server()` function to capture the behaviors of both the variables and aesthetics modules:
```{r}
#| eval: false
#| code-fold: false
movies_server <- function(input, output, session) {
output$vals <- renderPrint({
app_vals <- reactiveValuesToList(x = input, all.names = TRUE)
lobstr::tree(app_vals)
})
observe({ #<1>
browser() #<2>
selected_vars <- mod_var_input_server("vars")
selected_aes <- mod_aes_input_server("aes")
mod_scatter_display_server("plot",
var_inputs = selected_vars,
aes_inputs = selected_aes)
}) #<1>
}
```
1. Observer scope
2. Activate debugger
Then we'll load, document, install and launch the app:
```{r}
#| label: hot_key_03
#| echo: false
#| results: asis
#| eval: true
hot_key(fun = "all")
```
The application launches, but `browser()` pauses the execution of the modules and activates the IDE's debugger. This allows us to view the objects that are available in `movies_server()` *before* the variables are passed to the graph rendering functions.
We'll proceed with the interactive debugger until both `selected_vars` and `selected_aes` are returned from the input modules:
```{r}
#| eval: false
#| code-fold: false
Browse[1]> n
Browse[1]> n
Browse[1]> n
```
{width='100%' fig-align='center'}
This tells us both objects are returned from their respective module server functions. But we should pause and examine the structure of `selected_aes`:
```{r}
#| eval: false
#| code-fold: false
Browse[1]> str(selected_aes)
```
```{verbatim}
#| code-fold: false
function ()
- attr(*, "observable")=Classes 'Observable', 'R6' reactive({
list(alpha = input$alpha, size = input$size, plot_title = input$x)
})
- attr(*, "cacheHint")=List of 1
..$ userExpr: language { list(alpha = input$alpha, size = input$size,
plot_title = input$x) }
- attr(*, "class")= chr [1:3] "reactiveExpr" "reactive" "function"
```
The output above display `selected_vars` the **method**, not the selected input values. To view these, we need to include the parentheses:
```{r}
#| eval: false
#| code-fold: false
Browse[1]> str(selected_aes())
```
```{verbatim}
#| code-fold: false
List of 3
$ alpha : num 0.5
$ size : int 2
$ plot_title: chr ""
```
This confirms that the UI values are being collected by the aesthetic input module and stored in `selected_aes`, so the error must be coming from inside one of the modules.
:::{layout="[50,50]" layout-valign="top"}
*We've inspected the values in the exchange between `movies_ui()` and `movies_server()`*:
```{r}
#| eval: true
#| include: true
#| echo: false
lobstr::ast(
launch_app(