Skip to content

feat(tanstack): deferredTrigger: "load" — dispatch deferred sections on mount - #580

Merged
aline-pereira merged 3 commits into
mainfrom
feat/deferred-trigger-load
Sep 28, 2026
Merged

aline-pereira merged 3 commits into
mainfrom
feat/deferred-trigger-load

Conversation

@aline-pereira

@aline-pereira aline-pereira commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

feat(tanstack): deferredTrigger: "load" — dispatch deferred sections on mount

The gap

On Fresh, a ⚡ section ships a skeleton and then fills itself in right after
hydration: DispatchAsyncRender supports partialTriggerMode: "load", which
clicks the hidden partial trigger on mount, no scroll involved.

DeferredSectionWrapper has no equivalent. Its only trigger is an
IntersectionObserver (rootMargin: "300px", behind a requestAnimationFrame),
so on a migrated site everything below the fold does not exist until the user
scrolls. Measured on a storefront mid-migration, loading the home and never
scrolling:

                                   Fresh (prod)   TanStack (candidate)
document.documentElement.scrollHeight     5251     3488  (never changes)
product shelf in the DOM                ~700ms     never (30s timeout)

The page is short, the shelves/blog/footer are absent, and every
below-the-fold analytics impression is lost — on a fast flick the observer often
never fires at all. AsyncRenderingConfig had no knob for this, and neither the
loading: "eager" prop of CMS Lazy.tsx nor the behavior of Deferred.tsx
is read by resolveSectionShallow, so there was no way out from site code.

The change

setAsyncRenderingConfig({ deferredTrigger: "load" }) makes a deferred wrapper
call load() straight from its mount effect, skipping the rAF and the observer.

Default is "intersection" — an existing site that just bumps the framework
behaves exactly as before, and the cheap path stays the default for sites that
never had the Fresh semantics.

getDeferredTrigger() lives in its own zero-import module
(cms/deferredTrigger.ts) rather than in resolve.ts: DecoPageRenderer is a
client component and importing anything from the full cms barrel drags
node:async_hooks/node:fs/promises into the browser bundle — the same reason
cms/client.ts exists. It reads the same globalThis.__deco.asyncConfig bag
setAsyncRenderingConfig() writes, and sites run their setup.ts on both
sides, so the value is already there when a wrapper mounts.

Tests

  • cms/deferredTrigger.test.ts — the fallback to "intersection" when the
    config is missing entirely and when it exists but omits the option, plus the
    read of "load".
  • cms/resolve.test.ts — the default in setAsyncRenderingConfig(), and that a
    later partial call (the { alwaysEager } one applySectionConventions()
    makes after the site's setup) does not reset the trigger.

packages/blocks and packages/tanstack: typecheck ✅, build ✅, biome
diagnostics unchanged on every file touched. The 31 failures under
packages/blocks/src/cms/{loader,layoutCacheRace}.test.ts,
packages/tanstack/src/sdk/workerEntry.test.ts and
packages/blocks-cli/scripts/upgrade-6-to-7.test.ts reproduce identically on a
clean main — pre-existing, untouched here.

Co-Authored-By: Claude Opus 5 (1M context) [email protected]

Refs deco-sites/oficina-tanstack#419

🤖 Generated with Claude Code


Summary by cubic

Adds deferredTrigger: "load" so deferred (⚡) sections fetch their real markup on mount instead of waiting for the scroll-triggered IntersectionObserver, matching Deco on Fresh's partialTriggerMode: "load" behavior.

  • Default stays "intersection", so existing sites behave exactly as before.
  • getDeferredTrigger() is a zero-import module reading the shared globalThis.__deco.asyncConfig bag, keeping server-only deps out of the browser bundle.
  • deferredTrigger is optional on the exported AsyncRenderingConfig so a literal built outside the package keeps compiling; setAsyncRenderingConfig() always fills it.
  • Later partial setAsyncRenderingConfig() calls (like the { alwaysEager } merge after a site's setup) don't reset the trigger.
  • Set it from a client-loaded module (normally setup.ts); setting it server-only leaves the client silently on "intersection".
  • The cost is a request burst — every deferred section POSTs in the same commit, on first load and on each SPA navigation. Site-wide for now; a per-section override is the planned successor.
  • Read only by @decocms/tanstack; a no-op in @decocms/nextjs.

Written for commit 097f3ca. Summary will update on new commits.

Review in cubic

…on mount

## The gap

On Fresh, a ⚡ section ships a skeleton and then fills itself in right after
hydration: `DispatchAsyncRender` supports `partialTriggerMode: "load"`, which
clicks the hidden partial trigger on mount, no scroll involved.

`DeferredSectionWrapper` has no equivalent. Its only trigger is an
IntersectionObserver (`rootMargin: "300px"`, behind a `requestAnimationFrame`),
so on a migrated site everything below the fold does not exist until the user
scrolls. Measured on a storefront mid-migration, loading the home and never
scrolling:

```
                                   Fresh (prod)   TanStack (candidate)
document.documentElement.scrollHeight     5251     3488  (never changes)
product shelf in the DOM                ~700ms     never (30s timeout)
```

The page is short, the shelves/blog/footer are absent, and every
below-the-fold analytics impression is lost — on a fast flick the observer often
never fires at all. `AsyncRenderingConfig` had no knob for this, and neither the
`loading: "eager"` prop of CMS `Lazy.tsx` nor the `behavior` of `Deferred.tsx`
is read by `resolveSectionShallow`, so there was no way out from site code.

## The change

`setAsyncRenderingConfig({ deferredTrigger: "load" })` makes a deferred wrapper
call `load()` straight from its mount effect, skipping the rAF and the observer.

**Default is `"intersection"`** — an existing site that just bumps the framework
behaves exactly as before, and the cheap path stays the default for sites that
never had the Fresh semantics.

`getDeferredTrigger()` lives in its own zero-import module
(`cms/deferredTrigger.ts`) rather than in `resolve.ts`: `DecoPageRenderer` is a
client component and importing anything from the full `cms` barrel drags
`node:async_hooks`/`node:fs/promises` into the browser bundle — the same reason
`cms/client.ts` exists. It reads the same `globalThis.__deco.asyncConfig` bag
`setAsyncRenderingConfig()` writes, and sites run their `setup.ts` on both
sides, so the value is already there when a wrapper mounts.

## Tests

- `cms/deferredTrigger.test.ts` — the fallback to `"intersection"` when the
  config is missing entirely and when it exists but omits the option, plus the
  read of `"load"`.
- `cms/resolve.test.ts` — the default in `setAsyncRenderingConfig()`, and that a
  later partial call (the `{ alwaysEager }` one `applySectionConventions()`
  makes after the site's setup) does not reset the trigger.

`packages/blocks` and `packages/tanstack`: typecheck ✅, build ✅, biome
diagnostics unchanged on every file touched. The 31 failures under
`packages/blocks/src/cms/{loader,layoutCacheRace}.test.ts`,
`packages/tanstack/src/sdk/workerEntry.test.ts` and
`packages/blocks-cli/scripts/upgrade-6-to-7.test.ts` reproduce identically on a
clean `main` — pre-existing, untouched here.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@aline-pereira
aline-pereira requested a review from a team September 28, 2026 15:56
JonasJesus42
JonasJesus42 previously approved these changes Sep 28, 2026

@JonasJesus42 JonasJesus42 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM. It's opt-in, the default stays "intersection", so a framework bump changes nothing for existing sites.

What I checked:

  • deferredTrigger.ts has zero imports, so re-exporting it from cms/client.ts is browser-safe.
  • The client does see the value: router.tsx imports setup.ts, and the vite plugin stubs node:async_hooks, so setAsyncRenderingConfig() writes globalThis.__deco.asyncConfig in the browser too.
  • The later applySectionConventions() call spreads existing, so the trigger survives. The new test covers it.
  • load() runs inside useEffect, so there's no hydration mismatch risk.

Non-blocking notes:

  1. Where the setting has to run. It only takes effect on the client if setAsyncRenderingConfig({ deferredTrigger: "load" }) runs in a module the browser also loads (normally setup.ts imported from router.tsx). If a site sets it from server-only code (the worker entry or server.ts), the client silently falls back to "intersection". One line in the JSDoc would save someone a debugging session.
  2. Request burst. With "load", every deferred section fires its serverFn POST in the same commit, on first load and on SPA navigation. That matches Fresh, but it's exactly the burst the rAF/observer path was added to avoid. Worth stating the tradeoff in the docs. Longer term, a per-section override (for example, honoring Lazy.tsx's loading prop) might fit better than a single site-wide switch.
  3. Nit: the option lives in @decocms/blocks but only @decocms/tanstack reads it. The JSDoc could say it has no effect in @decocms/nextjs.

…o "load"

Notas não-bloqueantes do review, todas de documentação.

1. **Onde a opção roda.** `getDeferredTrigger()` é lido no browser, então
   `setAsyncRenderingConfig()` só tem efeito se rodar num módulo que o bundle do
   cliente também carrega — normalmente o `setup.ts`, importado pelo
   `router.tsx`. Setado só no servidor (worker entry, `server.ts`), o servidor
   defere como esperado e o cliente cai calado no `"intersection"`, o que parece
   exatamente a opção sendo ignorada. Documentado nos dois JSDoc e no CHANGELOG.

2. **Custo do burst.** Com `"load"`, toda seção deferida dispara o POST no mesmo
   commit, no primeiro load e em cada navegação SPA — que é justamente o que o
   rAF + observer existem pra evitar, e também exatamente o que o Fresh faz.
   Registrado como tradeoff explícito, junto com a sucessão natural que o review
   sugeriu: um override por seção, honrando o prop `loading` que o wrapper
   `Lazy.tsx` do CMS já carrega e que o resolver hoje descarta.

3. A opção mora no `@decocms/blocks` mas só o `@decocms/tanstack` lê. Dito nos
   dois JSDoc e no CHANGELOG: no-op no `@decocms/nextjs`.

Mais uma entrada no `CHANGELOG.md`, na seção Unreleased que já trata do deferral
— um leitor que chega ali pelo `foldThreshold` precisa saber que essa válvula
existe.

Sem mudança de código: testes 82/82, typecheck ✅ em blocks e tanstack, biome
limpo no `deferredTrigger.ts` (o `resolve.ts` segue com os mesmos 3 diagnósticos
pré-existentes).

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@aline-pereira

Copy link
Copy Markdown
Contributor Author

Obrigado — as três notas viraram documentação em 399542c, sem mudança de código.

1. Onde a opção roda. Ponto justo, e o modo de falha é o pior tipo: o servidor defere como esperado e o cliente cai calado no "intersection", o que parece exatamente a opção sendo ignorada. Está agora nos dois JSDoc (deferredTrigger.ts e o campo em AsyncRenderingConfig) e no CHANGELOG, com a frase "set from server-only code (the worker entry, server.ts) leaves the client on "intersection" with no warning".

2. Burst. Documentado como tradeoff explícito, e não como detalhe: toda seção deferida dispara o POST no mesmo commit, no primeiro load e em cada navegação SPA — que é exatamente o que o rAF + observer existem pra evitar, e também exatamente o que o Fresh faz. Ou seja, é o default certo pra um site migrado e o errado pra uma página com muitas seções deferidas pesadas.

Sobre o override por seção: concordo que é o sucessor natural, e a peça já existe — o wrapper Lazy.tsx do CMS carrega um prop loading, e o resolveSectionShallow (resolve.ts) descarta. Fica citado nominalmente no JSDoc e no CHANGELOG pra quem pegar isso depois não precisar redescobrir. Não trouxe pra cá porque mudaria o PR de "válvula opt-in" pra "novo eixo de configuração por seção", e o site que motivou isso precisa do interruptor global de qualquer jeito.

3. Dito nos dois JSDoc e no CHANGELOG: lido só pelo @decocms/tanstack, no-op no @decocms/nextjs.

Entrou também uma entrada no CHANGELOG.md, na seção Unreleased que já trata do deferral — quem chega ali pelo foldThreshold precisa saber que essa válvula existe.

Testes 82/82, typecheck ✅ em blocks e tanstack, biome limpo no deferredTrigger.ts.

aline-pereira added a commit that referenced this pull request Sep 28, 2026
… com o #580

As duas branches abertas inseriam a seção nova no mesmo ponto — logo antes do
`## 5.0.0` — então `git merge-tree` acusava conflito: quem mergeasse primeiro
deixava a outra pra resolver à mão, num arquivo em que o conflito é puro ruído.

Esta vai pro topo do corpo, depois do preâmbulo, que também é a ordem
convencional (mais recente primeiro). A do #580 continua encostada no
`## 5.0.0`, dentro da seção de deferral que ela estende. `merge-tree` limpo
agora.

Só reposicionamento; o texto é o mesmo.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Revisando a compatibilidade antes do merge: o campo tinha entrado como
**obrigatório** numa interface que o `@decocms/blocks/cms` exporta. Nada quebra
em runtime, mas qualquer consumidor fora do pacote que montasse um
`AsyncRenderingConfig` literal passaria a falhar o typecheck com "missing
property deferredTrigger" — uma quebra de tipo por uma feature puramente aditiva.
Foi exatamente o que aconteceu com o `mkCfg` do `resolve.test.ts` neste PR, o que
já era o sinal.

Opcional agora. Custo interno zero: o `setAsyncRenderingConfig()` sempre preenche,
então o config guardado nunca fica sem o campo; o setter lê
`existing?.deferredTrigger` com optional chaining; e o único leitor sancionado,
o `getDeferredTrigger()`, já cai no default. Nenhum código de produção lê
`.deferredTrigger` de um objeto de config — só do global.

O `mkCfg` do teste volta a **não** declarar o campo, de propósito: ele passa a
valer como o literal de um consumidor externo. Se aquilo voltar a quebrar, a
opção deixou de ser retrocompatível e o teste avisa.

blocks + tanstack typecheck ✅, 82/82 testes ✅.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@aline-pereira

Copy link
Copy Markdown
Contributor Author

Mais um achado ao revisar compatibilidade antes do merge, esse de tipo — corrigido em 097f3ca.

O campo tinha entrado como obrigatório no AsyncRenderingConfig, que o @decocms/blocks/cms exporta. Runtime seguia intacto, mas qualquer consumidor fora do pacote que montasse um literal dessa interface passaria a falhar o typecheck com "missing property deferredTrigger" — quebra de tipo por uma feature puramente aditiva. O sinal estava no próprio PR: o mkCfg do resolve.test.ts precisou ganhar o campo, e ele é exatamente o formato que um consumidor externo teria.

Opcional agora, com custo interno zero: o setAsyncRenderingConfig() sempre preenche (o config guardado nunca fica sem o campo), o setter lê existing?.deferredTrigger com optional chaining, e o getDeferredTrigger() já cai no default. Confirmei que nenhum código de produção lê .deferredTrigger de um objeto de config — só do global.

E o mkCfg do teste voltou a não declarar o campo, de propósito: ele passa a valer como o literal de um consumidor externo, então se isso quebrar de novo o teste avisa em vez de a gente descobrir num bump.

Com isso o "um bump não muda nada" vale também no typecheck, não só em runtime. blocks + tanstack typecheck ✅, 82/82 ✅.

@aline-pereira
aline-pereira merged commit 37661a5 into main Sep 28, 2026
1 check passed
aline-pereira added a commit that referenced this pull request Sep 29, 2026
`isCmsDeferralWrapped` treats every `website/sections/Rendering/Lazy.tsx`
wrapper as a deferral, whatever props it carries. Fresh does not: the
wrapper's own loader short-circuits on `loading: "eager"` and renders the
inner section inline, with no FallbackWrapper.

```ts
// website/sections/Rendering/Lazy.tsx
const shouldRender = loading === "eager" || shouldForceRender({ … });
if (shouldRender) return { loading: "eager", section: await section() };
```

```tsx
if (loading === "lazy") {
  return <ctx.FallbackWrapper …><section.Component … /></ctx.FallbackWrapper>;
}
return <section.Component {...section.props} />;   // eager → inline
```

Decofiles carried over from Deco on Fresh use exactly that shape for the
named `Footer` block — `Lazy.tsx` at the root plus `loading: "eager"` — so
ignoring the prop turns a section prod server-renders into a skeleton that
only materializes client-side.

Measured on a migrated storefront (`/sobre`, `respectCmsLazy: true`), with
JavaScript disabled — i.e. what a non-rendering consumer of the HTML sees:

|                        | prod (Fresh) | migrated target |
|------------------------|--------------|-----------------|
| `<footer>` links       | 17           | 2               |
| `<footer>` text length | 474          | 0               |
| links in the document  | 27           | 11              |

Gone from the served HTML: the newsletter heading, the three social links,
all fourteen sitemap links, the postal address and the CNPJ. With JavaScript
on, the footer stayed empty at `scrollY = 0` for as long as it was observed
(16s) — it only filled once scrolled into view. Bots are unaffected:
`shouldDeferSection` already short-circuits on `isBotReq`.

The fix keeps walking inward after an eager wrapper instead of returning
`false` outright, so a nested lazy wrapper further down still defers —
mirroring Fresh, which resolves the inner section and lets its own loader
decide.

This is not a code-level override of the admin: `loading` is authored in the
CMS, so the editor stays the source of truth. It reads the whole instruction
instead of half of it, which is why it does not run into the objection that
closed #573.

Refs #573, #580, deco-sites/oficina-tanstack#419

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
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

Successfully merging this pull request may close these issues.

2 participants