Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
Clamp spreadsheet arrow-key navigation at sheet edges
Elian Doran202b4d1da0f4
diff --git a/apps/client/src/widgets/type_widgets/spreadsheet/Spreadsheet.tsx b/apps/client/src/widgets/type_widgets/spreadsheet/Spreadsheet.tsxindex 4c60f3bedd..1954c9672e 100644--- a/apps/client/src/widgets/type_widgets/spreadsheet/Spreadsheet.tsx+++ b/apps/client/src/widgets/type_widgets/spreadsheet/Spreadsheet.tsx@@ -31,6 +31,7 @@ import { useColorScheme, useEffectiveReadOnly, useTriliumEvent, useTriliumEventsimport { TypeWidgetProps } from "../type_widget";import useSpreadsheetExport from "./export";import { loadUniverLocale, UniverLocale } from "./locales";+import useClampEdgeNavigation from "./navigation";import usePersistence from "./persistence";function buildReadOnlyLocaleOverrides() {@@ -92,6 +93,7 @@ function SpreadsheetEditor({ note, noteContext, readOnly, locale }: TypeWidgetPruseInitializeSpreadsheet(containerRef, apiRef, readOnly, locale);useReleaseFillShortcuts(apiRef);+ useClampEdgeNavigation(apiRef);useDarkMode(apiRef);usePersistence(note, noteContext, apiRef, containerRef);useSpreadsheetExport(apiRef, note, noteContext);diff --git a/apps/client/src/widgets/type_widgets/spreadsheet/navigation.spec.ts b/apps/client/src/widgets/type_widgets/spreadsheet/navigation.spec.tsnew file mode 100644index 0000000000..635c3d5f7b--- /dev/null+++ b/apps/client/src/widgets/type_widgets/spreadsheet/navigation.spec.ts@@ -0,0 +1,53 @@+import { describe, expect, it } from "vitest";++import { isOutOfBoundsMove, type SelectionBounds } from "./navigation";++describe("isOutOfBoundsMove", () => {+ // A 10x10 sheet (rows/columns 0..9) with the selection on a single, interior cell.+ function boundsAt(row: number, column: number, overrides: Partial<SelectionBounds> = {}): SelectionBounds {+ return {+ startRow: row,+ endRow: row,+ startColumn: column,+ endColumn: column,+ maxRows: 10,+ maxColumns: 10,+ ...overrides+ };+ }++ it("clamps at each of the four edges (the reported wrap-around)", () => {+ expect(isOutOfBoundsMove("up", boundsAt(0, 3))).toBe(true);+ expect(isOutOfBoundsMove("down", boundsAt(9, 3))).toBe(true);+ expect(isOutOfBoundsMove("left", boundsAt(3, 0))).toBe(true);+ expect(isOutOfBoundsMove("right", boundsAt(3, 9))).toBe(true);+ });++ it("allows moves that stay within the sheet", () => {+ const interior = boundsAt(5, 5);+ expect(isOutOfBoundsMove("up", interior)).toBe(false);+ expect(isOutOfBoundsMove("down", interior)).toBe(false);+ expect(isOutOfBoundsMove("left", interior)).toBe(false);+ expect(isOutOfBoundsMove("right", interior)).toBe(false);+ });++ it("allows a move toward the opposite edge from the boundary", () => {+ // Sitting on the first row only blocks Up — Down/Left/Right must still move.+ expect(isOutOfBoundsMove("down", boundsAt(0, 3))).toBe(false);+ // Sitting in the last column only blocks Right.+ expect(isOutOfBoundsMove("left", boundsAt(3, 9))).toBe(false);+ });++ it("uses the leading edge of a multi-cell selection", () => {+ // A range spanning rows 0..2: Up is blocked (top row is 0) but Down is free+ // (bottom row 2 is not the last row).+ const topRange = boundsAt(0, 0, { endRow: 2, endColumn: 2 });+ expect(isOutOfBoundsMove("up", topRange)).toBe(true);+ expect(isOutOfBoundsMove("down", topRange)).toBe(false);++ // A range whose bottom row touches the last row blocks Down.+ const bottomRange = boundsAt(7, 0, { endRow: 9, endColumn: 2 });+ expect(isOutOfBoundsMove("down", bottomRange)).toBe(true);+ expect(isOutOfBoundsMove("up", bottomRange)).toBe(false);+ });+});diff --git a/apps/client/src/widgets/type_widgets/spreadsheet/navigation.ts b/apps/client/src/widgets/type_widgets/spreadsheet/navigation.tsnew file mode 100644index 0000000000..9f9aaafd7d--- /dev/null+++ b/apps/client/src/widgets/type_widgets/spreadsheet/navigation.ts@@ -0,0 +1,108 @@+import { Direction } from "@univerjs/core";+import type { FUniver } from "@univerjs/presets";+import { type MutableRef, useEffect } from "preact/hooks";++// Univer's plain arrow-key navigation (the "sheet.command.move-selection" command) is+// cyclic: pressing Up on the first row wraps the selection to the last row, Down on the+// last row wraps back to the first, and Left/Right wrap across columns the same way. That+// differs from Excel and Google Sheets, where arrow keys clamp at the edge, and it is+// disorienting because the wrapped-to row is usually far off-screen. Ctrl+Arrow uses a+// different code path (findNextGapRange) that already clamps, so only the plain arrows+// need fixing.+const MOVE_SELECTION_COMMAND_ID = "sheet.command.move-selection";++export type NavigationDirection = "up" | "down" | "left" | "right";++export interface SelectionBounds {+ /** Top row of the current selection (0-based). */+ startRow: number;+ /** Bottom row of the current selection (0-based, inclusive). */+ endRow: number;+ /** Leftmost column of the current selection (0-based). */+ startColumn: number;+ /** Rightmost column of the current selection (0-based, inclusive). */+ endColumn: number;+ /** Total number of rows in the sheet. */+ maxRows: number;+ /** Total number of columns in the sheet. */+ maxColumns: number;+}++/**+ * Returns whether an arrow-key move in `direction` would step past the sheet's edge — which+ * is exactly when Univer wraps the selection to the opposite side. The caller cancels such+ * moves so the selection clamps at the edge instead. Mirrors the boundary check Univer's+ * `findNextRange` performs (boundary = the full sheet), keyed off the selection edge that+ * the move travels from: the top row for Up, the bottom row for Down, and likewise for+ * Left/Right across columns.+ */+export function isOutOfBoundsMove(direction: NavigationDirection, bounds: SelectionBounds): boolean {+ switch (direction) {+ case "up":+ return bounds.startRow <= 0;+ case "down":+ return bounds.endRow >= bounds.maxRows - 1;+ case "left":+ return bounds.startColumn <= 0;+ case "right":+ return bounds.endColumn >= bounds.maxColumns - 1;+ }+}++/**+ * Cancels cyclic arrow-key navigation so the selection clamps at the sheet edge (Excel /+ * Google Sheets behaviour) instead of wrapping to the opposite side. Hooks Univer's+ * before-command event and aborts the move command when the selection already sits against+ * the boundary in the travel direction.+ */+export default function useClampEdgeNavigation(apiRef: MutableRef<FUniver | undefined>) {+ useEffect(() => {+ const univerAPI = apiRef.current;+ if (!univerAPI) return;++ const disposable = univerAPI.addEvent(univerAPI.Event.BeforeCommandExecute, (event) => {+ if (event.id !== MOVE_SELECTION_COMMAND_ID) return;++ const params = event.params as { direction?: Direction; extra?: string } | undefined;+ // Leave the formula-editor range selector (and any other special mode that tags+ // itself via `extra`) untouched — this fix only targets plain cell navigation.+ if (params?.extra) return;++ const direction = params?.direction === undefined ? undefined : toNavigationDirection(params.direction);+ if (!direction) return;++ const worksheet = univerAPI.getActiveWorkbook()?.getActiveSheet();+ const range = worksheet?.getActiveRange();+ if (!worksheet || !range) return;++ const atEdge = isOutOfBoundsMove(direction, {+ startRow: range.getRow(),+ endRow: range.getLastRow(),+ startColumn: range.getColumn(),+ endColumn: range.getLastColumn(),+ maxRows: worksheet.getMaxRows(),+ maxColumns: worksheet.getMaxColumns()+ });++ if (atEdge) {+ event.cancel = true;+ }+ });+ return () => disposable.dispose();+ }, [ apiRef ]);+}++function toNavigationDirection(direction: Direction): NavigationDirection | undefined {+ switch (direction) {+ case Direction.UP:+ return "up";+ case Direction.DOWN:+ return "down";+ case Direction.LEFT:+ return "left";+ case Direction.RIGHT:+ return "right";+ default:+ return undefined;+ }+}