Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

107 lines
2.2KB

  1. typingStatsUI <- function(id) {
  2. ns <- NS(id)
  3. tagList(
  4. fluidRow(
  5. div(
  6. class = "col-xs-12 col-sm-9 col-md-6",
  7. uiOutput(ns("prompt"))
  8. ),
  9. div(
  10. class = "col-xs-12 col-sm-3 col-md-6",
  11. style = "min-height: 75px;",
  12. uiOutput(ns("wpm"))
  13. )
  14. )
  15. )
  16. }
  17. typingStats <- function(id, typing, typing_reset = reactive(NULL), n_prompt = 4) {
  18. callModule(typingStats_module, id, typing = typing, typing_reset = typing_reset)
  19. }
  20. date_now <- function() as.integer(Sys.time()) * 1000
  21. typingStats_module <- function(
  22. input,
  23. output,
  24. session,
  25. typing,
  26. typing_reset = reactive(NULL),
  27. n_prompt = 4
  28. ) {
  29. ns <- session$ns
  30. wpm <- reactiveValues(time = date_now(), wpm = 0)
  31. reactive_df <- function(x) {
  32. as.data.frame(reactiveValuesToList(x))
  33. }
  34. observeEvent(typing_reset(), {
  35. wpm$time <- date_now()
  36. wpm$wpm <- 0
  37. })
  38. observeEvent(typing()$time, {
  39. wpm$time <- c(wpm$time, typing()$time)
  40. wpm$wpm <- c(wpm$wpm, typing()$wpm)
  41. })
  42. prompt <- reactive({
  43. typing_reset()
  44. sample(stringr::sentences, n_prompt)
  45. })
  46. output$prompt <- renderUI({
  47. tags$blockquote(lapply(prompt(), tags$p))
  48. })
  49. has_stringdist <- requireNamespace("stringdist", quietly = TRUE)
  50. if (!has_stringdist) {
  51. warning(
  52. "Install `stringdist` to get typing errors: install.packages('stringdist')",
  53. immediate. = TRUE, call. = FALSE
  54. )
  55. }
  56. output$wpm <- renderUI({
  57. req(typing()$wpm)
  58. wpm_class <- paste(
  59. "wpm",
  60. if (typing()$wpm < 40) {
  61. "text-danger"
  62. } else if (typing()$wpm < 75) {
  63. "text-warning"
  64. } else {
  65. "text-success"
  66. }
  67. )
  68. tagList(
  69. div(
  70. class = if (!has_stringdist) "col-xs-12" else "col-xs-6 col-sm-12",
  71. tags$h2(
  72. class = wpm_class,
  73. round(typing()$wpm, 2), "wpm"
  74. )
  75. ),
  76. if (has_stringdist) div(
  77. class = "col-xs-6 col-sm-12",
  78. tags$h2(
  79. class = "errors",
  80. stringdist::stringdist(
  81. substring(
  82. paste(prompt(), collapse = "\n"),
  83. 1,
  84. nchar(typing()$text)
  85. ),
  86. typing()$text
  87. ),
  88. "errors"
  89. )
  90. )
  91. )
  92. })
  93. return(reactive(reactive_df(wpm)))
  94. }