kerfjs 5.0.0-beta.13 → 5.0.0-beta.131
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/CHANGELOG.md +3384 -108
- package/README.md +101 -37
- package/ai/cursorrules +127 -68
- package/ai/manifest.json +36 -7
- package/ai/skill.md +167 -86
- package/ai/ui-skill.md +18 -0
- package/dist/actions.d.ts +1 -1
- package/dist/actions.js +10 -6
- package/dist/actions.js.map +1 -1
- package/dist/array-signal.js +1 -1
- package/dist/async.d.ts +7 -3
- package/dist/async.js +39 -22
- package/dist/async.js.map +1 -1
- package/dist/attach.js +1 -66
- package/dist/attach.js.map +1 -1
- package/dist/{chunk-GY4XV2UV.js → chunk-4TX6YJDM.js} +10 -3
- package/dist/chunk-4TX6YJDM.js.map +1 -0
- package/dist/{chunk-SVATPF5R.js → chunk-5QDM6HPD.js} +637 -277
- package/dist/chunk-5QDM6HPD.js.map +1 -0
- package/dist/{chunk-QIP723L4.js → chunk-5WRGJZV6.js} +3 -2
- package/dist/chunk-5WRGJZV6.js.map +1 -0
- package/dist/chunk-AP2FT33F.js +87 -0
- package/dist/chunk-AP2FT33F.js.map +1 -0
- package/dist/chunk-BTOKH5FA.js +70 -0
- package/dist/chunk-BTOKH5FA.js.map +1 -0
- package/dist/{chunk-ZDCJZCNO.js → chunk-GGADRIQO.js} +168 -97
- package/dist/chunk-GGADRIQO.js.map +1 -0
- package/dist/chunk-KOEGJCIS.js +65 -0
- package/dist/chunk-KOEGJCIS.js.map +1 -0
- package/dist/{chunk-HW7KSM2Y.js → chunk-KUHXPPJ4.js} +1 -1
- package/dist/chunk-KUHXPPJ4.js.map +1 -0
- package/dist/{chunk-UZJ6I4T6.js → chunk-MK42GLPV.js} +1 -1
- package/dist/chunk-MK42GLPV.js.map +1 -0
- package/dist/chunk-N4VHHOCM.js +27 -0
- package/dist/chunk-N4VHHOCM.js.map +1 -0
- package/dist/{chunk-V46JKE44.js → chunk-NRPLVJVR.js} +43 -14
- package/dist/chunk-NRPLVJVR.js.map +1 -0
- package/dist/{chunk-LVH3GC6B.js → chunk-QOAB2ESQ.js} +3 -3
- package/dist/chunk-QOAB2ESQ.js.map +1 -0
- package/dist/{chunk-KZJXHFIB.js → chunk-V322Z7FX.js} +5 -5
- package/dist/chunk-V322Z7FX.js.map +1 -0
- package/dist/{delegate-CL9VTZFb.d.ts → delegate--CrfgYtC.d.ts} +0 -34
- package/dist/dev.d.ts +46 -15
- package/dist/dev.js +185 -40
- package/dist/dev.js.map +1 -1
- package/dist/html.js +20 -8
- package/dist/html.js.map +1 -1
- package/dist/index.d.ts +98 -13
- package/dist/index.js +49 -21
- package/dist/index.js.map +1 -1
- package/dist/jsx-runtime.d.ts +25 -10
- package/dist/jsx-runtime.js +1 -1
- package/dist/list.d.ts +7 -3
- package/dist/list.js +236 -78
- package/dist/list.js.map +1 -1
- package/dist/overlay.d.ts +287 -142
- package/dist/overlay.js +1040 -369
- package/dist/overlay.js.map +1 -1
- package/dist/remount.js +2 -2
- package/dist/remount.js.map +1 -1
- package/dist/router.d.ts +22 -6
- package/dist/router.js +58 -19
- package/dist/router.js.map +1 -1
- package/dist/scope.d.ts +45 -8
- package/dist/scope.js +69 -30
- package/dist/scope.js.map +1 -1
- package/dist/testing.js +1 -1
- package/dist/timing.d.ts +17 -7
- package/dist/timing.js +8 -3
- package/dist/timing.js.map +1 -1
- package/llms.txt +17 -6
- package/package.json +48 -12
- package/setup/apply.mjs +202 -0
- package/setup/cli.mjs +95 -0
- package/setup/common.mjs +91 -0
- package/setup/detect.mjs +274 -0
- package/setup/index.d.mts +39 -0
- package/setup/index.mjs +1290 -0
- package/setup/jsonc.mjs +201 -0
- package/setup/state.schema.json +57 -0
- package/setup/ui-baseline.mjs +210 -0
- package/dist/chunk-GY4XV2UV.js.map +0 -1
- package/dist/chunk-HW7KSM2Y.js.map +0 -1
- package/dist/chunk-KPXIOG2C.js +0 -54
- package/dist/chunk-KPXIOG2C.js.map +0 -1
- package/dist/chunk-KZJXHFIB.js.map +0 -1
- package/dist/chunk-LVH3GC6B.js.map +0 -1
- package/dist/chunk-QIP723L4.js.map +0 -1
- package/dist/chunk-SVATPF5R.js.map +0 -1
- package/dist/chunk-U6FK33SG.js +0 -20
- package/dist/chunk-U6FK33SG.js.map +0 -1
- package/dist/chunk-UZJ6I4T6.js.map +0 -1
- package/dist/chunk-V46JKE44.js.map +0 -1
- package/dist/chunk-ZDCJZCNO.js.map +0 -1
package/dist/html.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/utils/parseTemplate.ts","../src/html.ts"],"names":[],"mappings":";;;;;;AAiDA,IAAM,SAAA,GAAsB,EAAE,IAAA,EAAM,MAAA,EAAO;AAG3C,IAAM,SAAA,GAAY,8BAAA;AAKlB,SAAS,UAAU,MAAA,EAAuB;AACxC,EAAA,OAAO,IAAI,KAAA,CAAM,CAAA,UAAA,EAAa,MAAM,CAAA,CAAE,CAAA;AACxC;AAEA,SAAS,kBAAkB,IAAA,EAAqB;AAC9C,EAAA,OAAO,SAAA;AAAA,IACL,CAAA,iDAAA,EAAoD,KAAK,SAAA,CAAU,IAAA,CAAK,MAAM,GAAqC,CAAC,CAAC,CAAA,4OAAA;AAAA,GAIvH;AACF;AAEO,SAAS,cAAc,OAAA,EAA4C;AACxE,EAAA,MAAM,MAAA,GAAmB,IAAI,KAAA,CAAM,OAAA,CAAQ,MAAM,CAAA;AACjD,EAAA,MAAM,KAAA,GAAwB,IAAI,KAAA,CAAM,OAAA,CAAQ,SAAS,CAAC,CAAA;AAC1D,EAAA,MAAM,WAAqB,IAAI,KAAA,CAAc,QAAQ,MAAM,CAAA,CAAE,KAAK,EAAE,CAAA;AACpE,EAAA,IAAI,IAAA,GAAmC,MAAA;AACvC,EAAA,IAAI,KAAA,GAA0B,IAAA;AAE9B,EAAA,KAAA,IAAS,CAAA,GAAI,CAAA,EAAG,CAAA,GAAI,OAAA,CAAQ,QAAQ,CAAA,EAA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M,GAAA,GAAM,WAAW,KAAK,CAAA;AAC5B,MAAA,IAAI,GAAA,CAAI,SAAS,QAAA,EAAU;AACzB,QAAA,GAAA,IAAO,GAAA,CAAI,IAAA;AAAA,MACb,CAAA,MAAO;AACL,QAAA,KAAA,CAAM,KAAK,EAAE,IAAA,EAAM,QAAA,EAAU,IAAA,EAAM,KAAK,CAAA;AACxC,QAAA,GAAA,GAAM,EAAA;AACN,QAAA,KAAA,CAAM,KAAK,GAAG,CAAA;AAAA,MAChB;AAAA,IACF,CAAA,MAAA,IAAW,QAAA,CAAS,KAAK,CAAA,EAAG;AAI1B,MAAA,uBAAA,CAAyB,IAAA,CAAK,IAAA,EAAM,IAAA,CAAK,IAAA,EAAM,KAAK,CAAA;AACpD,MAAA,MAAM,EAAA,GAAK,QAAA,CAAS,IAAA,CAAK,IAAA,EAAM,KAAwB,CAAA;AACvD,MAAA,IAAI,OAAO,IAAA,EAAM;AACf,QAAA,CAAC,cAAA,KAAmB,EAAC,EAAG,IAAA,CAAK,EAAE,CAAA;AAAA,MACjC,CAAA,MAAO;AACL,QAAA,GAAA,IAAO,mBAAA,CAAoB,IAAA,CAAK,IAAA,EAAO,KAAA,CAA0B,KAAK,CAAA;AAAA,MACxE;AAAA,IACF,CAAA,MAAO;AACL,MAAA,GAAA,IAAO,mBAAA,CAAoB,IAAA,CAAK,IAAA,EAAM,KAAK,CAAA;AAAA,IAC7C;AAAA,EACF;AACA,EAAA,IAAI,GAAA,KAAQ,EAAA,IAAM,KAAA,CAAM,MAAA,KAAW,CAAA,EAAG,KAAA,CAAM,IAAA,CAAK,EAAE,IAAA,EAAM,QAAA,EAAU,IAAA,EAAM,GAAA,EAAK,CAAA;AAC9E,EAAA,OAAO,IAAI,QAAA,CAAS,kBAAA,CAAmB,KAAK,CAAC,CAAA;AAC/C","file":"html.js","sourcesContent":["/**\n * Static-parts parser for the `kerfjs/html` tagged template (`html\\`\\``).\n *\n * Parses a template's static string chunks ONCE into a `ParsedTemplate`:\n * the (possibly trimmed) chunks plus an ordered hole-descriptor list that\n * classifies each `${…}` hole as a TEXT hole (a child position) or an ATTR\n * hole (a complete attribute value, `attr=${v}` / `attr=\"${v}\"`). The\n * renderer in `src/html.ts` caches the parse per template-strings-array\n * identity, so repeated renders of the same call site skip this entirely.\n *\n * The state machine is deliberately small and strict: it tracks only\n * text / inside-open-tag / inside-comment modes and quote state. Holes in\n * any position it can't prove safe — tag names, attribute names, partial\n * attribute values, comments — THROW with an actionable message rather\n * than guessing. Static chunks are author-written markup and pass through\n * verbatim (the same trust model as JSX tag/attribute names).\n */\n\nexport interface AttrHole {\n kind: 'attr';\n /** The attribute name scanned from the preceding static chunk, verbatim. */\n name: string;\n /** The surrounding quote character, or null for an unquoted `attr=${v}`. */\n quote: '\"' | \"'\" | null;\n}\n\nexport interface TextHole {\n kind: 'text';\n}\n\nexport type TemplateHole = AttrHole | TextHole;\n\nexport interface ParsedTemplate {\n /**\n * Static chunks with attr-hole scaffolding (`name=`, quotes) stripped —\n * the renderer re-emits the whole ` name=\"value\"` via the JSX attribute\n * renderer. Always `holes.length + 1` entries.\n */\n chunks: string[];\n holes: TemplateHole[];\n /**\n * Per-chunk offset of the `>` that closes the element tag open at the\n * chunk's start, or -1. Only chunks that follow an attr hole can start\n * inside a tag; the renderer uses this to inject the bound-attribute\n * marker (`data-kfb` / `data-kfbrow`) for signal attribute holes.\n */\n tagClose: number[];\n}\n\nconst TEXT_HOLE: TextHole = { kind: 'text' };\n\n/** Matches a chunk tail of `name=` optionally followed by an opening quote. */\nconst ATTR_TAIL = /(\\s*)([^\\s\"'<>/=]+)=([\"'])?$/;\n\n/** Keep the actionable end of a malformed attribute without echoing an entire template. */\nconst PARTIAL_VALUE_DIAGNOSTIC_TAIL_LENGTH = 30;\n\nfunction holeError(detail: string): Error {\n return new Error(`html\\`\\`: ${detail}`);\n}\n\nfunction partialValueError(tail: string): Error {\n return holeError(\n `partial attribute values are not supported (near ${JSON.stringify(tail.slice(-PARTIAL_VALUE_DIAGNOSTIC_TAIL_LENGTH))}) — `\n + 'a hole must be the COMPLETE attribute value: attr=${v} or attr=\"${v}\". '\n + 'For class=\"a ${b}\"-style composition, build the full string first '\n + '(a plain template literal, or computed(() => `a ${b.value}`) for a bound attribute).',\n );\n}\n\nexport function parseTemplate(strings: readonly string[]): ParsedTemplate {\n const chunks: string[] = new Array(strings.length);\n const holes: TemplateHole[] = new Array(strings.length - 1);\n const tagClose: number[] = new Array<number>(strings.length).fill(-1);\n let mode: 'text' | 'tag' | 'comment' = 'text';\n let quote: '\"' | \"'\" | null = null;\n\n for (let i = 0; i < strings.length; i++) {\n let s = strings[i];\n // A quoted attr hole (`attr=\"${v}\"`) must be immediately closed by its\n // quote — the renderer emits the full quoted attribute itself, so the\n // author's closing quote is consumed here.\n if (i > 0) {\n const prev = holes[i - 1];\n if (prev.kind === 'attr' && prev.quote !== null) {\n if (s[0] !== prev.quote) throw partialValueError(strings[i - 1]);\n s = s.slice(1);\n }\n }\n\n const startedInTag = mode === 'tag';\n for (let j = 0; j < s.length; j++) {\n const ch = s[j];\n if (mode === 'text') {\n if (ch === '<') {\n if (s.startsWith('<!--', j)) {\n mode = 'comment';\n j += 3;\n } else if (j + 1 < s.length && /[a-zA-Z!/?]/.test(s[j + 1])) {\n mode = 'tag';\n }\n }\n } else if (mode === 'tag') {\n if (quote !== null) {\n if (ch === quote) quote = null;\n } else if (ch === '\"' || ch === \"'\") {\n quote = ch;\n } else if (ch === '>') {\n if (startedInTag && tagClose[i] === -1) tagClose[i] = j;\n mode = 'text';\n }\n } else if (ch === '-' && s.startsWith('-->', j)) {\n mode = 'text';\n j += 2;\n }\n }\n\n // Classify the hole that follows this chunk (no hole after the last one).\n if (i < strings.length - 1) {\n if (mode === 'comment') {\n throw holeError(\n 'holes inside HTML comments are not supported — move the ${…} hole outside the <!-- --> comment.',\n );\n }\n if (mode === 'text') {\n if (/<\\/?$/.test(s)) {\n throw holeError(\n 'tag-name holes (`<${…}>`) are not supported — write tag names statically. '\n + 'For a literal \"<\" before a hole, escape it as <.',\n );\n }\n holes[i] = TEXT_HOLE;\n } else {\n const m = ATTR_TAIL.exec(s);\n if (quote !== null) {\n // Inside a quoted attribute value: only valid if the quote opened\n // as the chunk's very last character (i.e. the hole IS the value).\n if (m === null || m[3] === undefined) throw partialValueError(s);\n holes[i] = { kind: 'attr', name: m[2], quote: m[3] as '\"' | \"'\" };\n s = s.slice(0, s.length - m[0].length);\n quote = null;\n } else if (m !== null && m[3] === undefined) {\n // Unquoted `attr=${v}`: the next static chunk must resume with an\n // attribute delimiter, or the template may simply end there.\n const next = strings[i + 1];\n const validNext = next.length > 0 ? /^[\\s>/]/.test(next) : i + 1 === strings.length - 1;\n if (!validNext) throw partialValueError(s);\n holes[i] = { kind: 'attr', name: m[2], quote: null };\n s = s.slice(0, s.length - m[0].length);\n } else if (/<\\/?$/.test(s)) {\n // The tag opened as the chunk's last characters (`</${…}`).\n throw holeError(\n 'tag-name holes (`<${…}>`) are not supported — write tag names statically. '\n + 'For a literal \"<\" before a hole, escape it as <.',\n );\n } else {\n throw holeError(\n 'a hole inside a tag must be a complete attribute value — attr=${…} or attr=\"${…}\". '\n + 'Tag-name and attribute-name holes are not supported; write those statically.',\n );\n }\n }\n }\n chunks[i] = s;\n }\n return { chunks, holes, tagClose };\n}\n","/**\n * `html` — tagged-template authoring at the `kerfjs/html` subpath, so\n * \"no build step\" is literally true: a CDN / importmap consumer can author\n * kerf UIs without a JSX transform.\n *\n * import { html } from 'kerfjs/html';\n * html`<div class=\"${cls}\">Count: ${count}</div>`\n * html`<ul>${each(items.value, (i) => html`<li id=\"${i.id}\">${i.label}</li>`)}</ul>`\n *\n * A thin front-end over the exact machinery JSX uses — the runtime paths are\n * IDENTICAL. Text holes go through the JSX child pipeline (`_toSegment`):\n * SafeHtml/list-segment passthrough (so `each()` composes and the keyed\n * reconciler owns its rows), string escaping, number stringify, boolean /\n * nullish → nothing, signal → fine-grained text binding, DOM-node and\n * unsupported-type errors. Attribute holes go through the JSX attribute\n * branch: signal → `_assertEmittableAttrName` + `bindAttr` (grouped into one\n * marker attribute per element); anything else → the JSX attribute renderer\n * (booleans, SafeHtml, URL screening, `on*` / malformed-name rejection).\n * `mount()` / `morph()` / the reconcilers need zero changes.\n *\n * Unlike JSX, NO camelCase attribute aliasing is applied — template authors\n * write real HTML attribute names (`class`, not `className`).\n *\n * Hole contract (enforced by the parser in `utils/parseTemplate.ts`): holes\n * are allowed in text/child positions and as a COMPLETE attribute value\n * (`attr=${v}` or `attr=\"${v}\"`). Tag-name holes, attribute-name holes,\n * partial attribute values (`class=\"a ${b}\"`), and holes inside comments\n * throw. Static chunks are author-written markup and pass through verbatim\n * (same trust model as JSX tags/attrs).\n *\n * Perf: the parse runs once per template call site — the tagged-template\n * strings array has stable identity, so a `WeakMap` keyed on it caches the\n * `ParsedTemplate`. Rendering is a chunk walk with string concatenation,\n * the same cost shape as the JSX runtime.\n */\n\nimport { bindAttr, bindMarkerAttr, isSignal } from './bindings.js';\nimport {\n _assertEmittableAttrName,\n _renderAttrVerbatim,\n _toSegment,\n SafeHtml,\n} from './jsx-runtime.js';\nimport type { ReadonlySignal, Signal } from './reactive.js';\nimport { mergeChildSegments, type Segment } from './segment.js';\nimport { type ParsedTemplate, parseTemplate } from './utils/parseTemplate.js';\n\n/**\n * Values accepted in `html\\`\\`` holes — the same set JSX accepts for\n * children (text holes) and attribute values (attr holes), including a\n * signal/`computed` itself for a fine-grained binding.\n */\nexport type HtmlValue =\n | SafeHtml\n | string\n | number\n | boolean\n | null\n | undefined\n | ReadonlySignal<unknown>\n | readonly HtmlValue[];\n\nconst PARSE_CACHE = new WeakMap<TemplateStringsArray, ParsedTemplate>();\n\n// Module-level mutable counter, sanctioned as observability-only state (see\n// CLAUDE.md design rule 5): it feeds the `_parseCount()` test hook that pins\n// the parse-once-per-callsite cache behavior and never influences rendering.\nlet parseCount = 0;\n\n/** Test hook: number of template parses performed (cache misses) so far. */\nexport function _parseCount(): number {\n return parseCount;\n}\n\nfunction getParsed(strings: TemplateStringsArray): ParsedTemplate {\n let parsed = PARSE_CACHE.get(strings);\n if (parsed === undefined) {\n parsed = parseTemplate(strings);\n parseCount++;\n PARSE_CACHE.set(strings, parsed);\n }\n return parsed;\n}\n\nexport function html(strings: TemplateStringsArray, ...values: HtmlValue[]): SafeHtml {\n const { chunks, holes, tagClose } = getParsed(strings);\n const parts: Segment[] = [];\n let buf = '';\n // Signal-attr binding ids for the currently-open element; flushed as one\n // marker attribute (`data-kfb` / `data-kfbrow`) at the tag's closing `>`,\n // mirroring the per-element grouping in `jsx()`.\n let pendingBindIds: string[] | null = null;\n\n for (let i = 0; i < chunks.length; i++) {\n let chunk = chunks[i];\n if (pendingBindIds !== null && tagClose[i] !== -1) {\n const off = tagClose[i];\n chunk = `${chunk.slice(0, off)} ${bindMarkerAttr()}=\"${pendingBindIds.join(',')}\"${chunk.slice(off)}`;\n pendingBindIds = null;\n }\n buf += chunk;\n if (i === holes.length) break;\n\n const hole = holes[i];\n const value = values[i];\n if (hole.kind === 'text') {\n const seg = _toSegment(value);\n if (seg.kind === 'static') {\n buf += seg.html;\n } else {\n parts.push({ kind: 'static', html: buf });\n buf = '';\n parts.push(seg);\n }\n } else if (isSignal(value)) {\n // Same contract as the `jsx()` signal-attribute branch: reject `on*` /\n // malformed names unconditionally (a signal's value changes over time),\n // then register the binding — or snapshot outside a mount render.\n _assertEmittableAttrName(hole.name, hole.name, false);\n const id = bindAttr(hole.name, value as Signal<unknown>);\n if (id !== null) {\n (pendingBindIds ??= []).push(id);\n } else {\n buf += _renderAttrVerbatim(hole.name, (value as Signal<unknown>).value);\n }\n } else {\n buf += _renderAttrVerbatim(hole.name, value);\n }\n }\n if (buf !== '' || parts.length === 0) parts.push({ kind: 'static', html: buf });\n return new SafeHtml(mergeChildSegments(parts));\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/utils/parseTemplate.ts","../src/html.ts"],"names":[],"mappings":";;;;;;AAmDA,IAAM,SAAA,GAAsB,E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,QAAA,EAAU,IAAA,EAAM,KAAK,CAAA;AACxC,QAAA,GAAA,GAAM,EAAA;AACN,QAAA,KAAA,CAAM,KAAK,GAAG,CAAA;AAAA,MAChB;AAAA,IACF,CAAA,MAAA,IAAW,QAAA,CAAS,KAAK,CAAA,EAAG;AAI1B,MAAA,uBAAA,CAAyB,IAAA,CAAK,IAAA,EAAM,IAAA,CAAK,IAAA,EAAM,KAAK,CAAA;AACpD,MAAA,MAAM,EAAA,GAAK,QAAA,CAAS,IAAA,CAAK,IAAA,EAAM,KAAwB,CAAA;AACvD,MAAA,IAAI,OAAO,IAAA,EAAM;AACf,QAAA,CAAC,cAAA,KAAmB,EAAC,EAAG,IAAA,CAAK,EAAE,CAAA;AAAA,MACjC,CAAA,MAAO;AACL,QAAA,GAAA,IAAO,mBAAA;AAAA,UACL,IAAA,CAAK,IAAA;AAAA,UACJ,KAAA,CAA0B,KAAA;AAAA,UAC3B,IAAA,CAAK;AAAA,SACP;AAAA,MACF;AAAA,IACF,CAAA,MAAO;AACL,MAAA,GAAA,IAAO,mBAAA,CAAoB,IAAA,CAAK,IAAA,EAAM,KAAA,EAAO,KAAK,GAAG,CAAA;AAAA,IACvD;AAAA,EACF;AACA,EAAA,IAAI,GAAA,KAAQ,EAAA,IAAM,KAAA,CAAM,MAAA,KAAW,CAAA;AACjC,IAAA,KAAA,CAAM,KAAK,EAAE,IAAA,EAAM,QAAA,EAAU,IAAA,EAAM,KAAK,CAAA;AAC1C,EAAA,OAAO,IAAI,QAAA,CAAS,kBAAA,CAAmB,KAAK,CAAC,CAAA;AAC/C","file":"html.js","sourcesContent":["/**\n * Static-parts parser for the `kerfjs/html` tagged template (`html\\`\\``).\n *\n * Parses a template's static string chunks ONCE into a `ParsedTemplate`:\n * the (possibly trimmed) chunks plus an ordered hole-descriptor list that\n * classifies each `${…}` hole as a TEXT hole (a child position) or an ATTR\n * hole (a complete attribute value, `attr=${v}` / `attr=\"${v}\"`). The\n * renderer in `src/html.ts` caches the parse per template-strings-array\n * identity, so repeated renders of the same call site skip this entirely.\n *\n * The state machine is deliberately small and strict: it tracks only\n * text / inside-open-tag / inside-comment modes and quote state. Holes in\n * any position it can't prove safe — tag names, attribute names, partial\n * attribute values, comments — THROW with an actionable message rather\n * than guessing. Static chunks are author-written markup and pass through\n * verbatim (the same trust model as JSX tag/attribute names).\n */\n\nexport interface AttrHole {\n kind: 'attr';\n /** The attribute name scanned from the preceding static chunk, verbatim. */\n name: string;\n /** The surrounding quote character, or null for an unquoted `attr=${v}`. */\n quote: '\"' | \"'\" | null;\n /** The element's tag name, lowercased, for sink-aware URL screening. */\n tag: string;\n}\n\nexport interface TextHole {\n kind: 'text';\n}\n\nexport type TemplateHole = AttrHole | TextHole;\n\nexport interface ParsedTemplate {\n /**\n * Static chunks with attr-hole scaffolding (`name=`, quotes) stripped —\n * the renderer re-emits the whole ` name=\"value\"` via the JSX attribute\n * renderer. Always `holes.length + 1` entries.\n */\n chunks: string[];\n holes: TemplateHole[];\n /**\n * Per-chunk offset of the `>` that closes the element tag open at the\n * chunk's start, or -1. Only chunks that follow an attr hole can start\n * inside a tag; the renderer uses this to inject the bound-attribute\n * marker (`data-kfb` / `data-kfbrow`) for signal attribute holes.\n */\n tagClose: number[];\n}\n\nconst TEXT_HOLE: TextHole = { kind: 'text' };\n\n/** Matches a chunk tail of `name=` optionally followed by an opening quote. */\nconst ATTR_TAIL = /(\\s*)([^\\s\"'<>/=]+)=([\"'])?$/;\n\n/** Keep the actionable end of a malformed attribute without echoing an entire template. */\nconst PARTIAL_VALUE_DIAGNOSTIC_TAIL_LENGTH = 30;\n\nfunction holeError(detail: string): Error {\n return new Error(`html\\`\\`: ${detail}`);\n}\n\nfunction partialValueError(tail: string): Error {\n return holeError(\n `partial attribute values are not supported (near ${JSON.stringify(tail.slice(-PARTIAL_VALUE_DIAGNOSTIC_TAIL_LENGTH))}) — ` +\n 'a hole must be the COMPLETE attribute value: attr=${v} or attr=\"${v}\". ' +\n 'For class=\"a ${b}\"-style composition, build the full string first ' +\n '(a plain template literal, or computed(() => `a ${b.value}`) for a bound attribute).',\n );\n}\n\nexport function parseTemplate(strings: readonly string[]): ParsedTemplate {\n const chunks: string[] = new Array(strings.length);\n const holes: TemplateHole[] = new Array(strings.length - 1);\n const tagClose: number[] = new Array<number>(strings.length).fill(-1);\n let mode: 'text' | 'tag' | 'comment' = 'text';\n let quote: '\"' | \"'\" | null = null;\n let tagName = '';\n\n for (let i = 0; i < strings.length; i++) {\n let s = strings[i];\n // A quoted attr hole (`attr=\"${v}\"`) must be immediately closed by its\n // quote — the renderer emits the full quoted attribute itself, so the\n // author's closing quote is consumed here.\n if (i > 0) {\n const prev = holes[i - 1];\n if (prev.kind === 'attr' && prev.quote !== null) {\n if (s[0] !== prev.quote) throw partialValueError(strings[i - 1]);\n s = s.slice(1);\n }\n }\n\n const startedInTag = mode === 'tag';\n for (let j = 0; j < s.length; j++) {\n const ch = s[j];\n if (mode === 'text') {\n if (ch === '<') {\n if (s.startsWith('<!--', j)) {\n mode = 'comment';\n j += 3;\n } else if (j + 1 < s.length && /[a-zA-Z!/?]/.test(s[j + 1])) {\n mode = 'tag';\n tagName = (\n /^[a-zA-Z][^\\s/>]*/.exec(s.slice(j + 1))?.[0] ?? ''\n ).toLowerCase();\n }\n }\n } else if (mode === 'tag') {\n if (quote !== null) {\n if (ch === quote) quote = null;\n } else if (ch === '\"' || ch === \"'\") {\n quote = ch;\n } else if (ch === '>') {\n if (startedInTag && tagClose[i] === -1) tagClose[i] = j;\n mode = 'text';\n }\n } else if (ch === '-' && s.startsWith('-->', j)) {\n mode = 'text';\n j += 2;\n }\n }\n\n // Classify the hole that follows this chunk (no hole after the last one).\n if (i < strings.length - 1) {\n if (mode === 'comment') {\n throw holeError(\n 'holes inside HTML comments are not supported — move the ${…} hole outside the <!-- --> comment.',\n );\n }\n if (mode === 'text') {\n if (/<\\/?$/.test(s)) {\n throw holeError(\n 'tag-name holes (`<${…}>`) are not supported — write tag names statically. ' +\n 'For a literal \"<\" before a hole, escape it as <.',\n );\n }\n holes[i] = TEXT_HOLE;\n } else {\n const m = ATTR_TAIL.exec(s);\n if (quote !== null) {\n // Inside a quoted attribute value: only valid if the quote opened\n // as the chunk's very last character (i.e. the hole IS the value).\n if (m === null || m[3] === undefined) throw partialValueError(s);\n holes[i] = {\n kind: 'attr',\n name: m[2],\n quote: m[3] as '\"' | \"'\",\n tag: tagName,\n };\n s = s.slice(0, s.length - m[0].length);\n quote = null;\n } else if (m !== null && m[3] === undefined) {\n // Unquoted `attr=${v}`: the next static chunk must resume with an\n // attribute delimiter, or the template may simply end there.\n const next = strings[i + 1];\n const validNext =\n next.length > 0\n ? /^[\\s>/]/.test(next)\n : i + 1 === strings.length - 1;\n if (!validNext) throw partialValueError(s);\n holes[i] = { kind: 'attr', name: m[2], quote: null, tag: tagName };\n s = s.slice(0, s.length - m[0].length);\n } else if (/<\\/?$/.test(s)) {\n // The tag opened as the chunk's last characters (`</${…}`).\n throw holeError(\n 'tag-name holes (`<${…}>`) are not supported — write tag names statically. ' +\n 'For a literal \"<\" before a hole, escape it as <.',\n );\n } else {\n throw holeError(\n 'a hole inside a tag must be a complete attribute value — attr=${…} or attr=\"${…}\". ' +\n 'Tag-name and attribute-name holes are not supported; write those statically.',\n );\n }\n }\n }\n chunks[i] = s;\n }\n return { chunks, holes, tagClose };\n}\n","/**\n * `html` — tagged-template authoring at the `kerfjs/html` subpath, so\n * \"no build step\" is literally true: a CDN / importmap consumer can author\n * kerf UIs without a JSX transform.\n *\n * import { html } from 'kerfjs/html';\n * html`<div class=\"${cls}\">Count: ${count}</div>`\n * html`<ul>${each(items.value, (i) => html`<li id=\"${i.id}\">${i.label}</li>`)}</ul>`\n *\n * A thin front-end over the exact machinery JSX uses — the runtime paths are\n * IDENTICAL. Text holes go through the JSX child pipeline (`_toSegment`):\n * SafeHtml/list-segment passthrough (so `each()` composes and the keyed\n * reconciler owns its rows), string escaping, number stringify, boolean /\n * nullish → nothing, signal → fine-grained text binding, DOM-node and\n * unsupported-type errors. Attribute holes go through the JSX attribute\n * branch: signal → `_assertEmittableAttrName` + `bindAttr` (grouped into one\n * marker attribute per element); anything else → the JSX attribute renderer\n * (booleans, SafeHtml, URL screening, `on*` / malformed-name rejection).\n * `mount()` / `morph()` / the reconcilers need zero changes.\n *\n * Unlike JSX, NO camelCase attribute aliasing is applied — template authors\n * write real HTML attribute names (`class`, not `className`).\n *\n * Hole contract (enforced by the parser in `utils/parseTemplate.ts`): holes\n * are allowed in text/child positions and as a COMPLETE attribute value\n * (`attr=${v}` or `attr=\"${v}\"`). Tag-name holes, attribute-name holes,\n * partial attribute values (`class=\"a ${b}\"`), and holes inside comments\n * throw. Static chunks are author-written markup and pass through verbatim\n * (same trust model as JSX tags/attrs).\n *\n * Perf: the parse runs once per template call site — the tagged-template\n * strings array has stable identity, so a `WeakMap` keyed on it caches the\n * `ParsedTemplate`. Rendering is a chunk walk with string concatenation,\n * the same cost shape as the JSX runtime.\n */\n\nimport { bindAttr, bindMarkerAttr, isSignal } from './bindings.js';\nimport {\n _assertEmittableAttrName,\n _renderAttrVerbatim,\n _toSegment,\n SafeHtml,\n} from './jsx-runtime.js';\nimport type { ReadonlySignal, Signal } from './reactive.js';\nimport { mergeChildSegments, type Segment } from './segment.js';\nimport { type ParsedTemplate, parseTemplate } from './utils/parseTemplate.js';\n\n/**\n * Values accepted in `html\\`\\`` holes — the same set JSX accepts for\n * children (text holes) and attribute values (attr holes), including a\n * signal/`computed` itself for a fine-grained binding.\n */\nexport type HtmlValue =\n | SafeHtml\n | string\n | number\n | boolean\n | null\n | undefined\n | ReadonlySignal<unknown>\n | readonly HtmlValue[];\n\nconst PARSE_CACHE = new WeakMap<TemplateStringsArray, ParsedTemplate>();\n\n// Module-level mutable counter, sanctioned as observability-only state (see\n// AGENTS.md design rule 5): it feeds the `_parseCount()` test hook that pins\n// the parse-once-per-callsite cache behavior and never influences rendering.\nlet parseCount = 0;\n\n/** Test hook: number of template parses performed (cache misses) so far. */\nexport function _parseCount(): number {\n return parseCount;\n}\n\nfunction getParsed(strings: TemplateStringsArray): ParsedTemplate {\n let parsed = PARSE_CACHE.get(strings);\n if (parsed === undefined) {\n parsed = parseTemplate(strings);\n parseCount++;\n PARSE_CACHE.set(strings, parsed);\n }\n return parsed;\n}\n\nexport function html(\n strings: TemplateStringsArray,\n ...values: HtmlValue[]\n): SafeHtml {\n const { chunks, holes, tagClose } = getParsed(strings);\n const parts: Segment[] = [];\n let buf = '';\n // Signal-attr binding ids for the currently-open element; flushed as one\n // marker attribute (`data-kfb` / `data-kfbrow`) at the tag's closing `>`,\n // mirroring the per-element grouping in `jsx()`.\n let pendingBindIds: string[] | null = null;\n\n for (let i = 0; i < chunks.length; i++) {\n let chunk = chunks[i];\n if (pendingBindIds !== null && tagClose[i] !== -1) {\n const off = tagClose[i];\n chunk = `${chunk.slice(0, off)} ${bindMarkerAttr()}=\"${pendingBindIds.join(',')}\"${chunk.slice(off)}`;\n pendingBindIds = null;\n }\n buf += chunk;\n if (i === holes.length) break;\n\n const hole = holes[i];\n const value = values[i];\n if (hole.kind === 'text') {\n const seg = _toSegment(value);\n if (seg.kind === 'static') {\n buf += seg.html;\n } else {\n parts.push({ kind: 'static', html: buf });\n buf = '';\n parts.push(seg);\n }\n } else if (isSignal(value)) {\n // Same contract as the `jsx()` signal-attribute branch: reject `on*` /\n // malformed names unconditionally (a signal's value changes over time),\n // then register the binding — or snapshot outside a mount render.\n _assertEmittableAttrName(hole.name, hole.name, false);\n const id = bindAttr(hole.name, value as Signal<unknown>);\n if (id !== null) {\n (pendingBindIds ??= []).push(id);\n } else {\n buf += _renderAttrVerbatim(\n hole.name,\n (value as Signal<unknown>).value,\n hole.tag,\n );\n }\n } else {\n buf += _renderAttrVerbatim(hole.name, value, hole.tag);\n }\n }\n if (buf !== '' || parts.length === 0)\n parts.push({ kind: 'static', html: buf });\n return new SafeHtml(mergeChildSegments(parts));\n}\n"]}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
export { A as AttrSpec, a as attr } from './attr-Cmu2ZoGO.js';
|
|
2
|
-
export { D as DelegateOptions, d as delegate, a as delegateCapture } from './delegate
|
|
2
|
+
export { D as DelegateOptions, d as delegate, a as delegateCapture } from './delegate--CrfgYtC.js';
|
|
3
3
|
import { ArraySignal } from './array-signal.js';
|
|
4
4
|
import { SafeHtml } from './jsx-runtime.js';
|
|
5
|
-
export { Fragment, isSafeHtml, raw } from './jsx-runtime.js';
|
|
5
|
+
export { Fragment, JSXChildren, isSafeHtml, raw } from './jsx-runtime.js';
|
|
6
6
|
export { M as MountResult, m as mount } from './mount-Bo2qOx25.js';
|
|
7
|
-
import { Signal } from '@preact/signals-core';
|
|
8
|
-
export { ReadonlySignal, Signal, batch
|
|
7
|
+
import { SignalOptions, ReadonlySignal, Signal } from '@preact/signals-core';
|
|
8
|
+
export { ReadonlySignal, Signal, batch } from '@preact/signals-core';
|
|
9
9
|
export { S as Store, d as defineStore, r as resetAllStores } from './testing-DNEY7wi3.js';
|
|
10
10
|
import './bindings-CYwoJpQb.js';
|
|
11
11
|
|
|
@@ -15,7 +15,7 @@ import './bindings-CYwoJpQb.js';
|
|
|
15
15
|
* later (or fronting it with a hand-rolled implementation) is a one-file
|
|
16
16
|
* change.
|
|
17
17
|
*
|
|
18
|
-
*
|
|
18
|
+
* Three dev hook slots sit in front of the bare re-exports:
|
|
19
19
|
*
|
|
20
20
|
* - `signalFactory` replaces the constructor so writes to never-subscribed
|
|
21
21
|
* signals can warn (`KERF_DEV_WARN_UNTRACKED_SIGNALS=1`).
|
|
@@ -23,18 +23,31 @@ import './bindings-CYwoJpQb.js';
|
|
|
23
23
|
* - `wrapEffect` wraps the user body so `delegate()` can detect that it's
|
|
24
24
|
* running inside an effect (`KERF_DEV_WARN_DELEGATE_IN_EFFECT=1`).
|
|
25
25
|
*
|
|
26
|
-
*
|
|
26
|
+
* - `wrapComputed` wraps a `computed()` body so the dev entry can count
|
|
27
|
+
* re-evaluations that produced no new value (`KERF_DEV_WARN_SELECTOR_FANOUT=1`,
|
|
28
|
+
* KF-AJ4KG6). `signalFactory` is its write side.
|
|
29
|
+
*
|
|
30
|
+
* All three are `undefined` unless the consumer imported `kerfjs/dev`, so production
|
|
27
31
|
* sees the bare `@preact/signals-core` exports behind one property read.
|
|
28
32
|
*
|
|
29
|
-
* ORDERING:
|
|
30
|
-
*
|
|
31
|
-
*
|
|
32
|
-
*
|
|
33
|
-
*
|
|
33
|
+
* ORDERING: all three slots are resolved at CREATION time. A signal created
|
|
34
|
+
* before `kerfjs/dev` is installed (or before `untrackedSignals` /
|
|
35
|
+
* `selectorFanout` is switched on) stays plain, an effect created before the
|
|
36
|
+
* install (or before `delegateInEffect` is switched on) is never wrapped, and
|
|
37
|
+
* neither is a computed created before `selectorFanout` is switched on. Static imports hoist
|
|
38
|
+
* above a `await import()`, so module-scope signals and effects in imported
|
|
39
|
+
* modules are created first. `mount()`'s `listenerRebuild` hook is the fourth
|
|
40
|
+
* creation-time boundary. See docs/11-dev-warnings.md §11.3.6.
|
|
34
41
|
*/
|
|
35
42
|
|
|
36
43
|
declare function signal<T>(value?: T): Signal<T>;
|
|
37
44
|
declare function effect(fn: () => void | (() => void)): () => void;
|
|
45
|
+
/**
|
|
46
|
+
* `@preact/signals-core`'s `computed()`, with the dev `wrapComputed` slot in
|
|
47
|
+
* front of the body (selector fan-out counting). `options` (`watched` /
|
|
48
|
+
* `unwatched`) are forwarded unchanged.
|
|
49
|
+
*/
|
|
50
|
+
declare function computed<T>(fn: () => T, options?: SignalOptions<T>): ReadonlySignal<T>;
|
|
38
51
|
|
|
39
52
|
/**
|
|
40
53
|
* `each(items, render, cacheKey?)` — keyed list iteration with per-item memoization.
|
|
@@ -160,7 +173,10 @@ declare function each<T extends object>(items: readonly T[] | ArraySignal<T>, re
|
|
|
160
173
|
/**
|
|
161
174
|
* Reconcile the children of `liveRoot` to match `template`.
|
|
162
175
|
*
|
|
163
|
-
*
|
|
176
|
+
* Only the children are reconciled: `liveRoot` itself is never replaced and
|
|
177
|
+
* its own attributes are never touched, so `template` describes the content
|
|
178
|
+
* that goes INSIDE the root. `template` can be an `Element` (its child nodes
|
|
179
|
+
* are used; its own tag and attributes are ignored), a `SafeHtml`, or a raw
|
|
164
180
|
* HTML string — the latter two are stringified and parsed into a transient
|
|
165
181
|
* element whose tag matches `liveRoot`. The active text-entry / focused-
|
|
166
182
|
* contenteditable preservation rules apply in all cases.
|
|
@@ -193,6 +209,75 @@ interface RenderDocumentOptions {
|
|
|
193
209
|
/** Prepend `<!DOCTYPE …>` to a rendered `SafeHtml` (or string) document and return the full HTML string. */
|
|
194
210
|
declare function renderDocument(node: SafeHtml | string, options?: RenderDocumentOptions): string;
|
|
195
211
|
|
|
212
|
+
/**
|
|
213
|
+
* `selector(source)` — keyed equality against one signal, at O(1) per change.
|
|
214
|
+
*
|
|
215
|
+
* The everyday "is this row the selected one?" pattern,
|
|
216
|
+
*
|
|
217
|
+
* className={computed(() => (row.id === selectedId.value ? 'danger' : ''))}
|
|
218
|
+
*
|
|
219
|
+
* subscribes EVERY row's computed to `selectedId`, so one write re-evaluates
|
|
220
|
+
* all N of them although only two rows change. `selector()` subscribes to the
|
|
221
|
+
* source ONCE and hands out a boolean signal per key; a source change flips
|
|
222
|
+
* only the previous key's and the next key's signals:
|
|
223
|
+
*
|
|
224
|
+
* const isSelected = selector(selectedId);
|
|
225
|
+
* <tr className={computed(() => (isSelected(row.id).value ? 'danger' : ''))}>
|
|
226
|
+
*
|
|
227
|
+
* Per-key entries exist only while something watches them. A key signal joins
|
|
228
|
+
* the closure's map when its first subscriber arrives and leaves it when its
|
|
229
|
+
* last one goes (signals-core's `watched` / `unwatched` hooks), so removing a
|
|
230
|
+
* row — which disposes its binding effects — removes its entry. The one
|
|
231
|
+
* subscription to `source` likewise exists only while at least one key is
|
|
232
|
+
* watched. A key signal handed out outside any subscriber is not cached, and
|
|
233
|
+
* a held one is always current: unsubscribed, it reads `source` lazily.
|
|
234
|
+
*
|
|
235
|
+
* Keys compare by `Map` identity (SameValueZero): primitives or object
|
|
236
|
+
* references. There is deliberately no custom equality — a comparator would
|
|
237
|
+
* need to visit every key, which is the O(N) this exists to avoid.
|
|
238
|
+
*/
|
|
239
|
+
|
|
240
|
+
/** A keyed-equality reader returned by {@link selector}. */
|
|
241
|
+
type Selector<K> = (key: K) => ReadonlySignal<boolean>;
|
|
242
|
+
/**
|
|
243
|
+
* Create a keyed-equality reader over `source`: `selector(source)(key).value`
|
|
244
|
+
* is `true` exactly when `source.value` equals `key`, and one source change
|
|
245
|
+
* notifies only the subscribers of the previous and next keys.
|
|
246
|
+
*/
|
|
247
|
+
declare function selector<K>(source: ReadonlySignal<K>): Selector<K>;
|
|
248
|
+
|
|
249
|
+
/**
|
|
250
|
+
* `setSelector(source)` — membership in one set signal, flipping only the
|
|
251
|
+
* members that changed (KF-1TFHMP).
|
|
252
|
+
*
|
|
253
|
+
* `selector()` answers "is this key THE selected one?". `setSelector()`
|
|
254
|
+
* answers "is this key IN the set?", for multi-select, a tree's expanded
|
|
255
|
+
* rows, fields with errors, or a router's active path prefixes:
|
|
256
|
+
*
|
|
257
|
+
* const checked = signal<ReadonlySet<string>>(new Set());
|
|
258
|
+
* const isChecked = setSelector(checked);
|
|
259
|
+
* <tr class={computed(() => (isChecked(row.id).value ? 'on' : ''))}>
|
|
260
|
+
*
|
|
261
|
+
* One write diffs the previous set against the next, O(|old| + |new|), and
|
|
262
|
+
* notifies only the subscribers of members that were added or removed. A
|
|
263
|
+
* new Set with the same members flips nothing. That pays off when the sets
|
|
264
|
+
* are small next to the number of subscribed keys (a few selected rows of
|
|
265
|
+
* many); for a set that holds most keys, a plain `computed` per row costs
|
|
266
|
+
* about the same.
|
|
267
|
+
*
|
|
268
|
+
* Per-key signals follow their subscribers exactly as `selector()`'s do, and
|
|
269
|
+
* membership is `Set.prototype.has` (SameValueZero).
|
|
270
|
+
*/
|
|
271
|
+
|
|
272
|
+
/** A set-membership reader returned by {@link setSelector}. */
|
|
273
|
+
type SetSelector<K> = (key: K) => ReadonlySignal<boolean>;
|
|
274
|
+
/**
|
|
275
|
+
* Create a membership reader over `source`: `setSelector(source)(key).value`
|
|
276
|
+
* is `true` exactly when `source.value.has(key)`, and one source change
|
|
277
|
+
* notifies only the subscribers of members added or removed.
|
|
278
|
+
*/
|
|
279
|
+
declare function setSelector<K>(source: ReadonlySignal<ReadonlySet<K>>): SetSelector<K>;
|
|
280
|
+
|
|
196
281
|
/**
|
|
197
282
|
* `toElement(jsx)` — JSX → DOM, with SVG-aware namespace handling.
|
|
198
283
|
*
|
|
@@ -219,4 +304,4 @@ declare function renderDocument(node: SafeHtml | string, options?: RenderDocumen
|
|
|
219
304
|
|
|
220
305
|
declare function toElement(jsx: SafeHtml | string): Element | DocumentFragment;
|
|
221
306
|
|
|
222
|
-
export { type RenderDocumentOptions, SafeHtml, each, effect, morph, renderDocument, signal, toElement };
|
|
307
|
+
export { type EachOptions, type RenderDocumentOptions, SafeHtml, type Selector, type SetSelector, computed, each, effect, morph, renderDocument, selector, setSelector, signal, toElement };
|
package/dist/index.js
CHANGED
|
@@ -1,11 +1,14 @@
|
|
|
1
|
-
|
|
2
|
-
export {
|
|
3
|
-
export {
|
|
4
|
-
export {
|
|
1
|
+
import { keyedFlags } from './chunk-KOEGJCIS.js';
|
|
2
|
+
export { setSelector } from './chunk-KOEGJCIS.js';
|
|
3
|
+
export { each, morph, mount } from './chunk-5QDM6HPD.js';
|
|
4
|
+
export { defineStore, resetAllStores } from './chunk-V322Z7FX.js';
|
|
5
|
+
export { attr } from './chunk-MK42GLPV.js';
|
|
6
|
+
export { delegate, delegateCapture } from './chunk-AP2FT33F.js';
|
|
5
7
|
|
|
6
8
|
|
|
7
|
-
export { Fragment, SafeHtml, isSafeHtml, raw } from './chunk-
|
|
8
|
-
|
|
9
|
+
export { Fragment, SafeHtml, isSafeHtml, raw } from './chunk-GGADRIQO.js';
|
|
10
|
+
import { effect } from './chunk-N4VHHOCM.js';
|
|
11
|
+
export { batch, computed, effect, signal } from './chunk-N4VHHOCM.js';
|
|
9
12
|
|
|
10
13
|
|
|
11
14
|
|
|
@@ -15,6 +18,22 @@ function renderDocument(node, options = {}) {
|
|
|
15
18
|
return `<!DOCTYPE ${doctype}>${node.toString()}`;
|
|
16
19
|
}
|
|
17
20
|
|
|
21
|
+
// src/selector.ts
|
|
22
|
+
var same = (a, b) => a === b || a !== a && b !== b;
|
|
23
|
+
function selector(source) {
|
|
24
|
+
return keyedFlags(source, same, (flip) => {
|
|
25
|
+
let current = source.peek();
|
|
26
|
+
return effect(() => {
|
|
27
|
+
const next = source.value;
|
|
28
|
+
if (same(next, current)) return;
|
|
29
|
+
const previous = current;
|
|
30
|
+
current = next;
|
|
31
|
+
flip(previous, false);
|
|
32
|
+
flip(next, true);
|
|
33
|
+
});
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
|
|
18
37
|
// src/toElement.ts
|
|
19
38
|
var SVG_NS = "http://www.w3.org/2000/svg";
|
|
20
39
|
var SVG_FRAGMENT_TAGS = /* @__PURE__ */ new Set([
|
|
@@ -31,17 +50,17 @@ var SVG_FRAGMENT_TAGS = /* @__PURE__ */ new Set([
|
|
|
31
50
|
"defs",
|
|
32
51
|
"use",
|
|
33
52
|
"symbol",
|
|
34
|
-
"
|
|
53
|
+
"clippath",
|
|
35
54
|
"mask",
|
|
36
55
|
"pattern",
|
|
37
56
|
"filter",
|
|
38
57
|
"marker",
|
|
39
|
-
"
|
|
40
|
-
"
|
|
58
|
+
"lineargradient",
|
|
59
|
+
"radialgradient",
|
|
41
60
|
"stop",
|
|
42
|
-
"
|
|
43
|
-
"foreignObject"
|
|
61
|
+
"foreignobject"
|
|
44
62
|
]);
|
|
63
|
+
var ORPHAN_SVG_IMAGE = /^\s*<image[\s/>]/i;
|
|
45
64
|
var EXCERPT_MAX_LEN = 100;
|
|
46
65
|
function excerpt(html) {
|
|
47
66
|
const trimmed = html.trim();
|
|
@@ -55,8 +74,10 @@ function parseSvgOrThrow(html, label, originalHtml) {
|
|
|
55
74
|
const doc = new DOMParser().parseFromString(html, "image/svg+xml");
|
|
56
75
|
const err = doc.querySelector("parsererror");
|
|
57
76
|
if (err !== null) {
|
|
58
|
-
throw new Error(
|
|
59
|
-
|
|
77
|
+
throw new Error(
|
|
78
|
+
`toElement: ${label} parse error \u2014 ${err.textContent}
|
|
79
|
+
input: ${excerpt(originalHtml)}`
|
|
80
|
+
);
|
|
60
81
|
}
|
|
61
82
|
return doc;
|
|
62
83
|
}
|
|
@@ -82,27 +103,34 @@ function toElement(jsx) {
|
|
|
82
103
|
if (tag === "svg") {
|
|
83
104
|
return adopt(parseSvgOrThrow(html.trim(), "SVG", html).documentElement);
|
|
84
105
|
}
|
|
85
|
-
if (SVG_FRAGMENT_TAGS.has(tag)) {
|
|
106
|
+
if (SVG_FRAGMENT_TAGS.has(tag) || tag === "img" && ORPHAN_SVG_IMAGE.test(html)) {
|
|
86
107
|
const wrapped = `<svg xmlns="${SVG_NS}">${html}</svg>`;
|
|
87
108
|
const doc = parseSvgOrThrow(wrapped, "SVG fragment", html);
|
|
88
109
|
const first = doc.documentElement.firstElementChild;
|
|
89
|
-
if (first === null)
|
|
90
|
-
|
|
110
|
+
if (first === null)
|
|
111
|
+
throw new Error(
|
|
112
|
+
`toElement: SVG fragment produced no element
|
|
113
|
+
input: ${excerpt(html)}`
|
|
114
|
+
);
|
|
91
115
|
return adopt(first);
|
|
92
116
|
}
|
|
93
117
|
return adopt(single);
|
|
94
118
|
}
|
|
95
119
|
if (content.childNodes.length === 0) {
|
|
96
|
-
throw new Error(
|
|
97
|
-
|
|
120
|
+
throw new Error(
|
|
121
|
+
`toElement: produced no element
|
|
122
|
+
input: ${excerpt(html)}`
|
|
123
|
+
);
|
|
98
124
|
}
|
|
99
125
|
if (content.children.length === 0) {
|
|
100
|
-
throw new Error(
|
|
101
|
-
|
|
126
|
+
throw new Error(
|
|
127
|
+
`toElement: produced no element
|
|
128
|
+
input: ${excerpt(html)}`
|
|
129
|
+
);
|
|
102
130
|
}
|
|
103
131
|
return adopt(content);
|
|
104
132
|
}
|
|
105
133
|
|
|
106
|
-
export { renderDocument, toElement };
|
|
134
|
+
export { renderDocument, selector, toElement };
|
|
107
135
|
|
|
108
136
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/renderDocument.ts","../src/toElement.ts"],"names":[],"mappings":";;;;;;;;;;;;AAuBO,SAAS,cAAA,CAAe,IAAA,EAAyB,OAAA,GAAiC,EAAC,EAAW;AACnG,EAAA,MAAM,EAAE,OAAA,GAAU,MAAA,EAAO,GAAI,OAAA;AAC7B,EAAA,OAAO,CAAA,UAAA,EAAa,OAAO,CAAA,CAAA,EAAI,IAAA,CAAK,UAAU,CAAA,CAAA;AAChD;;;ACAA,IAAM,MAAA,GAAS,4BAAA;AAEf,IAAM,iBAAA,uBAAwB,GAAA,CAAI;AAAA,EAChC,GAAA;AAAA,EAAK,MAAA;AAAA,EAAQ,QAAA;AAAA,EAAU,MAAA;AAAA,EAAQ,MAAA;AAAA,EAAQ,SAAA;AAAA,EAAW,UAAA;AAAA,EAAY,SAAA;AAAA,EAC9D,MAAA;AAAA,EAAQ,OAAA;AAAA,EAAS,MAAA;AAAA,EAAQ,KAAA;AAAA,EAAO,QAAA;AAAA,EAAU,UAAA;AAAA,EAAY,MAAA;AAAA,EAAQ,SAAA;AAAA,EAC9D,QAAA;AAAA,EAAU,QAAA;AAAA,EAAU,gBAAA;AAAA,EAAkB,gBAAA;AAAA,EAAkB,MAAA;AAAA,EAAQ,OAAA;AAAA,EAChE;AACF,CAAC,CAAA;AAED,IAAM,eAAA,GAAkB,GAAA;AAExB,SAAS,QAAQ,IAAA,EAAsB;AACrC,EAAA,MAAM,OAAA,GAAU,KAAK,IAAA,EAAK;AAC1B,EAAA,OAAO,OAAA,CAAQ,SAAS,eAAA,GAAkB,CAAA,EAAG,QAAQ,KAAA,C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AW,CAAA,EAAG;AAIjC,IAAA,MAAM,IAAI,KAAA,CAAM,CAAA;AAAA,SAAA,EAA4C,OAAA,CAAQ,IAAI,CAAC,CAAA,CAAE,CAAA;AAAA,EAC7E;AACA,EAAA,OAAO,MAAM,OAAO,CAAA;AACtB","file":"index.js","sourcesContent":["/**\n * `renderDocument(node)` — prepend the doctype to a rendered document.\n *\n * Every kerf SSR app ends its routes with the identical concat\n * `\"<!DOCTYPE html>\" + page.toString()`. This is that one line, blessed, so the\n * doctype isn't reinvented (or forgotten) per route.\n *\n * import { renderDocument } from 'kerfjs';\n * return c.html(renderDocument(<Page />)); // \"<!DOCTYPE html><html>…\"\n *\n * `node` is a `SafeHtml` (from JSX / the `html` tagged template) or a raw string\n * — both are stringified via `.toString()`. The optional `doctype` overrides the\n * default `'html'`.\n */\nimport type { SafeHtml } from './jsx-runtime.js';\n\n/** Options for {@link renderDocument}. */\nexport interface RenderDocumentOptions {\n /** The doctype name. Default `'html'` → `<!DOCTYPE html>`. */\n doctype?: string;\n}\n\n/** Prepend `<!DOCTYPE …>` to a rendered `SafeHtml` (or string) document and return the full HTML string. */\nexport function renderDocument(node: SafeHtml | string, options: RenderDocumentOptions = {}): string {\n const { doctype = 'html' } = options;\n return `<!DOCTYPE ${doctype}>${node.toString()}`;\n}\n","/**\n * `toElement(jsx)` — JSX → DOM, with SVG-aware namespace handling.\n *\n * Single-root inputs return an `Element`. Multi-root inputs (text + element,\n * `<><svg/> label</>`, two icons side by side, …) return a `DocumentFragment`\n * containing every top-level node. The DOM insertion APIs (`appendChild`,\n * `replaceChildren`, `append`) inline a `DocumentFragment`'s children on\n * insert, so `parent.replaceChildren(toElement(<>{ICON} label</>))` does the\n * obvious thing — parent gets the svg AND the text, no silent loss.\n *\n * The returned node is always adopted into the live `document` before it's\n * handed back (see `adopt()` below) — never left owned by the inert\n * `<template>`/`DOMParser` document it was parsed in, which is unsafe to mutate\n * before insertion on some engines.\n *\n * SVG namespacing: the HTML5 parser handles `<svg>` as foreign content\n * correctly even when wrapped in a fragment, so multi-root inputs containing\n * SVGs come out namespaced correctly via the `<template>.innerHTML` path. For\n * single-root SVG inputs the XML parser is preferred (stricter — catches\n * malformed markup the HTML5 parser would silently auto-correct). For orphan\n * SVG-namespace fragments without an `<svg>` wrapper (`<path/>`, `<g>`, …)\n * the input is wrapped in `<svg xmlns=...>` and XML-parsed.\n */\n\nimport type { SafeHtml } from './jsx-runtime.js';\n\nconst SVG_NS = 'http://www.w3.org/2000/svg';\n\nconst SVG_FRAGMENT_TAGS = new Set([\n 'g', 'path', 'circle', 'rect', 'line', 'polygon', 'polyline', 'ellipse',\n 'text', 'tspan', 'defs', 'use', 'symbol', 'clipPath', 'mask', 'pattern',\n 'filter', 'marker', 'linearGradient', 'radialGradient', 'stop', 'image',\n 'foreignObject',\n]);\n\nconst EXCERPT_MAX_LEN = 100;\n\nfunction excerpt(html: string): string {\n const trimmed = html.trim();\n return trimmed.length > EXCERPT_MAX_LEN ? `${trimmed.slice(0, EXCERPT_MAX_LEN)}…` : trimmed;\n}\n\n/**\n * Adopt `node` into the live `document` before returning it.\n *\n * Both parse paths produce nodes that belong to an *inert* document, not the\n * one the caller renders into: the `<template>.content` path yields nodes\n * owned by the template-contents owner document, and the `DOMParser` path\n * yields nodes owned by the parser's document. Returning such a node is a\n * footgun — operating on it before it's inserted (most notably `mount()`'s\n * first-render `rootEl.innerHTML = …`) runs against an inert-document element,\n * which on WebKit trips a fragment-parsing bug: under rapid bursts the parser\n * can hand back a *previous* parse's nodes, so a freshly-built element silently\n * inherits unrelated DOM. (Chromium never reproduces it; the originating\n * report was Safari-only — a feed mounting many `toElement(<div/>)` cards in\n * one flush, each painting a stale sibling's state.) `adoptNode` moves the node\n * into the live document (preserving identity and namespaces), so the returned\n * node is always safe to mutate before insertion.\n */\nfunction adopt<T extends Node>(node: T): T {\n document.adoptNode(node);\n return node;\n}\n\nfunction parseSvgOrThrow(html: string, label: string, originalHtml: string): Document {\n const doc = new DOMParser().parseFromString(html, 'image/svg+xml');\n const err = doc.querySelector('parsererror');\n if (err !== null) {\n throw new Error(`toElement: ${label} parse error — ${err.textContent}\\n input: ${excerpt(originalHtml)}`);\n }\n return doc;\n}\n\n// True when the fragment is effectively a single root — exactly one element\n// child, all sibling nodes whitespace-only text. Returns that element, else\n// null. The whitespace tolerance matches the pre-KF-232 behavior for inputs\n// like ` <svg/>\\n` (which were treated as a single SVG root).\nfunction singleRootElement(content: DocumentFragment): Element | null {\n if (content.children.length !== 1) return null;\n const onlyElement = content.firstElementChild;\n /* c8 ignore next — guarded by children.length === 1 above. */\n if (onlyElement === null) return null;\n for (const node of content.childNodes) {\n if (node === onlyElement) continue;\n if (node.nodeType !== Node.TEXT_NODE) return null;\n /* c8 ignore next — `textContent` on a TEXT_NODE is always a string; the `??` is a TypeScript-only guard. */\n if ((node.textContent ?? '').trim() !== '') return null;\n }\n return onlyElement;\n}\n\nexport function toElement(jsx: SafeHtml | string): Element | DocumentFragment {\n const html = typeof jsx === 'string' ? jsx : jsx.toString();\n\n // First pass: HTML <template> parse. This gives us correct namespacing for\n // `<svg>` (foreign content), reveals the multi-root vs single-root shape,\n // and is the universal fallback path. Orphan SVG fragments without an\n // `<svg>` wrapper are the one case that needs a different parser — handled\n // below.\n const t = document.createElement('template');\n t.innerHTML = html;\n const content = t.content;\n\n const single = singleRootElement(content);\n\n if (single !== null) {\n const tag = single.tagName.toLowerCase();\n\n // Single SVG root → re-parse via XML for strict validation. The HTML5\n // parser silently auto-corrects malformed SVG (`<svg><unclosed</svg>`),\n // which is worse than throwing. Trim so trailing whitespace in the input\n // doesn't trip up the XML parser.\n if (tag === 'svg') {\n return adopt(parseSvgOrThrow(html.trim(), 'SVG', html).documentElement);\n }\n\n // Single orphan SVG-namespace fragment (`<path/>`, `<g>`, …) — the HTML5\n // parser puts these in the XHTML namespace, so wrap in `<svg>` and\n // XML-parse to get the right namespace on the returned element.\n if (SVG_FRAGMENT_TAGS.has(tag)) {\n const wrapped = `<svg xmlns=\"${SVG_NS}\">${html}</svg>`;\n const doc = parseSvgOrThrow(wrapped, 'SVG fragment', html);\n const first = doc.documentElement.firstElementChild;\n /* c8 ignore next 2 — defensive: a successful XML parse of a wrapped svg always yields ≥1 child. */\n if (first === null) throw new Error(`toElement: SVG fragment produced no element\\n input: ${excerpt(html)}`);\n return adopt(first);\n }\n\n return adopt(single);\n }\n\n // Multi-root (or no roots): return the parsed DocumentFragment so the caller\n // can splat all the top-level nodes into their container via appendChild /\n // replaceChildren / append. If the input produced nothing at all, throw —\n // there's no useful Node to hand back.\n if (content.childNodes.length === 0) {\n throw new Error(`toElement: produced no element\\n input: ${excerpt(html)}`);\n }\n if (content.children.length === 0) {\n // No element children at all — only text or comments. Same \"no element\"\n // failure as the empty case; toElement's name implies at least one\n // element somewhere.\n throw new Error(`toElement: produced no element\\n input: ${excerpt(html)}`);\n }\n return adopt(content);\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/renderDocument.ts","../src/selector.ts","../src/toElement.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAuBO,SAAS,cAAA,CACd,IAAA,EACA,OAAA,GAAiC,EAAC,EAC1B;AACR,EAAA,MAAM,EAAE,OAAA,GAAU,MAAA,EAAO,GAAI,OAAA;AAC7B,EAAA,OAAO,CAAA,UAAA,EAAa,OAAO,CAAA,CAAA,EAAI,IAAA,CAAK,UAAU,CAAA,CAAA;AAChD;;;ACKA,IAAM,IAAA,GAAO,CAAC,CAAA,EAAY,CAAA,KACxB,MAAM,CAAA,IAAM,CAAA,KAAM,KAAK,CAAA,KAAM,CAAA;AAOxB,SAAS,SAAY,MAAA,EAAwC;AAClE,EAAA,OAAO,UAAA,CAAiB,MAAA,EAAQ,IAAA,EAAM,CAAC,IAAA,KAAS;AAC9C,IAAA,IAAI,OAAA,GAAU,OAAO,IAAA,EAAK;AAC1B,IAAA,OAAO,OAAO,MAAM;AAClB,MAAA,MAAM,OAAO,MAAA,CAAO,KAAA;AACpB,MAAA,IAAI,IAAA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erf SSR app ends its routes with the identical concat\n * `\"<!DOCTYPE html>\" + page.toString()`. This is that one line, blessed, so the\n * doctype isn't reinvented (or forgotten) per route.\n *\n * import { renderDocument } from 'kerfjs';\n * return c.html(renderDocument(<Page />)); // \"<!DOCTYPE html><html>…\"\n *\n * `node` is a `SafeHtml` (from JSX / the `html` tagged template) or a raw string\n * — both are stringified via `.toString()`. The optional `doctype` overrides the\n * default `'html'`.\n */\nimport type { SafeHtml } from './jsx-runtime.js';\n\n/** Options for {@link renderDocument}. */\nexport interface RenderDocumentOptions {\n /** The doctype name. Default `'html'` → `<!DOCTYPE html>`. */\n doctype?: string;\n}\n\n/** Prepend `<!DOCTYPE …>` to a rendered `SafeHtml` (or string) document and return the full HTML string. */\nexport function renderDocument(\n node: SafeHtml | string,\n options: RenderDocumentOptions = {},\n): string {\n const { doctype = 'html' } = options;\n return `<!DOCTYPE ${doctype}>${node.toString()}`;\n}\n","/**\n * `selector(source)` — keyed equality against one signal, at O(1) per change.\n *\n * The everyday \"is this row the selected one?\" pattern,\n *\n * className={computed(() => (row.id === selectedId.value ? 'danger' : ''))}\n *\n * subscribes EVERY row's computed to `selectedId`, so one write re-evaluates\n * all N of them although only two rows change. `selector()` subscribes to the\n * source ONCE and hands out a boolean signal per key; a source change flips\n * only the previous key's and the next key's signals:\n *\n * const isSelected = selector(selectedId);\n * <tr className={computed(() => (isSelected(row.id).value ? 'danger' : ''))}>\n *\n * Per-key entries exist only while something watches them. A key signal joins\n * the closure's map when its first subscriber arrives and leaves it when its\n * last one goes (signals-core's `watched` / `unwatched` hooks), so removing a\n * row — which disposes its binding effects — removes its entry. The one\n * subscription to `source` likewise exists only while at least one key is\n * watched. A key signal handed out outside any subscriber is not cached, and\n * a held one is always current: unsubscribed, it reads `source` lazily.\n *\n * Keys compare by `Map` identity (SameValueZero): primitives or object\n * references. There is deliberately no custom equality — a comparator would\n * need to visit every key, which is the O(N) this exists to avoid.\n */\nimport { effect, type ReadonlySignal } from './reactive.js';\nimport { keyedFlags } from './utils/keyed-flags.js';\n\n/** A keyed-equality reader returned by {@link selector}. */\nexport type Selector<K> = (key: K) => ReadonlySignal<boolean>;\n\n// SameValueZero, the comparison a Map key lookup uses.\nconst same = (a: unknown, b: unknown): boolean =>\n a === b || (a !== a && b !== b);\n\n/**\n * Create a keyed-equality reader over `source`: `selector(source)(key).value`\n * is `true` exactly when `source.value` equals `key`, and one source change\n * notifies only the subscribers of the previous and next keys.\n */\nexport function selector<K>(source: ReadonlySignal<K>): Selector<K> {\n return keyedFlags<K, K>(source, same, (flip) => {\n let current = source.peek();\n return effect(() => {\n const next = source.value;\n if (same(next, current)) return;\n const previous = current;\n current = next;\n flip(previous, false);\n flip(next, true);\n });\n });\n}\n","/**\n * `toElement(jsx)` — JSX → DOM, with SVG-aware namespace handling.\n *\n * Single-root inputs return an `Element`. Multi-root inputs (text + element,\n * `<><svg/> label</>`, two icons side by side, …) return a `DocumentFragment`\n * containing every top-level node. The DOM insertion APIs (`appendChild`,\n * `replaceChildren`, `append`) inline a `DocumentFragment`'s children on\n * insert, so `parent.replaceChildren(toElement(<>{ICON} label</>))` does the\n * obvious thing — parent gets the svg AND the text, no silent loss.\n *\n * The returned node is always adopted into the live `document` before it's\n * handed back (see `adopt()` below) — never left owned by the inert\n * `<template>`/`DOMParser` document it was parsed in, which is unsafe to mutate\n * before insertion on some engines.\n *\n * SVG namespacing: the HTML5 parser handles `<svg>` as foreign content\n * correctly even when wrapped in a fragment, so multi-root inputs containing\n * SVGs come out namespaced correctly via the `<template>.innerHTML` path. For\n * single-root SVG inputs the XML parser is preferred (stricter — catches\n * malformed markup the HTML5 parser would silently auto-correct). For orphan\n * SVG-namespace fragments without an `<svg>` wrapper (`<path/>`, `<g>`, …)\n * the input is wrapped in `<svg xmlns=...>` and XML-parsed.\n */\n\nimport type { SafeHtml } from './jsx-runtime.js';\n\nconst SVG_NS = 'http://www.w3.org/2000/svg';\n\n// Entries are lowercase: the lookup key is the HTML parser's\n// `tagName.toLowerCase()`, and the HTML parser has already folded\n// `<linearGradient>` to `lineargradient` by then. A camelCase entry would never\n// match (the orphan `clipPath` / `linearGradient` / `radialGradient` /\n// `foreignObject` fragments used to fall through to the XHTML namespace). The\n// XML re-parse restores the camelCase localName on the returned element. Keep\n// this a plain array literal — no `.map()` — so esbuild still marks the `Set`\n// pure and the whole module tree-shakes out of bundles that never import\n// `toElement`. `image` is not listed: the HTML parser rewrites `<image>` to\n// `<img>`, so it is detected from the raw input instead (see\n// `ORPHAN_SVG_IMAGE`).\nconst SVG_FRAGMENT_TAGS: ReadonlySet<string> = new Set([\n 'g',\n 'path',\n 'circle',\n 'rect',\n 'line',\n 'polygon',\n 'polyline',\n 'ellipse',\n 'text',\n 'tspan',\n 'defs',\n 'use',\n 'symbol',\n 'clippath',\n 'mask',\n 'pattern',\n 'filter',\n 'marker',\n 'lineargradient',\n 'radialgradient',\n 'stop',\n 'foreignobject',\n]);\n\n// A leading `<image` start tag (after whitespace), case-insensitive. The HTML\n// parser turns an orphan SVG `<image>` into an HTML `<img>`, so by the time\n// the tag name is inspected the only trace of the author's intent is the raw\n// input; this regex distinguishes it from a genuine `<img>`.\nconst ORPHAN_SVG_IMAGE = /^\\s*<image[\\s/>]/i;\n\nconst EXCERPT_MAX_LEN = 100;\n\nfunction excerpt(html: string): string {\n const trimmed = html.trim();\n return trimmed.length > EXCERPT_MAX_LEN\n ? `${trimmed.slice(0, EXCERPT_MAX_LEN)}…`\n : trimmed;\n}\n\n/**\n * Adopt `node` into the live `document` before returning it.\n *\n * Both parse paths produce nodes that belong to an *inert* document, not the\n * one the caller renders into: the `<template>.content` path yields nodes\n * owned by the template-contents owner document, and the `DOMParser` path\n * yields nodes owned by the parser's document. Returning such a node is a\n * footgun — operating on it before it's inserted (most notably `mount()`'s\n * first-render `rootEl.innerHTML = …`) runs against an inert-document element,\n * which on WebKit trips a fragment-parsing bug: under rapid bursts the parser\n * can hand back a *previous* parse's nodes, so a freshly-built element silently\n * inherits unrelated DOM. (Chromium never reproduces it; the originating\n * report was Safari-only — a feed mounting many `toElement(<div/>)` cards in\n * one flush, each painting a stale sibling's state.) `adoptNode` moves the node\n * into the live document (preserving identity and namespaces), so the returned\n * node is always safe to mutate before insertion.\n */\nfunction adopt<T extends Node>(node: T): T {\n document.adoptNode(node);\n return node;\n}\n\nfunction parseSvgOrThrow(\n html: string,\n label: string,\n originalHtml: string,\n): Document {\n const doc = new DOMParser().parseFromString(html, 'image/svg+xml');\n const err = doc.querySelector('parsererror');\n if (err !== null) {\n throw new Error(\n `toElement: ${label} parse error — ${err.textContent}\\n input: ${excerpt(originalHtml)}`,\n );\n }\n return doc;\n}\n\n// True when the fragment is effectively a single root — exactly one element\n// child, all sibling nodes whitespace-only text. Returns that element, else\n// null. The whitespace tolerance matches the pre-KF-232 behavior for inputs\n// like ` <svg/>\\n` (which were treated as a single SVG root).\nfunction singleRootElement(content: DocumentFragment): Element | null {\n if (content.children.length !== 1) return null;\n const onlyElement = content.firstElementChild;\n /* c8 ignore next — guarded by children.length === 1 above. */\n if (onlyElement === null) return null;\n for (const node of content.childNodes) {\n if (node === onlyElement) continue;\n if (node.nodeType !== Node.TEXT_NODE) return null;\n /* c8 ignore next — `textContent` on a TEXT_NODE is always a string; the `??` is a TypeScript-only guard. */\n if ((node.textContent ?? '').trim() !== '') return null;\n }\n return onlyElement;\n}\n\nexport function toElement(jsx: SafeHtml | string): Element | DocumentFragment {\n const html = typeof jsx === 'string' ? jsx : jsx.toString();\n\n // First pass: HTML <template> parse. This gives us correct namespacing for\n // `<svg>` (foreign content), reveals the multi-root vs single-root shape,\n // and is the universal fallback path. Orphan SVG fragments without an\n // `<svg>` wrapper are the one case that needs a different parser — handled\n // below.\n const t = document.createElement('template');\n t.innerHTML = html;\n const content = t.content;\n\n const single = singleRootElement(content);\n\n if (single !== null) {\n const tag = single.tagName.toLowerCase();\n\n // Single SVG root → re-parse via XML for strict validation. The HTML5\n // parser silently auto-corrects malformed SVG (`<svg><unclosed</svg>`),\n // which is worse than throwing. Trim so trailing whitespace in the input\n // doesn't trip up the XML parser.\n if (tag === 'svg') {\n return adopt(parseSvgOrThrow(html.trim(), 'SVG', html).documentElement);\n }\n\n // Single orphan SVG-namespace fragment (`<path/>`, `<g>`, …) — the HTML5\n // parser puts these in the XHTML namespace, so wrap in `<svg>` and\n // XML-parse to get the right namespace on the returned element.\n if (\n SVG_FRAGMENT_TAGS.has(tag) ||\n (tag === 'img' && ORPHAN_SVG_IMAGE.test(html))\n ) {\n const wrapped = `<svg xmlns=\"${SVG_NS}\">${html}</svg>`;\n const doc = parseSvgOrThrow(wrapped, 'SVG fragment', html);\n const first = doc.documentElement.firstElementChild;\n /* c8 ignore next 2 — defensive: a successful XML parse of a wrapped svg always yields ≥1 child. */\n if (first === null)\n throw new Error(\n `toElement: SVG fragment produced no element\\n input: ${excerpt(html)}`,\n );\n return adopt(first);\n }\n\n return adopt(single);\n }\n\n // Multi-root (or no roots): return the parsed DocumentFragment so the caller\n // can splat all the top-level nodes into their container via appendChild /\n // replaceChildren / append. If the input produced nothing at all, throw —\n // there's no useful Node to hand back.\n if (content.childNodes.length === 0) {\n throw new Error(\n `toElement: produced no element\\n input: ${excerpt(html)}`,\n );\n }\n if (content.children.length === 0) {\n // No element children at all — only text or comments. Same \"no element\"\n // failure as the empty case; toElement's name implies at least one\n // element somewhere.\n throw new Error(\n `toElement: produced no element\\n input: ${excerpt(html)}`,\n );\n }\n return adopt(content);\n}\n"]}
|
package/dist/jsx-runtime.d.ts
CHANGED
|
@@ -655,6 +655,11 @@ interface HTMLTrackAttrs extends KerfBaseAttrs {
|
|
|
655
655
|
}
|
|
656
656
|
interface HTMLDetailsAttrs extends KerfBaseAttrs {
|
|
657
657
|
open?: AttrLike<boolean>;
|
|
658
|
+
/**
|
|
659
|
+
* Exclusive accordion group: opening one `<details>` closes the others
|
|
660
|
+
* that share this name.
|
|
661
|
+
*/
|
|
662
|
+
name?: AttrLike<string>;
|
|
658
663
|
}
|
|
659
664
|
interface HTMLDialogAttrs extends KerfBaseAttrs {
|
|
660
665
|
open?: AttrLike<boolean>;
|
|
@@ -865,6 +870,7 @@ interface KerfBuiltinIntrinsicElements {
|
|
|
865
870
|
p: KerfBaseAttrs;
|
|
866
871
|
hr: KerfBaseAttrs;
|
|
867
872
|
br: KerfBaseAttrs;
|
|
873
|
+
wbr: KerfBaseAttrs;
|
|
868
874
|
pre: KerfBaseAttrs;
|
|
869
875
|
blockquote: HTMLBlockquoteAttrs;
|
|
870
876
|
q: HTMLQAttrs;
|
|
@@ -1133,10 +1139,12 @@ interface MixedSegment {
|
|
|
1133
1139
|
|
|
1134
1140
|
declare const SAFE_HTML_BRAND: unique symbol;
|
|
1135
1141
|
declare class SafeHtml {
|
|
1136
|
-
|
|
1142
|
+
#private;
|
|
1137
1143
|
readonly __segment: Segment;
|
|
1138
1144
|
readonly [SAFE_HTML_BRAND]: true;
|
|
1139
1145
|
constructor(input: string | Segment);
|
|
1146
|
+
/** The flattened HTML string (what `toString()` returns). */
|
|
1147
|
+
get __html(): string;
|
|
1140
1148
|
toString(): string;
|
|
1141
1149
|
}
|
|
1142
1150
|
/**
|
|
@@ -1190,12 +1198,12 @@ declare function raw(html: string): SafeHtml;
|
|
|
1190
1198
|
* Internal: build a `SafeHtml` representing a list segment. Used by
|
|
1191
1199
|
* `each()` so the JSX runtime is the sole owner of `SafeHtml` construction.
|
|
1192
1200
|
*/
|
|
1193
|
-
declare function
|
|
1201
|
+
declare function _listSafeHtml(id: string, items: ListSegment['items'], source?: object): SafeHtml;
|
|
1194
1202
|
/**
|
|
1195
1203
|
* Internal: build a `SafeHtml` representing a granular list segment with
|
|
1196
1204
|
* patches (KF-92). The reconciler applies the patches to the existing
|
|
1197
1205
|
* binding directly, skipping the per-item iteration that the snapshot
|
|
1198
|
-
* `
|
|
1206
|
+
* `_listSafeHtml` requires. `items` is included for fall-through paths
|
|
1199
1207
|
* (toString during SSR, fall-back when the binding doesn't exist yet).
|
|
1200
1208
|
*
|
|
1201
1209
|
* Patch HTML is rendered upstream (in `each()`) inside a try/catch — see
|
|
@@ -1203,11 +1211,18 @@ declare function listSafeHtml(id: string, items: ListSegment['items'], source?:
|
|
|
1203
1211
|
* already carries a `html` string, and the reconciler does no further
|
|
1204
1212
|
* row rendering.
|
|
1205
1213
|
*/
|
|
1206
|
-
declare function
|
|
1207
|
-
|
|
1208
|
-
|
|
1214
|
+
declare function _granularListSafeHtml(id: string, items: ListSegment['items'], patches: NonNullable<ListSegment['patches']>, source?: object): SafeHtml;
|
|
1215
|
+
/**
|
|
1216
|
+
* Content accepted by a Kerf JSX child position.
|
|
1217
|
+
*
|
|
1218
|
+
* Use this for `children` (and equivalent content slots) on third-party
|
|
1219
|
+
* function components. It deliberately mirrors the runtime: arrays may be
|
|
1220
|
+
* readonly and nested to any depth, signals bind fine-grained inside a mount,
|
|
1221
|
+
* and boolean/nullish values render nothing.
|
|
1222
|
+
*/
|
|
1223
|
+
type JSXChildren = SafeHtml | string | number | boolean | null | undefined | ReadonlySignal<unknown> | readonly JSXChildren[];
|
|
1209
1224
|
interface Props {
|
|
1210
|
-
children?:
|
|
1225
|
+
children?: JSXChildren;
|
|
1211
1226
|
[key: string]: unknown;
|
|
1212
1227
|
}
|
|
1213
1228
|
/**
|
|
@@ -1237,7 +1252,7 @@ declare function assertEmittableAttrName(key: string, name: string, isFn: boolea
|
|
|
1237
1252
|
declare function jsx(tag: string | ((props: Props) => SafeHtml), props: Props): SafeHtml;
|
|
1238
1253
|
|
|
1239
1254
|
declare function Fragment({ children }: {
|
|
1240
|
-
children?:
|
|
1255
|
+
children?: JSXChildren;
|
|
1241
1256
|
}): SafeHtml;
|
|
1242
1257
|
declare namespace JSX {
|
|
1243
1258
|
type Element = SafeHtml;
|
|
@@ -1258,6 +1273,6 @@ declare namespace JSX {
|
|
|
1258
1273
|
* (`class`, not `className`).
|
|
1259
1274
|
*/
|
|
1260
1275
|
declare function _toSegment(child: unknown): Segment;
|
|
1261
|
-
declare function _renderAttrVerbatim(name: string, value: unknown): string;
|
|
1276
|
+
declare function _renderAttrVerbatim(name: string, value: unknown, tag: string): string;
|
|
1262
1277
|
|
|
1263
|
-
export { type AttrLike, type AttrValue, type DataAriaAttrs, Fragment, JSX, type KerfBaseAttrs, type KerfCustomElement, SafeHtml, assertEmittableAttrName as _assertEmittableAttrName, _renderAttrVerbatim, _toSegment,
|
|
1278
|
+
export { type AttrLike, type AttrValue, type DataAriaAttrs, Fragment, JSX, type JSXChildren, type KerfBaseAttrs, type KerfCustomElement, SafeHtml, assertEmittableAttrName as _assertEmittableAttrName, _granularListSafeHtml, _listSafeHtml, _renderAttrVerbatim, _toSegment, isSafeHtml, jsx, jsx as jsxDEV, jsx as jsxs, raw };
|
package/dist/jsx-runtime.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { Fragment, SafeHtml, assertEmittableAttrName as _assertEmittableAttrName, _renderAttrVerbatim, _toSegment,
|
|
1
|
+
export { Fragment, SafeHtml, assertEmittableAttrName as _assertEmittableAttrName, _granularListSafeHtml, _listSafeHtml, _renderAttrVerbatim, _toSegment, isSafeHtml, jsx, jsx as jsxDEV, jsx as jsxs, raw } from './chunk-GGADRIQO.js';
|
|
2
2
|
|
|
3
3
|
|
|
4
4
|
|
package/dist/list.d.ts
CHANGED
|
@@ -88,7 +88,10 @@ interface BindListOptions<T> {
|
|
|
88
88
|
/**
|
|
89
89
|
* Turn on viewport virtualization. `parent` must be a scroll container (your
|
|
90
90
|
* CSS: a fixed height + `overflow: auto`). `overscan` (default 3) is how many
|
|
91
|
-
* extra rows to render above and below the viewport.
|
|
91
|
+
* extra rows to render above and below the viewport. Every height must be a
|
|
92
|
+
* finite, non-negative number of pixels (a fixed `rowHeight` must be > 0 in
|
|
93
|
+
* `'window'` mode), and `overscan` / `minRows` non-negative integers; invalid
|
|
94
|
+
* values throw a descriptive `bindList:` error.
|
|
92
95
|
*
|
|
93
96
|
* `rowHeight` (a {@link RowHeight}) is the height model:
|
|
94
97
|
* - **`number`** — every row is this fixed pixel height. O(1) windowing, no
|
|
@@ -176,8 +179,9 @@ declare function bindList<T>(parent: HTMLElement, source: ListSource<T>, options
|
|
|
176
179
|
* as the window shifts. Returns a disposer.
|
|
177
180
|
*
|
|
178
181
|
* This is the batteries-included measurement path; it is deliberately separate
|
|
179
|
-
* from `bindList` (which never
|
|
180
|
-
*
|
|
182
|
+
* from `bindList` (which never observes rows; its only `ResizeObserver` use is
|
|
183
|
+
* an optional observer on the scroll parent that re-windows on resize) — you
|
|
184
|
+
* can measure however you like and call `handle.setHeight` yourself instead. A no-op for a
|
|
181
185
|
* non-virtualized handle or where `ResizeObserver` is unavailable (SSR).
|
|
182
186
|
*
|
|
183
187
|
* const list = bindList(scrollEl, source, { key, render, virtualize: { rowHeight: { estimate: 64 } } });
|