ReviewOS

stacks/stx

signals: ship <Suspense>, useOptimistic, <Transition> — the standard reactive primitive set

#1742
Closed glennmichael123 opened this 23 days ago · 3 comments
23 days ago

Problem

Three patterns appear at every callsite in bench-review and have no framework support:

Loading boundaries

bench-review's pattern, repeated everywhere:

<ul :if="!commentsLoaded()">
  <li :for="i in [1, 2]">skeleton...</li>
</ul>
<div :else-if="comments().length === 0">empty state</div>
<ul :else>
  <li :for="c in comments()">{{ c.body }}</li>
</ul>

That's three branches per data dependency. Multiply by ~15 fetched surfaces in bench-review = ~45 conditional branches.

The standard primitive is <Suspense>:

<Suspense fallback="<Skeleton count={2} />">
  <CommentsList />   <!-- can throw a promise via useQuery suspense mode; Suspense catches and renders fallback -->
</Suspense>

One boundary handles all descendant loading states.

Optimistic mutations

bench-review's "like a review" flow:

async function toggleLike() {
  const prevLiked = liked()
  liked.set(!liked())          // optimistic
  likes.set(likes() + (liked() ? 1 : -1))
  try {
    await authStore.authFetch('/api/reviews/X/like', { method: 'POST' })
  } catch {
    liked.set(prevLiked)       // rollback
    likes.set(likes() - (liked() ? 1 : -1))
  }
}

That's a lot of manual snapshot/rollback. Vue + React both have first-class primitives:

const [optimisticLikes, addOptimistic] = useOptimistic(likes(), (current, delta) => current + delta)

async function toggleLike() {
  addOptimistic(liked() ? -1 : 1)
  try { await authStore.authFetch('/api/reviews/X/like', { method: 'POST' }) }
  catch { /* useOptimistic auto-rolls back on the next render after the action settles */ }
}

Enter/leave transitions

bench-review's dropdown reveal:

<div
  x-class="bellOpen() ? 'opacity-100 translate-y-0' : 'opacity-0 -translate-y-2 pointer-events-none'"
  class="transition-all duration-150"
>

Pre-existing memory note (feedback_stx_xclass_static_in_array) flags how easy this is to get wrong. The standard primitive is <Transition>:

<Transition name="fade-slide" enter-from="opacity-0 -translate-y-2" enter-to="opacity-100 translate-y-0" leave-to="opacity-0 -translate-y-2">
  <div :if="bellOpen()">...</div>
</Transition>

For list transitions (adding/removing review cards), <TransitionGroup> with auto-FLIP positioning is the standard primitive.

Proposed: ship all three

<Suspense>:

  • Catches any descendant component that's in a "suspended" state (via integration with P1.4's useQuery)
  • Renders the fallback slot until all descendants resolve
  • errorFallback slot catches errors thrown during render
  • Nested <Suspense> boundaries compose (inner fallback shows first, then outer when fully resolved)

useOptimistic(baseSignal, reducer):

  • Returns [optimisticValue, applyOptimistic]
  • applyOptimistic(input) queues a pending update that's visible immediately
  • When the corresponding async action settles, the optimistic state is discarded and baseSignal is the source of truth
  • Auto-rolls back on action error

<Transition> / <TransitionGroup>:

  • Class-driven enter/leave transitions on :if toggle
  • FLIP positioning for list reorders
  • appear prop for first-mount transitions
  • JS hook props (onEnter, onLeave) for advanced cases

Prior art

  • <Suspense> — React 18, Vue 3, SolidJS, Qwik. All have it.
  • useOptimistic — React 19's official primitive, TanStack Query's onMutate mechanic.
  • <Transition> — Vue's built-in, SolidJS Transition, React's Framer Motion + <motion.div>.

Impact

  • <Suspense> reduces every fetched-data surface's conditional rendering by 50-70%.
  • useOptimistic removes the snapshot-rollback boilerplate from every mutation.
  • <Transition> removes the hand-rolled x-class transition class strings (which have known footguns — see feedback_stx_xclass_static_in_array).

Phasing

  • Phase 1: <Transition> (smallest, doesn't depend on other primitives)
  • Phase 2: useOptimistic (depends on P1.4 if integrated with useMutation, but works standalone too)
  • Phase 3: <Suspense> (depends on P1.4's useQuery to throw promises in suspended state)

Happy to PR Phase 1.

22 days ago

Progress update — landing this incrementally.

Phase 2 — useOptimistic: shipped in aa284068a1 (on main). React-19-style optimistic state adapted to signals: const [optimistic, addOptimistic] = useOptimistic(base, reducer). The overlay auto-discards the moment base changes (happy path needs no cleanup); addOptimistic returns a settle() to roll back, or pass a promise as the 2nd arg to auto-settle. Implemented in both reactive impls (signals-api.ts + the runtime) with a parity test, exposed on window.stx, wired into <script client> auto-imports, typed, and documented. 9 unit + 12 parity tests; full suite green.

Phase 1 — <Transition>: already ships in @stacksjs/components (ui/transition/Transition.stx) with presets (fade/slide/scale/rotate/zoom), enter/leave/appear/duration/delay, backed by the JS mechanics in packages/stx/src/transitions.ts. No new work needed — usable today as <Transition name="fade">…</Transition>. (<TransitionGroup> FLIP list transitions would be the remaining extension here.)

Phase 3 — <Suspense>: in progress. Today only the streaming @suspense directive exists (server-push via streaming.ts). The Vue/React-style client <Suspense fallback> boundary — catch suspended descendants, render fallback until resolved, errorFallback on throw, nested composition — depends on a useQuery suspense mode (a query throws a promise while loading). Building that next.

22 days ago

Phase 3 — <Suspense>: shipped in 46be770f87 (on main). The trio is now complete:

PrimitiveStatus
useOptimistic✅ shipped (aa284068a1)
<Transition>✅ already in @stacksjs/components (presets + enter/leave/appear)
<Suspense>✅ shipped (46be770f87)

How <Suspense> works:

  • useQuery / useFetch gain a { suspense: true } option → the query registers { el, loading, error } in a page-global registry at creation time.
  • The <Suspense> builtin renders three regions (fallback / error / content, content present-but-hidden so descendant scripts run + register).
  • At init, bindSuspense claims the descendant queries for which it's the nearest [data-stx-suspense] ancestor (DOM containment + closest(), so nested boundaries don't steal each other's queries), derives the aggregate loading/error, and toggles the regions reactively.
  • fallback/errorFallback via props or slot="fallback" / slot="error"; no queries inside → content shows immediately. Boundaries nest.

Also added: transformSignalScript now sets __STX_CURRENT_ELEMENT__ during partial <script client> execution, so element-aware primitives (suspense registration, defineProps/defineEmits) resolve against the right element.

Verification: the boundary's reactive region-toggle logic is fully covered by DOM tests against the real runtime (test/signals/suspense-boundary.test.ts — loading/resolved/errored/no-queries). The end-to-end auto-wiring (a live page with useQuery({ suspense }) components inside <Suspense>) exercises parse-time partial-scope registration that's validated structurally + unit-level; a real-browser smoke on a bench-review surface is the recommended final check. Full suite 9264 pass / 0 fail.

Remaining (optional extension): <TransitionGroup> with FLIP positioning for list reorders — noted in the issue but not built here. Happy to follow up if wanted; otherwise this can close.

22 days ago

<TransitionGroup>: shipped in c5b3a885b1 (on main) — the whole primitive set is now done.

<TransitionGroup name="card" tag="ul" class="space-y-2">
  <li :for="r in reviews()" :key="r.id" class="card">{{ r.title }}</li>
</TransitionGroup>

The runtime's bindFor, when its parent is a [data-stx-transition-group] (and only after the first render), runs the Vue-style class lifecycle: name-enter-* on insert, name-leave-* on removal (the node stays in the DOM until the transition ends), and a FLIP move (name-move) on reorder. Every phase has a duration-based timeout fallback so a missed transitionend can't strand a leaving node. The integration is fully guarded — plain :for lists never touch any transition code, so the bindFor diff path is unchanged for them (pinned by the unchanged 476/0 signals suite).

Tested: the enter/leave/flip helpers driven against the real runtime via the DOM shim, plus builtin markup + pipeline resolution. The FLIP visual (real getBoundingClientRect deltas) warrants a quick real-browser smoke — happy-dom has no layout — but the class lifecycle and leave-then-remove timing are covered.


#1742 summary — all four addressed

PrimitiveStatus
useOptimistic✅ aa284068a1 — dual-impl + parity
<Transition>✅ already in @stacksjs/components
<Suspense>✅ 46be770f87 — client loading boundary + useQuery({ suspense })
<TransitionGroup>✅ c5b3a885b1 — FLIP list transitions

Closing — the standard reactive primitive set is in. (Full suite 9284 pass / 0 fail throughout.)

Sign in to comment on this issue.