Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

107 lines
2.4KB

  1. ---
  2. output: github_document
  3. ---
  4. ```{r setup, include=FALSE}
  5. knitr::opts_chunk$set(eval = FALSE)
  6. github_sha_link <- function(sha) {
  7. glue::glue("[{sha}](https://github.com/gadenbuie/js4shiny-frappeCharts/commit/{sha})")
  8. }
  9. ```
  10. # Building a Shiny Input
  11. In this project,
  12. we're going to create a typing speed app
  13. using a custom Shiny input.
  14. The app will give users typing prompts,
  15. monitor their typing speed,
  16. and use a Frappe Chart line chart
  17. to show their speed over time as they type.
  18. ## Setup a folder for our app inside the frappeCharts package
  19. `r github_sha_link("113340074c3af9c2cdf46cd7787829d4ec56bfcf")`
  20. Create the directory `inst/shiny-input-app` and add `app.R` and `typing.js`.
  21. ```{r}
  22. usethis::use_directory("inst/shiny-input-app")
  23. file.create("inst/shiny-input-app/app.R")
  24. file.create("inst/shiny-input-app/typing.js")
  25. ```
  26. ## Create a basic Shiny app with a typing area
  27. `r github_sha_link("ff3a962f7e6d16a75ebdb620aac0fdfc9949086e")`
  28. We'll start with typical Shiny inputs.
  29. ```r
  30. library(shiny)
  31. ui <- fluidPage(
  32. textAreaInput("typing", "Type here..."),
  33. verbatimTextOutput("debug")
  34. )
  35. server <- function(input, output, session) {
  36. output$debug <- renderPrint(input$typing)
  37. }
  38. shinyApp(ui, server)
  39. ```
  40. Run this app and type in the box.
  41. ## Create our own typingSpeedInput()
  42. Use Shiny's `textAreaInput()` to get the template
  43. for our own `typingSpeedInput()`
  44. ```{r, eval=TRUE}
  45. shiny_text_input <- shiny::textAreaInput(
  46. "INPUT", "LABEL", placeholder = "PLACEHOLDER"
  47. )
  48. cat(format(shiny_text_input))
  49. ```
  50. ```{r}
  51. typingSpeedInput <- function(inputId, label, placeholder = NULL) {
  52. .label <- label
  53. htmltools::withTags(
  54. div(
  55. class = "form-group typing-speed",
  56. label(class = "control-label", `for` = inputId, .label),
  57. textarea(id = inputId, class = "form-control", placeholder = placeholder)
  58. )
  59. )
  60. }
  61. ```
  62. Two points:
  63. 1. Notice that I used `htmltools::withTags()`,
  64. which makes it easier to write multiple tags at once.
  65. But it has the downside of masking the `label` argument of `typingSpeedInput()`.
  66. Hence, the first line `.label <- label`.
  67. 1. I added `.typing-speed` to our parent container so that we can
  68. find or style our custom input.
  69. Replace the `textAreaInput()` with our new `typingSpeedInput()` and run the app.
  70. It works the same!
  71. Wait, why?
  72. ```{r}
  73. ui <- fluidPage(
  74. # textAreaInput("typing", "Type here..."),
  75. typingSpeedInput("typing", "Type here..."),
  76. verbatimTextOutput("debug")
  77. )
  78. ```