Files
twenty/packages/twenty-ui/scripts/generateThemeConstants.ts
T
Charles BochetandGitHub eda905f271 [DevXP] Improve Linaria pre-build speed (#18382)
## Summary

This PR improves Linaria/WYW pre-build speed and continues the migration
of `twenty-ui` components away from runtime `ThemeContext` reads toward
static CSS variables and theme constants.

### Linaria/WYW profiling plugin improvements (`twenty-shared`)

- **Babel JIT warmup**: added a `buildStart` warmup step that triggers
WYW's Babel JIT compilation before the real build starts, so the first
real file doesn't pay the cold-start penalty
- **`configResolved` hook**: detects dev vs prod mode and resolves the
correct warmup file path relative to `config.root`
- **Dev-only per-file logging**: slow file warnings are now gated behind
`isDevMode`, keeping production/CI build output clean
- **`closeBundle` summary**: moved the final top-slow-files report to
`closeBundle` for accurate end-of-build reporting
- **Removed noisy progress interval logging** in favor of the warmup log
+ final summary

### Migration from `ThemeContext` to static CSS variables / constants

Across `twenty-ui`, replaced runtime `useTheme()` reads with:
- `themeCssVariables` CSS custom properties (colors, spacing)
- Hard-coded design-system constants (`ICON.size.md` → `16`,
`ICON.stroke.sm` → `1.6`) so components no longer need a React context
at render time — enabling Linaria static extraction

**Components migrated:**
- `Button`, `AnimatedButton`, `LightButton`, `LightIconButton`,
`AnimatedLightIconButton`, `ButtonIcon`, `ButtonSoon`
- `ProgressBar` (Framer Motion width animation → CSS `transition`)
- `Info`, `HorizontalSeparator`, `LinkChip`
- `MenuPicker`, `MenuItemLeftContent`, `MenuItemIconWithGripSwap`,
`NavigationBarItem`
- `JsonArrow`, `JsonNestedNode`
- `ModalHeader`

### Other
- Added `aria-valuenow` to `ProgressBar` for accessibility
- `VisibilityHidden` component updated to inline accessibility styles
2026-03-04 17:04:16 +01:00

136 lines
4.2 KiB
TypeScript

// Generates static TypeScript files with pre-computed theme constants.
// These values are string literals with no runtime imports, so wyw-in-js
// can evaluate them in its restricted sandbox without triggering the
// twenty-ui dist bundle's dependency chain (safe-regex-test / get-intrinsic).
//
// Usage (from workspace root):
// npx tsx packages/twenty-ui/scripts/generateThemeConstants.ts
//
// Prerequisites: twenty-ui must be built first (npx nx build twenty-ui).
import { createRequire } from 'node:module';
import { writeFileSync, mkdirSync } from 'node:fs';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
const scriptDir = dirname(fileURLToPath(import.meta.url));
const require = createRequire(import.meta.url);
const {
MOBILE_VIEWPORT,
THEME_LIGHT,
THEME_DARK,
ICON,
prepareThemeForRootCssVariableInjection,
} = require('../dist/theme.cjs');
const { themeCssVariables: existingThemeCssVariables } =
require('../dist/theme-constants.cjs');
const themeCssVariables =
existingThemeCssVariables ??
(() => {
const { buildThemeReferencingRootCssVariables } =
require('../dist/theme.cjs');
return buildThemeReferencingRootCssVariables({
themeNode: THEME_LIGHT,
prefix: 't',
});
})();
const HEADER = `\
// Auto-generated by scripts/generateThemeConstants.ts — do not edit manually.
// Regenerate: npx tsx packages/twenty-ui/scripts/generateThemeConstants.ts
`;
const serializeObject = (
obj: Record<string, unknown>,
indent = 2,
): string => {
const spaces = ' '.repeat(indent);
const entries = Object.entries(obj).map(([key, value]) => {
const safeKey = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(key)
? key
: JSON.stringify(key);
if (typeof value === 'object' && value !== null) {
return `${spaces}${safeKey}: ${serializeObject(value as Record<string, unknown>, indent + 2)},`;
}
return `${spaces}${safeKey}: ${JSON.stringify(value)},`;
});
return `{\n${entries.join('\n')}\n${' '.repeat(indent - 2)}}`;
};
const serializeTupleArray = (entries: [string, string][]): string => {
const lines = entries.map(
([name, value]) => ` [${JSON.stringify(name)}, ${JSON.stringify(value)}],`,
);
return `[\n${lines.join('\n')}\n]`;
};
const outputDir = resolve(scriptDir, '../src/theme-constants/generated');
mkdirSync(outputDir, { recursive: true });
// --- themeCssVariables.ts ---
writeFileSync(
resolve(outputDir, 'themeCssVariables.ts'),
`${HEADER}
import type { ThemeType } from '@ui/theme/types/ThemeType';
type DeepCSSVariableRefs<T> = {
[K in keyof T]: T[K] extends (...args: never[]) => unknown
? Record<string | number, string>
: T[K] extends Record<string, unknown>
? DeepCSSVariableRefs<T[K]>
: string;
};
export const themeCssVariables = ${serializeObject(themeCssVariables)} as DeepCSSVariableRefs<ThemeType>;
`,
'utf-8',
);
console.log('Generated themeCssVariables.ts');
// --- themeLightCssVariableEntries.ts ---
const lightEntries = prepareThemeForRootCssVariableInjection({
themeNode: THEME_LIGHT,
prefix: 't',
}) as [string, string][];
writeFileSync(
resolve(outputDir, 'themeLightCssVariableEntries.ts'),
`${HEADER}
// CSS custom properties don't work in media queries, so MOBILE_VIEWPORT
// must be a static number rather than a var(--...) reference.
export const MOBILE_VIEWPORT = ${MOBILE_VIEWPORT};
// Numeric icon size/stroke constants for components that require pixel values
// (e.g. icon size props) rather than CSS variable strings.
export const ICON_SIZES = ${serializeObject(ICON.size)} as const;
export const ICON_STROKES = ${serializeObject(ICON.stroke)} as const;
export const THEME_LIGHT_CSS_VARIABLE_ENTRIES: [string, string][] = ${serializeTupleArray(lightEntries)};
`,
'utf-8',
);
console.log('Generated themeLightCssVariableEntries.ts');
// --- themeDarkCssVariableEntries.ts ---
const darkEntries = prepareThemeForRootCssVariableInjection({
themeNode: THEME_DARK,
prefix: 't',
}) as [string, string][];
writeFileSync(
resolve(outputDir, 'themeDarkCssVariableEntries.ts'),
`${HEADER}
export const THEME_DARK_CSS_VARIABLE_ENTRIES: [string, string][] = ${serializeTupleArray(darkEntries)};
`,
'utf-8',
);
console.log('Generated themeDarkCssVariableEntries.ts');