fix(docs): improve trailing table editing (#272)

* fix(docs): allow typing after trailing tables

* fix(docs): use text cursor after trailing tables

* fix(docs): delete empty tables from cell cursor

* fix(docs): keep inserted tables at section width
This commit is contained in:
NIHoa
2026-09-10 11:51:32 +08:00
committed by GitHub
parent a5ed6f8cf0
commit f2f5fbd454
6 changed files with 319 additions and 3 deletions
@@ -220,6 +220,8 @@ export function insertTableAt(editor: Editor, rows: number, cols: number): void
const table = {
rows: Array.from({ length: rows }, () => Array.from({ length: cols }, () => ({ paras: [''] }))),
colWidthsPct: Array.from({ length: cols }, () => 100 / cols),
widthPct: 100,
autoFit: 'window' as const,
borders: { top: line, bottom: line, left: line, right: line, insideH: line, insideV: line },
}
// inside a cell a top-level docTable insert would split the outer table
+25 -2
View File
@@ -1,6 +1,6 @@
import { Editor, Extension, Node } from '@tiptap/core'
import type { ChainedCommands, RawCommands } from '@tiptap/core'
import { UndoRedo } from '@tiptap/extensions'
import { Gapcursor, UndoRedo } from '@tiptap/extensions'
import { DOMSerializer } from '@tiptap/pm/model'
import type { DOMOutputSpec, Node as PmNode } from '@tiptap/pm/model'
import {
@@ -158,6 +158,7 @@ import { AutoDirectionExtension } from './direction'
import { InactiveSelectionExtension } from './inactive-selection'
import { AiQueueAnchorsExtension } from './ai-queue-anchors'
import { PageGapNavExtension } from './page-gap-nav'
import { TrailingTableExitExtension } from './trailing-table-exit'
import { moveBlocks } from './move-block'
import {
foldQuarterTurnMargins,
@@ -2796,12 +2797,32 @@ export const DocNestedTable = Node.create({
},
})
/** Delete only an explicitly selected whole table; leave cursors and partial cell selections alone. */
function emptyTopLevelTableAtCursor(state: EditorState): { from: number; to: number } | null {
const { selection } = state
if (!(selection instanceof TextSelection) || !selection.empty) return null
const table = selection.$from.node(1)
if (table.type.name !== 'docTable') return null
let hasLeaf = false
table.descendants((node) => {
if (node.isLeaf) hasLeaf = true
return !hasLeaf
})
if (hasLeaf) return null
const from = selection.$from.before(1)
return { from, to: from + table.nodeSize }
}
/** Delete a selected table, or a completely empty table under a text cursor. */
export function deleteSelectedWholeTable(
state: EditorState,
dispatch?: (transaction: Transaction) => void,
): boolean {
const { selection } = state
const emptyTable = emptyTopLevelTableAtCursor(state)
if (emptyTable) {
dispatch?.(state.tr.delete(emptyTable.from, emptyTable.to).scrollIntoView())
return true
}
if (selection instanceof NodeSelection) {
if (selection.node.type.spec.tableRole !== 'table') return false
dispatch?.(state.tr.delete(selection.from, selection.to).scrollIntoView())
@@ -5527,6 +5548,8 @@ export const editorExtensions = [
InactiveSelectionExtension,
AiQueueAnchorsExtension,
PageGapNavExtension,
TrailingTableExitExtension,
Gapcursor,
ImageCopyExtension,
EnterReplacesSelection,
AutoLinkOnDelimiter,
@@ -0,0 +1,38 @@
import { Extension } from '@tiptap/core'
import { GapCursor } from '@tiptap/pm/gapcursor'
import { Plugin, PluginKey, TextSelection } from '@tiptap/pm/state'
const key = new PluginKey('trailingTableExit')
export const TrailingTableExitExtension = Extension.create({
name: 'trailingTableExit',
addProseMirrorPlugins() {
const editor = this.editor
return [
new Plugin({
key,
appendTransaction(transactions, oldState, newState) {
if (
!editor.view.editable ||
oldState.doc !== newState.doc ||
!(newState.selection instanceof GapCursor) ||
newState.selection.from !== newState.doc.content.size ||
newState.doc.lastChild?.type.name !== 'docTable' ||
!transactions.some((transaction) => transaction.selectionSet && !transaction.docChanged)
) {
return null
}
const paragraph = newState.schema.nodes.docParagraph?.createAndFill()
if (!paragraph) return null
const pos = newState.doc.content.size
const transaction = newState.tr.insert(pos, paragraph)
return transaction
.setSelection(TextSelection.create(transaction.doc, pos + 1))
.scrollIntoView()
},
}),
]
},
})
+27
View File
@@ -2205,6 +2205,33 @@ th.cell-rev-del {
text;
}
/* gap cursor between isolating blocks, such as a final table */
.ProseMirror-gapcursor {
display: none;
pointer-events: none;
position: absolute;
}
.ProseMirror-gapcursor::after {
content: '';
display: block;
position: absolute;
top: -2px;
width: 20px;
border-top: 1px solid var(--docs-paper-ink, currentColor);
animation: ProseMirror-cursor-blink 1.1s steps(2, start) infinite;
}
@keyframes ProseMirror-cursor-blink {
to {
visibility: hidden;
}
}
.ProseMirror-focused .ProseMirror-gapcursor {
display: block;
}
/* ---- Word basics: marks / columns / page border / header-footer / nav / ruler ---- */
/* ¶ editing marks (front-end only) */
+38
View File
@@ -40,6 +40,44 @@ async function saveAndUnzip(editor: Editor, parsed: Awaited<ReturnType<typeof pa
return { bytes, xml }
}
function topLevelTable(editor: Editor) {
for (let index = 0; index < editor.state.doc.childCount; index++) {
const node = editor.state.doc.child(index)
if (node.type.name === 'docTable') return node
}
throw new Error('Expected a top-level table')
}
describe('new top-level table sizing', () => {
it('fills the section content width through save and reload', async () => {
const { editor, parsed } = await openBlank()
insertTableAt(editor, 2, 2)
const inserted = topLevelTable(editor)
expect(inserted.attrs.tblAutoFit).toBe('window')
expect(inserted.attrs.widthPct).toBe(100)
expect(inserted.attrs.widthPx).toBeNull()
const { bytes, xml } = await saveAndUnzip(editor, parsed)
expect(xml).toContain('<w:tblW w:w="5000" w:type="pct"/>')
expect(xml).toContain('<w:tblLayout w:type="autofit"/>')
const reparsed = await parseDocx(bytes)
const reloaded = new Editor({
element: document.createElement('div'),
extensions: editorExtensions,
content: blocksToPmDoc(reparsed.blocks) as never,
})
const reopened = topLevelTable(reloaded)
expect(reopened.attrs.tblAutoFit).toBe('window')
expect(reopened.attrs.widthPct).toBe(100)
expect(reopened.attrs.widthPx).toBeNull()
expect(reopened.attrs.colWidthsPct).toEqual([50, 50])
reloaded.destroy()
editor.destroy()
})
})
describe('list toggle inside a table cell', () => {
it('setNode docListItem succeeds in a cell and saves w:numPr into the tc', async () => {
const { editor, parsed } = await openBlank()
+189 -1
View File
@@ -12,7 +12,7 @@ import { NodeSelection, TextSelection } from '@tiptap/pm/state'
import { parseDocx, saveDocx } from '@genoffice/docx-engine'
import { readFileSync } from 'node:fs'
import { resolve } from 'node:path'
import { describe, expect, it } from 'vitest'
import { describe, expect, it, vi } from 'vitest'
import { buildDocx } from '../../../packages/docx-engine/tests/helpers/build-docx'
import {
blocksToPmDoc,
@@ -63,7 +63,195 @@ async function openTable(): Promise<{
return { editor, parsed, source }
}
function openEmptyTable(): Editor {
return new Editor({
element: document.createElement('div'),
extensions: editorExtensions,
content: {
type: 'doc',
content: [
{
type: 'docTable',
content: [
{
type: 'docTableRow',
content: [{ type: 'docTableCell', content: [{ type: 'docParagraph' }] }],
},
],
},
],
} as never,
})
}
function selectFirstCellStart(editor: Editor): void {
const firstCell = cellPositions(editor)[0]
editor.view.dispatch(
editor.state.tr.setSelection(TextSelection.create(editor.state.doc, firstCell + 2)),
)
}
function tableHasLeafContent(editor: Editor): boolean {
let hasLeaf = false
editor.state.doc.firstChild?.descendants((node) => {
if (node.isLeaf) hasLeaf = true
return !hasLeaf
})
return hasLeaf
}
function selectLastCellTextEnd(editor: Editor): void {
let lastCellTextEnd = 0
editor.state.doc.descendants((node, pos) => {
if (node.isText && node.text === 'D') lastCellTextEnd = pos + node.nodeSize
})
editor.view.dispatch(
editor.state.tr.setSelection(TextSelection.create(editor.state.doc, lastCellTextEnd)),
)
}
function pressKey(editor: Editor, key: string): void {
const event = new KeyboardEvent('keydown', { key, bubbles: true, cancelable: true })
editor.view.someProp('handleKeyDown', (handler) => handler(editor.view, event))
}
function clickBelowTrailingTable(editor: Editor): void {
const event = new MouseEvent('mousedown', { button: 0, bubbles: true, cancelable: true })
Object.defineProperty(event, 'target', { value: editor.view.dom })
vi.spyOn(editor.view, 'posAtCoords').mockReturnValue({
pos: editor.state.doc.content.size,
inside: -1,
})
editor.view.someProp('handleClick', (handler) =>
handler(editor.view, editor.state.doc.content.size, event),
)
}
describe('native editable tables', () => {
it('deletes a completely empty table with Backspace and Delete', () => {
for (const key of ['Backspace', 'Delete']) {
const editor = openEmptyTable()
selectFirstCellStart(editor)
expect(tableHasLeafContent(editor)).toBe(false)
pressKey(editor, key)
expect(editor.state.doc.firstChild?.type.name).not.toBe('docTable')
editor.destroy()
}
})
it('keeps a non-empty table when the current cell is empty', async () => {
const { editor } = await openTable()
const firstCell = cellPositions(editor)[0]
const transaction = editor.state.tr.delete(firstCell + 2, firstCell + 3)
editor.view.dispatch(
transaction.setSelection(TextSelection.create(transaction.doc, firstCell + 2)),
)
pressKey(editor, 'Backspace')
expect(editor.state.doc.firstChild?.type.name).toBe('docTable')
expect(editor.state.doc.textContent).toContain('B')
editor.destroy()
})
it('keeps a table with a non-text leaf even when its text is empty', () => {
const editor = openEmptyTable()
selectFirstCellStart(editor)
editor.view.dispatch(
editor.state.tr.replaceSelectionWith(editor.schema.nodes.hardBreak.create()),
)
expect(editor.state.doc.textContent).toBe('')
expect(tableHasLeafContent(editor)).toBe(true)
pressKey(editor, 'Backspace')
expect(editor.state.doc.firstChild?.type.name).toBe('docTable')
editor.destroy()
})
it('restores an empty table when undoing its deletion', () => {
const editor = openEmptyTable()
selectFirstCellStart(editor)
pressKey(editor, 'Backspace')
expect(editor.state.doc.firstChild?.type.name).not.toBe('docTable')
expect(editor.commands.undo()).toBe(true)
expect(editor.state.doc.firstChild?.type.name).toBe('docTable')
expect(tableHasLeafContent(editor)).toBe(false)
editor.destroy()
})
it('allows typing after an imported trailing table', async () => {
const { editor } = await openTable()
selectLastCellTextEnd(editor)
vi.spyOn(editor.view, 'endOfTextblock').mockImplementation((dir) => dir === 'down')
vi.spyOn(editor.view, 'coordsAtPos').mockReturnValue({ left: 0, right: 0, top: 0, bottom: 0 })
pressKey(editor, 'ArrowDown')
expect(editor.state.doc.lastChild?.type.name).toBe('docParagraph')
expect(editor.state.doc.lastChild?.content.size).toBe(0)
expect(editor.state.selection).toBeInstanceOf(TextSelection)
expect(editor.state.selection.$from.parent.type.name).toBe('docParagraph')
editor.commands.insertContent('below')
expect(editor.state.doc.lastChild?.type.name).toBe('docParagraph')
expect(editor.state.doc.lastChild?.textContent).toBe('below')
editor.destroy()
})
it('clicking below an imported trailing table places a text cursor in a new paragraph', async () => {
const { editor } = await openTable()
clickBelowTrailingTable(editor)
expect(editor.state.doc.lastChild?.type.name).toBe('docParagraph')
expect(editor.state.doc.lastChild?.content.size).toBe(0)
expect(editor.state.selection).toBeInstanceOf(TextSelection)
expect(editor.state.selection.$from.parent.type.name).toBe('docParagraph')
editor.commands.insertContent('below-click')
expect(editor.state.doc.lastChild?.textContent).toBe('below-click')
editor.destroy()
})
it('does not add a second paragraph when clicking below a trailing table with one already', async () => {
const { editor } = await openTable()
const pos = editor.state.doc.content.size
const paragraph = editor.schema.nodes.docParagraph.create()
const transaction = editor.state.tr.insert(pos, paragraph)
editor.view.dispatch(transaction.setSelection(TextSelection.create(transaction.doc, pos + 1)))
const childCount = editor.state.doc.childCount
clickBelowTrailingTable(editor)
expect(editor.state.doc.childCount).toBe(childCount)
expect(editor.state.doc.lastChild?.type.name).toBe('docParagraph')
editor.destroy()
})
it('undoing a trailing-table exit does not recreate its paragraph', async () => {
const { editor } = await openTable()
selectLastCellTextEnd(editor)
vi.spyOn(editor.view, 'endOfTextblock').mockImplementation((dir) => dir === 'down')
vi.spyOn(editor.view, 'coordsAtPos').mockReturnValue({ left: 0, right: 0, top: 0, bottom: 0 })
pressKey(editor, 'ArrowDown')
expect(editor.state.doc.lastChild?.type.name).toBe('docParagraph')
expect(editor.commands.undo()).toBe(true)
expect(editor.state.doc.lastChild?.type.name).toBe('docTable')
expect(editor.state.doc.childCount).toBe(1)
editor.destroy()
})
it('redistributes requested column widths within the section content box', () => {
expect(fitColumnWidths([200, 200, 200], new Map([[0, 500]]), 600)).toEqual([500, 50, 50])
const many = fitColumnWidths(new Array(20).fill(100), new Map([[0, 1000]]), 600)