Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

♻️ refactor(styles): make one density spec the source for every density token (#23479)

Innei361266c4898d
diff --git a/.prettierignore b/.prettierignore
index 44f5b5f099e..b58ecf56d6c 100644
--- a/.prettierignore
+++ b/.prettierignore
@@ -84,3 +84,8 @@ packages/heterogeneous-agents/src/codex/protocol/generated.ts
# generated files (regenerate with `bun run shell:vendor` in apps/desktop)
apps/desktop/shell/rescue/electron-updater.cjs
+
+# generated from src/styles/densityScale.ts (regenerate with `pnpm gen:density`)
+src/styles/density.stylex.ts
+src/styles/densityTheme.ts
+src/styles/densityVars.ts
diff --git a/package.json b/package.json
index 9dc13659eaf..711af6d07eb 100644
--- a/package.json
+++ b/package.json
@@ -98,6 +98,8 @@
"fts-search:cleanup-ineligible-messages": "cross-env MIGRATION_DB=1 bun run scripts/elasticsearchCleanupIneligibleMessages/cli.ts",
"fts-search:reindex": "node scripts/elasticsearchReindex/runner.mjs",
"fts-search:sync": "cross-env MIGRATION_DB=1 bun run scripts/elasticsearchSync/cli.ts",
+ "gen:density": "tsx scripts/densityTokens.mts",
+ "gen:density:check": "tsx scripts/densityTokens.mts --check",
"hotfix:branch": "tsx ./scripts/hotfixWorkflow/index.ts",
"i18n": "npm run workflow:i18n && lobe-i18n && prettier -c --write \"locales/**\"",
"i18n:unused": "tsx ./scripts/i18nWorkflow/analyzeUnusedKeys.ts",
diff --git a/scripts/densityTokens.mts b/scripts/densityTokens.mts
new file mode 100644
index 00000000000..c7d980d36c1
--- /dev/null
+++ b/scripts/densityTokens.mts
@@ -0,0 +1,39 @@
+import { readFileSync, writeFileSync } from 'node:fs';
+import path from 'node:path';
+
+import { generateDensityTokenFiles } from './densityTokensCore.ts';
+
+const root = path.resolve(import.meta.dirname, '..');
+const check = process.argv.includes('--check');
+
+const files = generateDensityTokenFiles(root);
+const stale = files.filter((file) => {
+ try {
+ return readFileSync(file.filePath, 'utf8') !== file.content;
+ } catch {
+ return true;
+ }
+});
+
+if (check) {
+ if (stale.length === 0) {
+ console.log('βœ… density tokens are in sync with src/styles/densityScale.ts');
+ process.exit(0);
+ }
+
+ console.error(
+ `❌ density tokens are stale: ${stale.map((file) => file.relativePath).join(', ')}\n` +
+ ` Run \`pnpm gen:density\` and commit the result.`,
+ );
+ process.exit(1);
+}
+
+if (stale.length === 0) {
+ console.log('βœ… density tokens already up to date');
+ process.exit(0);
+}
+
+for (const file of stale) {
+ writeFileSync(file.filePath, file.content);
+ console.log(`✍️ wrote ${file.relativePath}`);
+}
diff --git a/scripts/densityTokens.test.ts b/scripts/densityTokens.test.ts
new file mode 100644
index 00000000000..8bd0a463750
--- /dev/null
+++ b/scripts/densityTokens.test.ts
@@ -0,0 +1,61 @@
+import { existsSync, readFileSync, readdirSync } from 'node:fs';
+import path from 'node:path';
+
+import { describe, expect, it } from 'vitest';
+
+import { DENSITY_VARS, generateDensityTokenFiles, toVarName } from './densityTokensCore';
+
+// Vitest serves modules over http, so import.meta.url is not a file URL here. Both the npm
+// script and CI run vitest from the repo root; the sync test asserts the spec is reachable.
+const root = process.cwd();
+const sourceRoot = path.join(root, 'src');
+const SPEC_FILE = path.join(sourceRoot, 'styles/densityScale.ts');
+
+const SCANNED_EXTENSIONS = ['.css', '.less', '.ts', '.tsx'];
+const VAR_REFERENCE = /var\((--lobe-density-[a-z-]+)/g;
+
+const walk = (dir: string): string[] =>
+ readdirSync(dir, { withFileTypes: true }).flatMap((entry) => {
+ if (entry.name === 'node_modules') return [];
+
+ const full = path.join(dir, entry.name);
+ return entry.isDirectory() ? walk(full) : [full];
+ });
+
+describe('density token codegen', () => {
+ it('keeps the generated StyleX vars and compact theme in sync with densityScale.ts', () => {
+ expect(existsSync(SPEC_FILE), `run vitest from the repo root (cwd: ${root})`).toBe(true);
+
+ for (const file of generateDensityTokenFiles(root)) {
+ expect(readFileSync(file.filePath, 'utf8'), `${file.relativePath} is stale`).toBe(
+ file.content,
+ );
+ }
+ });
+
+ it('declares every --lobe-density-* variable that the app references', () => {
+ const declared = new Set(DENSITY_VARS);
+ const unknown = new Map<string, string[]>();
+
+ for (const file of walk(sourceRoot)) {
+ if (!SCANNED_EXTENSIONS.some((extension) => file.endsWith(extension))) continue;
+
+ const relativePath = path.relative(root, file);
+ for (const [, name] of readFileSync(file, 'utf8').matchAll(VAR_REFERENCE)) {
+ if (declared.has(name)) continue;
+
+ unknown.set(name, [...(unknown.get(name) ?? []), relativePath]);
+ }
+ }
+
+ expect(
+ Object.fromEntries(unknown),
+ 'Add these keys to densityScale.ts (they become --lobe-density-* automatically)',
+ ).toEqual({});
+ });
+
+ it('derives kebab-case variable names from the scale keys', () => {
+ expect(toVarName('controlHeight')).toBe('--lobe-density-control-height');
+ expect(toVarName('pageTitleFontSize')).toBe('--lobe-density-page-title-font-size');
+ });
+});
diff --git a/scripts/densityTokensCore.ts b/scripts/densityTokensCore.ts
new file mode 100644
index 00000000000..cbc65f3c9d1
--- /dev/null
+++ b/scripts/densityTokensCore.ts
@@ -0,0 +1,133 @@
+import { existsSync, readFileSync } from 'node:fs';
+import path from 'node:path';
+
+import { DENSITY_SCALE, type DensityScale } from '../src/styles/densityScale';
+
+type DensityTokenKey = keyof DensityScale;
+
+const GENERATED_HEADER = `// @generated by scripts/densityTokens.mts from src/styles/densityScale.ts
+// Do not edit by hand β€” run \`pnpm gen:density\` after changing the spec.`;
+
+/**
+ * Everything after this marker in density.stylex.ts is hand-written (the semantic
+ * `sidebarRow` layer) and is carried over verbatim on regeneration.
+ */
+const HAND_MAINTAINED_MARKER =
+ '// --- hand-maintained below this line (preserved by the generator) ---';
+
+const STYLEX_RELATIVE_PATH = 'src/styles/density.stylex.ts';
+const THEME_RELATIVE_PATH = 'src/styles/densityTheme.ts';
+const VARS_RELATIVE_PATH = 'src/styles/densityVars.ts';
+
+export const toVarName = (key: string): string =>
+ `--lobe-density-${key.replaceAll(/[A-Z]/g, (char) => `-${char.toLowerCase()}`)}`;
+
+const scaleEntryKeys = (): DensityTokenKey[] =>
+ (Object.keys(DENSITY_SCALE.loose) as DensityTokenKey[]).sort((a, b) =>
+ toVarName(a).localeCompare(toVarName(b)),
+ );
+
+/** Every CSS variable owned by the generated token file, in generated order. */
+export const DENSITY_VARS: string[] = scaleEntryKeys().map(toVarName);
+
+/**
+ * `defineVars` keys are the literal `--lobe-density-*` names (global.css overrides them by
+ * name), so the VarGroup exposes those strings as properties. densityVars.ts carries the
+ * camelCase handles over the same variables; `stylex-enforce` forbids exporting anything but
+ * variables from the defineVars module, hence the separate file.
+ */
+const renderVarAliases = (): string =>
+ Object.keys(DENSITY_SCALE.loose)
+ .sort()
+ .map((key) => ` ${key}: densityTokens['${toVarName(key)}'],`)
+ .join('\n');
+
+const renderVarLines = (density: 'compact' | 'loose'): string =>
+ scaleEntryKeys()
+ .map((key) => ` '${toVarName(key)}': '${DENSITY_SCALE[density][key]}px',`)
+ .join('\n');
+
+const renderStylexDensity = (tail: string): string =>
+ `${GENERATED_HEADER}
+import * as stylex from '@stylexjs/stylex';
+
+export const densityTokens = stylex.defineVars({
+${renderVarLines('loose')}
+});
+
+${HAND_MAINTAINED_MARKER}
+
+${tail}
+`;
+
+const renderDensityVars = (): string =>
+ `${GENERATED_HEADER}
+import { densityTokens } from './density.stylex';
+
+/** camelCase handles over the same variables, for stylesheets and inline styles. */
+export const densityVars = {
+${renderVarAliases()}
+};
+`;
+
+const renderDensityTheme = (): string =>
+ `${GENERATED_HEADER}
+import * as stylex from '@stylexjs/stylex';
+
+import { densityTokens } from './density.stylex';
+
+export const compactDensityTheme = stylex.createTheme(densityTokens, {
+${renderVarLines('compact')}
+});
+`;
+
+const readHandMaintainedTail = (root: string): string => {
+ const file = path.join(root, STYLEX_RELATIVE_PATH);
+ if (!existsSync(file)) {
+ throw new Error(
+ `${STYLEX_RELATIVE_PATH} is missing. Restore it from git before running the generator β€” ` +
+ `its hand-maintained tail cannot be reconstructed.`,
+ );
+ }
+
+ const source = readFileSync(file, 'utf8');
+ const markerIndex = source.indexOf(HAND_MAINTAINED_MARKER);
+ if (markerIndex === -1) {
+ throw new Error(
+ `${STYLEX_RELATIVE_PATH} is missing "${HAND_MAINTAINED_MARKER}". ` +
+ `Add the marker back so the generator can preserve your hand-written tokens.`,
+ );
+ }
+
+ return source.slice(markerIndex + HAND_MAINTAINED_MARKER.length).replace(/^\n+/, '').trimEnd();
+};
+
+export interface GeneratedFile {
+ content: string;
+ /** Absolute path on disk. */
+ filePath: string;
+ /** Repo-relative path, for reporting. */
+ relativePath: string;
+}
+
+export const generateDensityTokenFiles = (root: string): GeneratedFile[] => {
+ const tail = readHandMaintainedTail(root);
+
+ return [
+ {
+ content: renderStylexDensity(tail),
+ filePath: path.join(root, STYLEX_RELATIVE_PATH),
+ relativePath: STYLEX_RELATIVE_PATH,
+ },
+ {
+ content: renderDensityVars(),
+ filePath: path.join(root, VARS_RELATIVE_PATH),
+ relativePath: VARS_RELATIVE_PATH,
+ },
+ {
+ content: renderDensityTheme(),
+ filePath: path.join(root, THEME_RELATIVE_PATH),
+ relativePath: THEME_RELATIVE_PATH,
+ },
+ ];
+};
diff --git a/src/components/ListSkeleton/index.tsx b/src/components/ListSkeleton/index.tsx
index 664d91ac1b1..acb0c245153 100644
--- a/src/components/ListSkeleton/index.tsx
+++ b/src/components/ListSkeleton/index.tsx
@@ -3,7 +3,7 @@
import { Flexbox, Skeleton } from '@lobehub/ui';
import { memo } from 'react';
-import { useInterfaceDensity } from '@/styles/density';
+import { useDensity } from '@/styles/density';
interface ListSkeletonProps {
/**
@@ -22,7 +22,7 @@ interface ListSkeletonProps {
* padding, 36px tile), matching a compact 6px-padded row with a 40px text stack.
*/
const ListSkeleton = memo<ListSkeletonProps>(({ paddingInline = 12, rows = 4 }) => {
- const compact = useInterfaceDensity() === 'compact';
+ const { compact, tokens } = useDensity();
return (
<Flexbox gap={2} width={'100%'}>
@@ -30,11 +30,11 @@ const ListSkeleton = memo<ListSkeletonProps>(({ paddingInline = 12, rows = 4 })
<Flexbox
horizontal
align={'center'}
- gap={compact ? 12 : 16}
+ gap={tokens.sectionGap}
key={index}
style={{ paddingBlock: compact ? 8 : 12, paddingInline }}
>
- <Skeleton.Avatar shape={'square'} size={compact ? 36 : 48} />
+ <Skeleton.Avatar shape={'square'} size={tokens.listRowHeight} />
<Flexbox flex={1} gap={8}>
<Skeleton height={14} width={140} />
<Skeleton height={12} width={200} />
diff --git a/src/components/MemberSelectionModal/MemberSelectionModal.tsx b/src/components/MemberSelectionModal/MemberSelectionModal.tsx
index 166c45e1852..a4f3f6ee329 100644
--- a/src/components/MemberSelectionModal/MemberSelectionModal.tsx
+++ b/src/components/MemberSelectionModal/MemberSelectionModal.tsx
@@ -32,6 +32,7 @@ import { homeAgentListSelectors } from '@/store/home/selectors';
import { useUserStore } from '@/store/user';
import { authSelectors } from '@/store/user/selectors';
import { useInterfaceDensity } from '@/styles/density';
+import { densityVars } from '@/styles/densityVars';
import { sx } from '@/styles/sx';
const AvailableAgentItem = memo<{
@@ -462,7 +463,7 @@ const MemberSelectionModal = memo<MemberSelectionModalProps>(
>
<Flexbox flex={1} gap={2}>
<Text
- style={{ fontSize: 'var(--lobe-density-font-size)', fontWeight: 500 }}
+ style={{ fontSize: densityVars.fontSize, fontWeight: 500 }}
type={isHostRemoved ? 'secondary' : undefined}
>
{t('groupWizard.host.title')}
diff --git a/src/components/Skeleton/AgentViewAll.tsx b/src/components/Skeleton/AgentViewAll.tsx
index efe74778b35..39065662c66 100644
--- a/src/components/Skeleton/AgentViewAll.tsx
+++ b/src/components/Skeleton/AgentViewAll.tsx
@@ -8,7 +8,7 @@ import WideScreenContainer from '@/features/WideScreenContainer';
import type { RouteSkeletonProps } from '@/spa/router/routeMeta';
import { useGlobalStore } from '@/store/global';
import { systemStatusSelectors } from '@/store/global/selectors';
-import { useDensityTokens, useInterfaceDensity } from '@/styles/density';
+import { useDensity, useDensityTokens } from '@/styles/density';
import SkeletonBar from './Bar';
@@ -82,8 +82,8 @@ export const AgentViewAllSidebarSectionSkeleton = () => {
* Also the page's own loading state while the agent list initialises.
*/
export const AgentViewAllRowsSkeleton = ({ rows = 8 }: { rows?: number }) => {
- const compact = useInterfaceDensity() === 'compact';
- const avatarSize = compact ? 24 : 28;
+ const { compact, tokens } = useDensity();
+ const avatarSize = tokens.headerAvatarSize;
return (
<Flexbox aria-busy gap={2}>
diff --git a/src/components/Skeleton/Settings/Sections.tsx b/src/components/Skeleton/Settings/Sections.tsx
index 344a164044e..7e6f75069d4 100644
--- a/src/components/Skeleton/Settings/Sections.tsx
+++ b/src/components/Skeleton/Settings/Sections.tsx
@@ -14,7 +14,7 @@ import { useTranslation } from 'react-i18next';
import NavHeader from '@/features/NavHeader';
import SettingContainer from '@/features/Setting/SettingContainer';
import type { RouteSkeletonProps } from '@/spa/router/routeMeta';
-import { useInterfaceDensity } from '@/styles/density';
+import { useDensity } from '@/styles/density';
import { sx } from '@/styles/sx';
import SkeletonBar from '../Bar';
@@ -791,12 +791,12 @@ const PageTabs = ({ count }: { count: number }) => (
* compact 20px / 31px) 24px (compact 16px) above the divider.
*/
const PageTitle = () => {
- const compact = useInterfaceDensity() === 'compact';
+ const { compact, tokens } = useDensity();
return (
<Flexbox gap={compact ? 16 : 24} style={{ paddingTop: 12 }}>
<Flexbox height={compact ? 31 : 38} justify={'center'}>
- <SkeletonBar height={compact ? 24 : 28} width={96} />
+ <SkeletonBar height={tokens.iconBox} width={96} />
</Flexbox>
<div {...stylex.props(styles.divider)} />
</Flexbox>
@@ -808,7 +808,7 @@ const PageTitle = () => {
* directly where a layout already draws the header and padded container.
*/
export const SettingsSectionsBody = ({ shape }: { shape: SettingsSectionsShape }) => {
- const compact = useInterfaceDensity() === 'compact';
+ const { compact } = useDensity();
const sections = (
<Flexbox
aria-busy
diff --git a/src/components/Skeleton/Settings/tabs/Creds.tsx b/src/components/Skeleton/Settings/tabs/Creds.tsx
index 0fa529f476a..c366fb0891e 100644
--- a/src/components/Skeleton/Settings/tabs/Creds.tsx
+++ b/src/components/Skeleton/Settings/tabs/Creds.tsx
@@ -2,7 +2,7 @@
import { cssVar, Flexbox } from '@lobehub/ui';
-import { useDensityTokens, useInterfaceDensity } from '@/styles/density';
+import { useDensity, useDensityTokens } from '@/styles/density';
import SkeletonBar from '../../Bar';
import type { SettingsTabSkeleton } from './types';
@@ -21,7 +21,7 @@ const ROW_WIDTHS = [
*/
export const CredsListSkeleton = ({ rows = 4 }: { rows?: number }) => {
// Compact `CredItem`: 6px padding, 36px tile, 22px title line + 2 + 18px key line = 54px.
- const compact = useInterfaceDensity() === 'compact';
+ const { compact, tokens } = useDensity();
const { controlHeight } = useDensityTokens();
return (
@@ -32,16 +32,16 @@ export const CredsListSkeleton = ({ rows = 4 }: { rows?: number }) => {
<Flexbox
horizontal
align={'center'}
- gap={compact ? 12 : 16}
+ gap={tokens.sectionGap}
justify={'space-between'}
key={index}
style={{ paddingBlock: compact ? 6 : 12 }}
>
- <Flexbox horizontal align={'center'} flex={1} gap={compact ? 12 : 16}>
+ <Flexbox horizontal align={'center'} flex={1} gap={tokens.sectionGap}>
<SkeletonBar
- height={compact ? 36 : 48}
+ height={tokens.listRowHeight}
radius={compact ? 10 : 12}
- width={compact ? 36 : 48}
+ width={tokens.listRowHeight}
/>
<Flexbox gap={compact ? 2 : 4}>
<Flexbox horizontal align={'center'} gap={8} height={22}>
diff --git a/src/features/AgentViewAll/AgentRow.tsx b/src/features/AgentViewAll/AgentRow.tsx
index 19b2d633f11..840e0683d56 100644
--- a/src/features/AgentViewAll/AgentRow.tsx
+++ b/src/features/AgentViewAll/AgentRow.tsx
@@ -21,7 +21,7 @@ import { memo, type MouseEvent, useCallback, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import WorkspaceLink from '@/features/Workspace/WorkspaceLink';
-import { useInterfaceDensity } from '@/styles/density';
+import { useDensity } from '@/styles/density';
import ItemActions from './ItemActions';
import LabelTags from './LabelTags';
@@ -161,7 +161,7 @@ const AgentRow = memo<AgentRowProps>(
const displayTitle = agentDisplayName(item, t('agentViewAll.untitled'));
const role = agentSecondaryDisplayName(item);
const [anchor, setAnchor] = useState<HTMLElement | null>(null);
- const compact = useInterfaceDensity() === 'compact';
+ const { compact, tokens } = useDensity();
// Right-click support (Task-List-style): the hook-bearing menu mounts on
// the ROW's pointer-enter (which always precedes a right-click) and hands
@@ -197,7 +197,7 @@ const AgentRow = memo<AgentRowProps>(
className={styles.identity}
to={type === 'group' ? GROUP_CHAT_URL(id) : AGENT_CHAT_URL(id, false)}
>
- <SidebarItemAvatar item={item} size={compact ? 24 : 28} />
+ <SidebarItemAvatar item={item} size={tokens.headerAvatarSize} />
{/* Three single-line columns: who the agent is, the role it plays,
and what it is responsible for. */}
<Text ellipsis className={cx('agent-row-title', styles.name)} weight={500}>
diff --git a/src/features/CommandMenu/styles.ts b/src/features/CommandMenu/styles.ts
index a35537a22c5..44e4c1bd90c 100644
--- a/src/features/CommandMenu/styles.ts
+++ b/src/features/CommandMenu/styles.ts
@@ -1,5 +1,7 @@
import { createStaticStyles, keyframes } from '@lobehub/ui';
+import { densityVars } from '@/styles/densityVars';
+
const slideDown = keyframes`
from {
transform: translateY(-20px) scale(0.96);
@@ -95,7 +97,7 @@ export const styles = createStaticStyles(({ css, cssVar }) => ({
align-items: center;
justify-content: center;
- padding-block: calc(var(--lobe-density-section-gap) - 4px);
+ padding-block: calc(${densityVars.sectionGap} - 4px);
padding-inline: 16px;
border-block-start: 1px solid ${cssVar.colorBorderSecondary};
`,
@@ -125,7 +127,7 @@ export const styles = createStaticStyles(({ css, cssVar }) => ({
border: none;
font-family: inherit;
- font-size: var(--lobe-density-page-title-font-size);
+ font-size: ${densityVars.pageTitleFontSize};
color: ${cssVar.colorText};
background: transparent;
@@ -146,7 +148,7 @@ export const styles = createStaticStyles(({ css, cssVar }) => ({
padding-block: 32px;
padding-inline: 16px;
- font-size: var(--lobe-density-font-size);
+ font-size: ${densityVars.fontSize};
color: ${cssVar.colorTextTertiary};
text-align: center;
}
@@ -159,10 +161,10 @@ export const styles = createStaticStyles(({ css, cssVar }) => ({
gap: 10px;
align-items: center;
- min-height: var(--lobe-density-row-height);
- padding-block: calc((var(--lobe-density-row-height) - 20px) / 2);
- padding-inline: var(--lobe-density-section-gap);
- border-radius: var(--lobe-density-radius);
+ min-height: ${densityVars.rowHeight};
+ padding-block: calc((${densityVars.rowHeight} - 20px) / 2);
+ padding-inline: ${densityVars.sectionGap};
+ border-radius: ${densityVars.radius};
color: ${cssVar.colorText};
@@ -181,7 +183,7 @@ export const styles = createStaticStyles(({ css, cssVar }) => ({
user-select: none;
padding-block: 6px;
- padding-inline: var(--lobe-density-section-gap);
+ padding-inline: ${densityVars.sectionGap};
font-size: 12px;
font-weight: 500;
@@ -203,12 +205,12 @@ export const styles = createStaticStyles(({ css, cssVar }) => ({
align-items: center;
padding-block: 6px;
- padding-inline: var(--lobe-density-section-gap);
+ padding-inline: ${densityVars.sectionGap};
`,
icon: css`
flex-shrink: 0;
- width: var(--lobe-density-icon-size);
- height: var(--lobe-density-icon-size);
+ width: ${densityVars.iconSize};
+ height: ${densityVars.iconSize};
color: ${cssVar.colorTextSecondary};
`,
inputWrapper: css`
@@ -216,8 +218,8 @@ export const styles = createStaticStyles(({ css, cssVar }) => ({
gap: 8px;
align-items: center;
- padding-block: calc(var(--lobe-density-section-gap) - 4px);
- padding-inline: var(--lobe-density-section-gap);
+ padding-block: calc(${densityVars.sectionGap} - 4px);
+ padding-inline: ${densityVars.sectionGap};
border-block-start: 1px solid ${cssVar.colorBorderSecondary};
`,
itemContent: css`
@@ -249,20 +251,20 @@ export const styles = createStaticStyles(({ css, cssVar }) => ({
align-items: center;
justify-content: center;
- width: var(--lobe-density-icon-size);
- height: var(--lobe-density-icon-size);
+ width: ${densityVars.iconSize};
+ height: ${densityVars.iconSize};
color: ${cssVar.colorTextSecondary};
`,
itemLabel: css`
- font-size: var(--lobe-density-font-size);
+ font-size: ${densityVars.fontSize};
font-weight: 500;
line-height: 1.4;
`,
itemTitle: css`
overflow: hidden;
- font-size: var(--lobe-density-font-size);
+ font-size: ${densityVars.fontSize};
font-weight: 500;
line-height: 1.4;
text-overflow: ellipsis;
diff --git a/src/features/EnvironmentManager/EnvironmentItem.tsx b/src/features/EnvironmentManager/EnvironmentItem.tsx
index 7ba2b4a7247..4428f3e29fe 100644
--- a/src/features/EnvironmentManager/EnvironmentItem.tsx
+++ b/src/features/EnvironmentManager/EnvironmentItem.tsx
@@ -22,7 +22,7 @@ import { useTranslation } from 'react-i18next';
import UserAvatar from '@/components/UserAvatar';
import VisibilityConfirmContent from '@/features/VisibilityConfirmContent';
-import { useInterfaceDensity } from '@/styles/density';
+import { useDensity } from '@/styles/density';
import { describeError } from './errorMessage';
import { repositoryPath } from './repository';
@@ -149,7 +149,7 @@ const EnvironmentItem = memo<EnvironmentItemProps>((props) => {
const { t: tCommon } = useTranslation('common');
const actions = useEnvironmentActions();
const canEdit = useCanEditEnvironment()(environment);
- const compact = useInterfaceDensity() === 'compact';
+ const { compact, tokens } = useDensity();
// A row restored from storage carries only its plain `owner/name`.
const repository = environment.configuration
@@ -238,7 +238,7 @@ const EnvironmentItem = memo<EnvironmentItemProps>((props) => {
horizontal
align={'center'}
className={cx(styles.row, compact && styles.rowCompact, selected && styles.rowActive)}
- gap={compact ? 12 : 16}
+ gap={tokens.sectionGap}
role={'button'}
tabIndex={0}
onClick={onSelect}
diff --git a/src/features/ExecutionTargetPicker/index.tsx b/src/features/ExecutionTargetPicker/index.tsx
index 8a201a9b43f..07ec2099e1c 100644
--- a/src/features/ExecutionTargetPicker/index.tsx
+++ b/src/features/ExecutionTargetPicker/index.tsx
@@ -6,6 +6,7 @@ import { BoxIcon, LaptopIcon, MonitorOffIcon, SparklesIcon } from 'lucide-react'
import { memo } from 'react';
import { getDeviceIcon } from '@/features/DeviceManager/getDeviceIcon';
+import { densityVars } from '@/styles/densityVars';
const styles = createStaticStyles(({ css }) => ({
dotOffline: css`
@@ -51,10 +52,10 @@ const styles = createStaticStyles(({ css }) => ({
align-items: center;
justify-content: center;
- width: var(--lobe-density-icon-box);
- height: var(--lobe-density-icon-box);
+ width: ${densityVars.iconBox};
+ height: ${densityVars.iconBox};
border: 1px solid ${cssVar.colorBorderSecondary};
- border-radius: var(--lobe-density-radius);
+ border-radius: ${densityVars.radius};
color: ${cssVar.colorText};
@@ -63,7 +64,7 @@ const styles = createStaticStyles(({ css }) => ({
optionName: css`
overflow: hidden;
- font-size: var(--lobe-density-font-size);
+ font-size: ${densityVars.fontSize};
font-weight: 500;
line-height: 20px;
color: ${cssVar.colorText};
@@ -71,7 +72,7 @@ const styles = createStaticStyles(({ css }) => ({
white-space: nowrap;
`,
selectItem: css`
- min-height: var(--lobe-density-list-row-height);
+ min-height: ${densityVars.listRowHeight};
`,
selectPopup: css`
max-width: calc(100vw - 24px);
diff --git a/src/features/Home/AgentSelect/AgentList.tsx b/src/features/Home/AgentSelect/AgentList.tsx
index e6aeb3bbd18..ce5bec36347 100644
--- a/src/features/Home/AgentSelect/AgentList.tsx
+++ b/src/features/Home/AgentSelect/AgentList.tsx
@@ -22,6 +22,7 @@ import SkeletonList from '@/features/NavPanel/components/SkeletonList';
import { useHomeStore } from '@/store/home';
import { homeAgentListSelectors } from '@/store/home/selectors';
import { useDensityTokens, useInterfaceDensity } from '@/styles/density';
+import { densityVars } from '@/styles/densityVars';
import { type AgentRow, useHomeAgentRows } from './useHomeAgentRows';
@@ -35,7 +36,7 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
padding-block: 24px;
padding-inline: 12px;
- font-size: var(--lobe-density-font-size);
+ font-size: ${densityVars.fontSize};
color: ${cssVar.colorTextTertiary};
text-align: center;
`,
@@ -49,10 +50,10 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
gap: 8px;
align-items: center;
- height: var(--lobe-density-row-height);
+ height: ${densityVars.rowHeight};
padding-block: 0;
padding-inline: 8px;
- border-radius: var(--lobe-density-radius);
+ border-radius: ${densityVars.radius};
&:hover {
background: ${cssVar.colorFillSecondary};
@@ -65,7 +66,7 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
`,
// Same spec as the agent-detail SwitchPanel's section header.
section: css`
- height: var(--lobe-density-control-height);
+ height: ${densityVars.controlHeight};
padding-block: 4px 2px;
padding-inline: 8px;
diff --git a/src/features/Home/AgentSelect/index.tsx b/src/features/Home/AgentSelect/index.tsx
index 43271f95f45..e06e32a36b4 100644
--- a/src/features/Home/AgentSelect/index.tsx
+++ b/src/features/Home/AgentSelect/index.tsx
@@ -23,6 +23,7 @@ import { useAgentStore } from '@/store/agent';
import { agentSelectors, builtinAgentSelectors } from '@/store/agent/selectors';
import { useHomeStore } from '@/store/home';
import { homeAgentListSelectors } from '@/store/home/selectors';
+import { densityVars } from '@/styles/densityVars';
import AgentList from './AgentList';
import { useResolvedHomeAgentId, useSelectHomeAgent } from './useResolvedHomeAgentId';
@@ -34,8 +35,8 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
transition: opacity 0.2s ${cssVar.motionEaseOut};
`,
name: css`
- font-size: var(--lobe-density-font-size);
- line-height: var(--lobe-density-line-height);
+ font-size: ${densityVars.fontSize};
+ line-height: ${densityVars.lineHeight};
`,
popup: css`
overflow: hidden;
diff --git a/src/features/HomeTeamBoard/AttentionList.tsx b/src/features/HomeTeamBoard/AttentionList.tsx
index 94c6d473a2c..ed70bc46cb1 100644
--- a/src/features/HomeTeamBoard/AttentionList.tsx
+++ b/src/features/HomeTeamBoard/AttentionList.tsx
@@ -10,7 +10,7 @@ import AgentAvatar from '@/components/AgentAvatar';
import AuthorChip from '@/features/HomeInbox/AuthorChip';
import { useGlobalStore } from '@/store/global';
import { systemStatusSelectors } from '@/store/global/selectors';
-import { useInterfaceDensity } from '@/styles/density';
+import { useDensity } from '@/styles/density';
import { sx } from '@/styles/sx';
import { formatDuration } from './layout';
@@ -96,7 +96,7 @@ const styles = stylex.create({
const Item = ({ item, now }: { item: AgentRunBoardAttentionItem; now: Date }) => {
const { t } = useTranslation('home');
const openDrawer = useOpenRunDrawer();
- const compact = useInterfaceDensity() === 'compact';
+ const { compact } = useDensity();
const failed = item.kind === 'failed';
const canAct = item.isMine && !failed;
const elapsed = formatDuration(now.getTime() - item.since.getTime());
@@ -177,7 +177,7 @@ const Section = ({
const AttentionList = ({ items, now }: { items: AgentRunBoardAttentionItem[]; now: Date }) => {
const { t } = useTranslation('home');
- const compact = useInterfaceDensity() === 'compact';
+ const { compact, tokens } = useDensity();
const collapsed = useGlobalStore(systemStatusSelectors.teamBoardAttentionCollapsed);
const updateSystemStatus = useGlobalStore((s) => s.updateSystemStatus);
const setCollapsed = (next: boolean) =>
@@ -194,7 +194,7 @@ const AttentionList = ({ items, now }: { items: AgentRunBoardAttentionItem[]; no
const card = (
<Flexbox
- gap={compact ? 12 : 16}
+ gap={tokens.sectionGap}
{...stylex.props(styles.card, compact && styles.cardCompact)}
data-testid={'team-board-attention'}
>
diff --git a/src/features/LibraryModal/AssignKnowledgeBase/Item/index.tsx b/src/features/LibraryModal/AssignKnowledgeBase/Item/index.tsx
index 22e9c6641ac..efb1cba66e2 100644
--- a/src/features/LibraryModal/AssignKnowledgeBase/Item/index.tsx
+++ b/src/features/LibraryModal/AssignKnowledgeBase/Item/index.tsx
@@ -8,6 +8,7 @@ import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspa
import KnowledgeIcon from '@/components/KnowledgeIcon';
import { buildFilePath, buildLibraryPath } from '@/features/ResourceManager/utils/resourcePath';
import { useInterfaceDensity } from '@/styles/density';
+import { densityVars } from '@/styles/densityVars';
import { type KnowledgeItem, KnowledgeType } from '@/types/knowledgeBase';
import Actions from './Action';
@@ -30,7 +31,7 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
`,
title: css`
margin: 0 !important;
- font-size: var(--lobe-density-font-size);
+ font-size: ${densityVars.fontSize};
line-height: 1;
`,
}));
diff --git a/src/features/MemoryRules/styles.ts b/src/features/MemoryRules/styles.ts
index d340209b36b..2e612735968 100644
--- a/src/features/MemoryRules/styles.ts
+++ b/src/features/MemoryRules/styles.ts
@@ -1,5 +1,7 @@
import { createStaticStyles, cssVar } from '@lobehub/ui';
+import { densityVars } from '@/styles/densityVars';
+
/**
* One sheet, Linear-style: a sticky header row, one hairline per row, group rows that run the
* full width, and hover-only controls. The grid is shared by the header row and every rule row
@@ -161,7 +163,7 @@ export const styles = createStaticStyles(({ css }) => ({
`,
// Compact group rows sit on the shared section-header height.
sectionCompact: css`
- height: var(--lobe-density-control-height);
+ height: ${densityVars.controlHeight};
margin-block-start: 6px;
`,
sectionCount: css`
diff --git a/src/features/ModelSwitchPanel/components/ModelDetailPanel.tsx b/src/features/ModelSwitchPanel/components/ModelDetailPanel.tsx
index a2d12ed0e8a..c3af85652d1 100644
--- a/src/features/ModelSwitchPanel/components/ModelDetailPanel.tsx
+++ b/src/features/ModelSwitchPanel/components/ModelDetailPanel.tsx
@@ -17,6 +17,7 @@ import type { FC } from 'react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
+import { densityVars } from '@/styles/densityVars';
import type { EnabledProviderWithModels } from '@/types/aiProvider';
import { getModelDescriptionI18nKey } from '@/utils/modelDescriptionI18n';
@@ -35,7 +36,7 @@ export type { PricingMode } from '../types';
const styles = createStaticStyles(({ css, cssVar }) => ({
actionText: css`
- font-size: var(--lobe-density-font-size);
+ font-size: ${densityVars.fontSize};
font-weight: 500;
color: ${cssVar.colorText};
`,
@@ -53,7 +54,7 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
`,
radarClickable: css`
cursor: pointer;
- border-radius: var(--lobe-density-radius);
+ border-radius: ${densityVars.radius};
transition: background 0.2s ${cssVar.motionEaseInOut};
&:hover {
@@ -89,7 +90,7 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
font-variant-numeric: tabular-nums;
`,
titleText: css`
- font-size: var(--lobe-density-font-size);
+ font-size: ${densityVars.fontSize};
font-weight: 400;
color: ${cssVar.colorTextSecondary};
`,
diff --git a/src/features/ModelSwitchPanel/styles.ts b/src/features/ModelSwitchPanel/styles.ts
index 25b63738983..aa81c3c621b 100644
--- a/src/features/ModelSwitchPanel/styles.ts
+++ b/src/features/ModelSwitchPanel/styles.ts
@@ -1,5 +1,7 @@
import { createStaticStyles } from '@lobehub/ui';
+import { densityVars } from '@/styles/densityVars';
+
export const styles = createStaticStyles(({ css, cssVar }) => ({
container: css`
pointer-events: auto;
@@ -24,11 +26,11 @@ export const styles = createStaticStyles(({ css, cssVar }) => ({
}
html[data-density='compact'] & [role='menuitem'] {
- min-height: var(--lobe-density-control-height);
- padding-block: calc((var(--lobe-density-control-height) - 20px) / 2);
- border-radius: var(--lobe-density-radius);
+ min-height: ${densityVars.controlHeight};
+ padding-block: calc((${densityVars.controlHeight} - 20px) / 2);
+ border-radius: ${densityVars.radius};
- font-size: var(--lobe-density-font-size);
+ font-size: ${densityVars.fontSize};
line-height: 20px;
}
`,
@@ -57,11 +59,11 @@ export const styles = createStaticStyles(({ css, cssVar }) => ({
border-radius: ${cssVar.borderRadiusSM};
html[data-density='compact'] & {
- min-height: var(--lobe-density-control-height);
- padding-block: calc((var(--lobe-density-control-height) - 20px) / 2);
- border-radius: var(--lobe-density-radius);
+ min-height: ${densityVars.controlHeight};
+ padding-block: calc((${densityVars.controlHeight} - 20px) / 2);
+ border-radius: ${densityVars.radius};
- font-size: var(--lobe-density-font-size);
+ font-size: ${densityVars.fontSize};
line-height: 20px;
}
`,
@@ -70,11 +72,11 @@ export const styles = createStaticStyles(({ css, cssVar }) => ({
padding-inline: 8px;
html[data-density='compact'] & {
- min-height: var(--lobe-density-control-height);
- padding-block: calc((var(--lobe-density-control-height) - 20px) / 2);
- border-radius: var(--lobe-density-radius);
+ min-height: ${densityVars.controlHeight};
+ padding-block: calc((${densityVars.controlHeight} - 20px) / 2);
+ border-radius: ${densityVars.radius};
- font-size: var(--lobe-density-font-size);
+ font-size: ${densityVars.fontSize};
line-height: 20px;
}
`,
diff --git a/src/features/NavPanel/components/NavPanelDraggable.tsx b/src/features/NavPanel/components/NavPanelDraggable.tsx
index b6814f1078a..a50fe2ad2d4 100644
--- a/src/features/NavPanel/components/NavPanelDraggable.tsx
+++ b/src/features/NavPanel/components/NavPanelDraggable.tsx
@@ -17,6 +17,7 @@ import {
systemStatusSelectors,
} from '@/store/global/selectors';
import { useInterfaceDensity } from '@/styles/density';
+import { densityVars } from '@/styles/densityVars';
import { isMacOS } from '@/utils/platform';
import { NavPanelDensityContext } from '../density';
@@ -84,12 +85,12 @@ const draggableStyles = createStaticStyles(({ css, cssVar }) => ({
width 0.2s ${cssVar.motionEaseOut};
}
#${BACK_BUTTON_ID} {
- width: var(--lobe-density-icon-box) !important;
+ width: ${densityVars.iconBox} !important;
}
&:hover {
#${TOGGLE_BUTTON_ID} {
- width: var(--lobe-density-icon-box) !important;
+ width: ${densityVars.iconBox} !important;
opacity: 1;
}
diff --git a/src/features/NavPanel/switcher/SwitcherRow.tsx b/src/features/NavPanel/switcher/SwitcherRow.tsx
index 3b1c1183b5d..c9be498c23c 100644
--- a/src/features/NavPanel/switcher/SwitcherRow.tsx
+++ b/src/features/NavPanel/switcher/SwitcherRow.tsx
@@ -3,6 +3,7 @@ import { CheckIcon } from 'lucide-react';
import { memo } from 'react';
import AgentAvatar from '@/components/AgentAvatar';
+import { densityVars } from '@/styles/densityVars';
import { useNavItemMetrics } from '../density';
import type { SwitcherItem } from './switcherItems';
@@ -18,7 +19,7 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
flex: none;
padding-inline: 8px;
- border-radius: var(--lobe-density-radius);
+ border-radius: ${densityVars.radius};
&:hover {
background: ${cssVar.colorFillTertiary};
diff --git a/src/features/Projects/KnowledgeBases/index.tsx b/src/features/Projects/KnowledgeBases/index.tsx
index f42199e1f24..62589494a26 100644
--- a/src/features/Projects/KnowledgeBases/index.tsx
+++ b/src/features/Projects/KnowledgeBases/index.tsx
@@ -16,7 +16,7 @@ import KnowledgeIcon from '@/components/KnowledgeIcon';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import type { ProjectDetail } from '@/store/project';
import { useProjectStore } from '@/store/project';
-import { useDensityTokens, useInterfaceDensity } from '@/styles/density';
+import { useDensity, useDensityTokens } from '@/styles/density';
import { KnowledgeType } from '@/types/knowledgeBase';
import { openAddKnowledgeBaseModal } from './AddKnowledgeBaseModal';
@@ -26,7 +26,7 @@ type ProjectKnowledgeBase = NonNullable<ProjectDetail['knowledgeBases']>[number]
export function ProjectKnowledgeBaseSettings({ detail }: { detail: ProjectDetail }) {
const { t } = useTranslation('project');
const { pageTitleFontSize } = useDensityTokens();
- const compact = useInterfaceDensity() === 'compact';
+ const { compact, tokens } = useDensity();
const navigate = useWorkspaceAwareNavigate();
const updateProjectKnowledgeBase = useProjectStore((s) => s.updateProjectKnowledgeBase);
const removeProjectKnowledgeBase = useProjectStore((s) => s.removeProjectKnowledgeBase);
@@ -98,7 +98,7 @@ export function ProjectKnowledgeBaseSettings({ detail }: { detail: ProjectDetail
>
<KnowledgeIcon
name={item.knowledgeBase.name}
- size={compact ? 24 : 28}
+ size={tokens.headerAvatarSize}
type={KnowledgeType.KnowledgeBase}
/>
<Flexbox
diff --git a/src/features/ResourceManager/components/Explorer/ListView/ListViewHeader.tsx b/src/features/ResourceManager/components/Explorer/ListView/ListViewHeader.tsx
index 88cabecf8ec..f336f413af4 100644
--- a/src/features/ResourceManager/components/Explorer/ListView/ListViewHeader.tsx
+++ b/src/features/ResourceManager/components/Explorer/ListView/ListViewHeader.tsx
@@ -5,6 +5,7 @@ import { useTranslation } from 'react-i18next';
import { useResourceManagerStore } from '@/features/ResourceManager/store';
import { useGlobalStore } from '@/store/global';
+import { densityVars } from '@/styles/densityVars';
import type { FileListItem } from '@/types/files';
import { SortType } from '@/types/files';
@@ -128,7 +129,7 @@ const ListViewHeader = ({
minWidth: getListViewMinWidth(showUploader),
}}
>
- <Center height={'var(--lobe-density-toolbar-height)'} style={{ paddingInline: 4 }}>
+ <Center height={densityVars.toolbarHeight} style={{ paddingInline: 4 }}>
<Checkbox
checked={allSelected}
disabled={!hasSelectableItems}
diff --git a/src/features/ResourceManager/components/Explorer/ListView/styles.ts b/src/features/ResourceManager/components/Explorer/ListView/styles.ts
index 1d4b11d962c..2c14ff4af21 100644
--- a/src/features/ResourceManager/components/Explorer/ListView/styles.ts
+++ b/src/features/ResourceManager/components/Explorer/ListView/styles.ts
@@ -1,5 +1,7 @@
import { createStaticStyles, cssVar } from '@lobehub/ui';
+import { densityVars } from '@/styles/densityVars';
+
export const styles = createStaticStyles(({ css }) => ({
dropZone: css`
position: relative;
@@ -12,8 +14,8 @@ export const styles = createStaticStyles(({ css }) => ({
`,
header: css`
min-width: 1040px;
- height: var(--lobe-density-toolbar-height);
- min-height: var(--lobe-density-toolbar-height);
+ height: ${densityVars.toolbarHeight};
+ min-height: ${densityVars.toolbarHeight};
color: ${cssVar.colorTextDescription};
`,
headerItem: css`
@@ -42,7 +44,7 @@ export const styles = createStaticStyles(({ css }) => ({
selectAllHint: css`
position: sticky;
z-index: 1;
- inset-block-start: var(--lobe-density-toolbar-height);
+ inset-block-start: ${densityVars.toolbarHeight};
min-width: 1040px;
padding-block: 8px;
diff --git a/src/features/ResourceManager/components/LibraryHierarchy/TreeSkeleton.tsx b/src/features/ResourceManager/components/LibraryHierarchy/TreeSkeleton.tsx
index 51aab423b60..04919c9bcdf 100644
--- a/src/features/ResourceManager/components/LibraryHierarchy/TreeSkeleton.tsx
+++ b/src/features/ResourceManager/components/LibraryHierarchy/TreeSkeleton.tsx
@@ -3,16 +3,18 @@
import { createStaticStyles, Flexbox, Skeleton } from '@lobehub/ui';
import { memo } from 'react';
+import { densityVars } from '@/styles/densityVars';
+
const styles = createStaticStyles(({ css, cssVar }) => ({
container: css`
display: flex;
gap: 6px;
align-items: center;
- height: var(--lobe-density-row-height);
+ height: ${densityVars.rowHeight};
padding-block: 4px;
padding-inline: 8px;
- border-radius: var(--lobe-density-radius);
+ border-radius: ${densityVars.radius};
`,
}));
diff --git a/src/features/Settings/creds/features/CredItem.tsx b/src/features/Settings/creds/features/CredItem.tsx
index 2ca1f7e6aa3..94a63de3b13 100644
--- a/src/features/Settings/creds/features/CredItem.tsx
+++ b/src/features/Settings/creds/features/CredItem.tsx
@@ -26,7 +26,7 @@ import {
import { type FC, memo } from 'react';
import { useTranslation } from 'react-i18next';
-import { useInterfaceDensity } from '@/styles/density';
+import { useDensity } from '@/styles/density';
import { styles } from './style';
@@ -64,7 +64,7 @@ const typeColors: Record<string, string> = {
const CredItem: FC<CredItemProps> = memo(
({ canManage, cred, extraMenuItems = [], onEdit, onDelete, onView, tags }) => {
const { t } = useTranslation('setting');
- const compact = useInterfaceDensity() === 'compact';
+ const { compact, tokens } = useDensity();
const handleDelete = () => {
if (!canManage) return;
@@ -119,7 +119,7 @@ const CredItem: FC<CredItemProps> = memo(
const renderAvatar = () => {
if (cred.type === 'oauth' && cred.oauthAvatar) {
- return <Avatar avatar={cred.oauthAvatar} size={compact ? 28 : 32} />;
+ return <Avatar avatar={cred.oauthAvatar} size={tokens.controlHeight} />;
}
return (
// `display: flex` collapses the inline span's line box so the svg sits
@@ -135,13 +135,13 @@ const CredItem: FC<CredItemProps> = memo(
horizontal
align="center"
className={stylex.props(styles.container, compact && styles.containerCompact).className}
- gap={compact ? 12 : 16}
+ gap={tokens.sectionGap}
justify="space-between"
>
<Flexbox
horizontal
align="center"
- gap={compact ? 12 : 16}
+ gap={tokens.sectionGap}
style={{ flex: 1, overflow: 'hidden' }}
>
<div {...stylex.props(styles.icon, compact && styles.iconCompact)}>{renderAvatar()}</div>
diff --git a/src/features/Settings/skill/features/LeftPanel.tsx b/src/features/Settings/skill/features/LeftPanel.tsx
index 769e00e2fb3..64ea9f70fe6 100644
--- a/src/features/Settings/skill/features/LeftPanel.tsx
+++ b/src/features/Settings/skill/features/LeftPanel.tsx
@@ -15,6 +15,7 @@ import { useConnectorManageable } from '@/hooks/useConnectorManagePolicy';
import { usePermission } from '@/hooks/usePermission';
import { useInterfaceDensity } from '@/styles/density';
import { sidebarRow } from '@/styles/density.stylex';
+import { densityVars } from '@/styles/densityVars';
import ConnectorManagePolicy from './ConnectorManagePolicy';
import { type ToolDetailType } from './SkillDetail';
@@ -219,7 +220,7 @@ const LeftPanel = memo<LeftPanelProps>(
style={fullWidth ? { borderInlineEnd: 'none', width: '100%' } : undefined}
>
<div {...stylex.props(styles.header)}>
- <Text strong style={{ fontSize: 'var(--lobe-density-font-size)' }}>
+ <Text strong style={{ fontSize: densityVars.fontSize }}>
{isConnectorView
? t('skillView.connectors', 'Connectors')
: t('skillView.skills', 'Skills')}
diff --git a/src/features/Settings/trash/features/ProjectFilter.tsx b/src/features/Settings/trash/features/ProjectFilter.tsx
index 847310b4960..5099ef87ee8 100644
--- a/src/features/Settings/trash/features/ProjectFilter.tsx
+++ b/src/features/Settings/trash/features/ProjectFilter.tsx
@@ -9,6 +9,7 @@ import { useTranslation } from 'react-i18next';
import AsyncError from '@/components/AsyncError';
import type { ProjectListItem } from '@/store/project';
+import { densityVars } from '@/styles/densityVars';
import {
fromProjectFilterValue,
@@ -107,7 +108,7 @@ export const ProjectFilter = ({
popupMatchSelectWidth={280}
prefix={FolderKanbanIcon}
size={'small'}
- style={{ maxWidth: 260, minHeight: 'var(--lobe-density-control-height)', minWidth: 160 }}
+ style={{ maxWidth: 260, minHeight: densityVars.controlHeight, minWidth: 160 }}
// Not `virtual`: the virtual list counts the whole project group as one
// row and crashes once search shrinks the options; search is the way
// through a long list.
diff --git a/src/features/SharePopover/style.ts b/src/features/SharePopover/style.ts
index 03507f2150c..bd3364f49b7 100644
--- a/src/features/SharePopover/style.ts
+++ b/src/features/SharePopover/style.ts
@@ -1,10 +1,12 @@
import { createStaticStyles } from '@lobehub/ui';
+import { densityVars } from '@/styles/densityVars';
+
export const styles = createStaticStyles(({ css, cssVar }) => ({
badge: css`
- width: var(--lobe-density-icon-box);
- height: var(--lobe-density-icon-box);
- border-radius: var(--lobe-density-radius);
+ width: ${densityVars.iconBox};
+ height: ${densityVars.iconBox};
+ border-radius: ${densityVars.radius};
color: ${cssVar.colorTextSecondary};
@@ -19,7 +21,7 @@ export const styles = createStaticStyles(({ css, cssVar }) => ({
background: ${cssVar.colorSuccessBg};
`,
container: css`
- padding: var(--lobe-density-section-gap);
+ padding: ${densityVars.sectionGap};
`,
divider: css`
height: 1px;
@@ -50,14 +52,14 @@ export const styles = createStaticStyles(({ css, cssVar }) => ({
align-items: center;
width: 100%;
- min-height: var(--lobe-density-row-height);
+ min-height: ${densityVars.rowHeight};
margin-block-start: 6px;
padding-inline: 10px;
border: none;
- border-radius: var(--lobe-density-radius);
+ border-radius: ${densityVars.radius};
font: inherit;
- font-size: var(--lobe-density-font-size);
+ font-size: ${densityVars.fontSize};
color: ${cssVar.colorText};
background: transparent;
@@ -76,7 +78,7 @@ export const styles = createStaticStyles(({ css, cssVar }) => ({
notice: css`
padding-block: 8px;
padding-inline: 10px;
- border-radius: var(--lobe-density-radius);
+ border-radius: ${densityVars.radius};
font-size: 12px;
line-height: 1.5;
diff --git a/src/features/SubscriptionAccounts/AccountRow.tsx b/src/features/SubscriptionAccounts/AccountRow.tsx
index 27c9c4ef64b..133fb9698ad 100644
--- a/src/features/SubscriptionAccounts/AccountRow.tsx
+++ b/src/features/SubscriptionAccounts/AccountRow.tsx
@@ -35,7 +35,7 @@ import { UsageBar } from '@/features/DeviceManager/DeviceHealth/UsageMeter';
import { type QuotaAccount, useAgentQuotaStore } from '@/store/agentQuota';
import { useUserStore } from '@/store/user';
import { userProfileSelectors } from '@/store/user/selectors';
-import { useInterfaceDensity } from '@/styles/density';
+import { useDensity } from '@/styles/density';
import {
type AccountStatus,
@@ -193,7 +193,7 @@ interface AccountRowProps {
const AccountRow = ({ account, active, onOpen }: AccountRowProps) => {
const { t } = useTranslation('setting');
- const compact = useInterfaceDensity() === 'compact';
+ const { compact, tokens } = useDensity();
const { t: tCommon } = useTranslation('common');
const [
useFetchQuotaReadings,
@@ -333,7 +333,7 @@ const AccountRow = ({ account, active, onOpen }: AccountRowProps) => {
opacity: view.status === 'disabled' ? 0.55 : undefined,
}}
>
- <span style={{ display: 'flex', flex: 'none' }}>{meta.icon(compact ? 24 : 28)}</span>
+ <span style={{ display: 'flex', flex: 'none' }}>{meta.icon(tokens.iconBox)}</span>
<Flexbox gap={2} style={{ minWidth: 0 }}>
{editing ? (
<Flexbox horizontal align={'center'} gap={4} {...stop}>
diff --git a/src/layout/GlobalProvider/AppTheme.tsx b/src/layout/GlobalProvider/AppTheme.tsx
index 6195195db8b..bb21453e94e 100644
--- a/src/layout/GlobalProvider/AppTheme.tsx
+++ b/src/layout/GlobalProvider/AppTheme.tsx
@@ -22,11 +22,11 @@ import { useGlobalStore } from '@/store/global';
import { systemStatusSelectors } from '@/store/global/selectors';
import { useUserStore } from '@/store/user';
import { preferenceSelectors, userGeneralSettingsSelectors } from '@/store/user/selectors';
+import { resolveEffectiveDensity } from '@/styles/density';
import { compactDensityTheme } from '@/styles/densityTheme';
import { sx } from '@/styles/sx';
import { setCookie } from '@/utils/client/cookie';
import { resolveLang } from '@/utils/client/switchLang';
-import { isMobileSurface } from '@/utils/mobileSurface';
import { resolveFontFamilyOverride } from './fontFamilyOverride';
@@ -132,7 +132,7 @@ const AppTheme = memo<AppThemeProps>(
}, [fontAntialiasing]);
useEffect(() => {
- const effectiveDensity = isMobileSurface() ? 'loose' : interfaceDensity;
+ const effectiveDensity = resolveEffectiveDensity(interfaceDensity);
document.documentElement.dataset.density = effectiveDensity;
if (effectiveDensity !== 'compact') return;
const classes =
diff --git a/src/routes/(main)/group/profile/features/Header/ChromeTabs/index.tsx b/src/routes/(main)/group/profile/features/Header/ChromeTabs/index.tsx
index 4f65b1d480a..d6e7730fdee 100644
--- a/src/routes/(main)/group/profile/features/Header/ChromeTabs/index.tsx
+++ b/src/routes/(main)/group/profile/features/Header/ChromeTabs/index.tsx
@@ -14,6 +14,8 @@ import { type ReactNode } from 'react';
import { memo, useEffect, useRef } from 'react';
import { useTranslation } from 'react-i18next';
+import { densityVars } from '@/styles/densityVars';
+
const styles = createStaticStyles(({ css, cssVar: cv }) => ({
addButton: css`
cursor: pointer;
@@ -23,9 +25,9 @@ const styles = createStaticStyles(({ css, cssVar: cv }) => ({
align-items: center;
justify-content: center;
- width: var(--lobe-density-icon-box);
- height: var(--lobe-density-icon-box);
- border-radius: var(--lobe-density-radius);
+ width: ${densityVars.iconBox};
+ height: ${densityVars.iconBox};
+ border-radius: ${densityVars.radius};
color: ${cv.colorTextTertiary};
@@ -72,12 +74,12 @@ const styles = createStaticStyles(({ css, cssVar: cv }) => ({
gap: 6px;
align-items: center;
- height: var(--lobe-density-control-height);
+ height: ${densityVars.controlHeight};
padding-block: 4px;
padding-inline: 12px;
- border-radius: var(--lobe-density-radius);
+ border-radius: ${densityVars.radius};
- font-size: var(--lobe-density-font-size);
+ font-size: ${densityVars.fontSize};
color: ${cv.colorTextTertiary};
diff --git a/src/routes/(main)/group/profile/features/Header/index.tsx b/src/routes/(main)/group/profile/features/Header/index.tsx
index 4b01d3ac39b..c19bdf08c91 100644
--- a/src/routes/(main)/group/profile/features/Header/index.tsx
+++ b/src/routes/(main)/group/profile/features/Header/index.tsx
@@ -15,6 +15,7 @@ import { useAgentGroupStore } from '@/store/agentGroup';
import { agentGroupSelectors } from '@/store/agentGroup/selectors';
import { useGlobalStore } from '@/store/global';
import { systemStatusSelectors } from '@/store/global/selectors';
+import { densityVars } from '@/styles/densityVars';
import { isMobileSurface } from '@/utils/mobileSurface';
import AgentBuilderToggle from './AgentBuilderToggle';
@@ -27,7 +28,7 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
flex: none;
width: 100%;
- height: var(--lobe-density-header-height);
+ height: ${densityVars.headerHeight};
padding-block: 0;
padding-inline: 12px;
border-block-end: 1px solid ${cssVar.colorBorderSecondary};
diff --git a/src/styles/density.stylex.ts b/src/styles/density.stylex.ts
index 007b969c4a7..423bb89181a 100644
--- a/src/styles/density.stylex.ts
+++ b/src/styles/density.stylex.ts
@@ -1,20 +1,30 @@
+// @generated by scripts/densityTokens.mts from src/styles/densityScale.ts
+// Do not edit by hand β€” run `pnpm gen:density` after changing the spec.
import * as stylex from '@stylexjs/stylex';
export const densityTokens = stylex.defineVars({
'--lobe-density-control-height': '32px',
'--lobe-density-font-size': '14px',
+ '--lobe-density-gap': '8px',
+ '--lobe-density-header-avatar-size': '28px',
'--lobe-density-header-height': '44px',
+ '--lobe-density-header-icon-size': '20px',
+ '--lobe-density-header-small-icon-size': '16px',
'--lobe-density-icon-box': '28px',
'--lobe-density-icon-size': '18px',
'--lobe-density-line-height': '22px',
'--lobe-density-list-row-height': '48px',
+ '--lobe-density-padding-inline': '4px',
'--lobe-density-page-title-font-size': '16px',
+ '--lobe-density-panel-padding-inline': '4px',
'--lobe-density-radius': '8px',
'--lobe-density-row-height': '36px',
'--lobe-density-section-gap': '16px',
'--lobe-density-toolbar-height': '40px',
});
+// --- hand-maintained below this line (preserved by the generator) ---
+
export const sidebarRow = stylex.defineVars({
controlHeight: 'var(--lobe-density-control-height)',
gap: '8px',
diff --git a/src/styles/density.test.ts b/src/styles/density.test.ts
index 8c151d7e49e..def0f16ed51 100644
--- a/src/styles/density.test.ts
+++ b/src/styles/density.test.ts
@@ -1,6 +1,6 @@
-import { describe, expect, it } from 'vitest';
+import { afterEach, describe, expect, it, vi } from 'vitest';
-import { DENSITY_TOKENS } from './density';
+import { DENSITY_TOKENS, resolveEffectiveDensity } from './density';
describe('DENSITY_TOKENS', () => {
it('uses 32px rows in compact', () => {
@@ -27,3 +27,20 @@ describe('DENSITY_TOKENS', () => {
expect(DENSITY_TOKENS.loose).toMatchObject({ fontSize: 14, iconSize: 18, rowHeight: 36 });
});
});
+
+describe('resolveEffectiveDensity', () => {
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ });
+
+ it('keeps the stored density on desktop bundles', () => {
+ vi.stubGlobal('__MOBILE__', false);
+ expect(resolveEffectiveDensity('compact')).toBe('compact');
+ expect(resolveEffectiveDensity('loose')).toBe('loose');
+ });
+
+ it('forces loose on the mobile bundle whatever the preference says', () => {
+ vi.stubGlobal('__MOBILE__', true);
+ expect(resolveEffectiveDensity('compact')).toBe('loose');
+ });
+});
diff --git a/src/styles/density.ts b/src/styles/density.ts
index 0748d66aaae..90f44bba76e 100644
--- a/src/styles/density.ts
+++ b/src/styles/density.ts
@@ -5,6 +5,8 @@ import { useUserStore } from '@/store/user';
import { userGeneralSettingsSelectors } from '@/store/user/selectors';
import { isMobileSurface } from '@/utils/mobileSurface';
+import { DENSITY_SCALE, type DensityScale } from './densityScale';
+
export interface ActionSize {
blockSize: number;
size: number;
@@ -34,18 +36,10 @@ export interface DensityTokens {
treeItemHeight: number;
}
-type DensityScale = Omit<
- DensityTokens,
- | 'headerActionSize'
- | 'headerActionSmallSize'
- | 'headerChevronSize'
- | 'sectionHeaderHeight'
- | 'treeItemHeight'
-> & {
- headerIconSize: number;
- headerSmallIconSize: number;
-};
-
+/**
+ * Adds the sizes the app composes from the raw scale (action hit areas, section
+ * headers, tree rows) so components never re-derive them by hand.
+ */
const withDerivedTokens = ({
headerIconSize,
headerSmallIconSize,
@@ -59,58 +53,36 @@ const withDerivedTokens = ({
treeItemHeight: scale.controlHeight,
});
-// The px values also live in density.stylex.ts and densityTheme.ts as --lobe-density-* CSS
-// variables, because StyleX only compiles literals; densityParity.test.ts keeps them in step.
+// The px values live in densityScale.ts. The matching --lobe-density-* CSS variables are
+// generated from that file into density.stylex.ts / densityTheme.ts (scripts/densityTokens.mts).
export const DENSITY_TOKENS: Record<InterfaceDensity, DensityTokens> = {
- compact: withDerivedTokens({
- controlHeight: 28,
- fontSize: 13,
- gap: 8,
- headerAvatarSize: 24,
- headerHeight: 40,
- headerIconSize: 16,
- headerSmallIconSize: 14,
- iconBox: 24,
- iconSize: 16,
- lineHeight: 20,
- listRowHeight: 40,
- pageTitleFontSize: 14,
- paddingInline: 4,
- panelPaddingInline: 6,
- radius: 6,
- rowHeight: 32,
- sectionGap: 12,
- toolbarHeight: 36,
- }),
- loose: withDerivedTokens({
- controlHeight: 32,
- fontSize: 14,
- gap: 8,
- headerAvatarSize: 28,
- headerHeight: 44,
- headerIconSize: 20,
- headerSmallIconSize: 16,
- iconBox: 28,
- iconSize: 18,
- lineHeight: 22,
- listRowHeight: 48,
- pageTitleFontSize: 16,
- paddingInline: 4,
- panelPaddingInline: 4,
- radius: 8,
- rowHeight: 36,
- sectionGap: 16,
- toolbarHeight: 40,
- }),
+ compact: withDerivedTokens(DENSITY_SCALE.compact),
+ loose: withDerivedTokens(DENSITY_SCALE.loose),
};
+/**
+ * Mobile surfaces always render loose, whatever the stored preference says. Both the
+ * stylesheet attribute and the hooks resolve density through here so they cannot drift.
+ */
+export const resolveEffectiveDensity = (density: InterfaceDensity): InterfaceDensity =>
+ isMobileSurface() ? 'loose' : density;
+
export const useInterfaceDensity = (): InterfaceDensity => {
const density = useUserStore(userGeneralSettingsSelectors.interfaceDensity);
- return isMobileSurface() ? 'loose' : density;
+ return resolveEffectiveDensity(density);
};
export const useDensityTokens = () => DENSITY_TOKENS[useInterfaceDensity()];
+/**
+ * One density read per component: the numeric scale for props, plus the boolean that
+ * picks between structural style variants.
+ */
+export const useDensity = (): { compact: boolean; density: InterfaceDensity; tokens: DensityTokens } => {
+ const density = useInterfaceDensity();
+ return { compact: density === 'compact', density, tokens: DENSITY_TOKENS[density] };
+};
+
export const PanelDensityContext = createContext<InterfaceDensity | null | undefined>(undefined);
export const usePanelDensityTokens = (): DensityTokens | null => {
diff --git a/src/styles/densityParity.test.ts b/src/styles/densityParity.test.ts
deleted file mode 100644
index 45dea410cde..00000000000
--- a/src/styles/densityParity.test.ts
+++ /dev/null
@@ -1,32 +0,0 @@
-import { readFileSync } from 'node:fs';
-import { join } from 'node:path';
-
-import { describe, expect, it } from 'vitest';
-
-import { DENSITY_TOKENS } from './density';
-
-const readTokens = (file: string) => {
- const source = readFileSync(join(__dirname, file), 'utf8');
- const tokens: Record<string, number> = {};
- for (const [, name, value] of source.matchAll(/'--lobe-density-([a-z-]+)': '(\d+)px'/g)) {
- tokens[name.replaceAll(/-([a-z])/g, (_, char: string) => char.toUpperCase())] = Number(value);
- }
- return tokens;
-};
-
-describe('density CSS variables', () => {
- it('declares loose defaults that match DENSITY_TOKENS.loose', () => {
- const tokens = readTokens('density.stylex.ts');
-
- expect(Object.keys(tokens).length).toBeGreaterThan(0);
- expect(DENSITY_TOKENS.loose).toMatchObject(tokens);
- });
-
- it('overrides every variable in the compact theme with DENSITY_TOKENS.compact', () => {
- const loose = readTokens('density.stylex.ts');
- const compact = readTokens('densityTheme.ts');
-
- expect(Object.keys(compact).sort()).toEqual(Object.keys(loose).sort());
- expect(DENSITY_TOKENS.compact).toMatchObject(compact);
- });
-});
diff --git a/src/styles/densityScale.ts b/src/styles/densityScale.ts
new file mode 100644
index 00000000000..c6abaf2caba
--- /dev/null
+++ b/src/styles/densityScale.ts
@@ -0,0 +1,81 @@
+import type { InterfaceDensity } from '@lobechat/types';
+
+/**
+ * Interface density scale β€” the single hand-written source of truth.
+ *
+ * StyleX only accepts literals in `defineVars` / `createTheme`, so the values
+ * cannot be read from JS at compile time. Instead the px numbers live here once
+ * and everything else is derived from this file:
+ *
+ * - `scripts/densityTokens.mts` generates `density.stylex.ts` (StyleX vars, Loose
+ * defaults) and `densityTheme.ts` (Compact overrides). Run `pnpm gen:density`.
+ * - `density.ts` derives `DENSITY_TOKENS`, the numeric scale used for component
+ * props, including composed values such as `headerActionSize`.
+ *
+ * Every key also becomes a `--lobe-density-<kebab-case>` CSS variable, so
+ * stylesheets read the same number instead of keeping a second token table.
+ * Editing a value only ever happens here.
+ */
+export interface DensityScale {
+ controlHeight: number;
+ fontSize: number;
+ gap: number;
+ headerAvatarSize: number;
+ headerHeight: number;
+ headerIconSize: number;
+ headerSmallIconSize: number;
+ iconBox: number;
+ iconSize: number;
+ lineHeight: number;
+ listRowHeight: number;
+ paddingInline: number;
+ pageTitleFontSize: number;
+ panelPaddingInline: number;
+ radius: number;
+ rowHeight: number;
+ sectionGap: number;
+ toolbarHeight: number;
+}
+
+export const DENSITY_SCALE: Record<InterfaceDensity, DensityScale> = {
+ compact: {
+ controlHeight: 28,
+ fontSize: 13,
+ gap: 8,
+ headerAvatarSize: 24,
+ headerHeight: 40,
+ headerIconSize: 16,
+ headerSmallIconSize: 14,
+ iconBox: 24,
+ iconSize: 16,
+ lineHeight: 20,
+ listRowHeight: 40,
+ paddingInline: 4,
+ pageTitleFontSize: 14,
+ panelPaddingInline: 6,
+ radius: 6,
+ rowHeight: 32,
+ sectionGap: 12,
+ toolbarHeight: 36,
+ },
+ loose: {
+ controlHeight: 32,
+ fontSize: 14,
+ gap: 8,
+ headerAvatarSize: 28,
+ headerHeight: 44,
+ headerIconSize: 20,
+ headerSmallIconSize: 16,
+ iconBox: 28,
+ iconSize: 18,
+ lineHeight: 22,
+ listRowHeight: 48,
+ paddingInline: 4,
+ pageTitleFontSize: 16,
+ panelPaddingInline: 4,
+ radius: 8,
+ rowHeight: 36,
+ sectionGap: 16,
+ toolbarHeight: 40,
+ },
+};
diff --git a/src/styles/densityTheme.ts b/src/styles/densityTheme.ts
index b8d7f1417a4..6cc4f08da8d 100644
--- a/src/styles/densityTheme.ts
+++ b/src/styles/densityTheme.ts
@@ -1,3 +1,5 @@
+// @generated by scripts/densityTokens.mts from src/styles/densityScale.ts
+// Do not edit by hand β€” run `pnpm gen:density` after changing the spec.
import * as stylex from '@stylexjs/stylex';
import { densityTokens } from './density.stylex';
@@ -5,12 +7,18 @@ import { densityTokens } from './density.stylex';
export const compactDensityTheme = stylex.createTheme(densityTokens, {
'--lobe-density-control-height': '28px',
'--lobe-density-font-size': '13px',
+ '--lobe-density-gap': '8px',
+ '--lobe-density-header-avatar-size': '24px',
'--lobe-density-header-height': '40px',
+ '--lobe-density-header-icon-size': '16px',
+ '--lobe-density-header-small-icon-size': '14px',
'--lobe-density-icon-box': '24px',
'--lobe-density-icon-size': '16px',
'--lobe-density-line-height': '20px',
'--lobe-density-list-row-height': '40px',
+ '--lobe-density-padding-inline': '4px',
'--lobe-density-page-title-font-size': '14px',
+ '--lobe-density-panel-padding-inline': '6px',
'--lobe-density-radius': '6px',
'--lobe-density-row-height': '32px',
'--lobe-density-section-gap': '12px',
diff --git a/src/styles/densityVars.ts b/src/styles/densityVars.ts
new file mode 100644
index 00000000000..69a415028b0
--- /dev/null
+++ b/src/styles/densityVars.ts
@@ -0,0 +1,25 @@
+// @generated by scripts/densityTokens.mts from src/styles/densityScale.ts
+// Do not edit by hand β€” run `pnpm gen:density` after changing the spec.
+import { densityTokens } from './density.stylex';
+
+/** camelCase handles over the same variables, for stylesheets and inline styles. */
+export const densityVars = {
+ controlHeight: densityTokens['--lobe-density-control-height'],
+ fontSize: densityTokens['--lobe-density-font-size'],
+ gap: densityTokens['--lobe-density-gap'],
+ headerAvatarSize: densityTokens['--lobe-density-header-avatar-size'],
+ headerHeight: densityTokens['--lobe-density-header-height'],
+ headerIconSize: densityTokens['--lobe-density-header-icon-size'],
+ headerSmallIconSize: densityTokens['--lobe-density-header-small-icon-size'],
+ iconBox: densityTokens['--lobe-density-icon-box'],
+ iconSize: densityTokens['--lobe-density-icon-size'],
+ lineHeight: densityTokens['--lobe-density-line-height'],
+ listRowHeight: densityTokens['--lobe-density-list-row-height'],
+ paddingInline: densityTokens['--lobe-density-padding-inline'],
+ pageTitleFontSize: densityTokens['--lobe-density-page-title-font-size'],
+ panelPaddingInline: densityTokens['--lobe-density-panel-padding-inline'],
+ radius: densityTokens['--lobe-density-radius'],
+ rowHeight: densityTokens['--lobe-density-row-height'],
+ sectionGap: densityTokens['--lobe-density-section-gap'],
+ toolbarHeight: densityTokens['--lobe-density-toolbar-height'],
+};