Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a function to update code box dynamically from server #770

Open
gadenbuie opened this issue Mar 10, 2023 · 0 comments
Open

Add a function to update code box dynamically from server #770

gadenbuie opened this issue Mar 10, 2023 · 0 comments

Comments

@gadenbuie
Copy link
Member

This has come up more than once and is likely fraught with edge cases. But we could provide something a little more user-friendly, based on my answer in the discussion here.

It is possible to update the text in a code box dynamically from the Shiny server that runs the learnr tutorial, which means that you could in theory use the query parameters to initialize the code boxes. There are probably more than a few edge cases you'd want to think through (or end up running into).

The process for updating an exercise code box from the server isn't very straightforward and it requires writing a little bit of JavaScript. I'd recommend taking a look at my answer to a similar question on Posit Community.

First, you'd include a chunk of JavaScript in your learnr document.

```{js echo=FALSE}
//
// A custom Shiny message handler that updates the code in any exercise
// From R you'll send a list(label = "exercise-chunk-label", code = "new code for editor"))
//
Shiny.addCustomMessageHandler('set-exercise-code', function(x) {
  var el = $(`.tutorial-exercise[data-label="${x.label}"] .tutorial-exercise-code-editor`)
  var exerciseInput = Shiny.inputBindings.bindingNames["tutorial.exerciseInput"].binding
  exerciseInput.setValue(el, {code: x.code})
})
```

Then, include this function in your setup chunk or in a chunk with context = "server":

update_exercise <- function(label, code, session = shiny::getDefaultReactiveDomain()) {
  session$sendCustomMessage("set-exercise-code", list(label = label, code = code))
}

which you can then use to update an exercise using the label of its chunk:

update_exercise("plus", "2 + 2")

I hope that helps! If you do figure out how to make this work, we'd love to see what you come up with!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant