🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
chore(web): Setup eslint rule `no-margin-on-root-elements` (#14560)
Ben Bacheme281df4a611b
diff --git a/packages/eslint-plugin/src/index.ts b/packages/eslint-plugin/src/index.tsindex 86a8ecef2a..c1e92bae4f 100644--- a/packages/eslint-plugin/src/index.ts+++ b/packages/eslint-plugin/src/index.ts@@ -1,5 +1,6 @@import { default as noTailwindOverflowScroll } from "./rules/no-tailwind-overflow-scroll.js";import { default as noInSourceVitest } from "./rules/no-in-source-vitest.js";+import { default as noMarginOnRootElements } from "./rules/no-margin-on-root-elements.js";import { default as noOverlayZindex } from "./rules/no-overlay-zindex.js";import { default as noStyleProps } from "./rules/no-style-props.js";import { default as noUnnecessaryCn } from "./rules/no-unnecessary-cn.js";@@ -7,6 +8,7 @@ import { default as noUnnecessaryCn } from "./rules/no-unnecessary-cn.js";export const plugin = {rules: {"no-in-source-vitest": noInSourceVitest,+ "no-margin-on-root-elements": noMarginOnRootElements,"no-overlay-zindex": noOverlayZindex,"no-style-props": noStyleProps,"no-tailwind-overflow-scroll": noTailwindOverflowScroll,diff --git a/packages/eslint-plugin/src/component-prop-types.ts b/packages/eslint-plugin/src/react-components.tssimilarity index 66%rename from packages/eslint-plugin/src/component-prop-types.tsrename to packages/eslint-plugin/src/react-components.tsindex dea1caf827..770365d91f 100644--- a/packages/eslint-plugin/src/component-prop-types.ts+++ b/packages/eslint-plugin/src/react-components.ts@@ -5,6 +5,10 @@ type PropTypeCallbacks = {onDestructuredProp?: (node: TSESTree.Property) => void;};+type RootElementCallbacks = {+ onRootElement: (node: TSESTree.JSXElement) => void;+};+const REACT_COMPONENT_TYPES = new Set(["FC","FunctionComponent",@@ -48,14 +52,21 @@ function expressionReturnsJsxOrNull(switch (node.type) {case AST_NODE_TYPES.ConditionalExpression:- return [node.consequent, node.alternate].some(expressionReturnsJsxOrNull);+ return (+ expressionReturnsJsxOrNull(node.consequent) ||+ expressionReturnsJsxOrNull(node.alternate)+ );case AST_NODE_TYPES.LogicalExpression:- return [node.left, node.right].some(expressionReturnsJsxOrNull);- case AST_NODE_TYPES.CallExpression:return (- isReactCreateElementCall(node) ||- node.arguments.some((argument) => expressionReturnsJsxOrNull(argument))+ expressionReturnsJsxOrNull(node.left) ||+ expressionReturnsJsxOrNull(node.right));+ case AST_NODE_TYPES.CallExpression:+ if (isReactCreateElementCall(node)) return true;+ for (const argument of node.arguments) {+ if (expressionReturnsJsxOrNull(argument)) return true;+ }+ return false;case AST_NODE_TYPES.ArrowFunctionExpression:case AST_NODE_TYPES.FunctionExpression:return functionReturnsJsxOrNull(node);@@ -69,6 +80,98 @@ function expressionReturnsJsxOrNull(}}+function visitRootElementsInExpression(+ node: TSESTree.Node | null | undefined,+ callbacks: RootElementCallbacks,+): void {+ if (!node) return;++ switch (node.type) {+ case AST_NODE_TYPES.JSXElement:+ callbacks.onRootElement(node);+ return;+ case AST_NODE_TYPES.JSXFragment:+ for (const child of node.children) {+ if (child.type === AST_NODE_TYPES.JSXElement) {+ callbacks.onRootElement(child);+ } else if (child.type === AST_NODE_TYPES.JSXFragment) {+ visitRootElementsInExpression(child, callbacks);+ } else if (child.type === AST_NODE_TYPES.JSXExpressionContainer) {+ visitRootElementsInExpression(child.expression, callbacks);+ }+ }+ return;+ case AST_NODE_TYPES.ConditionalExpression:+ visitRootElementsInExpression(node.consequent, callbacks);+ visitRootElementsInExpression(node.alternate, callbacks);+ return;+ case AST_NODE_TYPES.LogicalExpression:+ visitRootElementsInExpression(node.left, callbacks);+ visitRootElementsInExpression(node.right, callbacks);+ return;+ case AST_NODE_TYPES.TSAsExpression:+ case AST_NODE_TYPES.TSNonNullExpression:+ case AST_NODE_TYPES.TSSatisfiesExpression:+ visitRootElementsInExpression(node.expression, callbacks);+ return;+ default:+ return;+ }+}++function visitRootElementsInStatement(+ statement: TSESTree.Statement | null | undefined,+ callbacks: RootElementCallbacks,+): void {+ if (!statement) return;++ switch (statement.type) {+ case AST_NODE_TYPES.ReturnStatement:+ visitRootElementsInExpression(statement.argument, callbacks);+ return;+ case AST_NODE_TYPES.BlockStatement:+ for (const child of statement.body) {+ visitRootElementsInStatement(child, callbacks);+ }+ return;+ case AST_NODE_TYPES.IfStatement:+ visitRootElementsInStatement(statement.consequent, callbacks);+ visitRootElementsInStatement(statement.alternate, callbacks);+ return;+ case AST_NODE_TYPES.SwitchStatement:+ for (const switchCase of statement.cases) {+ for (const child of switchCase.consequent) {+ visitRootElementsInStatement(child, callbacks);+ }+ }+ return;+ case AST_NODE_TYPES.TryStatement:+ visitRootElementsInStatement(statement.block, callbacks);+ visitRootElementsInStatement(statement.handler?.body, callbacks);+ visitRootElementsInStatement(statement.finalizer, callbacks);+ return;+ default:+ return;+ }+}++function visitRootElementsInFunction(+ node:+ | TSESTree.ArrowFunctionExpression+ | TSESTree.FunctionDeclaration+ | TSESTree.FunctionExpression,+ callbacks: RootElementCallbacks,+): void {+ if (node.type === AST_NODE_TYPES.ArrowFunctionExpression && node.expression) {+ visitRootElementsInExpression(node.body, callbacks);+ return;+ }++ for (const statement of (node.body as TSESTree.BlockStatement).body) {+ visitRootElementsInStatement(statement, callbacks);+ }+}+function statementReturnsJsxOrNull(statement: TSESTree.Statement | null | undefined,): boolean {@@ -77,21 +180,28 @@ function statementReturnsJsxOrNull(case AST_NODE_TYPES.ReturnStatement:return expressionReturnsJsxOrNull(statement.argument);case AST_NODE_TYPES.BlockStatement:- return statement.body.some(statementReturnsJsxOrNull);+ for (const child of statement.body) {+ if (statementReturnsJsxOrNull(child)) return true;+ }+ return false;case AST_NODE_TYPES.IfStatement:- return [statement.consequent, statement.alternate].some(- statementReturnsJsxOrNull,+ return (+ statementReturnsJsxOrNull(statement.consequent) ||+ statementReturnsJsxOrNull(statement.alternate));case AST_NODE_TYPES.SwitchStatement:- return statement.cases.some((switchCase) =>- switchCase.consequent.some(statementReturnsJsxOrNull),- );+ for (const switchCase of statement.cases) {+ for (const child of switchCase.consequent) {+ if (statementReturnsJsxOrNull(child)) return true;+ }+ }+ return false;case AST_NODE_TYPES.TryStatement:- return [- statement.block,- statement.handler?.body,- statement.finalizer,- ].some(statementReturnsJsxOrNull);+ return (+ statementReturnsJsxOrNull(statement.block) ||+ statementReturnsJsxOrNull(statement.handler?.body) ||+ statementReturnsJsxOrNull(statement.finalizer)+ );default:return false;}@@ -107,9 +217,10 @@ function functionReturnsJsxOrNull(return expressionReturnsJsxOrNull(node.body);}- return (node.body as TSESTree.BlockStatement).body.some(- statementReturnsJsxOrNull,- );+ for (const statement of (node.body as TSESTree.BlockStatement).body) {+ if (statementReturnsJsxOrNull(statement)) return true;+ }+ return false;}function getTypeName(typeName: TSESTree.EntityName): string | null {@@ -202,6 +313,41 @@ function unwrapComponentInit(node: TSESTree.Node): TSESTree.Node {return current;}+export function createComponentRootElementVisitors(+ callbacks: RootElementCallbacks,+) {+ function maybeVisitFunctionComponentRoots(+ node:+ | TSESTree.ArrowFunctionExpression+ | TSESTree.FunctionDeclaration+ | TSESTree.FunctionExpression,+ name: string | null,+ ): void {+ if (name && !isCapitalizedName(name)) return;+ if (!functionReturnsJsxOrNull(node)) return;+ visitRootElementsInFunction(node, callbacks);+ }++ return {+ FunctionDeclaration(node: TSESTree.FunctionDeclaration) {+ maybeVisitFunctionComponentRoots(node, node.id?.name ?? null);+ },+ VariableDeclarator(node: TSESTree.VariableDeclarator) {+ if (node.id.type !== AST_NODE_TYPES.Identifier) return;+ if (!isCapitalizedName(node.id.name)) return;+ if (!node.init) return;++ const init = unwrapComponentInit(node.init);+ if (+ init.type === AST_NODE_TYPES.ArrowFunctionExpression ||+ init.type === AST_NODE_TYPES.FunctionExpression+ ) {+ maybeVisitFunctionComponentRoots(init, node.id.name);+ }+ },+ };+}+function getWrappedForwardRefPropsType(node: TSESTree.Node,): TSESTree.TypeNode | null {@@ -239,11 +385,11 @@ function visitDestructuredProps(): void {const firstParam = node.params[0];if (firstParam?.type !== AST_NODE_TYPES.ObjectPattern) return;- firstParam.properties.forEach((property) => {+ for (const property of firstParam.properties) {if (property.type === AST_NODE_TYPES.Property) {callbacks.onDestructuredProp?.(property);}- });+ }}export function createComponentPropTypeVisitors(callbacks: PropTypeCallbacks) {@@ -263,15 +409,17 @@ export function createComponentPropTypeVisitors(callbacks: PropTypeCallbacks) {): void {switch (node.type) {case AST_NODE_TYPES.TSTypeLiteral:- node.members.forEach((member) => {+ for (const member of node.members) {if (member.type === AST_NODE_TYPES.TSPropertySignature) {callbacks.onPropProperty(member);}- });+ }return;case AST_NODE_TYPES.TSIntersectionType:case AST_NODE_TYPES.TSUnionType:- node.types.forEach((type) => visitTypeNode(type, seen));+ for (const type of node.types) {+ visitTypeNode(type, seen);+ }return;case AST_NODE_TYPES.TSTypeReference: {const typeName = getTypeName(node.typeName);@@ -308,19 +456,19 @@ export function createComponentPropTypeVisitors(callbacks: PropTypeCallbacks) {seen: Set<string>,): void {if (declaration.type === AST_NODE_TYPES.TSInterfaceDeclaration) {- declaration.body.body.forEach((member) => {+ for (const member of declaration.body.body) {if (member.type === AST_NODE_TYPES.TSPropertySignature) {callbacks.onPropProperty(member);}- });- declaration.extends?.forEach((heritage) => {+ }+ for (const heritage of declaration.extends) {const heritageTypeName = getHeritageName(heritage.expression as| TSESTree.Identifier| TSESTree.MemberExpression,);visitDeclarationByName(heritageTypeName, seen);- });+ }return;}visitTypeNode(declaration.typeAnnotation, seen);@@ -391,7 +539,9 @@ export function createComponentPropTypeVisitors(callbacks: PropTypeCallbacks) {},"Program:exit"() {const seen = new Set<string>();- propTypeRoots.forEach((typeNode) => visitTypeNode(typeNode, seen));+ for (const typeNode of propTypeRoots) {+ visitTypeNode(typeNode, seen);+ }},};}diff --git a/packages/eslint-plugin/src/rules/no-margin-on-root-elements.test.ts b/packages/eslint-plugin/src/rules/no-margin-on-root-elements.test.tsnew file mode 100644index 0000000000..9ffbc0f81f--- /dev/null+++ b/packages/eslint-plugin/src/rules/no-margin-on-root-elements.test.ts@@ -0,0 +1,263 @@+import { RuleTester } from "@typescript-eslint/rule-tester";+import * as typescriptEslintParser from "@typescript-eslint/parser";+import rule from "./no-margin-on-root-elements.js";++const ruleTester = new RuleTester({+ languageOptions: {+ parser: typescriptEslintParser,+ parserOptions: {+ ecmaFeatures: {+ jsx: true,+ },+ },+ },+});++ruleTester.run("no-margin-on-root-elements", rule, {+ valid: [+ `function Card() { return <div className="flex gap-2" />; }`,+ `function Card() { return <div style={{ color: "red" }} />; }`,+ `function Card() { return <div><span className="mt-2" /></div>; }`,+ `function Card() { return <div><span style={{ marginTop: 4 }} /></div>; }`,+ `function Card() { return <><div><span className="mt-2" /></div></>; }`,+ `function Card() { const className = "mt-2"; return <div className={className} />; }`,+ `function Card() { return <div className />; }`,+ `function Card() { return <div className={} />; }`,+ `function Card() { return <div className={styles.root} />; }`,+ `function Card() { return <div className={[styles.root]} />; }`,+ `function Card() { return <div className={cn(styles.root)} />; }`,+ `function Card() { return <div className={cn()} />; }`,+ `function Card() { return <div className={styles.cn("mt-2")} />; }`,+ `function Card() { return <div className={n("mt-2")} />; }`,+ `function Card() { return <div className={cn({ flex: isActive })} />; }`,+ `function Card() { return <div className={cn({ flex: isActive, "gap-2": hasGap })} />; }`,+ `function Card() { return <div className={cn({ [className]: isActive })} />; }`,+ `function Card() { return <div className={cn({ ...styles, flex: isActive })} />; }`,+ `function Card() { return <div className={condition && styles.root} />; }`,+ `function Card() { return <div className={"flex"!} />; }`,+ `function Card() { return <div className={"flex" satisfies string} />; }`,+ `function Card() { return <div className={condition ? "flex" : "gap-2"} />; }`,+ "function Card() { return <div className={`flex ${size}`} />; }",+ `function Card() { return <div className={[, "flex"]} />; }`,+ `function Card() { return <>text</>; }`,+ `function Card() { if (open) return <div className="flex" />; return; }`,+ `function Card({ value }: { value: string }) { switch (value) { default: return 1; } }`,+ `function Card() { return 1; }`,+ `function renderCard() { return <div className="mt-2" />; }`,+ `const card = () => <div className="mt-2" />;`,+ `const Card = () => null;`,+ `const Card = () => maybe();`,+ `const Card = () => render(1);`,+ `const Card = () => render(<div className="mt-2" />);`,+ `let Card;`,+ `const [Card] = [() => <div className="mt-2" />];`,+ `const Card = hoc;`,+ `const Card = React.createElement("div", { className: "mt-2" });`,+ `class Card extends React.Component { render() { return <div className="mt-2" />; } }`,+ `const Card = () => <div className="m" />;`,+ `const Card = () => <div className="max-w-md" />;`,+ `const Card = () => <div className="m-0 mt-0 -mx-0 md:!mb-0" />;`,+ `const Card = () => <div className="mt-[0] mb-[0px] mx-[0rem]" />;`,+ `const Card = () => <div {...props} />;`,+ `const Card = () => <div foo:bar="mt-2" />;`,+ `const Card = () => <div className=<span /> />;`,+ `const Card = () => <div style={styles.root} />;`,+ `const Card = () => <div style />;`,+ 'const Card = () => <div style={{ margin: 0, marginTop: "0", marginBottom: "0px", marginInline: `0rem` }} />;',+ `const Card = () => <div style={{ [marginProp]: 4 }} />;`,+ `const Card = () => <div style={{ ...styles.root }} />;`,+ "const Card = () => <div style={{ [`marginTop`]: 4 }} />;",+ ],+ invalid: [+ {+ code: `function Card() { return <div className="mt-2" />; }`,+ errors: [{ messageId: "unexpectedClassName", data: { utility: "mt-2" } }],+ },+ {+ code: `export default function () { return <div className="mt-2" />; }`,+ errors: [{ messageId: "unexpectedClassName", data: { utility: "mt-2" } }],+ },+ {+ code: `const Card = () => <div className="m-2" />;`,+ errors: [{ messageId: "unexpectedClassName", data: { utility: "m-2" } }],+ },+ {+ code: `const Card = () => <div className="-mx-2" />;`,+ errors: [+ { messageId: "unexpectedClassName", data: { utility: "-mx-2" } },+ ],+ },+ {+ code: `const Card = () => <div className="md:!mt-[12px]" />;`,+ errors: [+ { messageId: "unexpectedClassName", data: { utility: "mt-[12px]" } },+ ],+ },+ {+ code: `const Card = () => <div className="hover:-me-4" />;`,+ errors: [+ { messageId: "unexpectedClassName", data: { utility: "-me-4" } },+ ],+ },+ {+ code: `const Card = () => <div className="empty:m-0.5" />;`,+ errors: [+ { messageId: "unexpectedClassName", data: { utility: "m-0.5" } },+ ],+ },+ {+ code: `const Card = () => <div className={\`flex mb-2\`} />;`,+ errors: [{ messageId: "unexpectedClassName", data: { utility: "mb-2" } }],+ },+ {+ code: `const Card = () => <div className={cn("flex", condition && "mt-2")} />;`,+ errors: [{ messageId: "unexpectedClassName", data: { utility: "mt-2" } }],+ },+ {+ code: `const Card = () => <div className={clsx("flex", condition && "mt-2")} />;`,+ errors: [{ messageId: "unexpectedClassName", data: { utility: "mt-2" } }],+ },+ {+ code: `const Card = () => <div className={cn({ "mt-2": isActive })} />;`,+ errors: [{ messageId: "unexpectedClassName", data: { utility: "mt-2" } }],+ },+ {+ code: "const Card = () => <div className={cn({ [`mt-2`]: isActive })} />;",+ errors: [{ messageId: "unexpectedClassName", data: { utility: "mt-2" } }],+ },+ {+ code: `const Card = () => <div className={n("flex", condition && "mt-2")} />;`,+ options: [{ classNameFunctions: ["cn", "clsx", "n"] }],+ errors: [{ messageId: "unexpectedClassName", data: { utility: "mt-2" } }],+ },+ {+ code: `const Card = () => <div className={cx("flex", condition && "mt-2")} />;`,+ options: [{ classNameFunctions: ["cx"] }],+ errors: [{ messageId: "unexpectedClassName", data: { utility: "mt-2" } }],+ },+ {+ code: `const Card = () => <div className={["flex", "mt-2"]} />;`,+ errors: [{ messageId: "unexpectedClassName", data: { utility: "mt-2" } }],+ },+ {+ code: `const Card = () => <div className={condition ? "mt-2" : "flex"} />;`,+ errors: [{ messageId: "unexpectedClassName", data: { utility: "mt-2" } }],+ },+ {+ code: `const Card = () => <div className={("mt-2" as string)} />;`,+ errors: [{ messageId: "unexpectedClassName", data: { utility: "mt-2" } }],+ },+ {+ code: `const Card = () => <div className={("mt-2"!)} />;`,+ errors: [{ messageId: "unexpectedClassName", data: { utility: "mt-2" } }],+ },+ {+ code: `const Card = () => <div className={("mt-2" satisfies string)} />;`,+ errors: [{ messageId: "unexpectedClassName", data: { utility: "mt-2" } }],+ },+ {+ code: `const Card = () => condition ? <div className="mt-2" /> : <span />;`,+ errors: [{ messageId: "unexpectedClassName", data: { utility: "mt-2" } }],+ },+ {+ code: `const Card = () => condition ? 1 : <div className="mt-2" />;`,+ errors: [{ messageId: "unexpectedClassName", data: { utility: "mt-2" } }],+ },+ {+ code: `const Card = () => condition && <div className="mt-2" />;`,+ errors: [{ messageId: "unexpectedClassName", data: { utility: "mt-2" } }],+ },+ {+ code: `const Card = () => <><div className="mt-2" /><span /></>;`,+ errors: [{ messageId: "unexpectedClassName", data: { utility: "mt-2" } }],+ },+ {+ code: `const Card = () => <><><div className="mt-2" /></></>;`,+ errors: [{ messageId: "unexpectedClassName", data: { utility: "mt-2" } }],+ },+ {+ code: `const Card = () => <>{condition && <div className="mt-2" />}</>;`,+ errors: [{ messageId: "unexpectedClassName", data: { utility: "mt-2" } }],+ },+ {+ code: `const Card = () => <>{condition ? <div className="mt-2" /> : <span />}</>;`,+ errors: [{ messageId: "unexpectedClassName", data: { utility: "mt-2" } }],+ },+ {+ code: `const Card = () => (<div className="mt-2" />)!;`,+ errors: [{ messageId: "unexpectedClassName", data: { utility: "mt-2" } }],+ },+ {+ code: `const Card = () => <div className="mt-2" /> satisfies React.ReactNode;`,+ errors: [{ messageId: "unexpectedClassName", data: { utility: "mt-2" } }],+ },+ {+ code: `const Card = () => <div className="mt-2" /> as React.ReactNode;`,+ errors: [{ messageId: "unexpectedClassName", data: { utility: "mt-2" } }],+ },+ {+ code: `function Card({ open }: { open: boolean }) { if (open) return <div className="mt-2" />; return null; }`,+ errors: [{ messageId: "unexpectedClassName", data: { utility: "mt-2" } }],+ },+ {+ code: `function Card({ open }: { open: boolean }) { if (open) return <div className="mt-2" />; }`,+ errors: [{ messageId: "unexpectedClassName", data: { utility: "mt-2" } }],+ },+ {+ code: `function Card({ value }: { value: string }) { switch (value) { case "a": return <div className="mt-2" />; default: return null; } }`,+ errors: [{ messageId: "unexpectedClassName", data: { utility: "mt-2" } }],+ },+ {+ code: `function Card() { try { return <div className="mt-2" />; } catch { return null; } }`,+ errors: [{ messageId: "unexpectedClassName", data: { utility: "mt-2" } }],+ },+ {+ code: `function Card() { try { return 1; } catch { return <div className="mt-2" />; } }`,+ errors: [{ messageId: "unexpectedClassName", data: { utility: "mt-2" } }],+ },+ {+ code: `function Card() { try { return 1; } finally { return <div className="mt-2" />; } }`,+ errors: [{ messageId: "unexpectedClassName", data: { utility: "mt-2" } }],+ },+ {+ code: `const Card = memo(() => <div className="mt-2" />);`,+ errors: [{ messageId: "unexpectedClassName", data: { utility: "mt-2" } }],+ },+ {+ code: `const Card = forwardRef<HTMLDivElement, Props>(() => <div className="mt-2" />);`,+ errors: [{ messageId: "unexpectedClassName", data: { utility: "mt-2" } }],+ },+ {+ code: `function Card() { return <div style={{ marginTop: 4 }} />; }`,+ errors: [+ {+ messageId: "unexpectedStyle",+ data: { propertyName: "marginTop" },+ },+ ],+ },+ {+ code: `function Card() { return <div style={{ "margin-block-start": 4, marginInline: 8 }} />; }`,+ errors: [+ {+ messageId: "unexpectedStyle",+ data: { propertyName: "margin-block-start" },+ },+ {+ messageId: "unexpectedStyle",+ data: { propertyName: "marginInline" },+ },+ ],+ },+ {+ code: `function Card() { return <div style={{ margin: 4, marginBottom: 8 }} />; }`,+ errors: [+ { messageId: "unexpectedStyle", data: { propertyName: "margin" } },+ {+ messageId: "unexpectedStyle",+ data: { propertyName: "marginBottom" },+ },+ ],+ },+ ],+});diff --git a/packages/eslint-plugin/src/rules/no-margin-on-root-elements.ts b/packages/eslint-plugin/src/rules/no-margin-on-root-elements.tsnew file mode 100644index 0000000000..2aeade42a2--- /dev/null+++ b/packages/eslint-plugin/src/rules/no-margin-on-root-elements.ts@@ -0,0 +1,331 @@+import { AST_NODE_TYPES, type TSESTree } from "@typescript-eslint/utils";++import { createComponentRootElementVisitors } from "../react-components.js";+import { createRule } from "../util.js";++const FORBIDDEN_STYLE_PROPERTIES = new Set([+ "margin",+ "margin-block",+ "margin-block-end",+ "margin-block-start",+ "marginBlock",+ "marginBlockEnd",+ "marginBlockStart",+ "marginBottom",+ "margin-bottom",+ "margin-inline",+ "margin-inline-end",+ "margin-inline-start",+ "marginInline",+ "marginInlineEnd",+ "marginInlineStart",+ "marginLeft",+ "margin-left",+ "marginRight",+ "margin-right",+ "marginTop",+ "margin-top",+]);++const TAILWIND_TOKEN_RE = /\S+/g;+const MARGIN_UTILITY_RE = /^(-?m[trblxyse]?)-(.+)$/;+const ZERO_CSS_VALUE_RE = /^-?0(?:\.0+)?(?:%|[a-z]+)?$/i;+const DEFAULT_CLASS_NAME_FUNCTIONS = ["cn", "clsx"];++type Options = [{ classNameFunctions: string[] }];+type MessageIds = "unexpectedClassName" | "unexpectedStyle";++function normalizeTailwindToken(token: string): string {+ return token.replace(/^!|!$/g, "");+}++function stripVariants(token: string): string {+ let depth = 0;+ let lastSeparator = -1;++ for (let i = 0; i < token.length; i++) {+ const ch = token[i];+ if (ch === "[") depth++;+ else if (ch === "]") depth = Math.max(0, depth - 1);+ else if (ch === ":" && depth === 0) lastSeparator = i;+ }++ return lastSeparator === -1 ? token : token.slice(lastSeparator + 1);+}++function isZeroCssValue(value: string): boolean {+ return ZERO_CSS_VALUE_RE.test(value.trim());+}++function getReportableMarginUtility(rawToken: string): string | null {+ const utility = normalizeTailwindToken(stripVariants(rawToken));+ const match = MARGIN_UTILITY_RE.exec(utility);+ if (!match) return null;++ const value = match[2];+ if (value === "0") return null;+ if (value.startsWith("[") && value.endsWith("]")) {+ return isZeroCssValue(value.slice(1, -1)) ? null : utility;+ }++ return utility;+}++function getStaticStringValue(+ node: TSESTree.Expression | TSESTree.SpreadElement,+): string | null {+ if (node.type === AST_NODE_TYPES.Literal && typeof node.value === "string") {+ return node.value;+ }++ if (+ node.type === AST_NODE_TYPES.TemplateLiteral &&+ node.expressions.length === 0+ ) {+ return node.quasis[0].value.cooked;+ }++ return null;+}++function getCallExpressionName(node: TSESTree.CallExpression): string | null {+ return node.callee.type === AST_NODE_TYPES.Identifier+ ? node.callee.name+ : null;+}++function getStaticPropertyKeyValue(+ key: TSESTree.PropertyName | TSESTree.PrivateIdentifier,+): string | null {+ if (key.type === AST_NODE_TYPES.Literal && typeof key.value === "string") {+ return key.value;+ }++ if (+ key.type === AST_NODE_TYPES.TemplateLiteral &&+ key.expressions.length === 0+ ) {+ return key.quasis[0].value.cooked;+ }++ return null;+}++function findReportableMarginUtilityInExpression(+ node: TSESTree.Expression | TSESTree.SpreadElement,+ classNameFunctions: Set<string>,+): string | null {+ const value = getStaticStringValue(node);+ if (value !== null) {+ return findReportableMarginUtility(value);+ }++ switch (node.type) {+ case AST_NODE_TYPES.ArrayExpression: {+ for (const element of node.elements) {+ if (!element) continue;+ const utility = findReportableMarginUtilityInExpression(+ element,+ classNameFunctions,+ );+ if (utility !== null) return utility;+ }+ return null;+ }+ case AST_NODE_TYPES.CallExpression: {+ const functionName = getCallExpressionName(node);+ if (!functionName || !classNameFunctions.has(functionName)) return null;++ for (const argument of node.arguments) {+ const utility = findReportableMarginUtilityInExpression(+ argument,+ classNameFunctions,+ );+ if (utility !== null) return utility;+ }+ return null;+ }+ case AST_NODE_TYPES.ObjectExpression: {+ for (const property of node.properties) {+ if (property.type !== AST_NODE_TYPES.Property) continue;+ const key = getStaticPropertyKeyValue(property.key);+ if (!key) continue;+ const utility = findReportableMarginUtility(key);+ if (utility !== null) return utility;+ }+ return null;+ }+ case AST_NODE_TYPES.ConditionalExpression:+ return (+ findReportableMarginUtilityInExpression(+ node.consequent,+ classNameFunctions,+ ) ??+ findReportableMarginUtilityInExpression(+ node.alternate,+ classNameFunctions,+ )+ );+ case AST_NODE_TYPES.LogicalExpression:+ return (+ findReportableMarginUtilityInExpression(+ node.left,+ classNameFunctions,+ ) ??+ findReportableMarginUtilityInExpression(node.right, classNameFunctions)+ );+ case AST_NODE_TYPES.TSAsExpression:+ case AST_NODE_TYPES.TSNonNullExpression:+ case AST_NODE_TYPES.TSSatisfiesExpression:+ return findReportableMarginUtilityInExpression(+ node.expression,+ classNameFunctions,+ );+ default:+ return null;+ }+}++function getReportableClassNameMarginUtility(+ attribute: TSESTree.JSXAttribute,+ classNameFunctions: Set<string>,+): string | null {+ const value = attribute.value;+ if (!value) return null;++ if (+ value.type === AST_NODE_TYPES.Literal &&+ typeof value.value === "string"+ ) {+ return findReportableMarginUtility(value.value);+ }++ if (value.type !== AST_NODE_TYPES.JSXExpressionContainer) return null;+ const expression = value.expression;+ if (expression.type === AST_NODE_TYPES.JSXEmptyExpression) return null;++ return findReportableMarginUtilityInExpression(+ expression,+ classNameFunctions,+ );+}++function getPropertyName(+ key: TSESTree.PropertyName | TSESTree.PrivateIdentifier,+): string | null {+ if (key.type === AST_NODE_TYPES.Identifier) return key.name;+ if (key.type === AST_NODE_TYPES.Literal && typeof key.value === "string") {+ return key.value;+ }+ return null;+}++function isZeroStyleValue(node: TSESTree.Node): boolean {+ if (node.type === AST_NODE_TYPES.Literal) {+ if (node.value === 0) return true;+ if (typeof node.value === "string") return isZeroCssValue(node.value);+ }++ if (+ node.type === AST_NODE_TYPES.TemplateLiteral &&+ node.expressions.length === 0+ ) {+ const cooked = node.quasis[0].value.cooked;+ return cooked !== null && isZeroCssValue(cooked);+ }++ return false;+}++function findReportableMarginUtility(value: string): string | null {+ for (const match of value.matchAll(TAILWIND_TOKEN_RE)) {+ const utility = getReportableMarginUtility(match[0]);+ if (utility) return utility;+ }+ return null;+}++const rule = createRule<Options, MessageIds>({+ name: "no-margin-on-root-elements",+ meta: {+ type: "problem",+ docs: {+ description:+ "Disallow margin styles on component root elements. Parent layout components should own spacing between siblings.",+ },+ schema: [+ {+ type: "object",+ additionalProperties: false,+ required: ["classNameFunctions"],+ properties: {+ classNameFunctions: {+ type: "array",+ items: { type: "string", minLength: 1 },+ uniqueItems: true,+ },+ },+ },+ ],+ messages: {+ unexpectedClassName:+ "Avoid margin utility `{{utility}}` on a component root element. Margin should be owned by the parent layout component.",+ unexpectedStyle:+ "Avoid `{{propertyName}}` on a component root element. Margin should be owned by the parent layout component.",+ },+ },+ defaultOptions: [{ classNameFunctions: DEFAULT_CLASS_NAME_FUNCTIONS }],+ create(context, [{ classNameFunctions }]) {+ const classNameFunctionNames = new Set(classNameFunctions);++ function checkClassName(attribute: TSESTree.JSXAttribute): void {+ const utility = getReportableClassNameMarginUtility(+ attribute,+ classNameFunctionNames,+ );+ if (!utility) return;++ context.report({+ node: attribute,+ messageId: "unexpectedClassName",+ data: { utility },+ });+ }++ function checkStyle(attribute: TSESTree.JSXAttribute): void {+ const value = attribute.value;+ if (value?.type !== AST_NODE_TYPES.JSXExpressionContainer) return;+ const expression = value.expression;+ if (expression.type !== AST_NODE_TYPES.ObjectExpression) return;++ for (const property of expression.properties) {+ if (property.type !== AST_NODE_TYPES.Property) continue;+ const propertyName = getPropertyName(property.key);+ if (!propertyName || !FORBIDDEN_STYLE_PROPERTIES.has(propertyName)) {+ continue;+ }+ if (isZeroStyleValue(property.value)) continue;++ context.report({+ node: property.key,+ messageId: "unexpectedStyle",+ data: { propertyName },+ });+ }+ }++ return createComponentRootElementVisitors({+ onRootElement(node) {+ for (const attribute of node.openingElement.attributes) {+ if (attribute.type !== AST_NODE_TYPES.JSXAttribute) continue;+ if (attribute.name.type !== AST_NODE_TYPES.JSXIdentifier) continue;++ if (attribute.name.name === "className") checkClassName(attribute);+ if (attribute.name.name === "style") checkStyle(attribute);+ }+ },+ });+ },+});++export default rule;diff --git a/packages/eslint-plugin/src/rules/no-style-props.test.ts b/packages/eslint-plugin/src/rules/no-style-props.test.tsindex 41596e1c96..72d3c6b234 100644--- a/packages/eslint-plugin/src/rules/no-style-props.test.ts+++ b/packages/eslint-plugin/src/rules/no-style-props.test.ts@@ -63,6 +63,11 @@ ruleTester.run("no-style-props", rule, {`const Button = forwardRef((props: { variant?: "primary" }) => <div />);`,`interface ButtonProps extends React.ButtonHTMLAttributes<HTMLButtonElement> { variant?: "primary"; }function Button(props: ButtonProps) { return <div />; }`,+ `interface ButtonProps {}+ function Button(props: ButtonProps) { return <div />; }`,+ `interface BaseProps { variant?: "primary"; }+ interface ButtonProps extends BaseProps { size?: "sm"; }+ const Button = (props: ButtonProps) => <div />;`,],invalid: [{diff --git a/packages/eslint-plugin/src/rules/no-style-props.ts b/packages/eslint-plugin/src/rules/no-style-props.tsindex 03ba1113d1..71a89d226f 100644--- a/packages/eslint-plugin/src/rules/no-style-props.ts+++ b/packages/eslint-plugin/src/rules/no-style-props.ts@@ -1,5 +1,5 @@import { AST_NODE_TYPES, type TSESTree } from "@typescript-eslint/utils";-import { createComponentPropTypeVisitors } from "../component-prop-types.js";+import { createComponentPropTypeVisitors } from "../react-components.js";import { createRule } from "../util.js";const FORBIDDEN_PROP_NAMES = new Set(["className", "style"]);diff --git a/web/eslint.config.mjs b/web/eslint.config.mjsindex 88be286506..629395db16 100644--- a/web/eslint.config.mjs+++ b/web/eslint.config.mjs@@ -72,13 +72,21 @@ export default [},},- // Design-system component APIs must use explicit variants instead of styling escape hatches.{- name: "langfuse/web/design-system-no-style-props",+ name: "langfuse/web/design-system-rules",files: ["src/components/design-system/**/*.{ts,tsx}"],ignores: ["src/components/design-system/**/*.stories.tsx"],rules: {+ // Design-system component APIs must use explicit variants instead of styling escape hatches."@repo/no-style-props": "error",++ // Margin makes components harder to compose and should therefore be applied by the parent.+ // See: https://mxstbr.com/thoughts/margin for a discussion of this pattern.+ // TODO: Consider expanding this rule beyond design-system components+ "@repo/no-margin-on-root-elements": [+ "warn",+ { classNameFunctions: ["cn", "clsx"] },+ ],},},