Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
175 changes: 175 additions & 0 deletions demo/tests/visual-tests/EditorPopupSelection.helpers.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,175 @@
import {useLayoutEffect, useRef, useState} from 'react';

import {MarkdownEditorView, useMarkdownEditor} from '@gravity-ui/markdown-editor';
import {NodeSelection, Plugin, TextSelection} from '@gravity-ui/markdown-editor/pm/state';
import type {EditorView} from '@gravity-ui/markdown-editor/pm/view';
import {MobileProvider, ThemeProvider, Toaster, ToasterProvider} from '@gravity-ui/uikit';
import * as ReactDOM from 'react-dom';

type Selection = {type: string; from: number; to: number};
type Probe = {
view?: EditorView;
depth: number;
maxDepth: number;
selections: Selection[];
destroyed: boolean;
updatesAfterDestroy: number;
settled: boolean;
publish: () => void;
};

const markup = '{% note info "Note" %}\n\nText in note\n\n{% endnote %}';
const toaster = new Toaster();

function SelectionEditor(props: {probe: Probe; startsWithNote: boolean}) {
const {probe, startsWithNote} = props;
const editor = useMarkdownEditor({
initial: {
markup: startsWithNote ? markup : `Before\n\n${markup}`,
mode: 'wysiwyg',
toolbarVisible: false,
},
wysiwygConfig: {
extensions: (builder) => {
builder.addPlugin(
() =>
new Plugin({
view(editorView) {
const view = editorView;
probe.view = view;
const updateState = view.updateState;
// Instrument this instance only, including the complete plugin update cycle.
view.updateState = function (state) {
probe.depth += 1;
probe.maxDepth = Math.max(probe.maxDepth, probe.depth);
if (probe.destroyed) probe.updatesAfterDestroy += 1;
probe.selections.push({
type:
state.selection instanceof NodeSelection
? 'node'
: 'text',
from: state.selection.from,
to: state.selection.to,
});
try {
return updateState.call(this, state);
} finally {
probe.depth -= 1;
probe.publish();
}
};
return {
destroy() {
probe.destroyed = true;
probe.publish();
},
};
},
}),
builder.Priority.Highest,
);
},
},
});

return <MarkdownEditorView editor={editor} settingsVisible={false} stickyToolbar={false} />;
}

function SelectionApp({startsWithNote}: {startsWithNote: boolean}) {
const output = useRef<HTMLOutputElement>(null);
const [mounted, setMounted] = useState(true);
const probe = useRef<Probe>({
depth: 0,
maxDepth: 0,
selections: [],
destroyed: false,
updatesAfterDestroy: 0,
settled: false,
publish() {
if (output.current) {
const {view: _view, publish: _publish, ...data} = probe;
output.current.textContent = JSON.stringify(data);
}
},
}).current;

function selectThen(action: 'move' | 'destroy') {
const view = probe.view;
if (!view) throw new Error('Editor view is missing');
let notePos: number | undefined;
view.state.doc.descendants((node, pos) => {
if (node.type.name === 'yfm_note') notePos = pos;
});
if (notePos === undefined) throw new Error('Note is missing');
view.focus();
probe.selections = [];
probe.maxDepth = 0;
view.dispatch(view.state.tr.setSelection(NodeSelection.create(view.state.doc, notePos)));
// Both actions happen before the deferred selection normalization can run.
if (action === 'move') {
view.dispatch(view.state.tr.setSelection(TextSelection.create(view.state.doc, 1)));
} else {
ReactDOM.flushSync(() => setMounted(false));
}
queueMicrotask(() => {
probe.settled = true;
probe.publish();
});
}

return (
<ThemeProvider>
<MobileProvider>
<ToasterProvider toaster={toaster}>
<div style={{marginTop: 120, width: 850}}>
<output ref={output} data-qa="selection-probe" style={{display: 'none'}} />
{mounted && (
<SelectionEditor probe={probe} startsWithNote={startsWithNote} />
)}
<button
onMouseDown={(event) => event.preventDefault()}
onClick={() => {
probe.selections = [];
probe.maxDepth = 0;
probe.publish();
}}
>
Reset probe
</button>
<button
onMouseDown={(event) => event.preventDefault()}
onClick={() => selectThen('move')}
>
Select note then paragraph
</button>
<button
onMouseDown={(event) => event.preventDefault()}
onClick={() => selectThen('destroy')}
>
Select note then destroy
</button>
</div>
</ToasterProvider>
</MobileProvider>
</ThemeProvider>
);
}

export function EditorPopupSelection({
legacy,
startsWithNote = false,
}: {
legacy: boolean;
startsWithNote?: boolean;
}) {
const target = useRef<HTMLDivElement>(null);
useLayoutEffect(() => {
if (!legacy || !target.current) return undefined;
const container = target.current;
ReactDOM.render(<SelectionApp startsWithNote={startsWithNote} />, container);
return () => {
ReactDOM.unmountComponentAtNode(container);
};
}, [legacy, startsWithNote]);
return legacy ? <div ref={target} /> : <SelectionApp startsWithNote={startsWithNote} />;
}
98 changes: 98 additions & 0 deletions demo/tests/visual-tests/EditorPopupSelection.visual.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
import {expect, test} from 'playwright/core';

import {EditorPopupSelection} from './EditorPopupSelection.helpers';

for (const legacy of [false, true]) {
test.describe(`Editor popup selection (${legacy ? 'legacy root' : 'createRoot'})`, () => {
for (const startsWithNote of [false, true]) {
test(`preserves selection behavior without nested updates (${startsWithNote ? 'menu already open' : 'from paragraph'})`, async ({
mount,
page,
}) => {
const errors: string[] = [];
page.on('pageerror', (error) => errors.push(error.message));
await mount(
<EditorPopupSelection legacy={legacy} startsWithNote={startsWithNote} />,
);
const editor = page.locator('.ProseMirror');
const note = editor.locator('.yfm-note');
const menu = page.getByTestId('g-md-toolbar-yfm-note');
if (startsWithNote) {
await note.getByText('Text in note', {exact: true}).click();
await expect(menu).toBeVisible();
} else {
await editor.getByText('Before', {exact: true}).click();
await expect(menu).toBeHidden();
}
await page.getByRole('button', {name: 'Reset probe'}).dispatchEvent('click');
await note.click({position: {x: 10, y: 10}});
await expect(menu).toBeVisible();
await expect
.poll(async () => {
const data = JSON.parse(
await page.getByTestId('selection-probe').innerText(),
);
const node = data.selections.find(
(selection: {type: string}) => selection.type === 'node',
);
const last = data.selections.at(-1);
return Boolean(
node &&
(startsWithNote
? last?.type === 'node' &&
last.from === node.from &&
last.to === node.to
: last?.type === 'text' &&
last.from > node.from &&
last.to < node.to &&
last.from < last.to),
);
})
.toBe(true);
const data = JSON.parse(await page.getByTestId('selection-probe').innerText());
expect(data.maxDepth).toBe(1);
if (startsWithNote) {
// Keeping the same open popup must not normalize a later block selection.
expect(data.selections.at(-1).type).toBe('node');
await expect(note).toHaveClass(/ProseMirror-selectednode/);
}
await expect(editor).toBeFocused();
expect(await page.evaluate(() => document.getSelection()?.toString())).toContain(
'Text in note',
);
expect(errors).toEqual([]);
});
}

for (const action of ['paragraph', 'destroy'] as const) {
test(`discards deferred work after ${action === 'paragraph' ? 'selection changes' : 'destroy'}`, async ({
mount,
page,
}) => {
const errors: string[] = [];
page.on('pageerror', (error) => errors.push(error.message));
await mount(<EditorPopupSelection legacy={legacy} />);
await page.locator('.ProseMirror').getByText('Before', {exact: true}).click();
await page.getByRole('button', {name: 'Reset probe'}).dispatchEvent('click');
await page.getByRole('button', {name: `Select note then ${action}`}).click();
const output = page.getByTestId('selection-probe');
await expect
.poll(async () => JSON.parse(await output.innerText()).settled)
.toBe(true);
const data = JSON.parse(await output.innerText());
expect(data.selections[0].type).toBe('node');
expect(data.maxDepth).toBe(1);
expect(data.updatesAfterDestroy).toBe(0);
if (action === 'paragraph') {
expect(data.selections).toHaveLength(2);
expect(data.selections[1]).toEqual({type: 'text', from: 1, to: 1});
await expect(page.getByTestId('g-md-toolbar-yfm-note')).toBeHidden();
} else {
expect(data.destroyed).toBe(true);
await expect(page.locator('.ProseMirror')).toHaveCount(0);
}
expect(errors).toEqual([]);
});
}
});
}
20 changes: 20 additions & 0 deletions demo/tests/visual-tests/EditorTooltips.helpers.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import {MarkdownEditorView, useMarkdownEditor} from '@gravity-ui/markdown-editor';
import {Button} from '@gravity-ui/uikit';

const defaultMarkup =
'{% note info "Note" %}\n\n#|\n|| Description |\n\n```js\nSelect this text inside the code block\n```\n\n||\n|| | Another table cell ||\n|#\n\n{% endnote %}';

export function EditorTooltips({markup = defaultMarkup}: {markup?: string}) {
const editor = useMarkdownEditor({
initial: {markup, mode: 'wysiwyg', toolbarVisible: false},
});

return (
<div style={{marginTop: 120, width: 850}}>
<div style={{overflow: 'clip'}}>
<MarkdownEditorView editor={editor} settingsVisible={false} stickyToolbar={false} />
</div>
<Button>After editor</Button>
</div>
);
}
Loading
Loading