Skip to content

Commit 678304f

Browse files
committed
fix(markdown-viewer): wait for ProseMirror's post-focus selection sync before keyboard selection
1 parent a22f4c6 commit 678304f

1 file changed

Lines changed: 25 additions & 131 deletions

File tree

‎apps/sim/scripts/test-markdown-viewer-e2e.ts‎

Lines changed: 25 additions & 131 deletions
Original file line numberDiff line numberDiff line change
@@ -368,6 +368,24 @@ async function proveToolbar(page: Page, toolbar: Locator) {
368368
)
369369
}
370370

371+
const FOCUS_SETTLED = 'markdownViewerFocusSettled'
372+
373+
/**
374+
* ProseMirror writes its own selection back to the DOM 20 ms after the editor gains focus
375+
* (prosemirror-view's focus handler). In WebKit that timer can run after a key's native selection
376+
* change but before the `selectionchange` event that reports it, so the keystroke is reverted.
377+
* Timers with equal delays fire in the order they were set, so one set by a later focus listener,
378+
* or now when the editor already has focus, sets {@link FOCUS_SETTLED} after ProseMirror's has run.
379+
*/
380+
async function armFocusSettled(editor: Locator) {
381+
await editor.evaluate((element, flag) => {
382+
Reflect.set(window, flag, false)
383+
const settle = () => setTimeout(() => Reflect.set(window, flag, true), 20)
384+
if (document.activeElement === element) settle()
385+
else element.addEventListener('focus', settle, { once: true })
386+
}, FOCUS_SETTLED)
387+
}
388+
371389
async function editLastCell(page: Page, marker: string) {
372390
await wideTableProof(page)
373391
const last = page
@@ -403,149 +421,25 @@ async function editLastCell(page: Page, marker: string) {
403421
await expect(page.locator('.rich-markdown-prose[contenteditable="true"]')).toBeVisible({
404422
timeout: 120_000,
405423
})
406-
const browserName = page.context().browser()?.browserType().name() ?? 'unknown'
407-
const failures: string[] = []
408-
try {
409-
await proveKeyboardSelection(page, 'first')
410-
} catch (error) {
411-
failures.push(`first: ${getErrorMessage(error)}`)
412-
}
413-
const iterations = browserName === 'webkit' ? 30 : 2
414-
for (let attempt = 0; attempt < iterations; attempt++) {
415-
await page.reload({ waitUntil: 'domcontentloaded' })
416-
await expect(page.locator('.rich-markdown-prose[contenteditable="true"]')).toBeVisible({
417-
timeout: 120_000,
418-
})
419-
try {
420-
await proveKeyboardSelection(page, `loop ${attempt}`)
421-
} catch (error) {
422-
failures.push(`attempt ${attempt}: ${getErrorMessage(error)}`)
423-
}
424-
}
425-
logger.info('EXPERIMENT selection loop', { browserName, iterations, failures: failures.length })
426-
if (failures.length) throw new Error(`EXPERIMENT failures:\n${failures.join('\n\n')}`)
427-
}
428-
429-
async function proveKeyboardSelection(page: Page, label: string) {
430424
await page.bringToFront()
431-
await page.evaluate(() => {
432-
const element = document.querySelector<TiptapEditorHTMLElement>(
433-
'.rich-markdown-prose[contenteditable="true"]'
434-
)
435-
const editor = element?.editor
436-
const start = performance.now()
437-
const log: string[] = []
438-
const now = () => Math.round(performance.now() - start)
439-
const dom = () => {
440-
const s = getSelection()
441-
return `${s?.anchorNode?.textContent?.slice(0, 10)}:${s?.anchorOffset}/${s?.focusNode?.textContent?.slice(0, 10)}:${s?.focusOffset}`
442-
}
443-
const pm = () => `${editor?.state.selection.from}-${editor?.state.selection.to}`
444-
const carets = () => document.querySelectorAll('.collaboration-carets__caret').length
445-
document.addEventListener('selectionchange', () =>
446-
log.push(`${now()} selectionchange dom=${dom()} pm=${pm()}`)
447-
)
448-
for (const type of ['keydown', 'keyup'] as const)
449-
document.addEventListener(
450-
type,
451-
(event) =>
452-
log.push(
453-
`${now()} ${type} ${event.shiftKey ? 'Shift+' : ''}${event.key} dom=${dom()} pm=${pm()}`
454-
),
455-
true
456-
)
457-
editor?.on('transaction', ({ transaction }) => {
458-
const sync = transaction.getMeta('y-sync$')
459-
const cursor = transaction.getMeta('yjs-cursor$')
460-
const metaKeys = Object.keys(
461-
(transaction as unknown as { meta: Record<string, unknown> }).meta ?? {}
462-
).join(',')
463-
log.push(
464-
`${now()} tr doc=${transaction.docChanged} selSet=${transaction.selectionSet} sel=${transaction.selection.from}-${transaction.selection.to} meta=[${metaKeys}] sync=${sync ? JSON.stringify({ origin: sync.isChangeOrigin, undo: sync.isUndoRedoOperation }) : ''} cursor=${cursor ? JSON.stringify(cursor) : ''} domAfter=${dom()} carets=${carets()} toolbar=${document.querySelectorAll('[aria-label="Text formatting"]').length}`
465-
)
466-
})
467-
const stack = () =>
468-
(new Error().stack ?? '')
469-
.split('\n')
470-
.slice(2, 9)
471-
.map((line) => line.replace(/https?:\/\/[^/]+/, '').trim())
472-
.join(' < ')
473-
const selectionMethods = [
474-
'collapse',
475-
'setBaseAndExtent',
476-
'addRange',
477-
'removeAllRanges',
478-
'extend',
479-
'modify',
480-
'collapseToEnd',
481-
'collapseToStart',
482-
'setPosition',
483-
'empty',
484-
'removeRange',
485-
] as const
486-
for (const method of selectionMethods) {
487-
const original = Reflect.get(Selection.prototype, method) as (...args: unknown[]) => unknown
488-
if (typeof original !== 'function') continue
489-
Reflect.set(Selection.prototype, method, function (this: Selection, ...args: unknown[]) {
490-
const before = dom()
491-
const result = original.apply(this, args)
492-
log.push(
493-
`${now()} Selection.${method}(${args.map((arg) => (arg instanceof Node ? (arg.textContent ?? '').slice(0, 8) : String(arg))).join(',')}) ${before} -> ${dom()} pm=${pm()} stack=${stack()}`
494-
)
495-
return result
496-
})
497-
}
498-
const originalFocus = HTMLElement.prototype.focus
499-
HTMLElement.prototype.focus = function (this: HTMLElement, options?: FocusOptions) {
500-
log.push(`${now()} focus() ${this.className.slice(0, 30)} dom=${dom()} stack=${stack()}`)
501-
return originalFocus.call(this, options)
502-
}
503-
document.addEventListener(
504-
'keydown',
505-
(event) => {
506-
if (event.key === 'ArrowRight')
507-
setTimeout(() => log.push(`${now()} after-default ArrowRight dom=${dom()} pm=${pm()}`))
508-
},
509-
true
510-
)
511-
for (const type of ['focus', 'blur', 'mousedown', 'mouseup', 'click'] as const)
512-
document.addEventListener(type, () => log.push(`${now()} ${type} dom=${dom()}`), true)
513-
const observer = new MutationObserver((records) => {
514-
const changed = records.filter((record) => record.type === 'childList').length
515-
if (changed) log.push(`${now()} mutations=${changed} dom=${dom()} carets=${carets()}`)
516-
})
517-
if (element) observer.observe(element, { childList: true, subtree: true })
518-
Object.assign(window, { __selectionLog: log, __selectionPm: pm })
519-
})
520-
const readLog = () =>
521-
page.evaluate(() => {
522-
const log = Reflect.get(window, '__selectionLog') as string[] | undefined
523-
return (log ?? []).slice(0, 300).join('\n')
524-
})
425+
const editor = page.locator('.rich-markdown-prose[contenteditable="true"]')
426+
await armFocusSettled(editor)
525427
await page
526428
.locator('.rich-markdown-prose strong')
527429
.filter({ hasText: /^bold$/ })
528430
.click()
529-
await expect(page.locator('.rich-markdown-prose[contenteditable="true"]')).toBeFocused()
530-
await page.evaluate(() =>
531-
(Reflect.get(window, '__selectionLog') as string[]).push('--- ArrowLeft')
532-
)
431+
await expect(editor).toBeFocused()
432+
await expect
433+
.poll(() => page.evaluate((flag) => Reflect.get(window, flag), FOCUS_SETTLED))
434+
.toBe(true)
533435
await page.keyboard.press('ArrowLeft')
534-
await page.evaluate(() =>
535-
(Reflect.get(window, '__selectionLog') as string[]).push('--- Shift+ArrowRight')
536-
)
537436
await page.keyboard.press('Shift+ArrowRight')
538-
await page.evaluate(() => (Reflect.get(window, '__selectionLog') as string[]).push('--- pressed'))
539437
try {
540438
await expect
541439
.poll(() => page.evaluate(() => getSelection()?.toString().trim() ?? ''))
542440
.not.toBe('')
543-
if (label === 'loop 0' || label === 'first')
544-
logger.info('EXPERIMENT passing trace', { label, trace: await readLog() })
545441
} catch {
546-
const trace = await readLog()
547-
logger.error('EXPERIMENT failing trace', { label, trace })
548-
// Rare in WebKit and not reproduced yet: name where the caret and focus ended up.
442+
// Name where the caret and focus ended up.
549443
const state = await page.evaluate(() => {
550444
const selection = getSelection()
551445
return {

0 commit comments

Comments
 (0)