@pithyjs/core 0.1.0-beta.13 → 0.1.0-beta.15
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 +13 -1
- package/dist/a11y/focus-trap.d.ts +11 -3
- package/dist/a11y/focus-trap.d.ts.map +1 -1
- package/dist/a11y/focus-trap.js +53 -10
- package/dist/a11y/focus-trap.js.map +1 -1
- package/dist/compile/bindSwitchCases.d.ts.map +1 -1
- package/dist/compile/bindSwitchCases.js +28 -7
- package/dist/compile/bindSwitchCases.js.map +1 -1
- package/dist/compile/binds/bindAfterComponents.d.ts +4 -0
- package/dist/compile/binds/bindAfterComponents.d.ts.map +1 -0
- package/dist/compile/binds/bindAfterComponents.js +26 -0
- package/dist/compile/binds/bindAfterComponents.js.map +1 -0
- package/dist/compile/binds/bindAfterProjection.d.ts +7 -0
- package/dist/compile/binds/bindAfterProjection.d.ts.map +1 -0
- package/dist/compile/binds/bindAfterProjection.js +13 -0
- package/dist/compile/binds/bindAfterProjection.js.map +1 -0
- package/dist/compile/binds/bindComponentsTags.d.ts.map +1 -1
- package/dist/compile/binds/bindComponentsTags.js +41 -11
- package/dist/compile/binds/bindComponentsTags.js.map +1 -1
- package/dist/compile/binds/bindErrorBoundary.d.ts +11 -1
- package/dist/compile/binds/bindErrorBoundary.d.ts.map +1 -1
- package/dist/compile/binds/bindErrorBoundary.js +44 -9
- package/dist/compile/binds/bindErrorBoundary.js.map +1 -1
- package/dist/compile/compileNodes.d.ts.map +1 -1
- package/dist/compile/compileNodes.js +2 -0
- package/dist/compile/compileNodes.js.map +1 -1
- package/dist/compile/compileTemplate.d.ts.map +1 -1
- package/dist/compile/compileTemplate.js +5 -24
- package/dist/compile/compileTemplate.js.map +1 -1
- package/dist/compile/contentProjection.d.ts +12 -0
- package/dist/compile/contentProjection.d.ts.map +1 -1
- package/dist/compile/contentProjection.js +42 -0
- package/dist/compile/contentProjection.js.map +1 -1
- package/dist/compile/disposeOrder.d.ts +35 -0
- package/dist/compile/disposeOrder.d.ts.map +1 -0
- package/dist/compile/disposeOrder.js +81 -0
- package/dist/compile/disposeOrder.js.map +1 -0
- package/dist/compile/forLoops/bindForLoops.d.ts +1 -1
- package/dist/compile/forLoops/bindForLoops.d.ts.map +1 -1
- package/dist/compile/forLoops/bindForLoops.js +10 -3
- package/dist/compile/forLoops/bindForLoops.js.map +1 -1
- package/dist/compile/forLoops/createLoopManager.d.ts.map +1 -1
- package/dist/compile/forLoops/createLoopManager.js +19 -2
- package/dist/compile/forLoops/createLoopManager.js.map +1 -1
- package/dist/compile/handleConditionalChain.d.ts.map +1 -1
- package/dist/compile/handleConditionalChain.js +2 -3
- package/dist/compile/handleConditionalChain.js.map +1 -1
- package/dist/compile/renderBranch.d.ts +1 -1
- package/dist/compile/renderBranch.d.ts.map +1 -1
- package/dist/compile/renderBranch.js +6 -4
- package/dist/compile/renderBranch.js.map +1 -1
- package/dist/compile/renderChildren.d.ts +3 -1
- package/dist/compile/renderChildren.d.ts.map +1 -1
- package/dist/compile/renderChildren.js +8 -1
- package/dist/compile/renderChildren.js.map +1 -1
- package/dist/runtime/applyBindings.d.ts +6 -2
- package/dist/runtime/applyBindings.d.ts.map +1 -1
- package/dist/runtime/applyBindings.js +43 -22
- package/dist/runtime/applyBindings.js.map +1 -1
- package/dist/runtime/bindings/applyComponent.d.ts.map +1 -1
- package/dist/runtime/bindings/applyComponent.js +12 -7
- package/dist/runtime/bindings/applyComponent.js.map +1 -1
- package/dist/runtime/bindings/applySimple.d.ts.map +1 -1
- package/dist/runtime/bindings/applySimple.js +4 -3
- package/dist/runtime/bindings/applySimple.js.map +1 -1
- package/dist/runtime/bindings/applyStructural.d.ts.map +1 -1
- package/dist/runtime/bindings/applyStructural.js +11 -13
- package/dist/runtime/bindings/applyStructural.js.map +1 -1
- package/dist/runtime/bindings/helpers.d.ts +7 -0
- package/dist/runtime/bindings/helpers.d.ts.map +1 -1
- package/dist/runtime/bindings/helpers.js +33 -1
- package/dist/runtime/bindings/helpers.js.map +1 -1
- package/dist/runtime/html.d.ts.map +1 -1
- package/dist/runtime/html.js +2 -3
- package/dist/runtime/html.js.map +1 -1
- package/dist/types/globals.d.ts +2 -0
- package/dist/types/globals.d.ts.map +1 -1
- package/dist/types/globals.js.map +1 -1
- package/package.json +5 -5
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bindErrorBoundary.js","sourceRoot":"","sources":["../../../src/compile/binds/bindErrorBoundary.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAEF,OAAO,EAAE,MAAM,EAAU,OAAO,EAAE,MAAM,kBAAkB,CAAC;AAE3D,MAAM,aAAa,GAAG,IAAI,OAAO,EAAW,CAAC;AAe7C;;GAEG;AACH,MAAM,gBAAgB,GAAmB,EAAE,CAAC;AAE5C;;GAEG;AACH,IAAI,sBAAsB,GAAwB,IAAI,CAAC;AAiBvD,IAAI,SAAS,GAAqB,IAAI,CAAC;AAEvC;;GAEG;AACH,IAAI,aAAa,GAAG,KAAK,CAAC;AAE1B;;;;GAIG;AACH,qKAAqK;AACrK,MAAM,UAAU,kBAAkB,CAAC,EAAkB;IACnD,MAAM,UAAU,GAAG,EAAE,EAAE,OAAO,CAAC,cAAc,CAAC,CAAC;IAC/C,IAAI,CAAC,UAAU;QAAE,OAAO,SAAS,EAAE,QAAQ,IAAI,IAAI,CAAC;IAEpD,oCAAoC;IACpC,OAAO,CACL,gBAAgB,CAAC,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAC,QAAQ,CAAC,OAAO,KAAK,UAAU,CAAC,IAAI,IAAI,CAC3E,CAAC;AACJ,CAAC;AAED,SAAS,cAAc,CAAC,QAAsB;IAC5C,MAAM,MAAM,GAAG,QAAQ,CAAC,UAAU,CAAC;IACnC,OAAO,MAAM,IAAI,gBAAgB,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC;AACrE,CAAC;AAED;;;;GAIG;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AAG,EAAE,CAAC,aAAa,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC,CAAC;IACzD,CAAC;AACH,CAAC","sourcesContent":["/** @codex\n{\n \"id\": \"pithy.feature.error-boundary\",\n \"title\": \"Error Boundary System\",\n \"category\": \"feature\"\n}\n*/\n\nimport { effect, Signal, untrack } from '@pithyjs/signals';\n\nconst boundElements = new WeakSet<Element>();\n\n/**\n * Represents an active error boundary in the DOM\n */\nexport interface BoundaryInfo {\n element: Element;\n errorSignal: Signal<Error | null>;\n fallbackElement: Element | null;\n contentPlaceholders: Map<Node, Comment>;\n isActive: boolean;\n /** The receiving boundary of the slot this one was rendered in, detached. */\n slotParent?: BoundaryInfo | null;\n}\n\n/**\n * Global registry of active error boundaries\n */\nconst activeBoundaries: BoundaryInfo[] = [];\n\n/**\n * Current boundary context for async error routing (used in later phases)\n */\nlet currentBoundaryContext: BoundaryInfo | null = null;\n\n/** A slot being rendered, detached, so its content cannot `closest()` its boundary. */\ninterface SlotFrame {\n boundary: BoundaryInfo | null;\n anchor: Node;\n /** The component placeholder whose render mounts this slot. */\n host: Element | undefined;\n /** The slot rendering `host`. */\n outer: SlotFrame | null;\n /** Whether `boundary` was resolved here rather than inherited from `outer`. */\n own: boolean;\n /** Whether the slot's nodes land directly in `boundary.element`, when `own`. */\n direct: boolean;\n /** Whether the slot is the boundary's normal content, which its fallback replaces. */\n isContent: boolean;\n}\nlet slotFrame: SlotFrame | null = null;\n\n/**\n * Flag to ensure timer patching happens only once\n */\nlet timersPatched = false;\n\n/**\n * Finds the BoundaryInfo for a given DOM element by traversing up the tree\n * @param el - Element to find boundary for\n * @returns BoundaryInfo if found, null otherwise\n */\n/** @codexApi {\"parent\":\"pithy.feature.error-boundary\",\"name\":\"boundaryForElement\",\"stability\":\"stable\",\"signature\":\"(el: Element | null) => BoundaryInfo | null\"} */\nexport function boundaryForElement(el: Element | null): BoundaryInfo | null {\n const boundaryEl = el?.closest('[data-error]');\n if (!boundaryEl) return slotFrame?.boundary ?? null;\n\n // Find the registered boundary info\n return (\n activeBoundaries.find(boundary => boundary.element === boundaryEl) || null\n );\n}\n\nfunction liveSlotParent(boundary: BoundaryInfo): BoundaryInfo | null {\n const parent = boundary.slotParent;\n return parent && activeBoundaries.includes(parent) ? parent : null;\n}\n\n/**\n * Renders a slot whose receiving `<slot>` sits at `anchor`, mounted by the\n * component placeholder `host`. Its content is detached while it renders, so\n * boundaries are resolved through the anchor.\n */\n/** @codexApi {\"parent\":\"pithy.feature.error-boundary\",\"name\":\"withSlotBoundary\",\"stability\":\"experimental\",\"signature\":\"<T>(anchor: Node | undefined, host: Element | undefined, fn: () => T) => T\"} */\nexport function withSlotBoundary<T>(\n anchor: Node | undefined,\n host: Element | undefined,\n fn: () => T\n): T {\n const outer = slotFrame;\n if (anchor) {\n // An anchor an earlier crash hid has no parent to resolve from.\n const hider = hiderOf(anchor);\n const boundary = hider ?? boundaryForElement(anchor.parentElement);\n slotFrame =\n boundary === outer?.boundary\n ? { ...outer, anchor, host, outer, own: false, direct: false }\n : {\n boundary,\n anchor,\n host,\n outer,\n own: true,\n direct: hider\n ? hider.contentPlaceholders.has(anchor)\n : anchor.parentElement === boundary?.element,\n isContent: !!hider || !boundary?.fallbackElement?.contains(anchor),\n };\n }\n try {\n return fn();\n } finally {\n slotFrame = outer;\n }\n}\n\n/** Whether `el`, in the slot being rendered, is normal content an active fallback has replaced. */\n/** @codexApi {\"parent\":\"pithy.feature.error-boundary\",\"name\":\"slotContentHidden\",\"stability\":\"experimental\",\"signature\":\"(el: Element) => boolean\"} */\nexport function slotContentHidden(el: Element): boolean {\n // Every boundary the slot frames pass through can hide it, not just the nearest.\n const inner = slotFrame;\n let up = 0;\n for (let frame = inner; frame; up++) {\n if (frame.isContent && frame.boundary?.isActive) {\n // As `hideContent`: an active nested boundary stays visible beside the fallback.\n const child = receiverChild(el, inner as SlotFrame, up);\n if (!activeBoundaries.some(b => b.element === child && b.isActive))\n return true;\n }\n while (!frame.own && frame.outer) frame = frame.outer;\n frame = frame.outer;\n }\n return false;\n}\n\n/**\n * The direct child of a boundary element that will hold `node`: the boundary\n * of `frame` when `up` is 0, else that many boundary changes further out.\n */\nfunction receiverChild(node: Node, frame: SlotFrame, up: number): Node | null {\n const top = rootOf(node);\n if (frame.own && up === 0) return frame.direct ? top : null;\n if (!frame.host || !frame.outer) return null;\n const hostChild = receiverChild(\n frame.host,\n frame.outer,\n frame.own ? up - 1 : up\n );\n if (hostChild !== frame.host) return hostChild;\n // The host's output replaces it; a bare slot puts this content in its place.\n // A boundary may have hidden the anchor since: its stand-in holds the place.\n const at = standInOf(frame.anchor) ?? frame.anchor;\n const anchorTop = rootOf(at);\n return anchorTop === at ? top : anchorTop;\n}\n\nfunction standInOf(node: Node): Comment | undefined {\n for (const boundary of activeBoundaries) {\n const standIn = boundary.contentPlaceholders.get(node);\n if (standIn) return standIn;\n }\n return undefined;\n}\n\nfunction rootOf(node: Node): Node {\n let top = node;\n while (\n top.parentNode &&\n top.parentNode.nodeType !== Node.DOCUMENT_FRAGMENT_NODE\n )\n top = top.parentNode;\n return top;\n}\n\nfunction hiderOf(node: Node): BoundaryInfo | undefined {\n let top = node;\n while (top.parentNode) top = top.parentNode;\n return activeBoundaries.find(b => b.contentPlaceholders.has(top));\n}\n\n/** @codexApi {\"parent\":\"pithy.feature.error-boundary\",\"name\":\"isHiddenByBoundary\",\"stability\":\"experimental\",\"signature\":\"(node: Node) => boolean\"} */\nexport function isHiddenByBoundary(node: Node): boolean {\n return activeBoundaries.some(\n b => !!b.contentPlaceholders.get(node)?.parentNode\n );\n}\n\n/**\n * Inserts `content` after `anchor` when an active boundary has hidden the\n * anchor, which a crash during a slot's render can do, and hides it too.\n */\n/** @codexApi {\"parent\":\"pithy.feature.error-boundary\",\"name\":\"insertBesideHidden\",\"stability\":\"experimental\",\"signature\":\"(anchor: Node, content: Node) => boolean\"} */\nexport function insertBesideHidden(anchor: Node, content: Node): boolean {\n for (const boundary of activeBoundaries) {\n const standIn = boundary.contentPlaceholders.get(anchor);\n if (!standIn?.parentNode) continue;\n standIn.parentNode.insertBefore(content, standIn.nextSibling);\n if (boundary.isActive) hideContent(boundary);\n return true;\n }\n return false;\n}\n\n/**\n * Finds the parent boundary for a given boundary (for error escalation)\n * @param childBoundary - The child boundary to find parent for\n * @returns Parent BoundaryInfo if found, null otherwise\n */\nfunction findParentBoundary(childBoundary: BoundaryInfo): BoundaryInfo | null {\n // Start searching from the child boundary's parent element\n const parentEl = childBoundary.element.parentElement;\n if (!parentEl) return liveSlotParent(childBoundary);\n\n // Find the closest ancestor boundary element\n const parentBoundaryEl = parentEl.closest('[data-error]');\n if (!parentBoundaryEl) return liveSlotParent(childBoundary);\n\n // Find the registered boundary info\n return (\n activeBoundaries.find(boundary => boundary.element === parentBoundaryEl) ||\n null\n );\n}\n\n/**\n * Clears the error state of a boundary, restoring normal content\n * @param boundary - The boundary to clear\n */\n/** @codexApi {\"parent\":\"pithy.feature.error-boundary\",\"name\":\"clearBoundaryError\",\"stability\":\"stable\",\"signature\":\"(boundary: BoundaryInfo) => void\"} */\nexport function clearBoundaryError(boundary: BoundaryInfo): void {\n if (untrack(() => boundary.errorSignal()) !== null) {\n boundary.errorSignal.set(null);\n }\n}\n\n/**\n * Sets an error on a boundary with escalation logic\n * If the boundary is already in error state, escalates to parent boundary\n * Matches React behavior: first error wins, subsequent errors ignored\n *\n * @param boundary - The boundary to set error on\n * @param error - The error to set\n * @returns `true` if some boundary took ownership of `error`; `false` if it was\n * dropped because this boundary was already showing an error and no ancestor\n * boundary was free to take it.\n *\n * Callers must not assume the error was handled. A component rendering inside an\n * *active* boundary's `@fallback` hits exactly the `false` path — the fallback is\n * the part the user actually sees, so a crash there that nobody records ships a\n * visibly broken page with a green build. `bindComponentTags` and\n * `applyComponent` use the return value to decide between retracting an SSR\n * crash record and adding one.\n */\n/** @codexApi {\"parent\":\"pithy.feature.error-boundary\",\"name\":\"setBoundaryError\",\"stability\":\"stable\",\"signature\":\"(boundary: BoundaryInfo, error: Error) => boolean\"} */\nexport function setBoundaryError(\n boundary: BoundaryInfo,\n error: Error\n): boolean {\n // Check if this boundary is already in error state\n if (untrack(() => boundary.errorSignal()) !== null) {\n // Escalate to parent boundary\n const parentBoundary = findParentBoundary(boundary);\n if (parentBoundary) {\n return setBoundaryError(parentBoundary, error);\n }\n // IGNORE subsequent errors (React behavior - first error wins).\n // Nobody owns this error now, and the caller needs to know.\n return false;\n }\n\n // Set the error on this boundary\n boundary.errorSignal.set(error);\n return true;\n}\n\n/**\n * Runs a function within the context of a specific boundary\n * Used for scoping async operations to the correct boundary\n * @param boundary - Boundary to run within\n * @param fn - Function to execute\n * @returns Result of function execution\n */\n/** @codexApi {\"parent\":\"pithy.feature.error-boundary\",\"name\":\"runWithBoundary\",\"stability\":\"stable\",\"signature\":\"<T>(boundary: BoundaryInfo | null, fn: () => T) => T\"} */\nexport function runWithBoundary<T>(\n boundary: BoundaryInfo | null,\n fn: () => T\n): T {\n const previousContext = currentBoundaryContext;\n currentBoundaryContext = boundary;\n try {\n return fn();\n } finally {\n currentBoundaryContext = previousContext;\n }\n}\n\nfunction patchTimersOnce(): void {\n if (timersPatched) return;\n timersPatched = true;\n\n // Patch setTimeout\n const originalSetTimeout = window.setTimeout;\n window.setTimeout = ((\n callback: TimerHandler,\n delay?: number,\n ...args: unknown[]\n ) => {\n // Don't wrap string callbacks; let the browser handle them\n if (typeof callback !== 'function') {\n return originalSetTimeout(callback, delay, ...args);\n }\n\n const capturedBoundary = currentBoundaryContext;\n const fn = callback as (...callbackArgs: unknown[]) => unknown;\n const wrappedCallback = (...callbackArgs: unknown[]) => {\n return runWithBoundary(capturedBoundary, () => {\n try {\n return fn(...callbackArgs);\n } catch (error) {\n if (capturedBoundary) {\n const err =\n error instanceof Error ? error : new Error(String(error));\n setBoundaryError(capturedBoundary, err);\n } else {\n throw error;\n }\n }\n });\n };\n return originalSetTimeout(wrappedCallback, delay, ...args);\n }) as typeof window.setTimeout;\n\n // Patch setInterval\n const originalSetInterval = window.setInterval;\n window.setInterval = ((\n callback: TimerHandler,\n delay?: number,\n ...args: unknown[]\n ) => {\n // Don't wrap string callbacks; let the browser handle them\n if (typeof callback !== 'function') {\n return originalSetInterval(callback, delay, ...args);\n }\n\n const capturedBoundary = currentBoundaryContext;\n const fn = callback as (...callbackArgs: unknown[]) => unknown;\n const wrappedCallback = (...callbackArgs: unknown[]) => {\n return runWithBoundary(capturedBoundary, () => {\n try {\n return fn(...callbackArgs);\n } catch (error) {\n if (capturedBoundary) {\n const err =\n error instanceof Error ? error : new Error(String(error));\n setBoundaryError(capturedBoundary, err);\n } else {\n throw error;\n }\n }\n });\n };\n return originalSetInterval(wrappedCallback, delay, ...args);\n }) as typeof window.setInterval;\n}\n\n/**\n * Finds the fallback element within a boundary\n * @param boundaryEl - The boundary element to search within\n * @returns The fallback element or null if not found\n */\nfunction findFallbackElement(boundaryEl: Element): Element | null {\n // Look through direct children first to avoid nested boundary fallbacks\n for (const child of Array.from(boundaryEl.children)) {\n if (child.hasAttribute('data-fallback')) {\n // Double-check that this fallback belongs to this boundary\n const fallbackBoundary = child.closest('[data-error]');\n if (fallbackBoundary === boundaryEl) {\n return child;\n }\n }\n }\n\n // If no direct child fallback found, search deeper but be more careful\n const allFallbacks = Array.from(\n boundaryEl.querySelectorAll('[data-fallback]')\n );\n for (const fallback of allFallbacks) {\n const fallbackBoundary = fallback.closest('[data-error]');\n if (fallbackBoundary === boundaryEl) {\n return fallback;\n }\n }\n\n if (import.meta.env?.DEV) {\n console.warn(\n `[ErrorBoundary] No fallback element found for boundary`,\n boundaryEl.tagName,\n 'Available children:',\n Array.from(boundaryEl.children).map(\n c =>\n c.tagName +\n (c.hasAttribute('data-fallback') ? '[fallback]' : '') +\n (c.hasAttribute('data-error') ? '[boundary]' : '')\n )\n );\n }\n\n return null;\n}\n\n/**\n * Gets current content nodes (excluding fallback) - recomputed each time\n * @param boundaryEl - The boundary element\n * @param fallbackEl - The fallback element to exclude\n * @returns Array of content nodes\n */\nfunction getCurrentContentNodes(\n boundaryEl: Element,\n fallbackEl: Element | null\n): Node[] {\n return Array.from(boundaryEl.childNodes).filter(n => {\n // Exclude the fallback element for this boundary\n if (n === fallbackEl) return false;\n\n // Exclude placeholder comments from other boundaries\n if (\n n.nodeType === Node.COMMENT_NODE &&\n (n as Comment).data === 'pithy-boundary-hidden'\n ) {\n return false;\n }\n\n // Don't hide nested boundary elements that are currently showing their fallback\n if (n.nodeType === Node.ELEMENT_NODE) {\n const element = n as Element;\n if (element.hasAttribute('data-error')) {\n // This is a nested boundary - check if it's currently in error state\n const nestedBoundary = activeBoundaries.find(\n b => b.element === element\n );\n if (nestedBoundary && nestedBoundary.isActive) {\n // If a nested boundary is already active, keep it visible instead of replacing with our fallback\n return false;\n }\n }\n }\n\n return true;\n });\n}\n\n/**\n * Hides content by replacing nodes with comment placeholders\n * @param boundary - The boundary info\n */\nfunction hideContent(boundary: BoundaryInfo): void {\n const { element, fallbackElement, contentPlaceholders } = boundary;\n const nodes = getCurrentContentNodes(element, fallbackElement);\n\n for (const node of nodes) {\n if (contentPlaceholders.has(node)) continue;\n const placeholder = document.createComment('pithy-boundary-hidden');\n node.parentNode?.replaceChild(placeholder, node);\n contentPlaceholders.set(node, placeholder);\n }\n\n // Always show the fallback element if it exists\n if (fallbackElement) {\n (fallbackElement as HTMLElement).style.display = '';\n }\n}\n\n/**\n * Restores content by replacing comment placeholders with original nodes\n * @param boundary - The boundary info\n */\nfunction restoreContent(boundary: BoundaryInfo): void {\n const { fallbackElement, contentPlaceholders } = boundary;\n\n for (const [node, placeholder] of Array.from(contentPlaceholders.entries())) {\n placeholder.parentNode?.replaceChild(node, placeholder);\n contentPlaceholders.delete(node);\n }\n\n if (fallbackElement) {\n (fallbackElement as HTMLElement).style.display = 'none';\n }\n}\n\n/**\n * Hides the fallback element\n * @param fallbackEl - The fallback element to hide\n */\nfunction hideFallback(fallbackEl: Element): void {\n (fallbackEl as HTMLElement).style.display = 'none';\n}\n\n/**\n * Creates and registers an error boundary\n * @param boundaryEl - The boundary element\n * @param errorSignal - The error signal from context\n * @param disposers - Array to add cleanup functions to\n * @returns The created BoundaryInfo\n */\nfunction createBoundary(\n boundaryEl: Element,\n errorSignal: Signal<Error | null>,\n disposers: (() => void)[]\n): BoundaryInfo {\n const fallbackEl = findFallbackElement(boundaryEl);\n\n const boundary: BoundaryInfo = {\n element: boundaryEl,\n errorSignal,\n fallbackElement: fallbackEl,\n contentPlaceholders: new Map(),\n isActive: false,\n slotParent: slotFrame?.boundary ?? null,\n };\n\n // Register BEFORE effect so nested lookups can find us\n activeBoundaries.push(boundary);\n\n // Initially hide fallback\n if (fallbackEl) {\n hideFallback(fallbackEl);\n }\n\n // Set up reactive effect to toggle content/fallback based on error state\n const dispose = effect(() => {\n const error = errorSignal();\n const hasError = error !== null;\n\n if (hasError && !boundary.isActive) {\n // Show error state\n boundary.isActive = true;\n hideContent(boundary);\n } else if (!hasError && boundary.isActive) {\n // Show normal state\n boundary.isActive = false;\n restoreContent(boundary);\n }\n });\n\n // Add cleanup function\n disposers.push(() => {\n dispose();\n\n // Restore any hidden content\n if (boundary.isActive) {\n restoreContent(boundary);\n }\n\n // Remove from registry\n const index = activeBoundaries.indexOf(boundary);\n if (index >= 0) {\n activeBoundaries.splice(index, 1);\n }\n });\n\n return boundary;\n}\n\n/**\n * Register a single element as an error boundary.\n * Used by AOT applyBindings where the boundary element is known directly\n * (unlike bindErrorBoundary which scans children via querySelectorAll).\n *\n * @param boundaryEl - The element with data-error attribute\n * @param context - Reactive context containing error signals\n * @param disposers - Array to add cleanup functions to\n */\n/** @codexApi {\"parent\":\"pithy.feature.error-boundary\",\"name\":\"registerBoundary\",\"stability\":\"stable\",\"signature\":\"(boundaryEl: Element, context: Record<string, unknown>, disposers: (() => void)[]) => void\"} */\nexport function registerBoundary(\n boundaryEl: Element,\n context: Record<string, unknown>,\n disposers: (() => void)[]\n): void {\n patchTimersOnce();\n\n const signalName = boundaryEl.getAttribute('data-error');\n if (!signalName) return;\n\n const errorSignal = context[signalName] as Signal<Error | null> | undefined;\n if (!errorSignal || typeof errorSignal !== 'function') {\n if (import.meta.env?.DEV) {\n console.warn(\n `[ErrorBoundary] Signal \"${signalName}\" not found in context for boundary ${boundaryEl.tagName}`\n );\n }\n return;\n }\n\n // Validate that the signal is writable — computed signals or non-signal\n // functions will throw at runtime when setBoundaryError calls .set()\n if (typeof errorSignal.set !== 'function') {\n if (import.meta.env?.DEV) {\n console.warn(\n `[ErrorBoundary] Signal \"${signalName}\" is not writable (no .set method) for boundary ${boundaryEl.tagName}`\n );\n }\n return;\n }\n\n createBoundary(boundaryEl, errorSignal, disposers);\n}\n\n/**\n * Binds error boundaries in the DOM fragment\n * Scans for [data-error] elements and sets up error boundary behavior\n *\n * @param fragment - DOM fragment to scan\n * @param context - Reactive context containing error signals\n * @param disposers - Array to add cleanup functions to\n */\n/** @codexApi {\"parent\":\"pithy.feature.error-boundary\",\"name\":\"bindErrorBoundary\",\"stability\":\"stable\",\"signature\":\"(fragment: Element | DocumentFragment, context: Record<string, unknown>, disposers: (() => void)[]) => void\"} */\nexport function bindErrorBoundary(\n fragment: Element | DocumentFragment,\n context: Record<string, unknown>,\n disposers: (() => void)[]\n): void {\n // Patch timers on first boundary registration\n patchTimersOnce();\n\n const boundaryElements = Array.from(\n fragment.querySelectorAll('[data-error]')\n );\n\n for (const boundaryEl of boundaryElements) {\n if (boundElements.has(boundaryEl)) continue;\n const signalName = boundaryEl.getAttribute('data-error');\n if (!signalName) continue;\n\n const errorSignal = context[signalName] as Signal<Error | null> | undefined;\n if (!errorSignal || typeof errorSignal !== 'function') {\n if (import.meta.env?.DEV) {\n console.warn(\n `[ErrorBoundary] Signal \"${signalName}\" not found in context for boundary ${boundaryEl.tagName}`\n );\n }\n continue;\n }\n\n // Validate that the signal is writable — computed signals or non-signal\n // functions will throw at runtime when setBoundaryError calls .set()\n if (typeof errorSignal.set !== 'function') {\n if (import.meta.env?.DEV) {\n console.warn(\n `[ErrorBoundary] Signal \"${signalName}\" is not writable (no .set method) for boundary ${boundaryEl.tagName}`\n );\n }\n continue;\n }\n\n // Create and register the boundary (registration happens inside createBoundary)\n createBoundary(boundaryEl, errorSignal, disposers);\n boundElements.add(boundaryEl);\n disposers.push(() => boundElements.delete(boundaryEl));\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"bindErrorBoundary.js","sourceRoot":"","sources":["../../../src/compile/binds/bindErrorBoundary.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAEF,OAAO,EAAE,MAAM,EAAU,OAAO,EAAE,MAAM,kBAAkB,CAAC;AAE3D,MAAM,aAAa,GAAG,IAAI,OAAO,EAAW,CAAC;AAe7C;;GAEG;AACH,MAAM,gBAAgB,GAAmB,EAAE,CAAC;AAE5C;;GAEG;AACH,IAAI,sBAAsB,GAAwB,IAAI,CAAC;AAiBvD,IAAI,SAAS,GAAqB,IAAI,CAAC;AAEvC;;GAEG;AACH,IAAI,aAAa,GAAG,KAAK,CAAC;AAE1B;;;;GAIG;AACH,qKAAqK;AACrK,MAAM,UAAU,kBAAkB,CAAC,EAAkB;IACnD,MAAM,UAAU,GAAG,EAAE,EAAE,OAAO,CAAC,cAAc,CAAC,CAAC;IAC/C,IAAI,CAAC,UAAU;QAAE,OAAO,SAAS,EAAE,QAAQ,IAAI,IAAI,CAAC;IAEpD,oCAAoC;IACpC,OAAO,CACL,gBAAgB,CAAC,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAC,QAAQ,CAAC,OAAO,KAAK,UAAU,CAAC,IAAI,IAAI,CAC3E,CAAC;AACJ,CAAC;AAED,SAAS,cAAc,CAAC,QAAsB;IAC5C,MAAM,MAAM,GAAG,QAAQ,CAAC,UAAU,CAAC;IACnC,OAAO,MAAM,IAAI,gBAAgB,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC;AACrE,CAAC;AAED;;;;;GAKG;AACH,wMAAwM;AACxM,MAAM,UA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AAI,CACjC,QAAQ,CAAC,gBAAgB,CAAC,cAAc,CAAC,CAC1C,CAAC;IAEF,KAAK,MAAM,UAAU,IAAI,gBAAgB,EAAE,CAAC;QAC1C,IAAI,aAAa,CAAC,GAAG,CAAC,UAAU,CAAC;YAAE,SAAS;QAC5C,MAAM,UAAU,GAAG,UAAU,CAAC,YAAY,CAAC,YAAY,CAAC,CAAC;QACzD,IAAI,CAAC,UAAU;YAAE,SAAS;QAE1B,MAAM,WAAW,GAAG,OAAO,CAAC,UAAU,CAAqC,CAAC;QAC5E,IAAI,CAAC,WAAW,IAAI,OAAO,WAAW,KAAK,UAAU,EAAE,CAAC;YACtD,IAAI,MAAM,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,EAAE,CAAC;gBACzB,OAAO,CAAC,IAAI,CACV,2BAA2B,UAAU,uCAAuC,UAAU,CAAC,OAAO,EAAE,CACjG,CAAC;YACJ,CAAC;YACD,SAAS;QACX,CAAC;QAED,wEAAwE;QACxE,qEAAqE;QACrE,IAAI,OAAO,WAAW,CAAC,GAAG,KAAK,UAAU,EAAE,CAAC;YAC1C,IAAI,MAAM,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,EAAE,CAAC;gBACzB,OAAO,CAAC,IAAI,CACV,2BAA2B,UAAU,mDAAmD,UAAU,CAAC,OAAO,EAAE,CAC7G,CAAC;YACJ,CAAC;YACD,SAAS;QACX,CAAC;QAED,gFAAgF;QAChF,cAAc,CAAC,UAAU,EAAE,WAAW,EAAE,SAAS,CAAC,CAAC;QACnD,aAAa,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC;QAC9B,SAAS,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,aAAa,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC,CAAC;IACzD,CAAC;AACH,CAAC","sourcesContent":["/** @codex\n{\n \"id\": \"pithy.feature.error-boundary\",\n \"title\": \"Error Boundary System\",\n \"category\": \"feature\"\n}\n*/\n\nimport { effect, Signal, untrack } from '@pithyjs/signals';\n\nconst boundElements = new WeakSet<Element>();\n\n/**\n * Represents an active error boundary in the DOM\n */\nexport interface BoundaryInfo {\n element: Element;\n errorSignal: Signal<Error | null>;\n fallbackElement: Element | null;\n contentPlaceholders: Map<Node, Comment>;\n isActive: boolean;\n /** The receiving boundary of the slot this one was rendered in, detached. */\n slotParent?: BoundaryInfo | null;\n}\n\n/**\n * Global registry of active error boundaries\n */\nconst activeBoundaries: BoundaryInfo[] = [];\n\n/**\n * Current boundary context for async error routing (used in later phases)\n */\nlet currentBoundaryContext: BoundaryInfo | null = null;\n\n/** A slot being rendered, detached, so its content cannot `closest()` its boundary. */\ninterface SlotFrame {\n boundary: BoundaryInfo | null;\n anchor: Node;\n /** The component placeholder whose render mounts this slot. */\n host: Element | undefined;\n /** The slot rendering `host`. */\n outer: SlotFrame | null;\n /** Whether `boundary` was resolved here rather than inherited from `outer`. */\n own: boolean;\n /** Whether the slot's nodes land directly in `boundary.element`, when `own`. */\n direct: boolean;\n /** Whether the slot is the boundary's normal content, which its fallback replaces. */\n isContent: boolean;\n}\nlet slotFrame: SlotFrame | null = null;\n\n/**\n * Flag to ensure timer patching happens only once\n */\nlet timersPatched = false;\n\n/**\n * Finds the BoundaryInfo for a given DOM element by traversing up the tree\n * @param el - Element to find boundary for\n * @returns BoundaryInfo if found, null otherwise\n */\n/** @codexApi {\"parent\":\"pithy.feature.error-boundary\",\"name\":\"boundaryForElement\",\"stability\":\"stable\",\"signature\":\"(el: Element | null) => BoundaryInfo | null\"} */\nexport function boundaryForElement(el: Element | null): BoundaryInfo | null {\n const boundaryEl = el?.closest('[data-error]');\n if (!boundaryEl) return slotFrame?.boundary ?? null;\n\n // Find the registered boundary info\n return (\n activeBoundaries.find(boundary => boundary.element === boundaryEl) || null\n );\n}\n\nfunction liveSlotParent(boundary: BoundaryInfo): BoundaryInfo | null {\n const parent = boundary.slotParent;\n return parent && activeBoundaries.includes(parent) ? parent : null;\n}\n\n/**\n * Renders a slot whose receiving `<slot>` sits at `anchor`, mounted by the\n * component placeholder `host`. Its content is detached while it renders, so\n * boundaries are resolved through the anchor, then the host's render. Without an\n * anchor (`renderChildren()`), the host is the frame's anchor.\n */\n/** @codexApi {\"parent\":\"pithy.feature.error-boundary\",\"name\":\"withSlotBoundary\",\"stability\":\"experimental\",\"signature\":\"<T>(anchor: Node | undefined, host: Element | undefined, fn: () => T) => T\"} */\nexport function withSlotBoundary<T>(\n anchor: Node | undefined,\n host: Element | undefined,\n fn: () => T\n): T {\n const outer = slotFrame;\n const at = anchor ?? host;\n if (at) {\n // An anchor an earlier crash hid has no parent to resolve from.\n const hider = hiderOf(at);\n const boundary =\n hider ??\n registeredClosest(anchor?.parentElement) ??\n outer?.boundary ??\n currentBoundaryContext;\n slotFrame =\n boundary === outer?.boundary\n ? { ...outer, anchor: at, host, outer, own: false, direct: false }\n : {\n boundary,\n anchor: at,\n host,\n outer,\n own: true,\n direct: hider\n ? hider.contentPlaceholders.has(at)\n : (anchor ?? host)?.parentElement === boundary?.element,\n isContent: !!hider || !boundary?.fallbackElement?.contains(at),\n };\n }\n try {\n return fn();\n } finally {\n slotFrame = outer;\n }\n}\n\n/** The registered boundary of `el`'s nearest `[data-error]`, ignoring slot frames. */\nfunction registeredClosest(\n el: Element | null | undefined\n): BoundaryInfo | null {\n const boundaryEl = el?.closest('[data-error]');\n return (\n (boundaryEl && activeBoundaries.find(b => b.element === boundaryEl)) || null\n );\n}\n\n/** Whether `el`, in the slot being rendered, is normal content an active fallback has replaced. */\n/** @codexApi {\"parent\":\"pithy.feature.error-boundary\",\"name\":\"slotContentHidden\",\"stability\":\"experimental\",\"signature\":\"(el: Element) => boolean\"} */\nexport function slotContentHidden(el: Element): boolean {\n // Every boundary the slot frames pass through can hide it, not just the nearest.\n const inner = slotFrame;\n let up = 0;\n for (let frame = inner; frame; up++) {\n if (frame.isContent && frame.boundary?.isActive) {\n // As `hideContent`: an active nested boundary stays visible beside the fallback.\n const child = receiverChild(el, inner as SlotFrame, up);\n if (!activeBoundaries.some(b => b.element === child && b.isActive))\n return true;\n }\n while (!frame.own && frame.outer) frame = frame.outer;\n frame = frame.outer;\n }\n return false;\n}\n\n/**\n * The direct child of a boundary element that will hold `node`: the boundary\n * of `frame` when `up` is 0, else that many boundary changes further out.\n */\nfunction receiverChild(node: Node, frame: SlotFrame, up: number): Node | null {\n const top = rootOf(node);\n if (frame.own && up === 0) return frame.direct ? top : null;\n if (!frame.host || !frame.outer) return null;\n const hostChild = receiverChild(\n frame.host,\n frame.outer,\n frame.own ? up - 1 : up\n );\n if (hostChild !== frame.host) return hostChild;\n // The host's output replaces it; a bare slot puts this content in its place.\n // Anchorless (`renderChildren()`), the host is the anchor: whether it wraps its\n // children is unknown while they render, so they count as unwrapped.\n // A boundary may have hidden the anchor since: its stand-in holds the place.\n const at = standInOf(frame.anchor) ?? frame.anchor;\n const anchorTop = rootOf(at);\n return anchorTop === at ? top : anchorTop;\n}\n\nfunction standInOf(node: Node): Comment | undefined {\n for (const boundary of activeBoundaries) {\n const standIn = boundary.contentPlaceholders.get(node);\n if (standIn) return standIn;\n }\n return undefined;\n}\n\nfunction rootOf(node: Node): Node {\n let top = node;\n while (\n top.parentNode &&\n top.parentNode.nodeType !== Node.DOCUMENT_FRAGMENT_NODE\n )\n top = top.parentNode;\n return top;\n}\n\nfunction hiderOf(node: Node): BoundaryInfo | undefined {\n let top = node;\n while (top.parentNode) top = top.parentNode;\n return activeBoundaries.find(b => b.contentPlaceholders.has(top));\n}\n\n/** @codexApi {\"parent\":\"pithy.feature.error-boundary\",\"name\":\"isHiddenByBoundary\",\"stability\":\"experimental\",\"signature\":\"(node: Node) => boolean\"} */\nexport function isHiddenByBoundary(node: Node): boolean {\n return activeBoundaries.some(\n b => !!b.contentPlaceholders.get(node)?.parentNode\n );\n}\n\n/**\n * Inserts `content` after `anchor` when an active boundary has hidden the\n * anchor, which a crash during a slot's render can do, and hides it too.\n */\n/** @codexApi {\"parent\":\"pithy.feature.error-boundary\",\"name\":\"insertBesideHidden\",\"stability\":\"experimental\",\"signature\":\"(anchor: Node, content: Node) => boolean\"} */\nexport function insertBesideHidden(anchor: Node, content: Node): boolean {\n for (const boundary of activeBoundaries) {\n const standIn = boundary.contentPlaceholders.get(anchor);\n if (!standIn?.parentNode) continue;\n standIn.parentNode.insertBefore(content, standIn.nextSibling);\n if (boundary.isActive) hideContent(boundary);\n return true;\n }\n return false;\n}\n\n/**\n * Puts `content` in the place of `node` when an active boundary has hidden it,\n * which a crash during `node`'s own render can do, and hides it there instead.\n */\n/** @codexApi {\"parent\":\"pithy.feature.error-boundary\",\"name\":\"replaceHidden\",\"stability\":\"experimental\",\"signature\":\"(node: Node, content: Node[]) => boolean\"} */\nexport function replaceHidden(node: Node, content: Node[]): boolean {\n for (const boundary of activeBoundaries) {\n const standIn = boundary.contentPlaceholders.get(node);\n if (!standIn?.parentNode) continue;\n boundary.contentPlaceholders.delete(node);\n standIn.replaceWith(...content);\n if (boundary.isActive) hideContent(boundary);\n return true;\n }\n return false;\n}\n\n/**\n * Finds the parent boundary for a given boundary (for error escalation)\n * @param childBoundary - The child boundary to find parent for\n * @returns Parent BoundaryInfo if found, null otherwise\n */\nfunction findParentBoundary(childBoundary: BoundaryInfo): BoundaryInfo | null {\n // Start searching from the child boundary's parent element\n const parentEl = childBoundary.element.parentElement;\n if (!parentEl) return liveSlotParent(childBoundary);\n\n // Find the closest ancestor boundary element\n const parentBoundaryEl = parentEl.closest('[data-error]');\n if (!parentBoundaryEl) return liveSlotParent(childBoundary);\n\n // Find the registered boundary info\n return (\n activeBoundaries.find(boundary => boundary.element === parentBoundaryEl) ||\n null\n );\n}\n\n/**\n * Clears the error state of a boundary, restoring normal content\n * @param boundary - The boundary to clear\n */\n/** @codexApi {\"parent\":\"pithy.feature.error-boundary\",\"name\":\"clearBoundaryError\",\"stability\":\"stable\",\"signature\":\"(boundary: BoundaryInfo) => void\"} */\nexport function clearBoundaryError(boundary: BoundaryInfo): void {\n if (untrack(() => boundary.errorSignal()) !== null) {\n boundary.errorSignal.set(null);\n }\n}\n\n/**\n * Sets an error on a boundary with escalation logic\n * If the boundary is already in error state, escalates to parent boundary\n * Matches React behavior: first error wins, subsequent errors ignored\n *\n * @param boundary - The boundary to set error on\n * @param error - The error to set\n * @returns `true` if some boundary took ownership of `error`; `false` if it was\n * dropped because this boundary was already showing an error and no ancestor\n * boundary was free to take it.\n *\n * Callers must not assume the error was handled. A component rendering inside an\n * *active* boundary's `@fallback` hits exactly the `false` path — the fallback is\n * the part the user actually sees, so a crash there that nobody records ships a\n * visibly broken page with a green build. `bindComponentTags` and\n * `applyComponent` use the return value to decide between retracting an SSR\n * crash record and adding one.\n */\n/** @codexApi {\"parent\":\"pithy.feature.error-boundary\",\"name\":\"setBoundaryError\",\"stability\":\"stable\",\"signature\":\"(boundary: BoundaryInfo, error: Error) => boolean\"} */\nexport function setBoundaryError(\n boundary: BoundaryInfo,\n error: Error\n): boolean {\n // Check if this boundary is already in error state\n if (untrack(() => boundary.errorSignal()) !== null) {\n // Escalate to parent boundary\n const parentBoundary = findParentBoundary(boundary);\n if (parentBoundary) {\n return setBoundaryError(parentBoundary, error);\n }\n // IGNORE subsequent errors (React behavior - first error wins).\n // Nobody owns this error now, and the caller needs to know.\n return false;\n }\n\n // Set the error on this boundary\n boundary.errorSignal.set(error);\n return true;\n}\n\n/** The boundary the component being rendered sits under. */\n/** @codexApi {\"parent\":\"pithy.feature.error-boundary\",\"name\":\"currentBoundary\",\"stability\":\"experimental\",\"signature\":\"() => BoundaryInfo | null\"} */\nexport function currentBoundary(): BoundaryInfo | null {\n return currentBoundaryContext;\n}\n\n/**\n * Runs a function within the context of a specific boundary\n * Used for scoping async operations to the correct boundary\n * @param boundary - Boundary to run within\n * @param fn - Function to execute\n * @returns Result of function execution\n */\n/** @codexApi {\"parent\":\"pithy.feature.error-boundary\",\"name\":\"runWithBoundary\",\"stability\":\"stable\",\"signature\":\"<T>(boundary: BoundaryInfo | null, fn: () => T) => T\"} */\nexport function runWithBoundary<T>(\n boundary: BoundaryInfo | null,\n fn: () => T\n): T {\n const previousContext = currentBoundaryContext;\n currentBoundaryContext = boundary;\n try {\n return fn();\n } finally {\n currentBoundaryContext = previousContext;\n }\n}\n\nfunction patchTimersOnce(): void {\n if (timersPatched) return;\n timersPatched = true;\n\n // Patch setTimeout\n const originalSetTimeout = window.setTimeout;\n window.setTimeout = ((\n callback: TimerHandler,\n delay?: number,\n ...args: unknown[]\n ) => {\n // Don't wrap string callbacks; let the browser handle them\n if (typeof callback !== 'function') {\n return originalSetTimeout(callback, delay, ...args);\n }\n\n const capturedBoundary = currentBoundaryContext;\n const fn = callback as (...callbackArgs: unknown[]) => unknown;\n const wrappedCallback = (...callbackArgs: unknown[]) => {\n return runWithBoundary(capturedBoundary, () => {\n try {\n return fn(...callbackArgs);\n } catch (error) {\n if (capturedBoundary) {\n const err =\n error instanceof Error ? error : new Error(String(error));\n setBoundaryError(capturedBoundary, err);\n } else {\n throw error;\n }\n }\n });\n };\n return originalSetTimeout(wrappedCallback, delay, ...args);\n }) as typeof window.setTimeout;\n\n // Patch setInterval\n const originalSetInterval = window.setInterval;\n window.setInterval = ((\n callback: TimerHandler,\n delay?: number,\n ...args: unknown[]\n ) => {\n // Don't wrap string callbacks; let the browser handle them\n if (typeof callback !== 'function') {\n return originalSetInterval(callback, delay, ...args);\n }\n\n const capturedBoundary = currentBoundaryContext;\n const fn = callback as (...callbackArgs: unknown[]) => unknown;\n const wrappedCallback = (...callbackArgs: unknown[]) => {\n return runWithBoundary(capturedBoundary, () => {\n try {\n return fn(...callbackArgs);\n } catch (error) {\n if (capturedBoundary) {\n const err =\n error instanceof Error ? error : new Error(String(error));\n setBoundaryError(capturedBoundary, err);\n } else {\n throw error;\n }\n }\n });\n };\n return originalSetInterval(wrappedCallback, delay, ...args);\n }) as typeof window.setInterval;\n}\n\n/**\n * Finds the fallback element within a boundary\n * @param boundaryEl - The boundary element to search within\n * @returns The fallback element or null if not found\n */\nfunction findFallbackElement(boundaryEl: Element): Element | null {\n // Look through direct children first to avoid nested boundary fallbacks\n for (const child of Array.from(boundaryEl.children)) {\n if (child.hasAttribute('data-fallback')) {\n // Double-check that this fallback belongs to this boundary\n const fallbackBoundary = child.closest('[data-error]');\n if (fallbackBoundary === boundaryEl) {\n return child;\n }\n }\n }\n\n // If no direct child fallback found, search deeper but be more careful\n const allFallbacks = Array.from(\n boundaryEl.querySelectorAll('[data-fallback]')\n );\n for (const fallback of allFallbacks) {\n const fallbackBoundary = fallback.closest('[data-error]');\n if (fallbackBoundary === boundaryEl) {\n return fallback;\n }\n }\n\n if (import.meta.env?.DEV) {\n console.warn(\n `[ErrorBoundary] No fallback element found for boundary`,\n boundaryEl.tagName,\n 'Available children:',\n Array.from(boundaryEl.children).map(\n c =>\n c.tagName +\n (c.hasAttribute('data-fallback') ? '[fallback]' : '') +\n (c.hasAttribute('data-error') ? '[boundary]' : '')\n )\n );\n }\n\n return null;\n}\n\n/**\n * Gets current content nodes (excluding fallback) - recomputed each time\n * @param boundaryEl - The boundary element\n * @param fallbackEl - The fallback element to exclude\n * @returns Array of content nodes\n */\nfunction getCurrentContentNodes(\n boundaryEl: Element,\n fallbackEl: Element | null\n): Node[] {\n return Array.from(boundaryEl.childNodes).filter(n => {\n // Exclude the fallback element for this boundary\n if (n === fallbackEl) return false;\n\n // Exclude placeholder comments from other boundaries\n if (\n n.nodeType === Node.COMMENT_NODE &&\n (n as Comment).data === 'pithy-boundary-hidden'\n ) {\n return false;\n }\n\n // Don't hide nested boundary elements that are currently showing their fallback\n if (n.nodeType === Node.ELEMENT_NODE) {\n const element = n as Element;\n if (element.hasAttribute('data-error')) {\n // This is a nested boundary - check if it's currently in error state\n const nestedBoundary = activeBoundaries.find(\n b => b.element === element\n );\n if (nestedBoundary && nestedBoundary.isActive) {\n // If a nested boundary is already active, keep it visible instead of replacing with our fallback\n return false;\n }\n }\n }\n\n return true;\n });\n}\n\n/**\n * Hides content by replacing nodes with comment placeholders\n * @param boundary - The boundary info\n */\nfunction hideContent(boundary: BoundaryInfo): void {\n const { element, fallbackElement, contentPlaceholders } = boundary;\n const nodes = getCurrentContentNodes(element, fallbackElement);\n\n for (const node of nodes) {\n if (contentPlaceholders.has(node)) continue;\n const placeholder = document.createComment('pithy-boundary-hidden');\n node.parentNode?.replaceChild(placeholder, node);\n contentPlaceholders.set(node, placeholder);\n }\n\n // Always show the fallback element if it exists\n if (fallbackElement) {\n (fallbackElement as HTMLElement).style.display = '';\n }\n}\n\n/**\n * Restores content by replacing comment placeholders with original nodes\n * @param boundary - The boundary info\n */\nfunction restoreContent(boundary: BoundaryInfo): void {\n const { fallbackElement, contentPlaceholders } = boundary;\n\n for (const [node, placeholder] of Array.from(contentPlaceholders.entries())) {\n placeholder.parentNode?.replaceChild(node, placeholder);\n contentPlaceholders.delete(node);\n }\n\n if (fallbackElement) {\n (fallbackElement as HTMLElement).style.display = 'none';\n }\n}\n\n/**\n * Hides the fallback element\n * @param fallbackEl - The fallback element to hide\n */\nfunction hideFallback(fallbackEl: Element): void {\n (fallbackEl as HTMLElement).style.display = 'none';\n}\n\n/**\n * Creates and registers an error boundary\n * @param boundaryEl - The boundary element\n * @param errorSignal - The error signal from context\n * @param disposers - Array to add cleanup functions to\n * @returns The created BoundaryInfo\n */\nfunction createBoundary(\n boundaryEl: Element,\n errorSignal: Signal<Error | null>,\n disposers: (() => void)[]\n): BoundaryInfo {\n const fallbackEl = findFallbackElement(boundaryEl);\n\n const boundary: BoundaryInfo = {\n element: boundaryEl,\n errorSignal,\n fallbackElement: fallbackEl,\n contentPlaceholders: new Map(),\n isActive: false,\n slotParent: slotFrame?.boundary ?? null,\n };\n\n // Register BEFORE effect so nested lookups can find us\n activeBoundaries.push(boundary);\n\n // Initially hide fallback\n if (fallbackEl) {\n hideFallback(fallbackEl);\n }\n\n // Set up reactive effect to toggle content/fallback based on error state\n const dispose = effect(() => {\n const error = errorSignal();\n const hasError = error !== null;\n\n if (hasError && !boundary.isActive) {\n // Show error state\n boundary.isActive = true;\n hideContent(boundary);\n } else if (!hasError && boundary.isActive) {\n // Show normal state\n boundary.isActive = false;\n restoreContent(boundary);\n }\n });\n\n // Add cleanup function\n disposers.push(() => {\n dispose();\n\n // Restore any hidden content\n if (boundary.isActive) {\n restoreContent(boundary);\n }\n\n // Remove from registry\n const index = activeBoundaries.indexOf(boundary);\n if (index >= 0) {\n activeBoundaries.splice(index, 1);\n }\n });\n\n return boundary;\n}\n\n/**\n * Register a single element as an error boundary.\n * Used by AOT applyBindings where the boundary element is known directly\n * (unlike bindErrorBoundary which scans children via querySelectorAll).\n *\n * @param boundaryEl - The element with data-error attribute\n * @param context - Reactive context containing error signals\n * @param disposers - Array to add cleanup functions to\n */\n/** @codexApi {\"parent\":\"pithy.feature.error-boundary\",\"name\":\"registerBoundary\",\"stability\":\"stable\",\"signature\":\"(boundaryEl: Element, context: Record<string, unknown>, disposers: (() => void)[]) => void\"} */\nexport function registerBoundary(\n boundaryEl: Element,\n context: Record<string, unknown>,\n disposers: (() => void)[]\n): void {\n patchTimersOnce();\n\n const signalName = boundaryEl.getAttribute('data-error');\n if (!signalName) return;\n\n const errorSignal = context[signalName] as Signal<Error | null> | undefined;\n if (!errorSignal || typeof errorSignal !== 'function') {\n if (import.meta.env?.DEV) {\n console.warn(\n `[ErrorBoundary] Signal \"${signalName}\" not found in context for boundary ${boundaryEl.tagName}`\n );\n }\n return;\n }\n\n // Validate that the signal is writable — computed signals or non-signal\n // functions will throw at runtime when setBoundaryError calls .set()\n if (typeof errorSignal.set !== 'function') {\n if (import.meta.env?.DEV) {\n console.warn(\n `[ErrorBoundary] Signal \"${signalName}\" is not writable (no .set method) for boundary ${boundaryEl.tagName}`\n );\n }\n return;\n }\n\n createBoundary(boundaryEl, errorSignal, disposers);\n}\n\n/**\n * Binds error boundaries in the DOM fragment\n * Scans for [data-error] elements and sets up error boundary behavior\n *\n * @param fragment - DOM fragment to scan\n * @param context - Reactive context containing error signals\n * @param disposers - Array to add cleanup functions to\n */\n/** @codexApi {\"parent\":\"pithy.feature.error-boundary\",\"name\":\"bindErrorBoundary\",\"stability\":\"stable\",\"signature\":\"(fragment: Element | DocumentFragment, context: Record<string, unknown>, disposers: (() => void)[]) => void\"} */\nexport function bindErrorBoundary(\n fragment: Element | DocumentFragment,\n context: Record<string, unknown>,\n disposers: (() => void)[]\n): void {\n // Patch timers on first boundary registration\n patchTimersOnce();\n\n const boundaryElements = Array.from(\n fragment.querySelectorAll('[data-error]')\n );\n\n for (const boundaryEl of boundaryElements) {\n if (boundElements.has(boundaryEl)) continue;\n const signalName = boundaryEl.getAttribute('data-error');\n if (!signalName) continue;\n\n const errorSignal = context[signalName] as Signal<Error | null> | undefined;\n if (!errorSignal || typeof errorSignal !== 'function') {\n if (import.meta.env?.DEV) {\n console.warn(\n `[ErrorBoundary] Signal \"${signalName}\" not found in context for boundary ${boundaryEl.tagName}`\n );\n }\n continue;\n }\n\n // Validate that the signal is writable — computed signals or non-signal\n // functions will throw at runtime when setBoundaryError calls .set()\n if (typeof errorSignal.set !== 'function') {\n if (import.meta.env?.DEV) {\n console.warn(\n `[ErrorBoundary] Signal \"${signalName}\" is not writable (no .set method) for boundary ${boundaryEl.tagName}`\n );\n }\n continue;\n }\n\n // Create and register the boundary (registration happens inside createBoundary)\n createBoundary(boundaryEl, errorSignal, disposers);\n boundElements.add(boundaryEl);\n disposers.push(() => boundElements.delete(boundaryEl));\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"compileNodes.d.ts","sourceRoot":"","sources":["../../src/compile/compileNodes.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAEF,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;
|
|
1
|
+
{"version":3,"file":"compileNodes.d.ts","sourceRoot":"","sources":["../../src/compile/compileNodes.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAEF,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;AASnD;;;;;;;;;;;;;;;;;GAiBG;AACH,0NAA0N;AAC1N,wBAAgB,YAAY,CAC1B,KAAK,EAAE,SAAS,EAAE,EAClB,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAC/B;IAAE,EAAE,EAAE,gBAAgB,CAAC;IAAC,OAAO,EAAE,MAAM,IAAI,CAAA;CAAE,CA4E/C"}
|
|
@@ -8,6 +8,7 @@
|
|
|
8
8
|
import { pithyTreeToDom } from './pithyTreeToDom.js';
|
|
9
9
|
import { bindStructuralDirectives, bindTemplateDirectives, } from './compileTemplate.js';
|
|
10
10
|
import { drainDestroyCallbacks } from '../runtime/onDestroy.js';
|
|
11
|
+
import { orderByDocument } from './disposeOrder.js';
|
|
11
12
|
/**
|
|
12
13
|
* Compiles an array of PithyNode AST nodes into live DOM with full binding pipeline.
|
|
13
14
|
*
|
|
@@ -40,6 +41,7 @@ export function compileNodes(nodes, context) {
|
|
|
40
41
|
bindStructuralDirectives(nodes, fragment, context, disposers);
|
|
41
42
|
// 3. Non-structural bindings (refs, error boundaries, components, text, events, etc.)
|
|
42
43
|
bindTemplateDirectives(fragment, context, disposers);
|
|
44
|
+
orderByDocument(disposers);
|
|
43
45
|
}
|
|
44
46
|
catch (err) {
|
|
45
47
|
// Clean up any disposers already registered during partial compilation
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"compileNodes.js","sourceRoot":"","sources":["../../src/compile/compileNodes.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAGF,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAClD,OAAO,EACL,wBAAwB,EACxB,sBAAsB,GACvB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,qBAAqB,EAAE,MAAM,sBAAsB,CAAC;
|
|
1
|
+
{"version":3,"file":"compileNodes.js","sourceRoot":"","sources":["../../src/compile/compileNodes.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAGF,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,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odes\",\n \"title\": \"AST Node Compiler\",\n \"category\": \"runtime\"\n}\n*/\n\nimport type { PithyNode } from '@pithyjs/compiler';\nimport { pithyTreeToDom } from './pithyTreeToDom';\nimport {\n bindStructuralDirectives,\n bindTemplateDirectives,\n} from './compileTemplate';\nimport { drainDestroyCallbacks } from '../runtime/onDestroy';\nimport { orderByDocument } from './disposeOrder';\n\n/**\n * Compiles an array of PithyNode AST nodes into live DOM with full binding pipeline.\n *\n * This is the AST counterpart to `compileTemplate`:\n * - `compileTemplate`: HTML string → parse → AST → DOM → structural → non-structural\n * - `compileNodes`: AST → DOM → structural → non-structural\n *\n * Use when you already have AST nodes (e.g. from `__childAstNodes` in component context)\n * and need the full compilation pipeline including structural directives (@if, @switch, @for).\n *\n * @example\n * ```ts\n * import { compileNodes } from \"@pithyjs/core\";\n * const { el, destroy } = compileNodes(astNodes, context);\n * document.body.appendChild(el);\n * // later: destroy();\n * ```\n */\n/** @codexApi {\"parent\":\"pithy.runtime.compile-nodes\",\"name\":\"compileNodes\",\"stability\":\"stable\",\"signature\":\"(nodes: PithyNode[], context: Record<string, unknown>) => { el: DocumentFragment; destroy: () => void }\"} */\nexport function compileNodes(\n nodes: PithyNode[],\n context: Record<string, unknown>\n): { el: DocumentFragment; destroy: () => void } {\n // Drain onDestroy() callbacks — prevents leaks when compileNodes is used\n // as a standalone entry point (renderChildren, ErrorBoundary).\n const destroyCallbacks = drainDestroyCallbacks();\n const disposers: (() => void)[] = [];\n\n let fragment: DocumentFragment;\n try {\n // 1. AST → unbound DOM\n fragment = pithyTreeToDom(nodes, context);\n\n // 2. Structural directives (@switch, @if/@else, @for)\n bindStructuralDirectives(nodes, fragment, context, disposers);\n\n // 3. Non-structural bindings (refs, error boundaries, components, text, events, etc.)\n bindTemplateDirectives(fragment, context, disposers);\n orderByDocument(disposers);\n } catch (err) {\n // Clean up any disposers already registered during partial compilation\n for (let i = disposers.length - 1; i >= 0; i--) {\n try {\n disposers[i]();\n } catch {\n /* ignore */\n }\n }\n // Run drained callbacks LIFO before rethrowing so partially-initialized\n // resources are still cleaned up.\n for (let i = destroyCallbacks.length - 1; i >= 0; i--) {\n try {\n destroyCallbacks[i]();\n } catch {\n /* ignore */\n }\n }\n throw err;\n }\n\n // Fast path when no onDestroy was called\n if (destroyCallbacks.length === 0) {\n return {\n el: fragment,\n destroy() {\n for (let i = disposers.length - 1; i >= 0; i--) {\n try {\n disposers[i]();\n } catch {\n /* ignore */\n }\n }\n disposers.length = 0;\n },\n };\n }\n\n return {\n el: fragment,\n destroy() {\n for (let i = disposers.length - 1; i >= 0; i--) {\n try {\n disposers[i]();\n } catch {\n /* ignore */\n }\n }\n disposers.length = 0;\n for (let i = destroyCallbacks.length - 1; i >= 0; i--) {\n try {\n destroyCallbacks[i]();\n } catch {\n /* ignore */\n }\n }\n destroyCallbacks.length = 0;\n },\n };\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"compileTemplate.d.ts","sourceRoot":"","sources":["../../src/compile/compileTemplate.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;
|
|
1
|
+
{"version":3,"file":"compileTemplate.d.ts","sourceRoot":"","sources":["../../src/compile/compileTemplate.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAiBF;;;;;;;GAOG;AACH,wBAAgB,wBAAwB,CACtC,KAAK,EAAE,OAAO,mBAAmB,EAAE,SAAS,EAAE,EAC9C,QAAQ,EAAE,gBAAgB,EAC1B,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAChC,SAAS,EAAE,CAAC,MAAM,IAAI,CAAC,EAAE,GACxB,IAAI,CAUN;AAED;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,+RAA+R;AAC/R,wBAAgB,eAAe,CAC7B,IAAI,EAAE,MAAM,EACZ,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAChC,GAAG,CAAC,EAAE,MAAM,EACZ,OAAO,CAAC,EAAE,MAAM,EAChB,mBAAmB,CAAC,EAAE,GAAG,CAAC,MAAM,CAAC,GAChC;IAAE,EAAE,EAAE,WAAW,GAAG,gBAAgB,CAAC;IAAC,OAAO,EAAE,MAAM,IAAI,CAAA;CAAE,CA8C7D;AAED;;;;;;;;;;;;;;;GAeG;AACH,qNAAqN;AACrN,wBAAgB,sBAAsB,CACpC,QAAQ,EAAE,gBAAgB,EAC1B,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAChC,SAAS,EAAE,CAAC,MAAM,IAAI,CAAC,EAAE,GACxB,IAAI,CAsBN"}
|
|
@@ -7,20 +7,14 @@
|
|
|
7
7
|
*/
|
|
8
8
|
import { parseHtml } from './parseHtml.js';
|
|
9
9
|
import { injectScopedStyle } from './injectScopedStyle.js';
|
|
10
|
-
import { bindTextInterpolations } from './binds/bindTextInterpolations.js';
|
|
11
|
-
import { bindEventHandlers } from './binds/bindEventHandlers.js';
|
|
12
|
-
import { bindClassDirectives } from './binds/bindClassDirectives.js';
|
|
13
|
-
import { bindComponentTags } from './binds/bindComponentsTags.js';
|
|
14
10
|
import { bindConditionals } from './binds/bindConditionals.js';
|
|
15
|
-
import { bindBoundAttributes } from './binds/bindBoundAttributes.js';
|
|
16
11
|
import { bindRefDirectives } from './binds/bindRefDirectives.js';
|
|
17
|
-
import { bindDefaultTwoWay } from './binds/bindDefaultTwoWay.js';
|
|
18
12
|
import { bindErrorBoundary } from './binds/bindErrorBoundary.js';
|
|
19
|
-
import { bindDeferDirectives } from './binds/bindDeferDirectives.js';
|
|
20
13
|
import { bindForLoops } from './forLoops/bindForLoops.js';
|
|
21
14
|
import { bindSwitchCases } from './bindSwitchCases.js';
|
|
22
15
|
import { extractSlotDefs, mountProjection, } from './contentProjection.js';
|
|
23
|
-
import {
|
|
16
|
+
import { bindAfterProjection } from './binds/bindAfterProjection.js';
|
|
17
|
+
import { orderByDocument } from './disposeOrder.js';
|
|
24
18
|
/**
|
|
25
19
|
* Runs all structural directive bindings on a fragment.
|
|
26
20
|
*
|
|
@@ -74,6 +68,7 @@ export function compileTemplate(html, context, css, scopeId, importedIdentifiers
|
|
|
74
68
|
}
|
|
75
69
|
// Remaining directives/bindings in carefully chosen order
|
|
76
70
|
bindTemplateDirectives(fragment, context, disposers);
|
|
71
|
+
orderByDocument(disposers);
|
|
77
72
|
}
|
|
78
73
|
catch (err) {
|
|
79
74
|
// Clean up any disposers registered during partial compilation
|
|
@@ -134,21 +129,7 @@ export function bindTemplateDirectives(fragment, context, disposers) {
|
|
|
134
129
|
if (slotDefs.length > 0) {
|
|
135
130
|
mountProjection(slotDefs, slotMap ?? new Map(), disposers);
|
|
136
131
|
}
|
|
137
|
-
// 4) components
|
|
138
|
-
|
|
139
|
-
// 5) two-way model bindings for native controls at this level
|
|
140
|
-
bindDefaultTwoWay(fragment, context, disposers);
|
|
141
|
-
// 6) text interpolations — our binder already skips nested loops & component roots
|
|
142
|
-
bindTextInterpolations(fragment, context, disposers);
|
|
143
|
-
// 7) events (idempotent; supports modifiers; nearest ctx; $event/$el)
|
|
144
|
-
bindEventHandlers(fragment, context, disposers);
|
|
145
|
-
// 8) classes and style properties
|
|
146
|
-
bindClassDirectives(fragment, context, disposers);
|
|
147
|
-
// 9) bound attributes
|
|
148
|
-
bindBoundAttributes(fragment, context, disposers);
|
|
149
|
-
// 10) custom directives — allows external packages (router, etc.) to register binders
|
|
150
|
-
executeCustomDirectiveBinders(fragment, context, disposers);
|
|
151
|
-
// 11) defer directives — lazy loading with @defer, @load, @placeholder
|
|
152
|
-
bindDeferDirectives(fragment, context, disposers);
|
|
132
|
+
// 4-11) components, two-way, text, events, classes, attributes, custom, defer
|
|
133
|
+
bindAfterProjection(fragment, context, disposers);
|
|
153
134
|
}
|
|
154
135
|
//# sourceMappingURL=compileTemplate.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"compileTemplate.js","sourceRoot":"","sources":["../../src/compile/compileTemplate.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;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E,iBAAiB,CAAC,QAAQ,EAAE,OAAO,EAAE,SAAS,CAAC,CAAC;IAEhD,kCAAkC;IAClC,mBAAmB,CAAC,QAAQ,EAAE,OAAO,EAAE,SAAS,CAAC,CAAC;IAElD,sBAAsB;IACtB,mBAAmB,CAAC,QAAQ,EAAE,OAAO,EAAE,SAAS,CAAC,CAAC;IAElD,sFAAsF;IACtF,6BAA6B,CAAC,QAAQ,EAAE,OAAO,EAAE,SAAS,CAAC,CAAC;IAE5D,uEAAuE;IACvE,mBAAmB,CAAC,QAAQ,EAAE,OAAO,EAAE,SAAS,CAAC,CAAC;AACpD,CAAC","sourcesContent":["/** @codex\n{\n \"id\": \"pithy.runtime.renderer\",\n \"title\": \"Template Compiler & Renderer\",\n \"category\": \"runtime\"\n}\n*/\n\nimport { parseHtml } from './parseHtml';\nimport { injectScopedStyle } from './injectScopedStyle';\nimport { bindTextInterpolations } from './binds/bindTextInterpolations';\nimport { bindEventHandlers } from './binds/bindEventHandlers';\nimport { bindClassDirectives } from './binds/bindClassDirectives';\nimport { bindComponentTags } from './binds/bindComponentsTags';\nimport { bindConditionals } from './binds/bindConditionals';\nimport { bindBoundAttributes } from './binds/bindBoundAttributes';\nimport { bindRefDirectives } from './binds/bindRefDirectives';\nimport { bindDefaultTwoWay } from './binds/bindDefaultTwoWay';\nimport { bindErrorBoundary } from './binds/bindErrorBoundary';\nimport { bindDeferDirectives } from './binds/bindDeferDirectives';\nimport { bindForLoops } from './forLoops/bindForLoops';\nimport { bindSwitchCases } from './bindSwitchCases';\nimport {\n extractSlotDefs,\n mountProjection,\n type SlotMap,\n} from './contentProjection';\nimport { executeCustomDirectiveBinders } from './binds/directiveRegistry';\n\n/**\n * Runs all structural directive bindings on a fragment.\n *\n * Ordering:\n * 1) Switch cases first — they claim their case subtrees before conditionals walk the DOM\n * 2) Conditionals (@if/@else) — each branch binds its own nested switches\n * 3) For loops — skips nodes already processed by switches and conditionals\n */\nexport function bindStructuralDirectives(\n nodes: import('@pithyjs/compiler').PithyNode[],\n fragment: DocumentFragment,\n context: Record<string, unknown>,\n disposers: (() => void)[]\n): void {\n const processed = bindSwitchCases(\n nodes,\n fragment,\n context,\n new Set(),\n disposers\n );\n bindConditionals(nodes, fragment, context, processed, disposers);\n bindForLoops(nodes, fragment, context, disposers, processed);\n}\n\n/**\n * Compiles a raw HTML template into live DOM nodes with signal bindings,\n * event handlers, and optional styles.\n *\n * Pipeline overview:\n * 1) parseHtml → returns a DocumentFragment + AST nodes (pithyNodes)\n * 2) structural directives first: @if/@else, @switch, @for (they shape the DOM)\n * 3) inject CSS (scoped)\n * 4) run remaining binders in an order that avoids double-binding and cross-contamination:\n * - refs (so later passes can access refs if needed)\n * - components (instantiate/replace custom tags BEFORE binding into their subtree)\n * - two-way (default model bindings for inputs)\n * - text interpolations\n * - events\n * - classes\n * - bound attributes\n *\n * @param html - Raw HTML template string\n * @param context - Reactive context object (signals, methods, components)\n * @param css - Optional CSS string to scope and inject\n * @param scopeId - Optional scope id for CSS scoping\n * @param importedIdentifiers - Optional set of ids exposed to expressions\n */\n/** @codexApi {\"parent\":\"pithy.runtime.renderer\",\"name\":\"compileTemplate\",\"stability\":\"stable\",\"signature\":\"(html: string, context: Record<string, any>, css?: string, scopeId?: string, importedIdentifiers?: Set<string>) => { el: HTMLElement | DocumentFragment; destroy: () => void }\"} */\nexport function compileTemplate(\n html: string,\n context: Record<string, unknown>,\n css?: string,\n scopeId?: string,\n importedIdentifiers?: Set<string>\n): { el: HTMLElement | DocumentFragment; destroy: () => void } {\n const id = scopeId ?? `pithy-${Math.random().toString(36).slice(2, 8)}`;\n const disposers: (() => void)[] = [];\n\n let fragment: DocumentFragment;\n try {\n // Parse into fragment + AST\n const parsed = parseHtml(html, id, context, importedIdentifiers);\n fragment = parsed.fragment;\n\n // Structural transforms first (they change the DOM shape and add anchors)\n bindStructuralDirectives(parsed.pithyNodes, fragment, context, disposers);\n\n // Scoped CSS after structure is stable\n if (css) {\n injectScopedStyle(css, id);\n }\n\n // Remaining directives/bindings in carefully chosen order\n bindTemplateDirectives(fragment, context, disposers);\n } catch (err) {\n // Clean up any disposers registered during partial compilation\n for (let i = disposers.length - 1; i >= 0; i--) {\n try {\n disposers[i]();\n } catch {\n /* ignore */\n }\n }\n throw err;\n }\n\n return {\n el: fragment,\n destroy() {\n for (let i = disposers.length - 1; i >= 0; i--) {\n try {\n disposers[i]();\n } catch {\n /* ignore */\n }\n }\n disposers.length = 0;\n },\n };\n}\n\n/**\n * Applies all non-structural bindings to the compiled fragment.\n *\n * Ordering rationale:\n * - refs: collected early, sometimes needed by subsequent binders\n * - error boundaries: register boundaries before components render (enables error capture)\n * - projection: mount projected content into slot anchors BEFORE component binding,\n * so nested component tags in projected content get processed\n * - components: instantiate/replace custom tags (including those in projected content);\n * prevents parent binders from walking into raw component tags\n * - two-way: attach default v-model-ish behavior on real inputs (not inside components)\n * - text: {{ ... }} bindings (skips nested loops / component subtrees via flags)\n * - events: add listeners (idempotent; supports modifiers; nearest ctx; $event/$el)\n * - classes: dynamic class toggles\n * - attributes: remaining [attr]=\"...\" bindings\n */\n/** @codexApi {\"parent\":\"pithy.runtime.renderer\",\"name\":\"bindTemplateDirectives\",\"stability\":\"stable\",\"signature\":\"(fragment: DocumentFragment, context: Record<string, any>, disposers: (() => void)[]) => void\"} */\nexport function bindTemplateDirectives(\n fragment: DocumentFragment,\n context: Record<string, unknown>,\n disposers: (() => void)[]\n): void {\n // 1) refs first — enables grabbing component roots/elements if needed\n bindRefDirectives(fragment, context, disposers);\n\n // 2) error boundaries — register before components so they can catch component errors\n bindErrorBoundary(fragment, context, disposers);\n\n // 3) content projection — mount projected content into slot anchors BEFORE components.\n // Projected content may contain component tags (e.g., nested <Show> inside <Show>).\n // If components ran first, those nested component tags would never be processed.\n // Without a SlotMap (a component called directly) slots still get their fallback.\n // Use 'in' operator to check via Proxy's has() trap without triggering the get() warning\n const slotMap = ('__slotMap' in context ? context.__slotMap : undefined) as\n | SlotMap\n | undefined;\n const slotDefs = extractSlotDefs(fragment);\n if (slotDefs.length > 0) {\n mountProjection(slotDefs, slotMap ?? new Map(), disposers);\n }\n\n // 4) components — materialize custom tags, including those in projected content\n bindComponentTags(fragment, context, disposers);\n\n // 5) two-way model bindings for native controls at this level\n bindDefaultTwoWay(fragment, context, disposers);\n\n // 6) text interpolations — our binder already skips nested loops & component roots\n bindTextInterpolations(fragment, context, disposers);\n\n // 7) events (idempotent; supports modifiers; nearest ctx; $event/$el)\n bindEventHandlers(fragment, context, disposers);\n\n // 8) classes and style properties\n bindClassDirectives(fragment, context, disposers);\n\n // 9) bound attributes\n bindBoundAttributes(fragment, context, disposers);\n\n // 10) custom directives — allows external packages (router, etc.) to register binders\n executeCustomDirectiveBinders(fragment, context, disposers);\n\n // 11) defer directives — lazy loading with @defer, @load, @placeholder\n bindDeferDirectives(fragment, context, disposers);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"compileTemplate.js","sourceRoot":"","sources":["../../src/compile/compileTemplate.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAEF,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AACxC,OAAO,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AACxD,OAAO,EAAE,gBAAgB,EAAE,MAAM,0BAA0B,CAAC;AAC5D,OAAO,EAAE,iBAAiB,EAAE,MAAM,2BAA2B,CAAC;AAC9D,OAAO,EAAE,iBAAiB,EAAE,MAAM,2BAA2B,CAAC;AAC9D,OAAO,EAAE,YAAY,EAAE,MAAM,yBAAyB,CAAC;AACvD,OAAO,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AACpD,OAAO,EACL,eAAe,EACf,eAAe,GAEhB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,mBAAmB,EAAE,MAAM,6BAA6B,CAAC;AAClE,OAAO,EAAE,eAAe,EAAE,MAAM,gBAAgB,CAAC;AAEjD;;;;;;;GAOG;AACH,MAAM,UAAU,wBAAwB,CACtC,KAA8C,EAC9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xB,eAAe,CAAC,QAAQ,EAAE,OAAO,IAAI,IAAI,GAAG,EAAE,EAAE,SAAS,CAAC,CAAC;IAC7D,CAAC;IAED,8EAA8E;IAC9E,mBAAmB,CAAC,QAAQ,EAAE,OAAO,EAAE,SAAS,CAAC,CAAC;AACpD,CAAC","sourcesContent":["/** @codex\n{\n \"id\": \"pithy.runtime.renderer\",\n \"title\": \"Template Compiler & Renderer\",\n \"category\": \"runtime\"\n}\n*/\n\nimport { parseHtml } from './parseHtml';\nimport { injectScopedStyle } from './injectScopedStyle';\nimport { bindConditionals } from './binds/bindConditionals';\nimport { bindRefDirectives } from './binds/bindRefDirectives';\nimport { bindErrorBoundary } from './binds/bindErrorBoundary';\nimport { bindForLoops } from './forLoops/bindForLoops';\nimport { bindSwitchCases } from './bindSwitchCases';\nimport {\n extractSlotDefs,\n mountProjection,\n type SlotMap,\n} from './contentProjection';\nimport { bindAfterProjection } from './binds/bindAfterProjection';\nimport { orderByDocument } from './disposeOrder';\n\n/**\n * Runs all structural directive bindings on a fragment.\n *\n * Ordering:\n * 1) Switch cases first — they claim their case subtrees before conditionals walk the DOM\n * 2) Conditionals (@if/@else) — each branch binds its own nested switches\n * 3) For loops — skips nodes already processed by switches and conditionals\n */\nexport function bindStructuralDirectives(\n nodes: import('@pithyjs/compiler').PithyNode[],\n fragment: DocumentFragment,\n context: Record<string, unknown>,\n disposers: (() => void)[]\n): void {\n const processed = bindSwitchCases(\n nodes,\n fragment,\n context,\n new Set(),\n disposers\n );\n bindConditionals(nodes, fragment, context, processed, disposers);\n bindForLoops(nodes, fragment, context, disposers, processed);\n}\n\n/**\n * Compiles a raw HTML template into live DOM nodes with signal bindings,\n * event handlers, and optional styles.\n *\n * Pipeline overview:\n * 1) parseHtml → returns a DocumentFragment + AST nodes (pithyNodes)\n * 2) structural directives first: @if/@else, @switch, @for (they shape the DOM)\n * 3) inject CSS (scoped)\n * 4) run remaining binders in an order that avoids double-binding and cross-contamination:\n * - refs (so later passes can access refs if needed)\n * - components (instantiate/replace custom tags BEFORE binding into their subtree)\n * - two-way (default model bindings for inputs)\n * - text interpolations\n * - events\n * - classes\n * - bound attributes\n *\n * @param html - Raw HTML template string\n * @param context - Reactive context object (signals, methods, components)\n * @param css - Optional CSS string to scope and inject\n * @param scopeId - Optional scope id for CSS scoping\n * @param importedIdentifiers - Optional set of ids exposed to expressions\n */\n/** @codexApi {\"parent\":\"pithy.runtime.renderer\",\"name\":\"compileTemplate\",\"stability\":\"stable\",\"signature\":\"(html: string, context: Record<string, any>, css?: string, scopeId?: string, importedIdentifiers?: Set<string>) => { el: HTMLElement | DocumentFragment; destroy: () => void }\"} */\nexport function compileTemplate(\n html: string,\n context: Record<string, unknown>,\n css?: string,\n scopeId?: string,\n importedIdentifiers?: Set<string>\n): { el: HTMLElement | DocumentFragment; destroy: () => void } {\n const id = scopeId ?? `pithy-${Math.random().toString(36).slice(2, 8)}`;\n const disposers: (() => void)[] = [];\n\n let fragment: DocumentFragment;\n try {\n // Parse into fragment + AST\n const parsed = parseHtml(html, id, context, importedIdentifiers);\n fragment = parsed.fragment;\n\n // Structural transforms first (they change the DOM shape and add anchors)\n bindStructuralDirectives(parsed.pithyNodes, fragment, context, disposers);\n\n // Scoped CSS after structure is stable\n if (css) {\n injectScopedStyle(css, id);\n }\n\n // Remaining directives/bindings in carefully chosen order\n bindTemplateDirectives(fragment, context, disposers);\n orderByDocument(disposers);\n } catch (err) {\n // Clean up any disposers registered during partial compilation\n for (let i = disposers.length - 1; i >= 0; i--) {\n try {\n disposers[i]();\n } catch {\n /* ignore */\n }\n }\n throw err;\n }\n\n return {\n el: fragment,\n destroy() {\n for (let i = disposers.length - 1; i >= 0; i--) {\n try {\n disposers[i]();\n } catch {\n /* ignore */\n }\n }\n disposers.length = 0;\n },\n };\n}\n\n/**\n * Applies all non-structural bindings to the compiled fragment.\n *\n * Ordering rationale:\n * - refs: collected early, sometimes needed by subsequent binders\n * - error boundaries: register boundaries before components render (enables error capture)\n * - projection: mount projected content into slot anchors BEFORE component binding,\n * so nested component tags in projected content get processed\n * - components: instantiate/replace custom tags (including those in projected content);\n * prevents parent binders from walking into raw component tags\n * - two-way: attach default v-model-ish behavior on real inputs (not inside components)\n * - text: {{ ... }} bindings (skips nested loops / component subtrees via flags)\n * - events: add listeners (idempotent; supports modifiers; nearest ctx; $event/$el)\n * - classes: dynamic class toggles\n * - attributes: remaining [attr]=\"...\" bindings\n */\n/** @codexApi {\"parent\":\"pithy.runtime.renderer\",\"name\":\"bindTemplateDirectives\",\"stability\":\"stable\",\"signature\":\"(fragment: DocumentFragment, context: Record<string, any>, disposers: (() => void)[]) => void\"} */\nexport function bindTemplateDirectives(\n fragment: DocumentFragment,\n context: Record<string, unknown>,\n disposers: (() => void)[]\n): void {\n // 1) refs first — enables grabbing component roots/elements if needed\n bindRefDirectives(fragment, context, disposers);\n\n // 2) error boundaries — register before components so they can catch component errors\n bindErrorBoundary(fragment, context, disposers);\n\n // 3) content projection — mount projected content into slot anchors BEFORE components.\n // Projected content may contain component tags (e.g., nested <Show> inside <Show>).\n // If components ran first, those nested component tags would never be processed.\n // Without a SlotMap (a component called directly) slots still get their fallback.\n // Use 'in' operator to check via Proxy's has() trap without triggering the get() warning\n const slotMap = ('__slotMap' in context ? context.__slotMap : undefined) as\n | SlotMap\n | undefined;\n const slotDefs = extractSlotDefs(fragment);\n if (slotDefs.length > 0) {\n mountProjection(slotDefs, slotMap ?? new Map(), disposers);\n }\n\n // 4-11) components, two-way, text, events, classes, attributes, custom, defer\n bindAfterProjection(fragment, context, disposers);\n}\n"]}
|
|
@@ -20,10 +20,22 @@ export interface SlotDef {
|
|
|
20
20
|
anchor: Comment;
|
|
21
21
|
fallbackFactory?: FallbackFactory;
|
|
22
22
|
}
|
|
23
|
+
/**
|
|
24
|
+
* The slot map of the template the children behind `slotMap` were written in:
|
|
25
|
+
* what a `<slot>` among those children receives.
|
|
26
|
+
*/
|
|
27
|
+
/** @codexApi {"parent":"pithy.feature.content-projection","name":"outerSlotMap","stability":"internal","signature":"(slotMap: SlotMap | undefined) => SlotMap | undefined"} */
|
|
28
|
+
export declare function outerSlotMap(slotMap: SlotMap | undefined): SlotMap | undefined;
|
|
29
|
+
/** Records `ctx`'s slot map as what a `<slot>` among `slotMap`'s children receives. */
|
|
30
|
+
/** @codexApi {"parent":"pithy.feature.content-projection","name":"linkOuterSlotMap","stability":"internal","signature":"(slotMap: SlotMap, ctx: Record<string, unknown>) => void"} */
|
|
31
|
+
export declare function linkOuterSlotMap(slotMap: SlotMap, ctx: Record<string, unknown>): void;
|
|
23
32
|
/** @codexApi {"parent":"pithy.feature.content-projection","name":"collectSlotMap","stability":"stable","signature":"(children: PithyNode[], parentContext: Record<string, any>) => SlotMap"} */
|
|
24
33
|
export declare function collectSlotMap(children: PithyNode[], parentContext: Record<string, unknown>): SlotMap;
|
|
25
34
|
/** @codexApi {"parent":"pithy.feature.content-projection","name":"extractSlotDefs","stability":"stable","signature":"(fragment: DocumentFragment) => SlotDef[]"} */
|
|
26
35
|
export declare function extractSlotDefs(fragment: DocumentFragment): SlotDef[];
|
|
36
|
+
/** Whether `node` is inside content a `<slot>` projected. */
|
|
37
|
+
/** @codexApi {"parent":"pithy.feature.content-projection","name":"inProjectedContent","stability":"internal","signature":"(node: Node) => boolean"} */
|
|
38
|
+
export declare function inProjectedContent(node: Node): boolean;
|
|
27
39
|
/** @codexApi {"parent":"pithy.feature.content-projection","name":"mountProjection","stability":"stable","signature":"(slotDefs: SlotDef[], slotMap: SlotMap, disposers: (() => void)[]) => void"} */
|
|
28
40
|
export declare function mountProjection(slotDefs: SlotDef[], slotMap: SlotMap, disposers: (() => void)[]): void;
|
|
29
41
|
//# sourceMappingURL=contentProjection.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"contentProjection.d.ts","sourceRoot":"","sources":["../../src/compile/contentProjection.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAEF,OAAO,EAAE,SAAS,EAAE,MAAM,mBAAmB,CA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AgB,cAAc,CAC5B,QAAQ,EAAE,SAAS,EAAE,EACrB,aAAa,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GACrC,OAAO,CAuFT;AAED,oKAAoK;AACpK,wBAAgB,eAAe,CAAC,QAAQ,EAAE,gBAAgB,GAAG,OAAO,EAAE,CA+BrE;AAED,6DAA6D;AAC7D,uJAAuJ;AACvJ,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,IAAI,GAAG,OAAO,CAItD;AAQD,qMAAqM;AACrM,wBAAgB,eAAe,CAC7B,QAAQ,EAAE,OAAO,EAAE,EACnB,OAAO,EAAE,OAAO,EAChB,SAAS,EAAE,CAAC,MAAM,IAAI,CAAC,EAAE,GACxB,IAAI,CAqKN"}
|
|
@@ -14,10 +14,31 @@ import { trimBlankEdges } from './trimBlankEdges.js';
|
|
|
14
14
|
function expando(node) {
|
|
15
15
|
return node;
|
|
16
16
|
}
|
|
17
|
+
const outerSlotMaps = new WeakMap();
|
|
18
|
+
function slotMapOf(ctx) {
|
|
19
|
+
return ('__slotMap' in ctx ? ctx.__slotMap : undefined);
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* The slot map of the template the children behind `slotMap` were written in:
|
|
23
|
+
* what a `<slot>` among those children receives.
|
|
24
|
+
*/
|
|
25
|
+
/** @codexApi {"parent":"pithy.feature.content-projection","name":"outerSlotMap","stability":"internal","signature":"(slotMap: SlotMap | undefined) => SlotMap | undefined"} */
|
|
26
|
+
export function outerSlotMap(slotMap) {
|
|
27
|
+
return slotMap && outerSlotMaps.get(slotMap);
|
|
28
|
+
}
|
|
29
|
+
/** Records `ctx`'s slot map as what a `<slot>` among `slotMap`'s children receives. */
|
|
30
|
+
/** @codexApi {"parent":"pithy.feature.content-projection","name":"linkOuterSlotMap","stability":"internal","signature":"(slotMap: SlotMap, ctx: Record<string, unknown>) => void"} */
|
|
31
|
+
export function linkOuterSlotMap(slotMap, ctx) {
|
|
32
|
+
const outer = slotMapOf(ctx);
|
|
33
|
+
if (outer)
|
|
34
|
+
outerSlotMaps.set(slotMap, outer);
|
|
35
|
+
}
|
|
17
36
|
/** @codexApi {"parent":"pithy.feature.content-projection","name":"collectSlotMap","stability":"stable","signature":"(children: PithyNode[], parentContext: Record<string, any>) => SlotMap"} */
|
|
18
37
|
export function collectSlotMap(children, parentContext) {
|
|
19
38
|
const slotMap = new Map();
|
|
20
39
|
const slotGroups = new Map();
|
|
40
|
+
linkOuterSlotMap(slotMap, parentContext);
|
|
41
|
+
const outer = slotMapOf(parentContext);
|
|
21
42
|
// Group children by slot attribute
|
|
22
43
|
for (const child of children) {
|
|
23
44
|
const slotName = child.directives?.slot || ''; // default slot if no slot attribute
|
|
@@ -64,6 +85,10 @@ export function collectSlotMap(children, parentContext) {
|
|
|
64
85
|
const fragment = pithyTreeToDom(capturedNodes, capturedContext);
|
|
65
86
|
bindStructuralDirectives(capturedNodes, fragment, capturedContext, disposers);
|
|
66
87
|
bindErrorBoundary(fragment, capturedContext, disposers);
|
|
88
|
+
// A `<slot>` passed through: the receiving component has already looked for its slots.
|
|
89
|
+
const passed = extractSlotDefs(fragment);
|
|
90
|
+
if (passed.length)
|
|
91
|
+
mountProjection(passed, outer ?? new Map(), disposers);
|
|
67
92
|
nodeExpando(fragment).__pithyCtx = capturedContext;
|
|
68
93
|
return fragment;
|
|
69
94
|
};
|
|
@@ -87,6 +112,9 @@ export function extractSlotDefs(fragment) {
|
|
|
87
112
|
});
|
|
88
113
|
let node;
|
|
89
114
|
while ((node = walker.nextNode())) {
|
|
115
|
+
// Inside a component tag, the slot is that component's content to place.
|
|
116
|
+
if (inComponentTag(node))
|
|
117
|
+
continue;
|
|
90
118
|
const slotName = expando(node).__slotName || '';
|
|
91
119
|
const fallbackFactory = expando(node).__fallbackFactory;
|
|
92
120
|
slotDefs.push({
|
|
@@ -100,6 +128,20 @@ export function extractSlotDefs(fragment) {
|
|
|
100
128
|
}
|
|
101
129
|
return slotDefs;
|
|
102
130
|
}
|
|
131
|
+
/** Whether `node` is inside content a `<slot>` projected. */
|
|
132
|
+
/** @codexApi {"parent":"pithy.feature.content-projection","name":"inProjectedContent","stability":"internal","signature":"(node: Node) => boolean"} */
|
|
133
|
+
export function inProjectedContent(node) {
|
|
134
|
+
for (let n = node; n; n = n.parentNode)
|
|
135
|
+
if (expando(n).__projectedContent)
|
|
136
|
+
return true;
|
|
137
|
+
return false;
|
|
138
|
+
}
|
|
139
|
+
function inComponentTag(node) {
|
|
140
|
+
for (let el = node.parentElement; el; el = el.parentElement)
|
|
141
|
+
if (nodeExpando(el).__pithyNode?.isComponent)
|
|
142
|
+
return true;
|
|
143
|
+
return false;
|
|
144
|
+
}
|
|
103
145
|
/** @codexApi {"parent":"pithy.feature.content-projection","name":"mountProjection","stability":"stable","signature":"(slotDefs: SlotDef[], slotMap: SlotMap, disposers: (() => void)[]) => void"} */
|
|
104
146
|
export function mountProjection(slotDefs, slotMap, disposers) {
|
|
105
147
|
for (const slotDef of slotDefs) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"contentProjection.js","sourceRoot":"","sources":["../../src/compile/contentProjection.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAGF,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAClD,OAAO,EAAE,wBAAwB,EAAE,MAAM,mBAAmB,CAAC;AAC7D,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAC5C,OAAO,EACL,iBAAiB,EACjB,kBAAkB,EAClB,kBAAkB,GACnB,MAAM,2BAA2B,CAAC;AACnC,OAAO,EAAE,YAAY,EAAE,MAAM,kBAAkB,CAAC;AAChD,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AA6BlD,SAAS,OAAO,CAAC,IAAU;IACzB,OAAO,IAAgC,CAAC;AAC1C,CAAC;AAED,gMAAgM;AAChM,MAAM,UAAU,cAAc,CAC5B,QAAqB,EACrB,aAAsC;IAEtC,MAAM,OAAO,GAAY,IAAI,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a,EAAE,CAAC;YACjC,IAAI,IAAI,CAAC,UAAU,EAAE,CAAC;gBACpB,IAAI,CAAC,UAAU,CAAC,WAAW,CAAC,IAAI,CAAC,CAAC;YACpC,CAAC;QACH,CAAC;QAED,8CAA8C;QAC9C,IAAI,CAAC,kBAAkB,CAAC,MAAM,EAAE,eAAe,CAAC;YAC9C,MAAM,EAAE,YAAY,CAAC,eAAe,EAAE,MAAM,CAAC,WAAW,CAAC,CAAC;QAE5D,iEAAiE;QACjE,SAAS,CAAC,IAAI,CAAC,GAAG,EAAE;YAClB,KAAK,MAAM,IAAI,IAAI,aAAa,EAAE,CAAC;gBACjC,IAAI,IAAI,CAAC,UAAU,EAAE,CAAC;oBACpB,IAAI,CAAC,UAAU,CAAC,WAAW,CAAC,IAAI,CAAC,CAAC;gBACpC,CAAC;YACH,CAAC;YACD,IAAI,MAAM,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,IAAI,YAAY,EAAE,CAAC,sBAAsB,EAAE,CAAC;gBAClE,OAAO,CAAC,GAAG,CAAC,yCAAyC,IAAI,GAAG,CAAC,CAAC;YAChE,CAAC;QACH,CAAC,CAAC,CAAC;QAEH,IAAI,MAAM,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,IAAI,YAAY,EAAE,CAAC,sBAAsB,EAAE,CAAC;YAClE,OAAO,CAAC,GAAG,CACT,6CAA6C,aAAa,CAAC,MAAM,oBAAoB,IAAI,GAAG,CAC7F,CAAC;QACJ,CAAC;IACH,CAAC;IAED,2BAA2B;IAC3B,2EAA2E;IAC3E,yEAAyE;IACzE,6EAA6E;IAC7E,sEAAsE;IACtE,uEAAuE;IACvE,qEAAqE;IACrE,gDAAgD;AAClD,CAAC","sourcesContent":["/** @codex\n{\n \"id\": \"pithy.feature.content-projection\",\n \"title\": \"Content Projection System\",\n \"category\": \"feature\"\n}\n*/\n\nimport { PithyNode } from '@pithyjs/compiler';\nimport { pithyTreeToDom } from './pithyTreeToDom';\nimport { bindStructuralDirectives } from './compileTemplate';\nimport { nodeExpando } from './nodeExpando';\nimport {\n bindErrorBoundary,\n insertBesideHidden,\n isHiddenByBoundary,\n} from './binds/bindErrorBoundary';\nimport { pithyGlobals } from '../types/globals';\nimport { trimBlankEdges } from './trimBlankEdges';\n\n/**\n * SlotMap contains renderer functions for each slot name.\n * Each entry is a factory that returns a DocumentFragment of the slot's content.\n */\nexport type SlotMap = Map<\n string,\n (disposers?: (() => void)[], anchor?: Node) => DocumentFragment\n>;\n\n/**\n * SlotDef describes a slot anchor and its fallback content\n */\nexport type FallbackFactory = () => HTMLElement | DocumentFragment | undefined;\n\nexport interface SlotDef {\n name: string;\n anchor: Comment;\n fallbackFactory?: FallbackFactory;\n}\n\ninterface ProjectionExpando {\n __slotName?: string;\n __fallbackFactory?: FallbackFactory;\n __projectionProcessed?: boolean;\n __projectedContent?: boolean;\n}\n\nfunction expando(node: Node): ProjectionExpando {\n return node as Node & ProjectionExpando;\n}\n\n/** @codexApi {\"parent\":\"pithy.feature.content-projection\",\"name\":\"collectSlotMap\",\"stability\":\"stable\",\"signature\":\"(children: PithyNode[], parentContext: Record<string, any>) => SlotMap\"} */\nexport function collectSlotMap(\n children: PithyNode[],\n parentContext: Record<string, unknown>\n): SlotMap {\n const slotMap: SlotMap = new Map();\n const slotGroups = new Map<string, PithyNode[]>();\n\n // Group children by slot attribute\n for (const child of children) {\n const slotName = child.directives?.slot || ''; // default slot if no slot attribute\n\n if (!slotGroups.has(slotName)) {\n slotGroups.set(slotName, []);\n }\n slotGroups.get(slotName)!.push(child);\n }\n const defaultSlot = slotGroups.get('');\n if (defaultSlot) {\n const content = trimBlankEdges(defaultSlot, node =>\n node.type === 'text' ? (node.textContent ?? '') : null\n );\n if (content.length) slotGroups.set('', content);\n else slotGroups.delete('');\n }\n\n // Validate slot usage in DEV mode\n if (import.meta.env?.DEV) {\n const slotNames = Array.from(slotGroups.keys());\n const duplicateSlots = slotNames.filter(\n name => name !== '' && slotGroups.get(name)!.length > 1\n );\n if (duplicateSlots.length > 0) {\n console.warn(\n `[ContentProjection] Multiple content nodes targeting the same slot. This is allowed but may indicate a mistake:`,\n duplicateSlots\n );\n }\n }\n\n // Create renderer functions for each slot group.\n // NOTE: We intentionally do NOT cache or clone DocumentFragments here.\n // Using fragment caching + cloneNode(true) would strip custom JS properties\n // like __pithyCtx that binders rely on to resolve projected content\n // expressions (including interpolation, [class], and [attr] bindings)\n // against the *parent* component's context.\n //\n // This behavior is relied upon by regression tests that exercise projected\n // nodes containing such bindings; changing this to reuse or clone\n // fragments will cause those tests to fail and break content projection.\n // pithyTreeToDom is cheap (just creates DOM nodes), so recreating is fine.\n\n for (const [slotName, nodes] of slotGroups) {\n // Capture nodes and context in closure for stable reference\n const capturedNodes = nodes;\n const capturedContext = parentContext;\n\n const render = (disposers: (() => void)[] = []): DocumentFragment => {\n if (import.meta.env?.DEV && pithyGlobals().PITHY_DEBUG_PROJECTION) {\n console.log(\n `[PithyJS:Projection] Rendering slot \"${slotName}\" with ${capturedNodes.length} nodes`\n );\n }\n\n const fragment = pithyTreeToDom(capturedNodes, capturedContext);\n bindStructuralDirectives(\n capturedNodes,\n fragment,\n capturedContext,\n disposers\n );\n bindErrorBoundary(fragment, capturedContext, disposers);\n nodeExpando(fragment).__pithyCtx = capturedContext;\n return fragment;\n };\n\n slotMap.set(slotName, render);\n }\n\n if (import.meta.env?.DEV && pithyGlobals().PITHY_DEBUG_PROJECTION) {\n console.log(\n `[PithyJS:Projection] Collected SlotMap with slots:`,\n Array.from(slotMap.keys())\n );\n }\n return slotMap;\n}\n\n/** @codexApi {\"parent\":\"pithy.feature.content-projection\",\"name\":\"extractSlotDefs\",\"stability\":\"stable\",\"signature\":\"(fragment: DocumentFragment) => SlotDef[]\"} */\nexport function extractSlotDefs(fragment: DocumentFragment): SlotDef[] {\n const slotDefs: SlotDef[] = [];\n const walker = document.createTreeWalker(fragment, NodeFilter.SHOW_COMMENT, {\n acceptNode: node => {\n const comment = node as Comment;\n return comment.textContent?.startsWith('slot:')\n ? NodeFilter.FILTER_ACCEPT\n : NodeFilter.FILTER_REJECT;\n },\n });\n\n let node: Comment | null;\n while ((node = walker.nextNode() as Comment | null)) {\n const slotName = expando(node).__slotName || '';\n const fallbackFactory = expando(node).__fallbackFactory;\n\n slotDefs.push({\n name: slotName,\n anchor: node,\n fallbackFactory,\n });\n }\n\n if (import.meta.env?.DEV && pithyGlobals().PITHY_DEBUG_PROJECTION) {\n console.log(\n `[PithyJS:Projection] Extracted ${slotDefs.length} slot definitions`\n );\n }\n return slotDefs;\n}\n\n/** @codexApi {\"parent\":\"pithy.feature.content-projection\",\"name\":\"mountProjection\",\"stability\":\"stable\",\"signature\":\"(slotDefs: SlotDef[], slotMap: SlotMap, disposers: (() => void)[]) => void\"} */\nexport function mountProjection(\n slotDefs: SlotDef[],\n slotMap: SlotMap,\n disposers: (() => void)[]\n): void {\n for (const slotDef of slotDefs) {\n const { name, anchor, fallbackFactory } = slotDef;\n const renderer = slotMap.get(name);\n\n // Skip if this slot has already been processed\n if (expando(anchor).__projectionProcessed) {\n continue;\n }\n\n // Mark this slot as processed to prevent multiple passes\n expando(anchor).__projectionProcessed = true;\n\n const parent = anchor.parentNode;\n // A crash in an earlier slot can have hidden this anchor behind a fallback.\n if (!parent && !isHiddenByBoundary(anchor)) {\n if (import.meta.env?.DEV) {\n console.warn(\n `[ContentProjection] Slot anchor \"${name}\" has no parent node - skipping`\n );\n }\n continue;\n }\n\n // Determine which content to render\n let contentFragment: HTMLElement | DocumentFragment | null = null;\n let isProjectedContent = false;\n\n if (renderer) {\n // Use projected content\n contentFragment = renderer(disposers, anchor);\n isProjectedContent = true;\n if (import.meta.env?.DEV && pithyGlobals().PITHY_DEBUG_PROJECTION) {\n console.log(\n `[PithyJS:Projection] Mounting projected content for slot \"${name}\"`\n );\n }\n } else if (fallbackFactory) {\n // Use fallback content\n contentFragment = fallbackFactory() ?? null;\n const slotNode = nodeExpando(anchor).__pithyNode;\n if (\n contentFragment instanceof DocumentFragment &&\n slotNode?.fallbackChildren\n ) {\n const fallbackCtx = nodeExpando(anchor).__pithyCtx ?? {};\n bindStructuralDirectives(\n slotNode.fallbackChildren,\n contentFragment,\n fallbackCtx,\n disposers\n );\n bindErrorBoundary(contentFragment, fallbackCtx, disposers);\n }\n if (import.meta.env?.DEV && pithyGlobals().PITHY_DEBUG_PROJECTION) {\n console.log(\n `[PithyJS:Projection] Mounting fallback content for slot \"${name}\"`\n );\n }\n } else {\n // No content to mount\n if (import.meta.env?.DEV && pithyGlobals().PITHY_DEBUG_PROJECTION) {\n console.log(`[PithyJS:Projection] No content for slot \"${name}\"`);\n }\n continue;\n }\n\n // Validate content\n if (!contentFragment || contentFragment.childNodes.length === 0) {\n if (import.meta.env?.DEV && pithyGlobals().PITHY_DEBUG_PROJECTION) {\n console.log(\n `[PithyJS:Projection] Empty content for slot \"${name}\" - skipping`\n );\n }\n continue;\n }\n\n // CRITICAL: Collect nodes BEFORE inserting into DOM (for cleanup tracking)\n // Once inserted, the fragment's childNodes will be empty\n const nodesToInsert: Node[] = Array.from(contentFragment.childNodes);\n\n // Mark nodes for tracking\n for (const node of nodesToInsert) {\n expando(node).__projectedContent = isProjectedContent;\n expando(node).__slotName = name;\n }\n\n // Find and remove any existing content for this slot\n const existingNodes: Node[] = [];\n let current = anchor.nextSibling;\n\n while (current) {\n // Stop if we hit another slot anchor\n if (\n current.nodeType === Node.COMMENT_NODE &&\n (current as Comment).textContent?.startsWith('slot:')\n ) {\n break;\n }\n\n // A sibling no projection marked is the component's own markup.\n const meta = expando(current);\n if (meta.__projectedContent === undefined || meta.__slotName !== name) {\n break;\n }\n existingNodes.push(current);\n\n current = current.nextSibling;\n }\n\n // Simple diffing: only replace if content appears different\n // Compare node count and types as a basic heuristic\n const shouldReplace =\n existingNodes.length !== nodesToInsert.length ||\n existingNodes.some(\n (node, i) => node.nodeType !== nodesToInsert[i]?.nodeType\n );\n\n if (!shouldReplace && existingNodes.length > 0) {\n if (import.meta.env?.DEV && pithyGlobals().PITHY_DEBUG_PROJECTION) {\n console.log(\n `[PithyJS:Projection] Content for slot \"${name}\" unchanged - skipping replacement`\n );\n }\n continue;\n }\n\n // Remove existing content\n for (const node of existingNodes) {\n if (node.parentNode) {\n node.parentNode.removeChild(node);\n }\n }\n\n // Insert new content after the anchor comment\n if (!insertBesideHidden(anchor, contentFragment))\n parent?.insertBefore(contentFragment, anchor.nextSibling);\n\n // Track cleanup - remove projected nodes when component unmounts\n disposers.push(() => {\n for (const node of nodesToInsert) {\n if (node.parentNode) {\n node.parentNode.removeChild(node);\n }\n }\n if (import.meta.env?.DEV && pithyGlobals().PITHY_DEBUG_PROJECTION) {\n console.log(`[PithyJS:Projection] Cleaned up slot \"${name}\"`);\n }\n });\n\n if (import.meta.env?.DEV && pithyGlobals().PITHY_DEBUG_PROJECTION) {\n console.log(\n `[PithyJS:Projection] Successfully mounted ${nodesToInsert.length} nodes for slot \"${name}\"`\n );\n }\n }\n\n // DEV: Validate slot usage\n // NOTE: We intentionally do NOT warn about unmatched projected slots here.\n // When a component uses @if/@else with different <slot> elements in each\n // branch (e.g., Show has <slot> in @if and <slot name=\"fallback\"> in @else),\n // the currently-rendered branch may not include all slot targets. The\n // projected \"fallback\" content is legitimate — it will be mounted when\n // the @else branch activates. Warnings here would be false positives\n // and fire repeatedly on every reactive toggle.\n}\n"]}
|
|
1
|
+
{"version":3,"file":"contentProjection.js","sourceRoot":"","sources":["../../src/compile/contentProjection.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAGF,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAClD,OAAO,EAAE,wBAAwB,EAAE,MAAM,mBAAmB,CAAC;AAC7D,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAC5C,OAAO,EACL,iBAAiB,EACjB,kBAAkB,EAClB,kBAAkB,GACnB,MAAM,2BAA2B,CAAC;AACnC,OAAO,EAAE,YAAY,EAAE,MAAM,kBAAkB,CAAC;AAChD,OAAO,EAAE,cAA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AAO,CAAC,GAAG,CACT,6CAA6C,aAAa,CAAC,MAAM,oBAAoB,IAAI,GAAG,CAC7F,CAAC;QACJ,CAAC;IACH,CAAC;IAED,2BAA2B;IAC3B,2EAA2E;IAC3E,yEAAyE;IACzE,6EAA6E;IAC7E,sEAAsE;IACtE,uEAAuE;IACvE,qEAAqE;IACrE,gDAAgD;AAClD,CAAC","sourcesContent":["/** @codex\n{\n \"id\": \"pithy.feature.content-projection\",\n \"title\": \"Content Projection System\",\n \"category\": \"feature\"\n}\n*/\n\nimport { PithyNode } from '@pithyjs/compiler';\nimport { pithyTreeToDom } from './pithyTreeToDom';\nimport { bindStructuralDirectives } from './compileTemplate';\nimport { nodeExpando } from './nodeExpando';\nimport {\n bindErrorBoundary,\n insertBesideHidden,\n isHiddenByBoundary,\n} from './binds/bindErrorBoundary';\nimport { pithyGlobals } from '../types/globals';\nimport { trimBlankEdges } from './trimBlankEdges';\n\n/**\n * SlotMap contains renderer functions for each slot name.\n * Each entry is a factory that returns a DocumentFragment of the slot's content.\n */\nexport type SlotMap = Map<\n string,\n (disposers?: (() => void)[], anchor?: Node) => DocumentFragment\n>;\n\n/**\n * SlotDef describes a slot anchor and its fallback content\n */\nexport type FallbackFactory = () => HTMLElement | DocumentFragment | undefined;\n\nexport interface SlotDef {\n name: string;\n anchor: Comment;\n fallbackFactory?: FallbackFactory;\n}\n\ninterface ProjectionExpando {\n __slotName?: string;\n __fallbackFactory?: FallbackFactory;\n __projectionProcessed?: boolean;\n __projectedContent?: boolean;\n}\n\nfunction expando(node: Node): ProjectionExpando {\n return node as Node & ProjectionExpando;\n}\n\nconst outerSlotMaps = new WeakMap<SlotMap, SlotMap>();\n\nfunction slotMapOf(ctx: Record<string, unknown>): SlotMap | undefined {\n return ('__slotMap' in ctx ? ctx.__slotMap : undefined) as\n | SlotMap\n | undefined;\n}\n\n/**\n * The slot map of the template the children behind `slotMap` were written in:\n * what a `<slot>` among those children receives.\n */\n/** @codexApi {\"parent\":\"pithy.feature.content-projection\",\"name\":\"outerSlotMap\",\"stability\":\"internal\",\"signature\":\"(slotMap: SlotMap | undefined) => SlotMap | undefined\"} */\nexport function outerSlotMap(\n slotMap: SlotMap | undefined\n): SlotMap | undefined {\n return slotMap && outerSlotMaps.get(slotMap);\n}\n\n/** Records `ctx`'s slot map as what a `<slot>` among `slotMap`'s children receives. */\n/** @codexApi {\"parent\":\"pithy.feature.content-projection\",\"name\":\"linkOuterSlotMap\",\"stability\":\"internal\",\"signature\":\"(slotMap: SlotMap, ctx: Record<string, unknown>) => void\"} */\nexport function linkOuterSlotMap(\n slotMap: SlotMap,\n ctx: Record<string, unknown>\n): void {\n const outer = slotMapOf(ctx);\n if (outer) outerSlotMaps.set(slotMap, outer);\n}\n\n/** @codexApi {\"parent\":\"pithy.feature.content-projection\",\"name\":\"collectSlotMap\",\"stability\":\"stable\",\"signature\":\"(children: PithyNode[], parentContext: Record<string, any>) => SlotMap\"} */\nexport function collectSlotMap(\n children: PithyNode[],\n parentContext: Record<string, unknown>\n): SlotMap {\n const slotMap: SlotMap = new Map();\n const slotGroups = new Map<string, PithyNode[]>();\n linkOuterSlotMap(slotMap, parentContext);\n const outer = slotMapOf(parentContext);\n\n // Group children by slot attribute\n for (const child of children) {\n const slotName = child.directives?.slot || ''; // default slot if no slot attribute\n\n if (!slotGroups.has(slotName)) {\n slotGroups.set(slotName, []);\n }\n slotGroups.get(slotName)!.push(child);\n }\n const defaultSlot = slotGroups.get('');\n if (defaultSlot) {\n const content = trimBlankEdges(defaultSlot, node =>\n node.type === 'text' ? (node.textContent ?? '') : null\n );\n if (content.length) slotGroups.set('', content);\n else slotGroups.delete('');\n }\n\n // Validate slot usage in DEV mode\n if (import.meta.env?.DEV) {\n const slotNames = Array.from(slotGroups.keys());\n const duplicateSlots = slotNames.filter(\n name => name !== '' && slotGroups.get(name)!.length > 1\n );\n if (duplicateSlots.length > 0) {\n console.warn(\n `[ContentProjection] Multiple content nodes targeting the same slot. This is allowed but may indicate a mistake:`,\n duplicateSlots\n );\n }\n }\n\n // Create renderer functions for each slot group.\n // NOTE: We intentionally do NOT cache or clone DocumentFragments here.\n // Using fragment caching + cloneNode(true) would strip custom JS properties\n // like __pithyCtx that binders rely on to resolve projected content\n // expressions (including interpolation, [class], and [attr] bindings)\n // against the *parent* component's context.\n //\n // This behavior is relied upon by regression tests that exercise projected\n // nodes containing such bindings; changing this to reuse or clone\n // fragments will cause those tests to fail and break content projection.\n // pithyTreeToDom is cheap (just creates DOM nodes), so recreating is fine.\n\n for (const [slotName, nodes] of slotGroups) {\n // Capture nodes and context in closure for stable reference\n const capturedNodes = nodes;\n const capturedContext = parentContext;\n\n const render = (disposers: (() => void)[] = []): DocumentFragment => {\n if (import.meta.env?.DEV && pithyGlobals().PITHY_DEBUG_PROJECTION) {\n console.log(\n `[PithyJS:Projection] Rendering slot \"${slotName}\" with ${capturedNodes.length} nodes`\n );\n }\n\n const fragment = pithyTreeToDom(capturedNodes, capturedContext);\n bindStructuralDirectives(\n capturedNodes,\n fragment,\n capturedContext,\n disposers\n );\n bindErrorBoundary(fragment, capturedContext, disposers);\n // A `<slot>` passed through: the receiving component has already looked for its slots.\n const passed = extractSlotDefs(fragment);\n if (passed.length) mountProjection(passed, outer ?? new Map(), disposers);\n nodeExpando(fragment).__pithyCtx = capturedContext;\n return fragment;\n };\n\n slotMap.set(slotName, render);\n }\n\n if (import.meta.env?.DEV && pithyGlobals().PITHY_DEBUG_PROJECTION) {\n console.log(\n `[PithyJS:Projection] Collected SlotMap with slots:`,\n Array.from(slotMap.keys())\n );\n }\n return slotMap;\n}\n\n/** @codexApi {\"parent\":\"pithy.feature.content-projection\",\"name\":\"extractSlotDefs\",\"stability\":\"stable\",\"signature\":\"(fragment: DocumentFragment) => SlotDef[]\"} */\nexport function extractSlotDefs(fragment: DocumentFragment): SlotDef[] {\n const slotDefs: SlotDef[] = [];\n const walker = document.createTreeWalker(fragment, NodeFilter.SHOW_COMMENT, {\n acceptNode: node => {\n const comment = node as Comment;\n return comment.textContent?.startsWith('slot:')\n ? NodeFilter.FILTER_ACCEPT\n : NodeFilter.FILTER_REJECT;\n },\n });\n\n let node: Comment | null;\n while ((node = walker.nextNode() as Comment | null)) {\n // Inside a component tag, the slot is that component's content to place.\n if (inComponentTag(node)) continue;\n const slotName = expando(node).__slotName || '';\n const fallbackFactory = expando(node).__fallbackFactory;\n\n slotDefs.push({\n name: slotName,\n anchor: node,\n fallbackFactory,\n });\n }\n\n if (import.meta.env?.DEV && pithyGlobals().PITHY_DEBUG_PROJECTION) {\n console.log(\n `[PithyJS:Projection] Extracted ${slotDefs.length} slot definitions`\n );\n }\n return slotDefs;\n}\n\n/** Whether `node` is inside content a `<slot>` projected. */\n/** @codexApi {\"parent\":\"pithy.feature.content-projection\",\"name\":\"inProjectedContent\",\"stability\":\"internal\",\"signature\":\"(node: Node) => boolean\"} */\nexport function inProjectedContent(node: Node): boolean {\n for (let n: Node | null = node; n; n = n.parentNode)\n if (expando(n).__projectedContent) return true;\n return false;\n}\n\nfunction inComponentTag(node: Node): boolean {\n for (let el = node.parentElement; el; el = el.parentElement)\n if (nodeExpando(el).__pithyNode?.isComponent) return true;\n return false;\n}\n\n/** @codexApi {\"parent\":\"pithy.feature.content-projection\",\"name\":\"mountProjection\",\"stability\":\"stable\",\"signature\":\"(slotDefs: SlotDef[], slotMap: SlotMap, disposers: (() => void)[]) => void\"} */\nexport function mountProjection(\n slotDefs: SlotDef[],\n slotMap: SlotMap,\n disposers: (() => void)[]\n): void {\n for (const slotDef of slotDefs) {\n const { name, anchor, fallbackFactory } = slotDef;\n const renderer = slotMap.get(name);\n\n // Skip if this slot has already been processed\n if (expando(anchor).__projectionProcessed) {\n continue;\n }\n\n // Mark this slot as processed to prevent multiple passes\n expando(anchor).__projectionProcessed = true;\n\n const parent = anchor.parentNode;\n // A crash in an earlier slot can have hidden this anchor behind a fallback.\n if (!parent && !isHiddenByBoundary(anchor)) {\n if (import.meta.env?.DEV) {\n console.warn(\n `[ContentProjection] Slot anchor \"${name}\" has no parent node - skipping`\n );\n }\n continue;\n }\n\n // Determine which content to render\n let contentFragment: HTMLElement | DocumentFragment | null = null;\n let isProjectedContent = false;\n\n if (renderer) {\n // Use projected content\n contentFragment = renderer(disposers, anchor);\n isProjectedContent = true;\n if (import.meta.env?.DEV && pithyGlobals().PITHY_DEBUG_PROJECTION) {\n console.log(\n `[PithyJS:Projection] Mounting projected content for slot \"${name}\"`\n );\n }\n } else if (fallbackFactory) {\n // Use fallback content\n contentFragment = fallbackFactory() ?? null;\n const slotNode = nodeExpando(anchor).__pithyNode;\n if (\n contentFragment instanceof DocumentFragment &&\n slotNode?.fallbackChildren\n ) {\n const fallbackCtx = nodeExpando(anchor).__pithyCtx ?? {};\n bindStructuralDirectives(\n slotNode.fallbackChildren,\n contentFragment,\n fallbackCtx,\n disposers\n );\n bindErrorBoundary(contentFragment, fallbackCtx, disposers);\n }\n if (import.meta.env?.DEV && pithyGlobals().PITHY_DEBUG_PROJECTION) {\n console.log(\n `[PithyJS:Projection] Mounting fallback content for slot \"${name}\"`\n );\n }\n } else {\n // No content to mount\n if (import.meta.env?.DEV && pithyGlobals().PITHY_DEBUG_PROJECTION) {\n console.log(`[PithyJS:Projection] No content for slot \"${name}\"`);\n }\n continue;\n }\n\n // Validate content\n if (!contentFragment || contentFragment.childNodes.length === 0) {\n if (import.meta.env?.DEV && pithyGlobals().PITHY_DEBUG_PROJECTION) {\n console.log(\n `[PithyJS:Projection] Empty content for slot \"${name}\" - skipping`\n );\n }\n continue;\n }\n\n // CRITICAL: Collect nodes BEFORE inserting into DOM (for cleanup tracking)\n // Once inserted, the fragment's childNodes will be empty\n const nodesToInsert: Node[] = Array.from(contentFragment.childNodes);\n\n // Mark nodes for tracking\n for (const node of nodesToInsert) {\n expando(node).__projectedContent = isProjectedContent;\n expando(node).__slotName = name;\n }\n\n // Find and remove any existing content for this slot\n const existingNodes: Node[] = [];\n let current = anchor.nextSibling;\n\n while (current) {\n // Stop if we hit another slot anchor\n if (\n current.nodeType === Node.COMMENT_NODE &&\n (current as Comment).textContent?.startsWith('slot:')\n ) {\n break;\n }\n\n // A sibling no projection marked is the component's own markup.\n const meta = expando(current);\n if (meta.__projectedContent === undefined || meta.__slotName !== name) {\n break;\n }\n existingNodes.push(current);\n\n current = current.nextSibling;\n }\n\n // Simple diffing: only replace if content appears different\n // Compare node count and types as a basic heuristic\n const shouldReplace =\n existingNodes.length !== nodesToInsert.length ||\n existingNodes.some(\n (node, i) => node.nodeType !== nodesToInsert[i]?.nodeType\n );\n\n if (!shouldReplace && existingNodes.length > 0) {\n if (import.meta.env?.DEV && pithyGlobals().PITHY_DEBUG_PROJECTION) {\n console.log(\n `[PithyJS:Projection] Content for slot \"${name}\" unchanged - skipping replacement`\n );\n }\n continue;\n }\n\n // Remove existing content\n for (const node of existingNodes) {\n if (node.parentNode) {\n node.parentNode.removeChild(node);\n }\n }\n\n // Insert new content after the anchor comment\n if (!insertBesideHidden(anchor, contentFragment))\n parent?.insertBefore(contentFragment, anchor.nextSibling);\n\n // Track cleanup - remove projected nodes when component unmounts\n disposers.push(() => {\n for (const node of nodesToInsert) {\n if (node.parentNode) {\n node.parentNode.removeChild(node);\n }\n }\n if (import.meta.env?.DEV && pithyGlobals().PITHY_DEBUG_PROJECTION) {\n console.log(`[PithyJS:Projection] Cleaned up slot \"${name}\"`);\n }\n });\n\n if (import.meta.env?.DEV && pithyGlobals().PITHY_DEBUG_PROJECTION) {\n console.log(\n `[PithyJS:Projection] Successfully mounted ${nodesToInsert.length} nodes for slot \"${name}\"`\n );\n }\n }\n\n // DEV: Validate slot usage\n // NOTE: We intentionally do NOT warn about unmatched projected slots here.\n // When a component uses @if/@else with different <slot> elements in each\n // branch (e.g., Show has <slot> in @if and <slot name=\"fallback\"> in @else),\n // the currently-rendered branch may not include all slot targets. The\n // projected \"fallback\" content is legitimate — it will be mounted when\n // the @else branch activates. Warnings here would be false positives\n // and fire repeatedly on every reactive toggle.\n}\n"]}
|