mirror of
https://github.com/binaricat/Netcatty.git
synced 2026-11-26 02:31:40 +00:00
refactor(domain): deduplicate ZIP builder, snippet shortkey recorder, hex-to-HSL math, and shell tokenizer (#4398)
This commit is contained in:
15 files changed
+934
-540
No files matched your search
@@ -1,47 +1,10 @@
|
||||
import type { TerminalTheme } from '../../types';
|
||||
import { resolveReadableForegroundForHsl } from '../../domain/colorContrast';
|
||||
|
||||
function hexToHslToken(hex: string): string {
|
||||
const normalized = hex.startsWith('#') ? hex : `#${hex}`;
|
||||
const r = parseInt(normalized.slice(1, 3), 16) / 255;
|
||||
const g = parseInt(normalized.slice(3, 5), 16) / 255;
|
||||
const b = parseInt(normalized.slice(5, 7), 16) / 255;
|
||||
const max = Math.max(r, g, b);
|
||||
const min = Math.min(r, g, b);
|
||||
let h = 0;
|
||||
let s = 0;
|
||||
const l = (max + min) / 2;
|
||||
|
||||
if (max !== min) {
|
||||
const d = max - min;
|
||||
s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
|
||||
switch (max) {
|
||||
case r:
|
||||
h = ((g - b) / d + (g < b ? 6 : 0)) / 6;
|
||||
break;
|
||||
case g:
|
||||
h = ((b - r) / d + 2) / 6;
|
||||
break;
|
||||
default:
|
||||
h = ((r - g) / d + 4) / 6;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return `${Math.round(h * 3600) / 10} ${Math.round(s * 1000) / 10}% ${Math.round(l * 1000) / 10}%`;
|
||||
}
|
||||
|
||||
function adjustLightnessToken(hsl: string, delta: number): string {
|
||||
const parts = hsl.split(/\s+/);
|
||||
const newL = Math.max(0, Math.min(100, parseFloat(parts[2]) + delta));
|
||||
return `${parts[0]} ${parts[1]} ${Math.round(newL * 10) / 10}%`;
|
||||
}
|
||||
|
||||
function adjustSaturationToken(hsl: string, factor: number): string {
|
||||
const parts = hsl.split(/\s+/);
|
||||
const newS = Math.max(0, Math.min(100, parseFloat(parts[1]) * factor));
|
||||
return `${parts[0]} ${Math.round(newS * 10) / 10}% ${parts[2]}`;
|
||||
}
|
||||
import {
|
||||
adjustLightnessToken,
|
||||
adjustSaturationToken,
|
||||
hexToHslToken,
|
||||
resolveReadableForegroundForHsl,
|
||||
} from '../../domain/colorContrast';
|
||||
|
||||
const setStylePropertyIfChanged = (element: HTMLElement, property: string, value: string) => {
|
||||
if (element.style.getPropertyValue(property) === value) return;
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
* and detached terminal popups) shares the same clear semantics.
|
||||
*/
|
||||
|
||||
import { tokenizeShellLike } from "../../domain/shellTokenizer";
|
||||
import { localStorageAdapter } from "../../infrastructure/persistence/localStorageAdapter";
|
||||
import {
|
||||
STORAGE_KEY_COMMAND_HISTORY,
|
||||
@@ -499,55 +500,6 @@ function normalizeArgumentToken(token: string): string {
|
||||
.toLowerCase();
|
||||
}
|
||||
|
||||
function tokenizeShellLike(input: string): string[] {
|
||||
const tokens: string[] = [];
|
||||
let current = "";
|
||||
let inSingleQuote = false;
|
||||
let inDoubleQuote = false;
|
||||
let escaped = false;
|
||||
|
||||
for (let i = 0; i < input.length; i++) {
|
||||
const ch = input[i];
|
||||
|
||||
if (escaped) {
|
||||
current += ch;
|
||||
escaped = false;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (ch === "\\") {
|
||||
escaped = true;
|
||||
current += ch;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (ch === "'" && !inDoubleQuote) {
|
||||
inSingleQuote = !inSingleQuote;
|
||||
current += ch;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (ch === '"' && !inSingleQuote) {
|
||||
inDoubleQuote = !inDoubleQuote;
|
||||
current += ch;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (ch === " " && !inSingleQuote && !inDoubleQuote) {
|
||||
if (current.length > 0) {
|
||||
tokens.push(current);
|
||||
current = "";
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
current += ch;
|
||||
}
|
||||
|
||||
tokens.push(current);
|
||||
return tokens;
|
||||
}
|
||||
|
||||
/**
|
||||
* Compute a fuzzy match score. Returns 0 for no match.
|
||||
* Higher score = better match quality.
|
||||
|
||||
@@ -11,46 +11,12 @@ import {
|
||||
import { runThemeTransition } from "./themeTransition";
|
||||
import { TERMINAL_THEMES } from "../../infrastructure/config/terminalThemes";
|
||||
import { netcattyBridge } from "../../infrastructure/services/netcattyBridge";
|
||||
import { resolveReadableForegroundForHsl } from "../../domain/colorContrast";
|
||||
|
||||
function hexToHsl(hex: string): string {
|
||||
const r = parseInt(hex.slice(1, 3), 16) / 255;
|
||||
const g = parseInt(hex.slice(3, 5), 16) / 255;
|
||||
const b = parseInt(hex.slice(5, 7), 16) / 255;
|
||||
const max = Math.max(r, g, b);
|
||||
const min = Math.min(r, g, b);
|
||||
let h = 0;
|
||||
let s = 0;
|
||||
const l = (max + min) / 2;
|
||||
if (max !== min) {
|
||||
const d = max - min;
|
||||
s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
|
||||
switch (max) {
|
||||
case r:
|
||||
h = ((g - b) / d + (g < b ? 6 : 0)) / 6;
|
||||
break;
|
||||
case g:
|
||||
h = ((b - r) / d + 2) / 6;
|
||||
break;
|
||||
default:
|
||||
h = ((r - g) / d + 4) / 6;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return `${Math.round(h * 3600) / 10} ${Math.round(s * 1000) / 10}% ${Math.round(l * 1000) / 10}%`;
|
||||
}
|
||||
|
||||
function adjustLightness(hsl: string, delta: number): string {
|
||||
const parts = hsl.split(/\s+/);
|
||||
const nextLightness = Math.max(0, Math.min(100, parseFloat(parts[2]) + delta));
|
||||
return `${parts[0]} ${parts[1]} ${Math.round(nextLightness * 10) / 10}%`;
|
||||
}
|
||||
|
||||
function adjustSaturation(hsl: string, factor: number): string {
|
||||
const parts = hsl.split(/\s+/);
|
||||
const nextSaturation = Math.max(0, Math.min(100, parseFloat(parts[1]) * factor));
|
||||
return `${parts[0]} ${Math.round(nextSaturation * 10) / 10}% ${parts[2]}`;
|
||||
}
|
||||
import {
|
||||
adjustLightnessToken,
|
||||
adjustSaturationToken,
|
||||
hexToHslToken,
|
||||
resolveReadableForegroundForHsl,
|
||||
} from "../../domain/colorContrast";
|
||||
|
||||
const CSS_VARS = [
|
||||
"background",
|
||||
@@ -75,15 +41,15 @@ const CSS_VARS = [
|
||||
] as const;
|
||||
|
||||
function buildChromeCss(theme: TerminalTheme): string {
|
||||
const bg = hexToHsl(theme.colors.background);
|
||||
const fg = hexToHsl(theme.colors.foreground);
|
||||
const cursor = hexToHsl(theme.colors.cursor);
|
||||
const bg = hexToHslToken(theme.colors.background);
|
||||
const fg = hexToHslToken(theme.colors.foreground);
|
||||
const cursor = hexToHslToken(theme.colors.cursor);
|
||||
const isDark = theme.type === "dark";
|
||||
const card = adjustLightness(bg, isDark ? 4 : -3);
|
||||
const secondary = adjustLightness(bg, isDark ? 6 : -5);
|
||||
const muted = adjustLightness(bg, isDark ? 10 : -8);
|
||||
const mutedFg = adjustSaturation(adjustLightness(fg, isDark ? -20 : 20), 0.5);
|
||||
const border = adjustLightness(bg, isDark ? 12 : -10);
|
||||
const card = adjustLightnessToken(bg, isDark ? 4 : -3);
|
||||
const secondary = adjustLightnessToken(bg, isDark ? 6 : -5);
|
||||
const muted = adjustLightnessToken(bg, isDark ? 10 : -8);
|
||||
const mutedFg = adjustSaturationToken(adjustLightnessToken(fg, isDark ? -20 : 20), 0.5);
|
||||
const border = adjustLightnessToken(bg, isDark ? 12 : -10);
|
||||
const primaryFg = resolveReadableForegroundForHsl(cursor);
|
||||
|
||||
const values = [
|
||||
|
||||
@@ -0,0 +1,251 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { JSDOM } from "jsdom";
|
||||
import React, { act } from "react";
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
|
||||
import type { KeyBinding, Snippet } from "../../domain/models.ts";
|
||||
import { useSnippetShortkeyRecorder } from "./useSnippetShortkeyRecorder.ts";
|
||||
|
||||
const makeSnippet = (id: string, label: string, shortkey?: string): Snippet => ({
|
||||
id,
|
||||
label,
|
||||
command: `echo ${id}`,
|
||||
tags: [],
|
||||
package: "",
|
||||
targets: [],
|
||||
shortkey,
|
||||
});
|
||||
|
||||
const stubT = (key: string, values?: Record<string, string | number | boolean | null | undefined>) => {
|
||||
if (!values) return key;
|
||||
return `${key}:${JSON.stringify(values)}`;
|
||||
};
|
||||
|
||||
function installDom() {
|
||||
const dom = new JSDOM("<!doctype html><html><body><div id='root'></div></body></html>");
|
||||
const prevWindow = globalThis.window;
|
||||
const prevDocument = globalThis.document;
|
||||
const prevKeyboardEvent = globalThis.KeyboardEvent;
|
||||
const prevNavigator = globalThis.navigator;
|
||||
const env = globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean };
|
||||
const prevAct = env.IS_REACT_ACT_ENVIRONMENT;
|
||||
|
||||
env.IS_REACT_ACT_ENVIRONMENT = true;
|
||||
Object.defineProperty(globalThis, "window", { value: dom.window, configurable: true });
|
||||
Object.defineProperty(globalThis, "document", { value: dom.window.document, configurable: true });
|
||||
Object.defineProperty(globalThis, "KeyboardEvent", { value: dom.window.KeyboardEvent, configurable: true });
|
||||
Object.defineProperty(globalThis, "navigator", { value: dom.window.navigator, configurable: true });
|
||||
|
||||
return {
|
||||
dom,
|
||||
cleanup() {
|
||||
env.IS_REACT_ACT_ENVIRONMENT = prevAct;
|
||||
Object.defineProperty(globalThis, "window", { value: prevWindow, configurable: true });
|
||||
Object.defineProperty(globalThis, "document", { value: prevDocument, configurable: true });
|
||||
Object.defineProperty(globalThis, "KeyboardEvent", { value: prevKeyboardEvent, configurable: true });
|
||||
Object.defineProperty(globalThis, "navigator", { value: prevNavigator, configurable: true });
|
||||
dom.window.close();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
test("useSnippetShortkeyRecorder captures valid shortkeys, ignores modifiers, and cancels on Escape", async () => {
|
||||
const { dom, cleanup } = installDom();
|
||||
const captured: string[] = [];
|
||||
let latest!: ReturnType<typeof useSnippetShortkeyRecorder>;
|
||||
|
||||
function Harness() {
|
||||
latest = useSnippetShortkeyRecorder({
|
||||
snippets: [],
|
||||
hotkeyScheme: "pc",
|
||||
keyBindings: [],
|
||||
t: stubT,
|
||||
onCapture: (key) => captured.push(key),
|
||||
});
|
||||
return null;
|
||||
}
|
||||
|
||||
let root: Root | undefined;
|
||||
try {
|
||||
await act(async () => {
|
||||
root = createRoot(dom.window.document.getElementById("root")!);
|
||||
root.render(React.createElement(Harness));
|
||||
});
|
||||
|
||||
await act(async () => {
|
||||
latest.setIsRecordingShortkey(true);
|
||||
});
|
||||
assert.equal(latest.isRecordingShortkey, true);
|
||||
|
||||
// Modifier-only key press keeps recording active.
|
||||
await act(async () => {
|
||||
dom.window.dispatchEvent(new dom.window.KeyboardEvent("keydown", { key: "Control", ctrlKey: true, cancelable: true }));
|
||||
});
|
||||
assert.equal(latest.isRecordingShortkey, true);
|
||||
assert.deepEqual(captured, []);
|
||||
|
||||
// Valid shortcut captures and stops recording.
|
||||
await act(async () => {
|
||||
dom.window.dispatchEvent(new dom.window.KeyboardEvent("keydown", { key: "k", ctrlKey: true, shiftKey: true, cancelable: true }));
|
||||
});
|
||||
assert.equal(latest.isRecordingShortkey, false);
|
||||
assert.equal(latest.shortkeyError, null);
|
||||
assert.deepEqual(captured, ["Ctrl + Shift + K"]);
|
||||
|
||||
// Escape cancels recording and clears error without capturing.
|
||||
await act(async () => {
|
||||
latest.setShortkeyError("some error");
|
||||
latest.setIsRecordingShortkey(true);
|
||||
});
|
||||
await act(async () => {
|
||||
dom.window.dispatchEvent(new dom.window.KeyboardEvent("keydown", { key: "Escape", cancelable: true }));
|
||||
});
|
||||
assert.equal(latest.isRecordingShortkey, false);
|
||||
assert.equal(latest.shortkeyError, null);
|
||||
assert.deepEqual(captured, ["Ctrl + Shift + K"]);
|
||||
} finally {
|
||||
await act(async () => {
|
||||
root?.unmount();
|
||||
});
|
||||
cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("useSnippetShortkeyRecorder reports system and snippet conflicts while ignoring self", async () => {
|
||||
const { dom, cleanup } = installDom();
|
||||
const captured: string[] = [];
|
||||
let latest!: ReturnType<typeof useSnippetShortkeyRecorder>;
|
||||
|
||||
const keyBindings: KeyBinding[] = [
|
||||
{
|
||||
id: "newTab",
|
||||
action: "newTab",
|
||||
label: "New Tab",
|
||||
mac: "\u2318 + T",
|
||||
pc: "Ctrl + T",
|
||||
category: "tabs",
|
||||
},
|
||||
];
|
||||
const snippets: Snippet[] = [
|
||||
makeSnippet("snip-self", "Self Snippet", "Ctrl + Shift + S"),
|
||||
makeSnippet("snip-other", "Other Snippet", "Ctrl + Shift + O"),
|
||||
];
|
||||
|
||||
function Harness() {
|
||||
latest = useSnippetShortkeyRecorder({
|
||||
snippets,
|
||||
editingSnippetId: "snip-self",
|
||||
hotkeyScheme: "pc",
|
||||
keyBindings,
|
||||
t: stubT,
|
||||
onCapture: (key) => captured.push(key),
|
||||
});
|
||||
return null;
|
||||
}
|
||||
|
||||
let root: Root | undefined;
|
||||
try {
|
||||
await act(async () => {
|
||||
root = createRoot(dom.window.document.getElementById("root")!);
|
||||
root.render(React.createElement(Harness));
|
||||
});
|
||||
|
||||
await act(async () => {
|
||||
latest.setIsRecordingShortkey(true);
|
||||
});
|
||||
|
||||
// Conflicts with system binding.
|
||||
await act(async () => {
|
||||
dom.window.dispatchEvent(new dom.window.KeyboardEvent("keydown", { key: "t", ctrlKey: true, cancelable: true }));
|
||||
});
|
||||
assert.equal(latest.isRecordingShortkey, true);
|
||||
assert.match(latest.shortkeyError ?? "", /snippets\.shortkey\.error\.systemConflict/);
|
||||
assert.match(latest.shortkeyError ?? "", /New Tab/);
|
||||
|
||||
// Conflicts with another snippet.
|
||||
await act(async () => {
|
||||
dom.window.dispatchEvent(new dom.window.KeyboardEvent("keydown", { key: "o", ctrlKey: true, shiftKey: true, cancelable: true }));
|
||||
});
|
||||
assert.equal(latest.isRecordingShortkey, true);
|
||||
assert.match(latest.shortkeyError ?? "", /snippets\.shortkey\.error\.snippetConflict/);
|
||||
assert.match(latest.shortkeyError ?? "", /Other Snippet/);
|
||||
|
||||
// Same shortcut as currently edited snippet is allowed.
|
||||
await act(async () => {
|
||||
dom.window.dispatchEvent(new dom.window.KeyboardEvent("keydown", { key: "s", ctrlKey: true, shiftKey: true, cancelable: true }));
|
||||
});
|
||||
assert.equal(latest.isRecordingShortkey, false);
|
||||
assert.equal(latest.shortkeyError, null);
|
||||
assert.deepEqual(captured, ["Ctrl + Shift + S"]);
|
||||
} finally {
|
||||
await act(async () => {
|
||||
root?.unmount();
|
||||
});
|
||||
cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("useSnippetShortkeyRecorder ignores keydowns while app lock overlay is active", async () => {
|
||||
const { dom, cleanup } = installDom();
|
||||
const captured: string[] = [];
|
||||
let latest!: ReturnType<typeof useSnippetShortkeyRecorder>;
|
||||
|
||||
function Harness() {
|
||||
latest = useSnippetShortkeyRecorder({
|
||||
snippets: [],
|
||||
hotkeyScheme: "pc",
|
||||
keyBindings: [],
|
||||
t: stubT,
|
||||
onCapture: (key) => captured.push(key),
|
||||
});
|
||||
return null;
|
||||
}
|
||||
|
||||
let root: Root | undefined;
|
||||
try {
|
||||
await act(async () => {
|
||||
root = createRoot(dom.window.document.getElementById("root")!);
|
||||
root.render(React.createElement(Harness));
|
||||
});
|
||||
|
||||
await act(async () => {
|
||||
latest.setIsRecordingShortkey(true);
|
||||
});
|
||||
|
||||
const lockOverlay = dom.window.document.createElement("div");
|
||||
lockOverlay.setAttribute("data-app-lock-overlay", "true");
|
||||
dom.window.document.body.appendChild(lockOverlay);
|
||||
|
||||
const lockedEvent = new dom.window.KeyboardEvent("keydown", {
|
||||
key: "p",
|
||||
ctrlKey: true,
|
||||
cancelable: true,
|
||||
});
|
||||
await act(async () => {
|
||||
dom.window.dispatchEvent(lockedEvent);
|
||||
});
|
||||
assert.equal(lockedEvent.defaultPrevented, false);
|
||||
assert.equal(latest.isRecordingShortkey, true);
|
||||
assert.deepEqual(captured, []);
|
||||
|
||||
// Removing the lock overlay restores normal capture.
|
||||
lockOverlay.remove();
|
||||
const unlockedEvent = new dom.window.KeyboardEvent("keydown", {
|
||||
key: "p",
|
||||
ctrlKey: true,
|
||||
cancelable: true,
|
||||
});
|
||||
await act(async () => {
|
||||
dom.window.dispatchEvent(unlockedEvent);
|
||||
});
|
||||
assert.equal(unlockedEvent.defaultPrevented, true);
|
||||
assert.equal(latest.isRecordingShortkey, false);
|
||||
assert.deepEqual(captured, ["Ctrl + P"]);
|
||||
} finally {
|
||||
await act(async () => {
|
||||
root?.unmount();
|
||||
});
|
||||
cleanup();
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,133 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import type { I18nContextValue } from '../i18n/I18nProvider';
|
||||
import { findActiveSystemShortcutConflict } from '../../domain/activeKeyBindings';
|
||||
import {
|
||||
type HotkeyScheme,
|
||||
type KeyBinding,
|
||||
type Snippet,
|
||||
keyEventToString,
|
||||
keyStringToKeyboardEvent,
|
||||
matchesKeyBinding,
|
||||
} from '../../domain/models';
|
||||
import { isAppLockOverlayActive } from '../../infrastructure/appLockOverlayDom';
|
||||
import { isMacPlatform } from '../../lib/utils';
|
||||
|
||||
const normalizeKeyString = (value: string): string => (
|
||||
value.toLowerCase().replace(/\s+/g, '')
|
||||
);
|
||||
|
||||
export interface UseSnippetShortkeyRecorderOptions {
|
||||
snippets: Snippet[];
|
||||
editingSnippetId?: string;
|
||||
hotkeyScheme: HotkeyScheme;
|
||||
keyBindings: KeyBinding[];
|
||||
t: I18nContextValue['t'];
|
||||
onCapture: (shortkey: string) => void;
|
||||
}
|
||||
|
||||
export function useSnippetShortkeyRecorder({
|
||||
snippets,
|
||||
editingSnippetId,
|
||||
hotkeyScheme,
|
||||
keyBindings,
|
||||
t,
|
||||
onCapture,
|
||||
}: UseSnippetShortkeyRecorderOptions) {
|
||||
const [isRecordingShortkey, setIsRecordingShortkey] = useState(false);
|
||||
const [shortkeyError, setShortkeyError] = useState<string | null>(null);
|
||||
const onCaptureRef = useRef(onCapture);
|
||||
onCaptureRef.current = onCapture;
|
||||
|
||||
const isMac = useMemo(() => (
|
||||
hotkeyScheme === 'mac' || (hotkeyScheme === 'disabled' && isMacPlatform())
|
||||
), [hotkeyScheme]);
|
||||
|
||||
const existingShortkeys = useMemo(() => (
|
||||
snippets.filter((snippet) => Boolean(snippet.shortkey) && snippet.id !== editingSnippetId)
|
||||
), [snippets, editingSnippetId]);
|
||||
|
||||
const validateShortkey = useCallback((key: string): string | null => {
|
||||
if (!key) return null;
|
||||
|
||||
const systemConflict = findActiveSystemShortcutConflict(key, hotkeyScheme, keyBindings);
|
||||
if (systemConflict) {
|
||||
const nameKey = `settings.shortcuts.binding.${systemConflict.id}`;
|
||||
const name = t(nameKey) !== nameKey ? t(nameKey) : systemConflict.label;
|
||||
return t('snippets.shortkey.error.systemConflict', { name });
|
||||
}
|
||||
|
||||
const syntheticEvent = keyStringToKeyboardEvent(key);
|
||||
if (syntheticEvent) {
|
||||
for (const snippet of existingShortkeys) {
|
||||
if (snippet.shortkey && matchesKeyBinding(syntheticEvent, snippet.shortkey, isMac)) {
|
||||
return t('snippets.shortkey.error.snippetConflict', { name: snippet.label });
|
||||
}
|
||||
}
|
||||
} else {
|
||||
const normalizedKey = normalizeKeyString(key);
|
||||
const conflictingSnippet = existingShortkeys.find((snippet) => (
|
||||
snippet.shortkey && normalizeKeyString(snippet.shortkey) === normalizedKey
|
||||
));
|
||||
if (conflictingSnippet) {
|
||||
return t('snippets.shortkey.error.snippetConflict', { name: conflictingSnippet.label });
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}, [existingShortkeys, hotkeyScheme, isMac, keyBindings, t]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isRecordingShortkey) return;
|
||||
|
||||
const handleKeyDown = (e: KeyboardEvent) => {
|
||||
// App lock overlay installs later; skip while locked so password keys
|
||||
// never mutate shortkeys (Codex P2).
|
||||
if (isAppLockOverlayActive()) return;
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
|
||||
if (e.key === 'Escape') {
|
||||
setIsRecordingShortkey(false);
|
||||
setShortkeyError(null);
|
||||
return;
|
||||
}
|
||||
|
||||
if (['Meta', 'Control', 'Alt', 'Shift'].includes(e.key)) return;
|
||||
|
||||
const keyString = keyEventToString(e, isMac);
|
||||
const error = validateShortkey(keyString);
|
||||
if (error) {
|
||||
setShortkeyError(error);
|
||||
return;
|
||||
}
|
||||
|
||||
setShortkeyError(null);
|
||||
onCaptureRef.current(keyString);
|
||||
setIsRecordingShortkey(false);
|
||||
};
|
||||
|
||||
const handleClick = () => {
|
||||
setIsRecordingShortkey(false);
|
||||
setShortkeyError(null);
|
||||
};
|
||||
|
||||
const timer = setTimeout(() => {
|
||||
window.addEventListener('click', handleClick, true);
|
||||
}, 100);
|
||||
|
||||
window.addEventListener('keydown', handleKeyDown, true);
|
||||
return () => {
|
||||
clearTimeout(timer);
|
||||
window.removeEventListener('keydown', handleKeyDown, true);
|
||||
window.removeEventListener('click', handleClick, true);
|
||||
};
|
||||
}, [isRecordingShortkey, isMac, validateShortkey]);
|
||||
|
||||
return {
|
||||
isRecordingShortkey,
|
||||
setIsRecordingShortkey,
|
||||
shortkeyError,
|
||||
setShortkeyError,
|
||||
validateShortkey,
|
||||
};
|
||||
}
|
||||
@@ -1,12 +1,169 @@
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { registerHooks } from "node:module";
|
||||
import { JSDOM } from "jsdom";
|
||||
import React, { act } from "react";
|
||||
import type { Root } from "react-dom/client";
|
||||
|
||||
import { getQuickAddSnippetInitialCommand } from "./QuickAddSnippetDialog.tsx";
|
||||
registerHooks({
|
||||
resolve(specifier, context, nextResolve) {
|
||||
if (
|
||||
specifier === "./snippets/SnippetScriptEditor"
|
||||
&& context.parentURL?.endsWith("/QuickAddSnippetDialog.tsx")
|
||||
) {
|
||||
return {
|
||||
url: "data:text/javascript,export function SnippetScriptEditor(){return null}",
|
||||
shortCircuit: true,
|
||||
};
|
||||
}
|
||||
return nextResolve(specifier, context);
|
||||
},
|
||||
});
|
||||
|
||||
const source = readFileSync(new URL("./QuickAddSnippetDialog.tsx", import.meta.url), "utf8");
|
||||
const recorderSource = readFileSync(
|
||||
new URL("../application/state/useSnippetShortkeyRecorder.ts", import.meta.url),
|
||||
"utf8",
|
||||
);
|
||||
|
||||
test("quick add snippet event can prefill command", () => {
|
||||
test("QuickAddSnippetDialog blocks shortkey recording while app lock overlay is active", async () => {
|
||||
const dom = new JSDOM("<!doctype html><html><body><div id='root'></div></body></html>");
|
||||
const prevWindow = globalThis.window;
|
||||
const prevDocument = globalThis.document;
|
||||
const prevNavigator = globalThis.navigator;
|
||||
const prevKeyboardEvent = globalThis.KeyboardEvent;
|
||||
const prevCustomEvent = globalThis.CustomEvent;
|
||||
const prevHTMLElement = globalThis.HTMLElement;
|
||||
const prevHTMLInputElement = globalThis.HTMLInputElement;
|
||||
const prevElement = globalThis.Element;
|
||||
const prevNode = globalThis.Node;
|
||||
const prevNodeFilter = globalThis.NodeFilter;
|
||||
const prevDocumentFragment = globalThis.DocumentFragment;
|
||||
const prevMutationObserver = globalThis.MutationObserver;
|
||||
const prevGetComputedStyle = globalThis.getComputedStyle;
|
||||
const prevRaf = globalThis.requestAnimationFrame;
|
||||
const prevCancelRaf = globalThis.cancelAnimationFrame;
|
||||
const env = globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean };
|
||||
const prevAct = env.IS_REACT_ACT_ENVIRONMENT;
|
||||
|
||||
env.IS_REACT_ACT_ENVIRONMENT = true;
|
||||
Object.defineProperty(globalThis, "window", { value: dom.window, configurable: true });
|
||||
Object.defineProperty(globalThis, "document", { value: dom.window.document, configurable: true });
|
||||
Object.defineProperty(globalThis, "navigator", { value: dom.window.navigator, configurable: true });
|
||||
Object.defineProperty(globalThis, "KeyboardEvent", { value: dom.window.KeyboardEvent, configurable: true });
|
||||
Object.defineProperty(globalThis, "CustomEvent", { value: dom.window.CustomEvent, configurable: true });
|
||||
Object.defineProperty(globalThis, "HTMLElement", { value: dom.window.HTMLElement, configurable: true });
|
||||
Object.defineProperty(globalThis, "HTMLInputElement", { value: dom.window.HTMLInputElement, configurable: true });
|
||||
Object.defineProperty(globalThis, "Element", { value: dom.window.Element, configurable: true });
|
||||
Object.defineProperty(globalThis, "Node", { value: dom.window.Node, configurable: true });
|
||||
Object.defineProperty(globalThis, "NodeFilter", { value: dom.window.NodeFilter, configurable: true });
|
||||
Object.defineProperty(globalThis, "DocumentFragment", { value: dom.window.DocumentFragment, configurable: true });
|
||||
Object.defineProperty(globalThis, "MutationObserver", { value: dom.window.MutationObserver, configurable: true });
|
||||
Object.defineProperty(globalThis, "getComputedStyle", { value: dom.window.getComputedStyle.bind(dom.window), configurable: true });
|
||||
Object.defineProperty(globalThis, "requestAnimationFrame", {
|
||||
value: (cb: FrameRequestCallback) => setTimeout(() => cb(Date.now()), 0),
|
||||
configurable: true,
|
||||
});
|
||||
Object.defineProperty(globalThis, "cancelAnimationFrame", {
|
||||
value: (id: number) => clearTimeout(id),
|
||||
configurable: true,
|
||||
});
|
||||
|
||||
// Import after installing DOM globals so React DOM and Radix Portal see the browser environment.
|
||||
const { createRoot } = await import("react-dom/client");
|
||||
const { I18nProvider } = await import("../application/i18n/I18nProvider.tsx");
|
||||
const { TooltipProvider } = await import("./ui/tooltip.tsx");
|
||||
const { default: QuickAddSnippetDialog } = await import("./QuickAddSnippetDialog.tsx");
|
||||
|
||||
let root: Root | undefined;
|
||||
try {
|
||||
await act(async () => {
|
||||
root = createRoot(dom.window.document.getElementById("root")!);
|
||||
root.render(
|
||||
<I18nProvider locale="en">
|
||||
<TooltipProvider>
|
||||
<QuickAddSnippetDialog
|
||||
snippets={[]}
|
||||
packages={[]}
|
||||
hotkeyScheme="pc"
|
||||
keyBindings={[]}
|
||||
onCreateSnippet={() => {}}
|
||||
/>
|
||||
</TooltipProvider>
|
||||
</I18nProvider>,
|
||||
);
|
||||
});
|
||||
|
||||
await act(async () => {
|
||||
dom.window.dispatchEvent(new dom.window.CustomEvent("netcatty:snippets:add", { detail: { command: "pwd" } }));
|
||||
});
|
||||
|
||||
const recordButton = dom.window.document.querySelector<HTMLButtonElement>("button[aria-pressed]");
|
||||
assert.ok(recordButton, "expected shortkey record button inside open QuickAddSnippetDialog");
|
||||
|
||||
await act(async () => {
|
||||
recordButton.click();
|
||||
});
|
||||
assert.equal(recordButton.getAttribute("aria-pressed"), "true");
|
||||
|
||||
const lockOverlay = dom.window.document.createElement("div");
|
||||
lockOverlay.setAttribute("data-app-lock-overlay", "true");
|
||||
dom.window.document.body.appendChild(lockOverlay);
|
||||
|
||||
const lockedEvent = new dom.window.KeyboardEvent("keydown", {
|
||||
key: "k",
|
||||
ctrlKey: true,
|
||||
shiftKey: true,
|
||||
cancelable: true,
|
||||
});
|
||||
await act(async () => {
|
||||
dom.window.dispatchEvent(lockedEvent);
|
||||
});
|
||||
assert.equal(lockedEvent.defaultPrevented, false);
|
||||
assert.equal(recordButton.getAttribute("aria-pressed"), "true");
|
||||
assert.doesNotMatch(recordButton.textContent ?? "", /Ctrl \+ Shift \+ K/);
|
||||
|
||||
lockOverlay.remove();
|
||||
|
||||
const unlockedEvent = new dom.window.KeyboardEvent("keydown", {
|
||||
key: "k",
|
||||
ctrlKey: true,
|
||||
shiftKey: true,
|
||||
cancelable: true,
|
||||
});
|
||||
await act(async () => {
|
||||
dom.window.dispatchEvent(unlockedEvent);
|
||||
});
|
||||
assert.equal(unlockedEvent.defaultPrevented, true);
|
||||
assert.equal(recordButton.getAttribute("aria-pressed"), "false");
|
||||
assert.match(recordButton.textContent ?? "", /Ctrl \+ Shift \+ K/);
|
||||
} finally {
|
||||
await act(async () => {
|
||||
root?.unmount();
|
||||
});
|
||||
env.IS_REACT_ACT_ENVIRONMENT = prevAct;
|
||||
Object.defineProperty(globalThis, "window", { value: prevWindow, configurable: true });
|
||||
Object.defineProperty(globalThis, "document", { value: prevDocument, configurable: true });
|
||||
Object.defineProperty(globalThis, "navigator", { value: prevNavigator, configurable: true });
|
||||
Object.defineProperty(globalThis, "KeyboardEvent", { value: prevKeyboardEvent, configurable: true });
|
||||
Object.defineProperty(globalThis, "CustomEvent", { value: prevCustomEvent, configurable: true });
|
||||
Object.defineProperty(globalThis, "HTMLElement", { value: prevHTMLElement, configurable: true });
|
||||
Object.defineProperty(globalThis, "HTMLInputElement", { value: prevHTMLInputElement, configurable: true });
|
||||
Object.defineProperty(globalThis, "Element", { value: prevElement, configurable: true });
|
||||
Object.defineProperty(globalThis, "Node", { value: prevNode, configurable: true });
|
||||
Object.defineProperty(globalThis, "NodeFilter", { value: prevNodeFilter, configurable: true });
|
||||
Object.defineProperty(globalThis, "DocumentFragment", { value: prevDocumentFragment, configurable: true });
|
||||
Object.defineProperty(globalThis, "MutationObserver", { value: prevMutationObserver, configurable: true });
|
||||
Object.defineProperty(globalThis, "getComputedStyle", { value: prevGetComputedStyle, configurable: true });
|
||||
Object.defineProperty(globalThis, "requestAnimationFrame", { value: prevRaf, configurable: true });
|
||||
Object.defineProperty(globalThis, "cancelAnimationFrame", { value: prevCancelRaf, configurable: true });
|
||||
dom.window.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("quick add snippet event can prefill command", async () => {
|
||||
const { getQuickAddSnippetInitialCommand } = await import("./QuickAddSnippetDialog.tsx");
|
||||
const event = {
|
||||
detail: { command: "ls -la\npwd" },
|
||||
} as CustomEvent<{ command?: string }>;
|
||||
@@ -14,7 +171,8 @@ test("quick add snippet event can prefill command", () => {
|
||||
assert.equal(getQuickAddSnippetInitialCommand(event), "ls -la\npwd");
|
||||
});
|
||||
|
||||
test("quick add snippet event defaults to an empty command", () => {
|
||||
test("quick add snippet event defaults to an empty command", async () => {
|
||||
const { getQuickAddSnippetInitialCommand } = await import("./QuickAddSnippetDialog.tsx");
|
||||
assert.equal(getQuickAddSnippetInitialCommand({} as Event), "");
|
||||
assert.equal(
|
||||
getQuickAddSnippetInitialCommand({
|
||||
@@ -29,8 +187,9 @@ test("quick add snippet form binds shortkeys and uses a centered Dialog modal",
|
||||
assert.match(source, /from '\.\/ui\/dialog'/);
|
||||
assert.doesNotMatch(source, /AsidePanel/);
|
||||
assert.match(source, /snippets\.field\.shortkey/);
|
||||
assert.match(source, /findActiveSystemShortcutConflict/);
|
||||
assert.match(source, /keyEventToString/);
|
||||
assert.match(source, /useSnippetShortkeyRecorder/);
|
||||
assert.match(recorderSource, /findActiveSystemShortcutConflict/);
|
||||
assert.match(recorderSource, /keyEventToString/);
|
||||
assert.match(source, /shortkey: shortkey \|\| undefined/);
|
||||
assert.match(source, /if \(e\.defaultPrevented\) return/);
|
||||
// Escape while recording a shortkey cancels capture instead of closing
|
||||
|
||||
@@ -11,17 +11,10 @@
|
||||
import { Keyboard, Package, RotateCcw } from 'lucide-react';
|
||||
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { useI18n } from '../application/i18n/I18nProvider';
|
||||
import type { Snippet } from '../domain/models';
|
||||
import { findActiveSystemShortcutConflict } from '../domain/activeKeyBindings';
|
||||
import {
|
||||
type HotkeyScheme,
|
||||
type KeyBinding,
|
||||
keyEventToString,
|
||||
keyStringToKeyboardEvent,
|
||||
matchesKeyBinding,
|
||||
} from '../domain/models';
|
||||
import { useSnippetShortkeyRecorder } from '../application/state/useSnippetShortkeyRecorder';
|
||||
import type { HotkeyScheme, KeyBinding, Snippet } from '../domain/models';
|
||||
import { isScriptSnippet } from '../domain/snippetScript.ts';
|
||||
import { cn, isMacPlatform } from '../lib/utils';
|
||||
import { cn } from '../lib/utils';
|
||||
import { Button } from './ui/button';
|
||||
import { Combobox } from './ui/combobox';
|
||||
import {
|
||||
@@ -71,11 +64,23 @@ export const QuickAddSnippetDialog: React.FC<QuickAddSnippetDialogProps> = ({
|
||||
const [noAutoRun, setNoAutoRun] = useState(false);
|
||||
const [multiLineRunMode, setMultiLineRunMode] = useState<Snippet['multiLineRunMode']>(undefined);
|
||||
const [shortkey, setShortkey] = useState<string | undefined>(undefined);
|
||||
const [isRecordingShortkey, setIsRecordingShortkey] = useState(false);
|
||||
const [shortkeyError, setShortkeyError] = useState<string | null>(null);
|
||||
const [editing, setEditing] = useState<Snippet | null>(null);
|
||||
const labelInputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
const {
|
||||
isRecordingShortkey,
|
||||
setIsRecordingShortkey,
|
||||
shortkeyError,
|
||||
setShortkeyError,
|
||||
} = useSnippetShortkeyRecorder({
|
||||
snippets,
|
||||
editingSnippetId: editing?.id,
|
||||
hotkeyScheme,
|
||||
keyBindings,
|
||||
t,
|
||||
onCapture: setShortkey,
|
||||
});
|
||||
|
||||
// Listen for the global "add snippet" request dispatched by the
|
||||
// terminal-side ScriptsSidePanel + button. We reset form state on
|
||||
// every open so stale input from a previous cancel does not leak.
|
||||
@@ -94,7 +99,7 @@ export const QuickAddSnippetDialog: React.FC<QuickAddSnippetDialogProps> = ({
|
||||
};
|
||||
window.addEventListener('netcatty:snippets:add', handler);
|
||||
return () => window.removeEventListener('netcatty:snippets:add', handler);
|
||||
}, []);
|
||||
}, [setIsRecordingShortkey, setShortkeyError]);
|
||||
|
||||
// Sibling event for editing an existing snippet from the ScriptsSidePanel
|
||||
// context menu. Prefills the form and flips the dialog into update mode.
|
||||
@@ -116,7 +121,7 @@ export const QuickAddSnippetDialog: React.FC<QuickAddSnippetDialogProps> = ({
|
||||
};
|
||||
window.addEventListener('netcatty:snippets:edit', handler);
|
||||
return () => window.removeEventListener('netcatty:snippets:edit', handler);
|
||||
}, []);
|
||||
}, [setIsRecordingShortkey, setShortkeyError]);
|
||||
|
||||
// Focus the label field when the modal opens.
|
||||
useEffect(() => {
|
||||
@@ -125,100 +130,6 @@ export const QuickAddSnippetDialog: React.FC<QuickAddSnippetDialogProps> = ({
|
||||
return () => window.clearTimeout(focusTimer);
|
||||
}, [open]);
|
||||
|
||||
const isMac = useMemo(() => (
|
||||
hotkeyScheme === 'mac' || (hotkeyScheme === 'disabled' && isMacPlatform())
|
||||
), [hotkeyScheme]);
|
||||
|
||||
const existingShortkeys = useMemo(() => (
|
||||
snippets.filter((s) => Boolean(s.shortkey) && s.id !== editing?.id)
|
||||
), [snippets, editing?.id]);
|
||||
|
||||
const normalizeKeyString = useCallback((value: string) => (
|
||||
value.toLowerCase().replace(/\s+/g, '')
|
||||
), []);
|
||||
|
||||
const validateShortkey = useCallback((key: string): string | null => {
|
||||
if (!key) return null;
|
||||
|
||||
const systemConflict = findActiveSystemShortcutConflict(key, hotkeyScheme, keyBindings);
|
||||
if (systemConflict) {
|
||||
const nameKey = `settings.shortcuts.binding.${systemConflict.id}`;
|
||||
const name = t(nameKey) !== nameKey ? t(nameKey) : systemConflict.label;
|
||||
return t('snippets.shortkey.error.systemConflict', { name });
|
||||
}
|
||||
|
||||
const syntheticEvent = keyStringToKeyboardEvent(key);
|
||||
if (syntheticEvent) {
|
||||
for (const snippet of existingShortkeys) {
|
||||
if (snippet.shortkey && matchesKeyBinding(syntheticEvent, snippet.shortkey, isMac)) {
|
||||
return t('snippets.shortkey.error.snippetConflict', { name: snippet.label });
|
||||
}
|
||||
}
|
||||
} else {
|
||||
const normalizedKey = normalizeKeyString(key);
|
||||
const conflictingSnippet = existingShortkeys.find((snippet) => (
|
||||
snippet.shortkey && normalizeKeyString(snippet.shortkey) === normalizedKey
|
||||
));
|
||||
if (conflictingSnippet) {
|
||||
return t('snippets.shortkey.error.snippetConflict', { name: conflictingSnippet.label });
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}, [
|
||||
existingShortkeys,
|
||||
hotkeyScheme,
|
||||
isMac,
|
||||
keyBindings,
|
||||
normalizeKeyString,
|
||||
t,
|
||||
]);
|
||||
|
||||
// Shortkey recording capture. Escape cancels recording only (does not close the modal).
|
||||
useEffect(() => {
|
||||
if (!isRecordingShortkey) return;
|
||||
|
||||
const handleKeyDown = (e: KeyboardEvent) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
|
||||
if (e.key === 'Escape') {
|
||||
setIsRecordingShortkey(false);
|
||||
setShortkeyError(null);
|
||||
return;
|
||||
}
|
||||
|
||||
if (['Meta', 'Control', 'Alt', 'Shift'].includes(e.key)) return;
|
||||
|
||||
const keyString = keyEventToString(e, isMac);
|
||||
const error = validateShortkey(keyString);
|
||||
if (error) {
|
||||
setShortkeyError(error);
|
||||
return;
|
||||
}
|
||||
|
||||
setShortkeyError(null);
|
||||
setShortkey(keyString);
|
||||
setIsRecordingShortkey(false);
|
||||
};
|
||||
|
||||
const handleClick = () => {
|
||||
setIsRecordingShortkey(false);
|
||||
setShortkeyError(null);
|
||||
};
|
||||
|
||||
const timer = setTimeout(() => {
|
||||
window.addEventListener('click', handleClick, true);
|
||||
}, 100);
|
||||
|
||||
window.addEventListener('keydown', handleKeyDown, true);
|
||||
return () => {
|
||||
clearTimeout(timer);
|
||||
window.removeEventListener('keydown', handleKeyDown, true);
|
||||
window.removeEventListener('click', handleClick, true);
|
||||
};
|
||||
}, [isRecordingShortkey, isMac, validateShortkey]);
|
||||
|
||||
// Derive combobox options from the union of existing packages (from
|
||||
// props) and any package path referenced by an existing snippet, so
|
||||
// the user can reuse anything they see in the main snippets view.
|
||||
@@ -239,7 +150,7 @@ export const QuickAddSnippetDialog: React.FC<QuickAddSnippetDialogProps> = ({
|
||||
setOpen(false);
|
||||
setIsRecordingShortkey(false);
|
||||
setShortkeyError(null);
|
||||
}, []);
|
||||
}, [setIsRecordingShortkey, setShortkeyError]);
|
||||
|
||||
const handleOpenChange = useCallback((nextOpen: boolean) => {
|
||||
if (!nextOpen) {
|
||||
|
||||
@@ -1,17 +1,37 @@
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { readFileSync } from "node:fs";
|
||||
import React from "react";
|
||||
import { registerHooks } from "node:module";
|
||||
import { JSDOM } from "jsdom";
|
||||
import React, { act } from "react";
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
|
||||
registerHooks({
|
||||
resolve(specifier, context, nextResolve) {
|
||||
if (
|
||||
specifier === "./snippets/SnippetScriptEditor"
|
||||
&& context.parentURL?.endsWith("/SnippetsRightPanel.tsx")
|
||||
) {
|
||||
return {
|
||||
url: "data:text/javascript,export function SnippetScriptEditor(){return null}",
|
||||
shortCircuit: true,
|
||||
};
|
||||
}
|
||||
return nextResolve(specifier, context);
|
||||
},
|
||||
});
|
||||
|
||||
import { I18nProvider, useI18n } from "../application/i18n/I18nProvider.tsx";
|
||||
import type { Snippet } from "../types.ts";
|
||||
import { Dialog } from "./ui/dialog.tsx";
|
||||
import SnippetsManager, {
|
||||
|
||||
const {
|
||||
default: SnippetsManager,
|
||||
SNIPPET_IMPORT_SAMPLE_FILES,
|
||||
SnippetImportDialogContent,
|
||||
buildSnippetImportSamplesZip,
|
||||
} from "./SnippetsManager.tsx";
|
||||
} = await import("./SnippetsManager.tsx");
|
||||
|
||||
const installStorageStub = () => {
|
||||
const values = new Map<string, string>();
|
||||
@@ -111,12 +131,133 @@ test("snippet import sample files include standard and array formats", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
test("buildSnippetImportSamplesZip returns a zip archive", async () => {
|
||||
test("buildSnippetImportSamplesZip returns a zip archive with all sample entries", async () => {
|
||||
const blob = buildSnippetImportSamplesZip();
|
||||
const bytes = new Uint8Array(await blob.arrayBuffer());
|
||||
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
||||
const text = new TextDecoder().decode(bytes);
|
||||
|
||||
assert.equal(blob.type, "application/zip");
|
||||
assert.deepEqual(Array.from(bytes.slice(0, 4)), [0x50, 0x4b, 0x03, 0x04]);
|
||||
// General purpose bit flag sets UTF-8 encoding (0x0800) via shared lib/textZip builder.
|
||||
assert.equal(view.getUint16(6, true), 0x0800);
|
||||
// End of central directory signature at tail (fixed 22-byte EOCD with 0-length comment).
|
||||
assert.equal(view.getUint32(bytes.length - 22, true), 0x06054b50);
|
||||
assert.equal(view.getUint16(bytes.length - 12, true), SNIPPET_IMPORT_SAMPLE_FILES.length);
|
||||
for (const file of SNIPPET_IMPORT_SAMPLE_FILES) {
|
||||
assert.ok(text.includes(file.name), `missing ${file.name} in zip archive`);
|
||||
assert.ok(text.includes(`${file.content}\n`), `missing trailing newline for ${file.name}`);
|
||||
}
|
||||
});
|
||||
|
||||
test("SnippetsManager blocks shortkey recording while app lock overlay is active", async () => {
|
||||
installStorageStub();
|
||||
const dom = new JSDOM("<!doctype html><html><body><div id='root'></div></body></html>");
|
||||
const prevWindow = globalThis.window;
|
||||
const prevDocument = globalThis.document;
|
||||
const prevNavigator = globalThis.navigator;
|
||||
const prevKeyboardEvent = globalThis.KeyboardEvent;
|
||||
const prevHTMLElement = globalThis.HTMLElement;
|
||||
const prevNode = globalThis.Node;
|
||||
const prevRaf = globalThis.requestAnimationFrame;
|
||||
const prevCancelRaf = globalThis.cancelAnimationFrame;
|
||||
const env = globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean };
|
||||
const prevAct = env.IS_REACT_ACT_ENVIRONMENT;
|
||||
|
||||
env.IS_REACT_ACT_ENVIRONMENT = true;
|
||||
Object.defineProperty(globalThis, "window", { value: dom.window, configurable: true });
|
||||
Object.defineProperty(globalThis, "document", { value: dom.window.document, configurable: true });
|
||||
Object.defineProperty(globalThis, "navigator", { value: dom.window.navigator, configurable: true });
|
||||
Object.defineProperty(globalThis, "KeyboardEvent", { value: dom.window.KeyboardEvent, configurable: true });
|
||||
Object.defineProperty(globalThis, "HTMLElement", { value: dom.window.HTMLElement, configurable: true });
|
||||
Object.defineProperty(globalThis, "Node", { value: dom.window.Node, configurable: true });
|
||||
Object.defineProperty(globalThis, "requestAnimationFrame", {
|
||||
value: (cb: FrameRequestCallback) => setTimeout(() => cb(Date.now()), 0),
|
||||
configurable: true,
|
||||
});
|
||||
Object.defineProperty(globalThis, "cancelAnimationFrame", {
|
||||
value: (id: number) => clearTimeout(id),
|
||||
configurable: true,
|
||||
});
|
||||
|
||||
const noop = () => {};
|
||||
let root: Root | undefined;
|
||||
try {
|
||||
await act(async () => {
|
||||
root = createRoot(dom.window.document.getElementById("root")!);
|
||||
root.render(
|
||||
<I18nProvider locale="en">
|
||||
<SnippetsManager
|
||||
snippets={[snippet]}
|
||||
packages={["ops"]}
|
||||
hosts={[]}
|
||||
hotkeyScheme="pc"
|
||||
keyBindings={[]}
|
||||
openSnippetId={snippet.id}
|
||||
openSnippetRequestId={1}
|
||||
onSave={noop}
|
||||
onBulkSave={noop}
|
||||
onDelete={noop}
|
||||
onPackagesChange={noop}
|
||||
/>
|
||||
</I18nProvider>,
|
||||
);
|
||||
});
|
||||
|
||||
const recordButton = (Array.from(dom.window.document.querySelectorAll("button")) as HTMLButtonElement[]).find((button) => (
|
||||
(button.textContent ?? "").includes("Click to set shortcut")
|
||||
));
|
||||
assert.ok(recordButton, "expected shortkey record button in SnippetsManager edit panel");
|
||||
|
||||
await act(async () => {
|
||||
recordButton.click();
|
||||
});
|
||||
assert.match(recordButton.textContent ?? "", /Press a key combination/);
|
||||
|
||||
const lockOverlay = dom.window.document.createElement("div");
|
||||
lockOverlay.setAttribute("data-app-lock-overlay", "true");
|
||||
dom.window.document.body.appendChild(lockOverlay);
|
||||
|
||||
const lockedEvent = new dom.window.KeyboardEvent("keydown", {
|
||||
key: "j",
|
||||
ctrlKey: true,
|
||||
shiftKey: true,
|
||||
cancelable: true,
|
||||
});
|
||||
await act(async () => {
|
||||
dom.window.dispatchEvent(lockedEvent);
|
||||
});
|
||||
assert.equal(lockedEvent.defaultPrevented, false);
|
||||
assert.match(recordButton.textContent ?? "", /Press a key combination/);
|
||||
|
||||
lockOverlay.remove();
|
||||
|
||||
const unlockedEvent = new dom.window.KeyboardEvent("keydown", {
|
||||
key: "j",
|
||||
ctrlKey: true,
|
||||
shiftKey: true,
|
||||
cancelable: true,
|
||||
});
|
||||
await act(async () => {
|
||||
dom.window.dispatchEvent(unlockedEvent);
|
||||
});
|
||||
assert.equal(unlockedEvent.defaultPrevented, true);
|
||||
assert.match(recordButton.textContent ?? "", /Ctrl \+ Shift \+ J/);
|
||||
} finally {
|
||||
await act(async () => {
|
||||
root?.unmount();
|
||||
});
|
||||
env.IS_REACT_ACT_ENVIRONMENT = prevAct;
|
||||
Object.defineProperty(globalThis, "window", { value: prevWindow, configurable: true });
|
||||
Object.defineProperty(globalThis, "document", { value: prevDocument, configurable: true });
|
||||
Object.defineProperty(globalThis, "navigator", { value: prevNavigator, configurable: true });
|
||||
Object.defineProperty(globalThis, "KeyboardEvent", { value: prevKeyboardEvent, configurable: true });
|
||||
Object.defineProperty(globalThis, "HTMLElement", { value: prevHTMLElement, configurable: true });
|
||||
Object.defineProperty(globalThis, "Node", { value: prevNode, configurable: true });
|
||||
Object.defineProperty(globalThis, "requestAnimationFrame", { value: prevRaf, configurable: true });
|
||||
Object.defineProperty(globalThis, "cancelAnimationFrame", { value: prevCancelRaf, configurable: true });
|
||||
dom.window.close();
|
||||
}
|
||||
});
|
||||
|
||||
const snippetsManagerSource = readFileSync(new URL("./SnippetsManager.tsx", import.meta.url), "utf8");
|
||||
|
||||
+23
-186
@@ -2,15 +2,16 @@ import { CheckSquare, ChevronDown, Clock, Copy, Download, Edit2, FileCode, Folde
|
||||
import React, { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react';
|
||||
import { useI18n } from '../application/i18n/I18nProvider';
|
||||
import { useStoredViewMode } from '../application/state/useStoredViewMode';
|
||||
import { useSnippetShortkeyRecorder } from '../application/state/useSnippetShortkeyRecorder';
|
||||
import { STORAGE_KEY_VAULT_SNIPPETS_VIEW_MODE } from '../infrastructure/config/storageKeys';
|
||||
import { cn, isMacPlatform } from '../lib/utils';
|
||||
import { buildTextFilesZipBlob } from '../lib/textZip';
|
||||
import { cn } from '../lib/utils';
|
||||
import { Host, ProxyProfile, ShellHistoryEntry, Snippet, SSHKey } from '../types';
|
||||
import {
|
||||
getShellHistorySnapshot,
|
||||
subscribeShellHistory,
|
||||
} from '../application/state/shellHistoryStore';
|
||||
import { findActiveSystemShortcutConflict } from '../domain/activeKeyBindings';
|
||||
import { HotkeyScheme, KeyBinding, keyEventToString, keyStringToKeyboardEvent, ManagedSource, matchesKeyBinding } from '../domain/models';
|
||||
import { HotkeyScheme, KeyBinding, ManagedSource } from '../domain/models';
|
||||
import {
|
||||
buildSnippetExportPayload,
|
||||
combineSnippetImportPayloads,
|
||||
@@ -227,94 +228,14 @@ export const SNIPPET_IMPORT_SAMPLE_FILES: SnippetImportSampleFile[] = [
|
||||
},
|
||||
];
|
||||
|
||||
const crcTable = Array.from({ length: 256 }, (_, index) => {
|
||||
let value = index;
|
||||
for (let bit = 0; bit < 8; bit += 1) {
|
||||
value = value & 1 ? 0xedb88320 ^ (value >>> 1) : value >>> 1;
|
||||
}
|
||||
return value >>> 0;
|
||||
});
|
||||
|
||||
const crc32 = (bytes: Uint8Array): number => {
|
||||
let crc = 0xffffffff;
|
||||
bytes.forEach((byte) => {
|
||||
crc = crcTable[(crc ^ byte) & 0xff] ^ (crc >>> 8);
|
||||
});
|
||||
return (crc ^ 0xffffffff) >>> 0;
|
||||
};
|
||||
|
||||
const pushUint16 = (parts: number[], value: number) => {
|
||||
parts.push(value & 0xff, (value >>> 8) & 0xff);
|
||||
};
|
||||
|
||||
const pushUint32 = (parts: number[], value: number) => {
|
||||
parts.push(value & 0xff, (value >>> 8) & 0xff, (value >>> 16) & 0xff, (value >>> 24) & 0xff);
|
||||
};
|
||||
|
||||
export const buildSnippetImportSamplesZip = (files: SnippetImportSampleFile[] = SNIPPET_IMPORT_SAMPLE_FILES): Blob => {
|
||||
const encoder = new TextEncoder();
|
||||
const chunks: Array<Uint8Array> = [];
|
||||
const centralDirectory: Uint8Array[] = [];
|
||||
let offset = 0;
|
||||
|
||||
files.forEach((file) => {
|
||||
const nameBytes = encoder.encode(file.name);
|
||||
const contentBytes = encoder.encode(`${file.content}\n`);
|
||||
const checksum = crc32(contentBytes);
|
||||
|
||||
const localHeader: number[] = [];
|
||||
pushUint32(localHeader, 0x04034b50);
|
||||
pushUint16(localHeader, 20);
|
||||
pushUint16(localHeader, 0);
|
||||
pushUint16(localHeader, 0);
|
||||
pushUint16(localHeader, 0);
|
||||
pushUint16(localHeader, 0);
|
||||
pushUint32(localHeader, checksum);
|
||||
pushUint32(localHeader, contentBytes.length);
|
||||
pushUint32(localHeader, contentBytes.length);
|
||||
pushUint16(localHeader, nameBytes.length);
|
||||
pushUint16(localHeader, 0);
|
||||
const localChunk = new Uint8Array([...localHeader, ...nameBytes, ...contentBytes]);
|
||||
chunks.push(localChunk);
|
||||
|
||||
const centralHeader: number[] = [];
|
||||
pushUint32(centralHeader, 0x02014b50);
|
||||
pushUint16(centralHeader, 20);
|
||||
pushUint16(centralHeader, 20);
|
||||
pushUint16(centralHeader, 0);
|
||||
pushUint16(centralHeader, 0);
|
||||
pushUint16(centralHeader, 0);
|
||||
pushUint16(centralHeader, 0);
|
||||
pushUint32(centralHeader, checksum);
|
||||
pushUint32(centralHeader, contentBytes.length);
|
||||
pushUint32(centralHeader, contentBytes.length);
|
||||
pushUint16(centralHeader, nameBytes.length);
|
||||
pushUint16(centralHeader, 0);
|
||||
pushUint16(centralHeader, 0);
|
||||
pushUint16(centralHeader, 0);
|
||||
pushUint16(centralHeader, 0);
|
||||
pushUint32(centralHeader, 0);
|
||||
pushUint32(centralHeader, offset);
|
||||
centralDirectory.push(new Uint8Array([...centralHeader, ...nameBytes]));
|
||||
|
||||
offset += localChunk.length;
|
||||
});
|
||||
|
||||
const centralDirectorySize = centralDirectory.reduce((total, chunk) => total + chunk.length, 0);
|
||||
const endRecord: number[] = [];
|
||||
pushUint32(endRecord, 0x06054b50);
|
||||
pushUint16(endRecord, 0);
|
||||
pushUint16(endRecord, 0);
|
||||
pushUint16(endRecord, files.length);
|
||||
pushUint16(endRecord, files.length);
|
||||
pushUint32(endRecord, centralDirectorySize);
|
||||
pushUint32(endRecord, offset);
|
||||
pushUint16(endRecord, 0);
|
||||
|
||||
return new Blob([...chunks, ...centralDirectory, new Uint8Array(endRecord)], {
|
||||
type: "application/zip",
|
||||
});
|
||||
};
|
||||
export const buildSnippetImportSamplesZip = (
|
||||
files: SnippetImportSampleFile[] = SNIPPET_IMPORT_SAMPLE_FILES,
|
||||
): Blob => buildTextFilesZipBlob(
|
||||
files.map((file) => ({
|
||||
name: file.name,
|
||||
content: `${file.content}\n`,
|
||||
})),
|
||||
);
|
||||
|
||||
type SnippetsT = ReturnType<typeof useI18n>['t'];
|
||||
|
||||
@@ -611,105 +532,21 @@ const SnippetsManager: React.FC<SnippetsManagerProps> = ({
|
||||
const historyScrollRef = useRef<HTMLDivElement>(null);
|
||||
const [isLoadingMore, setIsLoadingMore] = useState(false);
|
||||
|
||||
const [isRecordingShortkey, setIsRecordingShortkey] = useState(false);
|
||||
const [shortkeyError, setShortkeyError] = useState<string | null>(null);
|
||||
|
||||
const existingShortkeys = useMemo(() => (
|
||||
snippets.filter(s => Boolean(s.shortkey) && s.id !== editingSnippet.id)
|
||||
), [snippets, editingSnippet.id]);
|
||||
|
||||
const isMac = useMemo(() => (
|
||||
hotkeyScheme === 'mac' || (hotkeyScheme === 'disabled' && isMacPlatform())
|
||||
), [hotkeyScheme]);
|
||||
|
||||
const normalizeKeyString = useCallback((value: string) => (
|
||||
value.toLowerCase().replace(/\s+/g, '')
|
||||
), []);
|
||||
|
||||
const validateShortkey = useCallback((key: string): string | null => {
|
||||
if (!key) return null;
|
||||
|
||||
const systemConflict = findActiveSystemShortcutConflict(key, hotkeyScheme, keyBindings);
|
||||
if (systemConflict) {
|
||||
const nameKey = `settings.shortcuts.binding.${systemConflict.id}`;
|
||||
const name = t(nameKey) !== nameKey ? t(nameKey) : systemConflict.label;
|
||||
return t('snippets.shortkey.error.systemConflict', { name });
|
||||
}
|
||||
|
||||
const syntheticEvent = keyStringToKeyboardEvent(key);
|
||||
if (syntheticEvent) {
|
||||
for (const snippet of existingShortkeys) {
|
||||
if (snippet.shortkey && matchesKeyBinding(syntheticEvent, snippet.shortkey, isMac)) {
|
||||
return t('snippets.shortkey.error.snippetConflict', { name: snippet.label });
|
||||
}
|
||||
}
|
||||
} else {
|
||||
const normalizedKey = normalizeKeyString(key);
|
||||
const conflictingSnippet = existingShortkeys.find(snippet => (
|
||||
snippet.shortkey && normalizeKeyString(snippet.shortkey) === normalizedKey
|
||||
));
|
||||
if (conflictingSnippet) {
|
||||
return t('snippets.shortkey.error.snippetConflict', { name: conflictingSnippet.label });
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}, [
|
||||
existingShortkeys,
|
||||
const {
|
||||
isRecordingShortkey,
|
||||
setIsRecordingShortkey,
|
||||
shortkeyError,
|
||||
setShortkeyError,
|
||||
} = useSnippetShortkeyRecorder({
|
||||
snippets,
|
||||
editingSnippetId: editingSnippet.id,
|
||||
hotkeyScheme,
|
||||
isMac,
|
||||
keyBindings,
|
||||
normalizeKeyString,
|
||||
t,
|
||||
]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isRecordingShortkey) return;
|
||||
|
||||
const handleKeyDown = (e: KeyboardEvent) => {
|
||||
// App lock overlay installs later; skip while locked so password keys
|
||||
// never mutate shortkeys (Codex P2).
|
||||
if (isAppLockOverlayActive()) return;
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
|
||||
if (e.key === 'Escape') {
|
||||
setIsRecordingShortkey(false);
|
||||
setShortkeyError(null);
|
||||
return;
|
||||
}
|
||||
|
||||
if (['Meta', 'Control', 'Alt', 'Shift'].includes(e.key)) return;
|
||||
|
||||
const keyString = keyEventToString(e, isMac);
|
||||
|
||||
const error = validateShortkey(keyString);
|
||||
if (error) {
|
||||
setShortkeyError(error);
|
||||
return;
|
||||
}
|
||||
|
||||
setShortkeyError(null);
|
||||
onCapture: (keyString) => {
|
||||
setEditingSnippet(prev => ({ ...prev, shortkey: keyString }));
|
||||
setIsRecordingShortkey(false);
|
||||
};
|
||||
|
||||
const handleClick = () => {
|
||||
setIsRecordingShortkey(false);
|
||||
setShortkeyError(null);
|
||||
};
|
||||
|
||||
const timer = setTimeout(() => {
|
||||
window.addEventListener('click', handleClick, true);
|
||||
}, 100);
|
||||
|
||||
window.addEventListener('keydown', handleKeyDown, true);
|
||||
return () => {
|
||||
clearTimeout(timer);
|
||||
window.removeEventListener('keydown', handleKeyDown, true);
|
||||
window.removeEventListener('click', handleClick, true);
|
||||
};
|
||||
}, [isRecordingShortkey, isMac, validateShortkey]);
|
||||
},
|
||||
});
|
||||
|
||||
const handleEdit = useCallback((snippet?: Snippet, asScript = false) => {
|
||||
if (snippet) {
|
||||
|
||||
@@ -37,6 +37,7 @@ import {
|
||||
localizeSpecSuggestionDescriptions,
|
||||
} from "./autocompleteDescriptionI18n";
|
||||
import type { AutocompleteHistoryScope, Snippet } from "../../../domain/models";
|
||||
import { tokenizeShellLike } from "../../../domain/shellTokenizer";
|
||||
import type { AutocompleteCwdSource } from "./terminalAutocompleteLayout";
|
||||
|
||||
/** Source indicator for where a suggestion came from */
|
||||
@@ -168,65 +169,11 @@ export function shellEscape(name: string): string {
|
||||
return name;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse a command line string into tokens, handling quoting.
|
||||
*/
|
||||
function tokenize(input: string): string[] {
|
||||
const tokens: string[] = [];
|
||||
let current = "";
|
||||
let inSingleQuote = false;
|
||||
let inDoubleQuote = false;
|
||||
let escaped = false;
|
||||
|
||||
for (let i = 0; i < input.length; i++) {
|
||||
const ch = input[i];
|
||||
|
||||
if (escaped) {
|
||||
current += ch;
|
||||
escaped = false;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (ch === "\\") {
|
||||
escaped = true;
|
||||
current += ch;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (ch === "'" && !inDoubleQuote) {
|
||||
inSingleQuote = !inSingleQuote;
|
||||
current += ch;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (ch === '"' && !inSingleQuote) {
|
||||
inDoubleQuote = !inDoubleQuote;
|
||||
current += ch;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (ch === " " && !inSingleQuote && !inDoubleQuote) {
|
||||
if (current.length > 0) {
|
||||
tokens.push(current);
|
||||
current = "";
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
current += ch;
|
||||
}
|
||||
|
||||
// Always include the last token (even if empty, to indicate trailing space)
|
||||
tokens.push(current);
|
||||
|
||||
return tokens;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse the current command line into a CompletionContext.
|
||||
*/
|
||||
export function parseCommandLine(input: string): CompletionContext {
|
||||
const tokens = tokenize(input);
|
||||
const tokens = tokenizeShellLike(input);
|
||||
const wordIndex = tokens.length - 1;
|
||||
const currentWord = tokens[wordIndex] || "";
|
||||
const commandName = tokens.length > 0 ? normalizeCommandName(tokens[0]) : "";
|
||||
|
||||
@@ -138,47 +138,11 @@ export type PendingTerminalSelectionForAI = {
|
||||
text: string;
|
||||
};
|
||||
|
||||
export function hexToHslToken(hex: string): string {
|
||||
const normalized = hex.startsWith('#') ? hex : `#${hex}`;
|
||||
const r = parseInt(normalized.slice(1, 3), 16) / 255;
|
||||
const g = parseInt(normalized.slice(3, 5), 16) / 255;
|
||||
const b = parseInt(normalized.slice(5, 7), 16) / 255;
|
||||
const max = Math.max(r, g, b);
|
||||
const min = Math.min(r, g, b);
|
||||
let h = 0;
|
||||
let s = 0;
|
||||
const l = (max + min) / 2;
|
||||
|
||||
if (max !== min) {
|
||||
const d = max - min;
|
||||
s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
|
||||
switch (max) {
|
||||
case r:
|
||||
h = ((g - b) / d + (g < b ? 6 : 0)) / 6;
|
||||
break;
|
||||
case g:
|
||||
h = ((b - r) / d + 2) / 6;
|
||||
break;
|
||||
default:
|
||||
h = ((r - g) / d + 4) / 6;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return `${Math.round(h * 3600) / 10} ${Math.round(s * 1000) / 10}% ${Math.round(l * 1000) / 10}%`;
|
||||
}
|
||||
|
||||
export function adjustLightnessToken(hsl: string, delta: number): string {
|
||||
const parts = hsl.split(/\s+/);
|
||||
const newL = Math.max(0, Math.min(100, parseFloat(parts[2]) + delta));
|
||||
return `${parts[0]} ${parts[1]} ${Math.round(newL * 10) / 10}%`;
|
||||
}
|
||||
|
||||
export function adjustSaturationToken(hsl: string, factor: number): string {
|
||||
const parts = hsl.split(/\s+/);
|
||||
const newS = Math.max(0, Math.min(100, parseFloat(parts[1]) * factor));
|
||||
return `${parts[0]} ${Math.round(newS * 10) / 10}% ${parts[2]}`;
|
||||
}
|
||||
export {
|
||||
adjustLightnessToken,
|
||||
adjustSaturationToken,
|
||||
hexToHslToken,
|
||||
} from '../../domain/colorContrast';
|
||||
|
||||
export const clearTerminalPreviewVars = (sessionId: string | null) => {
|
||||
if (!sessionId || typeof document === 'undefined') return;
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
|
||||
import {
|
||||
adjustLightnessToken,
|
||||
adjustSaturationToken,
|
||||
hexToHslToken,
|
||||
resolveReadableForegroundForHsl,
|
||||
} from "./colorContrast.ts";
|
||||
|
||||
test("hexToHslToken converts hex colors with or without leading hash", () => {
|
||||
assert.equal(hexToHslToken("#000000"), "0 0% 0%");
|
||||
assert.equal(hexToHslToken("#ffffff"), "0 0% 100%");
|
||||
assert.equal(hexToHslToken("#ff0000"), "0 100% 50%");
|
||||
assert.equal(hexToHslToken("00ff00"), "120 100% 50%");
|
||||
assert.equal(hexToHslToken("#0000ff"), "240 100% 50%");
|
||||
assert.equal(hexToHslToken("#1e1e2e"), hexToHslToken("1e1e2e"));
|
||||
});
|
||||
|
||||
test("adjustLightnessToken shifts lightness and clamps to [0, 100]", () => {
|
||||
assert.equal(adjustLightnessToken("240 21.1% 14.9%", 6), "240 21.1% 20.9%");
|
||||
assert.equal(adjustLightnessToken("240 21.1% 14.9%", -20), "240 21.1% 0%");
|
||||
assert.equal(adjustLightnessToken("240 21.1% 95%", 15), "240 21.1% 100%");
|
||||
});
|
||||
|
||||
test("adjustSaturationToken scales saturation and clamps to [0, 100]", () => {
|
||||
assert.equal(adjustSaturationToken("220 50% 80%", 0.5), "220 25% 80%");
|
||||
assert.equal(adjustSaturationToken("220 80% 80%", 2), "220 100% 80%");
|
||||
assert.equal(adjustSaturationToken("220 80% 80%", -1), "220 0% 80%");
|
||||
});
|
||||
|
||||
test("hexToHslToken pairs with resolveReadableForegroundForHsl", () => {
|
||||
assert.equal(resolveReadableForegroundForHsl(hexToHslToken("#111111")), "0 0% 100%");
|
||||
assert.equal(resolveReadableForegroundForHsl(hexToHslToken("#f5f5f5")), "0 0% 0%");
|
||||
});
|
||||
@@ -66,3 +66,45 @@ export const resolveReadableForegroundForHsl = (
|
||||
const whiteContrast = getContrastRatio(1, backgroundLuminance);
|
||||
return whiteContrast >= blackContrast ? WHITE_HSL : BLACK_HSL;
|
||||
};
|
||||
|
||||
export function hexToHslToken(hex: string): string {
|
||||
const normalized = hex.startsWith('#') ? hex : `#${hex}`;
|
||||
const r = parseInt(normalized.slice(1, 3), 16) / 255;
|
||||
const g = parseInt(normalized.slice(3, 5), 16) / 255;
|
||||
const b = parseInt(normalized.slice(5, 7), 16) / 255;
|
||||
const max = Math.max(r, g, b);
|
||||
const min = Math.min(r, g, b);
|
||||
let h = 0;
|
||||
let s = 0;
|
||||
const l = (max + min) / 2;
|
||||
|
||||
if (max !== min) {
|
||||
const d = max - min;
|
||||
s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
|
||||
switch (max) {
|
||||
case r:
|
||||
h = ((g - b) / d + (g < b ? 6 : 0)) / 6;
|
||||
break;
|
||||
case g:
|
||||
h = ((b - r) / d + 2) / 6;
|
||||
break;
|
||||
default:
|
||||
h = ((r - g) / d + 4) / 6;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return `${Math.round(h * 3600) / 10} ${Math.round(s * 1000) / 10}% ${Math.round(l * 1000) / 10}%`;
|
||||
}
|
||||
|
||||
export function adjustLightnessToken(hsl: string, delta: number): string {
|
||||
const parts = hsl.split(/\s+/);
|
||||
const newL = Math.max(0, Math.min(100, parseFloat(parts[2]) + delta));
|
||||
return `${parts[0]} ${parts[1]} ${Math.round(newL * 10) / 10}%`;
|
||||
}
|
||||
|
||||
export function adjustSaturationToken(hsl: string, factor: number): string {
|
||||
const parts = hsl.split(/\s+/);
|
||||
const newS = Math.max(0, Math.min(100, parseFloat(parts[1]) * factor));
|
||||
return `${parts[0]} ${Math.round(newS * 10) / 10}% ${parts[2]}`;
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
|
||||
import { tokenizeShellLike } from "./shellTokenizer.ts";
|
||||
|
||||
test("tokenizeShellLike splits unquoted tokens and preserves trailing space indicator", () => {
|
||||
assert.deepEqual(tokenizeShellLike(""), [""]);
|
||||
assert.deepEqual(tokenizeShellLike("git status"), ["git", "status"]);
|
||||
assert.deepEqual(tokenizeShellLike("git status "), ["git", "status", ""]);
|
||||
assert.deepEqual(tokenizeShellLike("git commit -m"), ["git", "commit", "-m"]);
|
||||
assert.deepEqual(tokenizeShellLike(" ls -la"), ["ls", "-la"]);
|
||||
});
|
||||
|
||||
test("tokenizeShellLike preserves single and double quoted segments", () => {
|
||||
assert.deepEqual(
|
||||
tokenizeShellLike(`git commit -m "hello world"`),
|
||||
["git", "commit", "-m", `"hello world"`],
|
||||
);
|
||||
assert.deepEqual(
|
||||
tokenizeShellLike(`grep 'foo bar' "baz 'qux'"`),
|
||||
["grep", `'foo bar'`, `"baz 'qux'"`],
|
||||
);
|
||||
assert.deepEqual(
|
||||
tokenizeShellLike(`echo "unclosed quote `),
|
||||
["echo", `"unclosed quote `],
|
||||
);
|
||||
});
|
||||
|
||||
test("tokenizeShellLike preserves backslash-escaped spaces and quotes", () => {
|
||||
assert.deepEqual(
|
||||
tokenizeShellLike("cd My\\ Folder/sub\\ dir"),
|
||||
["cd", "My\\ Folder/sub\\ dir"],
|
||||
);
|
||||
assert.deepEqual(
|
||||
tokenizeShellLike(`echo \\"quoted\\" 'a b'`),
|
||||
["echo", `\\"quoted\\"`, `'a b'`],
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,55 @@
|
||||
/**
|
||||
* Parse a shell-like command line string into tokens, preserving quotes and
|
||||
* backslash escapes. Always appends the trailing token (which may be empty
|
||||
* when the input ends with an unquoted space).
|
||||
*/
|
||||
export function tokenizeShellLike(input: string): string[] {
|
||||
const tokens: string[] = [];
|
||||
let current = "";
|
||||
let inSingleQuote = false;
|
||||
let inDoubleQuote = false;
|
||||
let escaped = false;
|
||||
|
||||
for (let i = 0; i < input.length; i++) {
|
||||
const ch = input[i];
|
||||
|
||||
if (escaped) {
|
||||
current += ch;
|
||||
escaped = false;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (ch === "\\") {
|
||||
escaped = true;
|
||||
current += ch;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (ch === "'" && !inDoubleQuote) {
|
||||
inSingleQuote = !inSingleQuote;
|
||||
current += ch;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (ch === '"' && !inSingleQuote) {
|
||||
inDoubleQuote = !inDoubleQuote;
|
||||
current += ch;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (ch === " " && !inSingleQuote && !inDoubleQuote) {
|
||||
if (current.length > 0) {
|
||||
tokens.push(current);
|
||||
current = "";
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
current += ch;
|
||||
}
|
||||
|
||||
// Always include the last token (even if empty, to indicate trailing space)
|
||||
tokens.push(current);
|
||||
|
||||
return tokens;
|
||||
}
|
||||
Reference in new issue
Block a user