@upstart.gg/vite-plugins 0.1.67 → 0.1.69
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/upstart-editor-api.d.ts +2 -0
- package/dist/upstart-editor-api.d.ts.map +1 -1
- package/dist/upstart-editor-api.js +67 -9
- package/dist/upstart-editor-api.js.map +1 -1
- package/dist/vite-plugin-upstart-attrs.d.ts.map +1 -1
- package/dist/vite-plugin-upstart-attrs.js +18 -1
- package/dist/vite-plugin-upstart-attrs.js.map +1 -1
- package/dist/vite-plugin-upstart-editor/runtime/click-handler.d.ts.map +1 -1
- package/dist/vite-plugin-upstart-editor/runtime/click-handler.js +30 -16
- package/dist/vite-plugin-upstart-editor/runtime/click-handler.js.map +1 -1
- package/dist/vite-plugin-upstart-editor/runtime/dom-guard.js +45 -0
- package/dist/vite-plugin-upstart-editor/runtime/dom-guard.js.map +1 -0
- package/dist/vite-plugin-upstart-editor/runtime/error-handler.d.ts +7 -1
- package/dist/vite-plugin-upstart-editor/runtime/error-handler.d.ts.map +1 -1
- package/dist/vite-plugin-upstart-editor/runtime/error-handler.js +41 -2
- package/dist/vite-plugin-upstart-editor/runtime/error-handler.js.map +1 -1
- package/dist/vite-plugin-upstart-editor/runtime/image-pick.js +32 -0
- package/dist/vite-plugin-upstart-editor/runtime/image-pick.js.map +1 -0
- package/dist/vite-plugin-upstart-editor/runtime/index.d.ts.map +1 -1
- package/dist/vite-plugin-upstart-editor/runtime/index.js +7 -0
- package/dist/vite-plugin-upstart-editor/runtime/index.js.map +1 -1
- package/dist/vite-plugin-upstart-editor/runtime/text-editor.js +6 -0
- package/dist/vite-plugin-upstart-editor/runtime/text-editor.js.map +1 -1
- package/dist/vite-plugin-upstart-editor/runtime/types.d.ts +9 -0
- package/dist/vite-plugin-upstart-editor/runtime/types.d.ts.map +1 -1
- package/package.json +3 -3
- package/src/tests/dom-guard.test.ts +100 -0
- package/src/tests/image-pick.test.ts +50 -0
- package/src/tests/upstart-editor-api.test.ts +75 -0
- package/src/tests/vite-plugin-upstart-attrs.test.ts +21 -0
- package/src/upstart-editor-api.ts +74 -8
- package/src/vite-plugin-upstart-attrs.ts +44 -1
- package/src/vite-plugin-upstart-editor/runtime/click-handler.ts +29 -19
- package/src/vite-plugin-upstart-editor/runtime/dom-guard.ts +67 -0
- package/src/vite-plugin-upstart-editor/runtime/error-handler.ts +47 -1
- package/src/vite-plugin-upstart-editor/runtime/image-pick.ts +40 -0
- package/src/vite-plugin-upstart-editor/runtime/index.ts +8 -0
- package/src/vite-plugin-upstart-editor/runtime/text-editor.ts +14 -0
- package/src/vite-plugin-upstart-editor/runtime/types.ts +6 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"text-editor.js","names":[],"sources":["../../../src/vite-plugin-upstart-editor/runtime/text-editor.ts"],"sourcesContent":["import { Editor, Extension, Node } from \"@tiptap/core\";\nimport { BubbleMenu } from \"@tiptap/extension-bubble-menu\";\nimport Placeholder from \"@tiptap/extension-placeholder\";\nimport StarterKit from \"@tiptap/starter-kit\";\nimport { sendToParent } from \"./utils.js\";\nimport type { EditorInstance, TextEditorMode, UpstartEditorOptions } from \"./types.js\";\n\n/**\n * Custom Document node for inline elements (e.g. <a>, <span>, headings).\n * Uses `inline*` content instead of the default `block+` to prevent\n * TipTap from wrapping text in <p> tags inside inline elements.\n */\nconst InlineDocument = Node.create({\n name: \"doc\",\n topNode: true,\n content: \"inline*\",\n});\n\n/**\n * An atomic inline node that represents an i18n template variable like {{year}}.\n * It is displayed as a grayed non-editable chip showing the resolved value.\n * renderText() returns {{varName}} so getText() serialises back to the raw template.\n */\nconst TemplateVariable = Node.create({\n name: \"templateVariable\",\n group: \"inline\",\n inline: true,\n atom: true,\n\n addAttributes() {\n return {\n varName: { default: \"\" },\n value: { default: \"\" },\n };\n },\n\n parseHTML() {\n return [{ tag: \"span[data-tpl-var]\" }];\n },\n\n renderHTML({ node }) {\n return [\n \"span\",\n {\n \"data-tpl-var\": node.attrs.varName,\n contenteditable: \"false\",\n style:\n \"opacity:0.5;background:rgba(0,0,0,0.08);border-radius:3px;padding:0 3px;\" +\n \"font-family:monospace;font-size:0.875em;cursor:default;user-select:none;\",\n },\n node.attrs.value || `{{${node.attrs.varName}}}`,\n ];\n },\n\n renderText({ node }) {\n return `{{${node.attrs.varName}}}`;\n },\n});\n\n/**\n * An atomic inline node holding static text that surrounds an i18n node in the\n * source (e.g. the \" *\" in `<label><Trans i18nKey=\"…\" /> *</label>`).\n * It stays visible and non-editable, and renderText() returns \"\" so getText()\n * yields only the translation — the static part never leaks into the saved value.\n */\nconst StaticAffix = Node.create({\n name: \"staticAffix\",\n group: \"inline\",\n inline: true,\n atom: true,\n selectable: false,\n\n addAttributes() {\n return {\n text: { default: \"\" },\n };\n },\n\n parseHTML() {\n return [{ tag: \"span[data-static-affix]\" }];\n },\n\n renderHTML({ node }) {\n return [\n \"span\",\n {\n \"data-static-affix\": \"\",\n contenteditable: \"false\",\n style: \"cursor:default;user-select:none;white-space:pre;\",\n },\n node.attrs.text,\n ];\n },\n\n renderText() {\n return \"\";\n },\n});\n\n/**\n * Remaps Enter to insert a <br> (hard break) instead of creating a new paragraph.\n * Used in inline-rich mode where block nodes are not allowed.\n */\nconst EnterHardBreak = Extension.create({\n name: \"enterHardBreak\",\n addKeyboardShortcuts() {\n return {\n Enter: () => this.editor.commands.setHardBreak(),\n };\n },\n});\n\nconst DEFAULT_OPTIONS: Required<UpstartEditorOptions> = {\n richTextElements: [\"p\", \"div\", \"article\", \"section\"],\n inlineRichTextElements: [\"a\", \"span\", \"h1\", \"h2\", \"h3\", \"h4\", \"h5\", \"h6\"],\n plainTextElements: [\"button\", \"label\"],\n bubbleMenu: true,\n placeholder: \"Start typing...\",\n autoSaveDelay: 1000,\n getRawI18nTemplate: () => undefined,\n};\n\n/**\n * Parse a `data-upstart-i18n` value into its namespace and key.\n *\n * The build-time plugin guarantees a single \"namespace:key\" per element (a ternary\n * between two translations is emitted as a runtime-resolved expression), but a stale\n * build may still carry a comma-separated list of keys. Such a value is unresolvable —\n * we cannot tell which translation the edited text belongs to — so it is rejected\n * instead of being saved to a mangled key.\n */\nfunction parseI18nAttr(value: string | undefined): { namespace: string; key: string } | null {\n if (!value) return null;\n if (value.includes(\",\")) {\n console.warn(\"[Upstart Editor] Ambiguous i18n key, refusing to save:\", value);\n return null;\n }\n const colonIdx = value.indexOf(\":\");\n return colonIdx >= 0\n ? { namespace: value.slice(0, colonIdx), key: value.slice(colonIdx + 1) }\n : { namespace: \"translation\", key: value };\n}\n\n/**\n * Static text emitted by the build-time plugin around a single i18n node\n * (`data-upstart-i18n-prefix` / `data-upstart-i18n-suffix`).\n */\nfunction getAffixes(element: HTMLElement): { prefix: string; suffix: string } {\n return {\n prefix: element.dataset.upstartI18nPrefix ?? \"\",\n suffix: element.dataset.upstartI18nSuffix ?? \"\",\n };\n}\n\n/** Remove the static affixes from a rendered text to get the translation alone. */\nfunction stripAffixes(element: HTMLElement, text: string): string {\n const { prefix, suffix } = getAffixes(element);\n let out = text;\n if (prefix && out.startsWith(prefix)) out = out.slice(prefix.length);\n if (suffix && out.endsWith(suffix)) out = out.slice(0, out.length - suffix.length);\n return out;\n}\n\n/** Re-attach the static affixes to a translation for display purposes. */\nfunction applyAffixes(element: HTMLElement, text: string): string {\n const { prefix, suffix } = getAffixes(element);\n return `${prefix}${text}${suffix}`;\n}\n\n/**\n * Wrap the editable inline nodes with non-editable StaticAffix nodes so the static\n * parts stay visible while remaining outside of the edited (and saved) content.\n */\nfunction buildAffixDocument(element: HTMLElement, inlineNodes: object[]): object {\n const { prefix, suffix } = getAffixes(element);\n const content: object[] = [...inlineNodes];\n if (prefix) content.unshift({ type: \"staticAffix\", attrs: { text: prefix } });\n if (suffix) content.push({ type: \"staticAffix\", attrs: { text: suffix } });\n return { type: \"doc\", content: [{ type: \"paragraph\", content }] };\n}\n\n/** Extract the inline nodes of a single-paragraph document produced above. */\nfunction getInlineNodes(content: string | object): object[] {\n if (typeof content === \"string\") {\n return content ? [{ type: \"text\", text: content }] : [];\n }\n const paragraph = (content as { content?: { content?: object[] }[] }).content?.[0];\n return paragraph?.content ?? [];\n}\n\n/**\n * Parse a raw i18n template (e.g. \"Copyright {{year}}\") together with the\n * already-rendered text (e.g. \"Copyright 2026\") and produce a TipTap JSON\n * document where variable tokens become TemplateVariable nodes.\n */\nfunction buildI18nContent(rawTemplate: string, renderedText: string): object {\n const VAR_RE = /\\{\\{(\\w+)\\}\\}/g;\n type Segment = { type: \"text\"; text: string } | { type: \"var\"; varName: string };\n const segments: Segment[] = [];\n\n let lastIndex = 0;\n let m: RegExpExecArray | null;\n while ((m = VAR_RE.exec(rawTemplate)) !== null) {\n if (m.index > lastIndex) segments.push({ type: \"text\", text: rawTemplate.slice(lastIndex, m.index) });\n segments.push({ type: \"var\", varName: m[1] });\n lastIndex = m.index + m[0].length;\n }\n if (lastIndex < rawTemplate.length) segments.push({ type: \"text\", text: rawTemplate.slice(lastIndex) });\n\n // Build a regex over the rendered text to capture variable values\n const escRe = (s: string) => s.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n const regexParts = segments.map((s) => (s.type === \"text\" ? escRe(s.text) : \"(.+?)\"));\n const fullRegex = new RegExp(\"^\" + regexParts.join(\"\") + \"$\");\n const varSegments = segments.filter((s): s is Extract<Segment, { type: \"var\" }> => s.type === \"var\");\n\n const varValues: Record<string, string> = {};\n const match = renderedText.match(fullRegex);\n if (match) {\n varSegments.forEach((seg, i) => {\n varValues[seg.varName] = match[i + 1] ?? `{{${seg.varName}}}`;\n });\n } else {\n varSegments.forEach((seg) => {\n varValues[seg.varName] = `{{${seg.varName}}}`;\n });\n }\n\n const inlineNodes = segments\n .map((s) =>\n s.type === \"text\"\n ? { type: \"text\", text: s.text }\n : { type: \"templateVariable\", attrs: { varName: s.varName, value: varValues[s.varName] } },\n )\n .filter((n) => n.type !== \"text\" || (n as any).text !== \"\");\n\n return { type: \"doc\", content: [{ type: \"paragraph\", content: inlineNodes }] };\n}\n\n// Keyed by the host DOM element, NOT by data-upstart-hash: a component rendered\n// multiple times (e.g. a TimelineItem reused 4×) emits the same source-derived\n// hash on every instance, so keying by hash would let only the first instance\n// become editable. The element is the only per-instance unique identity.\nconst activeEditors = new Map<HTMLElement, EditorInstance>();\nlet i18nSyncInProgress = false;\nconst styleCache = new WeakMap<\n HTMLElement,\n { outline: string; outlineOffset: string; cursor: string; transition: string }\n>();\nlet resolvedOptions: Required<UpstartEditorOptions> = DEFAULT_OPTIONS;\nlet shortcutsRegistered = false;\nlet domObserver: MutationObserver | null = null;\nlet reactivateTimer: number | null = null;\n\n/**\n * Initialize TipTap text editing for elements marked as editable.\n * Activation is deferred to avoid conflicting with React hydration.\n */\nexport function initTextEditor(options: UpstartEditorOptions = {}): void {\n resolvedOptions = { ...DEFAULT_OPTIONS, ...options };\n registerKeyboardShortcuts();\n\n // Defer activation to let React finish hydrating the server-rendered HTML.\n injectEditorStyles();\n // activateAllEditors();\n startDomObserver();\n}\n\n/**\n * Inject CSS rules that visually hide original content when an editor is active.\n * This avoids moving DOM nodes (which breaks React hydration).\n *\n * - `font-size: 0` + `color: transparent` hides direct text nodes\n * - `> *:not(.ProseMirror)` hides child elements\n * - ProseMirror gets explicit inline styles to restore text rendering\n */\nfunction injectEditorStyles(): void {\n if (document.getElementById(\"upstart-editor-styles\")) return;\n\n const style = document.createElement(\"style\");\n style.id = \"upstart-editor-styles\";\n style.textContent = [\n \"[data-upstart-editor-active] {\",\n \" cursor: text;\",\n \"}\",\n // \"[data-upstart-editor-active] > *:not(.ProseMirror) {\",\n // \" display: none !important;\",\n // \"}\",\n \"[data-upstart-editor-active] .ProseMirror {\",\n \" outline: none !important;\",\n \" font-size: inherit !important;\",\n \" line-height: inherit !important;\",\n \" color: inherit !important;\",\n \" letter-spacing: inherit !important;\",\n \" font-weight: inherit !important;\",\n \" white-space: inherit !important;\",\n \"}\",\n \"[data-upstart-editor-active] .ProseMirror:focus {\",\n \" outline: none !important;\",\n \"}\",\n // Single-line editors (plain/direct, e.g. array-item pills) render their text\n // inside a ProseMirror <p>, which would otherwise pick up the browser's default\n // paragraph margin and change the element's height when edit mode activates.\n \"[data-upstart-editor-active][data-upstart-editable-text-mode='plain'] .ProseMirror p,\",\n \"[data-upstart-editor-active][data-upstart-editable-text-mode='direct'] .ProseMirror p {\",\n \" margin: 0 !important;\",\n \" padding: 0 !important;\",\n \"}\",\n ].join(\"\\n\");\n document.head.appendChild(style);\n}\n\n/**\n * Activate editors on all editable elements. Safe to call multiple times.\n */\nexport function activateAllEditors(): void {\n cleanupOrphanedEditors();\n const editables = document.querySelectorAll<HTMLElement>('[data-upstart-editable-text=\"true\"]');\n editables.forEach((element) => {\n try {\n setupEditableElement(element, resolvedOptions);\n } catch (error) {\n console.error(\"[Upstart Editor] Failed to activate element:\", element.dataset.upstartHash, error);\n }\n });\n console.log(\"[Upstart Editor] Text editors activated\");\n}\n\n/**\n * Destroy all active editors.\n */\nexport function destroyAllActiveEditors(): void {\n stopDomObserver();\n for (const element of activeEditors.keys()) {\n destroyEditor(element);\n }\n}\n\nfunction setupEditableElement(element: HTMLElement, options: Required<UpstartEditorOptions>): void {\n const hash = getEditableHash(element);\n if (!hash || activeEditors.has(element)) {\n return;\n }\n\n cacheStyles(element);\n activateEditor(element, hash, options);\n}\n\nfunction activateEditor(element: HTMLElement, hash: string, options: Required<UpstartEditorOptions>): void {\n const mode = getEditorMode(element, options);\n\n let editor: Editor;\n\n switch (mode) {\n case \"direct\":\n editor = createDirectEditor(element, options);\n break;\n case \"rich-panel\":\n editor = createRichPanelEditor(element, options);\n break;\n case \"block-rich\":\n editor = createRichTextEditor(element, options);\n break;\n case \"inline-rich\":\n editor = createInlineRichTextEditor(element, options);\n break;\n case \"plain\":\n editor = createPlainTextEditor(element, options);\n break;\n }\n\n // Mark element — triggers CSS rules that hide original content\n element.dataset.upstartEditorActive = \"true\";\n\n applyActiveStyles(element);\n activeEditors.set(element, { editor, element, hash, mode });\n}\n\nfunction createPlainTextEditor(element: HTMLElement, options: Required<UpstartEditorOptions>): Editor {\n // A label like `<Trans i18nKey=\"…\" /> *` renders the static \" *\" alongside the\n // translation: strip it so only the translation becomes editable.\n const renderedText = stripAffixes(element, element.textContent ?? \"\");\n\n let content: string | object = renderedText;\n const extraExtensions: ReturnType<typeof Node.create>[] = [];\n\n // Mixed-text: JSXText + expression chips (e.g. © {year} Some text)\n const mixedTemplate = element.dataset.upstartMixedTemplate;\n if (mixedTemplate) {\n content = buildI18nContent(mixedTemplate, renderedText);\n extraExtensions.push(TemplateVariable);\n } else {\n // Check for i18n template variables (e.g. data-i18n-values=\"year,month\")\n const i18nValueKeys = element.dataset.i18nValues?.split(\",\").filter(Boolean) ?? [];\n if (i18nValueKeys.length > 0) {\n const parsed = parseI18nAttr(element.dataset.upstartI18n);\n if (parsed) {\n const rawTemplate = options.getRawI18nTemplate(parsed.namespace, parsed.key);\n if (rawTemplate) {\n content = buildI18nContent(rawTemplate, renderedText);\n extraExtensions.push(TemplateVariable);\n }\n }\n }\n }\n\n const { prefix, suffix } = getAffixes(element);\n if (prefix || suffix) {\n extraExtensions.push(StaticAffix);\n content = buildAffixDocument(element, getInlineNodes(content));\n }\n\n element.textContent = \"\";\n let hasChanged = false;\n\n const editor = new Editor({\n element,\n extensions: [\n ...extraExtensions,\n StarterKit.configure({\n heading: false,\n bold: false,\n italic: false,\n strike: false,\n blockquote: false,\n bulletList: false,\n orderedList: false,\n listItem: false,\n codeBlock: false,\n horizontalRule: false,\n }),\n Placeholder.configure({\n placeholder: \"Click to edit...\",\n }),\n ],\n content,\n editorProps: {\n attributes: {\n class: \"upstart-editor-active\",\n },\n },\n onUpdate: () => {\n if (i18nSyncInProgress) return;\n hasChanged = true;\n syncI18nSiblings(element);\n },\n onBlur: ({ editor: e }) => {\n if (!hasChanged) return;\n hasChanged = false;\n saveText(element, e.getText());\n },\n });\n\n return editor;\n}\n\nfunction createRichTextEditor(element: HTMLElement, options: Required<UpstartEditorOptions>): Editor {\n const content = element.innerHTML;\n element.innerHTML = \"\"; // Clear the element first!\n let hasChanged = false;\n\n const bubbleMenuElement = createBubbleMenuElement();\n const extensions: Extension[] = [\n StarterKit,\n Placeholder.configure({\n placeholder: options.placeholder,\n }),\n ];\n\n if (options.bubbleMenu) {\n extensions.push(\n BubbleMenu.configure({\n element: bubbleMenuElement,\n }),\n );\n }\n\n const editor = new Editor({\n element,\n extensions,\n content,\n editorProps: {\n attributes: {\n class: \"upstart-editor-active\",\n },\n },\n onUpdate: () => {\n if (i18nSyncInProgress) return;\n hasChanged = true;\n syncI18nSiblings(element);\n },\n onBlur: ({ editor: e }) => {\n if (!hasChanged) return;\n hasChanged = false;\n saveText(element, e.getHTML());\n },\n });\n\n if (options.bubbleMenu) {\n wireBubbleMenu(bubbleMenuElement, editor);\n }\n\n return editor;\n}\n\nfunction createInlineRichTextEditor(element: HTMLElement, options: Required<UpstartEditorOptions>): Editor {\n const content = element.innerHTML;\n element.innerHTML = \"\"; // Clear the element first!\n let hasChanged = false;\n\n const bubbleMenuElement = createBubbleMenuElement(\"inline\");\n const extensions: (Extension | ReturnType<typeof Node.create>)[] = [\n InlineDocument,\n EnterHardBreak,\n StarterKit.configure({\n document: false,\n heading: false,\n blockquote: false,\n bulletList: false,\n orderedList: false,\n listItem: false,\n codeBlock: false,\n horizontalRule: false,\n }),\n Placeholder.configure({\n placeholder: \"Click to edit...\",\n }),\n ];\n\n if (options.bubbleMenu) {\n extensions.push(\n BubbleMenu.configure({\n element: bubbleMenuElement,\n }),\n );\n }\n\n const editor = new Editor({\n element,\n extensions,\n content,\n editorProps: {\n attributes: {\n class: \"upstart-editor-active\",\n },\n },\n onUpdate: () => {\n if (i18nSyncInProgress) return;\n hasChanged = true;\n syncI18nSiblings(element);\n },\n onBlur: ({ editor: e }) => {\n if (!hasChanged) return;\n hasChanged = false;\n saveText(element, e.getHTML());\n },\n });\n\n if (options.bubbleMenu) {\n wireBubbleMenu(bubbleMenuElement, editor);\n }\n\n return editor;\n}\n\nfunction createDirectEditor(element: HTMLElement, options: Required<UpstartEditorOptions>): Editor {\n const content = element.innerHTML;\n element.innerHTML = \"\";\n let hasChanged = false;\n\n const bubbleMenuElement = createBubbleMenuElement(\"inline\");\n const extensions: (Extension | ReturnType<typeof Node.create>)[] = [\n EnterHardBreak,\n StarterKit.configure({\n heading: false,\n blockquote: false,\n bulletList: false,\n orderedList: false,\n listItem: false,\n codeBlock: false,\n horizontalRule: false,\n }),\n Placeholder.configure({ placeholder: \"Click to edit...\" }),\n ];\n\n if (options.bubbleMenu) {\n extensions.push(BubbleMenu.configure({ element: bubbleMenuElement }));\n }\n\n const editor = new Editor({\n element,\n extensions,\n content,\n editorProps: { attributes: { class: \"upstart-editor-active\" } },\n onUpdate: () => {\n hasChanged = true;\n },\n onBlur: ({ editor: e }) => {\n if (!hasChanged) return;\n hasChanged = false;\n // Strip the outer <p> that TipTap adds when using default document schema\n saveText(element, e.getHTML().replace(/^<p>([\\s\\S]*)<\\/p>$/, \"$1\"));\n },\n });\n\n if (options.bubbleMenu) {\n wireBubbleMenu(bubbleMenuElement, editor);\n }\n\n return editor;\n}\n\nfunction createRichPanelEditor(element: HTMLElement, options: Required<UpstartEditorOptions>): Editor {\n const content = element.innerHTML;\n element.innerHTML = \"\";\n let hasChanged = false;\n\n const bubbleMenuElement = createBubbleMenuElement(\"inline\");\n const extensions: Extension[] = [StarterKit, Placeholder.configure({ placeholder: options.placeholder })];\n\n if (options.bubbleMenu) {\n extensions.push(BubbleMenu.configure({ element: bubbleMenuElement }));\n }\n\n const editor = new Editor({\n element,\n extensions,\n content,\n editorProps: { attributes: { class: \"upstart-editor-active\" } },\n onUpdate: () => {\n hasChanged = true;\n },\n onBlur: ({ editor: e }) => {\n if (!hasChanged) return;\n hasChanged = false;\n saveText(element, e.getHTML());\n },\n });\n\n if (options.bubbleMenu) {\n wireBubbleMenu(bubbleMenuElement, editor);\n }\n\n return editor;\n}\n\nfunction getEditorMode(element: HTMLElement, options: Required<UpstartEditorOptions>): TextEditorMode {\n const modeOverride = element.dataset.upstartEditableTextMode as TextEditorMode | undefined;\n if (\n modeOverride === \"plain\" ||\n modeOverride === \"inline-rich\" ||\n modeOverride === \"block-rich\" ||\n modeOverride === \"direct\" ||\n modeOverride === \"rich-panel\"\n ) {\n return modeOverride;\n }\n\n const tagName = element.tagName.toLowerCase();\n\n if (options.plainTextElements.includes(tagName)) {\n return \"plain\";\n }\n\n if (options.inlineRichTextElements.includes(tagName)) {\n return \"inline-rich\";\n }\n\n if (options.richTextElements.includes(tagName)) {\n return \"block-rich\";\n }\n\n return \"block-rich\";\n}\n\nfunction syncI18nSiblings(sourceElement: HTMLElement): void {\n const instance = activeEditors.get(sourceElement);\n console.log(\"[Upstart Editor] Syncing i18n siblings for\", instance?.hash);\n if (!instance) {\n console.warn(\"[Upstart Editor] No editor instance found for element:\", sourceElement);\n return;\n }\n\n const i18nKey = instance.element.dataset.upstartI18n;\n if (!i18nKey) {\n console.warn(\"[Upstart Editor] No sibling i18n key found for element:\", instance.element);\n return;\n }\n\n const siblings = document.querySelectorAll<HTMLElement>(`[data-upstart-i18n=\"${CSS.escape(i18nKey)}\"]`);\n console.log(`[Upstart Editor] Found ${siblings.length} sibling(s) with i18n key \"${i18nKey}\"`);\n\n // Always use plain text so each sibling's schema can wrap it correctly\n // (e.g. InlineDocument vs block Document have incompatible content rules).\n const plainContent = instance.editor.getText();\n\n i18nSyncInProgress = true;\n try {\n for (const sibling of siblings) {\n if (sibling === instance.element) continue;\n\n const siblingInstance = activeEditors.get(sibling);\n\n const { prefix, suffix } = getAffixes(sibling);\n const hasAffixes = Boolean(prefix || suffix);\n\n if (siblingInstance) {\n console.log(\n `[Upstart Editor] Updating sibling editor (hash: ${siblingInstance.hash}) with new content`,\n siblingInstance,\n );\n if (hasAffixes) {\n // setContent rebuilds the StaticAffix nodes, which insertContent would drop\n siblingInstance.editor.commands.setContent(\n buildAffixDocument(sibling, plainContent ? [{ type: \"text\", text: plainContent }] : []),\n );\n } else {\n sibling.innerText = plainContent;\n siblingInstance.editor.chain().selectAll().insertContent(plainContent).run();\n }\n } else {\n sibling.textContent = applyAffixes(sibling, plainContent);\n }\n }\n } finally {\n i18nSyncInProgress = false;\n }\n}\n\nfunction saveText(element: HTMLElement, newText: string): void {\n try {\n const instance = activeEditors.get(element);\n const dataset = instance?.element.dataset ?? {};\n\n // direct/rich-panel always go via editTextDirect; plain goes via editTextDirect when a\n // registry id is present (mixed-text), and via editText (i18n) otherwise.\n if (instance?.mode === \"direct\" || instance?.mode === \"rich-panel\" || dataset.upstartId) {\n sendToParent({\n type: \"text-edit\",\n payload: { action: \"editTextDirect\", id: dataset.upstartId!, content: newText },\n });\n } else {\n const parsed = parseI18nAttr(dataset.upstartI18n);\n if (!parsed) {\n console.warn(\"[Upstart Editor] No resolvable i18n key on element, edit not saved:\", element);\n return;\n }\n sendToParent({\n type: \"text-edit\",\n payload: {\n action: \"editText\",\n content: newText,\n namespace: parsed.namespace,\n key: parsed.key,\n language: document.documentElement.lang,\n },\n });\n }\n\n console.log(\"[Upstart Editor] Text save message sent:\", instance?.hash);\n } catch (error) {\n console.error(\"[Upstart Editor] Failed to send save message:\", error);\n sendToParent({\n type: \"editor-error\",\n error: error instanceof Error ? error.message : \"Unknown error\",\n });\n }\n}\n\nfunction destroyEditor(element: HTMLElement): void {\n const instance = activeEditors.get(element);\n if (!instance) {\n return;\n }\n\n const isPlainMode = instance.mode === \"plain\";\n const finalContent = isPlainMode ? instance.editor.getText() : instance.editor.getHTML();\n\n instance.editor.destroy();\n\n // Remove ProseMirror DOM\n const editorDom = instance.element.querySelector(\".ProseMirror\");\n if (editorDom) editorDom.remove();\n\n // Remove CSS-hiding marker — original content becomes visible again\n delete instance.element.dataset.upstartEditorActive;\n\n // Update element content with the final edited text\n if (isPlainMode) {\n instance.element.textContent = applyAffixes(instance.element, finalContent);\n } else {\n instance.element.innerHTML = finalContent;\n }\n\n restoreStyles(instance.element);\n activeEditors.delete(element);\n}\n\n// ---------------------------------------------------------------------------\n// MutationObserver — re-activates editors after React re-renders\n// ---------------------------------------------------------------------------\n\nfunction startDomObserver(): void {\n if (domObserver) return;\n\n domObserver = new MutationObserver((mutations) => {\n let needsReactivation = false;\n\n for (const mutation of mutations) {\n if (mutation.type !== \"childList\") continue;\n\n for (const node of mutation.addedNodes) {\n if (\n node instanceof HTMLElement &&\n (node.matches?.('[data-upstart-editable-text=\"true\"]') ||\n node.querySelector?.('[data-upstart-editable-text=\"true\"]'))\n ) {\n needsReactivation = true;\n break;\n }\n }\n\n if (!needsReactivation) {\n for (const node of mutation.removedNodes) {\n if (\n node instanceof HTMLElement &&\n (node.matches?.('[data-upstart-editable-text=\"true\"]') ||\n node.querySelector?.('[data-upstart-editable-text=\"true\"]'))\n ) {\n needsReactivation = true;\n break;\n }\n }\n }\n\n if (needsReactivation) break;\n }\n\n if (needsReactivation) {\n scheduleReactivation();\n }\n });\n\n domObserver.observe(document.body, { childList: true, subtree: true });\n}\n\nfunction stopDomObserver(): void {\n if (domObserver) {\n domObserver.disconnect();\n domObserver = null;\n }\n if (reactivateTimer) {\n clearTimeout(reactivateTimer);\n reactivateTimer = null;\n }\n}\n\nfunction scheduleReactivation(): void {\n if (reactivateTimer) clearTimeout(reactivateTimer);\n reactivateTimer = window.setTimeout(() => {\n reactivateTimer = null;\n activateAllEditors();\n }, 50);\n}\n\n/**\n * Remove editors whose host element has been detached from the document\n * (e.g. React replaced the subtree during a re-render).\n */\nfunction cleanupOrphanedEditors(): void {\n for (const [element, instance] of activeEditors) {\n if (!document.contains(instance.element)) {\n instance.editor.destroy();\n activeEditors.delete(element);\n }\n }\n}\n\n// ---------------------------------------------------------------------------\n// Keyboard shortcuts\n// ---------------------------------------------------------------------------\n\nfunction registerKeyboardShortcuts(): void {\n if (shortcutsRegistered) {\n return;\n }\n\n document.addEventListener(\"keydown\", (event) => {\n if (event.key === \"Escape\") {\n blurAllEditors();\n }\n\n if ((event.metaKey || event.ctrlKey) && event.key === \"Enter\") {\n blurAllEditors();\n }\n });\n\n shortcutsRegistered = true;\n}\n\nfunction blurAllEditors(): void {\n activeEditors.forEach((instance) => {\n instance.editor.commands.blur();\n });\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction getEditableHash(element: HTMLElement): string | null {\n return element.dataset.upstartHash ?? null;\n}\n\nfunction cacheStyles(element: HTMLElement): void {\n if (styleCache.has(element)) {\n return;\n }\n\n styleCache.set(element, {\n outline: element.style.outline || \"\",\n outlineOffset: element.style.outlineOffset || \"\",\n cursor: element.style.cursor || \"\",\n transition: element.style.transition || \"\",\n });\n}\n\nfunction applyActiveStyles(element: HTMLElement): void {\n cacheStyles(element);\n}\n\nfunction restoreStyles(element: HTMLElement): void {\n const cached = styleCache.get(element);\n if (!cached) {\n element.style.outline = \"\";\n element.style.outlineOffset = \"\";\n element.style.cursor = \"\";\n element.style.transition = \"\";\n return;\n }\n\n element.style.outline = cached.outline;\n element.style.outlineOffset = cached.outlineOffset;\n element.style.cursor = cached.cursor;\n element.style.transition = cached.transition;\n}\n\nconst BUBBLE_MENU_GROUPS: { command: string; icon: string; title: string }[][] = [\n [\n { command: \"bold\", icon: \"format-bold\", title: \"Bold\" },\n { command: \"italic\", icon: \"format-italic\", title: \"Italic\" },\n { command: \"strike\", icon: \"format-strikethrough\", title: \"Strikethrough\" },\n { command: \"code\", icon: \"code-tags\", title: \"Inline Code\" },\n ],\n [\n { command: \"heading\", icon: \"format-header-1\", title: \"Heading\" },\n { command: \"blockquote\", icon: \"format-quote-close\", title: \"Blockquote\" },\n ],\n [\n { command: \"bulletList\", icon: \"format-list-bulleted\", title: \"Bullet List\" },\n { command: \"orderedList\", icon: \"format-list-numbered\", title: \"Ordered List\" },\n ],\n];\n\nfunction getIconifyUrl(iconName: string): string {\n return `https://api.iconify.design/mdi/${iconName}.svg?height=none&color=%23fff`;\n}\n\nfunction createBubbleMenuElement(mode: \"block\" | \"inline\" = \"block\"): HTMLDivElement {\n const groups = mode === \"inline\" ? [BUBBLE_MENU_GROUPS[0]] : BUBBLE_MENU_GROUPS;\n const menu = document.createElement(\"div\");\n menu.className = \"upstart-editor-bubble-menu\";\n menu.style.cssText =\n \"display: flex; align-items: center; gap: 2px; padding: 4px; \" +\n \"background: #111827; color: #ffffff; border-radius: 8px; \" +\n \"font-size: 12px; box-shadow: 0 8px 24px rgba(0,0,0,0.25);\";\n\n groups.forEach((group, groupIndex) => {\n if (groupIndex > 0) {\n const separator = document.createElement(\"div\");\n separator.style.cssText =\n \"width: 1px; height: 16px; background: rgba(255,255,255,0.2); \" + \"margin: 0 4px; flex-shrink: 0;\";\n menu.appendChild(separator);\n }\n\n for (const { command, icon, title } of group) {\n const button = document.createElement(\"button\");\n button.type = \"button\";\n button.dataset.command = command;\n button.title = title;\n button.style.cssText =\n \"background: transparent; border: none; color: inherit; cursor: pointer; \" +\n \"display: flex; align-items: center; justify-content: center; \" +\n \"width: 28px; height: 28px; padding: 4px; border-radius: 4px; \" +\n \"transition: background 0.15s ease;\";\n\n const img = document.createElement(\"img\");\n img.src = getIconifyUrl(icon);\n img.alt = title;\n img.style.cssText = \"width: 18px; height: 18px; display: block; pointer-events: none;\";\n button.appendChild(img);\n\n button.addEventListener(\"mouseenter\", () => {\n if (!button.dataset.active) {\n button.style.background = \"rgba(255,255,255,0.12)\";\n }\n });\n button.addEventListener(\"mouseleave\", () => {\n button.style.background = button.dataset.active ? \"rgba(255,255,255,0.2)\" : \"transparent\";\n });\n\n menu.appendChild(button);\n }\n });\n\n return menu;\n}\n\nfunction wireBubbleMenu(menu: HTMLDivElement, editor: Editor): void {\n menu.addEventListener(\"mousedown\", (event) => {\n event.preventDefault();\n });\n\n menu.addEventListener(\n \"click\",\n (event) => {\n console.log(\"menu button cliked\");\n event.stopPropagation();\n const target = event.target as HTMLElement | null;\n const command = target?.dataset.command;\n if (!command) return;\n\n const chain = editor.chain().focus();\n\n switch (command) {\n case \"bold\":\n chain.toggleBold().run();\n break;\n case \"italic\":\n chain.toggleItalic().run();\n break;\n case \"strike\":\n chain.toggleStrike().run();\n break;\n case \"code\":\n chain.toggleCode().run();\n break;\n case \"heading\":\n chain.toggleHeading({ level: 1 }).run();\n break;\n case \"blockquote\":\n chain.toggleBlockquote().run();\n break;\n case \"bulletList\":\n chain.toggleBulletList().run();\n break;\n case \"orderedList\":\n chain.toggleOrderedList().run();\n break;\n }\n },\n { capture: true },\n );\n\n const updateActiveStates = (): void => {\n const buttons = menu.querySelectorAll<HTMLButtonElement>(\"button[data-command]\");\n for (const button of buttons) {\n const command = button.dataset.command!;\n const isActive =\n command === \"heading\" ? editor.isActive(\"heading\", { level: 1 }) : editor.isActive(command);\n\n if (isActive) {\n button.dataset.active = \"true\";\n button.style.background = \"rgba(255,255,255,0.2)\";\n } else {\n delete button.dataset.active;\n button.style.background = \"transparent\";\n }\n }\n };\n\n editor.on(\"transaction\", updateActiveStates);\n updateActiveStates();\n}\n"],"mappings":";;;;;;;;;;;AAYA,MAAM,iBAAiB,KAAK,OAAO;CACjC,MAAM;CACN,SAAS;CACT,SAAS;CACV,CAAC;;;;;;AAOF,MAAM,mBAAmB,KAAK,OAAO;CACnC,MAAM;CACN,OAAO;CACP,QAAQ;CACR,MAAM;CAEN,gBAAgB;EACd,OAAO;GACL,SAAS,EAAE,SAAS,IAAI;GACxB,OAAO,EAAE,SAAS,IAAI;GACvB;;CAGH,YAAY;EACV,OAAO,CAAC,EAAE,KAAK,sBAAsB,CAAC;;CAGxC,WAAW,EAAE,QAAQ;EACnB,OAAO;GACL;GACA;IACE,gBAAgB,KAAK,MAAM;IAC3B,iBAAiB;IACjB,OACE;IAEH;GACD,KAAK,MAAM,SAAS,KAAK,KAAK,MAAM,QAAQ;GAC7C;;CAGH,WAAW,EAAE,QAAQ;EACnB,OAAO,KAAK,KAAK,MAAM,QAAQ;;CAElC,CAAC;;;;;;;AAQF,MAAM,cAAc,KAAK,OAAO;CAC9B,MAAM;CACN,OAAO;CACP,QAAQ;CACR,MAAM;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T,QAAQ,IAAI,qBAAqB;EACjC,MAAM,iBAAiB;EAEvB,MAAM,UADS,MAAM,QACG,QAAQ;EAChC,IAAI,CAAC,SAAS;EAEd,MAAM,QAAQ,OAAO,OAAO,CAAC,OAAO;EAEpC,QAAQ,SAAR;GACE,KAAK;IACH,MAAM,YAAY,CAAC,KAAK;IACxB;GACF,KAAK;IACH,MAAM,cAAc,CAAC,KAAK;IAC1B;GACF,KAAK;IACH,MAAM,cAAc,CAAC,KAAK;IAC1B;GACF,KAAK;IACH,MAAM,YAAY,CAAC,KAAK;IACxB;GACF,KAAK;IACH,MAAM,cAAc,EAAE,OAAO,GAAG,CAAC,CAAC,KAAK;IACvC;GACF,KAAK;IACH,MAAM,kBAAkB,CAAC,KAAK;IAC9B;GACF,KAAK;IACH,MAAM,kBAAkB,CAAC,KAAK;IAC9B;GACF,KAAK;IACH,MAAM,mBAAmB,CAAC,KAAK;IAC/B;;IAGN,EAAE,SAAS,MAAM,CAClB;CAED,MAAM,2BAAiC;EACrC,MAAM,UAAU,KAAK,iBAAoC,uBAAuB;EAChF,KAAK,MAAM,UAAU,SAAS;GAC5B,MAAM,UAAU,OAAO,QAAQ;GAI/B,IAFE,YAAY,YAAY,OAAO,SAAS,WAAW,EAAE,OAAO,GAAG,CAAC,GAAG,OAAO,SAAS,QAAQ,EAE/E;IACZ,OAAO,QAAQ,SAAS;IACxB,OAAO,MAAM,aAAa;UACrB;IACL,OAAO,OAAO,QAAQ;IACtB,OAAO,MAAM,aAAa;;;;CAKhC,OAAO,GAAG,eAAe,mBAAmB;CAC5C,oBAAoB"}
|
|
1
|
+
{"version":3,"file":"text-editor.js","names":[],"sources":["../../../src/vite-plugin-upstart-editor/runtime/text-editor.ts"],"sourcesContent":["import { Editor, Extension, Node } from \"@tiptap/core\";\nimport { BubbleMenu } from \"@tiptap/extension-bubble-menu\";\nimport Placeholder from \"@tiptap/extension-placeholder\";\nimport StarterKit from \"@tiptap/starter-kit\";\nimport { sendToParent } from \"./utils.js\";\nimport type { EditorInstance, TextEditorMode, UpstartEditorOptions } from \"./types.js\";\n\n/**\n * Custom Document node for inline elements (e.g. <a>, <span>, headings).\n * Uses `inline*` content instead of the default `block+` to prevent\n * TipTap from wrapping text in <p> tags inside inline elements.\n */\nconst InlineDocument = Node.create({\n name: \"doc\",\n topNode: true,\n content: \"inline*\",\n});\n\n/**\n * An atomic inline node that represents an i18n template variable like {{year}}.\n * It is displayed as a grayed non-editable chip showing the resolved value.\n * renderText() returns {{varName}} so getText() serialises back to the raw template.\n */\nconst TemplateVariable = Node.create({\n name: \"templateVariable\",\n group: \"inline\",\n inline: true,\n atom: true,\n\n addAttributes() {\n return {\n varName: { default: \"\" },\n value: { default: \"\" },\n };\n },\n\n parseHTML() {\n return [{ tag: \"span[data-tpl-var]\" }];\n },\n\n renderHTML({ node }) {\n return [\n \"span\",\n {\n \"data-tpl-var\": node.attrs.varName,\n contenteditable: \"false\",\n style:\n \"opacity:0.5;background:rgba(0,0,0,0.08);border-radius:3px;padding:0 3px;\" +\n \"font-family:monospace;font-size:0.875em;cursor:default;user-select:none;\",\n },\n node.attrs.value || `{{${node.attrs.varName}}}`,\n ];\n },\n\n renderText({ node }) {\n return `{{${node.attrs.varName}}}`;\n },\n});\n\n/**\n * An atomic inline node holding static text that surrounds an i18n node in the\n * source (e.g. the \" *\" in `<label><Trans i18nKey=\"…\" /> *</label>`).\n * It stays visible and non-editable, and renderText() returns \"\" so getText()\n * yields only the translation — the static part never leaks into the saved value.\n */\nconst StaticAffix = Node.create({\n name: \"staticAffix\",\n group: \"inline\",\n inline: true,\n atom: true,\n selectable: false,\n\n addAttributes() {\n return {\n text: { default: \"\" },\n };\n },\n\n parseHTML() {\n return [{ tag: \"span[data-static-affix]\" }];\n },\n\n renderHTML({ node }) {\n return [\n \"span\",\n {\n \"data-static-affix\": \"\",\n contenteditable: \"false\",\n style: \"cursor:default;user-select:none;white-space:pre;\",\n },\n node.attrs.text,\n ];\n },\n\n renderText() {\n return \"\";\n },\n});\n\n/**\n * Remaps Enter to insert a <br> (hard break) instead of creating a new paragraph.\n * Used in inline-rich mode where block nodes are not allowed.\n */\nconst EnterHardBreak = Extension.create({\n name: \"enterHardBreak\",\n addKeyboardShortcuts() {\n return {\n Enter: () => this.editor.commands.setHardBreak(),\n };\n },\n});\n\nconst DEFAULT_OPTIONS: Required<UpstartEditorOptions> = {\n richTextElements: [\"p\", \"div\", \"article\", \"section\"],\n inlineRichTextElements: [\"a\", \"span\", \"h1\", \"h2\", \"h3\", \"h4\", \"h5\", \"h6\"],\n plainTextElements: [\"button\", \"label\"],\n bubbleMenu: true,\n placeholder: \"Start typing...\",\n autoSaveDelay: 1000,\n getRawI18nTemplate: () => undefined,\n};\n\n/**\n * Parse a `data-upstart-i18n` value into its namespace and key.\n *\n * The build-time plugin guarantees a single \"namespace:key\" per element (a ternary\n * between two translations is emitted as a runtime-resolved expression), but a stale\n * build may still carry a comma-separated list of keys. Such a value is unresolvable —\n * we cannot tell which translation the edited text belongs to — so it is rejected\n * instead of being saved to a mangled key.\n */\nfunction parseI18nAttr(value: string | undefined): { namespace: string; key: string } | null {\n if (!value) return null;\n if (value.includes(\",\")) {\n console.warn(\"[Upstart Editor] Ambiguous i18n key, refusing to save:\", value);\n return null;\n }\n const colonIdx = value.indexOf(\":\");\n return colonIdx >= 0\n ? { namespace: value.slice(0, colonIdx), key: value.slice(colonIdx + 1) }\n : { namespace: \"translation\", key: value };\n}\n\n/**\n * Static text emitted by the build-time plugin around a single i18n node\n * (`data-upstart-i18n-prefix` / `data-upstart-i18n-suffix`).\n */\nfunction getAffixes(element: HTMLElement): { prefix: string; suffix: string } {\n return {\n prefix: element.dataset.upstartI18nPrefix ?? \"\",\n suffix: element.dataset.upstartI18nSuffix ?? \"\",\n };\n}\n\n/** Remove the static affixes from a rendered text to get the translation alone. */\nfunction stripAffixes(element: HTMLElement, text: string): string {\n const { prefix, suffix } = getAffixes(element);\n let out = text;\n if (prefix && out.startsWith(prefix)) out = out.slice(prefix.length);\n if (suffix && out.endsWith(suffix)) out = out.slice(0, out.length - suffix.length);\n return out;\n}\n\n/** Re-attach the static affixes to a translation for display purposes. */\nfunction applyAffixes(element: HTMLElement, text: string): string {\n const { prefix, suffix } = getAffixes(element);\n return `${prefix}${text}${suffix}`;\n}\n\n/**\n * Wrap the editable inline nodes with non-editable StaticAffix nodes so the static\n * parts stay visible while remaining outside of the edited (and saved) content.\n */\nfunction buildAffixDocument(element: HTMLElement, inlineNodes: object[]): object {\n const { prefix, suffix } = getAffixes(element);\n const content: object[] = [...inlineNodes];\n if (prefix) content.unshift({ type: \"staticAffix\", attrs: { text: prefix } });\n if (suffix) content.push({ type: \"staticAffix\", attrs: { text: suffix } });\n return { type: \"doc\", content: [{ type: \"paragraph\", content }] };\n}\n\n/** Extract the inline nodes of a single-paragraph document produced above. */\nfunction getInlineNodes(content: string | object): object[] {\n if (typeof content === \"string\") {\n return content ? [{ type: \"text\", text: content }] : [];\n }\n const paragraph = (content as { content?: { content?: object[] }[] }).content?.[0];\n return paragraph?.content ?? [];\n}\n\n/**\n * Parse a raw i18n template (e.g. \"Copyright {{year}}\") together with the\n * already-rendered text (e.g. \"Copyright 2026\") and produce a TipTap JSON\n * document where variable tokens become TemplateVariable nodes.\n */\nfunction buildI18nContent(rawTemplate: string, renderedText: string): object {\n const VAR_RE = /\\{\\{(\\w+)\\}\\}/g;\n type Segment = { type: \"text\"; text: string } | { type: \"var\"; varName: string };\n const segments: Segment[] = [];\n\n let lastIndex = 0;\n let m: RegExpExecArray | null;\n while ((m = VAR_RE.exec(rawTemplate)) !== null) {\n if (m.index > lastIndex) segments.push({ type: \"text\", text: rawTemplate.slice(lastIndex, m.index) });\n segments.push({ type: \"var\", varName: m[1] });\n lastIndex = m.index + m[0].length;\n }\n if (lastIndex < rawTemplate.length) segments.push({ type: \"text\", text: rawTemplate.slice(lastIndex) });\n\n // Build a regex over the rendered text to capture variable values\n const escRe = (s: string) => s.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n const regexParts = segments.map((s) => (s.type === \"text\" ? escRe(s.text) : \"(.+?)\"));\n const fullRegex = new RegExp(\"^\" + regexParts.join(\"\") + \"$\");\n const varSegments = segments.filter((s): s is Extract<Segment, { type: \"var\" }> => s.type === \"var\");\n\n const varValues: Record<string, string> = {};\n const match = renderedText.match(fullRegex);\n if (match) {\n varSegments.forEach((seg, i) => {\n varValues[seg.varName] = match[i + 1] ?? `{{${seg.varName}}}`;\n });\n } else {\n varSegments.forEach((seg) => {\n varValues[seg.varName] = `{{${seg.varName}}}`;\n });\n }\n\n const inlineNodes = segments\n .map((s) =>\n s.type === \"text\"\n ? { type: \"text\", text: s.text }\n : { type: \"templateVariable\", attrs: { varName: s.varName, value: varValues[s.varName] } },\n )\n .filter((n) => n.type !== \"text\" || (n as any).text !== \"\");\n\n return { type: \"doc\", content: [{ type: \"paragraph\", content: inlineNodes }] };\n}\n\n// Keyed by the host DOM element, NOT by data-upstart-hash: a component rendered\n// multiple times (e.g. a TimelineItem reused 4×) emits the same source-derived\n// hash on every instance, so keying by hash would let only the first instance\n// become editable. The element is the only per-instance unique identity.\nconst activeEditors = new Map<HTMLElement, EditorInstance>();\nlet i18nSyncInProgress = false;\nconst styleCache = new WeakMap<\n HTMLElement,\n { outline: string; outlineOffset: string; cursor: string; transition: string }\n>();\nlet resolvedOptions: Required<UpstartEditorOptions> = DEFAULT_OPTIONS;\nlet shortcutsRegistered = false;\nlet domObserver: MutationObserver | null = null;\nlet reactivateTimer: number | null = null;\n\n/**\n * Initialize TipTap text editing for elements marked as editable.\n * Activation is deferred to avoid conflicting with React hydration.\n */\nexport function initTextEditor(options: UpstartEditorOptions = {}): void {\n resolvedOptions = { ...DEFAULT_OPTIONS, ...options };\n registerKeyboardShortcuts();\n\n // Defer activation to let React finish hydrating the server-rendered HTML.\n injectEditorStyles();\n // activateAllEditors();\n startDomObserver();\n}\n\n/**\n * Inject CSS rules that visually hide original content when an editor is active.\n * This avoids moving DOM nodes (which breaks React hydration).\n *\n * - `font-size: 0` + `color: transparent` hides direct text nodes\n * - `> *:not(.ProseMirror)` hides child elements\n * - ProseMirror gets explicit inline styles to restore text rendering\n */\nfunction injectEditorStyles(): void {\n if (document.getElementById(\"upstart-editor-styles\")) return;\n\n const style = document.createElement(\"style\");\n style.id = \"upstart-editor-styles\";\n style.textContent = [\n \"[data-upstart-editor-active] {\",\n \" cursor: text;\",\n \"}\",\n // \"[data-upstart-editor-active] > *:not(.ProseMirror) {\",\n // \" display: none !important;\",\n // \"}\",\n \"[data-upstart-editor-active] .ProseMirror {\",\n \" outline: none !important;\",\n \" font-size: inherit !important;\",\n \" line-height: inherit !important;\",\n \" color: inherit !important;\",\n \" letter-spacing: inherit !important;\",\n \" font-weight: inherit !important;\",\n \" white-space: inherit !important;\",\n \"}\",\n \"[data-upstart-editor-active] .ProseMirror:focus {\",\n \" outline: none !important;\",\n \"}\",\n // Single-line editors (plain/direct, e.g. array-item pills) render their text\n // inside a ProseMirror <p>, which would otherwise pick up the browser's default\n // paragraph margin and change the element's height when edit mode activates.\n \"[data-upstart-editor-active][data-upstart-editable-text-mode='plain'] .ProseMirror p,\",\n \"[data-upstart-editor-active][data-upstart-editable-text-mode='direct'] .ProseMirror p {\",\n \" margin: 0 !important;\",\n \" padding: 0 !important;\",\n \"}\",\n ].join(\"\\n\");\n document.head.appendChild(style);\n}\n\n/**\n * Activate editors on all editable elements. Safe to call multiple times.\n */\nexport function activateAllEditors(): void {\n cleanupOrphanedEditors();\n const editables = document.querySelectorAll<HTMLElement>('[data-upstart-editable-text=\"true\"]');\n editables.forEach((element) => {\n try {\n setupEditableElement(element, resolvedOptions);\n } catch (error) {\n console.error(\"[Upstart Editor] Failed to activate element:\", element.dataset.upstartHash, error);\n }\n });\n console.log(\"[Upstart Editor] Text editors activated\");\n}\n\n/**\n * Destroy all active editors.\n */\nexport function destroyAllActiveEditors(): void {\n stopDomObserver();\n for (const element of activeEditors.keys()) {\n destroyEditor(element);\n }\n}\n\n/** Descendants the plain editor cannot reproduce: taking over the element would destroy them. */\nconst PLAIN_EDITOR_FOREIGN_CHILDREN = \"svg, img, picture, video, iframe, canvas\";\n\nfunction setupEditableElement(element: HTMLElement, options: Required<UpstartEditorOptions>): void {\n const hash = getEditableHash(element);\n if (!hash || activeEditors.has(element)) {\n return;\n }\n // Older builds may still mark a container holding an icon next to its text as editable:\n // the plain editor would wipe the icon and React would later fight over it. Leave such\n // elements alone (the current plugin wraps the text in its own <span> instead).\n if (getEditorMode(element, options) === \"plain\" && element.querySelector(PLAIN_EDITOR_FOREIGN_CHILDREN)) {\n console.warn(\n \"[Upstart Editor] Skipping text editor on an element that also holds media/icons:\",\n element.dataset.upstartHash,\n element,\n );\n return;\n }\n\n cacheStyles(element);\n activateEditor(element, hash, options);\n}\n\nfunction activateEditor(element: HTMLElement, hash: string, options: Required<UpstartEditorOptions>): void {\n const mode = getEditorMode(element, options);\n\n let editor: Editor;\n\n switch (mode) {\n case \"direct\":\n editor = createDirectEditor(element, options);\n break;\n case \"rich-panel\":\n editor = createRichPanelEditor(element, options);\n break;\n case \"block-rich\":\n editor = createRichTextEditor(element, options);\n break;\n case \"inline-rich\":\n editor = createInlineRichTextEditor(element, options);\n break;\n case \"plain\":\n editor = createPlainTextEditor(element, options);\n break;\n }\n\n // Mark element — triggers CSS rules that hide original content\n element.dataset.upstartEditorActive = \"true\";\n\n applyActiveStyles(element);\n activeEditors.set(element, { editor, element, hash, mode });\n}\n\nfunction createPlainTextEditor(element: HTMLElement, options: Required<UpstartEditorOptions>): Editor {\n // A label like `<Trans i18nKey=\"…\" /> *` renders the static \" *\" alongside the\n // translation: strip it so only the translation becomes editable.\n const renderedText = stripAffixes(element, element.textContent ?? \"\");\n\n let content: string | object = renderedText;\n const extraExtensions: ReturnType<typeof Node.create>[] = [];\n\n // Mixed-text: JSXText + expression chips (e.g. © {year} Some text)\n const mixedTemplate = element.dataset.upstartMixedTemplate;\n if (mixedTemplate) {\n content = buildI18nContent(mixedTemplate, renderedText);\n extraExtensions.push(TemplateVariable);\n } else {\n // Check for i18n template variables (e.g. data-i18n-values=\"year,month\")\n const i18nValueKeys = element.dataset.i18nValues?.split(\",\").filter(Boolean) ?? [];\n if (i18nValueKeys.length > 0) {\n const parsed = parseI18nAttr(element.dataset.upstartI18n);\n if (parsed) {\n const rawTemplate = options.getRawI18nTemplate(parsed.namespace, parsed.key);\n if (rawTemplate) {\n content = buildI18nContent(rawTemplate, renderedText);\n extraExtensions.push(TemplateVariable);\n }\n }\n }\n }\n\n const { prefix, suffix } = getAffixes(element);\n if (prefix || suffix) {\n extraExtensions.push(StaticAffix);\n content = buildAffixDocument(element, getInlineNodes(content));\n }\n\n element.textContent = \"\";\n let hasChanged = false;\n\n const editor = new Editor({\n element,\n extensions: [\n ...extraExtensions,\n StarterKit.configure({\n heading: false,\n bold: false,\n italic: false,\n strike: false,\n blockquote: false,\n bulletList: false,\n orderedList: false,\n listItem: false,\n codeBlock: false,\n horizontalRule: false,\n }),\n Placeholder.configure({\n placeholder: \"Click to edit...\",\n }),\n ],\n content,\n editorProps: {\n attributes: {\n class: \"upstart-editor-active\",\n },\n },\n onUpdate: () => {\n if (i18nSyncInProgress) return;\n hasChanged = true;\n syncI18nSiblings(element);\n },\n onBlur: ({ editor: e }) => {\n if (!hasChanged) return;\n hasChanged = false;\n saveText(element, e.getText());\n },\n });\n\n return editor;\n}\n\nfunction createRichTextEditor(element: HTMLElement, options: Required<UpstartEditorOptions>): Editor {\n const content = element.innerHTML;\n element.innerHTML = \"\"; // Clear the element first!\n let hasChanged = false;\n\n const bubbleMenuElement = createBubbleMenuElement();\n const extensions: Extension[] = [\n StarterKit,\n Placeholder.configure({\n placeholder: options.placeholder,\n }),\n ];\n\n if (options.bubbleMenu) {\n extensions.push(\n BubbleMenu.configure({\n element: bubbleMenuElement,\n }),\n );\n }\n\n const editor = new Editor({\n element,\n extensions,\n content,\n editorProps: {\n attributes: {\n class: \"upstart-editor-active\",\n },\n },\n onUpdate: () => {\n if (i18nSyncInProgress) return;\n hasChanged = true;\n syncI18nSiblings(element);\n },\n onBlur: ({ editor: e }) => {\n if (!hasChanged) return;\n hasChanged = false;\n saveText(element, e.getHTML());\n },\n });\n\n if (options.bubbleMenu) {\n wireBubbleMenu(bubbleMenuElement, editor);\n }\n\n return editor;\n}\n\nfunction createInlineRichTextEditor(element: HTMLElement, options: Required<UpstartEditorOptions>): Editor {\n const content = element.innerHTML;\n element.innerHTML = \"\"; // Clear the element first!\n let hasChanged = false;\n\n const bubbleMenuElement = createBubbleMenuElement(\"inline\");\n const extensions: (Extension | ReturnType<typeof Node.create>)[] = [\n InlineDocument,\n EnterHardBreak,\n StarterKit.configure({\n document: false,\n heading: false,\n blockquote: false,\n bulletList: false,\n orderedList: false,\n listItem: false,\n codeBlock: false,\n horizontalRule: false,\n }),\n Placeholder.configure({\n placeholder: \"Click to edit...\",\n }),\n ];\n\n if (options.bubbleMenu) {\n extensions.push(\n BubbleMenu.configure({\n element: bubbleMenuElement,\n }),\n );\n }\n\n const editor = new Editor({\n element,\n extensions,\n content,\n editorProps: {\n attributes: {\n class: \"upstart-editor-active\",\n },\n },\n onUpdate: () => {\n if (i18nSyncInProgress) return;\n hasChanged = true;\n syncI18nSiblings(element);\n },\n onBlur: ({ editor: e }) => {\n if (!hasChanged) return;\n hasChanged = false;\n saveText(element, e.getHTML());\n },\n });\n\n if (options.bubbleMenu) {\n wireBubbleMenu(bubbleMenuElement, editor);\n }\n\n return editor;\n}\n\nfunction createDirectEditor(element: HTMLElement, options: Required<UpstartEditorOptions>): Editor {\n const content = element.innerHTML;\n element.innerHTML = \"\";\n let hasChanged = false;\n\n const bubbleMenuElement = createBubbleMenuElement(\"inline\");\n const extensions: (Extension | ReturnType<typeof Node.create>)[] = [\n EnterHardBreak,\n StarterKit.configure({\n heading: false,\n blockquote: false,\n bulletList: false,\n orderedList: false,\n listItem: false,\n codeBlock: false,\n horizontalRule: false,\n }),\n Placeholder.configure({ placeholder: \"Click to edit...\" }),\n ];\n\n if (options.bubbleMenu) {\n extensions.push(BubbleMenu.configure({ element: bubbleMenuElement }));\n }\n\n const editor = new Editor({\n element,\n extensions,\n content,\n editorProps: { attributes: { class: \"upstart-editor-active\" } },\n onUpdate: () => {\n hasChanged = true;\n },\n onBlur: ({ editor: e }) => {\n if (!hasChanged) return;\n hasChanged = false;\n // Strip the outer <p> that TipTap adds when using default document schema\n saveText(element, e.getHTML().replace(/^<p>([\\s\\S]*)<\\/p>$/, \"$1\"));\n },\n });\n\n if (options.bubbleMenu) {\n wireBubbleMenu(bubbleMenuElement, editor);\n }\n\n return editor;\n}\n\nfunction createRichPanelEditor(element: HTMLElement, options: Required<UpstartEditorOptions>): Editor {\n const content = element.innerHTML;\n element.innerHTML = \"\";\n let hasChanged = false;\n\n const bubbleMenuElement = createBubbleMenuElement(\"inline\");\n const extensions: Extension[] = [StarterKit, Placeholder.configure({ placeholder: options.placeholder })];\n\n if (options.bubbleMenu) {\n extensions.push(BubbleMenu.configure({ element: bubbleMenuElement }));\n }\n\n const editor = new Editor({\n element,\n extensions,\n content,\n editorProps: { attributes: { class: \"upstart-editor-active\" } },\n onUpdate: () => {\n hasChanged = true;\n },\n onBlur: ({ editor: e }) => {\n if (!hasChanged) return;\n hasChanged = false;\n saveText(element, e.getHTML());\n },\n });\n\n if (options.bubbleMenu) {\n wireBubbleMenu(bubbleMenuElement, editor);\n }\n\n return editor;\n}\n\nfunction getEditorMode(element: HTMLElement, options: Required<UpstartEditorOptions>): TextEditorMode {\n const modeOverride = element.dataset.upstartEditableTextMode as TextEditorMode | undefined;\n if (\n modeOverride === \"plain\" ||\n modeOverride === \"inline-rich\" ||\n modeOverride === \"block-rich\" ||\n modeOverride === \"direct\" ||\n modeOverride === \"rich-panel\"\n ) {\n return modeOverride;\n }\n\n const tagName = element.tagName.toLowerCase();\n\n if (options.plainTextElements.includes(tagName)) {\n return \"plain\";\n }\n\n if (options.inlineRichTextElements.includes(tagName)) {\n return \"inline-rich\";\n }\n\n if (options.richTextElements.includes(tagName)) {\n return \"block-rich\";\n }\n\n return \"block-rich\";\n}\n\nfunction syncI18nSiblings(sourceElement: HTMLElement): void {\n const instance = activeEditors.get(sourceElement);\n console.log(\"[Upstart Editor] Syncing i18n siblings for\", instance?.hash);\n if (!instance) {\n console.warn(\"[Upstart Editor] No editor instance found for element:\", sourceElement);\n return;\n }\n\n const i18nKey = instance.element.dataset.upstartI18n;\n if (!i18nKey) {\n console.warn(\"[Upstart Editor] No sibling i18n key found for element:\", instance.element);\n return;\n }\n\n const siblings = document.querySelectorAll<HTMLElement>(`[data-upstart-i18n=\"${CSS.escape(i18nKey)}\"]`);\n console.log(`[Upstart Editor] Found ${siblings.length} sibling(s) with i18n key \"${i18nKey}\"`);\n\n // Always use plain text so each sibling's schema can wrap it correctly\n // (e.g. InlineDocument vs block Document have incompatible content rules).\n const plainContent = instance.editor.getText();\n\n i18nSyncInProgress = true;\n try {\n for (const sibling of siblings) {\n if (sibling === instance.element) continue;\n\n const siblingInstance = activeEditors.get(sibling);\n\n const { prefix, suffix } = getAffixes(sibling);\n const hasAffixes = Boolean(prefix || suffix);\n\n if (siblingInstance) {\n console.log(\n `[Upstart Editor] Updating sibling editor (hash: ${siblingInstance.hash}) with new content`,\n siblingInstance,\n );\n if (hasAffixes) {\n // setContent rebuilds the StaticAffix nodes, which insertContent would drop\n siblingInstance.editor.commands.setContent(\n buildAffixDocument(sibling, plainContent ? [{ type: \"text\", text: plainContent }] : []),\n );\n } else {\n sibling.innerText = plainContent;\n siblingInstance.editor.chain().selectAll().insertContent(plainContent).run();\n }\n } else {\n sibling.textContent = applyAffixes(sibling, plainContent);\n }\n }\n } finally {\n i18nSyncInProgress = false;\n }\n}\n\nfunction saveText(element: HTMLElement, newText: string): void {\n try {\n const instance = activeEditors.get(element);\n const dataset = instance?.element.dataset ?? {};\n\n // direct/rich-panel always go via editTextDirect; plain goes via editTextDirect when a\n // registry id is present (mixed-text), and via editText (i18n) otherwise.\n if (instance?.mode === \"direct\" || instance?.mode === \"rich-panel\" || dataset.upstartId) {\n sendToParent({\n type: \"text-edit\",\n payload: { action: \"editTextDirect\", id: dataset.upstartId!, content: newText },\n });\n } else {\n const parsed = parseI18nAttr(dataset.upstartI18n);\n if (!parsed) {\n console.warn(\"[Upstart Editor] No resolvable i18n key on element, edit not saved:\", element);\n return;\n }\n sendToParent({\n type: \"text-edit\",\n payload: {\n action: \"editText\",\n content: newText,\n namespace: parsed.namespace,\n key: parsed.key,\n language: document.documentElement.lang,\n },\n });\n }\n\n console.log(\"[Upstart Editor] Text save message sent:\", instance?.hash);\n } catch (error) {\n console.error(\"[Upstart Editor] Failed to send save message:\", error);\n sendToParent({\n type: \"editor-error\",\n error: error instanceof Error ? error.message : \"Unknown error\",\n });\n }\n}\n\nfunction destroyEditor(element: HTMLElement): void {\n const instance = activeEditors.get(element);\n if (!instance) {\n return;\n }\n\n const isPlainMode = instance.mode === \"plain\";\n const finalContent = isPlainMode ? instance.editor.getText() : instance.editor.getHTML();\n\n instance.editor.destroy();\n\n // Remove ProseMirror DOM\n const editorDom = instance.element.querySelector(\".ProseMirror\");\n if (editorDom) editorDom.remove();\n\n // Remove CSS-hiding marker — original content becomes visible again\n delete instance.element.dataset.upstartEditorActive;\n\n // Update element content with the final edited text\n if (isPlainMode) {\n instance.element.textContent = applyAffixes(instance.element, finalContent);\n } else {\n instance.element.innerHTML = finalContent;\n }\n\n restoreStyles(instance.element);\n activeEditors.delete(element);\n}\n\n// ---------------------------------------------------------------------------\n// MutationObserver — re-activates editors after React re-renders\n// ---------------------------------------------------------------------------\n\nfunction startDomObserver(): void {\n if (domObserver) return;\n\n domObserver = new MutationObserver((mutations) => {\n let needsReactivation = false;\n\n for (const mutation of mutations) {\n if (mutation.type !== \"childList\") continue;\n\n for (const node of mutation.addedNodes) {\n if (\n node instanceof HTMLElement &&\n (node.matches?.('[data-upstart-editable-text=\"true\"]') ||\n node.querySelector?.('[data-upstart-editable-text=\"true\"]'))\n ) {\n needsReactivation = true;\n break;\n }\n }\n\n if (!needsReactivation) {\n for (const node of mutation.removedNodes) {\n if (\n node instanceof HTMLElement &&\n (node.matches?.('[data-upstart-editable-text=\"true\"]') ||\n node.querySelector?.('[data-upstart-editable-text=\"true\"]'))\n ) {\n needsReactivation = true;\n break;\n }\n }\n }\n\n if (needsReactivation) break;\n }\n\n if (needsReactivation) {\n scheduleReactivation();\n }\n });\n\n domObserver.observe(document.body, { childList: true, subtree: true });\n}\n\nfunction stopDomObserver(): void {\n if (domObserver) {\n domObserver.disconnect();\n domObserver = null;\n }\n if (reactivateTimer) {\n clearTimeout(reactivateTimer);\n reactivateTimer = null;\n }\n}\n\nfunction scheduleReactivation(): void {\n if (reactivateTimer) clearTimeout(reactivateTimer);\n reactivateTimer = window.setTimeout(() => {\n reactivateTimer = null;\n activateAllEditors();\n }, 50);\n}\n\n/**\n * Remove editors whose host element has been detached from the document\n * (e.g. React replaced the subtree during a re-render).\n */\nfunction cleanupOrphanedEditors(): void {\n for (const [element, instance] of activeEditors) {\n if (!document.contains(instance.element)) {\n instance.editor.destroy();\n activeEditors.delete(element);\n }\n }\n}\n\n// ---------------------------------------------------------------------------\n// Keyboard shortcuts\n// ---------------------------------------------------------------------------\n\nfunction registerKeyboardShortcuts(): void {\n if (shortcutsRegistered) {\n return;\n }\n\n document.addEventListener(\"keydown\", (event) => {\n if (event.key === \"Escape\") {\n blurAllEditors();\n }\n\n if ((event.metaKey || event.ctrlKey) && event.key === \"Enter\") {\n blurAllEditors();\n }\n });\n\n shortcutsRegistered = true;\n}\n\nfunction blurAllEditors(): void {\n activeEditors.forEach((instance) => {\n instance.editor.commands.blur();\n });\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction getEditableHash(element: HTMLElement): string | null {\n return element.dataset.upstartHash ?? null;\n}\n\nfunction cacheStyles(element: HTMLElement): void {\n if (styleCache.has(element)) {\n return;\n }\n\n styleCache.set(element, {\n outline: element.style.outline || \"\",\n outlineOffset: element.style.outlineOffset || \"\",\n cursor: element.style.cursor || \"\",\n transition: element.style.transition || \"\",\n });\n}\n\nfunction applyActiveStyles(element: HTMLElement): void {\n cacheStyles(element);\n}\n\nfunction restoreStyles(element: HTMLElement): void {\n const cached = styleCache.get(element);\n if (!cached) {\n element.style.outline = \"\";\n element.style.outlineOffset = \"\";\n element.style.cursor = \"\";\n element.style.transition = \"\";\n return;\n }\n\n element.style.outline = cached.outline;\n element.style.outlineOffset = cached.outlineOffset;\n element.style.cursor = cached.cursor;\n element.style.transition = cached.transition;\n}\n\nconst BUBBLE_MENU_GROUPS: { command: string; icon: string; title: string }[][] = [\n [\n { command: \"bold\", icon: \"format-bold\", title: \"Bold\" },\n { command: \"italic\", icon: \"format-italic\", title: \"Italic\" },\n { command: \"strike\", icon: \"format-strikethrough\", title: \"Strikethrough\" },\n { command: \"code\", icon: \"code-tags\", title: \"Inline Code\" },\n ],\n [\n { command: \"heading\", icon: \"format-header-1\", title: \"Heading\" },\n { command: \"blockquote\", icon: \"format-quote-close\", title: \"Blockquote\" },\n ],\n [\n { command: \"bulletList\", icon: \"format-list-bulleted\", title: \"Bullet List\" },\n { command: \"orderedList\", icon: \"format-list-numbered\", title: \"Ordered List\" },\n ],\n];\n\nfunction getIconifyUrl(iconName: string): string {\n return `https://api.iconify.design/mdi/${iconName}.svg?height=none&color=%23fff`;\n}\n\nfunction createBubbleMenuElement(mode: \"block\" | \"inline\" = \"block\"): HTMLDivElement {\n const groups = mode === \"inline\" ? [BUBBLE_MENU_GROUPS[0]] : BUBBLE_MENU_GROUPS;\n const menu = document.createElement(\"div\");\n menu.className = \"upstart-editor-bubble-menu\";\n menu.style.cssText =\n \"display: flex; align-items: center; gap: 2px; padding: 4px; \" +\n \"background: #111827; color: #ffffff; border-radius: 8px; \" +\n \"font-size: 12px; box-shadow: 0 8px 24px rgba(0,0,0,0.25);\";\n\n groups.forEach((group, groupIndex) => {\n if (groupIndex > 0) {\n const separator = document.createElement(\"div\");\n separator.style.cssText =\n \"width: 1px; height: 16px; background: rgba(255,255,255,0.2); \" + \"margin: 0 4px; flex-shrink: 0;\";\n menu.appendChild(separator);\n }\n\n for (const { command, icon, title } of group) {\n const button = document.createElement(\"button\");\n button.type = \"button\";\n button.dataset.command = command;\n button.title = title;\n button.style.cssText =\n \"background: transparent; border: none; color: inherit; cursor: pointer; \" +\n \"display: flex; align-items: center; justify-content: center; \" +\n \"width: 28px; height: 28px; padding: 4px; border-radius: 4px; \" +\n \"transition: background 0.15s ease;\";\n\n const img = document.createElement(\"img\");\n img.src = getIconifyUrl(icon);\n img.alt = title;\n img.style.cssText = \"width: 18px; height: 18px; display: block; pointer-events: none;\";\n button.appendChild(img);\n\n button.addEventListener(\"mouseenter\", () => {\n if (!button.dataset.active) {\n button.style.background = \"rgba(255,255,255,0.12)\";\n }\n });\n button.addEventListener(\"mouseleave\", () => {\n button.style.background = button.dataset.active ? \"rgba(255,255,255,0.2)\" : \"transparent\";\n });\n\n menu.appendChild(button);\n }\n });\n\n return menu;\n}\n\nfunction wireBubbleMenu(menu: HTMLDivElement, editor: Editor): void {\n menu.addEventListener(\"mousedown\", (event) => {\n event.preventDefault();\n });\n\n menu.addEventListener(\n \"click\",\n (event) => {\n console.log(\"menu button cliked\");\n event.stopPropagation();\n const target = event.target as HTMLElement | null;\n const command = target?.dataset.command;\n if (!command) return;\n\n const chain = editor.chain().focus();\n\n switch (command) {\n case \"bold\":\n chain.toggleBold().run();\n break;\n case \"italic\":\n chain.toggleItalic().run();\n break;\n case \"strike\":\n chain.toggleStrike().run();\n break;\n case \"code\":\n chain.toggleCode().run();\n break;\n case \"heading\":\n chain.toggleHeading({ level: 1 }).run();\n break;\n case \"blockquote\":\n chain.toggleBlockquote().run();\n break;\n case \"bulletList\":\n chain.toggleBulletList().run();\n break;\n case \"orderedList\":\n chain.toggleOrderedList().run();\n break;\n }\n },\n { capture: true },\n );\n\n const updateActiveStates = (): void => {\n const buttons = menu.querySelectorAll<HTMLButtonElement>(\"button[data-command]\");\n for (const button of buttons) {\n const command = button.dataset.command!;\n const isActive =\n command === \"heading\" ? editor.isActive(\"heading\", { level: 1 }) : editor.isActive(command);\n\n if (isActive) {\n button.dataset.active = \"true\";\n button.style.background = \"rgba(255,255,255,0.2)\";\n } else {\n delete button.dataset.active;\n button.style.background = \"transparent\";\n }\n }\n };\n\n editor.on(\"transaction\", updateActiveStates);\n updateActiveStates();\n}\n"],"mappings":";;;;;;;;;;;AAYA,MAAM,iBAAiB,KAAK,OAAO;CACjC,MAAM;CACN,SAAS;CACT,SAAS;CACV,CAAC;;;;;;AAOF,MAAM,mBAAmB,KAAK,OAAO;CACnC,MAAM;CACN,OAAO;CACP,QAAQ;CACR,MAAM;CAEN,gBAAgB;EACd,OAAO;GACL,SAAS,EAAE,SAAS,IAAI;GACxB,OAAO,EAAE,SAAS,IAAI;GACvB;;CAGH,YAAY;EACV,OAAO,CAAC,EAAE,KAAK,sBAAsB,CAAC;;CAGxC,WAAW,EAAE,QAAQ;EACnB,OAAO;GACL;GACA;IACE,gBAAgB,KAAK,MAAM;IAC3B,iBAAiB;IACjB,OACE;IAEH;GACD,KAAK,MAAM,SAAS,KAAK,KAAK,MAAM,QAAQ;GAC7C;;CAGH,WAAW,EAAE,QAAQ;EACnB,OAAO,KAAK,KAAK,MAAM,QAAQ;;CAElC,CAAC;;;;;;;AAQF,MAAM,cAAc,KAAK,OAAO;CAC9B,MAAM;CACN,OAAO;CACP,QAAQ;CACR,MAAM;CACN,YAAY;CAEZ,gBAAgB;EACd,OAAO,EACL,MAAM,EAAE,SAAS,IAAI,EACtB;;CAGH,YAAY;EACV,OAAO,CAAC,EAAE,KAAK,2BAA2B,CAAC;;CAG7C,WAAW,EAAE,QAAQ;EACnB,OAAO;GACL;GACA;IACE,qBAAqB;IACrB,iBAAiB;IACjB,OAAO;IACR;GACD,KAAK,MAAM;GACZ;;CAGH,aAAa;EACX,OAAO;;CAEV,CAAC;;;;;AAMF,MAAM,iBAAiB,UAAU,OAAO;CACtC,MAAM;CACN,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M,YAAY,CAAC,KAAK;IACxB;GACF,KAAK;IACH,MAAM,cAAc,CAAC,KAAK;IAC1B;GACF,KAAK;IACH,MAAM,cAAc,CAAC,KAAK;IAC1B;GACF,KAAK;IACH,MAAM,YAAY,CAAC,KAAK;IACxB;GACF,KAAK;IACH,MAAM,cAAc,EAAE,OAAO,GAAG,CAAC,CAAC,KAAK;IACvC;GACF,KAAK;IACH,MAAM,kBAAkB,CAAC,KAAK;IAC9B;GACF,KAAK;IACH,MAAM,kBAAkB,CAAC,KAAK;IAC9B;GACF,KAAK;IACH,MAAM,mBAAmB,CAAC,KAAK;IAC/B;;IAGN,EAAE,SAAS,MAAM,CAClB;CAED,MAAM,2BAAiC;EACrC,MAAM,UAAU,KAAK,iBAAoC,uBAAuB;EAChF,KAAK,MAAM,UAAU,SAAS;GAC5B,MAAM,UAAU,OAAO,QAAQ;GAI/B,IAFE,YAAY,YAAY,OAAO,SAAS,WAAW,EAAE,OAAO,GAAG,CAAC,GAAG,OAAO,SAAS,QAAQ,EAE/E;IACZ,OAAO,QAAQ,SAAS;IACxB,OAAO,MAAM,aAAa;UACrB;IACL,OAAO,OAAO,QAAQ;IACtB,OAAO,MAAM,aAAa;;;;CAKhC,OAAO,GAAG,eAAe,mBAAmB;CAC5C,oBAAoB"}
|
|
@@ -101,6 +101,15 @@ type EditorMessage = {
|
|
|
101
101
|
} | {
|
|
102
102
|
type: "editor-error";
|
|
103
103
|
error: string;
|
|
104
|
+
}
|
|
105
|
+
/**
|
|
106
|
+
* React's DOM reconciliation hit nodes the editor had replaced. `fatal: false`: the page was
|
|
107
|
+
* kept alive by the DOM guard (a refresh is advisable); `fatal: true`: the page crashed and
|
|
108
|
+
* the preview shows its recovery overlay.
|
|
109
|
+
*/
|
|
110
|
+
| {
|
|
111
|
+
type: "editor-desync";
|
|
112
|
+
fatal: boolean;
|
|
104
113
|
} | {
|
|
105
114
|
type: "selection-changed";
|
|
106
115
|
selection: SelectionRef[];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.ts","names":[],"sources":["../../../src/vite-plugin-upstart-editor/runtime/types.ts"],"mappings":";;;;;;AAeA;;;;KAAY,UAAA;AAOZ;;;;;AAAA,UAAiB,YAAA;EACf,GAAA;EACA,IAAA;EACA,QAAA;EACA,aAAA;EACA,QAAA;EACA,IAAA;EAMS;AAWX;;;;EAXE,SAAA;AAAA;;;;;;;;;KAWU,cAAA;;;AAiBZ;UAZiB,aAAA;EACf,GAAA;EACA,IAAA;EACA,KAAA;EACA,MAAA;EACA,KAAA;EACA,MAAA;AAAA;;;;UAMe,cAAA;EACf,MAAA,EAAQ,MAAA;EACR,OAAA,EAAS,WAAA;EACT,IAAA;EACA,IAAA,EAAM,cAAA;AAAA;;;;;UAOS,gBAAA;EACf,EAAA;EACA,GAAA;EACA,GAAA;EAKA;EAHA,WAAA;EACA,gBAAA;EAKA;EAHA,KAAA;EACA,MAAA;EACA,YAAA;EACA,aAAA;EAKe;EAHf,OAAA;EASuB;EAPvB,iBAAA;EACA,eAAA;AAAA;;;;KAMU,aAAA;EAEN,IAAA;EACA,OAAA,EACI,eAAA,GACA,qBAAA,GACA,mBAAA,GACA,sBAAA,GACA,eAAA;AAAA;EAEJ,IAAA;EAAsB,IAAA;AAAA;EACtB,IAAA;EAA0B,IAAA;AAAA;EAE1B,IAAA;EAAsB,OAAA;AAAA;EACtB,IAAA;EAAyB,CAAA;EAAW,CAAA;AAAA;EACpC,IAAA;EAAsB,KAAA;AAAA;
|
|
1
|
+
{"version":3,"file":"types.d.ts","names":[],"sources":["../../../src/vite-plugin-upstart-editor/runtime/types.ts"],"mappings":";;;;;;AAeA;;;;KAAY,UAAA;AAOZ;;;;;AAAA,UAAiB,YAAA;EACf,GAAA;EACA,IAAA;EACA,QAAA;EACA,aAAA;EACA,QAAA;EACA,IAAA;EAMS;AAWX;;;;EAXE,SAAA;AAAA;;;;;;;;;KAWU,cAAA;;;AAiBZ;UAZiB,aAAA;EACf,GAAA;EACA,IAAA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ATiB,oBAAA;EACf,MAAA;EACA,IAAA,EAAM,aAAA;EAAA,CACL,GAAA;AAAA;;;AAeH;UATiB,oBAAA;EACf,MAAA;EACA,IAAA,EAAM,aAAA;EAAA,CACL,GAAA;AAAA;;;;UAMc,oBAAA;EA2Cf;;;;EAtCA,gBAAA;EA4Ce;;;;;EArCf,sBAAA;;;;;EAMA,iBAAA;;;;;EAMA,UAAA;;;;;EAMA,WAAA;;;;;EAMA,aAAA;;;;;;EAOA,kBAAA,IAAsB,SAAA,UAAmB,GAAA;AAAA;;;;UAM1B,0BAAA;;;;;EAKf,OAAA;;;;;EAMA,UAAA;AAAA"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@upstart.gg/vite-plugins",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.69",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"files": [
|
|
6
6
|
"dist",
|
|
@@ -23,7 +23,7 @@
|
|
|
23
23
|
"oxc-parser": "0.101.0",
|
|
24
24
|
"unplugin": "^2.3.11",
|
|
25
25
|
"zimmerframe": "^1.1.4",
|
|
26
|
-
"@upstart.gg/sdk": "^0.1.
|
|
26
|
+
"@upstart.gg/sdk": "^0.1.69"
|
|
27
27
|
},
|
|
28
28
|
"devDependencies": {
|
|
29
29
|
"@rolldown/binding-linux-arm64-gnu": "1.0.0",
|
|
@@ -118,7 +118,7 @@
|
|
|
118
118
|
},
|
|
119
119
|
"peerDependencies": {
|
|
120
120
|
"zod": "4.3.6",
|
|
121
|
-
"@upstart.gg/sdk": "^0.1.
|
|
121
|
+
"@upstart.gg/sdk": "^0.1.69"
|
|
122
122
|
},
|
|
123
123
|
"author": "Upstart",
|
|
124
124
|
"publishConfig": {
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import { describe, expect, test, vi } from "vitest";
|
|
2
|
+
import { installDomGuard, type DomLike } from "../vite-plugin-upstart-editor/runtime/dom-guard";
|
|
3
|
+
|
|
4
|
+
/** Minimal parent/child model standing in for DOM nodes (vitest runs in node here). */
|
|
5
|
+
class FakeNode {
|
|
6
|
+
parentNode: FakeNode | null = null;
|
|
7
|
+
children: FakeNode[] = [];
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
function makeProto() {
|
|
11
|
+
const insertBefore = vi.fn(function (this: FakeNode, node: FakeNode, child: FakeNode | null) {
|
|
12
|
+
const idx = child ? this.children.indexOf(child) : -1;
|
|
13
|
+
if (child && idx === -1) throw new Error("NotFoundError: insertBefore");
|
|
14
|
+
if (child) this.children.splice(idx, 0, node);
|
|
15
|
+
else this.children.push(node);
|
|
16
|
+
node.parentNode = this;
|
|
17
|
+
return node;
|
|
18
|
+
});
|
|
19
|
+
const removeChild = vi.fn(function (this: FakeNode, child: FakeNode) {
|
|
20
|
+
const idx = this.children.indexOf(child);
|
|
21
|
+
if (idx === -1) throw new Error("NotFoundError: removeChild");
|
|
22
|
+
this.children.splice(idx, 1);
|
|
23
|
+
child.parentNode = null;
|
|
24
|
+
return child;
|
|
25
|
+
});
|
|
26
|
+
return { insertBefore, removeChild } as unknown as DomLike & { insertBefore: typeof insertBefore };
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
describe("installDomGuard", () => {
|
|
30
|
+
test("keeps normal inserts and removals untouched and silent", () => {
|
|
31
|
+
const proto = makeProto();
|
|
32
|
+
const onDesync = vi.fn();
|
|
33
|
+
installDomGuard(proto, onDesync);
|
|
34
|
+
const parent = new FakeNode();
|
|
35
|
+
const a = new FakeNode();
|
|
36
|
+
const b = new FakeNode();
|
|
37
|
+
(proto.insertBefore as unknown as (this: FakeNode, n: FakeNode, c: FakeNode | null) => FakeNode).call(
|
|
38
|
+
parent,
|
|
39
|
+
a,
|
|
40
|
+
null,
|
|
41
|
+
);
|
|
42
|
+
(proto.insertBefore as unknown as (this: FakeNode, n: FakeNode, c: FakeNode | null) => FakeNode).call(
|
|
43
|
+
parent,
|
|
44
|
+
b,
|
|
45
|
+
a,
|
|
46
|
+
);
|
|
47
|
+
expect(parent.children).toEqual([b, a]);
|
|
48
|
+
(proto.removeChild as unknown as (this: FakeNode, c: FakeNode) => FakeNode).call(parent, b);
|
|
49
|
+
expect(parent.children).toEqual([a]);
|
|
50
|
+
expect(onDesync).not.toHaveBeenCalled();
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
test("turns an insert before a vanished node into an append and reports once", () => {
|
|
54
|
+
const proto = makeProto();
|
|
55
|
+
const onDesync = vi.fn();
|
|
56
|
+
installDomGuard(proto, onDesync);
|
|
57
|
+
const parent = new FakeNode();
|
|
58
|
+
const existing = new FakeNode();
|
|
59
|
+
parent.children.push(existing);
|
|
60
|
+
existing.parentNode = parent;
|
|
61
|
+
const gone = new FakeNode(); // removed by the editor, React still references it
|
|
62
|
+
const fresh = new FakeNode();
|
|
63
|
+
const insert = proto.insertBefore as unknown as (
|
|
64
|
+
this: FakeNode,
|
|
65
|
+
n: FakeNode,
|
|
66
|
+
c: FakeNode | null,
|
|
67
|
+
) => FakeNode;
|
|
68
|
+
expect(() => insert.call(parent, fresh, gone)).not.toThrow();
|
|
69
|
+
expect(parent.children).toEqual([existing, fresh]);
|
|
70
|
+
expect(() => insert.call(parent, new FakeNode(), gone)).not.toThrow();
|
|
71
|
+
expect(onDesync).toHaveBeenCalledTimes(1);
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
test("logs every tolerated call with its stack so the culprit can be found", () => {
|
|
75
|
+
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
|
|
76
|
+
const proto = makeProto();
|
|
77
|
+
installDomGuard(proto, () => {});
|
|
78
|
+
const parent = new FakeNode();
|
|
79
|
+
const gone = new FakeNode();
|
|
80
|
+
const remove = proto.removeChild as unknown as (this: FakeNode, c: FakeNode) => FakeNode;
|
|
81
|
+
remove.call(parent, gone);
|
|
82
|
+
remove.call(parent, gone);
|
|
83
|
+
expect(warn).toHaveBeenCalledTimes(2);
|
|
84
|
+
expect(String(warn.mock.calls[0]?.[0])).toContain("DOM out of sync: removeChild");
|
|
85
|
+
expect(warn.mock.calls[0]?.[1]).toMatchObject({ parent, node: gone });
|
|
86
|
+
expect(String((warn.mock.calls[0]?.[1] as { stack: string }).stack)).toContain("DOM out of sync");
|
|
87
|
+
warn.mockRestore();
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
test("ignores the removal of a node that is no longer a child", () => {
|
|
91
|
+
const proto = makeProto();
|
|
92
|
+
const onDesync = vi.fn();
|
|
93
|
+
installDomGuard(proto, onDesync);
|
|
94
|
+
const parent = new FakeNode();
|
|
95
|
+
const gone = new FakeNode();
|
|
96
|
+
const remove = proto.removeChild as unknown as (this: FakeNode, c: FakeNode) => FakeNode;
|
|
97
|
+
expect(remove.call(parent, gone)).toBe(gone);
|
|
98
|
+
expect(onDesync).toHaveBeenCalledTimes(1);
|
|
99
|
+
});
|
|
100
|
+
});
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { describe, expect, test } from "vitest";
|
|
2
|
+
import { pickImagesForClick, rectContainsPoint } from "../vite-plugin-upstart-editor/runtime/image-pick";
|
|
3
|
+
|
|
4
|
+
const img = (id: string, left: number, top: number, size = 100) => ({
|
|
5
|
+
id,
|
|
6
|
+
rect: { left, top, width: size, height: size },
|
|
7
|
+
});
|
|
8
|
+
|
|
9
|
+
describe("rectContainsPoint", () => {
|
|
10
|
+
test("includes edges", () => {
|
|
11
|
+
const rect = { left: 10, top: 10, width: 20, height: 20 };
|
|
12
|
+
expect(rectContainsPoint(rect, { x: 10, y: 10 })).toBe(true);
|
|
13
|
+
expect(rectContainsPoint(rect, { x: 30, y: 30 })).toBe(true);
|
|
14
|
+
expect(rectContainsPoint(rect, { x: 31, y: 20 })).toBe(false);
|
|
15
|
+
});
|
|
16
|
+
});
|
|
17
|
+
|
|
18
|
+
describe("pickImagesForClick", () => {
|
|
19
|
+
test("a clicked element without images does not surface a sibling image (navbar title vs logo)", () => {
|
|
20
|
+
const logo = img("logo", 0, 0, 40);
|
|
21
|
+
expect(pickImagesForClick([], [[logo], [logo]], { x: 200, y: 20 })).toEqual([]);
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
test("a click visually on a hero covered by an overlay surfaces that hero", () => {
|
|
25
|
+
const hero = img("hero", 0, 0, 800);
|
|
26
|
+
expect(pickImagesForClick([], [[], [hero]], { x: 400, y: 300 })).toEqual([hero]);
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
test("ancestors never surface every image on the page", () => {
|
|
30
|
+
const a = img("a", 0, 0);
|
|
31
|
+
const b = img("b", 500, 500);
|
|
32
|
+
expect(pickImagesForClick([], [[a, b]], { x: 550, y: 550 })).toEqual([b]);
|
|
33
|
+
expect(pickImagesForClick([], [[a, b]], { x: 300, y: 300 })).toEqual([]);
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
test("images inside the clicked element are all candidates, narrowed to the one under the click", () => {
|
|
37
|
+
const a = img("a", 0, 0);
|
|
38
|
+
const b = img("b", 200, 0);
|
|
39
|
+
// Click on the container's padding: both images belong to what was clicked.
|
|
40
|
+
expect(pickImagesForClick([a, b], [], { x: 150, y: 50 })).toEqual([a, b]);
|
|
41
|
+
// Click on image b itself.
|
|
42
|
+
expect(pickImagesForClick([a, b], [], { x: 250, y: 50 })).toEqual([b]);
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
test("without a click point, own images are returned and ancestors are ignored", () => {
|
|
46
|
+
const a = img("a", 0, 0);
|
|
47
|
+
expect(pickImagesForClick([a], [], undefined)).toEqual([a]);
|
|
48
|
+
expect(pickImagesForClick([], [[a]], undefined)).toEqual([]);
|
|
49
|
+
});
|
|
50
|
+
});
|
|
@@ -170,6 +170,81 @@ describe("UpstartEditorAPI", () => {
|
|
|
170
170
|
expect(updatedContent).toBe(`<div className="px-8 py-4 bg-blue-500">Hello</div>`);
|
|
171
171
|
});
|
|
172
172
|
|
|
173
|
+
test("resolves a stale id by previousClassName once the registry was regenerated", async () => {
|
|
174
|
+
// A previous edit enlarged the parent's className, so the rebuild moved the image's
|
|
175
|
+
// className literal (and its `file:offset` id) while the preview still uses the old id.
|
|
176
|
+
const sourceContent = `<div className="wrap overflow-hidden"><img className="img object-cover" /></div>`;
|
|
177
|
+
const sourcePath = path.join(tempDir, "test.tsx");
|
|
178
|
+
await fs.writeFile(sourcePath, sourceContent);
|
|
179
|
+
const imgStart = sourceContent.indexOf("img object-cover");
|
|
180
|
+
const registry: EditableRegistry = {
|
|
181
|
+
version: 1,
|
|
182
|
+
generatedAt: new Date().toISOString(),
|
|
183
|
+
elements: {
|
|
184
|
+
"test.tsx:15": {
|
|
185
|
+
file: "test.tsx",
|
|
186
|
+
type: "className",
|
|
187
|
+
startOffset: 16,
|
|
188
|
+
endOffset: 36,
|
|
189
|
+
originalContent: "wrap overflow-hidden",
|
|
190
|
+
context: { parentTag: "div" },
|
|
191
|
+
},
|
|
192
|
+
[`test.tsx:${imgStart - 1}`]: {
|
|
193
|
+
file: "test.tsx",
|
|
194
|
+
type: "className",
|
|
195
|
+
startOffset: imgStart,
|
|
196
|
+
endOffset: imgStart + "img object-cover".length,
|
|
197
|
+
originalContent: "img object-cover",
|
|
198
|
+
context: { parentTag: "img" },
|
|
199
|
+
},
|
|
200
|
+
},
|
|
201
|
+
};
|
|
202
|
+
await fs.writeFile(registryPath, JSON.stringify(registry));
|
|
203
|
+
|
|
204
|
+
const result = await api.editClassName({
|
|
205
|
+
action: "editClassName",
|
|
206
|
+
id: "test.tsx:40", // the image's id before the rebuild
|
|
207
|
+
className: "img object-cover object-[50%_30%]",
|
|
208
|
+
previousClassName: "img object-cover",
|
|
209
|
+
});
|
|
210
|
+
|
|
211
|
+
expect(result.success).toBe(true);
|
|
212
|
+
const updated = await fs.readFile(sourcePath, "utf-8");
|
|
213
|
+
expect(updated).toBe(
|
|
214
|
+
`<div className="wrap overflow-hidden"><img className="img object-cover object-[50%_30%]" /></div>`,
|
|
215
|
+
);
|
|
216
|
+
});
|
|
217
|
+
|
|
218
|
+
test("falls back to a source search when neither the id nor the registry know the className", async () => {
|
|
219
|
+
const sourceContent = `<img className="img object-cover" />`;
|
|
220
|
+
const sourcePath = path.join(tempDir, "test.tsx");
|
|
221
|
+
await fs.writeFile(sourcePath, sourceContent);
|
|
222
|
+
const registry: EditableRegistry = { version: 1, generatedAt: new Date().toISOString(), elements: {} };
|
|
223
|
+
await fs.writeFile(registryPath, JSON.stringify(registry));
|
|
224
|
+
|
|
225
|
+
const result = await api.editClassName({
|
|
226
|
+
action: "editClassName",
|
|
227
|
+
id: "test.tsx:15",
|
|
228
|
+
className: "img object-contain",
|
|
229
|
+
previousClassName: "img object-cover",
|
|
230
|
+
});
|
|
231
|
+
|
|
232
|
+
expect(result.success).toBe(true);
|
|
233
|
+
expect(await fs.readFile(sourcePath, "utf-8")).toBe(`<img className="img object-contain" />`);
|
|
234
|
+
// Registered under the preview's id so the next edit resolves directly.
|
|
235
|
+
expect(api.getRegistry()?.elements["test.tsx:15"]?.originalContent).toBe("img object-contain");
|
|
236
|
+
});
|
|
237
|
+
|
|
238
|
+
test("keeps failing on a stale id without previousClassName", async () => {
|
|
239
|
+
await fs.writeFile(path.join(tempDir, "test.tsx"), `<img className="img" />`);
|
|
240
|
+
const registry: EditableRegistry = { version: 1, generatedAt: new Date().toISOString(), elements: {} };
|
|
241
|
+
await fs.writeFile(registryPath, JSON.stringify(registry));
|
|
242
|
+
|
|
243
|
+
const result = await api.editClassName({ action: "editClassName", id: "test.tsx:15", className: "x" });
|
|
244
|
+
expect(result.success).toBe(false);
|
|
245
|
+
expect(result.error).toContain("not found in registry");
|
|
246
|
+
});
|
|
247
|
+
|
|
173
248
|
test("should fail if element is not className type", async () => {
|
|
174
249
|
const registry: EditableRegistry = {
|
|
175
250
|
version: 1,
|
|
@@ -1569,6 +1569,27 @@ describe("upstart-editor-vite-plugin", () => {
|
|
|
1569
1569
|
expect(result).toContain('data-upstart-editable-text="true"');
|
|
1570
1570
|
});
|
|
1571
1571
|
|
|
1572
|
+
test("wraps a <Trans> in its own editable <span> when an icon sibling would be destroyed", () => {
|
|
1573
|
+
const code = `
|
|
1574
|
+
import { Trans } from "react-i18next";
|
|
1575
|
+
import { Icon } from "@iconify/react";
|
|
1576
|
+
export default function Badge() {
|
|
1577
|
+
return <div className="badge"><Icon icon="lucide:sparkles" /><Trans i18nKey="nav.badge" /></div>;
|
|
1578
|
+
}
|
|
1579
|
+
`;
|
|
1580
|
+
const result = transform(code) ?? "";
|
|
1581
|
+
// The container keeps its hash but is not editable itself…
|
|
1582
|
+
const container = result.match(/<div[^>]*className="badge"[^>]*>/)?.[0] ?? "";
|
|
1583
|
+
expect(container).toContain("data-upstart-hash=");
|
|
1584
|
+
expect(container).not.toContain("data-upstart-editable-text");
|
|
1585
|
+
// …the <Trans> is wrapped in an editable span carrying the i18n attributes.
|
|
1586
|
+
expect(result).toMatch(
|
|
1587
|
+
/<span data-upstart-hash="[a-f0-9]+" data-upstart-editable-text="true" data-upstart-editable-text-mode="plain" data-upstart-i18n="translation:nav\.badge"><Trans i18nKey="nav\.badge" \/><\/span>/,
|
|
1588
|
+
);
|
|
1589
|
+
// The icon is untouched.
|
|
1590
|
+
expect(result).toMatch(/<Icon [^>]*icon="lucide:sparkles"[^>]*\/>/);
|
|
1591
|
+
});
|
|
1592
|
+
|
|
1572
1593
|
test("should promote <Trans> with custom namespace to parent", () => {
|
|
1573
1594
|
const code = `
|
|
1574
1595
|
import { Trans } from "react-i18next";
|