Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

442 lines
13KB

  1. ---
  2. output: github_document
  3. ---
  4. [shiny-debounce]: https://shiny.rstudio.com/reference/shiny/latest/debounce.html
  5. [updateText-shiny-input-binding]: https://github.com/rstudio/shiny/blob/a2a4e40821b9811a40e461f67e3622196d8aa726/srcjs/input_binding_text.js#L31-L41
  6. [checkboxInput-shiny-input-binding]: https://github.com/rstudio/shiny/blob/a2a4e40821b9811a40e461f67e3622196d8aa726/srcjs/input_binding_checkbox.js
  7. ```{r setup, include=FALSE}
  8. knitr::opts_chunk$set(eval = FALSE)
  9. github_sha_link <- function(sha) {
  10. glue::glue("[{sha}](https://github.com/gadenbuie/js4shiny-frappeCharts/commit/{sha})")
  11. }
  12. get_last_sha <- function() {
  13. commit <- git2r::commits()[[1]]
  14. message(commit$summary)
  15. message(commit$sha)
  16. clipr::write_clip(glue::glue(
  17. "`r github_sha_link(\"{commit$sha}\")`"
  18. ))
  19. }
  20. ```
  21. # Building a Shiny Input
  22. In this project,
  23. we're going to create a typing speed app
  24. using a custom Shiny input.
  25. The app will give users typing prompts,
  26. monitor their typing speed,
  27. and use a Frappe Chart line chart
  28. to show their speed over time as they type.
  29. ## Setup a folder for our app inside the frappeCharts package
  30. `r github_sha_link("113340074c3af9c2cdf46cd7787829d4ec56bfcf")`
  31. Create the directory `inst/shiny-input-app` and add `app.R` and `typing.js`.
  32. ```{r}
  33. usethis::use_directory("inst/shiny-input-app")
  34. file.create("inst/shiny-input-app/app.R")
  35. file.create("inst/shiny-input-app/typing.js")
  36. ```
  37. ## Create a basic Shiny app with a typing area
  38. `r github_sha_link("ff3a962f7e6d16a75ebdb620aac0fdfc9949086e")`
  39. We'll start with typical Shiny inputs.
  40. ```r
  41. library(shiny)
  42. ui <- fluidPage(
  43. textAreaInput("typing", "Type here..."),
  44. verbatimTextOutput("debug")
  45. )
  46. server <- function(input, output, session) {
  47. output$debug <- renderPrint(input$typing)
  48. }
  49. shinyApp(ui, server)
  50. ```
  51. Run this app and type in the box.
  52. ## Create our own typingSpeedInput()
  53. `r github_sha_link("b7108029b58635652ce87f3e1ea9a2c5a6232020")`
  54. Use Shiny's `textAreaInput()` to get the template
  55. for our own `typingSpeedInput()`
  56. ```{r, eval=TRUE}
  57. shiny_text_input <- shiny::textAreaInput(
  58. "INPUT", "LABEL", placeholder = "PLACEHOLDER"
  59. )
  60. cat(format(shiny_text_input))
  61. ```
  62. ```{r}
  63. typingSpeedInput <- function(inputId, label, placeholder = NULL) {
  64. .label <- label
  65. htmltools::withTags(
  66. div(
  67. class = "form-group typing-speed",
  68. label(class = "control-label", `for` = inputId, .label),
  69. textarea(id = inputId, class = "form-control", placeholder = placeholder)
  70. )
  71. )
  72. }
  73. ```
  74. Two points:
  75. 1. Notice that I used `htmltools::withTags()`,
  76. which makes it easier to write multiple tags at once.
  77. But it has the downside of masking the `label` argument of `typingSpeedInput()`.
  78. Hence, the first line `.label <- label`.
  79. 1. I added `.typing-speed` to our parent container so that we can
  80. find or style our custom input.
  81. Replace the `textAreaInput()` with our new `typingSpeedInput()` and run the app.
  82. It works the same!
  83. Wait, why?
  84. ```{r}
  85. ui <- fluidPage(
  86. # textAreaInput("typing", "Type here..."),
  87. typingSpeedInput("typing", "Type here..."),
  88. verbatimTextOutput("debug")
  89. )
  90. ```
  91. ## Start creating an input binding for `typingSpeedInput()`
  92. `r github_sha_link("02adb896c50a97ebe7f9a7fef2a6f00488f9418d")`
  93. Now we can open `typing.js` and create a Shiny input binding.
  94. If you used `js4shiny::snippets_install()`,
  95. you have a `ShinyInputBinding` snippet that provides a template for you.
  96. Or you can copy the chunk below.
  97. <details><summary>Shiny Input Binding Template</summary>
  98. ```js
  99. // Ref: https://shiny.rstudio.com/articles/building-inputs.html
  100. // Ref: https://github.com/rstudio/shiny/blob/master/srcjs/input_binding.js
  101. const bindingName = new Shiny.InputBinding();
  102. $.extend(bindingName, {
  103. find: function(scope) {
  104. // Specify the selector that identifies your input. `scope` is a general
  105. // parent of your input elements. This function should return the nodes of
  106. // ALL of the inputs that are inside `scope`. These elements should all
  107. // have IDs that are used as the inputId on the server side.
  108. return scope.querySelectorAll("inputBindingSelector");
  109. },
  110. getValue: function(el) {
  111. // For a particular input, this function is given the element containing
  112. // your input. In this function, find or construct the value that will be
  113. // returned to Shiny. The ID of `el` is used for the inputId.
  114. // e.g: return el.value
  115. return 'FIXME';
  116. },
  117. setValue: function(el, value) {
  118. // This method is used for restoring the bookmarked state of your input
  119. // and allows you to set the input's state without triggering reactivity.
  120. // Basically, reverses .getValue()
  121. // e.g.; el.value = value
  122. console.error('bindingName.setValue() is not yet defined');
  123. },
  124. receiveMessage: function(el, data) {
  125. // Given the input's container and data, update the input
  126. // and its elements to reflect the given data.
  127. // The messages are sent from R/Shiny via
  128. // R> session$sendInputMessage(inputId, data)
  129. console.error('bindingName.receiveMessage() is not yet defined');
  130. // If you want the update to trigger reactivity, trigger a subscribed event
  131. $(el).trigger("change")
  132. },
  133. subscribe: function(el, callback) {
  134. // Listen to events on your input element. The following block listens to
  135. // the change event, but you might want to listen to another event.
  136. // Repeat the block for each event type you want to subscribe to.
  137. $(el).on("change.bindingName", function(e) {
  138. // Use callback() or callback(true).
  139. // If using callback(true) the rate policy applies,
  140. // for example if you need to throttle or debounce
  141. // the values being sent back to the server.
  142. callback();
  143. });
  144. },
  145. getRatePolicy: function() {
  146. return {
  147. policy: 'debounce', // 'debounce', 'throttle' or 'direct' (default)
  148. delay: 100 // milliseconds for debounce or throttle
  149. };
  150. },
  151. unsubscribe: function(el) {
  152. $(el).off(".bindingName");
  153. }
  154. });
  155. Shiny.inputBindings.register(bindingName, 'pkgName.bindingName');
  156. ```
  157. </details>
  158. `r github_sha_link("6fffc2337ad475af2ab09ee571014afdbb680fb6")`
  159. If you use the snippet,
  160. it automatically walks you through
  161. the first pass of parts that need to be changed.
  162. If you copied the template,
  163. you need to find and replace all:
  164. - `bindingName`: the name of the JavaScript object with the specifics of your
  165. Shiny input. This name isn't user facing, but helps Shiny keep track of which
  166. the inputs in an app.
  167. We'll call ours `typingSpeed`
  168. - `inputBindingSelector`: this is the CSS selector that can be used to find
  169. the HTML element of your input. The element you find here is the element in
  170. your input's HTML that has the `id` with the input's `inputId`.
  171. In our case, we want the `textarea` element
  172. that's a descendent of `.typing-speed`, so we use
  173. ```css
  174. .typing-speed textarea
  175. ```
  176. - `change`: This is the event that will be listened to by Shiny to know when
  177. the input has updated. For our typing speed input, we're going to listen to
  178. the `keyup` event.
  179. - `pkgName`: if you're writing this input as part of a package, use your package
  180. name. It's not critical; this just provides some namespacing in case there's
  181. another package that impelements an in put with the same `bindingName`.
  182. Here we use `js4shiny`.
  183. ## Add a dependency to the typing input
  184. `r github_sha_link("0be8efb83bef664f707b8716eab1d5478de933c7")`
  185. To have `typing.js` included with our input,
  186. we use `htmltools::htmlDependency()` inside our input function.
  187. This guarantees that `typing.js` is loaded once per page
  188. and is included whenever a `typingSpeedInput()` is created.
  189. ```{r}
  190. # I used the htmldeps snippet for this
  191. htmltools::htmlDependency(
  192. name = "typingSpeed",
  193. version = "0.0.1",
  194. src = ".",
  195. script = "typing.js",
  196. all_files = FALSE
  197. )
  198. ```
  199. Now when you run the app,
  200. you'll see `"FIXME"` as the output of `input$typing`.
  201. That's our next step.
  202. ## Explore the input binding
  203. Read through the comments of the input binding template.
  204. They explain the role of each function.
  205. In a nutshell,
  206. as a Shiny input author,
  207. your job is to tell Shiny a few key things:
  208. 1. **`.find()`** — How to find your input elements on the page
  209. 1. **`.subscribe()`** — What browser events will trigger an update from your input.
  210. The template show how to listen `'change'` events,
  211. but you may want to listen for a different event (or multiple events!),
  212. like a button `'click'` or a `'keydown'` or `'keyup'` event.
  213. 1. **`.getRatePolicy()`** — How often to send updates back to the server.
  214. There are three options here: `'debounce'`, `'throttle'`, and `'direct'`.
  215. See the [shiny debounce documentation][shiny-debounce] and my slides
  216. for more info.
  217. 1. **`.getValue()`** — What is the value of your input?
  218. This method is called whenever a subscribed event happens, and if the value
  219. of the input has changed it is reported back to Shiny. It's up to you,
  220. though, in this function, to read the HTML to determine the current value of
  221. the input and to construct the data that's sent back to the server.
  222. 1. **`.receiveMessage()`** - Let the input receive messages from the server.
  223. This works just like custom message handles, except that you call
  224. `shiny::sendInputMessage(inputId, data)` on the server side.
  225. This method receives the data and can be used to update the state of the
  226. input from values sent by the server.
  227. Ideally you would write an `update<InputName>()` function that wraps
  228. `shiny::sendInputMessage()`. This is how [`updateTextInput()`][updateText-shiny-input-binding] and others
  229. works.
  230. If you want the updated values to flow through the reactive graph
  231. (you probably do), then you need to trigger a subscribed event after
  232. you make the changes. This calls `.getValue()` which sets the input values
  233. and reports back to the server.
  234. 1. **`.setValue()`** — This method takes a value sent from your input and
  235. updates your HTML to match.
  236. This method is required to be able to restore the input from a bookmarked
  237. state. It also allows you to set the input's value without triggering
  238. reactivity.
  239. ### Read the input binding for `checkboxInput()`
  240. The input binding JavaScript for `checkboxInput()` is available
  241. in the [Shiny GitHub repository][checkboxInput-shiny-input-binding].
  242. Read through it and discuss what each method does.
  243. ## Setup our input binding
  244. Now it's time to setup our input binding. Replace `FIXME` with `el.value`.
  245. (`r github_sha_link("85205fbcbb93ccb506558e62f73a8f0d6a88c83c")`)
  246. ### Your Turn
  247. The `.value` of a `textarea` element
  248. is a string containing the text inside the element.
  249. Update `.getValue()` to
  250. 1. Return the number of characters the user has typed (`r github_sha_link("b3958d5e3f60fbac3a0100673696bd413a276fb4")`)
  251. 1. Return the number of words the user has entered (`r github_sha_link("e3fa485bb60853e391302289213d3cd5f0846b3e")`)
  252. 1. Create variables for both number of characters and words and return both
  253. in an object (`r github_sha_link("edfb9399eae5207cc4a3ef9b48e62c9c92230477")`)
  254. ### Tracking the timing
  255. You can add your own properties and methods to the input binding.
  256. As a convention,
  257. the property or method names start with `_`.
  258. Let's add a `_timing` property that with initialize with `null`.
  259. (`r github_sha_link("9568fdcd06fa1fe1815dc48bf6efb03f9af68b29")`)
  260. ```js
  261. $.extend(typingSpeed, {
  262. _timing: null,
  263. // ...
  264. }
  265. ```
  266. Inside our input binding methods,
  267. we can now access `this._timing`
  268. to get the timing property for the input.
  269. (And a new input binding is created for each input,
  270. so if there are multiple typingSpeed inputs,
  271. we'll automatically get the right `_timing` value.)
  272. For methods called on objects,
  273. `this` refers the the parent object.
  274. Try the `repl_example("this-simple")` example to see how this works.
  275. <details><summary>`repl_example("this-simple")`</summary>
  276. ```js
  277. const person = {
  278. name: "Christelle",
  279. sayHello: function() {
  280. console.log(`Hello, ${this.name}!`)
  281. }
  282. }
  283. person.sayHello()
  284. person.name = 'Mateo'
  285. person.sayHello()
  286. ```
  287. </details>
  288. #### Your Turn: Start `_timing`
  289. We're going to use this property to start timing the user's typing.
  290. On the one hand,
  291. when they delete all the text in the text area,
  292. we want to reset the timers.
  293. On the other hand,
  294. when they start typing,
  295. we want to know when they started.
  296. Update the `.getValue()` method so that whenever
  297. - there are no characters in the textarea
  298. `this._timing` is set to `null` and a `null` value is returned to Shiny.
  299. Similarly, when
  300. - `this._timing` is `null`
  301. - and there are any characters in the text area
  302. `this._timing` is updated to the current time (`Date.now()`)
  303. and a `null` value is returned.
  304. Include the timing value in the data returned to Shiny
  305. so that you can verify it's working.
  306. (`r github_sha_link("073186bcc9741cb2494b4b9a17042ea5716a7dd5")`)
  307. ### Your Turn: How Fast?
  308. Now you're ready to calculate typing statistics.
  309. Here's the idea:
  310. each time the user presses a key,
  311. we calculate the `elapsed` time in seconds since they started typing.
  312. Then, from that value calculate:
  313. - words per minute (`wpm`)
  314. - characters per second (`cps`)
  315. Return an object/list with
  316. - `wpm`,
  317. - `cps`,
  318. - the current timestamp as `time` and
  319. - the `text` in the input
  320. (`r github_sha_link("fa02cb2314fa58ea714002072be0f78da2c6aa82")`)
  321. ### Your Turn: Hold your horses
  322. How does the app report the initial typing speed rates?
  323. Add another `if` statement to continue to return `null`
  324. until there are at least 3 words in the text box.