[99] Befehle: Esc = Schritt zurück, Esc-Esc = Abbruch, Enter = abschliessen, unabhängig vom Fokus

Ein Tasten-Verteiler (state/commandKeys.ts) statt nur über das fokussierte
Befehlsfeld; Schritt-Verlauf in der Engine (escape/back, ESC_DOUBLE_MS);
Transformation mit gleichem Esc/Enter. Tests: Engine je Befehl, Verteiler,
e2e für jeden registrierten Befehl in drei Fokus-Lagen.
This commit is contained in:
Claude committed 2026-10-29 22:24:27 +00:00
1 parent f24d41607b
commit 91d336c761
10 files changed
+554 -9

No files matched your search

+34 -2
View File
@@ -175,6 +175,8 @@ import {
useTransformShortcuts,
useUndoRedoShortcut,
} from "./state/useKeyboardShortcuts";
import { useCommandKeys, type CommandKeyTarget } from "./state/commandKeys";
import { ESC_DOUBLE_MS } from "./commands/engine";
import { useFileDropImport, useImageImportHandling } from "./state/useImportHandling";
import { useExportHandlers } from "./state/useExportHandlers";
import { useThemeModeState } from "./theme/useThemeMode";
@@ -962,6 +964,9 @@ export default function App() {
engineRef.current = new CommandEngine(host);
}
const engine = engineRef.current;
// [99] Esc/Enter eines laufenden Befehls unabhängig vom Fokus (ein Verteiler, s. commandKeys.ts).
const transformKeysRef = useRef<CommandKeyTarget | null>(null);
useCommandKeys(engineRef, transformKeysRef);
// Nutzer-Kürzel-Übersteuerungen (Einstellungen → Remap) — aus localStorage
// geladen, bei jeder Änderung sofort an die Engine gereicht (s. `commands/
@@ -3007,6 +3012,30 @@ export default function App() {
setDraft(null);
transformDragInfoRef.current = null;
};
// [99] Esc in der Transformation wie in jedem Befehl: einmal = letzten Punkt zurück (ohne
// Punkt: Ende), Esc-Esc schnell = abbrechen.
const transformEscAtRef = useRef(-Infinity);
const escapeTransform = () => {
const now = Date.now();
const quick = now - transformEscAtRef.current <= ESC_DOUBLE_MS;
transformEscAtRef.current = now;
if (!activeTransform || quick || activeTransform.points.length === 0) cancelTransform();
else {
setActiveTransform({ ...activeTransform, points: activeTransform.points.slice(0, -1) });
setDraft(null);
transformDragInfoRef.current = null;
}
};
// Enter = Klick auf die letzte (gesnappte) Mausposition: setzt den nächsten Punkt bzw. schliesst ab.
const confirmTransform = () => {
const cursor = transformDragInfoRef.current?.cursor;
if (activeTransform && cursor) transformClick(cursor, 1, { shift: false, ctrl: true, alt: false });
};
transformKeysRef.current = {
active: () => !!activeTransform,
escape: escapeTransform,
confirm: confirmTransform,
};
// Maus-Schema: Auswahl + Kontextmenü aus Grundriss / 3D — siehe
@@ -3688,6 +3717,7 @@ export default function App() {
if (activeTransform) {
const v = parseFloat(text.replace(",", "."));
if (isFinite(v)) submitTransformValue(v);
else confirmTransform();
return;
}
// Getipptes „rotate"/„drehen" startet die interaktive Drehung (U/I/O/P),
@@ -3721,9 +3751,11 @@ export default function App() {
: grip3dEdit
? setGrip3dEdit(null)
: activeTransform
? cancelTransform()
: engine.cancel()
? escapeTransform()
: engine.escape()
}
stillActive={() => engine.isActive()}
steps={gripEdit || edgeEdit || grip3dEdit ? 0 : activeTransform ? activeTransform.points.length : engineView.steps}
suggest={(prefix) => engine.suggest(prefix)}
onTextChange={setCmdTyped}
/>
+118
View File
@@ -0,0 +1,118 @@
// [99] Esc/Enter in JEDEM Befehl gleich: Esc = ein Schritt zurück (ohne Schritt: Befehl endet),
// Esc-Esc schnell (≤ ESC_DOUBLE_MS) = ganzer Befehl abbrechen (nichts aus dem offenen Teil
// committet), Enter = abschliessen. Geprüft an der Engine mit einem Test-Host.
import { describe, expect, it } from "vitest";
import { COMMANDS } from "./registry";
import { CommandEngine, ESC_DOUBLE_MS, type EngineHost } from "./engine";
import type { CommandContext } from "./types";
import type { ToolDraft } from "../tools/types";
import { sampleProject } from "../model/sampleProject";
const level = sampleProject.drawingLevels.find((l) => l.kind === "floor")!;
const ctx: CommandContext = {
project: sampleProject,
level,
defaultCategoryCode: sampleProject.layers[0]?.code ?? "20",
activeLineStyleId: "",
activeWallTypeId: sampleProject.wallTypes[0]?.id ?? "",
lastPoint: null,
selection: { wallIds: [], drawingId: null, drawingIds: [] } as unknown as CommandContext["selection"],
};
function setup() {
const log = { commits: 0, draft: null as ToolDraft | null };
const host: EngineHost = {
context: (lastPoint) => ({ ...ctx, lastPoint }),
snap: () => null,
pxPerMeter: () => 50,
setDraft: (d) => (log.draft = d),
commit: () => void log.commits++,
isFloor: () => true,
};
return { engine: new CommandEngine(host), log };
}
const P = [
{ x: 0, y: 0 },
{ x: 5, y: 0 },
{ x: 5, y: 4 },
{ x: 1, y: 6 },
];
describe("Esc/Enter der Befehls-Engine", () => {
it("Wand: Esc nimmt den letzten Punkt zurück, Enter übernimmt den Rest", () => {
const { engine, log } = setup();
engine.start("wall");
for (const p of P.slice(0, 3)) engine.pick(p);
expect(engine.stepDepth()).toBe(3);
engine.escape(1000);
expect(engine.isActive()).toBe(true);
expect(engine.stepDepth()).toBe(2);
expect(log.draft?.vertices.length).toBe(2);
// Pause > ESC_DOUBLE_MS: zweites Esc ist wieder EIN Schritt zurück, kein Abbruch.
engine.escape(1000 + ESC_DOUBLE_MS + 50);
expect(engine.isActive()).toBe(true);
expect(engine.stepDepth()).toBe(1);
engine.pick(P[3]);
engine.confirm();
expect(engine.isActive()).toBe(false);
expect(log.commits).toBe(1);
});
it("Esc ohne Schritt beendet den Befehl", () => {
const { engine } = setup();
engine.start("polyline");
engine.escape(0);
expect(engine.isActive()).toBe(false);
});
it("Esc-Esc schnell bricht den ganzen Befehl ab, nichts wird committet", () => {
const { engine, log } = setup();
engine.start("polyline");
for (const p of P) engine.pick(p);
engine.escape(5000);
engine.escape(5000 + ESC_DOUBLE_MS - 50);
expect(engine.isActive()).toBe(false);
expect(log.commits).toBe(0);
expect(log.draft).toBe(null);
});
it("Esc löst zuerst einen getippten Feldwert (Lock), dann erst Punkte", () => {
const { engine } = setup();
engine.start("wall");
engine.pick(P[0]);
if (!engine.hasFields()) return;
engine.submitText("3");
expect(engine.view().fields.some((f) => f.locked)).toBe(true);
engine.escape(0);
expect(engine.view().fields.some((f) => f.locked)).toBe(false);
expect(engine.stepDepth()).toBe(1);
});
// Jeder registrierte interaktive Befehl: Punkte setzen, Esc = genau ein Schritt zurück
// (bzw. Ende ohne Schritt), Esc-Esc = aus, ohne dass Esc etwas committet.
for (const name of Object.keys(COMMANDS)) {
const cmd = COMMANDS[name];
if (cmd.autoRun) continue;
it(`${name}: Esc einen Schritt zurück, Esc-Esc bricht ab`, () => {
const { engine, log } = setup();
if (!engine.start(name)) return;
for (const p of P.slice(0, 2)) {
engine.move(p);
engine.pick(p);
}
if (!engine.isActive()) return; // Befehl mit zwei Punkten fertig
const depth = engine.stepDepth();
const commits = log.commits;
engine.escape(10_000);
if (depth === 0) expect(engine.isActive()).toBe(false);
else {
expect(engine.isActive()).toBe(true);
expect(engine.stepDepth()).toBe(depth - 1);
}
engine.escape(10_000 + 100);
expect(engine.isActive()).toBe(false);
expect(log.commits).toBe(commits);
});
}
});
+95
View File
@@ -85,6 +85,25 @@ export interface EngineView {
locked: boolean;
active: boolean;
}[];
/** Schritte, die Esc zurücknehmen kann ([99]; für Anzeige/E2E). */
steps?: number;
}
/**
* Zwei Esc innerhalb dieser Zeit (ms) = ganzen Befehl abbrechen; langsamer = je ein Schritt
* zurück ([99], Vorgabe Maintainer: Esc-Verhalten in jedem Befehl gleich).
*/
export const ESC_DOUBLE_MS = 300;
/** Zwei Befehls-Zustände gleich (ohne Maus-`cursor`)? Dann war die Eingabe kein Schritt. */
function sameStep(a: CommandState, b: CommandState): boolean {
if (a === b) return true;
try {
const strip = (k: string, v: unknown) => (k === "cursor" || k === "hover" ? undefined : v);
return JSON.stringify(a, strip) === JSON.stringify(b, strip);
} catch {
return false;
}
}
export class CommandEngine {
@@ -101,6 +120,13 @@ export class CommandEngine {
/** Identität des Schritts, für den der Feld-Zustand gilt (Reset bei Wechsel). */
private fieldPhaseKey: string | null = null;
private listeners = new Set<() => void>();
/**
* Schritt-Verlauf des laufenden Befehls ([99]): Zustand VOR jeder Eingabe, die den Schritt
* änderte. Esc holt den letzten zurück. Ein Commit ist eine Grenze (Committetes bleibt).
*/
private steps: CommandState[] = [];
/** Zeitpunkt des letzten Esc (für Esc-Esc = Abbruch). */
private lastEscAt = -Infinity;
/** Nutzer-Kürzel-Übersteuerungen (s. `state/commandAliasOverrides.ts`); leer bis gesetzt. */
private aliasOverrides: Record<string, string> = {};
@@ -161,6 +187,7 @@ export class CommandEngine {
options: this.command.options(this.state),
commandName: this.command.name,
fields,
steps: this.steps.length,
};
}
@@ -278,6 +305,7 @@ export class CommandEngine {
this.state = cmd.init();
this.lastCommandName = cmd.name;
this.lastCursor = null;
this.steps = [];
this.resetFields();
this.host.setDraft(null);
// Sofort-Befehl (Join/Split u. Ä.): direkt ausführen, ohne auf einen Pick zu
@@ -306,11 +334,69 @@ export class CommandEngine {
}
this.command = null;
this.state = null;
this.steps = [];
this.resetFields();
this.host.setDraft(null);
this.emit();
}
/** Anzahl Schritte, die Esc zurücknehmen kann (Test/Anzeige). */
stepDepth(): number {
return this.command ? this.steps.length : 0;
}
/**
* Esc ([99]): einmal = ein Schritt zurück (`back`), zweimal innerhalb `ESC_DOUBLE_MS` =
* ganzen Befehl abbrechen. `now` nur für Tests; sonst die Uhr.
*/
escape(now: number = Date.now()): void {
if (!this.command) return;
const quick = now - this.lastEscAt <= ESC_DOUBLE_MS;
this.lastEscAt = now;
if (quick) this.cancel();
else this.back();
}
/**
* Ein Schritt zurück: zuerst ein getippter Feldwert (Lock), sonst der letzte gesetzte Punkt/
* gewählte Schritt. Ohne Schritt endet der Befehl (wie Abbruch).
*/
back(): void {
if (!this.command || !this.state) return;
if (Object.keys(this.locks).length > 0) {
this.locks = {};
this.activeFieldIndex = 0;
this.redraw();
this.emit();
return;
}
const prev = this.steps.pop();
if (!prev) {
this.cancel();
return;
}
this.state = prev;
this.resetFields();
this.redraw();
this.emit();
}
/** Vorschau des aktuellen Zustands neu zeichnen (nach einem Schritt zurück). */
private redraw(): void {
if (!this.command || !this.state) return;
if (!this.lastCursor) {
this.host.setDraft(null);
return;
}
try {
const [st, res] = this.command.onMove(this.state, this.lastCursor, null, this.context());
this.state = st;
this.host.setDraft(res.draft ?? null);
} catch {
this.host.setDraft(null);
}
}
// ── Eingabe-Routing ────────────────────────────────────────────────────────
/**
@@ -464,8 +550,11 @@ export class CommandEngine {
}
}
const ctx = this.context();
const before = this.state;
const [st, res] = this.command.onConfirm(this.state, ctx);
this.state = st;
if (res.commit) this.steps = [];
else if (!res.done && !sameStep(before, st)) this.steps.push(before);
this.applyResult(res);
}
@@ -483,8 +572,13 @@ export class CommandEngine {
if (!this.command || !this.state) return;
if (input.kind === "point") this.lastCursor = input.point;
const ctx = this.context();
const before = this.state;
const [st, res] = this.command.onInput(this.state, input, ctx);
this.state = st;
// Schritt-Verlauf: die befehlseigene Option „Zurück" nimmt selbst einen Schritt zurück.
if (input.kind === "option" && input.id === "undo") this.steps.pop();
else if (!res.commit && !res.done && !sameStep(before, st)) this.steps.push(before);
if (res.commit) this.steps = [];
this.applyResult(res);
}
@@ -496,6 +590,7 @@ export class CommandEngine {
if (res.done) {
this.command = null;
this.state = null;
this.steps = [];
this.resetFields();
}
this.emit();
+4 -1
View File
@@ -194,7 +194,10 @@ export interface Command {
): [CommandState, CommandResult];
/** Enter/Space/Rechtsklick: Schritt bestätigen / mehrteilig beenden. */
onConfirm(state: CommandState, ctx: CommandContext): [CommandState, CommandResult];
/** Esc: Entwurf verwerfen, Befehl beenden. */
/**
* Abbruch (Esc-Esc bzw. Esc ohne Schritt): Entwurf verwerfen, Befehl beenden, nichts committen.
* Den Schritt zurück bei einfachem Esc führt die Engine selbst (Schritt-Verlauf, [99]).
*/
onCancel(state: CommandState): [CommandState, CommandResult];
/**
+38
View File
@@ -0,0 +1,38 @@
// [99] Fokus-Regeln des Esc/Enter-Verteilers.
import { describe, expect, it } from "vitest";
import { commandKeyAction } from "./commandKeys";
const el = (tagName: string, inDialog = false, editable = false) =>
({ tagName, isContentEditable: editable, closest: () => (inDialog ? {} : null) }) as unknown as EventTarget;
const ev = (key: string, target: EventTarget | null, extra: Partial<KeyboardEvent> = {}) => ({
key,
target,
repeat: false,
ctrlKey: false,
metaKey: false,
altKey: false,
defaultPrevented: false,
...extra,
});
describe("commandKeyAction", () => {
it("Körper, Zeichenfläche, Knopf: Esc = escape, Enter = confirm", () => {
for (const t of [null, el("BODY"), el("CANVAS"), el("BUTTON"), el("DIV")]) {
expect(commandKeyAction(ev("Escape", t), true)).toBe("escape");
expect(commandKeyAction(ev("Enter", t), true)).toBe("confirm");
}
});
it("ohne laufenden Befehl, in Feldern, Dialogen, mit Modifikator oder schon behandelt: nicht zuständig", () => {
expect(commandKeyAction(ev("Escape", el("BODY")), false)).toBe(null);
expect(commandKeyAction(ev("Escape", el("INPUT")), true)).toBe(null);
expect(commandKeyAction(ev("Enter", el("TEXTAREA")), true)).toBe(null);
expect(commandKeyAction(ev("Enter", el("DIV", false, true)), true)).toBe(null);
expect(commandKeyAction(ev("Escape", el("BUTTON", true)), true)).toBe(null);
expect(commandKeyAction(ev("Enter", el("BODY"), { metaKey: true }), true)).toBe(null);
expect(commandKeyAction(ev("Escape", el("BODY"), { defaultPrevented: true }), true)).toBe(null);
expect(commandKeyAction(ev("a", el("BODY")), true)).toBe(null);
});
it("gehaltene Taste wird geschluckt (kein Esc-Esc-Abbruch durch Wiederholung)", () => {
expect(commandKeyAction(ev("Escape", el("BODY"), { repeat: true }), true)).toBe("swallow");
});
});
+76
View File
@@ -0,0 +1,76 @@
// [99] EIN Tasten-Verteiler für Esc/Enter eines laufenden Befehls — egal, wo der Fokus steht
// (Zeichenfläche, Schnitt/Ansicht, Layout-Blatt, 3D, nach Klick in ein Panel oder auf einen
// Werkzeug-Knopf). Vorher bekam die Engine Esc/Enter NUR über das fokussierte Befehlsfeld; nach
// einem Klick daneben gingen die Tasten verloren bzw. Enter löste den fokussierten Knopf aus.
//
// Fokus-Regeln:
// • Befehlsfeld fokussiert → es behandelt Esc/Enter selbst (getippter Wert, Leer-Enter
// wiederholt den letzten Befehl) und ruft dieselben Engine-Aktionen; hier nichts tun.
// • anderes Eingabefeld (Panel-Zahl, Texteditor) oder offener Dialog → das Feld gehört der Taste.
// • sonst (Körper, Zeichenfläche, Knopf, Panel-Fläche) → Esc = `engine.escape()`, Enter =
// `engine.confirm()`; Standardaktion (Knopf-Klick) unterdrückt.
// • gehaltene Taste (Wiederholung) zählt nicht — sonst wäre gehaltenes Esc ein Esc-Esc-Abbruch.
// Registriert auf `document` (Bubble): läuft NACH den React-Handlern (Befehlsfeld, Dialoge)
// und VOR den `window`-Handlern (Griff-Abbruch, Auswahl aufheben), die `defaultPrevented` achten.
import { useEffect } from "react";
import type { RefObject } from "react";
import type { CommandEngine } from "../commands/engine";
/** Gehört die Taste einem Eingabefeld oder Dialog (nicht dem Befehl)? */
export function keyBelongsToField(target: EventTarget | null): boolean {
const el = target as HTMLElement | null;
if (!el || typeof el.closest !== "function") return false;
if (el.isContentEditable || /^(INPUT|TEXTAREA|SELECT)$/.test(el.tagName)) return true;
return !!el.closest('[role="dialog"],[aria-modal="true"]');
}
/** Was tut der Verteiler mit dieser Taste? null = nicht zuständig. */
export function commandKeyAction(
e: Pick<KeyboardEvent, "key" | "repeat" | "ctrlKey" | "metaKey" | "altKey" | "defaultPrevented" | "target">,
commandActive: boolean,
): "escape" | "confirm" | "swallow" | null {
if (!commandActive || e.defaultPrevented) return null;
if (e.key !== "Escape" && e.key !== "Enter") return null;
if (e.ctrlKey || e.metaKey || e.altKey) return null;
if (keyBelongsToField(e.target)) return null;
if (e.repeat) return "swallow";
return e.key === "Escape" ? "escape" : "confirm";
}
/**
* Weiterer Befehl ausserhalb der Engine (Auswahl-Transformation Bewegen/Drehen/Spiegeln …):
* gleiche Esc-/Enter-Regeln.
*/
export interface CommandKeyTarget {
active(): boolean;
escape(): void;
confirm(): void;
}
/** Hängt den Verteiler einmal an (liest Engine und Transformation über Refs). */
export function useCommandKeys(
engineRef: RefObject<CommandEngine | null>,
otherRef?: RefObject<CommandKeyTarget | null>,
): void {
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
const eng = engineRef.current;
const other = otherRef?.current;
const engActive = !!eng?.isActive();
const action = commandKeyAction(e, engActive || !!other?.active());
if (!action) return;
if (engActive && eng) {
e.preventDefault();
if (action === "escape") eng.escape();
else if (action === "confirm") eng.confirm();
} else if (other) {
e.preventDefault();
if (action === "escape") other.escape();
else if (action === "confirm") other.confirm();
}
};
document.addEventListener("keydown", onKey);
return () => document.removeEventListener("keydown", onKey);
}, [engineRef, otherRef]);
}
+2
View File
@@ -698,6 +698,8 @@ export function useTransformShortcuts(
} else if (k === "p") {
requestCopyCount("distribute");
} else if (e.key === "Escape") {
// [99] Esc der Transformation läuft über den zentralen Verteiler (commandKeys.ts).
if (e.defaultPrevented) return;
setActiveTransform(null);
setDraft(null);
} else return;
+21 -6
View File
@@ -46,8 +46,15 @@ export interface CommandLineProps {
onOption: (id: string) => void;
/** Tab im Feld-Modus: nächstes Feld aktivieren. */
onCycleField: () => void;
/** Esc: laufenden Befehl abbrechen. */
/** Esc: einen Schritt zurück bzw. (Esc-Esc schnell) laufenden Befehl abbrechen ([99]). */
onCancel: () => void;
/**
* Läuft nach Esc noch ein Befehl? Dann behält das Feld den Fokus (nächstes Esc = nächster
* Schritt zurück); sonst gibt es ihn ab. Fehlt die Funktion: immer abgeben.
*/
stillActive?: () => boolean;
/** Schritte, die Esc zurücknehmen kann (als `data-steps`, für E2E). */
steps?: number;
/**
* Live-Echo des Eingabetexts (bei jeder Änderung, inkl. Leeren nach Submit/
* Esc) — speist das Cursor-HUD, das den getippten Wert im aktiven Feld
@@ -77,7 +84,7 @@ export interface CommandLineHandle {
export const CommandLine = forwardRef<CommandLineHandle, CommandLineProps>(
function CommandLine(
{ active, promptKey, options, fields, onSubmit, onOption, onCycleField, onCancel, suggest, onTextChange },
{ active, promptKey, options, fields, onSubmit, onOption, onCycleField, onCancel, stillActive, steps, suggest, onTextChange },
ref,
) {
const [text, setTextRaw] = useState("");
@@ -127,14 +134,22 @@ export const CommandLine = forwardRef<CommandLineHandle, CommandLineProps>(
}
}
// Tasten NICHT zum globalen App-Handler durchreichen (eigener Eingabefokus).
if (e.key === "Enter") {
// Gehaltene Esc/Enter zählen nicht (sonst Esc-Esc-Abbruch bzw. Befehl-Wiederholung in Serie).
if ((e.key === "Enter" || e.key === "Escape") && e.repeat) {
e.preventDefault();
} else if (e.key === "Enter") {
e.preventDefault();
submit(text);
} else if (e.key === "Escape") {
e.preventDefault();
// [99] Getippter Text: Esc leert erst das Feld (ein Schritt). Sonst ein Schritt zurück im
// Befehl (Esc-Esc schnell: Abbruch); das Feld behält den Fokus, solange er noch läuft.
if (text !== "") {
setText("");
return;
}
if (active) onCancel();
setText("");
inputRef.current?.blur();
if (!active || !stillActive?.()) inputRef.current?.blur();
} else if (e.key === "Tab") {
if (hasFields) {
// Feld-Modus (§2.7): Tab zyklt die Felder. Steht eine getippte Zahl im
@@ -156,7 +171,7 @@ export const CommandLine = forwardRef<CommandLineHandle, CommandLineProps>(
: t("cmd.idle.prompt");
return (
<div className="cmdline" role="group" aria-label={t("cmd.aria")}>
<div className="cmdline" role="group" aria-label={t("cmd.aria")} data-steps={steps ?? 0}>
{suggestions.length > 0 && (
<ul className="cmdline-suggest" role="listbox">
{suggestions.map((s) => (