[99] Merge: Esc/Enter einheitlich in allen Befehlen (Esc = Schritt zurück, Doppel-Esc = Abbruch, Enter = fertig), zentraler Tasten-Verteiler
Claude-Session: https://claude.ai/code/session_01NTYBZBvLYCtugMJoKXaB67
This commit is contained in:
10 files changed
+559
-9
No files matched your search
@@ -1355,6 +1355,26 @@ Reihenfolge = Abhängigkeiten. Neue Geometrie entsteht in Rust ([K]).
|
||||
das exportierte Geschoss im Modellbereich); Viewport-Ausmass ohne Schatten der Sonnenstudie; reine Zahl-Schritte
|
||||
(Versatz-Abstand, Radius ohne Feld) bleiben in Metern; Viewport-Inhalt im PDF nicht aufs Rechteck geklippt (nicht
|
||||
geprüft); nicht in der Tauri-App/macOS geprüft. · M
|
||||
Element — identisch im Grundriss und auf dem Blatt). Offen: Blatt rendert über den SVG-Pfad der PlanView (wegen des
|
||||
Hintergrunds, wie bei Luftbildern), nicht über render2d; Lineale/Objekt-Info zeigen Meter (y negativ) statt
|
||||
Papier-mm; feste Modellgrössen anderer Befehle (Kote, Detailverweis, Punktmarke) nicht ans Papier angepasst; kein
|
||||
Fang auf Viewport-Inhalt; Layout-DXF (`--layout`) ohne Blatt-Zeichnung; PDF-Export der Blatt-Zeichnung nicht
|
||||
angesehen; nicht in der Tauri-App/macOS geprüft. · M
|
||||
- ✅ **[99] Esc/Enter in jedem Befehl gleich.** (29.10., Maintainer-Report „Esc bricht nicht immer ab, Enter
|
||||
beendet nicht immer") Ursachen: Esc/Enter erreichten die Befehls-Engine NUR über das fokussierte Befehlsfeld —
|
||||
nach Klick auf Zeichenfläche/Panel/Knopf gingen sie verloren (`useActiveToolKeys` schweigt bei laufendem Befehl),
|
||||
Enter löste stattdessen den fokussierten Knopf aus (Werkzeug-Knopf → Befehl aus); Esc brach immer den ganzen Befehl ab
|
||||
(kein Schritt zurück); gehaltene Tasten feuerten in Serie; die Transformation (Drehen) kannte kein Enter.
|
||||
Jetzt: EIN Verteiler (`state/commandKeys.ts`, auf `document`, nach React-Handlern, vor den `window`-Handlern):
|
||||
Fokus in Eingabefeld/Dialog → Feld gehört die Taste; Befehlsfeld behandelt Esc/Enter selbst mit denselben Aktionen;
|
||||
sonst Esc = `engine.escape()`, Enter = `engine.confirm()`, Knopf-Aktion unterdrückt, Wiederholung geschluckt.
|
||||
Engine: Schritt-Verlauf (Zustand vor jeder Eingabe, die den Schritt ändert); Esc = getippten Feldwert lösen bzw. einen
|
||||
Schritt zurück, ohne Schritt Ende; Esc-Esc ≤ `ESC_DOUBLE_MS` (300 ms) = Abbruch ohne Commit. Ein Commit mitten im
|
||||
Befehl ist eine Grenze (bleibt; Esc danach beendet). Im Befehlsfeld leert Esc zuerst getippten Text. Transformation:
|
||||
Esc = letzten Punkt zurück, Enter = Klick an der letzten Mausposition. Griff-Drags unverändert (Esc bricht ab).
|
||||
Tests: `commands/engine.keys.test.ts` (jeder Befehl), `state/commandKeys.test.ts`, e2e `commandKeys.spec.ts` (jeder
|
||||
registrierte Befehl: Punkte, Esc, Esc-Esc, Enter; Fokus Befehlsfeld/Fläche/Panel-Knopf; Wandzug in allen drei).
|
||||
Offen: 3D-Ansicht und Layout-Blatt nur über den gemeinsamen Verteiler, nicht eigens per e2e; nicht auf dem Mac geprüft. · S
|
||||
- ○ **[80] PDF mit Ebenen.** · M
|
||||
- ◐ **[81] Automatische Aussenbemassung.** (27.10.) Befehl `autodim` (Kürzel `ab`): je Seite Öffnungs-,
|
||||
Vor-/Rücksprung- und Gesamtkette. Offen: schiefe Wände, Massstab aus der Ansicht statt fest 1:100.
|
||||
|
||||
@@ -0,0 +1,151 @@
|
||||
// [99] Esc/Enter in JEDEM Befehl gleich, egal wo der Fokus steht: Esc = ein Schritt zurück (ohne
|
||||
// Schritt: Befehl endet), Esc-Esc schnell = ganzer Befehl abgebrochen, Enter = abschliessen.
|
||||
// Geprüft für jeden registrierten interaktiven Befehl, mit Fokus im Befehlsfeld, auf der
|
||||
// Zeichenfläche und nach einem Klick in ein Panel (Reiter-Knopf fokussiert).
|
||||
import { readFileSync } from "node:fs";
|
||||
import type { Page } from "@playwright/test";
|
||||
import { blurFocus, commandInput, elementRows, expect, openTab, startNewProject, test, typeCommand } from "./app";
|
||||
|
||||
/** Befehlsnamen der Registratur (Schlüssel von `COMMANDS` in src/commands/registry.ts). */
|
||||
function registeredCommands(): string[] {
|
||||
const src = readFileSync("src/commands/registry.ts", "utf8");
|
||||
const body = src.slice(src.indexOf("export const COMMANDS"), src.indexOf("};", src.indexOf("export const COMMANDS")));
|
||||
return [...body.matchAll(/^\s+(?:"([^"]+)"|(\w+)):\s*\w+,?$/gm)].map((m) => m[1] ?? m[2]);
|
||||
}
|
||||
|
||||
type Focus = "input" | "canvas" | "panel";
|
||||
const IDLE = "Befehl:";
|
||||
const prompt = (page: Page) => page.locator(".cmdline-prompt");
|
||||
const steps = async (page: Page) => Number(await page.locator(".cmdline").getAttribute("data-steps"));
|
||||
|
||||
async function canvasAt(page: Page, dx: number, dy: number) {
|
||||
const box = (await page.locator("canvas").first().boundingBox())!;
|
||||
return { x: box.x + dx, y: box.y + dy };
|
||||
}
|
||||
|
||||
async function clickCanvas(page: Page, dx: number, dy: number) {
|
||||
const p = await canvasAt(page, dx, dy);
|
||||
await page.mouse.move(p.x, p.y);
|
||||
await page.mouse.click(p.x, p.y);
|
||||
}
|
||||
|
||||
/** Fokus wie ein Nutzer setzen: Befehlsfeld, nichts (nach Klick auf die Fläche) oder ein Panel-Knopf. */
|
||||
async function setFocus(page: Page, focus: Focus) {
|
||||
if (focus === "input") await commandInput(page).focus();
|
||||
else if (focus === "canvas") await blurFocus(page);
|
||||
else await page.getByRole("tab", { name: "Elemente", exact: true }).focus();
|
||||
}
|
||||
|
||||
/** Zurück in den Ruhezustand (zwischen den Befehlen). */
|
||||
async function toIdle(page: Page) {
|
||||
for (let i = 0; i < 4 && (await prompt(page).textContent()) !== IDLE; i++) {
|
||||
await blurFocus(page);
|
||||
await page.keyboard.press("Escape");
|
||||
await page.keyboard.press("Escape");
|
||||
}
|
||||
await expect(prompt(page)).toHaveText(IDLE);
|
||||
}
|
||||
|
||||
/** Befehl starten; false, wenn er sofort fertig ist (Sofort-Befehl) oder hier nicht startet. */
|
||||
async function start(page: Page, name: string): Promise<boolean> {
|
||||
await typeCommand(page, name);
|
||||
return (await prompt(page).textContent()) !== IDLE;
|
||||
}
|
||||
|
||||
async function escEscEnter(page: Page, name: string, focus: Focus): Promise<string> {
|
||||
await toIdle(page);
|
||||
if (!(await start(page, name))) return "sofort";
|
||||
// Punkte setzen, je Schritt den Prompt merken (Index = Schritt-Tiefe).
|
||||
const prompts: string[] = [(await prompt(page).textContent())!];
|
||||
await clickCanvas(page, 200, 220);
|
||||
if ((await prompt(page).textContent()) === IDLE) return "nach 1 Punkt fertig";
|
||||
prompts[await steps(page)] = (await prompt(page).textContent())!;
|
||||
await clickCanvas(page, 380, 260);
|
||||
if ((await prompt(page).textContent()) === IDLE) return "nach 2 Punkten fertig";
|
||||
const depth = await steps(page);
|
||||
prompts[depth] = (await prompt(page).textContent())!;
|
||||
|
||||
// Esc einmal: genau ein Schritt zurück (ohne Schritt: Befehl endet).
|
||||
await setFocus(page, focus);
|
||||
await page.keyboard.press("Escape");
|
||||
if (depth === 0) {
|
||||
await expect(prompt(page), `${name}: Esc ohne Schritt beendet`).toHaveText(IDLE);
|
||||
return "ok";
|
||||
}
|
||||
await expect(page.locator(".cmdline"), `${name}: Esc = ein Schritt zurück`).toHaveAttribute("data-steps", String(depth - 1));
|
||||
if (prompts[depth - 1]) await expect(prompt(page)).toHaveText(prompts[depth - 1]);
|
||||
// Esc-Esc schnell: ganzer Befehl weg.
|
||||
await page.waitForTimeout(400);
|
||||
await setFocus(page, focus);
|
||||
await page.keyboard.press("Escape");
|
||||
await page.keyboard.press("Escape");
|
||||
await expect(prompt(page), `${name}: Esc-Esc bricht ab`).toHaveText(IDLE);
|
||||
|
||||
// Enter: die Engine bekommt es (Befehl endet oder geht weiter) — nie ein Knopf-Klick.
|
||||
if (!(await start(page, name))) return "sofort";
|
||||
await clickCanvas(page, 200, 220);
|
||||
await clickCanvas(page, 380, 260);
|
||||
if ((await prompt(page).textContent()) === IDLE) return "ok";
|
||||
const before = `${await prompt(page).textContent()}|${await steps(page)}`;
|
||||
await setFocus(page, focus);
|
||||
await page.keyboard.press("Enter");
|
||||
await expect
|
||||
.poll(async () => `${await prompt(page).textContent()}|${await steps(page)}`, { message: `${name}: Enter wirkt` })
|
||||
.not.toBe(before);
|
||||
return "ok";
|
||||
}
|
||||
|
||||
const NAMES = registeredCommands();
|
||||
const FOCI: Focus[] = ["input", "canvas", "panel"];
|
||||
const CHUNK = 5;
|
||||
|
||||
test("Registratur gelesen", () => {
|
||||
expect(NAMES.length).toBeGreaterThan(50);
|
||||
expect(NAMES).toContain("polyline");
|
||||
});
|
||||
|
||||
for (let c = 0; c < NAMES.length; c += CHUNK) {
|
||||
const chunk = NAMES.slice(c, c + CHUNK);
|
||||
test(`Esc/Esc-Esc/Enter: ${chunk.join(", ")}`, async ({ page }) => {
|
||||
test.setTimeout(150_000);
|
||||
for (const [i, name] of chunk.entries()) {
|
||||
// Je Befehl ein leeres Projekt: gezeichnete Elemente (z. B. unendliche Hilfslinien) machen
|
||||
// das headless Rendern sonst sehr langsam. Der Fokus wechselt je Befehl, damit alle drei
|
||||
// Fälle über die Registratur verteilt geprüft sind.
|
||||
await startNewProject(page);
|
||||
const t0 = Date.now();
|
||||
const r = await escEscEnter(page, name, FOCI[(c + i) % FOCI.length]);
|
||||
if (process.env.E2E_TIMING) console.log(`${name}: ${r} ${Date.now() - t0} ms`);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
for (const focus of FOCI) {
|
||||
test(`Wandzug: Esc nimmt den letzten Punkt, Enter übernimmt (Fokus: ${focus})`, async ({ page }) => {
|
||||
await startNewProject(page);
|
||||
await openTab(page, "Elemente");
|
||||
await page.getByRole("button", { name: "Wand", exact: true }).click();
|
||||
await expect(prompt(page)).toHaveText("Startpunkt der Wand:");
|
||||
await clickCanvas(page, 150, 300);
|
||||
await clickCanvas(page, 450, 300);
|
||||
await clickCanvas(page, 450, 150);
|
||||
await expect(page.locator(".cmdline")).toHaveAttribute("data-steps", "3");
|
||||
await setFocus(page, focus);
|
||||
await page.keyboard.press("Escape");
|
||||
await expect(page.locator(".cmdline")).toHaveAttribute("data-steps", "2");
|
||||
await expect(prompt(page)).toHaveText("Nächster Punkt:");
|
||||
await setFocus(page, focus);
|
||||
await page.keyboard.press("Enter");
|
||||
await expect(prompt(page)).toHaveText(IDLE);
|
||||
await expect(elementRows(page)).toHaveCount(1);
|
||||
// Esc-Esc schnell mitten im Zug: nichts dazu.
|
||||
await page.getByRole("button", { name: "Wand", exact: true }).click();
|
||||
await clickCanvas(page, 150, 350);
|
||||
await clickCanvas(page, 450, 350);
|
||||
await setFocus(page, focus);
|
||||
await page.keyboard.press("Escape");
|
||||
await page.keyboard.press("Escape");
|
||||
await expect(prompt(page)).toHaveText(IDLE);
|
||||
await expect(elementRows(page)).toHaveCount(1);
|
||||
});
|
||||
}
|
||||
+34
-2
@@ -177,6 +177,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";
|
||||
@@ -968,6 +970,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/
|
||||
@@ -3013,6 +3018,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
|
||||
@@ -3709,6 +3738,7 @@ export default function App() {
|
||||
if (activeTransform) {
|
||||
const v = typed(text);
|
||||
if (isFinite(v)) submitTransformValue(v);
|
||||
else confirmTransform();
|
||||
return;
|
||||
}
|
||||
// Getipptes „rotate"/„drehen" startet die interaktive Drehung (U/I/O/P),
|
||||
@@ -3742,9 +3772,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}
|
||||
/>
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
}
|
||||
});
|
||||
@@ -91,6 +91,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 {
|
||||
@@ -107,6 +126,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> = {};
|
||||
|
||||
@@ -167,6 +193,7 @@ export class CommandEngine {
|
||||
options: this.command.options(this.state),
|
||||
commandName: this.command.name,
|
||||
fields,
|
||||
steps: this.steps.length,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -290,6 +317,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
|
||||
@@ -318,11 +346,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 ────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
@@ -482,8 +568,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);
|
||||
}
|
||||
|
||||
@@ -501,8 +590,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);
|
||||
}
|
||||
|
||||
@@ -514,6 +608,7 @@ export class CommandEngine {
|
||||
if (res.done) {
|
||||
this.command = null;
|
||||
this.state = null;
|
||||
this.steps = [];
|
||||
this.resetFields();
|
||||
}
|
||||
this.emit();
|
||||
|
||||
@@ -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];
|
||||
|
||||
/**
|
||||
|
||||
@@ -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");
|
||||
});
|
||||
});
|
||||
@@ -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]);
|
||||
}
|
||||
@@ -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
@@ -48,8 +48,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
|
||||
@@ -81,7 +88,7 @@ export interface CommandLineHandle {
|
||||
|
||||
export const CommandLine = forwardRef<CommandLineHandle, CommandLineProps>(
|
||||
function CommandLine(
|
||||
{ active, promptKey, options, fields, onSubmit, onOption, onCycleField, onCancel, suggest, onTextChange, units = MODEL_UNITS },
|
||||
{ active, promptKey, options, fields, onSubmit, onOption, onCycleField, onCancel, stillActive, steps, suggest, onTextChange, units = MODEL_UNITS },
|
||||
ref,
|
||||
) {
|
||||
const [text, setTextRaw] = useState("");
|
||||
@@ -131,14 +138,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
|
||||
@@ -160,7 +175,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) => (
|
||||
|
||||
Reference in new issue
Block a user