@bettercms-ai/kit 3.1.4 → 3.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"ops.js","names":[],"sources":["../../../src/controls/rich-text/ops.ts"],"sourcesContent":["/**\n * RICH TEXT · pure DOM block operations on the editor surface (V2 HEAD controls/rich-text/ops.ts; no React, no\n * emitting). The editor wraps each one, then serializes and emits the new value.\n */\nimport { closestBlock, cloneModel, createIsland, defaultModel, esc, placeCaret, textBeforeCaret, topBlock, type IslandEl, type IslandKind, type IslandModels } from \"./dom\";\nimport type { RichTextFeature } from \"./codec\";\nimport type { BasicId } from \"./catalog\";\n\nconst emptyP = () => {\n const p = document.createElement(\"p\");\n p.innerHTML = \"<br>\";\n return p;\n};\nconst isWritable = (el: Element | null): el is HTMLElement => !!el && !el.hasAttribute(\"data-rt-island\") && el.tagName !== \"HR\";\n\n/** The writable line after a block, created when the block is last or followed by another rich block. */\nexport function ensureLineAfter(b: Element): HTMLElement {\n const next = b.nextElementSibling;\n if (isWritable(next)) return next;\n const p = emptyP();\n b.after(p);\n return p;\n}\n\nexport function duplicateBlock(b: HTMLElement): HTMLElement {\n let c: HTMLElement;\n if (b.hasAttribute(\"data-rt-island\")) {\n const k = b.getAttribute(\"data-rt-island\") as IslandKind;\n c = createIsland(k, cloneModel(k, (b as IslandEl).__rt as never));\n } else {\n c = b.cloneNode(true) as HTMLElement;\n c.removeAttribute(\"data-hint\");\n }\n b.after(c);\n return c;\n}\n\n/** Moves a block one step, keeping the caret where it was. Returns false at the edge. */\nexport function moveBlock(b: HTMLElement, dir: -1 | 1): boolean {\n const sib = dir < 0 ? b.previousElementSibling : b.nextElementSibling;\n if (!sib) return false;\n const s = window.getSelection();\n // ranges are live (a move collapses them), so keep the raw caret position\n const at = s && s.rangeCount ? { n: s.getRangeAt(0).startContainer, o: s.getRangeAt(0).startOffset } : null;\n const host = document.activeElement as HTMLElement | null;\n if (dir < 0) sib.before(b);\n else sib.after(b);\n if (at && s && b.contains(at.n)) {\n host?.focus({ preventScroll: true });\n const r = document.createRange();\n r.setStart(at.n, Math.min(at.o, at.n.nodeType === 3 ? (at.n as Text).length : at.n.childNodes.length));\n r.collapse(true);\n s.removeAllRanges();\n s.addRange(r);\n }\n return true;\n}\n\n/** Text / Heading / Quote / Code. Returns the new element, or null when nothing changed. */\nexport function turnInto(root: HTMLElement, b: HTMLElement | null, tag: string): HTMLElement | null {\n if (!b || b.parentNode !== root || b.hasAttribute(\"data-rt-island\") || b.tagName === \"HR\") return null;\n if (b.tagName.toLowerCase() === tag) return null;\n const inner =\n b.tagName === \"UL\" || b.tagName === \"OL\"\n ? Array.from(b.children).map((c) => c.innerHTML).join(\"<br>\")\n : b.tagName === \"PRE\"\n ? esc(b.textContent ?? \"\").replace(/\\n/g, \"<br>\")\n : b.innerHTML;\n const n = document.createElement(tag);\n n.innerHTML = tag === \"pre\" ? esc((b.textContent ?? \"\").replace(/​/g, \"\")) || \"<br>\" : inner || \"<br>\";\n b.replaceWith(n);\n root.focus({ preventScroll: true });\n placeCaret(n);\n return n;\n}\n\n/** An empty paragraph at the caret to build a block from (reuses the current one when it is empty). */\nexport function takeEmptyBlock(root: HTMLElement): HTMLElement {\n const s = window.getSelection();\n const anchor = s && s.rangeCount && root.contains(s.anchorNode) ? s.anchorNode : null;\n const li = anchor ? closestBlock(root, anchor) : null;\n let b = topBlock(root, anchor);\n if (li && li.tagName === \"LI\" && !li.textContent?.trim()) {\n const list = li.parentElement!;\n li.remove();\n if (!list.children.length) {\n const p = emptyP();\n list.replaceWith(p);\n b = p;\n } else b = list;\n }\n root.focus({ preventScroll: true });\n if (b && b.tagName === \"P\" && !b.textContent?.replace(/​/g, \"\").trim() && !b.querySelector(\"img\")) {\n b.innerHTML = \"<br>\";\n placeCaret(b);\n return b;\n }\n // an empty heading, quote or code line (e.g. \"/\" typed on one) is reused too, so no empty block is left behind\n if (b && /^(H[1-6]|BLOCKQUOTE|PRE)$/.test(b.tagName) && !b.textContent?.replace(/​/g, \"\").trim()) {\n const p = emptyP();\n b.replaceWith(p);\n placeCaret(p);\n return p;\n }\n const p = emptyP();\n if (b) b.after(p);\n else root.append(p);\n placeCaret(p);\n return p;\n}\n\nexport function insertIsland<K extends IslandKind>(root: HTMLElement, kind: K, model: IslandModels[K] = defaultModel(kind)): IslandEl {\n const target = takeEmptyBlock(root);\n const isl = createIsland(kind, model);\n // A table of contents is built from the headings: nothing in it is typed first, so the caret goes on in the\n // paragraph after it (RP-054: it sat in the title, and the next \"/pull\" was typed into \"In this article\").\n isl.__rtFocus = kind !== \"toc\";\n target.before(isl);\n // keep the document tidy: reuse the line that already follows instead of leaving an empty one\n const next = target.nextElementSibling;\n if (isWritable(next)) {\n target.remove();\n placeCaret(next, false);\n } else placeCaret(target);\n return isl;\n}\n\n/** Inserts a basic block at the caret. */\nexport function insertBasic(root: HTMLElement, id: BasicId) {\n switch (id) {\n case \"p\":\n takeEmptyBlock(root);\n return;\n case \"h1\": case \"h2\": case \"h3\": case \"h4\": case \"h5\": case \"h6\":\n turnInto(root, takeEmptyBlock(root), id);\n return;\n case \"quote\":\n turnInto(root, takeEmptyBlock(root), \"blockquote\");\n return;\n case \"code\":\n turnInto(root, takeEmptyBlock(root), \"pre\");\n return;\n case \"ul\": case \"ol\": {\n const t = takeEmptyBlock(root);\n const l = document.createElement(id);\n l.innerHTML = \"<li><br></li>\";\n t.replaceWith(l);\n placeCaret(l.firstElementChild!);\n return;\n }\n case \"hr\": {\n const t = takeEmptyBlock(root);\n t.before(document.createElement(\"hr\"));\n placeCaret(t);\n return;\n }\n case \"image\": case \"table\": case \"pullquote\": case \"takeaways\": case \"callout\": case \"toggle\": case \"video\": case \"file\":\n case \"gallery\": case \"embed\": case \"toc\": case \"columns\": case \"related\": case \"author\":\n insertIsland(root, id);\n return;\n }\n}\n\n/**\n * \"# \", \"> \", \"- \", \"1. \" and \"---\" at the start of a paragraph, each only when the field accepts what it makes.\n * Returns true when it converted.\n */\nexport function liveMarkdown(root: HTMLElement, data: string | null, allows: (f: RichTextFeature) => boolean = () => true): boolean {\n const s = window.getSelection();\n if (!s || !s.rangeCount || !s.isCollapsed) return false;\n const blk = topBlock(root, s.anchorNode);\n if (!blk || blk.tagName !== \"P\") return false;\n const before = textBeforeCaret(blk)?.replace(/ /g, \" \");\n if (before == null) return false;\n if (data === \"-\" && before === \"---\" && (blk.textContent ?? \"\").replace(/ /g, \" \") === \"---\") {\n if (!allows(\"hr\")) return false;\n const p = emptyP();\n blk.replaceWith(document.createElement(\"hr\"), p);\n placeCaret(p);\n return true;\n }\n if (data !== \" \") return false;\n const h = before.match(/^(#{1,6}) $/);\n let tag = h ? `h${h[1].length}` : before === \"> \" ? \"blockquote\" : null;\n let list = before === \"- \" || before === \"* \" ? \"ul\" : /^1[.)] $/.test(before) ? \"ol\" : null;\n if (tag && !allows(tag as RichTextFeature)) tag = null;\n if (list && !allows(list as RichTextFeature)) list = null;\n if (!tag && !list) return false;\n const r = document.createRange();\n r.selectNodeContents(blk);\n r.setEnd(s.anchorNode!, s.anchorOffset);\n r.deleteContents();\n const html = blk.textContent || blk.querySelector(\"img\") ? blk.innerHTML : \"<br>\";\n let target: HTMLElement;\n if (tag) {\n target = document.createElement(tag);\n target.innerHTML = html;\n blk.replaceWith(target);\n } else {\n const l = document.createElement(list!);\n target = document.createElement(\"li\");\n target.innerHTML = html;\n l.append(target);\n blk.replaceWith(l);\n }\n placeCaret(target, false);\n return true;\n}\n\n/** `text` typed between backticks becomes inline code. */\nexport function liveInlineCode(): boolean {\n const s = window.getSelection();\n if (!s || !s.rangeCount || !s.isCollapsed) return false;\n const r = s.getRangeAt(0);\n if (r.startContainer.nodeType !== 3 || r.startContainer.parentElement?.closest(\"code,pre\")) return false;\n const node = r.startContainer as Text;\n const m = node.data.slice(0, r.startOffset).match(/`([^`\\n]+)`$/);\n if (!m) return false;\n wrapTypedRun(s, node, r.startOffset, m[0].length, \"code\", m[1]);\n return true;\n}\n\n/**\n * RT-030: `**text**` becomes bold and `*text*` / `_text_` italic, run as the closing marker is typed (as\n * `liveInlineCode` is for the backtick), each only where the field accepts the mark. The first closing `*` of a\n * `**bold**` being typed is not an italic (its run starts with another `*`), and `_` inside a word (`snake_case_`)\n * stays as typed. Nothing inside code converts.\n */\nexport function liveInlineEmphasis(data: string | null, allows: (f: RichTextFeature) => boolean = () => true): boolean {\n if (data !== \"*\" && data !== \"_\") return false;\n const s = window.getSelection();\n if (!s || !s.rangeCount || !s.isCollapsed) return false;\n const r = s.getRangeAt(0);\n if (r.startContainer.nodeType !== 3 || r.startContainer.parentElement?.closest(\"code,pre\")) return false;\n const node = r.startContainer as Text;\n const before = node.data.slice(0, r.startOffset);\n const bold = data === \"*\" && allows(\"bold\") ? before.match(/\\*\\*([^*\\n]+)\\*\\*$/) : null;\n if (bold) {\n wrapTypedRun(s, node, r.startOffset, bold[0].length, \"strong\", bold[1]);\n return true;\n }\n if (!allows(\"italic\")) return false;\n const italic = data === \"*\" ? before.match(/(?:^|[^*])\\*([^*\\n]+)\\*$/) : before.match(/(?:^|[^\\w_])_([^_\\n]+)_$/);\n if (!italic) return false;\n // the match may start with the character before the opening marker: only the marked run is replaced\n const run = italic[0].replace(/^[^*_]/, \"\");\n wrapTypedRun(s, node, r.startOffset, run.length, \"em\", italic[1]);\n return true;\n}\n\n/* ── RT-028: list levels (Tab / Shift+Tab in a list item) ── */\n\n/**\n * Run `move` and put the caret back where it was. Moving a node takes the selection out of it, and a cloned Range is\n * live too (the DOM moves it to the old parent on removal), so the caret is kept as its plain node and offsets.\n */\nfunction keepingCaret(move: () => void): void {\n const s = window.getSelection();\n const at = s && s.rangeCount && s.anchorNode && s.focusNode ? [s.anchorNode, s.anchorOffset, s.focusNode, s.focusOffset] as const : null;\n move();\n if (s && at) s.setBaseAndExtent(at[0], at[1], at[2], at[3]);\n}\n\n/**\n * Tab: nest `li` one level deeper, under the item before it, in a list of the same kind (`ul` / `ol`). The\n * previous item's own nested list of that kind takes it when it has one. False (nothing moves) for the first item:\n * there is no item to nest under.\n */\nexport function indentListItem(li: HTMLElement): boolean {\n const list = li.parentElement;\n const prev = li.previousElementSibling as HTMLElement | null;\n if (!list || !/^(UL|OL)$/.test(list.tagName) || !prev || prev.tagName !== \"LI\") return false;\n keepingCaret(() => {\n const last = prev.lastElementChild;\n const nested = last && last.tagName === list.tagName ? last : prev.appendChild(document.createElement(list.tagName.toLowerCase()));\n nested.append(li);\n });\n return true;\n}\n\n/**\n * Shift+Tab: bring a nested `li` up one level, right after the item that held it. The items after it in its list stay\n * after it, nested under it, so the reading order never changes; an emptied nested list goes. False for an item\n * already at the top level.\n */\nexport function outdentListItem(li: HTMLElement): boolean {\n const list = li.parentElement;\n const parentLi = list?.parentElement;\n if (!list || !/^(UL|OL)$/.test(list.tagName) || !parentLi || parentLi.tagName !== \"LI\") return false;\n keepingCaret(() => {\n const after: Element[] = [];\n for (let n = li.nextElementSibling; n; n = n.nextElementSibling) after.push(n);\n if (after.length) {\n const own = li.lastElementChild && li.lastElementChild.tagName === list.tagName ? li.lastElementChild : li.appendChild(document.createElement(list.tagName.toLowerCase()));\n own.append(...after);\n }\n parentLi.after(li);\n if (!list.children.length) list.remove();\n });\n return true;\n}\n\n/** Replace the `length` characters typed before `end` in `node` with `<tag>text</tag>`, the caret after it. */\nfunction wrapTypedRun(s: Selection, node: Text, end: number, length: number, tag: \"code\" | \"strong\" | \"em\", text: string): void {\n const del = document.createRange();\n del.setStart(node, end - length);\n del.setEnd(node, end);\n del.deleteContents();\n const el = document.createElement(tag);\n el.textContent = text;\n del.insertNode(el);\n const next = el.nextSibling;\n if (next && next.nodeType === 3 && next.textContent) {\n const c = document.createRange();\n c.setStart(next, 0);\n c.collapse(true);\n s.removeAllRanges();\n s.addRange(c);\n } else {\n const after = document.createTextNode(\"​\");\n el.after(after);\n placeCaret(after);\n }\n}\n\n/* ── What a field accepts, applied to HTML that arrives from outside (paste, Markdown) ── */\nconst MARK_FEATURE: Record<string, RichTextFeature> = {\n STRONG: \"bold\", B: \"bold\", EM: \"italic\", I: \"italic\", U: \"underline\", S: \"strike\", STRIKE: \"strike\", DEL: \"strike\", CODE: \"code\", A: \"link\",\n};\nconst BLOCK_FEATURE: Record<string, RichTextFeature> = {\n H1: \"h1\", H2: \"h2\", H3: \"h3\", H4: \"h4\", H5: \"h5\", H6: \"h6\", BLOCKQUOTE: \"blockquote\", UL: \"ul\", OL: \"ol\", PRE: \"pre\", HR: \"hr\", FIGURE: \"image\", IMG: \"image\",\n};\nconst FEATURE_WORD: Partial<Record<RichTextFeature, string>> = {\n image: \"images\", hr: \"dividers\", pre: \"code blocks\", ul: \"bulleted lists\", ol: \"numbered lists\", blockquote: \"quotes\", link: \"links\",\n};\n\n/**\n * HTML with every element the field does not accept turned into what it does: a heading / quote / code block becomes a\n * paragraph, a list becomes one paragraph per item, a mark or link is unwrapped to its text, a divider or image is\n * removed. `dropped` names what was taken out entirely (said to the author, never silent).\n */\n/**\n * RT-016: HTML from another page as this editor takes it, before `restrictHtml` keeps it to the field. Classes, inline\n * styles and ids are the source page's look, not content: only a link's address is kept. A wrapper that is only styling\n * (a span, a font, Google Docs' `<b style=\"font-weight:normal\">` around a whole paste) is unwrapped to its contents. A\n * picture is taken out when `dropImages` (the field holds images, but a pasted address is not a media-library image);\n * otherwise it is left for `restrictHtml`, which removes it and says so. `images` counts what was taken out here.\n */\nexport function pastedHtml(html: string, dropImages: boolean): { html: string; images: number } {\n const doc = new DOMParser().parseFromString(`<body>${html}</body>`, \"text/html\");\n doc.body.querySelectorAll(\"script,style,meta,link,title,iframe,object,embed,form,input,button,textarea,select,noscript,template\").forEach((n) => n.remove());\n let images = 0;\n if (dropImages) {\n doc.body.querySelectorAll(\"picture,figure,img\").forEach((n) => {\n if (!n.isConnected) return;\n if (n.tagName === \"IMG\" || n.querySelector(\"img\")) images++;\n n.remove();\n });\n }\n const unwrap = (el: Element) => el.replaceWith(...Array.from(el.childNodes));\n for (const el of Array.from(doc.body.querySelectorAll(\"*\")).reverse()) {\n if (el.tagName === \"SPAN\" || el.tagName === \"FONT\" || ((el.tagName === \"B\" || el.tagName === \"STRONG\") && /font-weight\\s*:\\s*(normal|400)/i.test(el.getAttribute(\"style\") ?? \"\"))) {\n unwrap(el);\n continue;\n }\n for (const a of Array.from(el.attributes)) {\n const keep = (el.tagName === \"A\" && a.name === \"href\") || (el.tagName === \"IMG\" && (a.name === \"src\" || a.name === \"alt\"));\n if (!keep) el.removeAttribute(a.name);\n }\n }\n return { html: doc.body.innerHTML.trim(), images };\n}\n\nexport function restrictHtml(html: string, allows: (f: RichTextFeature) => boolean): { html: string; dropped: string[] } {\n if (!html) return { html, dropped: [] };\n const doc = new DOMParser().parseFromString(`<body>${html}</body>`, \"text/html\");\n const dropped = new Set<string>();\n const walk = (el: Element) => {\n for (const ch of Array.from(el.children)) {\n walk(ch);\n const mark = MARK_FEATURE[ch.tagName];\n const block = BLOCK_FEATURE[ch.tagName];\n if (mark && !allows(mark)) ch.replaceWith(...Array.from(ch.childNodes));\n else if (block && !allows(block)) {\n if (block === \"hr\" || block === \"image\") {\n dropped.add(FEATURE_WORD[block]!);\n ch.remove();\n } else if (block === \"ul\" || block === \"ol\") {\n const ps = Array.from(ch.children).map((li) => {\n const p = doc.createElement(\"p\");\n p.innerHTML = li.innerHTML;\n return p;\n });\n ch.replaceWith(...ps);\n } else {\n const p = doc.createElement(\"p\");\n p.innerHTML = block === \"pre\" ? esc(ch.textContent ?? \"\").replace(/\\n/g, \"<br>\") : ch.innerHTML;\n ch.replaceWith(p);\n }\n }\n }\n };\n walk(doc.body);\n return { html: doc.body.innerHTML, dropped: [...dropped] };\n}\n"],"mappings":";;;;;;AAQA,IAAM,eAAe;CACnB,MAAM,IAAI,SAAS,cAAc,GAAG;CACpC,EAAE,YAAY;CACd,OAAO;AACT;AACA,IAAM,cAAc,OAA0C,CAAC,CAAC,MAAM,CAAC,GAAG,aAAa,gBAAgB,KAAK,GAAG,YAAY;;AAG3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TEXT · pure DOM block operations on the editor surface (V2 HEAD controls/rich-text/ops.ts; no React, no\n * emitting). The editor wraps each one, then serializes and emits the new value.\n */\nimport { closestBlock, cloneModel, createIsland, defaultModel, esc, placeCaret, textBeforeCaret, topBlock, type IslandEl, type IslandKind, type IslandModels } from \"./dom\";\nimport type { RichTextFeature } from \"./codec\";\nimport type { BasicId } from \"./catalog\";\n\nconst emptyP = () => {\n const p = document.createElement(\"p\");\n p.innerHTML = \"<br>\";\n return p;\n};\nconst isWritable = (el: Element | null): el is HTMLElement => !!el && !el.hasAttribute(\"data-rt-island\") && el.tagName !== \"HR\";\n\n/** The writable line after a block, created when the block is last or followed by another rich block. */\nexport function ensureLineAfter(b: Element): HTMLElement {\n const next = b.nextElementSibling;\n if (isWritable(next)) return next;\n const p = emptyP();\n b.after(p);\n return p;\n}\n\nexport function duplicateBlock(b: HTMLElement): HTMLElement {\n let c: HTMLElement;\n if (b.hasAttribute(\"data-rt-island\")) {\n const k = b.getAttribute(\"data-rt-island\") as IslandKind;\n c = createIsland(k, cloneModel(k, (b as IslandEl).__rt as never));\n } else {\n c = b.cloneNode(true) as HTMLElement;\n c.removeAttribute(\"data-hint\");\n }\n b.after(c);\n return c;\n}\n\n/** Moves a block one step, keeping the caret where it was. Returns false at the edge. */\nexport function moveBlock(b: HTMLElement, dir: -1 | 1): boolean {\n const sib = dir < 0 ? b.previousElementSibling : b.nextElementSibling;\n if (!sib) return false;\n const s = window.getSelection();\n // ranges are live (a move collapses them), so keep the raw caret position\n const at = s && s.rangeCount ? { n: s.getRangeAt(0).startContainer, o: s.getRangeAt(0).startOffset } : null;\n const host = document.activeElement as HTMLElement | null;\n if (dir < 0) sib.before(b);\n else sib.after(b);\n if (at && s && b.contains(at.n)) {\n host?.focus({ preventScroll: true });\n const r = document.createRange();\n r.setStart(at.n, Math.min(at.o, at.n.nodeType === 3 ? (at.n as Text).length : at.n.childNodes.length));\n r.collapse(true);\n s.removeAllRanges();\n s.addRange(r);\n }\n return true;\n}\n\n/** Text / Heading / Quote / Code. Returns the new element, or null when nothing changed. */\nexport function turnInto(root: HTMLElement, b: HTMLElement | null, tag: string): HTMLElement | null {\n if (!b || b.parentNode !== root || b.hasAttribute(\"data-rt-island\") || b.tagName === \"HR\") return null;\n if (b.tagName.toLowerCase() === tag) return null;\n const inner =\n b.tagName === \"UL\" || b.tagName === \"OL\"\n ? Array.from(b.children).map((c) => c.innerHTML).join(\"<br>\")\n : b.tagName === \"PRE\"\n ? esc(b.textContent ?? \"\").replace(/\\n/g, \"<br>\")\n : b.innerHTML;\n const n = document.createElement(tag);\n n.innerHTML = tag === \"pre\" ? esc((b.textContent ?? \"\").replace(/​/g, \"\")) || \"<br>\" : inner || \"<br>\";\n b.replaceWith(n);\n root.focus({ preventScroll: true });\n placeCaret(n);\n return n;\n}\n\n/** An empty paragraph at the caret to build a block from (reuses the current one when it is empty). */\nexport function takeEmptyBlock(root: HTMLElement): HTMLElement {\n const s = window.getSelection();\n const anchor = s && s.rangeCount && root.contains(s.anchorNode) ? s.anchorNode : null;\n const li = anchor ? closestBlock(root, anchor) : null;\n let b = topBlock(root, anchor);\n if (li && li.tagName === \"LI\" && !li.textContent?.trim()) {\n const list = li.parentElement!;\n li.remove();\n if (!list.children.length) {\n const p = emptyP();\n list.replaceWith(p);\n b = p;\n } else b = list;\n }\n root.focus({ preventScroll: true });\n if (b && b.tagName === \"P\" && !b.textContent?.replace(/​/g, \"\").trim() && !b.querySelector(\"img\")) {\n b.innerHTML = \"<br>\";\n placeCaret(b);\n return b;\n }\n // an empty heading, quote or code line (e.g. \"/\" typed on one) is reused too, so no empty block is left behind\n if (b && /^(H[1-6]|BLOCKQUOTE|PRE)$/.test(b.tagName) && !b.textContent?.replace(/​/g, \"\").trim()) {\n const p = emptyP();\n b.replaceWith(p);\n placeCaret(p);\n return p;\n }\n const p = emptyP();\n if (b) b.after(p);\n else root.append(p);\n placeCaret(p);\n return p;\n}\n\nexport function insertIsland<K extends IslandKind>(root: HTMLElement, kind: K, model: IslandModels[K] = defaultModel(kind)): IslandEl {\n const target = takeEmptyBlock(root);\n const isl = createIsland(kind, model);\n // A table of contents is built from the headings: nothing in it is typed first, so the caret goes on in the\n // paragraph after it (RP-054: it sat in the title, and the next \"/pull\" was typed into \"In this article\").\n isl.__rtFocus = kind !== \"toc\";\n target.before(isl);\n // keep the document tidy: reuse the line that already follows instead of leaving an empty one\n const next = target.nextElementSibling;\n if (isWritable(next)) {\n target.remove();\n placeCaret(next, false);\n } else placeCaret(target);\n return isl;\n}\n\n/** Inserts a basic block at the caret. */\nexport function insertBasic(root: HTMLElement, id: BasicId) {\n switch (id) {\n case \"p\":\n takeEmptyBlock(root);\n return;\n case \"h1\": case \"h2\": case \"h3\": case \"h4\": case \"h5\": case \"h6\":\n turnInto(root, takeEmptyBlock(root), id);\n return;\n case \"quote\":\n turnInto(root, takeEmptyBlock(root), \"blockquote\");\n return;\n case \"code\":\n turnInto(root, takeEmptyBlock(root), \"pre\");\n return;\n case \"ul\": case \"ol\": {\n const t = takeEmptyBlock(root);\n const l = document.createElement(id);\n l.innerHTML = \"<li><br></li>\";\n t.replaceWith(l);\n placeCaret(l.firstElementChild!);\n return;\n }\n case \"hr\": {\n const t = takeEmptyBlock(root);\n t.before(document.createElement(\"hr\"));\n placeCaret(t);\n return;\n }\n case \"image\": case \"table\": case \"pullquote\": case \"takeaways\": case \"callout\": case \"toggle\": case \"video\": case \"file\":\n case \"gallery\": case \"embed\": case \"toc\": case \"columns\": case \"related\": case \"author\":\n insertIsland(root, id);\n return;\n }\n}\n\n/**\n * \"# \", \"> \", \"- \", \"1. \" and \"---\" at the start of a paragraph, each only when the field accepts what it makes.\n * Returns true when it converted.\n */\nexport function liveMarkdown(root: HTMLElement, data: string | null, allows: (f: RichTextFeature) => boolean = () => true): boolean {\n const s = window.getSelection();\n if (!s || !s.rangeCount || !s.isCollapsed) return false;\n const blk = topBlock(root, s.anchorNode);\n if (!blk || blk.tagName !== \"P\") return false;\n const before = textBeforeCaret(blk)?.replace(/ /g, \" \");\n if (before == null) return false;\n if (data === \"-\" && before === \"---\" && (blk.textContent ?? \"\").replace(/ /g, \" \") === \"---\") {\n if (!allows(\"hr\")) return false;\n const p = emptyP();\n blk.replaceWith(document.createElement(\"hr\"), p);\n placeCaret(p);\n return true;\n }\n if (data !== \" \") return false;\n const h = before.match(/^(#{1,6}) $/);\n let tag = h ? `h${h[1].length}` : before === \"> \" ? \"blockquote\" : null;\n let list = before === \"- \" || before === \"* \" ? \"ul\" : /^1[.)] $/.test(before) ? \"ol\" : null;\n if (tag && !allows(tag as RichTextFeature)) tag = null;\n if (list && !allows(list as RichTextFeature)) list = null;\n if (!tag && !list) return false;\n const r = document.createRange();\n r.selectNodeContents(blk);\n r.setEnd(s.anchorNode!, s.anchorOffset);\n r.deleteContents();\n const html = blk.textContent || blk.querySelector(\"img\") ? blk.innerHTML : \"<br>\";\n let target: HTMLElement;\n if (tag) {\n target = document.createElement(tag);\n target.innerHTML = html;\n blk.replaceWith(target);\n } else {\n const l = document.createElement(list!);\n target = document.createElement(\"li\");\n target.innerHTML = html;\n l.append(target);\n blk.replaceWith(l);\n }\n placeCaret(target, false);\n return true;\n}\n\n/** `text` typed between backticks becomes inline code. */\nexport function liveInlineCode(): boolean {\n const s = window.getSelection();\n if (!s || !s.rangeCount || !s.isCollapsed) return false;\n const r = s.getRangeAt(0);\n if (r.startContainer.nodeType !== 3 || r.startContainer.parentElement?.closest(\"code,pre\")) return false;\n const node = r.startContainer as Text;\n const m = node.data.slice(0, r.startOffset).match(/`([^`\\n]+)`$/);\n if (!m) return false;\n wrapTypedRun(s, node, r.startOffset, m[0].length, \"code\", m[1]);\n return true;\n}\n\n/**\n * RT-030: `**text**` becomes bold and `*text*` / `_text_` italic, run as the closing marker is typed (as\n * `liveInlineCode` is for the backtick), each only where the field accepts the mark. The first closing `*` of a\n * `**bold**` being typed is not an italic (its run starts with another `*`), and `_` inside a word (`snake_case_`)\n * stays as typed. Nothing inside code converts.\n */\nexport function liveInlineEmphasis(data: string | null, allows: (f: RichTextFeature) => boolean = () => true): boolean {\n if (data !== \"*\" && data !== \"_\") return false;\n const s = window.getSelection();\n if (!s || !s.rangeCount || !s.isCollapsed) return false;\n const r = s.getRangeAt(0);\n if (r.startContainer.nodeType !== 3 || r.startContainer.parentElement?.closest(\"code,pre\")) return false;\n const node = r.startContainer as Text;\n const before = node.data.slice(0, r.startOffset);\n const bold = data === \"*\" && allows(\"bold\") ? before.match(/\\*\\*([^*\\n]+)\\*\\*$/) : null;\n if (bold) {\n wrapTypedRun(s, node, r.startOffset, bold[0].length, \"strong\", bold[1]);\n return true;\n }\n if (!allows(\"italic\")) return false;\n const italic = data === \"*\" ? before.match(/(?:^|[^*])\\*([^*\\n]+)\\*$/) : before.match(/(?:^|[^\\w_])_([^_\\n]+)_$/);\n if (!italic) return false;\n // the match may start with the character before the opening marker: only the marked run is replaced\n const run = italic[0].replace(/^[^*_]/, \"\");\n wrapTypedRun(s, node, r.startOffset, run.length, \"em\", italic[1]);\n return true;\n}\n\n/* ── RT-028: list levels (Tab / Shift+Tab in a list item) ── */\n\n/**\n * Run `move` and put the caret back where it was. Moving a node takes the selection out of it, and a cloned Range is\n * live too (the DOM moves it to the old parent on removal), so the caret is kept as its plain node and offsets.\n */\nfunction keepingCaret(move: () => void): void {\n const s = window.getSelection();\n const at = s && s.rangeCount && s.anchorNode && s.focusNode ? [s.anchorNode, s.anchorOffset, s.focusNode, s.focusOffset] as const : null;\n move();\n if (s && at) s.setBaseAndExtent(at[0], at[1], at[2], at[3]);\n}\n\n/**\n * Tab: nest `li` one level deeper, under the item before it, in a list of the same kind (`ul` / `ol`). The\n * previous item's own nested list of that kind takes it when it has one. False (nothing moves) for the first item:\n * there is no item to nest under.\n */\nexport function indentListItem(li: HTMLElement): boolean {\n const list = li.parentElement;\n const prev = li.previousElementSibling as HTMLElement | null;\n if (!list || !/^(UL|OL)$/.test(list.tagName) || !prev || prev.tagName !== \"LI\") return false;\n keepingCaret(() => {\n const last = prev.lastElementChild;\n const nested = last && last.tagName === list.tagName ? last : prev.appendChild(document.createElement(list.tagName.toLowerCase()));\n nested.append(li);\n });\n return true;\n}\n\n/**\n * Shift+Tab: bring a nested `li` up one level, right after the item that held it. The items after it in its list stay\n * after it, nested under it, so the reading order never changes; an emptied nested list goes. False for an item\n * already at the top level.\n */\nexport function outdentListItem(li: HTMLElement): boolean {\n const list = li.parentElement;\n const parentLi = list?.parentElement;\n if (!list || !/^(UL|OL)$/.test(list.tagName) || !parentLi || parentLi.tagName !== \"LI\") return false;\n keepingCaret(() => {\n const after: Element[] = [];\n for (let n = li.nextElementSibling; n; n = n.nextElementSibling) after.push(n);\n if (after.length) {\n const own = li.lastElementChild && li.lastElementChild.tagName === list.tagName ? li.lastElementChild : li.appendChild(document.createElement(list.tagName.toLowerCase()));\n own.append(...after);\n }\n parentLi.after(li);\n if (!list.children.length) list.remove();\n });\n return true;\n}\n\n/** Replace the `length` characters typed before `end` in `node` with `<tag>text</tag>`, the caret after it. */\nfunction wrapTypedRun(s: Selection, node: Text, end: number, length: number, tag: \"code\" | \"strong\" | \"em\", text: string): void {\n const del = document.createRange();\n del.setStart(node, end - length);\n del.setEnd(node, end);\n del.deleteContents();\n const el = document.createElement(tag);\n el.textContent = text;\n del.insertNode(el);\n const next = el.nextSibling;\n if (next && next.nodeType === 3 && next.textContent) {\n const c = document.createRange();\n c.setStart(next, 0);\n c.collapse(true);\n s.removeAllRanges();\n s.addRange(c);\n } else {\n const after = document.createTextNode(\"​\");\n el.after(after);\n placeCaret(after);\n }\n}\n\n/* ── What a field accepts, applied to HTML that arrives from outside (paste, Markdown) ── */\nconst MARK_FEATURE: Record<string, RichTextFeature> = {\n STRONG: \"bold\", B: \"bold\", EM: \"italic\", I: \"italic\", U: \"underline\", S: \"strike\", STRIKE: \"strike\", DEL: \"strike\", CODE: \"code\", A: \"link\",\n};\nconst BLOCK_FEATURE: Record<string, RichTextFeature> = {\n H1: \"h1\", H2: \"h2\", H3: \"h3\", H4: \"h4\", H5: \"h5\", H6: \"h6\", BLOCKQUOTE: \"blockquote\", UL: \"ul\", OL: \"ol\", PRE: \"pre\", HR: \"hr\", FIGURE: \"image\", IMG: \"image\",\n};\nconst FEATURE_WORD: Partial<Record<RichTextFeature, string>> = {\n image: \"images\", hr: \"dividers\", pre: \"code blocks\", ul: \"bulleted lists\", ol: \"numbered lists\", blockquote: \"quotes\", link: \"links\",\n};\n\n/**\n * HTML with every element the field does not accept turned into what it does: a heading / quote / code block becomes a\n * paragraph, a list becomes one paragraph per item, a mark or link is unwrapped to its text, a divider or image is\n * removed. `dropped` names what was taken out entirely (said to the author, never silent).\n */\n/**\n * RT-016: HTML from another page as this editor takes it, before `restrictHtml` keeps it to the field. Classes, inline\n * styles and ids are the source page's look, not content: only a link's address is kept. A wrapper that is only styling\n * (a span, a font, Google Docs' `<b style=\"font-weight:normal\">` around a whole paste) is unwrapped to its contents. A\n * picture is taken out when `dropImages` (the field holds images, but a pasted address is not a media-library image);\n * otherwise it is left for `restrictHtml`, which removes it and says so. `images` counts what was taken out here.\n */\nexport function pastedHtml(html: string, dropImages: boolean): { html: string; images: number } {\n const doc = new DOMParser().parseFromString(`<body>${html}</body>`, \"text/html\");\n doc.body.querySelectorAll(\"script,style,meta,link,title,iframe,object,embed,form,input,button,textarea,select,noscript,template\").forEach((n) => n.remove());\n let images = 0;\n if (dropImages) {\n doc.body.querySelectorAll(\"picture,figure,img\").forEach((n) => {\n if (!n.isConnected) return;\n if (n.tagName === \"IMG\" || n.querySelector(\"img\")) images++;\n n.remove();\n });\n }\n for (const el of Array.from(doc.body.querySelectorAll(\"*\")).reverse()) {\n if (el.tagName === \"SPAN\" || el.tagName === \"FONT\" || ((el.tagName === \"B\" || el.tagName === \"STRONG\") && /font-weight\\s*:\\s*(normal|400)/i.test(el.getAttribute(\"style\") ?? \"\"))) {\n // RT-015: Google Docs writes bold / italic / underline / strike as a span's inline style, not a tag.\n const style = el.tagName === \"SPAN\" ? (el.getAttribute(\"style\") ?? \"\") : \"\";\n let inner: Node[] = Array.from(el.childNodes);\n const wrap = (tag: string) => {\n const w = doc.createElement(tag);\n w.append(...inner);\n inner = [w];\n };\n if (/font-weight\\s*:\\s*(bold|[6-9]00)/i.test(style)) wrap(\"strong\");\n if (/font-style\\s*:\\s*italic/i.test(style)) wrap(\"em\");\n if (/text-decoration[^;]*underline/i.test(style)) wrap(\"u\");\n if (/text-decoration[^;]*line-through/i.test(style)) wrap(\"s\");\n el.replaceWith(...inner);\n continue;\n }\n for (const a of Array.from(el.attributes)) {\n const keep = (el.tagName === \"A\" && a.name === \"href\") || (el.tagName === \"IMG\" && (a.name === \"src\" || a.name === \"alt\"));\n if (!keep) el.removeAttribute(a.name);\n }\n }\n return { html: doc.body.innerHTML.trim(), images };\n}\n\nexport function restrictHtml(html: string, allows: (f: RichTextFeature) => boolean): { html: string; dropped: string[] } {\n if (!html) return { html, dropped: [] };\n const doc = new DOMParser().parseFromString(`<body>${html}</body>`, \"text/html\");\n const dropped = new Set<string>();\n const walk = (el: Element) => {\n for (const ch of Array.from(el.children)) {\n walk(ch);\n const mark = MARK_FEATURE[ch.tagName];\n const block = BLOCK_FEATURE[ch.tagName];\n if (mark && !allows(mark)) ch.replaceWith(...Array.from(ch.childNodes));\n else if (block && !allows(block)) {\n if (block === \"hr\" || block === \"image\") {\n dropped.add(FEATURE_WORD[block]!);\n ch.remove();\n } else if (block === \"ul\" || block === \"ol\") {\n const ps = Array.from(ch.children).map((li) => {\n const p = doc.createElement(\"p\");\n p.innerHTML = li.innerHTML;\n return p;\n });\n ch.replaceWith(...ps);\n } else {\n const p = doc.createElement(\"p\");\n p.innerHTML = block === \"pre\" ? esc(ch.textContent ?? \"\").replace(/\\n/g, \"<br>\") : ch.innerHTML;\n ch.replaceWith(p);\n }\n }\n }\n };\n walk(doc.body);\n return { html: doc.body.innerHTML, dropped: [...dropped] };\n}\n"],"mappings":";;;;;;AAQA,IAAM,eAAe;CACnB,MAAM,IAAI,SAAS,cAAc,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Q,CAAC,CAAC,KAAK,OAAO;MAC7C,MAAM,IAAI,IAAI,cAAc,GAAG;MAC/B,EAAE,YAAY,GAAG;MACjB,OAAO;KACT,CAAC;KACD,GAAG,YAAY,GAAG,EAAE;IACtB,OAAO;KACL,MAAM,IAAI,IAAI,cAAc,GAAG;KAC/B,EAAE,YAAY,UAAU,QAAQ,IAAI,GAAG,eAAe,EAAE,CAAC,CAAC,QAAQ,OAAO,MAAM,IAAI,GAAG;KACtF,GAAG,YAAY,CAAC;IAClB;GACF;EACF;CACF;CACA,KAAK,IAAI,IAAI;CACb,OAAO;EAAE,MAAM,IAAI,KAAK;EAAW,SAAS,CAAC,GAAG,OAAO;CAAE;AAC3D"}
@@ -251,7 +251,14 @@ function FieldShell({ field, path, id, value, onChange, readOnly, issue, action,
251
251
  children: /* @__PURE__ */ jsx("button", {
252
252
  type: "button",
253
253
  "aria-label": `Undo last change to ${field.title}`,
254
- onClick: () => form?.undo(key),
254
+ onClick: (e) => {
255
+ const btn = e.currentTarget;
256
+ const box = btn.closest("[data-field-key]");
257
+ form?.undo(key);
258
+ requestAnimationFrame(() => {
259
+ if (!btn.isConnected) (document.getElementById(id) ?? box?.querySelector("textarea, input, [contenteditable=true], button"))?.focus({ preventScroll: true });
260
+ });
261
+ },
255
262
  className: "inline-flex size-5 items-center justify-center rounded-kit-md text-kit-fg-3 hover:bg-kit-hover hover:text-kit-fg",
256
263
  children: /* @__PURE__ */ jsx(IconArrowBackUp, {
257
264
  className: "size-3.5",
@@ -1 +1 @@
1
- {"version":3,"file":"field-shell.js","names":[],"sources":["../../src/engine/field-shell.tsx"],"sourcesContent":["/**\n * FIELD SHELL — the one field chrome (V2 HEAD 9829bf1 kit/engine/field-shell.tsx; production FieldShell + CPO D8).\n *\n * [Label *] [ⓘ] [override dot] [changed dot] [synced] [EN] …… [42 / 60] [action] [Reset] [undo] [comments] [presence] [⋯]\n * help text (CPO D39: 12/16 --fg-3, 4px under the label, 1–2 lines; hidden while an error shows)\n * ┌ control ───────────────────────────────┐ ← peer editing: the control's border in their colour\n * └────────────────────────────────────────┘\n * error / warning message ……………………… meta (42 / 60)\n *\n * Accessories (add-comment, ⋯) take NO space at rest; they appear on hover/focus (always on touch). A comment\n * COUNT chip is always visible. AI lives in ⋯ (\"Rewrite with AI\"), never as a label sparkle (CPO-142).\n *\n * Services (toast, AI rewrite, in-place comments) come from KitServices; a missing service hides its surface.\n */\nimport * as React from \"react\";\nimport { createPortal } from \"react-dom\";\nimport {\n IconAlertCircle, IconAlertTriangle, IconArrowBackUp, IconBraces, IconClipboard, IconCopy, IconDots, IconHistory, IconInfoCircle,\n IconLock, IconMessage, IconMessagePlus, IconRefresh, IconRotate, IconWorld,\n} from \"@tabler/icons-react\";\nimport { AnimatePresence, motion } from \"framer-motion\";\nimport { Button, Sparkle } from \"../ui/button\";\nimport { Avatar, avatarRingSpread } from \"../ui/display\";\nimport { Menu, MenuContent, MenuItem, MenuSeparator, MenuTrigger, Popover, PopoverAnchor, PopoverContent, Tooltip } from \"../ui/overlay\";\nimport { presenceColor } from \"../ui/presence\";\nimport { cn } from \"../lib/cn\";\nimport { HISTORY_SEGMENT, type FieldPath, type FieldSchema } from \"../schema/types\";\nimport { resolveHelp } from \"../schema/help\";\nimport { AI_PRESETS, FieldHeaderSlot, KitSectionTitle, seesDevSurfaces, useForm, useKitEnv, useKitServices, type AiPreset, type KitPeer } from \"../context\";\nimport { pathKey, same } from \"../lib/path\";\nimport { isTextual, plainText } from \"../lib/schema\";\nimport { textLength, type KitIssue } from \"../lib/validate\";\nimport { RowChrome } from \"./bits\";\n\n/* ── Clipboard shared by every field (typed, so Paste can refuse with a reason) ── */\n/** `html`: a rich text value as its editor html (read through the host's codec), so Paste re-stores it for the target field. */\nlet clip: { type: string; value: unknown; label: string; html?: string } | null = null;\n/** Test seam: forget the shared field clipboard. */\nexport const resetFieldClipboard = () => {\n clip = null;\n};\nconst KIND: Record<string, string> = { image: \"an image\", file: \"a file\", video: \"a video\", reference: \"a reference\", link: \"a link\", button: \"a button\", array: \"a list\", slot: \"blocks\", object: \"a group of fields\", boolean: \"an on/off value\", number: \"a number\", color: \"a colour\" };\nconst kindOf = (t: string) => (isTextual(t as FieldSchema[\"type\"]) ? \"text\" : KIND[t] ?? t);\n\ntype RichTextCodec = NonNullable<ReturnType<typeof useKitServices>[\"richText\"]>;\nconst escHtml = (s: string) => s.replace(/&/g, \"&amp;\").replace(/</g, \"&lt;\").replace(/>/g, \"&gt;\");\n/** Plain text as editor html: one escaped paragraph per line. */\nconst paragraphs = (text: string) =>\n text\n .split(/\\n+/)\n .map((l) => l.trim())\n .filter(Boolean)\n .map((l) => `<p>${escHtml(l)}</p>`)\n .join(\"\");\n/**\n * Html into a rich text field, stored in the field's own shape through the host's codec. A write that would drop\n * something is refused with the words the codec names; nothing is stored.\n */\nfunction richTextWrite(codec: RichTextCodec, field: FieldSchema, path: FieldPath, html: string, prev: unknown): { value: unknown } | { refused: string } {\n try {\n const out = codec.write(html, { field, path }, prev);\n return out.losses.length ? { refused: `${field.title} can't keep ${out.losses.join(\", \")}` } : { value: out.value };\n } catch (err) {\n return { refused: `${field.title} could not store this text (${err instanceof Error ? err.message : String(err)})` };\n }\n}\n/** A rich text value as editor html, when the host's codec reads it. */\nfunction richTextHtml(codec: RichTextCodec | undefined, field: FieldSchema, path: FieldPath, value: unknown): string | undefined {\n if (!codec || field.type !== \"richtext\") return undefined;\n try {\n return codec.read(value, { field, path }).html;\n } catch {\n return undefined; // Paste falls back to the value's words\n }\n}\n\nexport const apiName = (schemaName: string, path: FieldPath) =>\n [schemaName, ...path.filter((s) => s !== HISTORY_SEGMENT)].reduce<string>((a, s) => (typeof s === \"number\" ? `${a}[${s}]` : a ? `${a}.${s}` : String(s)), \"\");\n\n/** A long label truncates on one line; past this many characters a native `title` carries the full label (DESIGN 4.4). */\nexport const LABEL_HINT_AT = 28;\n\n/* D63: add-comment and ⋯ are hidden at rest and show on THIS field's hover or focus (not a parent group's), always on\n touch, and while their menu or popover is open. The rule lives in tokens.css ([data-field-reveal]) because a Tailwind\n group variant matches every ancestor field, so hovering a group used to reveal the chrome of all its children. */\n\nexport interface FieldShellProps {\n field: FieldSchema;\n path: FieldPath;\n id: string;\n value: unknown;\n onChange: (v: unknown) => void;\n readOnly?: boolean;\n issue?: KitIssue;\n /** label-row action (e.g. slug \"Generate\") */\n action?: React.ReactNode;\n /** \"card\" = the boolean switch card · \"row\" = the control IS a labelled row (a drill-in object, CPO D45): no label row,\n * the chrome goes into the row through `RowChrome` */\n layout?: \"stack\" | \"card\" | \"row\";\n /** layout fields get no comment control */\n noComments?: boolean;\n /** right side of the message line (counters, \"3 items · max 6\") */\n meta?: React.ReactNode;\n className?: string;\n children: React.ReactNode;\n}\n\nexport function FieldShell({ field, path, id, value, onChange, readOnly, issue, action, layout = \"stack\", noComments, meta, className, children }: FieldShellProps) {\n const env = useKitEnv();\n const form = useForm();\n const services = useKitServices();\n const key = pathKey(path);\n /* A host can lift this field's chrome into its own header (All fields: a block whose only field is \"Stats\" under a\n \"Stats\" section) — then there is no label row at all; the label stays for screen readers. */\n const slot = React.useContext(FieldHeaderSlot);\n const lifted = slot && slot.key === key && layout === \"stack\" ? slot.el : null;\n const [ai, setAi] = React.useState(false);\n const [commentsOpen, setCommentsOpen] = React.useState(false);\n /* V2 fieldPopoverCollision: the comments popover stays inside the scrolling area the field sits in */\n const [commentArea, setCommentArea] = React.useState<CommentCollision>({ collisionPadding: 12 });\n const peers = env.presence[key] ?? [];\n const editor = peers.find((p) => p.status !== \"viewing\");\n const InPlaceComments = services.FieldComments;\n /* a meta-form (the schema editor's field settings) shows no comment, ⋯ or per-field undo chrome (KitEnv.fieldChrome) */\n const quiet = env.fieldChrome === \"quiet\";\n const bare = quiet || env.fieldChrome === \"preview\";\n const canComment = !noComments && !bare && (!!env.onComment || !!InPlaceComments);\n const openCount = env.comments[key] ?? 0; // with no env.onComment and a count hook, CommentButton reads the store\n const useStoreCount = env.onComment ? undefined : services.useFieldCommentCount;\n const changed = !!form?.hasPublished && !same(value, form.publishedAt(path));\n /* component instance (D28): a top-level field either inherits the component's value or overrides it */\n const inh = form?.inherited && path.length === 1 ? form.inherited : undefined;\n const overridden = !!inh && inh.isOverridden(key);\n /* D61: while the host's History is open, a changed field gets the host's 2px author-colour bar at its left edge\n (with its hover card) instead of the quiet \"changed\" dot. At rest (History closed) the dot stays. */\n const reviewing = !!env.review;\n const bar = env.review && env.review.count(path) > 0 ? env.review.bar(path, field) : null;\n const sectionTitle = React.useContext(KitSectionTitle);\n /* \"Options\" in a section called \"Options\": the section heading already names the field (the label stays for readers) */\n const repeatsSection = quiet && layout === \"stack\" && !!sectionTitle && sectionTitle.trim().toLowerCase() === field.title.trim().toLowerCase();\n const canUndo = !bare && !!form?.canUndo(key) && !readOnly;\n const synced = field.synced?.from; // a whole synced form shows one notice at its root, not a chip per field\n const limit = field.validation?.max ?? field.validation?.recommendedMax;\n const len = textLength(value);\n /* counters stay quiet: shown while the field has focus, or when the value nears its limit */\n const near = !!limit && len >= limit * 0.8;\n const counter =\n limit && (field.type === \"string\" || field.type === \"text\" || field.type === \"richtext\") ? (\n <span\n data-slot=\"field-counter\"\n className={cn(\n \"tabular-nums text-kit-xs\",\n !near && \"hidden group-focus-within/field:inline\",\n field.validation?.max && len > field.validation.max ? \"text-kit-danger-fg\" : field.validation?.recommendedMax && len > field.validation.recommendedMax ? \"text-kit-warning-fg\" : \"text-kit-fg-3\",\n )}\n >\n {len} / {limit}\n </span>\n ) : null;\n\n /* ── Help (CPO D39) ── one line under the label; longer text behind ⓘ. Dense hosts (env.helpDisplay \"tooltip\")\n move the line into the ⓘ too. An error REPLACES the help (warnings keep it: they're advice, not a block). */\n const dense = env.helpDisplay === \"tooltip\";\n /* D70: a field locked for this person (its own edit cap, in a form they can otherwise change) says so: a small lock glyph\n before the reason. A whole read-only form (Viewer, view as) stays plain text with no glyphs (D58). */\n const lockedHere = !!readOnly && !!field.access?.edit && !env.readOnly && !env.can(field.access.edit);\n const help = lockedHere ? (field.lockReason?.trim() || \"Set by developers\").replace(/\\.?$/, \".\") : resolveHelp(field); // arrays / slots / objects reach the shell without KitField: conventions apply here too\n const helpNode = lockedHere ? (\n <span data-locked=\"\" className=\"inline-flex items-start gap-1\">\n <IconLock className=\"mt-px size-3 shrink-0\" stroke={1.75} aria-hidden />\n <span>\n <span className=\"sr-only\">Locked. </span>\n {help}\n </span>\n </span>\n ) : (\n help\n );\n const more = field.helpMore || undefined;\n const erroring = issue?.level === \"error\";\n // a lock's reason stays on the field even in a dense host: it says why the value can't change\n const helpInline = !!help && (!dense || lockedHere) && !erroring;\n const tip = dense && !lockedHere ? [help, more].filter(Boolean).join(\" \") : more;\n const helpId = `${id}-help`;\n const moreId = `${id}-more`;\n const msgId = `${id}-msg`;\n const describedBy = [helpInline && helpId, tip && moreId, issue && msgId].filter(Boolean).join(\" \");\n /* Controls are many (input, textarea, contenteditable, pickers); the shell owns the ids, so it wires\n aria-describedby onto whatever element carries the field id, keeping any ids the control set itself. */\n React.useEffect(() => {\n const el = document.getElementById(id);\n if (!el) return;\n const own = (el.getAttribute(\"aria-describedby\") ?? \"\").split(\" \").filter((t) => t && !t.startsWith(`${id}-`));\n const next = [...own, ...describedBy.split(\" \").filter(Boolean)].join(\" \");\n if (next) el.setAttribute(\"aria-describedby\", next);\n else el.removeAttribute(\"aria-describedby\");\n }, [id, describedBy]);\n const info = tip ? (\n <Tooltip content={<span className=\"block max-w-[260px] whitespace-normal font-normal leading-4\">{tip}</span>}>\n <button type=\"button\" aria-label={`About ${field.title}`} className=\"-my-0.5 inline-flex size-4 shrink-0 items-center justify-center rounded-kit-sm text-kit-fg-4 hover:text-kit-fg-2\">\n <IconInfoCircle className=\"size-3.5\" stroke={1.5} aria-hidden />\n <span id={moreId} className=\"sr-only\">{tip}</span>\n </button>\n </Tooltip>\n ) : null;\n\n // KP-029/223: a long label truncates on one line with a native title; the boolean card's label wraps under its switch.\n const longTitle = field.title.length > LABEL_HINT_AT ? field.title : undefined;\n const labelOf = (wrap: boolean) => (\n <>\n <span className={wrap ? \"min-w-0 break-words\" : \"truncate\"}>{field.title}</span>\n {field.validation?.required ? (\n <>\n <span aria-hidden className=\"text-kit-fg-2\">*</span>\n <span className=\"sr-only\">(required)</span>\n </>\n ) : null}\n </>\n );\n const label = labelOf(false);\n const badges = (\n <>\n {overridden ? (\n <Tooltip content={`Overrides ${inh!.from}. Changes to the block no longer reach this field.`}>\n <span role=\"img\" className=\"size-1.5 shrink-0 rounded-full bg-kit-accent\" aria-label={`Overrides ${inh!.from}`} />\n </Tooltip>\n ) : null}\n {changed && !reviewing ? (\n <Tooltip content=\"Changed since publish\">\n <span role=\"img\" className=\"size-1.5 shrink-0 rounded-full bg-kit-warning\" aria-label=\"Changed since publish\" />\n </Tooltip>\n ) : null}\n {synced ? (\n <Tooltip content={`Synced from ${synced}. Changes apply on every page that uses it.`}>\n <span className=\"inline-flex h-4 shrink-0 items-center gap-0.5 rounded-kit-md bg-kit-info-soft px-1 text-kit-2xs font-medium text-kit-info-fg\">\n <IconRefresh className=\"size-2.5\" stroke={2} aria-hidden />\n Synced\n </span>\n </Tooltip>\n ) : null}\n {field.localized ? (\n <Tooltip content=\"Translatable: this field can hold a value for each of the site's languages.\">\n <span className=\"inline-flex h-4 shrink-0 items-center gap-0.5 rounded-kit-md bg-kit-muted px-1 text-kit-2xs font-medium text-kit-fg-3\">\n <IconWorld className=\"size-2.5\" stroke={2} aria-hidden />\n EN\n </span>\n </Tooltip>\n ) : null}\n </>\n );\n const accessories = (\n <>\n {action}\n {overridden && !readOnly ? (\n <Tooltip content={`Use ${inh!.from}'s value again`}>\n <button\n type=\"button\"\n onClick={(e) => {\n const box = (e.currentTarget as HTMLElement).closest<HTMLElement>(\"[data-field-key]\");\n inh!.reset(key);\n // the button goes away with the override: keep focus in the field, never on <body>\n requestAnimationFrame(() => (document.getElementById(id) ?? box?.querySelector<HTMLElement>(\"textarea, input, [contenteditable=true], button\"))?.focus({ preventScroll: true }));\n }}\n aria-label={`Reset ${field.title} to ${inh!.from}`}\n className=\"inline-flex h-5 items-center rounded-kit-md px-1 text-kit-xs text-kit-fg-3 hover:bg-kit-hover hover:text-kit-fg\"\n >\n Reset\n </button>\n </Tooltip>\n ) : null}\n {canUndo ? (\n <Tooltip content={`Undo last change to ${field.title}`}>\n <button type=\"button\" aria-label={`Undo last change to ${field.title}`} onClick={() => form?.undo(key)} className=\"inline-flex size-5 items-center justify-center rounded-kit-md text-kit-fg-3 hover:bg-kit-hover hover:text-kit-fg\">\n <IconArrowBackUp className=\"size-3.5\" stroke={1.5} aria-hidden />\n </button>\n </Tooltip>\n ) : null}\n {canComment ? (\n <CommentButton\n count={openCount}\n useCount={useStoreCount ? () => useStoreCount(env.docId, key) : undefined}\n label={field.title}\n open={commentsOpen}\n onOpen={(el) => {\n if (env.onComment) return env.onComment(path, field); // the host owns comments (e.g. the document editor)\n setCommentArea(fieldPopoverCollision(el.closest(\"[data-field-key]\")));\n setCommentsOpen(true);\n }}\n />\n ) : null}\n <PeerStack peers={peers} />\n {bare ? null : <FieldMenu field={field} path={path} value={value} onChange={onChange} readOnly={!!readOnly} changed={changed} onAi={() => setAi(true)} />}\n </>\n );\n\n // Peer editing (Figma / Notion / Sanity): only the field's own input border takes their --presence-n colour (full strength:\n // the old 70% mix read as a validation error at 1.96:1) —\n // no outline around the input + preview, no name tag over the border, no layout shift. Who it is: the face in the label row.\n const control = (\n <div\n className={cn(\"relative\", editor && \"[&_.border-kit-field-border]:border-[var(--peer)]\")}\n style={editor ? ({ \"--peer\": editor.color ?? presenceColor(editor.id ?? editor.name) } as React.CSSProperties) : undefined}\n >\n {children}\n </div>\n );\n\n const message =\n issue || meta ? (\n <div className=\"flex min-h-4 items-start justify-between gap-3\">\n <AnimatePresence initial={false}>\n {issue ? (\n <motion.p\n key={issue.message}\n id={msgId}\n initial={{ opacity: 0, y: -2 }}\n animate={{ opacity: 1, y: 0 }}\n role={issue.level === \"error\" ? \"alert\" : \"status\"}\n className={cn(\"flex min-w-0 items-start gap-1 text-kit-xs\", issue.level === \"error\" ? \"text-kit-danger-fg\" : \"text-kit-warning-fg\")}\n >\n {issue.level === \"error\" ? <IconAlertCircle className=\"mt-px size-3.5 shrink-0\" stroke={1.5} aria-hidden /> : <IconAlertTriangle className=\"mt-px size-3.5 shrink-0\" stroke={1.5} aria-hidden />}\n <span className=\"min-w-0\">\n {issue.message}\n {issue.fix && !readOnly ? (\n <>\n {\" \"}\n <button type=\"button\" onClick={issue.fix.apply} className=\"font-medium text-kit-fg underline-offset-2 hover:underline\">\n {issue.fix.label}\n </button>\n </>\n ) : null}\n </span>\n </motion.p>\n ) : (\n <span />\n )}\n </AnimatePresence>\n {meta ? <span className=\"flex shrink-0 items-center gap-2\">{meta}</span> : null}\n </div>\n ) : null;\n\n const labelEl = (\n <label\n htmlFor={id}\n id={`${id}-label`}\n className=\"flex min-w-0 items-center gap-1 text-kit-sm font-medium text-kit-fg-2 transition-colors group-focus-within/field:text-kit-fg\"\n title={longTitle}\n >\n {label}\n </label>\n );\n\n const body =\n layout === \"row\" ? (\n <div className={cn(\"group/field relative flex min-w-0 flex-col gap-1.5\", className)} data-field-key={key} data-field={path.length === 1 ? key : undefined} data-slot=\"kit-field\">\n {bar}\n <RowChrome.Provider value={<>{info}{badges}{accessories}</>}>{control}</RowChrome.Provider>\n {message}\n </div>\n ) : layout === \"card\" && quiet ? (\n /* the inspector's PRow: label left, switch right, no card (a meta-form's Required, Unique, Tuck into Advanced) */\n <div className={cn(\"group/field relative flex flex-col gap-1\", className)} data-field-key={key} data-field={path.length === 1 ? key : undefined} data-slot=\"kit-field\">\n {bar}\n <div data-field-head=\"\" className=\"flex min-h-8 items-center gap-3\">\n <label htmlFor={id} id={`${id}-label`} className=\"min-w-0 flex-1 cursor-pointer\" title={longTitle}>\n <span className=\"flex min-w-0 items-center gap-1 text-kit-sm font-medium text-kit-fg-2 transition-colors group-focus-within/field:text-kit-fg\">\n {label}\n {info}\n {badges}\n </span>\n {helpInline ? (\n <span id={helpId} data-slot=\"field-help\" className=\"mt-0.5 block text-kit-xs leading-4 text-kit-fg-3\">\n {helpNode}\n </span>\n ) : null}\n </label>\n <span className=\"flex shrink-0 items-center gap-0.5 empty:hidden\">{accessories}</span>\n <span className=\"flex shrink-0 items-center\">{readOnly ? <span className=\"text-kit-sm text-kit-fg-2\">{value ? \"On\" : \"Off\"}</span> : control}</span>\n </div>\n {message}\n </div>\n ) : layout === \"card\" ? (\n <div className={cn(\"group/field relative flex flex-col gap-1.5\", className)} data-field-key={key} data-field={path.length === 1 ? key : undefined} data-slot=\"kit-field\">\n {bar}\n <div data-field-head=\"\" className={cn(\"flex items-center gap-3 rounded-kit-lg border bg-kit-surface px-3 py-2.5 transition-colors\", issue?.level === \"error\" ? \"border-[var(--kit-field-invalid)]\" : \"border-kit-line hover:border-kit-line-strong\")}>\n {control}\n <label htmlFor={id} id={`${id}-label`} className=\"min-w-0 flex-1 cursor-pointer\" title={longTitle}>\n <span className=\"flex min-w-0 items-center gap-1.5 text-kit-sm font-medium text-kit-fg\">\n {labelOf(true)}\n {info}\n {badges}\n </span>\n {helpInline ? (\n <span id={helpId} data-slot=\"field-help\" className=\"block text-kit-xs leading-4 text-kit-fg-3\">\n {helpNode}\n </span>\n ) : null}\n </label>\n <span className=\"shrink-0 text-kit-xs text-kit-fg-3\">{value ? \"On\" : \"Off\"}</span>\n <span className=\"flex shrink-0 items-center gap-0.5 empty:hidden\">{accessories}</span>\n </div>\n {message}\n </div>\n ) : (\n <div\n className={cn(\"group/field relative flex min-w-0 flex-col gap-1.5\", className)}\n data-field-key={key}\n data-field={path.length === 1 ? key : undefined}\n data-slot=\"kit-field\"\n data-inherited={inh && !overridden ? \"\" : undefined}\n data-overridden={overridden ? \"\" : undefined}\n >\n {bar}\n {repeatsSection ? (\n <label htmlFor={id} id={`${id}-label`} className=\"sr-only\">\n {label}\n </label>\n ) : lifted ? (\n <>\n <label htmlFor={id} id={`${id}-label`} className=\"sr-only\">\n {label}\n </label>\n {createPortal(\n <span className=\"flex items-center gap-0.5 [&>button]:!inline-flex\">\n {info}\n {badges}\n {counter}\n {accessories}\n </span>,\n lifted,\n )}\n </>\n ) : (\n <div data-slot=\"field-label-row\" data-field-head=\"\" className=\"flex min-h-5 min-w-0 items-center gap-1.5\">\n {labelEl}\n {info}\n {badges}\n <span className=\"flex-1\" />\n {counter}\n <span className=\"flex shrink-0 items-center gap-0.5\">{accessories}</span>\n </div>\n )}\n {helpInline ? (\n <p id={helpId} data-slot=\"field-help\" className=\"-mt-0.5 text-kit-xs leading-4 text-kit-fg-3\">\n {helpNode}\n </p>\n ) : null}\n {control}\n {message}\n </div>\n );\n\n /* The AI popover and the comments popover both anchor to the field (two stacked anchor divs). */\n return (\n <Popover open={ai} onOpenChange={setAi}>\n <PopoverAnchor className=\"min-w-0\">\n <Popover\n open={commentsOpen}\n onOpenChange={(open, d) => {\n /* V2 guardEscape: Escape inside the composer (data-esc-owner) belongs to the draft, not the popover */\n if (!open && d.reason === \"escape-key\" && (document.activeElement as HTMLElement | null)?.hasAttribute(\"data-esc-owner\")) return d.cancel();\n setCommentsOpen(open);\n }}\n >\n <PopoverAnchor className=\"min-w-0\">{body}</PopoverAnchor>\n {commentsOpen && InPlaceComments ? (\n <PopoverContent align=\"start\" sideOffset={8} {...commentArea} initialFocus={false} className=\"w-[clamp(280px,var(--anchor-width),420px)] p-0\">\n <InPlaceComments\n docId={env.docId}\n fieldKey={key}\n label={field.title}\n quote={plainText(value).slice(0, 80) || undefined}\n onClose={() => setCommentsOpen(false)}\n onOpenPanel={\n env.onComment\n ? () => {\n env.onComment?.(path, field);\n setCommentsOpen(false);\n }\n : undefined\n }\n />\n </PopoverContent>\n ) : null}\n </Popover>\n </PopoverAnchor>\n {ai ? (\n <PopoverContent align=\"start\" sideOffset={8} className=\"w-[clamp(300px,var(--anchor-width),440px)] p-0\">\n <AiRewrite field={field} path={path} value={value} onChange={onChange} onClose={() => setAi(false)} />\n </PopoverContent>\n ) : null}\n </Popover>\n );\n}\n\ntype CommentCollision = { collisionBoundary?: Element; collisionPadding: number | Partial<Record<\"top\" | \"right\" | \"bottom\" | \"left\", number>> };\n/** V2 features/comments fieldPopoverCollision: inside a scrolling panel, collide with that panel below its sticky header. */\nfunction fieldPopoverCollision(anchor: Element | null): CommentCollision {\n let area = anchor?.parentElement ?? null;\n while (area && !/(auto|scroll)/.test(getComputedStyle(area).overflowY)) area = area.parentElement;\n if (!area || area === document.scrollingElement) return { collisionPadding: 12 };\n const sticky = parseFloat(getComputedStyle(area).getPropertyValue(\"--kit-sticky-top\")) || 0;\n return { collisionBoundary: area, collisionPadding: { top: sticky + 8, right: 8, bottom: 8, left: 8 } };\n}\n\n/** Comment count chip (always visible) or the hover-revealed \"Add comment\" icon. `useCount` (the host's store hook)\n * replaces `count` when the kit draws the comments in place. */\nfunction CommentButton({ useCount, ...props }: CommentButtonProps & { useCount?: () => number }) {\n return useCount ? <StoreCommentButton useCount={useCount} {...props} /> : <CountedCommentButton {...props} />;\n}\ninterface CommentButtonProps {\n count: number;\n label: string;\n open: boolean;\n onOpen: (el: HTMLElement) => void;\n}\nfunction StoreCommentButton({ useCount, ...props }: CommentButtonProps & { useCount: () => number }) {\n return <CountedCommentButton {...props} count={useCount()} />;\n}\nfunction CountedCommentButton({ count, label, open, onOpen }: CommentButtonProps) {\n if (count > 0)\n return (\n <Tooltip content={`${count} open comment${count === 1 ? \"\" : \"s\"} on ${label}`}>\n <button\n type=\"button\"\n onClick={(e) => onOpen(e.currentTarget)}\n data-state={open ? \"open\" : \"closed\"}\n aria-label={`${count} open comments on ${label}`}\n className=\"-my-0.5 inline-flex h-5 items-center gap-0.5 rounded-kit-md px-1 text-kit-2xs font-medium text-kit-fg-3 hover:bg-kit-hover hover:text-kit-fg data-[state=open]:bg-kit-hover data-[state=open]:text-kit-fg\"\n >\n <IconMessage className=\"size-3.5\" stroke={1.5} aria-hidden />\n <span className=\"tabular-nums\">{count}</span>\n </button>\n </Tooltip>\n );\n return (\n <Tooltip content=\"Add comment\">\n <button\n type=\"button\"\n onClick={(e) => onOpen(e.currentTarget)}\n data-state={open ? \"open\" : \"closed\"}\n aria-label={`Add comment to ${label}`}\n data-field-reveal=\"\" className={cn(\"-my-0.5 size-6 items-center justify-center rounded-kit-md text-kit-fg-3 hover:bg-kit-hover hover:text-kit-fg\")}\n >\n <IconMessagePlus className=\"size-3.5\" stroke={1.5} aria-hidden />\n </button>\n </Tooltip>\n );\n}\n\n/** Who is in this field: 16px faces in the label row's action slot (no overlap with the label or the input), name on hover. */\nexport function PeerStack({ peers, size = 16 }: { peers: KitPeer[]; size?: number }) {\n const shown = peers.slice(0, 3);\n const rest = peers.length - shown.length;\n // Each slot reserves the ring band (1px surface gap + 1px presence colour) on every side, so the ring sits inside\n // the slot: a clipping ancestor or the row's edge can never shave it. Faces still overlap by 25% of their size.\n const ring = \"var(--kit-avatar-ring, var(--kit-surface))\";\n const band = avatarRingSpread({ ring, ringWidth: 1, ringAccent: \"x\" });\n const box = size + band * 2;\n const overlap = -(Math.round(size * 0.25) + band * 2);\n return (\n <AnimatePresence initial={false}>\n {shown.length ? (\n <motion.span key=\"peers\" initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }} transition={{ duration: 0.25 }} className=\"flex h-5 items-center\" data-slot=\"field-presence\">\n {/* D34 stack rules: same size, 25% overlap, first face on top; the ring is box-shadow (surface gap + the\n peer's presence colour) so the photo keeps its full size. */}\n {shown.map((p, i) => (\n <Tooltip key={p.name + i} content={`${p.name} · ${p.status === \"viewing\" ? \"Viewing\" : \"Editing\"} this field`}>\n <span\n style={{ marginLeft: i ? overlap : 0, zIndex: shown.length - i + 1, width: box, height: box }}\n className={cn(\"relative inline-flex shrink-0 rounded-full transition-transform duration-150 hover:!z-30 hover:-translate-y-px\", p.status === \"viewing\" && \"opacity-60\")}\n >\n <Avatar name={p.name} src={p.avatar} size={size} ring={ring} ringWidth={1} ringAccent={p.color ?? presenceColor(p.id ?? p.name)} decorative />\n </span>\n </Tooltip>\n ))}\n {rest > 0 ? (\n <Tooltip content={peers.slice(shown.length).map((p) => p.name).join(\", \")}>\n <span style={{ marginLeft: overlap, width: box, height: box, padding: band }} className=\"relative z-[1] inline-flex shrink-0\">\n <span\n style={{ width: size, height: size, boxShadow: `0 0 0 ${band}px var(--kit-surface)`, fontSize: Math.max(8, Math.round(size * 0.5)) }}\n className=\"inline-flex items-center justify-center rounded-full bg-kit-muted font-medium leading-none tabular-nums text-kit-fg-2\"\n >\n +{rest}\n </span>\n </span>\n </Tooltip>\n ) : null}\n </motion.span>\n ) : null}\n </AnimatePresence>\n );\n}\n\n/* ── ⋯ Field actions (DESIGN 8.25) ─────────────────────────────────── */\nfunction FieldMenu({ field, path, value, onChange, readOnly, changed, onAi }: { field: FieldSchema; path: FieldPath; value: unknown; onChange: (v: unknown) => void; readOnly: boolean; changed: boolean; onAi: () => void }) {\n const form = useForm();\n const env = useKitEnv();\n const { toast, aiRewrite, richText, FieldMenuExtras } = useKitServices();\n const key = pathKey(path);\n const api = apiName(form?.schema.name ?? \"doc\", path);\n const textual = isTextual(field.type);\n // rich text is rewritten only where the host's codec can store the result in the field's own shape\n const prose = field.type === \"string\" || field.type === \"text\" || (field.type === \"richtext\" && !!richText);\n const editable = !readOnly;\n const dev = seesDevSurfaces(env);\n return (\n <Menu>\n <Tooltip content=\"Field actions\">\n <MenuTrigger\n aria-label={`${field.title} actions`}\n data-field-reveal=\"\" className={cn(\"-my-0.5 size-6 items-center justify-center rounded-kit-md text-kit-fg-3 hover:bg-kit-hover hover:text-kit-fg data-[popup-open]:bg-kit-hover data-[popup-open]:text-kit-fg\")}\n >\n <IconDots className=\"size-3.5\" stroke={1.5} aria-hidden />\n </MenuTrigger>\n </Tooltip>\n <MenuContent align=\"end\" className=\"w-60\">\n <MenuItem\n icon={<IconCopy stroke={1.5} />}\n onClick={() => {\n const html = richTextHtml(richText, field, path, value);\n clip = { type: field.type, value: structuredCloneish(value), label: field.title, ...(html !== undefined ? { html } : {}) };\n const text = textual ? plainText(value) || \"\" : typeof value === \"string\" ? value : JSON.stringify(value ?? null, null, 2);\n void navigator.clipboard?.writeText(text).catch(() => {});\n toast?.success(`${field.title} copied`);\n }}\n >\n Copy value\n </MenuItem>\n {editable ? <PasteItem field={field} path={path} value={value} onChange={onChange} /> : null}\n {editable && form?.hasPublished && changed ? (\n <MenuItem\n icon={<IconRotate stroke={1.5} />}\n onClick={() => {\n const prev = value;\n onChange(form.publishedAt(path));\n toast?.(`${field.title} reset to published`, { action: { label: \"Undo\", onClick: () => onChange(prev) }, duration: 10_000 });\n }}\n >\n Reset to published\n </MenuItem>\n ) : null}\n {env.onFieldHistory ? (\n <MenuItem icon={<IconHistory stroke={1.5} />} onClick={() => env.onFieldHistory!(path, field)}>\n History\n </MenuItem>\n ) : null}\n {FieldMenuExtras ? <FieldMenuExtras field={field} path={path} readOnly={readOnly} /> : null}\n {editable && prose && aiRewrite ? (\n <>\n <MenuSeparator />\n {form?.aiKeys.has(key) ? (\n <MenuItem\n icon={<IconArrowBackUp stroke={1.5} />}\n onClick={() => {\n form.undo(key);\n form.markAi(key, false);\n }}\n >\n Undo AI change\n </MenuItem>\n ) : null}\n <MenuItem icon={<Sparkle size={16} />} onClick={() => window.setTimeout(onAi, 0)}>\n Rewrite with AI\n </MenuItem>\n </>\n ) : null}\n {dev ? <MenuSeparator /> : null}\n {dev ? (\n <MenuItem\n icon={<IconBraces stroke={1.5} />}\n onClick={() => {\n void navigator.clipboard?.writeText(api).catch(() => {});\n toast?.success(`Copied ${api}`);\n }}\n >\n <span className=\"flex w-full items-center justify-between gap-3\">\n Copy API name\n <span className=\"truncate font-kit-mono text-kit-2xs text-kit-fg-3\">{api.length > 22 ? `…${api.slice(-20)}` : api}</span>\n </span>\n </MenuItem>\n ) : null}\n </MenuContent>\n </Menu>\n );\n}\n/** Reads the shared clipboard when the menu opens (it mounts with the popup), so a copy in another field is seen. */\nfunction PasteItem({ field, path, value, onChange }: { field: FieldSchema; path: FieldPath; value: unknown; onChange: (v: unknown) => void }) {\n const { toast, richText } = useKitServices();\n const textual = isTextual(field.type);\n // text into rich text needs the host's codec to store it in the field's shape\n const needsCodec = !!clip && field.type === \"richtext\" && clip.type !== \"richtext\" && !richText;\n const pasteOk = clip && !needsCodec && (clip.type === field.type || (textual && isTextual(clip.type as FieldSchema[\"type\"])));\n const pasteReason = !clip\n ? \"Copy a value from a field first.\"\n : needsCodec\n ? \"This rich text field takes a copied rich text value only.\"\n : pasteOk\n ? null\n : `Clipboard holds ${kindOf(clip.type)}. This field takes ${kindOf(field.type)}.`;\n return (\n <MenuItem\n icon={<IconClipboard stroke={1.5} />}\n disabled={!pasteOk}\n className={cn(pasteReason && \"h-auto py-1.5\")}\n onClick={() => {\n if (!clip) return;\n const prev = value;\n let next: unknown;\n if (field.type === \"richtext\" && richText && (clip.type !== \"richtext\" || clip.html !== undefined)) {\n // through the codec: the target field's own shape and Accept list, refused by name when it would drop something\n const out = richTextWrite(richText, field, path, clip.html ?? paragraphs(plainText(clip.value)), prev);\n if (\"refused\" in out) {\n toast?.(`Not pasted: ${out.refused}.`);\n return;\n }\n next = out.value;\n } else next = textual && clip.type === \"richtext\" && field.type !== \"richtext\" ? plainText(clip.value) : structuredCloneish(clip.value);\n onChange(next);\n toast?.(`Pasted into ${field.title}`, { action: { label: \"Undo\", onClick: () => onChange(prev) }, duration: 10_000 });\n }}\n >\n <span className=\"flex flex-col\">\n Paste value\n {pasteReason ? <span className=\"whitespace-normal text-kit-xs text-kit-fg-3\">{pasteReason}</span> : null}\n </span>\n </MenuItem>\n );\n}\nfunction structuredCloneish<T>(v: T): T {\n try {\n return structuredClone(v);\n } catch {\n return v;\n }\n}\n\n/* ── Rewrite with AI (preview before apply) ────────────────────────── */\nfunction AiRewrite({ field, path, value, onChange, onClose }: { field: FieldSchema; path: FieldPath; value: unknown; onChange: (v: unknown) => void; onClose: () => void }) {\n const form = useForm();\n const { toast, aiRewrite, richText } = useKitServices();\n const key = pathKey(path);\n const [preset, setPreset] = React.useState<AiPreset | null>(null);\n const [out, setOut] = React.useState<string | null>(null);\n const [failed, setFailed] = React.useState(false);\n const attempt = React.useRef(0);\n const latest = React.useRef(0);\n const source = plainText(value);\n const run = (p: AiPreset) => {\n if (!aiRewrite) return;\n setPreset(p);\n setOut(null);\n setFailed(false);\n const ticket = ++latest.current;\n Promise.resolve()\n .then(() => aiRewrite(source, p, attempt.current++))\n .then(\n (result) => {\n if (latest.current === ticket) setOut(result);\n },\n () => {\n if (latest.current === ticket) setFailed(true);\n },\n );\n };\n const apply = () => {\n if (!out) return;\n const prev = value;\n let next: unknown = out;\n if (field.type === \"richtext\") {\n const stored = richText ? richTextWrite(richText, field, path, paragraphs(out), prev) : { refused: `${field.title} has no rich text storage here` };\n if (\"refused\" in stored) {\n toast?.(`Not applied: ${stored.refused}.`);\n return;\n }\n next = stored.value;\n }\n onChange(next);\n form?.markAi(key, true);\n toast?.(\"Rewritten with AI\", {\n icon: <Sparkle size={14} />,\n action: {\n label: \"Undo\",\n onClick: () => {\n onChange(prev);\n form?.markAi(key, false);\n },\n },\n duration: 10_000,\n });\n onClose();\n };\n return (\n <div className=\"flex flex-col\">\n <div className=\"flex items-center gap-2 border-b border-kit-line px-3 py-2.5\">\n <Sparkle size={16} />\n <span className=\"text-kit-sm font-medium text-kit-fg\">Rewrite {field.title.toLowerCase()}</span>\n </div>\n <div className=\"flex flex-wrap gap-1 px-3 pt-2.5\">\n {AI_PRESETS.map((p) => (\n <button\n key={p.id}\n type=\"button\"\n onClick={() => run(p.id)}\n className={cn(\"h-6 rounded-full border px-2 text-kit-xs transition-colors\", preset === p.id ? \"border-[var(--kit-emphasis-line)] bg-kit-surface text-kit-fg\" : \"border-kit-line text-kit-fg-2 hover:border-kit-line-strong hover:text-kit-fg\")}\n >\n {p.label}\n </button>\n ))}\n </div>\n <div className=\"px-3 py-3\">\n {!preset ? (\n <p className=\"text-kit-xs text-kit-fg-3\">Pick a direction. You'll see the suggestion before anything changes.</p>\n ) : failed ? (\n <p role=\"alert\" className=\"text-kit-xs text-kit-danger-fg\">\n Couldn't rewrite {field.title.toLowerCase()}. Try again.\n </p>\n ) : out == null ? (\n <p className=\"text-kit-sm\">\n <Shimmer>Rewriting {field.title.toLowerCase()}…</Shimmer>\n </p>\n ) : (\n <div className=\"rounded-kit-lg bg-kit-subtle p-2.5 text-kit-sm leading-5 text-kit-fg\">\n <TypeOut text={out} />\n </div>\n )}\n </div>\n <div className=\"flex items-center justify-between gap-2 border-t border-kit-line px-3 py-2\">\n <Button size=\"xs\" variant=\"ghost\" onClick={onClose}>\n Discard\n </Button>\n <div className=\"flex gap-1\">\n {out || failed ? (\n <Button size=\"xs\" variant=\"ghost\" leftIcon={<IconRefresh stroke={1.5} />} onClick={() => preset && run(preset)}>\n Try again\n </Button>\n ) : null}\n <Button size=\"xs\" variant=\"primary\" disabled={!out} onClick={apply}>\n Apply\n </Button>\n </div>\n </div>\n </div>\n );\n}\n\n/* V2 components/motion.tsx Shimmer + TypeOut, kept local to the AI popover (their only kit user). */\nfunction Shimmer({ children }: { children: React.ReactNode }) {\n return (\n <span className=\"bg-[linear-gradient(90deg,var(--kit-fg-3)_0%,var(--kit-fg)_45%,var(--kit-fg-3)_90%)] bg-[length:200%_100%] bg-clip-text text-transparent [animation:kit-shimmer-text_1.6s_linear_infinite] motion-reduce:[animation:none]\">\n {children}\n </span>\n );\n}\n/**\n * Reduced motion as the app reads it: the OS query or the in-app preference (which stamps `data-reduce-motion` on\n * <html>; the kit cannot import the app's hook). Read per render, so a toggle applies to the next answer.\n */\nfunction motionReduced(): boolean {\n if (typeof window === \"undefined\") return false;\n return document.documentElement.hasAttribute(\"data-reduce-motion\") || !!window.matchMedia?.(\"(prefers-reduced-motion: reduce)\").matches;\n}\n\n/** Reduced: the whole answer at once, with no caret (canvas revamp V701, lib/motion TypeOut semantics). */\nfunction TypeOut({ text, speed = 14 }: { text: string; speed?: number }) {\n const reduce = motionReduced();\n const [n, setN] = React.useState(reduce ? text.length : 0);\n React.useEffect(() => {\n if (reduce) {\n setN(text.length);\n return;\n }\n setN(0);\n const id = setInterval(() => {\n setN((x) => {\n const next = Math.min(text.length, x + Math.max(1, Math.round(text.length / 120)));\n if (next >= text.length) clearInterval(id);\n return next;\n });\n }, speed);\n return () => clearInterval(id);\n }, [text, speed, reduce]);\n return (\n <span>\n {text.slice(0, n)}\n {n < text.length ? <span data-typeout-caret className=\"ml-0.5 inline-block h-[1em] w-[2px] translate-y-[2px] bg-kit-fg motion-safe:animate-pulse\" /> : null}\n </span>\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoCA,IAAI,OAA8E;;AAElF,IAAa,4BAA4B;CACvC,OAAO;AACT;AACA,IAAM,OAA+B;CAAE,OAAO;CAAY,MAAM;CAAU,OAAO;CAAW,WAAW;CAAe,MAAM;CAAU,QAAQ;CAAY,OAAO;CAAU,MAAM;CAAU,QAAQ;CAAqB,SAAS;CAAmB,QAAQ;CAAY,OAAO;AAAW;AAC1R,IAAM,UAAU,MAAe,UAAU,CAAwB,IAAI,SAAS,KAAK,MAAM;AAGzF,IAAM,WAAW,MAAc,EAAE,QAAQ,MAAM,OAAO,CAAC,CAAC,QAAQ,MAAM,MAAM,CAAC,CAAC,QAAQ,MAAM,MAAM;;AAElG,IAAM,cAAc,SAClB,KACG,MAAM,KAAK,CAAC,CACZ,KAAK,MAAM,EAAE,KAAK,CAAC,CAAC,CACpB,OAAO,OAAO,CAAC,CACf,KAAK,MAAM,MAAM,QAAQ,CAAC,EAAE,KAAK,CAAC,CAClC,KAAK,EAAE;;;;;AAKZ,SAAS,cAAc,OAAsB,OAAoB,MAAiB,MAAc,MAAyD;CACvJ,IAAI;EACF,MAAM,MAAM,MAAM,MAAM,MAAM;GAAE;GAAO;EAAK,GAAG,IAAI;EACnD,OAAO,IAAI,OAAO,SAAS,EAAE,SAAS,GAAG,MAAM,MAAM,cAAc,IAAI,OAAO,KAAK,IAAI,IAAI,IAAI,EAAE,OAA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**\n * FIELD SHELL — the one field chrome (V2 HEAD 9829bf1 kit/engine/field-shell.tsx; production FieldShell + CPO D8).\n *\n * [Label *] [ⓘ] [override dot] [changed dot] [synced] [EN] …… [42 / 60] [action] [Reset] [undo] [comments] [presence] [⋯]\n * help text (CPO D39: 12/16 --fg-3, 4px under the label, 1–2 lines; hidden while an error shows)\n * ┌ control ───────────────────────────────┐ ← peer editing: the control's border in their colour\n * └────────────────────────────────────────┘\n * error / warning message ……………………… meta (42 / 60)\n *\n * Accessories (add-comment, ⋯) take NO space at rest; they appear on hover/focus (always on touch). A comment\n * COUNT chip is always visible. AI lives in ⋯ (\"Rewrite with AI\"), never as a label sparkle (CPO-142).\n *\n * Services (toast, AI rewrite, in-place comments) come from KitServices; a missing service hides its surface.\n */\nimport * as React from \"react\";\nimport { createPortal } from \"react-dom\";\nimport {\n IconAlertCircle, IconAlertTriangle, IconArrowBackUp, IconBraces, IconClipboard, IconCopy, IconDots, IconHistory, IconInfoCircle,\n IconLock, IconMessage, IconMessagePlus, IconRefresh, IconRotate, IconWorld,\n} from \"@tabler/icons-react\";\nimport { AnimatePresence, motion } from \"framer-motion\";\nimport { Button, Sparkle } from \"../ui/button\";\nimport { Avatar, avatarRingSpread } from \"../ui/display\";\nimport { Menu, MenuContent, MenuItem, MenuSeparator, MenuTrigger, Popover, PopoverAnchor, PopoverContent, Tooltip } from \"../ui/overlay\";\nimport { presenceColor } from \"../ui/presence\";\nimport { cn } from \"../lib/cn\";\nimport { HISTORY_SEGMENT, type FieldPath, type FieldSchema } from \"../schema/types\";\nimport { resolveHelp } from \"../schema/help\";\nimport { AI_PRESETS, FieldHeaderSlot, KitSectionTitle, seesDevSurfaces, useForm, useKitEnv, useKitServices, type AiPreset, type KitPeer } from \"../context\";\nimport { pathKey, same } from \"../lib/path\";\nimport { isTextual, plainText } from \"../lib/schema\";\nimport { textLength, type KitIssue } from \"../lib/validate\";\nimport { RowChrome } from \"./bits\";\n\n/* ── Clipboard shared by every field (typed, so Paste can refuse with a reason) ── */\n/** `html`: a rich text value as its editor html (read through the host's codec), so Paste re-stores it for the target field. */\nlet clip: { type: string; value: unknown; label: string; html?: string } | null = null;\n/** Test seam: forget the shared field clipboard. */\nexport const resetFieldClipboard = () => {\n clip = null;\n};\nconst KIND: Record<string, string> = { image: \"an image\", file: \"a file\", video: \"a video\", reference: \"a reference\", link: \"a link\", button: \"a button\", array: \"a list\", slot: \"blocks\", object: \"a group of fields\", boolean: \"an on/off value\", number: \"a number\", color: \"a colour\" };\nconst kindOf = (t: string) => (isTextual(t as FieldSchema[\"type\"]) ? \"text\" : KIND[t] ?? t);\n\ntype RichTextCodec = NonNullable<ReturnType<typeof useKitServices>[\"richText\"]>;\nconst escHtml = (s: string) => s.replace(/&/g, \"&amp;\").replace(/</g, \"&lt;\").replace(/>/g, \"&gt;\");\n/** Plain text as editor html: one escaped paragraph per line. */\nconst paragraphs = (text: string) =>\n text\n .split(/\\n+/)\n .map((l) => l.trim())\n .filter(Boolean)\n .map((l) => `<p>${escHtml(l)}</p>`)\n .join(\"\");\n/**\n * Html into a rich text field, stored in the field's own shape through the host's codec. A write that would drop\n * something is refused with the words the codec names; nothing is stored.\n */\nfunction richTextWrite(codec: RichTextCodec, field: FieldSchema, path: FieldPath, html: string, prev: unknown): { value: unknown } | { refused: string } {\n try {\n const out = codec.write(html, { field, path }, prev);\n return out.losses.length ? { refused: `${field.title} can't keep ${out.losses.join(\", \")}` } : { value: out.value };\n } catch (err) {\n return { refused: `${field.title} could not store this text (${err instanceof Error ? err.message : String(err)})` };\n }\n}\n/** A rich text value as editor html, when the host's codec reads it. */\nfunction richTextHtml(codec: RichTextCodec | undefined, field: FieldSchema, path: FieldPath, value: unknown): string | undefined {\n if (!codec || field.type !== \"richtext\") return undefined;\n try {\n return codec.read(value, { field, path }).html;\n } catch {\n return undefined; // Paste falls back to the value's words\n }\n}\n\nexport const apiName = (schemaName: string, path: FieldPath) =>\n [schemaName, ...path.filter((s) => s !== HISTORY_SEGMENT)].reduce<string>((a, s) => (typeof s === \"number\" ? `${a}[${s}]` : a ? `${a}.${s}` : String(s)), \"\");\n\n/** A long label truncates on one line; past this many characters a native `title` carries the full label (DESIGN 4.4). */\nexport const LABEL_HINT_AT = 28;\n\n/* D63: add-comment and ⋯ are hidden at rest and show on THIS field's hover or focus (not a parent group's), always on\n touch, and while their menu or popover is open. The rule lives in tokens.css ([data-field-reveal]) because a Tailwind\n group variant matches every ancestor field, so hovering a group used to reveal the chrome of all its children. */\n\nexport interface FieldShellProps {\n field: FieldSchema;\n path: FieldPath;\n id: string;\n value: unknown;\n onChange: (v: unknown) => void;\n readOnly?: boolean;\n issue?: KitIssue;\n /** label-row action (e.g. slug \"Generate\") */\n action?: React.ReactNode;\n /** \"card\" = the boolean switch card · \"row\" = the control IS a labelled row (a drill-in object, CPO D45): no label row,\n * the chrome goes into the row through `RowChrome` */\n layout?: \"stack\" | \"card\" | \"row\";\n /** layout fields get no comment control */\n noComments?: boolean;\n /** right side of the message line (counters, \"3 items · max 6\") */\n meta?: React.ReactNode;\n className?: string;\n children: React.ReactNode;\n}\n\nexport function FieldShell({ field, path, id, value, onChange, readOnly, issue, action, layout = \"stack\", noComments, meta, className, children }: FieldShellProps) {\n const env = useKitEnv();\n const form = useForm();\n const services = useKitServices();\n const key = pathKey(path);\n /* A host can lift this field's chrome into its own header (All fields: a block whose only field is \"Stats\" under a\n \"Stats\" section) — then there is no label row at all; the label stays for screen readers. */\n const slot = React.useContext(FieldHeaderSlot);\n const lifted = slot && slot.key === key && layout === \"stack\" ? slot.el : null;\n const [ai, setAi] = React.useState(false);\n const [commentsOpen, setCommentsOpen] = React.useState(false);\n /* V2 fieldPopoverCollision: the comments popover stays inside the scrolling area the field sits in */\n const [commentArea, setCommentArea] = React.useState<CommentCollision>({ collisionPadding: 12 });\n const peers = env.presence[key] ?? [];\n const editor = peers.find((p) => p.status !== \"viewing\");\n const InPlaceComments = services.FieldComments;\n /* a meta-form (the schema editor's field settings) shows no comment, ⋯ or per-field undo chrome (KitEnv.fieldChrome) */\n const quiet = env.fieldChrome === \"quiet\";\n const bare = quiet || env.fieldChrome === \"preview\";\n const canComment = !noComments && !bare && (!!env.onComment || !!InPlaceComments);\n const openCount = env.comments[key] ?? 0; // with no env.onComment and a count hook, CommentButton reads the store\n const useStoreCount = env.onComment ? undefined : services.useFieldCommentCount;\n const changed = !!form?.hasPublished && !same(value, form.publishedAt(path));\n /* component instance (D28): a top-level field either inherits the component's value or overrides it */\n const inh = form?.inherited && path.length === 1 ? form.inherited : undefined;\n const overridden = !!inh && inh.isOverridden(key);\n /* D61: while the host's History is open, a changed field gets the host's 2px author-colour bar at its left edge\n (with its hover card) instead of the quiet \"changed\" dot. At rest (History closed) the dot stays. */\n const reviewing = !!env.review;\n const bar = env.review && env.review.count(path) > 0 ? env.review.bar(path, field) : null;\n const sectionTitle = React.useContext(KitSectionTitle);\n /* \"Options\" in a section called \"Options\": the section heading already names the field (the label stays for readers) */\n const repeatsSection = quiet && layout === \"stack\" && !!sectionTitle && sectionTitle.trim().toLowerCase() === field.title.trim().toLowerCase();\n const canUndo = !bare && !!form?.canUndo(key) && !readOnly;\n const synced = field.synced?.from; // a whole synced form shows one notice at its root, not a chip per field\n const limit = field.validation?.max ?? field.validation?.recommendedMax;\n const len = textLength(value);\n /* counters stay quiet: shown while the field has focus, or when the value nears its limit */\n const near = !!limit && len >= limit * 0.8;\n const counter =\n limit && (field.type === \"string\" || field.type === \"text\" || field.type === \"richtext\") ? (\n <span\n data-slot=\"field-counter\"\n className={cn(\n \"tabular-nums text-kit-xs\",\n !near && \"hidden group-focus-within/field:inline\",\n field.validation?.max && len > field.validation.max ? \"text-kit-danger-fg\" : field.validation?.recommendedMax && len > field.validation.recommendedMax ? \"text-kit-warning-fg\" : \"text-kit-fg-3\",\n )}\n >\n {len} / {limit}\n </span>\n ) : null;\n\n /* ── Help (CPO D39) ── one line under the label; longer text behind ⓘ. Dense hosts (env.helpDisplay \"tooltip\")\n move the line into the ⓘ too. An error REPLACES the help (warnings keep it: they're advice, not a block). */\n const dense = env.helpDisplay === \"tooltip\";\n /* D70: a field locked for this person (its own edit cap, in a form they can otherwise change) says so: a small lock glyph\n before the reason. A whole read-only form (Viewer, view as) stays plain text with no glyphs (D58). */\n const lockedHere = !!readOnly && !!field.access?.edit && !env.readOnly && !env.can(field.access.edit);\n const help = lockedHere ? (field.lockReason?.trim() || \"Set by developers\").replace(/\\.?$/, \".\") : resolveHelp(field); // arrays / slots / objects reach the shell without KitField: conventions apply here too\n const helpNode = lockedHere ? (\n <span data-locked=\"\" className=\"inline-flex items-start gap-1\">\n <IconLock className=\"mt-px size-3 shrink-0\" stroke={1.75} aria-hidden />\n <span>\n <span className=\"sr-only\">Locked. </span>\n {help}\n </span>\n </span>\n ) : (\n help\n );\n const more = field.helpMore || undefined;\n const erroring = issue?.level === \"error\";\n // a lock's reason stays on the field even in a dense host: it says why the value can't change\n const helpInline = !!help && (!dense || lockedHere) && !erroring;\n const tip = dense && !lockedHere ? [help, more].filter(Boolean).join(\" \") : more;\n const helpId = `${id}-help`;\n const moreId = `${id}-more`;\n const msgId = `${id}-msg`;\n const describedBy = [helpInline && helpId, tip && moreId, issue && msgId].filter(Boolean).join(\" \");\n /* Controls are many (input, textarea, contenteditable, pickers); the shell owns the ids, so it wires\n aria-describedby onto whatever element carries the field id, keeping any ids the control set itself. */\n React.useEffect(() => {\n const el = document.getElementById(id);\n if (!el) return;\n const own = (el.getAttribute(\"aria-describedby\") ?? \"\").split(\" \").filter((t) => t && !t.startsWith(`${id}-`));\n const next = [...own, ...describedBy.split(\" \").filter(Boolean)].join(\" \");\n if (next) el.setAttribute(\"aria-describedby\", next);\n else el.removeAttribute(\"aria-describedby\");\n }, [id, describedBy]);\n const info = tip ? (\n <Tooltip content={<span className=\"block max-w-[260px] whitespace-normal font-normal leading-4\">{tip}</span>}>\n <button type=\"button\" aria-label={`About ${field.title}`} className=\"-my-0.5 inline-flex size-4 shrink-0 items-center justify-center rounded-kit-sm text-kit-fg-4 hover:text-kit-fg-2\">\n <IconInfoCircle className=\"size-3.5\" stroke={1.5} aria-hidden />\n <span id={moreId} className=\"sr-only\">{tip}</span>\n </button>\n </Tooltip>\n ) : null;\n\n // KP-029/223: a long label truncates on one line with a native title; the boolean card's label wraps under its switch.\n const longTitle = field.title.length > LABEL_HINT_AT ? field.title : undefined;\n const labelOf = (wrap: boolean) => (\n <>\n <span className={wrap ? \"min-w-0 break-words\" : \"truncate\"}>{field.title}</span>\n {field.validation?.required ? (\n <>\n <span aria-hidden className=\"text-kit-fg-2\">*</span>\n <span className=\"sr-only\">(required)</span>\n </>\n ) : null}\n </>\n );\n const label = labelOf(false);\n const badges = (\n <>\n {overridden ? (\n <Tooltip content={`Overrides ${inh!.from}. Changes to the block no longer reach this field.`}>\n <span role=\"img\" className=\"size-1.5 shrink-0 rounded-full bg-kit-accent\" aria-label={`Overrides ${inh!.from}`} />\n </Tooltip>\n ) : null}\n {changed && !reviewing ? (\n <Tooltip content=\"Changed since publish\">\n <span role=\"img\" className=\"size-1.5 shrink-0 rounded-full bg-kit-warning\" aria-label=\"Changed since publish\" />\n </Tooltip>\n ) : null}\n {synced ? (\n <Tooltip content={`Synced from ${synced}. Changes apply on every page that uses it.`}>\n <span className=\"inline-flex h-4 shrink-0 items-center gap-0.5 rounded-kit-md bg-kit-info-soft px-1 text-kit-2xs font-medium text-kit-info-fg\">\n <IconRefresh className=\"size-2.5\" stroke={2} aria-hidden />\n Synced\n </span>\n </Tooltip>\n ) : null}\n {field.localized ? (\n <Tooltip content=\"Translatable: this field can hold a value for each of the site's languages.\">\n <span className=\"inline-flex h-4 shrink-0 items-center gap-0.5 rounded-kit-md bg-kit-muted px-1 text-kit-2xs font-medium text-kit-fg-3\">\n <IconWorld className=\"size-2.5\" stroke={2} aria-hidden />\n EN\n </span>\n </Tooltip>\n ) : null}\n </>\n );\n const accessories = (\n <>\n {action}\n {overridden && !readOnly ? (\n <Tooltip content={`Use ${inh!.from}'s value again`}>\n <button\n type=\"button\"\n onClick={(e) => {\n const box = (e.currentTarget as HTMLElement).closest<HTMLElement>(\"[data-field-key]\");\n inh!.reset(key);\n // the button goes away with the override: keep focus in the field, never on <body>\n requestAnimationFrame(() => (document.getElementById(id) ?? box?.querySelector<HTMLElement>(\"textarea, input, [contenteditable=true], button\"))?.focus({ preventScroll: true }));\n }}\n aria-label={`Reset ${field.title} to ${inh!.from}`}\n className=\"inline-flex h-5 items-center rounded-kit-md px-1 text-kit-xs text-kit-fg-3 hover:bg-kit-hover hover:text-kit-fg\"\n >\n Reset\n </button>\n </Tooltip>\n ) : null}\n {canUndo ? (\n <Tooltip content={`Undo last change to ${field.title}`}>\n <button type=\"button\" aria-label={`Undo last change to ${field.title}`}\n onClick={(e) => {\n const btn = e.currentTarget as HTMLElement;\n const box = btn.closest<HTMLElement>(\"[data-field-key]\");\n form?.undo(key);\n // KB-006: the last undo takes the button away; keep focus in the field, never on <body>\n requestAnimationFrame(() => {\n if (!btn.isConnected) (document.getElementById(id) ?? box?.querySelector<HTMLElement>(\"textarea, input, [contenteditable=true], button\"))?.focus({ preventScroll: true });\n });\n }}\n className=\"inline-flex size-5 items-center justify-center rounded-kit-md text-kit-fg-3 hover:bg-kit-hover hover:text-kit-fg\">\n <IconArrowBackUp className=\"size-3.5\" stroke={1.5} aria-hidden />\n </button>\n </Tooltip>\n ) : null}\n {canComment ? (\n <CommentButton\n count={openCount}\n useCount={useStoreCount ? () => useStoreCount(env.docId, key) : undefined}\n label={field.title}\n open={commentsOpen}\n onOpen={(el) => {\n if (env.onComment) return env.onComment(path, field); // the host owns comments (e.g. the document editor)\n setCommentArea(fieldPopoverCollision(el.closest(\"[data-field-key]\")));\n setCommentsOpen(true);\n }}\n />\n ) : null}\n <PeerStack peers={peers} />\n {bare ? null : <FieldMenu field={field} path={path} value={value} onChange={onChange} readOnly={!!readOnly} changed={changed} onAi={() => setAi(true)} />}\n </>\n );\n\n // Peer editing (Figma / Notion / Sanity): only the field's own input border takes their --presence-n colour (full strength:\n // the old 70% mix read as a validation error at 1.96:1) —\n // no outline around the input + preview, no name tag over the border, no layout shift. Who it is: the face in the label row.\n const control = (\n <div\n className={cn(\"relative\", editor && \"[&_.border-kit-field-border]:border-[var(--peer)]\")}\n style={editor ? ({ \"--peer\": editor.color ?? presenceColor(editor.id ?? editor.name) } as React.CSSProperties) : undefined}\n >\n {children}\n </div>\n );\n\n const message =\n issue || meta ? (\n <div className=\"flex min-h-4 items-start justify-between gap-3\">\n <AnimatePresence initial={false}>\n {issue ? (\n <motion.p\n key={issue.message}\n id={msgId}\n initial={{ opacity: 0, y: -2 }}\n animate={{ opacity: 1, y: 0 }}\n role={issue.level === \"error\" ? \"alert\" : \"status\"}\n className={cn(\"flex min-w-0 items-start gap-1 text-kit-xs\", issue.level === \"error\" ? \"text-kit-danger-fg\" : \"text-kit-warning-fg\")}\n >\n {issue.level === \"error\" ? <IconAlertCircle className=\"mt-px size-3.5 shrink-0\" stroke={1.5} aria-hidden /> : <IconAlertTriangle className=\"mt-px size-3.5 shrink-0\" stroke={1.5} aria-hidden />}\n <span className=\"min-w-0\">\n {issue.message}\n {issue.fix && !readOnly ? (\n <>\n {\" \"}\n <button type=\"button\" onClick={issue.fix.apply} className=\"font-medium text-kit-fg underline-offset-2 hover:underline\">\n {issue.fix.label}\n </button>\n </>\n ) : null}\n </span>\n </motion.p>\n ) : (\n <span />\n )}\n </AnimatePresence>\n {meta ? <span className=\"flex shrink-0 items-center gap-2\">{meta}</span> : null}\n </div>\n ) : null;\n\n const labelEl = (\n <label\n htmlFor={id}\n id={`${id}-label`}\n className=\"flex min-w-0 items-center gap-1 text-kit-sm font-medium text-kit-fg-2 transition-colors group-focus-within/field:text-kit-fg\"\n title={longTitle}\n >\n {label}\n </label>\n );\n\n const body =\n layout === \"row\" ? (\n <div className={cn(\"group/field relative flex min-w-0 flex-col gap-1.5\", className)} data-field-key={key} data-field={path.length === 1 ? key : undefined} data-slot=\"kit-field\">\n {bar}\n <RowChrome.Provider value={<>{info}{badges}{accessories}</>}>{control}</RowChrome.Provider>\n {message}\n </div>\n ) : layout === \"card\" && quiet ? (\n /* the inspector's PRow: label left, switch right, no card (a meta-form's Required, Unique, Tuck into Advanced) */\n <div className={cn(\"group/field relative flex flex-col gap-1\", className)} data-field-key={key} data-field={path.length === 1 ? key : undefined} data-slot=\"kit-field\">\n {bar}\n <div data-field-head=\"\" className=\"flex min-h-8 items-center gap-3\">\n <label htmlFor={id} id={`${id}-label`} className=\"min-w-0 flex-1 cursor-pointer\" title={longTitle}>\n <span className=\"flex min-w-0 items-center gap-1 text-kit-sm font-medium text-kit-fg-2 transition-colors group-focus-within/field:text-kit-fg\">\n {label}\n {info}\n {badges}\n </span>\n {helpInline ? (\n <span id={helpId} data-slot=\"field-help\" className=\"mt-0.5 block text-kit-xs leading-4 text-kit-fg-3\">\n {helpNode}\n </span>\n ) : null}\n </label>\n <span className=\"flex shrink-0 items-center gap-0.5 empty:hidden\">{accessories}</span>\n <span className=\"flex shrink-0 items-center\">{readOnly ? <span className=\"text-kit-sm text-kit-fg-2\">{value ? \"On\" : \"Off\"}</span> : control}</span>\n </div>\n {message}\n </div>\n ) : layout === \"card\" ? (\n <div className={cn(\"group/field relative flex flex-col gap-1.5\", className)} data-field-key={key} data-field={path.length === 1 ? key : undefined} data-slot=\"kit-field\">\n {bar}\n <div data-field-head=\"\" className={cn(\"flex items-center gap-3 rounded-kit-lg border bg-kit-surface px-3 py-2.5 transition-colors\", issue?.level === \"error\" ? \"border-[var(--kit-field-invalid)]\" : \"border-kit-line hover:border-kit-line-strong\")}>\n {control}\n <label htmlFor={id} id={`${id}-label`} className=\"min-w-0 flex-1 cursor-pointer\" title={longTitle}>\n <span className=\"flex min-w-0 items-center gap-1.5 text-kit-sm font-medium text-kit-fg\">\n {labelOf(true)}\n {info}\n {badges}\n </span>\n {helpInline ? (\n <span id={helpId} data-slot=\"field-help\" className=\"block text-kit-xs leading-4 text-kit-fg-3\">\n {helpNode}\n </span>\n ) : null}\n </label>\n <span className=\"shrink-0 text-kit-xs text-kit-fg-3\">{value ? \"On\" : \"Off\"}</span>\n <span className=\"flex shrink-0 items-center gap-0.5 empty:hidden\">{accessories}</span>\n </div>\n {message}\n </div>\n ) : (\n <div\n className={cn(\"group/field relative flex min-w-0 flex-col gap-1.5\", className)}\n data-field-key={key}\n data-field={path.length === 1 ? key : undefined}\n data-slot=\"kit-field\"\n data-inherited={inh && !overridden ? \"\" : undefined}\n data-overridden={overridden ? \"\" : undefined}\n >\n {bar}\n {repeatsSection ? (\n <label htmlFor={id} id={`${id}-label`} className=\"sr-only\">\n {label}\n </label>\n ) : lifted ? (\n <>\n <label htmlFor={id} id={`${id}-label`} className=\"sr-only\">\n {label}\n </label>\n {createPortal(\n <span className=\"flex items-center gap-0.5 [&>button]:!inline-flex\">\n {info}\n {badges}\n {counter}\n {accessories}\n </span>,\n lifted,\n )}\n </>\n ) : (\n <div data-slot=\"field-label-row\" data-field-head=\"\" className=\"flex min-h-5 min-w-0 items-center gap-1.5\">\n {labelEl}\n {info}\n {badges}\n <span className=\"flex-1\" />\n {counter}\n <span className=\"flex shrink-0 items-center gap-0.5\">{accessories}</span>\n </div>\n )}\n {helpInline ? (\n <p id={helpId} data-slot=\"field-help\" className=\"-mt-0.5 text-kit-xs leading-4 text-kit-fg-3\">\n {helpNode}\n </p>\n ) : null}\n {control}\n {message}\n </div>\n );\n\n /* The AI popover and the comments popover both anchor to the field (two stacked anchor divs). */\n return (\n <Popover open={ai} onOpenChange={setAi}>\n <PopoverAnchor className=\"min-w-0\">\n <Popover\n open={commentsOpen}\n onOpenChange={(open, d) => {\n /* V2 guardEscape: Escape inside the composer (data-esc-owner) belongs to the draft, not the popover */\n if (!open && d.reason === \"escape-key\" && (document.activeElement as HTMLElement | null)?.hasAttribute(\"data-esc-owner\")) return d.cancel();\n setCommentsOpen(open);\n }}\n >\n <PopoverAnchor className=\"min-w-0\">{body}</PopoverAnchor>\n {commentsOpen && InPlaceComments ? (\n <PopoverContent align=\"start\" sideOffset={8} {...commentArea} initialFocus={false} className=\"w-[clamp(280px,var(--anchor-width),420px)] p-0\">\n <InPlaceComments\n docId={env.docId}\n fieldKey={key}\n label={field.title}\n quote={plainText(value).slice(0, 80) || undefined}\n onClose={() => setCommentsOpen(false)}\n onOpenPanel={\n env.onComment\n ? () => {\n env.onComment?.(path, field);\n setCommentsOpen(false);\n }\n : undefined\n }\n />\n </PopoverContent>\n ) : null}\n </Popover>\n </PopoverAnchor>\n {ai ? (\n <PopoverContent align=\"start\" sideOffset={8} className=\"w-[clamp(300px,var(--anchor-width),440px)] p-0\">\n <AiRewrite field={field} path={path} value={value} onChange={onChange} onClose={() => setAi(false)} />\n </PopoverContent>\n ) : null}\n </Popover>\n );\n}\n\ntype CommentCollision = { collisionBoundary?: Element; collisionPadding: number | Partial<Record<\"top\" | \"right\" | \"bottom\" | \"left\", number>> };\n/** V2 features/comments fieldPopoverCollision: inside a scrolling panel, collide with that panel below its sticky header. */\nfunction fieldPopoverCollision(anchor: Element | null): CommentCollision {\n let area = anchor?.parentElement ?? null;\n while (area && !/(auto|scroll)/.test(getComputedStyle(area).overflowY)) area = area.parentElement;\n if (!area || area === document.scrollingElement) return { collisionPadding: 12 };\n const sticky = parseFloat(getComputedStyle(area).getPropertyValue(\"--kit-sticky-top\")) || 0;\n return { collisionBoundary: area, collisionPadding: { top: sticky + 8, right: 8, bottom: 8, left: 8 } };\n}\n\n/** Comment count chip (always visible) or the hover-revealed \"Add comment\" icon. `useCount` (the host's store hook)\n * replaces `count` when the kit draws the comments in place. */\nfunction CommentButton({ useCount, ...props }: CommentButtonProps & { useCount?: () => number }) {\n return useCount ? <StoreCommentButton useCount={useCount} {...props} /> : <CountedCommentButton {...props} />;\n}\ninterface CommentButtonProps {\n count: number;\n label: string;\n open: boolean;\n onOpen: (el: HTMLElement) => void;\n}\nfunction StoreCommentButton({ useCount, ...props }: CommentButtonProps & { useCount: () => number }) {\n return <CountedCommentButton {...props} count={useCount()} />;\n}\nfunction CountedCommentButton({ count, label, open, onOpen }: CommentButtonProps) {\n if (count > 0)\n return (\n <Tooltip content={`${count} open comment${count === 1 ? \"\" : \"s\"} on ${label}`}>\n <button\n type=\"button\"\n onClick={(e) => onOpen(e.currentTarget)}\n data-state={open ? \"open\" : \"closed\"}\n aria-label={`${count} open comments on ${label}`}\n className=\"-my-0.5 inline-flex h-5 items-center gap-0.5 rounded-kit-md px-1 text-kit-2xs font-medium text-kit-fg-3 hover:bg-kit-hover hover:text-kit-fg data-[state=open]:bg-kit-hover data-[state=open]:text-kit-fg\"\n >\n <IconMessage className=\"size-3.5\" stroke={1.5} aria-hidden />\n <span className=\"tabular-nums\">{count}</span>\n </button>\n </Tooltip>\n );\n return (\n <Tooltip content=\"Add comment\">\n <button\n type=\"button\"\n onClick={(e) => onOpen(e.currentTarget)}\n data-state={open ? \"open\" : \"closed\"}\n aria-label={`Add comment to ${label}`}\n data-field-reveal=\"\" className={cn(\"-my-0.5 size-6 items-center justify-center rounded-kit-md text-kit-fg-3 hover:bg-kit-hover hover:text-kit-fg\")}\n >\n <IconMessagePlus className=\"size-3.5\" stroke={1.5} aria-hidden />\n </button>\n </Tooltip>\n );\n}\n\n/** Who is in this field: 16px faces in the label row's action slot (no overlap with the label or the input), name on hover. */\nexport function PeerStack({ peers, size = 16 }: { peers: KitPeer[]; size?: number }) {\n const shown = peers.slice(0, 3);\n const rest = peers.length - shown.length;\n // Each slot reserves the ring band (1px surface gap + 1px presence colour) on every side, so the ring sits inside\n // the slot: a clipping ancestor or the row's edge can never shave it. Faces still overlap by 25% of their size.\n const ring = \"var(--kit-avatar-ring, var(--kit-surface))\";\n const band = avatarRingSpread({ ring, ringWidth: 1, ringAccent: \"x\" });\n const box = size + band * 2;\n const overlap = -(Math.round(size * 0.25) + band * 2);\n return (\n <AnimatePresence initial={false}>\n {shown.length ? (\n <motion.span key=\"peers\" initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }} transition={{ duration: 0.25 }} className=\"flex h-5 items-center\" data-slot=\"field-presence\">\n {/* D34 stack rules: same size, 25% overlap, first face on top; the ring is box-shadow (surface gap + the\n peer's presence colour) so the photo keeps its full size. */}\n {shown.map((p, i) => (\n <Tooltip key={p.name + i} content={`${p.name} · ${p.status === \"viewing\" ? \"Viewing\" : \"Editing\"} this field`}>\n <span\n style={{ marginLeft: i ? overlap : 0, zIndex: shown.length - i + 1, width: box, height: box }}\n className={cn(\"relative inline-flex shrink-0 rounded-full transition-transform duration-150 hover:!z-30 hover:-translate-y-px\", p.status === \"viewing\" && \"opacity-60\")}\n >\n <Avatar name={p.name} src={p.avatar} size={size} ring={ring} ringWidth={1} ringAccent={p.color ?? presenceColor(p.id ?? p.name)} decorative />\n </span>\n </Tooltip>\n ))}\n {rest > 0 ? (\n <Tooltip content={peers.slice(shown.length).map((p) => p.name).join(\", \")}>\n <span style={{ marginLeft: overlap, width: box, height: box, padding: band }} className=\"relative z-[1] inline-flex shrink-0\">\n <span\n style={{ width: size, height: size, boxShadow: `0 0 0 ${band}px var(--kit-surface)`, fontSize: Math.max(8, Math.round(size * 0.5)) }}\n className=\"inline-flex items-center justify-center rounded-full bg-kit-muted font-medium leading-none tabular-nums text-kit-fg-2\"\n >\n +{rest}\n </span>\n </span>\n </Tooltip>\n ) : null}\n </motion.span>\n ) : null}\n </AnimatePresence>\n );\n}\n\n/* ── ⋯ Field actions (DESIGN 8.25) ─────────────────────────────────── */\nfunction FieldMenu({ field, path, value, onChange, readOnly, changed, onAi }: { field: FieldSchema; path: FieldPath; value: unknown; onChange: (v: unknown) => void; readOnly: boolean; changed: boolean; onAi: () => void }) {\n const form = useForm();\n const env = useKitEnv();\n const { toast, aiRewrite, richText, FieldMenuExtras } = useKitServices();\n const key = pathKey(path);\n const api = apiName(form?.schema.name ?? \"doc\", path);\n const textual = isTextual(field.type);\n // rich text is rewritten only where the host's codec can store the result in the field's own shape\n const prose = field.type === \"string\" || field.type === \"text\" || (field.type === \"richtext\" && !!richText);\n const editable = !readOnly;\n const dev = seesDevSurfaces(env);\n return (\n <Menu>\n <Tooltip content=\"Field actions\">\n <MenuTrigger\n aria-label={`${field.title} actions`}\n data-field-reveal=\"\" className={cn(\"-my-0.5 size-6 items-center justify-center rounded-kit-md text-kit-fg-3 hover:bg-kit-hover hover:text-kit-fg data-[popup-open]:bg-kit-hover data-[popup-open]:text-kit-fg\")}\n >\n <IconDots className=\"size-3.5\" stroke={1.5} aria-hidden />\n </MenuTrigger>\n </Tooltip>\n <MenuContent align=\"end\" className=\"w-60\">\n <MenuItem\n icon={<IconCopy stroke={1.5} />}\n onClick={() => {\n const html = richTextHtml(richText, field, path, value);\n clip = { type: field.type, value: structuredCloneish(value), label: field.title, ...(html !== undefined ? { html } : {}) };\n const text = textual ? plainText(value) || \"\" : typeof value === \"string\" ? value : JSON.stringify(value ?? null, null, 2);\n void navigator.clipboard?.writeText(text).catch(() => {});\n toast?.success(`${field.title} copied`);\n }}\n >\n Copy value\n </MenuItem>\n {editable ? <PasteItem field={field} path={path} value={value} onChange={onChange} /> : null}\n {editable && form?.hasPublished && changed ? (\n <MenuItem\n icon={<IconRotate stroke={1.5} />}\n onClick={() => {\n const prev = value;\n onChange(form.publishedAt(path));\n toast?.(`${field.title} reset to published`, { action: { label: \"Undo\", onClick: () => onChange(prev) }, duration: 10_000 });\n }}\n >\n Reset to published\n </MenuItem>\n ) : null}\n {env.onFieldHistory ? (\n <MenuItem icon={<IconHistory stroke={1.5} />} onClick={() => env.onFieldHistory!(path, field)}>\n History\n </MenuItem>\n ) : null}\n {FieldMenuExtras ? <FieldMenuExtras field={field} path={path} readOnly={readOnly} /> : null}\n {editable && prose && aiRewrite ? (\n <>\n <MenuSeparator />\n {form?.aiKeys.has(key) ? (\n <MenuItem\n icon={<IconArrowBackUp stroke={1.5} />}\n onClick={() => {\n form.undo(key);\n form.markAi(key, false);\n }}\n >\n Undo AI change\n </MenuItem>\n ) : null}\n <MenuItem icon={<Sparkle size={16} />} onClick={() => window.setTimeout(onAi, 0)}>\n Rewrite with AI\n </MenuItem>\n </>\n ) : null}\n {dev ? <MenuSeparator /> : null}\n {dev ? (\n <MenuItem\n icon={<IconBraces stroke={1.5} />}\n onClick={() => {\n void navigator.clipboard?.writeText(api).catch(() => {});\n toast?.success(`Copied ${api}`);\n }}\n >\n <span className=\"flex w-full items-center justify-between gap-3\">\n Copy API name\n <span className=\"truncate font-kit-mono text-kit-2xs text-kit-fg-3\">{api.length > 22 ? `…${api.slice(-20)}` : api}</span>\n </span>\n </MenuItem>\n ) : null}\n </MenuContent>\n </Menu>\n );\n}\n/** Reads the shared clipboard when the menu opens (it mounts with the popup), so a copy in another field is seen. */\nfunction PasteItem({ field, path, value, onChange }: { field: FieldSchema; path: FieldPath; value: unknown; onChange: (v: unknown) => void }) {\n const { toast, richText } = useKitServices();\n const textual = isTextual(field.type);\n // text into rich text needs the host's codec to store it in the field's shape\n const needsCodec = !!clip && field.type === \"richtext\" && clip.type !== \"richtext\" && !richText;\n const pasteOk = clip && !needsCodec && (clip.type === field.type || (textual && isTextual(clip.type as FieldSchema[\"type\"])));\n const pasteReason = !clip\n ? \"Copy a value from a field first.\"\n : needsCodec\n ? \"This rich text field takes a copied rich text value only.\"\n : pasteOk\n ? null\n : `Clipboard holds ${kindOf(clip.type)}. This field takes ${kindOf(field.type)}.`;\n return (\n <MenuItem\n icon={<IconClipboard stroke={1.5} />}\n disabled={!pasteOk}\n className={cn(pasteReason && \"h-auto py-1.5\")}\n onClick={() => {\n if (!clip) return;\n const prev = value;\n let next: unknown;\n if (field.type === \"richtext\" && richText && (clip.type !== \"richtext\" || clip.html !== undefined)) {\n // through the codec: the target field's own shape and Accept list, refused by name when it would drop something\n const out = richTextWrite(richText, field, path, clip.html ?? paragraphs(plainText(clip.value)), prev);\n if (\"refused\" in out) {\n toast?.(`Not pasted: ${out.refused}.`);\n return;\n }\n next = out.value;\n } else next = textual && clip.type === \"richtext\" && field.type !== \"richtext\" ? plainText(clip.value) : structuredCloneish(clip.value);\n onChange(next);\n toast?.(`Pasted into ${field.title}`, { action: { label: \"Undo\", onClick: () => onChange(prev) }, duration: 10_000 });\n }}\n >\n <span className=\"flex flex-col\">\n Paste value\n {pasteReason ? <span className=\"whitespace-normal text-kit-xs text-kit-fg-3\">{pasteReason}</span> : null}\n </span>\n </MenuItem>\n );\n}\nfunction structuredCloneish<T>(v: T): T {\n try {\n return structuredClone(v);\n } catch {\n return v;\n }\n}\n\n/* ── Rewrite with AI (preview before apply) ────────────────────────── */\nfunction AiRewrite({ field, path, value, onChange, onClose }: { field: FieldSchema; path: FieldPath; value: unknown; onChange: (v: unknown) => void; onClose: () => void }) {\n const form = useForm();\n const { toast, aiRewrite, richText } = useKitServices();\n const key = pathKey(path);\n const [preset, setPreset] = React.useState<AiPreset | null>(null);\n const [out, setOut] = React.useState<string | null>(null);\n const [failed, setFailed] = React.useState(false);\n const attempt = React.useRef(0);\n const latest = React.useRef(0);\n const source = plainText(value);\n const run = (p: AiPreset) => {\n if (!aiRewrite) return;\n setPreset(p);\n setOut(null);\n setFailed(false);\n const ticket = ++latest.current;\n Promise.resolve()\n .then(() => aiRewrite(source, p, attempt.current++))\n .then(\n (result) => {\n if (latest.current === ticket) setOut(result);\n },\n () => {\n if (latest.current === ticket) setFailed(true);\n },\n );\n };\n const apply = () => {\n if (!out) return;\n const prev = value;\n let next: unknown = out;\n if (field.type === \"richtext\") {\n const stored = richText ? richTextWrite(richText, field, path, paragraphs(out), prev) : { refused: `${field.title} has no rich text storage here` };\n if (\"refused\" in stored) {\n toast?.(`Not applied: ${stored.refused}.`);\n return;\n }\n next = stored.value;\n }\n onChange(next);\n form?.markAi(key, true);\n toast?.(\"Rewritten with AI\", {\n icon: <Sparkle size={14} />,\n action: {\n label: \"Undo\",\n onClick: () => {\n onChange(prev);\n form?.markAi(key, false);\n },\n },\n duration: 10_000,\n });\n onClose();\n };\n return (\n <div className=\"flex flex-col\">\n <div className=\"flex items-center gap-2 border-b border-kit-line px-3 py-2.5\">\n <Sparkle size={16} />\n <span className=\"text-kit-sm font-medium text-kit-fg\">Rewrite {field.title.toLowerCase()}</span>\n </div>\n <div className=\"flex flex-wrap gap-1 px-3 pt-2.5\">\n {AI_PRESETS.map((p) => (\n <button\n key={p.id}\n type=\"button\"\n onClick={() => run(p.id)}\n className={cn(\"h-6 rounded-full border px-2 text-kit-xs transition-colors\", preset === p.id ? \"border-[var(--kit-emphasis-line)] bg-kit-surface text-kit-fg\" : \"border-kit-line text-kit-fg-2 hover:border-kit-line-strong hover:text-kit-fg\")}\n >\n {p.label}\n </button>\n ))}\n </div>\n <div className=\"px-3 py-3\">\n {!preset ? (\n <p className=\"text-kit-xs text-kit-fg-3\">Pick a direction. You'll see the suggestion before anything changes.</p>\n ) : failed ? (\n <p role=\"alert\" className=\"text-kit-xs text-kit-danger-fg\">\n Couldn't rewrite {field.title.toLowerCase()}. Try again.\n </p>\n ) : out == null ? (\n <p className=\"text-kit-sm\">\n <Shimmer>Rewriting {field.title.toLowerCase()}…</Shimmer>\n </p>\n ) : (\n <div className=\"rounded-kit-lg bg-kit-subtle p-2.5 text-kit-sm leading-5 text-kit-fg\">\n <TypeOut text={out} />\n </div>\n )}\n </div>\n <div className=\"flex items-center justify-between gap-2 border-t border-kit-line px-3 py-2\">\n <Button size=\"xs\" variant=\"ghost\" onClick={onClose}>\n Discard\n </Button>\n <div className=\"flex gap-1\">\n {out || failed ? (\n <Button size=\"xs\" variant=\"ghost\" leftIcon={<IconRefresh stroke={1.5} />} onClick={() => preset && run(preset)}>\n Try again\n </Button>\n ) : null}\n <Button size=\"xs\" variant=\"primary\" disabled={!out} onClick={apply}>\n Apply\n </Button>\n </div>\n </div>\n </div>\n );\n}\n\n/* V2 components/motion.tsx Shimmer + TypeOut, kept local to the AI popover (their only kit user). */\nfunction Shimmer({ children }: { children: React.ReactNode }) {\n return (\n <span className=\"bg-[linear-gradient(90deg,var(--kit-fg-3)_0%,var(--kit-fg)_45%,var(--kit-fg-3)_90%)] bg-[length:200%_100%] bg-clip-text text-transparent [animation:kit-shimmer-text_1.6s_linear_infinite] motion-reduce:[animation:none]\">\n {children}\n </span>\n );\n}\n/**\n * Reduced motion as the app reads it: the OS query or the in-app preference (which stamps `data-reduce-motion` on\n * <html>; the kit cannot import the app's hook). Read per render, so a toggle applies to the next answer.\n */\nfunction motionReduced(): boolean {\n if (typeof window === \"undefined\") return false;\n return document.documentElement.hasAttribute(\"data-reduce-motion\") || !!window.matchMedia?.(\"(prefers-reduced-motion: reduce)\").matches;\n}\n\n/** Reduced: the whole answer at once, with no caret (canvas revamp V701, lib/motion TypeOut semantics). */\nfunction TypeOut({ text, speed = 14 }: { text: string; speed?: number }) {\n const reduce = motionReduced();\n const [n, setN] = React.useState(reduce ? text.length : 0);\n React.useEffect(() => {\n if (reduce) {\n setN(text.length);\n return;\n }\n setN(0);\n const id = setInterval(() => {\n setN((x) => {\n const next = Math.min(text.length, x + Math.max(1, Math.round(text.length / 120)));\n if (next >= text.length) clearInterval(id);\n return next;\n });\n }, speed);\n return () => clearInterval(id);\n }, [text, speed, reduce]);\n return (\n <span>\n {text.slice(0, n)}\n {n < text.length ? <span data-typeout-caret className=\"ml-0.5 inline-block h-[1em] w-[2px] translate-y-[2px] bg-kit-fg motion-safe:animate-pulse\" /> : null}\n </span>\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoCA,IAAI,OAA8E;;AAElF,IAAa,4BAA4B;CACvC,OAAO;AACT;AACA,IAAM,OAA+B;CAAE,OAAO;CAAY,MAAM;CAAU,OAAO;CAAW,WAAW;CAAe,MAAM;CAAU,QAAQ;CAAY,OAAO;CAAU,MAAM;CAAU,QAAQ;CAAqB,SAAS;CAAmB,QAAQ;CAAY,OAAO;AAAW;AAC1R,IAAM,UAAU,MAAe,UAAU,CAAwB,IAAI,SAAS,KAAK,MAAM;AAGzF,IAAM,WAAW,MAAc,EAAE,QAAQ,MAAM,OAAO,CAAC,CAAC,QAAQ,MAAM,MAAM,CAAC,CAAC,QAAQ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