r-for-educators / flair

decorate your R code
https://r-for-educators.github.io/flair/index.html
Other
211 stars 21 forks source link

Use consistent labels for flaired chunks #31

Closed jdblischak closed 3 years ago

jdblischak commented 3 years ago

Thanks for this great package. I really liked how @sciencificity combined flair with workflowr to share her R4DS exercise solutions.

However, I noticed that one of the workflowr features was missing. Typically below each figure, workflowr inserts a button with a table of past versions of the figure file. These are missing in https://sciencificity.github.io/R4DS_study_exams/ch1_ggplot.html

I did some investigating, and I think this is because flair creates a new unlabeled chunk to knit with knit_child(). Since this name is not constant, when workflowr searches the Git log for past versions of that figure file, it can't find them.

To address this, this PR gives each chunk a consistent label by appending -flaired to the existing chunk label. And in the case where the same source chunk is decorated more than once (like in the vignette), each chunk is additionally assigned a random string to ensure the labels are unique. This is fine for workflowr since the table of past versions of the figure would still be included the first time the source chunk was decorated.

Please let me know if you are interested in this PR. I'm happy to make adjustments to the strategy and also add tests.

Below is an example with a plot hook that demonstrates how the labels are applied.

---
title: flair with plot hook
output: html_document
---

```{r setup}
library(flair)
library(knitr)
custom_plot_hook <- function(x, options) {
  note <- sprintf("<small>The plot '%s' was created on %s</small>",
                  options$label, Sys.Date())
  c(knitr::hook_plot_md(x, options), "\n", note)
}
knit_hooks$set(plot = custom_plot_hook)
plot(1:10)
plot(1:10)
decorate_chunk("example-with-flair")
decorate_chunk("example-with-flair")

And here is an example of the edge case where the user already labeled a chunk with the same name that flair was going to automatically name the decorated chunk passed to `knit_child()`. In this case, it automatically adds the random string to ensure the label is unique.

title: flair with plot hook output: html_document

library(flair)
library(knitr)
custom_plot_hook <- function(x, options) {
  note <- sprintf("<small>The plot '%s' was created on %s</small>",
                  options$label, Sys.Date())
  c(knitr::hook_plot_md(x, options), "\n", note)
}
knit_hooks$set(plot = custom_plot_hook)
plot(1:10)
# Just happened to name this chunk exactly like the auto-generated chunk would be
kbodwin commented 3 years ago

This is awesome!

You've hit the nail on the head with why I drop the chunk label in the knit_child step; I see no harm in giving it a -flaired name instead, especially if it plays nicer with workflowr.

Thank you so much!