33 lines
1.5 KiB
TypeScript
33 lines
1.5 KiB
TypeScript
import { Prec } from "@codemirror/state";
|
|
import { keymap } from "@codemirror/view";
|
|
import { tableEditors } from "./tableControls";
|
|
|
|
// Tables are atomic in the prose editor. Intercept a movement that would cross
|
|
// one before CodeMirror skips the widget, and hand focus to its cell editor.
|
|
export const tableNavigation = Prec.high(keymap.of(["ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown"].map(key => ({
|
|
key,
|
|
run(view) {
|
|
const selection = view.state.selection.main;
|
|
if (!view.hasFocus || !selection.empty || view.state.selection.ranges.length !== 1) return false;
|
|
const forward = key === "ArrowRight" || key === "ArrowDown";
|
|
const vertical = key === "ArrowUp" || key === "ArrowDown";
|
|
const next = vertical ? view.moveVertically(selection, forward) : view.moveByChar(selection, forward);
|
|
const previews = [...view.dom.querySelectorAll<HTMLElement>(".writer-preview")];
|
|
if (!forward) previews.reverse();
|
|
for (const root of previews) {
|
|
const table = tableEditors.get(root);
|
|
if (!table) continue;
|
|
const from = view.posAtDOM(root), to = from + table.source.length;
|
|
const crosses = forward
|
|
? selection.head <= from && next.head >= from
|
|
: selection.head >= to && next.head <= to;
|
|
if (!crosses) continue;
|
|
const goal = selection.goalColumn ?? next.goalColumn;
|
|
const x = goal === undefined ? view.coordsAtPos(selection.head)?.left : view.contentDOM.getBoundingClientRect().left + goal;
|
|
table.enter(forward, vertical ? x : undefined);
|
|
return true;
|
|
}
|
|
return false;
|
|
},
|
|
}))));
|