qmd-lab / closeread

6 stars 0 forks source link

Code appears before plots when using figure layouts #41

Open andrewpbray opened 3 weeks ago

andrewpbray commented 3 weeks ago

In format: html, the following document will first show the echoed code, then a two column layout with a total of three plots and a data frame. In format: closeread-html, the echoed code shows up after the two column layout.


---
title: "Orphaned code output test"
format: closeread-html
---

:::{.cr-layout}

Test test test

:::{.cr-crossfade cr-to="big-code"}
Test test test
:::

Test test test

```{r}
#| echo: true
#| cr-id: big-code
#| layout-ncol: 2

a <- rnorm(100)
b <- 1 + rexp(100)
c <- a + b

a <- rnorm(100)
b <- 1 + rexp(100)
c <- a + b

a <- rnorm(100)
b <- 1 + rexp(100)
c <- a + b

plot(mtcars$mpg, mtcars$dist)

plot(mtcars$hp, mtcars$dist)

plot(mtcars$hp, mtcars$mpg)

mtcars
\```

:::
andrewpbray commented 3 weeks ago

Initial diagnosis

When our lua filter encounters the layout div, in the AST the code cell looks like:

Div {.cell cr-id="big-code" layout-ncol="2"} Blocks:

  1. CodeBlock {.r .cell-code}
  2. Div {.cell-output-display} Blocks:
    1. Image
  3. CodeBlock {.r .cell-code}
  4. Div {.cell-output-display} Blocks:
    1. Image
  5. CodeBlock {.r .cell-code}
  6. Div {.cell-output-display} Blocks:
    1. Image
  7. CodeBlock {.r .cell-code}
  8. Div {.cell-output-display} Blocks:
    1. CodeBlock

That is, it separates the code into different CodeBlocks based on the lines that produce output, then interleaves those CodeBlocks with output (3 images and a CodeBlock to print the dataframe).

At the end of our lua filter, the whole DivAbove is wrapped into two more Divs:

Div {.sticky-col} Blocks:

  1. Div {.sticky-col-stack} Blocks: DivAbove

That looks about right! The fact that in the flat html format the CodeBlock is not separated and interleaved into the output suggests the filter for layout-ncol runs after our filter does to rearrange those blocks. That rearrangement must be breaking out Div wrapper structure.

Next steps: write a separate lua filter that runs late to see if we can catch the AST post-layout filter.

andrewpbray commented 3 weeks ago

@jimjam-slam Oy, this was a deep cut:

https://github.com/quarto-dev/quarto-cli/discussions/10174

I think the issue is that we're looking for cr-id's which no longer are parents to the CodeBlock, so it gets treated as a separate thing.

jimjam-slam commented 3 weeks ago

Dang, nice work on the diagnosis!