Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
fix(open-knowledge): visible, editable block for empty Mermaid insert (#2661)
Andrew Mikofalvy33b6ca71cb75
diff --git a/.changeset/mermaid-empty-block-placeholder.md b/.changeset/mermaid-empty-block-placeholder.mdnew file mode 100644index 000000000..04d2de261--- /dev/null+++ b/.changeset/mermaid-empty-block-placeholder.md@@ -0,0 +1,5 @@+---+"@inkeep/open-knowledge": patch+---++Fix the Mermaid slash command inserting an invisible, zero-height block. Selecting Mermaid from the `/` menu previously dropped a near-zero-height sliver: nothing appeared to happen, repeated inserts stacked invisibly, and the hover toolbar (edit / delete) was clipped. An empty Mermaid block now renders a clear "Add a Mermaid diagram" placeholder card and opens the diagram source editor on insert, so there is always a visible, adequately-sized target to author or remove.diff --git a/packages/app/src/editor/components/CodePreviewEditModal.dom.test.tsx b/packages/app/src/editor/components/CodePreviewEditModal.dom.test.tsxindex 5c1e34eff..dd8712e39 100644--- a/packages/app/src/editor/components/CodePreviewEditModal.dom.test.tsx+++ b/packages/app/src/editor/components/CodePreviewEditModal.dom.test.tsx@@ -6,15 +6,19 @@* - the Save button commits the current draft via `onSave`* - a fresh open re-seeds from `initialValue` (no stale-draft carryover)* - the preview pane mounts only when `renderPreview` is supplied+ * - Cmd/Ctrl+Enter commits the draft and closes (the Mod-Enter save+ * binding must beat `defaultKeymap`'s insertBlankLine)*- * CodeMirror's keymap (Esc, Cmd+Enter) lives inside its own EditorView- * and isn't reachable via DOM-fire keyboard events in jsdom (it reads- * from KeyboardEvent.code which jsdom doesn't fully populate). Those- * shortcuts are exercised in Playwright instead.+ * CodeMirror's keymap runs off a native `keydown` on `.cm-content`; a+ * jsdom `KeyboardEvent` with `key`/`code` populated reaches it (same+ * pattern as `SourceEditor.dom.test.tsx`). Esc is still exercised only in+ * Playwright — it bubbles past CodeMirror to Radix's own dialog-close+ * handler, a path jsdom's synthetic event doesn't drive.*/import { afterEach, describe, expect, test } from 'bun:test';-import { fireEvent, render, screen, waitFor } from '@testing-library/react';+import { EditorView } from '@codemirror/view';+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';import { useState } from 'react';import { CodePreviewEditModal } from './CodePreviewEditModal';@@ -29,6 +33,15 @@ if (typeof window !== 'undefined' && !(globalThis as { NodeFilter?: unknown }).N).NodeFilter;}+// CodeMirror's post-mount measure pass (`isScrolledToBottom`) reads the bare+// `Window` constructor off the global scope; jsdom exposes it on `window` but+// not `globalThis`. Bridge it so the measure rAF doesn't spew unhandled+// `ReferenceError: Window is not defined` while the source editor lays out.+// Mirrors `SourceEditor.dom.test.tsx`.+if (typeof window !== 'undefined' && !(globalThis as { Window?: unknown }).Window) {+ (globalThis as { Window?: unknown }).Window = (window as unknown as { Window: unknown }).Window;+}+afterEach(() => {// jsdom doesn't auto-cleanup between tests under Bun's test runtime; do it// explicitly so the next render starts from a fresh document.@@ -186,4 +199,56 @@ describe('CodePreviewEditModal', () => {expect(saved).toEqual(['<h1>first</h1>', '<h1>second</h1>']);});});++ test('Cmd/Ctrl+Enter commits the draft via onSave and closes the modal', async () => {+ // Regression guard for the Mod-Enter precedence bug: `@codemirror/commands`+ // defaultKeymap binds Mod-Enter to insertBlankLine, so the modal's own save+ // binding has to sit ahead of the spread to win. If it slips behind+ // defaultKeymap, insertBlankLine consumes the key, onSave never fires, and+ // the waitFor below times out.+ let saved: string | null = null;+ render(+ <Harness+ initialValue="graph TD; A-->B"+ onSave={(v) => {+ saved = v;+ }}+ />,+ );+ const host = await screen.findByTestId('ok-code-preview-edit-modal-source');+ await waitFor(() => {+ expect(host.querySelector('.cm-content')).toBeTruthy();+ });+ const content = host.querySelector<HTMLElement>('.cm-content');+ if (!content) throw new Error('CodeMirror content never mounted');+ // Confirms the EditorView is live so the dispatched key reaches its keymap.+ expect(EditorView.findFromDOM(content)).toBeTruthy();++ // CodeMirror resolves `Mod` to Meta on macOS and Ctrl elsewhere, keyed off+ // the platform captured at `@codemirror/view` import time (navigator.platform,+ // unchanged in this file). Send whichever modifier matches so the binding+ // fires regardless of the CI host OS.+ const modProps = /Mac/.test(navigator.platform) ? { metaKey: true } : { ctrlKey: true };+ await act(async () => {+ content.dispatchEvent(+ new KeyboardEvent('keydown', {+ key: 'Enter',+ code: 'Enter',+ bubbles: true,+ cancelable: true,+ ...modProps,+ }),+ );+ });++ // onSave fired with the exact draft — no blank line inserted, because our+ // binding returned true before insertBlankLine could run …+ await waitFor(() => {+ expect(saved).toBe('graph TD; A-->B');+ });+ // … and the modal closed.+ await waitFor(() => {+ expect(screen.queryByTestId('ok-code-preview-edit-modal-body')).toBeNull();+ });+ });});diff --git a/packages/app/src/editor/components/CodePreviewEditModal.tsx b/packages/app/src/editor/components/CodePreviewEditModal.tsxindex cff72623d..495813213 100644--- a/packages/app/src/editor/components/CodePreviewEditModal.tsx+++ b/packages/app/src/editor/components/CodePreviewEditModal.tsx@@ -266,14 +266,21 @@ export function CodePreviewEditModal({// tuned for WCAG-AA contrast on both light and dark surfaces.syntaxHighlighting(defaultHighlightStyle, { fallback: true }),syntaxHighlighting(propEditorHighlight),- // `indentWithTab` MUST come first so Tab inserts indentation- // instead of moving focus to the next dialog control (the- // browser's default Tab handling). Esc still bubbles to Radix- // so the dialog close path works.+ // Within a single `keymap.of([...])`, earlier array entries win for+ // a given key (their commands run first; the first to return true+ // stops the chain). Two orderings ride on that:+ // - The `Mod-Enter` save binding MUST precede `...defaultKeymap`,+ // because defaultKeymap binds `Mod-Enter` to `insertBlankLine`.+ // Behind the spread, insertBlankLine would win and Cmd/Ctrl+Enter+ // would insert a newline instead of committing — contradicting+ // the footer's "⌘ Enter saves" promise. Our binding returns true,+ // so first position makes it authoritative.+ // - `indentWithTab` binds `Tab` (a different key), so its order+ // relative to the others is immaterial; it stays near the front+ // so Tab inserts indentation instead of moving focus to the next+ // dialog control. Esc still bubbles to Radix so the dialog close+ // path works.keymap.of([- indentWithTab,- ...defaultKeymap,- ...historyKeymap,{key: 'Mod-Enter',preventDefault: true,@@ -283,6 +290,9 @@ export function CodePreviewEditModal({return true;},},+ indentWithTab,+ ...defaultKeymap,+ ...historyKeymap,]),EditorView.lineWrapping,EditorState.tabSize.of(2),diff --git a/packages/app/src/editor/components/Mermaid.test.tsx b/packages/app/src/editor/components/Mermaid.test.tsxindex 17b19c009..b521294f8 100644--- a/packages/app/src/editor/components/Mermaid.test.tsx+++ b/packages/app/src/editor/components/Mermaid.test.tsx@@ -37,10 +37,15 @@ const {} = await import('./Mermaid.tsx');describe('MermaidView — placeholder branch', () => {- test('empty chart renders the placeholder shell', () => {+ test('empty chart renders the placeholder shell with real height', () => {const html = renderToString(<MermaidView chart="" />);- expect(html).toContain('class="mermaid mermaid-placeholder"');+ expect(html).toContain('mermaid-placeholder');expect(html).toContain('data-component-type="mermaid"');+ // The empty state must hold height so the block is a real target and the+ // hover chrome isn't clipped (the zero-height sliver bug); it also carries+ // a visible hint instead of a blank space.+ expect(html).toContain('min-h-16');+ expect(html).toContain('Empty diagram');});test('whitespace-only chart treated as empty', () => {diff --git a/packages/app/src/editor/components/Mermaid.tsx b/packages/app/src/editor/components/Mermaid.tsxindex 5064fa31b..18bd71a69 100644--- a/packages/app/src/editor/components/Mermaid.tsx+++ b/packages/app/src/editor/components/Mermaid.tsx@@ -1892,9 +1892,22 @@ export function MermaidView({ chart = '', className, editBinding }: MermaidProps}, [state.status, canEdit]);if (!chart.trim()) {+ // Reached in read-only render contexts and the edit-modal preview with an+ // empty draft. The editor's authoring path renders a click-to-edit+ // placeholder card upstream (JsxComponentView), so this stays passive and+ // non-interactive — but it MUST hold real height: a zero-height stub+ // collapses the block and clips the hover chrome (the sliver bug).return (- <div className="mermaid mermaid-placeholder" data-component-type="mermaid">- <span className="mermaid-empty"> </span>+ <div+ className={cn(+ 'mermaid mermaid-placeholder flex min-h-16 w-full items-center justify-center rounded-md border border-dashed border-border/60 bg-muted/10 px-3 py-6 text-sm text-muted-foreground',+ className,+ )}+ data-component-type="mermaid"+ >+ <span className="mermaid-empty">+ <Trans>Empty diagram</Trans>+ </span></div>);}diff --git a/packages/app/src/editor/extensions/JsxComponentView.tsx b/packages/app/src/editor/extensions/JsxComponentView.tsxindex 62112b293..59a5ebb75 100644--- a/packages/app/src/editor/extensions/JsxComponentView.tsx+++ b/packages/app/src/editor/extensions/JsxComponentView.tsx@@ -421,17 +421,44 @@ export function JsxComponentView({ node, editor, extension, getPos, selected }:: null;const [editModalOpen, setEditModalOpen] = useState(false);- // Auto-open popover when: (1) component becomes selected AND (2) the- // pendingAutoOpen flag is set. Uses controlled state so it works across- // React re-renders (defaultOpen only reads on first mount). `wasSelected`- // ref prevents double-fire under Strict Mode; explicit deps ensure the- // effect only runs when one of the watched values actually changes.+ // Source-bearing self-closing leaves (today only MermaidFence) hide their+ // single required prop from the PropPanel and author it in the fullscreen+ // edit modal (the pencil). With every prop hidden `hasEditableProps` is+ // false, so neither the gear nudge nor the autoFocus `shouldRenderPlaceholder`+ // path fires — an empty one would otherwise mount its renderer's zero-height+ // empty state, giving no click target and clipping the hover chrome. When the+ // source prop is empty/absent and the editor is editable, render the shared+ // placeholder card (real min-height + a clear CTA) wired to open the modal.+ const isSourceBearing = editableSource !== null;+ const sourcePropValue = editableSource ? currentProps[editableSource.propName] : undefined;+ const showSourcePlaceholder =+ isSourceBearing &&+ !hasEditableProps &&+ editor.isEditable &&+ (typeof sourcePropValue !== 'string' || sourcePropValue.trim() === '');+ const sourcePlaceholder = showSourcePlaceholder ? resolveDescriptorPlaceholder(descriptor) : null;++ // Auto-open the config surface when (1) the component becomes selected and+ // (2) the pendingAutoOpen flag is set (slash insert / add-child). Editable-+ // props components open the PropPanel popover; a source-bearing leaf has no+ // popover, so it opens the edit modal instead. Controlled state survives+ // re-renders (defaultOpen only reads on first mount); `wasSelected` prevents+ // a Strict-Mode double-fire.useEffect(() => {- if (selected && !wasSelected.current && hasEditableProps && consumeAutoOpen(pos)) {- setPopoverOpen(true);+ if (+ selected &&+ !wasSelected.current &&+ (hasEditableProps || isSourceBearing) &&+ consumeAutoOpen(pos)+ ) {+ if (hasEditableProps) {+ setPopoverOpen(true);+ } else {+ setEditModalOpen(true);+ }}wasSelected.current = selected;- }, [selected, hasEditableProps, pos]);+ }, [selected, hasEditableProps, isSourceBearing, pos]);const primitiveProps = extractPrimitiveProps(node.attrs, descriptor.reactNodePropNames);// Compat descriptors render through their canonical's React component via@@ -724,7 +751,7 @@ export function JsxComponentView({ node, editor, extension, getPos, selected }:// skip the wrapper-level handler so setNodeSelection does not double-fire// alongside `openPanel`'s own selection + popover-open.const handleBodyClick = (e: React.MouseEvent<HTMLDivElement>) => {- if (showPlaceholder) return;+ if (showPlaceholder || showSourcePlaceholder) return;if (!isSelfClosingLeaf) return;const target = e.target as HTMLElement;// React events bubble through the React tree including portals, so@@ -1295,6 +1322,18 @@ export function JsxComponentView({ node, editor, extension, getPos, selected }:selected={isInnermostSelected}/></PopoverAnchor>+ ) : showSourcePlaceholder && sourcePlaceholder ? (+ // Source-bearing leaf (Mermaid) with an empty source prop. No+ // PopoverAnchor: its authoring surface is the fullscreen edit modal,+ // not the PropPanel popover, so the card opens the modal directly.+ // The card's min-height is what keeps the block a real click target+ // and stops the hover chrome (pencil / trash) from being clipped.+ <DescriptorPlaceholder+ label={sourcePlaceholder.label}+ Icon={sourcePlaceholder.Icon}+ onClick={() => setEditModalOpen(true)}+ selected={isInnermostSelected}+ />) : (<ComponentErrorBoundaryresetKey={resetKey}diff --git a/packages/app/src/editor/slash-command/component-items.tsx b/packages/app/src/editor/slash-command/component-items.tsxindex 16881ce6b..e14ff5281 100644--- a/packages/app/src/editor/slash-command/component-items.tsx+++ b/packages/app/src/editor/slash-command/component-items.tsx@@ -432,6 +432,10 @@ export function consumeAutoOpen(pos?: number): boolean {* After inserting a component, focus appropriately:* - Has editable props → NodeSelect the component (triggers popover auto-open)* - Has children only → place cursor inside children for typing+ * - Self-closing leaf with no editable props (source-bearing, e.g. Mermaid,+ * whose source is authored in the fullscreen edit modal) → NodeSelect it so+ * the placeholder card + chrome show, and flag the NodeView to auto-open its+ * edit modal on selection*/export function focusInsertedComponent(editor: Editor,@@ -449,6 +453,18 @@ export function focusInsertedComponent(});} else if (descriptor.hasChildren) {editor.commands.setTextSelection(insertPos + 2);+ } else {+ // Self-closing leaf with no editable props — today only MermaidFence,+ // whose source lives in the fullscreen edit modal, not the PropPanel.+ // Without this branch a slash insert did nothing visible: no selection,+ // no cursor move, and the empty renderer collapsed to a zero-height+ // sliver. NodeSelect it so the placeholder card + chrome render, and let+ // the NodeView auto-open the edit modal off the same pendingAutoOpen flag+ // the popover path uses.+ setPendingAutoOpen(insertPos);+ requestAnimationFrame(() => {+ editor.commands.setNodeSelection(insertPos);+ });}}diff --git a/packages/app/src/editor/slash-command/focus-inserted-component.test.ts b/packages/app/src/editor/slash-command/focus-inserted-component.test.tsnew file mode 100644index 000000000..6ba994b1c--- /dev/null+++ b/packages/app/src/editor/slash-command/focus-inserted-component.test.ts@@ -0,0 +1,88 @@+/**+ * Unit tests for `focusInsertedComponent`'s branch selection — which post-+ * insert focus/auto-open action fires for each descriptor shape.+ *+ * The interesting case is a self-closing leaf with NO editable props (today+ * MermaidFence): its source is authored in the fullscreen edit modal, so+ * every prop is hidden and `hasEditableProps` is false. Before the fix this+ * fell through to a no-op — the slash insert did nothing visible. Now it must+ * flag a pending auto-open (consumed by the NodeView to open the edit modal),+ * exactly like the editable-props popover path.+ */++import { afterEach, beforeAll, describe, expect, test } from 'bun:test';+import type { Editor } from '@tiptap/react';+import type { JsxComponentDescriptor } from '../registry/types';+import {+ _resetPendingAutoOpenForTest,+ consumeAutoOpen,+ focusInsertedComponent,+} from './component-items';++// `focusInsertedComponent` schedules `setNodeSelection` inside rAF. The Bun+// unit runtime has no DOM, so rAF may be absent — stub it as a no-op (we only+// assert the synchronous pending-auto-open flag, not the deferred selection).+beforeAll(() => {+ if (typeof globalThis.requestAnimationFrame !== 'function') {+ (+ globalThis as { requestAnimationFrame: (cb: FrameRequestCallback) => number }+ ).requestAnimationFrame = () => 0;+ }+});++afterEach(() => {+ _resetPendingAutoOpenForTest();+});++// Minimal editor stub — the branch under test only reaches `commands.*`+// inside the rAF callback (stubbed away) or synchronously for the children+// path; neither needs a real editor.+const fakeEditor = {+ commands: {+ setNodeSelection: () => true,+ setTextSelection: () => true,+ },+} as unknown as Editor;++function descriptor(partial: Partial<JsxComponentDescriptor>): JsxComponentDescriptor {+ return {+ name: 'X',+ surface: 'canonical',+ hasChildren: false,+ props: [],+ ...partial,+ } as JsxComponentDescriptor;+}++describe('focusInsertedComponent — post-insert focus branch', () => {+ test('source-bearing self-closing leaf (all props hidden) flags a pending auto-open', () => {+ const mermaidLike = descriptor({+ name: 'MermaidFence',+ hasChildren: false,+ // Single required-but-hidden prop → hasEditableProps === false.+ props: [{ name: 'chart', type: 'string', required: true, hidden: true }],+ });+ focusInsertedComponent(fakeEditor, 12, mermaidLike);+ expect(consumeAutoOpen(12)).toBe(true);+ });++ test('descriptor with editable props flags a pending auto-open (popover path)', () => {+ const withProps = descriptor({+ name: 'img',+ hasChildren: false,+ props: [{ name: 'src', type: 'string', required: true }],+ });+ focusInsertedComponent(fakeEditor, 8, withProps);+ expect(consumeAutoOpen(8)).toBe(true);+ });++ test('children-only descriptor does NOT flag an auto-open (cursor goes inside)', () => {+ const container = descriptor({+ name: 'Callout',+ hasChildren: true,+ props: [],+ });+ focusInsertedComponent(fakeEditor, 20, container);+ expect(consumeAutoOpen(20)).toBe(false);+ });+});diff --git a/packages/app/src/globals.css b/packages/app/src/globals.cssindex ce7cc9626..b4ba26075 100644--- a/packages/app/src/globals.css+++ b/packages/app/src/globals.css@@ -965,6 +965,17 @@does not prematurely hide it. padding-left compensates so text is unchanged. */margin-left: -2.5rem;padding-left: 2.5rem;+ /* Mirror the same negative-margin/padding trick on the right. Without it, the+ content box's right edge sits flush with the editor element's border-box+ right edge (content-end), so a `w-full` bordered block (e.g. the empty-Mermaid+ placeholder card) paints its right border with ZERO in-element slack — the+ left border has 2.5rem of it. Any right-side clip (an overflow ancestor's edge+ or a scrollbar gutter at wide widths) then shaves that flush 1px right border+ while the slack-protected left/top/bottom survive. Extending the border-box+ 2.5rem into the right gutter (padding-right compensates, so text and every+ block stay put) gives the right border the same slack the left already has. */+ margin-right: -2.5rem;+ padding-right: 2.5rem;@apply text-gray-800 dark:text-white/80;}@@ -982,6 +993,11 @@line-height: 1.5;margin-left: 0;padding-left: 0;+ /* Drop the right gutter mirror too — the slim composer is a single-line prompt,+ not a document body, so it needs neither the drag-handle hit area nor the+ full-width-block border slack. */+ margin-right: 0;+ padding-right: 0;}.ProseMirror.composer-prosemirror p {diff --git a/packages/app/src/locales/en/messages.json b/packages/app/src/locales/en/messages.jsonindex 3633924c3..e6537b534 100644--- a/packages/app/src/locales/en/messages.json+++ b/packages/app/src/locales/en/messages.json@@ -427,6 +427,7 @@"8fRyLo": ["Invalid patch payload"],"8fc_3j": ["Protected branch — cannot push"],"8m8diM": ["No location selected. Use Browse to choose a folder."],+ "8nWu1k": ["Empty diagram"],"8tjQCz": ["Explore"],"8uAWix": ["This template lives in a parent folder — deleting it affects every folder beneath it that doesn't define its own version."diff --git a/packages/app/src/locales/en/messages.po b/packages/app/src/locales/en/messages.poindex a1080e491..7dda75226 100644--- a/packages/app/src/locales/en/messages.po+++ b/packages/app/src/locales/en/messages.po@@ -3030,6 +3030,10 @@ msgstr "empty"msgid "Empty"msgstr "Empty"+#: src/editor/components/Mermaid.tsx+msgid "Empty diagram"+msgstr "Empty diagram"+#: src/components/NewItemDialog.tsxmsgid "Empty starting content"msgstr "Empty starting content"diff --git a/packages/app/src/locales/pseudo/messages.json b/packages/app/src/locales/pseudo/messages.jsonindex 649769fe6..56d88dc74 100644--- a/packages/app/src/locales/pseudo/messages.json+++ b/packages/app/src/locales/pseudo/messages.json@@ -427,6 +427,7 @@"8fRyLo": ["Ĩńvàĺĩď ƥàţćĥ ƥàŷĺōàď"],"8fc_3j": ["Ƥŕōţēćţēď ƀŕàńćĥ — ćàńńōţ ƥũśĥ"],"8m8diM": ["Ńō ĺōćàţĩōń śēĺēćţēď. Ũśē ßŕōŵśē ţō ćĥōōśē à ƒōĺďēŕ."],+ "8nWu1k": ["Ēḿƥţŷ ďĩàĝŕàḿ"],"8tjQCz": ["Ēxƥĺōŕē"],"8uAWix": ["Ţĥĩś ţēḿƥĺàţē ĺĩvēś ĩń à ƥàŕēńţ ƒōĺďēŕ — ďēĺēţĩńĝ ĩţ àƒƒēćţś ēvēŕŷ ƒōĺďēŕ ƀēńēàţĥ ĩţ ţĥàţ ďōēśń'ţ ďēƒĩńē ĩţś ōŵń vēŕśĩōń."diff --git a/packages/app/src/locales/pseudo/messages.po b/packages/app/src/locales/pseudo/messages.poindex 65f505957..4ef9f4a67 100644--- a/packages/app/src/locales/pseudo/messages.po+++ b/packages/app/src/locales/pseudo/messages.po@@ -3025,6 +3025,10 @@ msgstr ""msgid "Empty"msgstr ""+#: src/editor/components/Mermaid.tsx+msgid "Empty diagram"+msgstr ""+#: src/components/NewItemDialog.tsxmsgid "Empty starting content"msgstr ""diff --git a/packages/core/src/registry/built-ins.ts b/packages/core/src/registry/built-ins.tsindex 268dfb937..d134d9528 100644--- a/packages/core/src/registry/built-ins.ts+++ b/packages/core/src/registry/built-ins.ts@@ -1336,6 +1336,11 @@ export const builtInComponents: JsxComponentMeta[] = [icon: 'Workflow',category: 'content',displayName: 'Mermaid',+ // Every prop is hidden (source is authored in the fullscreen edit modal,+ // not the PropPanel), so the editor can't fall back on the autoFocus+ // placeholder path for an empty diagram. This label drives an explicit+ // empty-state card the NodeView renders instead of a zero-height stub.+ placeholder: { label: 'Add a Mermaid diagram' },description:'Diagram rendered from Mermaid source (flowchart, sequence, class, state, ER, gantt, pie). Authored exclusively as ` ```mermaid ` fenced code.',searchTerms: [