選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

667 行
19KB

  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. [typing-stats-module-gist]: https://gist.github.com/gadenbuie/08546fd96b96fbf810f84ccdc7b69bcc
  8. [stringdist]: https://github.com/markvanderloo/stringdist
  9. [type-racer]: https://gadenbuie.shinyapps.io/type-racer/
  10. ```{r setup, include=FALSE}
  11. knitr::opts_chunk$set(eval = FALSE)
  12. github_sha_link <- function(sha) {
  13. glue::glue("[{sha}](https://github.com/gadenbuie/js4shiny-frappeCharts/commit/{sha})")
  14. }
  15. get_last_sha <- function() {
  16. commit <- git2r::commits()[[1]]
  17. message(commit$summary)
  18. message(commit$sha)
  19. clipr::write_clip(glue::glue(
  20. "`r github_sha_link(\"{commit$sha}\")`"
  21. ))
  22. }
  23. ```
  24. # Building a Shiny Input
  25. In this project,
  26. we're going to create a typing speed app
  27. using a custom Shiny input.
  28. The app will give users typing prompts,
  29. monitor their typing speed,
  30. and use a Frappe Chart line chart
  31. to show their speed over time as they type.
  32. ## Setup a folder for our app inside the frappeCharts package
  33. `r github_sha_link("113340074c3af9c2cdf46cd7787829d4ec56bfcf")`
  34. Create the directory `inst/shiny-input-app` and add `app.R` and `typing.js`.
  35. ```{r}
  36. usethis::use_directory("inst/shiny-input-app")
  37. file.create("inst/shiny-input-app/app.R")
  38. file.create("inst/shiny-input-app/typing.js")
  39. ```
  40. ## Create a basic Shiny app with a typing area
  41. `r github_sha_link("ff3a962f7e6d16a75ebdb620aac0fdfc9949086e")`
  42. We'll start with typical Shiny inputs.
  43. ```r
  44. library(shiny)
  45. ui <- fluidPage(
  46. textAreaInput("typing", "Type here..."),
  47. verbatimTextOutput("debug")
  48. )
  49. server <- function(input, output, session) {
  50. output$debug <- renderPrint(input$typing)
  51. }
  52. shinyApp(ui, server)
  53. ```
  54. Run this app and type in the box.
  55. ## Create our own typingSpeedInput()
  56. `r github_sha_link("b7108029b58635652ce87f3e1ea9a2c5a6232020")`
  57. Use Shiny's `textAreaInput()` to get the template
  58. for our own `typingSpeedInput()`
  59. ```{r, eval=TRUE}
  60. shiny_text_input <- shiny::textAreaInput(
  61. "INPUT", "LABEL", placeholder = "PLACEHOLDER"
  62. )
  63. cat(format(shiny_text_input))
  64. ```
  65. ```{r}
  66. typingSpeedInput <- function(inputId, label, placeholder = NULL) {
  67. .label <- label
  68. htmltools::withTags(
  69. div(
  70. class = "form-group typing-speed",
  71. label(class = "control-label", `for` = inputId, .label),
  72. textarea(id = inputId, class = "form-control", placeholder = placeholder)
  73. )
  74. )
  75. }
  76. ```
  77. Two points:
  78. 1. Notice that I used `htmltools::withTags()`,
  79. which makes it easier to write multiple tags at once.
  80. But it has the downside of masking the `label` argument of `typingSpeedInput()`.
  81. Hence, the first line `.label <- label`.
  82. 1. I added `.typing-speed` to our parent container so that we can
  83. find or style our custom input.
  84. Replace the `textAreaInput()` with our new `typingSpeedInput()` and run the app.
  85. It works the same!
  86. Wait, why?
  87. ```{r}
  88. ui <- fluidPage(
  89. # textAreaInput("typing", "Type here..."),
  90. typingSpeedInput("typing", "Type here..."),
  91. verbatimTextOutput("debug")
  92. )
  93. ```
  94. ## Start creating an input binding for `typingSpeedInput()`
  95. `r github_sha_link("02adb896c50a97ebe7f9a7fef2a6f00488f9418d")`
  96. Now we can open `typing.js` and create a Shiny input binding.
  97. If you used `js4shiny::snippets_install()`,
  98. you have a `ShinyInputBinding` snippet that provides a template for you.
  99. Or you can copy the chunk below.
  100. <details><summary>Shiny Input Binding Template</summary>
  101. ```js
  102. // Ref: https://shiny.rstudio.com/articles/building-inputs.html
  103. // Ref: https://github.com/rstudio/shiny/blob/master/srcjs/input_binding.js
  104. const bindingName = new Shiny.InputBinding();
  105. $.extend(bindingName, {
  106. find: function(scope) {
  107. // Specify the selector that identifies your input. `scope` is a general
  108. // parent of your input elements. This function should return the nodes of
  109. // ALL of the inputs that are inside `scope`. These elements should all
  110. // have IDs that are used as the inputId on the server side.
  111. return scope.querySelectorAll("inputBindingSelector");
  112. },
  113. getValue: function(el) {
  114. // For a particular input, this function is given the element containing
  115. // your input. In this function, find or construct the value that will be
  116. // returned to Shiny. The ID of `el` is used for the inputId.
  117. // e.g: return el.value
  118. return 'FIXME';
  119. },
  120. setValue: function(el, value) {
  121. // This method is used for restoring the bookmarked state of your input
  122. // and allows you to set the input's state without triggering reactivity.
  123. // Basically, reverses .getValue()
  124. // e.g.; el.value = value
  125. console.error('bindingName.setValue() is not yet defined');
  126. },
  127. receiveMessage: function(el, data) {
  128. // Given the input's container and data, update the input
  129. // and its elements to reflect the given data.
  130. // The messages are sent from R/Shiny via
  131. // R> session$sendInputMessage(inputId, data)
  132. console.error('bindingName.receiveMessage() is not yet defined');
  133. // If you want the update to trigger reactivity, trigger a subscribed event
  134. $(el).trigger("change")
  135. },
  136. subscribe: function(el, callback) {
  137. // Listen to events on your input element. The following block listens to
  138. // the change event, but you might want to listen to another event.
  139. // Repeat the block for each event type you want to subscribe to.
  140. $(el).on("change.bindingName", function(e) {
  141. // Use callback() or callback(true).
  142. // If using callback(true) the rate policy applies,
  143. // for example if you need to throttle or debounce
  144. // the values being sent back to the server.
  145. callback();
  146. });
  147. },
  148. getRatePolicy: function() {
  149. return {
  150. policy: 'debounce', // 'debounce', 'throttle' or 'direct' (default)
  151. delay: 100 // milliseconds for debounce or throttle
  152. };
  153. },
  154. unsubscribe: function(el) {
  155. $(el).off(".bindingName");
  156. }
  157. });
  158. Shiny.inputBindings.register(bindingName, 'pkgName.bindingName');
  159. ```
  160. </details>
  161. `r github_sha_link("6fffc2337ad475af2ab09ee571014afdbb680fb6")`
  162. If you use the snippet,
  163. it automatically walks you through
  164. the first pass of parts that need to be changed.
  165. If you copied the template,
  166. you need to find and replace all:
  167. - `bindingName`: the name of the JavaScript object with the specifics of your
  168. Shiny input. This name isn't user facing, but helps Shiny keep track of which
  169. the inputs in an app.
  170. We'll call ours `typingSpeed`
  171. - `inputBindingSelector`: this is the CSS selector that can be used to find
  172. the HTML element of your input. The element you find here is the element in
  173. your input's HTML that has the `id` with the input's `inputId`.
  174. In our case, we want the `textarea` element
  175. that's a descendent of `.typing-speed`, so we use
  176. ```css
  177. .typing-speed textarea
  178. ```
  179. - `change`: This is the event that will be listened to by Shiny to know when
  180. the input has updated. For our typing speed input, we're going to listen to
  181. the `keyup` event.
  182. - `pkgName`: if you're writing this input as part of a package, use your package
  183. name. It's not critical; this just provides some namespacing in case there's
  184. another package that impelements an in put with the same `bindingName`.
  185. Here we use `js4shiny`.
  186. ## Add a dependency to the typing input
  187. `r github_sha_link("0be8efb83bef664f707b8716eab1d5478de933c7")`
  188. To have `typing.js` included with our input,
  189. we use `htmltools::htmlDependency()` inside our input function.
  190. This guarantees that `typing.js` is loaded once per page
  191. and is included whenever a `typingSpeedInput()` is created.
  192. ```{r}
  193. # I used the htmldeps snippet for this
  194. htmltools::htmlDependency(
  195. name = "typingSpeed",
  196. version = "0.0.1",
  197. src = ".",
  198. script = "typing.js",
  199. all_files = FALSE
  200. )
  201. ```
  202. Now when you run the app,
  203. you'll see `"FIXME"` as the output of `input$typing`.
  204. That's our next step.
  205. ## Explore the input binding
  206. Read through the comments of the input binding template.
  207. They explain the role of each function.
  208. In a nutshell,
  209. as a Shiny input author,
  210. your job is to tell Shiny a few key things:
  211. 1. **`.find()`** — How to find your input elements on the page
  212. 1. **`.subscribe()`** — What browser events will trigger an update from your input.
  213. The template show how to listen `'change'` events,
  214. but you may want to listen for a different event (or multiple events!),
  215. like a button `'click'` or a `'keydown'` or `'keyup'` event.
  216. 1. **`.getRatePolicy()`** — How often to send updates back to the server.
  217. There are three options here: `'debounce'`, `'throttle'`, and `'direct'`.
  218. See the [shiny debounce documentation][shiny-debounce] and my slides
  219. for more info.
  220. 1. **`.getValue()`** — What is the value of your input?
  221. This method is called whenever a subscribed event happens, and if the value
  222. of the input has changed it is reported back to Shiny. It's up to you,
  223. though, in this function, to read the HTML to determine the current value of
  224. the input and to construct the data that's sent back to the server.
  225. 1. **`.receiveMessage()`** - Let the input receive messages from the server.
  226. This works just like custom message handles, except that you call
  227. `shiny::sendInputMessage(inputId, data)` on the server side.
  228. This method receives the data and can be used to update the state of the
  229. input from values sent by the server.
  230. Ideally you would write an `update<InputName>()` function that wraps
  231. `shiny::sendInputMessage()`. This is how [`updateTextInput()`][updateText-shiny-input-binding] and others
  232. works.
  233. If you want the updated values to flow through the reactive graph
  234. (you probably do), then you need to trigger a subscribed event after
  235. you make the changes. This calls `.getValue()` which sets the input values
  236. and reports back to the server.
  237. 1. **`.setValue()`** — This method takes a value sent from your input and
  238. updates your HTML to match.
  239. This method is required to be able to restore the input from a bookmarked
  240. state. It also allows you to set the input's value without triggering
  241. reactivity.
  242. ### Read the input binding for `checkboxInput()`
  243. The input binding JavaScript for `checkboxInput()` is available
  244. in the [Shiny GitHub repository][checkboxInput-shiny-input-binding].
  245. Read through it and discuss what each method does.
  246. ## Setup our input binding
  247. Now it's time to setup our input binding. Replace `FIXME` with `el.value`.
  248. (`r github_sha_link("85205fbcbb93ccb506558e62f73a8f0d6a88c83c")`)
  249. ### Your Turn
  250. The `.value` of a `textarea` element
  251. is a string containing the text inside the element.
  252. Update `.getValue()` to
  253. 1. Return the number of characters the user has typed (`r github_sha_link("b3958d5e3f60fbac3a0100673696bd413a276fb4")`)
  254. 1. Return the number of words the user has entered (`r github_sha_link("e3fa485bb60853e391302289213d3cd5f0846b3e")`)
  255. 1. Create variables for both number of characters and words and return both
  256. in an object (`r github_sha_link("edfb9399eae5207cc4a3ef9b48e62c9c92230477")`)
  257. ### Tracking the timing
  258. You can add your own properties and methods to the input binding.
  259. As a convention,
  260. the property or method names start with `_`.
  261. Let's add a `_timing` property that with initialize with `null`.
  262. (`r github_sha_link("9568fdcd06fa1fe1815dc48bf6efb03f9af68b29")`)
  263. ```js
  264. $.extend(typingSpeed, {
  265. _timing: null,
  266. // ...
  267. }
  268. ```
  269. Inside our input binding methods,
  270. we can now access `this._timing`
  271. to get the timing property for the input.
  272. (And a new input binding is created for each input,
  273. so if there are multiple typingSpeed inputs,
  274. we'll automatically get the right `_timing` value.)
  275. For methods called on objects,
  276. `this` refers the the parent object.
  277. Try the `repl_example("this-simple")` example to see how this works.
  278. <details><summary>`repl_example("this-simple")`</summary>
  279. ```js
  280. const person = {
  281. name: "Christelle",
  282. sayHello: function() {
  283. console.log(`Hello, ${this.name}!`)
  284. }
  285. }
  286. person.sayHello()
  287. person.name = 'Mateo'
  288. person.sayHello()
  289. ```
  290. </details>
  291. #### Your Turn: Start `_timing`
  292. We're going to use this property to start timing the user's typing.
  293. On the one hand,
  294. when they delete all the text in the text area,
  295. we want to reset the timers.
  296. On the other hand,
  297. when they start typing,
  298. we want to know when they started.
  299. Update the `.getValue()` method so that whenever
  300. - there are no characters in the textarea
  301. `this._timing` is set to `null` and a `null` value is returned to Shiny.
  302. Similarly, when
  303. - `this._timing` is `null`
  304. - and there are any characters in the text area
  305. `this._timing` is updated to the current time (`Date.now()`)
  306. and a `null` value is returned.
  307. Include the timing value in the data returned to Shiny
  308. so that you can verify it's working.
  309. (`r github_sha_link("073186bcc9741cb2494b4b9a17042ea5716a7dd5")`)
  310. ### Your Turn: How Fast?
  311. Now you're ready to calculate typing statistics.
  312. Here's the idea:
  313. each time the user presses a key,
  314. we calculate the `elapsed` time in seconds since they started typing.
  315. Then, from that value calculate:
  316. - words per minute (`wpm`)
  317. - characters per second (`cps`)
  318. Return an object/list with
  319. - `wpm`,
  320. - `cps`,
  321. - the current timestamp as `time` and
  322. - the `text` in the input
  323. (`r github_sha_link("fa02cb2314fa58ea714002072be0f78da2c6aa82")`)
  324. ### Your Turn: Hold your horses
  325. How does the app report the initial typing speed rates?
  326. Add another `if` statement to continue to return `null`
  327. until there are at least 3 words in the text box.
  328. `r github_sha_link("9f915337a2ab55c7e94eaa5cfa454c21bc8d72ba")`
  329. ### Your Turn: Find a rate policy balance
  330. At this point,
  331. we are streaming values straight from the browser to the server.
  332. This is probably a bit much.
  333. Change `callback()` to `callback(true)` in `subscribe()`.
  334. Try various settings of
  335. - `policy`: `debounce`, `throttle` or `direct`.
  336. Find a good delay rate.
  337. `r github_sha_link("8519d729bca13c730528a287c3601c4df2828e4f")`
  338. ### Almost done: Implement `receiveMessage()`
  339. There's not much we'd want to do from the server side
  340. in terms of updating the typing area.
  341. But maybe we'd like to be able to add a "Reset" button.
  342. Write a method that,
  343. when it recieves a `true` value from the server,
  344. clears the text input area.
  345. Add a reset button to your app that uses `shiny$sendInputMessage()`
  346. to send `typing` a `TRUE`
  347. whenever the button is clicked.
  348. `r github_sha_link("269e4ebdc48a66ecf7466192076c4fa259582cc6")`
  349. Once you get that working,
  350. refactor it into a `resetTypingSpeed()` function.
  351. This function should take an `inputId` and a `session` object.
  352. Use `shiny::getDefaultReactiveDomain()` for the default `session` value.
  353. `r github_sha_link("644a8b6c2e8f3719bda89cbd7801a90401c9eadb")`
  354. ### Final Step: Extra inputs on the side
  355. In our final app,
  356. we're going to want to know on the Shiny server side
  357. when the user has reset the typing input.
  358. We can watch for the typing speed input to be `NULL`,
  359. but ultimately it's a bit of a hassle
  360. to turn `is.null()`/`!is.null()` into an event.
  361. It will be easier for us if we can simply
  362. send an `{inputId}_reset` event to the server
  363. when the input has changed.
  364. Try adding a `Shiny.setInputValue()`
  365. that sends the current time
  366. to the input ID `{inputId}_reset`
  367. when the `this._timing` property is reset.
  368. Also, update the `debug` output to monitor `input$typing_reset` as well.
  369. `r github_sha_link("ccc35d6978dabf4a709a795f89719cc353ac72bd ")`
  370. ## Use our frappeChart widget to show speed over time
  371. ### First pass
  372. `r github_sha_link("fe55bf588400f8586472b1050c0da1b931bad1c3")`
  373. We're going to drop-in our `frappeChart` package to add a dynamic plot
  374. showing typing speed over time.
  375. If you didn't complete the `frappeChart` project earlier in the workshop,
  376. you can run the code below to install the package
  377. in the state I hope it's in by the time we finish that section.
  378. ```{r}
  379. devtools::install_github("gadenbuie/js4shiny-frappeCharts@pkg")
  380. ```
  381. Our first pass is going to add a chart,
  382. but it's not going to look super great.
  383. To get setup,
  384. we're going to cache the `time` and `wpm` sent from the browser
  385. in a `reactiveValues` object that we can coerce into a `data.frame`.
  386. ```{r}
  387. # server
  388. wpm <- reactiveValues(time = c(), wpm = c())
  389. observeEvent(input$typing_reset, {
  390. wpm$time <- c()
  391. wpm$wpm <- c()
  392. })
  393. observeEvent(input$typing, {
  394. req(input$typing)
  395. wpm$time <- c(wpm$time, input$typing$time)
  396. wpm$wpm <- c(wpm$wpm, input$typing$wpm)
  397. })
  398. ```
  399. We add the `frappeCharts` output to our UI
  400. ```{r}
  401. # ui
  402. frappeCharts::frappeChartOutput("chart_typing_speed")
  403. ```
  404. and use the following settings to render the `wpm` in "real time"
  405. ```{r}
  406. # server
  407. output$chart_typing_speed <- frappeCharts::renderFrappeChart({
  408. frappeCharts::frappeChart(
  409. data.frame(time = wpm$time, wpm = wpm$wpm),
  410. type = "line",
  411. title = "Your Typing Speed",
  412. is_navigable = FALSE,
  413. axisOptions = list(xIsSeries = TRUE),
  414. lineOptions = list(regionFill = TRUE)
  415. )
  416. })
  417. ```
  418. ### Don't redraw: Use the update method we made for frappeCharts
  419. `r github_sha_link("8d519b645abb990df17843f36cc418591e238aca")`
  420. Replace the initial `frappeChart()` with a simple placeholder.
  421. ```{r}
  422. # server
  423. output$chart_typing_speed <- frappeCharts::renderFrappeChart({
  424. frappeCharts::frappeChart(
  425. data.frame(time = 0, wpm = 0),
  426. type = "line",
  427. title = "Your Typing Speed",
  428. is_navigable = FALSE,
  429. axisOptions = list(xIsSeries = TRUE),
  430. lineOptions = list(regionFill = TRUE)
  431. )
  432. })
  433. ```
  434. and use the `updateFrappeChart()` function to update the chart in place.
  435. ```{r}
  436. observeEvent(wpm$time, {
  437. frappeCharts::updateFrappeChart(
  438. inputId = "chart_typing_speed",
  439. data = data.frame(time = wpm$time, wpm = wpm$wpm)
  440. )
  441. })
  442. ```
  443. ## Final Step: Make it fun
  444. Download the [Shiny module I created][typing-stats-module-gist] for this project
  445. into the directory with your `app.R` file.
  446. ```{r}
  447. download.file(
  448. "http://bit.ly/js4shiny-typing-stats-module",
  449. "module_typingStats.R"
  450. )
  451. ```
  452. Then source this module at the start of your app.
  453. ```{r}
  454. source("module_typingStats.R")
  455. ```
  456. Add the module's UI to your UI above the typing area.
  457. ```{r}
  458. # ui
  459. typingStatsUI('typing_stats')
  460. ```
  461. While you're in the UI area,
  462. fix something I missed earlier.
  463. With bootstrap,
  464. you can [set the number of rows](https://getbootstrap.com/docs/3.3/css/#textarea)
  465. in the `textarea`.
  466. Add this argument to `typingSpeedInput` and set the default value to `4`.
  467. Use the `typingStats()` module to calculate `wpm`.
  468. Replace the `wpm` reactive values list and the two observers we had before
  469. with the new `typingStats()` module.
  470. ```{r}
  471. # server
  472. wpm <- typingStats(
  473. "typing_stats",
  474. typing = reactive(input$typing),
  475. typing_reset = reactive(input$typing_reset)
  476. )
  477. ```
  478. And finally, use the new `wpm()` reactive from the module
  479. as the data for the `frappeChart` update.
  480. ```{r}
  481. observeEvent(wpm()$time, {
  482. frappeCharts::updateFrappeChart('chart_typing_speed', wpm())
  483. })
  484. ```
  485. If you don't have the [stringdist] package installed,
  486. install it now to get some extra stats.
  487. ```{r}
  488. install.packages("stringdist")
  489. ```
  490. Push the app to <https://shinyapps.io>!
  491. Or check out the one I deployed: [type-racer].