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
2 changes: 1 addition & 1 deletion e2e/docx-track.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ describe('docx tracked changes', () => {
await v.page.waitForTimeout(250)
let ps = await docxParas((await v.save()).bytes)
expect(show(ps.find((p) => show(p).startsWith('Hire'))!)).toBe('Hire the platform tea[-m]')
// typing at the caret (Save took the focus: put it back after "tea") goes in as inserted text, before the deletion
// typing at the caret, after "tea", goes in as inserted text, before the deletion
await v.selectText('platform tea', 'end')
await v.page.keyboard.type('ms')
await v.page.waitForTimeout(250)
Expand Down
130 changes: 129 additions & 1 deletion e2e/focus-qa3.spec.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/** QA round 3: the keyboard after a dialog, a thumbnail, a sheet tab */
import { describe, expect, test } from 'bun:test'
import { openFile, useBrowser, viewer, type Viewer } from './harness'
import { docxParas, openFile, paraText, runsOf, useBrowser, viewer, xlsxSheet, type Viewer } from './harness'

useBrowser()

Expand Down Expand Up @@ -86,3 +86,131 @@ describe('QA 3: spreadsheets', () => {
expect(v.errors).toEqual([])
})
})

describe('a click on Save leaves the keyboard in the document', () => {
test('a document: the caret stays, Ctrl/⌘+Z undoes the typing just saved', async () => {
const v = await viewer({ src: 'samples/sample.docx', editable: true, onSave: true })
await v.page.locator('.de-ebar').waitFor()
await v.selectText('Quarterly Report', 'end')
await v.page.keyboard.type('XYZ')
await v.page.waitForTimeout(200)
await v.save()
expect((await active(v)).cls).toContain('de-pages')
await v.page.keyboard.press('ControlOrMeta+z')
await v.page.waitForTimeout(200)
expect(await v.pagesText()).not.toContain('Quarterly ReportXYZ')
expect(v.errors).toEqual([])
})

test('a document: a word an IME is still composing is in the file saved, and the typing goes on after it', async () => {
const v = await viewer({ src: 'samples/sample.docx', editable: true, onSave: true })
await v.page.locator('.de-ebar').waitFor()
await v.selectText('Quarterly Report', 'end')
await v.page.keyboard.type(' ab')
await v.page.waitForTimeout(200)
// Telex half way through a word: "việ" is still underlined when Save is clicked
const cdp = await v.page.context().newCDPSession(v.page)
await cdp.send('Input.imeSetComposition', { text: 'việ', selectionStart: 3, selectionEnd: 3 })
await v.page.waitForTimeout(200)
const lines = (await docxParas((await v.save()).bytes)).map(paraText)
expect(lines).toContain('Quarterly Report abviệ')
expect((await active(v)).cls).toContain('de-pages')
await v.page.keyboard.type('t')
await v.page.waitForTimeout(200)
expect(await v.pagesText()).toContain('Quarterly Report abviệt')
expect(v.errors).toEqual([])
})

test('a document: a font size typed in the toolbar, with no Enter, is in the file saved', async () => {
const v = await viewer({ src: 'samples/sample.docx', editable: true, onSave: true })
await v.page.locator('.de-ebar').waitFor()
await v.selectText('Quarterly Report')
const size = v.page.locator('.de-size-input')
await size.click()
await size.fill('31')
const runs = (await docxParas((await v.save()).bytes)).flatMap(runsOf)
expect(runs.find((r) => r.text.includes('Quarterly Report'))?.s.sz).toBe(31)
expect(v.errors).toEqual([])
})

test('a sheet: the grid keeps the focus, Ctrl/⌘+Z takes the cell back', async () => {
const v = await viewer({ src: 'samples/sample.xlsx', editable: true, onSave: true })
await v.page.locator('.de-ebar').waitFor()
await v.typeCell('J10', 'saved')
await v.save()
expect((await active(v)).inViewer).toBe(true)
await v.page.keyboard.press('ControlOrMeta+z')
await v.page.waitForTimeout(300)
expect(await v.shown('J10')).toBe('')
expect(v.errors).toEqual([])
})

test('a sheet: a cell still being typed in, in the cell or the formula bar, is written into the file saved', async () => {
const v = await viewer({ src: 'samples/sample.xlsx', editable: true, onSave: true })
await v.page.locator('.de-ebar').waitFor()
// no Enter: the edit is still open when Save is clicked
await v.clickCell('J10')
await v.page.keyboard.type('typed, then Save')
expect((await xlsxSheet((await v.save()).bytes)).cell('J10')).toBe('typed, then Save')
expect((await active(v)).inViewer).toBe(true)
await v.clickCell('J11')
await v.page.locator('.de-fx-input').click()
await v.page.keyboard.type('in the bar, then Save')
const s = await xlsxSheet((await v.save()).bytes)
expect(s.cell('J10')).toBe('typed, then Save')
expect(s.cell('J11')).toBe('in the bar, then Save')
// the edit is closed: Ctrl/⌘+Z takes the last cell back
await v.page.keyboard.press('ControlOrMeta+z')
await v.page.waitForTimeout(300)
expect(await v.shown('J11')).toBe('')
expect(v.errors).toEqual([])
})

test('a sheet: a sheet name still being typed is the one saved', async () => {
const v = await viewer({ src: 'samples/sample.xlsx', editable: true, onSave: true })
await v.page.locator('.de-ebar').waitFor()
await v.page.locator('.de-tab').filter({ hasText: 'Sales' }).dblclick()
await v.page.locator('.de-tab-input').waitFor()
await v.page.keyboard.press('ControlOrMeta+a')
await v.page.keyboard.type('Renamed')
expect((await xlsxSheet((await v.save()).bytes)).names).toEqual(['Renamed', 'Notes', 'Data'])
expect(v.errors).toEqual([])
})

test('slides: Ctrl/⌘+Z takes back the text typed in a shape', async () => {
const v = await viewer({ src: 'samples/sample.pptx', editable: true, onSave: true })
await v.page.locator('.de-ebar').waitFor()
const slide = v.page.locator('.de-slide-frame').first()
await slide.getByText('office-engine').first().click()
await v.page.locator('.de-txt-edit').waitFor()
await v.page.keyboard.press('ControlOrMeta+a')
await v.page.keyboard.type('Saved title')
await v.page.keyboard.press('Escape')
await v.page.keyboard.press('Escape')
await v.page.waitForTimeout(300)
await v.save()
expect((await active(v)).cls).toContain('de-scroll')
await v.page.keyboard.press('ControlOrMeta+z')
await v.page.waitForFunction(() => !document.querySelector('.de-slide-frame')?.textContent?.includes('Saved title'))
expect(await slide.innerText()).toContain('office-engine')
expect(v.errors).toEqual([])
})

test('saving: the button is shown as busy but keeps a keyboard focus it had', async () => {
const v = await viewer({ src: 'samples/sample.docx', editable: true, onSave: true })
await v.page.locator('.de-ebar').waitFor()
await v.selectText('Quarterly Report', 'end')
await v.page.keyboard.type('!')
await v.page.waitForTimeout(200)
const button = v.barButton('Save')
await button.focus()
const n = await saves(v)
await v.page.keyboard.press('Enter')
await v.waitEvent('save', n + 1)
await v.page.waitForTimeout(100)
const a = await active(v)
expect(a.tag).toBe('BUTTON')
expect(a.inViewer).toBe(true)
expect(v.errors).toEqual([])
})
})
3 changes: 1 addition & 2 deletions e2e/markdown-math.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -124,8 +124,7 @@ describe('Markdown math in the document', () => {
// (the paragraph is written again: its dollar signs are escaped only where they would be read as math)
expect(saved).toContain('Euler’s identity: $e^{i\\pi} + 1 = 0$It costs $5 and $10, see `$x$`.')
expect(saved).toContain('Euler’s identity: $e^{i\\pi} + 1 = 0$ is famous.')
// (Save took the focus)
await v.selectText('It costs', 'start')
// (Save left the focus in the document)
await page.keyboard.press('Control+z')
await page.waitForTimeout(300)
expect(await inline()).toBe(3)
Expand Down
6 changes: 1 addition & 5 deletions e2e/pptx.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,11 +77,7 @@ describe('pptx editing', () => {
expect(s1.meta.count).toBe(5)
expect((await s1.slide(0)).els.some((e: any) => e.geom === 'rect' && e.fill?.c === '#00ff00')).toBe(true)

// Save took the focus: select the shape again (it is the topmost at the slide center)
const f = (await slide1(v).boundingBox())!
await v.page.mouse.click(f.x + f.width / 2, f.y + f.height / 2)
// a click on a shape with a text body edits its text: Esc keeps the shape selected
if (await v.page.locator('.de-txt-edit').count()) await stopEditing(v)
// Save left the shape selected
await v.btn('Delete').waitFor()
await v.btn('Delete').click()
await v.page.waitForTimeout(300)
Expand Down
3 changes: 1 addition & 2 deletions e2e/xlsx.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1087,8 +1087,7 @@ describe('xlsx whole columns and rows (QA 19/11/2026, P2-042)', () => {
// the column holds what was typed and where the row crosses it, not a cell per row
expect((xml.match(/<c r="M\d+"/g) ?? []).length).toBeLessThan(10)

// Undo takes the formats back, one at a time (the Save button has the focus: back to the grid)
await v.clickCell('J10')
// Undo takes the formats back, one at a time (Save left the focus in the grid)
await v.page.keyboard.press('Control+z')
await v.page.waitForTimeout(300)
expect((await cellBox(v, 'K22'))?.style ?? '').not.toMatch(yellow)
Expand Down
31 changes: 30 additions & 1 deletion src/react/DocViewer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -519,6 +519,25 @@ function Viewer(props: DocViewerProps) {
handle.addEventListener('pointercancel', up)
}
const rootRef = useRef<HTMLDivElement>(null)
/**
* A click on Save leaves the focus in the field it is in. What that field writes as it loses the focus is written
* first, as when the button took the focus: a cell or a sheet's name being typed, a font size, the word an IME is
* composing. Then the focus goes back to the field, unless its blur put it elsewhere (a cell gives it to its grid)
* or the field went away with its edit (a sheet's name).
*/
const saveFromBar = async () => {
const root = rootRef.current
const scope = root?.getRootNode() as Document | ShadowRoot | undefined
const field = scope?.activeElement as HTMLElement | null | undefined
if (root && field && root.contains(field) && isTextEntry(field)) {
field.blur()
// the field's edit renders before the focus goes back
await new Promise((r) => setTimeout(r))
const now = scope!.activeElement
if ((!now || !root.contains(now)) && field.isConnected) field.focus({ preventScroll: true })
}
await save()
}
// captureSelectAll: Ctrl/⌘+A from the rest of the page too (the viewer's own keys are handled in onKeyDown below)
useEffect(() => {
const root = rootRef.current
Expand Down Expand Up @@ -763,7 +782,17 @@ function Viewer(props: DocViewerProps) {
</button>
)}
{client && canSave && ((editing && !readOnly) || dirty) && (
<button type="button" className={dirty ? 'de-mode de-save-dirty' : 'de-mode'} disabled={saving} onClick={() => void save()} title={t.bar.saveTitle}>
// a click leaves the focus in the document (as the toolbar's buttons do), so Ctrl/⌘+Z goes on undoing there;
// aria-disabled, not disabled, while it saves: a disabled button loses the focus to the page, out of the viewer
// (a second save is refused by saveFile itself)
<button
type="button"
className={dirty ? 'de-mode de-save-dirty' : 'de-mode'}
aria-disabled={saving}
onMouseDown={(e) => e.preventDefault()}
onClick={() => void saveFromBar()}
title={t.bar.saveTitle}
>
<Icon name="save" size={16} />
{saving ? t.bar.saving : dirty || onSave ? t.bar.save : t.bar.download}
</button>
Expand Down
2 changes: 1 addition & 1 deletion src/react/styles.css
Original file line number Diff line number Diff line change
Expand Up @@ -705,7 +705,7 @@
.de-mode-on { border-color: var(--de-accent); color: var(--de-accent); }
.de-save-dirty { background: var(--de-accent); border-color: var(--de-accent); color: var(--de-accent-ink); }
.de-save-dirty:hover { background: var(--de-accent-hover); }
.de-mode:disabled { opacity: 0.6; cursor: default; }
.de-mode:disabled, .de-mode[aria-disabled='true'] { opacity: 0.6; cursor: default; }
.de-ebar-host {
flex: none;
padding: 6px 10px;
Expand Down
15 changes: 14 additions & 1 deletion src/react/xlsx/XlsxView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -388,7 +388,11 @@ export function XlsxView({ client, onStatus, initialSheet }: XlsxViewProps) {
// The workbook owns completion publication even when the grid that began the edit changed sheets.
// Layout cleanup removes this listener before a replacement document can receive late dirty state.
useLayoutEffect(() => store.onEdit(() => viewer.setDirty(true)), [store, viewer.setDirty])
/** the shown grid's: writes the cell being typed in and waits for its last edit (set by the grid as it renders) */
const flushGrid = useRef<() => Promise<void>>(() => Promise.resolve())
useFileOps({
// a save or an export that does not blur the cell being typed in (the host's own, through the controller, at any time): it is written first
flush: () => flushGrid.current(),
printable: () => sheetPrintable(client, cur, store.sheet(cur), meta, str),
text: (format) => client.call('xlsx.text', cur, format === 'tsv' ? '\t' : ','),
stats: () => {
Expand Down Expand Up @@ -564,6 +568,7 @@ export function XlsxView({ client, onStatus, initialSheet }: XlsxViewProps) {
edit={edit}
setEdit={setEdit}
hold={hold}
flush={flushGrid}
onSheet={setActive}
gotoSheet={gotoSheet}
/>
Expand Down Expand Up @@ -660,6 +665,8 @@ interface GridProps {
edit: EditState | null
setEdit: React.Dispatch<React.SetStateAction<EditState | null>>
hold: MutableRefObject<boolean>
/** set to what writes the cell being typed in and waits for the last edit sent, before the document is saved */
flush: MutableRefObject<() => Promise<void>>
onSheet: (i: number) => void
gotoSheet: (id: string) => void
}
Expand Down Expand Up @@ -856,7 +863,7 @@ export function withMerges(r: Range, merges: Merge[]): Range {
/** the hidden input field of a grid at rest: inside the view, so that nothing scrolls to it */
const SINK_STYLE: CSSProperties = { left: 4, top: 4, width: 1, height: 1 }

function SheetGrid({ store, sheet, meta, client, edit, setEdit, hold, onSheet, gotoSheet }: GridProps) {
function SheetGrid({ store, sheet, meta, client, edit, setEdit, hold, flush, onSheet, gotoSheet }: GridProps) {
const viewer = useViewer()
const str = useStrings()
const editable = viewer.editable
Expand Down Expand Up @@ -1509,6 +1516,12 @@ function SheetGrid({ store, sheet, meta, client, edit, setEdit, hold, onSheet, g
focusGrid()
}

// before a save: the cell being typed in is written (as Enter would) and the edits sent are waited for
flush.current = async () => {
commit()
await lastRun.current
}

/** Ctrl+Enter: the entry goes into every cell of the selection (a formula keeps its relative references) */
const commitFill = () => {
const e = edit
Expand Down