@astryxdesign/richtext 0.7.1-canary.ff40b78 → 0.7.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.
Files changed (48) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/README.md +47 -57
  3. package/astryx.integration.mjs +1 -1
  4. package/dist/RichTextEditor.d.ts +16 -12
  5. package/dist/RichTextEditor.d.ts.map +1 -1
  6. package/dist/RichTextEditor.js +40 -45
  7. package/dist/RichTextEditorAutoLinkPlugin.d.ts +3 -3
  8. package/dist/RichTextEditorAutoLinkPlugin.js +3 -3
  9. package/dist/RichTextEditorToolbar.d.ts +19 -8
  10. package/dist/RichTextEditorToolbar.d.ts.map +1 -1
  11. package/dist/RichTextEditorToolbar.js +16 -9
  12. package/dist/RichTextView.d.ts +1 -1
  13. package/dist/RichTextView.js +1 -1
  14. package/dist/editorTheme.d.ts.map +1 -1
  15. package/dist/editorTheme.js +15 -4
  16. package/dist/index.d.ts +10 -5
  17. package/dist/index.d.ts.map +1 -1
  18. package/dist/index.js +9 -4
  19. package/dist/linkUtils.js +1 -1
  20. package/dist/markdownLink.d.ts.map +1 -1
  21. package/dist/markdownLink.js +25 -33
  22. package/dist/markdownListExport.d.ts.map +1 -1
  23. package/dist/markdownListExport.js +4 -1
  24. package/dist/markdownSerializers.d.ts.map +1 -1
  25. package/dist/markdownSerializers.js +2 -3
  26. package/dist/richtext.css +6 -1
  27. package/package.json +34 -36
  28. package/src/RichTextEditor.doc.mjs +3 -3
  29. package/src/RichTextEditor.test.tsx +36 -2
  30. package/src/RichTextEditor.tsx +54 -54
  31. package/src/RichTextEditorAutoLinkPlugin.tsx +3 -3
  32. package/src/RichTextEditorToolbar.tsx +27 -10
  33. package/src/RichTextView.tsx +1 -1
  34. package/src/__tests__/MarkdownParitySandbox.a11y.chromium.spec.ts +40 -23
  35. package/src/__tests__/MarkdownPlugins.a11y.chromium.spec.ts +2 -2
  36. package/src/__tests__/MarkdownPluginsImportExport.a11y.chromium.spec.ts +35 -1
  37. package/src/__tests__/Playground.a11y.chromium.spec.ts +298 -0
  38. package/src/__tests__/RichTextEditorToolbar.a11y.chromium.spec.ts +1 -1
  39. package/src/__tests__/RichTextView.a11y.chromium.spec.ts +1 -1
  40. package/src/__tests__/TableCellSelection.a11y.chromium.spec.ts +379 -0
  41. package/src/editorTheme.ts +53 -3
  42. package/src/index.ts +9 -11
  43. package/src/linkUtils.ts +1 -1
  44. package/src/markdownAngleDestinations.test.ts +29 -0
  45. package/src/markdownLink.ts +29 -35
  46. package/src/markdownListExport.ts +6 -1
  47. package/src/markdownSerializers.ts +2 -3
  48. package/src/publicSurface.test.ts +42 -0
@@ -0,0 +1,298 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+
3
+ /**
4
+ * @file Playground.a11y.chromium.spec.ts
5
+ * @input The built Storybook's RichText/RichTextEditor "Playground" story.
6
+ * @output Real-browser proof that the playground is ONE editor carrying every
7
+ * feature at once: the seeded document brings every block type, each
8
+ * readout reports that same editor, switching a feature on or off leaves a
9
+ * single live editor behind, and the toolbar's endContent slot reaches the
10
+ * editor through the composer context.
11
+ *
12
+ * The playground exists so features can be combined; a story that silently
13
+ * lost its toolbar, its plugins, or its single-editor shape would still look
14
+ * fine in a screenshot. This holds the shape.
15
+ *
16
+ * Run after building Storybook:
17
+ * pnpm storybook:build
18
+ * pnpm exec playwright test packages/richtext --project chromium
19
+ */
20
+
21
+ import AxeBuilder from '@axe-core/playwright';
22
+ import {expect, test, type Page} from '@playwright/test';
23
+ import {
24
+ DEFAULT_STORYBOOK_DIR,
25
+ serveStorybook,
26
+ type StaticServer,
27
+ } from '@astryxdesign/a11y-spec/storybook';
28
+
29
+ const STORYBOOK_DIR = process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR;
30
+ const STORY = 'richtext-richtexteditor--playground';
31
+
32
+ /** The one editable surface the whole page is about. */
33
+ const EDITOR = '[data-playground-editor] [role="textbox"]';
34
+
35
+ let storybook: StaticServer;
36
+
37
+ test.beforeAll(async () => {
38
+ storybook = await serveStorybook(STORYBOOK_DIR);
39
+ });
40
+
41
+ test.afterAll(async () => {
42
+ await storybook?.close();
43
+ });
44
+
45
+ async function openStory(page: Page): Promise<string[]> {
46
+ const errors: string[] = [];
47
+ page.on('pageerror', error => errors.push(String(error)));
48
+ page.on('console', message => {
49
+ if (message.type() === 'error' && !message.text().includes('404')) {
50
+ errors.push(message.text());
51
+ }
52
+ });
53
+ await page.setViewportSize({width: 1440, height: 900});
54
+ await page.goto(
55
+ `${storybook.origin}/iframe.html?id=${STORY}&viewMode=story&globals=astryxTheme:neutral;colorMode:light;direction:ltr`,
56
+ {waitUntil: 'load'},
57
+ );
58
+ await expect(page.locator(EDITOR)).toBeVisible();
59
+ return errors;
60
+ }
61
+
62
+ const settings = (page: Page) => page.locator('[data-playground-settings]');
63
+
64
+ const toggle = (page: Page, label: string) =>
65
+ settings(page).getByRole('switch', {name: label, exact: false}).first();
66
+
67
+ test('one editor holds the seeded document, with every block type in it', async ({
68
+ page,
69
+ }) => {
70
+ const errors = await openStory(page);
71
+ // One editable surface on the page: the readouts beside it are read-only.
72
+ await expect(
73
+ page.locator('[role="textbox"][data-lexical-editor]'),
74
+ ).toHaveCount(1);
75
+ const editor = page.locator(EDITOR);
76
+ await expect(editor.locator('h1')).toHaveCount(1);
77
+ await expect(editor.locator('table')).toHaveCount(1);
78
+ await expect(editor.locator('a')).not.toHaveCount(0);
79
+ await expect(editor.locator('li')).not.toHaveCount(0);
80
+ await expect(editor.locator('hr')).toHaveCount(1);
81
+ // A task list draws real checkboxes, and a Markdown plugin node is adopted.
82
+ await expect(
83
+ page.locator('[data-playground-editor] input[type="checkbox"]'),
84
+ ).not.toHaveCount(0);
85
+ await expect(
86
+ page.locator('[data-playground-editor] [data-markdown-extension]'),
87
+ ).not.toHaveCount(0);
88
+ expect(errors).toEqual([]);
89
+ });
90
+
91
+ test('every readout reports the editor beside it, and follows it as it is typed into', async ({
92
+ page,
93
+ }) => {
94
+ const errors = await openStory(page);
95
+ const output = page.locator('[data-playground-output]');
96
+
97
+ await page.getByRole('tab', {name: 'Markdown'}).click();
98
+ await expect(output).toContainText('# Release notes');
99
+
100
+ await page.getByRole('tab', {name: 'Node tree'}).click();
101
+ await expect(output).toContainText('heading tag=h1');
102
+
103
+ await page.getByRole('tab', {name: 'Editor state'}).click();
104
+ await expect(output).toContainText('"root"');
105
+
106
+ await page.getByRole('tab', {name: 'HTML'}).click();
107
+ await expect(output).toContainText('<h1');
108
+
109
+ await page.getByRole('tab', {name: 'RichTextView'}).click();
110
+ await expect(output.locator('table')).toHaveCount(1);
111
+
112
+ // Type into the one editor; the Markdown readout of that same editor moves.
113
+ await page.getByRole('tab', {name: 'Markdown'}).click();
114
+ await page.locator(EDITOR).click();
115
+ await page.keyboard.press('ControlOrMeta+End');
116
+ await page.keyboard.type(' A sentence typed by the spec.');
117
+ await expect(output).toContainText('A sentence typed by the spec.');
118
+ expect(errors).toEqual([]);
119
+ });
120
+
121
+ test('switching a feature leaves one live editor behind', async ({page}) => {
122
+ const errors = await openStory(page);
123
+ for (const label of [
124
+ 'Toolbar',
125
+ 'Toolbar',
126
+ 'Autolink',
127
+ 'Autolink',
128
+ 'Markdown plugins',
129
+ 'Markdown plugins',
130
+ 'Restricted transformers',
131
+ 'Restricted transformers',
132
+ 'Character limit',
133
+ ]) {
134
+ await toggle(page, label).click();
135
+ await expect(page.locator(EDITOR)).toBeVisible();
136
+ }
137
+ // The character counter belongs to the editor that is still mounted.
138
+ await expect(page.locator('[data-playground-editor]')).toContainText('/500');
139
+
140
+ // Read-only keeps the content reachable but stops the editing.
141
+ await toggle(page, 'Read-only').click();
142
+ await expect(page.locator(EDITOR)).toHaveAttribute(
143
+ 'contenteditable',
144
+ 'false',
145
+ );
146
+ await toggle(page, 'Read-only').click();
147
+ await expect(page.locator(EDITOR)).toHaveAttribute('contenteditable', 'true');
148
+ expect(errors).toEqual([]);
149
+ });
150
+
151
+ test("the toolbar's endContent slot reaches the editor", async ({page}) => {
152
+ const errors = await openStory(page);
153
+ const editor = page.locator(EDITOR);
154
+ const tables = await editor.locator('table').count();
155
+ await editor.click();
156
+ await page.getByRole('button', {name: 'Table', exact: true}).click();
157
+ await expect(editor.locator('table')).toHaveCount(tables + 1);
158
+
159
+ // A header ROW and no header column, in every table the editor holds. GFM
160
+ // has no header column, so a table carrying one is dropped by the
161
+ // playground's own Markdown readout and reads as a round-trip bug no real
162
+ // document can produce — which is what Lexical's `includeHeaders: true`
163
+ // would make here. Asserted across all tables rather than on the one just
164
+ // inserted: the insert lands wherever the caret is, so position is not a
165
+ // reliable handle on it. `:first-of-type`, not `:first-child` — Lexical's
166
+ // table opens with a `<colgroup>` and puts the rows directly in `<table>`,
167
+ // so no `tr` is ever a first child.
168
+ await expect(editor.locator('table tr:first-of-type th')).not.toHaveCount(0);
169
+ await expect(editor.locator('table tr:not(:first-of-type) th')).toHaveCount(
170
+ 0,
171
+ );
172
+ expect(errors).toEqual([]);
173
+ });
174
+
175
+ test("the endContent controls disable with the editor, like the toolbar's own", async ({
176
+ page,
177
+ }) => {
178
+ const errors = await openStory(page);
179
+ const editor = page.locator(EDITOR);
180
+ const inserts = ['Table', 'Rule', 'Mention'].map(name =>
181
+ page.getByRole('button', {name, exact: true}),
182
+ );
183
+ const bold = page.getByRole('button', {name: 'Bold', exact: true});
184
+ for (const state of ['Read-only', 'Disabled']) {
185
+ await toggle(page, state).click();
186
+ await expect(editor).toHaveAttribute('contenteditable', 'false');
187
+ // The toolbar's own controls are the reference this matches.
188
+ await expect(bold).toBeDisabled();
189
+ for (const insert of inserts) {
190
+ await expect(insert, `${state}: insert control`).toBeDisabled();
191
+ }
192
+ // A forced click still changes nothing in a non-editable editor.
193
+ const before = await editor.innerHTML();
194
+ for (const insert of inserts) {
195
+ await insert.click({force: true});
196
+ }
197
+ expect(await editor.innerHTML(), `${state}: editor content`).toBe(before);
198
+ await toggle(page, state).click();
199
+ await expect(editor).toHaveAttribute('contenteditable', 'true');
200
+ for (const insert of inserts) {
201
+ await expect(insert, `${state} off: insert control`).toBeEnabled();
202
+ }
203
+ }
204
+ expect(errors).toEqual([]);
205
+ });
206
+
207
+ test('the shortcut table lists Cmd/Ctrl+K only while the toolbar registers it', async ({
208
+ page,
209
+ }) => {
210
+ const errors = await openStory(page);
211
+ const linkShortcut = settings(page).getByText('Insert or edit a link');
212
+ await expect(linkShortcut).toBeVisible();
213
+
214
+ // The toolbar registers that key, and only while its link button is on.
215
+ await toggle(page, 'Link button').click();
216
+ await expect(linkShortcut).toHaveCount(0);
217
+ await toggle(page, 'Link button').click();
218
+ await expect(linkShortcut).toBeVisible();
219
+
220
+ await toggle(page, 'Toolbar').click();
221
+ await expect(linkShortcut).toHaveCount(0);
222
+
223
+ // The rows that core and the always-on plugins answer stay listed.
224
+ await expect(settings(page).getByText('Bold', {exact: true})).toBeVisible();
225
+ await expect(settings(page).getByText('Undo', {exact: true})).toBeVisible();
226
+ expect(errors).toEqual([]);
227
+ });
228
+
229
+ /**
230
+ * Every Markdown shortcut the settings panel may promise, and what typing it
231
+ * must produce. The panel's description is read from the DOM and checked
232
+ * against this table, so a shortcut added to that sentence has to be proven
233
+ * here before the suite passes — the sentence is the part that goes stale
234
+ * (it once promised `- [ ] `, which `- ` turns into a plain bullet first, and
235
+ * `|`, which never converts while typing at all).
236
+ */
237
+ const MARKDOWN_SHORTCUTS: ReadonlyArray<{
238
+ token: string;
239
+ type: string;
240
+ produces: string;
241
+ }> = [
242
+ {token: '# ', type: '# a heading', produces: 'h1'},
243
+ {token: '- ', type: '- an item', produces: 'li'},
244
+ {token: '> ', type: '> a quote', produces: 'blockquote'},
245
+ {token: '```', type: '```ts\nconst a = 1;', produces: 'code'},
246
+ ];
247
+
248
+ test('every Markdown shortcut the panel promises actually fires', async ({
249
+ page,
250
+ }) => {
251
+ const errors = await openStory(page);
252
+ const description =
253
+ (await settings(page)
254
+ .getByText(/^Typing /)
255
+ .textContent()) ?? '';
256
+
257
+ // The sentence promises exactly the shortcuts this test proves.
258
+ const promised = [...description.matchAll(/'([^']+)'/g)].map(
259
+ match => match[1],
260
+ );
261
+ expect(promised).toEqual(MARKDOWN_SHORTCUTS.map(shortcut => shortcut.token));
262
+
263
+ const editor = page.locator(EDITOR);
264
+ for (const {type, produces} of MARKDOWN_SHORTCUTS) {
265
+ await page.getByRole('button', {name: 'Clear', exact: true}).click();
266
+ await editor.click();
267
+ await page.keyboard.type(type);
268
+ await expect(
269
+ editor.locator(produces),
270
+ `typing ${JSON.stringify(type)} should produce <${produces}>`,
271
+ ).not.toHaveCount(0);
272
+ }
273
+ expect(errors).toEqual([]);
274
+ });
275
+
276
+ // The repository's Storybook audit runs axe with these exemptions; a story
277
+ // renders inside the preview iframe, not as a whole page.
278
+ const AXE_DISABLED_RULES = [
279
+ 'html-has-lang',
280
+ 'document-title',
281
+ 'landmark-one-main',
282
+ 'page-has-heading-one',
283
+ 'region',
284
+ ];
285
+
286
+ test('the story has no axe violations', async ({page}) => {
287
+ const errors = await openStory(page);
288
+ const results = await new AxeBuilder({page})
289
+ .disableRules(AXE_DISABLED_RULES)
290
+ .analyze();
291
+ expect(
292
+ results.violations.map(violation => [
293
+ violation.id,
294
+ violation.nodes.map(node => node.target.join(' ')),
295
+ ]),
296
+ ).toEqual([]);
297
+ expect(errors).toEqual([]);
298
+ });
@@ -22,7 +22,7 @@ import {
22
22
  } from '@astryxdesign/a11y-spec/storybook';
23
23
 
24
24
  const STORYBOOK_DIR = process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR;
25
- const STORY = 'lab-richtexteditor--with-toolbar';
25
+ const STORY = 'richtext-richtexteditor--with-toolbar';
26
26
 
27
27
  let storybook: StaticServer;
28
28
 
@@ -21,7 +21,7 @@ import {
21
21
  } from '@astryxdesign/a11y-spec/storybook';
22
22
 
23
23
  const STORYBOOK_DIR = process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR;
24
- const STORY = 'lab-richtexteditor--markdown-serializers';
24
+ const STORY = 'richtext-richtexteditor--markdown-serializers';
25
25
  const DOCUMENT = [
26
26
  'Paragraph text',
27
27
  '',
@@ -0,0 +1,379 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+
3
+ /**
4
+ * @file TableCellSelection.a11y.chromium.spec.ts
5
+ * @input The built Storybook's Lab/RichTextEditor "Playground" story, whose
6
+ * editor takes a table from the toolbar's insert control.
7
+ * @output Real-browser proof that a table selection is visible: the cells a
8
+ * drag covers are marked and the cells it does not are not, the mark clears
9
+ * the surface it is drawn on in every shipped theme and mode, it costs the
10
+ * cell's own text no contrast, it marks exactly the cells the next keystroke
11
+ * replaces, and it goes when the selection goes.
12
+ *
13
+ * A table selection is made of DOM the engine owns and a class name the theme
14
+ * supplies. Nothing in a unit test can see whether that class was ever named:
15
+ * `addClassNamesToElement(element, theme.tableCellSelected)` is a silent
16
+ * no-op when the slot is undefined, which is how cells in a selection came to
17
+ * be painted exactly like cells outside one. Only a real engine, dragging
18
+ * across real cells, can tell the two apart.
19
+ *
20
+ * The theme sweep is not ceremony. A mark is only visible against the surface
21
+ * it lands on, and a token that clears the surface under one theme can equal
22
+ * it under another: `--color-accent-muted` resolves to the editor field's own
23
+ * colour under Neutral dark, where a background wash would be invisible while
24
+ * every computed-value assertion still passed.
25
+ *
26
+ * Run after building Storybook:
27
+ * pnpm storybook:build
28
+ * pnpm exec playwright test packages/richtext --project chromium
29
+ */
30
+
31
+ import {expect, test, type Page} from '@playwright/test';
32
+ import {
33
+ DEFAULT_STORYBOOK_DIR,
34
+ serveStorybook,
35
+ type StaticServer,
36
+ } from '@astryxdesign/a11y-spec/storybook';
37
+
38
+ const STORYBOOK_DIR = process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR;
39
+ const STORY = 'richtext-richtexteditor--playground';
40
+ const EDITOR = '[data-playground-editor] [role="textbox"]';
41
+ const CELLS = `${EDITOR} table th, ${EDITOR} table td`;
42
+
43
+ /** Every shipped theme, in both modes: a mark has to land on all of them. */
44
+ const THEMES = [
45
+ 'neutral',
46
+ 'stone',
47
+ 'butter',
48
+ 'chocolate',
49
+ 'gothic',
50
+ 'matcha',
51
+ 'y2k',
52
+ ] as const;
53
+ const MODES = ['light', 'dark'] as const;
54
+
55
+ /**
56
+ * WCAG 1.4.11's bar for a non-text indicator. The mark has to clear the
57
+ * surface it is drawn on by at least this much to be a mark at all.
58
+ */
59
+ const NON_TEXT_CONTRAST = 3;
60
+
61
+ let storybook: StaticServer;
62
+
63
+ test.beforeAll(async () => {
64
+ storybook = await serveStorybook(STORYBOOK_DIR);
65
+ });
66
+
67
+ test.afterAll(async () => {
68
+ await storybook?.close();
69
+ });
70
+
71
+ /**
72
+ * How a cell is marked, and what its text has to read against: enough to say
73
+ * whether two cells look different, without naming the treatment. A future
74
+ * mark that is a wash rather than a ring is described here just as well.
75
+ */
76
+ interface CellPaint {
77
+ readonly outline: string;
78
+ readonly background: string;
79
+ /** Contrast of the cell's own text against its own background. */
80
+ readonly textContrast: number;
81
+ }
82
+
83
+ /** Opens the story under one theme and mode, with a filled 3×3 table. */
84
+ async function openWithTable(
85
+ page: Page,
86
+ theme: string = 'neutral',
87
+ mode: string = 'light',
88
+ ): Promise<string[]> {
89
+ const errors: string[] = [];
90
+ page.on('pageerror', error => errors.push(String(error)));
91
+ page.on('console', message => {
92
+ if (message.type() === 'error' && !message.text().includes('404')) {
93
+ errors.push(message.text());
94
+ }
95
+ });
96
+ await page.setViewportSize({width: 1440, height: 900});
97
+ await page.goto(
98
+ `${storybook.origin}/iframe.html?id=${STORY}&viewMode=story&globals=astryxTheme:${theme};colorMode:${mode};direction:ltr`,
99
+ {waitUntil: 'load'},
100
+ );
101
+ await expect(page.locator(EDITOR)).toBeVisible();
102
+
103
+ // A table of its own, away from the seeded document, so the cell indices
104
+ // below mean what they say.
105
+ await page.getByRole('button', {name: 'Clear', exact: true}).click();
106
+ await page.locator(EDITOR).click();
107
+ await page.getByRole('button', {name: 'Table', exact: true}).click();
108
+ await expect(page.locator(CELLS)).toHaveCount(9);
109
+ for (const [index, word] of [
110
+ [0, 'Area'],
111
+ [1, 'Owner'],
112
+ [3, 'Sync'],
113
+ [4, 'Platform'],
114
+ ] as const) {
115
+ await page.locator(CELLS).nth(index).click();
116
+ await page.keyboard.type(word);
117
+ }
118
+ return errors;
119
+ }
120
+
121
+ /**
122
+ * Reads each cell's mark and its text contrast, compositing translucent
123
+ * colours over the first opaque surface behind the table so a measurement is
124
+ * of what a person actually sees, not of a token's nominal value.
125
+ */
126
+ const paints = (page: Page): Promise<CellPaint[]> =>
127
+ page.$$eval(CELLS, cells => {
128
+ const parse = (value: string): number[] => {
129
+ const parts = (value.match(/[\d.]+/g) ?? []).map(Number);
130
+ return parts.length === 3 ? [...parts, 1] : parts;
131
+ };
132
+ const over = (fg: number[], bg: number[]): number[] =>
133
+ [0, 1, 2].map(i => fg[i] * fg[3] + bg[i] * (1 - fg[3]));
134
+ const channel = (c: number): number => {
135
+ const v = c / 255;
136
+ return v <= 0.03928 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4;
137
+ };
138
+ const luminance = (c: number[]): number =>
139
+ 0.2126 * channel(c[0]) + 0.7152 * channel(c[1]) + 0.0722 * channel(c[2]);
140
+ const contrast = (a: number[], b: number[]): number => {
141
+ const [hi, lo] = [luminance(a), luminance(b)].sort((x, y) => y - x);
142
+ return (hi + 0.05) / (lo + 0.05);
143
+ };
144
+ /** The first opaque background behind an element. */
145
+ const backdrop = (el: Element): number[] => {
146
+ let node: Element | null = el.parentElement;
147
+ while (node != null) {
148
+ const parsed = parse(getComputedStyle(node).backgroundColor);
149
+ if (parsed[3] === 1) {
150
+ return parsed;
151
+ }
152
+ node = node.parentElement;
153
+ }
154
+ return [255, 255, 255, 1];
155
+ };
156
+ return cells.map(cell => {
157
+ const style = getComputedStyle(cell);
158
+ const behind = backdrop(cell);
159
+ const own = over(parse(style.backgroundColor), behind);
160
+ return {
161
+ outline: `${style.outlineStyle} ${style.outlineWidth} ${style.outlineColor}`,
162
+ background: style.backgroundColor,
163
+ textContrast: contrast(parse(style.color), own),
164
+ };
165
+ });
166
+ });
167
+
168
+ /** The mark's own contrast against the surface the table sits on. */
169
+ const markContrast = (page: Page): Promise<number> =>
170
+ page.$$eval(CELLS, cells => {
171
+ const parse = (value: string): number[] => {
172
+ const parts = (value.match(/[\d.]+/g) ?? []).map(Number);
173
+ return parts.length === 3 ? [...parts, 1] : parts;
174
+ };
175
+ const over = (fg: number[], bg: number[]): number[] =>
176
+ [0, 1, 2].map(i => fg[i] * fg[3] + bg[i] * (1 - fg[3]));
177
+ const channel = (c: number): number => {
178
+ const v = c / 255;
179
+ return v <= 0.03928 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4;
180
+ };
181
+ const luminance = (c: number[]): number =>
182
+ 0.2126 * channel(c[0]) + 0.7152 * channel(c[1]) + 0.0722 * channel(c[2]);
183
+ const contrast = (a: number[], b: number[]): number => {
184
+ const [hi, lo] = [luminance(a), luminance(b)].sort((x, y) => y - x);
185
+ return (hi + 0.05) / (lo + 0.05);
186
+ };
187
+ const backdrop = (el: Element): number[] => {
188
+ let node: Element | null = el.parentElement;
189
+ while (node != null) {
190
+ const parsed = parse(getComputedStyle(node).backgroundColor);
191
+ if (parsed[3] === 1) {
192
+ return parsed;
193
+ }
194
+ node = node.parentElement;
195
+ }
196
+ return [255, 255, 255, 1];
197
+ };
198
+ const selected = cells[0];
199
+ const style = getComputedStyle(selected);
200
+ const behind = backdrop(selected);
201
+ // Whichever way the cell is marked, measure that mark against the
202
+ // surface: the ring if it is ringed, the background if it is washed.
203
+ const mark =
204
+ style.outlineStyle !== 'none' && parseFloat(style.outlineWidth) > 0
205
+ ? parse(style.outlineColor)
206
+ : parse(style.backgroundColor);
207
+ return contrast(over(mark, behind), behind);
208
+ });
209
+
210
+ const texts = (page: Page): Promise<string[]> =>
211
+ page.$$eval(CELLS, cells =>
212
+ cells.map(cell => cell.textContent?.trim() ?? ''),
213
+ );
214
+
215
+ /** Drags from one cell to another, the gesture that selects a cell range. */
216
+ async function dragAcross(page: Page, from: number, to: number) {
217
+ const start = await page.locator(CELLS).nth(from).boundingBox();
218
+ const end = await page.locator(CELLS).nth(to).boundingBox();
219
+ if (start == null || end == null) {
220
+ throw new Error('a cell has no box');
221
+ }
222
+ await page.mouse.move(start.x + 15, start.y + start.height / 2);
223
+ await page.mouse.down();
224
+ // Past the anchor cell's edge first: the engine starts highlighting once
225
+ // the pointer leaves the cell it went down in.
226
+ await page.mouse.move(start.x + 40, start.y + start.height / 2, {steps: 4});
227
+ await page.mouse.move(end.x + end.width / 2, end.y + end.height / 2, {
228
+ steps: 20,
229
+ });
230
+ await page.mouse.up();
231
+ }
232
+
233
+ /** Did the selection change how this cell looks? */
234
+ const looksDifferent = (before: CellPaint, after: CellPaint): boolean =>
235
+ before.outline !== after.outline || before.background !== after.background;
236
+
237
+ test('the cells a selection covers are marked, and the rest are not', async ({
238
+ page,
239
+ }) => {
240
+ const errors = await openWithTable(page);
241
+ const before = await paints(page);
242
+
243
+ // The top-left 2×2 block of a 3-column table: cells 0, 1, 3 and 4.
244
+ await dragAcross(page, 0, 4);
245
+ const after = await paints(page);
246
+
247
+ const marked = after
248
+ .map((paint, index) => (looksDifferent(before[index], paint) ? index : -1))
249
+ .filter(index => index !== -1);
250
+ expect(marked, 'the selection marks the 2×2 block it covers').toEqual([
251
+ 0, 1, 3, 4,
252
+ ]);
253
+ expect(errors).toEqual([]);
254
+ });
255
+
256
+ test('the mark is visible against the surface in every theme and mode', async ({
257
+ page,
258
+ }) => {
259
+ const failures: string[] = [];
260
+ for (const theme of THEMES) {
261
+ for (const mode of MODES) {
262
+ await openWithTable(page, theme, mode);
263
+ const before = await paints(page);
264
+ await dragAcross(page, 0, 4);
265
+ const after = await paints(page);
266
+
267
+ // Seen, not merely computed: a mark whose colour equals the surface
268
+ // behind it is a different computed value and no mark at all.
269
+ if (!looksDifferent(before[0], after[0])) {
270
+ failures.push(`${theme}/${mode}: a selected cell looks unchanged`);
271
+ continue;
272
+ }
273
+ const contrast = await markContrast(page);
274
+ if (contrast < NON_TEXT_CONTRAST) {
275
+ failures.push(
276
+ `${theme}/${mode}: the mark clears the surface by only ${contrast.toFixed(2)}:1`,
277
+ );
278
+ }
279
+ // And the mark costs the cell's own text nothing: a wash drawn behind
280
+ // the text would show up here as a drop.
281
+ if (after[0].textContrast < before[0].textContrast - 0.01) {
282
+ failures.push(
283
+ `${theme}/${mode}: selecting drops header text from ${before[0].textContrast.toFixed(2)}:1 to ${after[0].textContrast.toFixed(2)}:1`,
284
+ );
285
+ }
286
+ }
287
+ }
288
+ expect(failures).toEqual([]);
289
+ });
290
+
291
+ test('the mark marks exactly the cells the next keystroke replaces', async ({
292
+ page,
293
+ }) => {
294
+ const errors = await openWithTable(page);
295
+ const before = await paints(page);
296
+ const filled = (await texts(page))
297
+ .map((text, index) => (text === '' ? -1 : index))
298
+ .filter(index => index !== -1);
299
+
300
+ await dragAcross(page, 0, 4);
301
+ const marked = (await paints(page))
302
+ .map((paint, index) => (looksDifferent(before[index], paint) ? index : -1))
303
+ .filter(index => index !== -1);
304
+
305
+ await page.keyboard.press('Backspace');
306
+ const emptied = (await texts(page))
307
+ .map((text, index) => (text === '' ? index : -1))
308
+ .filter(index => index !== -1 && filled.includes(index));
309
+
310
+ expect(emptied, 'the keystroke emptied the cells that were marked').toEqual(
311
+ marked.filter(index => filled.includes(index)),
312
+ );
313
+ expect(emptied.length, 'the keystroke emptied something').toBeGreaterThan(0);
314
+ expect(errors).toEqual([]);
315
+ });
316
+
317
+ test('the mark goes when the selection goes', async ({page}) => {
318
+ const errors = await openWithTable(page);
319
+ const before = await paints(page);
320
+
321
+ await dragAcross(page, 0, 4);
322
+ expect(looksDifferent(before[0], (await paints(page))[0])).toBe(true);
323
+
324
+ // A caret in one cell is not a cell selection.
325
+ await page.locator(CELLS).nth(8).click();
326
+ await expect
327
+ .poll(async () => {
328
+ const now = await paints(page);
329
+ return now.filter((paint, index) => looksDifferent(before[index], paint))
330
+ .length;
331
+ })
332
+ .toBe(0);
333
+ expect(errors).toEqual([]);
334
+ });
335
+
336
+ test('a read surface marks a dragged selection the same way', async ({
337
+ page,
338
+ }) => {
339
+ // Lexical's table pointer handler does not ask whether the surface is
340
+ // editable, so a read surface makes cell selections too — and a person
341
+ // selecting cells there is about to copy them, so the mark belongs. Held
342
+ // because the two surfaces must render the same document the same way:
343
+ // marking only one of them would be the drift this spec exists to catch.
344
+ const errors = await openWithTable(page);
345
+ await page.getByRole('tab', {name: 'RichTextView'}).click();
346
+
347
+ const VIEW =
348
+ '[data-playground-output="view"] table th, [data-playground-output="view"] table td';
349
+ await expect(page.locator(VIEW)).toHaveCount(9);
350
+ const outlines = () =>
351
+ page.$$eval(VIEW, cells =>
352
+ cells.map(cell => {
353
+ const style = getComputedStyle(cell);
354
+ return `${style.outlineStyle} ${style.outlineWidth}`;
355
+ }),
356
+ );
357
+ const before = await outlines();
358
+ expect(new Set(before).size, 'nothing is marked before a drag').toBe(1);
359
+
360
+ const start = await page.locator(VIEW).nth(0).boundingBox();
361
+ const end = await page.locator(VIEW).nth(4).boundingBox();
362
+ if (start == null || end == null) {
363
+ throw new Error('a cell has no box');
364
+ }
365
+ await page.mouse.move(start.x + 10, start.y + start.height / 2);
366
+ await page.mouse.down();
367
+ await page.mouse.move(start.x + 30, start.y + start.height / 2, {steps: 4});
368
+ await page.mouse.move(end.x + end.width / 2, end.y + end.height / 2, {
369
+ steps: 20,
370
+ });
371
+ await page.mouse.up();
372
+
373
+ await expect
374
+ .poll(
375
+ async () => (await outlines()).filter((o, i) => o !== before[i]).length,
376
+ )
377
+ .toBeGreaterThan(0);
378
+ expect(errors).toEqual([]);
379
+ });