Skip to content

The open alternative to Salesforce, designed for AI.

Resolve numeric twenty-ui theme tokens when CSS variables can't be read (#29436)

Weiko6544e137e4d7
diff --git a/packages/twenty-ui/design-tokens/pipeline/__tests__/buildThemeNumericValueByCssVariable.test.ts b/packages/twenty-ui/design-tokens/pipeline/__tests__/buildThemeNumericValueByCssVariable.test.ts
new file mode 100644
index 00000000000..3ae53174715
--- /dev/null
+++ b/packages/twenty-ui/design-tokens/pipeline/__tests__/buildThemeNumericValueByCssVariable.test.ts
@@ -0,0 +1,69 @@
+import { type CollectedTokenLeaf } from '../../types/CollectedTokenLeaf';
+import { buildThemeNumericValueByCssVariable } from '../buildThemeNumericValueByCssVariable';
+import { pathToVarName } from '../pathToVarName';
+
+const leaf = ({
+ path,
+ light,
+ dark = light,
+ unit,
+}: {
+ path: string[];
+ light: string;
+ dark?: string;
+ unit?: 'number';
+}): CollectedTokenLeaf => ({
+ path,
+ varName: pathToVarName(path),
+ light,
+ dark,
+ unit,
+});
+
+describe('buildThemeNumericValueByCssVariable', () => {
+ it('maps each numeric token to its literal value by CSS variable', () => {
+ const output = buildThemeNumericValueByCssVariable([
+ leaf({ path: ['icon', 'size', 'md'], light: '16', unit: 'number' }),
+ leaf({
+ path: ['animation', 'duration', 'fast'],
+ light: '0.15',
+ unit: 'number',
+ }),
+ leaf({ path: ['background', 'primary'], light: '#fff', dark: '#000' }),
+ leaf({ path: ['border', 'radius', 'md'], light: '8px' }),
+ ]);
+
+ expect(output).toContain("'--t-icon-size-md': 16,");
+ expect(output).toContain("'--t-animation-duration-fast': 0.15,");
+ expect(output).not.toContain('--t-background-primary');
+ expect(output).not.toContain('--t-border-radius-md');
+ });
+
+ it('accepts equivalent numeric spellings across schemes', () => {
+ const output = buildThemeNumericValueByCssVariable([
+ leaf({
+ path: ['icon', 'stroke', 'sm'],
+ light: '1',
+ dark: '1.0',
+ unit: 'number',
+ }),
+ ]);
+
+ expect(output).toContain("'--t-icon-stroke-sm': 1,");
+ });
+
+ it('throws when a numeric token differs between schemes', () => {
+ expect(() =>
+ buildThemeNumericValueByCssVariable([
+ leaf({
+ path: ['icon', 'size', 'md'],
+ light: '16',
+ dark: '20',
+ unit: 'number',
+ }),
+ ]),
+ ).toThrow(
+ 'Numeric token "icon.size.md" must be scheme-invariant, got light "16" / dark "20".',
+ );
+ });
+});
diff --git a/packages/twenty-ui/design-tokens/pipeline/buildThemeNumericValueByCssVariable.ts b/packages/twenty-ui/design-tokens/pipeline/buildThemeNumericValueByCssVariable.ts
new file mode 100644
index 00000000000..179f63d66d7
--- /dev/null
+++ b/packages/twenty-ui/design-tokens/pipeline/buildThemeNumericValueByCssVariable.ts
@@ -0,0 +1,28 @@
+import { type CollectedTokenLeaf } from '../types/CollectedTokenLeaf';
+import { isDefined } from '../../src/utilities/utils/isDefined';
+import { quoteSingle } from './quoteSingle';
+
+export const buildThemeNumericValueByCssVariable = (
+ leaves: CollectedTokenLeaf[],
+): string => {
+ const numericLeaves = leaves.filter((leaf) => leaf.unit === 'number');
+ const schemeVariantLeaf = numericLeaves.find(
+ (leaf) => Number(leaf.light) !== Number(leaf.dark),
+ );
+ if (isDefined(schemeVariantLeaf)) {
+ throw new Error(
+ `Numeric token "${schemeVariantLeaf.path.join('.')}" must be scheme-invariant, got light "${schemeVariantLeaf.light}" / dark "${schemeVariantLeaf.dark}".`,
+ );
+ }
+ const entries = numericLeaves
+ .map(
+ (leaf) =>
+ ` ${quoteSingle(leaf.varName)}: ${String(Number(leaf.light))},`,
+ )
+ .join('\n');
+ return `// Generated by scripts/generateThemeTokens.ts, do not edit.
+export const THEME_NUMERIC_VALUE_BY_CSS_VARIABLE: Record<string, number> = {
+${entries}
+};
+`;
+};
diff --git a/packages/twenty-ui/scripts/generateThemeTokens.ts b/packages/twenty-ui/scripts/generateThemeTokens.ts
index 4635d0f2be7..16741ffe7cd 100644
--- a/packages/twenty-ui/scripts/generateThemeTokens.ts
+++ b/packages/twenty-ui/scripts/generateThemeTokens.ts
@@ -10,6 +10,7 @@ import { buildThemeConstants } from '../design-tokens/pipeline/buildThemeConstan
import { buildThemeCss } from '../design-tokens/pipeline/buildThemeCss';
import { buildThemeCommon } from '../design-tokens/pipeline/buildThemeCommon';
import { buildThemeCssVariables } from '../design-tokens/pipeline/buildThemeCssVariables';
+import { buildThemeNumericValueByCssVariable } from '../design-tokens/pipeline/buildThemeNumericValueByCssVariable';
import { buildThemeSpacing } from '../design-tokens/pipeline/buildThemeSpacing';
import { buildThemeSubtreeConstant } from '../design-tokens/pipeline/buildThemeSubtreeConstant';
import { buildThemeTypes } from '../design-tokens/pipeline/buildThemeTypes';
@@ -43,6 +44,10 @@ const sourceOutputs = [
path: resolve(themeDirectory, 'internal/themeSpacing.ts'),
content: buildThemeSpacing(leaves),
},
+ {
+ path: resolve(themeDirectory, 'internal/ThemeNumericValueByCssVariable.ts'),
+ content: buildThemeNumericValueByCssVariable(leaves),
+ },
{
path: resolve(themeDirectory, 'constants/ThemeLight.ts'),
content: buildThemeConstants({ leaves, scheme: 'light' }),
diff --git a/packages/twenty-ui/src/theme/__stories__/ThemeProvider.stories.tsx b/packages/twenty-ui/src/theme/__stories__/ThemeProvider.stories.tsx
index e280eaf6a77..421ebe5a601 100644
--- a/packages/twenty-ui/src/theme/__stories__/ThemeProvider.stories.tsx
+++ b/packages/twenty-ui/src/theme/__stories__/ThemeProvider.stories.tsx
@@ -143,8 +143,8 @@ export const UnresolvedTokens: Story = {
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
- await expect(canvas.getByLabelText('Medium icon size')).toHaveTextContent(
- JSON.stringify(themeCssVariables.icon.size.md),
+ await expect(canvas.getByLabelText('Medium icon size').textContent).toBe(
+ String(THEME_LIGHT.icon.size.md),
);
await expect(canvas.getByLabelText('Primary font color')).toHaveTextContent(
JSON.stringify(themeCssVariables.font.color.primary),
@@ -155,16 +155,19 @@ export const UnresolvedTokens: Story = {
export const NumericTokens: Story = {
args: {
applyToRoot: false,
- overrides: { '--t-icon-size-md': '16', '--t-icon-size-sm': 'initial' },
+ overrides: {
+ '--t-icon-size-md': String(THEME_LIGHT.icon.size.md),
+ '--t-icon-size-sm': 'initial',
+ },
},
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
await expect(canvas.getByLabelText('Medium icon size').textContent).toBe(
- '16',
+ String(THEME_LIGHT.icon.size.md),
);
- await expect(canvas.getByLabelText('Small icon size')).toHaveTextContent(
- JSON.stringify(themeCssVariables.icon.size.sm),
+ await expect(canvas.getByLabelText('Small icon size').textContent).toBe(
+ String(THEME_LIGHT.icon.size.sm),
);
},
};
diff --git a/packages/twenty-ui/src/theme/__tests__/ThemeProvider.test.tsx b/packages/twenty-ui/src/theme/__tests__/ThemeProvider.test.tsx
index 189db667424..194b7ce9bd0 100644
--- a/packages/twenty-ui/src/theme/__tests__/ThemeProvider.test.tsx
+++ b/packages/twenty-ui/src/theme/__tests__/ThemeProvider.test.tsx
@@ -1,11 +1,43 @@
import { render, screen, within } from '@testing-library/react';
import { expect, it } from 'vitest';
+import { IconInfoCircle } from '@ui/icon/components/TablerIcons';
import { THEME_DARK } from '@ui/theme/constants/ThemeDark';
import { THEME_LIGHT } from '@ui/theme/constants/ThemeLight';
+import { themeCssVariables } from '@ui/theme/themeCssVariables';
import { ThemeProvider } from '@ui/theme/ThemeProvider';
import { useTheme } from '@ui/theme/useTheme';
+const ThemeSizedIcon = () => {
+ const theme = useTheme();
+
+ return (
+ <>
+ <IconInfoCircle
+ role="img"
+ aria-label="Info"
+ size={theme.icon.size.md}
+ stroke={theme.icon.stroke.sm}
+ />
+ <output aria-label="Font color">{theme.font.color.primary}</output>
+ </>
+ );
+};
+
+const expectNumericIconWithHostColor = () => {
+ const icon = screen.getByRole('img', { name: 'Info' });
+
+ expect(icon).toHaveAttribute('width', String(THEME_LIGHT.icon.size.md));
+ expect(icon).toHaveAttribute('height', String(THEME_LIGHT.icon.size.md));
+ expect(icon).toHaveAttribute(
+ 'stroke-width',
+ String(THEME_LIGHT.icon.stroke.sm),
+ );
+ expect(screen.getByLabelText('Font color')).toHaveTextContent(
+ themeCssVariables.font.color.primary,
+ );
+};
+
const SpacingReadout = () => {
const theme = useTheme();
@@ -18,6 +50,22 @@ const SpacingReadout = () => {
);
};
+it('gives icons numeric sizes without a provider', () => {
+ render(<ThemeSizedIcon />);
+
+ expectNumericIconWithHostColor();
+});
+
+it('gives icons numeric sizes when theme CSS variables cannot be read', () => {
+ render(
+ <ThemeProvider colorScheme="light" applyToRoot={false}>
+ <ThemeSizedIcon />
+ </ThemeProvider>,
+ );
+
+ expectNumericIconWithHostColor();
+});
+
it('exposes spacing entries when given static theme values', () => {
render(
<ThemeProvider colorScheme="dark" applyToRoot={false} theme={THEME_DARK}>
diff --git a/packages/twenty-ui/src/theme/__tests__/resolveThemeTokens.test.ts b/packages/twenty-ui/src/theme/__tests__/resolveThemeTokens.test.ts
new file mode 100644
index 00000000000..83d9820cb68
--- /dev/null
+++ b/packages/twenty-ui/src/theme/__tests__/resolveThemeTokens.test.ts
@@ -0,0 +1,41 @@
+import { THEME_LIGHT } from '../constants/ThemeLight';
+import { resolveThemeTokens } from '../internal/resolveThemeTokens';
+import { themeCssVariables } from '../themeCssVariables';
+
+it('uses static numeric values while keeping unresolved colors on the host', () => {
+ const theme = resolveThemeTokens();
+
+ expect(theme.icon).toEqual(THEME_LIGHT.icon);
+ expect(theme.font.weight).toEqual(THEME_LIGHT.font.weight);
+ expect(theme.animation).toEqual(THEME_LIGHT.animation);
+ expect(theme.spacingMultiplicator).toBe(THEME_LIGHT.spacingMultiplicator);
+ expect(theme.font.color).toEqual(themeCssVariables.font.color);
+ expect(theme.spacing).toEqual(themeCssVariables.spacing);
+});
+
+it('uses readable CSS overrides before numeric fallbacks', () => {
+ const cssValues: Record<string, string> = {
+ '--t-icon-size-md': '20',
+ '--t-icon-stroke-sm': '0',
+ '--t-font-color-primary': '#123456',
+ };
+ const theme = resolveThemeTokens((name) => cssValues[name] ?? '');
+
+ expect(theme.icon.size.md).toBe(20);
+ expect(theme.icon.size.sm).toBe(THEME_LIGHT.icon.size.sm);
+ expect(theme.icon.stroke.sm).toBe(0);
+ expect(theme.font.color.primary).toBe('#123456');
+ expect(theme.font.color.secondary).toBe(
+ themeCssVariables.font.color.secondary,
+ );
+});
+
+it('keeps resolved themes independent from each other and the static theme', () => {
+ const originalSize = THEME_LIGHT.icon.size.md;
+ const theme = resolveThemeTokens();
+
+ theme.icon.size.md = originalSize + 1;
+
+ expect(THEME_LIGHT.icon.size.md).toBe(originalSize);
+ expect(resolveThemeTokens().icon.size.md).toBe(originalSize);
+});
diff --git a/packages/twenty-ui/src/theme/internal/ThemeNumericValueByCssVariable.ts b/packages/twenty-ui/src/theme/internal/ThemeNumericValueByCssVariable.ts
new file mode 100644
index 00000000000..96cca5cbfdf
--- /dev/null
+++ b/packages/twenty-ui/src/theme/internal/ThemeNumericValueByCssVariable.ts
@@ -0,0 +1,26 @@
+// Generated by scripts/generateThemeTokens.ts, do not edit.
+export const THEME_NUMERIC_VALUE_BY_CSS_VARIABLE: Record<string, number> = {
+ '--t-icon-size-sm': 14,
+ '--t-icon-size-md': 16,
+ '--t-icon-size-lg': 20,
+ '--t-icon-size-xl': 24,
+ '--t-icon-stroke-sm': 1.6,
+ '--t-icon-stroke-md': 2,
+ '--t-icon-stroke-lg': 2.5,
+ '--t-text-line-height-lg': 1.5,
+ '--t-text-line-height-md': 1.1,
+ '--t-text-icon-size-medium': 16,
+ '--t-text-icon-size-small': 14,
+ '--t-text-icon-strike-light': 1.6,
+ '--t-text-icon-strike-medium': 2,
+ '--t-text-icon-strike-bold': 2.5,
+ '--t-animation-duration-instant': 0.075,
+ '--t-animation-duration-fast': 0.15,
+ '--t-animation-duration-normal': 0.3,
+ '--t-animation-duration-slow': 1.5,
+ '--t-spacing-multiplicator': 4,
+ '--t-last-layer-z-index': 2147483647,
+ '--t-font-weight-regular': 400,
+ '--t-font-weight-medium': 500,
+ '--t-font-weight-semi-bold': 600,
+};
diff --git a/packages/twenty-ui/src/theme/internal/ThemeTokenTree.ts b/packages/twenty-ui/src/theme/internal/ThemeTokenTree.ts
new file mode 100644
index 00000000000..b4f7673274b
--- /dev/null
+++ b/packages/twenty-ui/src/theme/internal/ThemeTokenTree.ts
@@ -0,0 +1,3 @@
+export type ThemeTokenTree = {
+ [key: string]: string | number | ThemeTokenTree;
+};
diff --git a/packages/twenty-ui/src/theme/internal/computeThemeFromCss.ts b/packages/twenty-ui/src/theme/internal/computeThemeFromCss.ts
index e1345107c3e..0c9555703a5 100644
--- a/packages/twenty-ui/src/theme/internal/computeThemeFromCss.ts
+++ b/packages/twenty-ui/src/theme/internal/computeThemeFromCss.ts
@@ -1,61 +1,19 @@
-import { isNonEmptyString, isObject, isString } from '@sniptt/guards';
-
-import { themeCssVariables } from '../themeCssVariables';
import { type ThemeType } from '../themeTypes';
-
-const resolveTokenValue = ({
- cssVariableReference,
- computedValue,
-}: {
- cssVariableReference: string;
- computedValue: string;
-}): string | number => {
- if (!isNonEmptyString(computedValue)) {
- return cssVariableReference;
- }
-
- const numericValue = Number(computedValue);
-
- return Number.isNaN(numericValue) ? computedValue : numericValue;
-};
+import { resolveThemeTokens } from './resolveThemeTokens';
export const computeThemeFromCss = (sourceElement?: HTMLElement): ThemeType => {
if (
typeof document === 'undefined' ||
typeof getComputedStyle !== 'function'
) {
- return themeCssVariables as unknown as ThemeType;
+ return resolveThemeTokens();
}
const computedStyle = getComputedStyle(
sourceElement ?? document.documentElement,
);
- const resolve = (
- tokens: Record<string, unknown>,
- ): Record<string, unknown> => {
- const result: Record<string, unknown> = {};
-
- for (const [key, value] of Object.entries(tokens)) {
- if (isString(value) && value.startsWith('var(')) {
- const cssVariableName = value.slice(4, -1);
-
- result[key] = resolveTokenValue({
- cssVariableReference: value,
- computedValue: computedStyle.getPropertyValue(cssVariableName).trim(),
- });
- continue;
- }
-
- result[key] = isObject(value)
- ? resolve(value as Record<string, unknown>)
- : value;
- }
-
- return result;
- };
-
- return resolve(
- themeCssVariables as unknown as Record<string, unknown>,
- ) as unknown as ThemeType;
+ return resolveThemeTokens((cssVariableName) =>
+ computedStyle.getPropertyValue(cssVariableName).trim(),
+ );
};
diff --git a/packages/twenty-ui/src/theme/internal/getThemeContext.ts b/packages/twenty-ui/src/theme/internal/getThemeContext.ts
index 0675638168f..766f9dfca10 100644
--- a/packages/twenty-ui/src/theme/internal/getThemeContext.ts
+++ b/packages/twenty-ui/src/theme/internal/getThemeContext.ts
@@ -1,13 +1,12 @@
import React from 'react';
-import { themeCssVariables } from '../themeCssVariables';
-import { type ThemeType } from '../themeTypes';
+import { resolveThemeTokens } from './resolveThemeTokens';
import { type ThemeContextType } from './ThemeContextType';
let themeContext: React.Context<ThemeContextType> | undefined;
export const getThemeContext = () =>
(themeContext ??= React.createContext<ThemeContextType>({
- theme: themeCssVariables as unknown as ThemeType,
+ theme: resolveThemeTokens(),
colorScheme: 'light',
}));
diff --git a/packages/twenty-ui/src/theme/internal/resolveThemeTokens.ts b/packages/twenty-ui/src/theme/internal/resolveThemeTokens.ts
new file mode 100644
index 00000000000..689af5ec5d4
--- /dev/null
+++ b/packages/twenty-ui/src/theme/internal/resolveThemeTokens.ts
@@ -0,0 +1,57 @@
+import { isNonEmptyString, isObject, isString } from '@sniptt/guards';
+
+import { themeCssVariables } from '../themeCssVariables';
+import { type ThemeType } from '../themeTypes';
+import { THEME_NUMERIC_VALUE_BY_CSS_VARIABLE } from './ThemeNumericValueByCssVariable';
+import { type ThemeTokenTree } from './ThemeTokenTree';
+
+const resolveTokenValue = ({
+ cssVariableName,
+ cssVariableReference,
+ computedValue,
+}: {
+ cssVariableName: string;
+ cssVariableReference: string;
+ computedValue: string;
+}): string | number => {
+ if (!isNonEmptyString(computedValue)) {
+ return (
+ THEME_NUMERIC_VALUE_BY_CSS_VARIABLE[cssVariableName] ??
+ cssVariableReference
+ );
+ }
+
+ const numericValue = Number(computedValue);
+
+ return Number.isNaN(numericValue) ? computedValue : numericValue;
+};
+
+export function resolveThemeTokens(
+ readCssVariable?: (cssVariableName: string) => string,
+): ThemeType;
+export function resolveThemeTokens(
+ readCssVariable?: (cssVariableName: string) => string,
+): ThemeTokenTree {
+ const resolve = (tokens: ThemeTokenTree): ThemeTokenTree => {
+ const result: ThemeTokenTree = {};
+
+ for (const [key, value] of Object.entries(tokens)) {
+ if (isString(value) && value.startsWith('var(')) {
+ const cssVariableName = value.slice(4, -1);
+
+ result[key] = resolveTokenValue({
+ cssVariableName,
+ cssVariableReference: value,
+ computedValue: readCssVariable?.(cssVariableName) ?? '',
+ });
+ continue;
+ }
+
+ result[key] = isObject(value) ? resolve(value) : value;
+ }
+
+ return result;
+ };
+
+ return resolve(themeCssVariables);
+}