Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat(scripts): check:ui-outlines catches focus rings outline-none cancels (MUL-9983) (#11323)
Jiayuan Zhang733727820abe
diff --git a/.github/actions/frontend-quality/action.yml b/.github/actions/frontend-quality/action.ymlindex ef73ea2cd1..dd4dc0726b 100644--- a/.github/actions/frontend-quality/action.yml+++ b/.github/actions/frontend-quality/action.yml@@ -21,6 +21,10 @@ runs:shell: bashrun: node scripts/check-ui-transition-properties.mjs+ - name: Check UI focus outlines+ shell: bash+ run: node scripts/check-ui-focus-outlines.mjs+- name: Check shared dependencies use the pnpm catalogshell: bashrun: node scripts/check-dependency-catalog.mjsdiff --git a/package.json b/package.jsonindex 28b2020f00..e264f67e2e 100644--- a/package.json+++ b/package.json@@ -28,6 +28,7 @@"lint": "turbo lint --filter=!@multica/mobile","knip": "knip","check:ui-exports": "node scripts/check-ui-wildcard-exports.mjs",+ "check:ui-outlines": "node scripts/check-ui-focus-outlines.mjs","check:ui-radii": "node scripts/check-ui-radius-tokens.mjs","check:ui-transitions": "node scripts/check-ui-transition-properties.mjs","check:deps-catalog": "node scripts/check-dependency-catalog.mjs",diff --git a/packages/ui/docs/motion.md b/packages/ui/docs/motion.mdindex 8875630c91..8eef51d7cc 100644--- a/packages/ui/docs/motion.md+++ b/packages/ui/docs/motion.md@@ -90,7 +90,7 @@ An animated container must not break the controls inside it, while it moves or a- Clip only while the size changes. A permanent `overflow-hidden` cuts off the focus rings and drop rings of the rows inside it. With motion, put `overflow: "hidden"` in `initial` and `exit`, and end `animate` with `transitionEnd: { overflow: "visible" }`, as `PanelDisclosure` in `packages/views/layout/panel-nav.tsx` and `ChatBarChip` in `packages/views/chat/components/chat-bar.tsx` do. `CollapsibleContent` already clips only while its height moves. A container that clips by design, such as a drawer that slides in from an edge or a card with rounded corners, keeps its rows inside their own scroll area, with room for the ring.- Content that is leaving takes no clicks and no focus. Read `useIsPresent()` in the component that `AnimatePresence` renders, and set `inert={!isPresent}` on the leaving element. `pointer-events-none` alone still lets Tab land on it. `CollapsibleContent` is inert while it closes.- motion owns every size it animates. motion writes `width` and `height` as inline styles, which win over a Tailwind class for the same property, such as `max-md:w-full`. When the size depends on the breakpoint, choose motion's target by breakpoint (`useIsMobile()`), as `StepInspectorDrawer` in `packages/views/common/task-transcript/agent-transcript-dialog.tsx` does.-- A focus ring has to be drawn before it can be kept whole. In Tailwind v4, `outline-none` also sets `--tw-outline-style: none`, which `focus-visible:outline-2` reads, so on the same element the two draw nothing. Add `focus-visible:outline-solid`, as `PANEL_ROW_CLASS` in `packages/views/layout/panel-nav.tsx` does. A ring on `::after` (`focus-visible:after:outline-2`) is unaffected, because the variable does not inherit.+- A focus ring has to be drawn before it can be kept whole. In Tailwind v4, `outline-none` also sets `--tw-outline-style: none`, which `focus-visible:outline-2` reads, so on the same element the two draw nothing. Add `focus-visible:outline-solid`, as `PANEL_ROW_CLASS` in `packages/views/layout/panel-nav.tsx` does. A ring on `::after` (`focus-visible:after:outline-2`) is unaffected, because the variable does not inherit. `pnpm check:ui-outlines` reports a width left without its style.## Reduced motiondiff --git a/packages/ui/docs/motion.zh.md b/packages/ui/docs/motion.zh.mdindex d4d999a8b5..1b284fb518 100644--- a/packages/ui/docs/motion.zh.md+++ b/packages/ui/docs/motion.zh.md@@ -90,7 +90,7 @@ Dialog、AlertDialog、Sheet、Popover、DropdownMenu、ContextMenu、Select、H- 只在尺寸变化期间裁切。常驻的 `overflow-hidden` 会裁掉里面各行的焦点环和拖放 ring。用 motion 时,把 `overflow: "hidden"` 放在 `initial` 和 `exit` 中,`animate` 以 `transitionEnd: { overflow: "visible" }` 收尾,参考 `packages/views/layout/panel-nav.tsx` 中的 `PanelDisclosure` 和 `packages/views/chat/components/chat-bar.tsx` 中的 `ChatBarChip`。`CollapsibleContent` 已经只在高度变化期间裁切。本身就要裁切的容器,比如从边缘滑入的抽屉、带圆角的卡片,要把行放在它们自己的滚动区域里,并给焦点环留出空间。- 正在退场的内容不接受点击,也不能获得焦点。在 `AnimatePresence` 渲染的组件中读取 `useIsPresent()`,给退场元素加 `inert={!isPresent}`。只加 `pointer-events-none` 时,Tab 仍然能落到它上面。`CollapsibleContent` 在折叠期间是 inert 的。- motion 动画的尺寸,全程由 motion 接管。motion 把 `width` 和 `height` 写成内联样式,优先级高于同一属性的 Tailwind class,比如 `max-md:w-full`。尺寸随断点变化时,按断点选择 motion 的目标值(`useIsMobile()`),参考 `packages/views/common/task-transcript/agent-transcript-dialog.tsx` 中的 `StepInspectorDrawer`。-- 焦点环先要画得出来,才谈得上完整。在 Tailwind v4 中,`outline-none` 同时会把 `--tw-outline-style` 设为 `none`,而 `focus-visible:outline-2` 读取的正是这个变量,两者在同一个元素上什么都画不出来。要加上 `focus-visible:outline-solid`,参考 `packages/views/layout/panel-nav.tsx` 中的 `PANEL_ROW_CLASS`。画在 `::after` 上的焦点环(`focus-visible:after:outline-2`)不受影响,因为这个变量不继承。+- 焦点环先要画得出来,才谈得上完整。在 Tailwind v4 中,`outline-none` 同时会把 `--tw-outline-style` 设为 `none`,而 `focus-visible:outline-2` 读取的正是这个变量,两者在同一个元素上什么都画不出来。要加上 `focus-visible:outline-solid`,参考 `packages/views/layout/panel-nav.tsx` 中的 `PANEL_ROW_CLASS`。画在 `::after` 上的焦点环(`focus-visible:after:outline-2`)不受影响,因为这个变量不继承。`pnpm check:ui-outlines` 会报出缺了样式的宽度写法。## 减少动态效果diff --git a/packages/views/layout/panels/inbox-section.tsx b/packages/views/layout/panels/inbox-section.tsxindex 4a0d77bbd2..3fb8d092d7 100644--- a/packages/views/layout/panels/inbox-section.tsx+++ b/packages/views/layout/panels/inbox-section.tsx@@ -1318,7 +1318,7 @@ function ArchivedSectionList({<span className="min-w-0 flex-1 truncate">{t(($) => $.filters.empty)}</span><buttontype="button"- className="shrink-0 rounded-md px-1 font-medium text-muted-foreground outline-none hover:text-foreground focus-visible:outline-2 focus-visible:outline-ring"+ className="shrink-0 rounded-md px-1 font-medium text-muted-foreground outline-none hover:text-foreground focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-ring"onClick={() => clearFilters(wsId)}>{t(($) => $.filters.clear)}diff --git a/scripts/check-ui-focus-outlines.mjs b/scripts/check-ui-focus-outlines.mjsnew file mode 100644index 0000000000..d33ff555f5--- /dev/null+++ b/scripts/check-ui-focus-outlines.mjs@@ -0,0 +1,150 @@+#!/usr/bin/env node+/**+ * Catches focus rings that `outline-none` erases before they are drawn.+ *+ * In Tailwind v4, `outline-none` and `outline-hidden` set+ * `--tw-outline-style: none`, and every outline width utility (`outline`,+ * `outline-2`, `outline-[3px]`) takes its `outline-style` from that variable.+ * On one element, `outline-none focus-visible:outline-2` therefore draws no+ * ring at all. A style utility under the same variants, such as+ * `focus-visible:outline-solid`, sets the variable back.+ *+ * A width is reported when it sits behind at least one variant, a reset is on+ * the same element, and no `outline-solid`/`dashed`/`dotted`/`double` applies+ * under the same or fewer variants. Rings on a pseudo-element or a child+ * (`after:`, `before:`, `*:`, `[&_svg]:`) are a different element: the+ * variable is registered with `inherits: false`, so the reset never reaches+ * them.+ *+ * Classes that land on one element are grouped as described in+ * `ui-class-groups.mjs`. apps/mobile is skipped: NativeWind runs Tailwind v3,+ * where `outline-none` is a transparent outline and widths do not read the+ * variable.+ *+ * Run: node scripts/check-ui-focus-outlines.mjs+ */++import { readFileSync, realpathSync } from "node:fs";+import { fileURLToPath } from "node:url";++import { classGroups, repoPath, sourceFiles } from "./ui-class-groups.mjs";++const elementVariants = new Set([+ "after",+ "before",+ "backdrop",+ "placeholder",+ "file",+ "marker",+ "selection",+ "first-line",+ "first-letter",+ "details-content",+ "*",+ "**",+]);++/** Splits `focus-visible:after:outline-2!` into its variants and utility. */+function parseToken(token) {+ const variants = [];+ let depth = 0;+ let start = 0;+ for (let index = 0; index < token.length; index++) {+ const char = token[index];+ if (char === "[" || char === "(") depth++;+ else if (char === "]" || char === ")") depth--;+ else if (char === ":" && depth === 0) {+ variants.push(token.slice(start, index));+ start = index + 1;+ }+ }+ const utility = token.slice(start).replace(/^!/, "").replace(/!$/, "");+ const element = variants.filter((variant) => elementVariants.has(variant) || variant.startsWith("["));+ const conditions = variants.filter((variant) => !element.includes(variant));+ return { variants, utility, element: element.join(":"), conditions };+}++function outlineRole(utility) {+ if (utility === "outline-none" || utility === "outline-hidden") return "reset";+ if (/^outline-(?:solid|dashed|dotted|double)$/.test(utility)) return "style";+ if (+ utility === "outline" ||+ /^outline-\d+$/.test(utility) ||+ /^outline-\[(?:length:[^\]]+|\d*\.?\d+[a-z%]*)\]$/.test(utility) ||+ /^outline-\(length:[^)]+\)$/.test(utility)+ ) {+ return "width";+ }+ return null;+}++/** Checks class strings that land on one element; each finding keeps its source string. */+export function classGroupViolations(strings) {+ const resets = new Set();+ const styles = [];+ const widths = [];++ for (const string of strings) {+ for (const token of string.text.split(/\s+/)) {+ if (!token) continue;+ const parsed = parseToken(token);+ const role = outlineRole(parsed.utility);+ if (role === "reset") resets.add(parsed.element);+ else if (role === "style") styles.push(parsed);+ else if (role === "width" && parsed.conditions.length > 0) widths.push({ string, token, ...parsed });+ }+ }++ return widths+ .filter(+ (width) =>+ resets.has(width.element) &&+ !styles.some(+ (style) =>+ style.element === width.element &&+ style.conditions.every((condition) => width.conditions.includes(condition)),+ ),+ )+ .map(({ string, token, variants }) => ({+ string,+ token,+ fix: [...variants, "outline-solid"].join(":"),+ }));+}++export function focusOutlineViolations(sourceText, filePath) {+ const file = repoPath(filePath);+ return classGroups(sourceText, filePath).flatMap((strings) =>+ classGroupViolations(strings).map(({ string, token, fix }) => ({+ file,+ line: string.line,+ column: string.column,+ token,+ fix,+ })),+ );+}++function main() {+ const files = sourceFiles();+ const violations = files.flatMap((file) =>+ focusOutlineViolations(readFileSync(file, "utf8"), file),+ );++ if (violations.length > 0) {+ console.error(`Focus outlines that outline-none cancels (${violations.length})`);+ for (const violation of violations) {+ console.error(+ ` ${violation.file}:${violation.line}:${violation.column} ${violation.token} draws nothing; add \`${violation.fix}\``,+ );+ }+ console.error(+ "\nIn Tailwind v4, `outline-none` and `outline-hidden` set `--tw-outline-style: none`, and `outline-<n>` takes its style from that variable, so on the same element the ring is never drawn. Add `focus-visible:outline-solid` (under the same variants as the width) in the same place.",+ );+ process.exit(1);+ }++ console.log(`UI focus outlines clean (${files.length} source files checked).`);+}++if (process.argv[1] && realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url))) main();diff --git a/scripts/check-ui-focus-outlines.test.mjs b/scripts/check-ui-focus-outlines.test.mjsnew file mode 100644index 0000000000..625cff5c82--- /dev/null+++ b/scripts/check-ui-focus-outlines.test.mjs@@ -0,0 +1,90 @@+import assert from "node:assert/strict";+import test from "node:test";+import { resolve } from "node:path";++import {+ classGroupViolations,+ focusOutlineViolations,+} from "./check-ui-focus-outlines.mjs";++const probe = resolve("packages/views/zz-outline-probe.tsx");+const tokens = (...texts) =>+ classGroupViolations(texts.map((text) => ({ text }))).map((finding) => finding.token);+const fixes = (...texts) =>+ classGroupViolations(texts.map((text) => ({ text }))).map((finding) => finding.fix);+const findings = (source) =>+ focusOutlineViolations(source, probe).map(({ line, token }) => `${line}:${token}`);++test("rejects widths that outline-none or outline-hidden leave without a style", () => {+ assert.deepEqual(+ tokens("outline-none focus-visible:outline-2 focus-visible:outline-ring"),+ ["focus-visible:outline-2"],+ );+ assert.deepEqual(tokens("outline-hidden focus:outline-1"), ["focus:outline-1"]);+ assert.deepEqual(tokens("focus-visible:outline-none focus-visible:outline-2"), ["focus-visible:outline-2"]);+ assert.deepEqual(+ tokens("outline-none group-focus-visible:outline focus-within:outline-[3px] focus-visible:outline-(length:--ring)"),+ ["group-focus-visible:outline", "focus-within:outline-[3px]", "focus-visible:outline-(length:--ring)"],+ );+ assert.deepEqual(tokens("outline-none! focus-visible:outline-2!"), ["focus-visible:outline-2!"]);+});++test("the fix names the width's own variants", () => {+ assert.deepEqual(fixes("outline-none focus-visible:outline-2"), ["focus-visible:outline-solid"]);+ assert.deepEqual(fixes("outline-none data-open:focus:outline-2"), ["data-open:focus:outline-solid"]);+});++test("accepts a style under the same or fewer variants", () => {+ assert.deepEqual(tokens("outline-none focus-visible:outline-2 focus-visible:outline-solid"), []);+ assert.deepEqual(tokens("outline-hidden focus-visible:outline-2 focus-visible:outline-dashed"), []);+ assert.deepEqual(tokens("outline-none focus-visible:outline-dotted data-open:focus-visible:outline-2"), []);+ assert.deepEqual(tokens("outline-none focus-visible:outline-2 focus:outline-double"), ["focus-visible:outline-2"]);+ assert.deepEqual(tokens("outline-none focus-visible:outline-2 hover:outline-solid"), ["focus-visible:outline-2"]);+});++test("ignores rings on pseudo-elements and children, which the reset never reaches", () => {+ assert.deepEqual(+ tokens("outline-none after:absolute after:inset-0 focus-visible:after:outline-2 focus-visible:after:outline-ring"),+ [],+ );+ assert.deepEqual(tokens("outline-none focus-visible:before:outline-1 *:focus:outline-2 [&_svg]:focus:outline-2"), []);+ assert.deepEqual(tokens("after:outline-none focus-visible:after:outline-2"), ["focus-visible:after:outline-2"]);+ assert.deepEqual(tokens("[&_.recharts-layer]:outline-hidden focus-visible:outline-2"), []);+});++test("ignores colors, offsets, unconditional widths and elements without a reset", () => {+ assert.deepEqual(tokens("focus-visible:outline-2 focus-visible:outline-ring"), []);+ assert.deepEqual(+ tokens("outline-none focus-visible:outline-ring focus-visible:outline-offset-2 focus-visible:outline-[#fff]"),+ [],+ );+ assert.deepEqual(tokens("outline", "outline-none"), []);+});++test("groups the string arguments of one cn() or clsx() call", () => {+ assert.deepEqual(+ findings(`+ const row = cn(+ "flex outline-none",+ active+ ? "focus-visible:outline-2"+ : "opacity-50",+ );+ const chip = clsx(["outline-hidden"], ready && \`focus:outline-1 \${x}\`);+ const fine = cn("outline-none", open ?? "focus-visible:outline-2 focus-visible:outline-solid");+ `),+ ["5:focus-visible:outline-2", "8:focus:outline-1"],+ );+});++test("does not follow classes passed through variables or other calls", () => {+ assert.deepEqual(+ findings(`+ const jsx = <button className="outline-none focus-visible:outline-2" />;+ const template = \`outline-none \${size} focus:outline-2\`;+ const ring = "focus-visible:outline-2";+ const split = cn("outline-none", ring, other("focus-visible:outline-2"));+ `),+ ["2:focus-visible:outline-2", "3:focus:outline-2"],+ );+});diff --git a/scripts/check-ui-transition-properties.mjs b/scripts/check-ui-transition-properties.mjsindex b32196841b..b4309ddf05 100644--- a/scripts/check-ui-transition-properties.mjs+++ b/scripts/check-ui-transition-properties.mjs@@ -14,43 +14,17 @@* Only that mix-up is reported. A list that names neither property, such as* `transition-[width]` next to a static `-translate-x-1/2`, is left alone.*- * Classes are grouped per string literal (a template literal's static text- * counts as one string), and the string arguments of one direct `cn()` or- * `clsx()` call — including ternary, `&&`/`||`/`??` and array branches — are- * grouped together. Classes passed through variables are not followed.- * apps/mobile is skipped: NativeWind runs Tailwind v3, where these utilities- * do go through `transform`.+ * Classes that land on one element are grouped as described in+ * `ui-class-groups.mjs`. apps/mobile is skipped: NativeWind runs Tailwind v3,+ * where these utilities do go through `transform`.** Run: node scripts/check-ui-transition-properties.mjs*/-import { readdirSync, readFileSync, realpathSync } from "node:fs";-import { extname, join, relative, resolve, sep } from "node:path";+import { readFileSync, realpathSync } from "node:fs";import { fileURLToPath } from "node:url";-import ts from "typescript";-const repoRoot = resolve(import.meta.dirname, "..");-const roots = [- "apps/web",- "apps/desktop",- "apps/docs",- "apps/storybook",- "packages/ui",- "packages/views",- "packages/ee",-];-const extensions = new Set([".ts", ".tsx", ".js", ".jsx", ".mjs", ".mdx"]);-const skippedDirectories = new Set(["node_modules", ".next", ".turbo", "dist", "build", "out"]);--function walk(directory, files = []) {- for (const entry of readdirSync(directory, { withFileTypes: true })) {- if (entry.name.startsWith(".") || skippedDirectories.has(entry.name)) continue;- const path = join(directory, entry.name);- if (entry.isDirectory()) walk(path, files);- else if (extensions.has(extname(entry.name))) files.push(path);- }- return files;-}+import { classGroups, repoPath, sourceFiles } from "./ui-class-groups.mjs";function utilityName(token) {const withoutVariant = token.slice(token.lastIndexOf(":") + 1);@@ -94,77 +68,21 @@ export function classGroupViolations(strings) {return movers.filter((mover) => isMismatch(listed, mover.property));}-function classStrings(node) {- if (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node)) return node.text;- if (ts.isTemplateExpression(node)) {- return [node.head.text, ...node.templateSpans.map((span) => span.literal.text)].join(" ");- }- return null;-}--const classMergers = new Set(["cn", "clsx"]);-const branchOperators = new Set([- ts.SyntaxKind.AmpersandAmpersandToken,- ts.SyntaxKind.BarBarToken,- ts.SyntaxKind.QuestionQuestionToken,-]);--/** String nodes an argument of `cn()` can resolve to without following variables. */-function mergedStringNodes(node, nodes = []) {- if (classStrings(node) !== null) nodes.push(node);- else if (ts.isParenthesizedExpression(node)) mergedStringNodes(node.expression, nodes);- else if (ts.isConditionalExpression(node)) {- mergedStringNodes(node.whenTrue, nodes);- mergedStringNodes(node.whenFalse, nodes);- } else if (ts.isBinaryExpression(node) && branchOperators.has(node.operatorToken.kind)) {- mergedStringNodes(node.left, nodes);- mergedStringNodes(node.right, nodes);- } else if (ts.isArrayLiteralExpression(node)) {- for (const element of node.elements) mergedStringNodes(element, nodes);- }- return nodes;-}-export function transitionViolations(sourceText, filePath) {- const source = ts.createSourceFile(filePath, sourceText, ts.ScriptTarget.Latest, true);- const relativePath = relative(repoRoot, filePath).split(sep).join("/");- const violations = [];- const grouped = new Set();-- const check = (nodes) => {- const strings = nodes.map((node) => ({ text: classStrings(node), node }));- for (const { string, token, property } of classGroupViolations(strings)) {- const { line, character } = source.getLineAndCharacterOfPosition(string.node.getStart(source));- violations.push({- file: relativePath,- line: line + 1,- column: character + 1,- token,- property,- });- }- };-- const visit = (node) => {- if (- ts.isCallExpression(node) &&- ts.isIdentifier(node.expression) &&- classMergers.has(node.expression.text)- ) {- const nodes = node.arguments.flatMap((argument) => mergedStringNodes(argument));- for (const string of nodes) grouped.add(string);- check(nodes);- } else if (classStrings(node) !== null && !grouped.has(node)) {- check([node]);- }- ts.forEachChild(node, visit);- };- visit(source);- return violations;+ const file = repoPath(filePath);+ return classGroups(sourceText, filePath).flatMap((strings) =>+ classGroupViolations(strings).map(({ string, token, property }) => ({+ file,+ line: string.line,+ column: string.column,+ token,+ property,+ })),+ );}function main() {- const files = roots.flatMap((root) => walk(join(repoRoot, root)));+ const files = sourceFiles();const violations = files.flatMap((file) =>transitionViolations(readFileSync(file, "utf8"), file),);diff --git a/scripts/ui-class-groups.mjs b/scripts/ui-class-groups.mjsnew file mode 100644index 0000000000..0d51b7d503--- /dev/null+++ b/scripts/ui-class-groups.mjs@@ -0,0 +1,114 @@+/**+ * Source scanning shared by the UI class checks that need to know which+ * classes land on one element.+ *+ * Classes are grouped per string literal (a template literal's static text+ * counts as one string), and the string arguments of one direct `cn()` or+ * `clsx()` call — including ternary, `&&`/`||`/`??` and array branches — are+ * grouped together. Classes passed through variables are not followed.+ */++import { readdirSync } from "node:fs";+import { extname, join, relative, resolve, sep } from "node:path";+import ts from "typescript";++export const repoRoot = resolve(import.meta.dirname, "..");++/** Workspaces styled by Tailwind v4. apps/mobile runs NativeWind on Tailwind v3. */+export const tailwindV4Roots = [+ "apps/web",+ "apps/desktop",+ "apps/docs",+ "apps/storybook",+ "packages/ui",+ "packages/views",+ "packages/ee",+];++const extensions = new Set([".ts", ".tsx", ".js", ".jsx", ".mjs", ".mdx"]);+const skippedDirectories = new Set(["node_modules", ".next", ".turbo", "dist", "build", "out"]);++function walk(directory, files) {+ for (const entry of readdirSync(directory, { withFileTypes: true })) {+ if (entry.name.startsWith(".") || skippedDirectories.has(entry.name)) continue;+ const path = join(directory, entry.name);+ if (entry.isDirectory()) walk(path, files);+ else if (extensions.has(extname(entry.name))) files.push(path);+ }+ return files;+}++export function sourceFiles(roots = tailwindV4Roots) {+ return roots.flatMap((root) => walk(join(repoRoot, root), []));+}++export function repoPath(filePath) {+ return relative(repoRoot, filePath).split(sep).join("/");+}++function classStrings(node) {+ if (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node)) return node.text;+ if (ts.isTemplateExpression(node)) {+ return [node.head.text, ...node.templateSpans.map((span) => span.literal.text)].join(" ");+ }+ return null;+}++const classMergers = new Set(["cn", "clsx"]);+const branchOperators = new Set([+ ts.SyntaxKind.AmpersandAmpersandToken,+ ts.SyntaxKind.BarBarToken,+ ts.SyntaxKind.QuestionQuestionToken,+]);++/** String nodes an argument of `cn()` can resolve to without following variables. */+function mergedStringNodes(node, nodes = []) {+ if (classStrings(node) !== null) nodes.push(node);+ else if (ts.isParenthesizedExpression(node)) mergedStringNodes(node.expression, nodes);+ else if (ts.isConditionalExpression(node)) {+ mergedStringNodes(node.whenTrue, nodes);+ mergedStringNodes(node.whenFalse, nodes);+ } else if (ts.isBinaryExpression(node) && branchOperators.has(node.operatorToken.kind)) {+ mergedStringNodes(node.left, nodes);+ mergedStringNodes(node.right, nodes);+ } else if (ts.isArrayLiteralExpression(node)) {+ for (const element of node.elements) mergedStringNodes(element, nodes);+ }+ return nodes;+}++/**+ * Every group of class strings in a file. Each string carries its text and a+ * 1-based `line` and `column`.+ */+export function classGroups(sourceText, filePath) {+ const source = ts.createSourceFile(filePath, sourceText, ts.ScriptTarget.Latest, true);+ const groups = [];+ const grouped = new Set();++ const add = (nodes) => {+ groups.push(+ nodes.map((node) => {+ const { line, character } = source.getLineAndCharacterOfPosition(node.getStart(source));+ return { text: classStrings(node), line: line + 1, column: character + 1 };+ }),+ );+ };++ const visit = (node) => {+ if (+ ts.isCallExpression(node) &&+ ts.isIdentifier(node.expression) &&+ classMergers.has(node.expression.text)+ ) {+ const nodes = node.arguments.flatMap((argument) => mergedStringNodes(argument));+ for (const string of nodes) grouped.add(string);+ add(nodes);+ } else if (classStrings(node) !== null && !grouped.has(node)) {+ add([node]);+ }+ ts.forEachChild(node, visit);+ };+ visit(source);+ return groups;+}