-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path03-user-interface.qmd
898 lines (621 loc) · 27.9 KB
/
03-user-interface.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
---
title: "User Interface (UI): Designing the front end"
---
- Learning outcomes:
- Understand logic underlying user interfaces in Shiny
- Learn how to create UIs using different layouts, inputs and outputs
- Become familiar with various UI widgets
- Create the foundations for reactive plots, tables, and maps
Source(s): @wickham2021mastering [Ch. 2]
```{r 03-user-interface-1, message=FALSE, warning=FALSE, include=FALSE}
# namer::unname_chunks("03-user-interface.qmd")
# namer::name_chunks("03-user-interface.qmd")
# install.packages("pacman)
pacman::p_load(knitr, quarto)
```
## Basics
- Shiny encourages separation of code that generates **UI (*front end*)** from code that drives **app's behaviour (*server/back end*)**.
- Here focus on front end & tour of Shiny inputs and outputs
- won't stitch inputs and outputs together yet
- primary focus on native Shiny components (contained in `Shiny` package) but vibrant community (see [awesome shiny extenstions](https://github.com/nanxstats/awesome-shiny-extensions))

## UI: Layout
- Any Shiny app consists of `ui`, `server` and `shinyApp(ui=ui, server = server)`
- `ui <- function()`: function is used to create UI
- UI then displays different inputs and outputs
- Shiny provides different functions that can be used to create basic layouts
- `fluidPage()` creates the classic fluid page layout
### fluidPage (1)
- `fluidPage()`: Creates most basic layout
- display that automatically adjusts to user's browser dimensions (smartphone!)
- layout consists of rows containing columns
- rows making sure elements appear on the same line
- columns define usage of horizontal space (within a **12-unit wide grid**)
- **UI with title panel and sidebar panel**
+ `titlePanel()` and `sidebarLayout()` create a basic Shiny app/layout with a sidebar
+ `sidebarLayout()` takes two functions
+ `sidebarPanel()`: Includes content displayed in the sidebar
+ `mainPanel()`: Includes content displayed in the main panel
+ `fluidRow()` and `column()`: Divide ui into rows/columns
* **Try code below** by pasting it into your console and running it
```{r 03-user-interface-2, cache=TRUE, eval=FALSE, include=TRUE}
#| code-fold: true
#| code-summary: "Code: Creating a simple UI"
ui <- fluidPage(
titlePanel("This is the title panel"),
sidebarLayout(
sidebarPanel( "Title: Sidebar panel"),
mainPanel("Title: Main panel",
fluidRow(
column(width = 4,"Column 1: Description here"),
column(width = 4, "Column 2: Model summary")
,
column(width = 3,
offset = 1,
"Column 3: Model visualization")
)
)))
server <- function(input, output, session){}
shinyApp(ui=ui, server = server)
```
### fluidPage (2)
- Change `sidebarLayout(position = "right",...)` to position sidebar on the right
- Sometimes adding borders helps to understand the UI
```{r 03-user-interface-2-3, cache=TRUE, eval=FALSE, include=TRUE}
#| code-fold: true
#| code-summary: "Code: Adding borders for better understanding of UI"
ui <- fluidPage(
titlePanel("This is the title panel"),
sidebarLayout(
sidebarPanel( "Title: Sidebar panel"),
mainPanel("Title: Main panel",
fluidRow(
column(style='border: 1px solid black',
width = 4,"
Column 1: Description here"),
column(style='border: 1px solid black',
width = 4, "Column 2: Model summary")
,
column(style='border: 1px solid black',
width = 3,
offset = 1,
"Column 3: Model visualization")
)
)))
server <- function(input, output, session){}
shinyApp(ui=ui, server = server)
```
### fluidPage (3): Creating panels and tabs
* `tabsetPanel()` + `tabPanel()`
+ Allows for using sidebar layout but dividing main panel into tabs
+ Users can switch between tabs that show different outputs
```{r 03-user-interface-3, cache=TRUE, eval=FALSE, include=TRUE}
ui <- fluidPage(
titlePanel("This is the title panel"),
sidebarLayout(
sidebarPanel( "This is the sidebar panel"),
mainPanel(
tabsetPanel(type = "tabs",
tabPanel("3d Frequency Plot",
"Tab 1: plot here"),
tabPanel("Histogram",
"Tab 2: another plot here"),
tabPanel("Model Summary",
h4("Tab 3: estimation results here")),
tabPanel("Data Summary",
h4("Tab 4: Variable summaries"))
))))
server <- function(input, output, session){}
shinyApp(ui=ui, server = server)
```
### Images {#sec-dashboardPage3}
* `img()` function places an image
- `img(src = "http://.../img-2.jpg", height = 35, width = 35)`: Load image from website or folder
* Store image(s) locally
+ `www` subfolder stores all sorts of additional files(images, data etc.)
+ If working directory = app directory create with: `dir.create("www")`
+ **Images place in folder `www` can be referenced without the `www` folder name/path**
+ e.g., `img(src = "guerry.jpg", width = "100%")`
```{r 03-user-interface-6, cache=TRUE, eval=FALSE, include=TRUE}
#| code-fold: true
#| code-summary: "Code: Adding images"
ui <- fluidPage(
titlePanel(span(img(src = "https://www.gesis.org/typo3conf/ext/gesis_web_ext/Resources/Public/webpack/dist/img/logo_gesis_en.svg", style = "height: 1.4em;"), "The ESS shiny app")),
sidebarLayout(
sidebarPanel( "This is the sidebar panel"),
mainPanel(
tabsetPanel(type = "tabs",
tabPanel("An image",
img(src = "https://journals.openedition.org/belgeo/docannexe/image/11893/img-1.jpg", width = 358, height = 476))
))))
server <- function(input, output, session){}
shinyApp(ui=ui, server = server)
```
### Exercise: UI layout
1. Familiarize yourself and use the code in @sec-dashboardPage3.
2. Change the website title to "A big name in politics"
3. Change the sidebar menu title with "The Arni Shiny App".
4. Replace the image of Guerry with an image Arnold Schwarzenegger from the web, e.g., [here](http://assets.schwarzenegger.com/images/img-2.jpg).
- Either store the image in a `www` subfolder of your app directory or use the URL in your code.
::: {.callout-warning collapse="true"}
#### Solution: Using image from link
```{r 03-user-interface-7-5, echo=TRUE, eval=FALSE, include=TRUE}
ui <- fluidPage(
titlePanel(span(img(src = "https://www.gesis.org/typo3conf/ext/gesis_web_ext/Resources/Public/webpack/dist/img/logo_gesis_en.svg", style = "height: 1.4em;"), "A big name in politics")),
sidebarLayout(
sidebarPanel( "The Arni Shiny App"),
mainPanel(
tabsetPanel(type = "tabs",
tabPanel("An image",
img(src = "http://assets.schwarzenegger.com/images/img-2.jpg",
width = 729, height = 423))
))))
server <- function(input, output, session){}
shinyApp(ui=ui, server = server)
```
:::
::: {.callout-warning collapse="true"}
#### Solution: Using image from www folder
1. Check the directory you are in with `getwd()`.
2. Make sure the `app.R` file you are using is saved in this directory.
3. Use `dir.create("www")` or the buttons in Rstudio to create the `www` folder.
4. Store the image from the [link](http://assets.schwarzenegger.com/images/img-2.jpg) in this `www` folder.
5. Add the image name simply in the code `img(src = "img-2.jpg", width = 729, height = 423)` (see below).
- **IMAGES PLACED UNDER `www` CAN BE REFERENCED WITHOUT THE `www` FOLDER NAME**
6. Run the app.
```{r 03-user-interface-7, echo=TRUE, eval=FALSE, include=TRUE}
ui <- fluidPage(
titlePanel(span(img(src = "https://www.gesis.org/typo3conf/ext/gesis_web_ext/Resources/Public/webpack/dist/img/logo_gesis_en.svg", style = "height: 1.4em;"), "A big name in politics")),
sidebarLayout(
sidebarPanel( "The Arni Shiny App"),
mainPanel(
tabsetPanel(type = "tabs",
tabPanel("An image",
img(src = "img-2.jpg",
width = 729, height = 423))
))))
server <- function(input, output, session){}
shinyApp(ui=ui, server = server)
```
:::
## UI: Inputs
### UI Inputs: common structure
- `textInput(inputId = "username", label = "Enter your username", value = "Write here")`
- `inputId` connects front end with back end, e.g., if UI has input with ID `name`, the server function will access it with `input$name`
- name` = **simple string** (only letters, numbers, and underscores) and **unique**
- `label` argument: Used to create human-readable label
- `value` argument: usually let's you set default value
- Inputs are stored in list called `input$...`
- Remaining 4+ arguments are unique to the particular input
- Recommendation: Supply `inputId` and `label` arguments by position, and all other arguments by name
- Q: How would we read the following?
- `sliderInput("min", "Limit (minimum)", value = 50, min = 0, max = 100)`
### UI Inputs: Logic
- Widget = Web element the user can interact with ([Shiny widget gallery](https://shiny.posit.co/r/gallery/widgets/widget-gallery/))
- Users can send messages to the SERVER/Computer (e.g. "I want to choose this variable")
* Underlying logic is the same for all widgets
- User uses widget to give input
- Input is inserted into the functions in the SERVER
- `server <- function(input, output, session) {}`
* `shiny` package contains many widgets
- Additional ones in other packages (e.g., `pickerInput()` in `shinyWidgets` package)
### UI Inputs: Exercise
- Read the code below. Can you guess what kind of inputs the various input functions create?
```{r 03-user-interface-9, cache=TRUE, eval=FALSE, include=TRUE}
library(shinyWidgets) # Install!
animals <- c("dog", "cat", "mouse") # Predefining some categories
ui <- fluidPage(
# Free text
textInput("name", "What's your name?"),
passwordInput("password", "What's your password?"),
textAreaInput("story", "Tell me about yourself", rows = 3),
# Numeric inputs
numericInput("num", "Number one", value = 0, min = 0, max = 100),
sliderInput("num2", "Number two", value = 50, min = 0, max = 100),
sliderInput("rng", "Range", value = c(10, 20), min = 0, max = 100),
# Dates
dateInput("dob", "When were you born?"),
dateRangeInput("holiday", "When do you want to go on vacation next?"),
# Limited choices
selectInput("state", "What's your favourite animal?", animals),
radioButtons("animal", "What's your favourite animal?", animals),
selectInput( "state", "What's your favourite animal?", animals, multiple = TRUE),
checkboxGroupInput("animal2", "What animals do you like?", animals),
pickerInput(
inputId = "animal3",
label = "What animals do you like?",
choices = animals
),
# Single checkbox
checkboxInput("cleanup", "Clean up?", value = TRUE),
checkboxInput("shutdown", "Shutdown?"),
# File uploads
fileInput("upload", NULL),
# Action buttons
actionButton("click", "Click me!"),
actionButton("drink", "Drink me!", icon = icon("cocktail"))
)
server <- function(input, output, session) {}
shinyApp(ui, server)
```
* Now try to run the code within Rstudio and take a look at the app itself!
### Additional exercise(s)
* See [Exercises 2.2.8](https://mastering-shiny.org/basic-ui.html#exercises-2).
1. When space is at a premium, it's useful to label text boxes using a placeholder that appears *inside* the text entry area.
How do you call `textInput()` to generate the UI in @fig-textInput below (see `?textInput`)?
{#fig-textInput width=100%}
::: {.callout-warning collapse="true"}
#### Solution
```{r 03-user-interface-10, echo = TRUE, out.width = NULL, message = FALSE, eval=FALSE}
textInput("text", "", placeholder = "Your name")
```
:::
2. Carefully read the documentation for `sliderInput()` to figure out how to create a date slider, as shown below in @fig-date-slider.
{#fig-date-slider width=100%}
::: {.callout-warning collapse="true"}
#### Solution
```{r 03-user-interface-11-3, eval=FALSE, echo = TRUE, out.width = NULL, message = FALSE}
sliderInput(
"dates",
"When should we deliver?",
min = as.Date("2019-08-09"),
max = as.Date("2019-08-16"),
value = as.Date("2019-08-10")
)
```
:::
3. Create a slider input to select values between 0 and 100 where the interval between each select able value on the slider is 5.
Then, add animation to the input widget so when the user presses play the input widget scrolls through the range automatically.
::: {.callout-warning collapse="true"}
#### Solution
```{r 03-user-interface-11-5, eval=FALSE, echo = TRUE, out.width = NULL, message = FALSE}
sliderInput("number", "Select a number:",
min = 0, max = 100, value = 0,
step = 5, animate = TRUE)
```
:::
4. If you have a moderately long list in a `selectInput()`, it's useful to create sub-headings that break the list up into pieces.
Read the documentation to figure out how. (Hint: the underlying HTML is called `<optgroup>`.)
::: {.callout-warning collapse="true"}
#### Solution
```{r 03-user-interface-11-4, eval=FALSE, echo = TRUE, out.width = NULL, message = FALSE}
selectInput(
"breed",
"Select your favorite animal breed:",
choices =
list(`dogs` = list('German Shepherd', 'Bulldog',
'Labrador Retriever'),
`cats` = list('Persian cat', 'Bengal cat',
'Siamese Cat'))
)
```
:::
::: {.callout-warning collapse="true"}
#### Solution: One app with all the widgets
```{r 03-user-interface-11-4-4-2, eval=FALSE, echo = TRUE}
ui <- fluidPage(
textInput("text", "", placeholder = "Your name"),
sliderInput(
"dates",
"When should we deliver?",
min = as.Date("2019-08-09"),
max = as.Date("2019-08-16"),
value = as.Date("2019-08-10")
),
sliderInput("number", "Select a number:",
min = 0, max = 100, value = 0,
step = 5, animate = TRUE),
selectInput(
"breed",
"Select your favorite animal breed:",
choices =
list(`dogs` = list('German Shepherd', 'Bulldog',
'Labrador Retriever'),
`cats` = list('Persian cat', 'Bengal cat',
'Siamese Cat'))
)
)
server <- function(input, output, session) {
}
shinyApp(ui, server)
```
:::
::: {.callout-warning collapse="true"}
#### Solution: App that displays the input values
- Solution taken from [stackoverflow](https://stackoverflow.com/a/41035132).
```{r 03-user-interface-11-4-4-2-1, eval=FALSE, echo = TRUE}
#rm(list=ls())
library(shiny)
ui <- basicPage(
textInput("text", "", placeholder = "Your name"),
sliderInput(
"dates",
"When should we deliver?",
min = as.Date("2019-08-09"),
max = as.Date("2019-08-16"),
value = as.Date("2019-08-10")
),
sliderInput("number", "Select a number:",
min = 0, max = 100, value = 0,
step = 5, animate = TRUE),
selectInput(
"breed",
"Select your favorite animal breed:",
choices =
list(`dogs` = list('German Shepherd', 'Bulldog',
'Labrador Retriever'),
`cats` = list('Persian cat', 'Bengal cat',
'Siamese Cat'))),
tableOutput('show_inputs')
)
server <- shinyServer(function(input, output, session){
AllInputs <- reactive({
myvalues <- NULL
for(i in 1:length(names(input))){
myvalues <- as.data.frame(rbind(myvalues,(cbind(names(input)[i],input[[names(input)[i]]]))))
}
names(myvalues) <- c("User Input","Last Value")
myvalues
})
output$show_inputs <- renderTable({
AllInputs()
})
})
shinyApp(ui = ui, server = server)
```
:::
## UI: Outputs
- Outputs in UI create placeholders that are later filled by the server function
- Have unique ID as first argument like inputs
- e.g., `textOutput("text")` as ID `text` that is filled by the server
- If UI specification creates an output with ID `text`, you'll access it in the server function with `output$text` (see below)
- Each output function on the front end is coupled with a **render function** in the back end (server)
- Three main types of output: **text**, **tables**, and **plots**
### Text output
* Below an example for text output
```{r 03-user-interface-12, cache=TRUE, eval=FALSE, include=TRUE}
ui <- fluidPage(
textOutput("text"),
verbatimTextOutput("code")
)
server <- function(input, output, session) {
output$text <- renderText({
"Hello friend!"
})
output$code <- renderPrint({
summary(1:10)
})
}
shinyApp(ui, server)
```
### Table output
* Below an example for table output
```{r 03-user-interface-14, cache=TRUE, eval=FALSE, include=TRUE}
ui <- fluidPage(
tableOutput("static"),
dataTableOutput("dynamic")
)
server <- function(input, output, session) {
output$static <- renderTable(head(mtcars))
output$dynamic <- renderDataTable(mtcars, options = list(pageLength = 5))
}
shinyApp(ui, server)
```
### Plot output
* Below an example for plot output
```{r 03-user-interface-15, cache=TRUE, eval=FALSE, include=TRUE}
ui <- fluidPage(
plotOutput("plot", width = "400px")
)
server <- function(input, output, session) {
output$plot <- renderPlot(plot(1:5), res = 96)
}
shinyApp(ui, server)
```
### Exercise(s)
* Taken from [Exercises 2.3.5](https://mastering-shiny.org/basic-ui.html#exercises-2).
1. Which of `textOutput()` and `verbatimTextOutput()` should each of the following render functions be paired with?
a. `renderPrint(summary(mtcars))`
b. `renderText("Good morning!")`
c. `renderPrint(t.test(1:5, 2:6))`
d. `renderPrint(str(lm(mpg ~ wt, data = mtcars)))`
::: {.callout-warning collapse="true"}
#### Solution
```{r 03-user-interface-11-4-4-3, eval=FALSE, echo = TRUE}
ui <- fluidPage(
verbatimTextOutput("mtcarsout1"),
br(), hr(),
textOutput("mtcarsout2"),
br(), hr(),
verbatimTextOutput("mtcarsout3"),
br(), hr(),
verbatimTextOutput("mtcarsout4")
)
server <- function(input, output, session) {
output$mtcarsout1 <- renderPrint(summary(mtcars))
output$mtcarsout2 <- renderText("Good morning!")
output$mtcarsout3 <- renderPrint(t.test(1:5, 2:6))
output$mtcarsout4 <- renderPrint(str(lm(mpg ~ wt, data = mtcars)))
}
shinyApp(ui, server)
```
:::
2. Update the options in the call to `renderDataTable()` below so that the data is displayed, but all other controls are suppress (i.e. remove the search, ordering, and filtering commands).
You'll need to read `?renderDataTable` and review the options at <https://shiny.posit.co/r/gallery/widgets/datatables-options/> by checking the code (or <https://datatables.net/reference/option/>).
```{r 03-user-interface-16, eval=FALSE}
ui <- fluidPage(
dataTableOutput("table")
)
server <- function(input, output, session) {
output$table <- renderDataTable(mtcars, options = list(pageLength = 5))
}
shinyApp(ui, server)
```
::: {.callout-warning collapse="true"}
#### Solution
```{r 03-user-interface-11-4-4, eval=FALSE, echo = TRUE}
ui <- fluidPage(
dataTableOutput("table")
)
server <- function(input, output, session) {
output$table <- renderDataTable(mtcars,
options = list(pageLength = 5,
searching = FALSE,
paging = FALSE,
ordering = FALSE,
filtering = FALSE))
}
shinyApp(ui, server)
```
:::
### Overview of Output functions
* Output functions
+ `htmlOutput()`... creates raw HTML
+ `imageOutput()`... creates image
+ `plotOutput()`... creates plot
+ `plotlyOutput` ... creates plotly graph (!)
+ `tableOutput()`... creates table (!)
+ `textOutput()`... creates text
+ `uiOutput()`... creates raw HTML
+ `verbatimTextOutput()`... creates text
+ `dataTableOutput()`... creates a data table (interactiv)
+ `leafletOutput()` ... creates leaflet map (!)
- Our example app uses those marked with (!).
## HTML tag functions
* Shiny's **HTML tag functions** translate input into html code
- Try pasting `h2("A NEW HOPE", align = "center")` into your console
- `h2()` function creates `<h2></h2>` html tag
- Common HTML tags (e.g., `<div`>) can be created by calling for their tag name directly (e.g., `div()`)
- Less common tags (e.g., `<article`>), use the tags list collection (e.g., `tags$article()`) stored in the `tags` object
- Try `tags$` in the console
- `.noWS = ...` argument to remove whitespace
- See [full reference for HTML tags](https://developer.mozilla.org/en-US/docs/Web/HTML/Element)
- Here we just do a quick example but in [this tutorial you find more information](https://shiny.rstudio.com/tutorial/written-tutorial/lesson3/)
- **Exercise**: Please run the shiny app below and explore the effect of different html tags. What do the different html tags do?
```{r 03-user-interface-17, cache=TRUE, eval=FALSE, include=TRUE}
ui <- fluidPage(
titlePanel("A big name in politics"),
sidebarLayout(
sidebarPanel( "The Arni Shiny App"),
mainPanel(
h2("A NEW HOPE", align = "center"),
h5("It is a period of civil war.", align = "center"),
p("p creates a paragraph of text."),
tags$p("A new p() command starts a new paragraph. Supply a style attribute to change the format of the entire paragraph.", style = "font-family: 'times'; font-si16pt"),
strong("strong() makes bold text."),
em("em() creates italicized (i.e, emphasized) text."),
tags$hr(style="border-color:black;"),
tags$br(),
tags$line(),
br(),
code("code displays your text similar to computer code"),
div("div creates segments of text with a similar style. This division of text is all blue because I passed the argument 'style = color:blue' to div", style = "color:blue"),
br(),
p("span does the same thing as div, but it works with",
span("groups of words", style = "color:blue"),
"that appear inside a paragraph.")
)))
server <- function(input, output, session){}
shinyApp(ui=ui, server = server)
```
## Summary
- UI Layout created with `fluidPage()`
- Image can be included using `img(src = "...", , width = ..., height = ...)` function
- `*Input()` functions: Used to generate input UI widgets
- input values are stored in list `input$...` with particular `name`, e.g., `input$tab_tabulate_select`
- `*Output()` functions: Used to display output, `dataTableOutput()`
- output is sent from server
- Both input/output functions have IDs the connect them to the server
- HTML tags can be used through `tags$name()` function, e.g., `tags$br()`
- Not covered here:
- **Dynamic **UI makes it possible to change UI as a function of input values (cf. `uiOutput()`)
## Other important concepts, functions and packages
* In addition to Shiny UI base functions (that are accessible throught the `shiny` package), various other packages allow for more advanced UIs
* `dashboardPage()` from the `bs4Dash` can be used to create dashboards (see @sec-dashboardPage)
- Custom theming and modern UI widgets: [`bslib`](https://rstudio.github.io/bslib/) and [`bsplus`](http://ijlyttle.github.io/bsplus/)
- Custom, more beautiful UI widgets: [`shinyWidgets`](https://dreamrs.github.io/shinyWidgets/index.html), [`spsComps`](https://systempipe.org/sps/dev/spscomps/)
- Custom theming: [`fresh`](https://github.com/dreamRs/fresh)
- UI frameworks:
- AdminLTE 2 ([`shinydashboard`](https://rstudio.github.io/shinydashboard/))
- AdminLTE 3 ([`bs4Dash`](https://rinterface.github.io/bs4Dash/index.html))
- Fluent UI ([shiny.fluent](https://appsilon.github.io/shiny.fluent/))
- bulma.io ([shinybulma](https://rinterface.github.io/shinybulma/))
- Fomantic ([`shiny.semantic`](https://appsilon.github.io/shiny.semantic/))
- Material Design ([`shinymaterial`](https://ericrayanderson.github.io/shinymaterial/))
- Argon ([`argonDash`](https://rinterface.github.io/argonDash/))
- Tabler ([`tablerDash`](https://rinterface.github.io/tablerDash/))
- Gentelella ([`gentelellaShiny`](http://code.markedmondson.me/gentelellaShiny/))
- Loaders, spinners, and progress bars: [`waiter`](https://waiter.john-coene.com/), [`shinycssloaders`](https://github.com/daattali/shinycssloaders), [`shinybusy`](https://dreamrs.github.io/shinybusy/), [`shinycustomloader`](https://emitanaka.org/shinycustomloader/)
- Designing Shiny apps for smaller screen sizes: [`shinyMobile`](https://shinymobile.rinterface.com/) and [`miniUI`](https://github.com/rstudio/miniUI)
- Popups and alerts: [`shinyalert`](https://github.com/daattali/shinyalert)
- Feedback and input validation: [`shinyFeedback`](https://merlinoa.github.io/shinyFeedback/)
- Walkthroughs: [`cicerone`](https://github.com/JohnCoene/cicerone)
- Translation / internationalization: [`shiny.i18n`](https://appsilon.github.io/shiny.i18n/)
- Embedding media:
- Behavioral data: [`shinysense`](http://nickstrayer.me/shinysense/)
- Doodles: [`pixels`](https://github.com/javierluraschi/pixels), [`fabricerin`](https://github.com/feddelegrand7/fabricerin)
- Videos: [`vembedr`](https://ijlyttle.github.io/vembedr/), [`video`](https://cran.r-project.org/web/packages/video/)
- PDF files: [`rpdf`](https://github.com/yonicd/rpdf/), [`shinyFiles`](https://github.com/thomasp85/shinyFiles)
- Image editing: [`drawer`](https://systempipe.org/sps/dev/drawer/)
- Code editing: [`shinyAce`](http://trestletech.github.io/shinyAce/)
### dashboardPage {#sec-dashboardPage}
- Alternative to `fluidPage()`
- `dashboardPage()`: creates a dashboard interface
- function contained in packages `shinydashboard` and `bs4Dash` (use `bs4Dash`^[Bootstrap 4 shinydashboard using AdminLTE3: [Website](https://rinterface.github.io/bs4Dash/)]!)
- `dashboardHeader()`: creates a dashboard header
- `dashboardSidebar()`: Creates dashboard sidebar
- sidebar typically contains a sidebarMenu, although it may also contain a sidebarSearchForm, or other Shiny inputs.
- `dashboardBody()`: creates main body typically containing boxes or tabItems
```{r 03-user-interface-4, cache=TRUE, eval=FALSE, include=TRUE}
library(bs4Dash)
# UI ----
ui <- dashboardPage(title = "The ESS shiny app",
### Header ----
header = dashboardHeader("Add title here"),
### Sidebar ----
sidebar = dashboardSidebar("Sidebar menu"),
### Body ----
body = dashboardBody("Main body")
)
# Server ----
server <- function(input, output, session) {}
shinyApp(ui, server)
```
<br><br>
- `?sidebarMenu()`: create sidebarMenu within dashboardSidebar
- `menuItem(tabName = "...", text = "...", icon = icon("table"))`: Creates one item in sidebarMenu
- `tabItems()`: creates container for tab items
- `tabItem(tabName = "insp", ...)`: creates tab to put inside a tab items container
- can be combined with `fluidRow()` and `column()`
- Connection through name `tabName` argument
```{r 03-user-interface-5, cache=TRUE, eval=FALSE, include=TRUE}
library(bs4Dash)
# UI ----
ui <- dashboardPage(title = "The ESS shiny app",
### Header ----
header = dashboardHeader(
title = "Title here"
),
### Sidebar ----
sidebar = dashboardSidebar(
sidebarMenu(
menuItem(tabName = "tab_table",
text = "Table data",
icon = icon("table"))
)
),
### Body ----
body = dashboardBody(
tabItems( # start tabItems
tabItem(
tabName = "tab_table",
hr(), # add separation line
"Here we will put a table"
)
) # end tabItems
)
) # End UI
# Server ----
server <- function(input, output, session) {}
shinyApp(ui, server)
```