@pithyjs/core 0.1.0-beta.14 → 0.1.0-beta.16

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.
Files changed (126) hide show
  1. package/README.md +14 -0
  2. package/dist/compile/bindSwitchCases.d.ts.map +1 -1
  3. package/dist/compile/bindSwitchCases.js +14 -7
  4. package/dist/compile/bindSwitchCases.js.map +1 -1
  5. package/dist/compile/binds/bindAfterComponents.d.ts +4 -0
  6. package/dist/compile/binds/bindAfterComponents.d.ts.map +1 -0
  7. package/dist/compile/binds/bindAfterComponents.js +26 -0
  8. package/dist/compile/binds/bindAfterComponents.js.map +1 -0
  9. package/dist/compile/binds/bindAfterProjection.d.ts.map +1 -1
  10. package/dist/compile/binds/bindAfterProjection.js +2 -21
  11. package/dist/compile/binds/bindAfterProjection.js.map +1 -1
  12. package/dist/compile/binds/bindBoundAttributes.d.ts +4 -0
  13. package/dist/compile/binds/bindBoundAttributes.d.ts.map +1 -1
  14. package/dist/compile/binds/bindBoundAttributes.js +63 -3
  15. package/dist/compile/binds/bindBoundAttributes.js.map +1 -1
  16. package/dist/compile/binds/bindClassDirectives.d.ts.map +1 -1
  17. package/dist/compile/binds/bindClassDirectives.js +3 -2
  18. package/dist/compile/binds/bindClassDirectives.js.map +1 -1
  19. package/dist/compile/binds/bindComponentsTags.d.ts.map +1 -1
  20. package/dist/compile/binds/bindComponentsTags.js +47 -11
  21. package/dist/compile/binds/bindComponentsTags.js.map +1 -1
  22. package/dist/compile/binds/bindDefaultTwoWay.d.ts.map +1 -1
  23. package/dist/compile/binds/bindDefaultTwoWay.js +2 -1
  24. package/dist/compile/binds/bindDefaultTwoWay.js.map +1 -1
  25. package/dist/compile/binds/bindDeferDirectives.d.ts.map +1 -1
  26. package/dist/compile/binds/bindDeferDirectives.js +17 -15
  27. package/dist/compile/binds/bindDeferDirectives.js.map +1 -1
  28. package/dist/compile/binds/bindErrorBoundary.d.ts +11 -1
  29. package/dist/compile/binds/bindErrorBoundary.d.ts.map +1 -1
  30. package/dist/compile/binds/bindErrorBoundary.js +50 -13
  31. package/dist/compile/binds/bindErrorBoundary.js.map +1 -1
  32. package/dist/compile/binds/bindEventHandlers.d.ts.map +1 -1
  33. package/dist/compile/binds/bindEventHandlers.js +2 -1
  34. package/dist/compile/binds/bindEventHandlers.js.map +1 -1
  35. package/dist/compile/binds/bindRefDirectives.d.ts.map +1 -1
  36. package/dist/compile/binds/bindRefDirectives.js +2 -1
  37. package/dist/compile/binds/bindRefDirectives.js.map +1 -1
  38. package/dist/compile/binds/bindStyleDirectives.d.ts.map +1 -1
  39. package/dist/compile/binds/bindStyleDirectives.js +2 -1
  40. package/dist/compile/binds/bindStyleDirectives.js.map +1 -1
  41. package/dist/compile/binds/bindTextInterpolations.d.ts +2 -1
  42. package/dist/compile/binds/bindTextInterpolations.d.ts.map +1 -1
  43. package/dist/compile/binds/bindTextInterpolations.js +25 -14
  44. package/dist/compile/binds/bindTextInterpolations.js.map +1 -1
  45. package/dist/compile/binds/declaredDirective.d.ts +12 -0
  46. package/dist/compile/binds/declaredDirective.d.ts.map +1 -0
  47. package/dist/compile/binds/declaredDirective.js +42 -0
  48. package/dist/compile/binds/declaredDirective.js.map +1 -0
  49. package/dist/compile/binds/forwardedAttrs.d.ts +4 -2
  50. package/dist/compile/binds/forwardedAttrs.d.ts.map +1 -1
  51. package/dist/compile/binds/forwardedAttrs.js +10 -2
  52. package/dist/compile/binds/forwardedAttrs.js.map +1 -1
  53. package/dist/compile/binds/staleRowProps.d.ts +9 -0
  54. package/dist/compile/binds/staleRowProps.d.ts.map +1 -0
  55. package/dist/compile/binds/staleRowProps.js +86 -0
  56. package/dist/compile/binds/staleRowProps.js.map +1 -0
  57. package/dist/compile/compileNodes.d.ts.map +1 -1
  58. package/dist/compile/compileNodes.js +2 -0
  59. package/dist/compile/compileNodes.js.map +1 -1
  60. package/dist/compile/compileTemplate.d.ts.map +1 -1
  61. package/dist/compile/compileTemplate.js +2 -0
  62. package/dist/compile/compileTemplate.js.map +1 -1
  63. package/dist/compile/contentProjection.d.ts +3 -0
  64. package/dist/compile/contentProjection.d.ts.map +1 -1
  65. package/dist/compile/contentProjection.js +8 -0
  66. package/dist/compile/contentProjection.js.map +1 -1
  67. package/dist/compile/disposeOrder.d.ts +35 -0
  68. package/dist/compile/disposeOrder.d.ts.map +1 -0
  69. package/dist/compile/disposeOrder.js +81 -0
  70. package/dist/compile/disposeOrder.js.map +1 -0
  71. package/dist/compile/forLoops/bindForLoops.d.ts +1 -1
  72. package/dist/compile/forLoops/bindForLoops.d.ts.map +1 -1
  73. package/dist/compile/forLoops/bindForLoops.js +10 -3
  74. package/dist/compile/forLoops/bindForLoops.js.map +1 -1
  75. package/dist/compile/forLoops/createLoopManager.d.ts.map +1 -1
  76. package/dist/compile/forLoops/createLoopManager.js +19 -2
  77. package/dist/compile/forLoops/createLoopManager.js.map +1 -1
  78. package/dist/compile/forLoops/loopSignals.d.ts.map +1 -1
  79. package/dist/compile/forLoops/loopSignals.js +15 -1
  80. package/dist/compile/forLoops/loopSignals.js.map +1 -1
  81. package/dist/compile/handleConditionalChain.d.ts.map +1 -1
  82. package/dist/compile/handleConditionalChain.js +2 -3
  83. package/dist/compile/handleConditionalChain.js.map +1 -1
  84. package/dist/compile/nodeExpando.d.ts +6 -0
  85. package/dist/compile/nodeExpando.d.ts.map +1 -1
  86. package/dist/compile/nodeExpando.js.map +1 -1
  87. package/dist/compile/pithyTreeToDom.js +1 -0
  88. package/dist/compile/pithyTreeToDom.js.map +1 -1
  89. package/dist/compile/renderBranch.d.ts +1 -1
  90. package/dist/compile/renderBranch.d.ts.map +1 -1
  91. package/dist/compile/renderBranch.js +5 -3
  92. package/dist/compile/renderBranch.js.map +1 -1
  93. package/dist/compile/renderChildren.d.ts.map +1 -1
  94. package/dist/compile/renderChildren.js +3 -2
  95. package/dist/compile/renderChildren.js.map +1 -1
  96. package/dist/runtime/applyBindings.d.ts.map +1 -1
  97. package/dist/runtime/applyBindings.js +5 -1
  98. package/dist/runtime/applyBindings.js.map +1 -1
  99. package/dist/runtime/bindings/applyComponent.d.ts.map +1 -1
  100. package/dist/runtime/bindings/applyComponent.js +19 -7
  101. package/dist/runtime/bindings/applyComponent.js.map +1 -1
  102. package/dist/runtime/bindings/applyDefer.d.ts.map +1 -1
  103. package/dist/runtime/bindings/applyDefer.js +10 -9
  104. package/dist/runtime/bindings/applyDefer.js.map +1 -1
  105. package/dist/runtime/bindings/applySimple.d.ts +2 -0
  106. package/dist/runtime/bindings/applySimple.d.ts.map +1 -1
  107. package/dist/runtime/bindings/applySimple.js +50 -10
  108. package/dist/runtime/bindings/applySimple.js.map +1 -1
  109. package/dist/runtime/bindings/applyStructural.d.ts.map +1 -1
  110. package/dist/runtime/bindings/applyStructural.js +11 -13
  111. package/dist/runtime/bindings/applyStructural.js.map +1 -1
  112. package/dist/runtime/bindings/helpers.d.ts +7 -0
  113. package/dist/runtime/bindings/helpers.d.ts.map +1 -1
  114. package/dist/runtime/bindings/helpers.js +35 -1
  115. package/dist/runtime/bindings/helpers.js.map +1 -1
  116. package/dist/runtime/bindings/index.d.ts +1 -1
  117. package/dist/runtime/bindings/index.d.ts.map +1 -1
  118. package/dist/runtime/bindings/index.js +1 -1
  119. package/dist/runtime/bindings/index.js.map +1 -1
  120. package/dist/runtime/html.d.ts.map +1 -1
  121. package/dist/runtime/html.js +2 -3
  122. package/dist/runtime/html.js.map +1 -1
  123. package/dist/types/globals.d.ts +2 -0
  124. package/dist/types/globals.d.ts.map +1 -1
  125. package/dist/types/globals.js.map +1 -1
  126. package/package.json +5 -5
@@ -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,MAA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;4BAC/D,IAAI;yBACL,CAAC,CAAC;oBACL,CAAC;oBACD,WAAW,CAAC,MAAM,CAAC,EAAE,EAAE,IAAI,CAAC,CAAC;gBAC/B,CAAC;YACH,CAAC;YAAC,OAAO,GAAY,EAAE,CAAC;gBACtB,2FAA2F;gBAC3F,IACE,CAAC,CAAC,GAAG,YAAY,cAAc,IAAI,gBAAgB,CAAC,IAAI,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,EACtE,CAAC;oBACD,OAAO,CAAC,KAAK,CAAC,4CAA4C,EAAE,GAAG,CAAC,CAAC;gBACnE,CAAC;gBACD,WAAW,CAAC,MAAM,CAAC,EAAE,EAAE,IAAI,CAAC,CAAC;YAC/B,CAAC;QACH,CAAC;QAED,IAAI,SAAS,EAAE,EAAE,CAAC;YAChB,6DAA6D;YAC7D,iBAAiB,EAAE,CAAC;QACtB,CAAC;aAAM,CAAC;YACN,yDAAyD;YACzD,MAAM,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,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AAC/C,OAAO,EAAE,cAAc,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAEhE,MAAM,eAAe,GAAG,IAAI,OAAO,EAAa,CAAC;AAEjD;;;;;;;;;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,CAAC,EAAE;QACnD,MAAM,GAAG,GAAG,EAAE,CAAC,YAAY,CAAC,UAAU,CAAC,CAAC;QACxC,IAAI,GAAG;YAAE,OAAO,CAAC,GAAG,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC;IAChC,CAAC,C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,EAAE,EAAE,CAAC;YAChB,6DAA6D;YAC7D,iBAAiB,EAAE,CAAC;YACpB,SAAS,CAAC,IAAI,CAAC,cAAc,CAAC,GAAG,EAAE,CAAC,WAAW,CAAC,UAAU,EAAE,EAAE,MAAM,CAAC,CAAC,CAAC;QACzE,CAAC;aAAM,CAAC;YACN,yDAAyD;YACzD,MAAM,IAAI,GAAG,MAAM,CAAC,GAAG,EAAE;gBACvB,iBAAiB,EAAE,CAAC;YACtB,CAAC,CAAC,CAAC;YACH,SAAS,CAAC,IAAI,CACZ,aAAa,CAAC,IAAI,EAAE,GAAG,EAAE,CAAC,WAAW,CAAC,UAAU,EAAE,EAAE,MAAM,CAAC,CAC5D,CAAC;QACJ,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 { loopConflictMessage, 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;AAwHvB,YAAY,EAAE,YAAY,EAAE,CAAC;AAE7B,MAAM,WAAW,QAAQ;IACvB,GAAG,EAAE,MAAM,CAAC;IACZ,QAAQ,EAAE,gBAAgB,GAAG,OAAO,CAAC;IACrC,OAAO,EAAE,WAAW,CAAC;IACrB,KAAK,EAAE,OAAO,CAAC;IACf,GAAG,EAAE,OAAO,CAAC;IACb,IAAI,CAAC,EAAE,SAAS,CAAC;IACjB,OAAO,EAAE,MAAM,IAAI,CAAC;CACrB;AAED,MAAM,WAAW,kBAAkB,CAAC,CAAC;IACnC,MAAM,EAAE,OAAO,CAAC;IAChB,SAAS,EAAE,CAAC,IAAI,EAAE,CAAC,EAAE,KAAK,EAAE,MAAM,KAAK,MAAM,CAAC;IAC9C,SAAS,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IACnC,OAAO,EAAE,MAAM,CAAC;IAChB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,aAAa,CAAC,EAAE,SAAS,EAAE,CAAC;IAC5B,WAAW,CAAC,EAAE,YAAY,CAAC;CAC5B;AAED,MAAM,WAAW,WAAW,CAAC,CAAC,GAAG,OAAO;IACtC,MAAM,EAAE,CAAC,UAAU,EAAE,CAAC,EAAE,EAAE,IAAI,CAAC,EAAE,SAAS,KAAK,IAAI,CAAC;IACpD,UAAU,EAAE,MAAM,IAAI,CAAC;CACxB;AAED,8KAA8K;AAC9K,wBAAgB,iBAAiB,CAAC,CAAC,EAAE,EACnC,MAAM,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,CA8XxC"}
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;AAyHvB,YAAY,EAAE,YAAY,EAAE,CAAC;AAE7B,MAAM,WAAW,QAAQ;IACvB,GAAG,EAAE,MAAM,CAAC;IACZ,QAAQ,EAAE,gBAAgB,GAAG,OAAO,CAAC;IACrC,OAAO,EAAE,WAAW,CAAC;IACrB,KAAK,EAAE,OAAO,CAAC;IACf,GAAG,EAAE,OAAO,CAAC;IACb,IAAI,CAAC,EAAE,SAAS,CAAC;IACjB,OAAO,EAAE,MAAM,IAAI,CAAC;CACrB;AAED,MAAM,WAAW,kBAAkB,CAAC,CAAC;IACnC,MAAM,EAAE,OAAO,CAAC;IAChB,SAAS,EAAE,CAAC,IAAI,EAAE,CAAC,EAAE,KAAK,EAAE,MAAM,KAAK,MAAM,CAAC;IAC9C,SAAS,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IACnC,OAAO,EAAE,MAAM,CAAC;IAChB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,aAAa,CAAC,EAAE,SAAS,EAAE,CAAC;IAC5B,WAAW,CAAC,EAAE,YAAY,CAAC;CAC5B;AAED,MAAM,WAAW,WAAW,CAAC,CAAC,GAAG,OAAO;IACtC,MAAM,EAAE,CAAC,UAAU,EAAE,CAAC,EAAE,EAAE,IAAI,CAAC,EAAE,SAAS,KAAK,IAAI,CAAC;IACpD,UAAU,EAAE,MAAM,IAAI,CAAC;CACxB;AAED,8KAA8K;AAC9K,wBAAgB,iBAAiB,CAAC,CAAC,EAAE,EACnC,MAAM,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 (const d of disposers)
408
- d();
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
  }
@@ -1 +1 @@
1
- {"version":3,"file":"createLoopManager.js","sourceRoot":"","sources":["../../../src/compile/forLoops/createLoopManager.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAkBF,OAAO,EAAE,KAAK,EAAE,UAAU,EAAE,OAAO,EAAE,MAAM,kBAAkB,CAAC;AAC9D,OAAO,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AACnD,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAC9C,OAAO,EAAE,WAAW,EAAE,MAAM,iCAAiC,CAAC;AAC9D,OAAO,EAAE,sBAAsB,EAAE,MAAM,IAAI,CAAC;AAC5C,OAAO,EAAE,gBAAgB,EAAE,MAAM,2BAA2B,CAAC;AAC7D,OAAO,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC;AACrD,OAAO,EAEL,iBAAiB,EACjB,iBAAiB,EACjB,iBAAiB,GAClB,MAAM,eAAe,CAAC;AACvB,OAAO,EACL,gBAAgB,EAChB,2BAA2B,EAC3B,eAAe,EACf,WAAW,EACX,WAAW,GACZ,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,sBAAsB,EAAE,MAAM,iBAAiB,CAAC;AACzD,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAM7C,wEAAwE;AACxE,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GAAG,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;IAC5B,MAAM,GAAG,GAAa,EAAE,CAAC;IACzB,KAAK,IAAI,CAAC,GAAG,GAAG,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC,IAAI,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC;QACzC,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;QACX,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;IACX,CAAC;IACD,OAAO,GAAG,CAAC;AACb,CAAC","sourcesContent":["/** @codex\n{\n \"id\": \"pithy.directive.loop-manager\",\n \"title\": \"Advanced Loop Manager\",\n \"category\": \"directive\"\n}\n*/\n\n/**\n * createLoopManager.ts\n *\n * A keyed, range-based list renderer optimized for deep nesting and high churn.\n *\n * Highlights:\n * - Uses [start..end] comment markers to represent each item range (stable DOM, easy move/remove).\n * - Minimal-move reordering using LIS (Longest Increasing Subsequence).\n * - Rebuild fast-path for heavy churn (bulk fragment insert for big updates).\n * - Caches nested loop nodes and tags their hosts to skip parent text-binding passes.\n * - Precise (configurable) visual flashing policy for inserts/moves/updates.\n * - Dev-time duplicate key detection.\n */\n\nimport type { PithyNode } from '@pithyjs/compiler';\nimport type { ChildFactory } from '../../runtime/bindings/types';\nimport { batch, createRoot, untrack } from '@pithyjs/signals';\nimport { pithyTreeToDom } from '../pithyTreeToDom';\nimport { bindForLoops } from './bindForLoops';\nimport { flashUpdate } from '../binds/bindTextInterpolations';\nimport { bindTemplateDirectives } from '..';\nimport { bindConditionals } from '../binds/bindConditionals';\nimport { bindSwitchCases } from '../bindSwitchCases';\nimport {\n LoopSignals,\n createLoopSignals,\n updateLoopSignals,\n createLoopContext,\n} from './loopSignals';\nimport {\n safeInsertBefore,\n markElementsAsLoopGenerated,\n createItemRange,\n wrapInRange,\n detachRange,\n} from './loopHelpers';\nimport { findAllNestedLoopNodes } from './loopTraversal';\nimport { nodeExpando } from '../nodeExpando';\n\n// ── Module-scope helpers (hoisted to avoid re-allocation per update() call) ──\n\ntype FlashUpdatePolicy = 'none' | 'identity' | 'shallow-nested-ignored';\n\n/** First real element between [start..end] to use as a flash target. */\nfunction firstElInRange(start: Comment, end: Comment): Element | null {\n let n: ChildNode | null = start.nextSibling;\n while (n && n !== end) {\n if (n.nodeType === Node.ELEMENT_NODE) return n as Element;\n n = n.nextSibling;\n }\n return null;\n}\n\n/** Extract inclusive [start..end] into a fragment (moving the range intact). */\nfunction collectRange(start: Comment, end: Comment): DocumentFragment {\n const frag = document.createDocumentFragment();\n let n: ChildNode | null = start;\n while (n) {\n const next: ChildNode | null = n.nextSibling;\n frag.appendChild(n);\n if (n === end) break;\n n = next;\n }\n return frag;\n}\n\n/** Compare only shallow, non-object fields to decide if update flash is meaningful. */\nfunction shallowChangedIgnoringObjects(a: unknown, b: unknown): boolean {\n if (a === b) return false;\n if (typeof a !== 'object' || a == null || typeof b !== 'object' || b == null)\n return true;\n\n const ar = a as Record<string, unknown>;\n const br = b as Record<string, unknown>;\n const keys = new Set([...Object.keys(ar), ...Object.keys(br)]);\n for (const k of keys) {\n const va = ar[k];\n const vb = br[k];\n const objA = va && typeof va === 'object';\n const objB = vb && typeof vb === 'object';\n if (objA || objB) continue; // ignore nested objects/arrays (child loops will flash)\n if (va !== vb) return true;\n }\n return false;\n}\n\nfunction shouldFlashUpdate(\n policy: FlashUpdatePolicy,\n prevItem: unknown,\n nextItem: unknown\n): boolean {\n switch (policy) {\n case 'none':\n return false;\n case 'identity':\n return prevItem !== nextItem;\n case 'shallow-nested-ignored':\n return shallowChangedIgnoringObjects(prevItem, nextItem);\n }\n}\n\n/** Clone a cached template fragment and restore JS metadata properties via parallel walk. */\nfunction cloneFragmentWithContext(\n template: DocumentFragment,\n ctx: Record<string, unknown>\n): DocumentFragment {\n const clone = template.cloneNode(true) as DocumentFragment;\n restoreNodeMetadata(template, clone, ctx);\n return clone;\n}\n\n/**\n * Walk source and target trees in parallel, copying metadata from source to target.\n * `__pithyCtx` is set to the new `ctx` (not copied from source).\n */\nfunction restoreNodeMetadata(\n source: Node,\n target: Node,\n ctx: Record<string, unknown>\n): void {\n const src = nodeExpando(source);\n const tgt = nodeExpando(target);\n\n if (src.__pithyCtx !== undefined) tgt.__pithyCtx = ctx;\n if (src.__pithyNode !== undefined) tgt.__pithyNode = src.__pithyNode;\n if (src.__nodeId !== undefined) tgt.__nodeId = src.__nodeId;\n if (src.__slotName !== undefined) tgt.__slotName = src.__slotName;\n\n // Slot fallback factory captures context — recreate with new ctx\n const srcNode = src.__pithyNode;\n if (\n src.__fallbackFactory !== undefined &&\n srcNode?.fallbackChildren?.length\n ) {\n tgt.__fallbackFactory = () =>\n pithyTreeToDom(srcNode.fallbackChildren!, ctx);\n }\n\n // Walk children in parallel (cloneNode preserves child count/order)\n const srcChildren = source.childNodes;\n const tgtChildren = target.childNodes;\n for (let i = 0; i < srcChildren.length; i++) {\n restoreNodeMetadata(srcChildren[i], tgtChildren[i], ctx);\n }\n}\n\n// ── Interfaces ──\n\nexport type { ChildFactory };\n\nexport interface LoopItem {\n key: string;\n fragment: DocumentFragment | Element; // contains [start, ...content..., end]\n signals: LoopSignals;\n start: Comment;\n end: Comment;\n node?: PithyNode; // original AST node (for caching, diagnostics); absent in templateNodes path\n destroy: () => void;\n}\n\nexport interface LoopManagerOptions<T> {\n anchor: Comment; // DOM anchor comment for the whole loop block\n trackByFn: (item: T, index: number) => string; // stable key selector\n parentCtx: Record<string, unknown>; // parent template context\n itemVar: string; // loop item var name (e.g., \"item\")\n indexVar?: string; // loop index var name (e.g., \"i\")\n countVar?: string; // count signal alias (default: \"count\")\n firstVar?: string; // first signal alias (default: \"first\")\n lastVar?: string; // last signal alias (default: \"last\")\n evenVar?: string; // even signal alias (default: \"even\")\n oddVar?: string; // odd signal alias (default: \"odd\")\n templateNodes?: PithyNode[]; // pre-parsed AST children for component-driven loops (e.g. <For>)\n itemFactory?: ChildFactory;\n}\n\nexport interface LoopManager<T = unknown> {\n update: (collection: T[], node?: PithyNode) => void;\n destroyAll: () => void;\n}\n\n/** @codexApi {\"parent\":\"pithy.directive.loop-manager\",\"name\":\"createLoopManager\",\"stability\":\"stable\",\"signature\":\"<T>(options: LoopManagerOptions<T>) => LoopManager<T>\"} */\nexport function createLoopManager<T>({\n anchor,\n trackByFn,\n parentCtx,\n itemVar,\n indexVar,\n countVar,\n firstVar,\n lastVar,\n evenVar,\n oddVar,\n templateNodes,\n itemFactory,\n}: LoopManagerOptions<T>): LoopManager<T> {\n // Map of key -> LoopItem (stable across updates as long as key is stable)\n const items = new Map<string, LoopItem>();\n let cachedNestedLoopNodes: PithyNode[] | null = null;\n let cachedTemplateFrag: DocumentFragment | null = null;\n\n /**\n * Update the loop to reflect the given collection:\n * - Diff keys (remove missing, add new).\n * - If churn is heavy: rebuild in a single batch (fast path).\n * - Else: compute minimal moves (LIS - Longest Increasing Subsequence), update signals, and reorder DOM ranges.\n */\n function update(collection: T[], node?: PithyNode): void {\n const liveParent = anchor.parentNode;\n\n // Flashing Policy\n const FLASH_ON_INSERT = true as const;\n const FLASH_ON_MOVE = false as const; // moves typically aren't \"re-renders\"\n const FLASH_ON_UPDATE: FlashUpdatePolicy = 'shallow-nested-ignored';\n\n // NOTE: We intentionally do NOT wrap the entire update() in batch().\n // createLoopItem builds DOM via pithyTreeToDom which creates reactive\n // effects. If those effects are deferred by an outer batch, the flush\n // can re-trigger the parent effect (in For.ts) causing infinite recursion.\n // Per-item batch() around signal updates is safe and sufficient.\n\n // Key Diff\n const newKeys = collection.map((it, idx) => trackByFn(it, idx));\n const newKeySet = new Set(newKeys);\n\n // Dev-time guard for duplicate keys (can corrupt the map & DOM)\n if (import.meta.env?.DEV) {\n const seen = new Set<string>();\n for (const k of newKeys) {\n if (seen.has(k)) {\n console.warn('[loop] duplicate key detected:', k, {\n node,\n collection,\n });\n }\n seen.add(k);\n }\n }\n\n if (!liveParent) {\n for (const [key, loopItem] of items) {\n if (!newKeySet.has(key)) {\n loopItem.destroy();\n items.delete(key);\n }\n }\n collection.forEach((item, idx) => {\n const existing = items.get(newKeys[idx]);\n if (existing) syncSignals(existing, item, idx, collection.length);\n });\n return;\n }\n\n // Remove items that no longer exist\n let removedCount = 0;\n items.forEach((loopItem, key) => {\n if (!newKeySet.has(key)) {\n loopItem.destroy(); // unsubscribes + removes its DOM range\n items.delete(key);\n removedCount++;\n }\n });\n\n // Count additions\n const addedCount = newKeys.reduce(\n (acc, k) => acc + (items.has(k) ? 0 : 1),\n 0\n );\n\n // Churn heuristic (how much of the list changed)\n const n = newKeys.length;\n const churn = (addedCount + removedCount) / Math.max(1, n);\n\n // Rebuild Fast-Path\n // For very heavy churn, a single rebuild is often faster than many moves.\n const REBUILD_THRESHOLD = 0.5;\n if (churn > REBUILD_THRESHOLD) {\n const batchFrag = document.createDocumentFragment();\n\n for (let idx = 0; idx < collection.length; idx++) {\n const key = newKeys[idx];\n const item = collection[idx];\n const existing = items.get(key);\n\n if (existing) {\n // Update item + positional signals in a single batch to avoid double effect firing\n const prev = syncSignals(existing, item, idx, collection.length);\n if (prev !== item && shouldFlashUpdate(FLASH_ON_UPDATE, prev, item)) {\n const el = firstElInRange(existing.start, existing.end);\n if (el) flashUpdate(el);\n }\n // Move entire range into the batchFrag fragment\n batchFrag.appendChild(collectRange(existing.start, existing.end));\n } else {\n // Create new item\n if (!node && !templateNodes && !itemFactory) continue;\n const created = createLoopItem(\n node,\n item,\n idx,\n collection.length,\n key\n );\n items.set(key, created);\n batchFrag.appendChild(created.fragment);\n if (FLASH_ON_INSERT) {\n const el = firstElInRange(created.start, created.end);\n if (el) flashUpdate(el);\n }\n }\n }\n\n // Insert everything at once before the anchor\n safeInsertBefore(liveParent, batchFrag, anchor);\n return;\n }\n\n // Minimal-Move Path (LIS)\n // Goal: only move items that are out of order (items in LIS keep their place).\n\n // Current DOM order of existing items (sort by document position)\n const existingItems = Array.from(items.values());\n existingItems.sort((a, b) => {\n const pos = a.start.compareDocumentPosition(b.start);\n // if a follows b, put b first (i.e., a after b => return 1)\n if (pos & Node.DOCUMENT_POSITION_FOLLOWING) return -1;\n return 1;\n });\n const oldOrder = existingItems.map(i => i.key);\n\n // Map key -> new position\n const newPos = new Map<string, number>();\n newKeys.forEach((k, i) => newPos.set(k, i));\n\n // Sequence of positions for old items that still exist\n const seq: number[] = [];\n const seqKeys: string[] = [];\n for (const k of oldOrder) {\n const p = newPos.get(k);\n if (p != null) {\n seq.push(p);\n seqKeys.push(k);\n }\n }\n\n // Compute LIS over positions and mark keys to keep (no move)\n const lisIdxs = lis(seq); // indices into seq[]\n const keep = new Set(lisIdxs.map(i => seqKeys[i]));\n\n // Reorder by iterating the new order backwards and inserting before a moving cursor\n let cursor: ChildNode = anchor;\n\n for (let idx = collection.length - 1; idx >= 0; idx--) {\n const item = collection[idx];\n const key = newKeys[idx];\n const existing = items.get(key);\n\n if (existing) {\n // Update item + positional signals in a single batch to avoid double effect firing\n const prev = syncSignals(existing, item, idx, collection.length);\n if (prev !== item && shouldFlashUpdate(FLASH_ON_UPDATE, prev, item)) {\n const el = firstElInRange(existing.start, existing.end);\n if (el) flashUpdate(el);\n }\n\n if (keep.has(key)) {\n // Already in good relative position, don't move; just advance cursor\n cursor = existing.start;\n } else {\n // Move the entire range right before the cursor\n const rangeFrag = collectRange(existing.start, existing.end);\n safeInsertBefore(liveParent, rangeFrag, cursor);\n if (FLASH_ON_MOVE) {\n const el = firstElInRange(existing.start, existing.end);\n if (el) flashUpdate(el);\n }\n cursor = existing.start;\n }\n } else {\n // New item: create and insert before cursor\n if (!node && !templateNodes && !itemFactory) continue;\n const created = createLoopItem(node, item, idx, collection.length, key);\n items.set(key, created);\n safeInsertBefore(liveParent, created.fragment, cursor);\n if (FLASH_ON_INSERT) {\n const el = firstElInRange(created.start, created.end);\n if (el) flashUpdate(el);\n }\n cursor = created.start;\n }\n }\n }\n\n function syncSignals(\n existing: LoopItem,\n item: T,\n idx: number,\n total: number\n ): T {\n const prev = untrack(existing.signals.itemSig) as T;\n batch(() => {\n if (prev !== item) existing.signals.itemSig.set(item);\n updateLoopSignals(existing.signals, idx, total);\n });\n return prev;\n }\n\n /**\n * Create a new LoopItem:\n * - Build the item's DOM from the AST node and local ctx.\n * - Tag top-level elements with __pithyCtx (so events resolve nearest context).\n * - Cache & tag nested loop hosts to skip parent text-binding.\n * - Bind template directives first; then bind nested loops inside this item.\n * - Wrap the item range with [start..end] markers (for move/remove).\n */\n function createLoopItem(\n node: PithyNode | undefined,\n item: T,\n idx: number,\n total: number,\n key: string\n ): LoopItem {\n return createRoot(disposeRoot => buildLoopItem(disposeRoot));\n\n function buildLoopItem(disposeRoot: () => void): LoopItem {\n const signals = createLoopSignals(item, idx, total);\n const ctx = createLoopContext(\n parentCtx,\n signals,\n itemVar,\n indexVar,\n countVar,\n firstVar,\n lastVar,\n evenVar,\n oddVar\n );\n\n if (itemFactory) {\n const built = itemFactory(ctx);\n for (const n of Array.from(built.el.childNodes)) {\n if (n.nodeType === Node.ELEMENT_NODE) nodeExpando(n).__pithyCtx = ctx;\n }\n const { start, end } = createItemRange(key);\n const destroy = () => {\n built.destroy();\n disposeRoot();\n detachRange(start, end);\n };\n return {\n key,\n fragment: wrapInRange(start, built.el, end),\n signals,\n start,\n end,\n destroy,\n };\n }\n\n // 1) Build static DOM for this item\n let fragmentFromNode: DocumentFragment;\n\n if (!cachedTemplateFrag) {\n // First item: build template from AST once and cache it.\n // Use parentCtx so the cached template does not retain per-item signals.\n // restoreNodeMetadata replaces __pithyCtx with the real per-item ctx on each clone.\n if (templateNodes) {\n cachedTemplateFrag = pithyTreeToDom(templateNodes, parentCtx);\n } else {\n const nodeForRender = {\n ...node!,\n directives: { ...node!.directives },\n };\n delete nodeForRender.directives.for;\n cachedTemplateFrag = pithyTreeToDom([nodeForRender], parentCtx);\n markElementsAsLoopGenerated(cachedTemplateFrag, node!);\n }\n // Clone for this item (cache stays pristine)\n fragmentFromNode = cloneFragmentWithContext(cachedTemplateFrag, ctx);\n } else {\n // Subsequent items: clone cached DOM + restore metadata\n fragmentFromNode = cloneFragmentWithContext(cachedTemplateFrag, ctx);\n }\n\n // 2) Tag local context on top-level elements for nearest-ctx event resolution\n for (const n of Array.from(fragmentFromNode.childNodes)) {\n if (n.nodeType === Node.ELEMENT_NODE) nodeExpando(n).__pithyCtx = ctx;\n }\n\n // 3) Find nested loop nodes ONCE per AST source (cache on the node or in closure)\n const astChildren =\n templateNodes ?? (node?.isComponent ? [] : node!.children || []);\n const allNestedLoopNodes: PithyNode[] = templateNodes\n ? (cachedNestedLoopNodes ??= templateNodes.flatMap(tn => {\n // Include root template nodes that themselves carry @for\n // (findAllNestedLoopNodes skips the root, which is correct for\n // the directive path but misses top-level loops in templateNodes)\n const nested = findAllNestedLoopNodes(tn);\n if (tn.directives?.for) nested.unshift(tn);\n return nested;\n }))\n : ((node as PithyNode & { __nested?: PithyNode[] }).__nested ??=\n findAllNestedLoopNodes(node!));\n\n // 4) Build a data-pid => element map for this fragment and tag hosts to skip text-binding\n const pidMap = new Map<string, Element>();\n (fragmentFromNode as Element | DocumentFragment)\n .querySelectorAll?.('[data-pid]')\n .forEach(el => pidMap.set(el.getAttribute('data-pid')!, el as Element));\n\n for (const n of allNestedLoopNodes) {\n if (!n.nodeId) continue;\n const host = pidMap.get(n.nodeId);\n if (host) nodeExpando(host).__pithySkipText = true; // parent text binder must skip this subtree\n }\n\n // 5) Bind structural directives in the same order as compileTemplate\n const disposers: (() => void)[] = [];\n\n // 5a) Switch/case, then conditionals outside switch cases\n const structuralProcessedIds = bindSwitchCases(\n astChildren,\n fragmentFromNode,\n ctx,\n new Set<string>(),\n disposers\n );\n bindConditionals(\n astChildren,\n fragmentFromNode,\n ctx,\n structuralProcessedIds,\n disposers\n );\n\n // 5c) Bind nested loops (pass processedNodeIds to skip loops inside conditionals)\n const nestedLoopDisposers: (() => void)[] = [];\n bindForLoops(\n allNestedLoopNodes,\n fragmentFromNode,\n ctx,\n nestedLoopDisposers,\n structuralProcessedIds\n );\n disposers.push(...nestedLoopDisposers);\n\n // 5d) Bind template directives (text interpolations, events, etc.)\n bindTemplateDirectives(fragmentFromNode, ctx, disposers);\n\n // 5e) Mark top-level elements to prevent parent from re-binding their text content\n for (const n of Array.from(fragmentFromNode.childNodes)) {\n if (n.nodeType === Node.ELEMENT_NODE) {\n nodeExpando(n).__pithySkipText = true;\n }\n }\n\n // 7) Wrap the whole item in [start..end] comments so we can move/remove it as a unit\n const { start, end } = createItemRange(key);\n const grouped = wrapInRange(start, fragmentFromNode, end);\n\n // 8) Cleanup function: unsubscribe effects/listeners and detach DOM range\n const destroy = () => {\n for (const d of disposers) d();\n disposeRoot();\n detachRange(start, end);\n };\n\n return { key, fragment: grouped, node, signals, start, end, destroy };\n }\n }\n\n function destroyAll(): void {\n items.forEach(item => item.destroy());\n items.clear();\n }\n\n return { update, destroyAll };\n}\n\n/**\n * O(n log n) Longest Increasing Subsequence.\n * Given an array of numbers `a`, returns the indices into `a` that form\n * a strictly increasing subsequence with maximal length.\n *\n * We use LIS on the sequence of \"new positions\" for existing items to minimize DOM moves:\n * - Items in the LIS are already in correct relative order and don't need to move.\n * - Only the remaining items are moved to their new positions.\n */\nfunction lis(a: number[]): number[] {\n const res: number[] = []; // res[k] is the index i of the smallest tail of an increasing subsequence of length k+1\n const m: number[] = []; // m[i] points to predecessor index for i in the LIS\n\n for (let i = 0; i < a.length; i++) {\n // binary search in res to find the length of the LIS that a[i] can extend\n let lo = 0,\n hi = res.length;\n while (lo < hi) {\n const mid = (lo + hi) >> 1;\n if (a[res[mid]] < a[i]) lo = mid + 1;\n else hi = mid;\n }\n\n // update res and predecessor\n if (lo === res.length) res.push(i);\n else res[lo] = i;\n\n m[i] = lo ? res[lo - 1] : -1;\n }\n\n // reconstruct LIS indices from res/m\n let k = res[res.length - 1];\n const out: number[] = [];\n for (let i = res.length - 1; i >= 0; i--) {\n out[i] = k;\n k = m[k];\n }\n return out;\n}\n"]}
1
+ {"version":3,"file":"createLoopManager.js","sourceRoot":"","sources":["../../../src/compile/forLoops/createLoopManager.ts"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,CAAC,CAAC,CAAC,CAAC;gBAAE,EAAE,GAAG,GAAG,GAAG,CAAC,CAAC;;gBAChC,EAAE,GAAG,GAAG,CAAC;QAChB,CAAC;QAED,6BAA6B;QAC7B,IAAI,EAAE,KAAK,GAAG,CAAC,MAAM;YAAE,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;;YAC9B,GAAG,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC;QAEjB,CAAC,CAAC,CAAC,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IAC/B,CAAC;IAED,qCAAqC;IACrC,IAAI,CAAC,GAAG,GAAG,CAAC,GAAG,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;IAC5B,MAAM,GAAG,GAAa,EAAE,CAAC;IACzB,KAAK,IAAI,CAAC,GAAG,GAAG,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC,IAAI,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC;QACzC,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;QACX,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;IACX,CAAC;IACD,OAAO,GAAG,CAAC;AACb,CAAC","sourcesContent":["/** @codex\n{\n \"id\": \"pithy.directive.loop-manager\",\n \"title\": \"Advanced Loop Manager\",\n \"category\": \"directive\"\n}\n*/\n\n/**\n * createLoopManager.ts\n *\n * A keyed, range-based list renderer optimized for deep nesting and high churn.\n *\n * Highlights:\n * - Uses [start..end] comment markers to represent each item range (stable DOM, easy move/remove).\n * - Minimal-move reordering using LIS (Longest Increasing Subsequence).\n * - Rebuild fast-path for heavy churn (bulk fragment insert for big updates).\n * - Caches nested loop nodes and tags their hosts to skip parent text-binding passes.\n * - Precise (configurable) visual flashing policy for inserts/moves/updates.\n * - Dev-time duplicate key detection.\n */\n\nimport type { PithyNode } from '@pithyjs/compiler';\nimport type { ChildFactory } from '../../runtime/bindings/types';\nimport { batch, createRoot, untrack } from '@pithyjs/signals';\nimport { pithyTreeToDom } from '../pithyTreeToDom';\nimport { bindForLoops } from './bindForLoops';\nimport { flashUpdate } from '../binds/bindTextInterpolations';\nimport { bindTemplateDirectives } from '..';\nimport { bindConditionals } from '../binds/bindConditionals';\nimport { bindSwitchCases } from '../bindSwitchCases';\nimport {\n LoopSignals,\n createLoopSignals,\n updateLoopSignals,\n createLoopContext,\n} from './loopSignals';\nimport {\n safeInsertBefore,\n markElementsAsLoopGenerated,\n createItemRange,\n wrapInRange,\n detachRange,\n} from './loopHelpers';\nimport { findAllNestedLoopNodes } from './loopTraversal';\nimport { nodeExpando } from '../nodeExpando';\nimport { orderByDocument } from '../disposeOrder';\n\n// ── Module-scope helpers (hoisted to avoid re-allocation per update() call) ──\n\ntype FlashUpdatePolicy = 'none' | 'identity' | 'shallow-nested-ignored';\n\n/** First real element between [start..end] to use as a flash target. */\nfunction firstElInRange(start: Comment, end: Comment): Element | null {\n let n: ChildNode | null = start.nextSibling;\n while (n && n !== end) {\n if (n.nodeType === Node.ELEMENT_NODE) return n as Element;\n n = n.nextSibling;\n }\n return null;\n}\n\n/** Extract inclusive [start..end] into a fragment (moving the range intact). */\nfunction collectRange(start: Comment, end: Comment): DocumentFragment {\n const frag = document.createDocumentFragment();\n let n: ChildNode | null = start;\n while (n) {\n const next: ChildNode | null = n.nextSibling;\n frag.appendChild(n);\n if (n === end) break;\n n = next;\n }\n return frag;\n}\n\n/** Compare only shallow, non-object fields to decide if update flash is meaningful. */\nfunction shallowChangedIgnoringObjects(a: unknown, b: unknown): boolean {\n if (a === b) return false;\n if (typeof a !== 'object' || a == null || typeof b !== 'object' || b == null)\n return true;\n\n const ar = a as Record<string, unknown>;\n const br = b as Record<string, unknown>;\n const keys = new Set([...Object.keys(ar), ...Object.keys(br)]);\n for (const k of keys) {\n const va = ar[k];\n const vb = br[k];\n const objA = va && typeof va === 'object';\n const objB = vb && typeof vb === 'object';\n if (objA || objB) continue; // ignore nested objects/arrays (child loops will flash)\n if (va !== vb) return true;\n }\n return false;\n}\n\nfunction shouldFlashUpdate(\n policy: FlashUpdatePolicy,\n prevItem: unknown,\n nextItem: unknown\n): boolean {\n switch (policy) {\n case 'none':\n return false;\n case 'identity':\n return prevItem !== nextItem;\n case 'shallow-nested-ignored':\n return shallowChangedIgnoringObjects(prevItem, nextItem);\n }\n}\n\n/** Clone a cached template fragment and restore JS metadata properties via parallel walk. */\nfunction cloneFragmentWithContext(\n template: DocumentFragment,\n ctx: Record<string, unknown>\n): DocumentFragment {\n const clone = template.cloneNode(true) as DocumentFragment;\n restoreNodeMetadata(template, clone, ctx);\n return clone;\n}\n\n/**\n * Walk source and target trees in parallel, copying metadata from source to target.\n * `__pithyCtx` is set to the new `ctx` (not copied from source).\n */\nfunction restoreNodeMetadata(\n source: Node,\n target: Node,\n ctx: Record<string, unknown>\n): void {\n const src = nodeExpando(source);\n const tgt = nodeExpando(target);\n\n if (src.__pithyCtx !== undefined) tgt.__pithyCtx = ctx;\n if (src.__pithyNode !== undefined) tgt.__pithyNode = src.__pithyNode;\n if (src.__nodeId !== undefined) tgt.__nodeId = src.__nodeId;\n if (src.__slotName !== undefined) tgt.__slotName = src.__slotName;\n\n // Slot fallback factory captures context — recreate with new ctx\n const srcNode = src.__pithyNode;\n if (\n src.__fallbackFactory !== undefined &&\n srcNode?.fallbackChildren?.length\n ) {\n tgt.__fallbackFactory = () =>\n pithyTreeToDom(srcNode.fallbackChildren!, ctx);\n }\n\n // Walk children in parallel (cloneNode preserves child count/order)\n const srcChildren = source.childNodes;\n const tgtChildren = target.childNodes;\n for (let i = 0; i < srcChildren.length; i++) {\n restoreNodeMetadata(srcChildren[i], tgtChildren[i], ctx);\n }\n}\n\n// ── Interfaces ──\n\nexport type { ChildFactory };\n\nexport interface LoopItem {\n key: string;\n fragment: DocumentFragment | Element; // contains [start, ...content..., end]\n signals: LoopSignals;\n start: Comment;\n end: Comment;\n node?: PithyNode; // original AST node (for caching, diagnostics); absent in templateNodes path\n destroy: () => void;\n}\n\nexport interface LoopManagerOptions<T> {\n anchor: Comment; // DOM anchor comment for the whole loop block\n trackByFn: (item: T, index: number) => string; // stable key selector\n parentCtx: Record<string, unknown>; // parent template context\n itemVar: string; // loop item var name (e.g., \"item\")\n indexVar?: string; // loop index var name (e.g., \"i\")\n countVar?: string; // count signal alias (default: \"count\")\n firstVar?: string; // first signal alias (default: \"first\")\n lastVar?: string; // last signal alias (default: \"last\")\n evenVar?: string; // even signal alias (default: \"even\")\n oddVar?: string; // odd signal alias (default: \"odd\")\n templateNodes?: PithyNode[]; // pre-parsed AST children for component-driven loops (e.g. <For>)\n itemFactory?: ChildFactory;\n}\n\nexport interface LoopManager<T = unknown> {\n update: (collection: T[], node?: PithyNode) => void;\n destroyAll: () => void;\n}\n\n/** @codexApi {\"parent\":\"pithy.directive.loop-manager\",\"name\":\"createLoopManager\",\"stability\":\"stable\",\"signature\":\"<T>(options: LoopManagerOptions<T>) => LoopManager<T>\"} */\nexport function createLoopManager<T>({\n anchor,\n trackByFn,\n parentCtx,\n itemVar,\n indexVar,\n countVar,\n firstVar,\n lastVar,\n evenVar,\n oddVar,\n templateNodes,\n itemFactory,\n}: LoopManagerOptions<T>): LoopManager<T> {\n // Map of key -> LoopItem (stable across updates as long as key is stable)\n const items = new Map<string, LoopItem>();\n // Row keys in on-screen order. `items` keeps insertion order, which a\n // reorder leaves behind, and the DOM may be detached by teardown time.\n let order: string[] = [];\n let cachedNestedLoopNodes: PithyNode[] | null = null;\n let cachedTemplateFrag: DocumentFragment | null = null;\n\n /**\n * Update the loop to reflect the given collection:\n * - Diff keys (remove missing, add new).\n * - If churn is heavy: rebuild in a single batch (fast path).\n * - Else: compute minimal moves (LIS - Longest Increasing Subsequence), update signals, and reorder DOM ranges.\n */\n function update(collection: T[], node?: PithyNode): void {\n const liveParent = anchor.parentNode;\n\n // Flashing Policy\n const FLASH_ON_INSERT = true as const;\n const FLASH_ON_MOVE = false as const; // moves typically aren't \"re-renders\"\n const FLASH_ON_UPDATE: FlashUpdatePolicy = 'shallow-nested-ignored';\n\n // NOTE: We intentionally do NOT wrap the entire update() in batch().\n // createLoopItem builds DOM via pithyTreeToDom which creates reactive\n // effects. If those effects are deferred by an outer batch, the flush\n // can re-trigger the parent effect (in For.ts) causing infinite recursion.\n // Per-item batch() around signal updates is safe and sufficient.\n\n // Key Diff\n const newKeys = collection.map((it, idx) => trackByFn(it, idx));\n const newKeySet = new Set(newKeys);\n\n // Dev-time guard for duplicate keys (can corrupt the map & DOM)\n if (import.meta.env?.DEV) {\n const seen = new Set<string>();\n for (const k of newKeys) {\n if (seen.has(k)) {\n console.warn('[loop] duplicate key detected:', k, {\n node,\n collection,\n });\n }\n seen.add(k);\n }\n }\n\n if (!liveParent) {\n for (const [key, loopItem] of items) {\n if (!newKeySet.has(key)) {\n loopItem.destroy();\n items.delete(key);\n }\n }\n collection.forEach((item, idx) => {\n const existing = items.get(newKeys[idx]);\n if (existing) syncSignals(existing, item, idx, collection.length);\n });\n order = order.filter(k => items.has(k));\n return;\n }\n\n // Remove items that no longer exist\n let removedCount = 0;\n items.forEach((loopItem, key) => {\n if (!newKeySet.has(key)) {\n loopItem.destroy(); // unsubscribes + removes its DOM range\n items.delete(key);\n removedCount++;\n }\n });\n\n // Count additions\n const addedCount = newKeys.reduce(\n (acc, k) => acc + (items.has(k) ? 0 : 1),\n 0\n );\n\n // Churn heuristic (how much of the list changed)\n const n = newKeys.length;\n const churn = (addedCount + removedCount) / Math.max(1, n);\n\n // Rebuild Fast-Path\n // For very heavy churn, a single rebuild is often faster than many moves.\n const REBUILD_THRESHOLD = 0.5;\n if (churn > REBUILD_THRESHOLD) {\n const batchFrag = document.createDocumentFragment();\n\n for (let idx = 0; idx < collection.length; idx++) {\n const key = newKeys[idx];\n const item = collection[idx];\n const existing = items.get(key);\n\n if (existing) {\n // Update item + positional signals in a single batch to avoid double effect firing\n const prev = syncSignals(existing, item, idx, collection.length);\n if (prev !== item && shouldFlashUpdate(FLASH_ON_UPDATE, prev, item)) {\n const el = firstElInRange(existing.start, existing.end);\n if (el) flashUpdate(el);\n }\n // Move entire range into the batchFrag fragment\n batchFrag.appendChild(collectRange(existing.start, existing.end));\n } else {\n // Create new item\n if (!node && !templateNodes && !itemFactory) continue;\n const created = createLoopItem(\n node,\n item,\n idx,\n collection.length,\n key\n );\n items.set(key, created);\n batchFrag.appendChild(created.fragment);\n if (FLASH_ON_INSERT) {\n const el = firstElInRange(created.start, created.end);\n if (el) flashUpdate(el);\n }\n }\n }\n\n // Insert everything at once before the anchor\n safeInsertBefore(liveParent, batchFrag, anchor);\n order = newKeys.filter(k => items.has(k));\n return;\n }\n\n // Minimal-Move Path (LIS)\n // Goal: only move items that are out of order (items in LIS keep their place).\n\n // Current DOM order of existing items (sort by document position)\n const existingItems = Array.from(items.values());\n existingItems.sort((a, b) => {\n const pos = a.start.compareDocumentPosition(b.start);\n // if a follows b, put b first (i.e., a after b => return 1)\n if (pos & Node.DOCUMENT_POSITION_FOLLOWING) return -1;\n return 1;\n });\n const oldOrder = existingItems.map(i => i.key);\n\n // Map key -> new position\n const newPos = new Map<string, number>();\n newKeys.forEach((k, i) => newPos.set(k, i));\n\n // Sequence of positions for old items that still exist\n const seq: number[] = [];\n const seqKeys: string[] = [];\n for (const k of oldOrder) {\n const p = newPos.get(k);\n if (p != null) {\n seq.push(p);\n seqKeys.push(k);\n }\n }\n\n // Compute LIS over positions and mark keys to keep (no move)\n const lisIdxs = lis(seq); // indices into seq[]\n const keep = new Set(lisIdxs.map(i => seqKeys[i]));\n\n // Reorder by iterating the new order backwards and inserting before a moving cursor\n let cursor: ChildNode = anchor;\n\n for (let idx = collection.length - 1; idx >= 0; idx--) {\n const item = collection[idx];\n const key = newKeys[idx];\n const existing = items.get(key);\n\n if (existing) {\n // Update item + positional signals in a single batch to avoid double effect firing\n const prev = syncSignals(existing, item, idx, collection.length);\n if (prev !== item && shouldFlashUpdate(FLASH_ON_UPDATE, prev, item)) {\n const el = firstElInRange(existing.start, existing.end);\n if (el) flashUpdate(el);\n }\n\n if (keep.has(key)) {\n // Already in good relative position, don't move; just advance cursor\n cursor = existing.start;\n } else {\n // Move the entire range right before the cursor\n const rangeFrag = collectRange(existing.start, existing.end);\n safeInsertBefore(liveParent, rangeFrag, cursor);\n if (FLASH_ON_MOVE) {\n const el = firstElInRange(existing.start, existing.end);\n if (el) flashUpdate(el);\n }\n cursor = existing.start;\n }\n } else {\n // New item: create and insert before cursor\n if (!node && !templateNodes && !itemFactory) continue;\n const created = createLoopItem(node, item, idx, collection.length, key);\n items.set(key, created);\n safeInsertBefore(liveParent, created.fragment, cursor);\n if (FLASH_ON_INSERT) {\n const el = firstElInRange(created.start, created.end);\n if (el) flashUpdate(el);\n }\n cursor = created.start;\n }\n }\n order = newKeys.filter(k => items.has(k));\n }\n\n function syncSignals(\n existing: LoopItem,\n item: T,\n idx: number,\n total: number\n ): T {\n const prev = untrack(existing.signals.itemSig) as T;\n batch(() => {\n if (prev !== item) existing.signals.itemSig.set(item);\n updateLoopSignals(existing.signals, idx, total);\n });\n return prev;\n }\n\n /**\n * Create a new LoopItem:\n * - Build the item's DOM from the AST node and local ctx.\n * - Tag top-level elements with __pithyCtx (so events resolve nearest context).\n * - Cache & tag nested loop hosts to skip parent text-binding.\n * - Bind template directives first; then bind nested loops inside this item.\n * - Wrap the item range with [start..end] markers (for move/remove).\n */\n function createLoopItem(\n node: PithyNode | undefined,\n item: T,\n idx: number,\n total: number,\n key: string\n ): LoopItem {\n return createRoot(disposeRoot => buildLoopItem(disposeRoot));\n\n function buildLoopItem(disposeRoot: () => void): LoopItem {\n const signals = createLoopSignals(item, idx, total);\n const ctx = createLoopContext(\n parentCtx,\n signals,\n itemVar,\n indexVar,\n countVar,\n firstVar,\n lastVar,\n evenVar,\n oddVar\n );\n\n if (itemFactory) {\n const built = itemFactory(ctx);\n for (const n of Array.from(built.el.childNodes)) {\n if (n.nodeType === Node.ELEMENT_NODE) nodeExpando(n).__pithyCtx = ctx;\n }\n const { start, end } = createItemRange(key);\n const destroy = () => {\n built.destroy();\n disposeRoot();\n detachRange(start, end);\n };\n return {\n key,\n fragment: wrapInRange(start, built.el, end),\n signals,\n start,\n end,\n destroy,\n };\n }\n\n // 1) Build static DOM for this item\n let fragmentFromNode: DocumentFragment;\n\n if (!cachedTemplateFrag) {\n // First item: build template from AST once and cache it.\n // Use parentCtx so the cached template does not retain per-item signals.\n // restoreNodeMetadata replaces __pithyCtx with the real per-item ctx on each clone.\n if (templateNodes) {\n cachedTemplateFrag = pithyTreeToDom(templateNodes, parentCtx);\n } else {\n const nodeForRender = {\n ...node!,\n directives: { ...node!.directives },\n };\n delete nodeForRender.directives.for;\n cachedTemplateFrag = pithyTreeToDom([nodeForRender], parentCtx);\n markElementsAsLoopGenerated(cachedTemplateFrag, node!);\n }\n // Clone for this item (cache stays pristine)\n fragmentFromNode = cloneFragmentWithContext(cachedTemplateFrag, ctx);\n } else {\n // Subsequent items: clone cached DOM + restore metadata\n fragmentFromNode = cloneFragmentWithContext(cachedTemplateFrag, ctx);\n }\n\n // 2) Tag local context on top-level elements for nearest-ctx event resolution\n for (const n of Array.from(fragmentFromNode.childNodes)) {\n if (n.nodeType === Node.ELEMENT_NODE) nodeExpando(n).__pithyCtx = ctx;\n }\n\n // 3) Find nested loop nodes ONCE per AST source (cache on the node or in closure)\n const astChildren =\n templateNodes ?? (node?.isComponent ? [] : node!.children || []);\n const allNestedLoopNodes: PithyNode[] = templateNodes\n ? (cachedNestedLoopNodes ??= templateNodes.flatMap(tn => {\n // Include root template nodes that themselves carry @for\n // (findAllNestedLoopNodes skips the root, which is correct for\n // the directive path but misses top-level loops in templateNodes)\n const nested = findAllNestedLoopNodes(tn);\n if (tn.directives?.for) nested.unshift(tn);\n return nested;\n }))\n : ((node as PithyNode & { __nested?: PithyNode[] }).__nested ??=\n findAllNestedLoopNodes(node!));\n\n // 4) Build a data-pid => element map for this fragment and tag hosts to skip text-binding\n const pidMap = new Map<string, Element>();\n (fragmentFromNode as Element | DocumentFragment)\n .querySelectorAll?.('[data-pid]')\n .forEach(el => pidMap.set(el.getAttribute('data-pid')!, el as Element));\n\n for (const n of allNestedLoopNodes) {\n if (!n.nodeId) continue;\n const host = pidMap.get(n.nodeId);\n if (host) nodeExpando(host).__pithySkipText = true; // parent text binder must skip this subtree\n }\n\n // 5) Bind structural directives in the same order as compileTemplate\n const disposers: (() => void)[] = [];\n\n // 5a) Switch/case, then conditionals outside switch cases\n const structuralProcessedIds = bindSwitchCases(\n astChildren,\n fragmentFromNode,\n ctx,\n new Set<string>(),\n disposers\n );\n bindConditionals(\n astChildren,\n fragmentFromNode,\n ctx,\n structuralProcessedIds,\n disposers\n );\n\n // 5c) Bind nested loops (pass processedNodeIds to skip loops inside conditionals)\n const nestedLoopDisposers: (() => void)[] = [];\n bindForLoops(\n allNestedLoopNodes,\n fragmentFromNode,\n ctx,\n nestedLoopDisposers,\n structuralProcessedIds\n );\n disposers.push(...nestedLoopDisposers);\n\n // 5d) Bind template directives (text interpolations, events, etc.)\n bindTemplateDirectives(fragmentFromNode, ctx, disposers);\n orderByDocument(disposers);\n\n // 5e) Mark top-level elements to prevent parent from re-binding their text content\n for (const n of Array.from(fragmentFromNode.childNodes)) {\n if (n.nodeType === Node.ELEMENT_NODE) {\n nodeExpando(n).__pithySkipText = true;\n }\n }\n\n // 7) Wrap the whole item in [start..end] comments so we can move/remove it as a unit\n const { start, end } = createItemRange(key);\n const grouped = wrapInRange(start, fragmentFromNode, end);\n\n // 8) Cleanup function: unsubscribe effects/listeners and detach DOM range\n const destroy = () => {\n for (let i = disposers.length - 1; i >= 0; i--) disposers[i]();\n disposeRoot();\n detachRange(start, end);\n };\n\n return { key, fragment: grouped, node, signals, start, end, destroy };\n }\n }\n\n // Last row first.\n function destroyAll(): void {\n for (let i = order.length - 1; i >= 0; i--) {\n const item = items.get(order[i]);\n if (!item) continue;\n items.delete(order[i]);\n item.destroy();\n }\n items.forEach(item => item.destroy());\n items.clear();\n order = [];\n }\n\n return { update, destroyAll };\n}\n\n/**\n * O(n log n) Longest Increasing Subsequence.\n * Given an array of numbers `a`, returns the indices into `a` that form\n * a strictly increasing subsequence with maximal length.\n *\n * We use LIS on the sequence of \"new positions\" for existing items to minimize DOM moves:\n * - Items in the LIS are already in correct relative order and don't need to move.\n * - Only the remaining items are moved to their new positions.\n */\nfunction lis(a: number[]): number[] {\n const res: number[] = []; // res[k] is the index i of the smallest tail of an increasing subsequence of length k+1\n const m: number[] = []; // m[i] points to predecessor index for i in the LIS\n\n for (let i = 0; i < a.length; i++) {\n // binary search in res to find the length of the LIS that a[i] can extend\n let lo = 0,\n hi = res.length;\n while (lo < hi) {\n const mid = (lo + hi) >> 1;\n if (a[res[mid]] < a[i]) lo = mid + 1;\n else hi = mid;\n }\n\n // update res and predecessor\n if (lo === res.length) res.push(i);\n else res[lo] = i;\n\n m[i] = lo ? res[lo - 1] : -1;\n }\n\n // reconstruct LIS indices from res/m\n let k = res[res.length - 1];\n const out: number[] = [];\n for (let i = res.length - 1; i >= 0; i--) {\n out[i] = k;\n k = m[k];\n }\n return out;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"loopSignals.d.ts","sourceRoot":"","sources":["../../../src/compile/forLoops/loopSignals.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAEF,OAAO,EAAiB,MAAM,EAAE,MAAM,kBAAkB,CAAC;AAEzD,MAAM,WAAW,WAAW;IAC1B,OAAO,EAAE,MAAM,CAAC,OAAO,CAAC,CAAC;IACzB,QAAQ,EAAE,MAAM,CAAC,MAAM,CAAC,CAAC;IACzB,MAAM,EAAE,MAAM,CAAC,MAAM,CAAC,CAAC;IACvB,QAAQ,EAAE,MAAM,CAAC,OAAO,CAAC,CAAC;IAC1B,OAAO,EAAE,MAAM,CAAC,OAAO,CAAC,CAAC;IACzB,OAAO,EAAE,MAAM,CAAC,OAAO,CAAC,CAAC;IACzB,MAAM,EAAE,MAAM,CAAC,OAAO,C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I,EAAE,CAAC,EACP,GAAG,EAAE,MAAM,EACX,KAAK,EAAE,MAAM,GACZ,WAAW,CAkBb;AAED,mLAAmL;AACnL;;;GAGG;AACH,wBAAgB,iBAAiB,CAC/B,OAAO,EAAE,WAAW,EACpB,GAAG,EAAE,MAAM,EACX,KAAK,EAAE,MAAM,GACZ,IAAI,CASN;AAED,6UAA6U;AAC7U;;;;GAIG;AACH,wBAAgB,iBAAiB,CAC/B,SAAS,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAClC,OAAO,EAAE,WAAW,EACpB,OAAO,EAAE,MAAM,EACf,QAAQ,CAAC,EAAE,MAAM,EACjB,QAAQ,SAAU,EAClB,QAAQ,SAAU,EAClB,OAAO,SAAS,EAChB,OAAO,SAAS,EAChB,MAAM,SAAQ,GACb,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAuBzB"}
@@ -6,6 +6,7 @@
6
6
  }
7
7
  */
8
8
  import { batch, signal } from '@pithyjs/signals';
9
+ import { rowLocalsOf } from '../binds/staleRowProps.js';
9
10
  /** @codexApi {"parent":"pithy.directive.loop-signals","name":"createLoopSignals","stability":"stable","signature":"<T>(item: T, idx: number, total: number) => LoopSignals"} */
10
11
  /**
11
12
  * Creates all the reactive signals needed for a loop item
@@ -50,7 +51,7 @@ export function updateLoopSignals(signals, idx, total) {
50
51
  * avoid shadowing in nested loops.
51
52
  */
52
53
  export function createLoopContext(parentCtx, signals, itemVar, indexVar, countVar = 'count', firstVar = 'first', lastVar = 'last', evenVar = 'even', oddVar = 'odd') {
53
- return {
54
+ const ctx = {
54
55
  ...parentCtx,
55
56
  [countVar]: signals.countSig,
56
57
  [firstVar]: signals.firstSig,
@@ -60,5 +61,18 @@ export function createLoopContext(parentCtx, signals, itemVar, indexVar, countVa
60
61
  [itemVar]: signals.itemSig,
61
62
  ...(indexVar ? { [indexVar]: signals.idxSig } : {}),
62
63
  };
64
+ if (import.meta.env?.DEV) {
65
+ const locals = new Map(rowLocalsOf(parentCtx));
66
+ locals.set(countVar, signals.countSig);
67
+ locals.set(firstVar, signals.firstSig);
68
+ locals.set(lastVar, signals.lastSig);
69
+ locals.set(evenVar, signals.evenSig);
70
+ locals.set(oddVar, signals.oddSig);
71
+ locals.set(itemVar, signals.itemSig);
72
+ if (indexVar)
73
+ locals.set(indexVar, signals.idxSig);
74
+ ctx.__pithyRowLocals = locals;
75
+ }
76
+ return ctx;
63
77
  }
64
78
  //# sourceMappingURL=loopSignals.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"loopSignals.js","sourceRoot":"","sources":["../../../src/compile/forLoops/loopSignals.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAEF,OAAO,EAAE,KAAK,EAAE,MAAM,EAAU,MAAM,kBAAkB,CAAC;AAYzD,gLAAgL;AAChL;;GAEG;AACH,MAAM,UAAU,iBAAiB,CAC/B,IAAO,EACP,GAAW,EACX,KAAa;IAEb,MAAM,OAAO,GAAG,MAAM,CAAU,IAAI,CAAC,CAAC;IACtC,MAAM,QAAQ,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC;IAC/B,MAAM,MAAM,GAAG,MAAM,CAAC,GAAG,CAAC,CAAC;IAC3B,MAAM,QAAQ,GAAG,MAAM,CAAC,GAAG,KAAK,CAAC,CAAC,CAAC;IACnC,MAAM,OAAO,GAAG,MAAM,CAAC,GAAG,KAAK,KAAK,GAAG,CAAC,CAAC,CAAC;IAC1C,MAAM,OAAO,GAAG,MAAM,CAAC,GAAG,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC;IACtC,MAAM,MAAM,GAAG,MAAM,CAAC,GAAG,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC;IAErC,OAAO;QACL,OAAO;QACP,QAAQ;QACR,MAAM;QACN,QAAQ;QACR,OAAO;QACP,OAAO;QACP,MAAM;KACP,CAAC;AACJ,CAAC;AAED,mLAAmL;AACnL;;;GAGG;AACH,MAAM,UAAU,iBAAiB,CAC/B,OAAoB,EACpB,GAAW,EACX,KA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Content":["/** @codex\n{\n \"id\": \"pithy.directive.loop-signals\",\n \"title\": \"Loop Reactive Signals\", \n \"category\": \"directive\"\n}\n*/\n\nimport { batch, signal, Signal } from '@pithyjs/signals';\n\nexport interface LoopSignals {\n itemSig: Signal<unknown>;\n countSig: Signal<number>;\n idxSig: Signal<number>;\n firstSig: Signal<boolean>;\n lastSig: Signal<boolean>;\n evenSig: Signal<boolean>;\n oddSig: Signal<boolean>;\n}\n\n/** @codexApi {\"parent\":\"pithy.directive.loop-signals\",\"name\":\"createLoopSignals\",\"stability\":\"stable\",\"signature\":\"<T>(item: T, idx: number, total: number) => LoopSignals\"} */\n/**\n * Creates all the reactive signals needed for a loop item\n */\nexport function createLoopSignals<T>(\n item: T,\n idx: number,\n total: number\n): LoopSignals {\n const itemSig = signal<unknown>(item);\n const countSig = signal(total);\n const idxSig = signal(idx);\n const firstSig = signal(idx === 0);\n const lastSig = signal(idx === total - 1);\n const evenSig = signal(idx % 2 === 0);\n const oddSig = signal(idx % 2 === 1);\n\n return {\n itemSig,\n countSig,\n idxSig,\n firstSig,\n lastSig,\n evenSig,\n oddSig,\n };\n}\n\n/** @codexApi {\"parent\":\"pithy.directive.loop-signals\",\"name\":\"updateLoopSignals\",\"stability\":\"stable\",\"signature\":\"(signals: LoopSignals, idx: number, total: number) => void\"} */\n/**\n * Updates all positional signals for a loop item (idx, first, last, even, odd, count)\n * Uses batch() for optimal performance\n */\nexport function updateLoopSignals(\n signals: LoopSignals,\n idx: number,\n total: number\n): void {\n batch(() => {\n signals.countSig.set(total);\n signals.idxSig.set(idx);\n signals.firstSig.set(idx === 0);\n signals.lastSig.set(idx === total - 1);\n signals.evenSig.set(idx % 2 === 0);\n signals.oddSig.set(idx % 2 === 1);\n });\n}\n\n/** @codexApi {\"parent\":\"pithy.directive.loop-signals\",\"name\":\"createLoopContext\",\"stability\":\"stable\",\"signature\":\"(parentCtx: Record<string, unknown>, signals: LoopSignals, itemVar: string, indexVar?: string, countVar?: string, firstVar?: string, lastVar?: string, evenVar?: string, oddVar?: string) => Record<string, unknown>\"} */\n/**\n * Creates the context object for a loop item with all necessary signals.\n * Helper signal names (count, first, last, even, odd) can be aliased to\n * avoid shadowing in nested loops.\n */\nexport function createLoopContext(\n parentCtx: Record<string, unknown>,\n signals: LoopSignals,\n itemVar: string,\n indexVar?: string,\n countVar = 'count',\n firstVar = 'first',\n lastVar = 'last',\n evenVar = 'even',\n oddVar = 'odd'\n): Record<string, unknown> {\n return {\n ...parentCtx,\n [countVar]: signals.countSig,\n [firstVar]: signals.firstSig,\n [lastVar]: signals.lastSig,\n [evenVar]: signals.evenSig,\n [oddVar]: signals.oddSig,\n [itemVar]: signals.itemSig,\n ...(indexVar ? { [indexVar]: signals.idxSig } : {}),\n };\n}\n"]}
1
+ {"version":3,"file":"loopSignals.js","sourceRoot":"","sources":["../../../src/compile/forLoops/loopSignals.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAEF,OAAO,EAAE,KAAK,EAAE,MAAM,EAAU,MAAM,kBAAkB,CAAC;AACzD,OAAO,EAAE,WAAW,EAAkB,MAAM,wBAAwB,CAAC;AAYrE,gLAAgL;AAChL;;GAEG;AACH,MAAM,UAAU,iBAAiB,CAC/B,IAAO,EACP,GAAW,EACX,KAAa;IAEb,MAAM,OAAO,GAAG,MAAM,CAAU,IAAI,CAAC,CAAC;IACtC,MAAM,QAAQ,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC;IAC/B,MAAM,MAAM,GAAG,MAAM,CAAC,GAAG,CAAC,CAAC;IAC3B,MAAM,QAAQ,GAAG,MAAM,CAAC,GAAG,KAAK,CAAC,CAAC,CAAC;IACnC,MAAM,OAAO,GAAG,MAAM,CAAC,GAAG,KAAK,KAAK,GAAG,CAAC,CAAC,CAAC;IAC1C,MAAM,OAAO,GAAG,MAAM,CAAC,GAAG,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC;IACtC,MAAM,MAAM,GAAG,MAAM,CAAC,GAAG,GAAG,CAAC,KAAK,C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EAAE,OAAO,CAAC,MAAM;QACxB,CAAC,OAAO,CAAC,EAAE,OAAO,CAAC,OAAO;QAC1B,GAAG,CAAC,QAAQ,CAAC,CAAC,CAAC,EAAE,CAAC,QAAQ,CAAC,EAAE,OAAO,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;KACpD,CAAC;IACF,IAAI,MAAM,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,EAAE,CAAC;QACzB,MAAM,MAAM,GAAc,IAAI,GAAG,CAAC,WAAW,CAAC,SAAS,CAAC,CAAC,CAAC;QAC1D,MAAM,CAAC,GAAG,CAAC,QAAQ,EAAE,OAAO,CAAC,QAAQ,CAAC,CAAC;QACvC,MAAM,CAAC,GAAG,CAAC,QAAQ,EAAE,OAAO,CAAC,QAAQ,CAAC,CAAC;QACvC,MAAM,CAAC,GAAG,CAAC,OAAO,EAAE,OAAO,CAAC,OAAO,CAAC,CAAC;QACrC,MAAM,CAAC,GAAG,CAAC,OAAO,EAAE,OAAO,CAAC,OAAO,CAAC,CAAC;QACrC,MAAM,CAAC,GAAG,CAAC,MAAM,EAAE,OAAO,CAAC,MAAM,CAAC,CAAC;QACnC,MAAM,CAAC,GAAG,CAAC,OAAO,EAAE,OAAO,CAAC,OAAO,CAAC,CAAC;QACrC,IAAI,QAAQ;YAAE,MAAM,CAAC,GAAG,CAAC,QAAQ,EAAE,OAAO,CAAC,MAAM,CAAC,CAAC;QACnD,GAAG,CAAC,gBAAgB,GAAG,MAAM,CAAC;IAChC,CAAC;IACD,OAAO,GAAG,CAAC;AACb,CAAC","sourcesContent":["/** @codex\n{\n \"id\": \"pithy.directive.loop-signals\",\n \"title\": \"Loop Reactive Signals\", \n \"category\": \"directive\"\n}\n*/\n\nimport { batch, signal, Signal } from '@pithyjs/signals';\nimport { rowLocalsOf, type RowLocals } from '../binds/staleRowProps';\n\nexport interface LoopSignals {\n itemSig: Signal<unknown>;\n countSig: Signal<number>;\n idxSig: Signal<number>;\n firstSig: Signal<boolean>;\n lastSig: Signal<boolean>;\n evenSig: Signal<boolean>;\n oddSig: Signal<boolean>;\n}\n\n/** @codexApi {\"parent\":\"pithy.directive.loop-signals\",\"name\":\"createLoopSignals\",\"stability\":\"stable\",\"signature\":\"<T>(item: T, idx: number, total: number) => LoopSignals\"} */\n/**\n * Creates all the reactive signals needed for a loop item\n */\nexport function createLoopSignals<T>(\n item: T,\n idx: number,\n total: number\n): LoopSignals {\n const itemSig = signal<unknown>(item);\n const countSig = signal(total);\n const idxSig = signal(idx);\n const firstSig = signal(idx === 0);\n const lastSig = signal(idx === total - 1);\n const evenSig = signal(idx % 2 === 0);\n const oddSig = signal(idx % 2 === 1);\n\n return {\n itemSig,\n countSig,\n idxSig,\n firstSig,\n lastSig,\n evenSig,\n oddSig,\n };\n}\n\n/** @codexApi {\"parent\":\"pithy.directive.loop-signals\",\"name\":\"updateLoopSignals\",\"stability\":\"stable\",\"signature\":\"(signals: LoopSignals, idx: number, total: number) => void\"} */\n/**\n * Updates all positional signals for a loop item (idx, first, last, even, odd, count)\n * Uses batch() for optimal performance\n */\nexport function updateLoopSignals(\n signals: LoopSignals,\n idx: number,\n total: number\n): void {\n batch(() => {\n signals.countSig.set(total);\n signals.idxSig.set(idx);\n signals.firstSig.set(idx === 0);\n signals.lastSig.set(idx === total - 1);\n signals.evenSig.set(idx % 2 === 0);\n signals.oddSig.set(idx % 2 === 1);\n });\n}\n\n/** @codexApi {\"parent\":\"pithy.directive.loop-signals\",\"name\":\"createLoopContext\",\"stability\":\"stable\",\"signature\":\"(parentCtx: Record<string, unknown>, signals: LoopSignals, itemVar: string, indexVar?: string, countVar?: string, firstVar?: string, lastVar?: string, evenVar?: string, oddVar?: string) => Record<string, unknown>\"} */\n/**\n * Creates the context object for a loop item with all necessary signals.\n * Helper signal names (count, first, last, even, odd) can be aliased to\n * avoid shadowing in nested loops.\n */\nexport function createLoopContext(\n parentCtx: Record<string, unknown>,\n signals: LoopSignals,\n itemVar: string,\n indexVar?: string,\n countVar = 'count',\n firstVar = 'first',\n lastVar = 'last',\n evenVar = 'even',\n oddVar = 'odd'\n): Record<string, unknown> {\n const ctx: Record<string, unknown> = {\n ...parentCtx,\n [countVar]: signals.countSig,\n [firstVar]: signals.firstSig,\n [lastVar]: signals.lastSig,\n [evenVar]: signals.evenSig,\n [oddVar]: signals.oddSig,\n [itemVar]: signals.itemSig,\n ...(indexVar ? { [indexVar]: signals.idxSig } : {}),\n };\n if (import.meta.env?.DEV) {\n const locals: RowLocals = new Map(rowLocalsOf(parentCtx));\n locals.set(countVar, signals.countSig);\n locals.set(firstVar, signals.firstSig);\n locals.set(lastVar, signals.lastSig);\n locals.set(evenVar, signals.evenSig);\n locals.set(oddVar, signals.oddSig);\n locals.set(itemVar, signals.itemSig);\n if (indexVar) locals.set(indexVar, signals.idxSig);\n ctx.__pithyRowLocals = locals;\n }\n return ctx;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"handleConditionalChain.d.ts","sourceRoot":"","sources":["../../src/compile/handleConditionalChain.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAIF,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;AAInD;;;GAGG;AACH,wRAAwR;AACxR,wBAAgB,sBAAsB,CACpC,QAAQ,EAAE,OAAO,EAAE,EACnB,QAAQ,EAAE,SAAS,EAAE,EACrB,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAC5B,gBAAgB,GAAE,GAAG,CAAC,MAAM,CAAa,EACzC,SAAS,GAAE,CAAC,MAAM,IAAI,CAAC,EAAO,GAC7B,GAAG,CAAC,MAAM,CAAC,CAqHb"}
1
+ {"version":3,"file":"handleConditionalChain.d.ts","sourceRoot":"","sources":["../../src/compile/handleConditionalChain.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAIF,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;AAKnD;;;GAGG;AACH,wRAAwR;AACxR,wBAAgB,sBAAsB,CACpC,QAAQ,EAAE,OAAO,EAAE,EACnB,QAAQ,EAAE,SAAS,EAAE,EACrB,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAC5B,gBAAgB,GAAE,GAAG,CAAC,MAAM,CAAa,EACzC,SAAS,GAAE,CAAC,MAAM,IAAI,CAAC,EAAO,GAC7B,GAAG,CAAC,MAAM,CAAC,CAmHb"}
@@ -7,6 +7,7 @@
7
7
  */
8
8
  import { effect } from '@pithyjs/signals';
9
9
  import { compileExpression } from './compileExpression.js';
10
+ import { blockDisposer } from './disposeOrder.js';
10
11
  import { clearBranch, renderBranch } from './renderBranch.js';
11
12
  import { isSSRMode } from './ssrMode.js';
12
13
  /**
@@ -108,11 +109,9 @@ export function handleConditionalChain(domChain, astChain, ctx, processedNodeIds
108
109
  // 2. When effect stops: clearCurrentBranch is in disposers array
109
110
  // Returning cleanup would cause it to run on EVERY re-run, even when match is same
110
111
  });
111
- // Add cleanup and effect stop to disposers for proper cleanup
112
112
  // Note: We add clearCurrentBranch explicitly because the effect may have
113
113
  // returned undefined on its last run (when match didn't change)
114
- disposers.push(clearCurrentBranch);
115
- disposers.push(stopEffect);
114
+ disposers.push(blockDisposer(stopEffect, clearCurrentBranch, placeholder));
116
115
  }
117
116
  return processedNodeIds;
118
117
  }
@@ -1 +1 @@
1
- {"version":3,"file":"handleConditionalChain.js","sourceRoot":"","sources":["../../src/compile/handleConditionalChain.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAEF,OAAO,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAC;AAC1C,OAAO,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AAExD,OAAO,EAAE,WAAW,EAAE,YAAY,EAAe,MAAM,gBAAgB,CAAC;AACxE,OAAO,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AAEtC;;;GAGG;AACH,wRAAwR;AACxR,MAAM,UAAU,sBAAsB,CACpC,QAAmB,EACnB,QAAqB,EACrB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AAC,GAAG,MAAM,CAAC,SAAS,CAAC,CAAC;IAClD,CAAC;SAAM,CAAC;QACN,mDAAmD;QACnD,qEAAqE;QACrE,IAAI,kBAAkB,GAAG,CAAC,CAAC,CAAC;QAE5B,wEAAwE;QACxE,MAAM,UAAU,GAAG,MAAM,CAAC,GAAG,EAAE;YAC7B,MAAM,UAAU,GAAG,iBAAiB,EAAE,CAAC;YAEvC,4CAA4C;YAC5C,IAAI,UAAU,KAAK,kBAAkB,EAAE,CAAC;gBACtC,OAAO;YACT,CAAC;YAED,kCAAkC;YAClC,kBAAkB,GAAG,UAAU,CAAC;YAEhC,gEAAgE;YAChE,kBAAkB,EAAE,CAAC;YACrB,OAAO,GAAG,mBAAmB,CAAC,UAAU,CAAC,CAAC;YAE1C,4DAA4D;YAC5D,8DAA8D;YAC9D,iEAAiE;YACjE,mFAAmF;QACrF,CAAC,CAAC,CAAC;QAEH,8DAA8D;QAC9D,yEAAyE;QACzE,gEAAgE;QAChE,SAAS,CAAC,IAAI,CAAC,kBAAkB,CAAC,CAAC;QACnC,SAAS,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;IAC7B,CAAC;IAED,OAAO,gBAAgB,CAAC;AAC1B,CAAC","sourcesContent":["/** @codex\n{\n \"id\": \"pithy.directive.conditional-chain\",\n \"title\": \"Conditional Chain Handler\",\n \"category\": \"directive\"\n}\n*/\n\nimport { effect } from '@pithyjs/signals';\nimport { compileExpression } from './compileExpression';\nimport type { PithyNode } from '@pithyjs/compiler';\nimport { clearBranch, renderBranch, type Branch } from './renderBranch';\nimport { isSSRMode } from './ssrMode';\n\n/**\n * Handles rendering and reactivity for an @if/@else-if/@else chain.\n * Returns a Set of all node IDs that were processed (to avoid double-binding).\n */\n/** @codexApi {\"parent\":\"pithy.directive.conditional-chain\",\"name\":\"handleConditionalChain\",\"stability\":\"stable\",\"signature\":\"(domChain: Element[], astChain: PithyNode[], ctx: Record<string, unknown>, processedNodeIds?: Set<string>, disposers?: (() => void)[]) => Set<string>\"} */\nexport function handleConditionalChain(\n domChain: Element[],\n astChain: PithyNode[],\n ctx: Record<string, unknown>,\n processedNodeIds: Set<string> = new Set(),\n disposers: (() => void)[] = []\n): Set<string> {\n // Generate a unique ID for this chain for debugging\n const chainId = Math.random().toString(36).substring(2, 8);\n\n // Create a placeholder comment to mark where our conditional content should go\n const placeholder = document.createComment(`conditional-chain-${chainId}`);\n\n // Insert the placeholder before the first element in the chain\n const firstElement = domChain[0];\n const parent = firstElement.parentNode;\n\n if (!parent) {\n console.error(`[Chain-${chainId}] No parent found for first element`);\n return processedNodeIds;\n }\n\n parent.insertBefore(placeholder, firstElement);\n\n // Remove all original elements from the DOM immediately\n for (const el of domChain) {\n el.remove();\n }\n\n // Note: We don't clone the original DOM elements because cloning loses\n // the structural transformations (e.g., @for loops need Comment anchors).\n // Instead, we rebuild from the AST when needed using pithyTreeToDom.\n\n // Note: We mark nodes as processed AFTER binding each matched branch,\n // not upfront, so that they can be properly bound first.\n\n let current: Branch | null = null;\n\n function clearCurrentBranch() {\n if (current) clearBranch(current);\n current = null;\n }\n\n // Shared logic for evaluating conditions and rendering the matched branch\n function evaluateAndRender() {\n // Find the first matching condition\n let matchIndex = -1;\n\n for (let i = 0; i < astChain.length; i++) {\n const node = astChain[i];\n\n if (node.directives?.if !== undefined) {\n // This is an @if node\n const fn = compileExpression(node.directives.if, ctx, false);\n const result = fn();\n if (result) {\n matchIndex = i;\n break;\n }\n } else if (node.directives?.elseIf !== undefined) {\n // This is an @else-if node\n const fn = compileExpression(node.directives.elseIf, ctx, false);\n if (fn()) {\n matchIndex = i;\n break;\n }\n } else if (node.directives?.else !== undefined) {\n // This is an @else node, which always matches if we reach it\n matchIndex = i;\n break;\n }\n }\n\n return matchIndex;\n }\n\n function renderMatchedBranch(matchIndex: number): Branch | null {\n if (matchIndex < 0 || !placeholder.parentNode) return null;\n return renderBranch(astChain[matchIndex], ctx, placeholder);\n }\n\n if (isSSRMode()) {\n // SSR mode: evaluate once synchronously, no reactive effects\n const matchIndex = evaluateAndRender();\n const branch = renderMatchedBranch(matchIndex);\n // Ensure nested directive disposers created during SSR are added\n // to the parent disposers array for proper cleanup on destroy()\n if (branch) disposers.push(...branch.disposers);\n } else {\n // Client mode: reactive effect for dynamic updates\n // Track the previous match index to avoid unnecessary DOM operations\n let previousMatchIndex = -1;\n\n // Set up the reactive effect and capture the stop function for disposal\n const stopEffect = effect(() => {\n const matchIndex = evaluateAndRender();\n\n // Skip re-insertion if match hasn't changed\n if (matchIndex === previousMatchIndex) {\n return;\n }\n\n // Update the previous match index\n previousMatchIndex = matchIndex;\n\n // Now clear the current branch (only if we're about to rebuild)\n clearCurrentBranch();\n current = renderMatchedBranch(matchIndex);\n\n // Don't return cleanup here - we handle cleanup explicitly:\n // 1. When match changes: clearCurrentBranch() is called above\n // 2. When effect stops: clearCurrentBranch is in disposers array\n // Returning cleanup would cause it to run on EVERY re-run, even when match is same\n });\n\n // Add cleanup and effect stop to disposers for proper cleanup\n // Note: We add clearCurrentBranch explicitly because the effect may have\n // returned undefined on its last run (when match didn't change)\n disposers.push(clearCurrentBranch);\n disposers.push(stopEffect);\n }\n\n return processedNodeIds;\n}\n"]}
1
+ {"version":3,"file":"handleConditionalChain.js","sourceRoot":"","sources":["../../src/compile/handleConditionalChain.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAEF,OAAO,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAC;AAC1C,OAAO,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AAExD,OAAO,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAC;AAC/C,OAAO,EAAE,WAAW,EAAE,YAAY,EAAe,MAAM,gBAAgB,CAAC;AACxE,OAAO,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AAEtC;;;GAGG;AACH,wRAAwR;AACxR,MAAM,UAAU,sBAAsB,CACpC,QAAmB,EACnB,QAAqB,EACrB,GAA4B,EAC5B,mBAAgC,IAAI,GAAG,EAAE,EACzC,Y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AC;SAAM,CAAC;QACN,mDAAmD;QACnD,qEAAqE;QACrE,IAAI,kBAAkB,GAAG,CAAC,CAAC,CAAC;QAE5B,wEAAwE;QACxE,MAAM,UAAU,GAAG,MAAM,CAAC,GAAG,EAAE;YAC7B,MAAM,UAAU,GAAG,iBAAiB,EAAE,CAAC;YAEvC,4CAA4C;YAC5C,IAAI,UAAU,KAAK,kBAAkB,EAAE,CAAC;gBACtC,OAAO;YACT,CAAC;YAED,kCAAkC;YAClC,kBAAkB,GAAG,UAAU,CAAC;YAEhC,gEAAgE;YAChE,kBAAkB,EAAE,CAAC;YACrB,OAAO,GAAG,mBAAmB,CAAC,UAAU,CAAC,CAAC;YAE1C,4DAA4D;YAC5D,8DAA8D;YAC9D,iEAAiE;YACjE,mFAAmF;QACrF,CAAC,CAAC,CAAC;QAEH,yEAAyE;QACzE,gEAAgE;QAChE,SAAS,CAAC,IAAI,CAAC,aAAa,CAAC,UAAU,EAAE,kBAAkB,EAAE,WAAW,CAAC,CAAC,CAAC;IAC7E,CAAC;IAED,OAAO,gBAAgB,CAAC;AAC1B,CAAC","sourcesContent":["/** @codex\n{\n \"id\": \"pithy.directive.conditional-chain\",\n \"title\": \"Conditional Chain Handler\",\n \"category\": \"directive\"\n}\n*/\n\nimport { effect } from '@pithyjs/signals';\nimport { compileExpression } from './compileExpression';\nimport type { PithyNode } from '@pithyjs/compiler';\nimport { blockDisposer } from './disposeOrder';\nimport { clearBranch, renderBranch, type Branch } from './renderBranch';\nimport { isSSRMode } from './ssrMode';\n\n/**\n * Handles rendering and reactivity for an @if/@else-if/@else chain.\n * Returns a Set of all node IDs that were processed (to avoid double-binding).\n */\n/** @codexApi {\"parent\":\"pithy.directive.conditional-chain\",\"name\":\"handleConditionalChain\",\"stability\":\"stable\",\"signature\":\"(domChain: Element[], astChain: PithyNode[], ctx: Record<string, unknown>, processedNodeIds?: Set<string>, disposers?: (() => void)[]) => Set<string>\"} */\nexport function handleConditionalChain(\n domChain: Element[],\n astChain: PithyNode[],\n ctx: Record<string, unknown>,\n processedNodeIds: Set<string> = new Set(),\n disposers: (() => void)[] = []\n): Set<string> {\n // Generate a unique ID for this chain for debugging\n const chainId = Math.random().toString(36).substring(2, 8);\n\n // Create a placeholder comment to mark where our conditional content should go\n const placeholder = document.createComment(`conditional-chain-${chainId}`);\n\n // Insert the placeholder before the first element in the chain\n const firstElement = domChain[0];\n const parent = firstElement.parentNode;\n\n if (!parent) {\n console.error(`[Chain-${chainId}] No parent found for first element`);\n return processedNodeIds;\n }\n\n parent.insertBefore(placeholder, firstElement);\n\n // Remove all original elements from the DOM immediately\n for (const el of domChain) {\n el.remove();\n }\n\n // Note: We don't clone the original DOM elements because cloning loses\n // the structural transformations (e.g., @for loops need Comment anchors).\n // Instead, we rebuild from the AST when needed using pithyTreeToDom.\n\n // Note: We mark nodes as processed AFTER binding each matched branch,\n // not upfront, so that they can be properly bound first.\n\n let current: Branch | null = null;\n\n function clearCurrentBranch() {\n if (current) clearBranch(current);\n current = null;\n }\n\n // Shared logic for evaluating conditions and rendering the matched branch\n function evaluateAndRender() {\n // Find the first matching condition\n let matchIndex = -1;\n\n for (let i = 0; i < astChain.length; i++) {\n const node = astChain[i];\n\n if (node.directives?.if !== undefined) {\n // This is an @if node\n const fn = compileExpression(node.directives.if, ctx, false);\n const result = fn();\n if (result) {\n matchIndex = i;\n break;\n }\n } else if (node.directives?.elseIf !== undefined) {\n // This is an @else-if node\n const fn = compileExpression(node.directives.elseIf, ctx, false);\n if (fn()) {\n matchIndex = i;\n break;\n }\n } else if (node.directives?.else !== undefined) {\n // This is an @else node, which always matches if we reach it\n matchIndex = i;\n break;\n }\n }\n\n return matchIndex;\n }\n\n function renderMatchedBranch(matchIndex: number): Branch | null {\n if (matchIndex < 0 || !placeholder.parentNode) return null;\n return renderBranch(astChain[matchIndex], ctx, placeholder);\n }\n\n if (isSSRMode()) {\n // SSR mode: evaluate once synchronously, no reactive effects\n const matchIndex = evaluateAndRender();\n const branch = renderMatchedBranch(matchIndex);\n // Ensure nested directive disposers created during SSR are added\n // to the parent disposers array for proper cleanup on destroy()\n if (branch) disposers.push(...branch.disposers);\n } else {\n // Client mode: reactive effect for dynamic updates\n // Track the previous match index to avoid unnecessary DOM operations\n let previousMatchIndex = -1;\n\n // Set up the reactive effect and capture the stop function for disposal\n const stopEffect = effect(() => {\n const matchIndex = evaluateAndRender();\n\n // Skip re-insertion if match hasn't changed\n if (matchIndex === previousMatchIndex) {\n return;\n }\n\n // Update the previous match index\n previousMatchIndex = matchIndex;\n\n // Now clear the current branch (only if we're about to rebuild)\n clearCurrentBranch();\n current = renderMatchedBranch(matchIndex);\n\n // Don't return cleanup here - we handle cleanup explicitly:\n // 1. When match changes: clearCurrentBranch() is called above\n // 2. When effect stops: clearCurrentBranch is in disposers array\n // Returning cleanup would cause it to run on EVERY re-run, even when match is same\n });\n\n // Note: We add clearCurrentBranch explicitly because the effect may have\n // returned undefined on its last run (when match didn't change)\n disposers.push(blockDisposer(stopEffect, clearCurrentBranch, placeholder));\n }\n\n return processedNodeIds;\n}\n"]}
@@ -1,4 +1,8 @@
1
1
  import type { PithyNode } from '@pithyjs/compiler';
2
+ export interface StyleOwners {
3
+ strings: string[];
4
+ props: Map<string, [value: string, priority: string]>;
5
+ }
2
6
  export interface NodeExpando {
3
7
  __pithyCtx?: Record<string, unknown>;
4
8
  __pithyNode?: PithyNode;
@@ -12,7 +16,9 @@ export interface NodeExpando {
12
16
  /** Renders a build's placeholder; returns the nodes that replaced it. */
13
17
  __pithyAotMount?: (disposers: (() => void)[]) => Node[];
14
18
  __styleProps?: string[];
19
+ __styleOwners?: StyleOwners;
15
20
  __classToggles?: string[];
21
+ __forwardedDirectives?: Map<string, string>;
16
22
  }
17
23
  export declare function nodeExpando<T extends Node>(node: T): T & NodeExpando;
18
24
  //# sourceMappingURL=nodeExpando.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"nodeExpando.d.ts","sourceRoot":"","sources":["../../src/compile/nodeExpando.ts"],"names":[],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,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,iBAAiB,CAAC,EAAE,MAAM,gBAAgB,CAAC;IAC3C,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB,eAAe,CAAC,EAAE,OAAO,CAAC;IAC1B,mBAAmB,CAAC,EAAE,OAAO,CAAC;IAC9B,0EAA0E;IAC1E,yEAAyE;IACzE,eAAe,CAAC,EAAE,CAAC,SAAS,EAAE,CAAC,MAAM,IAAI,CAAC,EAAE,KAAK,IAAI,EAAE,CAAC;IACxD,YAAY,CAAC,EAAE,MAAM,EAAE,CAAC;IACxB,aAAa,CAAC,EAAE,WAAW,CAAC;IAC5B,cAAc,CAAC,EAAE,MAAM,EAAE,CAAC;IAC1B,qBAAqB,CAAC,EAAE,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CAC7C;AAED,wBAAgB,WAAW,CAAC,CAAC,SAAS,IAAI,EAAE,IAAI,EAAE,CAAC,GAAG,CAAC,GAAG,WAAW,CAEpE"}
@@ -1 +1 @@
1
- {"version":3,"file":"nodeExpando.js","sourceRoot":"","sources":["../../src/compile/nodeExpando.ts"],"names":[],"mappings":"AAkBA,MAAM,UAAU,WAAW,CAAiB,IAAO;IACjD,OAAO,IAAuB,CAAC;AACjC,CAAC","sourcesContent":["import type { PithyNode } from '@pithyjs/compiler';\n\nexport interface NodeExpando {\n __pithyCtx?: Record<string, unknown>;\n __pithyNode?: PithyNode;\n __nodeId?: string;\n __slotName?: string;\n __fallbackFactory?: () => DocumentFragment;\n __nested?: boolean;\n __pithySkipText?: boolean;\n __pithyComponentDom?: boolean;\n /** A build's component placeholder: renders it through the AOT binder. */\n /** Renders a build's placeholder; returns the nodes that replaced it. */\n __pithyAotMount?: (disposers: (() => void)[]) => Node[];\n __styleProps?: string[];\n __classToggles?: string[];\n}\n\nexport function nodeExpando<T extends Node>(node: T): T & NodeExpando {\n return node as T & NodeExpando;\n}\n"]}
1
+ {"version":3,"file":"nodeExpando.js","sourceRoot":"","sources":["../../src/compile/nodeExpando.ts"],"names":[],"mappings":"AAyBA,MAAM,UAAU,WAAW,CAAiB,IAAO;IACjD,OAAO,IAAuB,CAAC;AACjC,CAAC","sourcesContent":["import type { PithyNode } from '@pithyjs/compiler';\n\nexport interface StyleOwners {\n strings: string[];\n props: Map<string, [value: string, priority: string]>;\n}\n\nexport interface NodeExpando {\n __pithyCtx?: Record<string, unknown>;\n __pithyNode?: PithyNode;\n __nodeId?: string;\n __slotName?: string;\n __fallbackFactory?: () => DocumentFragment;\n __nested?: boolean;\n __pithySkipText?: boolean;\n __pithyComponentDom?: boolean;\n /** A build's component placeholder: renders it through the AOT binder. */\n /** Renders a build's placeholder; returns the nodes that replaced it. */\n __pithyAotMount?: (disposers: (() => void)[]) => Node[];\n __styleProps?: string[];\n __styleOwners?: StyleOwners;\n __classToggles?: string[];\n __forwardedDirectives?: Map<string, string>;\n}\n\nexport function nodeExpando<T extends Node>(node: T): T & NodeExpando {\n return node as T & NodeExpando;\n}\n"]}
@@ -28,6 +28,7 @@ function createDomNodeFromPithy(node, context) {
28
28
  if (node.type === 'text') {
29
29
  const textNode = document.createTextNode(node.textContent ?? '');
30
30
  nodeExpando(textNode).__pithyCtx = context;
31
+ nodeExpando(textNode).__pithyNode = node;
31
32
  return textNode;
32
33
  }
33
34
  if (node.type === 'slot') {
@@ -1 +1 @@
1
- {"version":3,"file":"pithyTreeToDom.js","sourceRoot":"","sources":["../../src/compile/pithyTreeToDom.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAEF,OAAO,EACL,QAAQ,EACR,MAAM,EACN,oBAAoB,GAErB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAE5C;;;;GAIG;AACH,uLAAuL;AACvL,MAAM,UAAU,cAAc,CAC5B,KAAkB,EAClB,OAAgC;IAEhC,MAAM,QAAQ,GAAG,QAAQ,CAAC,sBAAsB,EAAE,CAAC;IAEnD,KAAK,MAAM,IAAI,IAAI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;QACtD,CAAC;QAED,+BAA+B;QAC/B,KAAK,MAAM,KAAK,IAAI,IAAI,CAAC,QAAQ,IAAI,EAAE,EAAE,CAAC;YACxC,MAAM,QAAQ,GAAG,sBAAsB,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC;YACxD,IAAI,QAAQ;gBAAE,EAAE,CAAC,WAAW,CAAC,QAAQ,CAAC,CAAC;QACzC,CAAC;QAED,OAAO,EAAE,CAAC;IACZ,CAAC;IAED,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["/** @codex\n{\n \"id\": \"pithy.compiler.dom-tree\",\n \"title\": \"PithyNode to DOM Tree Converter\",\n \"category\": \"compiler\"\n}\n*/\n\nimport {\n SVG_TAGS,\n SVG_NS,\n forEachDirectiveAttr,\n type PithyNode,\n} from '@pithyjs/compiler';\nimport { nodeExpando } from './nodeExpando';\n\n/**\n * Converts a list of PithyNodes into a DocumentFragment of real DOM nodes.\n * Component tags (isComponent: true) are rendered as placeholder elements.\n * No bindings or reactivity are applied here — those are handled in bind*() functions.\n */\n/** @codexApi {\"parent\":\"pithy.compiler.dom-tree\",\"name\":\"pithyTreeToDom\",\"stability\":\"stable\",\"signature\":\"(nodes: PithyNode[], context: Record<string, any>) => DocumentFragment\"} */\nexport function pithyTreeToDom(\n nodes: PithyNode[],\n context: Record<string, unknown>\n): DocumentFragment {\n const fragment = document.createDocumentFragment();\n\n for (const node of nodes) {\n const domNode = createDomNodeFromPithy(node, context);\n if (domNode) {\n fragment.appendChild(domNode);\n }\n }\n\n return fragment;\n}\n\n/** @codexApi {\"parent\":\"pithy.compiler.dom-tree\",\"name\":\"createDomNodeFromPithy\",\"stability\":\"stable\",\"signature\":\"(node: PithyNode, context: Record<string, any>) => Node | null\"} */\nfunction createDomNodeFromPithy(\n node: PithyNode,\n context: Record<string, unknown>\n): Node | null {\n if (node.type === 'text') {\n const textNode = document.createTextNode(node.textContent ?? '');\n nodeExpando(textNode).__pithyCtx = context;\n return textNode;\n }\n\n if (node.type === 'slot') {\n // Create comment anchor for slot\n const slotName = node.slotName || '';\n const anchor = document.createComment(\n `slot:${slotName} pid=\"${node.nodeId}\"`\n );\n\n // Store slot metadata for runtime stitching\n nodeExpando(anchor).__pithyCtx = context;\n nodeExpando(anchor).__nodeId = node.nodeId;\n nodeExpando(anchor).__slotName = slotName;\n nodeExpando(anchor).__pithyNode = node;\n\n // Create fallback fragment factory if fallback content exists\n if (node.fallbackChildren && node.fallbackChildren.length > 0) {\n nodeExpando(anchor).__fallbackFactory = () => {\n return pithyTreeToDom(node.fallbackChildren!, context);\n };\n }\n\n return anchor;\n }\n\n if (node.type === 'element') {\n // For components, create placeholder element (to be upgraded later)\n const tag = node.originalTagName ?? node.tagName ?? 'div';\n\n // SVG elements need to be created in the SVG namespace\n const el = SVG_TAGS.has(tag.toLowerCase())\n ? document.createElementNS(SVG_NS, tag)\n : document.createElement(tag);\n\n nodeExpando(el).__pithyCtx = context;\n\n // Store the PithyNode data for component binding to access:\n // - isComponent flag (to distinguish native elements from components)\n // - original attribute names (for prop name normalization)\n nodeExpando(el).__pithyNode = node;\n\n // Set static attributes\n for (const [name, value] of Object.entries(node.attrs ?? {})) {\n if (name.startsWith('@') || name.startsWith('[')) {\n continue; // Skip PithyJS directive attributes — handled in bind* functions\n }\n // Use original attribute name casing (important for SVG attributes like viewBox)\n const originalName = node.originalAttrs?.[name] || name;\n el.setAttribute(originalName, value);\n }\n\n // @for loop - REPLACE element with anchor\n if (node.directives?.for) {\n // Create a comment node as placeholder\n const placeholder = document.createComment(\n `Placeholder for loop items pid=\"${node.nodeId}\"`\n );\n nodeExpando(placeholder).__pithyCtx = context;\n\n // Store the nodeId on the comment for bindForLoops to find it\n if (node.nodeId) {\n nodeExpando(placeholder).__nodeId = node.nodeId;\n // Loop placeholders are comment nodes — discovered via __nodeId walk, not querySelectorAll (data-pid is for element nodes only)\n }\n\n // Store the original PithyNode structure for nested processing\n nodeExpando(placeholder).__pithyNode = node;\n\n return placeholder;\n }\n\n // Apply directive data-* attributes for runtime binders.\n // Uses the shared mapping from @pithyjs/compiler to stay in sync with AOT codegen.\n if (node.directives) {\n forEachDirectiveAttr(node.directives, (attr, value) => {\n el.setAttribute(attr, value);\n });\n\n // Preserve `slot` as a standard HTML attribute.\n // forEachDirectiveAttr intentionally skips slot (it's consumed by content\n // projection via directives.slot), but downstream binders like\n // bindDeferDirectives need it as a DOM attribute for querySelector lookups\n // (e.g., '[slot=\"placeholder\"]', '[slot=\"error\"]').\n if (node.directives.slot && !el.hasAttribute('slot')) {\n el.setAttribute('slot', node.directives.slot);\n }\n }\n\n // Optional: add dev/debug node ID\n if (node.nodeId) {\n el.setAttribute('data-pid', node.nodeId);\n } else if (node.attrs?.['data-pid']) {\n // Preserve existing data-pid from the original HTML\n el.setAttribute('data-pid', node.attrs['data-pid']);\n }\n\n // Recursively process children\n for (const child of node.children ?? []) {\n const childDom = createDomNodeFromPithy(child, context);\n if (childDom) el.appendChild(childDom);\n }\n\n return el;\n }\n\n return null;\n}\n"]}
1
+ {"version":3,"file":"pithyTreeToDom.js","sourceRoot":"","sources":["../../src/compile/pithyTreeToDom.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAEF,OAAO,EACL,QAAQ,EACR,MAAM,EACN,oBAAoB,GAErB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAE5C;;;;GAIG;AACH,uLAAuL;AACvL,MAAM,UAAU,cAAc,CAC5B,KAAkB,EAClB,OAAgC;IAEhC,MAAM,QAAQ,GAAG,QAAQ,CAAC,sBAAsB,EAAE,CAAC;IAEnD,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE,CAAC;QACzB,MAAM,OAAO,GAAG,sBAAsB,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;QACtD,IAAI,OAAO,EAAE,CAAC;YACZ,QAAQ,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC;QAChC,CAAC;IACH,CAAC;IAED,OAAO,QAAQ,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EAAE,OAAO,CAAC,CAAC;YACxD,IAAI,QAAQ;gBAAE,EAAE,CAAC,WAAW,CAAC,QAAQ,CAAC,CAAC;QACzC,CAAC;QAED,OAAO,EAAE,CAAC;IACZ,CAAC;IAED,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["/** @codex\n{\n \"id\": \"pithy.compiler.dom-tree\",\n \"title\": \"PithyNode to DOM Tree Converter\",\n \"category\": \"compiler\"\n}\n*/\n\nimport {\n SVG_TAGS,\n SVG_NS,\n forEachDirectiveAttr,\n type PithyNode,\n} from '@pithyjs/compiler';\nimport { nodeExpando } from './nodeExpando';\n\n/**\n * Converts a list of PithyNodes into a DocumentFragment of real DOM nodes.\n * Component tags (isComponent: true) are rendered as placeholder elements.\n * No bindings or reactivity are applied here — those are handled in bind*() functions.\n */\n/** @codexApi {\"parent\":\"pithy.compiler.dom-tree\",\"name\":\"pithyTreeToDom\",\"stability\":\"stable\",\"signature\":\"(nodes: PithyNode[], context: Record<string, any>) => DocumentFragment\"} */\nexport function pithyTreeToDom(\n nodes: PithyNode[],\n context: Record<string, unknown>\n): DocumentFragment {\n const fragment = document.createDocumentFragment();\n\n for (const node of nodes) {\n const domNode = createDomNodeFromPithy(node, context);\n if (domNode) {\n fragment.appendChild(domNode);\n }\n }\n\n return fragment;\n}\n\n/** @codexApi {\"parent\":\"pithy.compiler.dom-tree\",\"name\":\"createDomNodeFromPithy\",\"stability\":\"stable\",\"signature\":\"(node: PithyNode, context: Record<string, any>) => Node | null\"} */\nfunction createDomNodeFromPithy(\n node: PithyNode,\n context: Record<string, unknown>\n): Node | null {\n if (node.type === 'text') {\n const textNode = document.createTextNode(node.textContent ?? '');\n nodeExpando(textNode).__pithyCtx = context;\n nodeExpando(textNode).__pithyNode = node;\n return textNode;\n }\n\n if (node.type === 'slot') {\n // Create comment anchor for slot\n const slotName = node.slotName || '';\n const anchor = document.createComment(\n `slot:${slotName} pid=\"${node.nodeId}\"`\n );\n\n // Store slot metadata for runtime stitching\n nodeExpando(anchor).__pithyCtx = context;\n nodeExpando(anchor).__nodeId = node.nodeId;\n nodeExpando(anchor).__slotName = slotName;\n nodeExpando(anchor).__pithyNode = node;\n\n // Create fallback fragment factory if fallback content exists\n if (node.fallbackChildren && node.fallbackChildren.length > 0) {\n nodeExpando(anchor).__fallbackFactory = () => {\n return pithyTreeToDom(node.fallbackChildren!, context);\n };\n }\n\n return anchor;\n }\n\n if (node.type === 'element') {\n // For components, create placeholder element (to be upgraded later)\n const tag = node.originalTagName ?? node.tagName ?? 'div';\n\n // SVG elements need to be created in the SVG namespace\n const el = SVG_TAGS.has(tag.toLowerCase())\n ? document.createElementNS(SVG_NS, tag)\n : document.createElement(tag);\n\n nodeExpando(el).__pithyCtx = context;\n\n // Store the PithyNode data for component binding to access:\n // - isComponent flag (to distinguish native elements from components)\n // - original attribute names (for prop name normalization)\n nodeExpando(el).__pithyNode = node;\n\n // Set static attributes\n for (const [name, value] of Object.entries(node.attrs ?? {})) {\n if (name.startsWith('@') || name.startsWith('[')) {\n continue; // Skip PithyJS directive attributes — handled in bind* functions\n }\n // Use original attribute name casing (important for SVG attributes like viewBox)\n const originalName = node.originalAttrs?.[name] || name;\n el.setAttribute(originalName, value);\n }\n\n // @for loop - REPLACE element with anchor\n if (node.directives?.for) {\n // Create a comment node as placeholder\n const placeholder = document.createComment(\n `Placeholder for loop items pid=\"${node.nodeId}\"`\n );\n nodeExpando(placeholder).__pithyCtx = context;\n\n // Store the nodeId on the comment for bindForLoops to find it\n if (node.nodeId) {\n nodeExpando(placeholder).__nodeId = node.nodeId;\n // Loop placeholders are comment nodes — discovered via __nodeId walk, not querySelectorAll (data-pid is for element nodes only)\n }\n\n // Store the original PithyNode structure for nested processing\n nodeExpando(placeholder).__pithyNode = node;\n\n return placeholder;\n }\n\n // Apply directive data-* attributes for runtime binders.\n // Uses the shared mapping from @pithyjs/compiler to stay in sync with AOT codegen.\n if (node.directives) {\n forEachDirectiveAttr(node.directives, (attr, value) => {\n el.setAttribute(attr, value);\n });\n\n // Preserve `slot` as a standard HTML attribute.\n // forEachDirectiveAttr intentionally skips slot (it's consumed by content\n // projection via directives.slot), but downstream binders like\n // bindDeferDirectives need it as a DOM attribute for querySelector lookups\n // (e.g., '[slot=\"placeholder\"]', '[slot=\"error\"]').\n if (node.directives.slot && !el.hasAttribute('slot')) {\n el.setAttribute('slot', node.directives.slot);\n }\n }\n\n // Optional: add dev/debug node ID\n if (node.nodeId) {\n el.setAttribute('data-pid', node.nodeId);\n } else if (node.attrs?.['data-pid']) {\n // Preserve existing data-pid from the original HTML\n el.setAttribute('data-pid', node.attrs['data-pid']);\n }\n\n // Recursively process children\n for (const child of node.children ?? []) {\n const childDom = createDomNodeFromPithy(child, context);\n if (childDom) el.appendChild(childDom);\n }\n\n return el;\n }\n\n return null;\n}\n"]}
@@ -8,6 +8,6 @@ export interface Branch {
8
8
  * inserts it after `anchor`.
9
9
  */
10
10
  export declare function renderBranch(ast: PithyNode, ctx: Record<string, unknown>, anchor: Node): Branch;
11
- /** Disposes a branch's effects, then removes its nodes. */
11
+ /** Disposes a branch's effects, last registered first, then removes its nodes. */
12
12
  export declare function clearBranch(branch: Branch): void;
13
13
  //# sourceMappingURL=renderBranch.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"renderBranch.d.ts","sourceRoot":"","sources":["../../src/compile/renderBranch.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;AAUnD,MAAM,WAAW,MAAM;IACrB,KAAK,EAAE,IAAI,EAAE,CAAC;IACd,SAAS,EAAE,CAAC,MAAM,IAAI,CAAC,EAAE,CAAC;CAC3B;AAED;;;GAGG;AACH,wBAAgB,YAAY,CAC1B,GAAG,EAAE,SAAS,EACd,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAC5B,MAAM,EAAE,IAAI,GACX,MAAM,CAoCR;AAED,2DAA2D;AAC3D,wBAAgB,WAAW,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,CAahD"}
1
+ {"version":3,"file":"renderBranch.d.ts","sourceRoot":"","sources":["../../src/compile/renderBranch.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;AAWnD,MAAM,WAAW,MAAM;IACrB,KAAK,EAAE,IAAI,EAAE,CAAC;IACd,SAAS,EAAE,CAAC,MAAM,IAAI,CAAC,EAAE,CAAC;CAC3B;AAED;;;GAGG;AACH,wBAAgB,YAAY,CAC1B,GAAG,EAAE,SAAS,EACd,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAC5B,MAAM,EAAE,IAAI,GACX,MAAM,CAqCR;AAED,kFAAkF;AAClF,wBAAgB,WAAW,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,CAahD"}