@pithyjs/core 0.1.0-beta.14 → 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 +10 -0
- package/dist/compile/bindSwitchCases.d.ts.map +1 -1
- package/dist/compile/bindSwitchCases.js +14 -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.map +1 -1
- package/dist/compile/binds/bindAfterProjection.js +2 -21
- package/dist/compile/binds/bindAfterProjection.js.map +1 -1
- package/dist/compile/binds/bindComponentsTags.d.ts.map +1 -1
- package/dist/compile/binds/bindComponentsTags.js +32 -10
- 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 +2 -0
- package/dist/compile/compileTemplate.js.map +1 -1
- package/dist/compile/contentProjection.d.ts +3 -0
- package/dist/compile/contentProjection.d.ts.map +1 -1
- package/dist/compile/contentProjection.js +8 -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 +5 -3
- package/dist/compile/renderBranch.js.map +1 -1
- package/dist/compile/renderChildren.d.ts.map +1 -1
- package/dist/compile/renderChildren.js +2 -1
- package/dist/compile/renderChildren.js.map +1 -1
- package/dist/runtime/applyBindings.d.ts.map +1 -1
- package/dist/runtime/applyBindings.js +2 -0
- package/dist/runtime/applyBindings.js.map +1 -1
- package/dist/runtime/bindings/applyComponent.d.ts.map +1 -1
- package/dist/runtime/bindings/applyComponent.js +10 -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 +2 -2
- 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
|
@@ -14,6 +14,7 @@ import { bindForLoops } from './forLoops/bindForLoops.js';
|
|
|
14
14
|
import { bindSwitchCases } from './bindSwitchCases.js';
|
|
15
15
|
import { extractSlotDefs, mountProjection, } from './contentProjection.js';
|
|
16
16
|
import { bindAfterProjection } from './binds/bindAfterProjection.js';
|
|
17
|
+
import { orderByDocument } from './disposeOrder.js';
|
|
17
18
|
/**
|
|
18
19
|
* Runs all structural directive bindings on a fragment.
|
|
19
20
|
*
|
|
@@ -67,6 +68,7 @@ export function compileTemplate(html, context, css, scopeId, importedIdentifiers
|
|
|
67
68
|
}
|
|
68
69
|
// Remaining directives/bindings in carefully chosen order
|
|
69
70
|
bindTemplateDirectives(fragment, context, disposers);
|
|
71
|
+
orderByDocument(disposers);
|
|
70
72
|
}
|
|
71
73
|
catch (err) {
|
|
72
74
|
// Clean up any disposers registered during partial compilation
|
|
@@ -1 +1 @@
|
|
|
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;
|
|
1
|
+
{"version":3,"file":"compileTemplate.js","sourceRoot":"","sources":["../../src/compile/compileTemplate.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAEF,OAAO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,CAAC;AAED;;;;;;;;;;;;;;;GAeG;AACH,qNAAqN;AACrN,MAAM,UAAU,sBAAsB,CACpC,QAA0B,EAC1B,OAAgC,EAChC,SAAyB;IAEzB,sEAAsE;IACtE,iBAAiB,CAAC,QAAQ,EAAE,OAAO,EAAE,SAAS,CAAC,CAAC;IAEhD,sFAAsF;IACtF,iBAAiB,CAAC,QAAQ,EAAE,OAAO,EAAE,SAAS,CAAC,CAAC;IAEhD,uFAAuF;IACvF,oFAAoF;IACpF,iFAAiF;IACjF,kFAAkF;IAClF,yFAAyF;IACzF,MAAM,OAAO,GAAG,CAAC,WAAW,IAAI,OAAO,CAAC,CAAC,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC,CAAC,SAAS,CAE1D,CAAC;IACd,MAAM,QAAQ,GAAG,eAAe,CAAC,QAAQ,CAAC,CAAC;IAC3C,IAAI,QAAQ,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QACxB,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"]}
|
|
@@ -33,6 +33,9 @@ export declare function linkOuterSlotMap(slotMap: SlotMap, ctx: Record<string, u
|
|
|
33
33
|
export declare function collectSlotMap(children: PithyNode[], parentContext: Record<string, unknown>): SlotMap;
|
|
34
34
|
/** @codexApi {"parent":"pithy.feature.content-projection","name":"extractSlotDefs","stability":"stable","signature":"(fragment: DocumentFragment) => SlotDef[]"} */
|
|
35
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;
|
|
36
39
|
/** @codexApi {"parent":"pithy.feature.content-projection","name":"mountProjection","stability":"stable","signature":"(slotDefs: SlotDef[], slotMap: SlotMap, disposers: (() => void)[]) => void"} */
|
|
37
40
|
export declare function mountProjection(slotDefs: SlotDef[], slotMap: SlotMap, disposers: (() => void)[]): void;
|
|
38
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,CAAC;AAY9C;;;GAGG;AACH,MAAM,MAAM,OAAO,GAAG,GAAG,CACvB,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AAE,CAAC,MAAM,IAAI,CAAC,EAAE,EAAE,MAAM,CAAC,EAAE,IAAI,KAAK,gBAAgB,CAChE,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,eAAe,GAAG,MAAM,WAAW,GAAG,gBAAgB,GAAG,SAAS,CAAC;AAE/E,MAAM,WAAW,OAAO;IACtB,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,OAAO,CAAC;IAChB,eAAe,CAAC,EAAE,eAAe,CAAC;CACnC;AAqBD;;;GAGG;AACH,+KAA+K;AAC/K,wBAAgB,YAAY,CAC1B,OAAO,EAAE,OAAO,GAAG,SAAS,GAC3B,OAAO,GAAG,SAAS,CAErB;AAED,uFAAuF;AACvF,sLAAsL;AACtL,wBAAgB,gBAAgB,CAC9B,OAAO,EAAE,OAAO,EAChB,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAC3B,IAAI,CAGN;AAED,gMAAgM;AAChM,wBAAgB,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"}
|
|
@@ -128,6 +128,14 @@ export function extractSlotDefs(fragment) {
|
|
|
128
128
|
}
|
|
129
129
|
return slotDefs;
|
|
130
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
|
+
}
|
|
131
139
|
function inComponentTag(node) {
|
|
132
140
|
for (let el = node.parentElement; el; el = el.parentElement)
|
|
133
141
|
if (nodeExpando(el).__pithyNode?.isComponent)
|
|
@@ -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,MAAM,aAAa,GAAG,IAAI,OAAO,EAAoB,CAAC;AAEtD,SAAS,SAAS,CAAC,GAA4B;IAC7C,OAAO,CAAC,WAAW,IAAI,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC,CAAC,SAAS,CAEzC,CAAC;AAChB,CAAC;AAED;;;GAGG;AACH,+KAA+K;AAC/K,MAAM,UAAU,YAAY,CAC1B,OAA4B;IAE5B,OAAO,OAAO,IAAI,aAAa,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;AAC/C,CAAC;AAED,uFAAuF;AACvF,sLAAsL;AACtL,MAAM,UAAU,gBAAgB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M,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\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\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"]}
|
|
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,MAAM,aAAa,GAAG,IAAI,OAAO,EAAoB,CAAC;AAEtD,SAAS,SAAS,CAAC,GAA4B;IAC7C,OAAO,CAAC,WAAW,IAAI,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC,CAAC,SAAS,CAEzC,CAAC;AAChB,CAAC;AAED;;;GAGG;AACH,+KAA+K;AAC/K,MAAM,UAAU,YAAY,CAC1B,OAA4B;IAE5B,OAAO,OAAO,IAAI,aAAa,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;AAC/C,CAAC;AAED,uFAAuF;AACvF,sLAAsL;AACtL,MAAM,UAAU,gBAAgB,CAC9B,OAAgB,EAChB,GAA4B;IAE5B,MAAM,KAAK,GAAG,SAAS,CAAC,GAAG,CAAC,CAAC;IAC7B,IAAI,KA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,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\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"]}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
/** @codex
|
|
2
|
+
{
|
|
3
|
+
"id": "pithy.runtime.dispose-order",
|
|
4
|
+
"title": "Teardown Order",
|
|
5
|
+
"category": "runtime"
|
|
6
|
+
}
|
|
7
|
+
*/
|
|
8
|
+
/**
|
|
9
|
+
* Marks `dispose` as tearing down what renders at `node`: a component's first
|
|
10
|
+
* node, or a control-flow block's anchor. `orderByDocument` sorts by it.
|
|
11
|
+
*/
|
|
12
|
+
/** @codexApi {"parent":"pithy.runtime.dispose-order","name":"anchorDisposer","stability":"internal","signature":"<T extends () => void>(dispose: T, node: Node | null | undefined) => T"} */
|
|
13
|
+
export declare function anchorDisposer<T extends () => void>(dispose: T, node: Node | null | undefined): T;
|
|
14
|
+
/**
|
|
15
|
+
* Puts the anchored entries of `disposers` in document order, each in a slot
|
|
16
|
+
* an anchored entry held, so running the list backwards destroys later
|
|
17
|
+
* siblings first and children before parents. The binding passes register
|
|
18
|
+
* components and control flow separately, so registration order is not
|
|
19
|
+
* document order. Unanchored entries keep their place.
|
|
20
|
+
*/
|
|
21
|
+
/** @codexApi {"parent":"pithy.runtime.dispose-order","name":"orderByDocument","stability":"internal","signature":"(disposers: (() => void)[]) => void"} */
|
|
22
|
+
export declare function orderByDocument(disposers: (() => void)[]): void;
|
|
23
|
+
/**
|
|
24
|
+
* A control-flow block's teardown as one anchored entry: stops its watcher,
|
|
25
|
+
* then clears its content, so a write during the clear cannot re-enter it.
|
|
26
|
+
*/
|
|
27
|
+
/** @codexApi {"parent":"pithy.runtime.dispose-order","name":"blockDisposer","stability":"internal","signature":"(stop: () => void, clear: () => void, node: Node | null | undefined) => () => void"} */
|
|
28
|
+
export declare function blockDisposer(stop: () => void, clear: () => void, node: Node | null | undefined): () => void;
|
|
29
|
+
/**
|
|
30
|
+
* A rendered component's teardown as one anchored entry: its `destroy()`,
|
|
31
|
+
* then its setup root, which must not move apart when the list is sorted.
|
|
32
|
+
*/
|
|
33
|
+
/** @codexApi {"parent":"pithy.runtime.dispose-order","name":"componentDisposer","stability":"internal","signature":"(destroy: unknown, disposeSetup: (() => void) | undefined, node: Node | null | undefined) => (() => void) | undefined"} */
|
|
34
|
+
export declare function componentDisposer(destroy: unknown, disposeSetup: (() => void) | undefined, node: Node | null | undefined): (() => void) | undefined;
|
|
35
|
+
//# sourceMappingURL=disposeOrder.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"disposeOrder.d.ts","sourceRoot":"","sources":["../../src/compile/disposeOrder.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAIF;;;GAGG;AACH,6LAA6L;AAC7L,wBAAgB,cAAc,CAAC,CAAC,SAAS,MAAM,IAAI,EACjD,OAAO,EAAE,CAAC,EACV,IAAI,EAAE,IAAI,GAAG,IAAI,GAAG,SAAS,GAC5B,CAAC,CAGH;AAED;;;;;;GAMG;AACH,2JAA2J;AAC3J,wBAAgB,eAAe,CAAC,SAAS,EAAE,CAAC,MAAM,IAAI,CAAC,EAAE,GAAG,IAAI,CAiB/D;AAED;;;GAGG;AACH,wMAAwM;AACxM,wBAAgB,aAAa,CAC3B,IAAI,EAAE,MAAM,IAAI,EAChB,KAAK,EAAE,MAAM,IAAI,EACjB,IAAI,EAAE,IAAI,GAAG,IAAI,GAAG,SAAS,GAC5B,MAAM,IAAI,CAQZ;AAED;;;GAGG;AACH,+OAA+O;AAC/O,wBAAgB,iBAAiB,CAC/B,OAAO,EAAE,OAAO,EAChB,YAAY,EAAE,CAAC,MAAM,IAAI,CAAC,GAAG,SAAS,EACtC,IAAI,EAAE,IAAI,GAAG,IAAI,GAAG,SAAS,GAC5B,CAAC,MAAM,IAAI,CAAC,GAAG,SAAS,CAU1B"}
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
/** @codex
|
|
2
|
+
{
|
|
3
|
+
"id": "pithy.runtime.dispose-order",
|
|
4
|
+
"title": "Teardown Order",
|
|
5
|
+
"category": "runtime"
|
|
6
|
+
}
|
|
7
|
+
*/
|
|
8
|
+
const anchors = new WeakMap();
|
|
9
|
+
/**
|
|
10
|
+
* Marks `dispose` as tearing down what renders at `node`: a component's first
|
|
11
|
+
* node, or a control-flow block's anchor. `orderByDocument` sorts by it.
|
|
12
|
+
*/
|
|
13
|
+
/** @codexApi {"parent":"pithy.runtime.dispose-order","name":"anchorDisposer","stability":"internal","signature":"<T extends () => void>(dispose: T, node: Node | null | undefined) => T"} */
|
|
14
|
+
export function anchorDisposer(dispose, node) {
|
|
15
|
+
if (node)
|
|
16
|
+
anchors.set(dispose, node);
|
|
17
|
+
return dispose;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Puts the anchored entries of `disposers` in document order, each in a slot
|
|
21
|
+
* an anchored entry held, so running the list backwards destroys later
|
|
22
|
+
* siblings first and children before parents. The binding passes register
|
|
23
|
+
* components and control flow separately, so registration order is not
|
|
24
|
+
* document order. Unanchored entries keep their place.
|
|
25
|
+
*/
|
|
26
|
+
/** @codexApi {"parent":"pithy.runtime.dispose-order","name":"orderByDocument","stability":"internal","signature":"(disposers: (() => void)[]) => void"} */
|
|
27
|
+
export function orderByDocument(disposers) {
|
|
28
|
+
const slots = [];
|
|
29
|
+
const entries = [];
|
|
30
|
+
disposers.forEach((dispose, i) => {
|
|
31
|
+
const at = anchors.get(dispose);
|
|
32
|
+
if (!at)
|
|
33
|
+
return;
|
|
34
|
+
slots.push(i);
|
|
35
|
+
entries.push({ dispose, at });
|
|
36
|
+
});
|
|
37
|
+
if (slots.length < 2)
|
|
38
|
+
return;
|
|
39
|
+
entries.sort((a, b) => {
|
|
40
|
+
if (a.at === b.at)
|
|
41
|
+
return 0;
|
|
42
|
+
return a.at.compareDocumentPosition(b.at) & Node.DOCUMENT_POSITION_FOLLOWING
|
|
43
|
+
? -1
|
|
44
|
+
: 1;
|
|
45
|
+
});
|
|
46
|
+
slots.forEach((slot, k) => (disposers[slot] = entries[k].dispose));
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* A control-flow block's teardown as one anchored entry: stops its watcher,
|
|
50
|
+
* then clears its content, so a write during the clear cannot re-enter it.
|
|
51
|
+
*/
|
|
52
|
+
/** @codexApi {"parent":"pithy.runtime.dispose-order","name":"blockDisposer","stability":"internal","signature":"(stop: () => void, clear: () => void, node: Node | null | undefined) => () => void"} */
|
|
53
|
+
export function blockDisposer(stop, clear, node) {
|
|
54
|
+
return anchorDisposer(() => {
|
|
55
|
+
try {
|
|
56
|
+
stop();
|
|
57
|
+
}
|
|
58
|
+
finally {
|
|
59
|
+
clear();
|
|
60
|
+
}
|
|
61
|
+
}, node);
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* A rendered component's teardown as one anchored entry: its `destroy()`,
|
|
65
|
+
* then its setup root, which must not move apart when the list is sorted.
|
|
66
|
+
*/
|
|
67
|
+
/** @codexApi {"parent":"pithy.runtime.dispose-order","name":"componentDisposer","stability":"internal","signature":"(destroy: unknown, disposeSetup: (() => void) | undefined, node: Node | null | undefined) => (() => void) | undefined"} */
|
|
68
|
+
export function componentDisposer(destroy, disposeSetup, node) {
|
|
69
|
+
const own = typeof destroy === 'function' ? destroy : null;
|
|
70
|
+
if (!own && !disposeSetup)
|
|
71
|
+
return undefined;
|
|
72
|
+
return anchorDisposer(() => {
|
|
73
|
+
try {
|
|
74
|
+
own?.();
|
|
75
|
+
}
|
|
76
|
+
finally {
|
|
77
|
+
disposeSetup?.();
|
|
78
|
+
}
|
|
79
|
+
}, node);
|
|
80
|
+
}
|
|
81
|
+
//# sourceMappingURL=disposeOrder.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"disposeOrder.js","sourceRoot":"","sources":["../../src/compile/disposeOrder.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAEF,MAAM,OAAO,GAAG,IAAI,OAAO,EAAoB,CAAC;AAEhD;;;GAGG;AACH,6LAA6L;AAC7L,MAAM,UAAU,cAAc,CAC5B,OAAU,EACV,IAA6B;IAE7B,IAAI,IAAI;QAAE,OAAO,CAAC,GAAG,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC;IACrC,OAAO,OAAO,CAAC;AACjB,CAAC;AAED;;;;;;GAMG;AACH,2JAA2J;AAC3J,MAAM,UAAU,eAAe,CAAC,SAAyB;IACvD,MAAM,KAAK,GAAa,EAAE,CAAC;IAC3B,MAAM,OAAO,GAAwC,EAAE,CAAC;IACxD,SAAS,CAAC,OAAO,CAAC,CAAC,OAAO,EAAE,CAAC,EAAE,EAAE;QAC/B,MAAM,EAAE,GAAG,OAAO,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;QAChC,IAAI,CAAC,EAAE;YAAE,OAAO;QAChB,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;QACd,OAAO,CAAC,IAAI,CAAC,EAAE,OAAO,EAAE,EAAE,EAAE,CAAC,CAAC;IAChC,CAAC,CAAC,CAAC;IACH,IAAI,KAAK,CAAC,MAAM,GAAG,CAAC;QAAE,OAAO;I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,CAAC","sourcesContent":["/** @codex\n{\n \"id\": \"pithy.runtime.dispose-order\",\n \"title\": \"Teardown Order\",\n \"category\": \"runtime\"\n}\n*/\n\nconst anchors = new WeakMap<() => void, Node>();\n\n/**\n * Marks `dispose` as tearing down what renders at `node`: a component's first\n * node, or a control-flow block's anchor. `orderByDocument` sorts by it.\n */\n/** @codexApi {\"parent\":\"pithy.runtime.dispose-order\",\"name\":\"anchorDisposer\",\"stability\":\"internal\",\"signature\":\"<T extends () => void>(dispose: T, node: Node | null | undefined) => T\"} */\nexport function anchorDisposer<T extends () => void>(\n dispose: T,\n node: Node | null | undefined\n): T {\n if (node) anchors.set(dispose, node);\n return dispose;\n}\n\n/**\n * Puts the anchored entries of `disposers` in document order, each in a slot\n * an anchored entry held, so running the list backwards destroys later\n * siblings first and children before parents. The binding passes register\n * components and control flow separately, so registration order is not\n * document order. Unanchored entries keep their place.\n */\n/** @codexApi {\"parent\":\"pithy.runtime.dispose-order\",\"name\":\"orderByDocument\",\"stability\":\"internal\",\"signature\":\"(disposers: (() => void)[]) => void\"} */\nexport function orderByDocument(disposers: (() => void)[]): void {\n const slots: number[] = [];\n const entries: { dispose: () => void; at: Node }[] = [];\n disposers.forEach((dispose, i) => {\n const at = anchors.get(dispose);\n if (!at) return;\n slots.push(i);\n entries.push({ dispose, at });\n });\n if (slots.length < 2) return;\n entries.sort((a, b) => {\n if (a.at === b.at) return 0;\n return a.at.compareDocumentPosition(b.at) & Node.DOCUMENT_POSITION_FOLLOWING\n ? -1\n : 1;\n });\n slots.forEach((slot, k) => (disposers[slot] = entries[k].dispose));\n}\n\n/**\n * A control-flow block's teardown as one anchored entry: stops its watcher,\n * then clears its content, so a write during the clear cannot re-enter it.\n */\n/** @codexApi {\"parent\":\"pithy.runtime.dispose-order\",\"name\":\"blockDisposer\",\"stability\":\"internal\",\"signature\":\"(stop: () => void, clear: () => void, node: Node | null | undefined) => () => void\"} */\nexport function blockDisposer(\n stop: () => void,\n clear: () => void,\n node: Node | null | undefined\n): () => void {\n return anchorDisposer(() => {\n try {\n stop();\n } finally {\n clear();\n }\n }, node);\n}\n\n/**\n * A rendered component's teardown as one anchored entry: its `destroy()`,\n * then its setup root, which must not move apart when the list is sorted.\n */\n/** @codexApi {\"parent\":\"pithy.runtime.dispose-order\",\"name\":\"componentDisposer\",\"stability\":\"internal\",\"signature\":\"(destroy: unknown, disposeSetup: (() => void) | undefined, node: Node | null | undefined) => (() => void) | undefined\"} */\nexport function componentDisposer(\n destroy: unknown,\n disposeSetup: (() => void) | undefined,\n node: Node | null | undefined\n): (() => void) | undefined {\n const own = typeof destroy === 'function' ? (destroy as () => void) : null;\n if (!own && !disposeSetup) return undefined;\n return anchorDisposer(() => {\n try {\n own?.();\n } finally {\n disposeSetup?.();\n }\n }, node);\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bindForLoops.d.ts","sourceRoot":"","sources":["../../../src/compile/forLoops/bindForLoops.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAEF,OAAO,KAAK,
|
|
1
|
+
{"version":3,"file":"bindForLoops.d.ts","sourceRoot":"","sources":["../../../src/compile/forLoops/bindForLoops.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAEF,OAAO,EAAuB,KAAK,SAAS,EAAE,MAAM,mBAAmB,CAAC;AAYxE;;;;;;;;;GASG;AACH,qQAAqQ;AACrQ,wBAAgB,YAAY,CAC1B,KAAK,EAAE,SAAS,EAAE,EAClB,MAAM,EAAE,OAAO,GAAG,gBAAgB,EAClC,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAC5B,SAAS,GAAE,CAAC,MAAM,IAAI,CAAC,EAAO,EAC9B,gBAAgB,GAAE,GAAG,CAAC,MAAM,CAAa,GACxC,IAAI,CAwIN"}
|
|
@@ -5,6 +5,7 @@
|
|
|
5
5
|
"category": "directive"
|
|
6
6
|
}
|
|
7
7
|
*/
|
|
8
|
+
import { loopConflictMessage } from '@pithyjs/compiler';
|
|
8
9
|
import { compileExpression } from '../compileExpression.js';
|
|
9
10
|
import { createLoopManager } from './createLoopManager.js';
|
|
10
11
|
import { effect } from '@pithyjs/signals';
|
|
@@ -12,6 +13,8 @@ import { findAllNestedLoopNodes } from './loopTraversal.js';
|
|
|
12
13
|
import { isSSRMode } from '../ssrMode.js';
|
|
13
14
|
import { nodeExpando } from '../nodeExpando.js';
|
|
14
15
|
import { compileTrackBy } from './loopHelpers.js';
|
|
16
|
+
import { anchorDisposer, blockDisposer } from '../disposeOrder.js';
|
|
17
|
+
const warnedConflicts = new WeakSet();
|
|
15
18
|
/**
|
|
16
19
|
* Bind all @for loops found under `rootEl` using the parsed AST nodes.
|
|
17
20
|
*
|
|
@@ -83,6 +86,11 @@ export function bindForLoops(nodes, rootEl, ctx, disposers = [], processedNodeId
|
|
|
83
86
|
}
|
|
84
87
|
if (!node.directives?.for)
|
|
85
88
|
continue; // safety
|
|
89
|
+
if (import.meta.env?.DEV && !warnedConflicts.has(node)) {
|
|
90
|
+
warnedConflicts.add(node);
|
|
91
|
+
for (const name of node.loopConflicts ?? [])
|
|
92
|
+
console.warn(`[pithy] ${loopConflictMessage(node.originalTagName ?? node.tagName ?? '', name)}`);
|
|
93
|
+
}
|
|
86
94
|
const { itemVar, indexVar, collectionExpr } = node.directives.for;
|
|
87
95
|
const trackExpr = node.directives.for.trackBy || node.attrs?.track;
|
|
88
96
|
// Compile collection getter once (closes over ctx)
|
|
@@ -96,8 +104,6 @@ export function bindForLoops(nodes, rootEl, ctx, disposers = [], processedNodeId
|
|
|
96
104
|
itemVar,
|
|
97
105
|
indexVar,
|
|
98
106
|
});
|
|
99
|
-
// Ensure we can dispose everything later
|
|
100
|
-
disposers.push(() => loopManager.destroyAll());
|
|
101
107
|
// Shared logic for evaluating and updating the loop
|
|
102
108
|
function evaluateAndUpdate() {
|
|
103
109
|
try {
|
|
@@ -125,13 +131,14 @@ export function bindForLoops(nodes, rootEl, ctx, disposers = [], processedNodeId
|
|
|
125
131
|
if (isSSRMode()) {
|
|
126
132
|
// SSR mode: evaluate once synchronously, no reactive effects
|
|
127
133
|
evaluateAndUpdate();
|
|
134
|
+
disposers.push(anchorDisposer(() => loopManager.destroyAll(), anchor));
|
|
128
135
|
}
|
|
129
136
|
else {
|
|
130
137
|
// Client mode: reactive subscription for dynamic updates
|
|
131
138
|
const stop = effect(() => {
|
|
132
139
|
evaluateAndUpdate();
|
|
133
140
|
});
|
|
134
|
-
disposers.push(stop);
|
|
141
|
+
disposers.push(blockDisposer(stop, () => loopManager.destroyAll(), anchor));
|
|
135
142
|
}
|
|
136
143
|
}
|
|
137
144
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bindForLoops.js","sourceRoot":"","sources":["../../../src/compile/forLoops/bindForLoops.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAGF,OAAO,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AACzD,OAAO,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AACxD,OAAO,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAC;AAC1C,OAAO,EAAE,sBAAsB,EAAE,MAAM,iBAAiB,CAAC;AACzD,OAAO,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AACvC,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAC7C,OAAO,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AAE/C;;;;;;;;;GASG;AACH,qQAAqQ;AACrQ,MAAM,UAAU,YAAY,CAC1B,KAAkB,EAClB,MAAkC,EAClC,GAA4B,EAC5B,YAA4B,EAAE,EAC9B,mBAAgC,IAAI,GAAG,EAAE;IAEzC,8EAA8E;IAC9E,0FAA0F;IAC1F,8EAA8E;IAC9E,MAAM,OAAO,GAAG,IAAI,GAAG,EAA6B,CAAC;IAErD,6BAA6B;IAC7B,MAAM,CAAC,gBAAgB,EAAE,CAAC,YAAY,CAAC,CAAC,OAAO,CAAC,EAAE,CA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AM,IAAI,GAAG,MAAM,CAAC,GAAG,EAAE;gBACvB,iBAAiB,EAAE,CAAC;YACtB,CAAC,CAAC,CAAC;YACH,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QACvB,CAAC;IACH,CAAC;AACH,CAAC","sourcesContent":["/** @codex\n{\n \"id\": \"pithy.directive.for\",\n \"title\": \"For Loop Directive\",\n \"category\": \"directive\"\n}\n*/\n\nimport type { PithyNode } from '@pithyjs/compiler';\nimport { compileExpression } from '../compileExpression';\nimport { createLoopManager } from './createLoopManager';\nimport { effect } from '@pithyjs/signals';\nimport { findAllNestedLoopNodes } from './loopTraversal';\nimport { isSSRMode } from '../ssrMode';\nimport { nodeExpando } from '../nodeExpando';\nimport { compileTrackBy } from './loopHelpers';\n\n/**\n * Bind all @for loops found under `rootEl` using the parsed AST nodes.\n *\n * Key points:\n * - We build a nodeId -> DOM \"anchor\" map for both element placeholders ([data-pid]) and\n * comment anchors (set by the compiler/runtime) so we can locate the correct insertion point.\n * - We cache nested loop nodes on the AST node (`__nested`) to avoid repeated deep traversals.\n * - trackBy is compiled once per loop node and re-used.\n * - Each loop gets its own LoopManager which does minimal DOM moves and cleanup on dispose.\n */\n/** @codexApi {\"parent\":\"pithy.directive.for\",\"name\":\"bindForLoops\",\"stability\":\"stable\",\"signature\":\"(nodes: PithyNode[], rootEl: Element | DocumentFragment, ctx: Record<string, unknown>, disposers?: (() => void)[], processedNodeIds?: Set<string>) => void\"} */\nexport function bindForLoops(\n nodes: PithyNode[],\n rootEl: Element | DocumentFragment,\n ctx: Record<string, unknown>,\n disposers: (() => void)[] = [],\n processedNodeIds: Set<string> = new Set()\n): void {\n // ---------------------------------------------------------------------------\n // Build a map of nodeId -> DOM anchor (either an element with data-pid or a comment node)\n // ---------------------------------------------------------------------------\n const nodeMap = new Map<string, Element | Comment>();\n\n // Elements: [data-pid=\"...\"]\n rootEl.querySelectorAll?.('[data-pid]').forEach(el => {\n const pid = el.getAttribute('data-pid');\n if (pid) nodeMap.set(pid, el);\n });\n\n // Comment anchors: walk all comment nodes and read the private __nodeId we attach during compile\n const walker = document.createTreeWalker(rootEl, NodeFilter.SHOW_COMMENT);\n let comment: Comment | null;\n while ((comment = walker.nextNode() as Comment | null)) {\n const nodeId = nodeExpando(comment).__nodeId;\n if (nodeId) nodeMap.set(nodeId, comment);\n }\n\n // ---------------------------------------------------------------------------\n // Collect all loop nodes (top-level + nested) with caching per AST node\n // ---------------------------------------------------------------------------\n const allLoopNodes: PithyNode[] = [];\n\n // top-level loops - also check processedNodeIds to skip loops already handled by conditionals\n for (const node of nodes) {\n if (node.type === 'element' && node.directives?.for) {\n // Skip if this loop was already processed (e.g., by handleConditionalChain)\n if (node.nodeId && processedNodeIds.has(node.nodeId)) {\n continue;\n }\n allLoopNodes.push(node);\n }\n }\n\n // nested loops inside each node (cache once per AST node)\n // IMPORTANT: Only process nested loops for non-loop nodes (like conditionals).\n // Loops inside other loops will be handled by the parent loop's createLoopItem.\n for (const node of nodes) {\n // Skip finding nested loops if this node itself is a loop\n // (nested loops inside a loop will be handled by createLoopItem)\n if (node.type === 'element' && node.directives?.for) {\n continue;\n }\n\n const cacheNode = node as PithyNode & { __nested?: PithyNode[] };\n const nested: PithyNode[] =\n cacheNode.__nested ?? (cacheNode.__nested = findAllNestedLoopNodes(node));\n\n if (nested && nested.length) {\n // Filter out any nested loops that were already processed by conditionals\n const unprocessedNested = nested.filter(\n n => !n.nodeId || !processedNodeIds.has(n.nodeId)\n );\n\n allLoopNodes.push(...unprocessedNested);\n }\n }\n\n // ---------------------------------------------------------------------------\n // Bind each loop node found\n // ---------------------------------------------------------------------------\n for (const node of allLoopNodes) {\n const anchor = node.nodeId ? nodeMap.get(node.nodeId) : null;\n\n if (!(anchor instanceof Comment)) {\n continue; // loop anchor must be a comment\n }\n\n if (!node.directives?.for) continue; // safety\n\n const { itemVar, indexVar, collectionExpr } = node.directives.for;\n const trackExpr = node.directives.for.trackBy || node.attrs?.track;\n\n // Compile collection getter once (closes over ctx)\n const getCollection = compileExpression(collectionExpr, ctx);\n\n const getTrackBy = compileTrackBy(trackExpr, itemVar, indexVar, ctx);\n\n // Create a loop manager for this loop anchor\n const loopManager = createLoopManager({\n anchor,\n trackByFn: getTrackBy,\n parentCtx: ctx,\n itemVar,\n indexVar,\n });\n\n // Ensure we can dispose everything later\n disposers.push(() => loopManager.destroyAll());\n\n // Shared logic for evaluating and updating the loop\n function evaluateAndUpdate() {\n try {\n const coll = getCollection();\n if (Array.isArray(coll)) {\n loopManager.update(coll, node);\n } else {\n if (import.meta.env?.DEV) {\n console.warn('[bindForLoops] collection is not an array:', coll, {\n node,\n });\n }\n loopManager.update([], node);\n }\n } catch (err: unknown) {\n // Suppress TDZ/ReferenceErrors for nested loops (they'll be bound when child ctx is ready)\n if (\n !(err instanceof ReferenceError && /is not defined/.test(err.message))\n ) {\n console.error('[bindForLoops] error evaluating collection', err);\n }\n loopManager.update([], node);\n }\n }\n\n if (isSSRMode()) {\n // SSR mode: evaluate once synchronously, no reactive effects\n evaluateAndUpdate();\n } else {\n // Client mode: reactive subscription for dynamic updates\n const stop = effect(() => {\n evaluateAndUpdate();\n });\n disposers.push(stop);\n }\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"bindForLoops.js","sourceRoot":"","sources":["../../../src/compile/forLoops/bindForLoops.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAEF,OAAO,EAAE,mBAAmB,EAAkB,MAAM,mBAAmB,CAAC;AACxE,OAAO,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AACzD,OAAO,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AACxD,OAAO,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAC;AAC1C,OAAO,EAAE,sBAAsB,EAAE,MAAM,iBAAiB,CAAC;AACzD,OAAO,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AACvC,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAC7C,OAAO,E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opConflictMessage, type PithyNode } from '@pithyjs/compiler';\nimport { compileExpression } from '../compileExpression';\nimport { createLoopManager } from './createLoopManager';\nimport { effect } from '@pithyjs/signals';\nimport { findAllNestedLoopNodes } from './loopTraversal';\nimport { isSSRMode } from '../ssrMode';\nimport { nodeExpando } from '../nodeExpando';\nimport { compileTrackBy } from './loopHelpers';\nimport { anchorDisposer, blockDisposer } from '../disposeOrder';\n\nconst warnedConflicts = new WeakSet<PithyNode>();\n\n/**\n * Bind all @for loops found under `rootEl` using the parsed AST nodes.\n *\n * Key points:\n * - We build a nodeId -> DOM \"anchor\" map for both element placeholders ([data-pid]) and\n * comment anchors (set by the compiler/runtime) so we can locate the correct insertion point.\n * - We cache nested loop nodes on the AST node (`__nested`) to avoid repeated deep traversals.\n * - trackBy is compiled once per loop node and re-used.\n * - Each loop gets its own LoopManager which does minimal DOM moves and cleanup on dispose.\n */\n/** @codexApi {\"parent\":\"pithy.directive.for\",\"name\":\"bindForLoops\",\"stability\":\"stable\",\"signature\":\"(nodes: PithyNode[], rootEl: Element | DocumentFragment, ctx: Record<string, unknown>, disposers?: (() => void)[], processedNodeIds?: Set<string>) => void\"} */\nexport function bindForLoops(\n nodes: PithyNode[],\n rootEl: Element | DocumentFragment,\n ctx: Record<string, unknown>,\n disposers: (() => void)[] = [],\n processedNodeIds: Set<string> = new Set()\n): void {\n // ---------------------------------------------------------------------------\n // Build a map of nodeId -> DOM anchor (either an element with data-pid or a comment node)\n // ---------------------------------------------------------------------------\n const nodeMap = new Map<string, Element | Comment>();\n\n // Elements: [data-pid=\"...\"]\n rootEl.querySelectorAll?.('[data-pid]').forEach(el => {\n const pid = el.getAttribute('data-pid');\n if (pid) nodeMap.set(pid, el);\n });\n\n // Comment anchors: walk all comment nodes and read the private __nodeId we attach during compile\n const walker = document.createTreeWalker(rootEl, NodeFilter.SHOW_COMMENT);\n let comment: Comment | null;\n while ((comment = walker.nextNode() as Comment | null)) {\n const nodeId = nodeExpando(comment).__nodeId;\n if (nodeId) nodeMap.set(nodeId, comment);\n }\n\n // ---------------------------------------------------------------------------\n // Collect all loop nodes (top-level + nested) with caching per AST node\n // ---------------------------------------------------------------------------\n const allLoopNodes: PithyNode[] = [];\n\n // top-level loops - also check processedNodeIds to skip loops already handled by conditionals\n for (const node of nodes) {\n if (node.type === 'element' && node.directives?.for) {\n // Skip if this loop was already processed (e.g., by handleConditionalChain)\n if (node.nodeId && processedNodeIds.has(node.nodeId)) {\n continue;\n }\n allLoopNodes.push(node);\n }\n }\n\n // nested loops inside each node (cache once per AST node)\n // IMPORTANT: Only process nested loops for non-loop nodes (like conditionals).\n // Loops inside other loops will be handled by the parent loop's createLoopItem.\n for (const node of nodes) {\n // Skip finding nested loops if this node itself is a loop\n // (nested loops inside a loop will be handled by createLoopItem)\n if (node.type === 'element' && node.directives?.for) {\n continue;\n }\n\n const cacheNode = node as PithyNode & { __nested?: PithyNode[] };\n const nested: PithyNode[] =\n cacheNode.__nested ?? (cacheNode.__nested = findAllNestedLoopNodes(node));\n\n if (nested && nested.length) {\n // Filter out any nested loops that were already processed by conditionals\n const unprocessedNested = nested.filter(\n n => !n.nodeId || !processedNodeIds.has(n.nodeId)\n );\n\n allLoopNodes.push(...unprocessedNested);\n }\n }\n\n // ---------------------------------------------------------------------------\n // Bind each loop node found\n // ---------------------------------------------------------------------------\n for (const node of allLoopNodes) {\n const anchor = node.nodeId ? nodeMap.get(node.nodeId) : null;\n\n if (!(anchor instanceof Comment)) {\n continue; // loop anchor must be a comment\n }\n\n if (!node.directives?.for) continue; // safety\n\n if (import.meta.env?.DEV && !warnedConflicts.has(node)) {\n warnedConflicts.add(node);\n for (const name of node.loopConflicts ?? [])\n console.warn(\n `[pithy] ${loopConflictMessage(node.originalTagName ?? node.tagName ?? '', name)}`\n );\n }\n\n const { itemVar, indexVar, collectionExpr } = node.directives.for;\n const trackExpr = node.directives.for.trackBy || node.attrs?.track;\n\n // Compile collection getter once (closes over ctx)\n const getCollection = compileExpression(collectionExpr, ctx);\n\n const getTrackBy = compileTrackBy(trackExpr, itemVar, indexVar, ctx);\n\n // Create a loop manager for this loop anchor\n const loopManager = createLoopManager({\n anchor,\n trackByFn: getTrackBy,\n parentCtx: ctx,\n itemVar,\n indexVar,\n });\n\n // Shared logic for evaluating and updating the loop\n function evaluateAndUpdate() {\n try {\n const coll = getCollection();\n if (Array.isArray(coll)) {\n loopManager.update(coll, node);\n } else {\n if (import.meta.env?.DEV) {\n console.warn('[bindForLoops] collection is not an array:', coll, {\n node,\n });\n }\n loopManager.update([], node);\n }\n } catch (err: unknown) {\n // Suppress TDZ/ReferenceErrors for nested loops (they'll be bound when child ctx is ready)\n if (\n !(err instanceof ReferenceError && /is not defined/.test(err.message))\n ) {\n console.error('[bindForLoops] error evaluating collection', err);\n }\n loopManager.update([], node);\n }\n }\n\n if (isSSRMode()) {\n // SSR mode: evaluate once synchronously, no reactive effects\n evaluateAndUpdate();\n disposers.push(anchorDisposer(() => loopManager.destroyAll(), anchor));\n } else {\n // Client mode: reactive subscription for dynamic updates\n const stop = effect(() => {\n evaluateAndUpdate();\n });\n disposers.push(\n blockDisposer(stop, () => loopManager.destroyAll(), anchor)\n );\n }\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createLoopManager.d.ts","sourceRoot":"","sources":["../../../src/compile/forLoops/createLoopManager.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAEF;;;;;;;;;;;;GAYG;AAEH,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;AACnD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,8BAA8B,CAAC;AAQjE,OAAO,EACL,WAAW,EAIZ,MAAM,eAAe,CAAC;
|
|
1
|
+
{"version":3,"file":"createLoopManager.d.ts","sourceRoot":"","sources":["../../../src/compile/forLoops/createLoopManager.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAEF;;;;;;;;;;;;GAYG;AAEH,OAAO,KAAK,EAAE,SAAS,EAAE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AAM,EACN,SAAS,EACT,SAAS,EACT,OAAO,EACP,QAAQ,EACR,QAAQ,EACR,QAAQ,EACR,OAAO,EACP,OAAO,EACP,MAAM,EACN,aAAa,EACb,WAAW,GACZ,EAAE,kBAAkB,CAAC,CAAC,CAAC,GAAG,WAAW,CAAC,CAAC,CAAC,CA6YxC"}
|
|
@@ -16,6 +16,7 @@ import { createLoopSignals, updateLoopSignals, createLoopContext, } from './loop
|
|
|
16
16
|
import { safeInsertBefore, markElementsAsLoopGenerated, createItemRange, wrapInRange, detachRange, } from './loopHelpers.js';
|
|
17
17
|
import { findAllNestedLoopNodes } from './loopTraversal.js';
|
|
18
18
|
import { nodeExpando } from '../nodeExpando.js';
|
|
19
|
+
import { orderByDocument } from '../disposeOrder.js';
|
|
19
20
|
/** First real element between [start..end] to use as a flash target. */
|
|
20
21
|
function firstElInRange(start, end) {
|
|
21
22
|
let n = start.nextSibling;
|
|
@@ -108,6 +109,9 @@ function restoreNodeMetadata(source, target, ctx) {
|
|
|
108
109
|
export function createLoopManager({ anchor, trackByFn, parentCtx, itemVar, indexVar, countVar, firstVar, lastVar, evenVar, oddVar, templateNodes, itemFactory, }) {
|
|
109
110
|
// Map of key -> LoopItem (stable across updates as long as key is stable)
|
|
110
111
|
const items = new Map();
|
|
112
|
+
// Row keys in on-screen order. `items` keeps insertion order, which a
|
|
113
|
+
// reorder leaves behind, and the DOM may be detached by teardown time.
|
|
114
|
+
let order = [];
|
|
111
115
|
let cachedNestedLoopNodes = null;
|
|
112
116
|
let cachedTemplateFrag = null;
|
|
113
117
|
/**
|
|
@@ -155,6 +159,7 @@ export function createLoopManager({ anchor, trackByFn, parentCtx, itemVar, index
|
|
|
155
159
|
if (existing)
|
|
156
160
|
syncSignals(existing, item, idx, collection.length);
|
|
157
161
|
});
|
|
162
|
+
order = order.filter(k => items.has(k));
|
|
158
163
|
return;
|
|
159
164
|
}
|
|
160
165
|
// Remove items that no longer exist
|
|
@@ -207,6 +212,7 @@ export function createLoopManager({ anchor, trackByFn, parentCtx, itemVar, index
|
|
|
207
212
|
}
|
|
208
213
|
// Insert everything at once before the anchor
|
|
209
214
|
safeInsertBefore(liveParent, batchFrag, anchor);
|
|
215
|
+
order = newKeys.filter(k => items.has(k));
|
|
210
216
|
return;
|
|
211
217
|
}
|
|
212
218
|
// Minimal-Move Path (LIS)
|
|
@@ -282,6 +288,7 @@ export function createLoopManager({ anchor, trackByFn, parentCtx, itemVar, index
|
|
|
282
288
|
cursor = created.start;
|
|
283
289
|
}
|
|
284
290
|
}
|
|
291
|
+
order = newKeys.filter(k => items.has(k));
|
|
285
292
|
}
|
|
286
293
|
function syncSignals(existing, item, idx, total) {
|
|
287
294
|
const prev = untrack(existing.signals.itemSig);
|
|
@@ -393,6 +400,7 @@ export function createLoopManager({ anchor, trackByFn, parentCtx, itemVar, index
|
|
|
393
400
|
disposers.push(...nestedLoopDisposers);
|
|
394
401
|
// 5d) Bind template directives (text interpolations, events, etc.)
|
|
395
402
|
bindTemplateDirectives(fragmentFromNode, ctx, disposers);
|
|
403
|
+
orderByDocument(disposers);
|
|
396
404
|
// 5e) Mark top-level elements to prevent parent from re-binding their text content
|
|
397
405
|
for (const n of Array.from(fragmentFromNode.childNodes)) {
|
|
398
406
|
if (n.nodeType === Node.ELEMENT_NODE) {
|
|
@@ -404,17 +412,26 @@ export function createLoopManager({ anchor, trackByFn, parentCtx, itemVar, index
|
|
|
404
412
|
const grouped = wrapInRange(start, fragmentFromNode, end);
|
|
405
413
|
// 8) Cleanup function: unsubscribe effects/listeners and detach DOM range
|
|
406
414
|
const destroy = () => {
|
|
407
|
-
for (
|
|
408
|
-
|
|
415
|
+
for (let i = disposers.length - 1; i >= 0; i--)
|
|
416
|
+
disposers[i]();
|
|
409
417
|
disposeRoot();
|
|
410
418
|
detachRange(start, end);
|
|
411
419
|
};
|
|
412
420
|
return { key, fragment: grouped, node, signals, start, end, destroy };
|
|
413
421
|
}
|
|
414
422
|
}
|
|
423
|
+
// Last row first.
|
|
415
424
|
function destroyAll() {
|
|
425
|
+
for (let i = order.length - 1; i >= 0; i--) {
|
|
426
|
+
const item = items.get(order[i]);
|
|
427
|
+
if (!item)
|
|
428
|
+
continue;
|
|
429
|
+
items.delete(order[i]);
|
|
430
|
+
item.destroy();
|
|
431
|
+
}
|
|
416
432
|
items.forEach(item => item.destroy());
|
|
417
433
|
items.clear();
|
|
434
|
+
order = [];
|
|
418
435
|
}
|
|
419
436
|
return { update, destroyAll };
|
|
420
437
|
}
|