@pithyjs/core 0.1.0-beta.16 → 0.1.0-beta.18
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/compile/binds/bindBoundAttributes.d.ts.map +1 -1
- package/dist/compile/binds/bindBoundAttributes.js +3 -1
- package/dist/compile/binds/bindBoundAttributes.js.map +1 -1
- package/dist/compile/binds/bindClassDirectives.d.ts.map +1 -1
- package/dist/compile/binds/bindClassDirectives.js +1 -1
- package/dist/compile/binds/bindClassDirectives.js.map +1 -1
- package/dist/compile/binds/bindComponentsTags.d.ts.map +1 -1
- package/dist/compile/binds/bindComponentsTags.js +2 -1
- package/dist/compile/binds/bindComponentsTags.js.map +1 -1
- package/dist/compile/binds/bindEventHandlers.d.ts.map +1 -1
- package/dist/compile/binds/bindEventHandlers.js +12 -3
- package/dist/compile/binds/bindEventHandlers.js.map +1 -1
- package/dist/compile/nodeExpando.d.ts +10 -0
- package/dist/compile/nodeExpando.d.ts.map +1 -1
- package/dist/compile/nodeExpando.js +12 -0
- package/dist/compile/nodeExpando.js.map +1 -1
- package/dist/compile/parseHtml.js +2 -1
- package/dist/compile/parseHtml.js.map +1 -1
- package/dist/runtime/bindings/applyComponent.d.ts.map +1 -1
- package/dist/runtime/bindings/applyComponent.js +3 -2
- package/dist/runtime/bindings/applyComponent.js.map +1 -1
- package/dist/runtime/bindings/applySimple.d.ts.map +1 -1
- package/dist/runtime/bindings/applySimple.js +10 -7
- package/dist/runtime/bindings/applySimple.js.map +1 -1
- package/package.json +2 -2
|
@@ -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,
|
|
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,CA+CN;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;AA2BD,wBAAgB,iBAAiB,CAC/B,EAAE,EAAE,OAAO,EACX,IAAI,EAAE,MAAM,EACZ,IAAI,EAAE,MAAM,GACX,OAAO,CAiBT"}
|
|
@@ -17,7 +17,9 @@ export function bindBoundAttributes(root, context, disposers) {
|
|
|
17
17
|
root.querySelectorAll('*').forEach(el => {
|
|
18
18
|
// Use element's own __pithyCtx when available (projected slot content
|
|
19
19
|
// carries the parent component's context via this property).
|
|
20
|
-
const elCtx = nodeExpando(el).
|
|
20
|
+
const elCtx = nodeExpando(el).__pithyForwardCtx ??
|
|
21
|
+
nodeExpando(el).__pithyCtx ??
|
|
22
|
+
context;
|
|
21
23
|
for (const attr of Array.from(el.attributes)) {
|
|
22
24
|
if (!attr.name.startsWith('data-bind-') || !isDeclaredDirective(attr))
|
|
23
25
|
continue;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bindBo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AAC;IAC9C,MAAM,IAAI,GAAG,IAAI,KAAK,QAAQ,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC;IAC1D,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,SAAS,CAAC,GAAG,EAAE,IAAI,CAAC,MAAM,CAAC,CAAC;QAAE,OAAO,KAAK,CAAC;IACjE,IAAI,MAAM,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,EAAE,CAAC;QACzB,OAAO,CAAC,IAAI,CAAC,qBAAqB,IAAI,gBAAgB,IAAI,IAAI,CAAC,CAAC;IAClE,CAAC;IACD,OAAO,IAAI,CAAC;AACd,CAAC;AAED,SAAS,kBAAkB,CACzB,IAAY,EACZ,OAAgC;IAEhC,IAAI,CAAC;QACH,gHAAgH;QAChH,MAAM,QAAQ,GAAG,IAAI,QAAQ,CAC3B,GAAG,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,EACvB,WAAW,IAAI,GAAG,CACgB,CAAC;QACrC,OAAO,QAAQ,CAAC,GAAG,MAAM,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC;IAC7C,CAAC;IAAC,OAAO,GAAG,EAAE,CAAC;QACb,OAAO,CAAC,IAAI,CAAC,+BAA+B,IAAI,EAAE,EAAE,GAAG,CAAC,CAAC;QACzD,OAAO,SAAS,CAAC;IACnB,CAAC;AACH,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 = nodeExpando(el).__pithyCtx || 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 const value = evaluateExpression(expr, elCtx);\n\n if (writeStyle && typeof value === 'boolean') {\n writeStyle('');\n } else if (typeof value === 'boolean') {\n if (value) {\n el.setAttribute(attrName, '');\n } else {\n el.removeAttribute(attrName);\n }\n } else {\n const text = String(value ?? '');\n if (writeStyle) {\n writeStyle(text);\n } else if (rejectsScriptSink(el, attrName, text)) {\n el.removeAttribute(attrName);\n } else {\n el.setAttribute(attrName, text);\n }\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\nexport function rejectsScriptSink(\n el: Element,\n attr: string,\n text: string\n): 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\nfunction evaluateExpression(\n expr: string,\n context: Record<string, unknown>\n): unknown {\n try {\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 } catch (err) {\n console.warn(`[pithy] Failed to evaluate: ${expr}`, err);\n return undefined;\n }\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,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MAAM,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,EAAE,CAAC;QACzB,OAAO,CAAC,IAAI,CAAC,qBAAqB,IAAI,gBAAgB,IAAI,IAAI,CAAC,CAAC;IAClE,CAAC;IACD,OAAO,IAAI,CAAC;AACd,CAAC;AAED,SAAS,kBAAkB,CACzB,IAAY,EACZ,OAAgC;IAEhC,IAAI,CAAC;QACH,gHAAgH;QAChH,MAAM,QAAQ,GAAG,IAAI,QAAQ,CAC3B,GAAG,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,EACvB,WAAW,IAAI,GAAG,CACgB,CAAC;QACrC,OAAO,QAAQ,CAAC,GAAG,MAAM,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC;IAC7C,CAAC;IAAC,OAAO,GAAG,EAAE,CAAC;QACb,OAAO,CAAC,IAAI,CAAC,+BAA+B,IAAI,EAAE,EAAE,GAAG,CAAC,CAAC;QACzD,OAAO,SAAS,CAAC;IACnB,CAAC;AACH,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 const value = evaluateExpression(expr, elCtx);\n\n if (writeStyle && typeof value === 'boolean') {\n writeStyle('');\n } else if (typeof value === 'boolean') {\n if (value) {\n el.setAttribute(attrName, '');\n } else {\n el.removeAttribute(attrName);\n }\n } else {\n const text = String(value ?? '');\n if (writeStyle) {\n writeStyle(text);\n } else if (rejectsScriptSink(el, attrName, text)) {\n el.removeAttribute(attrName);\n } else {\n el.setAttribute(attrName, text);\n }\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\nexport function rejectsScriptSink(\n el: Element,\n attr: string,\n text: string\n): 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\nfunction evaluateExpression(\n expr: string,\n context: Record<string, unknown>\n): unknown {\n try {\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 } catch (err) {\n console.warn(`[pithy] Failed to evaluate: ${expr}`, err);\n return undefined;\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bindClassDirectives.d.ts","sourceRoot":"","sources":["../../../src/compile/binds/bindClassDirectives.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAUF;;;;;;;;;;GAUG;AACH,uNAAuN;AACvN,wBAAgB,mBAAmB,CACjC,IAAI,EAAE,OAAO,GAAG,gBAAgB,EAChC,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAC5B,SAAS,EAAE,CAAC,MAAM,IAAI,CAAC,EAAE,GACxB,IAAI,
|
|
1
|
+
{"version":3,"file":"bindClassDirectives.d.ts","sourceRoot":"","sources":["../../../src/compile/binds/bindClassDirectives.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAUF;;;;;;;;;;GAUG;AACH,uNAAuN;AACvN,wBAAgB,mBAAmB,CACjC,IAAI,EAAE,OAAO,GAAG,gBAAgB,EAChC,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAC5B,SAAS,EAAE,CAAC,MAAM,IAAI,CAAC,EAAE,GACxB,IAAI,CAkFN;AAED,4KAA4K;AAC5K,wBAAgB,eAAe,CAC7B,EAAE,EAAE,OAAO,EACX,MAAM,EAAE,OAAO,EACf,KAAK,EAAE,GAAG,CAAC,MAAM,CAAC,GACjB,IAAI,CA8BN"}
|
|
@@ -27,7 +27,7 @@ export function bindClassDirectives(root, ctx, disposers) {
|
|
|
27
27
|
root.querySelectorAll('*').forEach(el => {
|
|
28
28
|
// Use element's own __pithyCtx when available (projected slot content
|
|
29
29
|
// carries the parent component's context via this property).
|
|
30
|
-
const elCtx = nodeExpando(el).__pithyCtx
|
|
30
|
+
const elCtx = nodeExpando(el).__pithyForwardCtx ?? nodeExpando(el).__pithyCtx ?? ctx;
|
|
31
31
|
let declared;
|
|
32
32
|
for (const attr of Array.from(el.attributes)) {
|
|
33
33
|
if (!attr.name.startsWith(TOGGLE_PREFIX))
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bindClassDirectives.js","sourceRoot":"","sources":["../../../src/compile/binds/bindClassDirectives.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAEF,OAAO,EAAE,aAAa,EAAE,mBAAmB,EAAE,MAAM,qBAAqB,CAAC;AACzE,OAAO,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAC;AAC1C,OAAO,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AACzD,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAC7C,OAAO,EAAE,mBAAmB,EAAE,YAAY,EAAE,MAAM,uBAAuB,CAAC;AAE1E,MAAM,aAAa,GAAG,oBAAoB,CAAC;AAE3C;;;;;;;;;;GAUG;AACH,uNAAuN;AACvN,MAAM,UAAU,mBAAmB,CACjC,IAAgC,EAChC,GAA4B,EAC5B,SAAyB;IAEzB,IAAI,CAAC,gBAAgB,CAAC,GAAG,CAAC,CAAC,OAAO,CAAC,EAAE,CAAC,EAAE;QACtC,sEAAsE;QACtE,6DAA6D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*/\n\nimport { declaredValue, isDeclaredDirective } from './declaredDirective';\nimport { effect } from '@pithyjs/signals';\nimport { compileExpression } from '../compileExpression';\nimport { nodeExpando } from '../nodeExpando';\nimport { bindStyleProperties, declaredName } from './bindStyleDirectives';\n\nconst TOGGLE_PREFIX = 'data-class-toggle-';\n\n/**\n * Binds class directives like:\n * • [class.active]=\"isActive\"\n * • [classes]=\"{ active: isActive() }\"\n * • [classes]=\"['a', 'b']\"\n * • [classes]=\"'a b'\"\n *\n * @param root - The root node to search for class bindings\n * @param ctx - Context object containing reactive variables and functions\n * @param disposers - Cleanup functions to remove subscriptions\n */\n/** @codexApi {\"parent\":\"pithy.runtime.classes\",\"name\":\"bindClassDirectives\",\"stability\":\"stable\",\"signature\":\"(root: Element | DocumentFragment, ctx: Record<string, unknown>, disposers: (() => void)[]) => void\"} */\nexport function bindClassDirectives(\n root: Element | DocumentFragment,\n ctx: 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 ?? nodeExpando(el).__pithyCtx ?? ctx;\n\n let declared: string[] | undefined;\n for (const attr of Array.from(el.attributes)) {\n if (!attr.name.startsWith(TOGGLE_PREFIX)) continue;\n const expando = nodeExpando(el);\n declared ??= [\n ...(expando.__classToggles ?? []),\n ...Object.keys(expando.__pithyNode?.directives?.classMap ?? {}),\n ];\n const className = declaredName(\n attr.name.slice(TOGGLE_PREFIX.length),\n declared\n );\n if (!className || !isDeclaredDirective(attr)) continue;\n const expression = attr.value;\n\n // Remove directive attribute after capturing to prevent double-processing\n // when component subtrees are inserted into an outer DOM that re-runs binders\n el.removeAttribute(attr.name);\n\n let evaluate: () => unknown;\n\n try {\n evaluate = compileExpression(expression, elCtx);\n } catch (err) {\n console.warn(\n `[PithyJS] ⚠️ Failed to compile [class.${className}]=\"${expression}\"`,\n err\n );\n return;\n }\n\n const stop = effect(() => {\n try {\n const result = evaluate();\n el.classList.toggle(className, !!result);\n } catch {\n /* ignore */\n }\n });\n\n disposers.push(stop);\n }\n\n const classGroupExpr = declaredValue(el, 'data-classes');\n if (classGroupExpr) {\n // Remove directive attribute after capturing to prevent double-processing\n el.removeAttribute('data-classes');\n\n let evaluate: () => unknown;\n\n try {\n evaluate = compileExpression(classGroupExpr, elCtx);\n } catch (err) {\n console.warn(\n `[PithyJS] ⚠️ Failed to compile [classes]=\"${classGroupExpr}\"`,\n err\n );\n return;\n }\n\n const owned = new Set<string>();\n const stop = effect(() => {\n try {\n applyClassGroup(el, evaluate(), owned);\n } catch (err) {\n console.warn('[PithyJS] ⚠️ Failed to evaluate [classes]:', err);\n }\n });\n\n disposers.push(stop);\n }\n\n // After the classes, so the attributes serialise in the build's order.\n bindStyleProperties(el, elCtx, disposers);\n });\n}\n\n/** @codexApi {\"parent\":\"pithy.runtime.classes\",\"name\":\"applyClassGroup\",\"stability\":\"internal\",\"signature\":\"(el: Element, result: unknown, owned: Set<string>) => void\"} */\nexport function applyClassGroup(\n el: Element,\n result: unknown,\n owned: Set<string>\n): void {\n const named = new Map<string, boolean>();\n const name = (classes: string, on: boolean) => {\n for (const c of classes.split(/[\\t\\n\\f\\r ]+/)) if (c) named.set(c, on);\n };\n if (typeof result === 'string') {\n name(result, true);\n } else if (Array.isArray(result)) {\n for (const cls of result) if (typeof cls === 'string') name(cls, true);\n } else if (result && typeof result === 'object') {\n for (const [cls, on] of Object.entries(result)) name(cls, !!on);\n } else if (import.meta.env?.DEV && result) {\n console.warn(\n `[PithyJS] ⚠️ [classes] expects a string, an array or an object, got ${typeof result}; the classes it added are removed.`\n );\n }\n\n // `owned` is this binding's own record, not the element's: a component's\n // root `[classes]` and one forwarded from its tag share the element, and\n // each may only remove the classes it added.\n const previous = new Set(owned);\n owned.clear();\n for (const [c, on] of named) {\n if (!on) el.classList.remove(c);\n else if (previous.has(c) || !el.classList.contains(c)) {\n el.classList.add(c);\n owned.add(c);\n }\n }\n for (const c of previous) if (!named.has(c)) el.classList.remove(c);\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bindComponentsTags.d.ts","sourceRoot":"","sources":["../../../src/compile/binds/bindComponentsTags.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAgDF,qGAAqG;AACrG,wBAAgB,2BAA2B,IAAI,IAAI,CAElD;AAmKD;;;;;;GAMG;AACH,4NAA4N;AAC5N,wBAAgB,iBAAiB,CAC/B,IAAI,EAAE,OAAO,GAAG,gBAAgB,EAChC,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAChC,SAAS,EAAE,CAAC,MAAM,IAAI,CAAC,EAAE,GACxB,IAAI,
|
|
1
|
+
{"version":3,"file":"bindComponentsTags.d.ts","sourceRoot":"","sources":["../../../src/compile/binds/bindComponentsTags.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAgDF,qGAAqG;AACrG,wBAAgB,2BAA2B,IAAI,IAAI,CAElD;AAmKD;;;;;;GAMG;AACH,4NAA4N;AAC5N,wBAAgB,iBAAiB,CAC/B,IAAI,EAAE,OAAO,GAAG,gBAAgB,EAChC,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAChC,SAAS,EAAE,CAAC,MAAM,IAAI,CAAC,EAAE,GACxB,IAAI,CAmaN"}
|
|
@@ -14,7 +14,7 @@ import { componentChildDirectiveMessage, componentChildDirectives, nativeTags, }
|
|
|
14
14
|
import { collectForwardedAttrs, applyForwardedAttrs } from './forwardedAttrs.js';
|
|
15
15
|
import { createRoot, untrack } from '@pithyjs/signals';
|
|
16
16
|
import { watchStaleRowProp } from './staleRowProps.js';
|
|
17
|
-
import { nodeExpando } from '../nodeExpando.js';
|
|
17
|
+
import { markForwardTarget, nodeExpando } from '../nodeExpando.js';
|
|
18
18
|
import { componentDisposer } from '../disposeOrder.js';
|
|
19
19
|
import { pithyGlobals } from '../../types/globals.js';
|
|
20
20
|
import { isSSRMode } from '../ssrMode.js';
|
|
@@ -489,6 +489,7 @@ export function bindComponentTags(root, rootCtx, disposers) {
|
|
|
489
489
|
// Forward captured attributes so subsequent binders can attach the bindings
|
|
490
490
|
if (forwardedAttrs.length > 0 && forwardTarget) {
|
|
491
491
|
applyForwardedAttrs(forwardTarget, forwardedAttrs, tag);
|
|
492
|
+
markForwardTarget(forwardTarget, localCtx, new Set(forwardedAttrs.map(([name]) => name)));
|
|
492
493
|
const styleProps = Object.keys(pithyNode?.directives?.styleMap ?? {});
|
|
493
494
|
if (styleProps.length)
|
|
494
495
|
nodeExpando(forwardTarget).__styleProps = styleProps;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bindComponentsTags.js","sourceRoot":"","sources":["../../../src/compile/binds/bindComponentsTags.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAEF,OAAO,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AACzD,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AACrD,OAAO,EACL,kBAAkB,EAClB,eAAe,EACf,aAAa,EACb,eAAe,EACf,iBAAiB,EACjB,gBAAgB,GACjB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAC5D,OAAO,EAAE,cAAc,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AAC1E,OAAO,EACL,8BAA8B,EAC9B,wBAAwB,EACxB,UAAU,GAEX,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,qBAAqB,EAAE,mBAAmB,EAAE,MAAM,kBAAkB,CAAC;AAC9E,OAAO,EAAE,UAAU,EAAE,OAAO,EAAE,MAAM,kBAAkB,CAAC;AACvD,OAAO,EAAE,iBAAiB,EAAE,MAAM,iBAAiB,CAAC;AACpD,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAC7C,OAAO,EAAE,iBAAiB,EAAE,MAAM,iBAAiB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AAY,GAAG,MAAM,CAAC,IAAI,CAAC,SAAS,EAAE,UAAU,EAAE,QAAQ,IAAI,EAAE,CAAC,CAAC;YACxE,IAAI,YAAY,CAAC,MAAM;gBACrB,WAAW,CAAC,aAAa,CAAC,CAAC,cAAc,GAAG,YAAY,CAAC;YAC3D,wEAAwE;YACxE,qEAAqE;YACrE,IAAI,MAAM,IAAI,CAAC,aAAa,CAAC,UAAU,EAAE,CAAC;gBACxC,MAAM,QAAQ,GAAG,QAAQ,CAAC,sBAAsB,EAAE,CAAC;gBACnD,QAAQ,CAAC,MAAM,CAAC,aAAa,CAAC,CAAC;gBAC/B,mBAAmB,CAAC,QAAQ,EAAE,QAAQ,EAAE,SAAS,CAAC,CAAC;YACrD,CAAC;QACH,CAAC;IACH,CAAC;AACH,CAAC","sourcesContent":["/** @codex\n{\n \"id\": \"pithy.runtime.components\",\n \"title\": \"Component Tag Binding System\",\n \"category\": \"runtime\"\n}\n*/\n\nimport { compileExpression } from '../compileExpression';\nimport { isTemplateAttr } from './declaredDirective';\nimport {\n boundaryForElement,\n currentBoundary,\n replaceHidden,\n runWithBoundary,\n slotContentHidden,\n withSlotBoundary,\n} from './bindErrorBoundary';\nimport { bindAfterComponents } from './bindAfterComponents';\nimport { collectSlotMap, inProjectedContent } from '../contentProjection';\nimport {\n componentChildDirectiveMessage,\n componentChildDirectives,\n nativeTags,\n type PithyNode,\n} from '@pithyjs/compiler';\nimport { collectForwardedAttrs, applyForwardedAttrs } from './forwardedAttrs';\nimport { createRoot, untrack } from '@pithyjs/signals';\nimport { watchStaleRowProp } from './staleRowProps';\nimport { nodeExpando } from '../nodeExpando';\nimport { componentDisposer } from '../disposeOrder';\nimport { pithyGlobals } from '../../types/globals';\nimport { isSSRMode } from '../ssrMode';\nimport { clearSSRRenderCrash, reportComponentFailure } from '../ssrCrashes';\nimport { isRenderableComponentEl } from '../componentResult';\nimport { parsePropNames, type PropNames } from './propNames';\n\ninterface ComponentResult {\n /** Any DOM node — see the `Component` type for why this is not narrower. */\n el: Node;\n destroy?: () => void;\n}\ntype ComponentFn = (props: Record<string, unknown>) => ComponentResult;\n\n/**\n * Find the closest element-scoped context we attach in createLoopItem().\n * This is what exposes item(), gIdx(), count(), etc.\n */\n// Warn once per component/tag pair — the same idiom re-renders constantly\n// (e.g. a panel importing Button while using a native <button>), and\n// repeating the warning drowns out real ones.\nconst warnedComponentTags = new Set<string>();\nconst warnedChildDirectives = new WeakSet<PithyNode>();\n\n/** Test-only: forget which tags were warned about, so each render warns as a fresh process would. */\nexport function __resetComponentTagWarnings(): void {\n warnedComponentTags.clear();\n}\n\nfunction nearestCtx(\n el: Element,\n rootCtx: Record<string, unknown>\n): Record<string, unknown> {\n let n: Element | null = el;\n while (n) {\n const local = nodeExpando(n).__pithyCtx;\n if (local) return local;\n n = n.parentElement;\n }\n return rootCtx;\n}\n\n/**\n * Detect whether a node is inside a subtree that represents a NOT-YET-EXPANDED nested loop.\n * Those hosts are tagged in createLoopManager.createLoopItem() via `__pithySkipText`,\n * and real templates may also still carry @for / data-for before expansion.\n * We must *defer* binding for anything under such a host, otherwise expressions like item()\n * will throw ReferenceError (because inner loop ctx isn’t created yet).\n */\nfunction isInsidePendingLoopZone(node: Element): boolean {\n let p: Element | null = node;\n while (p) {\n if (nodeExpando(p).__pithySkipText) return true;\n if (\n p.hasAttribute &&\n (p.hasAttribute('@for') || p.hasAttribute('data-for'))\n ) {\n return true;\n }\n p = p.parentElement;\n }\n return false;\n}\n\n/** Evaluate `expr` in `ctx`. Try engine compiler first, then args-style fallback. */\nfunction evalInCtx(expr: string, ctx: Record<string, unknown>): unknown {\n // 1) Preferred: compileExpression uses `with(ctx) { return (...) }`\n try {\n const f = compileExpression(expr, ctx);\n try {\n return f();\n } catch {\n /* fall through to fallback */\n }\n } catch {\n /* fall through to fallback */\n }\n\n // 2) Fallback: args-style evaluator (robust even if compileExpression throws)\n const keys = Object.keys(ctx);\n const vals = keys.map(k => ctx[k]);\n // eslint-disable-next-line no-new-func -- args-style template expression evaluation is a core framework feature\n const fn = new Function(...keys, `return (${expr});`) as (\n ...args: unknown[]\n ) => unknown;\n return fn(...vals);\n}\n\nconst propNameCache = new WeakMap<ComponentFn, PropNames>();\n\nfunction readPropNames(componentFn: ComponentFn): PropNames {\n let cached = propNameCache.get(componentFn);\n if (!cached) {\n try {\n cached = parsePropNames(componentFn.toString());\n } catch {\n cached = { names: [], fromParam: false, exhaustive: false };\n }\n propNameCache.set(componentFn, cached);\n }\n return cached;\n}\n\nfunction extractExpectedPropNames(componentFn: ComponentFn): string[] {\n return readPropNames(componentFn).names;\n}\n\nconst warnedBoundProps = new Set<string>();\nconst GLOBAL_ATTRS = new Set([\n 'id',\n 'class',\n 'style',\n 'title',\n 'role',\n 'tabindex',\n 'hidden',\n]);\n\nfunction warnBoundProps(\n componentFn: ComponentFn,\n el: Element,\n componentName: string\n): void {\n const expected = extractExpectedPropNames(componentFn);\n for (const attr of Array.from(el.attributes)) {\n if (!attr.name.startsWith('data-bind-')) continue;\n const bound = attr.name.slice('data-bind-'.length);\n if (bound === 'slot' && !warnedBoundProps.has(`${componentName} slot`)) {\n warnedBoundProps.add(`${componentName} slot`);\n console.warn(\n `[PithyJS] <${componentName}> [slot] cannot choose a slot: the key is read as a literal, so this lands in the default slot. Write slot=\"name\".`\n );\n }\n if (GLOBAL_ATTRS.has(bound)) continue;\n const prop = expected.find(p => p.toLowerCase() === bound);\n const key = `${componentName} ${bound}`;\n if (!prop || warnedBoundProps.has(key)) continue;\n warnedBoundProps.add(key);\n console.warn(\n `[PithyJS] <${componentName}> [${bound}] sets an attribute on the rendered root, not the \\`${prop}\\` prop. Write ${prop}=\"…\" without brackets to set the prop; for a live value pass a signal or () => … if the prop accepts one.`\n );\n }\n}\n\n/** Dev warnings for unexpected props (only if destructuring is present). */\nfunction validateComponentProps(\n componentFn: ComponentFn,\n props: Record<string, unknown>,\n componentName: string\n): void {\n const { names: allNames, exhaustive } = readPropNames(componentFn);\n if (!exhaustive || allNames.length === 0) return;\n\n const passed = Object.keys(props);\n const expectedSet = new Set(allNames);\n\n const unexpected = passed.filter(p => !expectedSet.has(p));\n if (unexpected.length) {\n console.warn(\n `[PithyJS] 🔍 Component <${componentName}> received unexpected props: ${unexpected.join(\n ', '\n )}\\nExpected props: ${allNames.join(', ')}\\nPassed props: ${passed.join(', ')}`\n );\n }\n\n // NOTE: We intentionally do NOT warn about \"missing\" props here.\n // In template-driven usage, props are assembled at runtime by\n // bindComponentTags(), so TypeScript cannot catch missing required\n // props in this path. Components should self-validate critical\n // props where appropriate (e.g. Toggle warns on empty label).\n}\n\n/** DOM a component already rendered: its native tags may share a component's name. */\nfunction inComponentDom(el: Element): boolean {\n for (let n: Element | null = el; n; n = n.parentElement)\n if (nodeExpando(n).__pithyComponentDom) return true;\n return false;\n}\n\n/** Map lowercased DOM attr name to expected prop name (case-insensitive). */\nfunction normalizePropName(\n authoredName: string,\n expectedProps: string[]\n): string {\n if (expectedProps.includes(authoredName)) return authoredName;\n const lower = authoredName.toLowerCase();\n const matches = expectedProps.filter(p => p.toLowerCase() === lower);\n return matches.length === 1 ? matches[0] : authoredName;\n}\n\n/**\n * Replace custom component tags (<Counter/>, <NestedComponent/>) with rendered output.\n * - Skips anything under a pending nested loop host (bind after loop expansion)\n * - Evaluates prop expressions in nearest loop ctx\n * - Case-insensitive prop name normalization\n * - No raw-string fallback (prevents things like calling count() on a string)\n */\n/** @codexApi {\"parent\":\"pithy.runtime.components\",\"name\":\"bindComponentTags\",\"stability\":\"stable\",\"signature\":\"(root: Element | DocumentFragment, rootCtx: Record<string, unknown>, disposers: (() => void)[]) => void\"} */\nexport function bindComponentTags(\n root: Element | DocumentFragment,\n rootCtx: Record<string, unknown>,\n disposers: (() => void)[]\n): void {\n // case-insensitive tag lookup from context\n const tagMap = new Map<string, unknown>(\n Object.keys(rootCtx).map(k => [k.toLowerCase(), rootCtx[k]])\n );\n\n const scope =\n root instanceof Element ? (root as Element) : (root as DocumentFragment);\n const elements = Array.from(scope.querySelectorAll('*'));\n\n for (const el of elements) {\n // Skip elements removed from the tree by a parent component's render, or\n // hidden by an `@error-boundary` that has since activated.\n if (!scope.contains(el)) {\n // An element that has left the tree contributes nothing to the output, so\n // a crash recorded for it on an earlier DETACHED pass is stale. Leaving it\n // fails a route that rendered correctly: with two crashing components\n // under one boundary inside an `@if`, the detached pass records both, the\n // retry lets the boundary accept the first, and accepting synchronously\n // hides the second — which then never gets a retry to retract it.\n if (isSSRMode()) clearSSRRenderCrash(el);\n continue;\n }\n\n // Defer components inside not-yet-expanded loops\n if (isInsidePendingLoopZone(el)) continue;\n\n // A build's placeholder carries no AST: its children are DOM, which only\n // the AOT binder reads.\n const aotMount = nodeExpando(el).__pithyAotMount;\n if (aotMount) {\n // Marked as below, so the text pass skips what the component rendered.\n for (const node of aotMount(disposers))\n nodeExpando(node).__pithyComponentDom = true;\n continue;\n }\n\n const tag = el.tagName.toLowerCase();\n\n // Check if the parser marked this element as a component\n // This is the authoritative source - it checks originalTagName starts with uppercase\n // AND the tag name exists in importedIdentifiers\n const pithyNode = nodeExpando(el).__pithyNode;\n if (pithyNode) {\n // Parser processed this element - use its isComponent flag\n if (!pithyNode.isComponent) {\n // DEV: Warn if there's a component that matches case-insensitively\n // This helps developers catch typos like <button> when they meant <Button>\n // Skip warning if we're inside a component's render (the component might\n // legitimately use native elements like <button> in its implementation)\n const isInsideComponentRender =\n !!pithyGlobals().__pithyRenderingComponent;\n if (\n import.meta.env?.DEV &&\n !isInsideComponentRender &&\n !inComponentDom(el)\n ) {\n const matchingComponent = tagMap.get(tag);\n if (matchingComponent && typeof matchingComponent === 'function') {\n // Find the actual component name from context\n const componentName = Object.keys(rootCtx).find(\n k => k.toLowerCase() === tag && rootCtx[k] === matchingComponent\n );\n const warnKey = `${componentName}:${pithyNode.originalTagName}`;\n if (\n componentName &&\n componentName !== pithyNode.originalTagName &&\n !warnedComponentTags.has(warnKey)\n ) {\n warnedComponentTags.add(warnKey);\n console.warn(\n `[PithyJS] ⚠️ Component '${componentName}' is imported but used as '<${pithyNode.originalTagName}>'. ` +\n `Components must use PascalCase. Use '<${componentName}>' instead.`\n );\n }\n }\n }\n continue;\n }\n } else {\n // Fallback for elements not processed by our parser:\n // Skip native HTML elements to prevent <button> matching Button component\n if (nativeTags.has(tag)) continue;\n // Rendered already, e.g. a build's slot content.\n if (inComponentDom(el)) continue;\n }\n\n if (\n import.meta.env?.DEV &&\n pithyNode &&\n !warnedChildDirectives.has(pithyNode)\n ) {\n warnedChildDirectives.add(pithyNode);\n for (const name of componentChildDirectives(pithyNode))\n console.warn(\n `[pithy] ${componentChildDirectiveMessage(pithyNode.originalTagName ?? tag, name)}`\n );\n }\n\n let candidate = tagMap.get(tag);\n\n if (!candidate) continue;\n\n // Support default exports\n if (\n candidate &&\n typeof candidate === 'object' &&\n 'default' in candidate &&\n typeof candidate.default === 'function'\n ) {\n candidate = candidate.default;\n }\n if (typeof candidate !== 'function') continue;\n // Content a runtime-compiled receiver projected: bound detached, inside the\n // output of the component being rendered.\n const projectedHost =\n !el.closest('[data-error]') && inProjectedContent(el)\n ? pithyGlobals().__pithyComponentContext?.__slotHost\n : undefined;\n // Hidden like a sibling an activated boundary detached: never rendered.\n if (withSlotBoundary(undefined, projectedHost, () => slotContentHidden(el)))\n continue;\n\n const componentFn = candidate as ComponentFn;\n const localCtx = nearestCtx(el, rootCtx); // crucial for item(), gIdx(), etc.\n\n // Extract expected props for validation (DEV) and prop name normalization (always)\n // This ensures case-insensitive matching works even when originalAttrs is unavailable\n const { names, fromParam } = readPropNames(componentFn);\n const expectedProps = fromParam ? names : [];\n\n // Preserve originally-authored attribute names/casing from the parsed template\n // (pithyNode already extracted above for isComponent check)\n const originalAttrs: Record<string, string> | undefined =\n pithyNode?.originalAttrs;\n\n const props: Record<string, unknown> = {};\n\n const staleWatchers: (() => void)[] = [];\n\n // Evaluate attributes as expressions in localCtx\n for (const attr of Array.from(el.attributes)) {\n const name = attr.name;\n const raw = attr.value;\n\n // Skip internal/behavioral attributes\n if (name.startsWith('data-')) continue;\n if (name === 'class' || name === 'style' || name === 'slot') continue;\n if (!isTemplateAttr(attr)) continue;\n\n // Prefer originally-authored name (preserve casing), else DOM name\n const authored = originalAttrs?.[name] ?? name;\n const propName = normalizePropName(authored, expectedProps);\n\n try {\n const value = untrack(() => evalInCtx(raw, localCtx));\n props[propName] = value; // only set when evaluation succeeds\n if (import.meta.env?.DEV) {\n staleWatchers.push(() =>\n watchStaleRowProp(\n localCtx,\n pithyNode ?? el,\n pithyNode?.originalTagName || tag,\n propName,\n raw,\n value,\n () => evalInCtx(raw, localCtx),\n disposers\n )\n );\n }\n } catch (err) {\n if (import.meta.env?.DEV) {\n console.warn(\n `[PithyJS] ⚠️ Failed to evaluate prop \"${propName}\" = \"${raw}\"`,\n err\n );\n }\n // IMPORTANT: do NOT set a raw string fallback here.\n // Leaving it undefined lets the child use defaults and avoids count()-on-string.\n }\n }\n\n // Validate props for all components in DEV mode.\n // Native elements are already filtered out earlier (line 197 for fallback, line 171 for parser).\n if (import.meta.env?.DEV) {\n const displayTag = pithyNode?.originalTagName || tag;\n validateComponentProps(componentFn, props, displayTag);\n warnBoundProps(componentFn, el, displayTag);\n }\n\n // Collect content projection SlotMap from component children\n const pithyChildren: PithyNode[] = pithyNode?.children || [];\n const slotMap = collectSlotMap(pithyChildren, localCtx);\n\n // Create enhanced context with SlotMap for content projection\n const componentContext = {\n ...localCtx,\n __slotMap: slotMap,\n __childAstNodes: pithyChildren,\n __childFactory: undefined,\n __slotHost: el,\n };\n\n // Find nearest error boundary for this component\n const boundaryEl = el.closest('[data-error]') as Element | null;\n // Projected content is bound detached, during its receiver's render.\n const boundary =\n boundaryForElement(boundaryEl) ??\n (!boundaryEl && inProjectedContent(el) ? currentBoundary() : null);\n\n // Invoke component under boundary context; expect { el, destroy }\n let out: ComponentResult | undefined;\n let disposeSetup: (() => void) | undefined;\n try {\n out = runWithBoundary(boundary, () => {\n // Store the enhanced context globally for the component's html() calls to access.\n // This per-component context contains __slotMap for content projection.\n //\n // In SSR, there are TWO context sources that html() merges:\n // 1. AsyncLocalStorage context (__getComponentContext) - request-level isolation\n // 2. This global context (__pithyComponentContext) - per-component __slotMap\n //\n // Both are needed: AsyncLocalStorage provides request isolation, while this\n // global provides the __slotMap that changes for each component render.\n const g = pithyGlobals();\n const originalContext = g.__pithyComponentContext;\n const wasRendering = g.__pithyRenderingComponent;\n g.__pithyComponentContext = componentContext;\n // Mark that we're rendering a component to suppress casing warnings for\n // native elements used in component implementations (e.g., <button> in Button)\n g.__pithyRenderingComponent = true;\n\n try {\n const result = createRoot(disposeRoot => {\n disposeSetup = disposeRoot;\n return componentFn(props);\n });\n return result;\n } finally {\n // Restore original context\n g.__pithyComponentContext = originalContext;\n g.__pithyRenderingComponent = wasRendering;\n }\n });\n } catch (err) {\n // Route sync render errors to the nearest boundary with escalation\n if (boundary) {\n const error = err instanceof Error ? err : new Error(String(err));\n // A boundary being in scope does not mean it accepted the error: an\n // already-active boundary with no free ancestor drops it (React's\n // first-error-wins). A component inside that boundary's `@fallback` is\n // the everyday case, and the fallback is what the user actually sees.\n const accepted = reportComponentFailure(el, tag, error, boundary);\n if (import.meta.env?.DEV) {\n // Say which of the two actually happened. \"Captured\" on a rejected\n // error reports the opposite of the truth, and this branch exists\n // precisely because the two are not the same.\n console.log(\n accepted\n ? `[ErrorBoundary] Captured sync render error in <${tag}>:`\n : `[ErrorBoundary] Boundary already active — error from <${tag}> was NOT captured:`,\n error.message\n );\n }\n continue;\n }\n\n // No boundary in scope *yet*. Degrading is still the right call here in\n // both modes: throwing would pre-empt the retry pass that gives an\n // `@error-boundary` its only chance to claim a crash raised while the\n // subtree was detached.\n //\n // A static/server render additionally records the crash. Nobody reads a\n // console during `pithy-ssg`, so this used to leave the raw <${tag}> in\n // the emitted HTML while the route still counted as rendered and the CLI\n // exited 0 (BUG-018). Anything still recorded when the render finishes\n // makes the SSR renderer throw, and the per-route catch in `vite-ssg.ts`\n // fails that route.\n reportComponentFailure(\n el,\n tag,\n err instanceof Error ? err : new Error(String(err)),\n null\n );\n\n console.error(`❌ Component <${tag}> crashed during render:`, err);\n continue;\n }\n\n if (\n !out ||\n typeof out !== 'object' ||\n !('el' in out) ||\n !isRenderableComponentEl(out.el, el)\n ) {\n console.warn(\n `❌ Invalid render result from <${tag}>. Expected { el, destroy }`\n );\n // Not a throw, but the same outcome as one: the raw <${tag}> is left in\n // the document and the subtree never renders. Under SSR that is content\n // silently missing from the emitted HTML, so it is recorded exactly like\n // a crash (BUG-018). Recorded rather than merely left in place, because\n // this attempt may also be retracting an earlier attempt's record.\n // Same funnel as a throw: a boundary above this component gets the\n // chance to claim it and render its fallback, and only an unclaimed\n // failure is recorded. Bypassing this meant a component under\n // `@error-boundary` that returned garbage failed the route with the\n // boundary signal still null.\n reportComponentFailure(\n el,\n tag,\n new Error(\n `Invalid render result from <${tag}>; expected { el, destroy }`\n ),\n boundary\n );\n disposeSetup?.();\n continue;\n }\n\n const { el: renderedEl, destroy } = out;\n\n // Capture class and data-* attributes for forwarding to rendered root:\n // directive bindings (data-on-*, data-bind-*, data-class-toggle-*,\n // data-classes, data-style-*) plus any author-written data-* attribute.\n const forwardedClass = el.getAttribute('class');\n const forwardedAttrs = collectForwardedAttrs(el);\n\n const isFragment = renderedEl.nodeType === Node.DOCUMENT_FRAGMENT_NODE;\n let forwardTarget: HTMLElement | null = null;\n const hasForwardables = !!(forwardedClass || forwardedAttrs.length > 0);\n if (hasForwardables) {\n if (isFragment) {\n forwardTarget = (renderedEl as DocumentFragment)\n .firstElementChild as HTMLElement | null;\n if (import.meta.env?.DEV && !forwardTarget) {\n const displayTag = pithyNode?.originalTagName || tag;\n console.warn(\n `[PithyJS] <${displayTag}> has class or data-* attributes but returns a fragment with no element children — forwarding skipped.`\n );\n }\n } else if (renderedEl.nodeType === Node.ELEMENT_NODE) {\n forwardTarget = renderedEl as HTMLElement;\n }\n }\n\n const renderedNodes = isFragment\n ? Array.from(renderedEl.childNodes)\n : [renderedEl];\n for (const node of renderedNodes)\n nodeExpando(node).__pithyComponentDom = true;\n\n let replaced = true;\n let hidden = false;\n try {\n // A boundary that caught a crash in this render may have hidden `el`.\n hidden = replaceHidden(el, renderedNodes);\n if (!hidden) el.replaceWith(...renderedNodes);\n } catch (err) {\n // A failed replacement leaves the raw <${tag}> exactly where a crash\n // would have, so it is the same content loss and is recorded the same way.\n replaced = false;\n reportComponentFailure(\n el,\n tag,\n err instanceof Error ? err : new Error(String(err)),\n boundary\n );\n console.error(`❌ Failed to replace <${tag}> with rendered DOM:`, err);\n }\n\n // Retracted only here, and in the boundary catch above — never eagerly at\n // the top of an attempt, where any early `continue` added later would\n // silently drop a real record. This is the point at which the component is\n // known to have produced a usable node AND to have reached the document, so\n // an earlier detached attempt's crash is genuinely no longer the outcome.\n if (isSSRMode() && replaced) clearSSRRenderCrash(el);\n\n for (const watch of staleWatchers) watch();\n\n // Forward class from component tag onto the rendered root element\n if (forwardedClass && forwardTarget) {\n for (const cls of forwardedClass.split(/\\s+/)) {\n if (cls) forwardTarget.classList.add(cls);\n }\n }\n\n // Before any binding pass below, which can throw.\n const teardown = componentDisposer(\n destroy,\n disposeSetup,\n renderedNodes[0] ?? (replaced ? null : el)\n );\n if (teardown) disposers.push(teardown);\n\n // Forward captured attributes so subsequent binders can attach the bindings\n if (forwardedAttrs.length > 0 && forwardTarget) {\n applyForwardedAttrs(forwardTarget, forwardedAttrs, tag);\n const styleProps = Object.keys(pithyNode?.directives?.styleMap ?? {});\n if (styleProps.length)\n nodeExpando(forwardTarget).__styleProps = styleProps;\n const classToggles = Object.keys(pithyNode?.directives?.classMap ?? {});\n if (classToggles.length)\n nodeExpando(forwardTarget).__classToggles = classToggles;\n // Hidden, it is out of reach of this fragment's later passes. An active\n // nested boundary `hideContent` kept in place is still within reach.\n if (hidden && !forwardTarget.parentNode) {\n const detached = document.createDocumentFragment();\n detached.append(forwardTarget);\n bindAfterComponents(detached, localCtx, disposers);\n }\n }\n }\n}\n"]}
|
|
1
|
+
{"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,CAAC;gBACxC,MAAM,QAAQ,GAAG,QAAQ,CAAC,sBAAsB,EAAE,CAAC;gBACnD,QAAQ,CAAC,MAAM,CAAC,aAAa,CAAC,CAAC;gBAC/B,mBAAmB,CAAC,QAAQ,EAAE,QAAQ,EAAE,SAAS,CAAC,CAAC;YACrD,CAAC;QACH,CAAC;IACH,CAAC;AACH,CAAC","sourcesContent":["/** @codex\n{\n \"id\": \"pithy.runtime.components\",\n \"title\": \"Component Tag Binding System\",\n \"category\": \"runtime\"\n}\n*/\n\nimport { compileExpression } from '../compileExpression';\nimport { isTemplateAttr } from './declaredDirective';\nimport {\n boundaryForElement,\n currentBoundary,\n replaceHidden,\n runWithBoundary,\n slotContentHidden,\n withSlotBoundary,\n} from './bindErrorBoundary';\nimport { bindAfterComponents } from './bindAfterComponents';\nimport { collectSlotMap, inProjectedContent } from '../contentProjection';\nimport {\n componentChildDirectiveMessage,\n componentChildDirectives,\n nativeTags,\n type PithyNode,\n} from '@pithyjs/compiler';\nimport { collectForwardedAttrs, applyForwardedAttrs } from './forwardedAttrs';\nimport { createRoot, untrack } from '@pithyjs/signals';\nimport { watchStaleRowProp } from './staleRowProps';\nimport { markForwardTarget, nodeExpando } from '../nodeExpando';\nimport { componentDisposer } from '../disposeOrder';\nimport { pithyGlobals } from '../../types/globals';\nimport { isSSRMode } from '../ssrMode';\nimport { clearSSRRenderCrash, reportComponentFailure } from '../ssrCrashes';\nimport { isRenderableComponentEl } from '../componentResult';\nimport { parsePropNames, type PropNames } from './propNames';\n\ninterface ComponentResult {\n /** Any DOM node — see the `Component` type for why this is not narrower. */\n el: Node;\n destroy?: () => void;\n}\ntype ComponentFn = (props: Record<string, unknown>) => ComponentResult;\n\n/**\n * Find the closest element-scoped context we attach in createLoopItem().\n * This is what exposes item(), gIdx(), count(), etc.\n */\n// Warn once per component/tag pair — the same idiom re-renders constantly\n// (e.g. a panel importing Button while using a native <button>), and\n// repeating the warning drowns out real ones.\nconst warnedComponentTags = new Set<string>();\nconst warnedChildDirectives = new WeakSet<PithyNode>();\n\n/** Test-only: forget which tags were warned about, so each render warns as a fresh process would. */\nexport function __resetComponentTagWarnings(): void {\n warnedComponentTags.clear();\n}\n\nfunction nearestCtx(\n el: Element,\n rootCtx: Record<string, unknown>\n): Record<string, unknown> {\n let n: Element | null = el;\n while (n) {\n const local = nodeExpando(n).__pithyCtx;\n if (local) return local;\n n = n.parentElement;\n }\n return rootCtx;\n}\n\n/**\n * Detect whether a node is inside a subtree that represents a NOT-YET-EXPANDED nested loop.\n * Those hosts are tagged in createLoopManager.createLoopItem() via `__pithySkipText`,\n * and real templates may also still carry @for / data-for before expansion.\n * We must *defer* binding for anything under such a host, otherwise expressions like item()\n * will throw ReferenceError (because inner loop ctx isn’t created yet).\n */\nfunction isInsidePendingLoopZone(node: Element): boolean {\n let p: Element | null = node;\n while (p) {\n if (nodeExpando(p).__pithySkipText) return true;\n if (\n p.hasAttribute &&\n (p.hasAttribute('@for') || p.hasAttribute('data-for'))\n ) {\n return true;\n }\n p = p.parentElement;\n }\n return false;\n}\n\n/** Evaluate `expr` in `ctx`. Try engine compiler first, then args-style fallback. */\nfunction evalInCtx(expr: string, ctx: Record<string, unknown>): unknown {\n // 1) Preferred: compileExpression uses `with(ctx) { return (...) }`\n try {\n const f = compileExpression(expr, ctx);\n try {\n return f();\n } catch {\n /* fall through to fallback */\n }\n } catch {\n /* fall through to fallback */\n }\n\n // 2) Fallback: args-style evaluator (robust even if compileExpression throws)\n const keys = Object.keys(ctx);\n const vals = keys.map(k => ctx[k]);\n // eslint-disable-next-line no-new-func -- args-style template expression evaluation is a core framework feature\n const fn = new Function(...keys, `return (${expr});`) as (\n ...args: unknown[]\n ) => unknown;\n return fn(...vals);\n}\n\nconst propNameCache = new WeakMap<ComponentFn, PropNames>();\n\nfunction readPropNames(componentFn: ComponentFn): PropNames {\n let cached = propNameCache.get(componentFn);\n if (!cached) {\n try {\n cached = parsePropNames(componentFn.toString());\n } catch {\n cached = { names: [], fromParam: false, exhaustive: false };\n }\n propNameCache.set(componentFn, cached);\n }\n return cached;\n}\n\nfunction extractExpectedPropNames(componentFn: ComponentFn): string[] {\n return readPropNames(componentFn).names;\n}\n\nconst warnedBoundProps = new Set<string>();\nconst GLOBAL_ATTRS = new Set([\n 'id',\n 'class',\n 'style',\n 'title',\n 'role',\n 'tabindex',\n 'hidden',\n]);\n\nfunction warnBoundProps(\n componentFn: ComponentFn,\n el: Element,\n componentName: string\n): void {\n const expected = extractExpectedPropNames(componentFn);\n for (const attr of Array.from(el.attributes)) {\n if (!attr.name.startsWith('data-bind-')) continue;\n const bound = attr.name.slice('data-bind-'.length);\n if (bound === 'slot' && !warnedBoundProps.has(`${componentName} slot`)) {\n warnedBoundProps.add(`${componentName} slot`);\n console.warn(\n `[PithyJS] <${componentName}> [slot] cannot choose a slot: the key is read as a literal, so this lands in the default slot. Write slot=\"name\".`\n );\n }\n if (GLOBAL_ATTRS.has(bound)) continue;\n const prop = expected.find(p => p.toLowerCase() === bound);\n const key = `${componentName} ${bound}`;\n if (!prop || warnedBoundProps.has(key)) continue;\n warnedBoundProps.add(key);\n console.warn(\n `[PithyJS] <${componentName}> [${bound}] sets an attribute on the rendered root, not the \\`${prop}\\` prop. Write ${prop}=\"…\" without brackets to set the prop; for a live value pass a signal or () => … if the prop accepts one.`\n );\n }\n}\n\n/** Dev warnings for unexpected props (only if destructuring is present). */\nfunction validateComponentProps(\n componentFn: ComponentFn,\n props: Record<string, unknown>,\n componentName: string\n): void {\n const { names: allNames, exhaustive } = readPropNames(componentFn);\n if (!exhaustive || allNames.length === 0) return;\n\n const passed = Object.keys(props);\n const expectedSet = new Set(allNames);\n\n const unexpected = passed.filter(p => !expectedSet.has(p));\n if (unexpected.length) {\n console.warn(\n `[PithyJS] 🔍 Component <${componentName}> received unexpected props: ${unexpected.join(\n ', '\n )}\\nExpected props: ${allNames.join(', ')}\\nPassed props: ${passed.join(', ')}`\n );\n }\n\n // NOTE: We intentionally do NOT warn about \"missing\" props here.\n // In template-driven usage, props are assembled at runtime by\n // bindComponentTags(), so TypeScript cannot catch missing required\n // props in this path. Components should self-validate critical\n // props where appropriate (e.g. Toggle warns on empty label).\n}\n\n/** DOM a component already rendered: its native tags may share a component's name. */\nfunction inComponentDom(el: Element): boolean {\n for (let n: Element | null = el; n; n = n.parentElement)\n if (nodeExpando(n).__pithyComponentDom) return true;\n return false;\n}\n\n/** Map lowercased DOM attr name to expected prop name (case-insensitive). */\nfunction normalizePropName(\n authoredName: string,\n expectedProps: string[]\n): string {\n if (expectedProps.includes(authoredName)) return authoredName;\n const lower = authoredName.toLowerCase();\n const matches = expectedProps.filter(p => p.toLowerCase() === lower);\n return matches.length === 1 ? matches[0] : authoredName;\n}\n\n/**\n * Replace custom component tags (<Counter/>, <NestedComponent/>) with rendered output.\n * - Skips anything under a pending nested loop host (bind after loop expansion)\n * - Evaluates prop expressions in nearest loop ctx\n * - Case-insensitive prop name normalization\n * - No raw-string fallback (prevents things like calling count() on a string)\n */\n/** @codexApi {\"parent\":\"pithy.runtime.components\",\"name\":\"bindComponentTags\",\"stability\":\"stable\",\"signature\":\"(root: Element | DocumentFragment, rootCtx: Record<string, unknown>, disposers: (() => void)[]) => void\"} */\nexport function bindComponentTags(\n root: Element | DocumentFragment,\n rootCtx: Record<string, unknown>,\n disposers: (() => void)[]\n): void {\n // case-insensitive tag lookup from context\n const tagMap = new Map<string, unknown>(\n Object.keys(rootCtx).map(k => [k.toLowerCase(), rootCtx[k]])\n );\n\n const scope =\n root instanceof Element ? (root as Element) : (root as DocumentFragment);\n const elements = Array.from(scope.querySelectorAll('*'));\n\n for (const el of elements) {\n // Skip elements removed from the tree by a parent component's render, or\n // hidden by an `@error-boundary` that has since activated.\n if (!scope.contains(el)) {\n // An element that has left the tree contributes nothing to the output, so\n // a crash recorded for it on an earlier DETACHED pass is stale. Leaving it\n // fails a route that rendered correctly: with two crashing components\n // under one boundary inside an `@if`, the detached pass records both, the\n // retry lets the boundary accept the first, and accepting synchronously\n // hides the second — which then never gets a retry to retract it.\n if (isSSRMode()) clearSSRRenderCrash(el);\n continue;\n }\n\n // Defer components inside not-yet-expanded loops\n if (isInsidePendingLoopZone(el)) continue;\n\n // A build's placeholder carries no AST: its children are DOM, which only\n // the AOT binder reads.\n const aotMount = nodeExpando(el).__pithyAotMount;\n if (aotMount) {\n // Marked as below, so the text pass skips what the component rendered.\n for (const node of aotMount(disposers))\n nodeExpando(node).__pithyComponentDom = true;\n continue;\n }\n\n const tag = el.tagName.toLowerCase();\n\n // Check if the parser marked this element as a component\n // This is the authoritative source - it checks originalTagName starts with uppercase\n // AND the tag name exists in importedIdentifiers\n const pithyNode = nodeExpando(el).__pithyNode;\n if (pithyNode) {\n // Parser processed this element - use its isComponent flag\n if (!pithyNode.isComponent) {\n // DEV: Warn if there's a component that matches case-insensitively\n // This helps developers catch typos like <button> when they meant <Button>\n // Skip warning if we're inside a component's render (the component might\n // legitimately use native elements like <button> in its implementation)\n const isInsideComponentRender =\n !!pithyGlobals().__pithyRenderingComponent;\n if (\n import.meta.env?.DEV &&\n !isInsideComponentRender &&\n !inComponentDom(el)\n ) {\n const matchingComponent = tagMap.get(tag);\n if (matchingComponent && typeof matchingComponent === 'function') {\n // Find the actual component name from context\n const componentName = Object.keys(rootCtx).find(\n k => k.toLowerCase() === tag && rootCtx[k] === matchingComponent\n );\n const warnKey = `${componentName}:${pithyNode.originalTagName}`;\n if (\n componentName &&\n componentName !== pithyNode.originalTagName &&\n !warnedComponentTags.has(warnKey)\n ) {\n warnedComponentTags.add(warnKey);\n console.warn(\n `[PithyJS] ⚠️ Component '${componentName}' is imported but used as '<${pithyNode.originalTagName}>'. ` +\n `Components must use PascalCase. Use '<${componentName}>' instead.`\n );\n }\n }\n }\n continue;\n }\n } else {\n // Fallback for elements not processed by our parser:\n // Skip native HTML elements to prevent <button> matching Button component\n if (nativeTags.has(tag)) continue;\n // Rendered already, e.g. a build's slot content.\n if (inComponentDom(el)) continue;\n }\n\n if (\n import.meta.env?.DEV &&\n pithyNode &&\n !warnedChildDirectives.has(pithyNode)\n ) {\n warnedChildDirectives.add(pithyNode);\n for (const name of componentChildDirectives(pithyNode))\n console.warn(\n `[pithy] ${componentChildDirectiveMessage(pithyNode.originalTagName ?? tag, name)}`\n );\n }\n\n let candidate = tagMap.get(tag);\n\n if (!candidate) continue;\n\n // Support default exports\n if (\n candidate &&\n typeof candidate === 'object' &&\n 'default' in candidate &&\n typeof candidate.default === 'function'\n ) {\n candidate = candidate.default;\n }\n if (typeof candidate !== 'function') continue;\n // Content a runtime-compiled receiver projected: bound detached, inside the\n // output of the component being rendered.\n const projectedHost =\n !el.closest('[data-error]') && inProjectedContent(el)\n ? pithyGlobals().__pithyComponentContext?.__slotHost\n : undefined;\n // Hidden like a sibling an activated boundary detached: never rendered.\n if (withSlotBoundary(undefined, projectedHost, () => slotContentHidden(el)))\n continue;\n\n const componentFn = candidate as ComponentFn;\n const localCtx = nearestCtx(el, rootCtx); // crucial for item(), gIdx(), etc.\n\n // Extract expected props for validation (DEV) and prop name normalization (always)\n // This ensures case-insensitive matching works even when originalAttrs is unavailable\n const { names, fromParam } = readPropNames(componentFn);\n const expectedProps = fromParam ? names : [];\n\n // Preserve originally-authored attribute names/casing from the parsed template\n // (pithyNode already extracted above for isComponent check)\n const originalAttrs: Record<string, string> | undefined =\n pithyNode?.originalAttrs;\n\n const props: Record<string, unknown> = {};\n\n const staleWatchers: (() => void)[] = [];\n\n // Evaluate attributes as expressions in localCtx\n for (const attr of Array.from(el.attributes)) {\n const name = attr.name;\n const raw = attr.value;\n\n // Skip internal/behavioral attributes\n if (name.startsWith('data-')) continue;\n if (name === 'class' || name === 'style' || name === 'slot') continue;\n if (!isTemplateAttr(attr)) continue;\n\n // Prefer originally-authored name (preserve casing), else DOM name\n const authored = originalAttrs?.[name] ?? name;\n const propName = normalizePropName(authored, expectedProps);\n\n try {\n const value = untrack(() => evalInCtx(raw, localCtx));\n props[propName] = value; // only set when evaluation succeeds\n if (import.meta.env?.DEV) {\n staleWatchers.push(() =>\n watchStaleRowProp(\n localCtx,\n pithyNode ?? el,\n pithyNode?.originalTagName || tag,\n propName,\n raw,\n value,\n () => evalInCtx(raw, localCtx),\n disposers\n )\n );\n }\n } catch (err) {\n if (import.meta.env?.DEV) {\n console.warn(\n `[PithyJS] ⚠️ Failed to evaluate prop \"${propName}\" = \"${raw}\"`,\n err\n );\n }\n // IMPORTANT: do NOT set a raw string fallback here.\n // Leaving it undefined lets the child use defaults and avoids count()-on-string.\n }\n }\n\n // Validate props for all components in DEV mode.\n // Native elements are already filtered out earlier (line 197 for fallback, line 171 for parser).\n if (import.meta.env?.DEV) {\n const displayTag = pithyNode?.originalTagName || tag;\n validateComponentProps(componentFn, props, displayTag);\n warnBoundProps(componentFn, el, displayTag);\n }\n\n // Collect content projection SlotMap from component children\n const pithyChildren: PithyNode[] = pithyNode?.children || [];\n const slotMap = collectSlotMap(pithyChildren, localCtx);\n\n // Create enhanced context with SlotMap for content projection\n const componentContext = {\n ...localCtx,\n __slotMap: slotMap,\n __childAstNodes: pithyChildren,\n __childFactory: undefined,\n __slotHost: el,\n };\n\n // Find nearest error boundary for this component\n const boundaryEl = el.closest('[data-error]') as Element | null;\n // Projected content is bound detached, during its receiver's render.\n const boundary =\n boundaryForElement(boundaryEl) ??\n (!boundaryEl && inProjectedContent(el) ? currentBoundary() : null);\n\n // Invoke component under boundary context; expect { el, destroy }\n let out: ComponentResult | undefined;\n let disposeSetup: (() => void) | undefined;\n try {\n out = runWithBoundary(boundary, () => {\n // Store the enhanced context globally for the component's html() calls to access.\n // This per-component context contains __slotMap for content projection.\n //\n // In SSR, there are TWO context sources that html() merges:\n // 1. AsyncLocalStorage context (__getComponentContext) - request-level isolation\n // 2. This global context (__pithyComponentContext) - per-component __slotMap\n //\n // Both are needed: AsyncLocalStorage provides request isolation, while this\n // global provides the __slotMap that changes for each component render.\n const g = pithyGlobals();\n const originalContext = g.__pithyComponentContext;\n const wasRendering = g.__pithyRenderingComponent;\n g.__pithyComponentContext = componentContext;\n // Mark that we're rendering a component to suppress casing warnings for\n // native elements used in component implementations (e.g., <button> in Button)\n g.__pithyRenderingComponent = true;\n\n try {\n const result = createRoot(disposeRoot => {\n disposeSetup = disposeRoot;\n return componentFn(props);\n });\n return result;\n } finally {\n // Restore original context\n g.__pithyComponentContext = originalContext;\n g.__pithyRenderingComponent = wasRendering;\n }\n });\n } catch (err) {\n // Route sync render errors to the nearest boundary with escalation\n if (boundary) {\n const error = err instanceof Error ? err : new Error(String(err));\n // A boundary being in scope does not mean it accepted the error: an\n // already-active boundary with no free ancestor drops it (React's\n // first-error-wins). A component inside that boundary's `@fallback` is\n // the everyday case, and the fallback is what the user actually sees.\n const accepted = reportComponentFailure(el, tag, error, boundary);\n if (import.meta.env?.DEV) {\n // Say which of the two actually happened. \"Captured\" on a rejected\n // error reports the opposite of the truth, and this branch exists\n // precisely because the two are not the same.\n console.log(\n accepted\n ? `[ErrorBoundary] Captured sync render error in <${tag}>:`\n : `[ErrorBoundary] Boundary already active — error from <${tag}> was NOT captured:`,\n error.message\n );\n }\n continue;\n }\n\n // No boundary in scope *yet*. Degrading is still the right call here in\n // both modes: throwing would pre-empt the retry pass that gives an\n // `@error-boundary` its only chance to claim a crash raised while the\n // subtree was detached.\n //\n // A static/server render additionally records the crash. Nobody reads a\n // console during `pithy-ssg`, so this used to leave the raw <${tag}> in\n // the emitted HTML while the route still counted as rendered and the CLI\n // exited 0 (BUG-018). Anything still recorded when the render finishes\n // makes the SSR renderer throw, and the per-route catch in `vite-ssg.ts`\n // fails that route.\n reportComponentFailure(\n el,\n tag,\n err instanceof Error ? err : new Error(String(err)),\n null\n );\n\n console.error(`❌ Component <${tag}> crashed during render:`, err);\n continue;\n }\n\n if (\n !out ||\n typeof out !== 'object' ||\n !('el' in out) ||\n !isRenderableComponentEl(out.el, el)\n ) {\n console.warn(\n `❌ Invalid render result from <${tag}>. Expected { el, destroy }`\n );\n // Not a throw, but the same outcome as one: the raw <${tag}> is left in\n // the document and the subtree never renders. Under SSR that is content\n // silently missing from the emitted HTML, so it is recorded exactly like\n // a crash (BUG-018). Recorded rather than merely left in place, because\n // this attempt may also be retracting an earlier attempt's record.\n // Same funnel as a throw: a boundary above this component gets the\n // chance to claim it and render its fallback, and only an unclaimed\n // failure is recorded. Bypassing this meant a component under\n // `@error-boundary` that returned garbage failed the route with the\n // boundary signal still null.\n reportComponentFailure(\n el,\n tag,\n new Error(\n `Invalid render result from <${tag}>; expected { el, destroy }`\n ),\n boundary\n );\n disposeSetup?.();\n continue;\n }\n\n const { el: renderedEl, destroy } = out;\n\n // Capture class and data-* attributes for forwarding to rendered root:\n // directive bindings (data-on-*, data-bind-*, data-class-toggle-*,\n // data-classes, data-style-*) plus any author-written data-* attribute.\n const forwardedClass = el.getAttribute('class');\n const forwardedAttrs = collectForwardedAttrs(el);\n\n const isFragment = renderedEl.nodeType === Node.DOCUMENT_FRAGMENT_NODE;\n let forwardTarget: HTMLElement | null = null;\n const hasForwardables = !!(forwardedClass || forwardedAttrs.length > 0);\n if (hasForwardables) {\n if (isFragment) {\n forwardTarget = (renderedEl as DocumentFragment)\n .firstElementChild as HTMLElement | null;\n if (import.meta.env?.DEV && !forwardTarget) {\n const displayTag = pithyNode?.originalTagName || tag;\n console.warn(\n `[PithyJS] <${displayTag}> has class or data-* attributes but returns a fragment with no element children — forwarding skipped.`\n );\n }\n } else if (renderedEl.nodeType === Node.ELEMENT_NODE) {\n forwardTarget = renderedEl as HTMLElement;\n }\n }\n\n const renderedNodes = isFragment\n ? Array.from(renderedEl.childNodes)\n : [renderedEl];\n for (const node of renderedNodes)\n nodeExpando(node).__pithyComponentDom = true;\n\n let replaced = true;\n let hidden = false;\n try {\n // A boundary that caught a crash in this render may have hidden `el`.\n hidden = replaceHidden(el, renderedNodes);\n if (!hidden) el.replaceWith(...renderedNodes);\n } catch (err) {\n // A failed replacement leaves the raw <${tag}> exactly where a crash\n // would have, so it is the same content loss and is recorded the same way.\n replaced = false;\n reportComponentFailure(\n el,\n tag,\n err instanceof Error ? err : new Error(String(err)),\n boundary\n );\n console.error(`❌ Failed to replace <${tag}> with rendered DOM:`, err);\n }\n\n // Retracted only here, and in the boundary catch above — never eagerly at\n // the top of an attempt, where any early `continue` added later would\n // silently drop a real record. This is the point at which the component is\n // known to have produced a usable node AND to have reached the document, so\n // an earlier detached attempt's crash is genuinely no longer the outcome.\n if (isSSRMode() && replaced) clearSSRRenderCrash(el);\n\n for (const watch of staleWatchers) watch();\n\n // Forward class from component tag onto the rendered root element\n if (forwardedClass && forwardTarget) {\n for (const cls of forwardedClass.split(/\\s+/)) {\n if (cls) forwardTarget.classList.add(cls);\n }\n }\n\n // Before any binding pass below, which can throw.\n const teardown = componentDisposer(\n destroy,\n disposeSetup,\n renderedNodes[0] ?? (replaced ? null : el)\n );\n if (teardown) disposers.push(teardown);\n\n // Forward captured attributes so subsequent binders can attach the bindings\n if (forwardedAttrs.length > 0 && forwardTarget) {\n applyForwardedAttrs(forwardTarget, forwardedAttrs, tag);\n markForwardTarget(\n forwardTarget,\n localCtx,\n new Set(forwardedAttrs.map(([name]) => name))\n );\n const styleProps = Object.keys(pithyNode?.directives?.styleMap ?? {});\n if (styleProps.length)\n nodeExpando(forwardTarget).__styleProps = styleProps;\n const classToggles = Object.keys(pithyNode?.directives?.classMap ?? {});\n if (classToggles.length)\n nodeExpando(forwardTarget).__classToggles = classToggles;\n // Hidden, it is out of reach of this fragment's later passes. An active\n // nested boundary `hideContent` kept in place is still within reach.\n if (hidden && !forwardTarget.parentNode) {\n const detached = document.createDocumentFragment();\n detached.append(forwardTarget);\n bindAfterComponents(detached, localCtx, disposers);\n }\n }\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bindEventHandlers.d.ts","sourceRoot":"","sources":["../../../src/compile/binds/bindEventHandlers.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AA0GF;;;;;;GAMG;AACH,wNAAwN;AACxN,wBAAgB,iBAAiB,CAC/B,IAAI,EAAE,OAAO,GAAG,gBAAgB,EAChC,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAChC,SAAS,EAAE,CAAC,MAAM,IAAI,CAAC,EAAE,GACxB,IAAI,
|
|
1
|
+
{"version":3,"file":"bindEventHandlers.d.ts","sourceRoot":"","sources":["../../../src/compile/binds/bindEventHandlers.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AA0GF;;;;;;GAMG;AACH,wNAAwN;AACxN,wBAAgB,iBAAiB,CAC/B,IAAI,EAAE,OAAO,GAAG,gBAAgB,EAChC,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAChC,SAAS,EAAE,CAAC,MAAM,IAAI,CAAC,EAAE,GACxB,IAAI,CAyFN"}
|
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
*/
|
|
8
8
|
import { isDeclaredDirective } from './declaredDirective.js';
|
|
9
9
|
import { boundaryForElement, setBoundaryError } from './bindErrorBoundary.js';
|
|
10
|
-
import { nodeExpando } from '../nodeExpando.js';
|
|
10
|
+
import { forwardEventKey, nodeExpando } from '../nodeExpando.js';
|
|
11
11
|
/**
|
|
12
12
|
* Walk up the DOM to find the nearest local PithyJS context attached by loops/components.
|
|
13
13
|
* Falls back to the provided root context.
|
|
@@ -106,10 +106,15 @@ export function bindEventHandlers(root, rootCtx, disposers) {
|
|
|
106
106
|
continue;
|
|
107
107
|
// Idempotency key includes attr name (mods) + expression
|
|
108
108
|
const boundSet = getBoundSet(el, eventName);
|
|
109
|
-
const
|
|
109
|
+
const plainKey = `${attr.name}=${handlerExpr}`;
|
|
110
|
+
const fwdCtx = nodeExpando(el).__pithyForwardCtx;
|
|
111
|
+
const forwarded = !!fwdCtx && !!nodeExpando(el).__pithyForwardAttrs?.has(attr.name);
|
|
112
|
+
const boundKey = forwarded ? forwardEventKey(el, plainKey) : plainKey;
|
|
110
113
|
if (boundSet.has(boundKey))
|
|
111
114
|
continue;
|
|
112
|
-
|
|
115
|
+
// An outer level's pass must not rebind this forwarded value as its own.
|
|
116
|
+
const claimsPlain = forwarded && !boundSet.has(plainKey);
|
|
117
|
+
const ctx = forwarded ? fwdCtx : nearestCtx(el, rootCtx);
|
|
113
118
|
const isSimpleIdentifier = /^[a-zA-Z_][a-zA-Z0-9_]*$/.test(handlerExpr);
|
|
114
119
|
// If the expression is a bare identifier and resolves to a function on ctx,
|
|
115
120
|
// we'll call it directly (browser passes the event), preserving 'this' as ctx.
|
|
@@ -162,12 +167,16 @@ export function bindEventHandlers(root, rootCtx, disposers) {
|
|
|
162
167
|
};
|
|
163
168
|
el.addEventListener(eventName, listener, options);
|
|
164
169
|
boundSet.add(boundKey);
|
|
170
|
+
if (claimsPlain)
|
|
171
|
+
boundSet.add(plainKey);
|
|
165
172
|
disposers.push(() => {
|
|
166
173
|
// Note: removeEventListener only considers `capture`; `once`/`passive` are ignored here.
|
|
167
174
|
el.removeEventListener(eventName, listener, {
|
|
168
175
|
capture: !!mods.capture,
|
|
169
176
|
});
|
|
170
177
|
boundSet.delete(boundKey);
|
|
178
|
+
if (claimsPlain)
|
|
179
|
+
boundSet.delete(plainKey);
|
|
171
180
|
});
|
|
172
181
|
}
|
|
173
182
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bindEventHandlers.js","sourceRoot":"","sources":["../../../src/compile/binds/bindEventHandlers.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAEF,OAAO,EAAE,mBAAmB,EAAE,MAAM,qBAAqB,CAAC;AAC1D,OAAO,EAAE,kBAAkB,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAC3E,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAE7C;;;GAGG;AACH,SAAS,UAAU,CACjB,EAAW,EACX,OAAgC;IAEhC,IAAI,CAAC,GAAmB,EAAE,CAAC;IAC3B,OAAO,CAAC,EAAE,CAAC;QACT,MAAM,KAAK,GAAG,WAAW,CAAC,CAAC,CAAC,CAAC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YAEF,kCAAkC;YAClC,MAAM,OAAO,GAAG;gBACd,OAAO,EAAE,CAAC,CAAC,IAAI,CAAC,OAAO;gBACvB,OAAO,EAAE,CAAC,CAAC,IAAI,CAAC,OAAO;gBACvB,IAAI,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI;aACS,CAAC;YAE7B,EAAE,CAAC,gBAAgB,CAAC,SAAS,EAAE,QAAQ,EAAE,OAAO,CAAC,CAAC;YAElD,QAAQ,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;YACvB,SAAS,CAAC,IAAI,CAAC,GAAG,EAAE;gBAClB,yFAAyF;gBACzF,EAAE,CAAC,mBAAmB,CAAC,SAAS,EAAE,QAAQ,EAAE;oBAC1C,OAAO,EAAE,CAAC,CAAC,IAAI,CAAC,OAAO;iBACxB,CAAC,CAAC;gBACH,QAAQ,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;YAC5B,CAAC,CAAC,CAAC;QACL,CAAC;IACH,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["/** @codex\n{\n \"id\": \"pithy.runtime.events\",\n \"title\": \"Event Handler Binding System\",\n \"category\": \"runtime\"\n}\n*/\n\nimport { isDeclaredDirective } from './declaredDirective';\nimport { boundaryForElement, setBoundaryError } from './bindErrorBoundary';\nimport { nodeExpando } from '../nodeExpando';\n\n/**\n * Walk up the DOM to find the nearest local PithyJS context attached by loops/components.\n * Falls back to the provided root context.\n */\nfunction nearestCtx(\n el: Element,\n rootCtx: Record<string, unknown>\n): Record<string, unknown> {\n let n: Element | null = el;\n while (n) {\n const local = nodeExpando(n).__pithyCtx;\n if (local) return local;\n n = n.parentElement;\n }\n return rootCtx;\n}\n\ntype Mods = {\n once?: boolean;\n prevent?: boolean;\n stop?: boolean;\n self?: boolean;\n capture?: boolean;\n passive?: boolean;\n};\n\nfunction parseEventAttr(name: string): { type: string; mods: Mods } {\n // \"data-on-click\" or \"data-on-click.once.prevent\"\n const raw = name.slice('data-on-'.length);\n const parts = raw.split('.');\n const type = parts[0];\n const mods: Mods = {};\n for (let i = 1; i < parts.length; i++) {\n const p = parts[i];\n if (p === 'once') mods.once = true;\n else if (p === 'prevent') mods.prevent = true;\n else if (p === 'stop') mods.stop = true;\n else if (p === 'self') mods.self = true;\n else if (p === 'capture') mods.capture = true;\n else if (p === 'passive') mods.passive = true;\n }\n return { type, mods };\n}\n\n/**\n * Per-element, per-event registry of bound expressions,\n * so we don't double-attach listeners when DOM is moved or reprocessed.\n */\nconst BOUND_KEY: unique symbol = Symbol('pithy:bound');\n\nfunction getBoundSet(el: Element, type: string) {\n const host = el as Element & { [BOUND_KEY]?: Record<string, Set<string>> };\n const store =\n host[BOUND_KEY] ??\n (host[BOUND_KEY] = Object.create(null) as Record<string, Set<string>>);\n return (store[type] ??= new Set<string>());\n}\n\n/**\n * Compile an expression so it can see ctx + $event + $el.\n * We intentionally do not use compileExpression here so we can inject $event/$el.\n */\nfunction compileWithEvent(\n expr: string,\n ctx: Record<string, unknown>\n): (ev: Event, el: Element) => unknown {\n try {\n // Build a function that accepts (ctx, $event, $el) and returns the expression result.\n // `with(ctx)` makes identifiers resolve against the provided context object.\n // eslint-disable-next-line no-new-func -- JIT event-handler expression evaluation is a core framework feature\n const fn = new Function(\n 'ctx',\n '$event',\n '$el',\n `with (ctx) { return (${expr}); }`\n ) as (ctx: Record<string, unknown>, ev: Event, el: Element) => unknown;\n return (ev: Event, el: Element) => fn(ctx, ev, el);\n } catch (err) {\n if (import.meta.env?.DEV) {\n console.warn(`[bindEventHandlers] ❌ Failed to compile \"${expr}\"`, err);\n }\n // Return a noop runner\n return (_ev: Event, _el: Element) => undefined;\n }\n}\n\n/**\n * Traverse all elements under `root` (Element or DocumentFragment) using a TreeWalker.\n */\nfunction forEachElement(\n root: Element | DocumentFragment,\n cb: (el: Element) => void\n) {\n const walker = document.createTreeWalker(root, NodeFilter.SHOW_ELEMENT);\n let node: Node | null;\n while ((node = walker.nextNode())) {\n cb(node as Element);\n }\n}\n\n/**\n * Binds DOM event handlers within `root`.\n * - Uses nearest element context (e.g., loop item ctx) when present.\n * - Idempotent: won't re-bind the same element/event/expression+modifiers combo.\n * - Supports modifiers: .once .prevent .stop .self .capture .passive\n * - Injects `$event` and `$el` for expression handlers (e.g., @click=\"doThing($event)\")\n */\n/** @codexApi {\"parent\":\"pithy.runtime.events\",\"name\":\"bindEventHandlers\",\"stability\":\"stable\",\"signature\":\"(root: Element | DocumentFragment, rootCtx: Record<string, unknown>, disposers: (() => void)[]) => void\"} */\nexport function bindEventHandlers(\n root: Element | DocumentFragment,\n rootCtx: Record<string, unknown>,\n disposers: (() => void)[]\n): void {\n forEachElement(root, el => {\n // Iterate attributes once; bind any data-on-* handlers\n for (const attr of Array.from(el.attributes)) {\n if (!attr.name.startsWith('data-on-') || !isDeclaredDirective(attr))\n continue;\n\n const { type: eventName, mods } = parseEventAttr(attr.name);\n const handlerExpr = attr.value.trim();\n if (!handlerExpr) continue;\n\n // Idempotency key includes attr name (mods) + expression\n const boundSet = getBoundSet(el, eventName);\n const boundKey = `${attr.name}=${handlerExpr}`;\n if (boundSet.has(boundKey)) continue;\n\n const ctx = nearestCtx(el, rootCtx);\n const isSimpleIdentifier = /^[a-zA-Z_][a-zA-Z0-9_]*$/.test(handlerExpr);\n\n // If the expression is a bare identifier and resolves to a function on ctx,\n // we'll call it directly (browser passes the event), preserving 'this' as ctx.\n const directFn =\n isSimpleIdentifier && typeof ctx[handlerExpr] === 'function'\n ? (ctx[handlerExpr] as EventListener)\n : null;\n\n // Otherwise, compile an event-aware evaluator that can see `$event` & `$el`.\n const runWithEvent = directFn ? null : compileWithEvent(handlerExpr, ctx);\n\n // Final listener with modifiers + $event/$el support + error boundary capture\n const listener: EventListener = (ev: Event) => {\n if (mods.self && ev.target !== el) return;\n if (mods.prevent) ev.preventDefault();\n if (mods.stop) ev.stopPropagation();\n\n try {\n if (directFn) {\n // Call the function from ctx with ctx as 'this'\n return directFn.call(ctx, ev);\n } else if (runWithEvent) {\n const out = runWithEvent(ev, el);\n // If expression returns a function, treat that as a handler and pass the event\n if (typeof out === 'function') {\n return (out as (e: Event) => unknown).call(ctx, ev);\n }\n return out;\n }\n } catch (error) {\n // Find the nearest error boundary and set its error signal with escalation\n const boundaryEl = el.closest('[data-error]') as Element | null;\n const boundary = boundaryForElement(boundaryEl);\n if (boundary) {\n const err =\n error instanceof Error ? error : new Error(String(error));\n setBoundaryError(boundary, err);\n } else {\n // No boundary found, re-throw to maintain original behavior\n throw error;\n }\n }\n };\n\n // Attach with appropriate options\n const options = {\n capture: !!mods.capture,\n passive: !!mods.passive,\n once: !!mods.once,\n } as AddEventListenerOptions;\n\n el.addEventListener(eventName, listener, options);\n\n boundSet.add(boundKey);\n disposers.push(() => {\n // Note: removeEventListener only considers `capture`; `once`/`passive` are ignored here.\n el.removeEventListener(eventName, listener, {\n capture: !!mods.capture,\n });\n boundSet.delete(boundKey);\n });\n }\n });\n}\n"]}
|
|
1
|
+
{"version":3,"file":"bindEventHandlers.js","sourceRoot":"","sources":["../../../src/compile/binds/bindEventHandlers.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAEF,OAAO,EAAE,mBAAmB,EAAE,MAAM,qBAAqB,CAAC;AAC1D,OAAO,EAAE,kBAAkB,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAC3E,OAAO,EAAE,eAAe,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAE9D;;;GAGG;AACH,SAAS,UAAU,CACjB,EAAW,EACX,OAAgC;IAEhC,IAAI,CAAC,GAAmB,EAAE,CAAC;IAC3B,OAAO,CAAC,EAAE,CAAC;QACT,MAAM,KAAK,GAAG,WAAW,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC;QACxC,IAAI,KAAK;YAAE,OAAO,KAAK,CAAC;QACxB,CAAC,GAAG,CAAC,CAAC,aAAa,CAAC;IACtB,CAAC;IACD,OAAO,OAAO,CAAC;AACjB,CAAC;AAWD,SAAS,cAAc,CAAC,IAAY;IAClC,kD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wBACb,MAAM,GAAG,GACP,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,KAAK,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC;wBAC5D,gBAAgB,CAAC,QAAQ,EAAE,GAAG,CAAC,CAAC;oBAClC,CAAC;yBAAM,CAAC;wBACN,4DAA4D;wBAC5D,MAAM,KAAK,CAAC;oBACd,CAAC;gBACH,CAAC;YACH,CAAC,CAAC;YAEF,kCAAkC;YAClC,MAAM,OAAO,GAAG;gBACd,OAAO,EAAE,CAAC,CAAC,IAAI,CAAC,OAAO;gBACvB,OAAO,EAAE,CAAC,CAAC,IAAI,CAAC,OAAO;gBACvB,IAAI,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI;aACS,CAAC;YAE7B,EAAE,CAAC,gBAAgB,CAAC,SAAS,EAAE,QAAQ,EAAE,OAAO,CAAC,CAAC;YAElD,QAAQ,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;YACvB,IAAI,WAAW;gBAAE,QAAQ,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;YACxC,SAAS,CAAC,IAAI,CAAC,GAAG,EAAE;gBAClB,yFAAyF;gBACzF,EAAE,CAAC,mBAAmB,CAAC,SAAS,EAAE,QAAQ,EAAE;oBAC1C,OAAO,EAAE,CAAC,CAAC,IAAI,CAAC,OAAO;iBACxB,CAAC,CAAC;gBACH,QAAQ,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;gBAC1B,IAAI,WAAW;oBAAE,QAAQ,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;YAC7C,CAAC,CAAC,CAAC;QACL,CAAC;IACH,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["/** @codex\n{\n \"id\": \"pithy.runtime.events\",\n \"title\": \"Event Handler Binding System\",\n \"category\": \"runtime\"\n}\n*/\n\nimport { isDeclaredDirective } from './declaredDirective';\nimport { boundaryForElement, setBoundaryError } from './bindErrorBoundary';\nimport { forwardEventKey, nodeExpando } from '../nodeExpando';\n\n/**\n * Walk up the DOM to find the nearest local PithyJS context attached by loops/components.\n * Falls back to the provided root context.\n */\nfunction nearestCtx(\n el: Element,\n rootCtx: Record<string, unknown>\n): Record<string, unknown> {\n let n: Element | null = el;\n while (n) {\n const local = nodeExpando(n).__pithyCtx;\n if (local) return local;\n n = n.parentElement;\n }\n return rootCtx;\n}\n\ntype Mods = {\n once?: boolean;\n prevent?: boolean;\n stop?: boolean;\n self?: boolean;\n capture?: boolean;\n passive?: boolean;\n};\n\nfunction parseEventAttr(name: string): { type: string; mods: Mods } {\n // \"data-on-click\" or \"data-on-click.once.prevent\"\n const raw = name.slice('data-on-'.length);\n const parts = raw.split('.');\n const type = parts[0];\n const mods: Mods = {};\n for (let i = 1; i < parts.length; i++) {\n const p = parts[i];\n if (p === 'once') mods.once = true;\n else if (p === 'prevent') mods.prevent = true;\n else if (p === 'stop') mods.stop = true;\n else if (p === 'self') mods.self = true;\n else if (p === 'capture') mods.capture = true;\n else if (p === 'passive') mods.passive = true;\n }\n return { type, mods };\n}\n\n/**\n * Per-element, per-event registry of bound expressions,\n * so we don't double-attach listeners when DOM is moved or reprocessed.\n */\nconst BOUND_KEY: unique symbol = Symbol('pithy:bound');\n\nfunction getBoundSet(el: Element, type: string) {\n const host = el as Element & { [BOUND_KEY]?: Record<string, Set<string>> };\n const store =\n host[BOUND_KEY] ??\n (host[BOUND_KEY] = Object.create(null) as Record<string, Set<string>>);\n return (store[type] ??= new Set<string>());\n}\n\n/**\n * Compile an expression so it can see ctx + $event + $el.\n * We intentionally do not use compileExpression here so we can inject $event/$el.\n */\nfunction compileWithEvent(\n expr: string,\n ctx: Record<string, unknown>\n): (ev: Event, el: Element) => unknown {\n try {\n // Build a function that accepts (ctx, $event, $el) and returns the expression result.\n // `with(ctx)` makes identifiers resolve against the provided context object.\n // eslint-disable-next-line no-new-func -- JIT event-handler expression evaluation is a core framework feature\n const fn = new Function(\n 'ctx',\n '$event',\n '$el',\n `with (ctx) { return (${expr}); }`\n ) as (ctx: Record<string, unknown>, ev: Event, el: Element) => unknown;\n return (ev: Event, el: Element) => fn(ctx, ev, el);\n } catch (err) {\n if (import.meta.env?.DEV) {\n console.warn(`[bindEventHandlers] ❌ Failed to compile \"${expr}\"`, err);\n }\n // Return a noop runner\n return (_ev: Event, _el: Element) => undefined;\n }\n}\n\n/**\n * Traverse all elements under `root` (Element or DocumentFragment) using a TreeWalker.\n */\nfunction forEachElement(\n root: Element | DocumentFragment,\n cb: (el: Element) => void\n) {\n const walker = document.createTreeWalker(root, NodeFilter.SHOW_ELEMENT);\n let node: Node | null;\n while ((node = walker.nextNode())) {\n cb(node as Element);\n }\n}\n\n/**\n * Binds DOM event handlers within `root`.\n * - Uses nearest element context (e.g., loop item ctx) when present.\n * - Idempotent: won't re-bind the same element/event/expression+modifiers combo.\n * - Supports modifiers: .once .prevent .stop .self .capture .passive\n * - Injects `$event` and `$el` for expression handlers (e.g., @click=\"doThing($event)\")\n */\n/** @codexApi {\"parent\":\"pithy.runtime.events\",\"name\":\"bindEventHandlers\",\"stability\":\"stable\",\"signature\":\"(root: Element | DocumentFragment, rootCtx: Record<string, unknown>, disposers: (() => void)[]) => void\"} */\nexport function bindEventHandlers(\n root: Element | DocumentFragment,\n rootCtx: Record<string, unknown>,\n disposers: (() => void)[]\n): void {\n forEachElement(root, el => {\n // Iterate attributes once; bind any data-on-* handlers\n for (const attr of Array.from(el.attributes)) {\n if (!attr.name.startsWith('data-on-') || !isDeclaredDirective(attr))\n continue;\n\n const { type: eventName, mods } = parseEventAttr(attr.name);\n const handlerExpr = attr.value.trim();\n if (!handlerExpr) continue;\n\n // Idempotency key includes attr name (mods) + expression\n const boundSet = getBoundSet(el, eventName);\n const plainKey = `${attr.name}=${handlerExpr}`;\n const fwdCtx = nodeExpando(el).__pithyForwardCtx;\n const forwarded =\n !!fwdCtx && !!nodeExpando(el).__pithyForwardAttrs?.has(attr.name);\n const boundKey = forwarded ? forwardEventKey(el, plainKey) : plainKey;\n if (boundSet.has(boundKey)) continue;\n // An outer level's pass must not rebind this forwarded value as its own.\n const claimsPlain = forwarded && !boundSet.has(plainKey);\n\n const ctx = forwarded ? fwdCtx : nearestCtx(el, rootCtx);\n const isSimpleIdentifier = /^[a-zA-Z_][a-zA-Z0-9_]*$/.test(handlerExpr);\n\n // If the expression is a bare identifier and resolves to a function on ctx,\n // we'll call it directly (browser passes the event), preserving 'this' as ctx.\n const directFn =\n isSimpleIdentifier && typeof ctx[handlerExpr] === 'function'\n ? (ctx[handlerExpr] as EventListener)\n : null;\n\n // Otherwise, compile an event-aware evaluator that can see `$event` & `$el`.\n const runWithEvent = directFn ? null : compileWithEvent(handlerExpr, ctx);\n\n // Final listener with modifiers + $event/$el support + error boundary capture\n const listener: EventListener = (ev: Event) => {\n if (mods.self && ev.target !== el) return;\n if (mods.prevent) ev.preventDefault();\n if (mods.stop) ev.stopPropagation();\n\n try {\n if (directFn) {\n // Call the function from ctx with ctx as 'this'\n return directFn.call(ctx, ev);\n } else if (runWithEvent) {\n const out = runWithEvent(ev, el);\n // If expression returns a function, treat that as a handler and pass the event\n if (typeof out === 'function') {\n return (out as (e: Event) => unknown).call(ctx, ev);\n }\n return out;\n }\n } catch (error) {\n // Find the nearest error boundary and set its error signal with escalation\n const boundaryEl = el.closest('[data-error]') as Element | null;\n const boundary = boundaryForElement(boundaryEl);\n if (boundary) {\n const err =\n error instanceof Error ? error : new Error(String(error));\n setBoundaryError(boundary, err);\n } else {\n // No boundary found, re-throw to maintain original behavior\n throw error;\n }\n }\n };\n\n // Attach with appropriate options\n const options = {\n capture: !!mods.capture,\n passive: !!mods.passive,\n once: !!mods.once,\n } as AddEventListenerOptions;\n\n el.addEventListener(eventName, listener, options);\n\n boundSet.add(boundKey);\n if (claimsPlain) boundSet.add(plainKey);\n disposers.push(() => {\n // Note: removeEventListener only considers `capture`; `once`/`passive` are ignored here.\n el.removeEventListener(eventName, listener, {\n capture: !!mods.capture,\n });\n boundSet.delete(boundKey);\n if (claimsPlain) boundSet.delete(plainKey);\n });\n }\n });\n}\n"]}
|
|
@@ -19,6 +19,16 @@ export interface NodeExpando {
|
|
|
19
19
|
__styleOwners?: StyleOwners;
|
|
20
20
|
__classToggles?: string[];
|
|
21
21
|
__forwardedDirectives?: Map<string, string>;
|
|
22
|
+
/** A component root's forwarded bindings evaluate in the tag's template. */
|
|
23
|
+
__pithyForwardCtx?: Record<string, unknown>;
|
|
24
|
+
/** The attributes the tag that set `__pithyForwardCtx` forwarded. */
|
|
25
|
+
__pithyForwardAttrs?: Set<string>;
|
|
26
|
+
/** Identifies that forwarding, so two tags in one scope stay two bindings. */
|
|
27
|
+
__pithyForwardId?: number;
|
|
22
28
|
}
|
|
29
|
+
/** Records that `ctx`'s tag forwarded `names` onto `root`. */
|
|
30
|
+
export declare function markForwardTarget(root: Element, ctx: Record<string, unknown>, names: Set<string>): void;
|
|
31
|
+
/** Keys a forwarded event by the forwarding that put it on `el`. */
|
|
32
|
+
export declare function forwardEventKey(el: Element, key: string): string;
|
|
23
33
|
export declare function nodeExpando<T extends Node>(node: T): T & NodeExpando;
|
|
24
34
|
//# sourceMappingURL=nodeExpando.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"nodeExpando.d.ts","sourceRoot":"","sources":["../../src/compile/nodeExpando.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;AAEnD,MAAM,WAAW,WAAW;IAC1B,OAAO,EAAE,MAAM,EAAE,CAAC;IAClB,KAAK,EAAE,GAAG,CAAC,MAAM,EAAE,CAAC,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,CAAC,CAAC,CAAC;CACvD;AAED,MAAM,WAAW,WAAW;IAC1B,UAAU,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IACrC,WAAW,CAAC,EAAE,SAAS,CAAC;IACxB,QAAQ,CAA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AA0E;IAC1E,yEAAyE;IACzE,eAAe,CAAC,EAAE,CAAC,SAAS,EAAE,CAAC,MAAM,IAAI,CAAC,EAAE,KAAK,IAAI,EAAE,CAAC;IACxD,YAAY,CAAC,EAAE,MAAM,EAAE,CAAC;IACxB,aAAa,CAAC,EAAE,WAAW,CAAC;IAC5B,cAAc,CAAC,EAAE,MAAM,EAAE,CAAC;IAC1B,qBAAqB,CAAC,EAAE,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAC5C,4EAA4E;IAC5E,iBAAiB,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAC5C,qEAAqE;IACrE,mBAAmB,CAAC,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC;IAClC,8EAA8E;IAC9E,gBAAgB,CAAC,EAAE,MAAM,CAAC;CAC3B;AAID,8DAA8D;AAC9D,wBAAgB,iBAAiB,CAC/B,IAAI,EAAE,OAAO,EACb,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAC5B,KAAK,EAAE,GAAG,CAAC,MAAM,CAAC,GACjB,IAAI,CAKN;AAED,oEAAoE;AACpE,wBAAgB,eAAe,CAAC,EAAE,EAAE,OAAO,EAAE,GAAG,EAAE,MAAM,GAAG,MAAM,CAEhE;AAED,wBAAgB,WAAW,CAAC,CAAC,SAAS,IAAI,EAAE,IAAI,EAAE,CAAC,GAAG,CAAC,GAAG,WAAW,CAEpE"}
|
|
@@ -1,3 +1,15 @@
|
|
|
1
|
+
let nextForwardId = 0;
|
|
2
|
+
/** Records that `ctx`'s tag forwarded `names` onto `root`. */
|
|
3
|
+
export function markForwardTarget(root, ctx, names) {
|
|
4
|
+
const x = nodeExpando(root);
|
|
5
|
+
x.__pithyForwardCtx = ctx;
|
|
6
|
+
x.__pithyForwardAttrs = names;
|
|
7
|
+
x.__pithyForwardId = ++nextForwardId;
|
|
8
|
+
}
|
|
9
|
+
/** Keys a forwarded event by the forwarding that put it on `el`. */
|
|
10
|
+
export function forwardEventKey(el, key) {
|
|
11
|
+
return `${nodeExpando(el).__pithyForwardId}|${key}`;
|
|
12
|
+
}
|
|
1
13
|
export function nodeExpando(node) {
|
|
2
14
|
return node;
|
|
3
15
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"nodeExpando.js","sourceRoot":"","sources":["../../src/compile/nodeExpando.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"nodeExpando.js","sourceRoot":"","sources":["../../src/compile/nodeExpando.ts"],"names":[],"mappings":"AA+BA,IAAI,aAAa,GAAG,CAAC,CAAC;AAEtB,8DAA8D;AAC9D,MAAM,UAAU,iBAAiB,CAC/B,IAAa,EACb,GAA4B,EAC5B,KAAkB;IAElB,MAAM,CAAC,GAAG,WAAW,CAAC,IAAI,CAAC,CAAC;IAC5B,CAAC,CAAC,iBAAiB,GAAG,GAAG,CAAC;IAC1B,CAAC,CAAC,mBAAmB,GAAG,KAAK,CAAC;IAC9B,CAAC,CAAC,gBAAgB,GAAG,EAAE,aAAa,CAAC;AACvC,CAAC;AAED,oEAAoE;AACpE,MAAM,UAAU,eAAe,CAAC,EAAW,EAAE,GAAW;IACtD,OAAO,GAAG,WAAW,CAAC,EAAE,CAAC,CAAC,gBAAgB,IAAI,GAAG,EAAE,CAAC;AACtD,CAAC;AAED,MAAM,UAAU,WAAW,CAAiB,IAAO;IACjD,OAAO,IAAuB,CAAC;AACjC,CAAC","sourcesContent":["import type { PithyNode } from '@pithyjs/compiler';\n\nexport interface StyleOwners {\n strings: string[];\n props: Map<string, [value: string, priority: string]>;\n}\n\nexport interface NodeExpando {\n __pithyCtx?: Record<string, unknown>;\n __pithyNode?: PithyNode;\n __nodeId?: string;\n __slotName?: string;\n __fallbackFactory?: () => DocumentFragment;\n __nested?: boolean;\n __pithySkipText?: boolean;\n __pithyComponentDom?: boolean;\n /** A build's component placeholder: renders it through the AOT binder. */\n /** Renders a build's placeholder; returns the nodes that replaced it. */\n __pithyAotMount?: (disposers: (() => void)[]) => Node[];\n __styleProps?: string[];\n __styleOwners?: StyleOwners;\n __classToggles?: string[];\n __forwardedDirectives?: Map<string, string>;\n /** A component root's forwarded bindings evaluate in the tag's template. */\n __pithyForwardCtx?: Record<string, unknown>;\n /** The attributes the tag that set `__pithyForwardCtx` forwarded. */\n __pithyForwardAttrs?: Set<string>;\n /** Identifies that forwarding, so two tags in one scope stay two bindings. */\n __pithyForwardId?: number;\n}\n\nlet nextForwardId = 0;\n\n/** Records that `ctx`'s tag forwarded `names` onto `root`. */\nexport function markForwardTarget(\n root: Element,\n ctx: Record<string, unknown>,\n names: Set<string>\n): void {\n const x = nodeExpando(root);\n x.__pithyForwardCtx = ctx;\n x.__pithyForwardAttrs = names;\n x.__pithyForwardId = ++nextForwardId;\n}\n\n/** Keys a forwarded event by the forwarding that put it on `el`. */\nexport function forwardEventKey(el: Element, key: string): string {\n return `${nodeExpando(el).__pithyForwardId}|${key}`;\n}\n\nexport function nodeExpando<T extends Node>(node: T): T & NodeExpando {\n return node as T & NodeExpando;\n}\n"]}
|
|
@@ -152,7 +152,8 @@ function preprocessSelfClosingComponents(html, importedIdentifiers) {
|
|
|
152
152
|
// Matches: <ComponentName /> or <ComponentName/>
|
|
153
153
|
// IMPORTANT: Use 'g' flag only (NOT 'gi') - case-sensitive matching is required
|
|
154
154
|
// to avoid converting native elements like <input /> to <Input></Input>
|
|
155
|
-
|
|
155
|
+
// Quoted values may hold `>` (an arrow-function prop), so skip them whole.
|
|
156
|
+
const selfClosingRegex = new RegExp(`<${componentName}(\\s(?:[^>"']|"[^"]*"|'[^']*')*?)?\\s*\\/\\s*>`, 'g');
|
|
156
157
|
// Replace with regular opening and closing tags
|
|
157
158
|
processedHtml = processedHtml.replace(selfClosingRegex, (match, attributes) => {
|
|
158
159
|
const attrs = attributes || '';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"parseHtml.js","sourceRoot":"","sources":["../../src/compile/parseHtml.ts"],"names":[],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AI,CAAC,CAAC;IAE5C,sCAAsC;IACtC,MAAM,QAAQ,GAAG,cAAc,CAAC,UAAU,EAAE,OAAO,CAAC,CAAC;IAErD,8CAA8C;IAC9C,QAAQ,CAAC,gBAAgB,EAAE,CAAC,GAAG,CAAC,CAAC,OAAO,CAAC,EAAE,CAAC,EAAE;QAC5C,EAAE,CAAC,YAAY,CAAC,cAAc,OAAO,EAAE,EAAE,EAAE,CAAC,CAAC;IAC/C,CAAC,CAAC,CAAC;IAEH,OAAO;QACL,QAAQ;QACR,UAAU;KACX,CAAC;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,MAAM,gBAAgB,GAAG,IAAI,MAAM,CACjC,IAAI,aAAa,yBAAyB,EAC1C,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 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,CA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AI,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 +1 @@
|
|
|
1
|
-
{"version":3,"file":"applyComponent.d.ts","sourceRoot":"","sources":["../../../src/runtime/bindings/applyComponent.ts"],"names":[],"mappings":"AAkBA,OAAO,KAAK,EAAE,QAAQ,EAAE,cAAc,EAAgB,MAAM,SAAS,CAAC;AAyItE,wBAAgB,cAAc,CAC5B,CAAC,EAAE,QAAQ,EACX,EAAE,EAAE,OAAO,EACX,GAAG,EAAE,cAAc,EACnB,SAAS,EAAE,CAAC,MAAM,IAAI,CAAC,EAAE,EACzB,MAAM,EAAE,GAAG,CAAC,MAAM,EAAE,OAAO,CAAC,EAC5B,KAAK,CAAC,EAAE,cAAc,GACrB,IAAI,EAAE,GAAG,SAAS,
|
|
1
|
+
{"version":3,"file":"applyComponent.d.ts","sourceRoot":"","sources":["../../../src/runtime/bindings/applyComponent.ts"],"names":[],"mappings":"AAkBA,OAAO,KAAK,EAAE,QAAQ,EAAE,cAAc,EAAgB,MAAM,SAAS,CAAC;AAyItE,wBAAgB,cAAc,CAC5B,CAAC,EAAE,QAAQ,EACX,EAAE,EAAE,OAAO,EACX,GAAG,EAAE,cAAc,EACnB,SAAS,EAAE,CAAC,MAAM,IAAI,CAAC,EAAE,EACzB,MAAM,EAAE,GAAG,CAAC,MAAM,EAAE,OAAO,CAAC,EAC5B,KAAK,CAAC,EAAE,cAAc,GACrB,IAAI,EAAE,GAAG,SAAS,CA6QpB"}
|
|
@@ -13,7 +13,7 @@ import { clearSSRRenderCrash, reportComponentFailure, } from '../../compile/ssrC
|
|
|
13
13
|
import { isolateDestroyCallbacks } from '../onDestroy.js';
|
|
14
14
|
import { parsePropNames } from '../../compile/binds/propNames.js';
|
|
15
15
|
import { watchStaleRowProp } from '../../compile/binds/staleRowProps.js';
|
|
16
|
-
import { nodeExpando } from '../../compile/nodeExpando.js';
|
|
16
|
+
import { markForwardTarget, nodeExpando } from '../../compile/nodeExpando.js';
|
|
17
17
|
import { anchorDisposer, componentDisposer } from '../../compile/disposeOrder.js';
|
|
18
18
|
/** Map kebab-case or lowered DOM attr name to expected camelCase prop name. */
|
|
19
19
|
function normalizePropName(authored, expectedProps) {
|
|
@@ -272,7 +272,7 @@ export function applyComponent(d, el, ctx, disposers, pidMap, scope) {
|
|
|
272
272
|
const forwardedAttrs = collectForwardedAttrs(el);
|
|
273
273
|
const renderedRoot = renderedEl instanceof DocumentFragment
|
|
274
274
|
? renderedEl.firstElementChild
|
|
275
|
-
: renderedEl instanceof
|
|
275
|
+
: renderedEl instanceof Element
|
|
276
276
|
? renderedEl
|
|
277
277
|
: null;
|
|
278
278
|
const nodes = renderedEl instanceof DocumentFragment
|
|
@@ -311,6 +311,7 @@ export function applyComponent(d, el, ctx, disposers, pidMap, scope) {
|
|
|
311
311
|
// forwarded from the placeholder to the rendered root.
|
|
312
312
|
if (renderedRoot) {
|
|
313
313
|
pidMap.set(d.pid, renderedRoot);
|
|
314
|
+
markForwardTarget(renderedRoot, localCtx, new Set(forwardedAttrs.map(([name]) => name)));
|
|
314
315
|
}
|
|
315
316
|
else {
|
|
316
317
|
if (import.meta.env?.DEV &&
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"applyComponent.js","sourceRoot":"","sources":["../../../src/runtime/bindings/applyComponent.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,iCAAiC,CAAC;AACpE,OAAO,EACL,kBAAkB,EAClB,aAAa,EACb,eAAe,EACf,gBAAgB,EAChB,iBAAiB,GAClB,MAAM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MAAM,GAAG,CAAC,CAAC,CAAC,EAC/C,CAAC;YACD,OAAO,CAAC,IAAI,CACV,UAAU,CAAC,CAAC,GAAG,qGAAqG,CACrH,CAAC;QACJ,CAAC;QACD,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;IACvB,CAAC;IAED,IAAI,QAAQ;QAAE,KAAK,MAAM,KAAK,IAAI,aAAa;YAAE,KAAK,EAAE,CAAC;IAEzD,MAAM,QAAQ,GAAG,iBAAiB,CAChC,OAAO,EACP,YAAY,EACZ,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,CACnC,CAAC;IACF,IAAI,QAAQ;QAAE,SAAS,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;IACvC,OAAO,QAAQ,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,SAAS,CAAC;AACtC,CAAC","sourcesContent":["import { compileExpression } from '../../compile/compileExpression';\nimport {\n boundaryForElement,\n replaceHidden,\n runWithBoundary,\n withSlotBoundary,\n slotContentHidden,\n} from '../../compile/binds/bindErrorBoundary';\nimport {\n linkOuterSlotMap,\n type SlotMap,\n} from '../../compile/contentProjection';\nimport {\n collectForwardedAttrs,\n applyForwardedAttrs,\n} from '../../compile/binds/forwardedAttrs';\nimport { nativeTags } from '@pithyjs/compiler';\nimport { createRoot, untrack } from '@pithyjs/signals';\nimport type { CompDesc, BindingContext, ChildFactory } from './types';\nimport { nearestCtx } from './helpers';\nimport { trimBlankEdges } from '../../compile/trimBlankEdges';\nimport { pithyGlobals } from '../../types/globals';\nimport { isSSRMode } from '../../compile/ssrMode';\nimport { isRenderableComponentEl } from '../../compile/componentResult';\nimport {\n clearSSRRenderCrash,\n reportComponentFailure,\n} from '../../compile/ssrCrashes';\nimport { isolateDestroyCallbacks } from '../onDestroy';\nimport { parsePropNames } from '../../compile/binds/propNames';\nimport { watchStaleRowProp } from '../../compile/binds/staleRowProps';\nimport { nodeExpando } from '../../compile/nodeExpando';\nimport { anchorDisposer, componentDisposer } from '../../compile/disposeOrder';\n\ninterface ComponentResult {\n /** Any DOM node — see the `Component` type for why this is not narrower. */\n el: Node;\n destroy?: () => void;\n}\ntype ComponentFn = (props: Record<string, unknown>) => ComponentResult;\n\n/** Map kebab-case or lowered DOM attr name to expected camelCase prop name. */\nfunction normalizePropName(authored: string, expectedProps: string[]): string {\n if (expectedProps.includes(authored)) return authored;\n const lower = authored.toLowerCase();\n const matches = expectedProps.filter(p => p.toLowerCase() === lower);\n return matches.length === 1 ? matches[0] : authored;\n}\n\n/** Cache for extractExpectedPropNames to avoid re-parsing the same function. */\nconst propNamesCache = new WeakMap<ComponentFn, string[]>();\n\n/**\n * Extract destructured prop names from component function signature.\n * NOTE: Uses fn.toString() which may return mangled names under aggressive\n * minification (Terser). In that case, prop name normalization becomes a\n * no-op and props are passed as-is (kebab/lowered). This is acceptable\n * because Vite's default esbuild minifier preserves parameter names.\n */\nfunction extractExpectedPropNames(fn: ComponentFn): string[] {\n const cached = propNamesCache.get(fn);\n if (cached) return cached;\n try {\n const parsed = parsePropNames(fn.toString());\n const names = parsed.fromParam ? parsed.names : [];\n // Detect likely minification: single-char names suggest mangled output\n if (\n import.meta.env?.DEV &&\n names.length > 0 &&\n names.every(n => n.length === 1)\n ) {\n console.warn(\n `[AOT] extractExpectedPropNames: detected single-char names (${names.join(',')}) — prop normalization may not work under minification`\n );\n }\n propNamesCache.set(fn, names);\n return names;\n } catch {\n return [];\n }\n}\n\n/** Runs a slot factory against the parent's context, owned by the mount's disposers. */\nfunction renderSlot(\n factory: ChildFactory,\n ctx: BindingContext,\n disposers: (() => void)[],\n anchor?: Node,\n host?: Element\n): DocumentFragment {\n const g = pithyGlobals();\n const rendering = g.__pithyComponentContext;\n // Otherwise mergeContexts would read the child's names into the slot's context.\n g.__pithyComponentContext = undefined;\n try {\n const { el, destroy } = withSlotBoundary(anchor, host, () =>\n isolateDestroyCallbacks(() => factory(ctx))\n );\n disposers.push(anchorDisposer(destroy, anchor ?? el.firstChild));\n // Bound already: a runtime-compiled child's binders must not bind it again.\n el.childNodes.forEach(\n node => (nodeExpando(node).__pithyComponentDom = true)\n );\n return el;\n } finally {\n g.__pithyComponentContext = rendering;\n }\n}\n\n/**\n * Slot content serialized into the placeholder, from a descriptor without\n * `slots`. The nodes are moved, so each slot can be mounted only once.\n */\nfunction slotsFromChildren(\n el: Element,\n slotMap: SlotMap\n): DocumentFragment | undefined {\n const slotGroups = new Map<string, Node[]>();\n for (const child of Array.from(el.childNodes)) {\n const slotName =\n child.nodeType === Node.ELEMENT_NODE\n ? (child as Element).getAttribute('slot') || ''\n : '';\n const group = slotGroups.get(slotName);\n if (group) group.push(child);\n else slotGroups.set(slotName, [child]);\n }\n const defaultSlot = slotGroups.get('');\n if (defaultSlot) {\n const content = trimBlankEdges(defaultSlot, node =>\n node.nodeType === Node.TEXT_NODE ? node.textContent : null\n );\n if (content.length) slotGroups.set('', content);\n else slotGroups.delete('');\n }\n // `renderChildren()` and `<slot>` must share one fragment, or the later\n // consumer steals the nodes out of the first.\n let injection: DocumentFragment | undefined;\n for (const [slotName, nodes] of slotGroups) {\n if (slotName === '') {\n injection = document.createDocumentFragment();\n for (const node of nodes) injection.appendChild(node);\n const shared = injection;\n slotMap.set('', () => shared);\n continue;\n }\n slotMap.set(slotName, () => {\n const frag = document.createDocumentFragment();\n for (const node of nodes) frag.appendChild(node);\n return frag;\n });\n }\n return injection;\n}\n\nexport function applyComponent(\n d: CompDesc,\n el: Element,\n ctx: BindingContext,\n disposers: (() => void)[],\n pidMap: Map<string, Element>,\n scope?: BindingContext\n): Node[] | undefined {\n // Skip native HTML elements — prevents <div> matching a `div` in context.\n // Only apply when the authored tag is already lowercase; PascalCase tags like\n // <Button> are valid components even though \"button\" is a native tag.\n const tagLower = d.tag.toLowerCase();\n if (d.tag === tagLower && nativeTags.has(tagLower)) return;\n\n // Exact case first: the context holds the template's own locals alongside its\n // components, so a prop named `icon` sits next to the `Icon` component and\n // collides case-insensitively. The JIT path lowercases into a Map, where the\n // components — appended last — overwrite the locals; matching that ordering is\n // why `<Icon>` resolves in dev, and breaking on the first match is why it did\n // not in a build. Falling back last-wins keeps the two paths agreeing.\n let candidate: unknown = Object.prototype.hasOwnProperty.call(ctx, d.tag)\n ? ctx[d.tag]\n : undefined;\n if (candidate === undefined) {\n for (const key of Object.keys(ctx)) {\n if (key.toLowerCase() === tagLower) candidate = ctx[key];\n }\n }\n if (!candidate) return;\n\n // Support default exports\n if (\n candidate &&\n typeof candidate === 'object' &&\n 'default' in candidate &&\n typeof candidate.default === 'function'\n ) {\n candidate = candidate.default;\n }\n if (typeof candidate !== 'function') return;\n // Hidden like a sibling an activated boundary detached: never rendered.\n if (slotContentHidden(el)) return;\n\n const componentFn = candidate as ComponentFn;\n const localCtx = scope ?? nearestCtx(el, ctx);\n\n // Extract expected props for case-insensitive normalization\n const expectedProps = extractExpectedPropNames(componentFn);\n\n // Evaluate prop expressions with prop name normalization\n const props: Record<string, unknown> = {};\n const staleWatchers: (() => void)[] = [];\n for (const [rawName, expr] of Object.entries(d.props)) {\n const propName = normalizePropName(rawName, expectedProps);\n try {\n const fn = compileExpression(expr, localCtx);\n props[propName] = untrack(fn);\n if (import.meta.env?.DEV) {\n const value = props[propName];\n staleWatchers.push(() =>\n watchStaleRowProp(\n localCtx,\n d,\n d.tag,\n propName,\n expr,\n value,\n fn,\n disposers\n )\n );\n }\n } catch {\n // Leave undefined — child uses defaults\n }\n }\n\n const slotMap: SlotMap = new Map();\n linkOuterSlotMap(slotMap, localCtx);\n let injection: DocumentFragment | undefined;\n if (d.slots) {\n for (const [name, factory] of Object.entries(d.slots))\n slotMap.set(name, (ds = disposers, at) =>\n renderSlot(factory, localCtx, ds, at, el)\n );\n } else {\n injection = slotsFromChildren(el, slotMap);\n }\n\n let invoking = true;\n const childrenFactory = d.children;\n const childFactory: ChildFactory | undefined = childrenFactory\n ? (ctx, wrap) =>\n invoking\n ? childrenFactory(ctx, wrap)\n : isolateDestroyCallbacks(() => childrenFactory(ctx, wrap))\n : undefined;\n\n const componentContext = {\n ...localCtx,\n __slotMap: slotMap,\n __childAstNodes: undefined,\n __childFactory: childFactory,\n __slotHost: el,\n };\n\n // Find nearest error boundary\n const boundaryEl = el.closest('[data-error]') as Element | null;\n const boundary = boundaryForElement(boundaryEl);\n\n let out: ComponentResult | undefined;\n let disposeSetup: (() => void) | undefined;\n try {\n out = runWithBoundary(boundary, () => {\n const g = pithyGlobals();\n const originalContext = g.__pithyComponentContext;\n const wasRendering = g.__pithyRenderingComponent;\n const prevInjection = g.__pithyProjectedChildren;\n g.__pithyComponentContext = componentContext;\n g.__pithyRenderingComponent = true;\n g.__pithyProjectedChildren = injection;\n try {\n return createRoot(disposeRoot => {\n disposeSetup = disposeRoot;\n return componentFn(props);\n });\n } finally {\n g.__pithyComponentContext = originalContext;\n g.__pithyRenderingComponent = wasRendering;\n g.__pithyProjectedChildren = prevInjection;\n invoking = false;\n }\n });\n } catch (err) {\n if (boundary) {\n const error = err instanceof Error ? err : new Error(String(err));\n // See `setBoundaryError`: an already-active boundary with no free ancestor\n // drops the error rather than taking it, which is the normal case for a\n // component rendering inside that boundary's `@fallback`.\n reportComponentFailure(el, d.tag, error, boundary);\n return;\n }\n\n // No boundary in scope *yet*. Degrade in both modes — an AOT branch\n // factory renders detached, so `closest()` here cannot see a boundary the\n // element will sit under once the branch is inserted, and throwing would\n // only be swallowed by the structural handler's own catch\n // (`applyStructural.ts`) anyway.\n //\n // A static/server render records the crash instead: dropping the component\n // silently shipped HTML with <${d.tag}> left raw while `pithy-ssg` counted\n // the route as rendered and exited 0 (BUG-018). Anything still recorded\n // when the render finishes fails the route.\n //\n // Note this path cannot reach a boundary at all when the element is inside\n // a detached structural branch: `el.closest('[data-error]')` above found\n // nothing, and no later pass re-binds it, so the boundary never receives\n // the error even though the nodes are inserted underneath it. That is\n // BUG-023; recording is what stops it from shipping silently.\n reportComponentFailure(\n el,\n d.tag,\n err instanceof Error ? err : new Error(String(err)),\n null\n );\n\n console.error(`[AOT] Component <${d.tag}> crashed:`, err);\n return;\n }\n\n if (\n !out ||\n typeof out !== 'object' ||\n !('el' in out) ||\n !isRenderableComponentEl(out.el, el)\n ) {\n // Not a throw, but the same outcome: the raw <${d.tag}> is left in place\n // and the subtree never renders, which under SSR is content silently\n // missing from the emitted HTML. Recorded exactly like a crash (BUG-018).\n // Same funnel as a throw — see `bindComponentTags`. Recording without\n // offering it to the boundary left an AOT component under `@error-boundary`\n // failing its route with the boundary signal unset.\n reportComponentFailure(\n el,\n d.tag,\n new Error(\n `Invalid render result from <${d.tag}>; expected { el, destroy }`\n ),\n boundary\n );\n disposeSetup?.();\n return;\n }\n\n const { el: renderedEl, destroy } = out;\n\n // Capture rendered root element before fragment is consumed by replaceWith\n const forwardedClass = el.getAttribute('class');\n const forwardedAttrs = collectForwardedAttrs(el);\n const renderedRoot: HTMLElement | null =\n renderedEl instanceof DocumentFragment\n ? (renderedEl.firstElementChild as HTMLElement | null)\n : renderedEl instanceof HTMLElement\n ? renderedEl\n : null;\n\n const nodes =\n renderedEl instanceof DocumentFragment\n ? Array.from(renderedEl.childNodes)\n : [renderedEl];\n let replaced = true;\n try {\n // A boundary that caught a crash in this render may have hidden `el`.\n if (!replaceHidden(el, nodes)) el.replaceWith(...nodes);\n } catch (err) {\n // The raw <${d.tag}> is left exactly where a crash would have left it, so\n // this is the same content loss and is recorded the same way.\n replaced = false;\n reportComponentFailure(\n el,\n d.tag,\n err instanceof Error ? err : new Error(String(err)),\n boundary\n );\n console.error(`[AOT] Failed to replace <${d.tag}>:`, err);\n }\n\n // Retracted only here, and in the boundary catch above. This is the point at\n // which the component is known to have produced a usable node AND to have\n // reached the document.\n if (isSSRMode() && replaced) clearSSRRenderCrash(el);\n\n if (forwardedClass && renderedRoot) {\n for (const cls of forwardedClass.split(/\\s+/)) {\n if (cls) renderedRoot.classList.add(cls);\n }\n }\n\n if (forwardedAttrs.length > 0 && renderedRoot) {\n applyForwardedAttrs(renderedRoot, forwardedAttrs, d.tag);\n }\n\n // Re-target the component pid to the rendered root so subsequent binding\n // passes (event, bound, class, style) apply to the component's actual DOM\n // element. This matches the JIT path where data-on-* attributes are\n // forwarded from the placeholder to the rendered root.\n if (renderedRoot) {\n pidMap.set(d.pid, renderedRoot);\n } else {\n if (\n import.meta.env?.DEV &&\n (forwardedClass ||\n forwardedAttrs.length > 0 ||\n (d.props && Object.keys(d.props).length > 0))\n ) {\n console.warn(\n `[AOT] <${d.tag}> has forwarded attributes but returns a fragment with no single root element — forwarding skipped.`\n );\n }\n pidMap.delete(d.pid);\n }\n\n if (replaced) for (const watch of staleWatchers) watch();\n\n const teardown = componentDisposer(\n destroy,\n disposeSetup,\n nodes[0] ?? (replaced ? null : el)\n );\n if (teardown) disposers.push(teardown);\n return replaced ? nodes : undefined;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"applyComponent.js","sourceRoot":"","sources":["../../../src/runtime/bindings/applyComponent.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,iCAAiC,CAAC;AACpE,OAAO,EACL,kBAAkB,EAClB,aAAa,EACb,eAAe,EACf,gBAAgB,EAChB,iBAAiB,GAClB,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EACL,gBAAgB,GAEjB,MAAM,iCAAiC,CAAC;AACzC,OAAO,EACL,qBAAqB,EACrB,mBAAmB,GACpB,MAAM,oCAAoC,CAAC;AAC5C,OAAO,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAC/C,OAAO,EAAE,UAAU,EAAE,OAAO,EAAE,MAAM,kBAAkB,CAAC;AAEvD,OAAO,EAAE,UAAU,EAAE,MAAM,WAAW,CAAC;AACvC,OAAO,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AAC9D,OAAO,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AACnD,OAAO,EAAE,SAAS,EAAE,MAAM,u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,EAAE,CAAC;IAEzD,MAAM,QAAQ,GAAG,iBAAiB,CAChC,OAAO,EACP,YAAY,EACZ,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,CACnC,CAAC;IACF,IAAI,QAAQ;QAAE,SAAS,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;IACvC,OAAO,QAAQ,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,SAAS,CAAC;AACtC,CAAC","sourcesContent":["import { compileExpression } from '../../compile/compileExpression';\nimport {\n boundaryForElement,\n replaceHidden,\n runWithBoundary,\n withSlotBoundary,\n slotContentHidden,\n} from '../../compile/binds/bindErrorBoundary';\nimport {\n linkOuterSlotMap,\n type SlotMap,\n} from '../../compile/contentProjection';\nimport {\n collectForwardedAttrs,\n applyForwardedAttrs,\n} from '../../compile/binds/forwardedAttrs';\nimport { nativeTags } from '@pithyjs/compiler';\nimport { createRoot, untrack } from '@pithyjs/signals';\nimport type { CompDesc, BindingContext, ChildFactory } from './types';\nimport { nearestCtx } from './helpers';\nimport { trimBlankEdges } from '../../compile/trimBlankEdges';\nimport { pithyGlobals } from '../../types/globals';\nimport { isSSRMode } from '../../compile/ssrMode';\nimport { isRenderableComponentEl } from '../../compile/componentResult';\nimport {\n clearSSRRenderCrash,\n reportComponentFailure,\n} from '../../compile/ssrCrashes';\nimport { isolateDestroyCallbacks } from '../onDestroy';\nimport { parsePropNames } from '../../compile/binds/propNames';\nimport { watchStaleRowProp } from '../../compile/binds/staleRowProps';\nimport { markForwardTarget, nodeExpando } from '../../compile/nodeExpando';\nimport { anchorDisposer, componentDisposer } from '../../compile/disposeOrder';\n\ninterface ComponentResult {\n /** Any DOM node — see the `Component` type for why this is not narrower. */\n el: Node;\n destroy?: () => void;\n}\ntype ComponentFn = (props: Record<string, unknown>) => ComponentResult;\n\n/** Map kebab-case or lowered DOM attr name to expected camelCase prop name. */\nfunction normalizePropName(authored: string, expectedProps: string[]): string {\n if (expectedProps.includes(authored)) return authored;\n const lower = authored.toLowerCase();\n const matches = expectedProps.filter(p => p.toLowerCase() === lower);\n return matches.length === 1 ? matches[0] : authored;\n}\n\n/** Cache for extractExpectedPropNames to avoid re-parsing the same function. */\nconst propNamesCache = new WeakMap<ComponentFn, string[]>();\n\n/**\n * Extract destructured prop names from component function signature.\n * NOTE: Uses fn.toString() which may return mangled names under aggressive\n * minification (Terser). In that case, prop name normalization becomes a\n * no-op and props are passed as-is (kebab/lowered). This is acceptable\n * because Vite's default esbuild minifier preserves parameter names.\n */\nfunction extractExpectedPropNames(fn: ComponentFn): string[] {\n const cached = propNamesCache.get(fn);\n if (cached) return cached;\n try {\n const parsed = parsePropNames(fn.toString());\n const names = parsed.fromParam ? parsed.names : [];\n // Detect likely minification: single-char names suggest mangled output\n if (\n import.meta.env?.DEV &&\n names.length > 0 &&\n names.every(n => n.length === 1)\n ) {\n console.warn(\n `[AOT] extractExpectedPropNames: detected single-char names (${names.join(',')}) — prop normalization may not work under minification`\n );\n }\n propNamesCache.set(fn, names);\n return names;\n } catch {\n return [];\n }\n}\n\n/** Runs a slot factory against the parent's context, owned by the mount's disposers. */\nfunction renderSlot(\n factory: ChildFactory,\n ctx: BindingContext,\n disposers: (() => void)[],\n anchor?: Node,\n host?: Element\n): DocumentFragment {\n const g = pithyGlobals();\n const rendering = g.__pithyComponentContext;\n // Otherwise mergeContexts would read the child's names into the slot's context.\n g.__pithyComponentContext = undefined;\n try {\n const { el, destroy } = withSlotBoundary(anchor, host, () =>\n isolateDestroyCallbacks(() => factory(ctx))\n );\n disposers.push(anchorDisposer(destroy, anchor ?? el.firstChild));\n // Bound already: a runtime-compiled child's binders must not bind it again.\n el.childNodes.forEach(\n node => (nodeExpando(node).__pithyComponentDom = true)\n );\n return el;\n } finally {\n g.__pithyComponentContext = rendering;\n }\n}\n\n/**\n * Slot content serialized into the placeholder, from a descriptor without\n * `slots`. The nodes are moved, so each slot can be mounted only once.\n */\nfunction slotsFromChildren(\n el: Element,\n slotMap: SlotMap\n): DocumentFragment | undefined {\n const slotGroups = new Map<string, Node[]>();\n for (const child of Array.from(el.childNodes)) {\n const slotName =\n child.nodeType === Node.ELEMENT_NODE\n ? (child as Element).getAttribute('slot') || ''\n : '';\n const group = slotGroups.get(slotName);\n if (group) group.push(child);\n else slotGroups.set(slotName, [child]);\n }\n const defaultSlot = slotGroups.get('');\n if (defaultSlot) {\n const content = trimBlankEdges(defaultSlot, node =>\n node.nodeType === Node.TEXT_NODE ? node.textContent : null\n );\n if (content.length) slotGroups.set('', content);\n else slotGroups.delete('');\n }\n // `renderChildren()` and `<slot>` must share one fragment, or the later\n // consumer steals the nodes out of the first.\n let injection: DocumentFragment | undefined;\n for (const [slotName, nodes] of slotGroups) {\n if (slotName === '') {\n injection = document.createDocumentFragment();\n for (const node of nodes) injection.appendChild(node);\n const shared = injection;\n slotMap.set('', () => shared);\n continue;\n }\n slotMap.set(slotName, () => {\n const frag = document.createDocumentFragment();\n for (const node of nodes) frag.appendChild(node);\n return frag;\n });\n }\n return injection;\n}\n\nexport function applyComponent(\n d: CompDesc,\n el: Element,\n ctx: BindingContext,\n disposers: (() => void)[],\n pidMap: Map<string, Element>,\n scope?: BindingContext\n): Node[] | undefined {\n // Skip native HTML elements — prevents <div> matching a `div` in context.\n // Only apply when the authored tag is already lowercase; PascalCase tags like\n // <Button> are valid components even though \"button\" is a native tag.\n const tagLower = d.tag.toLowerCase();\n if (d.tag === tagLower && nativeTags.has(tagLower)) return;\n\n // Exact case first: the context holds the template's own locals alongside its\n // components, so a prop named `icon` sits next to the `Icon` component and\n // collides case-insensitively. The JIT path lowercases into a Map, where the\n // components — appended last — overwrite the locals; matching that ordering is\n // why `<Icon>` resolves in dev, and breaking on the first match is why it did\n // not in a build. Falling back last-wins keeps the two paths agreeing.\n let candidate: unknown = Object.prototype.hasOwnProperty.call(ctx, d.tag)\n ? ctx[d.tag]\n : undefined;\n if (candidate === undefined) {\n for (const key of Object.keys(ctx)) {\n if (key.toLowerCase() === tagLower) candidate = ctx[key];\n }\n }\n if (!candidate) return;\n\n // Support default exports\n if (\n candidate &&\n typeof candidate === 'object' &&\n 'default' in candidate &&\n typeof candidate.default === 'function'\n ) {\n candidate = candidate.default;\n }\n if (typeof candidate !== 'function') return;\n // Hidden like a sibling an activated boundary detached: never rendered.\n if (slotContentHidden(el)) return;\n\n const componentFn = candidate as ComponentFn;\n const localCtx = scope ?? nearestCtx(el, ctx);\n\n // Extract expected props for case-insensitive normalization\n const expectedProps = extractExpectedPropNames(componentFn);\n\n // Evaluate prop expressions with prop name normalization\n const props: Record<string, unknown> = {};\n const staleWatchers: (() => void)[] = [];\n for (const [rawName, expr] of Object.entries(d.props)) {\n const propName = normalizePropName(rawName, expectedProps);\n try {\n const fn = compileExpression(expr, localCtx);\n props[propName] = untrack(fn);\n if (import.meta.env?.DEV) {\n const value = props[propName];\n staleWatchers.push(() =>\n watchStaleRowProp(\n localCtx,\n d,\n d.tag,\n propName,\n expr,\n value,\n fn,\n disposers\n )\n );\n }\n } catch {\n // Leave undefined — child uses defaults\n }\n }\n\n const slotMap: SlotMap = new Map();\n linkOuterSlotMap(slotMap, localCtx);\n let injection: DocumentFragment | undefined;\n if (d.slots) {\n for (const [name, factory] of Object.entries(d.slots))\n slotMap.set(name, (ds = disposers, at) =>\n renderSlot(factory, localCtx, ds, at, el)\n );\n } else {\n injection = slotsFromChildren(el, slotMap);\n }\n\n let invoking = true;\n const childrenFactory = d.children;\n const childFactory: ChildFactory | undefined = childrenFactory\n ? (ctx, wrap) =>\n invoking\n ? childrenFactory(ctx, wrap)\n : isolateDestroyCallbacks(() => childrenFactory(ctx, wrap))\n : undefined;\n\n const componentContext = {\n ...localCtx,\n __slotMap: slotMap,\n __childAstNodes: undefined,\n __childFactory: childFactory,\n __slotHost: el,\n };\n\n // Find nearest error boundary\n const boundaryEl = el.closest('[data-error]') as Element | null;\n const boundary = boundaryForElement(boundaryEl);\n\n let out: ComponentResult | undefined;\n let disposeSetup: (() => void) | undefined;\n try {\n out = runWithBoundary(boundary, () => {\n const g = pithyGlobals();\n const originalContext = g.__pithyComponentContext;\n const wasRendering = g.__pithyRenderingComponent;\n const prevInjection = g.__pithyProjectedChildren;\n g.__pithyComponentContext = componentContext;\n g.__pithyRenderingComponent = true;\n g.__pithyProjectedChildren = injection;\n try {\n return createRoot(disposeRoot => {\n disposeSetup = disposeRoot;\n return componentFn(props);\n });\n } finally {\n g.__pithyComponentContext = originalContext;\n g.__pithyRenderingComponent = wasRendering;\n g.__pithyProjectedChildren = prevInjection;\n invoking = false;\n }\n });\n } catch (err) {\n if (boundary) {\n const error = err instanceof Error ? err : new Error(String(err));\n // See `setBoundaryError`: an already-active boundary with no free ancestor\n // drops the error rather than taking it, which is the normal case for a\n // component rendering inside that boundary's `@fallback`.\n reportComponentFailure(el, d.tag, error, boundary);\n return;\n }\n\n // No boundary in scope *yet*. Degrade in both modes — an AOT branch\n // factory renders detached, so `closest()` here cannot see a boundary the\n // element will sit under once the branch is inserted, and throwing would\n // only be swallowed by the structural handler's own catch\n // (`applyStructural.ts`) anyway.\n //\n // A static/server render records the crash instead: dropping the component\n // silently shipped HTML with <${d.tag}> left raw while `pithy-ssg` counted\n // the route as rendered and exited 0 (BUG-018). Anything still recorded\n // when the render finishes fails the route.\n //\n // Note this path cannot reach a boundary at all when the element is inside\n // a detached structural branch: `el.closest('[data-error]')` above found\n // nothing, and no later pass re-binds it, so the boundary never receives\n // the error even though the nodes are inserted underneath it. That is\n // BUG-023; recording is what stops it from shipping silently.\n reportComponentFailure(\n el,\n d.tag,\n err instanceof Error ? err : new Error(String(err)),\n null\n );\n\n console.error(`[AOT] Component <${d.tag}> crashed:`, err);\n return;\n }\n\n if (\n !out ||\n typeof out !== 'object' ||\n !('el' in out) ||\n !isRenderableComponentEl(out.el, el)\n ) {\n // Not a throw, but the same outcome: the raw <${d.tag}> is left in place\n // and the subtree never renders, which under SSR is content silently\n // missing from the emitted HTML. Recorded exactly like a crash (BUG-018).\n // Same funnel as a throw — see `bindComponentTags`. Recording without\n // offering it to the boundary left an AOT component under `@error-boundary`\n // failing its route with the boundary signal unset.\n reportComponentFailure(\n el,\n d.tag,\n new Error(\n `Invalid render result from <${d.tag}>; expected { el, destroy }`\n ),\n boundary\n );\n disposeSetup?.();\n return;\n }\n\n const { el: renderedEl, destroy } = out;\n\n // Capture rendered root element before fragment is consumed by replaceWith\n const forwardedClass = el.getAttribute('class');\n const forwardedAttrs = collectForwardedAttrs(el);\n const renderedRoot: Element | null =\n renderedEl instanceof DocumentFragment\n ? renderedEl.firstElementChild\n : renderedEl instanceof Element\n ? renderedEl\n : null;\n\n const nodes =\n renderedEl instanceof DocumentFragment\n ? Array.from(renderedEl.childNodes)\n : [renderedEl];\n let replaced = true;\n try {\n // A boundary that caught a crash in this render may have hidden `el`.\n if (!replaceHidden(el, nodes)) el.replaceWith(...nodes);\n } catch (err) {\n // The raw <${d.tag}> is left exactly where a crash would have left it, so\n // this is the same content loss and is recorded the same way.\n replaced = false;\n reportComponentFailure(\n el,\n d.tag,\n err instanceof Error ? err : new Error(String(err)),\n boundary\n );\n console.error(`[AOT] Failed to replace <${d.tag}>:`, err);\n }\n\n // Retracted only here, and in the boundary catch above. This is the point at\n // which the component is known to have produced a usable node AND to have\n // reached the document.\n if (isSSRMode() && replaced) clearSSRRenderCrash(el);\n\n if (forwardedClass && renderedRoot) {\n for (const cls of forwardedClass.split(/\\s+/)) {\n if (cls) renderedRoot.classList.add(cls);\n }\n }\n\n if (forwardedAttrs.length > 0 && renderedRoot) {\n applyForwardedAttrs(renderedRoot, forwardedAttrs, d.tag);\n }\n\n // Re-target the component pid to the rendered root so subsequent binding\n // passes (event, bound, class, style) apply to the component's actual DOM\n // element. This matches the JIT path where data-on-* attributes are\n // forwarded from the placeholder to the rendered root.\n if (renderedRoot) {\n pidMap.set(d.pid, renderedRoot);\n markForwardTarget(\n renderedRoot,\n localCtx,\n new Set(forwardedAttrs.map(([name]) => name))\n );\n } else {\n if (\n import.meta.env?.DEV &&\n (forwardedClass ||\n forwardedAttrs.length > 0 ||\n (d.props && Object.keys(d.props).length > 0))\n ) {\n console.warn(\n `[AOT] <${d.tag}> has forwarded attributes but returns a fragment with no single root element — forwarding skipped.`\n );\n }\n pidMap.delete(d.pid);\n }\n\n if (replaced) for (const watch of staleWatchers) watch();\n\n const teardown = componentDisposer(\n destroy,\n disposeSetup,\n nodes[0] ?? (replaced ? null : el)\n );\n if (teardown) disposers.push(teardown);\n return replaced ? nodes : undefined;\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"applySimple.d.ts","sourceRoot":"","sources":["../../../src/runtime/bindings/applySimple.ts"],"names":[],"mappings":"AAmBA,OAAO,KAAK,EACV,OAAO,EACP,SAAS,EACT,QAAQ,EACR,QAAQ,EACR,UAAU,EACV,SAAS,EACT,SAAS,EACT,WAAW,EACX,SAAS,EACT,SAAS,EACT,cAAc,EACf,MAAM,SAAS,CAAC;AAKjB,wBAAgB,QAAQ,CACtB,CAAC,EAAE,OAAO,EACV,EAAE,EAAE,OAAO,EACX,GAAG,EAAE,cAAc,EACnB,SAAS,EAAE,CAAC,MAAM,IAAI,CAAC,EAAE,GACxB,IAAI,CAQN;AAED,wBAAgB,UAAU,CACxB,CAAC,EAAE,SAAS,EACZ,EAAE,EAAE,OAAO,EACX,GAAG,EAAE,cAAc,EACnB,SAAS,EAAE,CAAC,MAAM,IAAI,CAAC,EAAE,GACxB,IAAI,CAYN;AAED,wBAAgB,eAAe,CAC7B,CAAC,EAAE,QAAQ,EACX,UAAU,EAAE,GAAG,CAAC,MAAM,EAAE,OAAO,CAAC,EAChC,GAAG,EAAE,cAAc,EACnB,SAAS,EAAE,CAAC,MAAM,IAAI,CAAC,EAAE,GACxB,IAAI,CAwEN;AAED,wBAAgB,SAAS,CACvB,CAAC,EAAE,QAAQ,EACX,EAAE,EAAE,OAAO,EACX,GAAG,EAAE,cAAc,EACnB,SAAS,EAAE,CAAC,MAAM,IAAI,CAAC,EAAE,GACxB,IAAI,CA6BN;AAoDD,qFAAqF;AACrF,wBAAgB,gBAAgB,CAAC,QAAQ,EAAE,gBAAgB,GAAG,IAAI,CAMjE;AAED,wBAAgB,kBAAkB,CAChC,CAAC,EAAE,UAAU,EACb,EAAE,EAAE,OAAO,GAAG,gBAAgB,EAC9B,GAAG,EAAE,cAAc,EACnB,SAAS,EAAE,CAAC,MAAM,IAAI,CAAC,EAAE,GACxB,IAAI,CA6EN;AAeD,wBAAgB,UAAU,CACxB,CAAC,EAAE,SAAS,EACZ,EAAE,EAAE,OAAO,EACX,GAAG,EAAE,cAAc,EACnB,SAAS,EAAE,CAAC,MAAM,IAAI,CAAC,EAAE,GACxB,IAAI,
|
|
1
|
+
{"version":3,"file":"applySimple.d.ts","sourceRoot":"","sources":["../../../src/runtime/bindings/applySimple.ts"],"names":[],"mappings":"AAmBA,OAAO,KAAK,EACV,OAAO,EACP,SAAS,EACT,QAAQ,EACR,QAAQ,EACR,UAAU,EACV,SAAS,EACT,SAAS,EACT,WAAW,EACX,SAAS,EACT,SAAS,EACT,cAAc,EACf,MAAM,SAAS,CAAC;AAKjB,wBAAgB,QAAQ,CACtB,CAAC,EAAE,OAAO,EACV,EAAE,EAAE,OAAO,EACX,GAAG,EAAE,cAAc,EACnB,SAAS,EAAE,CAAC,MAAM,IAAI,CAAC,EAAE,GACxB,IAAI,CAQN;AAED,wBAAgB,UAAU,CACxB,CAAC,EAAE,SAAS,EACZ,EAAE,EAAE,OAAO,EACX,GAAG,EAAE,cAAc,EACnB,SAAS,EAAE,CAAC,MAAM,IAAI,CAAC,EAAE,GACxB,IAAI,CAYN;AAED,wBAAgB,eAAe,CAC7B,CAAC,EAAE,QAAQ,EACX,UAAU,EAAE,GAAG,CAAC,MAAM,EAAE,OAAO,CAAC,EAChC,GAAG,EAAE,cAAc,EACnB,SAAS,EAAE,CAAC,MAAM,IAAI,CAAC,EAAE,GACxB,IAAI,CAwEN;A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@@ import { registerBoundary, boundaryForElement, setBoundaryError, withSlotBoundar
|
|
|
7
7
|
import { applyClassGroup } from '../../compile/binds/bindClassDirectives.js';
|
|
8
8
|
import { mountProjection } from '../../compile/contentProjection.js';
|
|
9
9
|
import { bindAfterProjection } from '../../compile/binds/bindAfterProjection.js';
|
|
10
|
-
import { nodeExpando } from '../../compile/nodeExpando.js';
|
|
10
|
+
import { forwardEventKey, nodeExpando } from '../../compile/nodeExpando.js';
|
|
11
11
|
import { nearestCtx, compileWithEvent } from './helpers.js';
|
|
12
12
|
// ─── Individual binding handlers ──────────────────────────────────────────────
|
|
13
13
|
export function applyRef(d, el, ctx, disposers) {
|
|
@@ -265,10 +265,13 @@ function getAotBoundSet(el, eventName) {
|
|
|
265
265
|
export function applyEvent(d, el, ctx, disposers) {
|
|
266
266
|
// Idempotency: skip if this exact event+expr combo was already bound
|
|
267
267
|
const boundSet = getAotBoundSet(el, d.event);
|
|
268
|
-
const
|
|
268
|
+
const key = `${d.event}${d.mods ? '.' + d.mods.join('.') : ''}=${d.expr}`;
|
|
269
|
+
const fwdCtx = nodeExpando(el).__pithyForwardCtx;
|
|
270
|
+
// A root is marked only after the child bound its own events.
|
|
271
|
+
const boundKey = fwdCtx ? forwardEventKey(el, key) : key;
|
|
269
272
|
if (boundSet.has(boundKey))
|
|
270
273
|
return;
|
|
271
|
-
const localCtx = nearestCtx(el, ctx);
|
|
274
|
+
const localCtx = fwdCtx ?? nearestCtx(el, ctx);
|
|
272
275
|
const mods = parseMods(d.mods);
|
|
273
276
|
const handlerExpr = d.expr;
|
|
274
277
|
const isSimpleIdentifier = /^[a-zA-Z_][a-zA-Z0-9_]*$/.test(handlerExpr);
|
|
@@ -326,7 +329,7 @@ function parseMods(mods) {
|
|
|
326
329
|
return m;
|
|
327
330
|
}
|
|
328
331
|
export function applyClass(d, el, ctx, disposers) {
|
|
329
|
-
const localCtx = nearestCtx(el, ctx);
|
|
332
|
+
const localCtx = nodeExpando(el).__pithyForwardCtx ?? nearestCtx(el, ctx);
|
|
330
333
|
try {
|
|
331
334
|
const evaluate = compileExpression(d.expr, localCtx);
|
|
332
335
|
const stop = effect(() => {
|
|
@@ -344,7 +347,7 @@ export function applyClass(d, el, ctx, disposers) {
|
|
|
344
347
|
}
|
|
345
348
|
}
|
|
346
349
|
export function applyClasses(d, el, ctx, disposers) {
|
|
347
|
-
const localCtx = nearestCtx(el, ctx);
|
|
350
|
+
const localCtx = nodeExpando(el).__pithyForwardCtx ?? nearestCtx(el, ctx);
|
|
348
351
|
try {
|
|
349
352
|
const evaluate = compileExpression(d.expr, localCtx);
|
|
350
353
|
const owned = new Set();
|
|
@@ -371,7 +374,7 @@ export function applyStyle(d, el, ctx, disposers) {
|
|
|
371
374
|
const style = el.style;
|
|
372
375
|
if (!style)
|
|
373
376
|
return;
|
|
374
|
-
const localCtx = nearestCtx(el, ctx);
|
|
377
|
+
const localCtx = nodeExpando(el).__pithyForwardCtx ?? nearestCtx(el, ctx);
|
|
375
378
|
// setProperty requires kebab-case; codegen may emit camelCase (e.g. fontSize)
|
|
376
379
|
const cssProp = d.prop.includes('-') ? d.prop : toKebabCase(d.prop);
|
|
377
380
|
try {
|
|
@@ -403,7 +406,7 @@ export function applyStyle(d, el, ctx, disposers) {
|
|
|
403
406
|
}
|
|
404
407
|
}
|
|
405
408
|
export function applyBound(d, el, ctx, disposers) {
|
|
406
|
-
const localCtx = nearestCtx(el, ctx);
|
|
409
|
+
const localCtx = nodeExpando(el).__pithyForwardCtx ?? nearestCtx(el, ctx);
|
|
407
410
|
// Compile once outside effect via compileExpression (consistent with applyClass/applyStyle).
|
|
408
411
|
try {
|
|
409
412
|
const evaluate = compileExpression(d.expr, localCtx);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"applySimple.js","sourceRoot":"","sources":["../../../src/runtime/bindings/applySimple.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AACpD,OAA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C;gBAClC,CAAC;qBAAM,CAAC;oBACN,MAAM,IAAI,GAAG,MAAM,CAAC,KAAK,IAAI,EAAE,CAAC,CAAC;oBACjC,IAAI,UAAU;wBAAE,UAAU,CAAC,IAAI,CAAC,CAAC;yBAC5B,IAAI,iBAAiB,CAAC,EAAE,EAAE,CAAC,CAAC,IAAI,EAAE,IAAI,CAAC;wBAC1C,EAAE,CAAC,eAAe,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC;;wBACxB,EAAE,CAAC,YAAY,CAAC,CAAC,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;gBACrC,CAAC;YACH,CAAC;YAAC,MAAM,CAAC;gBACP,YAAY;YACd,CAAC;QACH,CAAC,CAAC,CAAC;QACH,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IACvB,CAAC;IAAC,MAAM,CAAC;QACP,+BAA+B;IACjC,CAAC;AACH,CAAC","sourcesContent":["import { effect, isSignal } from '@pithyjs/signals';\nimport { compileExpression } from '../../compile/compileExpression';\nimport {\n rejectsScriptSink,\n setStyleProp,\n styleWriter,\n} from '../../compile/binds/bindBoundAttributes';\nimport { toTextValue } from '../../compile/textValue';\nimport { isSSRMode } from '../../compile/ssrMode';\nimport {\n registerBoundary,\n boundaryForElement,\n setBoundaryError,\n withSlotBoundary,\n} from '../../compile/binds/bindErrorBoundary';\nimport { applyClassGroup } from '../../compile/binds/bindClassDirectives';\nimport { mountProjection, type SlotMap } from '../../compile/contentProjection';\nimport { bindAfterProjection } from '../../compile/binds/bindAfterProjection';\nimport { nodeExpando } from '../../compile/nodeExpando';\nimport type {\n RefDesc,\n ErrorDesc,\n ProjDesc,\n BindDesc,\n InterpDesc,\n EventDesc,\n ClassDesc,\n ClassesDesc,\n StyleDesc,\n BoundDesc,\n BindingContext,\n} from './types';\nimport { nearestCtx, compileWithEvent } from './helpers';\n\n// ─── Individual binding handlers ──────────────────────────────────────────────\n\nexport function applyRef(\n d: RefDesc,\n el: Element,\n ctx: BindingContext,\n disposers: (() => void)[]\n): void {\n const ref = ctx[d.name] as\n | { set?: (value: Element | null) => void }\n | undefined;\n if (ref && typeof ref.set === 'function') {\n ref.set(el);\n disposers.push(() => ref.set!(null));\n }\n}\n\nexport function applyError(\n d: ErrorDesc,\n el: Element,\n ctx: BindingContext,\n disposers: (() => void)[]\n): void {\n // Ensure data-error attribute is set from descriptor (source of truth)\n // so registerBoundary can find the signal name, even if AOT codegen\n // stops emitting the transitional data-error attribute in the future.\n if (d.expr && !el.getAttribute('data-error')) {\n el.setAttribute('data-error', d.expr);\n }\n\n // Register el itself as an error boundary. We use registerBoundary (not\n // bindErrorBoundary) because bindErrorBoundary uses querySelectorAll which\n // only searches children — it would miss el itself.\n registerBoundary(el, ctx, disposers);\n}\n\nexport function applyProjection(\n d: ProjDesc,\n commentMap: Map<string, Comment>,\n ctx: BindingContext,\n disposers: (() => void)[]\n): void {\n const anchor = commentMap.get(`slot:${d.name}`);\n if (!anchor) return;\n\n const fallback = d.fallback;\n const anchorExpando = anchor as Comment & {\n __slotName?: string;\n __fallbackFactory?: (\n factoryCtx?: BindingContext\n ) => HTMLElement | DocumentFragment | undefined;\n };\n\n // Set expando properties that extractSlotDefs expects\n anchorExpando.__slotName = d.name;\n if (fallback) {\n anchorExpando.__fallbackFactory = (factoryCtx?: BindingContext) => {\n const result = fallback(factoryCtx || ctx);\n if (result && typeof result.destroy === 'function') {\n disposers.push(result.destroy);\n }\n return result?.el;\n };\n }\n\n // Check for SlotMap in context\n const slotMap = ('__slotMap' in ctx ? ctx.__slotMap : undefined) as\n | SlotMap\n | undefined;\n if (slotMap) {\n const slotDefs = [\n {\n name: d.name,\n anchor,\n fallbackFactory: anchorExpando.__fallbackFactory,\n },\n ];\n const render = slotMap.get(d.name);\n const bound: SlotMap = new Map();\n if (render)\n bound.set(d.name, (slotDisposers, at) => {\n const content = render(slotDisposers, at);\n const pageCtx = nodeExpando(content).__pithyCtx;\n // Runtime-built content: the page's own passes do not run on a remount.\n if (pageCtx)\n withSlotBoundary(at, ctx.__slotHost as Element | undefined, () =>\n bindAfterProjection(content, pageCtx, slotDisposers ?? disposers)\n );\n return content;\n });\n mountProjection(slotDefs, bound, disposers);\n } else if (fallback) {\n // No projected content — mount fallback\n const fallbackResult = fallback(ctx);\n const parent = anchor.parentNode;\n if (parent && fallbackResult?.el) {\n // Capture nodes for cleanup (fragment empties itself on insert)\n const nodes =\n fallbackResult.el instanceof DocumentFragment\n ? Array.from(fallbackResult.el.childNodes)\n : [fallbackResult.el];\n // Insert directly — fragment preserves child order; single node is trivial\n parent.insertBefore(fallbackResult.el, anchor.nextSibling);\n if (typeof fallbackResult.destroy === 'function') {\n disposers.push(fallbackResult.destroy);\n }\n disposers.push(() => {\n for (const node of nodes) {\n if (node.parentNode) node.parentNode.removeChild(node);\n }\n });\n }\n }\n}\n\nexport function applyBind(\n d: BindDesc,\n el: Element,\n ctx: BindingContext,\n disposers: (() => void)[]\n): void {\n if (!(el instanceof HTMLElement)) return;\n\n const sig = ctx[d.expr];\n if (!isSignal(sig) || typeof sig.set !== 'function') {\n if (import.meta.env?.DEV) {\n console.warn(`[AOT @bind] \"${d.expr}\" must refer to a writable signal`);\n }\n return;\n }\n const write = sig.set;\n\n const prop = inferBindableProperty(el);\n const target = el as HTMLElement & Record<string, unknown>;\n const stop = effect(() => {\n const value = sig();\n if (target[prop] !== value) target[prop] = value;\n });\n\n const event = prop === 'checked' ? 'change' : 'input';\n const handler = () => {\n write(extractBindableValue(el, prop));\n };\n el.addEventListener(event, handler);\n\n disposers.push(() => {\n el.removeEventListener(event, handler);\n stop();\n });\n}\n\nfunction inferBindableProperty(el: HTMLElement): string {\n const tag = el.tagName.toLowerCase();\n if (tag === 'input') {\n const type = (el as HTMLInputElement).type;\n if (type === 'checkbox' || type === 'radio') return 'checked';\n }\n return 'value';\n}\n\n/** Extract value from element with type coercion for number inputs. */\nfunction extractBindableValue(el: HTMLElement, prop: string): unknown {\n if (prop === 'checked') return (el as HTMLInputElement).checked;\n\n const tag = el.tagName.toLowerCase();\n if (tag === 'input') {\n const inputEl = el as HTMLInputElement;\n if (inputEl.type === 'number') {\n const numValue = Number(inputEl.value);\n return isNaN(numValue) ? inputEl.value : numValue;\n }\n return inputEl.value;\n }\n\n return (el as HTMLElement & Record<string, unknown>)[prop];\n}\n\n/**\n * Matches the skeleton's text exactly: the descriptor's own text and expressions.\n * A value can hold `{{` too, and text already bound can equal a later marker.\n */\nfunction holdsInterpolation(node: Text, parts: InterpDesc['parts']): boolean {\n if (!skeletonText.has(node)) return false;\n const text = node.nodeValue ?? '';\n let at = 0;\n for (const part of parts) {\n if ('s' in part) {\n if (!text.startsWith(part.s, at)) return false;\n at += part.s.length;\n continue;\n }\n if (!text.startsWith('{{', at)) return false;\n const end = text.indexOf('}}', at);\n if (end === -1 || text.slice(at + 2, end).trim() !== part.e) return false;\n at = end + 2;\n }\n return at === text.length;\n}\n\nconst skeletonText = new WeakSet<Text>();\n\n/** Record the skeleton's own `{{ }}` text, before components or bindings add any. */\nexport function markSkeletonText(fragment: DocumentFragment): void {\n const walker = document.createTreeWalker(fragment, NodeFilter.SHOW_TEXT);\n let node: Text | null;\n while ((node = walker.nextNode() as Text | null)) {\n if (node.nodeValue?.includes('{{')) skeletonText.add(node);\n }\n}\n\nexport function applyInterpolation(\n d: InterpDesc,\n el: Element | DocumentFragment,\n ctx: BindingContext,\n disposers: (() => void)[]\n): void {\n // Find text nodes within el that contain {{ }} markers\n const walker = document.createTreeWalker(el, NodeFilter.SHOW_TEXT);\n let textNode: Text | null;\n const targets: Text[] = [];\n\n const rootLevel = d.pid === '';\n while ((textNode = walker.nextNode() as Text | null)) {\n if (!holdsInterpolation(textNode, d.parts)) continue;\n if (rootLevel && textNode.parentElement?.closest('[data-pid]')) continue;\n targets.push(textNode);\n break;\n }\n\n if (targets.length === 0 && import.meta.env?.DEV) {\n console.warn(\n `[AOT interp] No text node with {{ }} markers found ${rootLevel ? 'at the template root' : `in element pid=\"${d.pid}\"`}`\n );\n }\n\n // Process each target text node matching this interpolation descriptor\n for (const node of targets) {\n const localCtx = nearestCtx(node, ctx);\n const parent = node.parentNode;\n if (!parent) continue;\n\n const nextSibling = node.nextSibling;\n parent.removeChild(node);\n\n for (const part of d.parts) {\n if ('s' in part) {\n // Static text\n parent.insertBefore(document.createTextNode(part.s), nextSibling);\n } else {\n // Dynamic expression\n const expr = part.e;\n const startComment = document.createComment('t');\n const dynText = document.createTextNode('');\n const endComment = document.createComment('/t');\n\n parent.insertBefore(startComment, nextSibling);\n parent.insertBefore(dynText, nextSibling);\n parent.insertBefore(endComment, nextSibling);\n\n try {\n const compiledFn = compileExpression(expr, localCtx);\n\n if (isSSRMode()) {\n try {\n dynText.nodeValue = toTextValue(compiledFn());\n } catch {\n dynText.nodeValue = '';\n }\n } else {\n let lastValue: string | undefined;\n const stop = effect(() => {\n try {\n const next = toTextValue(compiledFn());\n if (next !== lastValue) {\n dynText.nodeValue = next;\n lastValue = next;\n }\n } catch {\n dynText.nodeValue = '';\n }\n });\n disposers.push(stop);\n }\n } catch {\n dynText.nodeValue = '';\n }\n }\n }\n\n // Only process the first matching text node per interpolation descriptor\n break;\n }\n}\n\n/** Per-element, per-event idempotency guard (mirrors JIT's BOUND_KEY symbol). */\nconst AOT_BOUND_KEY: unique symbol = Symbol('pithy:aot-bound');\n\nfunction getAotBoundSet(el: Element, eventName: string): Set<string> {\n const host = el as Element & {\n [AOT_BOUND_KEY]?: Record<string, Set<string>>;\n };\n const store =\n host[AOT_BOUND_KEY] ??\n (host[AOT_BOUND_KEY] = Object.create(null) as Record<string, Set<string>>);\n return (store[eventName] ??= new Set<string>());\n}\n\nexport function applyEvent(\n d: EventDesc,\n el: Element,\n ctx: BindingContext,\n disposers: (() => void)[]\n): void {\n // Idempotency: skip if this exact event+expr combo was already bound\n const boundSet = getAotBoundSet(el, d.event);\n const boundKey = `${d.event}${d.mods ? '.' + d.mods.join('.') : ''}=${d.expr}`;\n if (boundSet.has(boundKey)) return;\n\n const localCtx = nearestCtx(el, ctx);\n const mods = parseMods(d.mods);\n const handlerExpr = d.expr;\n\n const isSimpleIdentifier = /^[a-zA-Z_][a-zA-Z0-9_]*$/.test(handlerExpr);\n const directFn =\n isSimpleIdentifier && typeof localCtx[handlerExpr] === 'function'\n ? (localCtx[handlerExpr] as EventListener)\n : null;\n const runWithEvt = directFn ? null : compileWithEvent(handlerExpr, localCtx);\n\n const listener: EventListener = (ev: Event) => {\n if (mods.self && ev.target !== el) return;\n if (mods.prevent) ev.preventDefault();\n if (mods.stop) ev.stopPropagation();\n\n try {\n if (directFn) {\n return directFn.call(localCtx, ev);\n } else if (runWithEvt) {\n const out = runWithEvt(ev, el);\n if (typeof out === 'function')\n return (out as (e: Event) => unknown).call(localCtx, ev);\n return out;\n }\n } catch (error) {\n const boundaryEl = el.closest('[data-error]') as Element | null;\n const boundary = boundaryForElement(boundaryEl);\n if (boundary) {\n setBoundaryError(\n boundary,\n error instanceof Error ? error : new Error(String(error))\n );\n } else {\n throw error;\n }\n }\n };\n\n const options: AddEventListenerOptions = {\n capture: !!mods.capture,\n passive: !!mods.passive,\n once: !!mods.once,\n };\n\n el.addEventListener(d.event, listener, options);\n boundSet.add(boundKey);\n disposers.push(() => {\n el.removeEventListener(d.event, listener, { capture: !!mods.capture });\n boundSet.delete(boundKey);\n });\n}\n\nfunction parseMods(mods?: string[]): {\n once?: boolean;\n prevent?: boolean;\n stop?: boolean;\n self?: boolean;\n capture?: boolean;\n passive?: boolean;\n} {\n if (!mods) return {};\n const m: Record<string, boolean> = {};\n for (const mod of mods) m[mod] = true;\n return m;\n}\n\nexport function applyClass(\n d: ClassDesc,\n el: Element,\n ctx: BindingContext,\n disposers: (() => void)[]\n): void {\n const localCtx = nearestCtx(el, ctx);\n try {\n const evaluate = compileExpression(d.expr, localCtx);\n const stop = effect(() => {\n try {\n el.classList.toggle(d.name, !!evaluate());\n } catch {\n /* ignore */\n }\n });\n disposers.push(stop);\n } catch {\n /* ignore */\n }\n}\n\nexport function applyClasses(\n d: ClassesDesc,\n el: Element,\n ctx: BindingContext,\n disposers: (() => void)[]\n): void {\n const localCtx = nearestCtx(el, ctx);\n try {\n const evaluate = compileExpression(d.expr, localCtx);\n const owned = new Set<string>();\n const stop = effect(() => {\n try {\n applyClassGroup(el, evaluate(), owned);\n } catch {\n /* ignore */\n }\n });\n disposers.push(stop);\n } catch {\n /* ignore */\n }\n}\n\n/** Convert camelCase to kebab-case for CSS property names. */\nfunction toKebabCase(prop: string): string {\n return prop.replace(/[A-Z]/g, m => `-${m.toLowerCase()}`);\n}\n\nexport function applyStyle(\n d: StyleDesc,\n el: Element,\n ctx: BindingContext,\n disposers: (() => void)[]\n): void {\n // Not `instanceof HTMLElement`: SVG elements have inline styles too.\n const style = (el as Partial<ElementCSSInlineStyle>).style;\n if (!style) return;\n const localCtx = nearestCtx(el, ctx);\n // setProperty requires kebab-case; codegen may emit camelCase (e.g. fontSize)\n const cssProp = d.prop.includes('-') ? d.prop : toKebabCase(d.prop);\n try {\n const evaluate = compileExpression(d.expr, localCtx);\n const stop = effect(() => {\n try {\n const value = evaluate();\n if (value == null || value === false) {\n setStyleProp(el, cssProp, null);\n return;\n }\n const text = String(value);\n const important = /\\s*!important\\s*$/i.exec(text);\n if (important) {\n setStyleProp(\n el,\n cssProp,\n text.slice(0, important.index),\n 'important'\n );\n } else {\n setStyleProp(el, cssProp, text);\n }\n } catch {\n /* ignore */\n }\n });\n disposers.push(stop);\n } catch {\n /* ignore */\n }\n}\n\nexport function applyBound(\n d: BoundDesc,\n el: Element,\n ctx: BindingContext,\n disposers: (() => void)[]\n): void {\n const localCtx = nearestCtx(el, ctx);\n // Compile once outside effect via compileExpression (consistent with applyClass/applyStyle).\n try {\n const evaluate = compileExpression(d.expr, localCtx);\n const writeStyle = d.attr === 'style' ? styleWriter(el) : null;\n\n const stop = effect(() => {\n try {\n const value = evaluate();\n if (writeStyle && typeof value === 'boolean') {\n writeStyle('');\n } else if (typeof value === 'boolean') {\n if (value) el.setAttribute(d.attr, '');\n else el.removeAttribute(d.attr);\n } else {\n const text = String(value ?? '');\n if (writeStyle) writeStyle(text);\n else if (rejectsScriptSink(el, d.attr, text))\n el.removeAttribute(d.attr);\n else el.setAttribute(d.attr, text);\n }\n } catch {\n /* ignore */\n }\n });\n disposers.push(stop);\n } catch {\n /* ignore invalid expression */\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"applySimple.js","sourceRoot":"","sources":["../../../src/runtime/bindings/applySimple.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AACpD,OAAO,EAAE,iBAAiB,EAAE,MAAM,iCAAiC,CAAC;AACpE,OAAO,EACL,iBAAiB,EACjB,YAAY,EACZ,WAAW,GACZ,MAAM,yCAAyC,CAAC;AACjD,OAAO,EAAE,WAAW,EAAE,MAAM,yBAAyB,CAAC;AACtD,OAAO,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAC;AAClD,OAAO,EACL,gBAAgB,EAChB,kBAAkB,EAClB,gBAAgB,EAChB,gBAAgB,GACjB,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EAAE,eAAe,EAAE,MAAM,yCAAyC,CAAC;AAC1E,OAAO,EAAE,eAAe,EAAgB,MAAM,iCAAiC,CAAC;AAChF,OAAO,EAAE,mBAAmB,EAAE,MAAM,yCAAyC,CAAC;AAC9E,OAAO,EAAE,eAAe,EAAE,WAAW,EAAE,MAAM,2BAA2B,CAAC;AAczE,OAAO,EAAE,UAAU,EAAE,gBAAgB,EAAE,MAAM,WAAW,CAAC;AAEzD,iFAAiF;AAEjF,MAAM,UAAU,QAAQ,CACtB,CAAU,EACV,EAAW,EACX,GAAmB,EACnB,SAAyB;IAEzB,MAAM,GAAG,GAAG,GAAG,CAAC,CAAC,CAAC,IAAI,CAET,CAAC;IACd,IAAI,GAAG,IAAI,OAAO,GAAG,CAAC,GAAG,KAAK,UAAU,EAAE,CAAC;QACzC,GAAG,CAAC,GAAG,CAA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AAC;QACH,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IACvB,CAAC;IAAC,MAAM,CAAC;QACP,+BAA+B;IACjC,CAAC;AACH,CAAC","sourcesContent":["import { effect, isSignal } from '@pithyjs/signals';\nimport { compileExpression } from '../../compile/compileExpression';\nimport {\n rejectsScriptSink,\n setStyleProp,\n styleWriter,\n} from '../../compile/binds/bindBoundAttributes';\nimport { toTextValue } from '../../compile/textValue';\nimport { isSSRMode } from '../../compile/ssrMode';\nimport {\n registerBoundary,\n boundaryForElement,\n setBoundaryError,\n withSlotBoundary,\n} from '../../compile/binds/bindErrorBoundary';\nimport { applyClassGroup } from '../../compile/binds/bindClassDirectives';\nimport { mountProjection, type SlotMap } from '../../compile/contentProjection';\nimport { bindAfterProjection } from '../../compile/binds/bindAfterProjection';\nimport { forwardEventKey, nodeExpando } from '../../compile/nodeExpando';\nimport type {\n RefDesc,\n ErrorDesc,\n ProjDesc,\n BindDesc,\n InterpDesc,\n EventDesc,\n ClassDesc,\n ClassesDesc,\n StyleDesc,\n BoundDesc,\n BindingContext,\n} from './types';\nimport { nearestCtx, compileWithEvent } from './helpers';\n\n// ─── Individual binding handlers ──────────────────────────────────────────────\n\nexport function applyRef(\n d: RefDesc,\n el: Element,\n ctx: BindingContext,\n disposers: (() => void)[]\n): void {\n const ref = ctx[d.name] as\n | { set?: (value: Element | null) => void }\n | undefined;\n if (ref && typeof ref.set === 'function') {\n ref.set(el);\n disposers.push(() => ref.set!(null));\n }\n}\n\nexport function applyError(\n d: ErrorDesc,\n el: Element,\n ctx: BindingContext,\n disposers: (() => void)[]\n): void {\n // Ensure data-error attribute is set from descriptor (source of truth)\n // so registerBoundary can find the signal name, even if AOT codegen\n // stops emitting the transitional data-error attribute in the future.\n if (d.expr && !el.getAttribute('data-error')) {\n el.setAttribute('data-error', d.expr);\n }\n\n // Register el itself as an error boundary. We use registerBoundary (not\n // bindErrorBoundary) because bindErrorBoundary uses querySelectorAll which\n // only searches children — it would miss el itself.\n registerBoundary(el, ctx, disposers);\n}\n\nexport function applyProjection(\n d: ProjDesc,\n commentMap: Map<string, Comment>,\n ctx: BindingContext,\n disposers: (() => void)[]\n): void {\n const anchor = commentMap.get(`slot:${d.name}`);\n if (!anchor) return;\n\n const fallback = d.fallback;\n const anchorExpando = anchor as Comment & {\n __slotName?: string;\n __fallbackFactory?: (\n factoryCtx?: BindingContext\n ) => HTMLElement | DocumentFragment | undefined;\n };\n\n // Set expando properties that extractSlotDefs expects\n anchorExpando.__slotName = d.name;\n if (fallback) {\n anchorExpando.__fallbackFactory = (factoryCtx?: BindingContext) => {\n const result = fallback(factoryCtx || ctx);\n if (result && typeof result.destroy === 'function') {\n disposers.push(result.destroy);\n }\n return result?.el;\n };\n }\n\n // Check for SlotMap in context\n const slotMap = ('__slotMap' in ctx ? ctx.__slotMap : undefined) as\n | SlotMap\n | undefined;\n if (slotMap) {\n const slotDefs = [\n {\n name: d.name,\n anchor,\n fallbackFactory: anchorExpando.__fallbackFactory,\n },\n ];\n const render = slotMap.get(d.name);\n const bound: SlotMap = new Map();\n if (render)\n bound.set(d.name, (slotDisposers, at) => {\n const content = render(slotDisposers, at);\n const pageCtx = nodeExpando(content).__pithyCtx;\n // Runtime-built content: the page's own passes do not run on a remount.\n if (pageCtx)\n withSlotBoundary(at, ctx.__slotHost as Element | undefined, () =>\n bindAfterProjection(content, pageCtx, slotDisposers ?? disposers)\n );\n return content;\n });\n mountProjection(slotDefs, bound, disposers);\n } else if (fallback) {\n // No projected content — mount fallback\n const fallbackResult = fallback(ctx);\n const parent = anchor.parentNode;\n if (parent && fallbackResult?.el) {\n // Capture nodes for cleanup (fragment empties itself on insert)\n const nodes =\n fallbackResult.el instanceof DocumentFragment\n ? Array.from(fallbackResult.el.childNodes)\n : [fallbackResult.el];\n // Insert directly — fragment preserves child order; single node is trivial\n parent.insertBefore(fallbackResult.el, anchor.nextSibling);\n if (typeof fallbackResult.destroy === 'function') {\n disposers.push(fallbackResult.destroy);\n }\n disposers.push(() => {\n for (const node of nodes) {\n if (node.parentNode) node.parentNode.removeChild(node);\n }\n });\n }\n }\n}\n\nexport function applyBind(\n d: BindDesc,\n el: Element,\n ctx: BindingContext,\n disposers: (() => void)[]\n): void {\n if (!(el instanceof HTMLElement)) return;\n\n const sig = ctx[d.expr];\n if (!isSignal(sig) || typeof sig.set !== 'function') {\n if (import.meta.env?.DEV) {\n console.warn(`[AOT @bind] \"${d.expr}\" must refer to a writable signal`);\n }\n return;\n }\n const write = sig.set;\n\n const prop = inferBindableProperty(el);\n const target = el as HTMLElement & Record<string, unknown>;\n const stop = effect(() => {\n const value = sig();\n if (target[prop] !== value) target[prop] = value;\n });\n\n const event = prop === 'checked' ? 'change' : 'input';\n const handler = () => {\n write(extractBindableValue(el, prop));\n };\n el.addEventListener(event, handler);\n\n disposers.push(() => {\n el.removeEventListener(event, handler);\n stop();\n });\n}\n\nfunction inferBindableProperty(el: HTMLElement): string {\n const tag = el.tagName.toLowerCase();\n if (tag === 'input') {\n const type = (el as HTMLInputElement).type;\n if (type === 'checkbox' || type === 'radio') return 'checked';\n }\n return 'value';\n}\n\n/** Extract value from element with type coercion for number inputs. */\nfunction extractBindableValue(el: HTMLElement, prop: string): unknown {\n if (prop === 'checked') return (el as HTMLInputElement).checked;\n\n const tag = el.tagName.toLowerCase();\n if (tag === 'input') {\n const inputEl = el as HTMLInputElement;\n if (inputEl.type === 'number') {\n const numValue = Number(inputEl.value);\n return isNaN(numValue) ? inputEl.value : numValue;\n }\n return inputEl.value;\n }\n\n return (el as HTMLElement & Record<string, unknown>)[prop];\n}\n\n/**\n * Matches the skeleton's text exactly: the descriptor's own text and expressions.\n * A value can hold `{{` too, and text already bound can equal a later marker.\n */\nfunction holdsInterpolation(node: Text, parts: InterpDesc['parts']): boolean {\n if (!skeletonText.has(node)) return false;\n const text = node.nodeValue ?? '';\n let at = 0;\n for (const part of parts) {\n if ('s' in part) {\n if (!text.startsWith(part.s, at)) return false;\n at += part.s.length;\n continue;\n }\n if (!text.startsWith('{{', at)) return false;\n const end = text.indexOf('}}', at);\n if (end === -1 || text.slice(at + 2, end).trim() !== part.e) return false;\n at = end + 2;\n }\n return at === text.length;\n}\n\nconst skeletonText = new WeakSet<Text>();\n\n/** Record the skeleton's own `{{ }}` text, before components or bindings add any. */\nexport function markSkeletonText(fragment: DocumentFragment): void {\n const walker = document.createTreeWalker(fragment, NodeFilter.SHOW_TEXT);\n let node: Text | null;\n while ((node = walker.nextNode() as Text | null)) {\n if (node.nodeValue?.includes('{{')) skeletonText.add(node);\n }\n}\n\nexport function applyInterpolation(\n d: InterpDesc,\n el: Element | DocumentFragment,\n ctx: BindingContext,\n disposers: (() => void)[]\n): void {\n // Find text nodes within el that contain {{ }} markers\n const walker = document.createTreeWalker(el, NodeFilter.SHOW_TEXT);\n let textNode: Text | null;\n const targets: Text[] = [];\n\n const rootLevel = d.pid === '';\n while ((textNode = walker.nextNode() as Text | null)) {\n if (!holdsInterpolation(textNode, d.parts)) continue;\n if (rootLevel && textNode.parentElement?.closest('[data-pid]')) continue;\n targets.push(textNode);\n break;\n }\n\n if (targets.length === 0 && import.meta.env?.DEV) {\n console.warn(\n `[AOT interp] No text node with {{ }} markers found ${rootLevel ? 'at the template root' : `in element pid=\"${d.pid}\"`}`\n );\n }\n\n // Process each target text node matching this interpolation descriptor\n for (const node of targets) {\n const localCtx = nearestCtx(node, ctx);\n const parent = node.parentNode;\n if (!parent) continue;\n\n const nextSibling = node.nextSibling;\n parent.removeChild(node);\n\n for (const part of d.parts) {\n if ('s' in part) {\n // Static text\n parent.insertBefore(document.createTextNode(part.s), nextSibling);\n } else {\n // Dynamic expression\n const expr = part.e;\n const startComment = document.createComment('t');\n const dynText = document.createTextNode('');\n const endComment = document.createComment('/t');\n\n parent.insertBefore(startComment, nextSibling);\n parent.insertBefore(dynText, nextSibling);\n parent.insertBefore(endComment, nextSibling);\n\n try {\n const compiledFn = compileExpression(expr, localCtx);\n\n if (isSSRMode()) {\n try {\n dynText.nodeValue = toTextValue(compiledFn());\n } catch {\n dynText.nodeValue = '';\n }\n } else {\n let lastValue: string | undefined;\n const stop = effect(() => {\n try {\n const next = toTextValue(compiledFn());\n if (next !== lastValue) {\n dynText.nodeValue = next;\n lastValue = next;\n }\n } catch {\n dynText.nodeValue = '';\n }\n });\n disposers.push(stop);\n }\n } catch {\n dynText.nodeValue = '';\n }\n }\n }\n\n // Only process the first matching text node per interpolation descriptor\n break;\n }\n}\n\n/** Per-element, per-event idempotency guard (mirrors JIT's BOUND_KEY symbol). */\nconst AOT_BOUND_KEY: unique symbol = Symbol('pithy:aot-bound');\n\nfunction getAotBoundSet(el: Element, eventName: string): Set<string> {\n const host = el as Element & {\n [AOT_BOUND_KEY]?: Record<string, Set<string>>;\n };\n const store =\n host[AOT_BOUND_KEY] ??\n (host[AOT_BOUND_KEY] = Object.create(null) as Record<string, Set<string>>);\n return (store[eventName] ??= new Set<string>());\n}\n\nexport function applyEvent(\n d: EventDesc,\n el: Element,\n ctx: BindingContext,\n disposers: (() => void)[]\n): void {\n // Idempotency: skip if this exact event+expr combo was already bound\n const boundSet = getAotBoundSet(el, d.event);\n const key = `${d.event}${d.mods ? '.' + d.mods.join('.') : ''}=${d.expr}`;\n const fwdCtx = nodeExpando(el).__pithyForwardCtx;\n // A root is marked only after the child bound its own events.\n const boundKey = fwdCtx ? forwardEventKey(el, key) : key;\n if (boundSet.has(boundKey)) return;\n\n const localCtx = fwdCtx ?? nearestCtx(el, ctx);\n const mods = parseMods(d.mods);\n const handlerExpr = d.expr;\n\n const isSimpleIdentifier = /^[a-zA-Z_][a-zA-Z0-9_]*$/.test(handlerExpr);\n const directFn =\n isSimpleIdentifier && typeof localCtx[handlerExpr] === 'function'\n ? (localCtx[handlerExpr] as EventListener)\n : null;\n const runWithEvt = directFn ? null : compileWithEvent(handlerExpr, localCtx);\n\n const listener: EventListener = (ev: Event) => {\n if (mods.self && ev.target !== el) return;\n if (mods.prevent) ev.preventDefault();\n if (mods.stop) ev.stopPropagation();\n\n try {\n if (directFn) {\n return directFn.call(localCtx, ev);\n } else if (runWithEvt) {\n const out = runWithEvt(ev, el);\n if (typeof out === 'function')\n return (out as (e: Event) => unknown).call(localCtx, ev);\n return out;\n }\n } catch (error) {\n const boundaryEl = el.closest('[data-error]') as Element | null;\n const boundary = boundaryForElement(boundaryEl);\n if (boundary) {\n setBoundaryError(\n boundary,\n error instanceof Error ? error : new Error(String(error))\n );\n } else {\n throw error;\n }\n }\n };\n\n const options: AddEventListenerOptions = {\n capture: !!mods.capture,\n passive: !!mods.passive,\n once: !!mods.once,\n };\n\n el.addEventListener(d.event, listener, options);\n boundSet.add(boundKey);\n disposers.push(() => {\n el.removeEventListener(d.event, listener, { capture: !!mods.capture });\n boundSet.delete(boundKey);\n });\n}\n\nfunction parseMods(mods?: string[]): {\n once?: boolean;\n prevent?: boolean;\n stop?: boolean;\n self?: boolean;\n capture?: boolean;\n passive?: boolean;\n} {\n if (!mods) return {};\n const m: Record<string, boolean> = {};\n for (const mod of mods) m[mod] = true;\n return m;\n}\n\nexport function applyClass(\n d: ClassDesc,\n el: Element,\n ctx: BindingContext,\n disposers: (() => void)[]\n): void {\n const localCtx = nodeExpando(el).__pithyForwardCtx ?? nearestCtx(el, ctx);\n try {\n const evaluate = compileExpression(d.expr, localCtx);\n const stop = effect(() => {\n try {\n el.classList.toggle(d.name, !!evaluate());\n } catch {\n /* ignore */\n }\n });\n disposers.push(stop);\n } catch {\n /* ignore */\n }\n}\n\nexport function applyClasses(\n d: ClassesDesc,\n el: Element,\n ctx: BindingContext,\n disposers: (() => void)[]\n): void {\n const localCtx = nodeExpando(el).__pithyForwardCtx ?? nearestCtx(el, ctx);\n try {\n const evaluate = compileExpression(d.expr, localCtx);\n const owned = new Set<string>();\n const stop = effect(() => {\n try {\n applyClassGroup(el, evaluate(), owned);\n } catch {\n /* ignore */\n }\n });\n disposers.push(stop);\n } catch {\n /* ignore */\n }\n}\n\n/** Convert camelCase to kebab-case for CSS property names. */\nfunction toKebabCase(prop: string): string {\n return prop.replace(/[A-Z]/g, m => `-${m.toLowerCase()}`);\n}\n\nexport function applyStyle(\n d: StyleDesc,\n el: Element,\n ctx: BindingContext,\n disposers: (() => void)[]\n): void {\n // Not `instanceof HTMLElement`: SVG elements have inline styles too.\n const style = (el as Partial<ElementCSSInlineStyle>).style;\n if (!style) return;\n const localCtx = nodeExpando(el).__pithyForwardCtx ?? nearestCtx(el, ctx);\n // setProperty requires kebab-case; codegen may emit camelCase (e.g. fontSize)\n const cssProp = d.prop.includes('-') ? d.prop : toKebabCase(d.prop);\n try {\n const evaluate = compileExpression(d.expr, localCtx);\n const stop = effect(() => {\n try {\n const value = evaluate();\n if (value == null || value === false) {\n setStyleProp(el, cssProp, null);\n return;\n }\n const text = String(value);\n const important = /\\s*!important\\s*$/i.exec(text);\n if (important) {\n setStyleProp(\n el,\n cssProp,\n text.slice(0, important.index),\n 'important'\n );\n } else {\n setStyleProp(el, cssProp, text);\n }\n } catch {\n /* ignore */\n }\n });\n disposers.push(stop);\n } catch {\n /* ignore */\n }\n}\n\nexport function applyBound(\n d: BoundDesc,\n el: Element,\n ctx: BindingContext,\n disposers: (() => void)[]\n): void {\n const localCtx = nodeExpando(el).__pithyForwardCtx ?? nearestCtx(el, ctx);\n // Compile once outside effect via compileExpression (consistent with applyClass/applyStyle).\n try {\n const evaluate = compileExpression(d.expr, localCtx);\n const writeStyle = d.attr === 'style' ? styleWriter(el) : null;\n\n const stop = effect(() => {\n try {\n const value = evaluate();\n if (writeStyle && typeof value === 'boolean') {\n writeStyle('');\n } else if (typeof value === 'boolean') {\n if (value) el.setAttribute(d.attr, '');\n else el.removeAttribute(d.attr);\n } else {\n const text = String(value ?? '');\n if (writeStyle) writeStyle(text);\n else if (rejectsScriptSink(el, d.attr, text))\n el.removeAttribute(d.attr);\n else el.setAttribute(d.attr, text);\n }\n } catch {\n /* ignore */\n }\n });\n disposers.push(stop);\n } catch {\n /* ignore invalid expression */\n }\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@pithyjs/core",
|
|
3
|
-
"version": "0.1.0-beta.
|
|
3
|
+
"version": "0.1.0-beta.18",
|
|
4
4
|
"repository": {
|
|
5
5
|
"type": "git",
|
|
6
6
|
"url": "git+https://github.com/PithyJS/pithyjs.git",
|
|
@@ -26,7 +26,7 @@
|
|
|
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.
|
|
29
|
+
"@pithyjs/compiler": "0.1.0-beta.8",
|
|
30
30
|
"@pithyjs/design-system": "0.1.0-beta.9"
|
|
31
31
|
},
|
|
32
32
|
"peerDependencies": {
|