Skip to content

Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active

🧪 fix: Close css-colors Triplet and Disabled-Recipe Rule Gaps (#17358)

Marco Beretta3d240e2b8ae6
diff --git a/e2e/specs/mock/scenarios/disabled-recipe.spec.ts b/e2e/specs/mock/scenarios/disabled-recipe.spec.ts
index 0932560e91..7528b668a1 100644
--- a/e2e/specs/mock/scenarios/disabled-recipe.spec.ts
+++ b/e2e/specs/mock/scenarios/disabled-recipe.spec.ts
@@ -61,4 +61,37 @@ test.describe('the disabled-recipe design rule', () => {
rmSync(probePath, { force: true });
}
});
+ test('a spelled-out recipe under the same variants as the dim passes the design lint @scenario:a-spelled-out-recipe-under-the-same-variants-passes-the-design-lint', () => {
+ inOneProject();
+ test.setTimeout(180_000);
+
+ const probe = 'client/src/__disabled_recipe_spelled_probe__.tsx';
+ const probePath = join(repoRoot, probe);
+ const lint = (body: string): LintMessage[] => {
+ writeFileSync(probePath, `import { cn } from '@librechat/client';\n${body}`);
+ const result = run(ESLINT, ['--format', 'json', '--no-warn-ignored', '--', probe]);
+ const [report] = JSON.parse(result.stdout) as { messages: LintMessage[] }[];
+ return report.messages.filter((message) => message.ruleId === RULE);
+ };
+
+ try {
+ const shared = lint(
+ "export const A = () => <input className={cn('disabled:hover:opacity-50', 'theme-disabled:hover:opacity-100')} />;\n",
+ );
+ expect(shared, 'a recipe marker followed by a shared variant').toEqual([]);
+
+ const constant = lint(
+ "const faded = 'opacity-50 theme-disabled:opacity-100';\n" +
+ 'export const A = ({ busy }: { busy: boolean }) => <input disabled={busy} className={cn(busy && faded)} />;\n',
+ );
+ expect(constant, 'a constant that spells its own recipe').toEqual([]);
+
+ const mismatched = lint(
+ "export const A = () => <input className={cn('disabled:opacity-50', 'md:theme-disabled:opacity-100')} />;\n",
+ );
+ expect(mismatched, 'a recipe under a variant the dim lacks').toHaveLength(1);
+ } finally {
+ rmSync(probePath, { force: true });
+ }
+ });
});
diff --git a/scripts/css-colors.mts b/scripts/css-colors.mts
index f7b4619533..2ad4c4fe95 100644
--- a/scripts/css-colors.mts
+++ b/scripts/css-colors.mts
@@ -53,13 +53,26 @@ const FUNCTION = new RegExp(
const RELATIVE_COLOR = /(?<![\w-])(?:rgba?|hsla?|hwb|lab|lch|oklab|oklch|color)\(\s*from\s+/gi;
const CHANNEL_KEYWORD = /(?<![\w-])(?:[rgbhslwcaxyz]|alpha)(?![\w-])/i;
const CHANNEL = '[+-]?(?:\\d+\\.?\\d*|\\.\\d+)(?:e[+-]?\\d+)?%?';
-/** An innermost math function, or grouping parenthesis, over numbers alone: no `var()` and no unit. */
-const NUMERIC_MATH = new RegExp(
- String.raw`(?<![\w-])(?:${MATH_FUNCTIONS})?\((?:[\d.%+*/,\s-]|e|pi|infinity|nan|nearest|up|down|to-zero)*\)`,
- 'gi',
+const ANGLE_UNIT = '(?:deg|grad|rad|turn)';
+/** An angle is a number with a unit; it is a hue when it leads a triplet. */
+const ANGLE = `[+-]?(?:\\d+\\.?\\d*|\\.\\d+)(?:e[+-]?\\d+)?${ANGLE_UNIT}`;
+/** An innermost function or grouping parenthesis: a body with no nested call. */
+const INNERMOST = /(?<![\w-])([a-z][\w-]*)?\(([^()]*)\)/gi;
+const MATH = new Set(
+ MATH_FUNCTIONS.split('|').flatMap((name) => (name === 'atan2?' ? ['atan', 'atan2'] : [name])),
);
+/** Functions whose result kind does not follow their arguments. */
+const FIXED_RESULT = new Map([
+ ...['sin', 'cos', 'tan', 'sign'].map((name) => [name, 'number'] as const),
+ ...['asin', 'acos', 'atan', 'atan2'].map((name) => [name, 'angle'] as const),
+]);
+/** A math body token: a number with its unit, an identifier (a constant such as `pi` or a
+ * rounding strategy such as `to-zero`), or an operator or separator. */
+const MATH_TOKEN =
+ /\s*(?:([+-]?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?)(%|[a-z]+)?|(-?[a-z][\w-]*)|([+*/,-]))/iy;
+const ANGLE_UNITS = new Set(['deg', 'grad', 'rad', 'turn']);
const SEPARATOR = '(?:\\s*,\\s*|\\s+)';
-const BARE_TRIPLET = `${CHANNEL}${SEPARATOR}${CHANNEL}${SEPARATOR}${CHANNEL}(?:\\s*/\\s*(?:${CHANNEL}|var\\([^)]*\\)))?`;
+const BARE_TRIPLET = `(?:${CHANNEL}|${ANGLE})${SEPARATOR}${CHANNEL}${SEPARATOR}${CHANNEL}(?:\\s*/\\s*(?:${CHANNEL}|var\\([^)]*\\)))?`;
/** The whole value is three bare channels, or one is the fallback of a `var()`. */
const TRIPLET = new RegExp(
`^\\s*${BARE_TRIPLET}\\s*$|var\\(\\s*--[\\w-]+\\s*,\\s*${BARE_TRIPLET}\\s*\\)`,
@@ -73,9 +86,40 @@ const NON_COLOR_PROPERTY =
const blank = (match: string): string => match.replace(/[^\n]/g, ' ');
-/** A math function over numbers (`calc(255)`, `min(100, max(0, 255))`) is a fixed channel, so it reads as one. */
+/** What a math body yields: a number, an angle, a length or other dimension, or `undefined` when
+ * it is not math. Any identifier is a keyword, so a new rounding strategy or constant still reads
+ * as a channel and is reported rather than skipped. */
+function mathKind(body: string): 'number' | 'angle' | 'dimension' | undefined {
+ let kind: 'number' | 'angle' | 'dimension' = 'number';
+ MATH_TOKEN.lastIndex = 0;
+ while (MATH_TOKEN.lastIndex < body.trimEnd().length) {
+ const token = MATH_TOKEN.exec(body);
+ if (!token) return undefined;
+ const unit = token[2]?.toLowerCase();
+ if (!unit || unit === '%' || kind === 'dimension') continue;
+ kind = ANGLE_UNITS.has(unit) ? 'angle' : 'dimension';
+ }
+ return kind;
+}
+
+/** A math function over numbers (`calc(255)`, `round(to-zero, 255, 1)`) is a fixed channel, and one
+ * over an angle is an angle (`0deg`), which a triplet reads only as its leading hue. Trigonometric
+ * functions and `sign` return a number and inverse trigonometric ones an angle whatever they are
+ * given; any other function over a length is a length (`0px`), which an enclosing trigonometric
+ * function still reads and a triplet does not. */
function collapseMath(text: string): string {
- const collapsed = text.replace(NUMERIC_MATH, '0');
+ const collapsed = text.replace(
+ INNERMOST,
+ (match: string, name: string | undefined, body: string) => {
+ const fn = name?.toLowerCase();
+ if (fn !== undefined && !MATH.has(fn)) return match;
+ const kind = mathKind(body);
+ if (kind === undefined) return match;
+ const result = (fn === undefined ? undefined : FIXED_RESULT.get(fn)) ?? kind;
+ if (result === 'dimension') return '0px';
+ return result === 'angle' ? '0deg' : '0';
+ },
+ );
return collapsed === text ? text : collapseMath(collapsed);
}
diff --git a/scripts/css-colors.test.mts b/scripts/css-colors.test.mts
index e59626cb40..840511625d 100644
--- a/scripts/css-colors.test.mts
+++ b/scripts/css-colors.test.mts
@@ -207,6 +207,52 @@ test('reads math function channels in a custom property triplet', () => {
);
});
+test('reads angle channels in a custom property triplet', () => {
+ assert.deepEqual(literals('a { --brand: sin(90deg) 0 0; }'), ['sin(90deg) 0 0']);
+ assert.deepEqual(literals('a { --h: 90deg 50% 50%; }'), ['90deg 50% 50%']);
+ assert.deepEqual(literals('a { --h: 0.25turn 50% 50%; }'), ['0.25turn 50% 50%']);
+ assert.deepEqual(literals('a { --h: calc(45deg * 2) 50% 50%; }'), ['calc(45deg * 2) 50% 50%']);
+ assert.deepEqual(literals('a { --h: 120 50% cos(1rad); }'), ['120 50% cos(1rad)']);
+ assert.deepEqual(literals('a { --h: sin(calc(90deg)) 0 0; }'), ['sin(calc(90deg)) 0 0']);
+ assert.deepEqual(literals('a { --size: calc(1px + 2px) 0 0; }'), []);
+ assert.deepEqual(literals('a { --size: calc(1deg + 2px) 0 0; }'), []);
+ assert.deepEqual(literals('a { --h: sin(var(--angle)) 0 0; }'), []);
+ assert.deepEqual(literals('a { --h: 0 90deg 0; }'), []);
+});
+
+test('reads rounding and other math functions over angles in a hue triplet', () => {
+ assert.deepEqual(literals('a { --h: round(to-zero, 90deg, 1deg) 50% 50%; }'), [
+ 'round(to-zero, 90deg, 1deg) 50% 50%',
+ ]);
+ assert.deepEqual(literals('a { --h: round(up, 90.5deg) 50% 50%; }'), [
+ 'round(up, 90.5deg) 50% 50%',
+ ]);
+ assert.deepEqual(literals('a { --h: mod(400deg, 360deg) 50% 50%; }'), [
+ 'mod(400deg, 360deg) 50% 50%',
+ ]);
+ assert.deepEqual(literals('a { --h: atan2(1, 1) 50% 50%; }'), ['atan2(1, 1) 50% 50%']);
+ assert.deepEqual(literals('a { --h: calc(pi * 1rad) 50% 50%; }'), ['calc(pi * 1rad) 50% 50%']);
+ assert.deepEqual(literals('a { --h: round(future-strategy, 90deg) 50% 50%; }'), [
+ 'round(future-strategy, 90deg) 50% 50%',
+ ]);
+ assert.deepEqual(literals('a { --h: round(to-zero, 90px, 1px) 50% 50%; }'), []);
+ assert.deepEqual(literals('a { --h: round(to-zero, var(--angle), 1deg) 50% 50%; }'), []);
+ assert.deepEqual(literals('a { --h: env(hue, 90deg) 50% 50%; }'), []);
+ assert.deepEqual(literals('a { --h: atan2(1px, 1px) 50% 50%; }'), ['atan2(1px, 1px) 50% 50%']);
+ assert.deepEqual(literals('a { --brand: 255 sign(90deg) 0; }'), ['255 sign(90deg) 0']);
+ assert.deepEqual(literals('a { --brand: 255 sign(-4px) 0; }'), ['255 sign(-4px) 0']);
+ assert.deepEqual(literals('a { --h: calc(90deg + 1px) 50% 50%; }'), []);
+ assert.deepEqual(literals('a { --orientation: 0 calc(90deg) 0; }'), []);
+ assert.deepEqual(literals('a { --orientation: 0 round(to-zero, 90deg, 1deg) 0; }'), []);
+ assert.deepEqual(literals('a { --orientation: 0 0 atan(1); }'), []);
+ assert.deepEqual(literals('a { --h: calc(90deg) 50% 50%; }'), ['calc(90deg) 50% 50%']);
+ assert.deepEqual(literals('a { --h: atan2(calc(1px + 1px), 1px) 50% 50%; }'), [
+ 'atan2(calc(1px + 1px), 1px) 50% 50%',
+ ]);
+ assert.deepEqual(literals('a { --brand: 255 sign(calc(-4px)) 0; }'), ['255 sign(calc(-4px)) 0']);
+ assert.deepEqual(literals('a { --size: max(calc(1px + 1px), 2px) 0 0; }'), []);
+});
+
test('a token source exempts its custom properties only', () => {
const css = ':root { --x: 255 0 0; --y: #fff; }\na { color: #fff; width: calc(1 * 2); }';
assert.deepEqual(findCssColorLiterals(css, [], true), [{ line: 2, literal: '#fff' }]);
diff --git a/scripts/eslint/design.mjs b/scripts/eslint/design.mjs
index ed66bc9e44..a02233b10b 100644
--- a/scripts/eslint/design.mjs
+++ b/scripts/eslint/design.mjs
@@ -3,6 +3,12 @@ import { dirname, resolve } from 'node:path';
/**
* Design rules `@shadcn/lint` does not cover, registered as the `design` plugin in
* `eslint.config.mjs` and recorded in `eslint-suppressions.json` like its rules.
+ *
+ * `disabled-recipe` reports only the shapes it reads positively and skips the rest: a utility
+ * under an arbitrary variant it cannot place (an enclosing selector such as `[.foo_&]:` or
+ * `[&:hover]:`, a media or supports query in brackets, or a disabled selector other than the
+ * recipes' markers, an ancestor `[..._&]` or a `:has()`) is neither a dim nor a recipe, because
+ * whether a recipe outranks it depends on selector order and specificity the rule cannot see.
*/
/** The shared disabled recipes (`packages/client/src/utils/theme.ts`) and the element each one
@@ -17,11 +23,11 @@ const RECIPES = new Map([
/** The full-opacity override every recipe carries, so a class list that spells one out also
* counts; another `theme-disabled:` utility alone still leaves the control faded. */
-const RECIPE_VARIANTS = [
- [/(?:^|\s)theme-disabled:(!?)opacity-100(!?)(?=\s|$)/, 'self'],
- [/(?:^|\s)theme-disabled-within:(!?)opacity-100(!?)(?=\s|$)/, 'within'],
- [/(?:^|\s)peer-theme-disabled:(!?)opacity-100(!?)(?=\s|$)/, 'peer'],
-];
+const RECIPE_VARIANTS = new Map([
+ ['theme-disabled', 'self'],
+ ['theme-disabled-within', 'within'],
+ ['peer-theme-disabled', 'peer'],
+]);
/** Where the shared primitives live, for a relative import inside the component library. */
const PRIMITIVES_DIR = /packages[\\/]client[\\/]src[\\/]components[\\/]([\w.-]+?)(?:\.tsx?)?$/;
@@ -73,11 +79,25 @@ const WITHIN_MARKERS = /^(?:has-\[:disabled\]|has-disabled|\[&:has\(:disabled\)\
* control restores. */
const isDescendantModifier = (variant) => /^\[&[\s_>~+]/.test(variant) || /^\*{1,2}$/.test(variant);
+/** Whether the rule can place an arbitrary variant: a descendant modifier, a recipe marker, an
+ * ancestor that is disabled (`[tr[data-disabled=true]_&]`) or a disabled `:has()`. Plain
+ * variants (`md`, `hover`, `group-disabled`) are always placed. */
+const isPlaced = (variant) =>
+ !variant.startsWith('[') ||
+ isDescendantModifier(variant) ||
+ (isDisabledVariant(variant) &&
+ (SELF_MARKERS.test(variant) ||
+ WITHIN_MARKERS.test(variant) ||
+ /_&\]$/.test(variant) ||
+ /:has\(/.test(variant)));
+
/** The disabled markers `theme-disabled` matches (`:disabled`, `[data-disabled]`,
- * `[aria-disabled='true']`); a self variant spelled with another marker, such as
- * `data-[state=disabled]`, is one no recipe restores. */
-const SELF_MARKERS =
- /^(?:disabled|aria-disabled|data-disabled|data-\[disabled(?:=["']?true["']?)?\]|aria-\[disabled=["']?true["']?\]|\[&:disabled\]|\[&\[data-disabled\]\]|\[&\[aria-disabled=["']?true["']?\]\])$/;
+ * `[aria-disabled='true']`, and `[&:is(:disabled)]`, which implies one; a valued
+ * `[&[data-disabled=true]]` selects a subset of `[data-disabled]`); a self variant spelled
+ * with another marker, such as `data-[state=disabled]`, is one no recipe restores. */
+const SELF_MARKERS = new RegExp(
+ String.raw`^(?:disabled|aria-disabled|data-disabled|data-\[disabled(?:=["']?true["']?)?\]|aria-\[disabled=["']?true["']?\]|\[&:(?:disabled|(?:is|where)\(:disabled\))\]|\[&\[data-disabled(?:=["']?[\w-]+["']?)?\]\]|\[&\[aria-disabled=["']?true["']?\]\])$`,
+);
const TOPOLOGY_ORDER = ['group', 'peer', 'within', 'self'];
@@ -129,6 +149,7 @@ const isImportant = (base) => base.startsWith('!') || base.endsWith('!');
function variantDims(value) {
return value.split(/\s+/).flatMap((token) => {
const { variants, base } = splitVariants(token);
+ if (!variants.every(isPlaced)) return [];
const selecting = isOpacity(base) ? variants.filter(isDisabledVariant) : [];
if (selecting.length === 0) return [];
/** A stacked utility (`disabled:group-disabled:opacity-50`) needs the recipe for its most
@@ -146,17 +167,50 @@ function variantDims(value) {
function bareDims(value, topology) {
return value.split(/\s+/).flatMap((token) => {
const { variants, base } = splitVariants(token);
- if (!isOpacity(base) || variants.some(isDisabledVariant)) return [];
+ if (!isOpacity(base) || variants.some(isDisabledVariant) || !variants.every(isPlaced)) {
+ return [];
+ }
const distant = variants.some(isDescendantModifier);
return [{ dim: token, topology: distant ? 'group' : topology, important: isImportant(base) }];
});
}
+/** The enclosing variants of a utility: every variant that is not a disabled selector, so
+ * `md:disabled:opacity-50` and `md:theme-disabled:opacity-100` share `md`. */
+const enclosingOf = (variants) => variants.filter((variant) => !isDisabledVariant(variant));
+
+/** Whether `value` spells out a recipe's full-opacity override for the element `need` fades.
+ * The override may sit under fewer enclosing variants than the dim, since it is then active
+ * whenever the dim is, but not under variants the dim lacks. A dim under a descendant modifier
+ * fades another element, which no recipe restores, so the order of variants never matters. */
+function spellsRecipe(value, need) {
+ const dimEnclosing = enclosingOf(splitVariants(need.dim ?? '').variants);
+ return value.split(/\s+/).some((token) => {
+ const { variants, base } = splitVariants(token);
+ const match = /^(!?)opacity-100(!?)$/.exec(base);
+ const marker = variants.findIndex((variant) => RECIPE_VARIANTS.has(variant));
+ if (!match || marker === -1) return false;
+ const recipe = RECIPE_VARIANTS.get(variants[marker]);
+ if (!(need.topology === 'any' || recipe === need.topology)) return false;
+ if (need.important && !match[1] && !match[2]) return false;
+ return variants
+ .filter((_, i) => i !== marker)
+ .every((variant) => dimEnclosing.includes(variant));
+ });
+}
+
/** Whether a shared recipe restores a dim: it targets the dim's element, and the dim is not
* `!important`, which no shared recipe outranks. */
const covers = (recipe, need) =>
recipe !== undefined && !need.important && (need.topology === 'any' || recipe === need.topology);
+/** The expression under TypeScript wrappers that do not change its value: `[recipe] as const`,
+ * `map satisfies ClassMap`, `value!`. */
+const unwrap = (node) =>
+ ['TSAsExpression', 'TSSatisfiesExpression', 'TSNonNullExpression'].includes(node?.type)
+ ? unwrap(node.expression)
+ : node;
+
/** The variable a name resolves to from `scope`, or `undefined` when nothing declares it. */
function findVariable(scope, name) {
for (let current = scope; current; current = current.upper) {
@@ -351,8 +405,6 @@ function classNameElement(root) {
return attribute?.name.name === 'className' ? attribute.parent : undefined;
}
-const isCva = (call) => call.type === 'CallExpression' && call.callee.name === 'cva';
-
/** The helpers that join their arguments into one class list; another call's result is not
* known to carry what it was given. */
const CLASS_CALLS = new Set(['cn', 'clsx', 'cx', 'classNames', 'twMerge', 'twJoin', 'cva']);
@@ -388,6 +440,14 @@ const isClassCall = (call, source, filename) => {
);
};
+/** A call of the `cva` helper, resolved the way the other class helpers are: a local `cva`
+ * or one imported from elsewhere is another function and its base proves nothing. */
+const isCva = (call, source, filename) =>
+ call.type === 'CallExpression' &&
+ call.callee.type === 'Identifier' &&
+ call.callee.name === 'cva' &&
+ isClassCall(call, source, filename);
+
/** Reads, for one class list, what a recipe reference resolves to and which strings and
* expressions always emit one. */
function recipeReader(context) {
@@ -427,13 +487,7 @@ function recipeReader(context) {
};
/** A spelled-out recipe for the dim's element, `!important` when the dim is. */
- const stringCovers = (value, need) =>
- typeof value === 'string' &&
- RECIPE_VARIANTS.some(([pattern, recipe]) => {
- const match = pattern.exec(value);
- if (!match || !(need.topology === 'any' || recipe === need.topology)) return false;
- return !need.important || Boolean(match[1] || match[2]);
- });
+ const stringCovers = (value, need) => typeof value === 'string' && spellsRecipe(value, need);
/** Whether `node` emits a recipe covering `need` (the dim's element and importance) on every
* path through it. */
@@ -453,7 +507,7 @@ function recipeReader(context) {
case 'MemberExpression':
return !node.computed && covers(memberRecipeOf(node), topology);
case 'CallExpression':
- if (isCva(node)) {
+ if (isCva(node, source, context.filename)) {
const [base] = node.arguments;
return base !== undefined && always(base, topology);
}
@@ -475,8 +529,10 @@ function recipeReader(context) {
);
case 'ObjectExpression':
return node.properties.some((property) => mapEntryAlways(property, topology));
- case 'SpreadElement':
- return always(node.argument, topology);
+ case 'SpreadElement': {
+ const argument = unwrap(node.argument);
+ return argument.type === 'ArrayExpression' && always(argument, topology);
+ }
case 'ChainExpression':
case 'TSAsExpression':
case 'TSSatisfiesExpression':
@@ -487,14 +543,54 @@ function recipeReader(context) {
}
};
- /** A class-map entry that is always on and names a covering recipe. */
+ /** The keys a class-map entry sets, by name or by the source of a computed key; a spread sets
+ * the keys of the object it spreads. */
+ const entryKeys = (property) => {
+ if (property.type === 'Property') {
+ const literal = property.key.type === 'Literal' ? String(property.key.value) : undefined;
+ if (!property.computed || literal !== undefined) return [literal ?? keyName(property)];
+ return [`[${source.getText(property.key)}]`];
+ }
+ const argument = unwrap(property.argument);
+ return argument.type === 'ObjectExpression' ? argument.properties.flatMap(entryKeys) : [];
+ };
+
+ /** A spread whose keys are not known statically: anything but an object literal, or an object
+ * literal that itself spreads one. */
+ const unknownSpread = (property) => {
+ if (property.type !== 'SpreadElement') return false;
+ const argument = unwrap(property.argument);
+ return argument.type !== 'ObjectExpression' || argument.properties.some(unknownSpread);
+ };
+
+ /** Whether a later entry of the same map can overwrite `property`: an unknown spread, or an
+ * entry or known spread that sets one of its keys. */
+ const overwritten = (property) => {
+ const { properties } = property.parent;
+ const keys = new Set(entryKeys(property));
+ return properties
+ .slice(properties.indexOf(property) + 1)
+ .some((later) => unknownSpread(later) || entryKeys(later).some((key) => keys.has(key)));
+ };
+
+ /** A class-map entry that is always on, names a covering recipe, and is not overwritten. */
const mapEntryAlways = (property, topology) =>
- property.type === 'Property' &&
- property.value.type === 'Literal' &&
- property.value.value === true &&
- (property.computed
- ? always(property.key, topology)
- : stringCovers(property.key.value, topology));
+ !overwritten(property) && mapEntryOn(property, topology);
+
+ const mapEntryOn = (property, topology) => {
+ if (property.type === 'SpreadElement') {
+ const argument = unwrap(property.argument);
+ return argument.type === 'ObjectExpression' && always(argument, topology);
+ }
+ return (
+ property.type === 'Property' &&
+ unwrap(property.value).type === 'Literal' &&
+ unwrap(property.value).value === true &&
+ (property.computed
+ ? always(property.key, topology)
+ : stringCovers(property.key.value, topology))
+ );
+ };
/** A sibling that always emits a covering recipe, or one guarded by the same condition as the
* dim's own entry, on the same side: `cn(disabled && 'opacity-50', disabled && recipe)` or
@@ -548,7 +644,7 @@ function recipeReader(context) {
switch (parent.type) {
case 'CallExpression': {
if (parent.callee === child) return false;
- if (isCva(parent)) {
+ if (isCva(parent, source, context.filename)) {
const [base] = parent.arguments;
return child !== base && base !== undefined && always(base, topology);
}
@@ -714,7 +810,7 @@ const disabledRecipe = {
};
/** `node` is the string as an expression; a template's text reports on its own part. */
- const check = (node, value, reported = node) => {
+ const check = (node, value, reported = node, bareOnly = false) => {
if (typeof value !== 'string' || !value.includes('opacity-')) return;
const list = classList(node);
const element = classNameElement(list);
@@ -729,17 +825,37 @@ const disabledRecipe = {
if (element) bareTopology = control ? 'self' : 'within';
const picked = known.get(STATIC) === true || chosenByDisabled(node, source, known);
const chosen = picked ? bareDims(value, bareTopology) : [];
- const dims = [...variantDims(value), ...chosen];
+ const spelled = (need) => bareOnly && spellsRecipe(value, need);
+ const dims = [...(bareOnly ? [] : variantDims(value)), ...chosen].filter(
+ (need) => !spelled(need),
+ );
if (dims.length === 0) return;
/** A primitive's own recipe restores a plain fade of the control itself; an important one,
* or one on another element, still needs the caller's recipe. */
const coveredByPrimitive = (need) =>
!need.important && (need.topology === 'self' || need.topology === 'any');
- if (isPrimitive(element) && dims.every(coveredByPrimitive)) return;
- const missing = dims.find((need) => !restored(node, list, { ...need, known }));
+ const unrestored = isPrimitive(element)
+ ? dims.filter((need) => !coveredByPrimitive(need))
+ : dims;
+ const missing = unrestored.find((need) => !restored(node, list, { ...need, known }));
if (!missing) return;
context.report({ node: reported, messageId: 'missing', data: { dim: missing.dim } });
};
+ /** The string a `const` identifier holds, when it is a plain string or a template without
+ * expressions. */
+ const constantString = (identifier) => {
+ const variable = findVariable(source.getScope(identifier), identifier.name);
+ const declarator = variable?.defs[0]?.node;
+ if (declarator?.type !== 'VariableDeclarator' || declarator.parent.kind !== 'const') {
+ return undefined;
+ }
+ const init = unwrap(declarator.init);
+ let value = init?.type === 'Literal' ? init.value : undefined;
+ if (init?.type === 'TemplateLiteral' && init.expressions.length === 0) {
+ value = init.quasis[0].value.cooked;
+ }
+ return typeof value === 'string' ? value : undefined;
+ };
/** A constant class string the element names (`const faded = 'opacity-50'` then
* `<button disabled className={faded} />`): read where it is used, since the literal on its
* own carries no disabled context. */
@@ -750,24 +866,12 @@ const disabledRecipe = {
if (expression?.type !== 'Identifier') return;
const element = attribute.parent;
if (disabledExpressions(element, source).get(STATIC) !== true) return;
- const variable = findVariable(source.getScope(expression), expression.name);
- const declarator = variable?.defs[0]?.node;
- if (declarator?.type !== 'VariableDeclarator' || declarator.parent.kind !== 'const') return;
- const init = declarator.init;
- let value = init?.type === 'Literal' ? init.value : undefined;
- if (init?.type === 'TemplateLiteral' && init.expressions.length === 0) {
- value = init.quasis[0].value.cooked;
- }
- if (typeof value !== 'string') return;
+ const value = constantString(expression);
+ if (value === undefined) return;
const primitive = isPrimitive(element);
const dim = bareDims(value, 'self').find((need) => {
if (primitive && !need.important && need.topology === 'self') return false;
- return !RECIPE_VARIANTS.some(([pattern, recipe]) => {
- const match = pattern.exec(value);
- return (
- match && recipe === need.topology && (!need.important || Boolean(match[1] || match[2]))
- );
- });
+ return !spellsRecipe(value, need);
});
if (!dim) return;
context.report({ node: expression, messageId: 'missing', data: { dim: dim.dim } });
@@ -775,6 +879,21 @@ const disabledRecipe = {
return {
JSXAttribute: checkReference,
+ /** A constant composed into a class list a `disabled` condition chooses
+ * (`cn(busy && faded)`): its bare fades are read where it is used, while a variant dim is
+ * reported once, at the constant. The bare `className={faded}` is
+ * `checkReference`'s. */
+ Identifier(node) {
+ const { parent } = node;
+ if (!COMPOSING.has(parent.type)) return;
+ if (parent.type === 'Property' && parent.key === node && !parent.computed) return;
+ if (parent.type === 'JSXExpressionContainer' && parent.parent.type === 'JSXAttribute') {
+ return;
+ }
+ const value = constantString(node);
+ if (value === undefined || !value.includes('opacity-')) return;
+ check(node, value, node, true);
+ },
Literal(node) {
check(node, node.value);
},
diff --git a/scripts/eslint/design.test.mjs b/scripts/eslint/design.test.mjs
index 4824f57538..c2a691a8f4 100644
--- a/scripts/eslint/design.test.mjs
+++ b/scripts/eslint/design.test.mjs
@@ -34,6 +34,9 @@ tester.run('design/disabled-recipe', design.rules['disabled-recipe'], {
"import { clsx } from 'clsx'; clsx('disabled:opacity-50', disabledFillClasses)",
"<input disabled={busy} className={cn('disabled:opacity-50', busy && disabledFillClasses)} />",
"const faded = 'opacity-50 theme-disabled:opacity-100'; <button disabled className={faded} />",
+ "const faded = 'opacity-50 theme-disabled:opacity-100'; <button className={cn(disabled && faded)} disabled={disabled} />",
+ "cn('disabled:hover:opacity-50', 'theme-disabled:hover:opacity-100')",
+ "cn('disabled:opacity-50', { ...{ [disabledFillClasses]: true } })",
{
code: 'import Button from \'./Button\'; <Button className="disabled:opacity-80" />',
filename: '/repo/packages/client/src/components/Dialog.tsx',
@@ -103,6 +106,40 @@ tester.run('design/disabled-recipe', design.rules['disabled-recipe'], {
"cn('[&:not(:disabled)]:opacity-50')",
"cn(isNotDisabled && 'opacity-50')",
"cn({ 'opacity-50': props.nonDisabled })",
+ "cn('md:disabled:opacity-50', 'md:theme-disabled:opacity-100')",
+ "cn('md:disabled:opacity-50', 'theme-disabled:opacity-100')",
+ "cn('md:hover:disabled:opacity-50 hover:md:theme-disabled:opacity-100')",
+ "cn(disabled && 'md:opacity-50', 'md:theme-disabled:opacity-100')",
+ "cn('md:peer-disabled:opacity-70', 'md:peer-theme-disabled:opacity-100')",
+ "import { cva } from 'class-variance-authority'; cva(disabledFillClasses, { variants: { size: { sm: 'disabled:opacity-50' } } })",
+ "cn('disabled:opacity-50', ...[disabledFillClasses])",
+ "cn('disabled:opacity-50', ...([disabledFillClasses] as const))",
+ "cn('disabled:opacity-50', ...([disabledFillClasses] satisfies string[]))",
+ "cn('disabled:opacity-50', { ...({ [disabledFillClasses]: true } as const) })",
+ "cn('disabled:opacity-50', { [disabledFillClasses]: true as const })",
+ "cn('disabled:opacity-50', { [disabledFillClasses]: true, [other]: busy, 'px-2': true })",
+ "cn('disabled:opacity-50', { [disabledFillClasses]: true, ...{ 'px-2': true } })",
+ "cn('[.foo_&]:disabled:opacity-50', 'theme-disabled:opacity-100!')",
+ "cn('[.foo_&]:[.bar_&]:disabled:opacity-50', '[.bar_&]:[.foo_&]:theme-disabled:opacity-100')",
+ "cn('[&:hover]:disabled:opacity-50')",
+ "cn('[@media(hover:hover)]:disabled:opacity-50')",
+ "cn('[&:disabled:hover]:opacity-50')",
+ "cn('[&:not(:disabled)]:hover:opacity-50 [&:disabled:hover]:opacity-50')",
+ "cn(disabled && '[.foo_&]:opacity-50')",
+ "cn('[&[data-disabled=true]]:opacity-50', disabledFillClasses)",
+ 'cn("[&[data-disabled=\'true\']]:opacity-50", disabledFillClasses)',
+ "cn('[&[aria-disabled=true]]:opacity-50', disabledFillClasses)",
+ 'cn(\'[&[aria-disabled="true"]]:opacity-50\', disabledFillClasses)',
+ "const faded = 'opacity-50'; cn(busy && faded, busy && disabledFillClasses)",
+ "const faded = 'opacity-50'; cn(faded)",
+ "cn('[&:is(:disabled)]:opacity-50 [&:where(:disabled)]:opacity-40', disabledFillClasses)",
+ "cn((a || b) && 'opacity-50', (a || b) && disabledFillClasses)",
+ "const faded = 'opacity-50'; <button disabled={busy} className={faded} />",
+ "const faded = 'opacity-50'; <button disabled={busy} className={cn(busy ? faded : '', disabledFillClasses)} />",
+ {
+ code: '<Button className="disabled:opacity-80 peer-disabled:opacity-70 peer-theme-disabled:opacity-100" />',
+ options: [{ primitives: ['Button'] }],
+ },
],
invalid: [
{
@@ -178,6 +215,34 @@ tester.run('design/disabled-recipe', design.rules['disabled-recipe'], {
code: "cn('data-[state=disabled]:opacity-50')",
errors: [missing('data-[state=disabled]:opacity-50')],
},
+ {
+ code: "cn('hover:[&_button]:disabled:opacity-50', '[&_button]:hover:theme-disabled:opacity-100')",
+ errors: [missing('hover:[&_button]:disabled:opacity-50')],
+ },
+ {
+ code: "cn('[&_button]:disabled:opacity-50', 'theme-disabled:[&_button]:opacity-100')",
+ errors: [missing('[&_button]:disabled:opacity-50')],
+ },
+ {
+ code: "cn('*:disabled:opacity-50', 'theme-disabled:*:opacity-100')",
+ errors: [missing('*:disabled:opacity-50')],
+ },
+ {
+ code: "cn('[&[data-disabled=true]]:opacity-50')",
+ errors: [missing('[&[data-disabled=true]]:opacity-50')],
+ },
+ {
+ code: 'cn("[&[data-disabled=\'true\']]:opacity-50")',
+ errors: [missing("[&[data-disabled='true']]:opacity-50")],
+ },
+ {
+ code: "cn('[&[aria-disabled=true]]:opacity-50')",
+ errors: [missing('[&[aria-disabled=true]]:opacity-50')],
+ },
+ {
+ code: 'cn(\'[&[aria-disabled="true"]]:opacity-50\')',
+ errors: [missing('[&[aria-disabled="true"]]:opacity-50')],
+ },
{
code: "cn('[&:disabled]:opacity-40')",
errors: [missing('[&:disabled]:opacity-40')],
@@ -398,6 +463,71 @@ tester.run('design/disabled-recipe', design.rules['disabled-recipe'], {
code: "<button disabled={importMutation.isLoading} className={cn('px-2', importMutation.isLoading && 'cursor-wait opacity-50')} />",
errors: [missing('opacity-50')],
},
+ {
+ code: "const faded = 'opacity-50'; <button disabled={busy} className={cn(busy && faded)} />",
+ errors: [missing('opacity-50')],
+ },
+ {
+ code: "const faded = 'opacity-50'; <button disabled={busy} className={cn(busy ? faded : '')} />",
+ errors: [missing('opacity-50')],
+ },
+ {
+ code: "const faded = 'opacity-50' as const; <button disabled={busy} className={cn(busy && faded)} />",
+ errors: [missing('opacity-50')],
+ },
+ {
+ code: "const faded = 'opacity-50' satisfies string; <button disabled className={faded} />",
+ errors: [missing('opacity-50')],
+ },
+ {
+ code: "cn('md:disabled:opacity-50', 'lg:theme-disabled:opacity-100')",
+ errors: [missing('md:disabled:opacity-50')],
+ },
+ {
+ code: "cn('disabled:opacity-50', 'md:theme-disabled:opacity-100')",
+ errors: [missing('disabled:opacity-50')],
+ },
+ {
+ code: "const cva = (base) => base; cva(disabledFillClasses, { variants: { size: { sm: 'disabled:opacity-50' } } })",
+ errors: [missing('disabled:opacity-50')],
+ },
+ {
+ code: "cn('disabled:opacity-50', [...disabledFillClasses])",
+ errors: [missing('disabled:opacity-50')],
+ },
+ {
+ code: "cn('disabled:opacity-50', [...(disabledFillClasses as string)])",
+ errors: [missing('disabled:opacity-50')],
+ },
+ {
+ code: "cn('disabled:opacity-50', { ...{ [disabledFillClasses]: true }, [disabledFillClasses]: false })",
+ errors: [missing('disabled:opacity-50')],
+ },
+ {
+ code: "cn('disabled:opacity-50', { [disabledFillClasses]: true, [disabledFillClasses]: busy })",
+ errors: [missing('disabled:opacity-50')],
+ },
+ {
+ code: "cn('disabled:opacity-50', { [disabledFillClasses]: true, ...overrides })",
+ errors: [missing('disabled:opacity-50')],
+ },
+ {
+ code: "cn('disabled:opacity-50', { [disabledFillClasses]: true, ...{ [disabledFillClasses]: false } })",
+ errors: [missing('disabled:opacity-50')],
+ },
+ {
+ code: "cn('disabled:opacity-50', { [disabledFillClasses]: true, ...{ ...overrides } })",
+ errors: [missing('disabled:opacity-50')],
+ },
+ {
+ code: "cn('disabled:opacity-50', { 'theme-disabled:opacity-100': true, ['theme-disabled:opacity-100']: false })",
+ errors: [missing('disabled:opacity-50')],
+ },
+ {
+ code: '<Button className="disabled:opacity-80 peer-disabled:opacity-70" />',
+ options: [{ primitives: ['Button'] }],
+ errors: [missing('peer-disabled:opacity-70')],
+ },
{
code: "<button disabled={!canOpenDetails} className={cn(canOpenDetails ? 'hover:bg-surface-hover' : 'opacity-50')} />",
errors: [missing('opacity-50')],