Add ESLint + pre-commit hook and fix the issues it surfaced

This commit is contained in:
2026-06-05 01:42:42 +03:00
parent 3d38dd1411
commit 939950b136
10 changed files with 1543 additions and 53 deletions
+4
View File
@@ -0,0 +1,4 @@
# Format + lint the staged files, then run the full verify gate.
# At this project's size all three finish in ~2s; if the suite grows slow,
# move typecheck/test to a pre-push hook and leave lint-staged here.
npx lint-staged && npm run typecheck && npm test
+54
View File
@@ -0,0 +1,54 @@
import js from '@eslint/js';
import tseslint from 'typescript-eslint';
import reactHooks from 'eslint-plugin-react-hooks';
import reactRefresh from 'eslint-plugin-react-refresh';
import globals from 'globals';
export default tseslint.config(
// Ignore build output and generated artifacts.
{ ignores: ['dist', 'dev-dist', 'coverage'] },
js.configs.recommended,
// Type-aware linting for the TypeScript sources only.
{
files: ['**/*.{ts,tsx}'],
extends: [...tseslint.configs.recommendedTypeChecked],
languageOptions: {
ecmaVersion: 2022,
globals: { ...globals.browser, __APP_VERSION__: 'readonly' },
parserOptions: {
// Type-aware linting: powers no-floating-promises, no-misused-promises, etc.
projectService: true,
tsconfigRootDir: import.meta.dirname,
},
},
plugins: {
'react-hooks': reactHooks,
'react-refresh': reactRefresh,
},
rules: {
...reactHooks.configs.recommended.rules,
'react-refresh/only-export-components': ['warn', { allowConstantExport: true }],
// Allow intentionally-unused args/vars when prefixed with _ (matches tsconfig intent).
'@typescript-eslint/no-unused-vars': [
'error',
{ argsIgnorePattern: '^_', varsIgnorePattern: '^_' },
],
},
},
// Tests exercise looser patterns and run in Node.
{
files: ['**/*.test.{ts,tsx}'],
languageOptions: { globals: { ...globals.node } },
},
// Plain JS config files (this file, etc.) are not part of the TS project —
// run them through the untyped ruleset only.
{
files: ['**/*.js'],
extends: [tseslint.configs.disableTypeChecked],
languageOptions: { globals: { ...globals.node } },
},
);
+1405
View File
File diff suppressed because it is too large Load Diff
+19 -1
View File
@@ -11,7 +11,17 @@
"typecheck": "tsc --noEmit",
"test": "vitest run",
"test:watch": "vitest",
"format": "prettier --write ."
"lint": "eslint .",
"lint:fix": "eslint . --fix",
"format": "prettier --write .",
"prepare": "husky"
},
"lint-staged": {
"*.{ts,tsx}": [
"eslint --fix",
"prettier --write"
],
"*.{json,css,md}": "prettier --write"
},
"dependencies": {
"@fontsource/ibm-plex-mono": "^5.2.7",
@@ -25,12 +35,20 @@
"zustand": "^5.0.14"
},
"devDependencies": {
"@eslint/js": "^10.0.1",
"@types/react": "^19.2.16",
"@types/react-dom": "^19.2.3",
"@vitejs/plugin-react": "^5.2.0",
"eslint": "^10.4.1",
"eslint-plugin-react-hooks": "^7.1.1",
"eslint-plugin-react-refresh": "^0.5.2",
"globals": "^17.6.0",
"happy-dom": "^20.0.0",
"husky": "^9.1.7",
"lint-staged": "^17.0.7",
"prettier": "^3.6.2",
"typescript": "^5.9.2",
"typescript-eslint": "^8.60.1",
"vite": "^7.1.0",
"vite-plugin-pwa": "^1.0.3",
"vitest": "^3.2.4"
+45 -41
View File
@@ -36,50 +36,54 @@ export function LivePreview() {
if (!node) return;
const text = draftText.trim();
const timer = setTimeout(async () => {
// Empty/blank is not an error — clean, empty pane (spec §04).
if (text === '') {
handleRef.current?.destroy();
handleRef.current = null;
setError(null);
return;
}
let parsed: unknown;
try {
parsed = JSON.parse(text);
} catch (e) {
setError(`Invalid JSON: ${(e as Error).message}`);
return;
}
const mine = ++generationRef.current;
try {
const prepared = prepareSpecForRender(parsed, { fitMode: 'default' });
const config = chartConfigFor(uiTheme);
handleRef.current?.destroy();
handleRef.current = null;
const handle = await renderSpec(node, prepared as VisualizationSpec, config);
if (mine !== generationRef.current) {
// TODO: a superseded render's destroy() calls node.replaceChildren(),
// which can blank the live chart if two embeds on the same node are
// ever in flight at once (heavy spec whose embed outlasts the 300ms
// debounce). The debounce makes this rare in M1; when fit-mode/dataset
// work (M2/M3) lands, serialize renders or finalize the stale view
// without clearing the shared node.
handle.destroy(); // a newer render superseded this one
// The debounced body is async; wrap in a void IIFE so the timer callback
// returns void (it handles its own errors internally — nothing awaits it).
const timer = setTimeout(() => {
void (async () => {
// Empty/blank is not an error — clean, empty pane (spec §04).
if (text === '') {
handleRef.current?.destroy();
handleRef.current = null;
setError(null);
return;
}
handleRef.current = handle;
setError(null);
} catch (e) {
if (mine === generationRef.current) {
setError(
`Rendering error: ${(e as Error).message}. ` +
`Check your JSON syntax and that the spec is valid Vega-Lite.`,
);
let parsed: unknown;
try {
parsed = JSON.parse(text);
} catch (e) {
setError(`Invalid JSON: ${(e as Error).message}`);
return;
}
}
const mine = ++generationRef.current;
try {
const prepared = prepareSpecForRender(parsed, { fitMode: 'default' });
const config = chartConfigFor(uiTheme);
handleRef.current?.destroy();
handleRef.current = null;
const handle = await renderSpec(node, prepared as VisualizationSpec, config);
if (mine !== generationRef.current) {
// TODO: a superseded render's destroy() calls node.replaceChildren(),
// which can blank the live chart if two embeds on the same node are
// ever in flight at once (heavy spec whose embed outlasts the 300ms
// debounce). The debounce makes this rare in M1; when fit-mode/dataset
// work (M2/M3) lands, serialize renders or finalize the stale view
// without clearing the shared node.
handle.destroy(); // a newer render superseded this one
return;
}
handleRef.current = handle;
setError(null);
} catch (e) {
if (mine === generationRef.current) {
setError(
`Rendering error: ${(e as Error).message}. ` +
`Check your JSON syntax and that the spec is valid Vega-Lite.`,
);
}
}
})();
}, RENDER_DEBOUNCE_MS);
return () => clearTimeout(timer);
+5 -4
View File
@@ -56,8 +56,9 @@ function tx<T>(
const transaction = db.transaction(store, mode);
const request = run(transaction.objectStore(store));
transaction.oncomplete = () => resolve(request.result);
transaction.onerror = () => reject(transaction.error);
transaction.onabort = () => reject(transaction.error);
const fail = () => reject(transaction.error ?? new Error('IndexedDB transaction failed'));
transaction.onerror = fail;
transaction.onabort = fail;
}),
);
}
@@ -69,10 +70,10 @@ export const getAll = <T>(store: string): Promise<T[]> =>
tx<T[]>(store, 'readonly', (s) => s.getAll() as IDBRequest<T[]>);
export const put = <T>(store: string, value: T): Promise<IDBValidKey> =>
tx<IDBValidKey>(store, 'readwrite', (s) => s.put(value as unknown as Record<string, unknown>));
tx<IDBValidKey>(store, 'readwrite', (s) => s.put(value));
export const del = (store: string, key: IDBValidKey): Promise<undefined> =>
tx<undefined>(store, 'readwrite', (s) => s.delete(key) as IDBRequest<undefined>);
tx<undefined>(store, 'readwrite', (s) => s.delete(key));
/** Test-only: forget the memoized connection so a fresh `openDB` reopens. */
export function _resetDbForTests(): void {
@@ -71,7 +71,11 @@ describe('settings-store · ui.theme', () => {
saveUiTheme('dark');
const stored = JSON.parse(localStorage.getItem(KEY)!);
const stored = JSON.parse(localStorage.getItem(KEY)!) as {
version: number;
ui: { theme: string; previewFitMode: string };
editor: { fontSize: number };
};
expect(stored.ui.theme).toBe('dark');
// Everything else survives — nothing clobbered.
expect(stored.version).toBe(1);
+1 -1
View File
@@ -40,7 +40,7 @@ function readRaw(): StoredSettings {
try {
const raw = localStorage.getItem(KEY);
if (!raw) return {};
const parsed = JSON.parse(raw);
const parsed: unknown = JSON.parse(raw);
return parsed && typeof parsed === 'object' ? (parsed as StoredSettings) : {};
} catch (err) {
console.warn('[settings] failed to read, using defaults', err);
+2 -4
View File
@@ -19,9 +19,7 @@ export interface FormatDetection {
function isTopology(value: unknown): boolean {
return (
typeof value === 'object' &&
value !== null &&
(value as { type?: unknown }).type === 'Topology'
typeof value === 'object' && value !== null && (value as { type?: unknown }).type === 'Topology'
);
}
@@ -32,7 +30,7 @@ export function detectFormat(raw: string): FormatDetection {
// 1. Try JSON first — highest confidence signal.
try {
const parsed = JSON.parse(text);
const parsed: unknown = JSON.parse(text);
return {
format: isTopology(parsed) ? 'topojson' : 'json',
confidence: 'high',
+3 -1
View File
@@ -4,7 +4,9 @@ import { VitePWA } from 'vite-plugin-pwa';
import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
const pkg = JSON.parse(readFileSync(new URL('./package.json', import.meta.url), 'utf-8'));
const pkg = JSON.parse(readFileSync(new URL('./package.json', import.meta.url), 'utf-8')) as {
version: string;
};
export default defineConfig({
resolve: {