ReviewOS

stacks/stx

signals: pre-evaluate :if / :else / :else-if at SSR when expressions are server-resolvable — emit only the active branch

#1739
Closed glennmichael123 opened this 22 days ago · 1 comment
22 days ago

Problem

The reactive conditional directives (:if, :else, :else-if, x-if, x-else, x-else-if, :show, x-show) currently emit ALL branches to the browser. The SSR processor doesn't analyze whether the branch condition is resolvable server-side; it bakes the directive attribute into the HTML and lets the client-side bindIf / bindIfChain runtime decide.

This is the single architectural decision behind the largest class of bugs and DX gaps in stx:

  • The FOUC class (#1736) — every conditional branch flashes visible until the runtime catches up
  • The scope-walk class (#1737) — disposeSubtreeScopes running during transient bindIf detach deletes nested-scope entries
  • The over-subscription class (#1738) — chain effects re-run on every signal in scope because the picker has to be defensive about which branches get evaluated
  • The "ship more HTML than needed" class — every reader of a published review downloads the markup for the "loading" and "not found" branches too
  • The "hydration mismatch" risk class — every divergence between server-rendered HTML and client-runtime evaluation has to be reconciled at runtime

The vast majority of :if conditions in real apps are server-resolvable. In bench-review (audited just now): 67 of 89 (~75%) :if / :else-if expressions reference only data already in scope at SSR time — judge.status, currentUser.is_admin, review.anonymized, c.author?.id, etc. The remaining 25% are genuinely client-reactive (waiting on an async fetch, derived from a client-only signal).

The framework already has the engine for this — @if(cond) ... @else ... @endif is the Blade-style server-side conditional that eliminates the false branch at render time. v-if / v-else-if / v-else compile down to @if at build time (process.ts ~line 2586's kK function). What's missing is the same treatment for the reactive family when the expression is server-resolvable.

Proposed approach

Two-pass SSR analysis on each :if / :else / :else-if / :show:

Pass 1 — Resolvability check. Parse the expression. Walk the AST. For each identifier:

  • If it's in the server-resolvable scope (variables defined in <script server>, @include parameters, parent loop variables, request context), mark resolvable.
  • If it's in the client-only scope (state from <script client>, store signals, derived values from client signals), mark NOT resolvable.
  • If mixed, mark NOT resolvable.

Pass 2 — Branch elimination. For chains where every branch's expression is server-resolvable:

  • Evaluate each branch's condition at SSR time using the server-scope values.
  • Emit ONLY the chosen branch's HTML.
  • Strip the :if / :else / :else-if attributes from the emitted element.

For chains where any branch references client-only state:

  • Behave exactly as today (emit all branches with directive attributes, let the runtime pick).

Concrete repro reference

Bench-review's article body has this pattern repeated dozens of times:

<article :if="reviewsStore.current">   <!-- client-reactive — keep as runtime :if -->
  <span :if="review.author && review.author.id">    <!-- server-resolvable when @include'd with review — could SSR-eliminate -->
    <StxLink :to="`/user/${review.author.id}`">{{ review.author.name }}</StxLink>
  </span>
  <span :else>Anonymous reviewer</span>
</article>

The outer :if="reviewsStore.current" legitimately needs runtime evaluation (waiting on fetch). The inner :if="review.author && review.author.id" could be evaluated server-side because review is in @include scope at SSR. Today both go through the runtime.

Prior art

  • Vue 3 SSR — compileSSR evaluates v-if with the bound context at server-render time and emits only the active branch
  • Next.js (App Router) — every if in a server component runs server-side, only result reaches the client
  • Astro — SSR-only by default; client interactivity is opt-in via client:* directives. False branches never enter the HTML.
  • SvelteKit — compiler analyzes which branches reference reactive vs static state
  • Nuxt 3 — Vue-equivalent treatment
  • Phoenix LiveView — server-side diffing; only changed branches stream

Impact

SurfaceTodayAfter fix
FOUC for server-known conditionsFlashes both branches until runtime detachesOnly active branch in HTML; no flash possible
HTML bytes for nested conditionalsAll branches shipOnly chosen branch ships
Runtime work (effect runs, processElement walks)Every conditional gets boundOnly client-reactive conditionals get bound
Hydration mismatch riskWhenever runtime evaluates a different answer than SSR expectedEliminated for server-resolved conditions
Cognitive load on adoptersMust understand SSR vs reactive distinctionFramework picks the right strategy per expression

Compatibility

  • Today's reactive runtime stays exactly as-is — the new pass only ELIMINATES branches that don't need runtime treatment
  • Adopters don't change anything; the SSR processor opts in transparently
  • @if/v-if are unaffected (they already SSR-eliminate)
  • :if on elements with data-stx-scope (component boundaries) gets treated as runtime-resolvable by default to avoid scope-init surprises

Phasing

  • Phase 1: AST walker + resolvability marker (no behavior change yet, just instrument and log "would have eliminated N of M conditionals on this page")
  • Phase 2: Eliminate single-branch :if (no :else)
  • Phase 3: Eliminate full chains (:if/:else-if/:else)
  • Phase 4: Eliminate :show (set inline display:none instead of emitting both states)

Happy to PR Phase 1 as a starting point — pure instrumentation, no behavior change, gives a real adoption number to debate Phase 2+ from.

22 days ago

Phase A landed in 5136925.

Shipped: preEvalLiteralReactiveIfs in signal-processing.ts, wired into process.ts after the signal-directive conversion. Literal-valued :if / :show (+ x-if/x-show/@if/@show aliases):

  • truthy literal → strip just the attribute, keep the element
  • falsy literal → drop the element + subtree (void/self-close → drop the start tag)

Only pure literals are decided (true/false/null/undefined/NaN, numeric, quoted string). Identifiers, member access, calls, operators, template strings → deferred to the runtime unchanged. if/else(-if) chains are deferred entirely — eliminating a literal :if head would orphan a sibling :else (the runtime renders an orphan else as a plain always-on element; for __stx_if="dHJ1ZQ==" that wrongly shows both branches). :show has no else partner → exempt.

Hardening: two adversarial review passes (31 agents) caught a class of corruption bugs the naive version had, all fixed + pinned with tests:

  • self-closing non-void elements with a space before /> (<section __stx_if="ZmFsc2U=" />) were deferred → browser swallows following siblings into the unclosed element → falsy drop deleted surviving content. Self-close now derived from the whole matched tag.
  • findElementEnd rewritten as a comment/raw-text-aware scanner so </div> inside a nested <script>/<style>/comment isn't mistaken for the real close (was emitting truncated/malformed HTML). Self-closed <script/>/<style/> treated as bodyless.
  • chain guard now skips text nodes (not just whitespace/comments), matching nextElementSibling.
  • nested literal :if no longer produces overlapping replacement ranges.

71 tests across pre-eval-literal-if + pre-eval-edge-cases.

Deferred to Phase B: server-resolvable expression analysis (the ~75% of :if reading <script server> vars / @include params / loop variables — needs scope-walk AST analysis), and chain-aware rebalancing (so a literal-headed chain emits only the active branch instead of deferring the whole chain).

Closing Phase A — the literal-elimination cut (feature flags, debug blocks) is the safe, high-confidence subset.

Sign in to comment on this issue.