Repository navigation
feat(tanstack): deferredTrigger: "load" — dispatch deferred sections on mount - #580
Conversation
…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]>
JonasJesus42
left a comment
There was a problem hiding this comment.
LGTM. It's opt-in, the default stays "intersection", so a framework bump changes nothing for existing sites.
What I checked:
deferredTrigger.tshas zero imports, so re-exporting it fromcms/client.tsis browser-safe.- The client does see the value:
router.tsximportssetup.ts, and the vite plugin stubsnode:async_hooks, sosetAsyncRenderingConfig()writesglobalThis.__deco.asyncConfigin the browser too. - The later
applySectionConventions()call spreadsexisting, so the trigger survives. The new test covers it. load()runs insideuseEffect, so there's no hydration mismatch risk.
Non-blocking notes:
- 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 (normallysetup.tsimported fromrouter.tsx). If a site sets it from server-only code (the worker entry orserver.ts), the client silently falls back to"intersection". One line in the JSDoc would save someone a debugging session. - 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, honoringLazy.tsx'sloadingprop) might fit better than a single site-wide switch. - Nit: the option lives in
@decocms/blocksbut only@decocms/tanstackreads 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]>
|
Obrigado — as três notas viraram documentação em 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 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 3. Dito nos dois JSDoc e no CHANGELOG: lido só pelo Entrou também uma entrada no Testes 82/82, typecheck ✅ em blocks e tanstack, biome limpo no |
… 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]>
|
Mais um achado ao revisar compatibilidade antes do merge, esse de tipo — corrigido em O campo tinha entrado como obrigatório no Opcional agora, com custo interno zero: o E o Com isso o "um bump não muda nada" vale também no typecheck, não só em runtime. blocks + tanstack typecheck ✅, 82/82 ✅. |
`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]>
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:
DispatchAsyncRendersupportspartialTriggerMode: "load", whichclicks the hidden partial trigger on mount, no scroll involved.
DeferredSectionWrapperhas no equivalent. Its only trigger is anIntersectionObserver (
rootMargin: "300px", behind arequestAnimationFrame),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:
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.
AsyncRenderingConfighad no knob for this, and neither theloading: "eager"prop of CMSLazy.tsxnor thebehaviorofDeferred.tsxis read by
resolveSectionShallow, so there was no way out from site code.The change
setAsyncRenderingConfig({ deferredTrigger: "load" })makes a deferred wrappercall
load()straight from its mount effect, skipping the rAF and the observer.Default is
"intersection"— an existing site that just bumps the frameworkbehaves 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 inresolve.ts:DecoPageRendereris aclient component and importing anything from the full
cmsbarrel dragsnode:async_hooks/node:fs/promisesinto the browser bundle — the same reasoncms/client.tsexists. It reads the sameglobalThis.__deco.asyncConfigbagsetAsyncRenderingConfig()writes, and sites run theirsetup.tson bothsides, so the value is already there when a wrapper mounts.
Tests
cms/deferredTrigger.test.ts— the fallback to"intersection"when theconfig is missing entirely and when it exists but omits the option, plus the
read of
"load".cms/resolve.test.ts— the default insetAsyncRenderingConfig(), and that alater partial call (the
{ alwaysEager }oneapplySectionConventions()makes after the site's setup) does not reset the trigger.
packages/blocksandpackages/tanstack: typecheck ✅, build ✅, biomediagnostics unchanged on every file touched. The 31 failures under
packages/blocks/src/cms/{loader,layoutCacheRace}.test.ts,packages/tanstack/src/sdk/workerEntry.test.tsandpackages/blocks-cli/scripts/upgrade-6-to-7.test.tsreproduce identically on aclean
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'spartialTriggerMode: "load"behavior."intersection", so existing sites behave exactly as before.getDeferredTrigger()is a zero-import module reading the sharedglobalThis.__deco.asyncConfigbag, keeping server-only deps out of the browser bundle.deferredTriggeris optional on the exportedAsyncRenderingConfigso a literal built outside the package keeps compiling;setAsyncRenderingConfig()always fills it.setAsyncRenderingConfig()calls (like the{ alwaysEager }merge after a site's setup) don't reset the trigger.setup.ts); setting it server-only leaves the client silently on"intersection".@decocms/tanstack; a no-op in@decocms/nextjs.Written for commit 097f3ca. Summary will update on new commits.