@pithyjs/core 0.1.0-beta.20 → 0.1.0-beta.21

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.
@@ -1 +1 @@
1
- {"version":3,"file":"bindBoundAttributes.d.ts","sourceRoot":"","sources":["../../../src/compile/binds/bindBoundAttributes.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAMF;;;GAGG;AACH,8NAA8N;AAC9N,wBAAgB,mBAAmB,CACjC,IAAI,EAAE,OAAO,GAAG,gBAAgB,EAChC,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAChC,SAAS,EAAE,CAAC,MAAM,IAAI,CAAC,EAAE,GACxB,IAAI,CA8BN;AAsBD,wJAAwJ;AACxJ,wBAAgB,WAAW,CAAC,EAAE,EAAE,OAAO,GAAG,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,CAY/D;AAED,8LAA8L;AAC9L,wBAAgB,YAAY,CAC1B,EAAE,EAAE,OAAO,EACX,IAAI,EAAE,MAAM,EACZ,KAAK,EAAE,MAAM,GAAG,IAAI,EACpB,QAAQ,SAAK,GACZ,IAAI,CAYN;AA+HD,qHAAqH;AACrH,eAAO,MAAM,UAAU,OAA+C,CAAC;AAEvE,mOAAmO;AACnO,wBAAgB,UAAU,CACxB,EAAE,EAAE,OAAO,EACX,IAAI,EAAE,MAAM,EACZ,IAAI,EAAE,MAAM,EACZ,UAAU,EAAE,CAAC,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,CAAC,GAAG,IAAI,EAC3C,IAAI,EAAE,MAAM,OAAO,GAClB,IAAI,CAYN"}
1
+ {"version":3,"file":"bindBoundAttributes.d.ts","sourceRoot":"","sources":["../../../src/compile/binds/bindBoundAttributes.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAMF;;;GAGG;AACH,8NAA8N;AAC9N,wBAAgB,mBAAmB,CACjC,IAAI,EAAE,OAAO,GAAG,gBAAgB,EAChC,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAChC,SAAS,EAAE,CAAC,MAAM,IAAI,CAAC,EAAE,GACxB,IAAI,CA8BN;AAsBD,wJAAwJ;AACxJ,wBAAgB,WAAW,CAAC,EAAE,EAAE,OAAO,GAAG,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,CAY/D;AAED,8LAA8L;AAC9L,wBAAgB,YAAY,CAC1B,EAAE,EAAE,OAAO,EACX,IAAI,EAAE,MAAM,EACZ,KAAK,EAAE,MAAM,GAAG,IAAI,EACpB,QAAQ,SAAK,GACZ,IAAI,CAYN;AAkID,qHAAqH;AACrH,eAAO,MAAM,UAAU,OAA+C,CAAC;AAEvE,mOAAmO;AACnO,wBAAgB,UAAU,CACxB,EAAE,EAAE,OAAO,EACX,IAAI,EAAE,MAAM,EACZ,IAAI,EAAE,MAAM,EACZ,UAAU,EAAE,CAAC,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,CAAC,GAAG,IAAI,EAC3C,IAAI,EAAE,MAAM,OAAO,GAClB,IAAI,CAYN"}
@@ -109,14 +109,17 @@ function hasScheme(url, scheme) {
109
109
  const compact = [...url].filter(c => c > ' ' && c !== '\x7f').join('');
110
110
  return scheme.test(compact);
111
111
  }
112
- function rejectsScriptSink(el, attr, text) {
113
- if (el.localName === 'iframe' && attr === 'srcdoc') {
112
+ function rejectsScriptSink(el, name, text) {
113
+ // An SVG name keeps its case, and the HTML parser lowercases it again when it reads SSR output.
114
+ const tag = el.localName.toLowerCase();
115
+ const attr = name.toLowerCase();
116
+ if (tag === 'iframe' && attr === 'srcdoc') {
114
117
  if (import.meta.env?.DEV && text !== '') {
115
118
  console.warn('[PithyJS] A bound [srcdoc] is rejected: its HTML runs with the page origin. Bind [src] to a data:text/html URL, which loads in an opaque origin.');
116
119
  }
117
120
  return true;
118
121
  }
119
- const sink = URL_SINKS.get(el.localName);
122
+ const sink = URL_SINKS.get(tag);
120
123
  if (!sink?.attrs.includes(attr))
121
124
  return false;
122
125
  const urls = attr === 'values' ? text.split(';') : [text];
@@ -1 +1 @@
1
- {"version":3,"file":"bindBoundAttributes.js","sourceRoot":"","sources":["../../../src/compile/binds/bindBoundAttributes.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAEF,OAAO,EAAE,mBAAmB,EAAE,MAAM,qBAAqB,CAAC;AAC1D,OAAO,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAC;AAC1C,OAAO,EAAE,WAAW,EAAoB,MAAM,gBAAgB,CAAC;AAE/D;;;GAGG;AACH,8NAA8N;AAC9N,MAAM,UAAU,mBAAmB,CACjC,IAAgC,EAChC,OAAgC,EAChC,SAAyB;IAEzB,IAAI,CAAC,gBAAgB,CAAC,GAAG,CAAC,CAAC,OAAO,CAAC,EAAE,CAAC,EAAE;QACtC,sEAAsE;QACtE,6DAA6D;QAC7D,MAAM,KAAK,GACT,WAAW,CAAC,EAAE,CAAC,CAAC,iBAAiB;YACjC,WAAW,CAAC,EAAE,CAAC,CAAC,UAAU;YAC1B,OAAO,CAAC;QAEV,KAAK,MAAM,IAAI,IAAI,KAAK,CAAC,IAAI,CAAC,EAAE,CAAC,UAAU,CAAC,EAAE,CAAC;YAC7C,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC,YAAY,CAAC,IAAI,CAAC,mBAAmB,CAAC,IAAI,CAAC;gBACnE,SAAS;YAEX,MAAM,QAAQ,GAAG,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,YAAY,CAAC,MAAM,CAAC,CAAC;YACtD,MAAM,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC;YAExB,qEAAqE;YACrE,wEAAwE;YACxE,EAAE,CAAC,eAAe,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;YAE9B,MAAM,UAAU,GAAG,QAAQ,KAAK,OAAO,CAAC,CAAC,CAAC,WAAW,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC;YACjE,MAAM,IAAI,GAAG,MAAM,C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CAC3B,GAAG,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,EACvB,WAAW,IAAI,GAAG,CACgB,CAAC;IACrC,OAAO,QAAQ,CAAC,GAAG,MAAM,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC;AAC7C,CAAC","sourcesContent":["/** @codex\n{\n \"id\": \"pithy.runtime.attributes\",\n \"title\": \"Bound Attribute Binding System\",\n \"category\": \"runtime\"\n}\n*/\n\nimport { isDeclaredDirective } from './declaredDirective';\nimport { effect } from '@pithyjs/signals';\nimport { nodeExpando, type StyleOwners } from '../nodeExpando';\n\n/**\n * Binds [attr]=\"expression\" bindings like [class]=\"dynamicClass\"\n * using reactive effect evaluation.\n */\n/** @codexApi {\"parent\":\"pithy.runtime.attributes\",\"name\":\"bindBoundAttributes\",\"stability\":\"stable\",\"signature\":\"(root: Element | DocumentFragment, context: Record<string, unknown>, disposers: (() => void)[]) => void\"} */\nexport function bindBoundAttributes(\n root: Element | DocumentFragment,\n context: Record<string, unknown>,\n disposers: (() => void)[]\n): void {\n root.querySelectorAll('*').forEach(el => {\n // Use element's own __pithyCtx when available (projected slot content\n // carries the parent component's context via this property).\n const elCtx =\n nodeExpando(el).__pithyForwardCtx ??\n nodeExpando(el).__pithyCtx ??\n context;\n\n for (const attr of Array.from(el.attributes)) {\n if (!attr.name.startsWith('data-bind-') || !isDeclaredDirective(attr))\n continue;\n\n const attrName = attr.name.slice('data-bind-'.length);\n const expr = attr.value;\n\n // Remove data-bind-* attribute after capturing expression to prevent\n // double-processing when component subtrees are inserted into outer DOM\n el.removeAttribute(attr.name);\n\n const writeStyle = attrName === 'style' ? styleWriter(el) : null;\n const stop = effect(() => {\n writeBound(el, attrName, expr, writeStyle, () =>\n evaluateExpression(expr, elCtx)\n );\n });\n\n disposers.push(stop);\n }\n });\n}\n\n/**\n * Every binding on one element's `style`. Strings compose in bind order, then\n * each `[style.x]` applies on top, so nothing depends on reading the CSSOM back:\n * a value there cannot show which binding wrote it.\n */\nfunction styleOwners(el: Element): StyleOwners {\n const node = nodeExpando(el);\n return (node.__styleOwners ??= { strings: [], props: new Map() });\n}\n\nfunction renderStyle(el: Element, owners: StyleOwners): void {\n const text = owners.strings.filter(Boolean).join('; ');\n if (text) el.setAttribute('style', text);\n else el.removeAttribute('style');\n const style = (el as Partial<ElementCSSInlineStyle>).style;\n for (const [prop, [value, priority]] of owners.props) {\n style?.setProperty(prop, value, priority);\n }\n}\n\n/** @codexApi {\"parent\":\"pithy.runtime.attributes\",\"name\":\"styleWriter\",\"stability\":\"internal\",\"signature\":\"(el: Element) => (text: string) => void\"} */\nexport function styleWriter(el: Element): (text: string) => void {\n const owners = styleOwners(el);\n if (!owners.strings.length) {\n const style = (el as Partial<ElementCSSInlineStyle>).style;\n for (const prop of owners.props.keys()) style?.removeProperty(prop);\n owners.strings.push(el.getAttribute('style') ?? '');\n }\n const slot = owners.strings.push('') - 1;\n return text => {\n owners.strings[slot] = text;\n renderStyle(el, owners);\n };\n}\n\n/** @codexApi {\"parent\":\"pithy.runtime.attributes\",\"name\":\"setStyleProp\",\"stability\":\"internal\",\"signature\":\"(el: Element, prop: string, value: string | null, priority?: string) => void\"} */\nexport function setStyleProp(\n el: Element,\n prop: string,\n value: string | null,\n priority = ''\n): void {\n const owners = styleOwners(el);\n const style = (el as Partial<ElementCSSInlineStyle>).style;\n owners.props.delete(prop);\n if (value !== null) owners.props.set(prop, [value, priority]);\n if (owners.strings.length) {\n renderStyle(el, owners);\n } else if (value === null) {\n style?.removeProperty(prop);\n } else {\n style?.setProperty(prop, value, priority);\n }\n}\n\nconst LINK_SCHEME_RE = /^(?:javascript|vbscript|data):/i;\n// A data: frame, form target or animated href loads in an opaque origin, so only a link refuses data:.\nconst SCRIPT_SCHEME_RE = /^(?:javascript|vbscript):/i;\nconst LINK_ATTRS = ['href', 'xlink:href'];\nconst LINK_SINK = { attrs: LINK_ATTRS, scheme: LINK_SCHEME_RE };\nconst FORM_ACTION_SINK = { attrs: ['formaction'], scheme: SCRIPT_SCHEME_RE };\nconst URL_SINKS = new Map<string, { attrs: readonly string[]; scheme: RegExp }>(\n [\n ['a', LINK_SINK],\n ['area', LINK_SINK],\n ['set', { attrs: ['to'], scheme: SCRIPT_SCHEME_RE }],\n ['animate', { attrs: ['to', 'from', 'values'], scheme: SCRIPT_SCHEME_RE }],\n ['iframe', { attrs: ['src'], scheme: SCRIPT_SCHEME_RE }],\n ['frame', { attrs: ['src'], scheme: SCRIPT_SCHEME_RE }],\n ['form', { attrs: ['action'], scheme: SCRIPT_SCHEME_RE }],\n ['button', FORM_ACTION_SINK],\n ['input', FORM_ACTION_SINK],\n ]\n);\n\nfunction hasScheme(url: string, scheme: RegExp): boolean {\n const compact = [...url].filter(c => c > ' ' && c !== '\\x7f').join('');\n return scheme.test(compact);\n}\n\nfunction rejectsScriptSink(el: Element, attr: string, text: string): boolean {\n if (el.localName === 'iframe' && attr === 'srcdoc') {\n if (import.meta.env?.DEV && text !== '') {\n console.warn(\n '[PithyJS] A bound [srcdoc] is rejected: its HTML runs with the page origin. Bind [src] to a data:text/html URL, which loads in an opaque origin.'\n );\n }\n return true;\n }\n const sink = URL_SINKS.get(el.localName);\n if (!sink?.attrs.includes(attr)) return false;\n const urls = attr === 'values' ? text.split(';') : [text];\n if (!urls.some(url => hasScheme(url, sink.scheme))) return false;\n if (import.meta.env?.DEV) {\n console.warn(`[PithyJS] Unsafe [${attr}] rejected: \"${text}\".`);\n }\n return true;\n}\n\nconst TEXT_BOOLEAN_ATTR = /^(?:aria-.+|contenteditable|draggable|spellcheck)$/i;\nconst FORM_CONTROLS = new Set(['input', 'select', 'textarea']);\n\nfunction syncSelect(select: HTMLSelectElement): void {\n const bound = nodeExpando(select).__selectValue;\n if (!bound) return;\n const picks = select.multiple ? bound.picks : null;\n let found = false;\n for (const option of select.querySelectorAll('option')) {\n const match: boolean = picks\n ? picks.has(option.value)\n : !found && option.value === bound.text;\n option.toggleAttribute('selected', match);\n if (select.multiple) option.selected = match;\n found ||= match;\n }\n if (!select.multiple) select.value = bound.text;\n}\n\nfunction syncOption(option: HTMLOptionElement): void {\n const select = option.closest('select');\n const bound = select && nodeExpando(select).__selectValue;\n if (!select || !bound) return;\n if (select.multiple && bound.picks) {\n const match = bound.picks.has(option.value);\n option.toggleAttribute('selected', match);\n option.selected = match;\n } else if (option.selected || option.value === bound.text) {\n syncSelect(select);\n }\n}\n\nfunction setControlValue(el: Element, text: string, value?: unknown): void {\n if (el.localName === 'option') {\n syncOption(el as HTMLOptionElement);\n return;\n }\n if (!FORM_CONTROLS.has(el.localName)) return;\n const control = el as HTMLInputElement;\n if (control.type === 'file') return;\n if (el.localName === 'select') {\n const picks = Array.isArray(value) ? new Set(value.map(String)) : null;\n nodeExpando(el).__selectValue = { text, picks };\n syncSelect(el as HTMLSelectElement);\n return;\n }\n if (el.localName === 'textarea' && el.textContent !== text) {\n el.textContent = text;\n }\n if (control.value !== text) control.value = text;\n}\n\nfunction writeValue(\n el: Element,\n attr: string,\n value: unknown,\n writeStyle: ((text: string) => void) | null\n): void {\n if (value == null) {\n if (writeStyle) writeStyle('');\n else el.removeAttribute(attr);\n if (attr === 'value') setControlValue(el, '');\n return;\n }\n if (typeof value === 'boolean' && !TEXT_BOOLEAN_ATTR.test(attr)) {\n if (writeStyle) writeStyle('');\n else if (value) el.setAttribute(attr, '');\n else el.removeAttribute(attr);\n return;\n }\n const text = String(value);\n if (writeStyle) {\n writeStyle(text);\n } else if (rejectsScriptSink(el, attr, text)) {\n el.removeAttribute(attr);\n } else {\n el.setAttribute(attr, text);\n if (attr === 'value') setControlValue(el, text, value);\n }\n}\n\n/** @codexApi {\"parent\":\"pithy.runtime.attributes\",\"name\":\"UNCOMPILED\",\"stability\":\"internal\",\"signature\":\"Error\"} */\nexport const UNCOMPILED = new Error('The expression does not compile');\n\n/** @codexApi {\"parent\":\"pithy.runtime.attributes\",\"name\":\"writeBound\",\"stability\":\"internal\",\"signature\":\"(el: Element, attr: string, expr: string, writeStyle: ((text: string) => void) | null, read: () => unknown) => void\"} */\nexport function writeBound(\n el: Element,\n attr: string,\n expr: string,\n writeStyle: ((text: string) => void) | null,\n read: () => unknown\n): void {\n try {\n writeValue(el, attr, read(), writeStyle);\n } catch (err) {\n if (import.meta.env?.DEV && err !== UNCOMPILED) {\n console.warn(`[pithy] Failed to evaluate: ${expr}`, err);\n }\n removeBound(el, attr, writeStyle);\n }\n if (attr === 'multiple' && el.localName === 'select') {\n syncSelect(el as HTMLSelectElement);\n }\n}\n\nfunction removeBound(\n el: Element,\n attr: string,\n writeStyle: ((text: string) => void) | null\n): void {\n try {\n if (writeStyle) {\n writeStyle('');\n } else {\n const control = el as HTMLInputElement;\n const kept = control.value;\n el.removeAttribute(attr);\n if (\n attr === 'value' &&\n FORM_CONTROLS.has(el.localName) &&\n control.value !== kept\n ) {\n control.value = kept;\n }\n }\n } catch {\n /* ignore */\n }\n}\n\nfunction evaluateExpression(\n expr: string,\n context: Record<string, unknown>\n): unknown {\n // eslint-disable-next-line no-new-func -- args-style template expression evaluation is a core framework feature\n const compiled = new Function(\n ...Object.keys(context),\n `return (${expr})`\n ) as (...args: unknown[]) => unknown;\n return compiled(...Object.values(context));\n}\n"]}
1
+ {"version":3,"file":"bindBoundAttributes.js","sourceRoot":"","sources":["../../../src/compile/binds/bindBoundAttributes.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAEF,OAAO,EAAE,mBAAmB,EAAE,MAAM,qBAAqB,CAAC;AAC1D,OAAO,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAC;AAC1C,OAAO,EAAE,WAAW,EAAoB,MAAM,gBAAgB,CAAC;AAE/D;;;GAGG;AACH,8NAA8N;AAC9N,MAAM,UAAU,mBAAmB,CACjC,IAAgC,EAChC,OAAgC,EAChC,SAAyB;IAEzB,IAAI,CAAC,gBAAgB,CAAC,GAAG,CAAC,CAAC,OAAO,CAAC,EAAE,CAAC,EAAE;QACtC,sEAAsE;QACtE,6DAA6D;QAC7D,MAAM,KAAK,GACT,WAA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C;IACD,IAAI,IAAI,KAAK,UAAU,IAAI,EAAE,CAAC,SAAS,KAAK,QAAQ,EAAE,CAAC;QACrD,UAAU,CAAC,EAAuB,CAAC,CAAC;IACtC,CAAC;AACH,CAAC;AAED,SAAS,WAAW,CAClB,EAAW,EACX,IAAY,EACZ,UAA2C;IAE3C,IAAI,CAAC;QACH,IAAI,UAAU,EAAE,CAAC;YACf,UAAU,CAAC,EAAE,CAAC,CAAC;QACjB,CAAC;aAAM,CAAC;YACN,MAAM,OAAO,GAAG,EAAsB,CAAC;YACvC,MAAM,IAAI,GAAG,OAAO,CAAC,KAAK,CAAC;YAC3B,EAAE,CAAC,eAAe,CAAC,IAAI,CAAC,CAAC;YACzB,IACE,IAAI,KAAK,OAAO;gBAChB,aAAa,CAAC,GAAG,CAAC,EAAE,CAAC,SAAS,CAAC;gBAC/B,OAAO,CAAC,KAAK,KAAK,IAAI,EACtB,CAAC;gBACD,OAAO,CAAC,KAAK,GAAG,IAAI,CAAC;YACvB,CAAC;QACH,CAAC;IACH,CAAC;IAAC,MAAM,CAAC;QACP,YAAY;IACd,CAAC;AACH,CAAC;AAED,SAAS,kBAAkB,CACzB,IAAY,EACZ,OAAgC;IAEhC,gHAAgH;IAChH,MAAM,QAAQ,GAAG,IAAI,QAAQ,CAC3B,GAAG,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,EACvB,WAAW,IAAI,GAAG,CACgB,CAAC;IACrC,OAAO,QAAQ,CAAC,GAAG,MAAM,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC;AAC7C,CAAC","sourcesContent":["/** @codex\n{\n \"id\": \"pithy.runtime.attributes\",\n \"title\": \"Bound Attribute Binding System\",\n \"category\": \"runtime\"\n}\n*/\n\nimport { isDeclaredDirective } from './declaredDirective';\nimport { effect } from '@pithyjs/signals';\nimport { nodeExpando, type StyleOwners } from '../nodeExpando';\n\n/**\n * Binds [attr]=\"expression\" bindings like [class]=\"dynamicClass\"\n * using reactive effect evaluation.\n */\n/** @codexApi {\"parent\":\"pithy.runtime.attributes\",\"name\":\"bindBoundAttributes\",\"stability\":\"stable\",\"signature\":\"(root: Element | DocumentFragment, context: Record<string, unknown>, disposers: (() => void)[]) => void\"} */\nexport function bindBoundAttributes(\n root: Element | DocumentFragment,\n context: Record<string, unknown>,\n disposers: (() => void)[]\n): void {\n root.querySelectorAll('*').forEach(el => {\n // Use element's own __pithyCtx when available (projected slot content\n // carries the parent component's context via this property).\n const elCtx =\n nodeExpando(el).__pithyForwardCtx ??\n nodeExpando(el).__pithyCtx ??\n context;\n\n for (const attr of Array.from(el.attributes)) {\n if (!attr.name.startsWith('data-bind-') || !isDeclaredDirective(attr))\n continue;\n\n const attrName = attr.name.slice('data-bind-'.length);\n const expr = attr.value;\n\n // Remove data-bind-* attribute after capturing expression to prevent\n // double-processing when component subtrees are inserted into outer DOM\n el.removeAttribute(attr.name);\n\n const writeStyle = attrName === 'style' ? styleWriter(el) : null;\n const stop = effect(() => {\n writeBound(el, attrName, expr, writeStyle, () =>\n evaluateExpression(expr, elCtx)\n );\n });\n\n disposers.push(stop);\n }\n });\n}\n\n/**\n * Every binding on one element's `style`. Strings compose in bind order, then\n * each `[style.x]` applies on top, so nothing depends on reading the CSSOM back:\n * a value there cannot show which binding wrote it.\n */\nfunction styleOwners(el: Element): StyleOwners {\n const node = nodeExpando(el);\n return (node.__styleOwners ??= { strings: [], props: new Map() });\n}\n\nfunction renderStyle(el: Element, owners: StyleOwners): void {\n const text = owners.strings.filter(Boolean).join('; ');\n if (text) el.setAttribute('style', text);\n else el.removeAttribute('style');\n const style = (el as Partial<ElementCSSInlineStyle>).style;\n for (const [prop, [value, priority]] of owners.props) {\n style?.setProperty(prop, value, priority);\n }\n}\n\n/** @codexApi {\"parent\":\"pithy.runtime.attributes\",\"name\":\"styleWriter\",\"stability\":\"internal\",\"signature\":\"(el: Element) => (text: string) => void\"} */\nexport function styleWriter(el: Element): (text: string) => void {\n const owners = styleOwners(el);\n if (!owners.strings.length) {\n const style = (el as Partial<ElementCSSInlineStyle>).style;\n for (const prop of owners.props.keys()) style?.removeProperty(prop);\n owners.strings.push(el.getAttribute('style') ?? '');\n }\n const slot = owners.strings.push('') - 1;\n return text => {\n owners.strings[slot] = text;\n renderStyle(el, owners);\n };\n}\n\n/** @codexApi {\"parent\":\"pithy.runtime.attributes\",\"name\":\"setStyleProp\",\"stability\":\"internal\",\"signature\":\"(el: Element, prop: string, value: string | null, priority?: string) => void\"} */\nexport function setStyleProp(\n el: Element,\n prop: string,\n value: string | null,\n priority = ''\n): void {\n const owners = styleOwners(el);\n const style = (el as Partial<ElementCSSInlineStyle>).style;\n owners.props.delete(prop);\n if (value !== null) owners.props.set(prop, [value, priority]);\n if (owners.strings.length) {\n renderStyle(el, owners);\n } else if (value === null) {\n style?.removeProperty(prop);\n } else {\n style?.setProperty(prop, value, priority);\n }\n}\n\nconst LINK_SCHEME_RE = /^(?:javascript|vbscript|data):/i;\n// A data: frame, form target or animated href loads in an opaque origin, so only a link refuses data:.\nconst SCRIPT_SCHEME_RE = /^(?:javascript|vbscript):/i;\nconst LINK_ATTRS = ['href', 'xlink:href'];\nconst LINK_SINK = { attrs: LINK_ATTRS, scheme: LINK_SCHEME_RE };\nconst FORM_ACTION_SINK = { attrs: ['formaction'], scheme: SCRIPT_SCHEME_RE };\nconst URL_SINKS = new Map<string, { attrs: readonly string[]; scheme: RegExp }>(\n [\n ['a', LINK_SINK],\n ['area', LINK_SINK],\n ['set', { attrs: ['to'], scheme: SCRIPT_SCHEME_RE }],\n ['animate', { attrs: ['to', 'from', 'values'], scheme: SCRIPT_SCHEME_RE }],\n ['iframe', { attrs: ['src'], scheme: SCRIPT_SCHEME_RE }],\n ['frame', { attrs: ['src'], scheme: SCRIPT_SCHEME_RE }],\n ['form', { attrs: ['action'], scheme: SCRIPT_SCHEME_RE }],\n ['button', FORM_ACTION_SINK],\n ['input', FORM_ACTION_SINK],\n ]\n);\n\nfunction hasScheme(url: string, scheme: RegExp): boolean {\n const compact = [...url].filter(c => c > ' ' && c !== '\\x7f').join('');\n return scheme.test(compact);\n}\n\nfunction rejectsScriptSink(el: Element, name: string, text: string): boolean {\n // An SVG name keeps its case, and the HTML parser lowercases it again when it reads SSR output.\n const tag = el.localName.toLowerCase();\n const attr = name.toLowerCase();\n if (tag === 'iframe' && attr === 'srcdoc') {\n if (import.meta.env?.DEV && text !== '') {\n console.warn(\n '[PithyJS] A bound [srcdoc] is rejected: its HTML runs with the page origin. Bind [src] to a data:text/html URL, which loads in an opaque origin.'\n );\n }\n return true;\n }\n const sink = URL_SINKS.get(tag);\n if (!sink?.attrs.includes(attr)) return false;\n const urls = attr === 'values' ? text.split(';') : [text];\n if (!urls.some(url => hasScheme(url, sink.scheme))) return false;\n if (import.meta.env?.DEV) {\n console.warn(`[PithyJS] Unsafe [${attr}] rejected: \"${text}\".`);\n }\n return true;\n}\n\nconst TEXT_BOOLEAN_ATTR = /^(?:aria-.+|contenteditable|draggable|spellcheck)$/i;\nconst FORM_CONTROLS = new Set(['input', 'select', 'textarea']);\n\nfunction syncSelect(select: HTMLSelectElement): void {\n const bound = nodeExpando(select).__selectValue;\n if (!bound) return;\n const picks = select.multiple ? bound.picks : null;\n let found = false;\n for (const option of select.querySelectorAll('option')) {\n const match: boolean = picks\n ? picks.has(option.value)\n : !found && option.value === bound.text;\n option.toggleAttribute('selected', match);\n if (select.multiple) option.selected = match;\n found ||= match;\n }\n if (!select.multiple) select.value = bound.text;\n}\n\nfunction syncOption(option: HTMLOptionElement): void {\n const select = option.closest('select');\n const bound = select && nodeExpando(select).__selectValue;\n if (!select || !bound) return;\n if (select.multiple && bound.picks) {\n const match = bound.picks.has(option.value);\n option.toggleAttribute('selected', match);\n option.selected = match;\n } else if (option.selected || option.value === bound.text) {\n syncSelect(select);\n }\n}\n\nfunction setControlValue(el: Element, text: string, value?: unknown): void {\n if (el.localName === 'option') {\n syncOption(el as HTMLOptionElement);\n return;\n }\n if (!FORM_CONTROLS.has(el.localName)) return;\n const control = el as HTMLInputElement;\n if (control.type === 'file') return;\n if (el.localName === 'select') {\n const picks = Array.isArray(value) ? new Set(value.map(String)) : null;\n nodeExpando(el).__selectValue = { text, picks };\n syncSelect(el as HTMLSelectElement);\n return;\n }\n if (el.localName === 'textarea' && el.textContent !== text) {\n el.textContent = text;\n }\n if (control.value !== text) control.value = text;\n}\n\nfunction writeValue(\n el: Element,\n attr: string,\n value: unknown,\n writeStyle: ((text: string) => void) | null\n): void {\n if (value == null) {\n if (writeStyle) writeStyle('');\n else el.removeAttribute(attr);\n if (attr === 'value') setControlValue(el, '');\n return;\n }\n if (typeof value === 'boolean' && !TEXT_BOOLEAN_ATTR.test(attr)) {\n if (writeStyle) writeStyle('');\n else if (value) el.setAttribute(attr, '');\n else el.removeAttribute(attr);\n return;\n }\n const text = String(value);\n if (writeStyle) {\n writeStyle(text);\n } else if (rejectsScriptSink(el, attr, text)) {\n el.removeAttribute(attr);\n } else {\n el.setAttribute(attr, text);\n if (attr === 'value') setControlValue(el, text, value);\n }\n}\n\n/** @codexApi {\"parent\":\"pithy.runtime.attributes\",\"name\":\"UNCOMPILED\",\"stability\":\"internal\",\"signature\":\"Error\"} */\nexport const UNCOMPILED = new Error('The expression does not compile');\n\n/** @codexApi {\"parent\":\"pithy.runtime.attributes\",\"name\":\"writeBound\",\"stability\":\"internal\",\"signature\":\"(el: Element, attr: string, expr: string, writeStyle: ((text: string) => void) | null, read: () => unknown) => void\"} */\nexport function writeBound(\n el: Element,\n attr: string,\n expr: string,\n writeStyle: ((text: string) => void) | null,\n read: () => unknown\n): void {\n try {\n writeValue(el, attr, read(), writeStyle);\n } catch (err) {\n if (import.meta.env?.DEV && err !== UNCOMPILED) {\n console.warn(`[pithy] Failed to evaluate: ${expr}`, err);\n }\n removeBound(el, attr, writeStyle);\n }\n if (attr === 'multiple' && el.localName === 'select') {\n syncSelect(el as HTMLSelectElement);\n }\n}\n\nfunction removeBound(\n el: Element,\n attr: string,\n writeStyle: ((text: string) => void) | null\n): void {\n try {\n if (writeStyle) {\n writeStyle('');\n } else {\n const control = el as HTMLInputElement;\n const kept = control.value;\n el.removeAttribute(attr);\n if (\n attr === 'value' &&\n FORM_CONTROLS.has(el.localName) &&\n control.value !== kept\n ) {\n control.value = kept;\n }\n }\n } catch {\n /* ignore */\n }\n}\n\nfunction evaluateExpression(\n expr: string,\n context: Record<string, unknown>\n): unknown {\n // eslint-disable-next-line no-new-func -- args-style template expression evaluation is a core framework feature\n const compiled = new Function(\n ...Object.keys(context),\n `return (${expr})`\n ) as (...args: unknown[]) => unknown;\n return compiled(...Object.values(context));\n}\n"]}
@@ -410,6 +410,7 @@ function parseTextIntoParts(rawText) {
410
410
  function isTemplateText(node) {
411
411
  const { __pithyCtx, __pithyNode } = nodeExpando(node);
412
412
  return (__pithyCtx !== undefined &&
413
+ !__pithyNode?.inert &&
413
414
  __pithyNode?.textContent === node.nodeValue &&
414
415
  !!node.nodeValue?.includes('{{'));
415
416
  }
@@ -1 +1 @@
1
- {"version":3,"file":"bindTextInterpolations.js","sourceRoot":"","sources":["../../../src/compile/binds/bindTextInterpolations.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAEF,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAC7C,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AACpD,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAC3C,OAAO,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AACzD,OAAO,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AACvC,OAAO,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC;AACrD,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAE7C,MAAM,gBAAgB,GAAG,uBAAuB,CAAC;AAEjD;;;;;;GAMG;AACH,iOAAiO;AACjO,MAAM,UAAU,sBAAsB,CACpC,IAAgC,EAChC,IAA6B,EAC7B,SAAyB;IAEzB,iBAAiB,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C;QACd,IACE,CAAC,CAAC,YAAY;YACd,CAAC,CAAC,CAAC,YAAY,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,YAAY,CAAC,UAAU,CAAC,CAAC,EACtD,CAAC;YACD,OAAO,IAAI,CAAC;QACd,CAAC;QACD,CAAC,GAAG,CAAC,CAAC,aAAa,CAAC;IACtB,CAAC;IACD,OAAO,KAAK,CAAC;AACf,CAAC","sourcesContent":["/** @codex\n{\n \"id\": \"pithy.runtime.interpolations\",\n \"title\": \"Text Interpolation Binding System\",\n \"category\": \"runtime\"\n}\n*/\n\nimport { defaultConfig } from '../../config';\nimport { effect, isSignal } from '@pithyjs/signals';\nimport { toTextValue } from '../textValue';\nimport { compileExpression } from '../compileExpression';\nimport { isSSRMode } from '../ssrMode';\nimport { textEvalMessage } from '../evalDiagnostics';\nimport { nodeExpando } from '../nodeExpando';\n\nconst INTERPOLATION_RE = /{{\\s*([\\s\\S]*?)\\s*}}/g;\n\n/**\n * Bind all text interpolations (e.g. \"Hello {{name()}}\") under `root`.\n * - Binds only text still as the template parser created it.\n * - Skips nested-loop subtrees (tagged with __pithySkipText) and real @for/data-for hosts.\n * - Skips DOM a component rendered (__pithyComponentDom); the component bound it itself.\n * - Binds per-text-node updates with fine-grained effects.\n */\n/** @codexApi {\"parent\":\"pithy.runtime.interpolations\",\"name\":\"bindTextInterpolations\",\"stability\":\"stable\",\"signature\":\"(root: Element | DocumentFragment, ctx: Record<string, unknown>, disposers: (() => void)[]) => void\"} */\nexport function bindTextInterpolations(\n root: Element | DocumentFragment,\n _ctx: Record<string, unknown>,\n disposers: (() => void)[]\n): void {\n processChildNodes(root, disposers);\n bindRemainingTextInterpolations(root, disposers);\n}\n\n/* -----------------------------------------------------------------------------\n * Internal: robust child iteration (Element | DocumentFragment)\n * ---------------------------------------------------------------------------*/\nfunction childElementsOf(root: Element | DocumentFragment): Element[] {\n if (root instanceof Element) return Array.from(root.children);\n // DocumentFragment doesn't have .children; filter childNodes to elements\n const out: Element[] = [];\n root.childNodes.forEach(n => {\n if (n.nodeType === Node.ELEMENT_NODE) out.push(n as Element);\n });\n return out;\n}\n\n/**\n * Walk immediate children and process text nodes inside them.\n * We purposely avoid stepping into nested-loop subtrees to prevent compiling\n * expressions like {{ item() }} against the parent context.\n */\nfunction processChildNodes(\n root: Element | DocumentFragment,\n disposers: (() => void)[]\n): void {\n for (const child of childElementsOf(root)) {\n // Fast-path: if the child itself is a loop host, we skip it entirely.\n if (\n child.hasAttribute?.('@for') ||\n nodeExpando(child).__pithySkipText ||\n nodeExpando(child).__pithyComponentDom\n )\n continue;\n\n const walker = document.createTreeWalker(child, NodeFilter.SHOW_TEXT);\n const targets: Text[] = [];\n let textNode: Text | null;\n\n while ((textNode = walker.nextNode() as Text | null)) {\n if (!isTemplateText(textNode)) continue;\n\n // Skip anything inside a nested loop host or explicit @for/data-for\n if (isInsideSkippedZone(textNode, root)) continue;\n\n targets.push(textNode);\n }\n\n // Mutate after collecting to avoid invalidating the walker during traversal.\n for (const node of targets) {\n // An earlier interpolation in this loop can write into a queued node.\n if (!isTemplateText(node)) continue;\n const rawText = node.nodeValue || '';\n const parts = parseTextIntoParts(rawText);\n const parent = node.parentElement;\n const nextSibling = node.nextSibling;\n if (!parent) continue;\n\n // Use the node's own __pithyCtx (set by pithyTreeToDom).\n // Projected slot content carries the *parent* component's context this way,\n // not the context of the component whose template holds the slot.\n // This mirrors the nearestCtx pattern used by bindEventHandlers.\n const nodeCtx = nodeExpando(node).__pithyCtx!;\n\n parent.removeChild(node);\n\n for (const part of parts) {\n if (part.type === 'static') {\n insertStaticTextNode(parent, nextSibling, part.value);\n } else {\n // Determine interpolation mode based on config\n const mode = defaultConfig.textInterpolationMode || 'text-node';\n const isSignal = isSignalExpression(part.value, nodeCtx);\n\n // Choose insertion strategy\n if (mode === 'span') {\n // Always use span wrappers\n insertDynamicSpan(\n parent,\n nextSibling,\n part.value,\n nodeCtx,\n disposers\n );\n } else if (mode === 'text-node') {\n // Always use text nodes with comment anchors\n insertDynamicTextNode(\n parent,\n nextSibling,\n part.value,\n nodeCtx,\n disposers\n );\n } else {\n // 'auto' mode: span for signals if autoWrapSignals is true, text node otherwise\n if (isSignal && defaultConfig.autoWrapSignals) {\n insertDynamicSpan(\n parent,\n nextSibling,\n part.value,\n nodeCtx,\n disposers\n );\n } else {\n insertDynamicTextNode(\n parent,\n nextSibling,\n part.value,\n nodeCtx,\n disposers\n );\n }\n }\n }\n }\n }\n }\n}\n\n/**\n * Second pass: text nodes directly under `root` (e.g., loose text, or nodes\n * not caught by processChildNodes). Also respects skip zones.\n */\nfunction bindRemainingTextInterpolations(\n root: Element | DocumentFragment,\n disposers: (() => void)[]\n): void {\n const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);\n\n let node: Text | null;\n while ((node = walker.nextNode() as Text | null)) {\n if (!isTemplateText(node)) continue;\n const rawText = node.nodeValue!;\n\n // Robust skip: private flag, @for, or data-for anywhere up the chain.\n if (isInsideSkippedZone(node, root)) continue;\n\n INTERPOLATION_RE.lastIndex = 0;\n const matches = [...rawText.matchAll(INTERPOLATION_RE)];\n if (matches.length === 0) continue;\n\n // Use the node's own __pithyCtx (projected slot content\n // carries the parent component's context via this property).\n const nodeCtx = nodeExpando(node).__pithyCtx!;\n // The node keeps its identity and now holds a value: an outer pass must not read it.\n nodeExpando(node).__pithyCtx = undefined;\n\n const renderFns: (() => unknown)[] = [];\n const matchStrings: string[] = [];\n const expressions: string[] = [];\n\n for (const match of matches) {\n const expr = match[1].trim();\n matchStrings.push(match[0]);\n expressions.push(expr);\n renderFns.push(compileExpression(expr, nodeCtx));\n }\n\n bindTextNodeUpdates(\n node,\n rawText,\n expressions,\n matchStrings,\n renderFns,\n disposers\n );\n }\n}\n\n/* -----------------------------------------------------------------------------\n * Node insertion helpers\n * ---------------------------------------------------------------------------*/\nfunction insertStaticTextNode(\n parent: Element,\n nextSibling: ChildNode | null,\n text: string\n): void {\n const staticNode = document.createTextNode(text);\n parent.insertBefore(staticNode, nextSibling);\n}\n\nfunction insertDynamicSpan(\n parent: Element,\n nextSibling: ChildNode | null,\n expression: string,\n ctx: Record<string, unknown>,\n disposers: (() => void)[]\n): void {\n const span = document.createElement('span');\n span.className = 'r-pithy';\n span.style.display = 'inline';\n\n const textNode = document.createTextNode('');\n span.appendChild(textNode);\n parent.insertBefore(span, nextSibling);\n\n bindDynamicTextNode(textNode, expression, ctx, disposers, span);\n}\n\nfunction insertDynamicTextNode(\n parent: Element,\n nextSibling: ChildNode | null,\n expression: string,\n ctx: Record<string, unknown>,\n disposers: (() => void)[]\n): void {\n // Create comment anchors for structural markers (Solid.js approach)\n // This provides better debugging and potential future optimizations\n const startComment = document.createComment('t');\n const textNode = document.createTextNode('');\n const endComment = document.createComment('/t');\n\n // Insert in order: start comment, text node, end comment\n parent.insertBefore(startComment, nextSibling);\n parent.insertBefore(textNode, nextSibling);\n parent.insertBefore(endComment, nextSibling);\n\n bindDynamicTextNode(textNode, expression, ctx, disposers);\n}\n\n/* -----------------------------------------------------------------------------\n * Binding helpers\n * ---------------------------------------------------------------------------*/\nfunction bindTextNodeUpdates(\n node: Text,\n rawText: string,\n expressions: string[],\n matchStrings: string[],\n renderFns: (() => unknown)[],\n disposers: (() => void)[]\n): void {\n function evaluate() {\n let output = rawText;\n\n // Evaluate each {{ expr }} and replace into the original text\n expressions.forEach((_, i) => {\n try {\n const result = renderFns[i](); // compileExpression already closes over ctx\n // Function replacer: never let `$&`, `$$`, `$\\``, `$'`, `$n` in the\n // value be interpreted as String.replace special patterns — the value\n // must be inserted verbatim (e.g. literal code like `str.replace(/a/, '$&')`).\n output = output.replace(matchStrings[i], () => toTextValue(result));\n } catch (err) {\n console.error(textEvalMessage(expressions[i]), err);\n output = output.replace(matchStrings[i], '');\n }\n });\n\n return output;\n }\n\n if (isSSRMode()) {\n // SSR mode: evaluate once synchronously, no reactive effects\n node.nodeValue = evaluate();\n } else {\n let lastInterpolatedText: string | undefined;\n\n const stop = effect(() => {\n const output = evaluate();\n\n if (output !== lastInterpolatedText) {\n node.nodeValue = output;\n flashUpdate(node);\n lastInterpolatedText = output;\n }\n });\n\n disposers.push(stop);\n }\n}\n\n/**\n * Bind a single dynamic expression into a text node, with optional highlight target (e.g., wrapper span).\n */\nfunction bindDynamicTextNode(\n textNode: Text,\n expression: string,\n ctx: Record<string, unknown>,\n disposers: (() => void)[],\n highlightTarget?: HTMLElement\n): void {\n try {\n const compiledFn = compileExpression(expression, ctx);\n\n if (isSSRMode()) {\n // SSR mode: evaluate once synchronously, no reactive effects\n try {\n textNode.nodeValue = toTextValue(compiledFn());\n } catch (err) {\n console.error(textEvalMessage(expression), err);\n textNode.nodeValue = '';\n }\n } else {\n let lastValue: string | undefined;\n\n const stop = effect(() => {\n try {\n const result = compiledFn(); // re-evaluates reactively\n const next = toTextValue(result); // ensure string\n\n if (next !== lastValue) {\n // only mutate/flash on change\n textNode.nodeValue = next;\n\n if (highlightTarget) {\n flashUpdate(highlightTarget);\n } else {\n flashUpdate(textNode);\n }\n\n lastValue = next;\n }\n } catch (err) {\n console.error(textEvalMessage(expression), err);\n textNode.nodeValue = '';\n lastValue = '';\n }\n });\n\n disposers.push(stop);\n }\n } catch (err) {\n console.error(`[PithyJS] ❌ Failed to compile: ${expression}`, err);\n }\n}\n\n/* -----------------------------------------------------------------------------\n * Batched flashing (dev only). Reduces style/layout churn vs per-node inline updates.\n *\n * For text nodes, we create temporary positioned overlays at the exact text location\n * to provide visual feedback without adding permanent DOM nodes or flashing parent elements.\n * ---------------------------------------------------------------------------*/\nexport function flashUpdate(node: Text | Element): void {\n const { highlightColor, highlightDuration, devHighlightDomUpdates } =\n defaultConfig;\n if (!import.meta.env?.DEV || !devHighlightDomUpdates) return;\n\n if (node.nodeType === Node.TEXT_NODE) {\n flashTextNode(node as Text, highlightColor || '', highlightDuration || 0.2);\n } else {\n enqueueFlash(\n node as HTMLElement,\n highlightColor || '',\n highlightDuration || 0.2\n );\n }\n}\n\nconst flashQueue = new Set<HTMLElement>();\nlet flashScheduled = false;\n// Pending cleanup timers per element — cancelled on re-flash so a previous\n// flash's timers can't clear the background/transition mid-fade of a newer\n// one (rapidly-updating bindings flash the same element in overlapping\n// windows).\nconst flashTimers = new WeakMap<\n HTMLElement,\n { fade: ReturnType<typeof setTimeout>; clear?: ReturnType<typeof setTimeout> }\n>();\nconst flashOriginals = new WeakMap<\n HTMLElement,\n {\n transition: string;\n backgroundColor: string;\n flashTransition: string;\n flashBackground: string;\n }\n>();\n\nfunction enqueueFlash(el: HTMLElement, color: string, duration: number) {\n flashQueue.add(el);\n if (flashScheduled) return;\n flashScheduled = true;\n\n requestAnimationFrame(() => {\n // Apply highlight to all queued nodes at once\n flashQueue.forEach(t => {\n const pending = flashTimers.get(t);\n if (pending) {\n clearTimeout(pending.fade);\n if (pending.clear !== undefined) clearTimeout(pending.clear);\n }\n const { style } = t;\n let original = flashOriginals.get(t);\n if (!original) {\n original = {\n transition: style.transition,\n backgroundColor: style.backgroundColor,\n flashTransition: '',\n flashBackground: '',\n };\n flashOriginals.set(t, original);\n } else {\n if (style.transition !== original.flashTransition) {\n original.transition = style.transition;\n }\n if (style.backgroundColor !== original.flashBackground) {\n original.backgroundColor = style.backgroundColor;\n }\n }\n const saved = original;\n\n style.transition = `background-color ${duration}s ease-out`;\n style.backgroundColor = color;\n saved.flashTransition = style.transition;\n saved.flashBackground = style.backgroundColor;\n\n const fade = setTimeout(() => {\n // Restore, don't set \"transparent\" — an explicit inline value would\n // permanently override the element's stylesheet background. Runs\n // even for disconnected nodes so a reattached element doesn't keep\n // stale inline highlight styles.\n if (style.backgroundColor === saved.flashBackground) {\n style.backgroundColor = saved.backgroundColor;\n }\n const clear = setTimeout(() => {\n if (style.transition === saved.flashTransition) {\n style.transition = saved.transition;\n }\n flashTimers.delete(t);\n flashOriginals.delete(t);\n }, duration * 1000);\n flashTimers.set(t, { fade, clear });\n }, 80);\n flashTimers.set(t, { fade });\n });\n\n flashQueue.clear();\n flashScheduled = false;\n });\n}\n\n/**\n * Flash a text node update by creating a temporary positioned overlay.\n * This provides visual feedback for text-node mode without permanent DOM nodes.\n */\nfunction flashTextNode(textNode: Text, color: string, duration: number) {\n if (!textNode.parentElement) return;\n\n // Get the exact bounding rect of the text node\n const range = document.createRange();\n range.selectNodeContents(textNode);\n const rect = range.getBoundingClientRect();\n range.detach();\n\n // Skip if text has no dimensions (empty or not rendered)\n if (rect.width === 0 || rect.height === 0) return;\n\n // Create temporary overlay positioned exactly over the text\n const overlay = document.createElement('div');\n overlay.style.cssText = `\n position: fixed;\n left: ${rect.left}px;\n top: ${rect.top}px;\n width: ${rect.width}px;\n height: ${rect.height}px;\n background-color: ${color};\n pointer-events: none;\n z-index: 999999;\n transition: opacity ${duration}s ease-out;\n opacity: 0.6;\n border-radius: 2px;\n `;\n\n document.body.appendChild(overlay);\n\n // Fade out and remove\n requestAnimationFrame(() => {\n overlay.style.opacity = '0';\n\n setTimeout(() => {\n overlay.remove();\n }, duration * 1000);\n });\n}\n\n/* -----------------------------------------------------------------------------\n * Text parsing & expression helpers\n * ---------------------------------------------------------------------------*/\nfunction parseTextIntoParts(\n rawText: string\n): { type: 'static' | 'dynamic'; value: string }[] {\n const parts: { type: 'static' | 'dynamic'; value: string }[] = [];\n\n let lastIndex = 0;\n let match: RegExpExecArray | null;\n\n INTERPOLATION_RE.lastIndex = 0;\n while ((match = INTERPOLATION_RE.exec(rawText)) !== null) {\n if (match.index > lastIndex) {\n parts.push({\n type: 'static',\n value: rawText.slice(lastIndex, match.index),\n });\n }\n parts.push({ type: 'dynamic', value: match[1].trim() });\n lastIndex = match.index + match[0].length;\n }\n\n if (lastIndex < rawText.length) {\n parts.push({ type: 'static', value: rawText.slice(lastIndex) });\n }\n\n return parts;\n}\n\nfunction isTemplateText(node: Text): boolean {\n const { __pithyCtx, __pithyNode } = nodeExpando(node);\n return (\n __pithyCtx !== undefined &&\n __pithyNode?.textContent === node.nodeValue &&\n !!node.nodeValue?.includes('{{')\n );\n}\n\n/**\n * Is the expression a signal call? (e.g., count(), user.tags())\n * We compile the callee (without \"()\") and ask isSignal() on the result.\n */\nfunction isSignalExpression(\n expr: string,\n ctx: Record<string, unknown>\n): boolean {\n // Quick test: must end with \"()\"\n if (!/\\(\\)$/.test(expr)) return false;\n\n try {\n const functionExpr = expr.replace(/\\(\\)$/, '');\n const compiledFn = compileExpression(functionExpr, ctx);\n const signalFunction = compiledFn();\n return isSignal(signalFunction);\n } catch {\n return false;\n }\n}\n\n/**\n * Returns true if `node` is inside any subtree we must not text-bind now:\n * - A nested-loop host we tagged earlier: __pithySkipText\n * - A node a component rendered, or one inside it: __pithyComponentDom\n * - An element that still carries @for or data-for (depending on compiler phase)\n */\nfunction isInsideSkippedZone(\n node: Node,\n root: Element | DocumentFragment\n): boolean {\n if (nodeExpando(node).__pithyComponentDom) return true;\n let insideRoot = true;\n let p: Element | null = node instanceof Element ? node : node.parentElement;\n while (p) {\n if (p === root) insideRoot = false;\n if (\n nodeExpando(p).__pithySkipText ||\n (insideRoot && nodeExpando(p).__pithyComponentDom)\n )\n return true;\n if (\n p.hasAttribute &&\n (p.hasAttribute('@for') || p.hasAttribute('data-for'))\n ) {\n return true;\n }\n p = p.parentElement;\n }\n return false;\n}\n"]}
1
+ {"version":3,"file":"bindTextInterpolations.js","sourceRoot":"","sources":["../../../src/compile/binds/bindTextInterpolations.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAEF,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAC7C,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AACpD,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAC3C,OAAO,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AACzD,OAAO,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AACvC,OAAO,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC;AACrD,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAE7C,M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AAK,IAAI;YAAE,UAAU,GAAG,KAAK,CAAC;QACnC,IACE,WAAW,CAAC,CAAC,CAAC,CAAC,eAAe;YAC9B,CAAC,UAAU,IAAI,WAAW,CAAC,CAAC,CAAC,CAAC,mBAAmB,CAAC;YAElD,OAAO,IAAI,CAAC;QACd,IACE,CAAC,CAAC,YAAY;YACd,CAAC,CAAC,CAAC,YAAY,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,YAAY,CAAC,UAAU,CAAC,CAAC,EACtD,CAAC;YACD,OAAO,IAAI,CAAC;QACd,CAAC;QACD,CAAC,GAAG,CAAC,CAAC,aAAa,CAAC;IACtB,CAAC;IACD,OAAO,KAAK,CAAC;AACf,CAAC","sourcesContent":["/** @codex\n{\n \"id\": \"pithy.runtime.interpolations\",\n \"title\": \"Text Interpolation Binding System\",\n \"category\": \"runtime\"\n}\n*/\n\nimport { defaultConfig } from '../../config';\nimport { effect, isSignal } from '@pithyjs/signals';\nimport { toTextValue } from '../textValue';\nimport { compileExpression } from '../compileExpression';\nimport { isSSRMode } from '../ssrMode';\nimport { textEvalMessage } from '../evalDiagnostics';\nimport { nodeExpando } from '../nodeExpando';\n\nconst INTERPOLATION_RE = /{{\\s*([\\s\\S]*?)\\s*}}/g;\n\n/**\n * Bind all text interpolations (e.g. \"Hello {{name()}}\") under `root`.\n * - Binds only text still as the template parser created it.\n * - Skips nested-loop subtrees (tagged with __pithySkipText) and real @for/data-for hosts.\n * - Skips DOM a component rendered (__pithyComponentDom); the component bound it itself.\n * - Binds per-text-node updates with fine-grained effects.\n */\n/** @codexApi {\"parent\":\"pithy.runtime.interpolations\",\"name\":\"bindTextInterpolations\",\"stability\":\"stable\",\"signature\":\"(root: Element | DocumentFragment, ctx: Record<string, unknown>, disposers: (() => void)[]) => void\"} */\nexport function bindTextInterpolations(\n root: Element | DocumentFragment,\n _ctx: Record<string, unknown>,\n disposers: (() => void)[]\n): void {\n processChildNodes(root, disposers);\n bindRemainingTextInterpolations(root, disposers);\n}\n\n/* -----------------------------------------------------------------------------\n * Internal: robust child iteration (Element | DocumentFragment)\n * ---------------------------------------------------------------------------*/\nfunction childElementsOf(root: Element | DocumentFragment): Element[] {\n if (root instanceof Element) return Array.from(root.children);\n // DocumentFragment doesn't have .children; filter childNodes to elements\n const out: Element[] = [];\n root.childNodes.forEach(n => {\n if (n.nodeType === Node.ELEMENT_NODE) out.push(n as Element);\n });\n return out;\n}\n\n/**\n * Walk immediate children and process text nodes inside them.\n * We purposely avoid stepping into nested-loop subtrees to prevent compiling\n * expressions like {{ item() }} against the parent context.\n */\nfunction processChildNodes(\n root: Element | DocumentFragment,\n disposers: (() => void)[]\n): void {\n for (const child of childElementsOf(root)) {\n // Fast-path: if the child itself is a loop host, we skip it entirely.\n if (\n child.hasAttribute?.('@for') ||\n nodeExpando(child).__pithySkipText ||\n nodeExpando(child).__pithyComponentDom\n )\n continue;\n\n const walker = document.createTreeWalker(child, NodeFilter.SHOW_TEXT);\n const targets: Text[] = [];\n let textNode: Text | null;\n\n while ((textNode = walker.nextNode() as Text | null)) {\n if (!isTemplateText(textNode)) continue;\n\n // Skip anything inside a nested loop host or explicit @for/data-for\n if (isInsideSkippedZone(textNode, root)) continue;\n\n targets.push(textNode);\n }\n\n // Mutate after collecting to avoid invalidating the walker during traversal.\n for (const node of targets) {\n // An earlier interpolation in this loop can write into a queued node.\n if (!isTemplateText(node)) continue;\n const rawText = node.nodeValue || '';\n const parts = parseTextIntoParts(rawText);\n const parent = node.parentElement;\n const nextSibling = node.nextSibling;\n if (!parent) continue;\n\n // Use the node's own __pithyCtx (set by pithyTreeToDom).\n // Projected slot content carries the *parent* component's context this way,\n // not the context of the component whose template holds the slot.\n // This mirrors the nearestCtx pattern used by bindEventHandlers.\n const nodeCtx = nodeExpando(node).__pithyCtx!;\n\n parent.removeChild(node);\n\n for (const part of parts) {\n if (part.type === 'static') {\n insertStaticTextNode(parent, nextSibling, part.value);\n } else {\n // Determine interpolation mode based on config\n const mode = defaultConfig.textInterpolationMode || 'text-node';\n const isSignal = isSignalExpression(part.value, nodeCtx);\n\n // Choose insertion strategy\n if (mode === 'span') {\n // Always use span wrappers\n insertDynamicSpan(\n parent,\n nextSibling,\n part.value,\n nodeCtx,\n disposers\n );\n } else if (mode === 'text-node') {\n // Always use text nodes with comment anchors\n insertDynamicTextNode(\n parent,\n nextSibling,\n part.value,\n nodeCtx,\n disposers\n );\n } else {\n // 'auto' mode: span for signals if autoWrapSignals is true, text node otherwise\n if (isSignal && defaultConfig.autoWrapSignals) {\n insertDynamicSpan(\n parent,\n nextSibling,\n part.value,\n nodeCtx,\n disposers\n );\n } else {\n insertDynamicTextNode(\n parent,\n nextSibling,\n part.value,\n nodeCtx,\n disposers\n );\n }\n }\n }\n }\n }\n }\n}\n\n/**\n * Second pass: text nodes directly under `root` (e.g., loose text, or nodes\n * not caught by processChildNodes). Also respects skip zones.\n */\nfunction bindRemainingTextInterpolations(\n root: Element | DocumentFragment,\n disposers: (() => void)[]\n): void {\n const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);\n\n let node: Text | null;\n while ((node = walker.nextNode() as Text | null)) {\n if (!isTemplateText(node)) continue;\n const rawText = node.nodeValue!;\n\n // Robust skip: private flag, @for, or data-for anywhere up the chain.\n if (isInsideSkippedZone(node, root)) continue;\n\n INTERPOLATION_RE.lastIndex = 0;\n const matches = [...rawText.matchAll(INTERPOLATION_RE)];\n if (matches.length === 0) continue;\n\n // Use the node's own __pithyCtx (projected slot content\n // carries the parent component's context via this property).\n const nodeCtx = nodeExpando(node).__pithyCtx!;\n // The node keeps its identity and now holds a value: an outer pass must not read it.\n nodeExpando(node).__pithyCtx = undefined;\n\n const renderFns: (() => unknown)[] = [];\n const matchStrings: string[] = [];\n const expressions: string[] = [];\n\n for (const match of matches) {\n const expr = match[1].trim();\n matchStrings.push(match[0]);\n expressions.push(expr);\n renderFns.push(compileExpression(expr, nodeCtx));\n }\n\n bindTextNodeUpdates(\n node,\n rawText,\n expressions,\n matchStrings,\n renderFns,\n disposers\n );\n }\n}\n\n/* -----------------------------------------------------------------------------\n * Node insertion helpers\n * ---------------------------------------------------------------------------*/\nfunction insertStaticTextNode(\n parent: Element,\n nextSibling: ChildNode | null,\n text: string\n): void {\n const staticNode = document.createTextNode(text);\n parent.insertBefore(staticNode, nextSibling);\n}\n\nfunction insertDynamicSpan(\n parent: Element,\n nextSibling: ChildNode | null,\n expression: string,\n ctx: Record<string, unknown>,\n disposers: (() => void)[]\n): void {\n const span = document.createElement('span');\n span.className = 'r-pithy';\n span.style.display = 'inline';\n\n const textNode = document.createTextNode('');\n span.appendChild(textNode);\n parent.insertBefore(span, nextSibling);\n\n bindDynamicTextNode(textNode, expression, ctx, disposers, span);\n}\n\nfunction insertDynamicTextNode(\n parent: Element,\n nextSibling: ChildNode | null,\n expression: string,\n ctx: Record<string, unknown>,\n disposers: (() => void)[]\n): void {\n // Create comment anchors for structural markers (Solid.js approach)\n // This provides better debugging and potential future optimizations\n const startComment = document.createComment('t');\n const textNode = document.createTextNode('');\n const endComment = document.createComment('/t');\n\n // Insert in order: start comment, text node, end comment\n parent.insertBefore(startComment, nextSibling);\n parent.insertBefore(textNode, nextSibling);\n parent.insertBefore(endComment, nextSibling);\n\n bindDynamicTextNode(textNode, expression, ctx, disposers);\n}\n\n/* -----------------------------------------------------------------------------\n * Binding helpers\n * ---------------------------------------------------------------------------*/\nfunction bindTextNodeUpdates(\n node: Text,\n rawText: string,\n expressions: string[],\n matchStrings: string[],\n renderFns: (() => unknown)[],\n disposers: (() => void)[]\n): void {\n function evaluate() {\n let output = rawText;\n\n // Evaluate each {{ expr }} and replace into the original text\n expressions.forEach((_, i) => {\n try {\n const result = renderFns[i](); // compileExpression already closes over ctx\n // Function replacer: never let `$&`, `$$`, `$\\``, `$'`, `$n` in the\n // value be interpreted as String.replace special patterns — the value\n // must be inserted verbatim (e.g. literal code like `str.replace(/a/, '$&')`).\n output = output.replace(matchStrings[i], () => toTextValue(result));\n } catch (err) {\n console.error(textEvalMessage(expressions[i]), err);\n output = output.replace(matchStrings[i], '');\n }\n });\n\n return output;\n }\n\n if (isSSRMode()) {\n // SSR mode: evaluate once synchronously, no reactive effects\n node.nodeValue = evaluate();\n } else {\n let lastInterpolatedText: string | undefined;\n\n const stop = effect(() => {\n const output = evaluate();\n\n if (output !== lastInterpolatedText) {\n node.nodeValue = output;\n flashUpdate(node);\n lastInterpolatedText = output;\n }\n });\n\n disposers.push(stop);\n }\n}\n\n/**\n * Bind a single dynamic expression into a text node, with optional highlight target (e.g., wrapper span).\n */\nfunction bindDynamicTextNode(\n textNode: Text,\n expression: string,\n ctx: Record<string, unknown>,\n disposers: (() => void)[],\n highlightTarget?: HTMLElement\n): void {\n try {\n const compiledFn = compileExpression(expression, ctx);\n\n if (isSSRMode()) {\n // SSR mode: evaluate once synchronously, no reactive effects\n try {\n textNode.nodeValue = toTextValue(compiledFn());\n } catch (err) {\n console.error(textEvalMessage(expression), err);\n textNode.nodeValue = '';\n }\n } else {\n let lastValue: string | undefined;\n\n const stop = effect(() => {\n try {\n const result = compiledFn(); // re-evaluates reactively\n const next = toTextValue(result); // ensure string\n\n if (next !== lastValue) {\n // only mutate/flash on change\n textNode.nodeValue = next;\n\n if (highlightTarget) {\n flashUpdate(highlightTarget);\n } else {\n flashUpdate(textNode);\n }\n\n lastValue = next;\n }\n } catch (err) {\n console.error(textEvalMessage(expression), err);\n textNode.nodeValue = '';\n lastValue = '';\n }\n });\n\n disposers.push(stop);\n }\n } catch (err) {\n console.error(`[PithyJS] ❌ Failed to compile: ${expression}`, err);\n }\n}\n\n/* -----------------------------------------------------------------------------\n * Batched flashing (dev only). Reduces style/layout churn vs per-node inline updates.\n *\n * For text nodes, we create temporary positioned overlays at the exact text location\n * to provide visual feedback without adding permanent DOM nodes or flashing parent elements.\n * ---------------------------------------------------------------------------*/\nexport function flashUpdate(node: Text | Element): void {\n const { highlightColor, highlightDuration, devHighlightDomUpdates } =\n defaultConfig;\n if (!import.meta.env?.DEV || !devHighlightDomUpdates) return;\n\n if (node.nodeType === Node.TEXT_NODE) {\n flashTextNode(node as Text, highlightColor || '', highlightDuration || 0.2);\n } else {\n enqueueFlash(\n node as HTMLElement,\n highlightColor || '',\n highlightDuration || 0.2\n );\n }\n}\n\nconst flashQueue = new Set<HTMLElement>();\nlet flashScheduled = false;\n// Pending cleanup timers per element — cancelled on re-flash so a previous\n// flash's timers can't clear the background/transition mid-fade of a newer\n// one (rapidly-updating bindings flash the same element in overlapping\n// windows).\nconst flashTimers = new WeakMap<\n HTMLElement,\n { fade: ReturnType<typeof setTimeout>; clear?: ReturnType<typeof setTimeout> }\n>();\nconst flashOriginals = new WeakMap<\n HTMLElement,\n {\n transition: string;\n backgroundColor: string;\n flashTransition: string;\n flashBackground: string;\n }\n>();\n\nfunction enqueueFlash(el: HTMLElement, color: string, duration: number) {\n flashQueue.add(el);\n if (flashScheduled) return;\n flashScheduled = true;\n\n requestAnimationFrame(() => {\n // Apply highlight to all queued nodes at once\n flashQueue.forEach(t => {\n const pending = flashTimers.get(t);\n if (pending) {\n clearTimeout(pending.fade);\n if (pending.clear !== undefined) clearTimeout(pending.clear);\n }\n const { style } = t;\n let original = flashOriginals.get(t);\n if (!original) {\n original = {\n transition: style.transition,\n backgroundColor: style.backgroundColor,\n flashTransition: '',\n flashBackground: '',\n };\n flashOriginals.set(t, original);\n } else {\n if (style.transition !== original.flashTransition) {\n original.transition = style.transition;\n }\n if (style.backgroundColor !== original.flashBackground) {\n original.backgroundColor = style.backgroundColor;\n }\n }\n const saved = original;\n\n style.transition = `background-color ${duration}s ease-out`;\n style.backgroundColor = color;\n saved.flashTransition = style.transition;\n saved.flashBackground = style.backgroundColor;\n\n const fade = setTimeout(() => {\n // Restore, don't set \"transparent\" — an explicit inline value would\n // permanently override the element's stylesheet background. Runs\n // even for disconnected nodes so a reattached element doesn't keep\n // stale inline highlight styles.\n if (style.backgroundColor === saved.flashBackground) {\n style.backgroundColor = saved.backgroundColor;\n }\n const clear = setTimeout(() => {\n if (style.transition === saved.flashTransition) {\n style.transition = saved.transition;\n }\n flashTimers.delete(t);\n flashOriginals.delete(t);\n }, duration * 1000);\n flashTimers.set(t, { fade, clear });\n }, 80);\n flashTimers.set(t, { fade });\n });\n\n flashQueue.clear();\n flashScheduled = false;\n });\n}\n\n/**\n * Flash a text node update by creating a temporary positioned overlay.\n * This provides visual feedback for text-node mode without permanent DOM nodes.\n */\nfunction flashTextNode(textNode: Text, color: string, duration: number) {\n if (!textNode.parentElement) return;\n\n // Get the exact bounding rect of the text node\n const range = document.createRange();\n range.selectNodeContents(textNode);\n const rect = range.getBoundingClientRect();\n range.detach();\n\n // Skip if text has no dimensions (empty or not rendered)\n if (rect.width === 0 || rect.height === 0) return;\n\n // Create temporary overlay positioned exactly over the text\n const overlay = document.createElement('div');\n overlay.style.cssText = `\n position: fixed;\n left: ${rect.left}px;\n top: ${rect.top}px;\n width: ${rect.width}px;\n height: ${rect.height}px;\n background-color: ${color};\n pointer-events: none;\n z-index: 999999;\n transition: opacity ${duration}s ease-out;\n opacity: 0.6;\n border-radius: 2px;\n `;\n\n document.body.appendChild(overlay);\n\n // Fade out and remove\n requestAnimationFrame(() => {\n overlay.style.opacity = '0';\n\n setTimeout(() => {\n overlay.remove();\n }, duration * 1000);\n });\n}\n\n/* -----------------------------------------------------------------------------\n * Text parsing & expression helpers\n * ---------------------------------------------------------------------------*/\nfunction parseTextIntoParts(\n rawText: string\n): { type: 'static' | 'dynamic'; value: string }[] {\n const parts: { type: 'static' | 'dynamic'; value: string }[] = [];\n\n let lastIndex = 0;\n let match: RegExpExecArray | null;\n\n INTERPOLATION_RE.lastIndex = 0;\n while ((match = INTERPOLATION_RE.exec(rawText)) !== null) {\n if (match.index > lastIndex) {\n parts.push({\n type: 'static',\n value: rawText.slice(lastIndex, match.index),\n });\n }\n parts.push({ type: 'dynamic', value: match[1].trim() });\n lastIndex = match.index + match[0].length;\n }\n\n if (lastIndex < rawText.length) {\n parts.push({ type: 'static', value: rawText.slice(lastIndex) });\n }\n\n return parts;\n}\n\nfunction isTemplateText(node: Text): boolean {\n const { __pithyCtx, __pithyNode } = nodeExpando(node);\n return (\n __pithyCtx !== undefined &&\n !__pithyNode?.inert &&\n __pithyNode?.textContent === node.nodeValue &&\n !!node.nodeValue?.includes('{{')\n );\n}\n\n/**\n * Is the expression a signal call? (e.g., count(), user.tags())\n * We compile the callee (without \"()\") and ask isSignal() on the result.\n */\nfunction isSignalExpression(\n expr: string,\n ctx: Record<string, unknown>\n): boolean {\n // Quick test: must end with \"()\"\n if (!/\\(\\)$/.test(expr)) return false;\n\n try {\n const functionExpr = expr.replace(/\\(\\)$/, '');\n const compiledFn = compileExpression(functionExpr, ctx);\n const signalFunction = compiledFn();\n return isSignal(signalFunction);\n } catch {\n return false;\n }\n}\n\n/**\n * Returns true if `node` is inside any subtree we must not text-bind now:\n * - A nested-loop host we tagged earlier: __pithySkipText\n * - A node a component rendered, or one inside it: __pithyComponentDom\n * - An element that still carries @for or data-for (depending on compiler phase)\n */\nfunction isInsideSkippedZone(\n node: Node,\n root: Element | DocumentFragment\n): boolean {\n if (nodeExpando(node).__pithyComponentDom) return true;\n let insideRoot = true;\n let p: Element | null = node instanceof Element ? node : node.parentElement;\n while (p) {\n if (p === root) insideRoot = false;\n if (\n nodeExpando(p).__pithySkipText ||\n (insideRoot && nodeExpando(p).__pithyComponentDom)\n )\n return true;\n if (\n p.hasAttribute &&\n (p.hasAttribute('@for') || p.hasAttribute('data-for'))\n ) {\n return true;\n }\n p = p.parentElement;\n }\n return false;\n}\n"]}
@@ -15,7 +15,7 @@ export function isDeclaredDirective(attr) {
15
15
  if (expando.__forwardedDirectives?.get(name) === value)
16
16
  return true;
17
17
  const node = expando.__pithyNode;
18
- if (!node)
18
+ if (!node || node.inert)
19
19
  return false;
20
20
  if (isTemplateAttr(attr))
21
21
  return true;
@@ -1 +1 @@
1
- {"version":3,"file":"declaredDirective.js","sourceRoot":"","sources":["../../../src/compile/binds/declaredDirective.ts"],"names":[],"mappings":"AAA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;IAChE,MAAM,KAAK,GAAG,YAAY,IAAI,WAAW,CAAC,YAAY,CAAC,CAAC,WAAW,EAAE,KAAK,CAAC;IAC3E,OAAO,KAAK,EAAE,CAAC,IAAI,CAAC,KAAK,KAAK,IAAI,KAAK,EAAE,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC,KAAK,KAAK,CAAC;AACxE,CAAC;AAED,2DAA2D;AAC3D,MAAM,UAAU,aAAa,CAAC,EAAW,EAAE,IAAY;IACrD,MAAM,IAAI,GAAG,EAAE,CAAC,gBAAgB,CAAC,IAAI,CAAC,CAAC;IACvC,OAAO,IAAI,IAAI,mBAAmB,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,SAAS,CAAC;AACpE,CAAC","sourcesContent":["import { forEachDirectiveAttr } from '@pithyjs/compiler';\nimport { nodeExpando } from '../nodeExpando';\n\nconst asciiLower = (s: string) => s.replace(/[A-Z]/g, c => c.toLowerCase());\n\n/**\n * Whether a directive attribute holds what a template wrote. A binder may\n * compile the value only then: `[data-on-click]` or a component can put data\n * into the same attribute, and a nested pass sees it. The value is compared\n * as well as the name, since such a write can replace a declared directive.\n */\nexport function isDeclaredDirective(attr: Attr): boolean {\n const { name, value, ownerElement: el } = attr;\n if (!el) return false;\n const expando = nodeExpando(el);\n if (expando.__forwardedDirectives?.get(name) === value) return true;\n const node = expando.__pithyNode;\n if (!node) return false;\n if (isTemplateAttr(attr)) return true;\n let declared = false;\n if (node.directives) {\n const lower = asciiLower(name);\n forEachDirectiveAttr(node.directives, (attrName, expr) => {\n if (expr === value && asciiLower(attrName) === lower) declared = true;\n });\n }\n return declared;\n}\n\n/** Whether a template wrote this attribute as a plain, unbound attribute. */\nexport function isTemplateAttr({ name, value, ownerElement }: Attr): boolean {\n const attrs = ownerElement && nodeExpando(ownerElement).__pithyNode?.attrs;\n return attrs?.[name] === value || attrs?.[asciiLower(name)] === value;\n}\n\n/** The value of `name` on `el`, if a template wrote it. */\nexport function declaredValue(el: Element, name: string): string | undefined {\n const attr = el.getAttributeNode(name);\n return attr && isDeclaredDirective(attr) ? attr.value : undefined;\n}\n"]}
1
+ {"version":3,"file":"declaredDirective.js","sourceRoot":"","sources":["../../../src/compile/binds/declaredDirective.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,oBAAoB,EAAE,MAAM,mBAAmB,CAAC;AACzD,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAE7C,MAAM,UAAU,GAAG,CAAC,CAAS,EAAE,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,QAAQ,EAAE,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,WAAW,EAAE,CAAC,CAAC;AAE5E;;;;;GAKG;AACH,MAAM,UAAU,mBAAmB,CAAC,IAAU;IAC5C,MAAM,EAAE,IAAI,EAAE,KAAK,EAAE,YAAY,EAAE,EAAE,EAAE,GAAG,IAAI,CAAC;IAC/C,IAAI,CAAC,EAAE;QAAE,OAAO,KAAK,CAAC;IACtB,MAAM,OAAO,GAAG,WAAW,CAAC,EAAE,CAAC,CAAC;IAChC,IAAI,OAAO,CAAC,qBAAqB,EAAE,GAAG,CAAC,IAAI,CAAC,KAAK,KAAK;QAAE,OAAO,IAAI,CAAC;IACpE,MAAM,IAAI,GAAG,OAAO,CAAC,WAAW,CAAC;IACjC,IAAI,CAAC,IAAI,IAAI,IAAI,CAAC,KAAK;QAAE,OAAO,KAAK,CAAC;IACtC,IAAI,cAAc,CAAC,IAAI,CAAC;QAAE,OAAO,IAAI,CAAC;IACtC,IAAI,QAAQ,GAAG,KAAK,CAAC;IACrB,IAAI,IAAI,CAAC,UAAU,EAAE,CAAC;QACpB,MAAM,KAAK,GAAG,UAAU,CAAC,IAAI,CAAC,CAAC;QAC/B,oBAAoB,CAAC,IAAI,CAAC,UAAU,EAAE,CAAC,QAAQ,EAAE,IAAI,EAAE,EAAE;YACvD,IAAI,IAAI,KAAK,KAAK,IAAI,UAAU,CAAC,QAAQ,CAAC,KAAK,KAAK;gBAAE,QAAQ,GAAG,IAAI,CAAC;QACxE,CAAC,CAAC,CAAC;IACL,CAAC;IACD,OAAO,QAAQ,CAAC;AAClB,CAAC;AAED,6EAA6E;AAC7E,MAAM,UAAU,cAAc,CAAC,EAAE,IAAI,EAAE,KAAK,EAAE,YAAY,EAAQ;IAChE,MAAM,KAAK,GAAG,YAAY,IAAI,WAAW,CAAC,YAAY,CAAC,CAAC,WAAW,EAAE,KAAK,CAAC;IAC3E,OAAO,KAAK,EAAE,CAAC,IAAI,CAAC,KAAK,KAAK,IAAI,KAAK,EAAE,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC,KAAK,KAAK,CAAC;AACxE,CAAC;AAED,2DAA2D;AAC3D,MAAM,UAAU,aAAa,CAAC,EAAW,EAAE,IAAY;IACrD,MAAM,IAAI,GAAG,EAAE,CAAC,gBAAgB,CAAC,IAAI,CAAC,CAAC;IACvC,OAAO,IAAI,IAAI,mBAAmB,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,SAAS,CAAC;AACpE,CAAC","sourcesContent":["import { forEachDirectiveAttr } from '@pithyjs/compiler';\nimport { nodeExpando } from '../nodeExpando';\n\nconst asciiLower = (s: string) => s.replace(/[A-Z]/g, c => c.toLowerCase());\n\n/**\n * Whether a directive attribute holds what a template wrote. A binder may\n * compile the value only then: `[data-on-click]` or a component can put data\n * into the same attribute, and a nested pass sees it. The value is compared\n * as well as the name, since such a write can replace a declared directive.\n */\nexport function isDeclaredDirective(attr: Attr): boolean {\n const { name, value, ownerElement: el } = attr;\n if (!el) return false;\n const expando = nodeExpando(el);\n if (expando.__forwardedDirectives?.get(name) === value) return true;\n const node = expando.__pithyNode;\n if (!node || node.inert) return false;\n if (isTemplateAttr(attr)) return true;\n let declared = false;\n if (node.directives) {\n const lower = asciiLower(name);\n forEachDirectiveAttr(node.directives, (attrName, expr) => {\n if (expr === value && asciiLower(attrName) === lower) declared = true;\n });\n }\n return declared;\n}\n\n/** Whether a template wrote this attribute as a plain, unbound attribute. */\nexport function isTemplateAttr({ name, value, ownerElement }: Attr): boolean {\n const attrs = ownerElement && nodeExpando(ownerElement).__pithyNode?.attrs;\n return attrs?.[name] === value || attrs?.[asciiLower(name)] === value;\n}\n\n/** The value of `name` on `el`, if a template wrote it. */\nexport function declaredValue(el: Element, name: string): string | undefined {\n const attr = el.getAttributeNode(name);\n return attr && isDeclaredDirective(attr) ? attr.value : undefined;\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;AA2HvB,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,C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;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,CAmZxC"}
@@ -106,6 +106,11 @@ function restoreNodeMetadata(source, target, ctx) {
106
106
  for (let i = 0; i < srcChildren.length; i++) {
107
107
  restoreNodeMetadata(srcChildren[i], tgtChildren[i], ctx);
108
108
  }
109
+ if (isTemplate(source) && isTemplate(target))
110
+ restoreNodeMetadata(source.content, target.content, ctx);
111
+ }
112
+ function isTemplate(node) {
113
+ return node.localName === 'template' && 'content' in node;
109
114
  }
110
115
  /** @codexApi {"parent":"pithy.directive.loop-manager","name":"createLoopManager","stability":"stable","signature":"<T>(options: LoopManagerOptions<T>) => LoopManager<T>"} */
111
116
  export function createLoopManager({ anchor, trackByFn, parentCtx, itemVar, indexVar, countVar, firstVar, lastVar, evenVar, oddVar, templateNodes, itemFactory, }) {
@@ -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;AAC7C,OAAO,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAClD,OAAO,EAAE,kBAAkB,EAAE,MAAM,4BAA4B,CAAC;AAChE,OAAO,EAAE,YAAY,EAAE,MAAM,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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';\nimport { withBranchBoundary } from '../binds/bindErrorBoundary';\nimport { withinRender } from '../ssrCrashes';\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 withinRender(() =>\n withBranchBoundary(anchor, () => updateNow(collection, node))\n );\n }\n\n function updateNow(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
+ {"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;AAC7C,OAAO,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAClD,OAAO,EAAE,kBAAkB,EAAE,MAAM,4BAA4B,CAAC;AAChE,OAAO,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AAM7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AAC,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';\nimport { withBranchBoundary } from '../binds/bindErrorBoundary';\nimport { withinRender } from '../ssrCrashes';\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 if (isTemplate(source) && isTemplate(target))\n restoreNodeMetadata(source.content, target.content, ctx);\n}\n\nfunction isTemplate(node: Node): node is HTMLTemplateElement {\n return (node as Element).localName === 'template' && 'content' in node;\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 withinRender(() =>\n withBranchBoundary(anchor, () => updateNow(collection, node))\n );\n }\n\n function updateNow(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":"parseHtml.d.ts","sourceRoot":"","sources":["../../src/compile/parseHtml.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAEF,OAAO,EAKL,KAAK,SAAS,EACf,MAAM,mBAAmB,CAAC;AAS3B,yFAAyF;AACzF,KAAK,eAAe,GAAG,CACrB,IAAI,EAAE,MAAM,EACZ,OAAO,CAAC,EAAE;IAAE,sBAAsB,CAAC,EAAE,OAAO,CAAA;CAAE,KAC3C,OAAO,CAAC;AAKb;;;;;;;;GAQG;AACH,wIAAwI;AACxI,wBAAgB,eAAe,IAAI,OAAO,CAAC,IAAI,CAAC,CAsB/C;AAED;;;;GAIG;AACH,gIAAgI;AAChI,wBAAgB,WAAW,IAAI,OAAO,CAErC;AAgBD;;;GAGG;AACH,+HAA+H;AAC/H,wBAAgB,aAAa,IAAI,IAAI,CAGpC;AAED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Q,wBAAgB,SAAS,CACvB,IAAI,EAAE,MAAM,EACZ,OAAO,EAAE,MAAM,EACf,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAChC,mBAAmB,GAAE,GAAG,CAAC,MAAM,CAAa,GAC3C;IACD,QAAQ,EAAE,gBAAgB,CAAC;IAC3B,UAAU,EAAE,SAAS,EAAE,CAAC;CACzB,CAqDA"}
@@ -127,9 +127,7 @@ export function parseHtml(html, scopeId, context, importedIdentifiers = new Set(
127
127
  // 3. Compile DOM tree from PithyNodes
128
128
  const fragment = pithyTreeToDom(pithyNodes, context);
129
129
  // 4. Add data-scope attribute to all elements
130
- fragment.querySelectorAll?.('*').forEach(el => {
131
- el.setAttribute(`data-scope-${scopeId}`, '');
132
- });
130
+ addScope(fragment, scopeId);
133
131
  return {
134
132
  fragment,
135
133
  pithyNodes,
@@ -162,4 +160,11 @@ function preprocessSelfClosingComponents(html, importedIdentifiers) {
162
160
  }
163
161
  return processedHtml;
164
162
  }
163
+ function addScope(root, scopeId) {
164
+ root.querySelectorAll?.('*').forEach(el => {
165
+ el.setAttribute(`data-scope-${scopeId}`, '');
166
+ if (el.localName === 'template' && 'content' in el)
167
+ addScope(el.content, scopeId);
168
+ });
169
+ }
165
170
  //# sourceMappingURL=parseHtml.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"parseHtml.js","sourceRoot":"","sources":["../../src/compile/parseHtml.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAEF,OAAO,EACL,iBAAiB,EACjB,mBAAmB,EACnB,uBAAuB,EACvB,6BAA6B,GAE9B,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAclD,IAAI,cAAc,GAA2B,IAAI,CAAC;AAClD,IAAI,YAAY,GAAyB,IAAI,CAAC;AAE9C;;;;;;;;GAQG;AACH,wIAAwI;AACxI,MAAM,UAAU,eAAe;IAC7B,IAAI,cAAc;QAAE,OAAO,OAAO,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AC;AACJ,CAAC;AAED;;;;;;;GAOG;AACH,+LAA+L;AAC/L,SAAS,+BAA+B,CACtC,IAAY,EACZ,mBAAgC;IAEhC,IAAI,aAAa,GAAG,IAAI,CAAC;IAEzB,mEAAmE;IACnE,KAAK,MAAM,aAAa,IAAI,mBAAmB,EAAE,CAAC;QAChD,oDAAoD;QACpD,iDAAiD;QACjD,gFAAgF;QAChF,wEAAwE;QACxE,2EAA2E;QAC3E,MAAM,gBAAgB,GAAG,IAAI,MAAM,CACjC,IAAI,aAAa,gDAAgD,EACjE,GAAG,CACJ,CAAC;QAEF,gDAAgD;QAChD,aAAa,GAAG,aAAa,CAAC,OAAO,CACnC,gBAAgB,EAChB,CAAC,KAAK,EAAE,UAAU,EAAE,EAAE;YACpB,MAAM,KAAK,GAAG,UAAU,IAAI,EAAE,CAAC;YAC/B,OAAO,IAAI,aAAa,GAAG,KAAK,MAAM,aAAa,GAAG,CAAC;QACzD,CAAC,CACF,CAAC;IACJ,CAAC;IAED,OAAO,aAAa,CAAC;AACvB,CAAC","sourcesContent":["/** @codex\n{\n \"id\": \"pithy.compiler.html-parser\",\n \"title\": \"HTML Template Parser\",\n \"category\": \"compiler\"\n}\n*/\n\nimport {\n parse5ToPithyTree,\n escapeComponentTags,\n extractOriginalTagNames,\n extractOriginalAttributeNames,\n type PithyNode,\n} from '@pithyjs/compiler';\nimport { pithyTreeToDom } from './pithyTreeToDom';\n\n// ─── Dynamic parse5 loading ──────────────────────────────────────────────────\n// parse5 is no longer statically imported. It is loaded on demand via\n// loadJITCompiler() and cached in this module-level variable.\n// This ensures parse5 (45.6 KB gzip) is tree-shaken from production bundles\n// when all templates are AOT-compiled.\n\n/** Structural type matching parse5's parseFragment — avoids leaking parse5 into .d.ts */\ntype ParseFragmentFn = (\n html: string,\n options?: { sourceCodeLocationInfo?: boolean }\n) => unknown;\n\nlet _parseFragment: ParseFragmentFn | null = null;\nlet _loadPromise: Promise<void> | null = null;\n\n/**\n * Dynamically import parse5 and cache the parseFragment function.\n * Must be called before using html() for runtime template compilation.\n *\n * If all templates are AOT-compiled, this function never needs to be called\n * and parse5 will be completely absent from the production bundle.\n *\n * @returns Promise that resolves when parse5 is ready\n */\n/** @codexApi {\"parent\":\"pithy.compiler.html-parser\",\"name\":\"loadJITCompiler\",\"stability\":\"stable\",\"signature\":\"() => Promise<void>\"} */\nexport function loadJITCompiler(): Promise<void> {\n if (_parseFragment) return Promise.resolve(); // Already loaded\n if (_loadPromise) return _loadPromise; // Loading in progress — reuse same promise\n\n _loadPromise = import('parse5')\n .then(mod => {\n _parseFragment = mod.parseFragment;\n _loadPromise = null;\n })\n .catch(err => {\n // Reset so a retry can be attempted (e.g., after installing parse5)\n _loadPromise = null;\n // Manual `.cause` assignment instead of `new Error(msg, { cause })`\n // because the project targets ES2020 which doesn't support Error cause.\n const loadErr = new Error(\n 'Failed to load parse5. Install it (`pnpm add parse5`) or enable AOT compilation to avoid the runtime compiler.'\n );\n (loadErr as Error & { cause?: unknown }).cause = err;\n throw loadErr;\n });\n\n return _loadPromise;\n}\n\n/**\n * Check if the JIT compiler (parse5) has been loaded.\n * Used internally by parseHtml to provide a clear error message.\n * @returns `true` if parse5 parseFragment is cached\n */\n/** @codexApi {\"parent\":\"pithy.compiler.html-parser\",\"name\":\"isJITLoaded\",\"stability\":\"internal\",\"signature\":\"() => boolean\"} */\nexport function isJITLoaded(): boolean {\n return _parseFragment !== null;\n}\n\n/**\n * Get the cached parseFragment function, throwing if not loaded.\n * @internal\n */\nfunction getParseFragment(): ParseFragmentFn {\n if (!_parseFragment) {\n throw new Error(\n 'Runtime template compiler not loaded. Enable AOT compilation (recommended) ' +\n 'or call loadJITCompiler() at startup.'\n );\n }\n return _parseFragment;\n}\n\n/**\n * Reset JIT compiler state. For testing only.\n * @internal\n */\n/** @codexApi {\"parent\":\"pithy.compiler.html-parser\",\"name\":\"resetJITState\",\"stability\":\"internal\",\"signature\":\"() => void\"} */\nexport function resetJITState(): void {\n _parseFragment = null;\n _loadPromise = null;\n}\n\n/**\n * Pre-load parse5 synchronously for environments where it's already available\n * (e.g., Node.js test environments, SSR). This is a convenience for the\n * transition period — production code should use loadJITCompiler().\n * @internal\n */\n/** @codexApi {\"parent\":\"pithy.compiler.html-parser\",\"name\":\"setParseFragment\",\"stability\":\"internal\",\"signature\":\"(fn: ParseFragmentFn) => void\"} */\nexport function setParseFragment(fn: ParseFragmentFn): void {\n _parseFragment = fn;\n}\n\n/**\n * Return the cached parseFragment function (or null if not loaded).\n * Used by parseIdentifiersFromTemplate to reuse the same parse5 instance\n * loaded via loadJITCompiler(), avoiding a separate dynamic import.\n * @internal\n */\n/** @codexApi {\"parent\":\"pithy.compiler.html-parser\",\"name\":\"getParseFragmentFn\",\"stability\":\"internal\",\"signature\":\"() => ParseFragmentFn | null\"} */\nexport function getParseFragmentFn(): ParseFragmentFn | null {\n return _parseFragment;\n}\n\n// ─── Main API ────────────────────────────────────────────────────────────────\n\n/**\n * Parse an HTML template string into a DOM fragment with PithyNode metadata.\n * Requires parse5 to be loaded first via `loadJITCompiler()` or `setParseFragment()`.\n * Throws if the runtime compiler has not been loaded.\n *\n * @param html - Raw HTML template string\n * @param scopeId - Unique scope identifier for style scoping\n * @param context - Reactive context for expression evaluation\n * @param importedIdentifiers - Set of imported component names for self-closing tag handling\n * @returns Object with `fragment` (live DOM) and `pithyNodes` (AST metadata)\n */\n/** @codexApi {\"parent\":\"pithy.compiler.html-parser\",\"name\":\"parseHtml\",\"stability\":\"stable\",\"signature\":\"(html: string, scopeId: string, context: Record<string, unknown>, importedIdentifiers?: Set<string>) => { fragment: DocumentFragment; pithyNodes: PithyNode[] }\"} */\nexport function parseHtml(\n html: string,\n scopeId: string,\n context: Record<string, unknown>,\n importedIdentifiers: Set<string> = new Set()\n): {\n fragment: DocumentFragment;\n pithyNodes: PithyNode[];\n} {\n const parseFragment = getParseFragment();\n\n // 1. Pre-process HTML to convert self-closing component tags to regular tags\n const processedHtml = preprocessSelfClosingComponents(\n html,\n importedIdentifiers\n );\n\n // 2. Escape PascalCase component tags so parse5 doesn't enter special\n // insertion modes (e.g., \"in select\", \"in table\") that corrupt the tree.\n const escapedHtml = escapeComponentTags(processedHtml);\n\n // 3. Parse HTML into parse5 tree\n const parsed = parseFragment(escapedHtml, {\n sourceCodeLocationInfo: true,\n }) as {\n childNodes: unknown[];\n };\n\n // 4. Restore casing and tag type via your parser\n // IMPORTANT: Use escapedHtml (not raw html) because parse5 reports\n // sourceCodeLocation offsets based on escapedHtml. If we used raw html,\n // self-closing tag expansion (e.g. <Foo/> → <Foo></Foo>) and escape\n // prefixing would shift all subsequent offsets, causing casing map\n // lookups to miss for components that appear after other components.\n const tagNameCasingMap = extractOriginalTagNames(escapedHtml);\n const attributeNameCasingMap = extractOriginalAttributeNames(escapedHtml);\n\n const pithyNodes = parsed.childNodes\n .map((n: unknown) =>\n parse5ToPithyTree(\n n as Parameters<typeof parse5ToPithyTree>[0],\n importedIdentifiers,\n tagNameCasingMap,\n undefined,\n attributeNameCasingMap,\n undefined,\n escapedHtml\n )\n )\n .filter((n): n is PithyNode => n != null);\n\n // 3. Compile DOM tree from PithyNodes\n const fragment = pithyTreeToDom(pithyNodes, context);\n\n // 4. Add data-scope attribute to all elements\n fragment.querySelectorAll?.('*').forEach(el => {\n el.setAttribute(`data-scope-${scopeId}`, '');\n });\n\n return {\n fragment,\n pithyNodes,\n };\n}\n\n/**\n * Pre-processes HTML to convert self-closing component tags to regular tags.\n * This works around parse5's limitation with self-closing custom elements.\n *\n * @param html - The HTML template string\n * @param importedIdentifiers - Set of imported component names\n * @returns Processed HTML with self-closing components converted to regular tags\n */\n/** @codexApi {\"parent\":\"pithy.compiler.html-parser\",\"name\":\"preprocessSelfClosingComponents\",\"stability\":\"stable\",\"signature\":\"(html: string, importedIdentifiers: Set<string>) => string\"} */\nfunction preprocessSelfClosingComponents(\n html: string,\n importedIdentifiers: Set<string>\n): string {\n let processedHtml = html;\n\n // Convert each imported component from self-closing to regular tag\n for (const componentName of importedIdentifiers) {\n // Create regex to match self-closing component tags\n // Matches: <ComponentName /> or <ComponentName/>\n // IMPORTANT: Use 'g' flag only (NOT 'gi') - case-sensitive matching is required\n // to avoid converting native elements like <input /> to <Input></Input>\n // Quoted values may hold `>` (an arrow-function prop), so skip them whole.\n const selfClosingRegex = new RegExp(\n `<${componentName}(\\\\s(?:[^>\"']|\"[^\"]*\"|'[^']*')*?)?\\\\s*\\\\/\\\\s*>`,\n 'g'\n );\n\n // Replace with regular opening and closing tags\n processedHtml = processedHtml.replace(\n selfClosingRegex,\n (match, attributes) => {\n const attrs = attributes || '';\n return `<${componentName}${attrs}></${componentName}>`;\n }\n );\n }\n\n return processedHtml;\n}\n"]}
1
+ {"version":3,"file":"parseHtml.js","sourceRoot":"","sources":["../../src/compile/parseHtml.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAEF,OAAO,EACL,iBAAiB,EACjB,mBAAmB,EACnB,uBAAuB,EACvB,6BAA6B,GAE9B,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAclD,IAAI,cAAc,GAA2B,IAAI,CAAC;AAClD,IAAI,YAAY,GAAyB,IAAI,CAAC;AAE9C;;;;;;;;GAQG;AACH,wIAAwI;AACxI,MAAM,UAAU,eAAe;IAC7B,IAAI,cAAc;QAAE,OAAO,OAAO,CAAC,OAAO,EAAE,CAAC,CAAC,iBAAiB;IAC/D,IAAI,YAAY;QAAE,OAAO,YAAY,CAAC,CAAC,2CAA2C;IAElF,YAAY,GAAG,MAAM,CAAC,QAAQ,CAAC;SAC5B,IAAI,CAAC,GAAG,CAAC,EAAE;QACV,cAAc,GAAG,GAAG,CAAC,aAAa,CAAC;QACnC,YAAY,GAAG,IAAI,CAAC;IACtB,CAAC,CAAC;SACD,KAAK,CAAC,GAAG,CAAC,EAAE;QACX,oEAAoE;QACpE,YAAY,GAAG,IAAI,CAAC;QACpB,oEAAoE;QACpE,wEAAwE;QACxE,MAAM,OAAO,G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O,IAAI,aAAa,GAAG,KAAK,MAAM,aAAa,GAAG,CAAC;QACzD,CAAC,CACF,CAAC;IACJ,CAAC;IAED,OAAO,aAAa,CAAC;AACvB,CAAC;AAED,SAAS,QAAQ,CAAC,IAAgB,EAAE,OAAe;IACjD,IAAI,CAAC,gBAAgB,EAAE,CAAC,GAAG,CAAC,CAAC,OAAO,CAAC,EAAE,CAAC,EAAE;QACxC,EAAE,CAAC,YAAY,CAAC,cAAc,OAAO,EAAE,EAAE,EAAE,CAAC,CAAC;QAC7C,IAAI,EAAE,CAAC,SAAS,KAAK,UAAU,IAAI,SAAS,IAAI,EAAE;YAChD,QAAQ,CAAE,EAA0B,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;IAC3D,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["/** @codex\n{\n \"id\": \"pithy.compiler.html-parser\",\n \"title\": \"HTML Template Parser\",\n \"category\": \"compiler\"\n}\n*/\n\nimport {\n parse5ToPithyTree,\n escapeComponentTags,\n extractOriginalTagNames,\n extractOriginalAttributeNames,\n type PithyNode,\n} from '@pithyjs/compiler';\nimport { pithyTreeToDom } from './pithyTreeToDom';\n\n// ─── Dynamic parse5 loading ──────────────────────────────────────────────────\n// parse5 is no longer statically imported. It is loaded on demand via\n// loadJITCompiler() and cached in this module-level variable.\n// This ensures parse5 (45.6 KB gzip) is tree-shaken from production bundles\n// when all templates are AOT-compiled.\n\n/** Structural type matching parse5's parseFragment — avoids leaking parse5 into .d.ts */\ntype ParseFragmentFn = (\n html: string,\n options?: { sourceCodeLocationInfo?: boolean }\n) => unknown;\n\nlet _parseFragment: ParseFragmentFn | null = null;\nlet _loadPromise: Promise<void> | null = null;\n\n/**\n * Dynamically import parse5 and cache the parseFragment function.\n * Must be called before using html() for runtime template compilation.\n *\n * If all templates are AOT-compiled, this function never needs to be called\n * and parse5 will be completely absent from the production bundle.\n *\n * @returns Promise that resolves when parse5 is ready\n */\n/** @codexApi {\"parent\":\"pithy.compiler.html-parser\",\"name\":\"loadJITCompiler\",\"stability\":\"stable\",\"signature\":\"() => Promise<void>\"} */\nexport function loadJITCompiler(): Promise<void> {\n if (_parseFragment) return Promise.resolve(); // Already loaded\n if (_loadPromise) return _loadPromise; // Loading in progress — reuse same promise\n\n _loadPromise = import('parse5')\n .then(mod => {\n _parseFragment = mod.parseFragment;\n _loadPromise = null;\n })\n .catch(err => {\n // Reset so a retry can be attempted (e.g., after installing parse5)\n _loadPromise = null;\n // Manual `.cause` assignment instead of `new Error(msg, { cause })`\n // because the project targets ES2020 which doesn't support Error cause.\n const loadErr = new Error(\n 'Failed to load parse5. Install it (`pnpm add parse5`) or enable AOT compilation to avoid the runtime compiler.'\n );\n (loadErr as Error & { cause?: unknown }).cause = err;\n throw loadErr;\n });\n\n return _loadPromise;\n}\n\n/**\n * Check if the JIT compiler (parse5) has been loaded.\n * Used internally by parseHtml to provide a clear error message.\n * @returns `true` if parse5 parseFragment is cached\n */\n/** @codexApi {\"parent\":\"pithy.compiler.html-parser\",\"name\":\"isJITLoaded\",\"stability\":\"internal\",\"signature\":\"() => boolean\"} */\nexport function isJITLoaded(): boolean {\n return _parseFragment !== null;\n}\n\n/**\n * Get the cached parseFragment function, throwing if not loaded.\n * @internal\n */\nfunction getParseFragment(): ParseFragmentFn {\n if (!_parseFragment) {\n throw new Error(\n 'Runtime template compiler not loaded. Enable AOT compilation (recommended) ' +\n 'or call loadJITCompiler() at startup.'\n );\n }\n return _parseFragment;\n}\n\n/**\n * Reset JIT compiler state. For testing only.\n * @internal\n */\n/** @codexApi {\"parent\":\"pithy.compiler.html-parser\",\"name\":\"resetJITState\",\"stability\":\"internal\",\"signature\":\"() => void\"} */\nexport function resetJITState(): void {\n _parseFragment = null;\n _loadPromise = null;\n}\n\n/**\n * Pre-load parse5 synchronously for environments where it's already available\n * (e.g., Node.js test environments, SSR). This is a convenience for the\n * transition period — production code should use loadJITCompiler().\n * @internal\n */\n/** @codexApi {\"parent\":\"pithy.compiler.html-parser\",\"name\":\"setParseFragment\",\"stability\":\"internal\",\"signature\":\"(fn: ParseFragmentFn) => void\"} */\nexport function setParseFragment(fn: ParseFragmentFn): void {\n _parseFragment = fn;\n}\n\n/**\n * Return the cached parseFragment function (or null if not loaded).\n * Used by parseIdentifiersFromTemplate to reuse the same parse5 instance\n * loaded via loadJITCompiler(), avoiding a separate dynamic import.\n * @internal\n */\n/** @codexApi {\"parent\":\"pithy.compiler.html-parser\",\"name\":\"getParseFragmentFn\",\"stability\":\"internal\",\"signature\":\"() => ParseFragmentFn | null\"} */\nexport function getParseFragmentFn(): ParseFragmentFn | null {\n return _parseFragment;\n}\n\n// ─── Main API ────────────────────────────────────────────────────────────────\n\n/**\n * Parse an HTML template string into a DOM fragment with PithyNode metadata.\n * Requires parse5 to be loaded first via `loadJITCompiler()` or `setParseFragment()`.\n * Throws if the runtime compiler has not been loaded.\n *\n * @param html - Raw HTML template string\n * @param scopeId - Unique scope identifier for style scoping\n * @param context - Reactive context for expression evaluation\n * @param importedIdentifiers - Set of imported component names for self-closing tag handling\n * @returns Object with `fragment` (live DOM) and `pithyNodes` (AST metadata)\n */\n/** @codexApi {\"parent\":\"pithy.compiler.html-parser\",\"name\":\"parseHtml\",\"stability\":\"stable\",\"signature\":\"(html: string, scopeId: string, context: Record<string, unknown>, importedIdentifiers?: Set<string>) => { fragment: DocumentFragment; pithyNodes: PithyNode[] }\"} */\nexport function parseHtml(\n html: string,\n scopeId: string,\n context: Record<string, unknown>,\n importedIdentifiers: Set<string> = new Set()\n): {\n fragment: DocumentFragment;\n pithyNodes: PithyNode[];\n} {\n const parseFragment = getParseFragment();\n\n // 1. Pre-process HTML to convert self-closing component tags to regular tags\n const processedHtml = preprocessSelfClosingComponents(\n html,\n importedIdentifiers\n );\n\n // 2. Escape PascalCase component tags so parse5 doesn't enter special\n // insertion modes (e.g., \"in select\", \"in table\") that corrupt the tree.\n const escapedHtml = escapeComponentTags(processedHtml);\n\n // 3. Parse HTML into parse5 tree\n const parsed = parseFragment(escapedHtml, {\n sourceCodeLocationInfo: true,\n }) as {\n childNodes: unknown[];\n };\n\n // 4. Restore casing and tag type via your parser\n // IMPORTANT: Use escapedHtml (not raw html) because parse5 reports\n // sourceCodeLocation offsets based on escapedHtml. If we used raw html,\n // self-closing tag expansion (e.g. <Foo/> → <Foo></Foo>) and escape\n // prefixing would shift all subsequent offsets, causing casing map\n // lookups to miss for components that appear after other components.\n const tagNameCasingMap = extractOriginalTagNames(escapedHtml);\n const attributeNameCasingMap = extractOriginalAttributeNames(escapedHtml);\n\n const pithyNodes = parsed.childNodes\n .map((n: unknown) =>\n parse5ToPithyTree(\n n as Parameters<typeof parse5ToPithyTree>[0],\n importedIdentifiers,\n tagNameCasingMap,\n undefined,\n attributeNameCasingMap,\n undefined,\n escapedHtml\n )\n )\n .filter((n): n is PithyNode => n != null);\n\n // 3. Compile DOM tree from PithyNodes\n const fragment = pithyTreeToDom(pithyNodes, context);\n\n // 4. Add data-scope attribute to all elements\n addScope(fragment, scopeId);\n\n return {\n fragment,\n pithyNodes,\n };\n}\n\n/**\n * Pre-processes HTML to convert self-closing component tags to regular tags.\n * This works around parse5's limitation with self-closing custom elements.\n *\n * @param html - The HTML template string\n * @param importedIdentifiers - Set of imported component names\n * @returns Processed HTML with self-closing components converted to regular tags\n */\n/** @codexApi {\"parent\":\"pithy.compiler.html-parser\",\"name\":\"preprocessSelfClosingComponents\",\"stability\":\"stable\",\"signature\":\"(html: string, importedIdentifiers: Set<string>) => string\"} */\nfunction preprocessSelfClosingComponents(\n html: string,\n importedIdentifiers: Set<string>\n): string {\n let processedHtml = html;\n\n // Convert each imported component from self-closing to regular tag\n for (const componentName of importedIdentifiers) {\n // Create regex to match self-closing component tags\n // Matches: <ComponentName /> or <ComponentName/>\n // IMPORTANT: Use 'g' flag only (NOT 'gi') - case-sensitive matching is required\n // to avoid converting native elements like <input /> to <Input></Input>\n // Quoted values may hold `>` (an arrow-function prop), so skip them whole.\n const selfClosingRegex = new RegExp(\n `<${componentName}(\\\\s(?:[^>\"']|\"[^\"]*\"|'[^']*')*?)?\\\\s*\\\\/\\\\s*>`,\n 'g'\n );\n\n // Replace with regular opening and closing tags\n processedHtml = processedHtml.replace(\n selfClosingRegex,\n (match, attributes) => {\n const attrs = attributes || '';\n return `<${componentName}${attrs}></${componentName}>`;\n }\n );\n }\n\n return processedHtml;\n}\n\nfunction addScope(root: ParentNode, scopeId: string): void {\n root.querySelectorAll?.('*').forEach(el => {\n el.setAttribute(`data-scope-${scopeId}`, '');\n if (el.localName === 'template' && 'content' in el)\n addScope((el as HTMLTemplateElement).content, scopeId);\n });\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"pithyTreeToDom.d.ts","sourceRoot":"","sources":["../../src/compile/pithyTreeToDom.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAEF,OAAO,EAIL,KAAK,SAAS,EACf,MAAM,mBAAmB,CAAC;AAG3B;;;;GAIG;AACH,uLAAuL;AACvL,wBAAgB,cAAc,CAC5B,KAAK,EAAE,SAAS,EAAE,EAClB,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAC/B,gBAAgB,CAWlB"}
1
+ {"version":3,"file":"pithyTreeToDom.d.ts","sourceRoot":"","sources":["../../src/compile/pithyTreeToDom.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAEF,OAAO,EAKL,KAAK,SAAS,EACf,MAAM,mBAAmB,CAAC;AAG3B;;;;GAIG;AACH,uLAAuL;AACvL,wBAAgB,cAAc,CAC5B,KAAK,EAAE,SAAS,EAAE,EAClB,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAC/B,gBAAgB,CAWlB"}
@@ -5,7 +5,7 @@
5
5
  "category": "compiler"
6
6
  }
7
7
  */
8
- import { SVG_TAGS, SVG_NS, forEachDirectiveAttr, } from '@pithyjs/compiler';
8
+ import { elementTagName, isSvgNode, SVG_NS, forEachDirectiveAttr, } from '@pithyjs/compiler';
9
9
  import { nodeExpando } from './nodeExpando.js';
10
10
  /**
11
11
  * Converts a list of PithyNodes into a DocumentFragment of real DOM nodes.
@@ -24,9 +24,9 @@ export function pithyTreeToDom(nodes, context) {
24
24
  return fragment;
25
25
  }
26
26
  /** @codexApi {"parent":"pithy.compiler.dom-tree","name":"createDomNodeFromPithy","stability":"stable","signature":"(node: PithyNode, context: Record<string, any>) => Node | null"} */
27
- function createDomNodeFromPithy(node, context) {
27
+ function createDomNodeFromPithy(node, context, doc = document) {
28
28
  if (node.type === 'text') {
29
- const textNode = document.createTextNode(node.textContent ?? '');
29
+ const textNode = doc.createTextNode(node.textContent ?? '');
30
30
  nodeExpando(textNode).__pithyCtx = context;
31
31
  nodeExpando(textNode).__pithyNode = node;
32
32
  return textNode;
@@ -50,11 +50,10 @@ function createDomNodeFromPithy(node, context) {
50
50
  }
51
51
  if (node.type === 'element') {
52
52
  // For components, create placeholder element (to be upgraded later)
53
- const tag = node.originalTagName ?? node.tagName ?? 'div';
54
- // SVG elements need to be created in the SVG namespace
55
- const el = SVG_TAGS.has(tag.toLowerCase())
56
- ? document.createElementNS(SVG_NS, tag)
57
- : document.createElement(tag);
53
+ const tag = elementTagName(node);
54
+ const el = isSvgNode(node)
55
+ ? doc.createElementNS(SVG_NS, tag)
56
+ : doc.createElement(tag);
58
57
  nodeExpando(el).__pithyCtx = context;
59
58
  // Store the PithyNode data for component binding to access:
60
59
  // - isComponent flag (to distinguish native elements from components)
@@ -106,14 +105,19 @@ function createDomNodeFromPithy(node, context) {
106
105
  // Preserve existing data-pid from the original HTML
107
106
  el.setAttribute('data-pid', node.attrs['data-pid']);
108
107
  }
109
- // Recursively process children
108
+ const template = isTemplate(el);
109
+ const parent = template ? el.content : el;
110
+ const childDoc = template ? el.content.ownerDocument : doc;
110
111
  for (const child of node.children ?? []) {
111
- const childDom = createDomNodeFromPithy(child, context);
112
+ const childDom = createDomNodeFromPithy(child, context, childDoc);
112
113
  if (childDom)
113
- el.appendChild(childDom);
114
+ parent.appendChild(childDom);
114
115
  }
115
116
  return el;
116
117
  }
117
118
  return null;
118
119
  }
120
+ function isTemplate(el) {
121
+ return el.localName === 'template' && el.namespaceURI !== SVG_NS;
122
+ }
119
123
  //# sourceMappingURL=pithyTreeToDom.js.map
@@ -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,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,CAAC;AAClB,CAAC;AAED,uLAAuL;AACvL,SAAS,sBAAsB,CAC7B,IAAe,EACf,OAAgC;IAEhC,IAAI,IAAI,CAAC,IAAI,KAAK,MAAM,EAAE,CAAC;QACzB,MAAM,QAAQ,GAAG,QAAQ,CAAC,cAAc,CAAC,IAAI,CAAC,WAAW,IAAI,EAAE,CAAC,CAAC;QACjE,WAAW,CAAC,QAAQ,CAAC,CAAC,UAAU,GAAG,OAAO,CAAC;QAC3C,WAAW,CAAC,QAAQ,CAAC,CAAC,WAAW,GAAG,IAAI,CAAC;QACzC,OAAO,QAAQ,CAAC;IAClB,CAAC;IAED,IAAI,IAAI,CAAC,IAAI,KAAK,MAAM,EAAE,CAAC;QACzB,iCAAiC;QACjC,MAAM,Q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/B,CAAC,CAAC,CAAC;YAEH,gDAAgD;YAChD,0EAA0E;YAC1E,+DAA+D;YAC/D,2EAA2E;YAC3E,oDAAoD;YACpD,IAAI,IAAI,CAAC,UAAU,CAAC,IAAI,IAAI,CAAC,EAAE,CAAC,YAAY,CAAC,MAAM,CAAC,EAAE,CAAC;gBACrD,EAAE,CAAC,YAAY,CAAC,MAAM,EAAE,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC;YAChD,CAAC;QACH,CAAC;QAED,kCAAkC;QAClC,IAAI,IAAI,CAAC,MAAM,EAAE,CAAC;YAChB,EAAE,CAAC,YAAY,CAAC,UAAU,EAAE,IAAI,CAAC,MAAM,CAAC,CAAC;QAC3C,CAAC;aAAM,IAAI,IAAI,CAAC,KAAK,EAAE,CAAC,UAAU,CAAC,EAAE,CAAC;YACpC,oDAAoD;YACpD,EAAE,CAAC,YAAY,CAAC,UAAU,EAAE,IAAI,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC,CAAC;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 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(child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tree Converter\",\n \"category\": \"compiler\"\n}\n*/\n\nimport {\n elementTagName,\n isSvgNode,\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 doc: Document = document\n): Node | null {\n if (node.type === 'text') {\n const textNode = doc.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 = elementTagName(node);\n\n const el = isSvgNode(node)\n ? doc.createElementNS(SVG_NS, tag)\n : doc.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 const template = isTemplate(el);\n const parent = template ? el.content : el;\n const childDoc = template ? el.content.ownerDocument : doc;\n for (const child of node.children ?? []) {\n const childDom = createDomNodeFromPithy(child, context, childDoc);\n if (childDom) parent.appendChild(childDom);\n }\n\n return el;\n }\n\n return null;\n}\n\nfunction isTemplate(el: Element): el is HTMLTemplateElement {\n return el.localName === 'template' && el.namespaceURI !== SVG_NS;\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pithyjs/core",
3
- "version": "0.1.0-beta.20",
3
+ "version": "0.1.0-beta.21",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/PithyJS/pithyjs.git",
@@ -26,8 +26,8 @@
26
26
  "dependencies": {
27
27
  "@pithyjs/shared": "0.1.0-beta.4",
28
28
  "@pithyjs/signals": "0.1.0-beta.2",
29
- "@pithyjs/compiler": "0.1.0-beta.8",
30
- "@pithyjs/design-system": "0.1.0-beta.11"
29
+ "@pithyjs/compiler": "0.1.0-beta.9",
30
+ "@pithyjs/design-system": "0.1.0-beta.12"
31
31
  },
32
32
  "peerDependencies": {
33
33
  "parse5": ">=7.0.0"