Skip to content

Commit 1b3b9b8

Browse files
author
Tim Sinaeve
committed
fix: code editor focus stability, mermaid error isolation, and release v0.9.7
- Preserve Monaco code editor and prompt editor focus during keystrokes by stabilizing callback references and decoupling editor lifecycle - Isolate Mermaid syntax errors within preview cards to prevent document.body SVG pollution and layout distortion - Resolve cross-platform path resolution in GUI test plan script - Update package version, changelog, and release documentation for v0.9.7
1 parent afd727c commit 1b3b9b8

17 files changed

Lines changed: 440 additions & 64 deletions

‎VERSION_LOG.md‎

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,20 @@
11
## Unreleased
22

3-
- _No entries yet._
3+
- _No entries yet._
4+
5+
## v0.9.7 - Code Editor Focus Stability & Mermaid Error Isolation (September 2026)
6+
7+
### 🐛 Bug Fixes & Stability
8+
9+
- **Code Editor Focus Preservation on Text Entry**:
10+
- Fixed a regression where typing into the Monaco code editor caused immediate loss of focus after entering the first character.
11+
- Stabilized event and action callback references (`onManualSave`, `onSaveToFile`, `onChange`, `onScroll`, `onFocusChange`, `onSelectionChange`) via mutable refs in `CodeEditor`, `PromptEditor`, and `MonacoDiffEditor`.
12+
- Decoupled Monaco editor mounting and shortcut registration dependencies to prevent the editor DOM container from detaching, tearing down, and recreating on keystrokes.
13+
- **Mermaid Syntax Error DOM Pollution Fix**:
14+
- Prevented Mermaid from injecting "Syntax error in text" bomb SVGs into `document.body` when diagram syntax is invalid.
15+
- Enabled `suppressErrorRendering: true`, pre-validated syntax with `mermaid.parse()`, rendered into detached containers, and added active cleanup and CSS containment rules to isolate diagram errors cleanly within the preview pane error card without distorting the application layout.
16+
- **Cross-Platform Test Runner**:
17+
- Resolved Windows path prefix resolution in test plan validation script using `fileURLToPath`.
418

519
## v0.9.6 - Multi-Format Export & Navigation Polish (September 2026)
620

Lines changed: 145 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,145 @@
1+
import React, { useState, act } from 'react';
2+
import { render, waitFor } from '@testing-library/react';
3+
import { beforeEach, describe, expect, it, vi } from 'vitest';
4+
import CodeEditor from '../components/CodeEditor';
5+
6+
let mockModelContentCallback: (() => void) | null = null;
7+
let mockEditorInstance: any = null;
8+
let mockContainer: HTMLDivElement | null = null;
9+
let getSharedEditorCallCount = 0;
10+
let switchToDocumentCallCount = 0;
11+
let saveCurrentViewStateCallCount = 0;
12+
13+
vi.mock('../hooks/useTheme', () => ({
14+
useTheme: () => ({
15+
theme: 'dark',
16+
toggleTheme: vi.fn(),
17+
}),
18+
}));
19+
20+
vi.mock('../services/editor/monacoLoader', () => ({
21+
ensureMonaco: vi.fn().mockResolvedValue({
22+
KeyMod: { CtrlCmd: 2048, WinCtrl: 256, Shift: 1024, Alt: 512 },
23+
KeyCode: { KeyS: 49, KeyA: 31, Slash: 85 },
24+
editor: {
25+
setModelLanguage: vi.fn(),
26+
defineTheme: vi.fn(),
27+
setTheme: vi.fn(),
28+
},
29+
}),
30+
}));
31+
32+
vi.mock('../services/editor/registerTomlLanguage', () => ({
33+
registerTomlLanguage: vi.fn(),
34+
}));
35+
36+
vi.mock('../services/editor/registerPlantumlLanguage', () => ({
37+
registerPlantumlLanguage: vi.fn(),
38+
}));
39+
40+
vi.mock('../services/editor/monacoEditorPool', () => ({
41+
monacoEditorPool: {
42+
getSharedEditor: vi.fn().mockImplementation(async () => {
43+
getSharedEditorCallCount++;
44+
return { editor: mockEditorInstance, container: mockContainer };
45+
}),
46+
switchToDocument: vi.fn().mockImplementation(() => {
47+
switchToDocumentCallCount++;
48+
}),
49+
saveCurrentViewState: vi.fn().mockImplementation(() => {
50+
saveCurrentViewStateCallCount++;
51+
}),
52+
},
53+
}));
54+
55+
describe('CodeEditor Stability & Focus Preservation', () => {
56+
beforeEach(() => {
57+
vi.clearAllMocks();
58+
getSharedEditorCallCount = 0;
59+
switchToDocumentCallCount = 0;
60+
saveCurrentViewStateCallCount = 0;
61+
mockModelContentCallback = null;
62+
63+
mockContainer = document.createElement('div');
64+
mockContainer.className = 'mock-monaco-container';
65+
66+
let currentVal = 'Hello';
67+
mockEditorInstance = {
68+
addAction: vi.fn().mockReturnValue({ dispose: vi.fn() }),
69+
onDidChangeModelContent: vi.fn().mockImplementation((cb) => {
70+
mockModelContentCallback = cb;
71+
return { dispose: vi.fn() };
72+
}),
73+
onDidScrollChange: vi.fn().mockReturnValue({ dispose: vi.fn() }),
74+
onDidChangeCursorSelection: vi.fn().mockReturnValue({ dispose: vi.fn() }),
75+
onContextMenu: vi.fn().mockReturnValue({ dispose: vi.fn() }),
76+
onDidFocusEditorWidget: vi.fn().mockReturnValue({ dispose: vi.fn() }),
77+
onDidBlurEditorWidget: vi.fn().mockReturnValue({ dispose: vi.fn() }),
78+
updateOptions: vi.fn(),
79+
getValue: vi.fn().mockImplementation(() => currentVal),
80+
setValue: vi.fn().mockImplementation((v) => { currentVal = v; }),
81+
getSelection: vi.fn().mockReturnValue(null),
82+
saveViewState: vi.fn().mockReturnValue(null),
83+
restoreViewState: vi.fn(),
84+
getModel: vi.fn().mockReturnValue({}),
85+
getLayoutInfo: vi.fn().mockReturnValue({ height: 500 }),
86+
getScrollTop: vi.fn().mockReturnValue(0),
87+
getScrollHeight: vi.fn().mockReturnValue(500),
88+
};
89+
});
90+
91+
it('does not re-initialize editor or detach container when content and callbacks change on keystroke', async () => {
92+
let parentRenderCount = 0;
93+
94+
const TestHarness: React.FC = () => {
95+
parentRenderCount++;
96+
const [content, setContent] = useState('Hello');
97+
98+
// Re-created on every render (simulating dynamic handleManualSave in PromptEditor)
99+
const dynamicManualSave = () => {
100+
// manual save
101+
};
102+
103+
return (
104+
<CodeEditor
105+
documentId="doc-123"
106+
content={content}
107+
language="markdown"
108+
onChange={(newVal) => setContent(newVal)}
109+
onManualSave={dynamicManualSave}
110+
/>
111+
);
112+
};
113+
114+
render(<TestHarness />);
115+
116+
await waitFor(() => {
117+
expect(getSharedEditorCallCount).toBe(1);
118+
expect(switchToDocumentCallCount).toBe(1);
119+
});
120+
121+
const initialContainerParent = mockContainer?.parentNode;
122+
expect(initialContainerParent).not.toBeNull();
123+
expect(saveCurrentViewStateCallCount).toBe(0);
124+
125+
// Simulate entering a character: Monaco changes its internal value and fires onDidChangeModelContent
126+
act(() => {
127+
mockEditorInstance.setValue('Hello World');
128+
mockModelContentCallback?.();
129+
});
130+
131+
// Verify parent re-rendered with new state and new callback reference
132+
expect(parentRenderCount).toBeGreaterThanOrEqual(2);
133+
134+
// CRITICAL CHECKS:
135+
// 1. Monaco editor was NOT re-initialized
136+
expect(getSharedEditorCallCount).toBe(1);
137+
expect(switchToDocumentCallCount).toBe(1);
138+
139+
// 2. The DOM container was NOT detached from the editor DOM node
140+
expect(mockContainer?.parentNode).toBe(initialContainerParent);
141+
142+
// 3. Save current view state was not triggered (meaning the cleanup function did NOT run)
143+
expect(saveCurrentViewStateCallCount).toBe(0);
144+
});
145+
});

‎artifacts/gui-test-plan-validation.html‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@
5858
</head>
5959
<body>
6060
<h1>GUI Test Plan Validation Results</h1>
61-
<p class="meta">Generated: 2025-10-04T19:14:02.925Z</p>
61+
<p class="meta">Generated: 2026-09-16T13:47:22.376Z</p>
6262
<table>
6363
<thead>
6464
<tr><th>Test</th><th>Status</th><th>Details</th></tr>

‎artifacts/gui-test-plan-validation.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
{
2-
"timestamp": "2025-10-04T19:14:02.925Z",
2+
"timestamp": "2026-09-16T13:47:22.376Z",
33
"validations": [
44
{
55
"name": "Heading present: ## 1. Prioritized Test Scenarios",

‎artifacts/gui-test-plan-validation.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
# GUI Test Plan Validation Results
22

3-
Generated: 2025-10-04T19:14:02.925Z
3+
Generated: 2026-09-16T13:47:22.376Z
44

55
| Test | Status | Details |
66
| --- | --- | --- |

‎components/CodeEditor.tsx‎

Lines changed: 51 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -438,6 +438,37 @@ const CodeEditor = forwardRef<CodeEditorHandle, CodeEditorProps>(({
438438
emojiActionDisposableRef.current = null;
439439
}, []);
440440

441+
const onChangeRef = useRef(onChange);
442+
const onScrollRef = useRef(onScroll);
443+
const onSelectionChangeRef = useRef(onSelectionChange);
444+
const onFocusChangeRef = useRef(onFocusChange);
445+
const onSaveToFileRef = useRef(onSaveToFile);
446+
const onManualSaveRef = useRef(onManualSave);
447+
448+
useEffect(() => {
449+
onChangeRef.current = onChange;
450+
}, [onChange]);
451+
452+
useEffect(() => {
453+
onScrollRef.current = onScroll;
454+
}, [onScroll]);
455+
456+
useEffect(() => {
457+
onSelectionChangeRef.current = onSelectionChange;
458+
}, [onSelectionChange]);
459+
460+
useEffect(() => {
461+
onFocusChangeRef.current = onFocusChange;
462+
}, [onFocusChange]);
463+
464+
useEffect(() => {
465+
onSaveToFileRef.current = onSaveToFile;
466+
}, [onSaveToFile]);
467+
468+
useEffect(() => {
469+
onManualSaveRef.current = onManualSave;
470+
}, [onManualSave]);
471+
441472
const disposeFocusListeners = useCallback(() => {
442473
focusDisposableRef.current?.dispose();
443474
focusDisposableRef.current = null;
@@ -478,20 +509,20 @@ const CodeEditor = forwardRef<CodeEditorHandle, CodeEditorProps>(({
478509
}
479510
});
480511

481-
if (onSaveToFile) {
512+
if (onSaveToFileRef.current) {
482513
const saveToFileDisposable = monacoInstanceRef.current.addAction({
483514
id: 'docforge.saveToFile',
484515
label: 'Save to File…',
485516
contextMenuGroupId: 'navigation',
486517
contextMenuOrder: 1.5,
487-
run: () => onSaveToFile(),
518+
run: () => onSaveToFileRef.current?.(),
488519
});
489520
if (saveToFileDisposable) {
490521
actionDisposablesRef.current.push(saveToFileDisposable);
491522
}
492523
}
493524

494-
if (onManualSave) {
525+
if (onManualSaveRef.current) {
495526
const customSaveKeys = customShortcutsRef.current['document-manual-save'];
496527
const saveKeybinding = customSaveKeys && customSaveKeys.length > 0
497528
? toMonacoKeybinding(monacoApi, customSaveKeys)
@@ -502,21 +533,21 @@ const CodeEditor = forwardRef<CodeEditorHandle, CodeEditorProps>(({
502533
id: 'docforge.manualSave',
503534
label: 'Save Document Version',
504535
keybindings: [saveKeybinding],
505-
run: () => onManualSave(),
536+
run: () => onManualSaveRef.current?.(),
506537
});
507538
if (manualSaveDisposable) {
508539
actionDisposablesRef.current.push(manualSaveDisposable);
509540
}
510541
}
511542
}
512-
}, [disposeEditorShortcuts, onSaveToFile, onManualSave]);
543+
}, [disposeEditorShortcuts]);
513544

514545
useEffect(() => {
515546
customShortcutsRef.current = customShortcuts ?? {};
516547
if (monacoInstanceRef.current) {
517548
applyEditorShortcuts();
518549
}
519-
}, [customShortcuts, applyEditorShortcuts]);
550+
}, [customShortcuts, applyEditorShortcuts, Boolean(onSaveToFile), Boolean(onManualSave)]);
520551

521552
useEffect(() => {
522553
contentRef.current = content;
@@ -604,14 +635,14 @@ const CodeEditor = forwardRef<CodeEditorHandle, CodeEditorProps>(({
604635
const contentDisposable = editorInstance.onDidChangeModelContent(() => {
605636
const currentValue = editorInstance.getValue();
606637
if (currentValue !== contentRef.current) {
607-
onChange(currentValue);
638+
onChangeRef.current(currentValue);
608639
}
609640
});
610641
listenerDisposablesRef.current.push(contentDisposable);
611642

612643
const scrollDisposable = editorInstance.onDidScrollChange((e: any) => {
613644
if (e.scrollTopChanged) {
614-
onScroll?.({
645+
onScrollRef.current?.({
615646
scrollTop: e.scrollTop,
616647
scrollHeight: e.scrollHeight,
617648
clientHeight: editorInstance.getLayoutInfo().height
@@ -624,9 +655,9 @@ const CodeEditor = forwardRef<CodeEditorHandle, CodeEditorProps>(({
624655
const selectionDisposable = editorInstance.onDidChangeCursorSelection(() => {
625656
const selection = editorInstance.getSelection();
626657
if (selection && !selection.isEmpty()) {
627-
onSelectionChange?.(editorInstance.getModel().getValueInRange(selection));
658+
onSelectionChangeRef.current?.(editorInstance.getModel().getValueInRange(selection));
628659
} else {
629-
onSelectionChange?.(undefined);
660+
onSelectionChangeRef.current?.(undefined);
630661
}
631662
});
632663
listenerDisposablesRef.current.push(selectionDisposable);
@@ -642,17 +673,15 @@ const CodeEditor = forwardRef<CodeEditorHandle, CodeEditorProps>(({
642673
});
643674
listenerDisposablesRef.current.push(contextDisposable);
644675

645-
if (onFocusChange) {
646-
const focusDisposable = editorInstance.onDidFocusEditorWidget(() => {
647-
onFocusChange(true);
648-
});
649-
listenerDisposablesRef.current.push(focusDisposable);
650-
651-
const blurDisposable = editorInstance.onDidBlurEditorWidget(() => {
652-
onFocusChange(false);
653-
});
654-
listenerDisposablesRef.current.push(blurDisposable);
655-
}
676+
const focusDisposable = editorInstance.onDidFocusEditorWidget(() => {
677+
onFocusChangeRef.current?.(true);
678+
});
679+
listenerDisposablesRef.current.push(focusDisposable);
680+
681+
const blurDisposable = editorInstance.onDidBlurEditorWidget(() => {
682+
onFocusChangeRef.current?.(false);
683+
});
684+
listenerDisposablesRef.current.push(blurDisposable);
656685

657686
monacoInstanceRef.current = editorInstance;
658687
applyEditorShortcuts();
@@ -698,7 +727,7 @@ const CodeEditor = forwardRef<CodeEditorHandle, CodeEditorProps>(({
698727
emojiActionDisposableRef.current = null;
699728
monacoApiRef.current = null;
700729
};
701-
}, [documentId, onChange, onScroll, applyEditorShortcuts, disposeEditorShortcuts, disposeListeners, readOnly, onFocusChange]);
730+
}, [documentId, disposeEditorShortcuts, disposeListeners]);
702731

703732
// Effect to update content from props if it changes externally
704733
useEffect(() => {

0 commit comments

Comments
 (0)