rstudio / learnr

Interactive Tutorials with R Markdown
https://pkgs.rstudio.com/learnr
Apache License 2.0
713 stars 239 forks source link

Initial code in exercises with `exercise.eval = TRUE` is missing new lines #602

Open gadenbuie opened 3 years ago

gadenbuie commented 3 years ago

When exercise.eval=TRUE, the initial code in an exercise does not match the code entered by the user. It appears to be concatenated with " " rather than "\n".

---
title: "Tutorial"
output: learnr::tutorial
runtime: shiny_prerendered
---

```{r setup, include=FALSE}
library(learnr)
knitr::opts_chunk$set(echo = FALSE)

Topic 1

round(1) 

sqrt(1)

The exercise on initialization will have 

```r
round(1)  sqrt(1)
gadenbuie commented 3 years ago

The current implementation was written when we the tutorial app didn't "know" that much about each exercise. As it is now, we pre-render the code into HTML and then find the source <pre> chunks, using the inner text for the initial code and leaving behind the output.

Now that we have an exercise object and we know what the initial code should be exactly, we don't need to read the source from the HTML directly, especially since that's lossy -- knitr drops empty lines when the output is interleaved with the source. Instead, we can pre-render the output, hiding the source and always get the source from the exercise data.

That said, because we store the exercise object in an R data structure for use by the Shiny app, we'd probably be better off serializing the initial code into JSON in a <script> element in the HTML and using that directly so that it's available to the browser on load.