Skip to content
Merged
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
165 changes: 165 additions & 0 deletions e2e/docx-jump.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,165 @@
import { expect, test } from 'bun:test'
import { parasToDocx } from '../src/core/convert'
import { useBrowser, viewer, type Viewer } from './harness'

// Find and the outline scroll to their target, then select it once the scroll has come to rest, some frames later.
// What the reader does in the document meanwhile comes first: the late selection is dropped, and the next key typed
// goes where the reader put the caret, instead of replacing the word found.

useBrowser()

const TARGET = 'alpha TARGETWORD omega'

async function open(): Promise<Viewer> {
const blob = await parasToDocx([
{ runs: [{ text: 'Start here' }] },
{ runs: [{ text: TARGET }] },
{ runs: [{ text: 'NEIGHBOR line' }] },
...Array.from({ length: 300 }, (_, i) => ({ runs: [{ text: `Filler ${i + 1}` }] })),
{ heading: 1, runs: [{ text: 'Far heading' }] },
{ runs: [{ text: 'After the heading' }] },
])
const v = await viewer({ editable: true })
await v.page.evaluate((bytes) => window.__setProps({ src: new Uint8Array(bytes), name: 'jump.docx' }), [...new Uint8Array(await blob.arrayBuffer())])
await v.ready('docx')
return v
}

/** every animation frame `ms` late (a busy machine), or on time again with 0; a frame cancelled is cancelled however late */
async function slowFrames(v: Viewer, ms: number) {
await v.page.evaluate((ms) => {
const w = window as unknown as { __frames?: { raf: typeof requestAnimationFrame; caf: typeof cancelAnimationFrame } }
w.__frames ??= { raf: window.requestAnimationFrame.bind(window), caf: window.cancelAnimationFrame.bind(window) }
const { raf, caf } = w.__frames
if (!ms) {
window.requestAnimationFrame = raf
window.cancelAnimationFrame = caf
return
}
const late = new Map<number, { frame: number; timer?: ReturnType<typeof setTimeout> }>()
let next = 1e9
window.requestAnimationFrame = (cb) => {
const id = next++
const entry: { frame: number; timer?: ReturnType<typeof setTimeout> } = {
frame: raf(() => {
entry.timer = setTimeout(() => {
late.delete(id)
cb(performance.now())
}, ms)
}),
}
late.set(id, entry)
return id
}
window.cancelAnimationFrame = (id) => {
const entry = late.get(id)
if (!entry) return caf(id)
caf(entry.frame)
clearTimeout(entry.timer)
late.delete(id)
}
}, ms)
}

/** the document's selection (not a field's): its text, when it is in the pages */
const docSelection = (v: Viewer) =>
v.page.evaluate(() => {
const s = getSelection()
return s?.anchorNode && document.querySelector('.de-pages')?.contains(s.anchorNode) ? s.toString() : null
})

async function find(v: Viewer, q: string) {
await v.btn('Find & replace').click()
const input = v.page.locator('.de-find input[aria-label="Find"]')
await input.fill(q)
await v.page.locator('.de-find-count', { hasText: '1' }).waitFor()
return input
}

for (const how of ['clicked', 'put by the host'] as const) {
test(`a caret ${how} in the text while Find is on its way stays where it is put`, async () => {
const v = await open()
await find(v, 'TARGETWORD')
await slowFrames(v, 1000)
await v.page.keyboard.press('Enter')
if (how === 'clicked') {
const at = await v.page.evaluate(() => {
const root = document.querySelector('.de-pages')!
const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT)
for (let n = walker.nextNode(); n; n = walker.nextNode()) {
const i = n.textContent!.indexOf('NEIGHBOR')
if (i < 0) continue
const r = document.createRange()
r.setStart(n, i + 'NEIGHBOR'.length)
r.collapse(true)
const box = r.getBoundingClientRect()
return { x: box.left, y: box.top + box.height / 2 }
}
return null
})
expect(at).not.toBeNull()
await v.page.mouse.click(at!.x, at!.y)
} else await v.selectText('NEIGHBOR', 'end')
// Find's late selection would come within this, and the keys typed next would replace the word
await v.page.waitForTimeout(3500)
await slowFrames(v, 0)
await v.page.keyboard.type('XY')
await v.page.waitForFunction(() => document.querySelector('.de-pages')?.textContent?.includes('XY'))
const text = await v.pagesText()
expect(text).toContain(TARGET)
expect(text).toContain('NEIGHBORXY line')
expect(v.errors).toEqual([])
})
}

test('with nothing done meanwhile, Find still selects what it found, however late the frames', async () => {
const v = await open()
await find(v, 'TARGETWORD')
await slowFrames(v, 300)
await v.page.keyboard.press('Enter')
await v.page.waitForFunction(() => {
const s = getSelection()
return !!s?.anchorNode && !!document.querySelector('.de-pages')?.contains(s.anchorNode) && s.toString() === 'TARGETWORD'
}, null, { timeout: 10_000 })
expect(v.errors).toEqual([])
})

test('a query typed on while Find is on its way: the match of the query before is not selected', async () => {
const v = await open()
const input = await find(v, 'TARGET')
await slowFrames(v, 1000)
await v.page.keyboard.press('Enter')
await v.page.keyboard.press('End')
await v.page.keyboard.type('WORD')
await v.page.waitForTimeout(3500)
await slowFrames(v, 0)
expect(await docSelection(v)).toBeNull()
expect(await input.inputValue()).toBe('TARGETWORD')
expect(v.errors).toEqual([])
})

test('a field gone to while the outline is on its way keeps the keys typed', async () => {
const v = await open()
const input = await find(v, 'NEIGHBOR')
await v.btn('Document outline').click()
await slowFrames(v, 1000)
await v.page.locator('.de-outline-item', { hasText: 'Far heading' }).click({ force: true })
await input.click({ force: true })
await v.page.waitForTimeout(3500)
await slowFrames(v, 0)
await v.page.keyboard.type('abc')
expect(await input.inputValue()).toBe('NEIGHBORabc')
expect(await v.pagesText()).not.toContain('abcFar heading')
expect(v.errors).toEqual([])
})

test('the outline puts the caret at the heading it scrolled to, from a caret pages above', async () => {
const v = await open()
await v.selectText('Start here', 'start')
await v.btn('Document outline').click()
await v.page.locator('.de-outline-item', { hasText: 'Far heading' }).click()
await v.page.waitForFunction(() => getSelection()?.anchorNode?.parentElement?.closest('[data-pa]')?.textContent === 'Far heading', null, { timeout: 10_000 })
await v.page.keyboard.type('Z')
await v.page.waitForFunction(() => document.querySelector('.de-pages')?.textContent?.includes('ZFar heading'))
expect(v.errors).toEqual([])
})
42 changes: 38 additions & 4 deletions src/react/docx/DocxView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -241,16 +241,39 @@ export function DocxView({ client, onStatus, initialZoom = 'fit' }: DocxViewProp
useIsoLayoutEffect(() => { renderedScroll.current = scroll.y })
// A native scroll changes the viewport before useScroll's frame-batched
// update repositions the pages. Measure a target only after that commit.
// A jump (Find, the outline, a comment) ends there, a few frames later, and Find and the outline then select their
// target. What happens meanwhile comes first, and the rest of the jump is dropped: a newer jump (a page or a comment
// too), a new query in Find, or a click, a key or the wheel in the document (`dropJump`). Else the match was
// selected over the caret the reader had just clicked in, and the next key typed replaced the word. (Not the event
// that began the jump, as a host's shortcut listening before the document: it is older than the jump.)
const jump = useRef({ id: 0, at: 0 })
const dropJump = (e?: { timeStamp: number }) => {
if (!e || e.timeStamp >= jump.current.at) jump.current = { id: jump.current.id + 1, at: 0 }
}
const afterScroll = (run: () => void) => {
const id = jump.current.id + 1
jump.current = { id, at: performance.now() }
let frames = 0
const tick = () => {
const sc = scrollRef.current
if (!sc || ++frames > 120) return
if (!sc || id !== jump.current.id || ++frames > 120) return
if (Math.abs(sc.scrollTop - renderedScroll.current) > 1) requestAnimationFrame(tick)
else run()
}
requestAnimationFrame(tick)
}
// The selection a jump puts in place at its end is not put where the reader has gone since it began: the focus has
// moved (into the text, set there by the host, or into a field of the Find bar or the toolbar), unless the element
// that had it is gone (the Find bar closed). Nor in a paragraph whose text has changed since: the offsets are out of
// date. `jumpFrom` is taken when the jump begins, `jumpLands` asked at its end, each with what the target's
// offsets depend on (`stamp`).
const focused = () => (pagesRef.current?.getRootNode() as Document | ShadowRoot | undefined)?.activeElement ?? null
const jumpFrom = (stamp: string) => ({ active: focused(), stamp })
const jumpLands = (from: ReturnType<typeof jumpFrom>, stamp: string) => {
const now = focused()
return isEditing && stamp === from.stamp && (now === from.active || (!!from.active && !from.active.isConnected && (!now || now === document.body)))
}
const stampOf = (b: Block | undefined, text = true) => (!b ? '' : b.t === 'p' ? `${b.pid}` + (text ? `\n${runsText(b.runs as RRun[])}` : '') : b.t === 'tbl' ? `t${b.tid}` : b.t)
const totalW = Math.max(size.w, pageW * z + PAD * 2)
const left = Math.max(PAD, (totalW - pageW * z) / 2)

Expand Down Expand Up @@ -600,14 +623,15 @@ export function DocxView({ client, onStatus, initialZoom = 'fit' }: DocxViewProp
const pi = pageOfPos(m.pa, m.a)
if (pi >= 0) scrollToY(tops[pi] - 16)
setFind((f) => ({ ...f, idx }))
const from = jumpFrom(stampOf(editor.para(m.pa)))
afterScroll(() => {
const root = pagesRef.current
const r = root && paraRanges(root, m.pa, m.a, m.b)[0]
if (!r) return
const rect = r.getBoundingClientRect()
const box = sc.getBoundingClientRect()
scrollByY(rect.top - box.top - box.height / 3)
if (isEditing) editor.input.restore({ a: { pa: m.pa, o: m.a }, f: { pa: m.pa, o: m.b } }, false)
if (jumpLands(from, stampOf(editor.para(m.pa)))) editor.input.restore({ a: { pa: m.pa, o: m.a }, f: { pa: m.pa, o: m.b } }, false)
})
}

Expand Down Expand Up @@ -908,6 +932,7 @@ export function DocxView({ client, onStatus, initialZoom = 'fit' }: DocxViewProp
if (!place || !sc) return
const pi = pageOfPos(place.pa, place.o)
if (pi < 0) return
dropJump()
const show = () => {
const el = pagesRef.current?.querySelector(`[data-cm~="${CSS.escape(id)}"]`)
if (!el) return false
Expand Down Expand Up @@ -992,10 +1017,12 @@ export function DocxView({ client, onStatus, initialZoom = 'fit' }: DocxViewProp
if (!sc || pi < 0) return
setJumpBi(bi)
scrollToY(tops[pi] - 16)
// (the caret goes to the start of the block: only which block it is matters)
const from = jumpFrom(stampOf(st.blocks[bi], false))
afterScroll(() => {
const el = pagesRef.current?.querySelector(`[data-pa="${bi}"]`)
if (el) scrollByY(el.getBoundingClientRect().top - sc.getBoundingClientRect().top - 24)
if (isEditing) editor.input.restore({ a: { pa: String(bi), o: 0 }, f: { pa: String(bi), o: 0 } })
if (jumpLands(from, stampOf(st.blocks[bi], false))) editor.input.restore({ a: { pa: String(bi), o: 0 }, f: { pa: String(bi), o: 0 } })
})
}

Expand Down Expand Up @@ -1034,6 +1061,7 @@ export function DocxView({ client, onStatus, initialZoom = 'fit' }: DocxViewProp
setZoom,
goto: (id) => gotoBlock(Number(id)),
gotoPage: (n) => {
dropJump()
const top = tops[Math.min(Math.max(1, n), tops.length) - 1]
if (top !== undefined) scrollToY(top - 16)
},
Expand Down Expand Up @@ -1070,6 +1098,9 @@ export function DocxView({ client, onStatus, initialZoom = 'fit' }: DocxViewProp
ref={scrollRef}
className="de-scroll"
tabIndex={-1}
onPointerDownCapture={dropJump}
onKeyDownCapture={dropJump}
onWheelCapture={dropJump}
onKeyDown={(e) => {
if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'f') {
e.preventDefault()
Expand Down Expand Up @@ -1186,7 +1217,10 @@ export function DocxView({ client, onStatus, initialZoom = 'fit' }: DocxViewProp
index={find.idx}
count={matches.length}
editable={isEditing}
onQuery={(q) => setFind({ open: true, q, idx: 0 })}
onQuery={(q) => {
dropJump()
setFind({ open: true, q, idx: 0 })
}}
onNav={(d) => matches.length && gotoMatch((find.idx + d + matches.length) % matches.length)}
onClose={() => setFind({ open: false, q: find.q, idx: 0 })}
onReplace={(text, all) => {
Expand Down