@pithyjs/core 0.1.0-beta.23 → 0.1.0-beta.24
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -0
- package/dist/compile/binds/bindComponentsTags.d.ts.map +1 -1
- package/dist/compile/binds/bindComponentsTags.js +21 -10
- package/dist/compile/binds/bindComponentsTags.js.map +1 -1
- package/dist/compile/binds/bindDeferDirectives.d.ts +3 -3
- package/dist/compile/binds/bindDeferDirectives.d.ts.map +1 -1
- package/dist/compile/binds/bindDeferDirectives.js +7 -5
- package/dist/compile/binds/bindDeferDirectives.js.map +1 -1
- package/dist/compile/binds/bindErrorBoundary.d.ts +6 -2
- package/dist/compile/binds/bindErrorBoundary.d.ts.map +1 -1
- package/dist/compile/binds/bindErrorBoundary.js +86 -20
- package/dist/compile/binds/bindErrorBoundary.js.map +1 -1
- package/dist/compile/contentProjection.d.ts +14 -2
- package/dist/compile/contentProjection.d.ts.map +1 -1
- package/dist/compile/contentProjection.js +42 -4
- package/dist/compile/contentProjection.js.map +1 -1
- package/dist/compile/nodeExpando.d.ts +1 -0
- package/dist/compile/nodeExpando.d.ts.map +1 -1
- package/dist/compile/nodeExpando.js.map +1 -1
- package/dist/compile/ssrCrashes.d.ts.map +1 -1
- package/dist/compile/ssrCrashes.js +76 -20
- package/dist/compile/ssrCrashes.js.map +1 -1
- package/dist/runtime/applyBindings.d.ts +6 -0
- package/dist/runtime/applyBindings.d.ts.map +1 -1
- package/dist/runtime/applyBindings.js +6 -0
- package/dist/runtime/applyBindings.js.map +1 -1
- package/dist/runtime/bindings/applyComponent.d.ts.map +1 -1
- package/dist/runtime/bindings/applyComponent.js +3 -1
- package/dist/runtime/bindings/applyComponent.js.map +1 -1
- package/dist/runtime/bindings/applyDefer.js +2 -2
- package/dist/runtime/bindings/applyDefer.js.map +1 -1
- package/dist/runtime/bindings/applySimple.d.ts.map +1 -1
- package/dist/runtime/bindings/applySimple.js +10 -4
- package/dist/runtime/bindings/applySimple.js.map +1 -1
- package/dist/runtime/bindings/helpers.d.ts.map +1 -1
- package/dist/runtime/bindings/helpers.js +2 -1
- package/dist/runtime/bindings/helpers.js.map +1 -1
- package/dist/runtime/bindings/types.d.ts +2 -0
- package/dist/runtime/bindings/types.d.ts.map +1 -1
- package/dist/runtime/bindings/types.js.map +1 -1
- package/dist/types/globals.d.ts +1 -0
- package/dist/types/globals.d.ts.map +1 -1
- package/dist/types/globals.js.map +1 -1
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -299,6 +299,7 @@ The `@for` directive provides keyed, reactive list rendering with:
|
|
|
299
299
|
| resolveBeforeFallback | ssr-crashes | `(el: Element) => void` | internal | - |
|
|
300
300
|
| isSSRMode | ssr-mode | `() => boolean` | stable | - |
|
|
301
301
|
| toTextValue | dom-safety | `(input: unknown) => string` | internal | - |
|
|
302
|
+
| __slotDup | apply-bindings | `true` | internal | - |
|
|
302
303
|
| __applyBindings | apply-bindings | `(fragment: DocumentFragment, bindings: Desc[], context: Record<string, unknown>, ownsDestroyCallbacks?: boolean) => { el: DocumentFragment; destroy: () => void }` | experimental | - |
|
|
303
304
|
| bootstrap | bootstrap | `(options: BootstrapOptions) => Promise<void>` | stable | - |
|
|
304
305
|
| createContextProxy | context | `(contexts: Record<string, unknown>[]) => Record<string, unknown>` | stable | - |
|
|
@@ -444,6 +445,7 @@ pnpm test -- --watch # Watch mode
|
|
|
444
445
|
| resolveBeforeFallback | - | - | - | Missing unit, integration, e2e |
|
|
445
446
|
| isSSRMode | - | - | - | Missing unit, integration, e2e |
|
|
446
447
|
| toTextValue | - | - | - | Missing unit, integration, e2e |
|
|
448
|
+
| __slotDup | - | - | - | Missing unit, integration, e2e |
|
|
447
449
|
| __applyBindings | - | - | - | Missing unit, integration, e2e |
|
|
448
450
|
| bootstrap | ✓ | - | - | Missing integration, e2e |
|
|
449
451
|
| createContextProxy | - | - | - | Missing unit, integration, e2e |
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bindComponentsTags.d.ts","sourceRoot":"","sources":["../../../src/compile/binds/bindComponentsTags.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AA+DF,qGAAqG;AACrG,wBAAgB,2BAA2B,IAAI,IAAI,CAElD;AAqGD;;;;;;GAMG;AACH,4NAA4N;AAC5N,wBAAgB,iBAAiB,CAC/B,IAAI,EAAE,OAAO,GAAG,gBAAgB,EAChC,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAChC,SAAS,EAAE,CAAC,MAAM,IAAI,CAAC,EAAE,GACxB,IAAI,
|
|
1
|
+
{"version":3,"file":"bindComponentsTags.d.ts","sourceRoot":"","sources":["../../../src/compile/binds/bindComponentsTags.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AA+DF,qGAAqG;AACrG,wBAAgB,2BAA2B,IAAI,IAAI,CAElD;AAqGD;;;;;;GAMG;AACH,4NAA4N;AAC5N,wBAAgB,iBAAiB,CAC/B,IAAI,EAAE,OAAO,GAAG,gBAAgB,EAChC,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAChC,SAAS,EAAE,CAAC,MAAM,IAAI,CAAC,EAAE,GACxB,IAAI,CAkbN"}
|
|
@@ -274,7 +274,7 @@ export function bindComponentTags(root, rootCtx, disposers) {
|
|
|
274
274
|
}
|
|
275
275
|
// Collect content projection SlotMap from component children
|
|
276
276
|
const pithyChildren = pithyNode?.children || [];
|
|
277
|
-
const slotMap = collectSlotMap(pithyChildren, localCtx, el);
|
|
277
|
+
const slotMap = collectSlotMap(pithyChildren, localCtx, el, componentFn);
|
|
278
278
|
// Create enhanced context with SlotMap for content projection
|
|
279
279
|
const componentContext = {
|
|
280
280
|
...localCtx,
|
|
@@ -321,7 +321,7 @@ export function bindComponentTags(root, rootCtx, disposers) {
|
|
|
321
321
|
g.__pithyComponentContext = originalContext;
|
|
322
322
|
g.__pithyRenderingComponent = wasRendering;
|
|
323
323
|
}
|
|
324
|
-
});
|
|
324
|
+
}, el);
|
|
325
325
|
}
|
|
326
326
|
catch (err) {
|
|
327
327
|
// Route sync render errors to the nearest boundary with escalation
|
|
@@ -331,14 +331,25 @@ export function bindComponentTags(root, rootCtx, disposers) {
|
|
|
331
331
|
// already-active boundary with no free ancestor drops it (React's
|
|
332
332
|
// first-error-wins). A component inside that boundary's `@fallback` is
|
|
333
333
|
// the everyday case, and the fallback is what the user actually sees.
|
|
334
|
-
const
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
334
|
+
const message = `❌ Component <${tag}> crashed during render:`;
|
|
335
|
+
const accepted = reportComponentFailure(el, tag, error, boundary, {
|
|
336
|
+
message,
|
|
337
|
+
onCaptured: () => {
|
|
338
|
+
if (import.meta.env?.DEV)
|
|
339
|
+
console.log(`[ErrorBoundary] Captured sync render error in <${tag}>:`, error.message);
|
|
340
|
+
},
|
|
341
|
+
});
|
|
342
|
+
if (!hasCrashed(el)) {
|
|
343
|
+
if (import.meta.env?.DEV) {
|
|
344
|
+
// Say which of the two actually happened. "Captured" on a rejected
|
|
345
|
+
// error reports the opposite of the truth, and this branch exists
|
|
346
|
+
// precisely because the two are not the same.
|
|
347
|
+
console.log(accepted
|
|
348
|
+
? `[ErrorBoundary] Captured sync render error in <${tag}>:`
|
|
349
|
+
: `[ErrorBoundary] No boundary took the error from <${tag}>:`, error.message);
|
|
350
|
+
}
|
|
351
|
+
if (!accepted)
|
|
352
|
+
logFailure(el, () => console.error(message, error));
|
|
342
353
|
}
|
|
343
354
|
continue;
|
|
344
355
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bindComponentsTags.js","sourceRoot":"","sources":["../../../src/compile/binds/bindComponentsTags.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAEF,OAAO,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AACzD,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB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AAa,CAAC,CAAC,cAAc,GAAG,YAAY,CAAC;YAC3D,wEAAwE;YACxE,qEAAqE;YACrE,IAAI,MAAM,IAAI,CAAC,aAAa,CAAC,UAAU,EAAE,CAAC;gBACxC,MAAM,QAAQ,GAAG,QAAQ,CAAC,sBAAsB,EAAE,CAAC;gBACnD,QAAQ,CAAC,MAAM,CAAC,aAAa,CAAC,CAAC;gBAC/B,mBAAmB,CAAC,QAAQ,EAAE,QAAQ,EAAE,SAAS,CAAC,CAAC;YACrD,CAAC;QACH,CAAC;IACH,CAAC;AACH,CAAC","sourcesContent":["/** @codex\n{\n \"id\": \"pithy.runtime.components\",\n \"title\": \"Component Tag Binding System\",\n \"category\": \"runtime\"\n}\n*/\n\nimport { compileExpression } from '../compileExpression';\nimport { isTemplateAttr } from './declaredDirective';\nimport {\n boundaryForElement,\n currentBoundary,\n replaceHidden,\n runWithBoundary,\n slotContentHidden,\n withSlotBoundary,\n} from './bindErrorBoundary';\nimport { bindAfterComponents } from './bindAfterComponents';\nimport { collectSlotMap, inProjectedContent } from '../contentProjection';\nimport {\n boundSlotMessage,\n componentChildDirectiveMessage,\n componentChildDirectives,\n nativeTags,\n type PithyNode,\n} from '@pithyjs/compiler';\nimport { collectForwardedAttrs, applyForwardedAttrs } from './forwardedAttrs';\nimport { createRoot, untrack } from '@pithyjs/signals';\nimport { watchStaleRowProp } from './staleRowProps';\nimport { markForwardTarget, nodeExpando } from '../nodeExpando';\nimport {\n invalidRenderError,\n invalidRenderMessage,\n propEvalMessage,\n} from '../evalDiagnostics';\nimport { componentDisposer } from '../disposeOrder';\nimport { pithyGlobals } from '../../types/globals';\nimport { isSSRMode } from '../ssrMode';\nimport {\n clearSSRRenderCrash,\n forgetCrash,\n hasCrashed,\n failedInBranch,\n logFailure,\n reportComponentFailure,\n resolveBeforeFallback,\n} from '../ssrCrashes';\nimport { isRenderableComponentEl } from '../componentResult';\nimport { readPropNames } from './propNames';\nimport { warnBoundProps, warnUnexpectedProps } from './propWarnings';\n\ninterface ComponentResult {\n /** Any DOM node — see the `Component` type for why this is not narrower. */\n el: Node;\n destroy?: () => void;\n}\ntype ComponentFn = (props: Record<string, unknown>) => ComponentResult;\n\n/**\n * Find the closest element-scoped context we attach in createLoopItem().\n * This is what exposes item(), gIdx(), count(), etc.\n */\n// Warn once per component/tag pair — the same idiom re-renders constantly\n// (e.g. a panel importing Button while using a native <button>), and\n// repeating the warning drowns out real ones.\nconst warnedComponentTags = new Set<string>();\nconst warnedChildDirectives = new WeakSet<PithyNode>();\n\n/** Test-only: forget which tags were warned about, so each render warns as a fresh process would. */\nexport function __resetComponentTagWarnings(): void {\n warnedComponentTags.clear();\n}\n\nfunction nearestCtx(\n el: Element,\n rootCtx: Record<string, unknown>\n): Record<string, unknown> {\n let n: Element | null = el;\n while (n) {\n const local = nodeExpando(n).__pithyCtx;\n if (local) return local;\n n = n.parentElement;\n }\n return rootCtx;\n}\n\n/**\n * Detect whether a node is inside a subtree that represents a NOT-YET-EXPANDED nested loop.\n * Those hosts are tagged in createLoopManager.createLoopItem() via `__pithySkipText`,\n * and real templates may also still carry @for / data-for before expansion.\n * We must *defer* binding for anything under such a host, otherwise expressions like item()\n * will throw ReferenceError (because inner loop ctx isn’t created yet).\n */\nfunction isInsidePendingLoopZone(node: Element): boolean {\n let p: Element | null = node;\n while (p) {\n if (nodeExpando(p).__pithySkipText) return true;\n if (\n p.hasAttribute &&\n (p.hasAttribute('@for') || p.hasAttribute('data-for'))\n ) {\n return true;\n }\n p = p.parentElement;\n }\n return false;\n}\n\n/** Evaluate `expr` in `ctx`. Try engine compiler first, then args-style fallback. */\nfunction evalInCtx(expr: string, ctx: Record<string, unknown>): unknown {\n // 1) Preferred: compileExpression uses `with(ctx) { return (...) }`\n try {\n const f = compileExpression(expr, ctx);\n try {\n return f();\n } catch {\n /* fall through to fallback */\n }\n } catch {\n /* fall through to fallback */\n }\n\n // 2) Fallback: args-style evaluator (robust even if compileExpression throws)\n const keys = Object.keys(ctx);\n const vals = keys.map(k => ctx[k]);\n // eslint-disable-next-line no-new-func -- args-style template expression evaluation is a core framework feature\n const fn = new Function(...keys, `return (${expr});`) as (\n ...args: unknown[]\n ) => unknown;\n return fn(...vals);\n}\n\nfunction extractExpectedPropNames(componentFn: ComponentFn): string[] {\n return readPropNames(componentFn).names;\n}\n\nconst warnedBoundSlots = new Set<string>();\n\nfunction warnBoundAttrs(\n componentFn: ComponentFn,\n el: Element,\n componentName: string\n): void {\n const bound: string[] = [];\n for (const attr of Array.from(el.attributes))\n if (attr.name.startsWith('data-bind-'))\n bound.push(attr.name.slice('data-bind-'.length));\n if (bound.includes('slot') && !warnedBoundSlots.has(componentName)) {\n warnedBoundSlots.add(componentName);\n console.warn(`[PithyJS] ${boundSlotMessage(componentName)}`);\n }\n warnBoundProps(extractExpectedPropNames(componentFn), bound, componentName);\n}\n\n/** DOM a component already rendered: its native tags may share a component's name. */\nfunction inComponentDom(el: Element): boolean {\n for (let n: Element | null = el; n; n = n.parentElement)\n if (nodeExpando(n).__pithyComponentDom) return true;\n return false;\n}\n\n/** Map lowercased DOM attr name to expected prop name (case-insensitive). */\nfunction normalizePropName(\n authoredName: string,\n expectedProps: string[]\n): string {\n if (expectedProps.includes(authoredName)) return authoredName;\n const lower = authoredName.toLowerCase();\n const matches = expectedProps.filter(p => p.toLowerCase() === lower);\n return matches.length === 1 ? matches[0] : authoredName;\n}\n\n/**\n * Replace custom component tags (<Counter/>, <NestedComponent/>) with rendered output.\n * - Skips anything under a pending nested loop host (bind after loop expansion)\n * - Evaluates prop expressions in nearest loop ctx\n * - Case-insensitive prop name normalization\n * - No raw-string fallback (prevents things like calling count() on a string)\n */\n/** @codexApi {\"parent\":\"pithy.runtime.components\",\"name\":\"bindComponentTags\",\"stability\":\"stable\",\"signature\":\"(root: Element | DocumentFragment, rootCtx: Record<string, unknown>, disposers: (() => void)[]) => void\"} */\nexport function bindComponentTags(\n root: Element | DocumentFragment,\n rootCtx: Record<string, unknown>,\n disposers: (() => void)[]\n): void {\n // case-insensitive tag lookup from context\n const tagMap = new Map<string, unknown>(\n Object.keys(rootCtx).map(k => [k.toLowerCase(), rootCtx[k]])\n );\n\n const scope =\n root instanceof Element ? (root as Element) : (root as DocumentFragment);\n const elements = Array.from(scope.querySelectorAll('*'));\n\n for (const el of elements) {\n // Skip elements removed from the tree by a parent component's render, or\n // hidden by an `@error-boundary` that has since activated.\n if (!scope.contains(el)) {\n // An element that has left the tree contributes nothing to the output, so\n // a crash recorded for it on an earlier detached pass is stale.\n forgetCrash(el);\n continue;\n }\n\n // Defer components inside not-yet-expanded loops\n if (isInsidePendingLoopZone(el)) continue;\n\n // A build's placeholder carries no AST: its children are DOM, which only\n // the AOT binder reads.\n const aotMount = nodeExpando(el).__pithyAotMount;\n if (aotMount) {\n // Marked as below, so the text pass skips what the component rendered.\n for (const node of aotMount(disposers))\n nodeExpando(node).__pithyComponentDom = true;\n continue;\n }\n\n const tag = el.tagName.toLowerCase();\n\n // Check if the parser marked this element as a component\n // This is the authoritative source - it checks originalTagName starts with uppercase\n // AND the tag name exists in importedIdentifiers\n const pithyNode = nodeExpando(el).__pithyNode;\n if (pithyNode) {\n // Parser processed this element - use its isComponent flag\n if (!pithyNode.isComponent) {\n // DEV: Warn if there's a component that matches case-insensitively\n // This helps developers catch typos like <button> when they meant <Button>\n // Skip warning if we're inside a component's render (the component might\n // legitimately use native elements like <button> in its implementation)\n const isInsideComponentRender =\n !!pithyGlobals().__pithyRenderingComponent;\n if (\n import.meta.env?.DEV &&\n !isInsideComponentRender &&\n !inComponentDom(el)\n ) {\n const matchingComponent = tagMap.get(tag);\n if (matchingComponent && typeof matchingComponent === 'function') {\n // Find the actual component name from context\n const componentName = Object.keys(rootCtx).find(\n k => k.toLowerCase() === tag && rootCtx[k] === matchingComponent\n );\n const warnKey = `${componentName}:${pithyNode.originalTagName}`;\n if (\n componentName &&\n componentName !== pithyNode.originalTagName &&\n !warnedComponentTags.has(warnKey)\n ) {\n warnedComponentTags.add(warnKey);\n console.warn(\n `[PithyJS] ⚠️ Component '${componentName}' is imported but used as '<${pithyNode.originalTagName}>'. ` +\n `Components must use PascalCase. Use '<${componentName}>' instead.`\n );\n }\n }\n }\n continue;\n }\n } else {\n // Fallback for elements not processed by our parser:\n // Skip native HTML elements to prevent <button> matching Button component\n if (nativeTags.has(tag)) continue;\n // Rendered already, e.g. a build's slot content.\n if (inComponentDom(el)) continue;\n }\n\n if (\n import.meta.env?.DEV &&\n pithyNode &&\n !warnedChildDirectives.has(pithyNode)\n ) {\n warnedChildDirectives.add(pithyNode);\n for (const name of componentChildDirectives(pithyNode))\n console.warn(\n `[pithy] ${componentChildDirectiveMessage(pithyNode.originalTagName ?? tag, name)}`\n );\n }\n\n let candidate = tagMap.get(tag);\n\n if (!candidate) continue;\n\n // Support default exports\n if (\n candidate &&\n typeof candidate === 'object' &&\n 'default' in candidate &&\n typeof candidate.default === 'function'\n ) {\n candidate = candidate.default;\n }\n if (typeof candidate !== 'function') continue;\n // Content a runtime-compiled receiver projected: bound detached, inside the\n // output of the component being rendered.\n const projectedHost =\n !el.closest('[data-error]') && inProjectedContent(el)\n ? pithyGlobals().__pithyComponentContext?.__slotHost\n : undefined;\n // Hidden like a sibling an activated boundary detached: never rendered.\n if (withSlotBoundary(undefined, projectedHost, () => slotContentHidden(el)))\n continue;\n\n // It failed already, and a build never retries (BUG-161).\n if (hasCrashed(el) || failedInBranch(el)) continue;\n\n const componentFn = candidate as ComponentFn;\n resolveBeforeFallback(el);\n const localCtx = nearestCtx(el, rootCtx); // crucial for item(), gIdx(), etc.\n\n // Extract expected props for validation (DEV) and prop name normalization (always)\n // This ensures case-insensitive matching works even when originalAttrs is unavailable\n const { names, fromParam } = readPropNames(componentFn);\n const expectedProps = fromParam ? names : [];\n\n // Preserve originally-authored attribute names/casing from the parsed template\n // (pithyNode already extracted above for isComponent check)\n const originalAttrs: Record<string, string> | undefined =\n pithyNode?.originalAttrs;\n\n const props: Record<string, unknown> = {};\n\n const staleWatchers: (() => void)[] = [];\n\n // Evaluate attributes as expressions in localCtx\n for (const attr of Array.from(el.attributes)) {\n const name = attr.name;\n const raw = attr.value;\n\n // Skip internal/behavioral attributes\n if (name.startsWith('data-')) continue;\n if (name === 'class' || name === 'style' || name === 'slot') continue;\n if (!isTemplateAttr(attr)) continue;\n\n // Prefer originally-authored name (preserve casing), else DOM name\n const authored = originalAttrs?.[name] ?? name;\n const propName = normalizePropName(authored, expectedProps);\n\n try {\n const value = untrack(() => evalInCtx(raw, localCtx));\n props[propName] = value; // only set when evaluation succeeds\n if (import.meta.env?.DEV) {\n staleWatchers.push(() =>\n watchStaleRowProp(\n localCtx,\n pithyNode ?? el,\n pithyNode?.originalTagName || tag,\n propName,\n raw,\n value,\n () => evalInCtx(raw, localCtx),\n disposers\n )\n );\n }\n } catch (err) {\n if (import.meta.env?.DEV) {\n console.warn(propEvalMessage(propName, raw), err);\n }\n // IMPORTANT: do NOT set a raw string fallback here.\n // Leaving it undefined lets the child use defaults and avoids count()-on-string.\n }\n }\n\n // Validate props for all components in DEV mode.\n // Native elements are already filtered out earlier (line 197 for fallback, line 171 for parser).\n if (import.meta.env?.DEV) {\n const displayTag = pithyNode?.originalTagName || tag;\n warnUnexpectedProps(readPropNames(componentFn), props, displayTag);\n warnBoundAttrs(componentFn, el, displayTag);\n }\n\n // Collect content projection SlotMap from component children\n const pithyChildren: PithyNode[] = pithyNode?.children || [];\n const slotMap = collectSlotMap(pithyChildren, localCtx, el);\n\n // Create enhanced context with SlotMap for content projection\n const componentContext = {\n ...localCtx,\n __slotMap: slotMap,\n __childAstNodes: pithyChildren,\n __childFactory: undefined,\n __slotHost: el,\n };\n\n // Find nearest error boundary for this component\n const boundaryEl = el.closest('[data-error]') as Element | null;\n // Projected content is bound detached, during its receiver's render.\n const boundary =\n boundaryForElement(boundaryEl) ??\n (!boundaryEl && inProjectedContent(el) ? currentBoundary() : null);\n\n // Invoke component under boundary context; expect { el, destroy }\n let out: ComponentResult | undefined;\n let disposeSetup: (() => void) | undefined;\n try {\n out = runWithBoundary(boundary, () => {\n // Store the enhanced context globally for the component's html() calls to access.\n // This per-component context contains __slotMap for content projection.\n //\n // In SSR, there are TWO context sources that html() merges:\n // 1. AsyncLocalStorage context (__getComponentContext) - request-level isolation\n // 2. This global context (__pithyComponentContext) - per-component __slotMap\n //\n // Both are needed: AsyncLocalStorage provides request isolation, while this\n // global provides the __slotMap that changes for each component render.\n const g = pithyGlobals();\n const originalContext = g.__pithyComponentContext;\n const wasRendering = g.__pithyRenderingComponent;\n g.__pithyComponentContext = componentContext;\n // Mark that we're rendering a component to suppress casing warnings for\n // native elements used in component implementations (e.g., <button> in Button)\n g.__pithyRenderingComponent = true;\n\n try {\n const result = createRoot(disposeRoot => {\n disposeSetup = disposeRoot;\n return componentFn(props);\n });\n return result;\n } finally {\n // Restore original context\n g.__pithyComponentContext = originalContext;\n g.__pithyRenderingComponent = wasRendering;\n }\n });\n } catch (err) {\n // Route sync render errors to the nearest boundary with escalation\n if (boundary) {\n const error = err instanceof Error ? err : new Error(String(err));\n // A boundary being in scope does not mean it accepted the error: an\n // already-active boundary with no free ancestor drops it (React's\n // first-error-wins). A component inside that boundary's `@fallback` is\n // the everyday case, and the fallback is what the user actually sees.\n const accepted = reportComponentFailure(el, tag, error, boundary);\n if (import.meta.env?.DEV) {\n // Say which of the two actually happened. \"Captured\" on a rejected\n // error reports the opposite of the truth, and this branch exists\n // precisely because the two are not the same.\n console.log(\n accepted\n ? `[ErrorBoundary] Captured sync render error in <${tag}>:`\n : `[ErrorBoundary] Boundary already active — error from <${tag}> was NOT captured:`,\n error.message\n );\n }\n continue;\n }\n\n // No boundary reachable through the DOM. A branch, slot or component\n // built detached knows the one it will sit under (`deferCrash`).\n // Otherwise degrade in both modes.\n //\n // A static/server render additionally records the crash. Nobody reads a\n // console during `pithy-ssg`, so this used to leave the raw <${tag}> in\n // the emitted HTML while the route still counted as rendered and the CLI\n // exited 0 (BUG-018). Anything still recorded when the render finishes\n // makes the SSR renderer throw, and the per-route catch in `vite-ssg.ts`\n // fails that route.\n const error = err instanceof Error ? err : new Error(String(err));\n const message = `❌ Component <${tag}> crashed during render:`;\n const attributed = reportComponentFailure(el, tag, error, null, {\n message,\n onCaptured: () => {\n if (import.meta.env?.DEV)\n console.log(\n `[ErrorBoundary] Captured sync render error in <${tag}>:`,\n error.message\n );\n },\n });\n if (!attributed) logFailure(el, () => console.error(message, err));\n continue;\n }\n\n if (\n !out ||\n typeof out !== 'object' ||\n !('el' in out) ||\n !isRenderableComponentEl(out.el, el)\n ) {\n const displayTag = pithyNode?.originalTagName || tag;\n logFailure(el, () => console.warn(invalidRenderMessage(displayTag)));\n // Not a throw, but the same outcome as one: the raw <${tag}> is left in\n // the document and the subtree never renders. Under SSR that is content\n // silently missing from the emitted HTML, so it is recorded exactly like\n // a crash (BUG-018). Recorded rather than merely left in place, because\n // this attempt may also be retracting an earlier attempt's record.\n // Same funnel as a throw: a boundary above this component gets the\n // chance to claim it and render its fallback, and only an unclaimed\n // failure is recorded. Bypassing this meant a component under\n // `@error-boundary` that returned garbage failed the route with the\n // boundary signal still null.\n reportComponentFailure(\n el,\n displayTag,\n invalidRenderError(displayTag),\n boundary\n );\n disposeSetup?.();\n continue;\n }\n\n const { el: renderedEl, destroy } = out;\n\n // Capture class and data-* attributes for forwarding to rendered root:\n // directive bindings (data-on-*, data-bind-*, data-class-toggle-*,\n // data-classes, data-style-*) plus any author-written data-* attribute.\n const forwardedClass = el.getAttribute('class');\n const forwardedAttrs = collectForwardedAttrs(el);\n\n const isFragment = renderedEl.nodeType === Node.DOCUMENT_FRAGMENT_NODE;\n let forwardTarget: HTMLElement | null = null;\n const hasForwardables = !!(forwardedClass || forwardedAttrs.length > 0);\n if (hasForwardables) {\n if (isFragment) {\n forwardTarget = (renderedEl as DocumentFragment)\n .firstElementChild as HTMLElement | null;\n if (import.meta.env?.DEV && !forwardTarget) {\n const displayTag = pithyNode?.originalTagName || tag;\n console.warn(\n `[PithyJS] <${displayTag}> has class or data-* attributes but returns a fragment with no element children — forwarding skipped.`\n );\n }\n } else if (renderedEl.nodeType === Node.ELEMENT_NODE) {\n forwardTarget = renderedEl as HTMLElement;\n }\n }\n\n const renderedNodes = isFragment\n ? Array.from(renderedEl.childNodes)\n : [renderedEl];\n const slotOwner = nodeExpando(el).__pithySlotOwner;\n for (const node of renderedNodes) {\n const x = nodeExpando(node);\n x.__pithyComponentDom = true;\n if (slotOwner) x.__pithySlotOwner ??= slotOwner;\n }\n\n let replaced = true;\n let hidden = false;\n try {\n // A boundary that caught a crash in this render may have hidden `el`.\n hidden = replaceHidden(el, renderedNodes);\n if (!hidden) el.replaceWith(...renderedNodes);\n } catch (err) {\n // A failed replacement leaves the raw <${tag}> exactly where a crash\n // would have, so it is the same content loss and is recorded the same way.\n replaced = false;\n const error = err instanceof Error ? err : new Error(String(err));\n reportComponentFailure(el, tag, error, boundary);\n console.error(`❌ Failed to replace <${tag}> with rendered DOM:`, err);\n }\n\n // Retracted only here, and in the boundary catch above — never eagerly at\n // the top of an attempt, where any early `continue` added later would\n // silently drop a real record. This is the point at which the component is\n // known to have produced a usable node AND to have reached the document, so\n // an earlier detached attempt's crash is genuinely no longer the outcome.\n if (isSSRMode() && replaced) clearSSRRenderCrash(el);\n\n for (const watch of staleWatchers) watch();\n\n // Forward class from component tag onto the rendered root element\n if (forwardedClass && forwardTarget) {\n for (const cls of forwardedClass.split(/\\s+/)) {\n if (cls) forwardTarget.classList.add(cls);\n }\n }\n\n // Before any binding pass below, which can throw.\n const teardown = componentDisposer(\n destroy,\n disposeSetup,\n renderedNodes[0] ?? (replaced ? null : el)\n );\n if (teardown) disposers.push(teardown);\n\n // Forward captured attributes so subsequent binders can attach the bindings\n if (forwardedAttrs.length > 0 && forwardTarget) {\n applyForwardedAttrs(forwardTarget, forwardedAttrs, tag);\n markForwardTarget(\n forwardTarget,\n localCtx,\n new Set(forwardedAttrs.map(([name]) => name))\n );\n const styleProps = Object.keys(pithyNode?.directives?.styleMap ?? {});\n if (styleProps.length)\n nodeExpando(forwardTarget).__styleProps = styleProps;\n const classToggles = Object.keys(pithyNode?.directives?.classMap ?? {});\n if (classToggles.length)\n nodeExpando(forwardTarget).__classToggles = classToggles;\n // Hidden, it is out of reach of this fragment's later passes. An active\n // nested boundary `hideContent` kept in place is still within reach.\n if (hidden && !forwardTarget.parentNode) {\n const detached = document.createDocumentFragment();\n detached.append(forwardTarget);\n bindAfterComponents(detached, localCtx, disposers);\n }\n }\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"bindComponentsTags.js","sourceRoot":"","sources":["../../../src/compile/binds/bindComponentsTags.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAEF,OAAO,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AACzD,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AACrD,OAAO,EACL,kBAAkB,EAClB,eAAe,EACf,aAAa,EACb,eAAe,EACf,iBAAiB,EACjB,gBAAgB,GACjB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAC5D,OAAO,EAAE,cAAc,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AAC1E,OAAO,EACL,gBAAgB,EAChB,8BAA8B,EAC9B,wBAAwB,EACxB,UAAU,GAEX,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,qBAAqB,EAAE,mBAAmB,EAAE,MAAM,kBAAkB,CAAC;AAC9E,OAAO,EAAE,UAAU,EAAE,OAAO,EAAE,MAAM,kBAAkB,CAAC;AACvD,OAAO,EAAE,iBAAiB,EAAE,MAAM,iBAAiB,CAAC;AACpD,OAAO,EAAE,iBAAiB,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAChE,OAAO,EACL,kBAAkB,EAClB,oBAAoB,EACpB,eAAe,GAChB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAAE,iBAAiB,EAAE,MAAM,iBAAiB,CAAC;AACpD,OAAO,E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B,mBAAmB,CAAC,QAAQ,EAAE,QAAQ,EAAE,SAAS,CAAC,CAAC;YACrD,CAAC;QACH,CAAC;IACH,CAAC;AACH,CAAC","sourcesContent":["/** @codex\n{\n \"id\": \"pithy.runtime.components\",\n \"title\": \"Component Tag Binding System\",\n \"category\": \"runtime\"\n}\n*/\n\nimport { compileExpression } from '../compileExpression';\nimport { isTemplateAttr } from './declaredDirective';\nimport {\n boundaryForElement,\n currentBoundary,\n replaceHidden,\n runWithBoundary,\n slotContentHidden,\n withSlotBoundary,\n} from './bindErrorBoundary';\nimport { bindAfterComponents } from './bindAfterComponents';\nimport { collectSlotMap, inProjectedContent } from '../contentProjection';\nimport {\n boundSlotMessage,\n componentChildDirectiveMessage,\n componentChildDirectives,\n nativeTags,\n type PithyNode,\n} from '@pithyjs/compiler';\nimport { collectForwardedAttrs, applyForwardedAttrs } from './forwardedAttrs';\nimport { createRoot, untrack } from '@pithyjs/signals';\nimport { watchStaleRowProp } from './staleRowProps';\nimport { markForwardTarget, nodeExpando } from '../nodeExpando';\nimport {\n invalidRenderError,\n invalidRenderMessage,\n propEvalMessage,\n} from '../evalDiagnostics';\nimport { componentDisposer } from '../disposeOrder';\nimport { pithyGlobals } from '../../types/globals';\nimport { isSSRMode } from '../ssrMode';\nimport {\n clearSSRRenderCrash,\n forgetCrash,\n hasCrashed,\n failedInBranch,\n logFailure,\n reportComponentFailure,\n resolveBeforeFallback,\n} from '../ssrCrashes';\nimport { isRenderableComponentEl } from '../componentResult';\nimport { readPropNames } from './propNames';\nimport { warnBoundProps, warnUnexpectedProps } from './propWarnings';\n\ninterface ComponentResult {\n /** Any DOM node — see the `Component` type for why this is not narrower. */\n el: Node;\n destroy?: () => void;\n}\ntype ComponentFn = (props: Record<string, unknown>) => ComponentResult;\n\n/**\n * Find the closest element-scoped context we attach in createLoopItem().\n * This is what exposes item(), gIdx(), count(), etc.\n */\n// Warn once per component/tag pair — the same idiom re-renders constantly\n// (e.g. a panel importing Button while using a native <button>), and\n// repeating the warning drowns out real ones.\nconst warnedComponentTags = new Set<string>();\nconst warnedChildDirectives = new WeakSet<PithyNode>();\n\n/** Test-only: forget which tags were warned about, so each render warns as a fresh process would. */\nexport function __resetComponentTagWarnings(): void {\n warnedComponentTags.clear();\n}\n\nfunction nearestCtx(\n el: Element,\n rootCtx: Record<string, unknown>\n): Record<string, unknown> {\n let n: Element | null = el;\n while (n) {\n const local = nodeExpando(n).__pithyCtx;\n if (local) return local;\n n = n.parentElement;\n }\n return rootCtx;\n}\n\n/**\n * Detect whether a node is inside a subtree that represents a NOT-YET-EXPANDED nested loop.\n * Those hosts are tagged in createLoopManager.createLoopItem() via `__pithySkipText`,\n * and real templates may also still carry @for / data-for before expansion.\n * We must *defer* binding for anything under such a host, otherwise expressions like item()\n * will throw ReferenceError (because inner loop ctx isn’t created yet).\n */\nfunction isInsidePendingLoopZone(node: Element): boolean {\n let p: Element | null = node;\n while (p) {\n if (nodeExpando(p).__pithySkipText) return true;\n if (\n p.hasAttribute &&\n (p.hasAttribute('@for') || p.hasAttribute('data-for'))\n ) {\n return true;\n }\n p = p.parentElement;\n }\n return false;\n}\n\n/** Evaluate `expr` in `ctx`. Try engine compiler first, then args-style fallback. */\nfunction evalInCtx(expr: string, ctx: Record<string, unknown>): unknown {\n // 1) Preferred: compileExpression uses `with(ctx) { return (...) }`\n try {\n const f = compileExpression(expr, ctx);\n try {\n return f();\n } catch {\n /* fall through to fallback */\n }\n } catch {\n /* fall through to fallback */\n }\n\n // 2) Fallback: args-style evaluator (robust even if compileExpression throws)\n const keys = Object.keys(ctx);\n const vals = keys.map(k => ctx[k]);\n // eslint-disable-next-line no-new-func -- args-style template expression evaluation is a core framework feature\n const fn = new Function(...keys, `return (${expr});`) as (\n ...args: unknown[]\n ) => unknown;\n return fn(...vals);\n}\n\nfunction extractExpectedPropNames(componentFn: ComponentFn): string[] {\n return readPropNames(componentFn).names;\n}\n\nconst warnedBoundSlots = new Set<string>();\n\nfunction warnBoundAttrs(\n componentFn: ComponentFn,\n el: Element,\n componentName: string\n): void {\n const bound: string[] = [];\n for (const attr of Array.from(el.attributes))\n if (attr.name.startsWith('data-bind-'))\n bound.push(attr.name.slice('data-bind-'.length));\n if (bound.includes('slot') && !warnedBoundSlots.has(componentName)) {\n warnedBoundSlots.add(componentName);\n console.warn(`[PithyJS] ${boundSlotMessage(componentName)}`);\n }\n warnBoundProps(extractExpectedPropNames(componentFn), bound, componentName);\n}\n\n/** DOM a component already rendered: its native tags may share a component's name. */\nfunction inComponentDom(el: Element): boolean {\n for (let n: Element | null = el; n; n = n.parentElement)\n if (nodeExpando(n).__pithyComponentDom) return true;\n return false;\n}\n\n/** Map lowercased DOM attr name to expected prop name (case-insensitive). */\nfunction normalizePropName(\n authoredName: string,\n expectedProps: string[]\n): string {\n if (expectedProps.includes(authoredName)) return authoredName;\n const lower = authoredName.toLowerCase();\n const matches = expectedProps.filter(p => p.toLowerCase() === lower);\n return matches.length === 1 ? matches[0] : authoredName;\n}\n\n/**\n * Replace custom component tags (<Counter/>, <NestedComponent/>) with rendered output.\n * - Skips anything under a pending nested loop host (bind after loop expansion)\n * - Evaluates prop expressions in nearest loop ctx\n * - Case-insensitive prop name normalization\n * - No raw-string fallback (prevents things like calling count() on a string)\n */\n/** @codexApi {\"parent\":\"pithy.runtime.components\",\"name\":\"bindComponentTags\",\"stability\":\"stable\",\"signature\":\"(root: Element | DocumentFragment, rootCtx: Record<string, unknown>, disposers: (() => void)[]) => void\"} */\nexport function bindComponentTags(\n root: Element | DocumentFragment,\n rootCtx: Record<string, unknown>,\n disposers: (() => void)[]\n): void {\n // case-insensitive tag lookup from context\n const tagMap = new Map<string, unknown>(\n Object.keys(rootCtx).map(k => [k.toLowerCase(), rootCtx[k]])\n );\n\n const scope =\n root instanceof Element ? (root as Element) : (root as DocumentFragment);\n const elements = Array.from(scope.querySelectorAll('*'));\n\n for (const el of elements) {\n // Skip elements removed from the tree by a parent component's render, or\n // hidden by an `@error-boundary` that has since activated.\n if (!scope.contains(el)) {\n // An element that has left the tree contributes nothing to the output, so\n // a crash recorded for it on an earlier detached pass is stale.\n forgetCrash(el);\n continue;\n }\n\n // Defer components inside not-yet-expanded loops\n if (isInsidePendingLoopZone(el)) continue;\n\n // A build's placeholder carries no AST: its children are DOM, which only\n // the AOT binder reads.\n const aotMount = nodeExpando(el).__pithyAotMount;\n if (aotMount) {\n // Marked as below, so the text pass skips what the component rendered.\n for (const node of aotMount(disposers))\n nodeExpando(node).__pithyComponentDom = true;\n continue;\n }\n\n const tag = el.tagName.toLowerCase();\n\n // Check if the parser marked this element as a component\n // This is the authoritative source - it checks originalTagName starts with uppercase\n // AND the tag name exists in importedIdentifiers\n const pithyNode = nodeExpando(el).__pithyNode;\n if (pithyNode) {\n // Parser processed this element - use its isComponent flag\n if (!pithyNode.isComponent) {\n // DEV: Warn if there's a component that matches case-insensitively\n // This helps developers catch typos like <button> when they meant <Button>\n // Skip warning if we're inside a component's render (the component might\n // legitimately use native elements like <button> in its implementation)\n const isInsideComponentRender =\n !!pithyGlobals().__pithyRenderingComponent;\n if (\n import.meta.env?.DEV &&\n !isInsideComponentRender &&\n !inComponentDom(el)\n ) {\n const matchingComponent = tagMap.get(tag);\n if (matchingComponent && typeof matchingComponent === 'function') {\n // Find the actual component name from context\n const componentName = Object.keys(rootCtx).find(\n k => k.toLowerCase() === tag && rootCtx[k] === matchingComponent\n );\n const warnKey = `${componentName}:${pithyNode.originalTagName}`;\n if (\n componentName &&\n componentName !== pithyNode.originalTagName &&\n !warnedComponentTags.has(warnKey)\n ) {\n warnedComponentTags.add(warnKey);\n console.warn(\n `[PithyJS] ⚠️ Component '${componentName}' is imported but used as '<${pithyNode.originalTagName}>'. ` +\n `Components must use PascalCase. Use '<${componentName}>' instead.`\n );\n }\n }\n }\n continue;\n }\n } else {\n // Fallback for elements not processed by our parser:\n // Skip native HTML elements to prevent <button> matching Button component\n if (nativeTags.has(tag)) continue;\n // Rendered already, e.g. a build's slot content.\n if (inComponentDom(el)) continue;\n }\n\n if (\n import.meta.env?.DEV &&\n pithyNode &&\n !warnedChildDirectives.has(pithyNode)\n ) {\n warnedChildDirectives.add(pithyNode);\n for (const name of componentChildDirectives(pithyNode))\n console.warn(\n `[pithy] ${componentChildDirectiveMessage(pithyNode.originalTagName ?? tag, name)}`\n );\n }\n\n let candidate = tagMap.get(tag);\n\n if (!candidate) continue;\n\n // Support default exports\n if (\n candidate &&\n typeof candidate === 'object' &&\n 'default' in candidate &&\n typeof candidate.default === 'function'\n ) {\n candidate = candidate.default;\n }\n if (typeof candidate !== 'function') continue;\n // Content a runtime-compiled receiver projected: bound detached, inside the\n // output of the component being rendered.\n const projectedHost =\n !el.closest('[data-error]') && inProjectedContent(el)\n ? pithyGlobals().__pithyComponentContext?.__slotHost\n : undefined;\n // Hidden like a sibling an activated boundary detached: never rendered.\n if (withSlotBoundary(undefined, projectedHost, () => slotContentHidden(el)))\n continue;\n\n // It failed already, and a build never retries (BUG-161).\n if (hasCrashed(el) || failedInBranch(el)) continue;\n\n const componentFn = candidate as ComponentFn;\n resolveBeforeFallback(el);\n const localCtx = nearestCtx(el, rootCtx); // crucial for item(), gIdx(), etc.\n\n // Extract expected props for validation (DEV) and prop name normalization (always)\n // This ensures case-insensitive matching works even when originalAttrs is unavailable\n const { names, fromParam } = readPropNames(componentFn);\n const expectedProps = fromParam ? names : [];\n\n // Preserve originally-authored attribute names/casing from the parsed template\n // (pithyNode already extracted above for isComponent check)\n const originalAttrs: Record<string, string> | undefined =\n pithyNode?.originalAttrs;\n\n const props: Record<string, unknown> = {};\n\n const staleWatchers: (() => void)[] = [];\n\n // Evaluate attributes as expressions in localCtx\n for (const attr of Array.from(el.attributes)) {\n const name = attr.name;\n const raw = attr.value;\n\n // Skip internal/behavioral attributes\n if (name.startsWith('data-')) continue;\n if (name === 'class' || name === 'style' || name === 'slot') continue;\n if (!isTemplateAttr(attr)) continue;\n\n // Prefer originally-authored name (preserve casing), else DOM name\n const authored = originalAttrs?.[name] ?? name;\n const propName = normalizePropName(authored, expectedProps);\n\n try {\n const value = untrack(() => evalInCtx(raw, localCtx));\n props[propName] = value; // only set when evaluation succeeds\n if (import.meta.env?.DEV) {\n staleWatchers.push(() =>\n watchStaleRowProp(\n localCtx,\n pithyNode ?? el,\n pithyNode?.originalTagName || tag,\n propName,\n raw,\n value,\n () => evalInCtx(raw, localCtx),\n disposers\n )\n );\n }\n } catch (err) {\n if (import.meta.env?.DEV) {\n console.warn(propEvalMessage(propName, raw), err);\n }\n // IMPORTANT: do NOT set a raw string fallback here.\n // Leaving it undefined lets the child use defaults and avoids count()-on-string.\n }\n }\n\n // Validate props for all components in DEV mode.\n // Native elements are already filtered out earlier (line 197 for fallback, line 171 for parser).\n if (import.meta.env?.DEV) {\n const displayTag = pithyNode?.originalTagName || tag;\n warnUnexpectedProps(readPropNames(componentFn), props, displayTag);\n warnBoundAttrs(componentFn, el, displayTag);\n }\n\n // Collect content projection SlotMap from component children\n const pithyChildren: PithyNode[] = pithyNode?.children || [];\n const slotMap = collectSlotMap(pithyChildren, localCtx, el, componentFn);\n\n // Create enhanced context with SlotMap for content projection\n const componentContext = {\n ...localCtx,\n __slotMap: slotMap,\n __childAstNodes: pithyChildren,\n __childFactory: undefined,\n __slotHost: el,\n };\n\n // Find nearest error boundary for this component\n const boundaryEl = el.closest('[data-error]') as Element | null;\n // Projected content is bound detached, during its receiver's render.\n const boundary =\n boundaryForElement(boundaryEl) ??\n (!boundaryEl && inProjectedContent(el) ? currentBoundary() : null);\n\n // Invoke component under boundary context; expect { el, destroy }\n let out: ComponentResult | undefined;\n let disposeSetup: (() => void) | undefined;\n try {\n out = runWithBoundary(\n boundary,\n () => {\n // Store the enhanced context globally for the component's html() calls to access.\n // This per-component context contains __slotMap for content projection.\n //\n // In SSR, there are TWO context sources that html() merges:\n // 1. AsyncLocalStorage context (__getComponentContext) - request-level isolation\n // 2. This global context (__pithyComponentContext) - per-component __slotMap\n //\n // Both are needed: AsyncLocalStorage provides request isolation, while this\n // global provides the __slotMap that changes for each component render.\n const g = pithyGlobals();\n const originalContext = g.__pithyComponentContext;\n const wasRendering = g.__pithyRenderingComponent;\n g.__pithyComponentContext = componentContext;\n // Mark that we're rendering a component to suppress casing warnings for\n // native elements used in component implementations (e.g., <button> in Button)\n g.__pithyRenderingComponent = true;\n\n try {\n const result = createRoot(disposeRoot => {\n disposeSetup = disposeRoot;\n return componentFn(props);\n });\n return result;\n } finally {\n // Restore original context\n g.__pithyComponentContext = originalContext;\n g.__pithyRenderingComponent = wasRendering;\n }\n },\n el\n );\n } catch (err) {\n // Route sync render errors to the nearest boundary with escalation\n if (boundary) {\n const error = err instanceof Error ? err : new Error(String(err));\n // A boundary being in scope does not mean it accepted the error: an\n // already-active boundary with no free ancestor drops it (React's\n // first-error-wins). A component inside that boundary's `@fallback` is\n // the everyday case, and the fallback is what the user actually sees.\n const message = `❌ Component <${tag}> crashed during render:`;\n const accepted = reportComponentFailure(el, tag, error, boundary, {\n message,\n onCaptured: () => {\n if (import.meta.env?.DEV)\n console.log(\n `[ErrorBoundary] Captured sync render error in <${tag}>:`,\n error.message\n );\n },\n });\n if (!hasCrashed(el)) {\n if (import.meta.env?.DEV) {\n // Say which of the two actually happened. \"Captured\" on a rejected\n // error reports the opposite of the truth, and this branch exists\n // precisely because the two are not the same.\n console.log(\n accepted\n ? `[ErrorBoundary] Captured sync render error in <${tag}>:`\n : `[ErrorBoundary] No boundary took the error from <${tag}>:`,\n error.message\n );\n }\n if (!accepted) logFailure(el, () => console.error(message, error));\n }\n continue;\n }\n\n // No boundary reachable through the DOM. A branch, slot or component\n // built detached knows the one it will sit under (`deferCrash`).\n // Otherwise degrade in both modes.\n //\n // A static/server render additionally records the crash. Nobody reads a\n // console during `pithy-ssg`, so this used to leave the raw <${tag}> in\n // the emitted HTML while the route still counted as rendered and the CLI\n // exited 0 (BUG-018). Anything still recorded when the render finishes\n // makes the SSR renderer throw, and the per-route catch in `vite-ssg.ts`\n // fails that route.\n const error = err instanceof Error ? err : new Error(String(err));\n const message = `❌ Component <${tag}> crashed during render:`;\n const attributed = reportComponentFailure(el, tag, error, null, {\n message,\n onCaptured: () => {\n if (import.meta.env?.DEV)\n console.log(\n `[ErrorBoundary] Captured sync render error in <${tag}>:`,\n error.message\n );\n },\n });\n if (!attributed) logFailure(el, () => console.error(message, err));\n continue;\n }\n\n if (\n !out ||\n typeof out !== 'object' ||\n !('el' in out) ||\n !isRenderableComponentEl(out.el, el)\n ) {\n const displayTag = pithyNode?.originalTagName || tag;\n logFailure(el, () => console.warn(invalidRenderMessage(displayTag)));\n // Not a throw, but the same outcome as one: the raw <${tag}> is left in\n // the document and the subtree never renders. Under SSR that is content\n // silently missing from the emitted HTML, so it is recorded exactly like\n // a crash (BUG-018). Recorded rather than merely left in place, because\n // this attempt may also be retracting an earlier attempt's record.\n // Same funnel as a throw: a boundary above this component gets the\n // chance to claim it and render its fallback, and only an unclaimed\n // failure is recorded. Bypassing this meant a component under\n // `@error-boundary` that returned garbage failed the route with the\n // boundary signal still null.\n reportComponentFailure(\n el,\n displayTag,\n invalidRenderError(displayTag),\n boundary\n );\n disposeSetup?.();\n continue;\n }\n\n const { el: renderedEl, destroy } = out;\n\n // Capture class and data-* attributes for forwarding to rendered root:\n // directive bindings (data-on-*, data-bind-*, data-class-toggle-*,\n // data-classes, data-style-*) plus any author-written data-* attribute.\n const forwardedClass = el.getAttribute('class');\n const forwardedAttrs = collectForwardedAttrs(el);\n\n const isFragment = renderedEl.nodeType === Node.DOCUMENT_FRAGMENT_NODE;\n let forwardTarget: HTMLElement | null = null;\n const hasForwardables = !!(forwardedClass || forwardedAttrs.length > 0);\n if (hasForwardables) {\n if (isFragment) {\n forwardTarget = (renderedEl as DocumentFragment)\n .firstElementChild as HTMLElement | null;\n if (import.meta.env?.DEV && !forwardTarget) {\n const displayTag = pithyNode?.originalTagName || tag;\n console.warn(\n `[PithyJS] <${displayTag}> has class or data-* attributes but returns a fragment with no element children — forwarding skipped.`\n );\n }\n } else if (renderedEl.nodeType === Node.ELEMENT_NODE) {\n forwardTarget = renderedEl as HTMLElement;\n }\n }\n\n const renderedNodes = isFragment\n ? Array.from(renderedEl.childNodes)\n : [renderedEl];\n const slotOwner = nodeExpando(el).__pithySlotOwner;\n for (const node of renderedNodes) {\n const x = nodeExpando(node);\n x.__pithyComponentDom = true;\n if (slotOwner) x.__pithySlotOwner ??= slotOwner;\n }\n\n let replaced = true;\n let hidden = false;\n try {\n // A boundary that caught a crash in this render may have hidden `el`.\n hidden = replaceHidden(el, renderedNodes);\n if (!hidden) el.replaceWith(...renderedNodes);\n } catch (err) {\n // A failed replacement leaves the raw <${tag}> exactly where a crash\n // would have, so it is the same content loss and is recorded the same way.\n replaced = false;\n const error = err instanceof Error ? err : new Error(String(err));\n reportComponentFailure(el, tag, error, boundary);\n console.error(`❌ Failed to replace <${tag}> with rendered DOM:`, err);\n }\n\n // Retracted only here, and in the boundary catch above — never eagerly at\n // the top of an attempt, where any early `continue` added later would\n // silently drop a real record. This is the point at which the component is\n // known to have produced a usable node AND to have reached the document, so\n // an earlier detached attempt's crash is genuinely no longer the outcome.\n if (isSSRMode() && replaced) clearSSRRenderCrash(el);\n\n for (const watch of staleWatchers) watch();\n\n // Forward class from component tag onto the rendered root element\n if (forwardedClass && forwardTarget) {\n for (const cls of forwardedClass.split(/\\s+/)) {\n if (cls) forwardTarget.classList.add(cls);\n }\n }\n\n // Before any binding pass below, which can throw.\n const teardown = componentDisposer(\n destroy,\n disposeSetup,\n renderedNodes[0] ?? (replaced ? null : el)\n );\n if (teardown) disposers.push(teardown);\n\n // Forward captured attributes so subsequent binders can attach the bindings\n if (forwardedAttrs.length > 0 && forwardTarget) {\n applyForwardedAttrs(forwardTarget, forwardedAttrs, tag);\n markForwardTarget(\n forwardTarget,\n localCtx,\n new Set(forwardedAttrs.map(([name]) => name))\n );\n const styleProps = Object.keys(pithyNode?.directives?.styleMap ?? {});\n if (styleProps.length)\n nodeExpando(forwardTarget).__styleProps = styleProps;\n const classToggles = Object.keys(pithyNode?.directives?.classMap ?? {});\n if (classToggles.length)\n nodeExpando(forwardTarget).__classToggles = classToggles;\n // Hidden, it is out of reach of this fragment's later passes. An active\n // nested boundary `hideContent` kept in place is still within reach.\n if (hidden && !forwardTarget.parentNode) {\n const detached = document.createDocumentFragment();\n detached.append(forwardTarget);\n bindAfterComponents(detached, localCtx, disposers);\n }\n }\n }\n}\n"]}
|
|
@@ -13,9 +13,9 @@
|
|
|
13
13
|
* - `when`: Load when a boolean expression becomes truthy
|
|
14
14
|
*
|
|
15
15
|
* @param fragment - The root document fragment
|
|
16
|
-
* @param
|
|
16
|
+
* @param templateContext - Template context with signals and lazy handles, for an element that carries no context of its own
|
|
17
17
|
* @param disposers - Array to collect cleanup functions
|
|
18
18
|
*/
|
|
19
|
-
/** @codexApi {"parent":"pithy.core.bind-defer-directives","name":"bindDeferDirectives","stability":"stable","signature":"(fragment: DocumentFragment,
|
|
20
|
-
export declare function bindDeferDirectives(fragment: DocumentFragment,
|
|
19
|
+
/** @codexApi {"parent":"pithy.core.bind-defer-directives","name":"bindDeferDirectives","stability":"stable","signature":"(fragment: DocumentFragment, templateContext: Record<string, unknown>, disposers: Array<() => void>) => void"} */
|
|
20
|
+
export declare function bindDeferDirectives(fragment: DocumentFragment, templateContext: Record<string, unknown>, disposers: Array<() => void>): void;
|
|
21
21
|
//# sourceMappingURL=bindDeferDirectives.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bindDeferDirectives.d.ts","sourceRoot":"","sources":["../../../src/compile/binds/bindDeferDirectives.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;
|
|
1
|
+
{"version":3,"file":"bindDeferDirectives.d.ts","sourceRoot":"","sources":["../../../src/compile/binds/bindDeferDirectives.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAsCF;;;;;;;;;;GAUG;AACH,2OAA2O;AAC3O,wBAAgB,mBAAmB,CACjC,QAAQ,EAAE,gBAAgB,EAC1B,eAAe,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EACxC,SAAS,EAAE,KAAK,CAAC,MAAM,IAAI,CAAC,GAC3B,IAAI,CAqiBN"}
|
|
@@ -18,9 +18,10 @@ import { DEFAULT_LAZY_TIMEOUT, } from '@pithyjs/compiler';
|
|
|
18
18
|
import { compileExpression } from '../compileExpression.js';
|
|
19
19
|
import { declaredValue } from './declaredDirective.js';
|
|
20
20
|
import { DEFAULT_VISIBILITY_MARGIN, isLazyHandle, observeVisibilityOnce, } from '../../runtime/index.js';
|
|
21
|
-
import {
|
|
21
|
+
import { boundaryTaking, setBoundaryError } from './bindErrorBoundary.js';
|
|
22
22
|
import { loadWithTimeout, scheduleByPriority, } from '../../runtime/deferHelpers.js';
|
|
23
23
|
import { setStyleProp } from './bindBoundAttributes.js';
|
|
24
|
+
import { nodeExpando } from '../nodeExpando.js';
|
|
24
25
|
/** Unique ID counter for defer anchors */
|
|
25
26
|
let deferIdCounter = 0;
|
|
26
27
|
/**
|
|
@@ -31,15 +32,16 @@ let deferIdCounter = 0;
|
|
|
31
32
|
* - `when`: Load when a boolean expression becomes truthy
|
|
32
33
|
*
|
|
33
34
|
* @param fragment - The root document fragment
|
|
34
|
-
* @param
|
|
35
|
+
* @param templateContext - Template context with signals and lazy handles, for an element that carries no context of its own
|
|
35
36
|
* @param disposers - Array to collect cleanup functions
|
|
36
37
|
*/
|
|
37
|
-
/** @codexApi {"parent":"pithy.core.bind-defer-directives","name":"bindDeferDirectives","stability":"stable","signature":"(fragment: DocumentFragment,
|
|
38
|
-
export function bindDeferDirectives(fragment,
|
|
38
|
+
/** @codexApi {"parent":"pithy.core.bind-defer-directives","name":"bindDeferDirectives","stability":"stable","signature":"(fragment: DocumentFragment, templateContext: Record<string, unknown>, disposers: Array<() => void>) => void"} */
|
|
39
|
+
export function bindDeferDirectives(fragment, templateContext, disposers) {
|
|
39
40
|
// Find all elements with @defer directive
|
|
40
41
|
const deferElements = fragment.querySelectorAll('[data-defer]');
|
|
41
42
|
for (const el of deferElements) {
|
|
42
43
|
const element = el;
|
|
44
|
+
const context = nodeExpando(element).__pithyCtx ?? templateContext;
|
|
43
45
|
// Skip elements already processed (e.g., inside component subtrees that
|
|
44
46
|
// ran their own bindDeferDirectives before being inserted into the outer DOM)
|
|
45
47
|
if (element.hasAttribute('data-defer-state'))
|
|
@@ -317,7 +319,7 @@ export function bindDeferDirectives(fragment, context, disposers) {
|
|
|
317
319
|
placeholderEl = null;
|
|
318
320
|
}
|
|
319
321
|
// Propagate error to nearest error boundary (if one exists)
|
|
320
|
-
const boundary =
|
|
322
|
+
const boundary = boundaryTaking(element);
|
|
321
323
|
if (boundary) {
|
|
322
324
|
setBoundaryError(boundary, error);
|
|
323
325
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bindDeferDirectives.js","sourceRoot":"","sources":["../../../src/compile/binds/bindDeferDirectives.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAEF;;;;;;;GAOG;AAEH,OAAO,EAAE,UAAU,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAC;AACtD,OAAO,EACL,oBAAoB,GAGrB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AACzD,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAEpD,OAAO,EACL,yBAAyB,EACzB,YAAY,EACZ,qBAAqB,GAEtB,MAAM,eAAe,CAAC;AAEvB,OAAO,EAAE,kBAAkB,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAC3E,OAAO,EACL,eAAe,EACf,kBAAkB,GACnB,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAAE,YAAY,EAAE,MAAM,uBAAuB,CAAC;AAErD,0CAA0C;AAC1C,IAAI,cAAc,GAAG,CAAC,CAAC;AAEvB;;;;;;;;;;GAUG;AACH,mOAAmO;AACnO,MAAM,UAAU,mBAAmB,CACjC,QAA0B,EAC1B,OAAgC,EAChC,SA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qBAAM,CAAC;oBACN,0EAA0E;oBAC1E,kBAAkB,EAAE,CAAC;oBAErB,iDAAiD;oBACjD,uEAAuE;oBACvE,IAAI,SAAS,IAAI,UAAU,EAAE,CAAC;wBAC5B,gBAAgB,EAAE,CAAC;oBACrB,CAAC;oBACD,qEAAqE;oBACrE,IAAI,OAAO,EAAE,CAAC;wBACZ,YAAY,CAAC,OAAO,EAAE,SAAS,EAAE,MAAM,CAAC,CAAC;oBAC3C,CAAC;gBACH,CAAC;YACH,CAAC,CAAC,CAAC;YAEH,SAAS,CAAC,IAAI,CAAC,GAAG,EAAE;gBAClB,UAAU,EAAE,CAAC;gBACb,OAAO,EAAE,CAAC;YACZ,CAAC,CAAC,CAAC;QACL,CAAC;aAAM,CAAC;YACN,IAAI,MAAM,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,EAAE,CAAC;gBACzB,OAAO,CAAC,IAAI,CAAC,gDAAgD,EAAE,OAAO,CAAC,CAAC;YAC1E,CAAC;QACH,CAAC;IACH,CAAC;AACH,CAAC","sourcesContent":["/** @codex\n{\n \"id\": \"pithy.core.bind-defer-directives\",\n \"title\": \"Defer Directive Binder for Lazy Loading\",\n \"category\": \"directive\"\n}\n*/\n\n/**\n * Lazy Loading Directive Binder\n *\n * Handles @defer directives to lazily load components based on\n * visibility (IntersectionObserver) or boolean conditions.\n *\n * @module compile/binds/bindDeferDirectives\n */\n\nimport { createRoot, effect } from '@pithyjs/signals';\nimport {\n DEFAULT_LAZY_TIMEOUT,\n type DeferTrigger,\n type LoadingPriority,\n} from '@pithyjs/compiler';\nimport { compileExpression } from '../compileExpression';\nimport { declaredValue } from './declaredDirective';\n\nimport {\n DEFAULT_VISIBILITY_MARGIN,\n isLazyHandle,\n observeVisibilityOnce,\n type LazyHandle,\n} from '../../runtime';\n\nimport { boundaryForElement, setBoundaryError } from './bindErrorBoundary';\nimport {\n loadWithTimeout,\n scheduleByPriority,\n} from '../../runtime/deferHelpers';\nimport { setStyleProp } from './bindBoundAttributes';\n\n/** Unique ID counter for defer anchors */\nlet deferIdCounter = 0;\n\n/**\n * Bind @defer directives to enable lazy loading of components.\n *\n * Supports two trigger modes:\n * - `visible`: Load when element scrolls into viewport (IntersectionObserver)\n * - `when`: Load when a boolean expression becomes truthy\n *\n * @param fragment - The root document fragment\n * @param context - Template context with signals and lazy handles\n * @param disposers - Array to collect cleanup functions\n */\n/** @codexApi {\"parent\":\"pithy.core.bind-defer-directives\",\"name\":\"bindDeferDirectives\",\"stability\":\"stable\",\"signature\":\"(fragment: DocumentFragment, context: Record<string, unknown>, disposers: Array<() => void>) => void\"} */\nexport function bindDeferDirectives(\n fragment: DocumentFragment,\n context: Record<string, unknown>,\n disposers: Array<() => void>\n): void {\n // Find all elements with @defer directive\n const deferElements = fragment.querySelectorAll('[data-defer]');\n\n for (const el of deferElements) {\n const element = el as HTMLElement;\n\n // Skip elements already processed (e.g., inside component subtrees that\n // ran their own bindDeferDirectives before being inserted into the outer DOM)\n if (element.hasAttribute('data-defer-state')) continue;\n\n // Read directive values from data attributes\n const trigger = declaredValue(element, 'data-defer') as\n | DeferTrigger\n | undefined;\n const loadExpr = declaredValue(element, 'data-load');\n const placeholderExpr = declaredValue(element, 'data-placeholder');\n const whenExpr = declaredValue(element, 'data-when');\n const priority = declaredValue(element, 'data-defer-priority') as\n | LoadingPriority\n | undefined;\n const timeoutStr = declaredValue(element, 'data-defer-timeout');\n const timeout = timeoutStr ? parseInt(timeoutStr, 10) : undefined;\n\n // Validate required attributes\n if (!trigger) {\n if (import.meta.env?.DEV) {\n console.warn('[pithy] @defer element missing trigger type', element);\n }\n continue;\n }\n\n if (!loadExpr) {\n if (import.meta.env?.DEV) {\n console.warn('[pithy] @defer element missing @load directive', element);\n }\n continue;\n }\n\n // Get the lazy handle from context\n const lazyHandleGetter = compileExpression<LazyHandle<unknown>>(\n loadExpr,\n context,\n undefined\n );\n const lazyHandle = lazyHandleGetter();\n\n if (!isLazyHandle(lazyHandle)) {\n if (import.meta.env?.DEV) {\n console.warn(\n `[pithy] @load=\"${loadExpr}\" did not resolve to a LazyHandle`,\n element\n );\n }\n continue;\n }\n\n // Use existing data-defer-id or generate a unique one\n const existingId = element.getAttribute('data-defer-id');\n const deferId = existingId || `defer-${++deferIdCounter}`;\n\n // Set data attributes for SSR markers (preserve existing ID if present)\n if (!existingId) {\n element.setAttribute('data-defer-id', deferId);\n }\n element.setAttribute('data-defer-state', 'pending');\n\n // Create anchor comment\n const anchor = document.createComment(`defer:${deferId}`);\n\n // Setup placeholder - check both data-placeholder attribute and slot=\"placeholder\" children\n let placeholderEl: HTMLElement | Text | null = null;\n\n // First, try to extract slot=\"placeholder\" from element children\n const slotPlaceholder = element.querySelector('[slot=\"placeholder\"]');\n if (slotPlaceholder) {\n // Remove from original parent and use as placeholder\n placeholderEl = slotPlaceholder as HTMLElement;\n placeholderEl.removeAttribute('slot');\n // Add data attribute for test accessibility\n placeholderEl.setAttribute('data-defer-placeholder', deferId);\n } else if (placeholderExpr) {\n // Fallback to data-placeholder attribute\n // Check if it's a string literal\n if (\n (placeholderExpr.startsWith(\"'\") && placeholderExpr.endsWith(\"'\")) ||\n (placeholderExpr.startsWith('\"') && placeholderExpr.endsWith('\"'))\n ) {\n // String placeholder\n const text = placeholderExpr.slice(1, -1);\n placeholderEl = document.createTextNode(text) as unknown as HTMLElement;\n } else {\n // Component placeholder - get from context\n const placeholderGetter = compileExpression<unknown>(\n placeholderExpr,\n context,\n null\n );\n const placeholder = placeholderGetter();\n\n if (typeof placeholder === 'function') {\n // It's a component function\n try {\n const result = (placeholder as () => unknown)();\n if (result && typeof result === 'object' && 'el' in result) {\n placeholderEl = (result as { el: HTMLElement }).el as HTMLElement;\n }\n } catch (err) {\n if (import.meta.env?.DEV) {\n console.warn(\n `[pithy] Error rendering placeholder component:`,\n err\n );\n }\n }\n }\n }\n }\n\n // Also extract slot=\"error\" for error handling\n const slotError = element.querySelector('[slot=\"error\"]');\n let errorEl: HTMLElement | null = null;\n if (slotError) {\n errorEl = slotError as HTMLElement;\n errorEl.removeAttribute('slot');\n // Add data attribute for test accessibility\n errorEl.setAttribute('data-defer-error', deferId);\n // Keep error slot hidden until needed\n setStyleProp(errorEl, 'display', 'none');\n }\n\n // Insert anchor and placeholder\n const parent = element.parentNode;\n if (!parent) continue;\n\n parent.insertBefore(anchor, element);\n\n if (placeholderEl) {\n // For @defer=\"when\", placeholder starts hidden (only shows during loading)\n // For @defer=\"visible\", placeholder shows immediately (triggers on visibility)\n if (trigger === 'when' && placeholderEl instanceof HTMLElement) {\n setStyleProp(placeholderEl, 'display', 'none');\n }\n parent.insertBefore(placeholderEl, element);\n }\n\n // Insert error element (hidden) after placeholder\n if (errorEl) {\n parent.insertBefore(errorEl, element);\n }\n\n // Hide the original element (it becomes the container after load)\n setStyleProp(element, 'display', 'none');\n\n // Track mounted component for cleanup\n let mountedDestroy: (() => void) | null = null;\n let disposeMountedSetup: (() => void) | null = null;\n let isMounted = false;\n let isMounting = false; // true while an async mount is in-flight\n\n // Mount generation counter — incremented on every unmount/cleanup to\n // invalidate in-flight async mounts that started before the unmount.\n let mountGeneration = 0;\n\n // Track inserted nodes directly (no wrapper div)\n let insertedNodes: Node[] = [];\n\n /**\n * Run and clear the mounted instance's teardown. Claimed before DOM\n * insertion, so a throw between the two still reaches it.\n */\n function releaseMountedComponent(): void {\n const destroyMounted = mountedDestroy;\n const disposeSetup = disposeMountedSetup;\n mountedDestroy = null;\n disposeMountedSetup = null;\n try {\n destroyMounted?.();\n } catch (err) {\n if (import.meta.env?.DEV) {\n console.warn('[pithy] @defer error in component destroy():', err);\n }\n } finally {\n try {\n disposeSetup?.();\n } catch (err) {\n if (import.meta.env?.DEV) {\n console.warn('[pithy] @defer error in setup cleanup:', err);\n }\n }\n }\n }\n\n /**\n * Remove mounted component nodes from DOM\n */\n function unmountComponent(): void {\n // Invalidate any in-flight async mount\n mountGeneration++;\n isMounting = false;\n\n releaseMountedComponent();\n\n // Remove all inserted nodes\n for (const node of insertedNodes) {\n if (node.parentNode) {\n node.parentNode.removeChild(node);\n }\n }\n insertedNodes = [];\n isMounted = false;\n\n // Hide placeholder if it was shown during a cancelled in-flight mount\n if (placeholderEl && placeholderEl instanceof HTMLElement) {\n setStyleProp(placeholderEl, 'display', 'none');\n }\n\n // Reset state to pending (ready for re-mount on next trigger)\n element.setAttribute('data-defer-state', 'pending');\n }\n\n /**\n * Mount the lazy component with timeout support\n */\n async function mountComponent(): Promise<void> {\n // If already mounted or a mount is in-flight, skip\n if (isMounted || isMounting) return;\n\n isMounting = true;\n\n // Capture generation so we can detect if an unmount happened while awaiting\n const thisGeneration = mountGeneration;\n\n element.setAttribute('data-defer-state', 'loading');\n\n // Show placeholder during loading (for @defer=\"when\" it starts hidden)\n if (placeholderEl && placeholderEl instanceof HTMLElement) {\n setStyleProp(placeholderEl, 'display', null);\n }\n\n try {\n // Load the module with timeout (chunk is cached after first load)\n const effectiveTimeout = timeout ?? DEFAULT_LAZY_TIMEOUT;\n const module = await loadWithTimeout(lazyHandle, effectiveTimeout);\n\n // Check if an unmount/cleanup happened during async load (generation changed)\n if (thisGeneration !== mountGeneration) {\n isMounting = false;\n return;\n }\n\n // Use fresh parentNode — the element may have been moved into the real DOM\n // by bindComponentTags.replaceWith() during the async gap\n const freshParent = element.parentNode;\n if (!freshParent) {\n isMounting = false;\n return;\n }\n\n element.setAttribute('data-defer-state', 'loaded');\n\n // Remove placeholder\n if (placeholderEl && placeholderEl.parentNode) {\n placeholderEl.parentNode.removeChild(placeholderEl);\n placeholderEl = null;\n }\n\n // Remove error element (no longer needed on success)\n if (errorEl && errorEl.parentNode) {\n errorEl.parentNode.removeChild(errorEl);\n errorEl = null;\n }\n\n // Get the component from the module\n const Component = (module as { default?: unknown }).default || module;\n\n if (typeof Component === 'function') {\n // Render the component\n let disposeSetup: (() => void) | undefined;\n const result = createRoot(disposeRoot => {\n disposeSetup = disposeRoot;\n return (Component as () => unknown)();\n });\n\n if (result && typeof result === 'object' && 'el' in result) {\n const { el, destroy } = result as {\n el: HTMLElement | DocumentFragment;\n destroy?: () => void;\n };\n\n mountedDestroy = destroy ?? null;\n disposeMountedSetup = disposeSetup ?? null;\n\n // Insert component content directly (no wrapper div)\n if (el instanceof DocumentFragment) {\n // Track all children before moving them\n const nodes = Array.from(el.childNodes);\n insertedNodes = nodes;\n // Insert fragment directly - this moves all children to the DOM\n freshParent.insertBefore(el, element);\n } else {\n insertedNodes = [el];\n freshParent.insertBefore(el, element);\n }\n\n isMounted = true;\n isMounting = false;\n\n // Dispatch loaded event\n element.dispatchEvent(\n new CustomEvent('loaded', {\n detail: {\n ttiMs: Date.now(), // Could track actual load time\n chunkId: lazyHandle.key,\n },\n bubbles: true,\n })\n );\n } else {\n disposeSetup?.();\n isMounting = false;\n }\n } else {\n isMounting = false;\n }\n } catch (err) {\n isMounting = false;\n if (!isMounted) releaseMountedComponent();\n\n // Check if an unmount/cleanup happened during async load\n if (thisGeneration !== mountGeneration) return;\n\n element.setAttribute('data-defer-state', 'error');\n\n const error = err instanceof Error ? err : new Error(String(err));\n\n // Remove placeholder and show error slot if available\n if (placeholderEl && placeholderEl.parentNode) {\n placeholderEl.parentNode.removeChild(placeholderEl);\n placeholderEl = null;\n }\n\n // Propagate error to nearest error boundary (if one exists)\n const boundary = boundaryForElement(element);\n if (boundary) {\n setBoundaryError(boundary, error);\n } else if (errorEl) {\n // No error boundary - fall back to local error slot\n setStyleProp(errorEl, 'display', null);\n }\n\n // Dispatch error event (for programmatic handling)\n element.dispatchEvent(\n new CustomEvent('error', {\n detail: {\n error,\n retry: () => {\n // Hide error, re-show placeholder if we had one\n if (errorEl) {\n setStyleProp(errorEl, 'display', 'none');\n }\n lazyHandle.retry().then(mountComponent);\n },\n },\n bubbles: true,\n })\n );\n\n if (import.meta.env?.DEV) {\n console.error(`[pithy] Failed to load lazy component:`, err);\n }\n }\n }\n\n // Track idle callback for cancellation\n let idleCallbackId: number | undefined;\n\n /**\n * Cleanup function\n */\n function cleanup(): void {\n // Cancel any scheduled-but-not-started mount\n cancelPendingMount();\n\n // Invalidate any in-flight async mount (unmountComponent also does this,\n // but we bump it here too in case unmountComponent is skipped)\n mountGeneration++;\n\n // Cancel pending idle callback (cancelPendingMount handles the scheduled\n // case, but cover the already-in-flight case too)\n if (\n idleCallbackId !== undefined &&\n typeof cancelIdleCallback !== 'undefined'\n ) {\n cancelIdleCallback(idleCallbackId);\n idleCallbackId = undefined;\n }\n\n // Unmount component (calls destroy and removes nodes)\n unmountComponent();\n\n // Cancel any in-flight load\n lazyHandle.cancel();\n }\n\n // Track whether a mount has been scheduled but not yet started.\n // This is needed so that unmount/cancel can invalidate pending\n // scheduled mounts (e.g., rapid toggle: true → false → true).\n let mountScheduled = false;\n\n /**\n * Trigger mount with priority scheduling\n */\n function triggerMount(): void {\n mountScheduled = true;\n // Capture current generation so the microtask can detect cancellation.\n // cancelPendingMount bumps mountGeneration, so if it fires between\n // scheduling and execution, the microtask will see the mismatch.\n const expectedGen = mountGeneration;\n const result = scheduleByPriority(() => {\n mountScheduled = false;\n if (expectedGen !== mountGeneration) return; // cancelled\n mountComponent();\n }, priority);\n\n // Track idle callback ID for cleanup\n if (typeof result === 'number') {\n idleCallbackId = result;\n }\n }\n\n /**\n * Cancel any pending scheduled mount that hasn't started yet.\n * Bumps mountGeneration to also invalidate any in-flight async mounts.\n */\n function cancelPendingMount(): void {\n if (mountScheduled) {\n mountScheduled = false;\n mountGeneration++;\n // Cancel pending idle callback if one is tracked\n if (\n idleCallbackId !== undefined &&\n typeof cancelIdleCallback !== 'undefined'\n ) {\n cancelIdleCallback(idleCallbackId);\n idleCallbackId = undefined;\n }\n }\n }\n\n // Subscribe to lazy handle state for external retry support\n // This allows calling lazyHandle.retry() from error slot buttons\n const stopStateEffect = effect(() => {\n const handleState = lazyHandle.state();\n const elementState = element.getAttribute('data-defer-state');\n\n // If handle loaded externally (via retry) and we're in error state, try to mount\n if (\n handleState === 'loaded' &&\n !isMounted &&\n !isMounting &&\n elementState === 'error'\n ) {\n // Hide error slot\n if (errorEl) {\n setStyleProp(errorEl, 'display', 'none');\n }\n // Mount the component - it will handle state transitions\n mountComponent();\n }\n });\n\n disposers.push(stopStateEffect);\n\n // Setup trigger based on mode\n if (trigger === 'visible') {\n // Visibility trigger using IntersectionObserver\n // IMPORTANT: Observe the placeholder (which is visible), not the hidden element\n // If no placeholder exists, create a sentinel element to observe\n let observeTarget: Element;\n let sentinelEl: HTMLElement | null = null;\n\n if (placeholderEl && placeholderEl instanceof HTMLElement) {\n observeTarget = placeholderEl;\n } else {\n // Create a minimal sentinel element to observe\n sentinelEl = document.createElement('span');\n sentinelEl.style.display = 'inline-block';\n sentinelEl.style.width = '1px';\n sentinelEl.style.height = '1px';\n parent.insertBefore(sentinelEl, element);\n observeTarget = sentinelEl;\n }\n\n const stopObserving = observeVisibilityOnce(observeTarget, triggerMount, {\n rootMargin: DEFAULT_VISIBILITY_MARGIN,\n });\n\n disposers.push(() => {\n stopObserving();\n // Remove sentinel if we created one\n if (sentinelEl && sentinelEl.parentNode) {\n sentinelEl.parentNode.removeChild(sentinelEl);\n }\n cleanup();\n });\n } else if (trigger === 'when' && whenExpr) {\n // Boolean trigger using effect\n const conditionGetter = compileExpression<boolean>(\n whenExpr,\n context,\n false\n );\n\n const stopEffect = effect(() => {\n const shouldShow = conditionGetter();\n\n if (shouldShow) {\n // Mount component (chunk is cached after first load, so remounting is fast)\n if (!isMounted && !isMounting && !mountScheduled) {\n triggerMount();\n }\n } else {\n // Cancel any scheduled-but-not-started mount first (handles rapid toggle)\n cancelPendingMount();\n\n // Destroy component when condition becomes false\n // This is consistent with React, Vue, Angular - no automatic show/hide\n if (isMounted || isMounting) {\n unmountComponent();\n }\n // Hide error slot when condition becomes false (after a failed load)\n if (errorEl) {\n setStyleProp(errorEl, 'display', 'none');\n }\n }\n });\n\n disposers.push(() => {\n stopEffect();\n cleanup();\n });\n } else {\n if (import.meta.env?.DEV) {\n console.warn(`[pithy] @defer=\"when\" requires @when attribute`, element);\n }\n }\n }\n}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H,SAAS,CAAC,IAAI,CAAC,GAAG,EAAE;gBAClB,UAAU,EAAE,CAAC;gBACb,OAAO,EAAE,CAAC;YACZ,CAAC,CAAC,CAAC;QACL,CAAC;aAAM,CAAC;YACN,IAAI,MAAM,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,EAAE,CAAC;gBACzB,OAAO,CAAC,IAAI,CAAC,gDAAgD,EAAE,OAAO,CAAC,CAAC;YAC1E,CAAC;QACH,CAAC;IACH,CAAC;AACH,CAAC","sourcesContent":["/** @codex\n{\n \"id\": \"pithy.core.bind-defer-directives\",\n \"title\": \"Defer Directive Binder for Lazy Loading\",\n \"category\": \"directive\"\n}\n*/\n\n/**\n * Lazy Loading Directive Binder\n *\n * Handles @defer directives to lazily load components based on\n * visibility (IntersectionObserver) or boolean conditions.\n *\n * @module compile/binds/bindDeferDirectives\n */\n\nimport { createRoot, effect } from '@pithyjs/signals';\nimport {\n DEFAULT_LAZY_TIMEOUT,\n type DeferTrigger,\n type LoadingPriority,\n} from '@pithyjs/compiler';\nimport { compileExpression } from '../compileExpression';\nimport { declaredValue } from './declaredDirective';\n\nimport {\n DEFAULT_VISIBILITY_MARGIN,\n isLazyHandle,\n observeVisibilityOnce,\n type LazyHandle,\n} from '../../runtime';\n\nimport { boundaryTaking, setBoundaryError } from './bindErrorBoundary';\nimport {\n loadWithTimeout,\n scheduleByPriority,\n} from '../../runtime/deferHelpers';\nimport { setStyleProp } from './bindBoundAttributes';\nimport { nodeExpando } from '../nodeExpando';\n\n/** Unique ID counter for defer anchors */\nlet deferIdCounter = 0;\n\n/**\n * Bind @defer directives to enable lazy loading of components.\n *\n * Supports two trigger modes:\n * - `visible`: Load when element scrolls into viewport (IntersectionObserver)\n * - `when`: Load when a boolean expression becomes truthy\n *\n * @param fragment - The root document fragment\n * @param templateContext - Template context with signals and lazy handles, for an element that carries no context of its own\n * @param disposers - Array to collect cleanup functions\n */\n/** @codexApi {\"parent\":\"pithy.core.bind-defer-directives\",\"name\":\"bindDeferDirectives\",\"stability\":\"stable\",\"signature\":\"(fragment: DocumentFragment, templateContext: Record<string, unknown>, disposers: Array<() => void>) => void\"} */\nexport function bindDeferDirectives(\n fragment: DocumentFragment,\n templateContext: Record<string, unknown>,\n disposers: Array<() => void>\n): void {\n // Find all elements with @defer directive\n const deferElements = fragment.querySelectorAll('[data-defer]');\n\n for (const el of deferElements) {\n const element = el as HTMLElement;\n const context = nodeExpando(element).__pithyCtx ?? templateContext;\n\n // Skip elements already processed (e.g., inside component subtrees that\n // ran their own bindDeferDirectives before being inserted into the outer DOM)\n if (element.hasAttribute('data-defer-state')) continue;\n\n // Read directive values from data attributes\n const trigger = declaredValue(element, 'data-defer') as\n | DeferTrigger\n | undefined;\n const loadExpr = declaredValue(element, 'data-load');\n const placeholderExpr = declaredValue(element, 'data-placeholder');\n const whenExpr = declaredValue(element, 'data-when');\n const priority = declaredValue(element, 'data-defer-priority') as\n | LoadingPriority\n | undefined;\n const timeoutStr = declaredValue(element, 'data-defer-timeout');\n const timeout = timeoutStr ? parseInt(timeoutStr, 10) : undefined;\n\n // Validate required attributes\n if (!trigger) {\n if (import.meta.env?.DEV) {\n console.warn('[pithy] @defer element missing trigger type', element);\n }\n continue;\n }\n\n if (!loadExpr) {\n if (import.meta.env?.DEV) {\n console.warn('[pithy] @defer element missing @load directive', element);\n }\n continue;\n }\n\n // Get the lazy handle from context\n const lazyHandleGetter = compileExpression<LazyHandle<unknown>>(\n loadExpr,\n context,\n undefined\n );\n const lazyHandle = lazyHandleGetter();\n\n if (!isLazyHandle(lazyHandle)) {\n if (import.meta.env?.DEV) {\n console.warn(\n `[pithy] @load=\"${loadExpr}\" did not resolve to a LazyHandle`,\n element\n );\n }\n continue;\n }\n\n // Use existing data-defer-id or generate a unique one\n const existingId = element.getAttribute('data-defer-id');\n const deferId = existingId || `defer-${++deferIdCounter}`;\n\n // Set data attributes for SSR markers (preserve existing ID if present)\n if (!existingId) {\n element.setAttribute('data-defer-id', deferId);\n }\n element.setAttribute('data-defer-state', 'pending');\n\n // Create anchor comment\n const anchor = document.createComment(`defer:${deferId}`);\n\n // Setup placeholder - check both data-placeholder attribute and slot=\"placeholder\" children\n let placeholderEl: HTMLElement | Text | null = null;\n\n // First, try to extract slot=\"placeholder\" from element children\n const slotPlaceholder = element.querySelector('[slot=\"placeholder\"]');\n if (slotPlaceholder) {\n // Remove from original parent and use as placeholder\n placeholderEl = slotPlaceholder as HTMLElement;\n placeholderEl.removeAttribute('slot');\n // Add data attribute for test accessibility\n placeholderEl.setAttribute('data-defer-placeholder', deferId);\n } else if (placeholderExpr) {\n // Fallback to data-placeholder attribute\n // Check if it's a string literal\n if (\n (placeholderExpr.startsWith(\"'\") && placeholderExpr.endsWith(\"'\")) ||\n (placeholderExpr.startsWith('\"') && placeholderExpr.endsWith('\"'))\n ) {\n // String placeholder\n const text = placeholderExpr.slice(1, -1);\n placeholderEl = document.createTextNode(text) as unknown as HTMLElement;\n } else {\n // Component placeholder - get from context\n const placeholderGetter = compileExpression<unknown>(\n placeholderExpr,\n context,\n null\n );\n const placeholder = placeholderGetter();\n\n if (typeof placeholder === 'function') {\n // It's a component function\n try {\n const result = (placeholder as () => unknown)();\n if (result && typeof result === 'object' && 'el' in result) {\n placeholderEl = (result as { el: HTMLElement }).el as HTMLElement;\n }\n } catch (err) {\n if (import.meta.env?.DEV) {\n console.warn(\n `[pithy] Error rendering placeholder component:`,\n err\n );\n }\n }\n }\n }\n }\n\n // Also extract slot=\"error\" for error handling\n const slotError = element.querySelector('[slot=\"error\"]');\n let errorEl: HTMLElement | null = null;\n if (slotError) {\n errorEl = slotError as HTMLElement;\n errorEl.removeAttribute('slot');\n // Add data attribute for test accessibility\n errorEl.setAttribute('data-defer-error', deferId);\n // Keep error slot hidden until needed\n setStyleProp(errorEl, 'display', 'none');\n }\n\n // Insert anchor and placeholder\n const parent = element.parentNode;\n if (!parent) continue;\n\n parent.insertBefore(anchor, element);\n\n if (placeholderEl) {\n // For @defer=\"when\", placeholder starts hidden (only shows during loading)\n // For @defer=\"visible\", placeholder shows immediately (triggers on visibility)\n if (trigger === 'when' && placeholderEl instanceof HTMLElement) {\n setStyleProp(placeholderEl, 'display', 'none');\n }\n parent.insertBefore(placeholderEl, element);\n }\n\n // Insert error element (hidden) after placeholder\n if (errorEl) {\n parent.insertBefore(errorEl, element);\n }\n\n // Hide the original element (it becomes the container after load)\n setStyleProp(element, 'display', 'none');\n\n // Track mounted component for cleanup\n let mountedDestroy: (() => void) | null = null;\n let disposeMountedSetup: (() => void) | null = null;\n let isMounted = false;\n let isMounting = false; // true while an async mount is in-flight\n\n // Mount generation counter — incremented on every unmount/cleanup to\n // invalidate in-flight async mounts that started before the unmount.\n let mountGeneration = 0;\n\n // Track inserted nodes directly (no wrapper div)\n let insertedNodes: Node[] = [];\n\n /**\n * Run and clear the mounted instance's teardown. Claimed before DOM\n * insertion, so a throw between the two still reaches it.\n */\n function releaseMountedComponent(): void {\n const destroyMounted = mountedDestroy;\n const disposeSetup = disposeMountedSetup;\n mountedDestroy = null;\n disposeMountedSetup = null;\n try {\n destroyMounted?.();\n } catch (err) {\n if (import.meta.env?.DEV) {\n console.warn('[pithy] @defer error in component destroy():', err);\n }\n } finally {\n try {\n disposeSetup?.();\n } catch (err) {\n if (import.meta.env?.DEV) {\n console.warn('[pithy] @defer error in setup cleanup:', err);\n }\n }\n }\n }\n\n /**\n * Remove mounted component nodes from DOM\n */\n function unmountComponent(): void {\n // Invalidate any in-flight async mount\n mountGeneration++;\n isMounting = false;\n\n releaseMountedComponent();\n\n // Remove all inserted nodes\n for (const node of insertedNodes) {\n if (node.parentNode) {\n node.parentNode.removeChild(node);\n }\n }\n insertedNodes = [];\n isMounted = false;\n\n // Hide placeholder if it was shown during a cancelled in-flight mount\n if (placeholderEl && placeholderEl instanceof HTMLElement) {\n setStyleProp(placeholderEl, 'display', 'none');\n }\n\n // Reset state to pending (ready for re-mount on next trigger)\n element.setAttribute('data-defer-state', 'pending');\n }\n\n /**\n * Mount the lazy component with timeout support\n */\n async function mountComponent(): Promise<void> {\n // If already mounted or a mount is in-flight, skip\n if (isMounted || isMounting) return;\n\n isMounting = true;\n\n // Capture generation so we can detect if an unmount happened while awaiting\n const thisGeneration = mountGeneration;\n\n element.setAttribute('data-defer-state', 'loading');\n\n // Show placeholder during loading (for @defer=\"when\" it starts hidden)\n if (placeholderEl && placeholderEl instanceof HTMLElement) {\n setStyleProp(placeholderEl, 'display', null);\n }\n\n try {\n // Load the module with timeout (chunk is cached after first load)\n const effectiveTimeout = timeout ?? DEFAULT_LAZY_TIMEOUT;\n const module = await loadWithTimeout(lazyHandle, effectiveTimeout);\n\n // Check if an unmount/cleanup happened during async load (generation changed)\n if (thisGeneration !== mountGeneration) {\n isMounting = false;\n return;\n }\n\n // Use fresh parentNode — the element may have been moved into the real DOM\n // by bindComponentTags.replaceWith() during the async gap\n const freshParent = element.parentNode;\n if (!freshParent) {\n isMounting = false;\n return;\n }\n\n element.setAttribute('data-defer-state', 'loaded');\n\n // Remove placeholder\n if (placeholderEl && placeholderEl.parentNode) {\n placeholderEl.parentNode.removeChild(placeholderEl);\n placeholderEl = null;\n }\n\n // Remove error element (no longer needed on success)\n if (errorEl && errorEl.parentNode) {\n errorEl.parentNode.removeChild(errorEl);\n errorEl = null;\n }\n\n // Get the component from the module\n const Component = (module as { default?: unknown }).default || module;\n\n if (typeof Component === 'function') {\n // Render the component\n let disposeSetup: (() => void) | undefined;\n const result = createRoot(disposeRoot => {\n disposeSetup = disposeRoot;\n return (Component as () => unknown)();\n });\n\n if (result && typeof result === 'object' && 'el' in result) {\n const { el, destroy } = result as {\n el: HTMLElement | DocumentFragment;\n destroy?: () => void;\n };\n\n mountedDestroy = destroy ?? null;\n disposeMountedSetup = disposeSetup ?? null;\n\n // Insert component content directly (no wrapper div)\n if (el instanceof DocumentFragment) {\n // Track all children before moving them\n const nodes = Array.from(el.childNodes);\n insertedNodes = nodes;\n // Insert fragment directly - this moves all children to the DOM\n freshParent.insertBefore(el, element);\n } else {\n insertedNodes = [el];\n freshParent.insertBefore(el, element);\n }\n\n isMounted = true;\n isMounting = false;\n\n // Dispatch loaded event\n element.dispatchEvent(\n new CustomEvent('loaded', {\n detail: {\n ttiMs: Date.now(), // Could track actual load time\n chunkId: lazyHandle.key,\n },\n bubbles: true,\n })\n );\n } else {\n disposeSetup?.();\n isMounting = false;\n }\n } else {\n isMounting = false;\n }\n } catch (err) {\n isMounting = false;\n if (!isMounted) releaseMountedComponent();\n\n // Check if an unmount/cleanup happened during async load\n if (thisGeneration !== mountGeneration) return;\n\n element.setAttribute('data-defer-state', 'error');\n\n const error = err instanceof Error ? err : new Error(String(err));\n\n // Remove placeholder and show error slot if available\n if (placeholderEl && placeholderEl.parentNode) {\n placeholderEl.parentNode.removeChild(placeholderEl);\n placeholderEl = null;\n }\n\n // Propagate error to nearest error boundary (if one exists)\n const boundary = boundaryTaking(element);\n if (boundary) {\n setBoundaryError(boundary, error);\n } else if (errorEl) {\n // No error boundary - fall back to local error slot\n setStyleProp(errorEl, 'display', null);\n }\n\n // Dispatch error event (for programmatic handling)\n element.dispatchEvent(\n new CustomEvent('error', {\n detail: {\n error,\n retry: () => {\n // Hide error, re-show placeholder if we had one\n if (errorEl) {\n setStyleProp(errorEl, 'display', 'none');\n }\n lazyHandle.retry().then(mountComponent);\n },\n },\n bubbles: true,\n })\n );\n\n if (import.meta.env?.DEV) {\n console.error(`[pithy] Failed to load lazy component:`, err);\n }\n }\n }\n\n // Track idle callback for cancellation\n let idleCallbackId: number | undefined;\n\n /**\n * Cleanup function\n */\n function cleanup(): void {\n // Cancel any scheduled-but-not-started mount\n cancelPendingMount();\n\n // Invalidate any in-flight async mount (unmountComponent also does this,\n // but we bump it here too in case unmountComponent is skipped)\n mountGeneration++;\n\n // Cancel pending idle callback (cancelPendingMount handles the scheduled\n // case, but cover the already-in-flight case too)\n if (\n idleCallbackId !== undefined &&\n typeof cancelIdleCallback !== 'undefined'\n ) {\n cancelIdleCallback(idleCallbackId);\n idleCallbackId = undefined;\n }\n\n // Unmount component (calls destroy and removes nodes)\n unmountComponent();\n\n // Cancel any in-flight load\n lazyHandle.cancel();\n }\n\n // Track whether a mount has been scheduled but not yet started.\n // This is needed so that unmount/cancel can invalidate pending\n // scheduled mounts (e.g., rapid toggle: true → false → true).\n let mountScheduled = false;\n\n /**\n * Trigger mount with priority scheduling\n */\n function triggerMount(): void {\n mountScheduled = true;\n // Capture current generation so the microtask can detect cancellation.\n // cancelPendingMount bumps mountGeneration, so if it fires between\n // scheduling and execution, the microtask will see the mismatch.\n const expectedGen = mountGeneration;\n const result = scheduleByPriority(() => {\n mountScheduled = false;\n if (expectedGen !== mountGeneration) return; // cancelled\n mountComponent();\n }, priority);\n\n // Track idle callback ID for cleanup\n if (typeof result === 'number') {\n idleCallbackId = result;\n }\n }\n\n /**\n * Cancel any pending scheduled mount that hasn't started yet.\n * Bumps mountGeneration to also invalidate any in-flight async mounts.\n */\n function cancelPendingMount(): void {\n if (mountScheduled) {\n mountScheduled = false;\n mountGeneration++;\n // Cancel pending idle callback if one is tracked\n if (\n idleCallbackId !== undefined &&\n typeof cancelIdleCallback !== 'undefined'\n ) {\n cancelIdleCallback(idleCallbackId);\n idleCallbackId = undefined;\n }\n }\n }\n\n // Subscribe to lazy handle state for external retry support\n // This allows calling lazyHandle.retry() from error slot buttons\n const stopStateEffect = effect(() => {\n const handleState = lazyHandle.state();\n const elementState = element.getAttribute('data-defer-state');\n\n // If handle loaded externally (via retry) and we're in error state, try to mount\n if (\n handleState === 'loaded' &&\n !isMounted &&\n !isMounting &&\n elementState === 'error'\n ) {\n // Hide error slot\n if (errorEl) {\n setStyleProp(errorEl, 'display', 'none');\n }\n // Mount the component - it will handle state transitions\n mountComponent();\n }\n });\n\n disposers.push(stopStateEffect);\n\n // Setup trigger based on mode\n if (trigger === 'visible') {\n // Visibility trigger using IntersectionObserver\n // IMPORTANT: Observe the placeholder (which is visible), not the hidden element\n // If no placeholder exists, create a sentinel element to observe\n let observeTarget: Element;\n let sentinelEl: HTMLElement | null = null;\n\n if (placeholderEl && placeholderEl instanceof HTMLElement) {\n observeTarget = placeholderEl;\n } else {\n // Create a minimal sentinel element to observe\n sentinelEl = document.createElement('span');\n sentinelEl.style.display = 'inline-block';\n sentinelEl.style.width = '1px';\n sentinelEl.style.height = '1px';\n parent.insertBefore(sentinelEl, element);\n observeTarget = sentinelEl;\n }\n\n const stopObserving = observeVisibilityOnce(observeTarget, triggerMount, {\n rootMargin: DEFAULT_VISIBILITY_MARGIN,\n });\n\n disposers.push(() => {\n stopObserving();\n // Remove sentinel if we created one\n if (sentinelEl && sentinelEl.parentNode) {\n sentinelEl.parentNode.removeChild(sentinelEl);\n }\n cleanup();\n });\n } else if (trigger === 'when' && whenExpr) {\n // Boolean trigger using effect\n const conditionGetter = compileExpression<boolean>(\n whenExpr,\n context,\n false\n );\n\n const stopEffect = effect(() => {\n const shouldShow = conditionGetter();\n\n if (shouldShow) {\n // Mount component (chunk is cached after first load, so remounting is fast)\n if (!isMounted && !isMounting && !mountScheduled) {\n triggerMount();\n }\n } else {\n // Cancel any scheduled-but-not-started mount first (handles rapid toggle)\n cancelPendingMount();\n\n // Destroy component when condition becomes false\n // This is consistent with React, Vue, Angular - no automatic show/hide\n if (isMounted || isMounting) {\n unmountComponent();\n }\n // Hide error slot when condition becomes false (after a failed load)\n if (errorEl) {\n setStyleProp(errorEl, 'display', 'none');\n }\n }\n });\n\n disposers.push(() => {\n stopEffect();\n cleanup();\n });\n } else {\n if (import.meta.env?.DEV) {\n console.warn(`[pithy] @defer=\"when\" requires @when attribute`, element);\n }\n }\n }\n}\n"]}
|
|
@@ -33,6 +33,10 @@ export declare function boundaryForElement(el: Element | null): BoundaryInfo | n
|
|
|
33
33
|
*/
|
|
34
34
|
/** @codexApi {"parent":"pithy.feature.error-boundary","name":"withSlotBoundary","stability":"experimental","signature":"<T>(anchor: Node | undefined, host: Element | undefined, fn: () => T) => T"} */
|
|
35
35
|
export declare function withSlotBoundary<T>(anchor: Node | undefined, host: Element | undefined, fn: () => T): T;
|
|
36
|
+
/** @codexApi {"parent":"pithy.feature.error-boundary","name":"inOwnFallback","stability":"internal","signature":"(boundary: BoundaryInfo, el: Element) => boolean"} */
|
|
37
|
+
export declare function inOwnFallback(boundary: BoundaryInfo, el: Element): boolean;
|
|
38
|
+
/** @codexApi {"parent":"pithy.feature.error-boundary","name":"boundaryTaking","stability":"internal","signature":"(el: Element) => BoundaryInfo | null"} */
|
|
39
|
+
export declare function boundaryTaking(el: Element): BoundaryInfo | null;
|
|
36
40
|
/** The boundary element of the slot that rendered `node`, if a slot did. */
|
|
37
41
|
/** @codexApi {"parent":"pithy.feature.error-boundary","name":"slotOwnerOf","stability":"internal","signature":"(node: Node) => Element | null"} */
|
|
38
42
|
export declare function slotOwnerOf(node: Node): Element | null;
|
|
@@ -119,8 +123,8 @@ export declare function currentBoundary(): BoundaryInfo | null;
|
|
|
119
123
|
* @param fn - Function to execute
|
|
120
124
|
* @returns Result of function execution
|
|
121
125
|
*/
|
|
122
|
-
/** @codexApi {"parent":"pithy.feature.error-boundary","name":"runWithBoundary","stability":"stable","signature":"<T>(boundary: BoundaryInfo | null, fn: () => T) => T"} */
|
|
123
|
-
export declare function runWithBoundary<T>(boundary: BoundaryInfo | null, fn: () => T): T;
|
|
126
|
+
/** @codexApi {"parent":"pithy.feature.error-boundary","name":"runWithBoundary","stability":"stable","signature":"<T>(boundary: BoundaryInfo | null, fn: () => T, host?: Element) => T"} */
|
|
127
|
+
export declare function runWithBoundary<T>(boundary: BoundaryInfo | null, fn: () => T, host?: Element): T;
|
|
124
128
|
/**
|
|
125
129
|
* Register a single element as an error boundary.
|
|
126
130
|
* Used by AOT applyBindings where the boundary element is known directly
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bindErrorBoundary.d.ts","sourceRoot":"","sources":["../../../src/compile/binds/bindErrorBoundary.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAIF,OAAO,EAAU,MAAM,EAAW,MAAM,kB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