Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 28 additions & 24 deletions configurator/src/App.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,12 @@
import { generateCSS } from './lib/codec';
import { loadInitialOverrides, injectLivePreview, saveOverrides, hasWpBoot } from './lib/persistence';
import { domainOf } from './lib/domains';
import { parseImport, summarizeImport } from './lib/importOverrides';
import tokensRaw from './data/api-index.generated.json';
import CommandPalette from './components/CommandPalette.svelte';

const ALL_TOKENS = ((tokensRaw as ApiIndex).tokens ?? tokensRaw) as SlashedToken[];
const LIVE_TOKEN_NAMES = new Set(ALL_TOKENS.map((t) => t.name));

const DOMAIN_LABELS: Record<string, string> = {
home: "Home", colors: "Colors", typography: "Typography", spacing: "Spacing",
Expand Down Expand Up @@ -54,6 +56,9 @@
// be re-focused (a second search for it still scrolls/highlights).
let focusRequest = $state<{ token: string; nonce: number } | null>(null);
let focusNonce = 0;
// Transient feedback after an import (the old flow failed silently).
let importStatus = $state<string | null>(null);
let importStatusTimer: ReturnType<typeof setTimeout> | null = null;

function navigateTo(domainId: string, token?: string) {
domain = domainId;
Expand Down Expand Up @@ -210,6 +215,12 @@
overrides = next;
}

function showImportStatus(msg: string) {
importStatus = msg;
if (importStatusTimer) clearTimeout(importStatusTimer);
importStatusTimer = setTimeout(() => { importStatus = null; importStatusTimer = null; }, 6000);
}

function handleImport() {
const input = document.createElement("input");
input.type = "file";
Expand All @@ -220,32 +231,16 @@
const reader = new FileReader();
reader.onload = (ev) => {
const text = ev.target?.result as string;
if (!text) return;
if (file.name.endsWith(".json")) {
try {
const data = JSON.parse(text);
if (data !== null && typeof data === "object" && !Array.isArray(data)) {
// Restrict to real token-name keys too, not just string values — an
// imported JSON file is untrusted input and its keys end up as
// object property names downstream (CodeQL: remote-property-injection).
const safe = Object.fromEntries(
Object.entries(data as Record<string, unknown>).filter(
([k, v]) => typeof v === "string" && /^--sf-[\w-]+$/.test(k)
)
) as Record<string, string>;
if (Object.keys(safe).length > 0) setOverrides(safe);
}
} catch {}
} else {
const parsed: Record<string, string> = {};
const re = /(--sf-[\w-]+)\s*:\s*([^;]+);/g;
let m;
while ((m = re.exec(text)) !== null) {
parsed[m[1].trim()] = m[2].trim();
}
if (Object.keys(parsed).length > 0) setOverrides((prev) => ({ ...prev, ...parsed }));
if (!text) { showImportStatus("Nothing imported — the selected file is empty."); return; }
// One validated pipeline for both CSS and JSON: sanitised, migrated,
// merged (non-destructive), and always reported — no more silent no-ops.
const { overrides: imported, report } = parseImport(text, file.name, LIVE_TOKEN_NAMES);
if (Object.keys(imported).length > 0) {
setOverrides((prev) => ({ ...prev, ...imported }));
}
showImportStatus(summarizeImport(report));
};
reader.onerror = () => { showImportStatus("Import failed — the selected file could not be read."); };
reader.readAsText(file);
};
input.click();
Expand Down Expand Up @@ -285,6 +280,7 @@
return () => {
window.removeEventListener("keydown", handler);
if (saveStateTimer) clearTimeout(saveStateTimer);
if (importStatusTimer) clearTimeout(importStatusTimer);
};
});
</script>
Expand Down Expand Up @@ -322,6 +318,14 @@
onOpenSearch={() => { showPalette = true; }}
/>

<!-- Import feedback: a transient banner (the previous import flow gave none). -->
{#if importStatus}
<div role="status" class="shrink-0 flex items-center gap-2 px-4 py-1.5 bg-indigo-500/10 border-b border-indigo-500/20 text-[11px] text-indigo-700 dark:text-indigo-300">
<span class="flex-1">{importStatus}</span>
<button onclick={() => { importStatus = null; }} aria-label="Dismiss" class="text-indigo-500 hover:text-indigo-700 dark:hover:text-indigo-200 cursor-pointer font-bold">×</button>
</div>
{/if}

<!-- Mobile fold toggle: switch between the controls panel and the live
preview. Lives right under the header (not at the bottom) so it's
visible without scrolling and doesn't compete with the status bar. -->
Expand Down
15 changes: 13 additions & 2 deletions configurator/src/components/shell/PreviewPanel.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -258,8 +258,19 @@ ${buildTab(template)}
<!-- Preview toolbar — always a single row (scrolls horizontally instead of
wrapping) so it can't eat a growing chunk of a short mobile viewport. -->
<div class="min-h-10 bg-slate-50 dark:bg-[#0d0d14] border-b border-black/8 dark:border-white/8 flex flex-nowrap items-center px-3 gap-2 overflow-x-auto shrink-0">
<!-- Template tabs -->
<div class="shrink-0 flex bg-black/5 dark:bg-white/5 border border-black/8 dark:border-white/8 rounded-lg p-0.5 gap-0.5 max-w-full overflow-x-auto">
<!-- Template selector. Mobile: a compact dropdown (the tab strip used to be
clipped in the narrow viewport). Desktop (sm+): the full tab strip. -->
<select
value={previewTemplate}
onchange={(e) => onTemplateChange((e.target as HTMLSelectElement).value as PreviewTemplate)}
aria-label="Preview template"
class="sm:hidden shrink-0 bg-black/5 dark:bg-white/5 border border-black/8 dark:border-white/8 rounded-lg px-2 py-1 text-[11px] font-bold text-slate-700 dark:text-slate-300 focus:outline-none focus:border-indigo-500 cursor-pointer"
>
{#each TABS as t (t.id)}
<option value={t.id}>{t.label}</option>
{/each}
</select>
<div class="hidden sm:flex shrink-0 bg-black/5 dark:bg-white/5 border border-black/8 dark:border-white/8 rounded-lg p-0.5 gap-0.5 max-w-full overflow-x-auto">
{#each TABS as t (t.id)}
<button
onclick={() => onTemplateChange(t.id)}
Expand Down
2 changes: 1 addition & 1 deletion configurator/src/components/shell/StudioHeader.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,7 @@

<button
onclick={onImport}
title="Import CSS overrides"
title="Import overrides (CSS or JSON)"
class="p-1.5 rounded-lg text-slate-600 dark:text-slate-400 hover:text-slate-900 dark:hover:text-white hover:bg-black/8 dark:hover:bg-white/8 transition-all cursor-pointer shrink-0"
>
<FolderOpen class="w-3.5 h-3.5" />
Expand Down
131 changes: 131 additions & 0 deletions configurator/src/lib/importOverrides.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
/**
* @license
* SPDX-License-Identifier: Apache-2.0
*/

/**
* Unified override import.
*
* The header import used to have two silent, inconsistent paths: a `.json` file
* REPLACED the whole state with no validation, while a `.css` file MERGED via a
* loose regex — and a file with nothing recognisable just did nothing, with no
* feedback. This parses either format through ONE pipeline:
*
* 1. detect JSON (flat map or a theme-file `{ tokens }`) vs CSS
* 2. sanitise every value (codec.sanitizeValue) and drop keys that aren't a
* real `--sf-*` name or whose value is structurally unsafe (would be
* dropped on export anyway)
* 3. migrate renamed/removed tokens and flag unknown ones (themeFile)
* 4. return the cleaned overrides plus a report the caller can surface
*
* The caller decides merge vs replace; the default header flow merges, which is
* the predictable, non-destructive choice for both formats.
*/
import { parseCSS, sanitizeValue } from "./codec";
import { migrateOverrides } from "./themeFile";
import { isStructurallySafe } from "./tokenModel";

export interface ImportReport {
format: "json" | "css";
/** Tokens accepted into the result. */
accepted: number;
/** Old names migrated to their current name. */
renamed: number;
/** Tokens dropped because the framework removed them. */
removed: number;
/** Accepted tokens that aren't part of this framework build. */
unknown: number;
/** Keys rejected for a bad name or an unsafe/empty value. */
invalid: string[];
/** Keys dropped because multiple legacy names map to one current token. */
collisions: number;
/** True when the file couldn't be parsed into any tokens. */
malformed: boolean;
}

export interface ImportResult {
overrides: Record<string, string>;
report: ImportReport;
}

const KEY_RE = /^--sf-[\w-]+$/;

function looksLikeJson(text: string): boolean {
return text.trim().startsWith("{");
}

/** Extract a raw name→value map from JSON (flat, or a theme-file wrapper). */
function readJsonMap(text: string): { map: Record<string, unknown>; malformed: boolean } {
try {
const data = JSON.parse(text);
if (!data || typeof data !== "object" || Array.isArray(data)) return { map: {}, malformed: true };
const src =
"overrides" in data && data.overrides && typeof data.overrides === "object" && !Array.isArray(data.overrides)
? (data.overrides as Record<string, unknown>)
: "tokens" in data && data.tokens && typeof data.tokens === "object" && !Array.isArray(data.tokens)
? (data.tokens as Record<string, unknown>)
: (data as Record<string, unknown>);
return { map: src, malformed: false };
} catch {
return { map: {}, malformed: true };
}
}

/**
* Parse and validate an imported CSS or JSON override file.
*
* @param text the raw file contents
* @param filename used (with a content sniff) to pick the JSON vs CSS path
* @param liveTokens the set of token names in the current framework build
*/
export function parseImport(
text: string,
filename: string,
liveTokens: Set<string>,
): ImportResult {
const isJson = /\.json$/i.test(filename) || looksLikeJson(text);
const { map: rawMap, malformed } = isJson
? readJsonMap(text)
: { map: parseCSS(text), malformed: false };

const cleaned: Record<string, string> = {};
const invalid: string[] = [];
for (const [key, value] of Object.entries(rawMap)) {
if (!KEY_RE.test(key) || typeof value !== "string") { invalid.push(key); continue; }
// Preserve normal whitespace (sanitizeValue will collapse it) but reject
// non-printing control characters that theme files and share links reject.
if (/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/.test(value)) { invalid.push(key); continue; }
const safe = sanitizeValue(value);
if (!isStructurallySafe(safe)) { invalid.push(key); continue; }
cleaned[key] = safe;
}

const migrated = migrateOverrides(cleaned, { live: liveTokens });

return {
overrides: migrated.overrides,
report: {
format: isJson ? "json" : "css",
accepted: Object.keys(migrated.overrides).length,
renamed: migrated.renamed.length,
removed: migrated.removed.length,
unknown: migrated.unknown.length,
invalid,
Comment on lines +106 to +113

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Import collisions remain silent

When two legacy token names migrate to the same current token, migration drops one value and records a collision, but this report omits that collision. The import banner consequently reports success without telling the user that one override was discarded.

collisions: migrated.collisions.length,
malformed: malformed && Object.keys(cleaned).length === 0,
},
};
}

/** A short human summary of an import for a status banner. */
export function summarizeImport(r: ImportReport): string {
if (r.malformed) return "Import failed — the file has no recognisable SLASHED tokens.";
if (r.accepted === 0) return "Nothing imported — no valid SLASHED tokens found.";
const parts = [`Imported ${r.accepted} token${r.accepted === 1 ? "" : "s"}`];
if (r.renamed) parts.push(`${r.renamed} migrated`);
if (r.removed) parts.push(`${r.removed} removed`);
if (r.unknown) parts.push(`${r.unknown} unknown`);
if (r.invalid.length) parts.push(`${r.invalid.length} skipped`);
if (r.collisions) parts.push(`${r.collisions} migration collision${r.collisions === 1 ? "" : "s"}`);
return parts.join(" · ") + ".";
}
83 changes: 83 additions & 0 deletions configurator/tests/importOverrides.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
/**
* Unit tests for src/lib/importOverrides.ts — the single, validated import
* pipeline that replaced the two silent, inconsistent header-import paths.
* Pins that CSS and JSON behave the same, values are sanitised, bad keys/values
* are reported (not silently dropped), and renamed tokens are migrated.
*/
import { describe, test, expect } from 'vitest';
import { parseImport, summarizeImport } from '../src/lib/importOverrides';

const LIVE = new Set([
'--sf-color-primary', '--sf-space-m', '--sf-radius-l',
'--sf-color-primary-source-light', // migration target
]);

describe('parseImport — JSON', () => {
test('accepts a flat name→value map', () => {
const r = parseImport('{"--sf-color-primary":"red","--sf-space-m":"2rem"}', 'x.json', LIVE);
expect(r.overrides).toEqual({ '--sf-color-primary': 'red', '--sf-space-m': '2rem' });
expect(r.report.format).toBe('json');
expect(r.report.accepted).toBe(2);
});
test('accepts a theme-file { tokens } shape', () => {
const r = parseImport('{"schemaVersion":1,"tokens":{"--sf-space-m":"3rem"}}', 't.json', LIVE);
expect(r.overrides).toEqual({ '--sf-space-m': '3rem' });
});
test('accepts exported theme-file { overrides } and reports invalid values', () => {
const r = parseImport('{"schemaVersion":1,"overrides":{"--sf-space-m":"3rem","--sf-radius-l":4}}', 'theme.json', LIVE);
expect(r.overrides).toEqual({ '--sf-space-m': '3rem' });
expect(r.report.invalid).toEqual(['--sf-radius-l']);
});
test('repairs CSS-breaking values but rejects bad keys and empty-after-sanitise ones', () => {
// "1rem; }" sanitises to "1rem" (kept); ";;" sanitises to "" (rejected);
// a non --sf key is rejected.
const r = parseImport('{"notatoken":"x","--sf-space-m":";;","--sf-color-primary":"1rem; }","--sf-radius-l":"8px"}', 'x.json', LIVE);
expect(r.overrides).toEqual({ '--sf-color-primary': '1rem', '--sf-radius-l': '8px' });
expect(r.report.invalid.sort()).toEqual(['--sf-space-m', 'notatoken']);
});
test('malformed JSON is reported, not thrown', () => {
const r = parseImport('{ not json', 'x.json', LIVE);
expect(r.report.malformed).toBe(true);
expect(r.report.accepted).toBe(0);
});
});

describe('parseImport — CSS', () => {
test('parses declarations and merges consistently with JSON', () => {
const css = ':root{ --sf-color-primary: blue; --sf-radius-l: 12px; }';
const r = parseImport(css, 'overrides.css', LIVE);
expect(r.overrides).toEqual({ '--sf-color-primary': 'blue', '--sf-radius-l': '12px' });
expect(r.report.format).toBe('css');
});
test('a CSS file with no --sf tokens is reported empty', () => {
const r = parseImport('body { color: red; }', 'x.css', LIVE);
expect(r.report.accepted).toBe(0);
});
});

describe('parseImport — migration & unknown', () => {
test('migrates a renamed token to its current name', () => {
const r = parseImport('{"--sf-color-primary-light":"red"}', 'x.json', LIVE);
expect(r.overrides['--sf-color-primary-source-light']).toBe('red');
expect(r.report.renamed).toBe(1);
});
test('keeps but flags a token not in this build', () => {
const r = parseImport('{"--sf-made-up-token":"1px"}', 'x.json', LIVE);
expect(r.overrides['--sf-made-up-token']).toBe('1px');
expect(r.report.unknown).toBe(1);
});
});

describe('summarizeImport', () => {
test('summarises a mixed result', () => {
const msg = summarizeImport({ format: 'json', accepted: 3, renamed: 1, removed: 0, unknown: 1, invalid: ['x'], collisions: 0, malformed: false });
expect(msg).toContain('Imported 3 tokens');
expect(msg).toContain('1 migrated');
expect(msg).toContain('1 unknown');
expect(msg).toContain('1 skipped');
});
test('reports malformed and empty distinctly', () => {
expect(summarizeImport({ format: 'css', accepted: 0, renamed: 0, removed: 0, unknown: 0, invalid: [], collisions: 0, malformed: true })).toMatch(/failed/i);
expect(summarizeImport({ format: 'css', accepted: 0, renamed: 0, removed: 0, unknown: 0, invalid: [], collisions: 0, malformed: false })).toMatch(/Nothing imported/i);
});
});