@venix-sistemas/jade 1.3.0 → 1.4.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.
Files changed (46) hide show
  1. package/README.md +969 -789
  2. package/dist/module.d.mts +8 -1
  3. package/dist/module.json +1 -1
  4. package/dist/module.mjs +66 -6
  5. package/dist/runtime/components/VenixThemeSwitcher.d.vue.ts +5 -1
  6. package/dist/runtime/components/VenixThemeSwitcher.vue +455 -280
  7. package/dist/runtime/components/VenixThemeSwitcher.vue.d.ts +5 -1
  8. package/dist/runtime/composables/useThemeCookies.d.ts +7 -7
  9. package/dist/runtime/composables/useVenixTheme.d.ts +12 -0
  10. package/dist/runtime/composables/useVenixTheme.js +68 -1
  11. package/dist/runtime/plugins/overlay-scrollbars.client.d.ts +1 -1
  12. package/dist/runtime/plugins/theme-init.server.d.ts +1 -1
  13. package/dist/runtime/plugins/vuetify-theme.d.ts +1 -1
  14. package/dist/shared/constants.d.ts +1 -1
  15. package/dist/shared/constants.js +3 -1
  16. package/dist/shared/css/colors.d.ts +2 -2
  17. package/dist/shared/css/colors.js +7 -2
  18. package/dist/shared/css/cursor.js +73 -9
  19. package/dist/shared/css/index.js +1 -1
  20. package/dist/shared/css/scrollbar.js +7 -1
  21. package/dist/shared/css/tokens.d.ts +40 -0
  22. package/dist/shared/css/tokens.js +119 -0
  23. package/dist/shared/theme.json +320 -308
  24. package/dist/shared/token-names.d.ts +37 -0
  25. package/dist/shared/token-names.js +53 -0
  26. package/dist/shared/types/color-options.d.ts +23 -2
  27. package/dist/shared/types/colors.d.ts +38 -0
  28. package/dist/shared/types/experimental.d.ts +19 -0
  29. package/dist/shared/types/experimental.js +0 -0
  30. package/dist/shared/types/index.d.ts +3 -1
  31. package/dist/shared/types/runtime-config.d.ts +39 -25
  32. package/dist/shared/unocss-preset.d.ts +27 -1
  33. package/dist/shared/unocss-preset.js +20 -2
  34. package/dist/shared/utils/contrast.d.ts +11 -0
  35. package/dist/shared/utils/contrast.js +24 -0
  36. package/dist/shared/utils/index.d.ts +3 -2
  37. package/dist/shared/utils/index.js +3 -2
  38. package/dist/shared/utils/merge-themes.d.ts +8 -0
  39. package/dist/shared/utils/merge-themes.js +25 -3
  40. package/dist/shared/utils/oklab.d.ts +21 -0
  41. package/dist/shared/utils/oklab.js +74 -0
  42. package/dist/shared/utils/scale.d.ts +53 -0
  43. package/dist/shared/utils/scale.js +164 -0
  44. package/dist/shared/utils/theme-config.d.ts +8 -0
  45. package/dist/shared/utils/theme-config.js +10 -1
  46. package/package.json +15 -9
@@ -6,6 +6,10 @@ type __VLS_Props = {
6
6
  /** Hides "Save changes" in the settings, for a site whose own cookie banner already records consent. */
7
7
  hideConsent?: boolean;
8
8
  };
9
- declare const __VLS_export: import("vue").DefineComponent<__VLS_Props, {}, {}, {}, {}, import("vue").ComponentOptionsMixin, import("vue").ComponentOptionsMixin, {}, string, import("vue").PublicProps, Readonly<__VLS_Props> & Readonly<{}>, {}, {}, {}, {}, string, import("vue").ComponentProvideOptions, false, {}, any>;
9
+ declare const __VLS_export: import("vue").DefineComponent<__VLS_Props, {}, {}, {}, {}, import("vue").ComponentOptionsMixin, import("vue").ComponentOptionsMixin, {
10
+ "consent-needed": () => any;
11
+ }, string, import("vue").PublicProps, Readonly<__VLS_Props> & Readonly<{
12
+ "onConsent-needed"?: (() => any) | undefined;
13
+ }>, {}, {}, {}, {}, string, import("vue").ComponentProvideOptions, false, {}, any>;
10
14
  declare const _default: typeof __VLS_export;
11
15
  export default _default;
@@ -4,13 +4,13 @@ export interface UseThemeCookiesOptions {
4
4
  requireConsent?: boolean;
5
5
  }
6
6
  export declare const useThemeCookies: (options?: UseThemeCookiesOptions) => {
7
- preferenceCookie: import("nuxt/app").CookieRef<string>;
8
- resolvedCookie: import("nuxt/app").CookieRef<string>;
9
- modeCookie: import("nuxt/app").CookieRef<string>;
10
- localeCookie: import("nuxt/app").CookieRef<string>;
11
- scrollbarCookie: import("nuxt/app").CookieRef<string>;
12
- cursorCookie: import("nuxt/app").CookieRef<string>;
13
- fontCookie: import("nuxt/app").CookieRef<string>;
7
+ preferenceCookie: import("#app").CookieRef<string>;
8
+ resolvedCookie: import("#app").CookieRef<string>;
9
+ modeCookie: import("#app").CookieRef<string>;
10
+ localeCookie: import("#app").CookieRef<string>;
11
+ scrollbarCookie: import("#app").CookieRef<string>;
12
+ cursorCookie: import("#app").CookieRef<string>;
13
+ fontCookie: import("#app").CookieRef<string>;
14
14
  canPersist: () => boolean;
15
15
  persistIfConsented: (preference: string, mode: string, resolved: string) => void;
16
16
  persistTogglesIfConsented: (toggles: {
@@ -22,6 +22,18 @@ export declare const useVenixTheme: () => {
22
22
  icon: import("../../shared/utils/icon.js").ResolvedThemeIcon | null;
23
23
  custom: boolean;
24
24
  }[]>;
25
+ /**
26
+ * The semantic color tokens (experimental, v1.4.0) of the themes with
27
+ * `tokens: true`. `current` follows the applied theme and is `undefined`
28
+ * when it has none; `all` is every variant's tokens by `data-theme` id.
29
+ * `cssVar('text-primary')` is `'var(--jade-text-primary)'`, to use in
30
+ * styles that should follow the theme without reading the value.
31
+ */
32
+ tokens: {
33
+ all: Record<string, Record<string, string> | undefined>;
34
+ current: import("vue").ComputedRef<Record<string, string> | undefined>;
35
+ cssVar: (name: string) => string;
36
+ };
25
37
  mode: {
26
38
  value: import("vue").ComputedRef<ThemeMode>;
27
39
  preference: import("vue").Ref<ThemeModePreference, ThemeModePreference>;
@@ -1,6 +1,6 @@
1
1
  import { computed, effectScope, watch } from "vue";
2
2
  import { onNuxtReady, useNuxtApp, useRuntimeConfig, useState } from "#app";
3
- import { DEFAULT_LOCALE, COOKIE_PREFERENCES_UPDATED_EVENT, COOKIE_CONSENT_STORAGE_KEY, THEME_APPLIED_EVENT, SYSTEM_THEME, SCROLLBAR_ATTRIBUTE, CURSOR_ATTRIBUTE, FONT_ATTRIBUTE } from "../../shared/constants";
3
+ import { DEFAULT_LOCALE, COOKIE_PREFERENCES_UPDATED_EVENT, COOKIE_CONSENT_STORAGE_KEY, THEME_APPLIED_EVENT, SYSTEM_THEME, SCROLLBAR_ATTRIBUTE, CURSOR_ATTRIBUTE, FONT_ATTRIBUTE, THEME_PREFERENCE_COOKIE, THEME_MODE_COOKIE, SCROLLBAR_COOKIE, CURSOR_COOKIE, FONT_COOKIE } from "../../shared/constants";
4
4
  import { useThemeCookies } from "./useThemeCookies.js";
5
5
  import { useThemeLocale } from "./useThemeLocale.js";
6
6
  import { useThemeSeasonal } from "./useThemeSeasonal.js";
@@ -199,6 +199,25 @@ function createThemeCore() {
199
199
  isSeasonalActive
200
200
  };
201
201
  }
202
+ function readDocumentCookie(name) {
203
+ for (const part of document.cookie.split(";")) {
204
+ const separator = part.indexOf("=");
205
+ if (separator === -1 || part.slice(0, separator).trim() !== name) continue;
206
+ let value = part.slice(separator + 1).trim();
207
+ try {
208
+ value = decodeURIComponent(value);
209
+ } catch {
210
+ return value;
211
+ }
212
+ try {
213
+ const parsed = JSON.parse(value);
214
+ return typeof parsed === "string" ? parsed : value;
215
+ } catch {
216
+ return value;
217
+ }
218
+ }
219
+ return void 0;
220
+ }
202
221
  function installThemeEffects(core) {
203
222
  const { themeConfig, shouldApplyColors, cookies, hasConsent, locale, preference, modePreference, environmentVersion, scrollbarEnabled, cursorEnabled, fontEnabled } = core;
204
223
  if (themeConfig?.enabled?.manageHtmlLang) {
@@ -207,6 +226,7 @@ function installThemeEffects(core) {
207
226
  document.documentElement.lang = newLocale;
208
227
  });
209
228
  }
229
+ let skipNextThemePersist = false;
210
230
  if (shouldApplyColors) {
211
231
  if (cookies.preferenceCookie.value || cookies.modeCookie.value) {
212
232
  const fromCookies = core.readCookieSelection();
@@ -219,9 +239,37 @@ function installThemeEffects(core) {
219
239
  watch([preference, modePreference], () => {
220
240
  const selection = core.currentSelection();
221
241
  core.applyWithTransition(selection);
242
+ if (skipNextThemePersist) {
243
+ skipNextThemePersist = false;
244
+ return;
245
+ }
222
246
  cookies.persistIfConsented(selection.theme, selection.mode, core.getResolvedTheme(selection));
223
247
  });
224
248
  }
249
+ const syncFromCookies = () => {
250
+ if (!cookies.canPersist()) return;
251
+ if (shouldApplyColors) {
252
+ const themeRaw = readDocumentCookie(THEME_PREFERENCE_COOKIE);
253
+ const modeRaw = readDocumentCookie(THEME_MODE_COOKIE);
254
+ if (themeRaw !== void 0 || modeRaw !== void 0) {
255
+ const fromCookies = normalizeThemeSelection(themeRaw, modeRaw, core.theme.colors);
256
+ if (fromCookies.theme !== preference.value || fromCookies.mode !== modePreference.value) {
257
+ skipNextThemePersist = true;
258
+ preference.value = fromCookies.theme;
259
+ modePreference.value = fromCookies.mode;
260
+ }
261
+ }
262
+ }
263
+ const toggles = [
264
+ [SCROLLBAR_COOKIE, scrollbarEnabled],
265
+ [CURSOR_COOKIE, cursorEnabled],
266
+ [FONT_COOKIE, fontEnabled]
267
+ ];
268
+ for (const [name, state] of toggles) {
269
+ const raw = readDocumentCookie(name);
270
+ if (raw !== void 0 && raw !== "off" !== state.value) state.value = raw !== "off";
271
+ }
272
+ };
225
273
  scrollbarEnabled.value = cookies.scrollbarCookie.value !== "off";
226
274
  cursorEnabled.value = cookies.cursorCookie.value !== "off";
227
275
  fontEnabled.value = cookies.fontCookie.value !== "off";
@@ -233,6 +281,12 @@ function installThemeEffects(core) {
233
281
  onNuxtReady(() => {
234
282
  hasConsent.value = hasCookieConsent();
235
283
  window.addEventListener(COOKIE_PREFERENCES_UPDATED_EVENT, core.syncPersistence);
284
+ const cookieStore = window.cookieStore;
285
+ cookieStore?.addEventListener("change", syncFromCookies);
286
+ window.addEventListener("focus", syncFromCookies);
287
+ document.addEventListener("visibilitychange", () => {
288
+ if (document.visibilityState === "visible") syncFromCookies();
289
+ });
236
290
  if (!shouldApplyColors) return;
237
291
  window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change", () => {
238
292
  environmentVersion.value++;
@@ -259,6 +313,7 @@ export const useVenixTheme = () => {
259
313
  effectScope(true).run(() => installThemeEffects(createThemeCore()));
260
314
  }
261
315
  }
316
+ const tokensByTheme = core.themeConfig?.tokens ?? {};
262
317
  return {
263
318
  theme: {
264
319
  value: core.resolvedTheme,
@@ -272,6 +327,18 @@ export const useVenixTheme = () => {
272
327
  colors: core.theme.colors
273
328
  },
274
329
  themes: core.colors.themes,
330
+ /**
331
+ * The semantic color tokens (experimental, v1.4.0) of the themes with
332
+ * `tokens: true`. `current` follows the applied theme and is `undefined`
333
+ * when it has none; `all` is every variant's tokens by `data-theme` id.
334
+ * `cssVar('text-primary')` is `'var(--jade-text-primary)'`, to use in
335
+ * styles that should follow the theme without reading the value.
336
+ */
337
+ tokens: {
338
+ all: tokensByTheme,
339
+ current: computed(() => tokensByTheme[core.resolvedTheme.value]),
340
+ cssVar: (name) => `var(--jade-${name})`
341
+ },
275
342
  mode: {
276
343
  value: core.resolvedMode,
277
344
  preference: core.modePreference,
@@ -1,2 +1,2 @@
1
- declare const _default: import("nuxt/app").Plugin<Record<string, unknown>> & import("nuxt/app").ObjectPlugin<Record<string, unknown>>;
1
+ declare const _default: import("#app").Plugin<Record<string, unknown>> & import("#app").ObjectPlugin<Record<string, unknown>>;
2
2
  export default _default;
@@ -1,2 +1,2 @@
1
- declare const _default: import("nuxt/app").Plugin<Record<string, unknown>> & import("nuxt/app").ObjectPlugin<Record<string, unknown>>;
1
+ declare const _default: import("#app").Plugin<Record<string, unknown>> & import("#app").ObjectPlugin<Record<string, unknown>>;
2
2
  export default _default;
@@ -1,2 +1,2 @@
1
- declare const _default: import("nuxt/app").Plugin<Record<string, unknown>> & import("nuxt/app").ObjectPlugin<Record<string, unknown>>;
1
+ declare const _default: import("#app").Plugin<Record<string, unknown>> & import("#app").ObjectPlugin<Record<string, unknown>>;
2
2
  export default _default;
@@ -94,4 +94,4 @@ export declare const SWITCHER_CREDIT: {
94
94
  readonly url: "https://github.com/Venix-Sistemas/jade";
95
95
  };
96
96
  export declare const COLOR_PROPERTIES: readonly ["primary", "secondary", "accent", "error", "info", "success", "warning", "background", "background2", "background3"];
97
- export declare const NON_COLOR_PROPERTIES: readonly ["id", "dark", "light", "seasonal", "dateRange", "translations", "icon"];
97
+ export declare const NON_COLOR_PROPERTIES: readonly ["id", "dark", "light", "seasonal", "dateRange", "translations", "icon", "tokens", "neutralTint"];
@@ -61,5 +61,7 @@ export const NON_COLOR_PROPERTIES = [
61
61
  "seasonal",
62
62
  "dateRange",
63
63
  "translations",
64
- "icon"
64
+ "icon",
65
+ "tokens",
66
+ "neutralTint"
65
67
  ];
@@ -1,2 +1,2 @@
1
- import type { ThemeColors } from '../types/index.js';
2
- export declare function generateThemeVars(mode: string, colors: ThemeColors): string;
1
+ import type { ContrastLevel, ThemeColors } from '../types/index.js';
2
+ export declare function generateThemeVars(mode: string, colors: ThemeColors, contrast?: ContrastLevel): string;
@@ -1,6 +1,11 @@
1
1
  import { getThemeHexColors } from "../utils/theme-resolve.js";
2
- export function generateThemeVars(mode, colors) {
2
+ import { tokensEnabled } from "../token-names.js";
3
+ import { generateTokenVars } from "./tokens.js";
4
+ export function generateThemeVars(mode, colors, contrast) {
3
5
  const colorVars = getThemeHexColors(colors).map(([key, value]) => ` --color-${key}: ${value};`).join("\n");
6
+ const tokenVars = tokensEnabled(colors) ? `
7
+ /* Semantic tokens */
8
+ ${generateTokenVars(colors, contrast)}` : "";
4
9
  const isDark = colors.dark === true;
5
10
  const colorScheme = isDark ? "dark" : "light";
6
11
  const inverseColor = isDark ? "#FFFFFF" : "#000000";
@@ -13,7 +18,7 @@ export function generateThemeVars(mode, colors) {
13
18
  color-scheme: ${colorScheme};
14
19
  --color-scheme: ${colorScheme === "dark" ? "#000000" : "#FFFFFF"};
15
20
  --color-inverse: ${inverseColor};
16
- ` + colorVars + `
21
+ ` + colorVars + tokenVars + `
17
22
  }
18
23
  `;
19
24
  }
@@ -2,6 +2,67 @@ import { isColorTheme } from "../utils/theme-resolve.js";
2
2
  import { generateCursorSVG } from "./cursor-svg.js";
3
3
  import { CURSOR_ATTRIBUTE } from "../constants.js";
4
4
  const CURSOR_TYPES = ["default", "pointer", "text"];
5
+ const VUETIFY_DEFAULT = [
6
+ ".v-text-field__prefix, .v-text-field__suffix",
7
+ ".v-slider .v-slider__container input",
8
+ ".v-time-picker-clock__item",
9
+ ".v-file-upload-dropzone--has-files:not(.v-file-upload-dropzone--clickable), .v-file-upload-dropzone--readonly"
10
+ ];
11
+ const VUETIFY_POINTER = [
12
+ // Clickable components Vuetify marks with a class (a plain `.v-icon` or
13
+ // `.v-list-item` is often just decoration or text)
14
+ ".v-btn:not(.v-btn--disabled)",
15
+ ".v-icon--clickable",
16
+ ".v-icon-btn",
17
+ ".v-list-item--link",
18
+ ".v-chip--link",
19
+ ".v-chip__close",
20
+ ".v-tab",
21
+ ".v-card--link",
22
+ ".v-card--hover",
23
+ ".v-breadcrumbs-item--link",
24
+ ".v-pagination__item",
25
+ ".v-slide-group__next, .v-slide-group__prev",
26
+ ".v-avatar-group--hoverable .v-avatar",
27
+ // Menu activators and the like
28
+ "[aria-controls]",
29
+ // Tables
30
+ ".v-data-table__tr--clickable",
31
+ ".v-data-table__th--sortable",
32
+ // Form controls
33
+ ".v-field__clearable",
34
+ ".v-select .v-field .v-text-field__prefix, .v-select .v-field .v-text-field__suffix, .v-select .v-field .v-field__input, .v-select .v-field.v-field",
35
+ ".v-label--clickable",
36
+ ".v-selection-control__input input",
37
+ ".v-switch__track",
38
+ ".v-slider__container",
39
+ ".v-slider-thumb__surface",
40
+ ".v-rating__item label",
41
+ ".v-file-upload-dropzone--clickable:not(.v-file-upload-dropzone--readonly)",
42
+ ".v-file-upload-dropzone input[type=file]",
43
+ // Pickers
44
+ ".v-date-picker-header--clickable .v-date-picker-header__content",
45
+ ".v-color-picker-swatches__color",
46
+ // Calendar
47
+ ".v-calendar .v-event, .v-calendar .v-event-more, .v-calendar .v-event-timed",
48
+ ".v-calendar-weekly__day-label",
49
+ ".v-calendar-daily_head-day-label",
50
+ ".v-calendar-daily .v-calendar-daily__day-interval--hover",
51
+ // Labs
52
+ ".v-heatmap--hover .v-heatmap__cell",
53
+ ".v-heatmap-legend > .v-heatmap-legend__cell",
54
+ ".v-media-progress-bar--interactive",
55
+ ".v-video:not(.v-video--error) .v-video__content"
56
+ ];
57
+ const VUETIFY_TEXT = [
58
+ ".v-text-field .v-field",
59
+ ".v-autocomplete .v-field .v-text-field__prefix, .v-autocomplete .v-field .v-text-field__suffix, .v-autocomplete .v-field .v-field__input, .v-autocomplete .v-field.v-field",
60
+ ".v-combobox .v-field .v-text-field__prefix, .v-combobox .v-field .v-text-field__suffix, .v-combobox .v-field .v-field__input, .v-combobox .v-field.v-field"
61
+ ];
62
+ const rule = (selectors, type) => `${selectors.join(",\n")} {
63
+ cursor: var(--cursor-${type});
64
+ }
65
+ `;
5
66
  const imageValue = (image, type) => `url('${image.path}')${image.hotspot ? ` ${image.hotspot}` : ""}, ${type}`;
6
67
  export function generateCustomCursorCSS(theme) {
7
68
  const cursor = theme.customCursor;
@@ -69,6 +130,8 @@ input[type="range"], input[type="color"], input[type="file"] {
69
130
  cursor: var(--cursor-default);
70
131
  }
71
132
  `;
133
+ css += "\n/* 1c. Vuetify elements with a fixed `cursor: default` */\n";
134
+ css += rule(VUETIFY_DEFAULT, "default");
72
135
  }
73
136
  if (types.includes("pointer")) {
74
137
  css += "\n/* 2. Pointer cursor for clickable elements */\n";
@@ -77,18 +140,12 @@ button, button *,
77
140
  summary,
78
141
  [role="button"], [role="link"], [role="tab"],
79
142
  input[type="button"], input[type="submit"], input[type="reset"],
80
- .v-btn:not(.v-btn--disabled),
81
- .v-icon--clickable,
82
- .v-list-item--link,
83
- .v-chip--link,
84
- .v-tab,
85
- .v-card--link,
86
- .v-breadcrumbs-item--link,
87
- .v-pagination__item,
88
143
  .os-scrollbar, .os-scrollbar * {
89
144
  cursor: var(--cursor-pointer) !important;
90
145
  }
91
146
  `;
147
+ css += "\n/* 2b. Vuetify elements with a fixed `cursor: pointer` */\n";
148
+ css += rule(VUETIFY_POINTER, "pointer");
92
149
  }
93
150
  if (types.includes("text")) {
94
151
  css += "\n/* 3. Text cursor (i-beam) for editable fields only */\n";
@@ -110,9 +167,16 @@ textarea,
110
167
  cursor: var(--cursor-text) !important;
111
168
  }
112
169
  `;
170
+ css += "\n/* 3b. Vuetify elements with a fixed `cursor: text` (the field around the input) */\n";
171
+ css += rule(VUETIFY_TEXT, "text");
113
172
  }
173
+ css += "\n/* 4. Cursor utility classes */\n";
174
+ css += types.map((type) => `html .cursor-${type} {
175
+ cursor: var(--cursor-${type});
176
+ }
177
+ `).join("");
114
178
  if (types.includes("default")) {
115
- css += "\n/* 4. Disabled elements, and what they contain */\n";
179
+ css += "\n/* 5. Disabled elements, and what they contain */\n";
116
180
  css += `html :disabled, html :disabled *,
117
181
  html [disabled], html [disabled] *,
118
182
  html [aria-disabled="true"], html [aria-disabled="true"] *,
@@ -15,7 +15,7 @@ export function processTheme(theme) {
15
15
  output.push(generateThemeTransitionCSS());
16
16
  for (const [themeName, themeColors] of Object.entries(theme.colors.themes)) {
17
17
  if (themeName === "system" || !isColorTheme(themeColors)) continue;
18
- output.push(generateThemeVars(themeName, themeColors));
18
+ output.push(generateThemeVars(themeName, themeColors, theme.colors.contrast || void 0));
19
19
  }
20
20
  }
21
21
  }
@@ -2,6 +2,11 @@ import { OVERLAY_SCROLLBAR_THEME, SCROLLBAR_ATTRIBUTE } from "../constants.js";
2
2
  const ON = `html:not([${SCROLLBAR_ATTRIBUTE}='off'])`;
3
3
  const on = (pseudo) => `${ON}${pseudo},
4
4
  ${ON} ${pseudo}`;
5
+ const SURFACE_TOKENS = {
6
+ background: "bg",
7
+ background2: "bg-subtle",
8
+ background3: "bg-muted"
9
+ };
5
10
  export function generateCustomScrollbarCSS(theme) {
6
11
  const scrollbar = theme.customScrollbar;
7
12
  if (!scrollbar || !scrollbar.enabled) return "";
@@ -13,7 +18,8 @@ export function generateCustomScrollbarCSS(theme) {
13
18
  if (value.startsWith("var(--") || value.startsWith("#") || value.startsWith("rgb")) {
14
19
  return value;
15
20
  }
16
- return `var(--color-${value})`;
21
+ const token = SURFACE_TOKENS[value];
22
+ return token ? `var(--color-${value}, var(--jade-${token}))` : `var(--color-${value})`;
17
23
  };
18
24
  const thumb = colorVar("thumb", "primary");
19
25
  const thumbHover = colorVar("thumbHover", "secondary");
@@ -0,0 +1,40 @@
1
+ import type { ContrastLevel, ThemeColors } from '../types/index.js';
2
+ /**
3
+ * `[name, hex]` pairs, without the `--jade-` prefix, in the order they are
4
+ * written. Memoized: the CSS and the build check ask for the same variant.
5
+ */
6
+ export declare function generateTokens(colors: ThemeColors, level?: ContrastLevel): Array<[string, string]>;
7
+ /** The `--jade-*` declarations for `generateTokens`, one per line, indented for a theme block. */
8
+ export declare function generateTokenVars(colors: ThemeColors, level?: ContrastLevel): string;
9
+ /**
10
+ * The tokens of every variant with `tokens: true`, by variant id and token
11
+ * name, as plain hex values — what the runtime config carries so the client
12
+ * can read them without the color engine.
13
+ */
14
+ export declare function collectTokens(themes: Record<string, ThemeColors>, level?: ContrastLevel): Record<string, Record<string, string>>;
15
+ export interface TokenContrastIssue {
16
+ /** The token used as text or outline. */
17
+ text: string;
18
+ /** The token it sits on. */
19
+ surface: string;
20
+ ratio: number;
21
+ min: number;
22
+ }
23
+ /**
24
+ * The pairs that fall short of `level`: text 4.5:1 (7:1 for AAA), outlines
25
+ * 3:1. A pair is skipped when either token doesn't exist (a theme without
26
+ * `secondary` has no `text-secondary`).
27
+ */
28
+ export declare function checkTokenContrast(tokens: Array<[string, string]>, level: ContrastLevel): TokenContrastIssue[];
29
+ /**
30
+ * One build warning per token theme variant with pairs below `level`, or an
31
+ * empty list when everything passes. Variants without tokens are skipped.
32
+ */
33
+ export declare function findTokenContrastIssues(themes: Record<string, ThemeColors>, level: ContrastLevel): string[];
34
+ /**
35
+ * One build warning per token theme variant whose `tokens` overrides name an
36
+ * unknown token (or `on-<role>`), a step that doesn't exist, or a role the
37
+ * variant has no seed for. Those entries are ignored, so the warning is the
38
+ * only sign.
39
+ */
40
+ export declare function findTokenOverrideIssues(themes: Record<string, ThemeColors>): string[];
@@ -0,0 +1,119 @@
1
+ import { contrastRatio } from "../utils/contrast.js";
2
+ import { generateScales } from "../utils/scale.js";
3
+ import { NEUTRAL_TOKENS, OVERRIDABLE_TOKEN_NAMES, ROLE_TOKENS, TOKEN_ROLES as ROLES, parseStepRef, roleTokenName, tokenOverrides, tokensEnabled } from "../token-names.js";
4
+ const FALLBACK_BACKGROUND = { light: "#FFFFFF", dark: "#121212" };
5
+ const tokenCache = /* @__PURE__ */ new Map();
6
+ export function generateTokens(colors, level = "AA") {
7
+ const key = JSON.stringify([colors.dark === true, colors.background, colors.primary, colors.secondary, level, colors.neutralTint !== false, tokenOverrides(colors)]);
8
+ let tokens = tokenCache.get(key);
9
+ if (!tokens) {
10
+ tokens = buildTokens(colors, level);
11
+ tokenCache.set(key, tokens);
12
+ }
13
+ return tokens;
14
+ }
15
+ function buildTokens(colors, level) {
16
+ const mode = colors.dark === true ? "dark" : "light";
17
+ const background = colors.background ?? FALLBACK_BACKGROUND[mode];
18
+ const seeds = {};
19
+ for (const role of ROLES) {
20
+ const seed = colors[role];
21
+ if (seed) seeds[role] = seed;
22
+ }
23
+ const { neutral, roles } = generateScales(background, seeds, mode, level, { tint: colors.neutralTint !== false });
24
+ const tokens = NEUTRAL_TOKENS.map(([name, step]) => [name, neutral[step - 1]]);
25
+ const primary = roles.primary;
26
+ if (primary) tokens.push(["border-focus", primary.steps[10]]);
27
+ for (const role of ROLES) {
28
+ const scale = roles[role];
29
+ if (!scale) continue;
30
+ for (const [name, step] of ROLE_TOKENS) {
31
+ tokens.push([roleTokenName(name, role), scale.steps[step - 1]]);
32
+ }
33
+ tokens.push([`on-${role}`, scale.on]);
34
+ }
35
+ applyOverrides(tokens, tokenOverrides(colors), neutral, roles);
36
+ return tokens;
37
+ }
38
+ function applyOverrides(tokens, overrides, neutral, roles) {
39
+ for (const [name, ref] of Object.entries(overrides)) {
40
+ const parsed = parseStepRef(ref);
41
+ const entry = tokens.find(([tokenName]) => tokenName === name);
42
+ if (!parsed || !entry || !OVERRIDABLE_TOKEN_NAMES.includes(name)) continue;
43
+ const scale = parsed.scale === "neutral" ? neutral : roles[parsed.scale]?.steps;
44
+ const color = scale?.[parsed.step - 1];
45
+ if (color) entry[1] = color;
46
+ }
47
+ }
48
+ export function generateTokenVars(colors, level = "AA") {
49
+ return generateTokens(colors, level).map(([name, value]) => ` --jade-${name}: ${value};`).join("\n");
50
+ }
51
+ export function collectTokens(themes, level = "AA") {
52
+ const collected = {};
53
+ for (const [id, colors] of Object.entries(themes)) {
54
+ if (tokensEnabled(colors)) collected[id] = Object.fromEntries(generateTokens(colors, level));
55
+ }
56
+ return collected;
57
+ }
58
+ const NEUTRAL_SURFACES = ["bg", "bg-subtle", "bg-muted"];
59
+ const NEUTRAL_RULES = [
60
+ ["text", [...NEUTRAL_SURFACES, "bg-hover", "bg-active"], "text"],
61
+ ["text-muted", NEUTRAL_SURFACES, "text"],
62
+ ["border-strong", ["bg", "bg-subtle"], "outline"],
63
+ ["border-focus", ["bg", "bg-subtle"], "outline"]
64
+ ];
65
+ function roleRules(role) {
66
+ return [
67
+ [`on-${role}`, [`fill-${role}`, `fill-${role}-hover`], "text"],
68
+ [`text-${role}`, [...NEUTRAL_SURFACES, `bg-${role}`], "text"],
69
+ [`text-${role}-strong`, [`bg-${role}-hover`, `bg-${role}-active`], "text"],
70
+ ["text", [`bg-${role}`, `bg-${role}-active`], "text"],
71
+ [`border-${role}-strong`, ["bg"], "outline"]
72
+ ];
73
+ }
74
+ const OUTLINE_MIN = 3;
75
+ const TEXT_MIN = { AA: 4.5, AAA: 7 };
76
+ export function checkTokenContrast(tokens, level) {
77
+ const byName = new Map(tokens);
78
+ const roles = ROLES.filter((role) => byName.has(`fill-${role}`));
79
+ const issues = [];
80
+ for (const [text, surfaces, kind] of [...NEUTRAL_RULES, ...roles.flatMap(roleRules)]) {
81
+ const foreground = byName.get(text);
82
+ if (!foreground) continue;
83
+ const min = kind === "text" ? TEXT_MIN[level] : OUTLINE_MIN;
84
+ for (const surface of surfaces) {
85
+ const background = byName.get(surface);
86
+ if (!background) continue;
87
+ const ratio = contrastRatio(foreground, background);
88
+ if (ratio < min) issues.push({ text, surface, ratio, min });
89
+ }
90
+ }
91
+ return issues;
92
+ }
93
+ const formatRatio = (ratio) => (Math.floor(ratio * 100) / 100).toFixed(2);
94
+ export function findTokenContrastIssues(themes, level) {
95
+ const messages = [];
96
+ for (const [id, colors] of Object.entries(themes)) {
97
+ if (!tokensEnabled(colors)) continue;
98
+ const issues = checkTokenContrast(generateTokens(colors, level), level);
99
+ if (!issues.length) continue;
100
+ const pairs = issues.map((issue) => `\`${issue.text}\` on \`${issue.surface}\` ${formatRatio(issue.ratio)}:1 (needs ${issue.min}:1)`).join("; ");
101
+ const hint = level === "AAA" ? "Pick another seed, or set `color.contrast` to `'AA'` (or `false` to skip this check)." : "Pick another seed, or set `color.contrast` to `false` to skip this check.";
102
+ messages.push(`The semantic tokens of \`${id}\` fall short of WCAG ${level}: ${pairs}. ${hint}`);
103
+ }
104
+ return messages;
105
+ }
106
+ export function findTokenOverrideIssues(themes) {
107
+ const messages = [];
108
+ for (const [id, colors] of Object.entries(themes)) {
109
+ const problems = [];
110
+ for (const [name, ref] of Object.entries(tokenOverrides(colors))) {
111
+ const parsed = parseStepRef(ref);
112
+ if (!OVERRIDABLE_TOKEN_NAMES.includes(name)) problems.push(`\`${name}\` is not a token that can be overridden`);
113
+ else if (!parsed) problems.push(`\`${name}\`: \`${String(ref)}\` is not a step (use \`neutral-1\` to \`neutral-12\`, \`primary-1\`\u2026)`);
114
+ else if (parsed.scale !== "neutral" && !colors[parsed.scale]) problems.push(`\`${name}\`: the variant has no \`${parsed.scale}\` seed`);
115
+ }
116
+ if (problems.length) messages.push(`Some \`tokens\` overrides of \`${id}\` were ignored: ${problems.join("; ")}.`);
117
+ }
118
+ return messages;
119
+ }