@adea-ai/app-framework 0.42.0 → 0.44.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -24,11 +24,6 @@ export type AppearanceContextValue = Omit<UiThemeContextValue, 'preview'> & {
24
24
  export declare function appearanceProviderProps(options?: {
25
25
  nativeTranslucency?: () => boolean;
26
26
  }): Omit<UiThemeProviderProps, 'children'>;
27
- /**
28
- * The V2 view of a shared theme context. Reads derive from the provider's selection;
29
- * writes go through its `setSelection`, so the shared provider remains the only
30
- * writer of the document and of storage.
31
- */
32
27
  export declare function createAppearanceContext(ui: UiThemeContextValue): AppearanceContextValue;
33
28
  type ThemeProviderProps = ParentProps<{
34
29
  /**
@@ -56,15 +56,21 @@ function projectCachedTokens(tokens, rules) {
56
56
  * writes go through its `setSelection`, so the shared provider remains the only
57
57
  * writer of the document and of storage.
58
58
  */
59
+ function previewSelection(value) {
60
+ return selectionFromPreferences({
61
+ ...value,
62
+ codeThemeId: value.codeThemeId ?? "theme"
63
+ });
64
+ }
59
65
  function createAppearanceContext(ui) {
60
66
  let draft;
61
67
  const preview = (next) => {
62
68
  draft = next;
63
- ui.preview(next ? selectionFromPreferences(next) : void 0);
69
+ ui.preview(next ? previewSelection(next) : void 0);
64
70
  };
65
71
  createEffect(() => {
66
72
  ui.selection();
67
- if (draft !== void 0 && !ui.previewing()) ui.preview(selectionFromPreferences(draft));
73
+ if (draft !== void 0 && !ui.previewing()) ui.preview(previewSelection(draft));
68
74
  });
69
75
  return {
70
76
  ...ui,
@@ -19,6 +19,13 @@ export type AppearancePreferencesV2 = Readonly<{
19
19
  * theme id pins that theme's terminal colours regardless of appearance.
20
20
  */
21
21
  terminalThemeId: 'theme' | string;
22
+ /**
23
+ * Code's palette (editor, diff and file views), on the terminal's rule: `'theme'`
24
+ * follows the resolved interface theme, a theme id pins that theme's syntax
25
+ * colours and code canvas. Optional like `fonts`: absent reads as `'theme'`, and
26
+ * a document that never chose one is rewritten without the key.
27
+ */
28
+ codeThemeId?: 'theme' | string;
22
29
  /** A built-in preset id, a theme-carried `ansi-<slot>` id, or a validated `#rrggbb` color. `'theme'` normalizes to the default preset. */
23
30
  accent: 'theme' | string;
24
31
  surface: SurfacePreference;
@@ -76,6 +76,7 @@ function normalizeAppearancePreferences(raw) {
76
76
  lightThemeId: normalizeThemeId(record.lightThemeId, defaultAppearancePreferences.lightThemeId),
77
77
  darkThemeId: normalizeThemeId(record.darkThemeId, defaultAppearancePreferences.darkThemeId),
78
78
  terminalThemeId: normalizeThemeId(record.terminalThemeId, "theme"),
79
+ ...record.codeThemeId === void 0 ? {} : { codeThemeId: normalizeThemeId(record.codeThemeId, "theme") },
79
80
  accent: normalizeAccent(record.accent),
80
81
  surface: normalizeSurface$1(record.surface),
81
82
  reduceTransparency: record.reduceTransparency === true,
@@ -92,6 +93,7 @@ function selectionFromPreferences(preferences) {
92
93
  ...preferences.lightThemeId === void 0 ? {} : { lightThemeId: preferences.lightThemeId },
93
94
  ...preferences.darkThemeId === void 0 ? {} : { darkThemeId: preferences.darkThemeId },
94
95
  ...preferences.terminalThemeId === void 0 ? {} : { terminalThemeId: preferences.terminalThemeId },
96
+ ...preferences.codeThemeId === void 0 ? {} : { codeThemeId: preferences.codeThemeId },
95
97
  ...preferences.accent === void 0 ? {} : { accent: preferences.accent === "theme" ? DEFAULT_ACCENT_PRESET_ID : preferences.accent },
96
98
  ...preferences.surface === void 0 ? {} : { surface: preferences.surface },
97
99
  ...preferences.reduceTransparency === void 0 ? {} : { reduceTransparency: preferences.reduceTransparency },
@@ -109,9 +111,14 @@ function preferencesFromSelection(selection) {
109
111
  accent: selection.accent === "theme" ? DEFAULT_ACCENT_PRESET_ID : selection.accent,
110
112
  surface: selection.surface ?? "opaque",
111
113
  reduceTransparency: selection.reduceTransparency === true,
114
+ ...codeThemeIdOf(selection) === void 0 ? {} : { codeThemeId: codeThemeIdOf(selection) },
112
115
  ...selection.fonts === void 0 ? {} : { fonts: selection.fonts }
113
116
  };
114
117
  }
118
+ /** The selection's code pin; read loosely so an older `@adea-ai/ui` still type-checks. */
119
+ function codeThemeIdOf(selection) {
120
+ return selection.codeThemeId;
121
+ }
115
122
  function sameFonts(left, right) {
116
123
  return [
117
124
  "ui",
@@ -1,9 +1,10 @@
1
1
  import { mutateCustomThemeLibrary } from "./theme-library-mutation.js";
2
2
  import { flatVariantTokens, validateThemeRegistry } from "./theme-library-schema.js";
3
3
  import { LEGACY_IMPORTED_THEME_TOKEN_PROJECTION } from "./legacy-imported-theme-token-projection.js";
4
+ import { canonicalFromVsCode, isVsCodeTheme } from "./vscode-theme-import.js";
4
5
  import { projectThemeTokens } from "@adea-ai/ui/components/theme/token-projection";
5
6
  import { colorToHex, contrastRatio, ensureContrast, parseColor } from "@adea-ai/ui/lib/accent-roles";
6
- import { defaultThemeRecord, editorRolesHex, oklchToHex, parseOklchColor, shadcnDestructiveProjection, shadcnVariables, syntaxRolesHex, toXtermTheme } from "@adea-ai/ui/lib/theme-projection";
7
+ import { defaultThemeRecord, editorRolesHex, oklchToHex, parseOklchColor, parseVsCodeTheme, shadcnDestructiveProjection, shadcnVariables, syntaxRolesHex, toXtermTheme } from "@adea-ai/ui/lib/theme-projection";
7
8
  // src/appearance/custom-theme-import.ts
8
9
  var CANONICAL_COLOR_KEYS = [
9
10
  "background",
@@ -184,7 +185,7 @@ function projectCanonical(theme) {
184
185
  ].map((value) => hexOf(value));
185
186
  let editor;
186
187
  try {
187
- editor = { ...editorRolesHex(theme) };
188
+ editor = theme.syntax ? Object.fromEntries(Object.entries(syntaxRolesHex(theme)).map(([role, value]) => [role, hexOf(value)])) : { ...editorRolesHex(theme) };
188
189
  } catch {
189
190
  const raw = syntaxRolesHex(theme);
190
191
  editor = Object.fromEntries(Object.entries(raw).filter(([role]) => role in SYNTAX_SOURCES).map(([role, value]) => [role, hexOf(value)]));
@@ -226,17 +227,28 @@ function prepareCustomTheme(text) {
226
227
  try {
227
228
  source = JSON.parse(text);
228
229
  } catch {
229
- return {
230
+ try {
231
+ source = parseVsCodeTheme(text);
232
+ } catch {
233
+ return {
234
+ ok: false,
235
+ error: "That file is not valid JSON."
236
+ };
237
+ }
238
+ if (!isVsCodeTheme(source)) return {
230
239
  ok: false,
231
240
  error: "That file is not valid JSON."
232
241
  };
233
242
  }
234
- const record = typeof source === "object" && source !== null && "theme" in source ? source.theme : source;
235
- if (typeof record !== "object" || record === null) return {
243
+ const unwrapped = typeof source === "object" && source !== null && "theme" in source ? source.theme : source;
244
+ if (typeof unwrapped !== "object" || unwrapped === null) return {
236
245
  ok: false,
237
246
  error: "That file does not describe a theme."
238
247
  };
239
248
  const notes = [];
249
+ const fromVsCode = isVsCodeTheme(unwrapped);
250
+ const record = fromVsCode ? canonicalFromVsCode(unwrapped) : unwrapped;
251
+ if (fromVsCode) notes.push("Read as a VS Code colour theme; code keeps its colours.");
240
252
  const rawColors = record.colors ?? {};
241
253
  const appearance = record.appearance === "light" || record.appearance === "dark" ? record.appearance : isHex(rawColors.background) ? contrastRatio(rawColors.background, "#ffffff") > contrastRatio(rawColors.background, "#000000") ? "dark" : "light" : rawColors.background === void 0 ? "dark" : "light";
242
254
  const base = defaultThemeRecord(appearance);
@@ -272,7 +284,8 @@ function prepareCustomTheme(text) {
272
284
  colors,
273
285
  ansi: Object.fromEntries(ANSI_KEYS.map((key, index) => [key, ansi[index]])),
274
286
  cursor: isHex(record.cursor) ? normalizeHex(record.cursor) : base.cursor,
275
- selection: isHex(record.selection) ? normalizeHex(record.selection) : base.selection
287
+ selection: isHex(record.selection) ? normalizeHex(record.selection) : base.selection,
288
+ ...syntaxOf(record.syntax)
276
289
  };
277
290
  let variant;
278
291
  try {
@@ -309,6 +322,12 @@ function prepareCustomTheme(text) {
309
322
  }
310
323
  };
311
324
  }
325
+ /** The syntax colours a file names, as hex, or nothing when it names none. */
326
+ function syntaxOf(value) {
327
+ if (typeof value !== "object" || value === null) return {};
328
+ const roles = Object.fromEntries(Object.entries(value).flatMap(([role, color]) => isHex(color) ? [[role, normalizeHex(color)]] : []));
329
+ return Object.keys(roles).length > 0 ? { syntax: roles } : {};
330
+ }
312
331
  /** Name the prepared theme against the latest library snapshot. */
313
332
  function storedTheme(prepared, existing) {
314
333
  const id = uniqueThemeId(prepared.name, existing);
@@ -14,6 +14,7 @@ var scalarFields = Object.keys({
14
14
  function samePreferences(left, right) {
15
15
  if (left === right) return true;
16
16
  if (!scalarFields.every((field) => left[field] === right[field])) return false;
17
+ if ((left.codeThemeId ?? "theme") !== (right.codeThemeId ?? "theme")) return false;
17
18
  if (left.fonts === right.fonts) return true;
18
19
  const leftFonts = normalizeAppearanceEditorFontSettings(left.fonts).settings;
19
20
  const rightFonts = normalizeAppearanceEditorFontSettings(right.fonts).settings;
@@ -57,9 +58,13 @@ function createAppearanceEditor(committed = defaultAppearancePreferences) {
57
58
  merge: (current) => {
58
59
  const before = snapshot();
59
60
  const after = draft();
60
- if (resetAll()) return after;
61
+ if (resetAll()) return {
62
+ ...after,
63
+ ...current.codeThemeId === void 0 ? {} : { codeThemeId: after.codeThemeId ?? "theme" }
64
+ };
61
65
  const merged = { ...current };
62
66
  for (const field of scalarFields) if (before[field] !== after[field]) Object.assign(merged, { [field]: after[field] });
67
+ if ((before.codeThemeId ?? "theme") !== (after.codeThemeId ?? "theme")) merged.codeThemeId = after.codeThemeId ?? "theme";
63
68
  const originalFonts = normalizeAppearanceEditorFontSettings(before.fonts).settings;
64
69
  const draftFonts = normalizeAppearanceEditorFontSettings(after.fonts).settings;
65
70
  const currentFonts = normalizeAppearanceEditorFontSettings(current.fonts).settings;
@@ -26,6 +26,14 @@ export type StoredThemeEditorRoles = Readonly<{
26
26
  diffDelete: string;
27
27
  diffHunk: string;
28
28
  searchMatch: string;
29
+ /** Roles a file with its own syntax colours carries; absent, they derive from the above. */
30
+ storage?: string;
31
+ parameter?: string;
32
+ property?: string;
33
+ field?: string;
34
+ member?: string;
35
+ constant?: string;
36
+ punctuation?: string;
29
37
  }>;
30
38
  export type StoredThemeChartRoles = Readonly<{
31
39
  chart1: string;
@@ -0,0 +1,9 @@
1
+ import { type VsCodeTheme } from '@adea-ai/ui/lib/theme-projection';
2
+ /** True for a file shaped like a VS Code colour theme rather than a canonical one. */
3
+ export declare function isVsCodeTheme(source: unknown): source is VsCodeTheme;
4
+ /**
5
+ * The canonical theme file a VS Code theme describes: name, appearance, the
6
+ * surface and ANSI roles it sets, and its syntax roles. Roles it does not set are
7
+ * left out, for the importer to fill as it fills any partial file.
8
+ */
9
+ export declare function canonicalFromVsCode(theme: VsCodeTheme): Record<string, unknown>;
@@ -0,0 +1,115 @@
1
+ import { opaqueHex, vsCodeSyntax } from "@adea-ai/ui/lib/theme-projection";
2
+ // src/appearance/vscode-theme-import.ts
3
+ var HEX = /^#(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i;
4
+ /** Canonical role → the workbench colours that supply it, first present wins. */
5
+ var COLOR_SOURCES = {
6
+ background: ["editor.background"],
7
+ foreground: ["editor.foreground", "foreground"],
8
+ text: ["editor.foreground", "foreground"],
9
+ surface: ["sideBar.background", "editor.background"],
10
+ surfaceElevated: [
11
+ "editorWidget.background",
12
+ "dropdown.background",
13
+ "sideBar.background"
14
+ ],
15
+ surfaceHover: ["list.hoverBackground", "toolbar.hoverBackground"],
16
+ surfaceActive: ["list.activeSelectionBackground", "list.inactiveSelectionBackground"],
17
+ border: [
18
+ "panel.border",
19
+ "editorGroup.border",
20
+ "sideBar.border",
21
+ "focusBorder"
22
+ ],
23
+ borderMuted: [
24
+ "editorIndentGuide.background1",
25
+ "editorIndentGuide.background",
26
+ "panel.border"
27
+ ],
28
+ textMuted: [
29
+ "descriptionForeground",
30
+ "sideBar.foreground",
31
+ "editorLineNumber.foreground"
32
+ ],
33
+ textSubtle: ["editorLineNumber.foreground", "descriptionForeground"],
34
+ accent: [
35
+ "button.background",
36
+ "focusBorder",
37
+ "textLink.foreground"
38
+ ],
39
+ accentForeground: ["button.foreground"],
40
+ success: ["gitDecoration.addedResourceForeground", "terminal.ansiGreen"],
41
+ warning: ["editorWarning.foreground", "terminal.ansiYellow"],
42
+ error: [
43
+ "editorError.foreground",
44
+ "errorForeground",
45
+ "terminal.ansiRed"
46
+ ],
47
+ info: ["editorInfo.foreground", "terminal.ansiBlue"]
48
+ };
49
+ var ANSI_SOURCES = {
50
+ black: "terminal.ansiBlack",
51
+ red: "terminal.ansiRed",
52
+ green: "terminal.ansiGreen",
53
+ yellow: "terminal.ansiYellow",
54
+ blue: "terminal.ansiBlue",
55
+ magenta: "terminal.ansiMagenta",
56
+ cyan: "terminal.ansiCyan",
57
+ white: "terminal.ansiWhite",
58
+ brightBlack: "terminal.ansiBrightBlack",
59
+ brightRed: "terminal.ansiBrightRed",
60
+ brightGreen: "terminal.ansiBrightGreen",
61
+ brightYellow: "terminal.ansiBrightYellow",
62
+ brightBlue: "terminal.ansiBrightBlue",
63
+ brightMagenta: "terminal.ansiBrightMagenta",
64
+ brightCyan: "terminal.ansiBrightCyan",
65
+ brightWhite: "terminal.ansiBrightWhite"
66
+ };
67
+ /** True for a file shaped like a VS Code colour theme rather than a canonical one. */
68
+ function isVsCodeTheme(source) {
69
+ if (typeof source !== "object" || source === null) return false;
70
+ const record = source;
71
+ if (Array.isArray(record.tokenColors)) return true;
72
+ const colors = record.colors;
73
+ return typeof colors === "object" && colors !== null && typeof colors["editor.background"] === "string";
74
+ }
75
+ /**
76
+ * The canonical theme file a VS Code theme describes: name, appearance, the
77
+ * surface and ANSI roles it sets, and its syntax roles. Roles it does not set are
78
+ * left out, for the importer to fill as it fills any partial file.
79
+ */
80
+ function canonicalFromVsCode(theme) {
81
+ const workbench = theme.colors ?? {};
82
+ const background = color(workbench["editor.background"], void 0);
83
+ const pick = (keys) => {
84
+ for (const key of keys) {
85
+ const value = color(workbench[key], background);
86
+ if (value) return value;
87
+ }
88
+ };
89
+ const colors = Object.fromEntries(Object.entries(COLOR_SOURCES).flatMap(([role, keys]) => {
90
+ const value = pick(keys);
91
+ return value ? [[role, value]] : [];
92
+ }));
93
+ const ansi = Object.fromEntries(Object.entries(ANSI_SOURCES).flatMap(([role, key]) => {
94
+ const value = color(workbench[key], background);
95
+ return value ? [[role, value]] : [];
96
+ }));
97
+ const type = theme.type?.toLowerCase();
98
+ const appearance = type === "light" || type === "hc-light" ? "light" : type === "dark" || type === "hc" || type === "hc-black" ? "dark" : void 0;
99
+ return {
100
+ ...theme.name ? { name: theme.name } : {},
101
+ ...appearance ? { appearance } : {},
102
+ colors,
103
+ ansi,
104
+ ...optional("cursor", pick(["editorCursor.foreground", "terminalCursor.foreground"])),
105
+ ...optional("selection", pick(["editor.selectionBackground", "terminal.selectionBackground"])),
106
+ syntax: vsCodeSyntax(theme)
107
+ };
108
+ }
109
+ function color(value, background) {
110
+ return typeof value === "string" && HEX.test(value) ? opaqueHex(value, background) : void 0;
111
+ }
112
+ function optional(key, value) {
113
+ return value ? { [key]: value } : {};
114
+ }
115
+ export { canonicalFromVsCode, isVsCodeTheme };
@@ -1 +1 @@
1
- {"version":"0.42.0","commit":"36321bb94166ff7531a2562ea320e341c3906976"}
1
+ {"version":"0.44.0","commit":"697bea93a6e3eda0f2c89c9b75f062604360c691"}
@@ -135,7 +135,8 @@ function AppearanceHost(props) {
135
135
  return {
136
136
  ...draft,
137
137
  accent: rawCustomAccent() && !getAccent(draft.accent) && !isThemeAccentId(draft.accent) && draft.accent !== "theme" ? rawCustomAccent() : draft.accent,
138
- surface: draft.surface === "translucent" ? "theme" : draft.surface
138
+ surface: draft.surface === "translucent" ? "theme" : draft.surface,
139
+ codeThemeId: draft.codeThemeId ?? "theme"
139
140
  };
140
141
  });
141
142
  const sampleVariant = () => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@adea-ai/app-framework",
3
- "version": "0.42.0",
3
+ "version": "0.44.0",
4
4
  "license": "Apache-2.0",
5
5
  "repository": {
6
6
  "type": "git",
@@ -426,7 +426,7 @@
426
426
  "tar": "^7.5.22"
427
427
  },
428
428
  "devDependencies": {
429
- "@adea-ai/ui": "0.154.0",
429
+ "@adea-ai/ui": "0.157.0",
430
430
  "@babel/core": "8.1.0",
431
431
  "@babel/preset-typescript": "^8.0.7",
432
432
  "@happy-dom/global-registrator": "^21.0.4",
@@ -448,7 +448,7 @@
448
448
  "vite-plus": "1.5.1"
449
449
  },
450
450
  "peerDependencies": {
451
- "@adea-ai/ui": "^0.154.0",
451
+ "@adea-ai/ui": "^0.157.0",
452
452
  "lucide-solid": "^1.51.0",
453
453
  "solid-js": "^1.9.15"
454
454
  },
@@ -126,19 +126,23 @@ function projectCachedTokens(
126
126
  * writes go through its `setSelection`, so the shared provider remains the only
127
127
  * writer of the document and of storage.
128
128
  */
129
+ function previewSelection(value: AppearancePreferencesV2) {
130
+ return selectionFromPreferences({ ...value, codeThemeId: value.codeThemeId ?? 'theme' })
131
+ }
132
+
129
133
  export function createAppearanceContext(ui: UiThemeContextValue): AppearanceContextValue {
130
134
  let draft: AppearancePreferencesV2 | undefined
131
135
 
132
136
  const preview = (next: AppearancePreferencesV2 | undefined) => {
133
137
  draft = next
134
- ui.preview(next ? selectionFromPreferences(next) : undefined)
138
+ ui.preview(next ? previewSelection(next) : undefined)
135
139
  }
136
140
 
137
141
  // The shared provider ends a preview when the selection is committed. The editor's
138
142
  // draft is still open, though, so it keeps showing until the editor ends it.
139
143
  createEffect(() => {
140
144
  ui.selection()
141
- if (draft !== undefined && !ui.previewing()) ui.preview(selectionFromPreferences(draft))
145
+ if (draft !== undefined && !ui.previewing()) ui.preview(previewSelection(draft))
142
146
  })
143
147
 
144
148
  return {
@@ -49,6 +49,13 @@ export type AppearancePreferencesV2 = Readonly<{
49
49
  * theme id pins that theme's terminal colours regardless of appearance.
50
50
  */
51
51
  terminalThemeId: 'theme' | string
52
+ /**
53
+ * Code's palette (editor, diff and file views), on the terminal's rule: `'theme'`
54
+ * follows the resolved interface theme, a theme id pins that theme's syntax
55
+ * colours and code canvas. Optional like `fonts`: absent reads as `'theme'`, and
56
+ * a document that never chose one is rewritten without the key.
57
+ */
58
+ codeThemeId?: 'theme' | string
52
59
  /** A built-in preset id, a theme-carried `ansi-<slot>` id, or a validated `#rrggbb` color. `'theme'` normalizes to the default preset. */
53
60
  accent: 'theme' | string
54
61
  surface: SurfacePreference
@@ -154,6 +161,9 @@ export function normalizeAppearancePreferences(raw: unknown): NormalizedPreferen
154
161
  ),
155
162
  darkThemeId: normalizeThemeId(record.darkThemeId, defaultAppearancePreferences.darkThemeId),
156
163
  terminalThemeId: normalizeThemeId(record.terminalThemeId, 'theme'),
164
+ ...(record.codeThemeId === undefined
165
+ ? {}
166
+ : { codeThemeId: normalizeThemeId(record.codeThemeId, 'theme') }),
157
167
  accent: normalizeAccent(record.accent),
158
168
  surface: normalizeSurface(record.surface),
159
169
  reduceTransparency: record.reduceTransparency === true,
@@ -183,6 +193,7 @@ export function selectionFromPreferences(
183
193
  ...(preferences.terminalThemeId === undefined
184
194
  ? {}
185
195
  : { terminalThemeId: preferences.terminalThemeId }),
196
+ ...(preferences.codeThemeId === undefined ? {} : { codeThemeId: preferences.codeThemeId }),
186
197
  // `'theme'` is the default preset everywhere a draft, a
187
198
  // stored record or a direct update can reach: the provider's own `theme` means
188
199
  // "the variant's primary", which no V2 preference can select.
@@ -210,10 +221,16 @@ export function preferencesFromSelection(selection: ThemeSelection): AppearanceP
210
221
  accent: selection.accent === 'theme' ? DEFAULT_ACCENT_PRESET_ID : selection.accent,
211
222
  surface: selection.surface ?? 'opaque',
212
223
  reduceTransparency: selection.reduceTransparency === true,
224
+ ...(codeThemeIdOf(selection) === undefined ? {} : { codeThemeId: codeThemeIdOf(selection) }),
213
225
  ...(selection.fonts === undefined ? {} : { fonts: selection.fonts }),
214
226
  }
215
227
  }
216
228
 
229
+ /** The selection's code pin; read loosely so an older `@adea-ai/ui` still type-checks. */
230
+ function codeThemeIdOf(selection: ThemeSelection): string | undefined {
231
+ return (selection as ThemeSelection & { codeThemeId?: string }).codeThemeId
232
+ }
233
+
217
234
  function sameFonts(left: AppearanceEditorFontSettings, right: AppearanceEditorFontSettings) {
218
235
  return (['ui', 'content', 'code'] as const).every(
219
236
  (axis) => left[axis].family === right[axis].family && left[axis].size === right[axis].size
@@ -21,6 +21,7 @@ import {
21
21
  editorRolesHex,
22
22
  oklchToHex,
23
23
  parseOklchColor,
24
+ parseVsCodeTheme,
24
25
  shadcnDestructiveProjection,
25
26
  shadcnVariables,
26
27
  syntaxRolesHex,
@@ -40,6 +41,7 @@ import {
40
41
  type StoredThemeVariant as ThemeVariant,
41
42
  } from './custom-theme-library'
42
43
  import { LEGACY_IMPORTED_THEME_TOKEN_PROJECTION } from './legacy-imported-theme-token-projection'
44
+ import { canonicalFromVsCode, isVsCodeTheme } from './vscode-theme-import'
43
45
 
44
46
  const CANONICAL_COLOR_KEYS = [
45
47
  'background',
@@ -300,7 +302,13 @@ function projectCanonical(theme: AdeaTheme): ThemeVariant {
300
302
  ].map((value) => hexOf(value))
301
303
  let editor: Record<string, string>
302
304
  try {
303
- editor = { ...editorRolesHex(theme) }
305
+ // A file that names its syntax colours (a VS Code theme does) keeps them exactly,
306
+ // as the catalogue keeps its editor themes'; the rest are held to the floor.
307
+ editor = theme.syntax
308
+ ? Object.fromEntries(
309
+ Object.entries(syntaxRolesHex(theme)).map(([role, value]) => [role, hexOf(value)])
310
+ )
311
+ : { ...editorRolesHex(theme) }
304
312
  } catch {
305
313
  // Some palettes cannot reach the 4.5:1 syntax floor from their own ramp;
306
314
  // fall back to the raw roles repaired toward the floor.
@@ -351,18 +359,27 @@ function prepareCustomTheme(
351
359
  try {
352
360
  source = JSON.parse(text)
353
361
  } catch {
354
- return { ok: false, error: 'That file is not valid JSON.' }
362
+ // VS Code theme files are JSON with comments and trailing commas.
363
+ try {
364
+ source = parseVsCodeTheme(text)
365
+ } catch {
366
+ return { ok: false, error: 'That file is not valid JSON.' }
367
+ }
368
+ if (!isVsCodeTheme(source)) return { ok: false, error: 'That file is not valid JSON.' }
355
369
  }
356
- const record = (
370
+ const unwrapped = (
357
371
  typeof source === 'object' && source !== null && 'theme' in (source as Record<string, unknown>)
358
372
  ? (source as { theme: unknown }).theme
359
373
  : source
360
374
  ) as Record<string, unknown>
361
- if (typeof record !== 'object' || record === null) {
375
+ if (typeof unwrapped !== 'object' || unwrapped === null) {
362
376
  return { ok: false, error: 'That file does not describe a theme.' }
363
377
  }
364
378
 
365
379
  const notes: string[] = []
380
+ const fromVsCode = isVsCodeTheme(unwrapped)
381
+ const record = fromVsCode ? canonicalFromVsCode(unwrapped) : unwrapped
382
+ if (fromVsCode) notes.push('Read as a VS Code colour theme; code keeps its colours.')
366
383
  const rawColors = (record.colors ?? {}) as Record<string, unknown>
367
384
  // A file that names no appearance is read from its background, so a dark palette
368
385
  // lands in the Dark menu instead of replacing the light theme.
@@ -438,6 +455,7 @@ function prepareCustomTheme(
438
455
  ) as unknown as AdeaTheme['ansi'],
439
456
  cursor: isHex(record.cursor) ? normalizeHex(record.cursor) : base.cursor,
440
457
  selection: isHex(record.selection) ? normalizeHex(record.selection) : base.selection,
458
+ ...syntaxOf(record.syntax),
441
459
  }
442
460
 
443
461
  let variant: ThemeVariant
@@ -490,6 +508,17 @@ function prepareCustomTheme(
490
508
  }
491
509
  }
492
510
 
511
+ /** The syntax colours a file names, as hex, or nothing when it names none. */
512
+ function syntaxOf(value: unknown): Pick<AdeaTheme, 'syntax'> {
513
+ if (typeof value !== 'object' || value === null) return {}
514
+ const roles = Object.fromEntries(
515
+ Object.entries(value as Record<string, unknown>).flatMap(([role, color]) =>
516
+ isHex(color) ? [[role, normalizeHex(color)]] : []
517
+ )
518
+ )
519
+ return Object.keys(roles).length > 0 ? { syntax: roles } : {}
520
+ }
521
+
493
522
  /** Name the prepared theme against the latest library snapshot. */
494
523
  function storedTheme(
495
524
  prepared: PreparedTheme,
@@ -41,7 +41,7 @@ export type AppearanceEditor = Readonly<{
41
41
  save: () => AppearancePreferencesV2
42
42
  }>
43
43
 
44
- type ScalarPreference = Exclude<keyof AppearancePreferencesV2, 'version' | 'fonts'>
44
+ type ScalarPreference = Exclude<keyof AppearancePreferencesV2, 'version' | 'fonts' | 'codeThemeId'>
45
45
  // Record exhaustiveness makes a newly added scalar preference require a merge policy.
46
46
  const scalarFields = Object.keys({
47
47
  mode: true,
@@ -56,6 +56,7 @@ const scalarFields = Object.keys({
56
56
  function samePreferences(left: AppearancePreferencesV2, right: AppearancePreferencesV2): boolean {
57
57
  if (left === right) return true
58
58
  if (!scalarFields.every((field) => left[field] === right[field])) return false
59
+ if ((left.codeThemeId ?? 'theme') !== (right.codeThemeId ?? 'theme')) return false
59
60
  if (left.fonts === right.fonts) return true
60
61
  const leftFonts = normalizeAppearanceEditorFontSettings(left.fonts).settings
61
62
  const rightFonts = normalizeAppearanceEditorFontSettings(right.fonts).settings
@@ -101,11 +102,20 @@ export function createAppearanceEditor(
101
102
  merge: (current) => {
102
103
  const before = snapshot()
103
104
  const after = draft()
104
- if (resetAll()) return after
105
+ if (resetAll())
106
+ return {
107
+ ...after,
108
+ ...(current.codeThemeId === undefined
109
+ ? {}
110
+ : { codeThemeId: after.codeThemeId ?? 'theme' }),
111
+ }
105
112
  const merged = { ...current }
106
113
  for (const field of scalarFields) {
107
114
  if (before[field] !== after[field]) Object.assign(merged, { [field]: after[field] })
108
115
  }
116
+ // Optional like `fonts`: merged only when the draft changed it.
117
+ if ((before.codeThemeId ?? 'theme') !== (after.codeThemeId ?? 'theme'))
118
+ merged.codeThemeId = after.codeThemeId ?? 'theme'
109
119
  const originalFonts = normalizeAppearanceEditorFontSettings(before.fonts).settings
110
120
  const draftFonts = normalizeAppearanceEditorFontSettings(after.fonts).settings
111
121
  const currentFonts = normalizeAppearanceEditorFontSettings(current.fonts).settings
@@ -43,6 +43,14 @@ export type StoredThemeEditorRoles = Readonly<{
43
43
  diffDelete: string
44
44
  diffHunk: string
45
45
  searchMatch: string
46
+ /** Roles a file with its own syntax colours carries; absent, they derive from the above. */
47
+ storage?: string
48
+ parameter?: string
49
+ property?: string
50
+ field?: string
51
+ member?: string
52
+ constant?: string
53
+ punctuation?: string
46
54
  }>
47
55
 
48
56
  export type StoredThemeChartRoles = Readonly<{
@@ -0,0 +1,120 @@
1
+ /*
2
+ * VS Code colour theme files, read as a canonical theme file.
3
+ *
4
+ * A VS Code theme carries workbench colours (`colors`, keyed `editor.background`,
5
+ * `terminal.ansiRed` and so on) and syntax rules (`tokenColors`, TextMate scope
6
+ * selectors, plus semantic token colours). The workbench colours map onto the
7
+ * canonical surface, text, status and ANSI roles; the syntax roles are resolved
8
+ * the way VS Code resolves them (`vsCodeSyntax`), so code reads as it does there.
9
+ * Translucent colours are composited over the editor background, as VS Code
10
+ * paints them.
11
+ */
12
+ import { opaqueHex, vsCodeSyntax, type VsCodeTheme } from '@adea-ai/ui/lib/theme-projection'
13
+
14
+ const HEX = /^#(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i
15
+
16
+ /** Canonical role → the workbench colours that supply it, first present wins. */
17
+ const COLOR_SOURCES = {
18
+ background: ['editor.background'],
19
+ foreground: ['editor.foreground', 'foreground'],
20
+ text: ['editor.foreground', 'foreground'],
21
+ surface: ['sideBar.background', 'editor.background'],
22
+ surfaceElevated: ['editorWidget.background', 'dropdown.background', 'sideBar.background'],
23
+ surfaceHover: ['list.hoverBackground', 'toolbar.hoverBackground'],
24
+ surfaceActive: ['list.activeSelectionBackground', 'list.inactiveSelectionBackground'],
25
+ border: ['panel.border', 'editorGroup.border', 'sideBar.border', 'focusBorder'],
26
+ borderMuted: ['editorIndentGuide.background1', 'editorIndentGuide.background', 'panel.border'],
27
+ textMuted: ['descriptionForeground', 'sideBar.foreground', 'editorLineNumber.foreground'],
28
+ textSubtle: ['editorLineNumber.foreground', 'descriptionForeground'],
29
+ accent: ['button.background', 'focusBorder', 'textLink.foreground'],
30
+ accentForeground: ['button.foreground'],
31
+ success: ['gitDecoration.addedResourceForeground', 'terminal.ansiGreen'],
32
+ warning: ['editorWarning.foreground', 'terminal.ansiYellow'],
33
+ error: ['editorError.foreground', 'errorForeground', 'terminal.ansiRed'],
34
+ info: ['editorInfo.foreground', 'terminal.ansiBlue'],
35
+ } as const
36
+
37
+ const ANSI_SOURCES = {
38
+ black: 'terminal.ansiBlack',
39
+ red: 'terminal.ansiRed',
40
+ green: 'terminal.ansiGreen',
41
+ yellow: 'terminal.ansiYellow',
42
+ blue: 'terminal.ansiBlue',
43
+ magenta: 'terminal.ansiMagenta',
44
+ cyan: 'terminal.ansiCyan',
45
+ white: 'terminal.ansiWhite',
46
+ brightBlack: 'terminal.ansiBrightBlack',
47
+ brightRed: 'terminal.ansiBrightRed',
48
+ brightGreen: 'terminal.ansiBrightGreen',
49
+ brightYellow: 'terminal.ansiBrightYellow',
50
+ brightBlue: 'terminal.ansiBrightBlue',
51
+ brightMagenta: 'terminal.ansiBrightMagenta',
52
+ brightCyan: 'terminal.ansiBrightCyan',
53
+ brightWhite: 'terminal.ansiBrightWhite',
54
+ } as const
55
+
56
+ /** True for a file shaped like a VS Code colour theme rather than a canonical one. */
57
+ export function isVsCodeTheme(source: unknown): source is VsCodeTheme {
58
+ if (typeof source !== 'object' || source === null) return false
59
+ const record = source as Record<string, unknown>
60
+ if (Array.isArray(record.tokenColors)) return true
61
+ const colors = record.colors
62
+ return (
63
+ typeof colors === 'object' &&
64
+ colors !== null &&
65
+ typeof (colors as Record<string, unknown>)['editor.background'] === 'string'
66
+ )
67
+ }
68
+
69
+ /**
70
+ * The canonical theme file a VS Code theme describes: name, appearance, the
71
+ * surface and ANSI roles it sets, and its syntax roles. Roles it does not set are
72
+ * left out, for the importer to fill as it fills any partial file.
73
+ */
74
+ export function canonicalFromVsCode(theme: VsCodeTheme): Record<string, unknown> {
75
+ const workbench = theme.colors ?? {}
76
+ const background = color(workbench['editor.background'], undefined)
77
+ const pick = (keys: readonly string[]): string | undefined => {
78
+ for (const key of keys) {
79
+ const value = color(workbench[key], background)
80
+ if (value) return value
81
+ }
82
+ return undefined
83
+ }
84
+ const colors = Object.fromEntries(
85
+ Object.entries(COLOR_SOURCES).flatMap(([role, keys]) => {
86
+ const value = pick(keys)
87
+ return value ? [[role, value]] : []
88
+ })
89
+ )
90
+ const ansi = Object.fromEntries(
91
+ Object.entries(ANSI_SOURCES).flatMap(([role, key]) => {
92
+ const value = color(workbench[key], background)
93
+ return value ? [[role, value]] : []
94
+ })
95
+ )
96
+ const type = theme.type?.toLowerCase()
97
+ const appearance =
98
+ type === 'light' || type === 'hc-light'
99
+ ? 'light'
100
+ : type === 'dark' || type === 'hc' || type === 'hc-black'
101
+ ? 'dark'
102
+ : undefined
103
+ return {
104
+ ...(theme.name ? { name: theme.name } : {}),
105
+ ...(appearance ? { appearance } : {}),
106
+ colors,
107
+ ansi,
108
+ ...optional('cursor', pick(['editorCursor.foreground', 'terminalCursor.foreground'])),
109
+ ...optional('selection', pick(['editor.selectionBackground', 'terminal.selectionBackground'])),
110
+ syntax: vsCodeSyntax(theme),
111
+ }
112
+ }
113
+
114
+ function color(value: string | null | undefined, background: string | undefined) {
115
+ return typeof value === 'string' && HEX.test(value) ? opaqueHex(value, background) : undefined
116
+ }
117
+
118
+ function optional(key: string, value: string | undefined): Record<string, string> {
119
+ return value ? { [key]: value } : {}
120
+ }
@@ -221,6 +221,8 @@ function AppearanceHost(props: { popover?: AppearanceControlProps }) {
221
221
  ? rawCustomAccent()
222
222
  : draft.accent,
223
223
  surface: draft.surface === 'translucent' ? 'theme' : draft.surface,
224
+ // Always present, so the editor shows its Code row: absent means "follow the UI".
225
+ codeThemeId: draft.codeThemeId ?? 'theme',
224
226
  }
225
227
  })
226
228