@bendyline/squisq-editor-react 1.6.0 → 1.6.1
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/README.md +57 -10
- package/dist/index.d.ts +401 -76
- package/dist/index.js +1334 -930
- package/dist/index.js.map +1 -1
- package/dist/styles/fa-brands-400-AHOAZHCU.woff2 +0 -0
- package/dist/styles/fa-regular-400-VRZYIBIZ.woff2 +0 -0
- package/dist/styles/fa-solid-900-MDEYK55F.woff2 +0 -0
- package/dist/styles/fa-v4compatibility-ETEVP6IB.woff2 +0 -0
- package/dist/styles/index.css +13867 -0
- package/package.json +15 -7
- package/src/EditorContext.tsx +22 -16
- package/src/EditorShell.tsx +68 -27
- package/src/OutlinePanel.tsx +26 -4
- package/src/PreviewControls.tsx +338 -141
- package/src/PreviewPanel.tsx +15 -9
- package/src/RawEditor.tsx +10 -4
- package/src/Toolbar.tsx +21 -11
- package/src/VersionHistoryPanel.tsx +2 -2
- package/src/__tests__/codeContextSectionView.test.tsx +95 -0
- package/src/__tests__/codeContextZoneManager.test.ts +127 -0
- package/src/__tests__/diffContextSections.test.ts +39 -0
- package/src/__tests__/editorShellCodeContext.test.tsx +86 -0
- package/src/__tests__/editorShellProps.test.tsx +96 -0
- package/src/__tests__/previewControls.test.tsx +70 -0
- package/src/__tests__/useJsonEditorTokens.test.ts +59 -0
- package/src/__tests__/useMediaRecorder.test.ts +17 -0
- package/src/codeContext/CodeContextSectionView.tsx +124 -0
- package/src/codeContext/CodeContextZoneManager.ts +149 -0
- package/src/codeContext/CodeContextZones.tsx +121 -0
- package/src/codeContext/diffContextSections.ts +38 -0
- package/src/codeContext/types.ts +75 -0
- package/src/index.ts +32 -1
- package/src/jsonEditor/useJsonEditorTokens.ts +13 -43
- package/src/recorder/hooks/useMediaRecorder.ts +9 -10
- package/src/styles/code-context.css +155 -0
- package/src/styles/editor.css +149 -3
- package/src/styles/index.css +1 -0
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @vitest-environment jsdom
|
|
3
|
+
*/
|
|
4
|
+
import { afterEach, describe, expect, it } from 'vitest';
|
|
5
|
+
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
|
|
6
|
+
import { EditorProvider, useEditorContext } from '../EditorContext';
|
|
7
|
+
import { PreviewModeSwitch, PreviewSettingsProvider, usePreviewSettings } from '../PreviewControls';
|
|
8
|
+
|
|
9
|
+
function ModeProbe() {
|
|
10
|
+
const { activeDisplayMode } = usePreviewSettings();
|
|
11
|
+
return <div data-testid="active-mode">{activeDisplayMode}</div>;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
function PreviewHarness() {
|
|
15
|
+
const { doc } = useEditorContext();
|
|
16
|
+
return (
|
|
17
|
+
<PreviewSettingsProvider doc={doc}>
|
|
18
|
+
<PreviewModeSwitch />
|
|
19
|
+
<ModeProbe />
|
|
20
|
+
</PreviewSettingsProvider>
|
|
21
|
+
);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function renderPreviewControls(markdown: string) {
|
|
25
|
+
render(
|
|
26
|
+
<EditorProvider initialMarkdown={markdown}>
|
|
27
|
+
<PreviewHarness />
|
|
28
|
+
</EditorProvider>,
|
|
29
|
+
);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
afterEach(() => cleanup());
|
|
33
|
+
|
|
34
|
+
describe('PreviewModeSwitch', () => {
|
|
35
|
+
it('labels the plain document preview as Document and the styled view as Page', () => {
|
|
36
|
+
renderPreviewControls('# Hello');
|
|
37
|
+
|
|
38
|
+
const labels = screen
|
|
39
|
+
.getAllByRole('button')
|
|
40
|
+
.map((button) => button.textContent)
|
|
41
|
+
.filter(Boolean);
|
|
42
|
+
|
|
43
|
+
expect(labels).toEqual(['Video', 'Slideshow', 'Page', 'Document']);
|
|
44
|
+
|
|
45
|
+
fireEvent.click(screen.getByRole('button', { name: 'Document' }));
|
|
46
|
+
expect(screen.getByTestId('active-mode').textContent).toBe('page');
|
|
47
|
+
|
|
48
|
+
fireEvent.click(screen.getByRole('button', { name: 'Page' }));
|
|
49
|
+
expect(screen.getByTestId('active-mode').textContent).toBe('linear');
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
it('maps product-facing display-mode frontmatter to the correct renderer values', async () => {
|
|
53
|
+
renderPreviewControls('---\ndisplay-mode: document\n---\n\n# Hello');
|
|
54
|
+
|
|
55
|
+
await waitFor(() => {
|
|
56
|
+
expect(screen.getByTestId('active-mode').textContent).toBe('page');
|
|
57
|
+
});
|
|
58
|
+
expect(screen.getByRole('button', { name: 'Document' }).getAttribute('aria-pressed')).toBe(
|
|
59
|
+
'true',
|
|
60
|
+
);
|
|
61
|
+
|
|
62
|
+
cleanup();
|
|
63
|
+
renderPreviewControls('---\ndisplay-mode: page\n---\n\n# Hello');
|
|
64
|
+
|
|
65
|
+
await waitFor(() => {
|
|
66
|
+
expect(screen.getByTestId('active-mode').textContent).toBe('linear');
|
|
67
|
+
});
|
|
68
|
+
expect(screen.getByRole('button', { name: 'Page' }).getAttribute('aria-pressed')).toBe('true');
|
|
69
|
+
});
|
|
70
|
+
});
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
|
|
2
|
+
import { renderHook } from '@testing-library/react';
|
|
3
|
+
import { DARK_SURFACE, LIGHT_SURFACE, DEFAULT_THEME } from '@bendyline/squisq/schemas';
|
|
4
|
+
import { useJsonEditorTokens } from '../jsonEditor/useJsonEditorTokens';
|
|
5
|
+
|
|
6
|
+
type StyleBag = Record<string, string>;
|
|
7
|
+
|
|
8
|
+
/** Install a matchMedia stub whose `(prefers-color-scheme: dark)` resolves to `dark`. */
|
|
9
|
+
function mockPrefersDark(dark: boolean): void {
|
|
10
|
+
Object.defineProperty(window, 'matchMedia', {
|
|
11
|
+
configurable: true,
|
|
12
|
+
value: (query: string) => ({
|
|
13
|
+
matches: dark && query.includes('dark'),
|
|
14
|
+
media: query,
|
|
15
|
+
onchange: null,
|
|
16
|
+
addListener: vi.fn(),
|
|
17
|
+
removeListener: vi.fn(),
|
|
18
|
+
addEventListener: vi.fn(),
|
|
19
|
+
removeEventListener: vi.fn(),
|
|
20
|
+
dispatchEvent: vi.fn(() => false),
|
|
21
|
+
}),
|
|
22
|
+
});
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
describe('useJsonEditorTokens', () => {
|
|
26
|
+
afterEach(() => {
|
|
27
|
+
vi.restoreAllMocks();
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
it('emits jsonform-prefixed tokens', () => {
|
|
31
|
+
mockPrefersDark(false);
|
|
32
|
+
const { result } = renderHook(() => useJsonEditorTokens(DEFAULT_THEME, LIGHT_SURFACE));
|
|
33
|
+
const style = result.current.style as StyleBag;
|
|
34
|
+
expect(style['--squisq-jsonform-bg']).toBe(LIGHT_SURFACE.background);
|
|
35
|
+
expect(style).toHaveProperty('--squisq-jsonform-warning');
|
|
36
|
+
expect(style).toHaveProperty('--squisq-jsonform-input-bg');
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
it("responds to a dark OS preference under surface='auto' (reactive via useAutoSurface)", () => {
|
|
40
|
+
mockPrefersDark(true);
|
|
41
|
+
const { result } = renderHook(() => useJsonEditorTokens(DEFAULT_THEME, 'auto'));
|
|
42
|
+
const style = result.current.style as StyleBag;
|
|
43
|
+
expect(style['--squisq-jsonform-bg']).toBe(DARK_SURFACE.background);
|
|
44
|
+
expect(style['--squisq-jsonform-text']).toBe(DARK_SURFACE.text);
|
|
45
|
+
expect(result.current.theme.colors.background).toBe(DARK_SURFACE.background);
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
it("uses light surface under surface='auto' when the OS prefers light", () => {
|
|
49
|
+
mockPrefersDark(false);
|
|
50
|
+
const { result } = renderHook(() => useJsonEditorTokens(DEFAULT_THEME, 'auto'));
|
|
51
|
+
const style = result.current.style as StyleBag;
|
|
52
|
+
expect(style['--squisq-jsonform-bg']).toBe(LIGHT_SURFACE.background);
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
beforeEach(() => {
|
|
56
|
+
// Default to a defined matchMedia so the hook's useAutoSurface can subscribe.
|
|
57
|
+
mockPrefersDark(false);
|
|
58
|
+
});
|
|
59
|
+
});
|
|
@@ -165,6 +165,23 @@ describe('useMediaRecorder lifecycle', () => {
|
|
|
165
165
|
expect(result.current.stream).not.toBeNull();
|
|
166
166
|
});
|
|
167
167
|
|
|
168
|
+
it('defaults to the mic source when called with no options', async () => {
|
|
169
|
+
const { result } = renderHook(() => useMediaRecorder());
|
|
170
|
+
|
|
171
|
+
expect(result.current.state).toBe('idle');
|
|
172
|
+
|
|
173
|
+
await act(async () => {
|
|
174
|
+
await result.current.request();
|
|
175
|
+
});
|
|
176
|
+
|
|
177
|
+
// Mic path: audio-only capture via getUserMedia, lands in `audio/`.
|
|
178
|
+
expect(result.current.state).toBe('ready');
|
|
179
|
+
expect(result.current.mimeType).toMatch(/^audio\/webm/);
|
|
180
|
+
expect(result.current.directory).toBe('audio');
|
|
181
|
+
const getUserMedia = navigator.mediaDevices.getUserMedia as ReturnType<typeof vi.fn>;
|
|
182
|
+
expect(getUserMedia).toHaveBeenCalled();
|
|
183
|
+
});
|
|
184
|
+
|
|
168
185
|
it('camera includes the mic by default', async () => {
|
|
169
186
|
const { result } = renderHook(() => useMediaRecorder({ source: 'camera' }));
|
|
170
187
|
await act(async () => {
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
import { parseMarkdown } from '@bendyline/squisq/markdown';
|
|
2
|
+
import { MarkdownRenderer } from '@bendyline/squisq-react';
|
|
3
|
+
import { useCallback, useEffect, useMemo, useRef } from 'react';
|
|
4
|
+
import type { CodeContext, CodeContextSection } from './types';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* One context section rendered inside a Monaco view zone: a single-line
|
|
8
|
+
* disclosure strip, plus the full markdown body while expanded. The body is
|
|
9
|
+
* rendered lazily — a file with 100 collapsed sections parses 100 one-liners,
|
|
10
|
+
* nothing more.
|
|
11
|
+
*/
|
|
12
|
+
export interface CodeContextSectionViewProps {
|
|
13
|
+
section: Omit<CodeContextSection, 'line'>;
|
|
14
|
+
expanded: boolean;
|
|
15
|
+
onToggle: (id: string) => void;
|
|
16
|
+
linkSchemes?: readonly string[] | undefined;
|
|
17
|
+
onLinkClick?: CodeContext['onLinkClick'] | undefined;
|
|
18
|
+
/** Native `#L<n>` handling: reveal that line in the editor. */
|
|
19
|
+
onRevealLine: (line: number) => void;
|
|
20
|
+
/** Reports the rendered content height so the zone can be resized to fit. */
|
|
21
|
+
onMeasure: (id: string, px: number) => void;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function CodeContextSectionView({
|
|
25
|
+
section,
|
|
26
|
+
expanded,
|
|
27
|
+
onToggle,
|
|
28
|
+
linkSchemes,
|
|
29
|
+
onLinkClick,
|
|
30
|
+
onRevealLine,
|
|
31
|
+
onMeasure,
|
|
32
|
+
}: CodeContextSectionViewProps) {
|
|
33
|
+
const rootRef = useRef<HTMLDivElement | null>(null);
|
|
34
|
+
|
|
35
|
+
const stripNodes = useMemo(
|
|
36
|
+
() => parseMarkdown(section.summaryMarkdown).children,
|
|
37
|
+
[section.summaryMarkdown],
|
|
38
|
+
);
|
|
39
|
+
const bodyNodes = useMemo(
|
|
40
|
+
() => (expanded && section.markdown ? parseMarkdown(section.markdown).children : null),
|
|
41
|
+
[expanded, section.markdown],
|
|
42
|
+
);
|
|
43
|
+
|
|
44
|
+
// Height feedback loop: report the content's real height whenever it
|
|
45
|
+
// changes. Monaco display:none's offscreen zones and ResizeObserver reports
|
|
46
|
+
// 0×0 for those — ignore zeros so scrolled-away zones keep their height.
|
|
47
|
+
useEffect(() => {
|
|
48
|
+
const el = rootRef.current;
|
|
49
|
+
if (!el || typeof ResizeObserver === 'undefined') return;
|
|
50
|
+
const report = () => {
|
|
51
|
+
const h = el.offsetHeight;
|
|
52
|
+
if (h > 0) onMeasure(section.id, h);
|
|
53
|
+
};
|
|
54
|
+
report();
|
|
55
|
+
const ro = new ResizeObserver(report);
|
|
56
|
+
ro.observe(el);
|
|
57
|
+
return () => ro.disconnect();
|
|
58
|
+
}, [section.id, onMeasure]);
|
|
59
|
+
|
|
60
|
+
// Delegated link interception. `#L<n>` reveals natively; everything else
|
|
61
|
+
// goes to the host callback (returning false opts back into default
|
|
62
|
+
// navigation).
|
|
63
|
+
const handleClick = useCallback(
|
|
64
|
+
(e: React.MouseEvent) => {
|
|
65
|
+
const anchor = (e.target as HTMLElement).closest?.('a');
|
|
66
|
+
if (!anchor) return;
|
|
67
|
+
const href = anchor.getAttribute('href') ?? '';
|
|
68
|
+
const lineMatch = /^#L(\d+)$/.exec(href);
|
|
69
|
+
if (lineMatch) {
|
|
70
|
+
e.preventDefault();
|
|
71
|
+
e.stopPropagation();
|
|
72
|
+
onRevealLine(Number(lineMatch[1]));
|
|
73
|
+
return;
|
|
74
|
+
}
|
|
75
|
+
if (onLinkClick) {
|
|
76
|
+
const handled = onLinkClick(href, { sectionId: section.id });
|
|
77
|
+
if (handled !== false) {
|
|
78
|
+
e.preventDefault();
|
|
79
|
+
e.stopPropagation();
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
},
|
|
83
|
+
[onLinkClick, onRevealLine, section.id],
|
|
84
|
+
);
|
|
85
|
+
|
|
86
|
+
// Keep Monaco's container-level mousedown handler from hijacking clicks
|
|
87
|
+
// and text selection inside the section.
|
|
88
|
+
const stopMouseDown = useCallback((e: React.MouseEvent) => {
|
|
89
|
+
e.stopPropagation();
|
|
90
|
+
}, []);
|
|
91
|
+
|
|
92
|
+
return (
|
|
93
|
+
// Click handler is delegated anchor interception only; keyboard users
|
|
94
|
+
// reach links natively and the strip itself is a real <button>.
|
|
95
|
+
<div
|
|
96
|
+
ref={rootRef}
|
|
97
|
+
className={`squisq-ccx-section${expanded ? ' squisq-ccx-section--expanded' : ''}`}
|
|
98
|
+
onClick={handleClick}
|
|
99
|
+
onMouseDown={stopMouseDown}
|
|
100
|
+
>
|
|
101
|
+
<button
|
|
102
|
+
type="button"
|
|
103
|
+
className="squisq-ccx-strip"
|
|
104
|
+
aria-expanded={expanded}
|
|
105
|
+
onClick={() => onToggle(section.id)}
|
|
106
|
+
>
|
|
107
|
+
<span className="squisq-ccx-chevron" aria-hidden="true">
|
|
108
|
+
{expanded ? '▾' : '▸'}
|
|
109
|
+
</span>
|
|
110
|
+
<span className="squisq-ccx-strip-text">
|
|
111
|
+
<MarkdownRenderer nodes={stripNodes} {...(linkSchemes ? { linkSchemes } : {})} />
|
|
112
|
+
</span>
|
|
113
|
+
</button>
|
|
114
|
+
{expanded &&
|
|
115
|
+
(bodyNodes ? (
|
|
116
|
+
<div className="squisq-ccx-body">
|
|
117
|
+
<MarkdownRenderer nodes={bodyNodes} {...(linkSchemes ? { linkSchemes } : {})} />
|
|
118
|
+
</div>
|
|
119
|
+
) : (
|
|
120
|
+
<div className="squisq-ccx-body squisq-ccx-body--loading">Loading…</div>
|
|
121
|
+
))}
|
|
122
|
+
</div>
|
|
123
|
+
);
|
|
124
|
+
}
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
import type { editor as MonacoEditorNs } from 'monaco-editor';
|
|
2
|
+
import { type ZoneSpec, diffContextSections } from './diffContextSections';
|
|
3
|
+
|
|
4
|
+
type MonacoEditor = MonacoEditorNs.IStandaloneCodeEditor;
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Owns the Monaco view zones behind the code-context sections. React-free —
|
|
8
|
+
* the React layer portals content into the zone dom nodes it hands out and
|
|
9
|
+
* feeds measured heights back via {@link setHeight}.
|
|
10
|
+
*
|
|
11
|
+
* Zone mechanics this leans on (monaco 0.50):
|
|
12
|
+
* - `changeViewZones` batches adds/removes/layouts into one whitespace
|
|
13
|
+
* re-layout.
|
|
14
|
+
* - `layoutZone(id)` re-reads the zone delegate, so mutating our own
|
|
15
|
+
* delegate's `afterLineNumber`/`heightInPx` then calling layoutZone both
|
|
16
|
+
* moves and resizes without remove/re-add churn (expanded DOM survives).
|
|
17
|
+
* - Zone dom nodes live in `.view-zones` (absolutely positioned, offscreen
|
|
18
|
+
* ones display:none'd by Monaco). They sit BELOW `.view-lines` in hit-test
|
|
19
|
+
* order, so the stylesheet raises `.squisq-ccx-zone` with a z-index and
|
|
20
|
+
* `pointer-events: auto` to make section content clickable.
|
|
21
|
+
* - Model swaps invalidate zone ids; the owner listens to onDidChangeModel
|
|
22
|
+
* and rebuilds.
|
|
23
|
+
*/
|
|
24
|
+
export class CodeContextZoneManager {
|
|
25
|
+
private readonly editor: MonacoEditor;
|
|
26
|
+
private entries = new Map<
|
|
27
|
+
string,
|
|
28
|
+
{
|
|
29
|
+
zoneId: string;
|
|
30
|
+
delegate: MonacoEditorNs.IViewZone;
|
|
31
|
+
domNode: HTMLDivElement;
|
|
32
|
+
spec: ZoneSpec;
|
|
33
|
+
}
|
|
34
|
+
>();
|
|
35
|
+
private listeners = new Set<() => void>();
|
|
36
|
+
private modelListener: { dispose(): void } | null = null;
|
|
37
|
+
private disposed = false;
|
|
38
|
+
|
|
39
|
+
/** Initial height estimate for a strip; the ResizeObserver corrects it. */
|
|
40
|
+
static readonly INITIAL_HEIGHT_PX = 28;
|
|
41
|
+
|
|
42
|
+
constructor(editor: MonacoEditor) {
|
|
43
|
+
this.editor = editor;
|
|
44
|
+
// A model swap (file change / external reset) invalidates every zone id.
|
|
45
|
+
// Drop our bookkeeping; the next sync() recreates zones against the new
|
|
46
|
+
// model.
|
|
47
|
+
this.modelListener = editor.onDidChangeModel(() => {
|
|
48
|
+
this.entries.clear();
|
|
49
|
+
this.emit();
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Reconcile the live zones against `specs` in one changeViewZones batch. */
|
|
54
|
+
sync(specs: ZoneSpec[]): void {
|
|
55
|
+
if (this.disposed) return;
|
|
56
|
+
const prev = [...this.entries.values()].map((e) => e.spec);
|
|
57
|
+
const { add, remove, move } = diffContextSections(prev, specs);
|
|
58
|
+
if (add.length === 0 && remove.length === 0 && move.length === 0) return;
|
|
59
|
+
|
|
60
|
+
this.editor.changeViewZones((accessor) => {
|
|
61
|
+
for (const id of remove) {
|
|
62
|
+
const entry = this.entries.get(id);
|
|
63
|
+
if (!entry) continue;
|
|
64
|
+
accessor.removeZone(entry.zoneId);
|
|
65
|
+
this.entries.delete(id);
|
|
66
|
+
}
|
|
67
|
+
for (const spec of move) {
|
|
68
|
+
const entry = this.entries.get(spec.id);
|
|
69
|
+
if (!entry) continue;
|
|
70
|
+
entry.spec = spec;
|
|
71
|
+
entry.delegate.afterLineNumber = Math.max(spec.line - 1, 0);
|
|
72
|
+
setOrdinal(entry.delegate, spec.ordinal);
|
|
73
|
+
accessor.layoutZone(entry.zoneId);
|
|
74
|
+
}
|
|
75
|
+
for (const spec of add) {
|
|
76
|
+
const domNode = document.createElement('div');
|
|
77
|
+
domNode.className = 'squisq-ccx-zone';
|
|
78
|
+
domNode.dataset.sectionId = spec.id;
|
|
79
|
+
const delegate: MonacoEditorNs.IViewZone = {
|
|
80
|
+
afterLineNumber: Math.max(spec.line - 1, 0),
|
|
81
|
+
heightInPx: CodeContextZoneManager.INITIAL_HEIGHT_PX,
|
|
82
|
+
domNode,
|
|
83
|
+
suppressMouseDown: true,
|
|
84
|
+
};
|
|
85
|
+
setOrdinal(delegate, spec.ordinal);
|
|
86
|
+
const zoneId = accessor.addZone(delegate);
|
|
87
|
+
this.entries.set(spec.id, { zoneId, delegate, domNode, spec });
|
|
88
|
+
}
|
|
89
|
+
});
|
|
90
|
+
this.emit();
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** Measured-content feedback: resize the zone to fit its rendered DOM. */
|
|
94
|
+
setHeight(id: string, px: number): void {
|
|
95
|
+
if (this.disposed) return;
|
|
96
|
+
const entry = this.entries.get(id);
|
|
97
|
+
if (!entry) return;
|
|
98
|
+
const height = Math.max(Math.ceil(px), 1);
|
|
99
|
+
if (Math.abs((entry.delegate.heightInPx ?? 0) - height) < 1) return;
|
|
100
|
+
entry.delegate.heightInPx = height;
|
|
101
|
+
this.editor.changeViewZones((accessor) => {
|
|
102
|
+
accessor.layoutZone(entry.zoneId);
|
|
103
|
+
});
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
getDomNode(id: string): HTMLDivElement | undefined {
|
|
107
|
+
return this.entries.get(id)?.domNode;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
liveIds(): string[] {
|
|
111
|
+
return [...this.entries.keys()];
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** Fires after sync/model-change so the React layer rebuilds its portals. */
|
|
115
|
+
onDidChangeZones(cb: () => void): () => void {
|
|
116
|
+
this.listeners.add(cb);
|
|
117
|
+
return () => this.listeners.delete(cb);
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
dispose(): void {
|
|
121
|
+
if (this.disposed) return;
|
|
122
|
+
this.disposed = true;
|
|
123
|
+
this.modelListener?.dispose();
|
|
124
|
+
this.modelListener = null;
|
|
125
|
+
if (this.entries.size > 0) {
|
|
126
|
+
try {
|
|
127
|
+
this.editor.changeViewZones((accessor) => {
|
|
128
|
+
for (const entry of this.entries.values()) accessor.removeZone(entry.zoneId);
|
|
129
|
+
});
|
|
130
|
+
} catch {
|
|
131
|
+
// Editor already disposed — its zones died with it.
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
this.entries.clear();
|
|
135
|
+
this.listeners.clear();
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
private emit(): void {
|
|
139
|
+
for (const cb of [...this.listeners]) cb();
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* `ordinal` orders zones sharing an afterLineNumber (monaco 0.50 supports it
|
|
145
|
+
* but the public IViewZone typing lags behind) — hence the structural write.
|
|
146
|
+
*/
|
|
147
|
+
function setOrdinal(zone: MonacoEditorNs.IViewZone, ordinal: number): void {
|
|
148
|
+
(zone as MonacoEditorNs.IViewZone & { ordinal?: number }).ordinal = ordinal;
|
|
149
|
+
}
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
|
2
|
+
import { createPortal } from 'react-dom';
|
|
3
|
+
import { useEditorContext } from '../EditorContext';
|
|
4
|
+
import { CodeContextZoneManager } from './CodeContextZoneManager';
|
|
5
|
+
import { CodeContextSectionView } from './CodeContextSectionView';
|
|
6
|
+
import type { ZoneSpec } from './diffContextSections';
|
|
7
|
+
import type { CodeContext, CodeContextSection } from './types';
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Bridges a host-supplied {@link CodeContext} onto the live Monaco editor:
|
|
11
|
+
* owns a {@link CodeContextZoneManager} per editor instance, reconciles zones
|
|
12
|
+
* when the context prop changes, and portals a `CodeContextSectionView` into
|
|
13
|
+
* each zone's dom node. Mounted by EditorShell in code mode; also exported
|
|
14
|
+
* for hosts composing a custom shell around `RawEditor`.
|
|
15
|
+
*/
|
|
16
|
+
export function CodeContextZones({ options }: { options: CodeContext }) {
|
|
17
|
+
const { monacoEditor } = useEditorContext();
|
|
18
|
+
const [manager, setManager] = useState<CodeContextZoneManager | null>(null);
|
|
19
|
+
// Bumped whenever the zone set changes so portals rebuild.
|
|
20
|
+
const [, setZonesVersion] = useState(0);
|
|
21
|
+
// Expansion state per section id: seeded from defaultExpanded the first
|
|
22
|
+
// time an id appears; the user's toggle wins afterwards.
|
|
23
|
+
const [expandedById, setExpandedById] = useState<Record<string, boolean>>({});
|
|
24
|
+
const seenIds = useRef(new Set<string>());
|
|
25
|
+
|
|
26
|
+
useEffect(() => {
|
|
27
|
+
if (!monacoEditor) return;
|
|
28
|
+
const mgr = new CodeContextZoneManager(monacoEditor);
|
|
29
|
+
const off = mgr.onDidChangeZones(() => setZonesVersion((v) => v + 1));
|
|
30
|
+
setManager(mgr);
|
|
31
|
+
return () => {
|
|
32
|
+
off();
|
|
33
|
+
mgr.dispose();
|
|
34
|
+
setManager(null);
|
|
35
|
+
};
|
|
36
|
+
}, [monacoEditor]);
|
|
37
|
+
|
|
38
|
+
const fileTop = options.fileTop;
|
|
39
|
+
const sections = options.sections;
|
|
40
|
+
|
|
41
|
+
// Resolved render list: fileTop pinned above line 1 at ordinal 0, then the
|
|
42
|
+
// host's sections in array order.
|
|
43
|
+
const resolved = useMemo(() => {
|
|
44
|
+
const out: Array<{ spec: ZoneSpec; section: Omit<CodeContextSection, 'line'> }> = [];
|
|
45
|
+
if (fileTop) {
|
|
46
|
+
out.push({ spec: { id: fileTop.id, line: 0, ordinal: 0 }, section: fileTop });
|
|
47
|
+
}
|
|
48
|
+
sections?.forEach((s, i) => {
|
|
49
|
+
out.push({ spec: { id: s.id, line: s.line, ordinal: i + 1 }, section: s });
|
|
50
|
+
});
|
|
51
|
+
return out;
|
|
52
|
+
}, [fileTop, sections]);
|
|
53
|
+
|
|
54
|
+
useEffect(() => {
|
|
55
|
+
if (!manager) return;
|
|
56
|
+
manager.sync(resolved.map((r) => r.spec));
|
|
57
|
+
// Seed expansion defaults for ids we haven't seen before (sections can
|
|
58
|
+
// arrive after mount).
|
|
59
|
+
setExpandedById((prev) => {
|
|
60
|
+
let next: Record<string, boolean> | null = null;
|
|
61
|
+
for (const { section } of resolved) {
|
|
62
|
+
if (seenIds.current.has(section.id)) continue;
|
|
63
|
+
seenIds.current.add(section.id);
|
|
64
|
+
if (section.defaultExpanded) {
|
|
65
|
+
next = next ?? { ...prev };
|
|
66
|
+
next[section.id] = true;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
return next ?? prev;
|
|
70
|
+
});
|
|
71
|
+
}, [manager, resolved]);
|
|
72
|
+
|
|
73
|
+
const onToggleSection = options.onToggleSection;
|
|
74
|
+
const handleToggle = useCallback(
|
|
75
|
+
(id: string) => {
|
|
76
|
+
setExpandedById((prev) => {
|
|
77
|
+
const expanded = !prev[id];
|
|
78
|
+
onToggleSection?.(id, expanded);
|
|
79
|
+
return { ...prev, [id]: expanded };
|
|
80
|
+
});
|
|
81
|
+
},
|
|
82
|
+
[onToggleSection],
|
|
83
|
+
);
|
|
84
|
+
|
|
85
|
+
const handleMeasure = useCallback(
|
|
86
|
+
(id: string, px: number) => manager?.setHeight(id, px),
|
|
87
|
+
[manager],
|
|
88
|
+
);
|
|
89
|
+
|
|
90
|
+
const handleRevealLine = useCallback(
|
|
91
|
+
(line: number) => {
|
|
92
|
+
monacoEditor?.revealLineInCenter(line);
|
|
93
|
+
monacoEditor?.setPosition({ lineNumber: line, column: 1 });
|
|
94
|
+
},
|
|
95
|
+
[monacoEditor],
|
|
96
|
+
);
|
|
97
|
+
|
|
98
|
+
if (!manager) return null;
|
|
99
|
+
return (
|
|
100
|
+
<>
|
|
101
|
+
{resolved.map(({ section }) => {
|
|
102
|
+
const domNode = manager.getDomNode(section.id);
|
|
103
|
+
if (!domNode) return null;
|
|
104
|
+
return createPortal(
|
|
105
|
+
<CodeContextSectionView
|
|
106
|
+
key={section.id}
|
|
107
|
+
section={section}
|
|
108
|
+
expanded={!!expandedById[section.id]}
|
|
109
|
+
onToggle={handleToggle}
|
|
110
|
+
linkSchemes={options.linkSchemes}
|
|
111
|
+
onLinkClick={options.onLinkClick}
|
|
112
|
+
onRevealLine={handleRevealLine}
|
|
113
|
+
onMeasure={handleMeasure}
|
|
114
|
+
/>,
|
|
115
|
+
domNode,
|
|
116
|
+
section.id,
|
|
117
|
+
);
|
|
118
|
+
})}
|
|
119
|
+
</>
|
|
120
|
+
);
|
|
121
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pure reconciler for context-section zones. Diffs the previous resolved spec
|
|
3
|
+
* list against the next by section id, so the zone layer can apply one
|
|
4
|
+
* changeViewZones batch: create `add`, delete `remove`, and re-anchor `move`
|
|
5
|
+
* (same id, different line or ordinal). Content-only changes are not the zone
|
|
6
|
+
* layer's business — React re-renders the portal and the resize observer
|
|
7
|
+
* corrects the height.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
export interface ZoneSpec {
|
|
11
|
+
id: string;
|
|
12
|
+
/** 1-based anchor line (0 = file-top, above line 1). */
|
|
13
|
+
line: number;
|
|
14
|
+
/** Stable order among zones sharing an anchor line. */
|
|
15
|
+
ordinal: number;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export interface ZoneDiff {
|
|
19
|
+
add: ZoneSpec[];
|
|
20
|
+
remove: string[];
|
|
21
|
+
move: ZoneSpec[];
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function diffContextSections(prev: ZoneSpec[], next: ZoneSpec[]): ZoneDiff {
|
|
25
|
+
const prevById = new Map(prev.map((z) => [z.id, z]));
|
|
26
|
+
const nextIds = new Set<string>();
|
|
27
|
+
const add: ZoneSpec[] = [];
|
|
28
|
+
const move: ZoneSpec[] = [];
|
|
29
|
+
for (const spec of next) {
|
|
30
|
+
if (nextIds.has(spec.id)) continue; // duplicate id — first occurrence wins
|
|
31
|
+
nextIds.add(spec.id);
|
|
32
|
+
const before = prevById.get(spec.id);
|
|
33
|
+
if (!before) add.push(spec);
|
|
34
|
+
else if (before.line !== spec.line || before.ordinal !== spec.ordinal) move.push(spec);
|
|
35
|
+
}
|
|
36
|
+
const remove = prev.filter((z) => !nextIds.has(z.id)).map((z) => z.id);
|
|
37
|
+
return { add, remove, move };
|
|
38
|
+
}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Host-supplied context sections rendered INSIDE the Monaco (raw/code)
|
|
3
|
+
* surface: collapsible markdown blurbs injected above anchor lines, plus an
|
|
4
|
+
* optional file-top summary. Squisq stays host-agnostic — anchors are plain
|
|
5
|
+
* line numbers, ids are opaque strings, links are intercepted via callback.
|
|
6
|
+
*
|
|
7
|
+
* Accessibility note: Monaco marks its view-zone layer `aria-hidden`, so
|
|
8
|
+
* sections are invisible to screen readers in v1.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* One host-supplied markdown blurb anchored above a line of the code buffer.
|
|
13
|
+
* Rendered as a compact one-line strip that expands in place to the full
|
|
14
|
+
* markdown body.
|
|
15
|
+
*/
|
|
16
|
+
export interface CodeContextSection {
|
|
17
|
+
/**
|
|
18
|
+
* Stable identity used to reconcile zones across prop updates — e.g. a
|
|
19
|
+
* symbol id like 'resolveImportEdges@60'. Zones are diffed by id: same id +
|
|
20
|
+
* new line moves the zone; same id + new markdown re-renders in place; a
|
|
21
|
+
* new id creates a new zone.
|
|
22
|
+
*/
|
|
23
|
+
id: string;
|
|
24
|
+
/**
|
|
25
|
+
* 1-based line the section renders ABOVE. Out-of-range values are clamped
|
|
26
|
+
* by Monaco. In editable buffers the zone rides Monaco's whitespace
|
|
27
|
+
* semantics — it shifts as lines are inserted/deleted above it and
|
|
28
|
+
* collapses onto the previous line if its anchor lines are deleted. Squisq
|
|
29
|
+
* never re-derives anchors from edits; the host re-supplies lines when it
|
|
30
|
+
* re-analyzes the file.
|
|
31
|
+
*/
|
|
32
|
+
line: number;
|
|
33
|
+
/**
|
|
34
|
+
* Compact markdown for the collapsed strip. Rendered on one line (block
|
|
35
|
+
* structure flattened, overflow ellipsized). Links work here too and go
|
|
36
|
+
* through `onLinkClick`.
|
|
37
|
+
*/
|
|
38
|
+
summaryMarkdown: string;
|
|
39
|
+
/**
|
|
40
|
+
* Full markdown body shown when expanded. Omit while still loading — the
|
|
41
|
+
* expanded view shows a muted loading row and fills in when a later prop
|
|
42
|
+
* update supplies it.
|
|
43
|
+
*/
|
|
44
|
+
markdown?: string;
|
|
45
|
+
/** Start expanded. The user's toggle wins after first interaction. Default false. */
|
|
46
|
+
defaultExpanded?: boolean;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** The full context dictionary passed to `EditorShell.codeContext`. */
|
|
50
|
+
export interface CodeContext {
|
|
51
|
+
/**
|
|
52
|
+
* Section pinned above line 1 (file summary). Rendered before any line-1
|
|
53
|
+
* `sections` entry. `line` is implicit.
|
|
54
|
+
*/
|
|
55
|
+
fileTop?: Omit<CodeContextSection, 'line'>;
|
|
56
|
+
/** Line-anchored sections. Array order is preserved for equal lines. */
|
|
57
|
+
sections?: CodeContextSection[];
|
|
58
|
+
/**
|
|
59
|
+
* Extra URI schemes section links may use (e.g. `['gezel-nav']`).
|
|
60
|
+
* http/https/mailto/tel are always allowed; executable schemes
|
|
61
|
+
* (javascript:, data:) are never allowed regardless.
|
|
62
|
+
*/
|
|
63
|
+
linkSchemes?: readonly string[];
|
|
64
|
+
/**
|
|
65
|
+
* Intercepts link clicks inside sections, receiving the href exactly as
|
|
66
|
+
* authored in the markdown. Return `false` to let the browser's default
|
|
67
|
+
* navigation proceed; any other return (or void) suppresses it. Fragment
|
|
68
|
+
* links of the form `#L<digits>` are handled natively by squisq (reveal
|
|
69
|
+
* that line in the editor) and never reach this callback. When omitted:
|
|
70
|
+
* http(s)/mailto links open normally, custom-scheme links do nothing.
|
|
71
|
+
*/
|
|
72
|
+
onLinkClick?: (href: string, meta: { sectionId: string }) => boolean | undefined;
|
|
73
|
+
/** Notified on expand/collapse — lets hosts lazy-load bodies on first expand. */
|
|
74
|
+
onToggleSection?: (sectionId: string, expanded: boolean) => void;
|
|
75
|
+
}
|