Skip to content
Open
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
7 changes: 7 additions & 0 deletions .changeset/table-soft-wrap-arrow-keys.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
'@lexical/table': patch
---

[fix] Arrow keys at a soft wrap in a table cell move to the right line or cell

Verify: in a table cell whose text wraps, put the caret at the start of the last visual line and press ArrowDown: it moves to the cell below. Put it at a wrap boundary and press ArrowUp: it moves up one visual line instead of jumping out of the table. In a first-row cell with nothing above the table, ArrowUp from the end of the first line moves to the start of that line and a second press leaves the table. Home, End and clicks on either side of the wrap keep their behavior.
46 changes: 46 additions & 0 deletions packages/lexical-table/src/LexicalTableObserver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,32 @@ export type TableNextFocus = {
override: boolean;
};

/**
* A vertical arrow key was pressed with the caret at an ambiguous soft wrap
* boundary (where "end of line N" and "start of line N+1" are the same DOM
* position and the caret's affinity is not exposed in the DOM), so the
* native movement was allowed to run. If the resulting selection leaves the
* original cell's column it must be corrected to the cell at x,y.
*/
export type TablePendingVerticalExit = {
/**
* The DOM position of the caret when the exit was armed. The correction
* only applies to the selection change the deferred native movement
* causes, and that movement is the one that takes the DOM selection away
* from this position: a selection change made by code or a collaborator
* dispatches while the DOM selection still sits here, so it must not be
* corrected.
*/
domAnchorNode: Node;
domAnchorOffset: number;
direction: 'up' | 'down';
tableKey: NodeKey;
/** The cell the arrow key was pressed in. */
cellKey: NodeKey;
x: number;
y: number;
};

/**
* Tracks table selection state that sits across all tables.
*/
Expand All @@ -102,6 +128,7 @@ export class TableObservers {
>;
nextFocus: TableNextFocus | null;
shouldCheckSelectionForTable: NodeKey | null;
pendingVerticalExit: TablePendingVerticalExit | null;
/** The last touch-tapped cell, retained after pointerup for native word selection. */
touchTapCellKey: NodeKey | null;

Expand All @@ -112,6 +139,7 @@ export class TableObservers {
>();
this.nextFocus = null;
this.shouldCheckSelectionForTable = null;
this.pendingVerticalExit = null;
this.touchTapCellKey = null;
}

Expand Down Expand Up @@ -159,6 +187,24 @@ export class TableObservers {
return null;
}

/**
* @internal
*/
setPendingVerticalExit(pendingVerticalExit: TablePendingVerticalExit): void {
this.pendingVerticalExit = pendingVerticalExit;
}
/**
* @internal
*/
getAndClearPendingVerticalExit(): TablePendingVerticalExit | null {
const {pendingVerticalExit} = this;
if (pendingVerticalExit !== null) {
this.pendingVerticalExit = null;
return pendingVerticalExit;
}
return null;
}

/**
* @internal
* Remove the observer for tableKey from the registry and unregister all
Expand Down
171 changes: 165 additions & 6 deletions packages/lexical-table/src/LexicalTableSelectionHelpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ import {
isDOMDocumentNode,
isDOMNode,
isDOMShadowRoot,
isDOMTextNode,
isHTMLElement,
KEY_ARROW_DOWN_COMMAND,
KEY_ARROW_LEFT_COMMAND,
Expand Down Expand Up @@ -266,6 +267,12 @@ export function registerTableWindowHandlers(

const pointerDownCallback = (event: PointerEvent) => {
tableObservers.touchTapCellKey = null;
// A pointer interaction invalidates a pending vertical exit armed by a
// vertical arrow key at a soft wrap: if the deferred native movement
// never happened, the next selection change is this pointer one and
// must not be corrected. Cleared before the checks so any button and
// any target invalidate it.
tableObservers.pendingVerticalExit = null;
// Listener is on editorWindow; the composed target is needed so the
// rootElement.contains check below sees the shadow-internal target.
const target = getComposedEventTarget(event);
Expand Down Expand Up @@ -311,19 +318,24 @@ export function registerTableWindowHandlers(
});
};

const clearTouchTap = () => {
// Keydown and blur clear pending interaction state in the capture
// phase, before any key handler can extend the selection or stop
// propagation: a later keyboard selection is not a tap, and a keydown
// that does not move the caret (Alt+ArrowDown does not on Linux and
// Windows) must not leave a pending vertical exit armed for the next,
// unrelated selection change to correct.
const clearPendingInteraction = () => {
tableObservers.touchTapCellKey = null;
tableObservers.pendingVerticalExit = null;
};
return mergeRegister(
registerEventListener(editorWindow, 'pointerdown', pointerDownCallback),
// Clear before a key handler can extend the selection, including when
// that handler stops propagation. A later keyboard selection is not a tap.
registerEventListeners(
editorWindow,
{blur: clearTouchTap, keydown: clearTouchTap},
{blur: clearPendingInteraction, keydown: clearPendingInteraction},
{capture: true},
),
clearTouchTap,
clearPendingInteraction,
);
});
}
Expand Down Expand Up @@ -1337,6 +1349,79 @@ export function $handleTableSelectionChangeCommand(
}
}
}
const pendingVerticalExit = tableObservers.getAndClearPendingVerticalExit();
// A vertical arrow key was pressed with the caret at an ambiguous soft
// wrap boundary, so the native movement ran with the engine's own
// affinity. If the caret left the original cell's column it was placed
// outside the cell (or outside the table): move it to the cell the exit
// detection would have chosen. Within the column the native movement
// found a line of the same cell, which is correct.
if (
pendingVerticalExit !== null &&
$isRangeSelection(selection) &&
selection.isCollapsed()
) {
// The correction is only for the selection change the deferred native
// movement causes: the engine moves the DOM selection before Lexical
// dispatches the command for it, while a selection change made by code
// or a collaborator dispatches before reconciliation writes the DOM
// selection. When the DOM selection still sits at the armed caret, the
// native movement never happened (a modifier combo that moves nothing,
// for example) and the intent is void.
const domSelection = getDOMSelection(getEditorWindow(editor));
const domRange =
domSelection === null || domSelection.rangeCount === 0
? null
: getDOMSelectionRange(domSelection, editor.getRootElement());
const nativeMovement =
domRange !== null &&
(domRange.startContainer !== pendingVerticalExit.domAnchorNode ||
domRange.startOffset !== pendingVerticalExit.domAnchorOffset);
// The table may have been removed before this selection change was
// dispatched, in which case there is nothing to correct. A grid whose
// armed cell is gone is stale: correcting from its coordinates would
// throw or land at a wrong cell.
const tableNode = $getNodeByKey(pendingVerticalExit.tableKey);
const observerAndTable = tableObservers.observers.get(
pendingVerticalExit.tableKey,
);
const originCellNode = $getNodeByKey(pendingVerticalExit.cellKey);
if (
nativeMovement &&
$isTableNode(tableNode) &&
observerAndTable !== undefined &&
$isTableCellNode(originCellNode)
) {
const [tableObserver] = observerAndTable;
// A native landing inside the armed cell's own subtree (a nested
// table under the cell's text, for example) is a line of the same
// cell: trust it like a same-column landing.
const anchorInOriginCell =
$findMatchingParent(selection.anchor.getNode(), node =>
node.is(originCellNode),
) !== null;
if (!anchorInOriginCell) {
const anchorCellNode = $findCellNode(selection.anchor.getNode());
const leftTheColumn =
!(
$isTableCellNode(anchorCellNode) &&
tableNode.is($findTableNode(anchorCellNode))
) ||
tableNode.getCordsFromCellNode(anchorCellNode, tableObserver.table)
.x !== pendingVerticalExit.x;
if (leftTheColumn) {
selectTableNodeInDirection(
tableObserver,
tableNode,
pendingVerticalExit.x,
pendingVerticalExit.y,
pendingVerticalExit.direction,
);
return true;
}
}
}
}

if ($isTableSelection(selection)) {
$fixTableSelectionForSelectedTable(editor, selection);
Expand Down Expand Up @@ -2399,6 +2484,46 @@ function $isSelectionBeforeTable(
);
}

/**
* Returns the rect of the visual line the caret's adjacent character renders
* on, or null when it cannot be measured. A collapsed range at a soft wrap
* reports its rect at the end of the previous line while the adjacent
* character renders on the next one, so comparing the two detects the
* ambiguous wrap boundary, where only the caret's affinity (not exposed in
* the DOM) tells the two positions apart. The character to the left is
* measured when the caret ends its text node; engines without layout (such
* as jsdom) get null and the caller keeps the collapsed range's own rect.
* The measurement stays within the start container, so a wrap whose next
* line starts a new text node is not detected as ambiguous.
*/
function getVisualLineRectAtCaret(range: Range): DOMRect | null {
if (typeof range.getClientRects !== 'function') {
return null;
}
const {startContainer, startOffset} = range;
if (!isDOMTextNode(startContainer)) {
return null;
}
const {length} = startContainer.data;
// The range may alias the live selection, so mutate a clone only
const characterRange = range.cloneRange();
for (const [start, end] of [
[startOffset, startOffset + 1],
[startOffset - 1, startOffset],
]) {
if (start < 0 || end > length || start >= end) {
continue;
}
characterRange.setStart(startContainer, start);
characterRange.setEnd(startContainer, end);
const rects = characterRange.getClientRects();
Comment thread
lou-magnenat marked this conversation as resolved.
Resolved
if (rects.length > 0) {
return rects[rects.length - 1];
}
}
Comment thread
lou-magnenat marked this conversation as resolved.
Resolved
return null;
}

function $handleArrowKey(
editor: LexicalEditor,
event: KeyboardEvent,
Expand Down Expand Up @@ -2679,7 +2804,41 @@ function $handleArrowKey(
if (range === null) {
return false;
}
edgeSelectionRect = range.getBoundingClientRect();
// A collapsed range at a soft wrap sits between two visual lines:
// "end of line N" and "start of line N+1" are the same DOM position,
// and only the caret's affinity, which the DOM does not expose,
// tells them apart. The collapsed range always reports its rect at
// the end of the previous line, so when the adjacent character
// renders on a different line the position is ambiguous: rather
// than guess the affinity, let the native movement run and correct
// the landing if it leaves the cell's column (see
// $handleTableSelectionChangeCommand). This deferral is
// collapsed-caret only: with shift, the keypress extends the
// selection and the correction cannot repair a non-collapsed
// landing, so the pre-existing caret-rect behavior is kept there.
const caretRect = range.getBoundingClientRect();
const adjacentCharacterRect = getVisualLineRectAtCaret(range);
if (
!event.shiftKey &&
adjacentCharacterRect !== null &&
Math.abs(adjacentCharacterRect.top - caretRect.top) > 4
) {
const cords = tableNode.getCordsFromCellNode(
anchorCellNode,
tableObserver.table,
);
tableObservers.setPendingVerticalExit({
cellKey: anchorCellNode.getKey(),
direction,
domAnchorNode: range.startContainer,
domAnchorOffset: range.startOffset,
tableKey: tableNode.getKey(),
x: cords.x,
y: cords.y,
});
return false;
Comment thread
lou-magnenat marked this conversation as resolved.
Resolved
}
edgeSelectionRect = caretRect;
}

const edgeChild =
Expand Down
Loading