@astryxdesign/richtext 0.7.5 → 0.7.6-canary.0bd3b37

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.
Files changed (44) hide show
  1. package/package.json +19 -6
  2. package/src/CodeBlockHeaderPlugin.test.tsx +0 -100
  3. package/src/CodeSyntaxPlugin.test.tsx +0 -60
  4. package/src/MarkdownExtensionsPlugin.test.tsx +0 -279
  5. package/src/RichTextEditor.test.tsx +0 -2258
  6. package/src/TableColumnFloorPlugin.test.tsx +0 -49
  7. package/src/TableScrollRegionPlugin.test.tsx +0 -138
  8. package/src/__tests__/MarkdownParitySandbox.a11y.chromium.spec.ts +0 -2092
  9. package/src/__tests__/MarkdownPlugins.a11y.chromium.spec.ts +0 -483
  10. package/src/__tests__/MarkdownPluginsImportExport.a11y.chromium.spec.ts +0 -152
  11. package/src/__tests__/Playground.a11y.chromium.spec.ts +0 -755
  12. package/src/__tests__/RichTextCodeLanguages.a11y.chromium.spec.ts +0 -61
  13. package/src/__tests__/RichTextEditorToolbar.a11y.chromium.spec.ts +0 -113
  14. package/src/__tests__/RichTextView.a11y.chromium.spec.ts +0 -101
  15. package/src/__tests__/TableCellSelection.a11y.chromium.spec.ts +0 -380
  16. package/src/markdownAngleCodeSpans.test.ts +0 -92
  17. package/src/markdownAngleDestinations.test.ts +0 -332
  18. package/src/markdownCharacterReferences.test.ts +0 -202
  19. package/src/markdownCodeFence.test.ts +0 -195
  20. package/src/markdownCodeSpans.test.ts +0 -399
  21. package/src/markdownEscapes.test.ts +0 -234
  22. package/src/markdownExtensionSelection.test.ts +0 -102
  23. package/src/markdownExtensions.test.ts +0 -765
  24. package/src/markdownHeadingMarkers.test.ts +0 -132
  25. package/src/markdownIndentedFences.test.ts +0 -43
  26. package/src/markdownIndentedTables.test.ts +0 -43
  27. package/src/markdownListContinuation.test.ts +0 -34
  28. package/src/markdownListIndentation.test.ts +0 -235
  29. package/src/markdownListThematicBreak.test.ts +0 -31
  30. package/src/markdownListThematicBreakInside.test.ts +0 -64
  31. package/src/markdownOpenFence.test.ts +0 -35
  32. package/src/markdownOrderedList.test.ts +0 -62
  33. package/src/markdownQuoteMarkers.test.ts +0 -206
  34. package/src/markdownRefusedLinks.test.tsx +0 -193
  35. package/src/markdownSource.test.tsx +0 -750
  36. package/src/markdownSpaceRuns.test.ts +0 -204
  37. package/src/markdownSpacedBlockStarts.test.ts +0 -96
  38. package/src/markdownTabRuns.test.ts +0 -75
  39. package/src/markdownTable.test.tsx +0 -214
  40. package/src/markdownTableLinks.test.ts +0 -69
  41. package/src/markdownTaskList.test.tsx +0 -445
  42. package/src/markdownThematicBreak.test.tsx +0 -185
  43. package/src/publicSurface.test.ts +0 -42
  44. package/src/textSemantics.test.tsx +0 -368
@@ -1,61 +0,0 @@
1
- // Copyright (c) Meta Platforms, Inc. and affiliates.
2
-
3
- /**
4
- * @file RichTextCodeLanguages.a11y.chromium.spec.ts
5
- * @input The built Storybook's "Code language modules" story: one Thrift
6
- * fence with `codeLanguages={[thrift]}` and the same fence without it
7
- * @output CodeBlock FR13 for RichText in a real browser: CodeSyntaxPlugin
8
- * paints a listed value and labels with its name; unlisted stays plain
9
- * @position spec:AST-061 read/edit parity, CodeBlock FR13 evidence
10
- */
11
-
12
- import {expect, test, type Page} from '@playwright/test';
13
- import {
14
- DEFAULT_STORYBOOK_DIR,
15
- serveStorybook,
16
- type StaticServer,
17
- } from '@astryxdesign/a11y-spec/storybook';
18
-
19
- let storybook: StaticServer;
20
- test.beforeAll(async () => {
21
- storybook = await serveStorybook(
22
- process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR,
23
- );
24
- });
25
- test.afterAll(async () => {
26
- await storybook?.close();
27
- });
28
-
29
- /** The keyword-highlighted text inside the element with `testId`. */
30
- async function keywordsIn(page: Page, testId: string) {
31
- return page.evaluate(id => {
32
- const root = document.querySelector(`[data-testid="${id}"]`);
33
- const highlight = CSS.highlights.get('astryx-keyword');
34
- if (!root || !highlight) {
35
- return [];
36
- }
37
- return Array.from(highlight as unknown as Iterable<Range>)
38
- .filter(range => root.contains(range.startContainer))
39
- .map(range => range.toString());
40
- }, testId);
41
- }
42
-
43
- test('RichText code blocks colour and label a listed language value', async ({
44
- page,
45
- }) => {
46
- await page.goto(
47
- `${storybook.origin}/iframe.html?id=richtext-richtexteditor--code-language-modules&viewMode=story`,
48
- );
49
- await expect(page.getByText('struct User {').first()).toBeVisible();
50
- await expect
51
- .poll(async () => keywordsIn(page, 'listed'))
52
- .toEqual(expect.arrayContaining(['struct', 'required', 'string']));
53
- expect(await keywordsIn(page, 'unlisted')).toEqual([]);
54
- await expect(
55
- page.locator('[data-testid="listed"] [data-richtext-code-header]'),
56
- ).toContainText('thrift');
57
- // An `objc` fence matched by objectiveC is labelled with the value's name.
58
- await expect(
59
- page.locator('[data-testid="listed-renamed"] [data-richtext-code-header]'),
60
- ).toContainText('objective-c');
61
- });
@@ -1,113 +0,0 @@
1
- // Copyright (c) Meta Platforms, Inc. and affiliates.
2
- // @pr-a11y scope core/Markdown richtext/* ^(apps/storybook/stories/RichTextEditor\.(markdownParity|stories)|packages/richtext/src/__tests__/(MarkdownParitySandbox|RichTextView|RichTextEditorToolbar)) ^packages/richtext/src/
3
-
4
- /**
5
- * @file RichTextEditorToolbar.a11y.chromium.spec.ts
6
- * @input The built Storybook's "With toolbar" RichTextEditor story.
7
- * @output Real-browser proof that the toolbar's action row scrolls at phone
8
- * widths instead of squeezing a control: the block-format selector keeps its
9
- * whole label, no control overlaps its neighbour, and every control keeps a
10
- * 24px target.
11
- *
12
- * Run after building Storybook:
13
- * pnpm storybook:build
14
- * pnpm exec playwright test packages/richtext --project chromium
15
- */
16
-
17
- import AxeBuilder from '@axe-core/playwright';
18
- import {expect, test} from '@playwright/test';
19
- import {
20
- DEFAULT_STORYBOOK_DIR,
21
- serveStorybook,
22
- type StaticServer,
23
- } from '@astryxdesign/a11y-spec/storybook';
24
-
25
- const STORYBOOK_DIR = process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR;
26
- const STORY = 'richtext-richtexteditor--with-toolbar';
27
-
28
- let storybook: StaticServer;
29
-
30
- test.beforeAll(async () => {
31
- storybook = await serveStorybook(STORYBOOK_DIR);
32
- });
33
-
34
- test.afterAll(async () => {
35
- await storybook?.close();
36
- });
37
-
38
- for (const width of [320, 390, 1240]) {
39
- for (const direction of ['ltr', 'rtl'] as const) {
40
- test(`the action row scrolls instead of squeezing a control (${width}px, ${direction})`, async ({
41
- page,
42
- }) => {
43
- await page.setViewportSize({width, height: 700});
44
- await page.goto(
45
- `${storybook.origin}/iframe.html?id=${STORY}&viewMode=story&globals=astryxTheme:neutral;colorMode:light;direction:${direction}`,
46
- {waitUntil: 'load'},
47
- );
48
- const toolbar = page.getByRole('toolbar', {name: 'Text formatting'});
49
- await expect(toolbar).toBeVisible();
50
-
51
- const layout = await toolbar.evaluate(root => {
52
- const row = root.querySelector('[role="group"]') as HTMLElement;
53
- const combobox = root.querySelector('[role="combobox"]') as HTMLElement;
54
- const label = [...combobox.querySelectorAll('span')].find(
55
- span => span.textContent === 'Paragraph',
56
- );
57
- const controls = [...row.children]
58
- .filter(child => child.getAttribute('role') !== 'separator')
59
- .map(child => child.getBoundingClientRect())
60
- .filter(box => box.width > 0)
61
- .sort((a, b) => a.left - b.left);
62
- let overlap = 0;
63
- for (let index = 1; index < controls.length; index++) {
64
- overlap = Math.max(
65
- overlap,
66
- controls[index - 1].right - controls[index].left,
67
- );
68
- }
69
- return {
70
- labelWidth: label?.getBoundingClientRect().width ?? 0,
71
- labelNeeds: label?.scrollWidth ?? -1,
72
- overlap,
73
- rowOverflow: row.scrollWidth - row.clientWidth,
74
- rowRoom: row.clientWidth,
75
- pageOverflow:
76
- document.documentElement.scrollWidth -
77
- document.documentElement.clientWidth,
78
- shortest: Math.min(...controls.map(box => box.height)),
79
- };
80
- });
81
-
82
- expect(layout.labelNeeds, 'label found').toBeGreaterThan(0);
83
- expect(
84
- layout.labelWidth,
85
- 'the selector shows its whole label',
86
- ).toBeGreaterThanOrEqual(layout.labelNeeds - 0.5);
87
- expect(
88
- layout.overlap,
89
- 'no control overlaps the next',
90
- ).toBeLessThanOrEqual(0.5);
91
- expect(
92
- layout.shortest,
93
- 'every control is a 24px target',
94
- ).toBeGreaterThanOrEqual(24);
95
- expect(
96
- layout.pageOverflow,
97
- 'the page never scrolls sideways',
98
- ).toBeLessThanOrEqual(0);
99
- if (width < 400) {
100
- expect(
101
- layout.rowOverflow,
102
- 'at phone width the row scrolls',
103
- ).toBeGreaterThan(0);
104
- }
105
-
106
- const targets = await new AxeBuilder({page})
107
- .include('[role="toolbar"]')
108
- .withRules(['target-size'])
109
- .analyze();
110
- expect(targets.violations).toEqual([]);
111
- });
112
- }
113
- }
@@ -1,101 +0,0 @@
1
- // Copyright (c) Meta Platforms, Inc. and affiliates.
2
- // @pr-a11y scope core/Markdown richtext/* ^(apps/storybook/stories/RichTextEditor\.(markdownParity|stories)|packages/richtext/src/__tests__/(MarkdownParitySandbox|RichTextView|RichTextEditorToolbar)) ^packages/richtext/src/
3
-
4
- /**
5
- * @file RichTextView.a11y.chromium.spec.ts
6
- * @input The built Storybook's "Markdown serializers" story, which renders one
7
- * document in a RichTextEditor and in a RichTextView.
8
- * @output Real-browser proof for spec:AST-061 FR2 on the view: every block's
9
- * text takes the theme's body type, not the host page's font, so the view and
10
- * the editor draw the same document the same size.
11
- *
12
- * Run after building Storybook:
13
- * pnpm storybook:build
14
- * pnpm exec playwright test packages/richtext --project chromium
15
- */
16
-
17
- import {expect, test} from '@playwright/test';
18
- import {
19
- DEFAULT_STORYBOOK_DIR,
20
- serveStorybook,
21
- type StaticServer,
22
- } from '@astryxdesign/a11y-spec/storybook';
23
-
24
- const STORYBOOK_DIR = process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR;
25
- const STORY = 'richtext-richtexteditor--markdown-serializers';
26
- const DOCUMENT = [
27
- 'Paragraph text',
28
- '',
29
- '- List item',
30
- ' - Nested item',
31
- '',
32
- '> Quoted text',
33
- '',
34
- '| Cell | Other |',
35
- '| --- | --- |',
36
- '| Body | Cell |',
37
- '',
38
- ].join('\n');
39
-
40
- let storybook: StaticServer;
41
-
42
- test.beforeAll(async () => {
43
- storybook = await serveStorybook(STORYBOOK_DIR);
44
- });
45
-
46
- test.afterAll(async () => {
47
- await storybook?.close();
48
- });
49
-
50
- for (const colorMode of ['light', 'dark'] as const) {
51
- test(`the view draws every block in the body type the editor uses (${colorMode})`, async ({
52
- page,
53
- }) => {
54
- // The story host's own font is 16px/24px, so inheriting it shows.
55
- await page.setViewportSize({width: 1240, height: 1000});
56
- await page.goto(
57
- `${storybook.origin}/iframe.html?id=${STORY}&viewMode=story&globals=astryxTheme:neutral;colorMode:${colorMode};direction:ltr`,
58
- {waitUntil: 'load'},
59
- );
60
- await page.locator('textarea').fill(DOCUMENT);
61
- const surfaces = page.locator('[data-lexical-editor]');
62
- await expect(surfaces).toHaveCount(2);
63
- await expect(surfaces.nth(1).locator('td, th')).toHaveCount(4);
64
-
65
- const read = (index: number) =>
66
- surfaces.nth(index).evaluate(root => {
67
- const textOf = (selector: string) => {
68
- const block = root.querySelector(selector);
69
- // The innermost element holding the block's words.
70
- let leaf: Element | null = block;
71
- while (leaf?.firstElementChild != null) {
72
- leaf = leaf.firstElementChild;
73
- }
74
- if (leaf == null) {
75
- return null;
76
- }
77
- const style = getComputedStyle(leaf);
78
- return `${style.fontFamily} ${style.fontSize}/${style.lineHeight} | ${style.color}`;
79
- };
80
- return {
81
- paragraph: textOf('p'),
82
- listItem: textOf('li'),
83
- quote: textOf('blockquote'),
84
- cell: textOf('td'),
85
- };
86
- });
87
-
88
- const editor = await read(0);
89
- const view = await read(1);
90
- expect(editor.paragraph).not.toBeNull();
91
- // Every block in the view matches the same block in the editor.
92
- expect(view).toEqual(editor);
93
- // And it is the body type, not the page's: every block shares the
94
- // paragraph's family, size, and leading. (A quote's color differs by
95
- // design.)
96
- const typeOf = (block: string | null) => block?.split(' | ')[0];
97
- for (const block of [view.listItem, view.quote, view.cell]) {
98
- expect(typeOf(block)).toBe(typeOf(view.paragraph));
99
- }
100
- });
101
- }
@@ -1,380 +0,0 @@
1
- // Copyright (c) Meta Platforms, Inc. and affiliates.
2
- // @pr-a11y release-only
3
-
4
- /**
5
- * @file TableCellSelection.a11y.chromium.spec.ts
6
- * @input The built Storybook's Lab/RichTextEditor "Playground" story, whose
7
- * editor takes a table from the toolbar's insert control.
8
- * @output Real-browser proof that a table selection is visible: the cells a
9
- * drag covers are marked and the cells it does not are not, the mark clears
10
- * the surface it is drawn on in every shipped theme and mode, it costs the
11
- * cell's own text no contrast, it marks exactly the cells the next keystroke
12
- * replaces, and it goes when the selection goes.
13
- *
14
- * A table selection is made of DOM the engine owns and a class name the theme
15
- * supplies. Nothing in a unit test can see whether that class was ever named:
16
- * `addClassNamesToElement(element, theme.tableCellSelected)` is a silent
17
- * no-op when the slot is undefined, which is how cells in a selection came to
18
- * be painted exactly like cells outside one. Only a real engine, dragging
19
- * across real cells, can tell the two apart.
20
- *
21
- * The theme sweep is not ceremony. A mark is only visible against the surface
22
- * it lands on, and a token that clears the surface under one theme can equal
23
- * it under another: `--color-accent-muted` resolves to the editor field's own
24
- * colour under Neutral dark, where a background wash would be invisible while
25
- * every computed-value assertion still passed.
26
- *
27
- * Run after building Storybook:
28
- * pnpm storybook:build
29
- * pnpm exec playwright test packages/richtext --project chromium
30
- */
31
-
32
- import {expect, test, type Page} from '@playwright/test';
33
- import {
34
- DEFAULT_STORYBOOK_DIR,
35
- serveStorybook,
36
- type StaticServer,
37
- } from '@astryxdesign/a11y-spec/storybook';
38
-
39
- const STORYBOOK_DIR = process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR;
40
- const STORY = 'richtext-richtexteditor--playground';
41
- const EDITOR = '[data-playground-editor] [role="textbox"]';
42
- const CELLS = `${EDITOR} table th, ${EDITOR} table td`;
43
-
44
- /** Every shipped theme, in both modes: a mark has to land on all of them. */
45
- const THEMES = [
46
- 'neutral',
47
- 'stone',
48
- 'butter',
49
- 'chocolate',
50
- 'gothic',
51
- 'matcha',
52
- 'y2k',
53
- ] as const;
54
- const MODES = ['light', 'dark'] as const;
55
-
56
- /**
57
- * WCAG 1.4.11's bar for a non-text indicator. The mark has to clear the
58
- * surface it is drawn on by at least this much to be a mark at all.
59
- */
60
- const NON_TEXT_CONTRAST = 3;
61
-
62
- let storybook: StaticServer;
63
-
64
- test.beforeAll(async () => {
65
- storybook = await serveStorybook(STORYBOOK_DIR);
66
- });
67
-
68
- test.afterAll(async () => {
69
- await storybook?.close();
70
- });
71
-
72
- /**
73
- * How a cell is marked, and what its text has to read against: enough to say
74
- * whether two cells look different, without naming the treatment. A future
75
- * mark that is a wash rather than a ring is described here just as well.
76
- */
77
- interface CellPaint {
78
- readonly outline: string;
79
- readonly background: string;
80
- /** Contrast of the cell's own text against its own background. */
81
- readonly textContrast: number;
82
- }
83
-
84
- /** Opens the story under one theme and mode, with a filled 3×3 table. */
85
- async function openWithTable(
86
- page: Page,
87
- theme: string = 'neutral',
88
- mode: string = 'light',
89
- ): Promise<string[]> {
90
- const errors: string[] = [];
91
- page.on('pageerror', error => errors.push(String(error)));
92
- page.on('console', message => {
93
- if (message.type() === 'error' && !message.text().includes('404')) {
94
- errors.push(message.text());
95
- }
96
- });
97
- await page.setViewportSize({width: 1440, height: 900});
98
- await page.goto(
99
- `${storybook.origin}/iframe.html?id=${STORY}&viewMode=story&globals=astryxTheme:${theme};colorMode:${mode};direction:ltr`,
100
- {waitUntil: 'load'},
101
- );
102
- await expect(page.locator(EDITOR)).toBeVisible();
103
-
104
- // A table of its own, away from the seeded document, so the cell indices
105
- // below mean what they say.
106
- await page.getByRole('button', {name: 'Clear', exact: true}).click();
107
- await page.locator(EDITOR).click();
108
- await page.getByRole('button', {name: 'Table', exact: true}).click();
109
- await expect(page.locator(CELLS)).toHaveCount(9);
110
- for (const [index, word] of [
111
- [0, 'Area'],
112
- [1, 'Owner'],
113
- [3, 'Sync'],
114
- [4, 'Platform'],
115
- ] as const) {
116
- await page.locator(CELLS).nth(index).click();
117
- await page.keyboard.type(word);
118
- }
119
- return errors;
120
- }
121
-
122
- /**
123
- * Reads each cell's mark and its text contrast, compositing translucent
124
- * colours over the first opaque surface behind the table so a measurement is
125
- * of what a person actually sees, not of a token's nominal value.
126
- */
127
- const paints = (page: Page): Promise<CellPaint[]> =>
128
- page.$$eval(CELLS, cells => {
129
- const parse = (value: string): number[] => {
130
- const parts = (value.match(/[\d.]+/g) ?? []).map(Number);
131
- return parts.length === 3 ? [...parts, 1] : parts;
132
- };
133
- const over = (fg: number[], bg: number[]): number[] =>
134
- [0, 1, 2].map(i => fg[i] * fg[3] + bg[i] * (1 - fg[3]));
135
- const channel = (c: number): number => {
136
- const v = c / 255;
137
- return v <= 0.03928 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4;
138
- };
139
- const luminance = (c: number[]): number =>
140
- 0.2126 * channel(c[0]) + 0.7152 * channel(c[1]) + 0.0722 * channel(c[2]);
141
- const contrast = (a: number[], b: number[]): number => {
142
- const [hi, lo] = [luminance(a), luminance(b)].sort((x, y) => y - x);
143
- return (hi + 0.05) / (lo + 0.05);
144
- };
145
- /** The first opaque background behind an element. */
146
- const backdrop = (el: Element): number[] => {
147
- let node: Element | null = el.parentElement;
148
- while (node != null) {
149
- const parsed = parse(getComputedStyle(node).backgroundColor);
150
- if (parsed[3] === 1) {
151
- return parsed;
152
- }
153
- node = node.parentElement;
154
- }
155
- return [255, 255, 255, 1];
156
- };
157
- return cells.map(cell => {
158
- const style = getComputedStyle(cell);
159
- const behind = backdrop(cell);
160
- const own = over(parse(style.backgroundColor), behind);
161
- return {
162
- outline: `${style.outlineStyle} ${style.outlineWidth} ${style.outlineColor}`,
163
- background: style.backgroundColor,
164
- textContrast: contrast(parse(style.color), own),
165
- };
166
- });
167
- });
168
-
169
- /** The mark's own contrast against the surface the table sits on. */
170
- const markContrast = (page: Page): Promise<number> =>
171
- page.$$eval(CELLS, cells => {
172
- const parse = (value: string): number[] => {
173
- const parts = (value.match(/[\d.]+/g) ?? []).map(Number);
174
- return parts.length === 3 ? [...parts, 1] : parts;
175
- };
176
- const over = (fg: number[], bg: number[]): number[] =>
177
- [0, 1, 2].map(i => fg[i] * fg[3] + bg[i] * (1 - fg[3]));
178
- const channel = (c: number): number => {
179
- const v = c / 255;
180
- return v <= 0.03928 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4;
181
- };
182
- const luminance = (c: number[]): number =>
183
- 0.2126 * channel(c[0]) + 0.7152 * channel(c[1]) + 0.0722 * channel(c[2]);
184
- const contrast = (a: number[], b: number[]): number => {
185
- const [hi, lo] = [luminance(a), luminance(b)].sort((x, y) => y - x);
186
- return (hi + 0.05) / (lo + 0.05);
187
- };
188
- const backdrop = (el: Element): number[] => {
189
- let node: Element | null = el.parentElement;
190
- while (node != null) {
191
- const parsed = parse(getComputedStyle(node).backgroundColor);
192
- if (parsed[3] === 1) {
193
- return parsed;
194
- }
195
- node = node.parentElement;
196
- }
197
- return [255, 255, 255, 1];
198
- };
199
- const selected = cells[0];
200
- const style = getComputedStyle(selected);
201
- const behind = backdrop(selected);
202
- // Whichever way the cell is marked, measure that mark against the
203
- // surface: the ring if it is ringed, the background if it is washed.
204
- const mark =
205
- style.outlineStyle !== 'none' && parseFloat(style.outlineWidth) > 0
206
- ? parse(style.outlineColor)
207
- : parse(style.backgroundColor);
208
- return contrast(over(mark, behind), behind);
209
- });
210
-
211
- const texts = (page: Page): Promise<string[]> =>
212
- page.$$eval(CELLS, cells =>
213
- cells.map(cell => cell.textContent?.trim() ?? ''),
214
- );
215
-
216
- /** Drags from one cell to another, the gesture that selects a cell range. */
217
- async function dragAcross(page: Page, from: number, to: number) {
218
- const start = await page.locator(CELLS).nth(from).boundingBox();
219
- const end = await page.locator(CELLS).nth(to).boundingBox();
220
- if (start == null || end == null) {
221
- throw new Error('a cell has no box');
222
- }
223
- await page.mouse.move(start.x + 15, start.y + start.height / 2);
224
- await page.mouse.down();
225
- // Past the anchor cell's edge first: the engine starts highlighting once
226
- // the pointer leaves the cell it went down in.
227
- await page.mouse.move(start.x + 40, start.y + start.height / 2, {steps: 4});
228
- await page.mouse.move(end.x + end.width / 2, end.y + end.height / 2, {
229
- steps: 20,
230
- });
231
- await page.mouse.up();
232
- }
233
-
234
- /** Did the selection change how this cell looks? */
235
- const looksDifferent = (before: CellPaint, after: CellPaint): boolean =>
236
- before.outline !== after.outline || before.background !== after.background;
237
-
238
- test('the cells a selection covers are marked, and the rest are not', async ({
239
- page,
240
- }) => {
241
- const errors = await openWithTable(page);
242
- const before = await paints(page);
243
-
244
- // The top-left 2×2 block of a 3-column table: cells 0, 1, 3 and 4.
245
- await dragAcross(page, 0, 4);
246
- const after = await paints(page);
247
-
248
- const marked = after
249
- .map((paint, index) => (looksDifferent(before[index], paint) ? index : -1))
250
- .filter(index => index !== -1);
251
- expect(marked, 'the selection marks the 2×2 block it covers').toEqual([
252
- 0, 1, 3, 4,
253
- ]);
254
- expect(errors).toEqual([]);
255
- });
256
-
257
- test('the mark is visible against the surface in every theme and mode', async ({
258
- page,
259
- }) => {
260
- const failures: string[] = [];
261
- for (const theme of THEMES) {
262
- for (const mode of MODES) {
263
- await openWithTable(page, theme, mode);
264
- const before = await paints(page);
265
- await dragAcross(page, 0, 4);
266
- const after = await paints(page);
267
-
268
- // Seen, not merely computed: a mark whose colour equals the surface
269
- // behind it is a different computed value and no mark at all.
270
- if (!looksDifferent(before[0], after[0])) {
271
- failures.push(`${theme}/${mode}: a selected cell looks unchanged`);
272
- continue;
273
- }
274
- const contrast = await markContrast(page);
275
- if (contrast < NON_TEXT_CONTRAST) {
276
- failures.push(
277
- `${theme}/${mode}: the mark clears the surface by only ${contrast.toFixed(2)}:1`,
278
- );
279
- }
280
- // And the mark costs the cell's own text nothing: a wash drawn behind
281
- // the text would show up here as a drop.
282
- if (after[0].textContrast < before[0].textContrast - 0.01) {
283
- failures.push(
284
- `${theme}/${mode}: selecting drops header text from ${before[0].textContrast.toFixed(2)}:1 to ${after[0].textContrast.toFixed(2)}:1`,
285
- );
286
- }
287
- }
288
- }
289
- expect(failures).toEqual([]);
290
- });
291
-
292
- test('the mark marks exactly the cells the next keystroke replaces', async ({
293
- page,
294
- }) => {
295
- const errors = await openWithTable(page);
296
- const before = await paints(page);
297
- const filled = (await texts(page))
298
- .map((text, index) => (text === '' ? -1 : index))
299
- .filter(index => index !== -1);
300
-
301
- await dragAcross(page, 0, 4);
302
- const marked = (await paints(page))
303
- .map((paint, index) => (looksDifferent(before[index], paint) ? index : -1))
304
- .filter(index => index !== -1);
305
-
306
- await page.keyboard.press('Backspace');
307
- const emptied = (await texts(page))
308
- .map((text, index) => (text === '' ? index : -1))
309
- .filter(index => index !== -1 && filled.includes(index));
310
-
311
- expect(emptied, 'the keystroke emptied the cells that were marked').toEqual(
312
- marked.filter(index => filled.includes(index)),
313
- );
314
- expect(emptied.length, 'the keystroke emptied something').toBeGreaterThan(0);
315
- expect(errors).toEqual([]);
316
- });
317
-
318
- test('the mark goes when the selection goes', async ({page}) => {
319
- const errors = await openWithTable(page);
320
- const before = await paints(page);
321
-
322
- await dragAcross(page, 0, 4);
323
- expect(looksDifferent(before[0], (await paints(page))[0])).toBe(true);
324
-
325
- // A caret in one cell is not a cell selection.
326
- await page.locator(CELLS).nth(8).click();
327
- await expect
328
- .poll(async () => {
329
- const now = await paints(page);
330
- return now.filter((paint, index) => looksDifferent(before[index], paint))
331
- .length;
332
- })
333
- .toBe(0);
334
- expect(errors).toEqual([]);
335
- });
336
-
337
- test('a read surface marks a dragged selection the same way', async ({
338
- page,
339
- }) => {
340
- // Lexical's table pointer handler does not ask whether the surface is
341
- // editable, so a read surface makes cell selections too — and a person
342
- // selecting cells there is about to copy them, so the mark belongs. Held
343
- // because the two surfaces must render the same document the same way:
344
- // marking only one of them would be the drift this spec exists to catch.
345
- const errors = await openWithTable(page);
346
- await page.getByRole('tab', {name: 'RichTextView'}).click();
347
-
348
- const VIEW =
349
- '[data-playground-output="view"] table th, [data-playground-output="view"] table td';
350
- await expect(page.locator(VIEW)).toHaveCount(9);
351
- const outlines = () =>
352
- page.$$eval(VIEW, cells =>
353
- cells.map(cell => {
354
- const style = getComputedStyle(cell);
355
- return `${style.outlineStyle} ${style.outlineWidth}`;
356
- }),
357
- );
358
- const before = await outlines();
359
- expect(new Set(before).size, 'nothing is marked before a drag').toBe(1);
360
-
361
- const start = await page.locator(VIEW).nth(0).boundingBox();
362
- const end = await page.locator(VIEW).nth(4).boundingBox();
363
- if (start == null || end == null) {
364
- throw new Error('a cell has no box');
365
- }
366
- await page.mouse.move(start.x + 10, start.y + start.height / 2);
367
- await page.mouse.down();
368
- await page.mouse.move(start.x + 30, start.y + start.height / 2, {steps: 4});
369
- await page.mouse.move(end.x + end.width / 2, end.y + end.height / 2, {
370
- steps: 20,
371
- });
372
- await page.mouse.up();
373
-
374
- await expect
375
- .poll(
376
- async () => (await outlines()).filter((o, i) => o !== before[i]).length,
377
- )
378
- .toBeGreaterThan(0);
379
- expect(errors).toEqual([]);
380
- });