Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

fix(lint): enable curly rule to require braces on all control flow (#2258)

Andrey Goder78c6bbec1999
diff --git a/apps/docsite/src/__tests__/data-extraction.test.ts b/apps/docsite/src/__tests__/data-extraction.test.ts
index cdc51e8c8b..bc0ce138f7 100644
--- a/apps/docsite/src/__tests__/data-extraction.test.ts
+++ b/apps/docsite/src/__tests__/data-extraction.test.ts
@@ -381,7 +381,9 @@ describe('blockRegistry', () => {
const showcases = blocks.filter(b => b.isShowcase);
const seen = new Map<string, string[]>();
for (const s of showcases) {
- if (!seen.has(s.exampleFor)) seen.set(s.exampleFor, []);
+ if (!seen.has(s.exampleFor)) {
+ seen.set(s.exampleFor, []);
+ }
seen.get(s.exampleFor)!.push(s.dirName);
}
const dupes = [...seen.entries()].filter(([, v]) => v.length > 1);
diff --git a/apps/docsite/src/app/(docs)/components/[name]/page.tsx b/apps/docsite/src/app/(docs)/components/[name]/page.tsx
index 2ec5145018..d061fd29de 100644
--- a/apps/docsite/src/app/(docs)/components/[name]/page.tsx
+++ b/apps/docsite/src/app/(docs)/components/[name]/page.tsx
@@ -25,7 +25,9 @@ export default async function ComponentPage({
}) {
const {name} = await params;
const comp = allComponents.find(c => c.name === name);
- if (!comp) notFound();
+ if (!comp) {
+ notFound();
+ }
const pkg = Object.entries(components).find(([, comps]) =>
comps.includes(comp),
diff --git a/apps/docsite/src/app/(docs)/docs/[topic]/page.tsx b/apps/docsite/src/app/(docs)/docs/[topic]/page.tsx
index 437e991eee..c4c00dab9c 100644
--- a/apps/docsite/src/app/(docs)/docs/[topic]/page.tsx
+++ b/apps/docsite/src/app/(docs)/docs/[topic]/page.tsx
@@ -34,7 +34,9 @@ export default async function DocPage({
}) {
const {topic: slug} = await params;
const topic = docTopics.find(d => d.topic === slug);
- if (!topic) notFound();
+ if (!topic) {
+ notFound();
+ }
const isTokenTopic =
topic.category === 'foundations' && TOKEN_TOPICS.has(topic.topic);
diff --git a/apps/docsite/src/app/(docs)/packages/[name]/ComponentPreviewCard.tsx b/apps/docsite/src/app/(docs)/packages/[name]/ComponentPreviewCard.tsx
index 7e5909f74b..2fc8a478a8 100644
--- a/apps/docsite/src/app/(docs)/packages/[name]/ComponentPreviewCard.tsx
+++ b/apps/docsite/src/app/(docs)/packages/[name]/ComponentPreviewCard.tsx
@@ -82,7 +82,9 @@ function ComponentThumbnail({name}: {name: string}) {
useEffect(() => {
const el = containerRef.current;
- if (!el) return;
+ if (!el) {
+ return;
+ }
const observer = new IntersectionObserver(
([entry]) => setIsVisible(entry.isIntersecting),
{rootMargin: '200px'},
@@ -94,7 +96,9 @@ function ComponentThumbnail({name}: {name: string}) {
useEffect(() => {
updateWidth();
const el = containerRef.current;
- if (!el) return;
+ if (!el) {
+ return;
+ }
const ro = new ResizeObserver(updateWidth);
ro.observe(el);
return () => ro.disconnect();
diff --git a/apps/docsite/src/app/(docs)/packages/[name]/page.tsx b/apps/docsite/src/app/(docs)/packages/[name]/page.tsx
index 9221551f82..bc98ac3096 100644
--- a/apps/docsite/src/app/(docs)/packages/[name]/page.tsx
+++ b/apps/docsite/src/app/(docs)/packages/[name]/page.tsx
@@ -78,7 +78,9 @@ export default async function PackagePage({
const {name: slug} = await params;
const pkgName = slugToPackageName(slug);
const pkg = packages.find(p => p.name === pkgName);
- if (!pkg) notFound();
+ if (!pkg) {
+ notFound();
+ }
const isTheme = pkg.name.includes('theme-');
const isComponentPkg = pkg.name === '@xds/core';
diff --git a/apps/docsite/src/app/(docs)/page.tsx b/apps/docsite/src/app/(docs)/page.tsx
index 1da85e5f27..06e371120c 100644
--- a/apps/docsite/src/app/(docs)/page.tsx
+++ b/apps/docsite/src/app/(docs)/page.tsx
@@ -175,8 +175,12 @@ const styles = stylex.create({
const foundationTopics = docTopics
.filter(d => d.category === 'foundations')
.sort((a, b) => {
- if (a.topic === 'tokens') return -1;
- if (b.topic === 'tokens') return 1;
+ if (a.topic === 'tokens') {
+ return -1;
+ }
+ if (b.topic === 'tokens') {
+ return 1;
+ }
return a.title.localeCompare(b.title);
});
diff --git a/apps/docsite/src/app/(preview)/playground-preview/page.tsx b/apps/docsite/src/app/(preview)/playground-preview/page.tsx
index 5d26c0dadf..ed7caadf48 100644
--- a/apps/docsite/src/app/(preview)/playground-preview/page.tsx
+++ b/apps/docsite/src/app/(preview)/playground-preview/page.tsx
@@ -1,6 +1,6 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
-"use client";
+'use client';
import React, {
useCallback,
@@ -9,15 +9,15 @@ import React, {
useState,
type ErrorInfo,
type ReactNode,
-} from "react";
-import {XDSTheme} from "@xds/core/theme";
-import type {XDSDefinedTheme} from "@xds/core/theme";
-import type {ThemeMode} from "@xds/core/theme";
-import {defaultTheme} from "@xds/theme-default/built";
-import {neutralTheme} from "@xds/theme-neutral/built";
-import {dailyTheme} from "@xds/theme-daily/built";
-import {matchaTheme} from "@xds/theme-matcha/built";
-import {runCode, setBabel} from "./runner";
+} from 'react';
+import {XDSTheme} from '@xds/core/theme';
+import type {XDSDefinedTheme} from '@xds/core/theme';
+import type {ThemeMode} from '@xds/core/theme';
+import {defaultTheme} from '@xds/theme-default/built';
+import {neutralTheme} from '@xds/theme-neutral/built';
+import {dailyTheme} from '@xds/theme-daily/built';
+import {matchaTheme} from '@xds/theme-matcha/built';
+import {runCode, setBabel} from './runner';
const THEME_MAP: Record<string, XDSDefinedTheme> = {
default: defaultTheme,
@@ -66,23 +66,23 @@ class ErrorBoundary extends React.Component<
function ErrorDisplay({message}: {message: string}) {
const [expanded, setExpanded] = useState(false);
- const preview = message.length > 120 ? message.slice(0, 120) + "…" : message;
+ const preview = message.length > 120 ? message.slice(0, 120) + '…' : message;
return (
<div
style={{
padding: 16,
- fontFamily: "ui-monospace, monospace",
+ fontFamily: 'ui-monospace, monospace',
fontSize: 13,
- color: "#ef4444",
+ color: '#ef4444',
lineHeight: 1.5,
}}>
<div
- style={{fontWeight: 600, marginBottom: 8, cursor: "pointer"}}
- onClick={() => setExpanded((e) => !e)}>
- ⚠ Render Error {message.length > 120 && (expanded ? "▾" : "▸")}
+ style={{fontWeight: 600, marginBottom: 8, cursor: 'pointer'}}
+ onClick={() => setExpanded(e => !e)}>
+ ⚠ Render Error {message.length > 120 && (expanded ? '▾' : '▸')}
</div>
- <pre style={{whiteSpace: "pre-wrap", margin: 0}}>
+ <pre style={{whiteSpace: 'pre-wrap', margin: 0}}>
{expanded ? message : preview}
</pre>
</div>
@@ -90,33 +90,33 @@ function ErrorDisplay({message}: {message: string}) {
}
type PreviewMessage =
- | {type: "preview-ping"}
- | {type: "preview-code"; code: string}
- | {type: "preview-clear"}
- | {type: "preview-theme"; mode?: string; theme?: string};
+ | {type: 'preview-ping'}
+ | {type: 'preview-code'; code: string}
+ | {type: 'preview-clear'}
+ | {type: 'preview-theme'; mode?: string; theme?: string};
function isPreviewMessage(data: unknown): data is PreviewMessage {
return (
- typeof data === "object" &&
+ typeof data === 'object' &&
data !== null &&
- "type" in data &&
- typeof (data as {type: unknown}).type === "string"
+ 'type' in data &&
+ typeof (data as {type: unknown}).type === 'string'
);
}
export default function PreviewPage() {
const [Component, setComponent] = useState<React.ComponentType | null>(null);
const [error, setError] = useState<string | null>(null);
- const [themeMode, setThemeMode] = useState<ThemeMode>("system");
- const [themeName, setThemeName] = useState("default");
+ const [themeMode, setThemeMode] = useState<ThemeMode>('system');
+ const [themeName, setThemeName] = useState('default');
const [resetKey, setResetKey] = useState(0);
const [babelReady, setBabelReady] = useState(false);
const readyRef = useRef(false);
// Load Babel from CDN — avoids bundling the 5MB package through Next.js
useEffect(() => {
- const script = document.createElement("script");
- script.src = "https://unpkg.com/@babel/standalone@7/babel.min.js";
+ const script = document.createElement('script');
+ script.src = 'https://unpkg.com/@babel/standalone@7/babel.min.js';
script.onload = () => {
const w = window as unknown as Record<string, unknown>;
if (w.Babel) {
@@ -130,7 +130,7 @@ export default function PreviewPage() {
const theme = THEME_MAP[themeName] ?? defaultTheme;
const postToParent = useCallback((msg: Record<string, unknown>) => {
- window.parent.postMessage(msg, "*");
+ window.parent.postMessage(msg, '*');
}, []);
const handleCode = useCallback(
@@ -139,13 +139,13 @@ export default function PreviewPage() {
if (result.Component) {
setComponent(() => result.Component);
setError(null);
- setResetKey((k) => k + 1);
- postToParent({type: "preview-rendered"});
+ setResetKey(k => k + 1);
+ postToParent({type: 'preview-rendered'});
} else {
setComponent(null);
setError(`[${result.phase}] ${result.error}`);
postToParent({
- type: "preview-error",
+ type: 'preview-error',
error: result.error,
phase: result.phase,
});
@@ -159,56 +159,57 @@ export default function PreviewPage() {
setError(null);
}, []);
- const handleTheme = useCallback(
- (msg: {mode?: string; theme?: string}) => {
- if (msg.mode === "light" || msg.mode === "dark" || msg.mode === "system") {
- setThemeMode(msg.mode);
- }
- if (msg.theme && msg.theme in THEME_MAP) {
- setThemeName(msg.theme);
- }
- },
- [],
- );
+ const handleTheme = useCallback((msg: {mode?: string; theme?: string}) => {
+ if (msg.mode === 'light' || msg.mode === 'dark' || msg.mode === 'system') {
+ setThemeMode(msg.mode);
+ }
+ if (msg.theme && msg.theme in THEME_MAP) {
+ setThemeName(msg.theme);
+ }
+ }, []);
useEffect(() => {
- if (!babelReady) return;
+ if (!babelReady) {
+ return;
+ }
function onMessage(event: MessageEvent) {
- if (!isPreviewMessage(event.data)) return;
+ if (!isPreviewMessage(event.data)) {
+ return;
+ }
switch (event.data.type) {
- case "preview-ping":
- postToParent({type: "preview-ready"});
+ case 'preview-ping':
+ postToParent({type: 'preview-ready'});
break;
- case "preview-code":
+ case 'preview-code':
handleCode(event.data.code);
break;
- case "preview-clear":
+ case 'preview-clear':
handleClear();
break;
- case "preview-theme":
+ case 'preview-theme':
handleTheme(event.data);
break;
}
}
- window.addEventListener("message", onMessage);
+ window.addEventListener('message', onMessage);
if (!readyRef.current) {
readyRef.current = true;
- postToParent({type: "preview-ready"});
+ postToParent({type: 'preview-ready'});
}
- return () => window.removeEventListener("message", onMessage);
+ return () => window.removeEventListener('message', onMessage);
}, [babelReady, postToParent, handleCode, handleClear, handleTheme]);
const handleBoundaryError = useCallback(
(err: Error) => {
postToParent({
- type: "preview-error",
+ type: 'preview-error',
error: err.message,
- phase: "runtime",
+ phase: 'runtime',
});
},
[postToParent],
@@ -216,12 +217,10 @@ export default function PreviewPage() {
return (
<XDSTheme theme={theme} mode={themeMode}>
- <div style={{minHeight: "100%", padding: 24}}>
+ <div style={{minHeight: '100%', padding: 24}}>
{error && <ErrorDisplay message={error} />}
{Component && (
- <ErrorBoundary
- resetKey={resetKey}
- onError={handleBoundaryError}>
+ <ErrorBoundary resetKey={resetKey} onError={handleBoundaryError}>
<Component />
</ErrorBoundary>
)}
diff --git a/apps/docsite/src/app/craft/templates/[slug]/page.tsx b/apps/docsite/src/app/craft/templates/[slug]/page.tsx
index be266848e3..6b09f38f1f 100644
--- a/apps/docsite/src/app/craft/templates/[slug]/page.tsx
+++ b/apps/docsite/src/app/craft/templates/[slug]/page.tsx
@@ -23,7 +23,9 @@ export default async function TemplatePage({
}) {
const {slug} = await params;
const template = templates.find(t => t.slug === slug);
- if (!template) notFound();
+ if (!template) {
+ notFound();
+ }
return (
<XDSSection maxWidth="lg" padding={6}>
diff --git a/apps/docsite/src/app/playground/PlaygroundClient.tsx b/apps/docsite/src/app/playground/PlaygroundClient.tsx
index 04d60c4e3a..0ac9a5016b 100644
--- a/apps/docsite/src/app/playground/PlaygroundClient.tsx
+++ b/apps/docsite/src/app/playground/PlaygroundClient.tsx
@@ -1,25 +1,25 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
-"use client";
+'use client';
-import {useCallback, useEffect, useMemo, useRef, useState} from "react";
-import dynamic from "next/dynamic";
-import * as stylex from "@stylexjs/stylex";
+import {useCallback, useEffect, useMemo, useRef, useState} from 'react';
+import dynamic from 'next/dynamic';
+import * as stylex from '@stylexjs/stylex';
import {
compressToEncodedURIComponent,
decompressFromEncodedURIComponent,
-} from "lz-string";
-import {XDSButton} from "@xds/core/Button";
-import {XDSSelector} from "@xds/core/Selector";
-import {XDSHStack} from "@xds/core/Layout";
-import {XDSText} from "@xds/core/Text";
-import {XDSStatusDot} from "@xds/core/StatusDot";
-import {XDSDivider} from "@xds/core/Divider";
-import {useXDSResizable, XDSResizeHandle} from "@xds/core/Resizable";
-import githubLight from "./themes/github-light.json";
-import githubDark from "./themes/github-dark.json";
-
-import type * as MonacoTypes from "monaco-editor";
+} from 'lz-string';
+import {XDSButton} from '@xds/core/Button';
+import {XDSSelector} from '@xds/core/Selector';
+import {XDSHStack} from '@xds/core/Layout';
+import {XDSText} from '@xds/core/Text';
+import {XDSStatusDot} from '@xds/core/StatusDot';
+import {XDSDivider} from '@xds/core/Divider';
+import {useXDSResizable, XDSResizeHandle} from '@xds/core/Resizable';
+import githubLight from './themes/github-light.json';
+import githubDark from './themes/github-dark.json';
+
+import type * as MonacoTypes from 'monaco-editor';
/** Monaco instance type — the full runtime object passed to onMount */
type MonacoInstance = typeof MonacoTypes & {
@@ -41,10 +41,16 @@ type MonacoInstance = typeof MonacoTypes & {
};
};
-const MonacoEditor = dynamic(() => import("@monaco-editor/react"), {
+const MonacoEditor = dynamic(() => import('@monaco-editor/react'), {
ssr: false,
loading: () => (
- <div style={{flex: 1, display: "flex", alignItems: "center", justifyContent: "center"}}>
+ <div
+ style={{
+ flex: 1,
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ }}>
<XDSText color="secondary">Loading editor…</XDSText>
</div>
),
@@ -85,12 +91,18 @@ export default function Demo() {
}`;
function getInitialCode(): string {
- if (typeof window === "undefined") return DEFAULT_CODE;
+ if (typeof window === 'undefined') {
+ return DEFAULT_CODE;
+ }
const hash = window.location.hash.slice(1);
- if (!hash) return DEFAULT_CODE;
+ if (!hash) {
+ return DEFAULT_CODE;
+ }
const params = new URLSearchParams(hash);
- const compressed = params.get("code");
- if (!compressed) return DEFAULT_CODE;
+ const compressed = params.get('code');
+ if (!compressed) {
+ return DEFAULT_CODE;
+ }
try {
return decompressFromEncodedURIComponent(compressed) || DEFAULT_CODE;
} catch {
@@ -100,14 +112,14 @@ function getInitialCode(): string {
function updateURL(code: string) {
const compressed = compressToEncodedURIComponent(code);
- window.history.replaceState(null, "", `#code=${compressed}`);
+ window.history.replaceState(null, '', `#code=${compressed}`);
}
const THEME_OPTIONS = [
- {value: "default", label: "Default"},
- {value: "neutral", label: "Neutral"},
- {value: "daily", label: "Daily"},
- {value: "matcha", label: "Matcha"},
+ {value: 'default', label: 'Default'},
+ {value: 'neutral', label: 'Neutral'},
+ {value: 'daily', label: 'Daily'},
+ {value: 'matcha', label: 'Matcha'},
];
/**
@@ -142,7 +154,7 @@ function configureMonaco(monaco: MonacoInstance) {
declare function useRef<T>(init: T): { current: T };
declare function useReducer<S, A>(reducer: (state: S, action: A) => S, init: S): [S, (action: A) => void];
declare function useContext<T>(ctx: unknown): T;`,
- "file:///globals.d.ts",
+ 'file:///globals.d.ts',
);
// Heroicons wildcard stub
@@ -151,21 +163,24 @@ function configureMonaco(monaco: MonacoInstance) {
declare module '@heroicons/react/20/solid' { const icons: Record<string, React.ComponentType<{width?: number; height?: number; className?: string}>>; export = icons; }
declare module '@heroicons/react/24/outline' { const icons: Record<string, React.ComponentType<{width?: number; height?: number; className?: string}>>; export = icons; }
declare module '@heroicons/react/24/solid' { const icons: Record<string, React.ComponentType<{width?: number; height?: number; className?: string}>>; export = icons; }`,
- "file:///node_modules/@heroicons/react/index.d.ts",
+ 'file:///node_modules/@heroicons/react/index.d.ts',
);
// Load real type definitions from the pre-built JSON bundle
- fetch("/playground-types.json")
- .then((r) => r.json())
+ fetch('/playground-types.json')
+ .then(r => r.json())
.then((packages: Record<string, Record<string, string>>) => {
// React types
- const reactFiles = packages["react"] ?? {};
+ const reactFiles = packages['react'] ?? {};
for (const [fileName, content] of Object.entries(reactFiles)) {
- ts.addExtraLib(content, `file:///node_modules/@types/react/${fileName}`);
+ ts.addExtraLib(
+ content,
+ `file:///node_modules/@types/react/${fileName}`,
+ );
}
// StyleX types
- const stylexFiles = packages["@stylexjs/stylex"] ?? {};
+ const stylexFiles = packages['@stylexjs/stylex'] ?? {};
for (const [fileName, content] of Object.entries(stylexFiles)) {
ts.addExtraLib(
content,
@@ -174,7 +189,7 @@ function configureMonaco(monaco: MonacoInstance) {
}
// XDS core types — register each .d.ts under its dist path AND subpath
- const xdsFiles = packages["@xds/core"] ?? {};
+ const xdsFiles = packages['@xds/core'] ?? {};
const submoduleReexports: string[] = [];
for (const [relPath, content] of Object.entries(xdsFiles)) {
@@ -184,8 +199,8 @@ function configureMonaco(monaco: MonacoInstance) {
);
// Also register as @xds/core/<SubModule>/index.d.ts
- if (relPath.endsWith("/index.d.ts")) {
- const moduleName = relPath.replace("/index.d.ts", "");
+ if (relPath.endsWith('/index.d.ts')) {
+ const moduleName = relPath.replace('/index.d.ts', '');
ts.addExtraLib(
content,
`file:///node_modules/@xds/core/${moduleName}/index.d.ts`,
@@ -196,11 +211,11 @@ function configureMonaco(monaco: MonacoInstance) {
// Build @xds/core barrel from submodule re-exports
const barrelContent = submoduleReexports
- .map((m) => `export * from '@xds/core/${m}';`)
- .join("\n");
+ .map(m => `export * from '@xds/core/${m}';`)
+ .join('\n');
ts.addExtraLib(
`declare module '@xds/core' {\n${barrelContent}\n}`,
- "file:///node_modules/@xds/core/index.d.ts",
+ 'file:///node_modules/@xds/core/index.d.ts',
);
// Types loaded — enable semantic validation
@@ -216,58 +231,58 @@ function configureMonaco(monaco: MonacoInstance) {
const s = stylex.create({
root: {
- display: "flex",
- flexDirection: "column",
- height: "100%",
- overflow: "hidden",
+ display: 'flex',
+ flexDirection: 'column',
+ height: '100%',
+ overflow: 'hidden',
},
toolbar: {
- display: "flex",
- alignItems: "center",
- justifyContent: "space-between",
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'space-between',
paddingInline: 16,
paddingBlock: 6,
flexShrink: 0,
},
main: {
- display: "flex",
+ display: 'flex',
flex: 1,
minHeight: 0,
flexDirection: {
- default: "row",
- "@media (max-width: 768px)": "column",
+ default: 'row',
+ '@media (max-width: 768px)': 'column',
},
},
editorPane: {
- display: "flex",
- flexDirection: "column",
+ display: 'flex',
+ flexDirection: 'column',
flexShrink: 0,
minWidth: 0,
minHeight: {
default: 0,
- "@media (max-width: 768px)": 300,
+ '@media (max-width: 768px)': 300,
},
},
previewPane: {
flex: 1,
- display: "flex",
- flexDirection: "column",
+ display: 'flex',
+ flexDirection: 'column',
minWidth: 0,
minHeight: {
default: 0,
- "@media (max-width: 768px)": 300,
+ '@media (max-width: 768px)': 300,
},
},
iframe: {
flex: 1,
- border: "none",
- width: "100%",
- height: "100%",
+ border: 'none',
+ width: '100%',
+ height: '100%',
},
previewBar: {
- display: "flex",
- alignItems: "center",
- justifyContent: "space-between",
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'space-between',
paddingInline: 12,
paddingBlock: 6,
flexShrink: 0,
@@ -276,7 +291,7 @@ const s = stylex.create({
export function PlaygroundClient() {
const [code, setCode] = useState(getInitialCode);
- const [theme, setTheme] = useState("default");
+ const [theme, setTheme] = useState('default');
const [copied, setCopied] = useState(false);
const [previewReady, setPreviewReady] = useState(false);
const [previewError, setPreviewError] = useState<string | null>(null);
@@ -286,37 +301,42 @@ export function PlaygroundClient() {
const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const editorPanel = useXDSResizable({
- defaultSize: "50%",
+ defaultSize: '50%',
minSizePx: 200,
collapsible: true,
snaps: [400, 600],
- autoSaveId: "xds-playground-editor-width",
+ autoSaveId: 'xds-playground-editor-width',
});
- const [editorTheme, setEditorTheme] = useState("github-dark");
+ const [editorTheme, setEditorTheme] = useState('github-dark');
// Sync editor theme with system preference
useEffect(() => {
- const mq = window.matchMedia("(prefers-color-scheme: dark)");
- const update = () => setEditorTheme(mq.matches ? "github-dark" : "github-light");
+ const mq = window.matchMedia('(prefers-color-scheme: dark)');
+ const update = () =>
+ setEditorTheme(mq.matches ? 'github-dark' : 'github-light');
update();
- mq.addEventListener("change", update);
- return () => mq.removeEventListener("change", update);
+ mq.addEventListener('change', update);
+ return () => mq.removeEventListener('change', update);
}, []);
const send = useCallback((c: string) => {
const win = iframeRef.current?.contentWindow;
- if (!win) return;
+ if (!win) {
+ return;
+ }
win.postMessage(
- c ? {type: "preview-code", code: c} : {type: "preview-clear"},
+ c ? {type: 'preview-code', code: c} : {type: 'preview-clear'},
window.location.origin,
);
}, []);
useEffect(() => {
const handler = (e: MessageEvent) => {
- if (e.source !== iframeRef.current?.contentWindow) return;
- if (e.data?.type === "preview-ready") {
+ if (e.source !== iframeRef.current?.contentWindow) {
+ return;
+ }
+ if (e.data?.type === 'preview-ready') {
readyRef.current = true;
setPreviewReady(true);
if (pendingRef.current != null) {
@@ -324,34 +344,53 @@ export function PlaygroundClient() {
pendingRef.current = null;
}
}
- if (e.data?.type === "preview-rendered") setPreviewError(null);
- if (e.data?.type === "preview-error") setPreviewError(e.data.message ?? "Unknown error");
+ if (e.data?.type === 'preview-rendered') {
+ setPreviewError(null);
+ }
+ if (e.data?.type === 'preview-error') {
+ setPreviewError(e.data.message ?? 'Unknown error');
+ }
};
- window.addEventListener("message", handler);
- return () => window.removeEventListener("message", handler);
+ window.addEventListener('message', handler);
+ return () => window.removeEventListener('message', handler);
}, [send]);
useEffect(() => {
const interval = setInterval(() => {
- if (readyRef.current) { clearInterval(interval); return; }
- iframeRef.current?.contentWindow?.postMessage({type: "preview-ping"}, window.location.origin);
+ if (readyRef.current) {
+ clearInterval(interval);
+ return;
+ }
+ iframeRef.current?.contentWindow?.postMessage(
+ {type: 'preview-ping'},
+ window.location.origin,
+ );
}, 300);
return () => clearInterval(interval);
}, []);
useEffect(() => {
- if (debounceRef.current) clearTimeout(debounceRef.current);
+ if (debounceRef.current) {
+ clearTimeout(debounceRef.current);
+ }
debounceRef.current = setTimeout(() => {
- if (!readyRef.current) pendingRef.current = code;
- else send(code);
+ if (!readyRef.current) {
+ pendingRef.current = code;
+ } else {
+ send(code);
+ }
updateURL(code);
}, 400);
- return () => { if (debounceRef.current) clearTimeout(debounceRef.current); };
+ return () => {
+ if (debounceRef.current) {
+ clearTimeout(debounceRef.current);
+ }
+ };
}, [code, send]);
useEffect(() => {
iframeRef.current?.contentWindow?.postMessage(
- {type: "preview-theme", theme},
+ {type: 'preview-theme', theme},
window.location.origin,
);
}, [theme]);
@@ -363,14 +402,11 @@ export function PlaygroundClient() {
});
}, []);
- const handleMonacoBeforeMount = useCallback(
- (monaco: MonacoInstance) => {
- // Register themes before editor renders so initial theme applies
- monaco.editor.defineTheme("github-light", githubLight);
- monaco.editor.defineTheme("github-dark", githubDark);
- },
- [],
- );
+ const handleMonacoBeforeMount = useCallback((monaco: MonacoInstance) => {
+ // Register themes before editor renders so initial theme applies
+ monaco.editor.defineTheme('github-light', githubLight);
+ monaco.editor.defineTheme('github-dark', githubDark);
+ }, []);
const handleMonacoMount = useCallback(
(_editor: unknown, monaco: MonacoInstance) => {
@@ -379,19 +415,19 @@ export function PlaygroundClient() {
[],
);
- const isMobile = typeof window !== "undefined" && window.innerWidth <= 768;
+ const isMobile = typeof window !== 'undefined' && window.innerWidth <= 768;
const editorOptions = useMemo(
() => ({
minimap: {enabled: false},
fontSize: isMobile ? 16 : 13,
- lineNumbers: "on" as const,
+ lineNumbers: 'on' as const,
scrollBeyondLastLine: false,
automaticLayout: true,
tabSize: 2,
- wordWrap: "on" as const,
+ wordWrap: 'on' as const,
padding: {top: 12},
- accessibilitySupport: "off" as const,
+ accessibilitySupport: 'off' as const,
}),
[isMobile],
);
@@ -401,11 +437,13 @@ export function PlaygroundClient() {
<div {...stylex.props(s.toolbar)}>
<XDSHStack gap={8} align="center">
<XDSStatusDot
- variant={previewError ? "error" : previewReady ? "success" : "warning"}
- label={previewError ? "Error" : previewReady ? "Ready" : "Loading"}
+ variant={
+ previewError ? 'error' : previewReady ? 'success' : 'warning'
+ }
+ label={previewError ? 'Error' : previewReady ? 'Ready' : 'Loading'}
/>
<XDSText color="secondary" type="supporting">
- {previewError ? "Error" : previewReady ? "Ready" : "Loading…"}
+ {previewError ? 'Error' : previewReady ? 'Ready' : 'Loading…'}
</XDSText>
</XDSHStack>
<XDSHStack gap={4} align="center">
@@ -424,8 +462,8 @@ export function PlaygroundClient() {
onClick={() => setCode(DEFAULT_CODE)}
/>
<XDSButton
- label={copied ? "✓ Copied!" : "Copy Link"}
- variant={copied ? "primary" : "secondary"}
+ label={copied ? '✓ Copied!' : 'Copy Link'}
+ variant={copied ? 'primary' : 'secondary'}
size="sm"
onClick={handleShare}
/>
@@ -435,14 +473,15 @@ export function PlaygroundClient() {
<div {...stylex.props(s.main)}>
<div
{...stylex.props(s.editorPane)}
- style={isMobile ? {height: editorPanel.size} : {width: editorPanel.size}}
- >
+ style={
+ isMobile ? {height: editorPanel.size} : {width: editorPanel.size}
+ }>
<MonacoEditor
defaultLanguage="typescript"
defaultValue={code}
path="playground.tsx"
theme={editorTheme}
- onChange={(v) => setCode(v ?? "")}
+ onChange={v => setCode(v ?? '')}
beforeMount={handleMonacoBeforeMount}
onMount={handleMonacoMount}
options={editorOptions}
@@ -450,14 +489,16 @@ export function PlaygroundClient() {
</div>
<XDSResizeHandle
label="Resize editor panel"
- direction={isMobile ? "vertical" : "horizontal"}
+ direction={isMobile ? 'vertical' : 'horizontal'}
hasDivider
- pillPlacement={isMobile ? "end" : "auto"}
+ pillPlacement={isMobile ? 'end' : 'auto'}
resizable={editorPanel.props}
/>
<div {...stylex.props(s.previewPane)}>
<div {...stylex.props(s.previewBar)}>
- <XDSText color="secondary" type="supporting">Preview</XDSText>
+ <XDSText color="secondary" type="supporting">
+ Preview
+ </XDSText>
<XDSText color="disabled" type="supporting">
{theme.charAt(0).toUpperCase() + theme.slice(1)}
</XDSText>
@@ -475,9 +516,13 @@ export function PlaygroundClient() {
{previewError && (
<>
<XDSDivider />
- <div style={{padding: "8px 16px", maxHeight: 120, overflow: "auto"}}>
+ <div style={{padding: '8px 16px', maxHeight: 120, overflow: 'auto'}}>
<XDSText type="code" color="inherit">
- <span style={{color: "var(--color-text-error, #ef4444)", whiteSpace: "pre-wrap"}}>
+ <span
+ style={{
+ color: 'var(--color-text-error, #ef4444)',
+ whiteSpace: 'pre-wrap',
+ }}>
{previewError}
</span>
</XDSText>
diff --git a/apps/docsite/src/components/ChangelogView.tsx b/apps/docsite/src/components/ChangelogView.tsx
index 1c288f7102..94167d05e5 100644
--- a/apps/docsite/src/components/ChangelogView.tsx
+++ b/apps/docsite/src/components/ChangelogView.tsx
@@ -21,7 +21,9 @@ function stripTitle(markdown: string): string {
}
function linkifyComponents(markdown: string, names: string[]): string {
- if (names.length === 0) return markdown;
+ if (names.length === 0) {
+ return markdown;
+ }
const nameToHref = new Map<string, string>();
for (const name of names) {
@@ -38,7 +40,9 @@ function linkifyComponents(markdown: string, names: string[]): string {
return markdown.replace(pattern, match => {
const href = nameToHref.get(match);
- if (!href) return match;
+ if (!href) {
+ return match;
+ }
return '[' + match + '](' + href + ')';
});
}
diff --git a/apps/docsite/src/components/DocsShell.tsx b/apps/docsite/src/components/DocsShell.tsx
index 3f44878b52..1811c1095f 100644
--- a/apps/docsite/src/components/DocsShell.tsx
+++ b/apps/docsite/src/components/DocsShell.tsx
@@ -26,8 +26,12 @@ interface DocsShellProps {
/** Foundations: tokens first, then alphabetical */
const foundationsSort = (a: DocTopic, b: DocTopic) => {
- if (a.topic === 'tokens') return -1;
- if (b.topic === 'tokens') return 1;
+ if (a.topic === 'tokens') {
+ return -1;
+ }
+ if (b.topic === 'tokens') {
+ return 1;
+ }
return a.title.localeCompare(b.title);
};
@@ -40,7 +44,9 @@ function buildComponentSidebar(): {
utilities: Array<{name: string; href: string}>;
} {
const grouped = groupedComponents['@xds/core'];
- if (!grouped) return {componentItems: [], utilities: []};
+ if (!grouped) {
+ return {componentItems: [], utilities: []};
+ }
return {componentItems: grouped.items, utilities: grouped.utilities};
}
diff --git a/apps/docsite/src/components/SearchPalette.tsx b/apps/docsite/src/components/SearchPalette.tsx
index 50f83d13d9..f8bb882067 100644
--- a/apps/docsite/src/components/SearchPalette.tsx
+++ b/apps/docsite/src/components/SearchPalette.tsx
@@ -43,7 +43,9 @@ export function SearchPalette({
for (const entries of Object.values(components)) {
for (const comp of entries) {
- if (comp.hidden || comp.parentDoc) continue;
+ if (comp.hidden || comp.parentDoc) {
+ continue;
+ }
items.push({
id: `/components/${comp.name}`,
label: comp.name,
diff --git a/apps/docsite/src/components/ShowcaseThumbnail.tsx b/apps/docsite/src/components/ShowcaseThumbnail.tsx
index 05ac23f444..f258a1df69 100644
--- a/apps/docsite/src/components/ShowcaseThumbnail.tsx
+++ b/apps/docsite/src/components/ShowcaseThumbnail.tsx
@@ -130,7 +130,9 @@ export function ShowcaseThumbnail({
useEffect(() => {
const el = containerRef.current;
- if (!el) return;
+ if (!el) {
+ return;
+ }
const observer = new IntersectionObserver(
([entry]) => setIsVisible(entry.isIntersecting),
{rootMargin: '200px'},
@@ -142,7 +144,9 @@ export function ShowcaseThumbnail({
useEffect(() => {
updateWidth();
const el = containerRef.current;
- if (!el) return;
+ if (!el) {
+ return;
+ }
const ro = new ResizeObserver(updateWidth);
ro.observe(el);
return () => ro.disconnect();
diff --git a/apps/docsite/src/components/TemplateThumbnail.tsx b/apps/docsite/src/components/TemplateThumbnail.tsx
index f7611330e6..3d9827509a 100644
--- a/apps/docsite/src/components/TemplateThumbnail.tsx
+++ b/apps/docsite/src/components/TemplateThumbnail.tsx
@@ -180,7 +180,9 @@ export function TemplateThumbnail({slug}: {slug: string}) {
// Intersection observer: track visibility for Activity mode
useEffect(() => {
const el = containerRef.current;
- if (!el) return;
+ if (!el) {
+ return;
+ }
const observer = new IntersectionObserver(
([entry]) => setIsVisible(entry.isIntersecting),
@@ -194,14 +196,18 @@ export function TemplateThumbnail({slug}: {slug: string}) {
useEffect(() => {
updateWidth();
const el = containerRef.current;
- if (!el) return;
+ if (!el) {
+ return;
+ }
const ro = new ResizeObserver(updateWidth);
ro.observe(el);
return () => ro.disconnect();
}, [updateWidth]);
const Component = TEMPLATE_COMPONENTS[slug];
- if (!Component) return null;
+ if (!Component) {
+ return null;
+ }
return (
<div ref={containerRef} {...stylex.props(styles.container)} inert>
diff --git a/apps/docsite/src/components/ThemeShowcasePreview.tsx b/apps/docsite/src/components/ThemeShowcasePreview.tsx
index 7b76955769..df2ac3a675 100644
--- a/apps/docsite/src/components/ThemeShowcasePreview.tsx
+++ b/apps/docsite/src/components/ThemeShowcasePreview.tsx
@@ -153,7 +153,9 @@ function FontLabel({cssVar, fallback}: {cssVar: string; fallback: string}) {
const [label, setLabel] = useState(fallback);
useEffect(() => {
- if (!ref.current) return;
+ if (!ref.current) {
+ return;
+ }
const computed = getComputedStyle(ref.current)
.getPropertyValue(cssVar)
.trim();
diff --git a/apps/docsite/src/components/component-detail/Anatomy.tsx b/apps/docsite/src/components/component-detail/Anatomy.tsx
index b9b38c7557..e89356bb99 100644
--- a/apps/docsite/src/components/component-detail/Anatomy.tsx
+++ b/apps/docsite/src/components/component-detail/Anatomy.tsx
@@ -14,7 +14,9 @@ interface AnatomyProps {
}
export function Anatomy({elements}: AnatomyProps) {
- if (elements.length === 0) return null;
+ if (elements.length === 0) {
+ return null;
+ }
const data = elements.map(el => ({
name: el.name as unknown,
diff --git a/apps/docsite/src/components/component-detail/BestPractices.tsx b/apps/docsite/src/components/component-detail/BestPractices.tsx
index 2d170228d1..bd288fa93e 100644
--- a/apps/docsite/src/components/component-detail/BestPractices.tsx
+++ b/apps/docsite/src/components/component-detail/BestPractices.tsx
@@ -11,7 +11,9 @@ interface BestPracticesProps {
}
export function BestPractices({practices}: BestPracticesProps) {
- if (practices.length === 0) return null;
+ if (practices.length === 0) {
+ return null;
+ }
return (
<XDSSection>
diff --git a/apps/docsite/src/components/component-detail/InteractivePreview.tsx b/apps/docsite/src/components/component-detail/InteractivePreview.tsx
index 962b9150a9..84218090e9 100644
--- a/apps/docsite/src/components/component-detail/InteractivePreview.tsx
+++ b/apps/docsite/src/components/component-detail/InteractivePreview.tsx
@@ -63,7 +63,9 @@ class PreviewErrorBoundary extends Component<
}
function pickPrimaryProps(name: string, props: PropDoc[]): KnobProp[] {
- if (props.length === 0) return [];
+ if (props.length === 0) {
+ return [];
+ }
return props.map(row => ({
row,
control: parsePropType(row.type, row.name, row.slotElements),
@@ -85,7 +87,9 @@ function buildInitialState(
// Fill in remaining props from doc defaults / auto-generation
for (const {row, control} of knobs) {
- if (state[row.name] !== undefined) continue;
+ if (state[row.name] !== undefined) {
+ continue;
+ }
const def = coerceDefault(row.default, control);
if (def !== undefined) {
state[row.name] = def;
@@ -130,11 +134,18 @@ function buildInitialState(
}
function formatValue(value: unknown): string {
- if (value === undefined) return 'undefined';
- if (value === null) return 'null';
- if (typeof value === 'string') return `"${value}"`;
- if (typeof value === 'boolean' || typeof value === 'number')
+ if (value === undefined) {
+ return 'undefined';
+ }
+ if (value === null) {
+ return 'null';
+ }
+ if (typeof value === 'string') {
+ return `"${value}"`;
+ }
+ if (typeof value === 'boolean' || typeof value === 'number') {
return String(value);
+ }
if (isValidElement(value)) {
const el = value as React.ReactElement<Record<string, unknown>>;
const type =
@@ -144,11 +155,15 @@ function formatValue(value: unknown): string {
el.type.name ??
'Component');
const props = el.props;
- if (!props || Object.keys(props).length === 0) return `<${type} />`;
+ if (!props || Object.keys(props).length === 0) {
+ return `<${type} />`;
+ }
const propStr = Object.entries(props)
.filter(([k]) => k !== 'children')
.map(([k, v]) => {
- if (typeof v === 'string') return `${k}="${v}"`;
+ if (typeof v === 'string') {
+ return `${k}="${v}"`;
+ }
return `${k}={${JSON.stringify(v)}}`;
})
.join(' ');
@@ -164,11 +179,17 @@ function generateCode(name: string, state: Record<string, unknown>): string {
([k, v]) => v !== undefined && k !== 'isInline',
);
- if (entries.length === 0) return `<${componentName} />`;
+ if (entries.length === 0) {
+ return `<${componentName} />`;
+ }
const propLines = entries.map(([key, value]) => {
- if (typeof value === 'boolean' && value === true) return ` ${key}`;
- if (typeof value === 'string') return ` ${key}="${value}"`;
+ if (typeof value === 'boolean' && value === true) {
+ return ` ${key}`;
+ }
+ if (typeof value === 'string') {
+ return ` ${key}="${value}"`;
+ }
return ` ${key}={${formatValue(value)}}`;
});
diff --git a/apps/docsite/src/components/component-detail/PlaygroundPropsTable.tsx b/apps/docsite/src/components/component-detail/PlaygroundPropsTable.tsx
index abb823c694..383335e72b 100644
--- a/apps/docsite/src/components/component-detail/PlaygroundPropsTable.tsx
+++ b/apps/docsite/src/components/component-detail/PlaygroundPropsTable.tsx
@@ -120,8 +120,9 @@ function ElementControl({
onChange(undefined);
} else {
const opt = control.options.find(o => o.label === next);
- if (opt)
+ if (opt) {
onChange(resolveSlotElement(opt.componentName, prop.slotElements));
+ }
}
}}
/>
@@ -144,12 +145,18 @@ function SlotListControl({
const addItem = () => {
const slotEl = prop.slotElements?.[0];
- if (!slotEl) return;
+ if (!slotEl) {
+ return;
+ }
const n = count + 1;
const tweaked = {...slotEl};
const props = {...(tweaked.props ?? {})};
- if (typeof props.label === 'string') props.label = `${props.label} ${n}`;
- if (typeof props.value === 'string') props.value = `${props.value}-${n}`;
+ if (typeof props.label === 'string') {
+ props.label = `${props.label} ${n}`;
+ }
+ if (typeof props.value === 'string') {
+ props.value = `${props.value}-${n}`;
+ }
tweaked.props = props;
const children =
typeof tweaked.children === 'string'
@@ -163,7 +170,9 @@ function SlotListControl({
};
const removeItem = () => {
- if (count > 0) onChange(items.slice(0, -1));
+ if (count > 0) {
+ onChange(items.slice(0, -1));
+ }
};
return (
diff --git a/apps/docsite/src/components/component-detail/PropsTable.tsx b/apps/docsite/src/components/component-detail/PropsTable.tsx
index 6a063baf2f..afd3548d1d 100644
--- a/apps/docsite/src/components/component-detail/PropsTable.tsx
+++ b/apps/docsite/src/components/component-detail/PropsTable.tsx
@@ -22,7 +22,9 @@ interface PropsTableProps {
}
export function PropsTable({props, heading}: PropsTableProps) {
- if (props.length === 0) return null;
+ if (props.length === 0) {
+ return null;
+ }
const required = props.filter(p => p.required);
const optional = props.filter(p => !p.required);
diff --git a/apps/docsite/src/components/component-detail/parsePropType.ts b/apps/docsite/src/components/component-detail/parsePropType.ts
index 9f8e415f8a..05fa7655a0 100644
--- a/apps/docsite/src/components/component-detail/parsePropType.ts
+++ b/apps/docsite/src/components/component-detail/parsePropType.ts
@@ -38,7 +38,9 @@ function splitUnion(input: string): string[] {
const c = input[i];
if (inString) {
- if (c === inString && input[i - 1] !== '\\') inString = null;
+ if (c === inString && input[i - 1] !== '\\') {
+ inString = null;
+ }
continue;
}
@@ -47,9 +49,11 @@ function splitUnion(input: string): string[] {
continue;
}
- if (c === '(' || c === '[' || c === '{' || c === '<') depth++;
- else if (c === ')' || c === ']' || c === '}' || c === '>') depth--;
- else if (c === '|' && depth === 0) {
+ if (c === '(' || c === '[' || c === '{' || c === '<') {
+ depth++;
+ } else if (c === ')' || c === ']' || c === '}' || c === '>') {
+ depth--;
+ } else if (c === '|' && depth === 0) {
parts.push(input.slice(start, i).trim());
start = i + 1;
}
@@ -65,7 +69,9 @@ export function parsePropType(
slotElements?: Array<{__element: string; props?: Record<string, unknown>}>,
): PropControlDescriptor {
const t = typeStr.trim();
- if (!t) return {kind: 'unknown'};
+ if (!t) {
+ return {kind: 'unknown'};
+ }
// If slotElements is declared, use it directly for the element control
if (slotElements && slotElements.length > 0) {
@@ -80,11 +86,19 @@ export function parsePropType(
return {kind: 'element', options};
}
- if (CALLBACK_RE.test(t)) return {kind: 'callback'};
+ if (CALLBACK_RE.test(t)) {
+ return {kind: 'callback'};
+ }
- if (t === 'boolean') return {kind: 'boolean'};
- if (t === 'string') return {kind: 'string'};
- if (t === 'number') return {kind: 'number'};
+ if (t === 'boolean') {
+ return {kind: 'boolean'};
+ }
+ if (t === 'string') {
+ return {kind: 'string'};
+ }
+ if (t === 'number') {
+ return {kind: 'number'};
+ }
if (t === 'SpacingStep') {
return {
@@ -93,7 +107,9 @@ export function parsePropType(
allowEmpty: false,
};
}
- if (t === 'SizeValue') return {kind: 'number'};
+ if (t === 'SizeValue') {
+ return {kind: 'number'};
+ }
if (t === 'XDSIconType' || t === 'XDSIconName') {
return {
kind: 'enum',
@@ -203,9 +219,13 @@ export function coerceDefault(
raw: string | undefined,
control: PropControlDescriptor,
): unknown {
- if (raw == null) return undefined;
+ if (raw == null) {
+ return undefined;
+ }
const v = raw.trim();
- if (!v) return undefined;
+ if (!v) {
+ return undefined;
+ }
switch (control.kind) {
case 'boolean':
diff --git a/apps/docsite/src/components/component-detail/resolveElements.ts b/apps/docsite/src/components/component-detail/resolveElements.ts
index 4866631ce1..20032efa8a 100644
--- a/apps/docsite/src/components/component-detail/resolveElements.ts
+++ b/apps/docsite/src/components/component-detail/resolveElements.ts
@@ -60,6 +60,8 @@ export function resolveElementDescriptor(
}
export function resolveValue(v: unknown): unknown {
- if (isElementDescriptor(v)) return resolveElementDescriptor(v);
+ if (isElementDescriptor(v)) {
+ return resolveElementDescriptor(v);
+ }
return v;
}
diff --git a/apps/docsite/src/components/tokens/MotionTokenTable.tsx b/apps/docsite/src/components/tokens/MotionTokenTable.tsx
index 27cc64ca47..3d0fc8fc85 100644
--- a/apps/docsite/src/components/tokens/MotionTokenTable.tsx
+++ b/apps/docsite/src/components/tokens/MotionTokenTable.tsx
@@ -82,9 +82,13 @@ function evaluateBezier(
let g = t;
for (let i = 0; i < 8; i++) {
const cur = sampleX(g) - t;
- if (Math.abs(cur) < 1e-6) break;
+ if (Math.abs(cur) < 1e-6) {
+ break;
+ }
const d = sampleXDeriv(g);
- if (Math.abs(d) < 1e-6) break;
+ if (Math.abs(d) < 1e-6) {
+ break;
+ }
g -= cur / d;
}
return sampleY(Math.max(0, Math.min(1, g)));
@@ -99,28 +103,39 @@ function EasingCurve({value}: {value: string}) {
);
useEffect(() => {
- if (!match) return;
+ if (!match) {
+ return;
+ }
let running = true;
const duration = 1200,
pause = 800,
cycle = duration + pause;
function tick(ts: number) {
- if (!running) return;
- if (!startRef.current) startRef.current = ts;
+ if (!running) {
+ return;
+ }
+ if (!startRef.current) {
+ startRef.current = ts;
+ }
const inCycle = (ts - startRef.current) % cycle;
setProgress(inCycle < duration ? inCycle / duration : 1);
- if ((ts - startRef.current) % (cycle * 2) >= cycle * 2 - 16)
+ if ((ts - startRef.current) % (cycle * 2) >= cycle * 2 - 16) {
startRef.current = ts;
+ }
animRef.current = requestAnimationFrame(tick);
}
animRef.current = requestAnimationFrame(tick);
return () => {
running = false;
- if (animRef.current) cancelAnimationFrame(animRef.current);
+ if (animRef.current) {
+ cancelAnimationFrame(animRef.current);
+ }
};
}, [match]);
- if (!match) return null;
+ if (!match) {
+ return null;
+ }
const [, x1, y1, x2, y2] = match.map(Number);
const easedY = evaluateBezier(x1, y1, x2, y2, progress);
const pad = 0.12;
diff --git a/apps/docsite/src/components/tokens/ShapeTokenTable.tsx b/apps/docsite/src/components/tokens/ShapeTokenTable.tsx
index d787cb2e01..ff510bbc30 100644
--- a/apps/docsite/src/components/tokens/ShapeTokenTable.tsx
+++ b/apps/docsite/src/components/tokens/ShapeTokenTable.tsx
@@ -63,7 +63,9 @@ export function RadiusTokenTable({theme}: TokenTableProps) {
export function BorderTokenTable({theme}: TokenTableProps) {
const tokens = getTokensByPrefix(theme, '--border-');
- if (tokens.length === 0) return null;
+ if (tokens.length === 0) {
+ return null;
+ }
const data = tokens.map(name => ({
tokenName: name,
diff --git a/apps/sandbox/src/app/(fullscreen)/PreviewShell.tsx b/apps/sandbox/src/app/(fullscreen)/PreviewShell.tsx
index 3586e6d3e5..d54d81cc5a 100644
--- a/apps/sandbox/src/app/(fullscreen)/PreviewShell.tsx
+++ b/apps/sandbox/src/app/(fullscreen)/PreviewShell.tsx
@@ -39,7 +39,9 @@ function buildNavTree(currentPath: string): XDSTreeListItemData[] {
const componentMap = new Map<string, XDSTreeListItemData[]>();
for (const b of blocks) {
const group = b.component;
- if (!componentMap.has(group)) componentMap.set(group, []);
+ if (!componentMap.has(group)) {
+ componentMap.set(group, []);
+ }
const shortName = b.name.includes('—')
? b.name.split('—').slice(1).join('—').trim()
: b.name;
@@ -269,11 +271,17 @@ type Version = {
function formatRelativeTime(ts: number): string {
const diff = Date.now() - ts;
const seconds = Math.floor(diff / 1000);
- if (seconds < 60) return 'just now';
+ if (seconds < 60) {
+ return 'just now';
+ }
const minutes = Math.floor(seconds / 60);
- if (minutes < 60) return `${minutes} min ago`;
+ if (minutes < 60) {
+ return `${minutes} min ago`;
+ }
const hours = Math.floor(minutes / 60);
- if (hours < 24) return `${hours}h ago`;
+ if (hours < 24) {
+ return `${hours}h ago`;
+ }
const days = Math.floor(hours / 24);
return `${days}d ago`;
}
@@ -369,7 +377,9 @@ function VersionDropdown({pathname}: {pathname: string}) {
useEffect(() => {
try {
const stored = localStorage.getItem(getStorageKey(pathname));
- if (stored) setLocalVersions(JSON.parse(stored));
+ if (stored) {
+ setLocalVersions(JSON.parse(stored));
+ }
} catch {
// ignore
}
@@ -403,7 +413,9 @@ function VersionDropdown({pathname}: {pathname: string}) {
// Click outside to close
useEffect(() => {
- if (!isOpen) return;
+ if (!isOpen) {
+ return;
+ }
const handler = (e: MouseEvent) => {
if (
dropdownRef.current &&
@@ -419,7 +431,9 @@ function VersionDropdown({pathname}: {pathname: string}) {
const handleSave = () => {
const nextNum = localVersions.length + 1;
const name = prompt('Version name:', `Version ${nextNum}`);
- if (!name) return;
+ if (!name) {
+ return;
+ }
const newVersion: Version = {
id: crypto.randomUUID(),
name,
@@ -627,7 +641,9 @@ export function PreviewShell({children}: {children: React.ReactNode}) {
typeof window !== 'undefined' ? window.location.search : '',
);
const isEmbed = searchParams.get('embed') === '1';
- if (isEmbed) return <>{children}</>;
+ if (isEmbed) {
+ return <>{children}</>;
+ }
const [view, setView] = useState<'preview' | 'code'>('preview');
const [viewport, setViewport] = useState<ViewportSize>('desktop');
const [copied, setCopied] = useState(false);
@@ -640,15 +656,16 @@ export function PreviewShell({children}: {children: React.ReactNode}) {
// on initial load. Only recomputes when pathname changes — theme/mode changes
// are synced to the iframe via postMessage to avoid triggering a reload.
const iframeSrc = useMemo(
- () =>
- `${basePath}${pathname}?embed=1&theme=${themeName}&mode=${mode}`,
+ () => `${basePath}${pathname}?embed=1&theme=${themeName}&mode=${mode}`,
[pathname], // intentionally excludes themeName/mode — live updates use postMessage
);
// Broadcast theme/mode changes to the embedded iframe via postMessage
useEffect(() => {
const iframe = iframeRef.current;
- if (!iframe?.contentWindow) return;
+ if (!iframe?.contentWindow) {
+ return;
+ }
iframe.contentWindow.postMessage(
{type: 'xds-theme-sync', theme: themeName, mode},
'*',
@@ -665,7 +682,9 @@ export function PreviewShell({children}: {children: React.ReactNode}) {
useEffect(() => {
const saved = localStorage.getItem('sandbox-toolbar-hidden');
- if (saved === 'true') setToolbarHidden(true);
+ if (saved === 'true') {
+ setToolbarHidden(true);
+ }
}, []);
useEffect(() => {
@@ -689,8 +708,9 @@ export function PreviewShell({children}: {children: React.ReactNode}) {
for (const page of cat.pages) {
const normalizedHref = page.href.replace(/\/$/, '');
const normalizedPath = pathname.replace(/\/$/, '');
- if (normalizedHref === normalizedPath)
+ if (normalizedHref === normalizedPath) {
return {page, category: cat.label};
+ }
}
}
return null;
@@ -731,7 +751,9 @@ export function PreviewShell({children}: {children: React.ReactNode}) {
}, []);
const handleCopy = useCallback(async () => {
- if (!resolvedSource) return;
+ if (!resolvedSource) {
+ return;
+ }
await navigator.clipboard.writeText(resolvedSource);
setCopied(true);
setTimeout(() => setCopied(false), 2000);
diff --git a/apps/sandbox/src/app/(fullscreen)/pages/codeblock-perf/page.tsx b/apps/sandbox/src/app/(fullscreen)/pages/codeblock-perf/page.tsx
index da3ba40154..6d5df88781 100644
--- a/apps/sandbox/src/app/(fullscreen)/pages/codeblock-perf/page.tsx
+++ b/apps/sandbox/src/app/(fullscreen)/pages/codeblock-perf/page.tsx
@@ -133,12 +133,16 @@ function usePerfMetrics() {
const runScrollTest = useCallback(() => {
const el = scrollRef.current;
- if (!el) return;
+ if (!el) {
+ return;
+ }
const scrollContainer =
el.querySelector<HTMLElement>('[style*="max-height"]') ??
el.querySelector<HTMLElement>('pre');
- if (!scrollContainer) return;
+ if (!scrollContainer) {
+ return;
+ }
scrollContainer.scrollTop = 0;
const s = scrollState.current;
@@ -149,10 +153,14 @@ function usePerfMetrics() {
s.lastFrameTime = performance.now();
function tick() {
- if (!s.measuring) return;
+ if (!s.measuring) {
+ return;
+ }
const now = performance.now();
s.frames++;
- if (now - s.lastFrameTime > 20) s.drops++;
+ if (now - s.lastFrameTime > 20) {
+ s.drops++;
+ }
s.lastFrameTime = now;
s.rafId = requestAnimationFrame(tick);
}
@@ -201,14 +209,22 @@ function metricVariant(
value: number | null,
thresholds?: {good: number; warn: number},
): 'green' | 'orange' | 'red' | 'neutral' {
- if (value == null || !thresholds) return 'neutral';
- if (value <= thresholds.good) return 'green';
- if (value <= thresholds.warn) return 'orange';
+ if (value == null || !thresholds) {
+ return 'neutral';
+ }
+ if (value <= thresholds.good) {
+ return 'green';
+ }
+ if (value <= thresholds.warn) {
+ return 'orange';
+ }
return 'red';
}
function formatMetric(value: number | null, unit: string): string {
- if (value == null) return '\u2014';
+ if (value == null) {
+ return '\u2014';
+ }
return `${value.toFixed(1)}${unit}`;
}
diff --git a/apps/sandbox/src/app/(fullscreen)/pages/dictation-lab/page.tsx b/apps/sandbox/src/app/(fullscreen)/pages/dictation-lab/page.tsx
index 2204f376de..72cdf15525 100644
--- a/apps/sandbox/src/app/(fullscreen)/pages/dictation-lab/page.tsx
+++ b/apps/sandbox/src/app/(fullscreen)/pages/dictation-lab/page.tsx
@@ -679,8 +679,9 @@ export default function DictationLabPage() {
const pattern = notePatterns.find(
p => p.id === selectedPattern,
);
- if (style && pattern)
+ if (style && pattern) {
playMixedNotes(pattern.startNotes, style, volume);
+ }
}}
/>
<XDSButton
@@ -692,8 +693,9 @@ export default function DictationLabPage() {
const pattern = notePatterns.find(
p => p.id === selectedPattern,
);
- if (style && pattern)
+ if (style && pattern) {
playMixedNotes(pattern.stopNotes, style, volume);
+ }
}}
/>
</XDSHStack>
diff --git a/apps/sandbox/src/app/(fullscreen)/pages/docsite/AppTopNav.tsx b/apps/sandbox/src/app/(fullscreen)/pages/docsite/AppTopNav.tsx
index fa9eebf6a6..f83519accb 100644
--- a/apps/sandbox/src/app/(fullscreen)/pages/docsite/AppTopNav.tsx
+++ b/apps/sandbox/src/app/(fullscreen)/pages/docsite/AppTopNav.tsx
@@ -80,7 +80,9 @@ export function AppTopNav({
useEffect(() => {
const el = document.getElementById('docsite-scroll');
- if (!el) return;
+ if (!el) {
+ return;
+ }
const handleScroll = () => setIsScrolled(el.scrollTop > 170);
el.addEventListener('scroll', handleScroll, {passive: true});
handleScroll();
diff --git a/apps/sandbox/src/app/(fullscreen)/pages/docsite/ChatPanel.tsx b/apps/sandbox/src/app/(fullscreen)/pages/docsite/ChatPanel.tsx
index 014cb66e1e..96fc884c44 100644
--- a/apps/sandbox/src/app/(fullscreen)/pages/docsite/ChatPanel.tsx
+++ b/apps/sandbox/src/app/(fullscreen)/pages/docsite/ChatPanel.tsx
@@ -292,7 +292,9 @@ function CodeEditor() {
if (e.key === 'Tab') {
e.preventDefault();
const ta = textareaRef.current;
- if (!ta) return;
+ if (!ta) {
+ return;
+ }
const start = ta.selectionStart;
const end = ta.selectionEnd;
const val = ta.value;
@@ -472,7 +474,9 @@ export function ChatPanel({
}>
<XDSChatComposer
onSubmit={() => {
- if (!prompt.trim()) return;
+ if (!prompt.trim()) {
+ return;
+ }
setMessages(prev => [
...prev,
{role: 'user', text: prompt.trim()},
diff --git a/apps/sandbox/src/app/(fullscreen)/pages/docsite/DocsView.tsx b/apps/sandbox/src/app/(fullscreen)/pages/docsite/DocsView.tsx
index f8e14bb10b..918aed103e 100644
--- a/apps/sandbox/src/app/(fullscreen)/pages/docsite/DocsView.tsx
+++ b/apps/sandbox/src/app/(fullscreen)/pages/docsite/DocsView.tsx
@@ -329,7 +329,9 @@ function ItemText({item}: {item: ChangelogItem}) {
<span>
{parts.map((part, i) => {
const boldMatch = part.match(/^\*\*(.+)\*\*$/);
- if (boldMatch) return <strong key={i}>{boldMatch[1]}</strong>;
+ if (boldMatch) {
+ return <strong key={i}>{boldMatch[1]}</strong>;
+ }
return <span key={i}>{part}</span>;
})}
</span>
@@ -393,7 +395,9 @@ function ChangelogSection({
items: ChangelogItem[];
dotVariant: 'error' | 'success' | 'warning' | 'accent';
}) {
- if (items.length === 0) return null;
+ if (items.length === 0) {
+ return null;
+ }
return (
<XDSStack direction="vertical" gap={0} style={{marginBottom: 20}}>
<XDSStack
@@ -650,7 +654,9 @@ function DeprecationsPanel() {
const map = new Map<string, typeof deprecations>();
for (const d of deprecations) {
const key = d.file;
- if (!map.has(key)) map.set(key, []);
+ if (!map.has(key)) {
+ map.set(key, []);
+ }
map.get(key)!.push(d);
}
return Array.from(map.entries());
@@ -1645,7 +1651,9 @@ function TypographyFoundationPage() {
: String(scaleRatio)
}
onChange={(v: string) => {
- if (v !== 'custom') setScaleRatio(Number(v));
+ if (v !== 'custom') {
+ setScaleRatio(Number(v));
+ }
}}
/>
</div>
@@ -3606,7 +3614,9 @@ function ThemePackagePage({
onCraft?: () => void;
}) {
const theme = THEME_DETAILS[packageKey];
- if (!theme) return null;
+ if (!theme) {
+ return null;
+ }
const isDefault = packageKey === 'pkg-theme-default';
const themeObject = THEME_OBJECTS[packageKey];
@@ -4268,9 +4278,15 @@ function PublishingPage() {
}
function ResourcePage({resourceKey}: {resourceKey: string}) {
- if (resourceKey === 'res-npm') return <NpmPackagesPage />;
- if (resourceKey === 'res-agent-docs') return <AgentDocsPage />;
- if (resourceKey === 'res-publishing') return <PublishingPage />;
+ if (resourceKey === 'res-npm') {
+ return <NpmPackagesPage />;
+ }
+ if (resourceKey === 'res-agent-docs') {
+ return <AgentDocsPage />;
+ }
+ if (resourceKey === 'res-publishing') {
+ return <PublishingPage />;
+ }
return null;
}
@@ -4741,7 +4757,9 @@ function LibraryOverview({
const idx = offering.description.lastIndexOf(
offering.descriptionLinkText,
);
- if (idx === -1) return offering.description;
+ if (idx === -1) {
+ return offering.description;
+ }
return (
<>
{offering.description.slice(0, idx)}
diff --git a/apps/sandbox/src/app/(fullscreen)/pages/docsite/ProfileView.tsx b/apps/sandbox/src/app/(fullscreen)/pages/docsite/ProfileView.tsx
index b161684853..3b263287ad 100644
--- a/apps/sandbox/src/app/(fullscreen)/pages/docsite/ProfileView.tsx
+++ b/apps/sandbox/src/app/(fullscreen)/pages/docsite/ProfileView.tsx
@@ -65,10 +65,18 @@ function timeAgo(dateStr: string): string {
const then = new Date(dateStr);
const diffMs = now.getTime() - then.getTime();
const days = Math.floor(diffMs / (1000 * 60 * 60 * 24));
- if (days < 1) return 'today';
- if (days < 7) return `${days}d ago`;
- if (days < 30) return `${Math.floor(days / 7)}w ago`;
- if (days < 365) return `${Math.floor(days / 30)}mo ago`;
+ if (days < 1) {
+ return 'today';
+ }
+ if (days < 7) {
+ return `${days}d ago`;
+ }
+ if (days < 30) {
+ return `${Math.floor(days / 7)}w ago`;
+ }
+ if (days < 365) {
+ return `${Math.floor(days / 30)}mo ago`;
+ }
return `${Math.floor(days / 365)}y ago`;
}
@@ -456,7 +464,9 @@ function PreviewDialogShell({
<XDSDialog
isOpen={isOpen}
onOpenChange={open => {
- if (!open) onClose();
+ if (!open) {
+ onClose();
+ }
}}
width="90vw"
maxHeight="90vh"
@@ -608,7 +618,9 @@ export function ProfileView({
const setIsSettingsOpen = onSettingsChange;
const previewItem = useMemo(() => {
- if (!profileCraftName) return null;
+ if (!profileCraftName) {
+ return null;
+ }
return (PROFILE_CRAFT_ITEMS.find(i => i.name === profileCraftName) ??
null) as CraftItem | null;
}, [profileCraftName]);
@@ -661,7 +673,9 @@ export function ProfileView({
const [usedSort, setUsedSort] = useState('recent');
const [usedTypeFilter, setUsedTypeFilter] = useState('all');
const previewUsedItem = useMemo(() => {
- if (!profileUsedName) return null;
+ if (!profileUsedName) {
+ return null;
+ }
return (PROFILE_USED_ITEMS.find(i => i.name === profileUsedName) ??
null) as UsedItem | null;
}, [profileUsedName]);
@@ -743,7 +757,9 @@ export function ProfileView({
items: [] as string[],
};
}
- if (!profileCollectionName) return null;
+ if (!profileCollectionName) {
+ return null;
+ }
return (
PROFILE_COLLECTIONS.find(c => c.name === profileCollectionName) ?? null
);
@@ -763,8 +779,12 @@ export function ProfileView({
items = items.filter(i => i.status === craftStatusFilter);
}
items.sort((a, b) => {
- if (craftSort === 'views') return b.views - a.views;
- if (craftSort === 'uses') return b.used - a.used;
+ if (craftSort === 'views') {
+ return b.views - a.views;
+ }
+ if (craftSort === 'uses') {
+ return b.used - a.used;
+ }
return (
new Date(b.lastUpdated).getTime() - new Date(a.lastUpdated).getTime()
);
@@ -786,8 +806,12 @@ export function ProfileView({
);
}
items.sort((a, b) => {
- if (usedSort === 'frequency') return b.usageCount - a.usageCount;
- if (usedSort === 'name') return a.name.localeCompare(b.name);
+ if (usedSort === 'frequency') {
+ return b.usageCount - a.usageCount;
+ }
+ if (usedSort === 'name') {
+ return a.name.localeCompare(b.name);
+ }
return new Date(b.lastUsed).getTime() - new Date(a.lastUsed).getTime();
});
return items;
@@ -807,7 +831,9 @@ export function ProfileView({
}, [bookmarkSearch, removedBookmarks]);
const collectionItems = useMemo(() => {
- if (!selectedCollection) return [];
+ if (!selectedCollection) {
+ return [];
+ }
const itemNames = new Set(selectedCollection.items);
return PROFILE_LIKED_ITEMS.filter(
i => itemNames.has(i.name) && !removedBookmarks.has(i.name),
@@ -1172,8 +1198,11 @@ export function ProfileView({
onClick={() => {
setCollectionItemsDraft(prev => {
const next = new Set(prev);
- if (next.has(item.name)) next.delete(item.name);
- else next.add(item.name);
+ if (next.has(item.name)) {
+ next.delete(item.name);
+ } else {
+ next.add(item.name);
+ }
return next;
});
}}
@@ -1213,9 +1242,11 @@ export function ProfileView({
onChange={() => {
setCollectionItemsDraft(prev => {
const next = new Set(prev);
- if (next.has(item.name))
+ if (next.has(item.name)) {
next.delete(item.name);
- else next.add(item.name);
+ } else {
+ next.add(item.name);
+ }
return next;
});
}}
@@ -1691,7 +1722,9 @@ export function ProfileView({
<XDSDialog
isOpen={componentDrawerKey !== null}
onOpenChange={open => {
- if (!open) setComponentDrawerKey(null);
+ if (!open) {
+ setComponentDrawerKey(null);
+ }
}}
width="90vw"
maxHeight="90vh"
@@ -1891,7 +1924,9 @@ export function ProfileView({
}
onMoreLikeThisClick={mlItem => {
const found = PROFILE_LIKED_ITEMS.find(i => i.name === mlItem.name);
- if (found) setPreviewBookmarkItem(found);
+ if (found) {
+ setPreviewBookmarkItem(found);
+ }
}}
exploreTags={[
'website',
@@ -1967,7 +2002,9 @@ export function ProfileView({
const entries = THEME_PICKER_ENTRIES.filter(
e => e.category === category,
);
- if (entries.length === 0) return null;
+ if (entries.length === 0) {
+ return null;
+ }
return (
<div key={category} style={{marginBottom: 20}}>
<div style={{marginBottom: 8}}>
diff --git a/apps/sandbox/src/app/(fullscreen)/pages/docsite/ShimmerText.tsx b/apps/sandbox/src/app/(fullscreen)/pages/docsite/ShimmerText.tsx
index 943517f4b4..76ebbad988 100644
--- a/apps/sandbox/src/app/(fullscreen)/pages/docsite/ShimmerText.tsx
+++ b/apps/sandbox/src/app/(fullscreen)/pages/docsite/ShimmerText.tsx
@@ -10,7 +10,9 @@ export function ShimmerText({isActive}: {isActive: boolean}) {
const [dots, setDots] = useState('');
useEffect(() => {
- if (!isActive) return;
+ if (!isActive) {
+ return;
+ }
const id = setInterval(() => {
setDots(prev => (prev.length >= 3 ? '' : prev + '.'));
}, 500);
diff --git a/apps/sandbox/src/app/(fullscreen)/pages/docsite/TemplateCard.tsx b/apps/sandbox/src/app/(fullscreen)/pages/docsite/TemplateCard.tsx
index 54c7f8f794..7bf6d94b9c 100644
--- a/apps/sandbox/src/app/(fullscreen)/pages/docsite/TemplateCard.tsx
+++ b/apps/sandbox/src/app/(fullscreen)/pages/docsite/TemplateCard.tsx
@@ -55,10 +55,14 @@ export function TemplateCard({
}, []);
useEffect(() => {
- if (!slug) return;
+ if (!slug) {
+ return;
+ }
updateIframeScale();
const el = iframeWrapperRef.current;
- if (!el) return;
+ if (!el) {
+ return;
+ }
const resizeObs = new ResizeObserver(updateIframeScale);
resizeObs.observe(el);
diff --git a/apps/sandbox/src/app/(fullscreen)/pages/docsite/TemplatePreview.tsx b/apps/sandbox/src/app/(fullscreen)/pages/docsite/TemplatePreview.tsx
index e2dab60abb..34e2a64fc6 100644
--- a/apps/sandbox/src/app/(fullscreen)/pages/docsite/TemplatePreview.tsx
+++ b/apps/sandbox/src/app/(fullscreen)/pages/docsite/TemplatePreview.tsx
@@ -94,7 +94,9 @@ export function TemplatePreview({
useEffect(() => {
const el = scrollRef.current;
- if (!el) return;
+ if (!el) {
+ return;
+ }
const handleScroll = () => setIsScrolled(el.scrollTop > 8);
el.addEventListener('scroll', handleScroll, {passive: true});
return () => el.removeEventListener('scroll', handleScroll);
diff --git a/apps/sandbox/src/app/(fullscreen)/pages/docsite/TemplatePreviewModal.tsx b/apps/sandbox/src/app/(fullscreen)/pages/docsite/TemplatePreviewModal.tsx
index 8988e6b8fd..14df2b4c75 100644
--- a/apps/sandbox/src/app/(fullscreen)/pages/docsite/TemplatePreviewModal.tsx
+++ b/apps/sandbox/src/app/(fullscreen)/pages/docsite/TemplatePreviewModal.tsx
@@ -138,13 +138,18 @@ export function TemplatePreviewModal({
const togglePin = useCallback((key: string) => {
setPinnedThemes(prev => {
const next = new Set(prev);
- if (next.has(key)) next.delete(key);
- else next.add(key);
+ if (next.has(key)) {
+ next.delete(key);
+ } else {
+ next.add(key);
+ }
return next;
});
}, []);
- if (!item) return null;
+ if (!item) {
+ return null;
+ }
const themedImg = item.themeImages?.[selectedTheme] ?? item.img;
const hasThemedImage =
@@ -355,7 +360,9 @@ export function TemplatePreviewModal({
isOpen={themeBrowseOpen}
onOpenChange={open => {
setThemeBrowseOpen(open);
- if (!open) setThemeSearch('');
+ if (!open) {
+ setThemeSearch('');
+ }
}}
xstyle={popoverStyles.themeBrowse}
content={
@@ -400,7 +407,9 @@ export function TemplatePreviewModal({
.toLowerCase()
.includes(themeSearch.toLowerCase()),
);
- if (entries.length === 0) return null;
+ if (entries.length === 0) {
+ return null;
+ }
return (
<div key={category}>
<div style={{marginBottom: 8}}>
diff --git a/apps/sandbox/src/app/(fullscreen)/pages/docsite/ThemeEditorView.tsx b/apps/sandbox/src/app/(fullscreen)/pages/docsite/ThemeEditorView.tsx
index c0d60304ef..c9921a58b4 100644
--- a/apps/sandbox/src/app/(fullscreen)/pages/docsite/ThemeEditorView.tsx
+++ b/apps/sandbox/src/app/(fullscreen)/pages/docsite/ThemeEditorView.tsx
@@ -2534,9 +2534,13 @@ function MotionPreview() {
React.useEffect(() => {
const el = containerRef.current;
- if (!el) return;
+ if (!el) {
+ return;
+ }
const ro = new ResizeObserver(entries => {
- for (const entry of entries) setContainerWidth(entry.contentRect.width);
+ for (const entry of entries) {
+ setContainerWidth(entry.contentRect.width);
+ }
});
ro.observe(el);
return () => ro.disconnect();
@@ -2741,8 +2745,9 @@ function MotionPreview() {
!row ||
!row.parentElement ||
row.parentElement.tagName === 'THEAD'
- )
+ ) {
return;
+ }
const index = Array.from(row.parentElement.children).indexOf(
row,
);
@@ -2930,7 +2935,9 @@ const CODE_LABEL: React.CSSProperties = {
function TokenScalePreview({tokens}: {tokens: Record<string, string>}) {
const resolveSize = (raw: string) => {
- if (!raw) return raw;
+ if (!raw) {
+ return raw;
+ }
const resolved = raw.startsWith('var(')
? tokens[raw.slice(4, -1)] || raw
: raw;
@@ -2938,8 +2945,9 @@ function TokenScalePreview({tokens}: {tokens: Record<string, string>}) {
};
const toPx = (raw: string) => {
const resolved = resolveSize(raw);
- if (resolved.endsWith('rem'))
+ if (resolved.endsWith('rem')) {
return `${Math.round(parseFloat(resolved) * 16)}px`;
+ }
return resolved;
};
@@ -3171,10 +3179,14 @@ function TemplateIframePreview({
React.useEffect(() => {
const iframe = iframeRef.current;
- if (!iframe) return;
+ if (!iframe) {
+ return;
+ }
const inject = () => {
const doc = iframe.contentDocument;
- if (!doc) return;
+ if (!doc) {
+ return;
+ }
doc.documentElement.setAttribute('data-xds-theme', theme.name);
doc.documentElement.setAttribute('data-color-scheme', mode);
doc.documentElement.style.colorScheme = mode;
@@ -3183,7 +3195,9 @@ function TemplateIframePreview({
const root = doc.body?.firstElementChild as HTMLElement | null;
if (root) {
const toolbar = root.firstElementChild as HTMLElement | null;
- if (toolbar) toolbar.style.display = 'none';
+ if (toolbar) {
+ toolbar.style.display = 'none';
+ }
}
let styleEl = doc.querySelector<HTMLStyleElement>(
@@ -3273,14 +3287,21 @@ function generateThemeCode(
> = {};
for (const [key, value] of Object.entries(tokens)) {
- if (value === defaults[key]) continue;
- if (hasCustomTypeScale && typeScaleTokenKeys.has(key)) continue;
+ if (value === defaults[key]) {
+ continue;
+ }
+ if (hasCustomTypeScale && typeScaleTokenKeys.has(key)) {
+ continue;
+ }
const mapping = COMPONENT_VAR_TO_OVERRIDE[key];
if (mapping) {
const {component, cssProperty} = mapping;
- if (!componentOverrides[component]) componentOverrides[component] = {};
- if (!componentOverrides[component].base)
+ if (!componentOverrides[component]) {
+ componentOverrides[component] = {};
+ }
+ if (!componentOverrides[component].base) {
componentOverrides[component].base = {};
+ }
componentOverrides[component].base[cssProperty] = value;
} else {
changedTokens[key] = value;
@@ -3317,8 +3338,9 @@ function generateThemeCode(
const tokenEntries = Object.entries(changedTokens)
.map(([key, value]) => {
const parsed = parseLightDark(value);
- if (parsed)
+ if (parsed) {
return ` '${key}': ['${parsed.light}', '${parsed.dark}'],`;
+ }
return ` '${key}': '${value}',`;
})
.join('\n');
@@ -3394,8 +3416,12 @@ export function ThemeEditorView({
}, []);
React.useEffect(() => {
- if (panelMode === 'editor') setActivePreview('tokens');
- if (panelMode === 'target') setActivePreview('preview');
+ if (panelMode === 'editor') {
+ setActivePreview('tokens');
+ }
+ if (panelMode === 'target') {
+ setActivePreview('preview');
+ }
}, [panelMode]);
const [flashComponent, setFlashComponent] = React.useState<string | null>(
null,
@@ -3404,7 +3430,9 @@ export function ThemeEditorView({
const previewRef = React.useRef<HTMLDivElement>(null);
React.useEffect(() => {
- if (!flashComponent || !previewRef.current) return;
+ if (!flashComponent || !previewRef.current) {
+ return;
+ }
const container = previewRef.current;
const selector = `.xds-${flashComponent}`;
const elements = container.querySelectorAll<HTMLElement>(selector);
@@ -3554,7 +3582,9 @@ export function ThemeEditorView({
const applyUnifiedPreset = React.useCallback(
(presetKey: string) => {
const p = UNIFIED_PRESETS[presetKey as keyof typeof UNIFIED_PRESETS];
- if (!p) return;
+ if (!p) {
+ return;
+ }
setActivePreset(presetKey);
setTypeScaleBase(p.typeBase);
setTypeScaleRatio(p.typeRatio);
@@ -3786,7 +3816,9 @@ export function ThemeEditorView({
);
React.useEffect(() => {
- if (!initialTheme) return;
+ if (!initialTheme) {
+ return;
+ }
const fontLabel = initialTheme.font
? initialTheme.font.split(',')[0].replace(/["']/g, '').trim()
: 'System';
@@ -3936,11 +3968,15 @@ export function ThemeEditorView({
<div style={{display: 'flex', flexDirection: 'column', gap: '4px'}}>
{Object.entries(COLOR_CATEGORIES).map(([category, tokenNames]) => {
const uniqueTokens = tokenNames.filter(t => {
- if (seen.has(t)) return false;
+ if (seen.has(t)) {
+ return false;
+ }
seen.add(t);
return true;
});
- if (uniqueTokens.length === 0) return null;
+ if (uniqueTokens.length === 0) {
+ return null;
+ }
return (
<React.Fragment key={category}>
<XDSText
@@ -4005,11 +4041,15 @@ export function ThemeEditorView({
? (categoryValue as string[])
: (categoryValue as unknown as {tokens: string[]}).tokens;
const uniqueTokens = catTokens.filter(t => {
- if (seen.has(t)) return false;
+ if (seen.has(t)) {
+ return false;
+ }
seen.add(t);
return true;
});
- if (uniqueTokens.length === 0) return null;
+ if (uniqueTokens.length === 0) {
+ return null;
+ }
return (
<React.Fragment key={category}>
<XDSText
@@ -4200,7 +4240,9 @@ export function ThemeEditorView({
size="sm"
value={activeGroup}
onChange={(v: string | null) => {
- if (v != null) setActiveGroup(v as TokenGroupKey);
+ if (v != null) {
+ setActiveGroup(v as TokenGroupKey);
+ }
}}>
{(Object.keys(TOKEN_GROUPS) as TokenGroupKey[]).map(
groupKey => {
@@ -4473,8 +4515,9 @@ export function ThemeEditorView({
size="sm"
value={String(typeScaleBase)}
onChange={(v: string | null) => {
- if (v != null)
+ if (v != null) {
applyTypeScale(Number(v), typeScaleRatio);
+ }
}}>
<XDSToggleButton label="S" value="12">
S
@@ -4537,8 +4580,9 @@ export function ThemeEditorView({
: String(typeScaleRatio)
}
onChange={(v: string) => {
- if (v !== 'custom')
+ if (v !== 'custom') {
applyTypeScale(typeScaleBase, Number(v));
+ }
}}
/>
</div>
@@ -4573,7 +4617,9 @@ export function ThemeEditorView({
size="sm"
value={String(radiusBase)}
onChange={(v: string | null) => {
- if (v != null) applyRadiusScale(Number(v));
+ if (v != null) {
+ applyRadiusScale(Number(v));
+ }
}}>
<XDSToggleButton label="S" value="2">
S
@@ -4623,7 +4669,9 @@ export function ThemeEditorView({
size="sm"
value={String(spacingBase)}
onChange={(v: string | null) => {
- if (v != null) applySpacingScale(Number(v));
+ if (v != null) {
+ applySpacingScale(Number(v));
+ }
}}>
<XDSToggleButton label="S" value="2">
S
@@ -4673,7 +4721,9 @@ export function ThemeEditorView({
size="sm"
value={String(sizeBase)}
onChange={(v: string | null) => {
- if (v != null) applySizeScale(Number(v));
+ if (v != null) {
+ applySizeScale(Number(v));
+ }
}}>
<XDSToggleButton label="S" value="28">
S
@@ -4727,7 +4777,9 @@ export function ThemeEditorView({
size="sm"
value={String(durationStep)}
onChange={(v: string | null) => {
- if (v != null) applyDurationScale(Number(v));
+ if (v != null) {
+ applyDurationScale(Number(v));
+ }
}}>
<XDSToggleButton label="0.5×" value="0.5">
0.5×
@@ -5151,7 +5203,9 @@ export function ThemeEditorView({
input.accept = 'image/png,image/jpeg,image/webp';
input.onchange = () => {
const file = input.files?.[0];
- if (file) handleImageUpload(file);
+ if (file) {
+ handleImageUpload(file);
+ }
};
input.click();
}}
diff --git a/apps/sandbox/src/app/(fullscreen)/pages/docsite/docsview-data.ts b/apps/sandbox/src/app/(fullscreen)/pages/docsite/docsview-data.ts
index 8755e060a0..739a0760b9 100644
--- a/apps/sandbox/src/app/(fullscreen)/pages/docsite/docsview-data.ts
+++ b/apps/sandbox/src/app/(fullscreen)/pages/docsite/docsview-data.ts
@@ -452,7 +452,9 @@ const COMPONENT_DOCS: {
export function getComponentName(key: string): string {
for (const cat of COMPONENT_CATEGORIES) {
const item = cat.items.find(i => i.key === key);
- if (item) return item.name;
+ if (item) {
+ return item.name;
+ }
}
return key;
}
@@ -460,13 +462,17 @@ export function getComponentName(key: string): string {
export function getComponentDesc(key: string): string {
for (const cat of COMPONENT_CATEGORIES) {
const item = cat.items.find(i => i.key === key);
- if (item) return item.desc;
+ if (item) {
+ return item.desc;
+ }
}
return '';
}
export function getComponentDocs(key: string) {
- if (COMPONENT_DOCS[key]) return COMPONENT_DOCS[key];
+ if (COMPONENT_DOCS[key]) {
+ return COMPONENT_DOCS[key];
+ }
const name = getComponentName(key);
const desc = getComponentDesc(key);
return {
diff --git a/apps/sandbox/src/app/(fullscreen)/pages/docsite/page.tsx b/apps/sandbox/src/app/(fullscreen)/pages/docsite/page.tsx
index cb12b07bb4..962e4599d4 100644
--- a/apps/sandbox/src/app/(fullscreen)/pages/docsite/page.tsx
+++ b/apps/sandbox/src/app/(fullscreen)/pages/docsite/page.tsx
@@ -96,7 +96,9 @@ function SearchableFilterDropdown({
isOpen={isOpen}
onOpenChange={open => {
setIsOpen(open);
- if (!open) setSearch('');
+ if (!open) {
+ setSearch('');
+ }
}}
xstyle={popoverStyles.filterDropdown}
content={
@@ -496,8 +498,11 @@ function DocsiteLandingTemplate() {
const handleToggleResultFilter = useCallback((filter: string) => {
setResultFilters(prev => {
const next = new Set(prev);
- if (next.has(filter)) next.delete(filter);
- else next.add(filter);
+ if (next.has(filter)) {
+ next.delete(filter);
+ } else {
+ next.add(filter);
+ }
return next;
});
}, []);
@@ -509,7 +514,9 @@ function DocsiteLandingTemplate() {
setIsProfileResults(false);
setIsCraftResults(false);
setCraftStatusFilter('all');
- if (craftLoadingTimer.current) clearTimeout(craftLoadingTimer.current);
+ if (craftLoadingTimer.current) {
+ clearTimeout(craftLoadingTimer.current);
+ }
craftLoadingTimer.current = setTimeout(() => {
setCraftTitle(null);
setCraftLoading(false);
@@ -522,7 +529,9 @@ function DocsiteLandingTemplate() {
setCraftTitle(label);
setIsProfileResults(false);
setCraftLoading(true);
- if (craftLoadingTimer.current) clearTimeout(craftLoadingTimer.current);
+ if (craftLoadingTimer.current) {
+ clearTimeout(craftLoadingTimer.current);
+ }
craftLoadingTimer.current = setTimeout(() => {
setCraftLoading(false);
craftLoadingTimer.current = null;
@@ -665,7 +674,9 @@ function DocsiteLandingTemplate() {
}
const qs = params.toString();
- if (qs === window.location.search.slice(1)) return;
+ if (qs === window.location.search.slice(1)) {
+ return;
+ }
const url = `${basePath}/pages/docsite/${qs ? '?' + qs : ''}`;
if (isPopstateRef.current) {
@@ -763,7 +774,9 @@ function DocsiteLandingTemplate() {
const prevViewRef = useRef(activeView);
const skipViewResetRef = useRef(false);
useEffect(() => {
- if (prevViewRef.current === activeView) return;
+ if (prevViewRef.current === activeView) {
+ return;
+ }
prevViewRef.current = activeView;
if (skipViewResetRef.current) {
skipViewResetRef.current = false;
@@ -802,7 +815,9 @@ function DocsiteLandingTemplate() {
useEffect(() => {
const el = document.getElementById('docsite-scroll');
- if (!el) return;
+ if (!el) {
+ return;
+ }
const onScroll = () => setIsHeaderCollapsed(el.scrollTop > 170);
el.addEventListener('scroll', onScroll, {passive: true});
return () => el.removeEventListener('scroll', onScroll);
@@ -810,7 +825,9 @@ function DocsiteLandingTemplate() {
const handleMoreLikeThis = useCallback(
(index: number) => {
- if (generatingSource !== null) return;
+ if (generatingSource !== null) {
+ return;
+ }
setGeneratingSource(index);
setChatOpen(true);
timerRef.current = setTimeout(() => {
@@ -864,7 +881,9 @@ function DocsiteLandingTemplate() {
const handlePreviewSend = useCallback(
(prompt?: string) => {
- if (previewGenerating) return;
+ if (previewGenerating) {
+ return;
+ }
const lower = (prompt ?? '').toLowerCase();
const matchedKey = Object.keys(layoutVariantMap).find(key =>
@@ -894,9 +913,15 @@ function DocsiteLandingTemplate() {
useEffect(() => {
return () => {
- if (timerRef.current) clearTimeout(timerRef.current);
- if (previewTimerRef.current) clearTimeout(previewTimerRef.current);
- if (craftLoadingTimer.current) clearTimeout(craftLoadingTimer.current);
+ if (timerRef.current) {
+ clearTimeout(timerRef.current);
+ }
+ if (previewTimerRef.current) {
+ clearTimeout(previewTimerRef.current);
+ }
+ if (craftLoadingTimer.current) {
+ clearTimeout(craftLoadingTimer.current);
+ }
};
}, []);
@@ -905,8 +930,12 @@ function DocsiteLandingTemplate() {
const templateAuthors = useMemo(() => {
const authors = Array.from(new Set(TEMPLATES.map(t => t.author)));
return authors.sort((a, b) => {
- if (a === 'XDS Design') return -1;
- if (b === 'XDS Design') return 1;
+ if (a === 'XDS Design') {
+ return -1;
+ }
+ if (b === 'XDS Design') {
+ return 1;
+ }
return a.localeCompare(b);
});
}, []);
@@ -914,8 +943,11 @@ function DocsiteLandingTemplate() {
const handleToggleFilter = useCallback((filter: string) => {
setActiveFilters(prev => {
const next = new Set(prev);
- if (next.has(filter)) next.delete(filter);
- else next.add(filter);
+ if (next.has(filter)) {
+ next.delete(filter);
+ } else {
+ next.add(filter);
+ }
return next;
});
}, []);
@@ -926,8 +958,12 @@ function DocsiteLandingTemplate() {
const filteredTemplates = useMemo(() => {
return TEMPLATES.map((t, i) => ({...t, originalIndex: i})).filter(t => {
- if (templateFilter === 'all') return true;
- if (templateFilter === 'official') return t.isOfficial;
+ if (templateFilter === 'all') {
+ return true;
+ }
+ if (templateFilter === 'official') {
+ return t.isOfficial;
+ }
return t.author.toLowerCase().includes(templateFilter.toLowerCase());
});
}, [templateFilter]);
@@ -943,7 +979,9 @@ function DocsiteLandingTemplate() {
);
const filteredCraftItems = useMemo(() => {
- if (craftStatusFilter === 'all') return PROFILE_CRAFT_ITEMS;
+ if (craftStatusFilter === 'all') {
+ return PROFILE_CRAFT_ITEMS;
+ }
return PROFILE_CRAFT_ITEMS.filter(
item => item.status === craftStatusFilter,
);
@@ -2139,7 +2177,9 @@ function DocsiteLandingTemplate() {
? previewTarget % TEMPLATES.length
: 0
];
- if (!t) return null;
+ if (!t) {
+ return null;
+ }
const isLandingPage = t.name === 'Landing Page';
const settingsVariants = [
{
@@ -2285,14 +2325,18 @@ function DocsiteLandingTemplate() {
{themePreviewKey !== null &&
(() => {
const t = THEME_PICKER_ENTRIES.find(e => e.key === themePreviewKey);
- if (!t) return null;
+ if (!t) {
+ return null;
+ }
const r = t.preview.radius ?? 8;
const font = t.preview.font ?? 'system-ui, sans-serif';
return (
<XDSDialog
isOpen={true}
onOpenChange={open => {
- if (!open) setThemePreviewKey(null);
+ if (!open) {
+ setThemePreviewKey(null);
+ }
}}
width="90vw"
maxHeight="90vh"
diff --git a/apps/sandbox/src/app/(fullscreen)/pages/documentation/page.tsx b/apps/sandbox/src/app/(fullscreen)/pages/documentation/page.tsx
index f5b2ce51a1..dc784673b1 100644
--- a/apps/sandbox/src/app/(fullscreen)/pages/documentation/page.tsx
+++ b/apps/sandbox/src/app/(fullscreen)/pages/documentation/page.tsx
@@ -587,7 +587,9 @@ const COMPONENT_DOCS: Record<
function getComponentName(key: string): string {
for (const cat of COMPONENT_CATEGORIES) {
const item = cat.items.find(i => i.key === key);
- if (item) return item.name;
+ if (item) {
+ return item.name;
+ }
}
return key;
}
@@ -595,13 +597,17 @@ function getComponentName(key: string): string {
function getComponentDesc(key: string): string {
for (const cat of COMPONENT_CATEGORIES) {
const item = cat.items.find(i => i.key === key);
- if (item) return item.desc;
+ if (item) {
+ return item.desc;
+ }
}
return '';
}
function getComponentDocs(key: string) {
- if (COMPONENT_DOCS[key]) return COMPONENT_DOCS[key];
+ if (COMPONENT_DOCS[key]) {
+ return COMPONENT_DOCS[key];
+ }
const name = getComponentName(key);
const desc = getComponentDesc(key);
return {
diff --git a/apps/sandbox/src/app/(sandbox)/[category]/CategoryContent.tsx b/apps/sandbox/src/app/(sandbox)/[category]/CategoryContent.tsx
index b08d292987..02d764b88e 100644
--- a/apps/sandbox/src/app/(sandbox)/[category]/CategoryContent.tsx
+++ b/apps/sandbox/src/app/(sandbox)/[category]/CategoryContent.tsx
@@ -26,8 +26,12 @@ export function CategoryContent({slug}: {slug: string}) {
const [search, setSearch] = useState('');
const filtered = useMemo(() => {
- if (!category) return [];
- if (!search.trim()) return category.pages;
+ if (!category) {
+ return [];
+ }
+ if (!search.trim()) {
+ return category.pages;
+ }
const q = search.toLowerCase();
return category.pages.filter(
p =>
diff --git a/apps/sandbox/src/app/(sandbox)/page.tsx b/apps/sandbox/src/app/(sandbox)/page.tsx
index 0254a05475..2a06b597ee 100644
--- a/apps/sandbox/src/app/(sandbox)/page.tsx
+++ b/apps/sandbox/src/app/(sandbox)/page.tsx
@@ -62,10 +62,14 @@ export default function Home() {
}, [activeTab, search]);
const groupedSections = useMemo(() => {
- if (activeTab !== 'All') return null;
+ if (activeTab !== 'All') {
+ return null;
+ }
const map = new Map<string, typeof allPages>();
for (const page of filtered) {
- if (!map.has(page.category)) map.set(page.category, []);
+ if (!map.has(page.category)) {
+ map.set(page.category, []);
+ }
map.get(page.category)!.push(page);
}
return categories
diff --git a/apps/sandbox/src/app/(sandbox)/pages/color-studio/colorUtils.ts b/apps/sandbox/src/app/(sandbox)/pages/color-studio/colorUtils.ts
index 77dd568f86..b6b351c0b1 100644
--- a/apps/sandbox/src/app/(sandbox)/pages/color-studio/colorUtils.ts
+++ b/apps/sandbox/src/app/(sandbox)/pages/color-studio/colorUtils.ts
@@ -101,7 +101,9 @@ export function hexToHct(hex: string): HCT {
);
const [L, a, bLab] = xyzToLab(x, y, z);
let hue = (Math.atan2(bLab, a) * 180) / Math.PI;
- if (hue < 0) hue += 360;
+ if (hue < 0) {
+ hue += 360;
+ }
return {
hue,
chroma: Math.sqrt(a * a + bLab * bLab),
@@ -111,8 +113,12 @@ export function hexToHct(hex: string): HCT {
export function hctToHex(hct: HCT): string {
const {hue, chroma, tone} = hct;
- if (tone <= 0) return '#000000';
- if (tone >= 100) return '#ffffff';
+ if (tone <= 0) {
+ return '#000000';
+ }
+ if (tone >= 100) {
+ return '#ffffff';
+ }
if (chroma < 0.5) {
const y = labFInv((tone + 16) / 116);
const g = linearToSrgb(y);
@@ -155,7 +161,11 @@ export function hctToHex(hct: HCT): string {
// Perceptually uniform color space where equal chroma looks equally
// saturated across all hues at the same lightness.
-function linearRgbToOklab(r: number, g: number, b: number): [number, number, number] {
+function linearRgbToOklab(
+ r: number,
+ g: number,
+ b: number,
+): [number, number, number] {
const l_ = 0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b;
const m_ = 0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b;
const s_ = 0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b;
@@ -169,7 +179,11 @@ function linearRgbToOklab(r: number, g: number, b: number): [number, number, num
];
}
-function oklabToLinearRgb(L: number, a: number, b: number): [number, number, number] {
+function oklabToLinearRgb(
+ L: number,
+ a: number,
+ b: number,
+): [number, number, number] {
const l_ = L + 0.3963377774 * a + 0.2158037573 * b;
const m_ = L - 0.1055613458 * a - 0.0638541728 * b;
const s_ = L - 0.0894841775 * a - 1.291485548 * b;
@@ -184,9 +198,9 @@ function oklabToLinearRgb(L: number, a: number, b: number): [number, number, num
}
export interface OKLCH {
- L: number; // 0–1
- C: number; // 0–~0.4
- H: number; // 0–360 degrees
+ L: number; // 0–1
+ C: number; // 0–~0.4
+ H: number; // 0–360 degrees
}
export function hexToOklch(hex: string): OKLCH {
@@ -197,7 +211,9 @@ export function hexToOklch(hex: string): OKLCH {
srgbToLinear(b),
);
let H = (Math.atan2(labB, labA) * 180) / Math.PI;
- if (H < 0) H += 360;
+ if (H < 0) {
+ H += 360;
+ }
return {
L: labL,
C: Math.sqrt(labA * labA + labB * labB),
@@ -207,8 +223,12 @@ export function hexToOklch(hex: string): OKLCH {
export function oklchToHex(oklch: OKLCH): string {
const {L, C, H} = oklch;
- if (L <= 0) return '#000000';
- if (L >= 1) return '#ffffff';
+ if (L <= 0) {
+ return '#000000';
+ }
+ if (L >= 1) {
+ return '#ffffff';
+ }
const hRad = (H * Math.PI) / 180;
const a = C * Math.cos(hRad);
const b = C * Math.sin(hRad);
@@ -224,18 +244,29 @@ function oklchInGamut(L: number, C: number, H: number): boolean {
const a = C * Math.cos(hRad);
const b = C * Math.sin(hRad);
const [lr, lg, lb] = oklabToLinearRgb(L, a, b);
- return lr >= -0.001 && lr <= 1.001 &&
- lg >= -0.001 && lg <= 1.001 &&
- lb >= -0.001 && lb <= 1.001;
+ return (
+ lr >= -0.001 &&
+ lr <= 1.001 &&
+ lg >= -0.001 &&
+ lg <= 1.001 &&
+ lb >= -0.001 &&
+ lb <= 1.001
+ );
}
export function oklchClampedHex(L: number, C: number, H: number): string {
- if (oklchInGamut(L, C, H)) return oklchToHex({L, C, H});
- let lo = 0, hi = C;
+ if (oklchInGamut(L, C, H)) {
+ return oklchToHex({L, C, H});
+ }
+ let lo = 0,
+ hi = C;
for (let i = 0; i < 16; i++) {
const mid = (lo + hi) / 2;
- if (oklchInGamut(L, mid, H)) lo = mid;
- else hi = mid;
+ if (oklchInGamut(L, mid, H)) {
+ lo = mid;
+ } else {
+ hi = mid;
+ }
}
return oklchToHex({L, C: lo, H});
}
@@ -248,11 +279,13 @@ export const TONE_STEPS = [
// CIELab L* (0–100) to OKLAB L (0–1).
// L* → relative luminance Y, then OKLAB L ≈ Y^(1/3).
export function toneToOklabL(tone: number): number {
- if (tone <= 0) return 0;
- if (tone >= 100) return 1;
- const Y = tone > 8
- ? Math.pow((tone + 16) / 116, 3)
- : tone / 903.3;
+ if (tone <= 0) {
+ return 0;
+ }
+ if (tone >= 100) {
+ return 1;
+ }
+ const Y = tone > 8 ? Math.pow((tone + 16) / 116, 3) : tone / 903.3;
return Math.cbrt(Y);
}
@@ -269,11 +302,15 @@ export function tonalPalette(
}
export function maxOklchChroma(hue: number, L: number): number {
- let lo = 0, hi = 0.4;
+ let lo = 0,
+ hi = 0.4;
for (let i = 0; i < 20; i++) {
const mid = (lo + hi) / 2;
- if (oklchInGamut(L, mid, hue)) lo = mid;
- else hi = mid;
+ if (oklchInGamut(L, mid, hue)) {
+ lo = mid;
+ } else {
+ hi = mid;
+ }
}
return lo;
}
@@ -284,7 +321,9 @@ const _eqCache = new Map<string, Record<number, number>>();
export function equalizedChromaSteps(hues: number[]): Record<number, number> {
const key = hues.map(h => h.toFixed(1)).join(',');
const cached = _eqCache.get(key);
- if (cached) return cached;
+ if (cached) {
+ return cached;
+ }
const result: Record<number, number> = {};
for (const t of TONE_STEPS) {
const L = toneToOklabL(t);
@@ -771,7 +810,9 @@ export function generateExpressive(
// === WCAG Contrast ===
export function luminance(hex: string): number {
- if (hex.length > 7) hex = hex.substring(0, 7);
+ if (hex.length > 7) {
+ hex = hex.substring(0, 7);
+ }
const [r, g, b] = hexToRgb(hex).map(c => {
const s = c / 255;
return s <= 0.03928 ? s / 12.92 : Math.pow((s + 0.055) / 1.055, 2.4);
@@ -784,9 +825,15 @@ export function contrastRatio(fg: string, bg: string): number {
return (Math.max(l1, l2) + 0.05) / (Math.min(l1, l2) + 0.05);
}
export function wcagGrade(ratio: number): 'AAA' | 'AA' | 'AA18' | 'FAIL' {
- if (ratio >= 7) return 'AAA';
- if (ratio >= 4.5) return 'AA';
- if (ratio >= 3) return 'AA18';
+ if (ratio >= 7) {
+ return 'AAA';
+ }
+ if (ratio >= 4.5) {
+ return 'AA';
+ }
+ if (ratio >= 3) {
+ return 'AA18';
+ }
return 'FAIL';
}
@@ -797,7 +844,9 @@ export function extractColorsFromImage(
): string[] {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
- if (!ctx) return [];
+ if (!ctx) {
+ return [];
+ }
const w = 200,
h = Math.round((img.naturalHeight * 200) / img.naturalWidth);
canvas.width = w;
@@ -806,12 +855,18 @@ export function extractColorsFromImage(
const data = ctx.getImageData(0, 0, w, h).data;
const pixels: [number, number, number][] = [];
for (let i = 0; i < data.length; i += 4) {
- if (data[i + 3] < 128) continue;
+ if (data[i + 3] < 128) {
+ continue;
+ }
const lum = 0.299 * data[i] + 0.587 * data[i + 1] + 0.114 * data[i + 2];
- if (lum < 15 || lum > 245) continue;
+ if (lum < 15 || lum > 245) {
+ continue;
+ }
pixels.push([data[i], data[i + 1], data[i + 2]]);
}
- if (!pixels.length) return ['#0064e0'];
+ if (!pixels.length) {
+ return ['#0064e0'];
+ }
function medianCut(px: [number, number, number][], depth: number): string[] {
if (depth === 0 || px.length < 2) {
const avg = px.reduce(
@@ -845,8 +900,9 @@ export function extractColorsFromImage(
Math.abs(h1.chroma - h2.chroma) < 10
);
})
- )
+ ) {
unique.push(c);
+ }
}
unique.sort((a, b) => hexToHct(b).chroma - hexToHct(a).chroma);
return unique.slice(0, count);
@@ -856,9 +912,19 @@ export function extractColorsFromImage(
export type ThemeRole =
| 'accent'
- | 'success' | 'error' | 'warning'
- | 'blue' | 'cyan' | 'gray' | 'green' | 'orange'
- | 'pink' | 'purple' | 'red' | 'teal' | 'yellow';
+ | 'success'
+ | 'error'
+ | 'warning'
+ | 'blue'
+ | 'cyan'
+ | 'gray'
+ | 'green'
+ | 'orange'
+ | 'pink'
+ | 'purple'
+ | 'red'
+ | 'teal'
+ | 'yellow';
export interface PaletteColor {
id: string;
@@ -889,8 +955,16 @@ export const THEME_ROLES: {value: ThemeRole; label: string; group: string}[] = [
];
const CATEGORICAL_ROLES: ThemeRole[] = [
- 'blue', 'cyan', 'gray', 'green', 'orange',
- 'pink', 'purple', 'red', 'teal', 'yellow',
+ 'blue',
+ 'cyan',
+ 'gray',
+ 'green',
+ 'orange',
+ 'pink',
+ 'purple',
+ 'red',
+ 'teal',
+ 'yellow',
];
const STATUS_ROLES: ThemeRole[] = ['success', 'error', 'warning'];
@@ -916,10 +990,20 @@ export const DEFAULT_OKLCH_CHROMA: Record<string, number> = {
// OKLCH hue defaults for each role
export const DEFAULT_OKLCH_HUE: Record<string, number> = {
- red: 25, orange: 55, yellow: 90, green: 145,
- teal: 175, cyan: 200, blue: 260, purple: 300,
- pink: 350, gray: 264, success: 145, warning: 85,
- error: 25, accent: 264,
+ red: 25,
+ orange: 55,
+ yellow: 90,
+ green: 145,
+ teal: 175,
+ cyan: 200,
+ blue: 260,
+ purple: 300,
+ pink: 350,
+ gray: 264,
+ success: 145,
+ warning: 85,
+ error: 25,
+ accent: 264,
};
export interface ThemeOptions {
@@ -960,18 +1044,24 @@ export function buildThemeTokens(
aOklch.H,
);
tokens['--color-accent'] = [accentHex, accentDark];
- tokens['--color-accent-muted'] = [hexWithAlpha(accentHex, 0.2), hexWithAlpha(accentDark, 0.25)];
+ tokens['--color-accent-muted'] = [
+ hexWithAlpha(accentHex, 0.2),
+ hexWithAlpha(accentDark, 0.25),
+ ];
}
const v = options.vibrancy;
for (const pc of palette) {
- if (!pc.role || pc.role === 'accent') continue;
+ if (!pc.role || pc.role === 'accent') {
+ continue;
+ }
const oklch = hexToOklch(pc.hex);
const defaultC = DEFAULT_OKLCH_CHROMA[pc.role] ?? 0.13;
- const chrm = pc.role === 'gray'
- ? Math.min(oklch.C, 0.02) * v
- : Math.max(oklch.C, defaultC) * v;
+ const chrm =
+ pc.role === 'gray'
+ ? Math.min(oklch.C, 0.02) * v
+ : Math.max(oklch.C, defaultC) * v;
// Generate the OKLCH tonal palette — same function the ramps use.
// Token values are pulled from specific tone stops so components
@@ -1068,9 +1158,13 @@ export function parseColorInput(input: string): string | null {
const h = s.replace('#', '');
return '#' + h[0] + h[0] + h[1] + h[1] + h[2] + h[2];
}
- if (/^#?[0-9a-f]{6}$/i.test(s)) return '#' + s.replace('#', '');
+ if (/^#?[0-9a-f]{6}$/i.test(s)) {
+ return '#' + s.replace('#', '');
+ }
const rgbM = s.match(/^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/);
- if (rgbM) return rgbToHex(+rgbM[1], +rgbM[2], +rgbM[3]);
+ if (rgbM) {
+ return rgbToHex(+rgbM[1], +rgbM[2], +rgbM[3]);
+ }
const hslM = s.match(/^hsla?\(\s*([\d.]+)\s*,\s*([\d.]+)%\s*,\s*([\d.]+)%/);
if (hslM) {
const hh = +hslM[1] / 360,
@@ -1079,11 +1173,21 @@ export function parseColorInput(input: string): string | null {
const q = ll < 0.5 ? ll * (1 + ss) : ll + ss - ll * ss,
p = 2 * ll - q;
const h2r = (pp: number, qq: number, t: number) => {
- if (t < 0) t += 1;
- if (t > 1) t -= 1;
- if (t < 1 / 6) return pp + (qq - pp) * 6 * t;
- if (t < 1 / 2) return qq;
- if (t < 2 / 3) return pp + (qq - pp) * (2 / 3 - t) * 6;
+ if (t < 0) {
+ t += 1;
+ }
+ if (t > 1) {
+ t -= 1;
+ }
+ if (t < 1 / 6) {
+ return pp + (qq - pp) * 6 * t;
+ }
+ if (t < 1 / 2) {
+ return qq;
+ }
+ if (t < 2 / 3) {
+ return pp + (qq - pp) * (2 / 3 - t) * 6;
+ }
return pp;
};
return rgbToHex(
diff --git a/apps/sandbox/src/app/(sandbox)/pages/color-studio/page.tsx b/apps/sandbox/src/app/(sandbox)/pages/color-studio/page.tsx
index f08672c54d..fb90fa0f5b 100644
--- a/apps/sandbox/src/app/(sandbox)/pages/color-studio/page.tsx
+++ b/apps/sandbox/src/app/(sandbox)/pages/color-studio/page.tsx
@@ -198,7 +198,9 @@ function PaletteEntry({
value={color.hex}
onChange={v => {
const parsed = parseColorInput(v.trim());
- if (parsed) onChange(color.id, {hex: parsed});
+ if (parsed) {
+ onChange(color.id, {hex: parsed});
+ }
}}
size="sm"
/>
@@ -269,7 +271,9 @@ interface CustomChannel {
}
function generateToneSteps(count: number): number[] {
- if (count <= 1) return [50];
+ if (count <= 1) {
+ return [50];
+ }
return Array.from({length: count}, (_, i) =>
Math.round((i / (count - 1)) * 100),
);
@@ -291,7 +295,9 @@ function TonalRamps({
const roleMap = useMemo(() => {
const map = new Map<ThemeRole, PaletteColor>();
for (const pc of palette) {
- if (pc.role) map.set(pc.role, pc);
+ if (pc.role) {
+ map.set(pc.role, pc);
+ }
}
return map;
}, [palette]);
diff --git a/apps/sandbox/src/app/(sandbox)/pages/doc-preview/DocPreview.tsx b/apps/sandbox/src/app/(sandbox)/pages/doc-preview/DocPreview.tsx
index 59f1ccfe94..aebc91a691 100644
--- a/apps/sandbox/src/app/(sandbox)/pages/doc-preview/DocPreview.tsx
+++ b/apps/sandbox/src/app/(sandbox)/pages/doc-preview/DocPreview.tsx
@@ -60,7 +60,9 @@ function ThemeTokenSection({
theme: XDSDefinedTheme;
}) {
const Component = TOKEN_TABLE_BY_CATEGORY[category];
- if (!Component) return null;
+ if (!Component) {
+ return null;
+ }
return <Component theme={theme} />;
}
@@ -173,10 +175,7 @@ export function DocPreview({
{doc.tokenCategory && (
<>
<XDSDivider />
- <ThemeTokenSection
- category={doc.tokenCategory}
- theme={theme}
- />
+ <ThemeTokenSection category={doc.tokenCategory} theme={theme} />
</>
)}
</XDSVStack>
diff --git a/apps/sandbox/src/app/(sandbox)/pages/doc-preview/token-tables/MotionTokenTable.tsx b/apps/sandbox/src/app/(sandbox)/pages/doc-preview/token-tables/MotionTokenTable.tsx
index 0f35d540eb..6af8c09a8d 100644
--- a/apps/sandbox/src/app/(sandbox)/pages/doc-preview/token-tables/MotionTokenTable.tsx
+++ b/apps/sandbox/src/app/(sandbox)/pages/doc-preview/token-tables/MotionTokenTable.tsx
@@ -83,26 +83,41 @@ function DurationBar({value}: {value: string}) {
<div {...stylex.props(styles.durationTrack)}>
<div
{...stylex.props(styles.durationFill)}
- style={{width: animate ? '100%' : '0%', transition: `width ${value} ease`}}
+ style={{
+ width: animate ? '100%' : '0%',
+ transition: `width ${value} ease`,
+ }}
/>
</div>
);
}
function evaluateBezier(
- x1: number, y1: number, x2: number, y2: number, t: number,
+ x1: number,
+ y1: number,
+ x2: number,
+ y2: number,
+ t: number,
): number {
- const cx = 3 * x1, bx = 3 * (x2 - x1) - cx, ax = 1 - cx - bx;
- const cy = 3 * y1, by = 3 * (y2 - y1) - cy, ay = 1 - cy - by;
+ const cx = 3 * x1,
+ bx = 3 * (x2 - x1) - cx,
+ ax = 1 - cx - bx;
+ const cy = 3 * y1,
+ by = 3 * (y2 - y1) - cy,
+ ay = 1 - cy - by;
const sampleX = (s: number) => ((ax * s + bx) * s + cx) * s;
const sampleY = (s: number) => ((ay * s + by) * s + cy) * s;
const sampleXDeriv = (s: number) => (3 * ax * s + 2 * bx) * s + cx;
let g = t;
for (let i = 0; i < 8; i++) {
const cur = sampleX(g) - t;
- if (Math.abs(cur) < 1e-6) break;
+ if (Math.abs(cur) < 1e-6) {
+ break;
+ }
const d = sampleXDeriv(g);
- if (Math.abs(d) < 1e-6) break;
+ if (Math.abs(d) < 1e-6) {
+ break;
+ }
g -= cur / d;
}
return sampleY(Math.max(0, Math.min(1, g)));
@@ -117,35 +132,77 @@ function EasingCurve({value}: {value: string}) {
);
useEffect(() => {
- if (!match) return;
+ if (!match) {
+ return;
+ }
let running = true;
- const duration = 1200, pause = 800, cycle = duration + pause;
+ const duration = 1200,
+ pause = 800,
+ cycle = duration + pause;
function tick(ts: number) {
- if (!running) return;
- if (!startRef.current) startRef.current = ts;
+ if (!running) {
+ return;
+ }
+ if (!startRef.current) {
+ startRef.current = ts;
+ }
const inCycle = (ts - startRef.current) % cycle;
setProgress(inCycle < duration ? inCycle / duration : 1);
- if ((ts - startRef.current) % (cycle * 2) >= cycle * 2 - 16) startRef.current = ts;
+ if ((ts - startRef.current) % (cycle * 2) >= cycle * 2 - 16) {
+ startRef.current = ts;
+ }
animRef.current = requestAnimationFrame(tick);
}
animRef.current = requestAnimationFrame(tick);
- return () => { running = false; if (animRef.current) cancelAnimationFrame(animRef.current); };
+ return () => {
+ running = false;
+ if (animRef.current) {
+ cancelAnimationFrame(animRef.current);
+ }
+ };
}, [match]);
- if (!match) return null;
+ if (!match) {
+ return null;
+ }
const [, x1, y1, x2, y2] = match.map(Number);
const easedY = evaluateBezier(x1, y1, x2, y2, progress);
const pad = 0.12;
return (
<XDSHStack gap={2} align="center">
- <svg width={32} height={24} viewBox={`${-pad} ${-pad} ${1+pad*2} ${1+pad*2}`} style={{flexShrink: 0}}>
- <path d={`M 0 1 C ${x1} ${1-y1}, ${x2} ${1-y2}, 1 0`} fill="none" stroke="var(--color-neutral)" strokeWidth={0.04} />
- <path d={`M 0 1 C ${x1} ${1-y1}, ${x2} ${1-y2}, 1 0`} fill="none" stroke="var(--color-accent)" strokeWidth={0.06} strokeDasharray="1" strokeDashoffset={1-progress} pathLength={1} />
- <circle cx={progress} cy={1-easedY} r={0.06} fill="var(--color-accent)" />
+ <svg
+ width={32}
+ height={24}
+ viewBox={`${-pad} ${-pad} ${1 + pad * 2} ${1 + pad * 2}`}
+ style={{flexShrink: 0}}>
+ <path
+ d={`M 0 1 C ${x1} ${1 - y1}, ${x2} ${1 - y2}, 1 0`}
+ fill="none"
+ stroke="var(--color-neutral)"
+ strokeWidth={0.04}
+ />
+ <path
+ d={`M 0 1 C ${x1} ${1 - y1}, ${x2} ${1 - y2}, 1 0`}
+ fill="none"
+ stroke="var(--color-accent)"
+ strokeWidth={0.06}
+ strokeDasharray="1"
+ strokeDashoffset={1 - progress}
+ pathLength={1}
+ />
+ <circle
+ cx={progress}
+ cy={1 - easedY}
+ r={0.06}
+ fill="var(--color-accent)"
+ />
</svg>
<div {...stylex.props(styles.easingTrack)}>
- <div {...stylex.props(styles.easingDot)} style={{left: `${easedY*100}%`}} />
+ <div
+ {...stylex.props(styles.easingDot)}
+ style={{left: `${easedY * 100}%`}}
+ />
</div>
</XDSHStack>
);
@@ -173,7 +230,9 @@ export function DurationTokenTable({theme}: TokenTableProps) {
renderCell: (item: Record<string, unknown>) => (
<XDSHStack gap={2} align="center">
<DurationBar value={item.value as string} />
- <XDSText type="code" color="secondary">{item.value as string}</XDSText>
+ <XDSText type="code" color="secondary">
+ {item.value as string}
+ </XDSText>
</XDSHStack>
),
},
@@ -207,7 +266,9 @@ export function EasingTokenTable({theme}: TokenTableProps) {
renderCell: (item: Record<string, unknown>) => (
<XDSHStack gap={2} align="center">
<EasingCurve value={item.value as string} />
- <XDSText type="code" color="secondary">{item.value as string}</XDSText>
+ <XDSText type="code" color="secondary">
+ {item.value as string}
+ </XDSText>
</XDSHStack>
),
},
diff --git a/apps/sandbox/src/app/(sandbox)/pages/doc-preview/token-tables/ShapeTokenTable.tsx b/apps/sandbox/src/app/(sandbox)/pages/doc-preview/token-tables/ShapeTokenTable.tsx
index d481fd7bb7..aacbccf8a0 100644
--- a/apps/sandbox/src/app/(sandbox)/pages/doc-preview/token-tables/ShapeTokenTable.tsx
+++ b/apps/sandbox/src/app/(sandbox)/pages/doc-preview/token-tables/ShapeTokenTable.tsx
@@ -46,7 +46,10 @@ function sortByOrder(tokens: string[], order: string[]): string[] {
}
function RadiusTokenTable({theme}: TokenTableProps) {
- const tokens = sortByOrder(getTokensByPrefix(theme, '--radius-'), RADIUS_ORDER);
+ const tokens = sortByOrder(
+ getTokensByPrefix(theme, '--radius-'),
+ RADIUS_ORDER,
+ );
const data = tokens.map(name => ({
tokenName: name,
value: resolveToken(theme, name),
@@ -62,8 +65,13 @@ function RadiusTokenTable({theme}: TokenTableProps) {
header: 'Value',
renderCell: (item: Record<string, unknown>) => (
<XDSHStack gap={2} align="center">
- <div {...stylex.props(styles.radiusBox)} style={{borderRadius: item.value as string}} />
- <XDSText type="code" color="secondary">{item.value as string}</XDSText>
+ <div
+ {...stylex.props(styles.radiusBox)}
+ style={{borderRadius: item.value as string}}
+ />
+ <XDSText type="code" color="secondary">
+ {item.value as string}
+ </XDSText>
</XDSHStack>
),
},
@@ -77,7 +85,9 @@ function RadiusTokenTable({theme}: TokenTableProps) {
function BorderTokenTable({theme}: TokenTableProps) {
const tokens = getTokensByPrefix(theme, '--border-');
- if (tokens.length === 0) return null;
+ if (tokens.length === 0) {
+ return null;
+ }
const data = tokens.map(name => ({
tokenName: name,
@@ -94,8 +104,13 @@ function BorderTokenTable({theme}: TokenTableProps) {
header: 'Value',
renderCell: (item: Record<string, unknown>) => (
<XDSHStack gap={2} align="center">
- <div {...stylex.props(styles.borderLine)} style={{borderBottomWidth: item.value as string}} />
- <XDSText type="code" color="secondary">{item.value as string}</XDSText>
+ <div
+ {...stylex.props(styles.borderLine)}
+ style={{borderBottomWidth: item.value as string}}
+ />
+ <XDSText type="code" color="secondary">
+ {item.value as string}
+ </XDSText>
</XDSHStack>
),
},
diff --git a/apps/sandbox/src/app/(sandbox)/pages/doc-preview/token-tables/helpers.ts b/apps/sandbox/src/app/(sandbox)/pages/doc-preview/token-tables/helpers.ts
index fb654ed702..2c8268a842 100644
--- a/apps/sandbox/src/app/(sandbox)/pages/doc-preview/token-tables/helpers.ts
+++ b/apps/sandbox/src/app/(sandbox)/pages/doc-preview/token-tables/helpers.ts
@@ -8,7 +8,9 @@ import {xdsTokenDefaults} from '@xds/core/theme';
*/
export function parseLightDark(value: string): [string, string] | null {
const match = value.match(/^light-dark\(\s*([^,]+?)\s*,\s*(.+?)\s*\)$/);
- if (!match) return null;
+ if (!match) {
+ return null;
+ }
return [match[1], match[2]];
}
@@ -27,10 +29,14 @@ export function resolveTokenForMode(
const inputTokens = theme.__inputTokens;
if (inputTokens) {
const val = inputTokens[tokenName];
- if (Array.isArray(val)) return mode === 'dark' ? val[1] : val[0];
+ if (Array.isArray(val)) {
+ return mode === 'dark' ? val[1] : val[0];
+ }
if (typeof val === 'string') {
const parsed = parseLightDark(val);
- if (parsed) return mode === 'dark' ? parsed[1] : parsed[0];
+ if (parsed) {
+ return mode === 'dark' ? parsed[1] : parsed[0];
+ }
return val;
}
}
@@ -38,14 +44,18 @@ export function resolveTokenForMode(
const resolved = theme.tokens[tokenName];
if (resolved) {
const parsed = parseLightDark(resolved);
- if (parsed) return mode === 'dark' ? parsed[1] : parsed[0];
+ if (parsed) {
+ return mode === 'dark' ? parsed[1] : parsed[0];
+ }
return resolved;
}
// 3. Fall back to defaults
const def = xdsTokenDefaults[tokenName];
if (def) {
const parsed = parseLightDark(def);
- if (parsed) return mode === 'dark' ? parsed[1] : parsed[0];
+ if (parsed) {
+ return mode === 'dark' ? parsed[1] : parsed[0];
+ }
return def;
}
return '';
@@ -62,13 +72,17 @@ export function resolveToken(
if (resolved) {
const parsed = parseLightDark(resolved);
// Default to light mode for display
- if (parsed) return parsed[0];
+ if (parsed) {
+ return parsed[0];
+ }
return resolved;
}
const def = xdsTokenDefaults[tokenName];
if (def) {
const parsed = parseLightDark(def);
- if (parsed) return parsed[0];
+ if (parsed) {
+ return parsed[0];
+ }
return def;
}
return '';
@@ -108,7 +122,9 @@ export function getTokensByPrefix(
// Try numeric comparison first
const numA = parseFloat(suffA);
const numB = parseFloat(suffB);
- if (!isNaN(numA) && !isNaN(numB)) return numA - numB;
+ if (!isNaN(numA) && !isNaN(numB)) {
+ return numA - numB;
+ }
// Non-numeric suffixes: sort alphabetically
return suffA.localeCompare(suffB);
});
diff --git a/apps/sandbox/src/app/(sandbox)/pages/media-mode/useImageModeTest.ts b/apps/sandbox/src/app/(sandbox)/pages/media-mode/useImageModeTest.ts
index 21be220136..edc1e60379 100644
--- a/apps/sandbox/src/app/(sandbox)/pages/media-mode/useImageModeTest.ts
+++ b/apps/sandbox/src/app/(sandbox)/pages/media-mode/useImageModeTest.ts
@@ -30,11 +30,14 @@ function wcagLuminance(r: number, g: number, b: number): number {
/** APCA perceptual lightness: linearize, compute Y, apply power curve */
function apcaLightness(r: number, g: number, b: number): number {
const lin = (c: number) => Math.pow(c / 255, 2.4);
- const y = 0.2126729 * lin(r) + 0.7151522 * lin(g) + 0.0721750 * lin(b);
+ const y = 0.2126729 * lin(r) + 0.7151522 * lin(g) + 0.072175 * lin(b);
return Math.pow(y, 0.56);
}
-const ALGO_CONFIG: Record<Algorithm, {fn: (r: number, g: number, b: number) => number; threshold: number}> = {
+const ALGO_CONFIG: Record<
+ Algorithm,
+ {fn: (r: number, g: number, b: number) => number; threshold: number}
+> = {
gamma: {fn: gammaLuma, threshold: 0.5},
wcag: {fn: wcagLuminance, threshold: 0.18},
apca: {fn: apcaLightness, threshold: 0.5},
@@ -55,7 +58,10 @@ export function useImageModeTest(
options: UseImageModeTestOptions = {},
): {mode: 'dark' | 'light' | null; value: number | null} {
const {region, algorithm = 'gamma', fallback = null} = options;
- const [result, setResult] = useState<{mode: 'dark' | 'light' | null; value: number | null}>({
+ const [result, setResult] = useState<{
+ mode: 'dark' | 'light' | null;
+ value: number | null;
+ }>({
mode: fallback,
value: null,
});
@@ -75,22 +81,32 @@ export function useImageModeTest(
const blob = await response.blob();
const bitmap = await createImageBitmap(blob);
- if (cancelled) return;
+ if (cancelled) {
+ return;
+ }
const sx = region ? Math.round(region.x * bitmap.width) : 0;
const sy = region ? Math.round(region.y * bitmap.height) : 0;
- const sw = region ? Math.round(region.width * bitmap.width) : bitmap.width;
- const sh = region ? Math.round(region.height * bitmap.height) : bitmap.height;
+ const sw = region
+ ? Math.round(region.width * bitmap.width)
+ : bitmap.width;
+ const sh = region
+ ? Math.round(region.height * bitmap.height)
+ : bitmap.height;
const sampleSize = 10;
const canvas = new OffscreenCanvas(sampleSize, sampleSize);
const ctx = canvas.getContext('2d');
- if (!ctx) return;
+ if (!ctx) {
+ return;
+ }
ctx.drawImage(bitmap, sx, sy, sw, sh, 0, 0, sampleSize, sampleSize);
const imageData = ctx.getImageData(0, 0, sampleSize, sampleSize).data;
- let totalR = 0, totalG = 0, totalB = 0;
+ let totalR = 0,
+ totalG = 0,
+ totalB = 0;
const pixelCount = sampleSize * sampleSize;
for (let i = 0; i < imageData.length; i += 4) {
totalR += imageData[i];
@@ -98,7 +114,9 @@ export function useImageModeTest(
totalB += imageData[i + 2];
}
- if (cancelled) return;
+ if (cancelled) {
+ return;
+ }
const r = totalR / pixelCount;
const g = totalG / pixelCount;
@@ -108,13 +126,25 @@ export function useImageModeTest(
setResult({mode, value});
} catch {
- if (!cancelled) setResult({mode: fallback, value: null});
+ if (!cancelled) {
+ setResult({mode: fallback, value: null});
+ }
}
}
detect();
- return () => { cancelled = true; };
- }, [src, region?.x, region?.y, region?.width, region?.height, algorithm, fallback]);
+ return () => {
+ cancelled = true;
+ };
+ }, [
+ src,
+ region?.x,
+ region?.y,
+ region?.width,
+ region?.height,
+ algorithm,
+ fallback,
+ ]);
return result;
}
diff --git a/apps/sandbox/src/app/(sandbox)/pages/table-overview/page.tsx b/apps/sandbox/src/app/(sandbox)/pages/table-overview/page.tsx
index d9bcc6e3cc..14a1054b49 100644
--- a/apps/sandbox/src/app/(sandbox)/pages/table-overview/page.tsx
+++ b/apps/sandbox/src/app/(sandbox)/pages/table-overview/page.tsx
@@ -436,7 +436,9 @@ export default function TableOverviewPage() {
const [selectedKeys, setSelectedKeys] = useState<Set<string>>(new Set());
const filterRows = (rows: ReviewRow[]) => {
- if (!search.trim()) return rows;
+ if (!search.trim()) {
+ return rows;
+ }
const q = search.toLowerCase();
return rows.filter(
row =>
diff --git a/apps/sandbox/src/app/(sandbox)/templates/page.tsx b/apps/sandbox/src/app/(sandbox)/templates/page.tsx
index 6316a0010c..e656be535c 100644
--- a/apps/sandbox/src/app/(sandbox)/templates/page.tsx
+++ b/apps/sandbox/src/app/(sandbox)/templates/page.tsx
@@ -73,14 +73,20 @@ function parseSortFromParams(
params: URLSearchParams,
): XDSTableSortState | undefined {
const raw = params.get('sort');
- if (!raw) return undefined;
+ if (!raw) {
+ return undefined;
+ }
const [sortKey, dir] = raw.split(':');
- if (!sortKey || (dir !== 'asc' && dir !== 'desc')) return undefined;
+ if (!sortKey || (dir !== 'asc' && dir !== 'desc')) {
+ return undefined;
+ }
return [{sortKey, direction: dir === 'asc' ? 'ascending' : 'descending'}];
}
function serializeSort(sort: XDSTableSortState): string | null {
- if (sort.length === 0) return null;
+ if (sort.length === 0) {
+ return null;
+ }
const {sortKey, direction} = sort[0];
return `${sortKey}:${direction === 'ascending' ? 'asc' : 'desc'}`;
}
@@ -101,9 +107,13 @@ function buildSearchParams(
): string {
const params = new URLSearchParams();
const sortStr = serializeSort(sort);
- if (sortStr) params.set('sort', sortStr);
+ if (sortStr) {
+ params.set('sort', sortStr);
+ }
for (const [key, value] of Object.entries(filters)) {
- if (value != null) params.set(`${FILTER_PREFIX}${key}`, String(value));
+ if (value != null) {
+ params.set(`${FILTER_PREFIX}${key}`, String(value));
+ }
}
const str = params.toString();
return str ? `?${str}` : '';
@@ -141,8 +151,11 @@ function useTableSearchParams() {
const onFilterChange = useCallback(
(key: string, value: XDSTableFilterValue | null) => {
const next = {...filters};
- if (value == null) delete next[key];
- else next[key] = value;
+ if (value == null) {
+ delete next[key];
+ } else {
+ next[key] = value;
+ }
updateURL(sort, next);
},
[updateURL, sort, filters],
@@ -230,9 +243,7 @@ const columns: XDSTableColumn<TemplateRow>[] = [
filter: 'isShowcase',
width: pixel(100),
renderCell: (row: TemplateRow) =>
- row.isShowcase ? (
- <XDSBadge label="Showcase" variant="info" />
- ) : null,
+ row.isShowcase ? <XDSBadge label="Showcase" variant="info" /> : null,
},
{
key: 'description',
diff --git a/apps/sandbox/src/app/SandboxShell.tsx b/apps/sandbox/src/app/SandboxShell.tsx
index bb00cc8026..cc30668fe3 100644
--- a/apps/sandbox/src/app/SandboxShell.tsx
+++ b/apps/sandbox/src/app/SandboxShell.tsx
@@ -12,7 +12,9 @@ export function SandboxShell({children}: {children: React.ReactNode}) {
const pathname = usePathname();
const isFullscreen = FULLSCREEN_PATHS.some(p => pathname.startsWith(p));
- if (isFullscreen) return <>{children}</>;
+ if (isFullscreen) {
+ return <>{children}</>;
+ }
return (
<XDSAppShell sideNav={<SandboxNav />} contentPadding={0}>
diff --git a/apps/sandbox/src/app/providers.tsx b/apps/sandbox/src/app/providers.tsx
index 6aeb6bbe6d..e2bd49a15a 100644
--- a/apps/sandbox/src/app/providers.tsx
+++ b/apps/sandbox/src/app/providers.tsx
@@ -112,7 +112,9 @@ export function Providers({children}: {children: React.ReactNode}) {
try {
const storedTheme = window.localStorage.getItem(THEME_STORAGE_KEY);
const storedMode = window.localStorage.getItem(MODE_STORAGE_KEY);
- if (storedTheme && storedTheme in themes) setThemeName(storedTheme);
+ if (storedTheme && storedTheme in themes) {
+ setThemeName(storedTheme);
+ }
if (storedMode === 'light' || storedMode === 'dark') {
setMode(storedMode as ThemeMode);
}
@@ -126,7 +128,9 @@ export function Providers({children}: {children: React.ReactNode}) {
// Skip writes until after hydration to avoid overwriting stored values on
// first render, and skip entirely when embedded (parent controls theme).
useEffect(() => {
- if (isEmbed || !hasHydrated) return;
+ if (isEmbed || !hasHydrated) {
+ return;
+ }
try {
window.localStorage.setItem(THEME_STORAGE_KEY, themeName);
} catch {
@@ -135,7 +139,9 @@ export function Providers({children}: {children: React.ReactNode}) {
}, [themeName, isEmbed, hasHydrated]);
useEffect(() => {
- if (isEmbed || !hasHydrated) return;
+ if (isEmbed || !hasHydrated) {
+ return;
+ }
try {
window.localStorage.setItem(MODE_STORAGE_KEY, mode);
} catch {
@@ -145,12 +151,18 @@ export function Providers({children}: {children: React.ReactNode}) {
// When embedded, sync theme/mode from parent shell via postMessage
useEffect(() => {
- if (!isEmbed) return;
+ if (!isEmbed) {
+ return;
+ }
const handler = (event: MessageEvent) => {
if (event.data?.type === 'xds-theme-sync') {
const {theme: newTheme, mode: newMode} = event.data;
- if (newTheme && newTheme in themes) setThemeName(newTheme);
- if (newMode === 'light' || newMode === 'dark') setMode(newMode);
+ if (newTheme && newTheme in themes) {
+ setThemeName(newTheme);
+ }
+ if (newMode === 'light' || newMode === 'dark') {
+ setMode(newMode);
+ }
}
};
window.addEventListener('message', handler);
diff --git a/apps/sandbox/src/components/ThemePalettePreview.tsx b/apps/sandbox/src/components/ThemePalettePreview.tsx
index b77bb6711e..82b12d5b05 100644
--- a/apps/sandbox/src/components/ThemePalettePreview.tsx
+++ b/apps/sandbox/src/components/ThemePalettePreview.tsx
@@ -110,7 +110,9 @@ function hexToHct(hex: string): HCT {
);
const [L, a, bL] = xyzToLab(x, y, z);
let hue = (Math.atan2(bL, a) * 180) / Math.PI;
- if (hue < 0) hue += 360;
+ if (hue < 0) {
+ hue += 360;
+ }
return {
hue,
chroma: Math.sqrt(a * a + bL * bL),
@@ -119,8 +121,12 @@ function hexToHct(hex: string): HCT {
}
function hctToHex({hue, chroma, tone}: HCT): string {
- if (tone <= 0) return '#000000';
- if (tone >= 100) return '#ffffff';
+ if (tone <= 0) {
+ return '#000000';
+ }
+ if (tone >= 100) {
+ return '#ffffff';
+ }
if (chroma < 0.5) {
const y = labFInv((tone + 16) / 116);
const g = linearToSrgb(y);
@@ -1073,7 +1079,9 @@ function TonalSection({
const resolveTone = (t: number): string => {
if (effectiveTones) {
const v = effectiveTones[t];
- if (typeof v === 'string') return v;
+ if (typeof v === 'string') {
+ return v;
+ }
}
return computedTones[t];
};
diff --git a/apps/sandbox/src/components/themePreview/ThemeAuditDrawer.tsx b/apps/sandbox/src/components/themePreview/ThemeAuditDrawer.tsx
index 93fcdcd9d0..36ed2b0f9c 100644
--- a/apps/sandbox/src/components/themePreview/ThemeAuditDrawer.tsx
+++ b/apps/sandbox/src/components/themePreview/ThemeAuditDrawer.tsx
@@ -95,9 +95,13 @@ export function useThemeAudit(
const diff = diffThemeTokens(theme);
const snap = auditSnapToRamps(theme, rampSeeds);
const snapByToken: Record<string, SnapAuditEntry> = {};
- for (const e of snap) snapByToken[e.name] = e;
+ for (const e of snap) {
+ snapByToken[e.name] = e;
+ }
const diffByToken: Record<string, TokenDiffEntry> = {};
- for (const e of diff.entries) diffByToken[e.name] = e;
+ for (const e of diff.entries) {
+ diffByToken[e.name] = e;
+ }
const usage = buildTonalUsageMap(snap);
return {diff, snap, snapByToken, diffByToken, usage, rampSeeds};
}, [theme, rampSeeds]);
@@ -448,7 +452,9 @@ export function ThemeAuditDrawer({
// Pasting into Cursor / Claude / any other coding agent gives the model
// enough context to apply the edits without further instruction.
const promptSnippet = useMemo(() => {
- if (overrideCount === 0) return '';
+ if (overrideCount === 0) {
+ return '';
+ }
const inner = serializeAsTokensBlock(overrides, serializeCtx);
const filePath = `packages/themes/${themeName}/src/${themeName}Theme.ts`;
return [
@@ -466,7 +472,9 @@ export function ThemeAuditDrawer({
}, [overrides, serializeCtx, themeName, overrideCount]);
const handleCopySnippet = async () => {
- if (!promptSnippet) return;
+ if (!promptSnippet) {
+ return;
+ }
try {
await navigator.clipboard.writeText(promptSnippet);
setJustCopied(true);
@@ -489,8 +497,12 @@ export function ThemeAuditDrawer({
// instead of being silently hidden.
const categorized = useMemo(() => {
const known = new Set<string>();
- for (const e of audit.snap) known.add(e.name);
- for (const e of audit.diff.entries) known.add(e.name);
+ for (const e of audit.snap) {
+ known.add(e.name);
+ }
+ for (const e of audit.diff.entries) {
+ known.add(e.name);
+ }
return getCategorizedColorTokens(known);
}, [audit.snap, audit.diff.entries]);
@@ -553,7 +565,9 @@ export function ThemeAuditDrawer({
// (the theme doesn't define any of them) so we don't render
// empty headers.
const visibleTokens = tokens.filter(t => audit.snapByToken[t]);
- if (visibleTokens.length === 0) return null;
+ if (visibleTokens.length === 0) {
+ return null;
+ }
return (
<div key={category}>
<h3 style={S.categoryHeader}>{category}</h3>
@@ -570,7 +584,9 @@ export function ThemeAuditDrawer({
const seed = audit.rampSeeds.find(
s => s.name === rampName,
);
- if (!seed) return;
+ if (!seed) {
+ return;
+ }
dispatchOverrides({
type: 'set',
token: tokenName,
@@ -1057,7 +1073,9 @@ function CustomTab({
const colorInputRef = useRef<HTMLInputElement | null>(null);
const openNativePicker = () => {
const el = colorInputRef.current;
- if (!el) return;
+ if (!el) {
+ return;
+ }
if (typeof el.showPicker === 'function') {
el.showPicker();
} else {
@@ -1209,7 +1227,9 @@ function AlphaInput({
}
const clamped = Math.max(0, Math.min(100, Math.round(n)));
setDraft(String(clamped));
- if (clamped !== alphaPct) setAlphaPct(clamped);
+ if (clamped !== alphaPct) {
+ setAlphaPct(clamped);
+ }
};
return (
diff --git a/apps/sandbox/src/components/themePreview/colorCategories.ts b/apps/sandbox/src/components/themePreview/colorCategories.ts
index 8ddb3efeec..b2d5e5d3d8 100644
--- a/apps/sandbox/src/components/themePreview/colorCategories.ts
+++ b/apps/sandbox/src/components/themePreview/colorCategories.ts
@@ -181,18 +181,24 @@ export type CategorizedTokens = Array<{
* `defineSyntaxTheme()` API rather than as raw color tokens, and
* surfacing them here would create a confusing second source of truth.
*/
-export function getCategorizedColorTokens(knownTokens?: Iterable<string>): CategorizedTokens {
+export function getCategorizedColorTokens(
+ knownTokens?: Iterable<string>,
+): CategorizedTokens {
const seen = new Set<string>();
const result: CategorizedTokens = [];
- for (const [category, tokenNames] of Object.entries(COLOR_CATEGORIES) as Array<
- [ColorCategoryName, readonly string[]]
- >) {
+ for (const [category, tokenNames] of Object.entries(
+ COLOR_CATEGORIES,
+ ) as Array<[ColorCategoryName, readonly string[]]>) {
const uniqueTokens = tokenNames.filter(t => {
- if (seen.has(t)) return false;
+ if (seen.has(t)) {
+ return false;
+ }
seen.add(t);
return true;
});
- if (uniqueTokens.length === 0) continue;
+ if (uniqueTokens.length === 0) {
+ continue;
+ }
result.push({category, tokens: [...uniqueTokens]});
}
@@ -201,9 +207,15 @@ export function getCategorizedColorTokens(knownTokens?: Iterable<string>): Categ
// Colors". Syntax tokens are filtered out entirely — see the JSDoc.
const leftovers: string[] = [];
for (const t of knownTokens) {
- if (!t.startsWith('--color-')) continue;
- if (t.startsWith('--color-syntax-')) continue;
- if (seen.has(t)) continue;
+ if (!t.startsWith('--color-')) {
+ continue;
+ }
+ if (t.startsWith('--color-syntax-')) {
+ continue;
+ }
+ if (seen.has(t)) {
+ continue;
+ }
seen.add(t);
leftovers.push(t);
}
diff --git a/apps/sandbox/src/components/themePreview/colorMath.ts b/apps/sandbox/src/components/themePreview/colorMath.ts
index b69dbb5396..6ab81c9913 100644
--- a/apps/sandbox/src/components/themePreview/colorMath.ts
+++ b/apps/sandbox/src/components/themePreview/colorMath.ts
@@ -104,7 +104,11 @@ export function labToXyz(L: number, a: number, b: number): Rgb {
export function hexToLab(hex: string): Rgb {
const [r, g, b] = hexToRgb(hex);
- const [x, y, z] = linearRgbToXyz(srgbToLinear(r), srgbToLinear(g), srgbToLinear(b));
+ const [x, y, z] = linearRgbToXyz(
+ srgbToLinear(r),
+ srgbToLinear(g),
+ srgbToLinear(b),
+ );
return xyzToLab(x, y, z);
}
@@ -115,7 +119,9 @@ export function hexToLab(hex: string): Rgb {
export function hexToHct(hex: string): HCT {
const [L, a, bL] = hexToLab(hex);
let hue = (Math.atan2(bL, a) * 180) / Math.PI;
- if (hue < 0) hue += 360;
+ if (hue < 0) {
+ hue += 360;
+ }
return {
hue,
chroma: Math.sqrt(a * a + bL * bL),
@@ -130,8 +136,12 @@ export function hexToHct(hex: string): HCT {
* round-trip cleanly through sRGB).
*/
export function hctToHex({hue, chroma, tone}: HCT): string {
- if (tone <= 0) return '#000000';
- if (tone >= 100) return '#ffffff';
+ if (tone <= 0) {
+ return '#000000';
+ }
+ if (tone >= 100) {
+ return '#ffffff';
+ }
if (chroma < 0.5) {
const y = labFInv((tone + 16) / 116);
const g = linearToSrgb(y);
@@ -161,7 +171,8 @@ export function hctToHex({hue, chroma, tone}: HCT): string {
bv >= 0 &&
bv <= 255;
if (ok) {
- best = '#' + [r, g, bv].map(c => c.toString(16).padStart(2, '0')).join('');
+ best =
+ '#' + [r, g, bv].map(c => c.toString(16).padStart(2, '0')).join('');
lo = mid;
} else {
hi = mid;
@@ -187,7 +198,10 @@ export type ToneStep = (typeof TONE_STEPS)[number];
* stays visibly hued; capped at chroma × 1.8 so peak saturation doesn't
* exceed what the gamut binary-search inside hctToHex can reach.
*/
-export function tonalPalette(hue: number, chroma: number): Record<number, string> {
+export function tonalPalette(
+ hue: number,
+ chroma: number,
+): Record<number, string> {
const result: Record<number, string> = {};
const maxChroma = chroma * 1.8;
for (const t of TONE_STEPS) {
@@ -283,9 +297,15 @@ export function deltaEHex(a: string, b: string): number {
export type SnapVerdict = 'exact' | 'snapped' | 'near' | 'off';
export function deltaEVerdict(d: number): SnapVerdict {
- if (d <= 1.0) return 'exact';
- if (d <= 2.5) return 'snapped';
- if (d <= 5.0) return 'near';
+ if (d <= 1.0) {
+ return 'exact';
+ }
+ if (d <= 2.5) {
+ return 'snapped';
+ }
+ if (d <= 5.0) {
+ return 'near';
+ }
return 'off';
}
@@ -347,7 +367,9 @@ export function findClosestRampStep(
seeds: RampSeed[],
mode: Mode,
): SnapMatch | null {
- if (seeds.length === 0) return null;
+ if (seeds.length === 0) {
+ return null;
+ }
const targetLab = hexToLab(targetHex);
let best: SnapMatch | null = null;
for (const seed of seeds) {
@@ -374,7 +396,9 @@ export function findClosestRampStep(
const swatch = lookup(t);
// Canonical ramps may be sparse (e.g. only 0/5/10/…/100). Skip
// tone steps without a value rather than crashing on `undefined`.
- if (!swatch) continue;
+ if (!swatch) {
+ continue;
+ }
const d = deltaE(targetLab, hexToLab(swatch));
if (best == null || d < best.deltaE) {
best = {
diff --git a/apps/sandbox/src/components/themePreview/themeAudit.ts b/apps/sandbox/src/components/themePreview/themeAudit.ts
index b6b38850fd..9e1b0de573 100644
--- a/apps/sandbox/src/components/themePreview/themeAudit.ts
+++ b/apps/sandbox/src/components/themePreview/themeAudit.ts
@@ -67,21 +67,37 @@ const CATEGORY_ORDER: TokenCategory[] = [
];
export function categorizeToken(name: string): TokenCategory {
- if (name.startsWith('--color-syntax-')) return 'syntax';
- if (name.startsWith('--color-background-')) return 'background';
+ if (name.startsWith('--color-syntax-')) {
+ return 'syntax';
+ }
+ if (name.startsWith('--color-background-')) {
+ return 'background';
+ }
if (name.startsWith('--color-text-') || name.startsWith('--color-icon-')) {
return 'text';
}
- if (name.startsWith('--color-border-') || name === '--color-border' || name === '--color-border-emphasized') {
+ if (
+ name.startsWith('--color-border-') ||
+ name === '--color-border' ||
+ name === '--color-border-emphasized'
+ ) {
return 'border';
}
- if (name.startsWith('--color-')) return 'color';
- if (name.startsWith('--shadow-')) return 'shadow';
- if (name.startsWith('--radius-')) return 'radius';
+ if (name.startsWith('--color-')) {
+ return 'color';
+ }
+ if (name.startsWith('--shadow-')) {
+ return 'shadow';
+ }
+ if (name.startsWith('--radius-')) {
+ return 'radius';
+ }
if (name.startsWith('--space-') || name.startsWith('--spacing-')) {
return 'spacing';
}
- if (name.startsWith('--size-')) return 'size';
+ if (name.startsWith('--size-')) {
+ return 'size';
+ }
if (
name.startsWith('--font-') ||
name.startsWith('--text-') ||
@@ -157,7 +173,9 @@ export function diffThemeTokens(theme: XDSDefinedTheme): TokenDiff {
removed: 0,
};
const changedByCategory = {} as Record<TokenCategory, number>;
- for (const c of CATEGORY_ORDER) changedByCategory[c] = 0;
+ for (const c of CATEGORY_ORDER) {
+ changedByCategory[c] = 0;
+ }
for (const name of allKeys) {
const defaultValue = xdsTokenDefaults[name];
@@ -223,7 +241,8 @@ export function diffThemeTokens(theme: XDSDefinedTheme): TokenDiff {
* care about the base color for snap detection.
*/
const LIGHT_DARK_RE = /^light-dark\(\s*([^,]+?)\s*,\s*([^)]+?)\s*\)$/;
-const HEX_RE = /^#([0-9a-fA-F]{3}|[0-9a-fA-F]{4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/;
+const HEX_RE =
+ /^#([0-9a-fA-F]{3}|[0-9a-fA-F]{4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/;
export interface TokenColor {
light: string | null;
@@ -307,7 +326,9 @@ export function parseTokenColor(value: string | undefined): TokenColor {
function extractAlpha(input: string): number {
const v = input.trim();
const hex8 = v.match(/^#([0-9a-fA-F]{6})([0-9a-fA-F]{2})$/);
- if (hex8) return parseInt(hex8[2], 16) / 255;
+ if (hex8) {
+ return parseInt(hex8[2], 16) / 255;
+ }
const hex4 = v.match(/^#([0-9a-fA-F]{3})([0-9a-fA-F])$/);
if (hex4) {
const aChar = hex4[2];
@@ -318,7 +339,9 @@ function extractAlpha(input: string): number {
);
if (rgba) {
const a = Number(rgba[1]);
- if (Number.isFinite(a)) return Math.max(0, Math.min(1, a));
+ if (Number.isFinite(a)) {
+ return Math.max(0, Math.min(1, a));
+ }
}
return 1;
}
@@ -339,12 +362,20 @@ function normalizeColorString(input: string): string | null {
if (v.length === 4) {
return ('#' + v[1] + v[1] + v[2] + v[2] + v[3] + v[3]).toLowerCase();
}
- if (v.length === 9) return v.slice(0, 7).toLowerCase();
+ if (v.length === 9) {
+ return v.slice(0, 7).toLowerCase();
+ }
return v.toLowerCase();
}
- if (v === 'black') return '#000000';
- if (v === 'white') return '#ffffff';
- if (v === 'transparent') return null;
+ if (v === 'black') {
+ return '#000000';
+ }
+ if (v === 'white') {
+ return '#ffffff';
+ }
+ if (v === 'transparent') {
+ return null;
+ }
// rgb()/rgba() - parse the three channels
const rgbMatch = v.match(
/^rgba?\(\s*(\d+(?:\.\d+)?)\s*[,\s]\s*(\d+(?:\.\d+)?)\s*[,\s]\s*(\d+(?:\.\d+)?)/,
@@ -409,12 +440,20 @@ export function auditSnapToRamps(
];
for (const [name, value] of Object.entries(theme.tokens)) {
const category = categorizeToken(name);
- if (!eligibleCategories.includes(category)) continue;
+ if (!eligibleCategories.includes(category)) {
+ continue;
+ }
const {light, dark, indirect, alphaLight, alphaDark, hasAlpha} =
parseTokenColor(value);
- if (!light && !dark && !indirect) continue;
- const lightMatch = light ? findClosestRampStep(light, rampSeeds, 'light') : null;
- const darkMatch = dark ? findClosestRampStep(dark, rampSeeds, 'dark') : null;
+ if (!light && !dark && !indirect) {
+ continue;
+ }
+ const lightMatch = light
+ ? findClosestRampStep(light, rampSeeds, 'light')
+ : null;
+ const darkMatch = dark
+ ? findClosestRampStep(dark, rampSeeds, 'dark')
+ : null;
out.push({
name,
category,
@@ -431,13 +470,19 @@ export function auditSnapToRamps(
// Sort: worst (off-ramp) first so the noisy rows surface to the top.
// Within the same verdict, alphabetical for stable ordering.
const verdictRank = (m: SnapMatch | null) =>
- m == null
- ? 99
- : {off: 0, near: 1, snapped: 2, exact: 3}[m.verdict];
+ m == null ? 99 : {off: 0, near: 1, snapped: 2, exact: 3}[m.verdict];
out.sort((a, b) => {
- const aWorst = Math.min(verdictRank(a.lightMatch), verdictRank(a.darkMatch));
- const bWorst = Math.min(verdictRank(b.lightMatch), verdictRank(b.darkMatch));
- if (aWorst !== bWorst) return aWorst - bWorst;
+ const aWorst = Math.min(
+ verdictRank(a.lightMatch),
+ verdictRank(a.darkMatch),
+ );
+ const bWorst = Math.min(
+ verdictRank(b.lightMatch),
+ verdictRank(b.darkMatch),
+ );
+ if (aWorst !== bWorst) {
+ return aWorst - bWorst;
+ }
return a.name.localeCompare(b.name);
});
return out;
@@ -507,7 +552,9 @@ export function buildTonalUsageMap(
usage: TonalUsage,
) => {
const k = `${rampName}::${mode}::${tone}`;
- if (!map[k]) map[k] = [];
+ if (!map[k]) {
+ map[k] = [];
+ }
map[k].push(usage);
};
@@ -518,7 +565,11 @@ export function buildTonalUsageMap(
// markers entirely (they're explicitly off-ramp by definition);
// off-ramp tokens with no override also get no marker — there's
// nowhere on the ramp to put one.
- if (ov?.light?.kind === 'palette' && ov.light.rampName && ov.light.tone != null) {
+ if (
+ ov?.light?.kind === 'palette' &&
+ ov.light.rampName &&
+ ov.light.tone != null
+ ) {
push(ov.light.rampName, 'light', ov.light.tone, {
name: e.name,
mode: 'light',
@@ -533,7 +584,11 @@ export function buildTonalUsageMap(
deltaE: e.lightMatch.deltaE,
});
}
- if (ov?.dark?.kind === 'palette' && ov.dark.rampName && ov.dark.tone != null) {
+ if (
+ ov?.dark?.kind === 'palette' &&
+ ov.dark.rampName &&
+ ov.dark.tone != null
+ ) {
push(ov.dark.rampName, 'dark', ov.dark.tone, {
name: e.name,
mode: 'dark',
diff --git a/apps/sandbox/src/components/themePreview/themeOverrides.ts b/apps/sandbox/src/components/themePreview/themeOverrides.ts
index 6ac59e1f60..15f2a62abf 100644
--- a/apps/sandbox/src/components/themePreview/themeOverrides.ts
+++ b/apps/sandbox/src/components/themePreview/themeOverrides.ts
@@ -96,7 +96,9 @@ export function overridesReducer(
}
case 'clearMode': {
const prev = state[action.token];
- if (!prev) return state;
+ if (!prev) {
+ return state;
+ }
const next: TokenOverride = {...prev};
delete next[action.mode];
// Drop the token entry entirely when neither mode is set so the
@@ -134,7 +136,9 @@ export function resolveOverrideHex(
): string {
if (seed.tones) {
const v = seed.tones[tone];
- if (typeof v === 'string') return v;
+ if (typeof v === 'string') {
+ return v;
+ }
}
const {hue, chroma} = hexToHct(seed.sourceHex);
return tonalPaletteForMode(hue, chroma, mode)[tone];
@@ -189,7 +193,9 @@ export function buildCustomOverride(input: string): ModeOverride {
export function normalizeHex(input: string): string {
const trimmed = input.trim().toLowerCase();
const m = trimmed.match(/^#?([0-9a-f]{3,8})$/);
- if (!m) return '#000000';
+ if (!m) {
+ return '#000000';
+ }
const body = m[1];
if (body.length === 3) {
return '#' + body[0] + body[0] + body[1] + body[1] + body[2] + body[2];
@@ -197,15 +203,21 @@ export function normalizeHex(input: string): string {
if (body.length === 4) {
return '#' + body[0] + body[0] + body[1] + body[1] + body[2] + body[2];
}
- if (body.length === 6) return '#' + body;
- if (body.length === 8) return '#' + body.slice(0, 6);
+ if (body.length === 6) {
+ return '#' + body;
+ }
+ if (body.length === 8) {
+ return '#' + body.slice(0, 6);
+ }
return '#000000';
}
export function isValidHex(input: string): boolean {
// Accept either a bare hex or the `'#hex N%'` shape used by the
// alpha-aware Custom-tab input.
- if (/^#?[0-9a-fA-F]{3,8}$/.test(input.trim())) return true;
+ if (/^#?[0-9a-fA-F]{3,8}$/.test(input.trim())) {
+ return true;
+ }
return /^#?[0-9a-fA-F]{3,8}\s+\d{1,3}%?$/.test(input.trim());
}
@@ -219,9 +231,15 @@ export function isValidHex(input: string): boolean {
* specified" in CSS color literals.
*/
export function clampAlpha(alpha: number | undefined): number {
- if (alpha == null || !Number.isFinite(alpha)) return 1;
- if (alpha < 0) return 0;
- if (alpha > 1) return 1;
+ if (alpha == null || !Number.isFinite(alpha)) {
+ return 1;
+ }
+ if (alpha < 0) {
+ return 0;
+ }
+ if (alpha > 1) {
+ return 1;
+ }
return alpha;
}
@@ -242,7 +260,9 @@ export function alphaToHex(alpha: number): string {
export function composeAlphaHex(hex: string, alpha?: number): string {
const a = clampAlpha(alpha);
const base = normalizeHex(hex);
- if (a === 1) return base;
+ if (a === 1) {
+ return base;
+ }
return base + alphaToHex(a);
}
@@ -254,7 +274,9 @@ export function composeAlphaHex(hex: string, alpha?: number): string {
export function formatHexWithAlpha(hex: string, alpha?: number): string {
const a = clampAlpha(alpha);
const base = normalizeHex(hex);
- if (a === 1) return base;
+ if (a === 1) {
+ return base;
+ }
return base + ' ' + Math.round(a * 100) + '%';
}
@@ -317,8 +339,12 @@ export function countModeOverrides(state: OverridesMap): {
let light = 0;
let dark = 0;
for (const t of Object.values(state)) {
- if (t.light) light++;
- if (t.dark) dark++;
+ if (t.light) {
+ light++;
+ }
+ if (t.dark) {
+ dark++;
+ }
}
return {light, dark};
}
@@ -343,7 +369,10 @@ export function countModeOverrides(state: OverridesMap): {
export interface SerializeContext {
/** Current resolved hex per token per mode — used to fill in the side
* the user didn't reassign. */
- currentTokenValues: Record<string, {light: string | null; dark: string | null}>;
+ currentTokenValues: Record<
+ string,
+ {light: string | null; dark: string | null}
+ >;
}
export function serializeAsTokensBlock(
@@ -369,8 +398,12 @@ export function serializeAsTokensBlock(
: `[${formatHex(lightHex)}, ${formatHex(darkHex)}]`;
const annotations: string[] = [];
- if (ov.light) annotations.push(`light: ${describeOverride(ov.light)}`);
- if (ov.dark) annotations.push(`dark: ${describeOverride(ov.dark)}`);
+ if (ov.light) {
+ annotations.push(`light: ${describeOverride(ov.light)}`);
+ }
+ if (ov.dark) {
+ annotations.push(`dark: ${describeOverride(ov.dark)}`);
+ }
const comment = annotations.length ? ` // ${annotations.join(' · ')}` : '';
lines.push(` '${token}': ${value},${comment}`);
@@ -391,7 +424,9 @@ export function describeOverride(ov: ModeOverride): string {
}
function formatHex(hex: string | null): string {
- if (!hex) return `''`;
+ if (!hex) {
+ return `''`;
+ }
return `'${hex}'`;
}
@@ -429,8 +464,12 @@ export function toApplyPayload(
lightHex === darkHex ? lightHex : [lightHex, darkHex];
const annotations: string[] = [];
- if (ov.light) annotations.push(`light: ${describeOverride(ov.light)}`);
- if (ov.dark) annotations.push(`dark: ${describeOverride(ov.dark)}`);
+ if (ov.light) {
+ annotations.push(`light: ${describeOverride(ov.light)}`);
+ }
+ if (ov.dark) {
+ annotations.push(`dark: ${describeOverride(ov.dark)}`);
+ }
entries.push({
token,
value,
@@ -471,7 +510,9 @@ export function buildOverrideCSSVars(
const current = ctx.currentTokenValues[token] ?? {light: null, dark: null};
const lightHex = ov.light?.hex ?? current.light;
const darkHex = ov.dark?.hex ?? current.dark;
- if (!lightHex && !darkHex) continue;
+ if (!lightHex && !darkHex) {
+ continue;
+ }
if (lightHex === darkHex && lightHex) {
vars[token] = lightHex;
} else {
@@ -479,7 +520,8 @@ export function buildOverrideCSSVars(
// unparseable (e.g. var() reference). Fall back to a transparent
// sentinel rather than emitting `light-dark(null, ...)` which is
// invalid CSS and would silently break the cascade for that token.
- vars[token] = `light-dark(${lightHex ?? 'transparent'}, ${darkHex ?? 'transparent'})`;
+ vars[token] =
+ `light-dark(${lightHex ?? 'transparent'}, ${darkHex ?? 'transparent'})`;
}
}
return vars as React.CSSProperties;
diff --git a/apps/storybook/stories/Chart.stories.tsx b/apps/storybook/stories/Chart.stories.tsx
index 8d75d0c5cd..90cd74566f 100644
--- a/apps/storybook/stories/Chart.stories.tsx
+++ b/apps/storybook/stories/Chart.stories.tsx
@@ -46,7 +46,9 @@ export const BarChart: StoryObj = {
const colors = useXDSChartColors();
const [raw, loading] = useDataset<Barley>('barley.json');
const data = useMemo(() => {
- if (!raw.length) return [];
+ if (!raw.length) {
+ return [];
+ }
const byVariety = new Map<string, {sum: number; count: number}>();
for (const d of raw) {
const e = byVariety.get(d.variety) ?? {sum: 0, count: 0};
@@ -62,7 +64,9 @@ export const BarChart: StoryObj = {
.sort((a, b) => b.avgYield - a.avgYield)
.slice(0, 10);
}, [raw]);
- if (loading) return <XDSText type="supporting">Loading…</XDSText>;
+ if (loading) {
+ return <XDSText type="supporting">Loading…</XDSText>;
+ }
return (
<XDSChart data={data} xKey="variety" yKeys={['avgYield']} height={300}>
<XDSChartGrid horizontal />
@@ -81,7 +85,9 @@ export const LineChart: StoryObj = {
const colors = useXDSChartColors();
const [raw, loading] = useDataset<Stock>('stocks.csv');
const data = useMemo(() => {
- if (!raw.length) return [];
+ if (!raw.length) {
+ return [];
+ }
const filtered = raw.filter(
d => d.symbol === 'AAPL' || d.symbol === 'GOOG',
);
@@ -95,7 +101,9 @@ export const LineChart: StoryObj = {
.filter(d => d.AAPL != null && d.GOOG != null)
.slice(-12);
}, [raw]);
- if (loading) return <XDSText type="supporting">Loading…</XDSText>;
+ if (loading) {
+ return <XDSText type="supporting">Loading…</XDSText>;
+ }
const c = colors.categorical(2);
return (
<XDSChart
@@ -131,7 +139,9 @@ export const ScatterPlot: StoryObj = {
.filter(d => d.Horsepower != null && d.Miles_per_Gallon != null)
.map(d => ({hp: d.Horsepower, mpg: d.Miles_per_Gallon}));
}, [raw]);
- if (loading) return <XDSText type="supporting">Loading…</XDSText>;
+ if (loading) {
+ return <XDSText type="supporting">Loading…</XDSText>;
+ }
return (
<XDSChart
data={data}
@@ -163,8 +173,9 @@ export const WebGLScatter: StoryObj = {
.filter(d => d.delay != null && d.distance != null)
.map(d => ({distance: d.distance, delay: d.delay}));
}, [raw]);
- if (loading)
+ if (loading) {
return <XDSText type="supporting">Loading 10k flights…</XDSText>;
+ }
return (
<XDSStack direction="vertical" gap={2}>
<XDSText type="supporting" color="secondary">
@@ -197,7 +208,9 @@ export const ConfidenceBand: StoryObj = {
const colors = useXDSChartColors();
const [raw, loading] = useDataset<Weather>('seattle-weather.csv');
const data = useMemo(() => {
- if (!raw.length) return [];
+ if (!raw.length) {
+ return [];
+ }
const byMonth = new Map<
string,
{maxSum: number; minSum: number; count: number}
@@ -220,7 +233,9 @@ export const ConfidenceBand: StoryObj = {
.sort((a, b) => a.month.localeCompare(b.month))
.slice(-24);
}, [raw]);
- if (loading) return <XDSText type="supporting">Loading…</XDSText>;
+ if (loading) {
+ return <XDSText type="supporting">Loading…</XDSText>;
+ }
return (
<XDSChart
data={data}
@@ -250,7 +265,9 @@ export const Heatmap: StoryObj = {
const colors = useXDSChartColors();
const [raw, loading] = useDataset<Gapminder>('gapminder.json');
const data = useMemo(() => {
- if (!raw.length) return [];
+ if (!raw.length) {
+ return [];
+ }
const countries = [
'United States',
'China',
@@ -274,7 +291,9 @@ export const Heatmap: StoryObj = {
lifeExp: Math.round(d.life_expect),
}));
}, [raw]);
- if (loading) return <XDSText type="supporting">Loading…</XDSText>;
+ if (loading) {
+ return <XDSText type="supporting">Loading…</XDSText>;
+ }
return (
<XDSChart data={data} xKey="year" yKeys={['lifeExp']} height={300}>
<XDSChartAxis position="bottom" />
diff --git a/apps/storybook/stories/ChartCoordinated.stories.tsx b/apps/storybook/stories/ChartCoordinated.stories.tsx
index f7ccde6174..1fa0e7ef68 100644
--- a/apps/storybook/stories/ChartCoordinated.stories.tsx
+++ b/apps/storybook/stories/ChartCoordinated.stories.tsx
@@ -47,7 +47,9 @@ export const CoordinatedViews: StoryObj = {
);
const filteredData = useMemo(() => {
- if (!brushRange) return allData;
+ if (!brushRange) {
+ return allData;
+ }
return allData.filter(
d => d.Horsepower >= brushRange[0] && d.Horsepower <= brushRange[1],
);
@@ -88,8 +90,9 @@ export const CoordinatedViews: StoryObj = {
[filteredData],
);
- if (!allData.length)
+ if (!allData.length) {
return <XDSText type="supporting">Loading\u2026</XDSText>;
+ }
const c = colors.categorical(3);
diff --git a/apps/storybook/stories/ChartInteractions.stories.tsx b/apps/storybook/stories/ChartInteractions.stories.tsx
index 7013ab3414..647aaecd1c 100644
--- a/apps/storybook/stories/ChartInteractions.stories.tsx
+++ b/apps/storybook/stories/ChartInteractions.stories.tsx
@@ -122,7 +122,9 @@ export const Brush2D: StoryObj = {
.map(d => ({hp: d.Horsepower, mpg: d.Miles_per_Gallon})),
[raw],
);
- if (!data.length) return <XDSText type="supporting">Loading…</XDSText>;
+ if (!data.length) {
+ return <XDSText type="supporting">Loading…</XDSText>;
+ }
return (
<XDSStack direction="vertical" gap={4}>
<XDSHeading level={3}>2D Brush — Scatter Plot</XDSHeading>
@@ -167,7 +169,9 @@ export const Crosshair: StoryObj = {
.map(d => ({hp: d.Horsepower, mpg: d.Miles_per_Gallon})),
[raw],
);
- if (!data.length) return <XDSText type="supporting">Loading…</XDSText>;
+ if (!data.length) {
+ return <XDSText type="supporting">Loading…</XDSText>;
+ }
return (
<XDSStack direction="vertical" gap={4}>
<XDSHeading level={3}>Crosshair</XDSHeading>
@@ -211,7 +215,9 @@ export const ZoomPan: StoryObj = {
);
const [xDomain, setXDomain] = useState<[number, number]>([40, 230]);
const [yDomain, setYDomain] = useState<[number, number]>([8, 47]);
- if (!data.length) return <XDSText type="supporting">Loading…</XDSText>;
+ if (!data.length) {
+ return <XDSText type="supporting">Loading…</XDSText>;
+ }
return (
<XDSStack direction="vertical" gap={4}>
<XDSHeading level={3}>Zoom & Pan</XDSHeading>
@@ -257,7 +263,9 @@ export const ClickSelect: StoryObj = {
[raw],
);
const [selected, setSelected] = useState<number[]>([]);
- if (!data.length) return <XDSText type="supporting">Loading…</XDSText>;
+ if (!data.length) {
+ return <XDSText type="supporting">Loading…</XDSText>;
+ }
return (
<XDSStack direction="vertical" gap={4}>
<XDSHeading level={3}>Click to Select</XDSHeading>
diff --git a/apps/storybook/stories/ChartStreamPerf.stories.tsx b/apps/storybook/stories/ChartStreamPerf.stories.tsx
index 515f00eef0..8cf0e0a674 100644
--- a/apps/storybook/stories/ChartStreamPerf.stories.tsx
+++ b/apps/storybook/stories/ChartStreamPerf.stories.tsx
@@ -42,7 +42,9 @@ export const XDomainUpdateCost: StoryObj = {
lastFrameRef.current = now;
frameTimesRef.current.push(dt);
- if (frameTimesRef.current.length > 60) frameTimesRef.current.shift();
+ if (frameTimesRef.current.length > 60) {
+ frameTimesRef.current.shift();
+ }
// Update stats every 30 frames
if (tRef.current % 30 === 0 && frameTimesRef.current.length > 0) {
@@ -127,7 +129,9 @@ export const ThrottledXDomain: StoryObj = {
lastFrameRef.current = now;
frameTimesRef.current.push(dt);
- if (frameTimesRef.current.length > 60) frameTimesRef.current.shift();
+ if (frameTimesRef.current.length > 60) {
+ frameTimesRef.current.shift();
+ }
if (tRef.current % 30 === 0 && frameTimesRef.current.length > 0) {
const avg =
@@ -213,7 +217,9 @@ export const StressTest: StoryObj = {
const dt = now - lastFrameRef.current;
lastFrameRef.current = now;
frameTimesRef.current.push(dt);
- if (frameTimesRef.current.length > 60) frameTimesRef.current.shift();
+ if (frameTimesRef.current.length > 60) {
+ frameTimesRef.current.shift();
+ }
if (tRef.current % 30 === 0 && frameTimesRef.current.length > 0) {
const avg =
frameTimesRef.current.reduce((a, b) => a + b, 0) /
diff --git a/apps/storybook/stories/CodeEditorPerf.stories.tsx b/apps/storybook/stories/CodeEditorPerf.stories.tsx
index 53ca6bb7e5..0d6126fa6c 100644
--- a/apps/storybook/stories/CodeEditorPerf.stories.tsx
+++ b/apps/storybook/stories/CodeEditorPerf.stories.tsx
@@ -21,13 +21,19 @@ function generateCode(lineCount: number): string {
const lines: string[] = [];
for (let i = 0; i < lineCount; i++) {
const mod = i % 6;
- if (mod === 0) lines.push(`import {Component${i}} from './module${i}';`);
- else if (mod === 1) lines.push(`const value${i} = ${i} + Math.random();`);
- else if (mod === 2) lines.push(`function compute${i}(x: number): number {`);
- else if (mod === 3)
+ if (mod === 0) {
+ lines.push(`import {Component${i}} from './module${i}';`);
+ } else if (mod === 1) {
+ lines.push(`const value${i} = ${i} + Math.random();`);
+ } else if (mod === 2) {
+ lines.push(`function compute${i}(x: number): number {`);
+ } else if (mod === 3) {
lines.push(` return x * ${i} + value${Math.max(0, i - 2)};`);
- else if (mod === 4) lines.push(`}`);
- else lines.push(`// Line ${i + 1}: performance test`);
+ } else if (mod === 4) {
+ lines.push(`}`);
+ } else {
+ lines.push(`// Line ${i + 1}: performance test`);
+ }
}
return lines.join('\n');
}
diff --git a/apps/storybook/stories/Markdown.stories.tsx b/apps/storybook/stories/Markdown.stories.tsx
index ba5ae8bb29..b4e5c92c9b 100644
--- a/apps/storybook/stories/Markdown.stories.tsx
+++ b/apps/storybook/stories/Markdown.stories.tsx
@@ -204,7 +204,9 @@ export const Streaming: Story = {
const [key, setKey] = useState(0);
useEffect(() => {
- if (!isStreaming) return;
+ if (!isStreaming) {
+ return;
+ }
if (charIndex >= text.length) {
setIsStreaming(false);
return;
@@ -346,8 +348,7 @@ export const InlinePlugins: Story = {
color: 'var(--color-text-accent, #0066FF)',
textDecoration: 'none',
fontWeight: 600,
- }}
- >
+ }}>
{match[0]}
</a>
),
@@ -363,8 +364,7 @@ export const InlinePlugins: Story = {
color: 'var(--color-text-accent, #0066FF)',
textDecoration: 'none',
fontWeight: 600,
- }}
- >
+ }}>
{match[0]}
</a>
),
@@ -400,7 +400,10 @@ export const InlinePlugins: Story = {
return (
<div style={{maxWidth: 680}}>
- <XDSMarkdown inlinePlugins={inlinePlugins} density="compact" headingLevelStart={2}>
+ <XDSMarkdown
+ inlinePlugins={inlinePlugins}
+ density="compact"
+ headingLevelStart={2}>
{markdown}
</XDSMarkdown>
</div>
diff --git a/apps/storybook/stories/MarkdownCitations.stories.tsx b/apps/storybook/stories/MarkdownCitations.stories.tsx
index 0b2549e80b..adbd668c24 100644
--- a/apps/storybook/stories/MarkdownCitations.stories.tsx
+++ b/apps/storybook/stories/MarkdownCitations.stories.tsx
@@ -130,7 +130,9 @@ export const StreamingWithCitations: Story = {
const [key, setKey] = useState(0);
useEffect(() => {
- if (!isStreaming) return;
+ if (!isStreaming) {
+ return;
+ }
if (charIndex >= text.length) {
setIsStreaming(false);
return;
diff --git a/apps/storybook/stories/SVGIconRegistry.stories.tsx b/apps/storybook/stories/SVGIconRegistry.stories.tsx
index 3737ba4609..adf621bf61 100644
--- a/apps/storybook/stories/SVGIconRegistry.stories.tsx
+++ b/apps/storybook/stories/SVGIconRegistry.stories.tsx
@@ -50,7 +50,9 @@ function estimateBBox(attrs: Record<string, string>, type: string): BBox {
attrs.d ||
`${attrs.x1 || 0} ${attrs.y1 || 0} ${attrs.x2 || 0} ${attrs.y2 || 0}`;
const nums = d.match(/-?[\d.]+/g)?.map(Number) || [];
- if (nums.length < 2) return {x: 0, y: 0, width: 24, height: 24};
+ if (nums.length < 2) {
+ return {x: 0, y: 0, width: 24, height: 24};
+ }
let minX = Infinity,
minY = Infinity,
@@ -67,7 +69,9 @@ function estimateBBox(attrs: Record<string, string>, type: string): BBox {
maxY = Math.max(maxY, y);
}
}
- if (!isFinite(minX)) return {x: 0, y: 0, width: 24, height: 24};
+ if (!isFinite(minX)) {
+ return {x: 0, y: 0, width: 24, height: 24};
+ }
return {x: minX, y: minY, width: maxX - minX, height: maxY - minY};
}
@@ -93,7 +97,9 @@ function jsxSvgToIconDef(
name: string,
element: ReactElement,
): SVGIconDef | null {
- if (!element?.props) return null;
+ if (!element?.props) {
+ return null;
+ }
const elementProps = element.props as Record<string, unknown>;
const children = Children.toArray(elementProps.children as ReactNode).filter(
@@ -104,12 +110,15 @@ function jsxSvgToIconDef(
const shapes: Array<IconShape & {bbox: BBox}> = [];
for (const child of children) {
- if (!isValidElement(child)) continue;
+ if (!isValidElement(child)) {
+ continue;
+ }
const type = child.type as string;
if (
!['path', 'circle', 'rect', 'line', 'polyline', 'polygon'].includes(type)
- )
+ ) {
continue;
+ }
const childProps = child.props as Record<string, unknown>;
const {key: _key, children: _, ...rawAttrs} = childProps;
@@ -163,7 +172,9 @@ function jsxSvgToIconDef(
shapes.push({type: type as IconShape['type'], attrs, role, bbox});
}
- if (shapes.length === 0) return null;
+ if (shapes.length === 0) {
+ return null;
+ }
// Layer classification: CONTAINMENT-BASED
// Only classify as secondary if geometrically contained within a larger shape
@@ -232,7 +243,9 @@ export const DefaultRegistryIcons: StoryObj = {
const converted: Array<{name: string; def: SVGIconDef}> = [];
for (const [name, jsx] of Object.entries(defaultIcons)) {
const def = jsxSvgToIconDef(name, jsx as ReactElement);
- if (def) converted.push({name, def});
+ if (def) {
+ converted.push({name, def});
+ }
}
return (
diff --git a/apps/storybook/stories/SankeyChart.stories.tsx b/apps/storybook/stories/SankeyChart.stories.tsx
index 98f0c4d291..1ec9b6ccee 100644
--- a/apps/storybook/stories/SankeyChart.stories.tsx
+++ b/apps/storybook/stories/SankeyChart.stories.tsx
@@ -519,10 +519,15 @@ const budgetColumns = [
];
function formatBudget(value: number): string {
- if (value >= 1_000_000_000)
+ if (value >= 1_000_000_000) {
return '$' + (value / 1_000_000_000).toFixed(1) + 'T';
- if (value >= 1_000_000) return '$' + Math.round(value / 1_000_000) + 'B';
- if (value >= 1_000) return '$' + Math.round(value / 1_000) + 'M';
+ }
+ if (value >= 1_000_000) {
+ return '$' + Math.round(value / 1_000_000) + 'B';
+ }
+ if (value >= 1_000) {
+ return '$' + Math.round(value / 1_000) + 'M';
+ }
return '$' + value.toLocaleString();
}
diff --git a/apps/storybook/stories/Thumbnail.stories.tsx b/apps/storybook/stories/Thumbnail.stories.tsx
index 7d5b76e9e5..9ffa7920a2 100644
--- a/apps/storybook/stories/Thumbnail.stories.tsx
+++ b/apps/storybook/stories/Thumbnail.stories.tsx
@@ -55,7 +55,13 @@ export const WithLabel: Story = {
export const WithRemove: Story = {
render: () => {
const [visible, setVisible] = useState(true);
- if (!visible) return <p style={{color: '#888', fontSize: 12}}>Removed. <button onClick={() => setVisible(true)}>Undo</button></p>;
+ if (!visible) {
+ return (
+ <p style={{color: '#888', fontSize: 12}}>
+ Removed. <button onClick={() => setVisible(true)}>Undo</button>
+ </p>
+ );
+ }
return (
<XDSThumbnail
src={LIGHT_IMAGE}
@@ -70,7 +76,13 @@ export const WithRemove: Story = {
export const WithCaption: Story = {
render: () => {
const [visible, setVisible] = useState(true);
- if (!visible) return <p style={{color: '#888', fontSize: 12}}>Removed. <button onClick={() => setVisible(true)}>Undo</button></p>;
+ if (!visible) {
+ return (
+ <p style={{color: '#888', fontSize: 12}}>
+ Removed. <button onClick={() => setVisible(true)}>Undo</button>
+ </p>
+ );
+ }
return (
<XDSThumbnail
src={WARM_IMAGE}
@@ -113,12 +125,15 @@ export const Placeholder: Story = {
name: 'No Image (Placeholder)',
render: () => {
const [visible, setVisible] = useState(true);
- if (!visible) return <p style={{color: '#888', fontSize: 12}}>Removed. <button onClick={() => setVisible(true)}>Undo</button></p>;
+ if (!visible) {
+ return (
+ <p style={{color: '#888', fontSize: 12}}>
+ Removed. <button onClick={() => setVisible(true)}>Undo</button>
+ </p>
+ );
+ }
return (
- <XDSThumbnail
- label="report.pdf"
- onRemove={() => setVisible(false)}
- />
+ <XDSThumbnail label="report.pdf" onRemove={() => setVisible(false)} />
);
},
};
@@ -146,7 +161,8 @@ export const MediaModeTest: Story = {
return (
<div>
<p style={{fontSize: 12, color: '#888', marginBottom: 8}}>
- Remove buttons should adapt: light icon on dark images, dark icon on light images.
+ Remove buttons should adapt: light icon on dark images, dark icon on
+ light images.
</p>
<div style={{display: 'flex', gap: 8, alignItems: 'flex-start'}}>
{items.map(item => (
@@ -155,12 +171,15 @@ export const MediaModeTest: Story = {
src={item.src}
alt={item.alt}
label={item.label}
- onRemove={() => setItems(prev => prev.filter(i => i.label !== item.label))}
+ onRemove={() =>
+ setItems(prev => prev.filter(i => i.label !== item.label))
+ }
/>
))}
{items.length === 0 && (
<p style={{color: '#888', fontSize: 12}}>
- All removed. <button onClick={() => setItems(images)}>Reset</button>
+ All removed.{' '}
+ <button onClick={() => setItems(images)}>Reset</button>
</p>
)}
</div>
@@ -185,12 +204,15 @@ export const Gallery: Story = {
src={item.src}
alt={item.label}
label={item.label}
- onRemove={() => setItems(prev => prev.filter(i => i.id !== item.id))}
+ onRemove={() =>
+ setItems(prev => prev.filter(i => i.id !== item.id))
+ }
/>
))}
{items.length === 0 && (
<p style={{color: '#888', fontSize: 12}}>
- All removed. <button onClick={() => setItems(initial)}>Reset</button>
+ All removed.{' '}
+ <button onClick={() => setItems(initial)}>Reset</button>
</p>
)}
</div>
diff --git a/apps/storybook/stories/XIFSpec.stories.tsx b/apps/storybook/stories/XIFSpec.stories.tsx
index 78ed5f42f1..0ac46bee03 100644
--- a/apps/storybook/stories/XIFSpec.stories.tsx
+++ b/apps/storybook/stories/XIFSpec.stories.tsx
@@ -104,13 +104,21 @@ export const SpecExamples: StoryObj = {
{xifExamples.map(xif => {
const def = xifToSvgIconDef(xif);
const features: string[] = [];
- if (xif.slots?.length) features.push('🔌 slots');
- if (xif.paths.some(p => p.animate)) features.push('✨ animated');
- if (xif.paths.some(p => p.personality))
+ if (xif.slots?.length) {
+ features.push('🔌 slots');
+ }
+ if (xif.paths.some(p => p.animate)) {
+ features.push('✨ animated');
+ }
+ if (xif.paths.some(p => p.personality)) {
features.push('🎨 personality');
- if (xif.overrides) features.push('🔀 overrides');
- if (xif.paths.some(p => p.layer === 'secondary'))
+ }
+ if (xif.overrides) {
+ features.push('🔀 overrides');
+ }
+ if (xif.paths.some(p => p.layer === 'secondary')) {
features.push('📐 two-layer');
+ }
return (
<Fragment key={xif.name}>
diff --git a/apps/storybook/stories/datasets.ts b/apps/storybook/stories/datasets.ts
index a3a413e671..1acae0a841 100644
--- a/apps/storybook/stories/datasets.ts
+++ b/apps/storybook/stories/datasets.ts
@@ -11,7 +11,9 @@ const cache = new Map<string, unknown[]>();
/** Minimal CSV parser — handles quoted fields and numeric detection */
function parseCSV(text: string): Record<string, unknown>[] {
const lines = text.trim().split('\n');
- if (lines.length < 2) return [];
+ if (lines.length < 2) {
+ return [];
+ }
const headers = lines[0].split(',').map(h => h.trim().replace(/^"|"$/g, ''));
return lines.slice(1).map(line => {
const values = line.split(',').map(v => v.trim().replace(/^"|"$/g, ''));
@@ -28,7 +30,9 @@ function parseCSV(text: string): Record<string, unknown>[] {
export async function loadDataset<T = Record<string, unknown>>(
name: string,
): Promise<T[]> {
- if (cache.has(name)) return cache.get(name) as T[];
+ if (cache.has(name)) {
+ return cache.get(name) as T[];
+ }
const isCSV = name.endsWith('.csv');
const hasExt = name.endsWith('.json') || isCSV;
diff --git a/apps/storybook/stories/useXDSChartRange.stories.tsx b/apps/storybook/stories/useXDSChartRange.stories.tsx
index dcd286d257..7825b34c65 100644
--- a/apps/storybook/stories/useXDSChartRange.stories.tsx
+++ b/apps/storybook/stories/useXDSChartRange.stories.tsx
@@ -138,7 +138,9 @@ export const ZeroCentered: StoryObj = {
let raf: number;
const tick = () => {
tRef.current += 1;
- if (Math.random() < 0.003) quakeRef.current = 30 + Math.random() * 50;
+ if (Math.random() < 0.003) {
+ quakeRef.current = 30 + Math.random() * 50;
+ }
quakeRef.current *= 0.97;
const tremor = (Math.random() - 0.5) * 2;
const quake =
diff --git a/apps/storybook/stories/useXDSStreamingText.stories.tsx b/apps/storybook/stories/useXDSStreamingText.stories.tsx
index 4a0dc68bf6..e0a877861c 100644
--- a/apps/storybook/stories/useXDSStreamingText.stories.tsx
+++ b/apps/storybook/stories/useXDSStreamingText.stories.tsx
@@ -28,7 +28,9 @@ function StreamingDemo({
const displayed = useXDSStreamingText(target, isStreaming, {speed});
const start = useCallback(() => {
- if (timerRef.current) clearInterval(timerRef.current);
+ if (timerRef.current) {
+ clearInterval(timerRef.current);
+ }
indexRef.current = 0;
setTarget('');
setIsStreaming(true);
@@ -38,7 +40,9 @@ function StreamingDemo({
setTarget(text.slice(0, indexRef.current));
if (indexRef.current >= text.length) {
- if (timerRef.current) clearInterval(timerRef.current);
+ if (timerRef.current) {
+ clearInterval(timerRef.current);
+ }
timerRef.current = null;
setTimeout(() => setIsStreaming(false), 200);
}
@@ -47,7 +51,9 @@ function StreamingDemo({
useEffect(() => {
return () => {
- if (timerRef.current) clearInterval(timerRef.current);
+ if (timerRef.current) {
+ clearInterval(timerRef.current);
+ }
};
}, []);
@@ -83,7 +89,8 @@ function StreamingDemo({
);
}
-const SAMPLE_TEXT = 'Here is how you fetch a user in TypeScript:\n\nconst response = await fetch("/api/users/" + id);\nconst user = await response.json();\n\nKey points:\n- Always check response.ok before parsing\n- Use AbortController for cancellation\n- Consider a useUser hook for React apps\n\nThis approach gives you type-safe API calls with proper error handling.';
+const SAMPLE_TEXT =
+ 'Here is how you fetch a user in TypeScript:\n\nconst response = await fetch("/api/users/" + id);\nconst user = await response.json();\n\nKey points:\n- Always check response.ok before parsing\n- Use AbortController for cancellation\n- Consider a useUser hook for React apps\n\nThis approach gives you type-safe API calls with proper error handling.';
const meta: Meta<typeof StreamingDemo> = {
title: 'Core/Hooks/useXDSStreamingText',
@@ -101,7 +108,12 @@ export default meta;
type Story = StoryObj<typeof StreamingDemo>;
export const Natural: Story = {
- args: {text: SAMPLE_TEXT, speed: 'natural', chunkSize: 20, chunkIntervalMs: 50},
+ args: {
+ text: SAMPLE_TEXT,
+ speed: 'natural',
+ chunkSize: 20,
+ chunkIntervalMs: 50,
+ },
};
export const Fast: Story = {
@@ -109,15 +121,30 @@ export const Fast: Story = {
};
export const Instant: Story = {
- args: {text: SAMPLE_TEXT, speed: 'instant', chunkSize: 20, chunkIntervalMs: 50},
+ args: {
+ text: SAMPLE_TEXT,
+ speed: 'instant',
+ chunkSize: 20,
+ chunkIntervalMs: 50,
+ },
};
export const BurstyChunks: Story = {
name: 'Bursty chunks (large backlog)',
- args: {text: SAMPLE_TEXT, speed: 'natural', chunkSize: 80, chunkIntervalMs: 200},
+ args: {
+ text: SAMPLE_TEXT,
+ speed: 'natural',
+ chunkSize: 80,
+ chunkIntervalMs: 200,
+ },
};
export const SlowTrickle: Story = {
name: 'Slow trickle',
- args: {text: SAMPLE_TEXT, speed: 'natural', chunkSize: 1, chunkIntervalMs: 100},
+ args: {
+ text: SAMPLE_TEXT,
+ speed: 'natural',
+ chunkSize: 1,
+ chunkIntervalMs: 100,
+ },
};
diff --git a/eslint.config.js b/eslint.config.js
index 58437c2037..ca7fe28984 100644
--- a/eslint.config.js
+++ b/eslint.config.js
@@ -63,6 +63,7 @@ export default tseslint.config(
caughtErrorsIgnorePattern: "^_",
}],
"no-console": ["warn", { allow: ["warn", "error"] }],
+ "curly": "warn",
"@typescript-eslint/no-non-null-assertion": "warn",
"@typescript-eslint/consistent-type-assertions": ["warn", {
assertionStyle: "as",
diff --git a/internal/vibe-tests/app/src/report/CompareView.tsx b/internal/vibe-tests/app/src/report/CompareView.tsx
index fb59df2428..676a949f44 100644
--- a/internal/vibe-tests/app/src/report/CompareView.tsx
+++ b/internal/vibe-tests/app/src/report/CompareView.tsx
@@ -68,14 +68,20 @@ function costWinner(
['xds', xdsVal],
['baseline', baseVal],
];
- if (htmlVal != null) entries.push(['html', htmlVal]);
- if (twVal != null) entries.push(['xds-tailwind', twVal]);
+ if (htmlVal != null) {
+ entries.push(['html', htmlVal]);
+ }
+ if (twVal != null) {
+ entries.push(['xds-tailwind', twVal]);
+ }
const best = lowerIsBetter
? Math.min(...entries.map(([, v]) => v))
: Math.max(...entries.map(([, v]) => v));
const atBest = entries.filter(([, v]) => v === best);
- if (atBest.length > 1) return 'tie';
+ if (atBest.length > 1) {
+ return 'tie';
+ }
return atBest[0][0];
}
@@ -112,8 +118,12 @@ function winnerLabel(w: string): string {
}
function deltaClassName(delta: number): string {
- if (delta > 0) return 'report-color-positive';
- if (delta < 0) return 'report-color-negative';
+ if (delta > 0) {
+ return 'report-color-positive';
+ }
+ if (delta < 0) {
+ return 'report-color-negative';
+ }
return 'report-color-neutral';
}
@@ -252,9 +262,7 @@ function CostComparisonSection({
xds: String(xdsCost.avgDocsRead),
baseline: String(baselineCost.avgDocsRead),
...(isThreeWay ? {html: String(htmlCost!.avgDocsRead)} : {}),
- ...(isFourWay
- ? {xdsTailwind: String(xdsTailwindCost!.avgDocsRead)}
- : {}),
+ ...(isFourWay ? {xdsTailwind: String(xdsTailwindCost!.avgDocsRead)} : {}),
winner: 'tie', // not inherently better or worse
},
];
@@ -328,11 +336,17 @@ export function CompareView({comparison}: CompareViewProps) {
let ties = 0;
for (const dim of ALL_DIMENSIONS) {
const w = winners[dim];
- if (w === 'xds') xdsWins++;
- else if (w === 'baseline') baselineWins++;
- else if (w === 'html') htmlWins++;
- else if (w === 'xds-tailwind') xdsTailwindWins++;
- else ties++;
+ if (w === 'xds') {
+ xdsWins++;
+ } else if (w === 'baseline') {
+ baselineWins++;
+ } else if (w === 'html') {
+ htmlWins++;
+ } else if (w === 'xds-tailwind') {
+ xdsTailwindWins++;
+ } else {
+ ties++;
+ }
}
const dimData: DimRow[] = ALL_DIMENSIONS.filter(
@@ -519,8 +533,7 @@ export function CompareView({comparison}: CompareViewProps) {
];
// Determine grid class based on number of win cards
- const winCardCount =
- 2 + (isThreeWay ? 1 : 0) + (isFourWay ? 1 : 0) + 1; // targets + ties
+ const winCardCount = 2 + (isThreeWay ? 1 : 0) + (isFourWay ? 1 : 0) + 1; // targets + ties
const summaryGridClass =
winCardCount >= 5
? 'report-compare-summaryGrid5'
diff --git a/internal/vibe-tests/app/src/report/Report.tsx b/internal/vibe-tests/app/src/report/Report.tsx
index 2e04926a3d..d7ce032645 100644
--- a/internal/vibe-tests/app/src/report/Report.tsx
+++ b/internal/vibe-tests/app/src/report/Report.tsx
@@ -38,10 +38,14 @@ function EfficiencyMetricsCard({
byPrompt: ReportData['universal']['byPrompt'];
}) {
const entries = Object.values(byPrompt);
- if (entries.length === 0) return null;
+ if (entries.length === 0) {
+ return null;
+ }
const metrics = entries.map(s => s.efficiency.metrics).filter(Boolean);
- if (metrics.length === 0) return null;
+ if (metrics.length === 0) {
+ return null;
+ }
const avgDecisions =
metrics.reduce((s, m) => s + (m?.decisionsPerElement ?? 0), 0) /
@@ -89,10 +93,14 @@ function MaintainabilityMetricsCard({
byPrompt: ReportData['universal']['byPrompt'];
}) {
const entries = Object.values(byPrompt);
- if (entries.length === 0) return null;
+ if (entries.length === 0) {
+ return null;
+ }
const metrics = entries.map(s => s.maintainability.metrics).filter(Boolean);
- if (metrics.length === 0) return null;
+ if (metrics.length === 0) {
+ return null;
+ }
const avgSemantic =
metrics.reduce((s, m) => s + (m?.semanticRatio ?? 0), 0) / metrics.length;
@@ -122,7 +130,9 @@ function MaintainabilityMetricsCard({
}
function CostMetricsCard({cost}: {cost: ReportData['universal']['cost']}) {
- if (!cost) return null;
+ if (!cost) {
+ return null;
+ }
return (
<XDSCard>
diff --git a/internal/vibe-tests/app/src/report/ScoreCard.tsx b/internal/vibe-tests/app/src/report/ScoreCard.tsx
index e1fcee956c..6970f3e678 100644
--- a/internal/vibe-tests/app/src/report/ScoreCard.tsx
+++ b/internal/vibe-tests/app/src/report/ScoreCard.tsx
@@ -17,8 +17,12 @@ interface ScoreCardProps {
}
function deltaClassName(delta: number): string {
- if (delta > 0) return 'report-color-positive';
- if (delta < 0) return 'report-color-negative';
+ if (delta > 0) {
+ return 'report-color-positive';
+ }
+ if (delta < 0) {
+ return 'report-color-negative';
+ }
return 'report-color-neutral';
}
diff --git a/internal/vibe-tests/app/src/report/utils.ts b/internal/vibe-tests/app/src/report/utils.ts
index 57a7b972af..b03c1e304d 100644
--- a/internal/vibe-tests/app/src/report/utils.ts
+++ b/internal/vibe-tests/app/src/report/utils.ts
@@ -29,25 +29,39 @@ export const DIMENSION_LABELS: Record<UniversalDimension, string> = {
export function scoreToStatusVariant(
score: number,
): 'success' | 'neutral' | 'warning' | 'error' {
- if (score >= 90) return 'success';
- if (score >= 70) return 'neutral';
- if (score >= 50) return 'warning';
+ if (score >= 90) {
+ return 'success';
+ }
+ if (score >= 70) {
+ return 'neutral';
+ }
+ if (score >= 50) {
+ return 'warning';
+ }
return 'error';
}
export function scoreToProgressVariant(
score: number,
): 'success' | 'accent' | 'warning' | 'error' {
- if (score >= 90) return 'success';
- if (score >= 70) return 'accent';
- if (score >= 50) return 'warning';
+ if (score >= 90) {
+ return 'success';
+ }
+ if (score >= 70) {
+ return 'accent';
+ }
+ if (score >= 50) {
+ return 'warning';
+ }
return 'error';
}
/** Compute overall score. Null-safe for optional design dimension. */
export function computeOverall(score: UniversalScore): number {
const available = ALL_DIMENSIONS.filter(d => score[d] != null);
- if (available.length === 0) return 0;
+ if (available.length === 0) {
+ return 0;
+ }
const total = available.reduce((sum, d) => sum + (score[d]?.score ?? 0), 0);
return Math.round(total / available.length);
}
diff --git a/internal/vibe-tests/src/build-previews.ts b/internal/vibe-tests/src/build-previews.ts
index be5788b61f..e717e57293 100644
--- a/internal/vibe-tests/src/build-previews.ts
+++ b/internal/vibe-tests/src/build-previews.ts
@@ -57,7 +57,9 @@ function fixMissingXDSImports(filePath: string): string[] {
while ((match = jsxPattern.exec(code)) !== null) {
usedComponents.add(match[1]);
}
- if (usedComponents.size === 0) return [];
+ if (usedComponents.size === 0) {
+ return [];
+ }
const importedComponents = new Set<string>();
const importPattern =
/import\s*\{([^}]+)\}\s*from\s*['"]@xds\/core[^'"]*['"]/g;
@@ -67,11 +69,15 @@ function fixMissingXDSImports(filePath: string): string[] {
.trim()
.split(/\s+as\s+/)[0]
.trim();
- if (name.startsWith('XDS')) importedComponents.add(name);
+ if (name.startsWith('XDS')) {
+ importedComponents.add(name);
+ }
}
}
const missing = [...usedComponents].filter(c => !importedComponents.has(c));
- if (missing.length === 0) return [];
+ if (missing.length === 0) {
+ return [];
+ }
const importLine = `import {${missing.sort().join(', ')}} from '@xds/core';\n`;
fs.writeFileSync(filePath, importLine + code);
return missing.sort();
@@ -500,7 +506,9 @@ function buildPreview(
console.error(` ✗ Failed to build ${promptId}/${target}: ${msg}`);
return false;
} finally {
- if (fs.existsSync(tmpDir)) fs.rmSync(tmpDir, {recursive: true});
+ if (fs.existsSync(tmpDir)) {
+ fs.rmSync(tmpDir, {recursive: true});
+ }
}
}
@@ -615,7 +623,9 @@ function runTscCheck(filePath: string, target: string): TscResult {
};
} finally {
// Clean up temp config
- if (fs.existsSync(tmpConfig)) fs.unlinkSync(tmpConfig);
+ if (fs.existsSync(tmpConfig)) {
+ fs.unlinkSync(tmpConfig);
+ }
}
}
@@ -637,7 +647,9 @@ function runTscChecks(
for (const file of files) {
const promptId = path.basename(file, '.tsx');
- if (promptFilter && !promptFilter.includes(promptId)) continue;
+ if (promptFilter && !promptFilter.includes(promptId)) {
+ continue;
+ }
const filePath = path.resolve(codeDir, file);
const result = runTscCheck(filePath, target);
@@ -692,7 +704,9 @@ async function main() {
const target = iterManifest.config?.target ?? 'xds';
const codeDir = path.join(iterDir, 'results');
- if (!fs.existsSync(codeDir)) continue;
+ if (!fs.existsSync(codeDir)) {
+ continue;
+ }
// Extract .tsx from JSON results if no .tsx files exist yet
ensureTsxFiles(codeDir);
@@ -710,7 +724,9 @@ async function main() {
for (const file of files) {
const promptId = path.basename(file, '.tsx');
- if (prompts && !prompts.includes(promptId)) continue;
+ if (prompts && !prompts.includes(promptId)) {
+ continue;
+ }
const componentPath = path.resolve(codeDir, file);
const previewFile = `${promptId}/${target}.html`;
@@ -743,7 +759,9 @@ async function main() {
}
}
- if (!manifest[promptId]) manifest[promptId] = {};
+ if (!manifest[promptId]) {
+ manifest[promptId] = {};
+ }
manifest[promptId][target] = `previews/${previewFile}`;
console.log(` ✓ ${previewFile}`);
}
@@ -756,9 +774,13 @@ async function main() {
if (fs.existsSync(manifestOutPath)) {
const existing = readJson<PreviewManifest>(manifestOutPath);
for (const [promptId, targets] of Object.entries(existing)) {
- if (!manifest[promptId]) manifest[promptId] = {};
+ if (!manifest[promptId]) {
+ manifest[promptId] = {};
+ }
for (const [target, url] of Object.entries(targets)) {
- if (!manifest[promptId][target]) manifest[promptId][target] = url;
+ if (!manifest[promptId][target]) {
+ manifest[promptId][target] = url;
+ }
}
}
}
diff --git a/internal/vibe-tests/src/build-report.ts b/internal/vibe-tests/src/build-report.ts
index b3070e635d..a35df92a7d 100644
--- a/internal/vibe-tests/src/build-report.ts
+++ b/internal/vibe-tests/src/build-report.ts
@@ -42,9 +42,12 @@ function ensureCssDist(): void {
);
const missing: string[] = [];
- if (!fs.existsSync(xdsCss)) missing.push('@xds/core/dist/xds.css');
- if (!fs.existsSync(themeCss))
+ if (!fs.existsSync(xdsCss)) {
+ missing.push('@xds/core/dist/xds.css');
+ }
+ if (!fs.existsSync(themeCss)) {
missing.push('@xds/theme-default/dist/theme.css');
+ }
if (missing.length > 0) {
console.log('📦 Building CSS dist files (required for report)...');
@@ -139,8 +142,12 @@ function ensureComparison(
): UniversalComparison {
const resultsDir = getResultsDir();
const idParts = [xdsId, baselineId];
- if (htmlId) idParts.push(htmlId);
- if (xdsTailwindId) idParts.push(xdsTailwindId);
+ if (htmlId) {
+ idParts.push(htmlId);
+ }
+ if (xdsTailwindId) {
+ idParts.push(xdsTailwindId);
+ }
const comparisonFilename = `comparison-${idParts.join('-')}.json`;
const comparisonPath = path.join(resultsDir, comparisonFilename);
@@ -235,10 +242,14 @@ function injectDataIntoHtml(htmlPath: string, dataScript: string): void {
*/
function inlineCss(htmlPath: string, distDir: string): void {
const assetsDir = path.join(distDir, 'assets');
- if (!fs.existsSync(assetsDir)) return;
+ if (!fs.existsSync(assetsDir)) {
+ return;
+ }
const cssFiles = fs.readdirSync(assetsDir).filter(f => f.endsWith('.css'));
- if (cssFiles.length === 0) return;
+ if (cssFiles.length === 0) {
+ return;
+ }
console.log(` Inlining ${cssFiles.length} CSS file(s)...`);
let html = fs.readFileSync(htmlPath, 'utf-8');
@@ -382,7 +393,9 @@ async function main() {
const manifest = JSON.parse(
fs.readFileSync(screenshotManifestPath, 'utf-8'),
);
- if (!screenshots) screenshots = {};
+ if (!screenshots) {
+ screenshots = {};
+ }
// Flatten the nested manifest into filename → relative URL
for (const [_promptId, targets] of Object.entries(manifest)) {
for (const [_target, viewports] of Object.entries(
diff --git a/internal/vibe-tests/src/correct-previews.ts b/internal/vibe-tests/src/correct-previews.ts
index 6f5720865c..23444ba0e1 100644
--- a/internal/vibe-tests/src/correct-previews.ts
+++ b/internal/vibe-tests/src/correct-previews.ts
@@ -62,7 +62,9 @@ interface CorrectionTask {
* Gives the LLM the actual API surface to fix against.
*/
function getComponentDocs(code: string, target: string): string {
- if (target !== 'xds') return '';
+ if (target !== 'xds') {
+ return '';
+ }
// Extract XDS component names used in the file
const components = new Set<string>();
diff --git a/internal/vibe-tests/src/deploy-report.ts b/internal/vibe-tests/src/deploy-report.ts
index fafe14e45d..10f3df66c3 100644
--- a/internal/vibe-tests/src/deploy-report.ts
+++ b/internal/vibe-tests/src/deploy-report.ts
@@ -81,9 +81,13 @@ async function main() {
console.log(`\n📦 Deploy Report Pipeline`);
console.log(` Iteration: ${iteration}`);
- if (baseline) console.log(` Baseline: ${baseline}`);
+ if (baseline) {
+ console.log(` Baseline: ${baseline}`);
+ }
console.log(` Deploy to: ${deployPath}`);
- if (dryRun) console.log(` ⚠️ DRY RUN — will build but not push`);
+ if (dryRun) {
+ console.log(` ⚠️ DRY RUN — will build but not push`);
+ }
console.log('');
// Step 1: Build previews if result files exist (.tsx or .json)
@@ -123,9 +127,15 @@ async function main() {
// Step 2: Build the report
console.log('🏗️ Step 2: Building report...');
const buildArgs = [`--iteration ${iteration}`];
- if (baseline) buildArgs.push(`--baseline ${baseline}`);
- if (html) buildArgs.push(`--html ${html}`);
- if (xdsTailwind) buildArgs.push(`--xds-tailwind ${xdsTailwind}`);
+ if (baseline) {
+ buildArgs.push(`--baseline ${baseline}`);
+ }
+ if (html) {
+ buildArgs.push(`--html ${html}`);
+ }
+ if (xdsTailwind) {
+ buildArgs.push(`--xds-tailwind ${xdsTailwind}`);
+ }
run(`npx tsx src/build-report.ts ${buildArgs.join(' ')}`, {cwd: VIBE_DIR});
@@ -284,7 +294,9 @@ function injectScreenshotsIntoReport(
}
}
- if (Object.keys(screenshots).length === 0) return;
+ if (Object.keys(screenshots).length === 0) {
+ return;
+ }
let html = fs.readFileSync(htmlPath, 'utf-8');
@@ -327,7 +339,9 @@ function copyDirRecursive(src: string, dest: string): void {
function countFiles(dir: string, ext: string): number {
let count = 0;
- if (!fs.existsSync(dir)) return 0;
+ if (!fs.existsSync(dir)) {
+ return 0;
+ }
for (const entry of fs.readdirSync(dir, {withFileTypes: true})) {
if (entry.isDirectory()) {
count += countFiles(path.join(dir, entry.name), ext);
@@ -340,7 +354,9 @@ function countFiles(dir: string, ext: string): number {
function updateReportsIndex(ghPagesDir: string): void {
const reportsDir = path.join(ghPagesDir, 'reports');
- if (!fs.existsSync(reportsDir)) return;
+ if (!fs.existsSync(reportsDir)) {
+ return;
+ }
const entries = fs
.readdirSync(reportsDir, {withFileTypes: true})
diff --git a/internal/vibe-tests/src/design-judge.ts b/internal/vibe-tests/src/design-judge.ts
index f5689332b9..d925068290 100644
--- a/internal/vibe-tests/src/design-judge.ts
+++ b/internal/vibe-tests/src/design-judge.ts
@@ -313,15 +313,21 @@ function findIdeal(
idealsDir,
`${promptId}__${viewport}__${theme}.png`,
);
- if (fs.existsSync(specific)) return specific;
+ if (fs.existsSync(specific)) {
+ return specific;
+ }
// Viewport match: cwm-1__desktop.png
const viewportMatch = path.join(idealsDir, `${promptId}__${viewport}.png`);
- if (fs.existsSync(viewportMatch)) return viewportMatch;
+ if (fs.existsSync(viewportMatch)) {
+ return viewportMatch;
+ }
// Generic fallback: cwm-1.png
const generic = path.join(idealsDir, `${promptId}.png`);
- if (fs.existsSync(generic)) return generic;
+ if (fs.existsSync(generic)) {
+ return generic;
+ }
return null;
}
@@ -331,7 +337,9 @@ function findIdeal(
*/
export function listAvailableIdeals(): string[] {
const idealsDir = getIdealsDir();
- if (!fs.existsSync(idealsDir)) return [];
+ if (!fs.existsSync(idealsDir)) {
+ return [];
+ }
const files = fs.readdirSync(idealsDir).filter(f => f.endsWith('.png'));
const promptIds = new Set<string>();
@@ -368,7 +376,9 @@ function loadPromptText(promptId: string): string {
testSetPath,
);
const match = testSet.prompts.find(p => p.id === promptId);
- if (match) return match.prompt;
+ if (match) {
+ return match.prompt;
+ }
}
return `UI component identified as ${promptId}`;
@@ -465,8 +475,12 @@ async function main() {
// Filter to prompts that have both screenshots and ideals
const promptsToEvaluate = Object.keys(manifest).filter(promptId => {
- if (prompts && !prompts.includes(promptId)) return false;
- if (!availableIdeals.includes(promptId)) return false;
+ if (prompts && !prompts.includes(promptId)) {
+ return false;
+ }
+ if (!availableIdeals.includes(promptId)) {
+ return false;
+ }
return true;
});
diff --git a/internal/vibe-tests/src/fix-imports.ts b/internal/vibe-tests/src/fix-imports.ts
index 5a5eb7cece..37710af00d 100644
--- a/internal/vibe-tests/src/fix-imports.ts
+++ b/internal/vibe-tests/src/fix-imports.ts
@@ -27,7 +27,9 @@ function fixMissingXDSImports(filePath: string, dryRun: boolean): string[] {
while ((match = jsxPattern.exec(code)) !== null) {
usedComponents.add(match[1]);
}
- if (usedComponents.size === 0) return [];
+ if (usedComponents.size === 0) {
+ return [];
+ }
// Find already-imported XDS components
const importedComponents = new Set<string>();
@@ -39,12 +41,16 @@ function fixMissingXDSImports(filePath: string, dryRun: boolean): string[] {
.trim()
.split(/\s+as\s+/)[0]
.trim();
- if (name.startsWith('XDS')) importedComponents.add(name);
+ if (name.startsWith('XDS')) {
+ importedComponents.add(name);
+ }
}
}
const missing = [...usedComponents].filter(c => !importedComponents.has(c));
- if (missing.length === 0) return [];
+ if (missing.length === 0) {
+ return [];
+ }
if (!dryRun) {
const importLine = `import {${missing.sort().join(', ')}} from '@xds/core';\n`;
@@ -106,7 +112,9 @@ function main() {
}
const codeDir = path.join(iterDir, 'results');
- if (!fs.existsSync(codeDir)) continue;
+ if (!fs.existsSync(codeDir)) {
+ continue;
+ }
const files = fs.readdirSync(codeDir).filter(f => f.endsWith('.tsx'));
diff --git a/internal/vibe-tests/src/generate-a11y-manifest.ts b/internal/vibe-tests/src/generate-a11y-manifest.ts
index 1b2c779ed1..efad41e9bc 100644
--- a/internal/vibe-tests/src/generate-a11y-manifest.ts
+++ b/internal/vibe-tests/src/generate-a11y-manifest.ts
@@ -177,11 +177,15 @@ function generateXDSManifest(): A11yManifest {
// Find all component directories with README.md
const findReadmes = (dir: string): string[] => {
const readmes: string[] = [];
- if (!fs.existsSync(dir)) return readmes;
+ if (!fs.existsSync(dir)) {
+ return readmes;
+ }
const entries = fs.readdirSync(dir, {withFileTypes: true});
for (const entry of entries) {
- if (entry.name === 'node_modules') continue;
+ if (entry.name === 'node_modules') {
+ continue;
+ }
const fullPath = path.join(dir, entry.name);
if (entry.isDirectory()) {
const readmePath = path.join(fullPath, 'README.md');
diff --git a/internal/vibe-tests/src/interactive.ts b/internal/vibe-tests/src/interactive.ts
index e47c531358..eafa5e9ee8 100644
--- a/internal/vibe-tests/src/interactive.ts
+++ b/internal/vibe-tests/src/interactive.ts
@@ -687,7 +687,9 @@ function installHtmlDocs(): void {
if (fs.existsSync(agentsMdPath)) {
const stats = fs.statSync(agentsMdPath);
const ageMs = Date.now() - stats.mtimeMs;
- if (ageMs < 60 * 60 * 1000) return;
+ if (ageMs < 60 * 60 * 1000) {
+ return;
+ }
}
const agentsMd = `# AGENTS.md
@@ -1138,11 +1140,15 @@ async function main() {
console.log(`\n🧪 Interactive Vibe Test Setup`);
console.log(`================================`);
console.log(`Iteration: ${iterationId}`);
- if (label) console.log(`Label: ${label}`);
+ if (label) {
+ console.log(`Label: ${label}`);
+ }
console.log(`Test set: ${testSetName}`);
console.log(`Target: ${target.toUpperCase()}`);
console.log(`Persona: ${persona}`);
- if (skillDocOverride) console.log(`Skill doc: ${skillDocOverride}`);
+ if (skillDocOverride) {
+ console.log(`Skill doc: ${skillDocOverride}`);
+ }
console.log(
`Mode: ${target === 'xds' ? 'AGENTS.md' : target === 'baseline' ? 'AGENTS.baseline.md' : 'AGENTS.html.md'} (retrieval-led)`,
);
diff --git a/internal/vibe-tests/src/sampling.ts b/internal/vibe-tests/src/sampling.ts
index 02e23067a0..91a3221185 100644
--- a/internal/vibe-tests/src/sampling.ts
+++ b/internal/vibe-tests/src/sampling.ts
@@ -36,7 +36,9 @@ export function stratifiedSample(
// First pass: one from each category
for (const category of categories) {
- if (result.length >= sampleSize) break;
+ if (result.length >= sampleSize) {
+ break;
+ }
const categoryPrompts = byCategory.get(category)!;
const randomIndex = Math.floor(Math.random() * categoryPrompts.length);
diff --git a/internal/vibe-tests/src/screenshot-previews.ts b/internal/vibe-tests/src/screenshot-previews.ts
index 2aac118b37..421206f9d0 100644
--- a/internal/vibe-tests/src/screenshot-previews.ts
+++ b/internal/vibe-tests/src/screenshot-previews.ts
@@ -143,21 +143,24 @@ async function main() {
const screenshotsDir = path.join(iterDir, 'screenshots');
if (!fs.existsSync(previewsDir)) {
- console.error(
- ` ⚠ No previews directory for ${iterationId}, skipping`,
- );
+ console.error(` ⚠ No previews directory for ${iterationId}, skipping`);
continue;
}
// Read the preview manifest to find all HTML files
const manifestPath = path.join(previewsDir, 'manifest.json');
- const previewFiles: Array<{promptId: string; target: string; path: string}> =
- [];
+ const previewFiles: Array<{
+ promptId: string;
+ target: string;
+ path: string;
+ }> = [];
if (fs.existsSync(manifestPath)) {
const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf-8'));
for (const [promptId, targets] of Object.entries(manifest)) {
- if (prompts && !prompts.includes(promptId)) continue;
+ if (prompts && !prompts.includes(promptId)) {
+ continue;
+ }
for (const [target, relPath] of Object.entries(
targets as Record<string, string>,
)) {
@@ -170,12 +173,16 @@ async function main() {
} else {
// No manifest — scan for HTML files directly
const scanDir = (dir: string) => {
- if (!fs.existsSync(dir)) return;
+ if (!fs.existsSync(dir)) {
+ return;
+ }
for (const entry of fs.readdirSync(dir, {withFileTypes: true})) {
if (entry.isDirectory()) {
scanDir(path.join(dir, entry.name));
} else if (entry.name.endsWith('.html')) {
- const promptId = path.basename(path.dirname(path.join(dir, entry.name)));
+ const promptId = path.basename(
+ path.dirname(path.join(dir, entry.name)),
+ );
const target = path.basename(entry.name, '.html');
previewFiles.push({
promptId,
@@ -208,10 +215,7 @@ async function main() {
for (const preview of previewFiles) {
// Compute the URL relative to the served directory
- const relPath = path.relative(
- path.dirname(previewsDir),
- preview.path,
- );
+ const relPath = path.relative(path.dirname(previewsDir), preview.path);
for (const [viewportName, viewport] of Object.entries(VIEWPORTS)) {
for (const theme of THEMES) {
@@ -265,10 +269,7 @@ async function main() {
}
// Write screenshot manifest
- writeJson(
- path.join(screenshotsDir, 'manifest.json'),
- screenshotManifest,
- );
+ writeJson(path.join(screenshotsDir, 'manifest.json'), screenshotManifest);
await server.close();
}
diff --git a/internal/vibe-tests/src/universal-aggregate.ts b/internal/vibe-tests/src/universal-aggregate.ts
index dfdafc1333..6c2618d040 100644
--- a/internal/vibe-tests/src/universal-aggregate.ts
+++ b/internal/vibe-tests/src/universal-aggregate.ts
@@ -169,7 +169,9 @@ async function main() {
if (taskMeta.createdAt && completedAt) {
const start = new Date(taskMeta.createdAt).getTime();
const end = new Date(completedAt).getTime();
- if (end > start) durationMs = Math.round(end - start);
+ if (end > start) {
+ durationMs = Math.round(end - start);
+ }
}
} catch {
// ignore
@@ -180,7 +182,9 @@ async function main() {
const taskStat = fs.statSync(taskPath);
const resultStat = fs.statSync(codePath);
const inferred = resultStat.mtimeMs - taskStat.mtimeMs;
- if (inferred > 0) durationMs = Math.round(inferred);
+ if (inferred > 0) {
+ durationMs = Math.round(inferred);
+ }
}
}
diff --git a/internal/vibe-tests/src/universal-compare.ts b/internal/vibe-tests/src/universal-compare.ts
index a689a8e2c9..4df76d8910 100644
--- a/internal/vibe-tests/src/universal-compare.ts
+++ b/internal/vibe-tests/src/universal-compare.ts
@@ -66,12 +66,18 @@ function winner(
['xds', xdsVal],
['baseline', baseVal],
];
- if (htmlVal != null) entries.push(['html', htmlVal]);
- if (xdsTailwindVal != null) entries.push(['xds-tailwind', xdsTailwindVal]);
+ if (htmlVal != null) {
+ entries.push(['html', htmlVal]);
+ }
+ if (xdsTailwindVal != null) {
+ entries.push(['xds-tailwind', xdsTailwindVal]);
+ }
const max = Math.max(...entries.map(([, v]) => v));
const atMax = entries.filter(([, v]) => v === max);
- if (atMax.length > 1) return 'tie';
+ if (atMax.length > 1) {
+ return 'tie';
+ }
return atMax[0][0];
}
@@ -144,10 +150,14 @@ function toMarkdown(opts: {
xdsTailwindId?: string;
byPrompt: UniversalComparison['byPrompt'];
}): string {
- const {comparison, xdsId, baselineId, htmlId, xdsTailwindId, byPrompt} =
- opts;
- const {xds, baseline, html: htmlData, xdsTailwind: twData, winners} =
- comparison;
+ const {comparison, xdsId, baselineId, htmlId, xdsTailwindId, byPrompt} = opts;
+ const {
+ xds,
+ baseline,
+ html: htmlData,
+ xdsTailwind: twData,
+ winners,
+ } = comparison;
const dimensions = getDimensionNames();
const lines: string[] = [];
@@ -199,15 +209,25 @@ function toMarkdown(opts: {
let twWins = 0;
let ties = 0;
for (const [, data] of promptEntries) {
- if (data.winner === 'xds') xWins++;
- else if (data.winner === 'baseline') bWins++;
- else if (data.winner === 'html') hWins++;
- else if (data.winner === 'xds-tailwind') twWins++;
- else ties++;
+ if (data.winner === 'xds') {
+ xWins++;
+ } else if (data.winner === 'baseline') {
+ bWins++;
+ } else if (data.winner === 'html') {
+ hWins++;
+ } else if (data.winner === 'xds-tailwind') {
+ twWins++;
+ } else {
+ ties++;
+ }
}
const parts = [`XDS ${xWins}`, `Baseline ${bWins}`];
- if (htmlData) parts.push(`HTML ${hWins}`);
- if (twData) parts.push(`XDS+TW ${twWins}`);
+ if (htmlData) {
+ parts.push(`HTML ${hWins}`);
+ }
+ if (twData) {
+ parts.push(`XDS+TW ${twWins}`);
+ }
parts.push(`Tie ${ties}`);
lines.push(
`**Per-prompt wins:** ${parts.join(' · ')} (${promptEntries.length} prompts)`,
@@ -220,8 +240,12 @@ function toMarkdown(opts: {
`XDS ${xds.darkModeRate}%`,
`Baseline ${baseline.darkModeRate}%`,
];
- if (htmlData) dmParts.push(`HTML ${htmlData.darkModeRate}%`);
- if (twData) dmParts.push(`XDS+TW ${twData.darkModeRate}%`);
+ if (htmlData) {
+ dmParts.push(`HTML ${htmlData.darkModeRate}%`);
+ }
+ if (twData) {
+ dmParts.push(`XDS+TW ${twData.darkModeRate}%`);
+ }
lines.push(`**Dark mode:** ${dmParts.join(' · ')}`);
// Dimension winners
@@ -315,8 +339,12 @@ async function main() {
// Save — include all IDs in filename for uniqueness
const idParts = [xdsId, baselineId];
- if (htmlId) idParts.push(htmlId);
- if (xdsTailwindId) idParts.push(xdsTailwindId);
+ if (htmlId) {
+ idParts.push(htmlId);
+ }
+ if (xdsTailwindId) {
+ idParts.push(xdsTailwindId);
+ }
const outputFilename = `comparison-${idParts.join('-')}.json`;
const outputPath = path.join(getResultsDir(), outputFilename);
writeJson(outputPath, comparison);
@@ -342,8 +370,12 @@ async function main() {
// --- Print report ---
const targetNames = ['XDS', 'Baseline'];
- if (isThreeWay) targetNames.push('HTML');
- if (isFourWay) targetNames.push('XDS+TW');
+ if (isThreeWay) {
+ targetNames.push('HTML');
+ }
+ if (isFourWay) {
+ targetNames.push('XDS+TW');
+ }
const title = `📊 Universal Comparison: ${targetNames.join(' vs ')}`;
console.log(`\n${title}`);
@@ -355,8 +387,12 @@ async function main() {
{label: 'XDS', data: xds},
{label: 'Baseline', data: baseline},
];
- if (isThreeWay) targets.push({label: 'HTML', data: htmlData!});
- if (isFourWay) targets.push({label: 'XDS+TW', data: twData!});
+ if (isThreeWay) {
+ targets.push({label: 'HTML', data: htmlData!});
+ }
+ if (isFourWay) {
+ targets.push({label: 'XDS+TW', data: twData!});
+ }
// Use markdown-style table for CLI (simpler than box-drawing for N targets)
const header = ['Dimension', ...targets.map(t => t.label), 'Winner'];
@@ -390,9 +426,7 @@ async function main() {
const sep = colWidths.map(w => '─'.repeat(w + 2)).join('┼');
console.log('┌' + sep.replaceAll('┼', '┬') + '┐');
console.log(
- '│' +
- header.map((h, i) => ` ${h.padEnd(colWidths[i])} `).join('│') +
- '│',
+ '│' + header.map((h, i) => ` ${h.padEnd(colWidths[i])} `).join('│') + '│',
);
console.log('├' + sep + '┤');
for (let ri = 0; ri < rows.length; ri++) {
@@ -418,35 +452,48 @@ async function main() {
}));
if (targetEffMetrics.every(t => t.metrics.length > 0)) {
const avgDpe = targetEffMetrics.map(
- t => t.metrics.reduce((s, m) => s + m.decisionsPerElement, 0) / t.metrics.length,
+ t =>
+ t.metrics.reduce((s, m) => s + m.decisionsPerElement, 0) /
+ t.metrics.length,
);
const avgLines = targetEffMetrics.map(
t => t.metrics.reduce((s, m) => s + m.codeLines, 0) / t.metrics.length,
);
console.log(`\n⚡ Efficiency Metrics:`);
// For decisions/element, lower is better (reverse args for winner)
- const dpeParts = targetEffMetrics.map((t, i) => `${t.label} ${avgDpe[i].toFixed(1)}`);
+ const dpeParts = targetEffMetrics.map(
+ (t, i) => `${t.label} ${avgDpe[i].toFixed(1)}`,
+ );
console.log(` Decisions/element: ${dpeParts.join(' | ')}`);
- const linesParts = targetEffMetrics.map((t, i) => `${t.label} ${Math.round(avgLines[i])}`);
+ const linesParts = targetEffMetrics.map(
+ (t, i) => `${t.label} ${Math.round(avgLines[i])}`,
+ );
console.log(` Avg code lines: ${linesParts.join(' | ')}`);
}
// Maintainability metrics comparison
const targetMaintMetrics = targets.map(t => ({
label: t.label,
- metrics: Object.values(t.data.byPrompt).map(s => s.maintainability.metrics!),
+ metrics: Object.values(t.data.byPrompt).map(
+ s => s.maintainability.metrics!,
+ ),
}));
if (targetMaintMetrics.every(t => t.metrics.length > 0)) {
const avgSem = targetMaintMetrics.map(
- t => t.metrics.reduce((s, m) => s + m.semanticRatio, 0) / t.metrics.length,
+ t =>
+ t.metrics.reduce((s, m) => s + m.semanticRatio, 0) / t.metrics.length,
);
- const totalMagic = targetMaintMetrics.map(
- t => t.metrics.reduce((s, m) => s + m.magicValueCount, 0),
+ const totalMagic = targetMaintMetrics.map(t =>
+ t.metrics.reduce((s, m) => s + m.magicValueCount, 0),
);
console.log(`\n🔧 Maintainability Metrics:`);
- const semParts = targetMaintMetrics.map((t, i) => `${t.label} ${(avgSem[i] * 100).toFixed(0)}%`);
+ const semParts = targetMaintMetrics.map(
+ (t, i) => `${t.label} ${(avgSem[i] * 100).toFixed(0)}%`,
+ );
console.log(` Semantic ratio: ${semParts.join(' | ')}`);
- const magicParts = targetMaintMetrics.map((t, i) => `${t.label} ${totalMagic[i]}`);
+ const magicParts = targetMaintMetrics.map(
+ (t, i) => `${t.label} ${totalMagic[i]}`,
+ );
console.log(` Magic values: ${magicParts.join(' | ')}`);
}
@@ -456,15 +503,22 @@ async function main() {
const costTargets = targets.filter(t => t.data.cost);
const hasDuration = costTargets.some(t => t.data.cost!.avgDurationMs > 0);
if (hasDuration) {
- const durParts = costTargets.map(t => `${t.label} ${(t.data.cost!.avgDurationMs / 1000).toFixed(1)}s`);
+ const durParts = costTargets.map(
+ t => `${t.label} ${(t.data.cost!.avgDurationMs / 1000).toFixed(1)}s`,
+ );
console.log(` Avg duration: ${durParts.join(' | ')}`);
}
- const linesParts = costTargets.map(t => `${t.label} ${t.data.cost!.avgOutputLines}`);
+ const linesParts = costTargets.map(
+ t => `${t.label} ${t.data.cost!.avgOutputLines}`,
+ );
console.log(` Avg output lines: ${linesParts.join(' | ')}`);
- const docsParts = costTargets.map(t => `${t.label} ${t.data.cost!.avgDocsRead}`);
+ const docsParts = costTargets.map(
+ t => `${t.label} ${t.data.cost!.avgDocsRead}`,
+ );
console.log(` Avg docs read: ${docsParts.join(' | ')}`);
const tokenParts = costTargets.map(t => {
- const total = t.data.cost!.estimatedInputTokens + t.data.cost!.estimatedOutputTokens;
+ const total =
+ t.data.cost!.estimatedInputTokens + t.data.cost!.estimatedOutputTokens;
return `${t.label} ~${total}`;
});
console.log(` Est. tokens: ${tokenParts.join(' | ')}`);
@@ -474,14 +528,22 @@ async function main() {
const promptEntries = Object.entries(byPrompt);
if (promptEntries.length > 0) {
const winCounts: Record<string, number> = {};
- for (const t of targets) winCounts[t.label] = 0;
+ for (const t of targets) {
+ winCounts[t.label] = 0;
+ }
winCounts['Tie'] = 0;
for (const [, data] of promptEntries) {
- if (data.winner === 'xds') winCounts['XDS']++;
- else if (data.winner === 'baseline') winCounts['Baseline']++;
- else if (data.winner === 'html') winCounts['HTML']++;
- else if (data.winner === 'xds-tailwind') winCounts['XDS+TW']++;
- else winCounts['Tie']++;
+ if (data.winner === 'xds') {
+ winCounts['XDS']++;
+ } else if (data.winner === 'baseline') {
+ winCounts['Baseline']++;
+ } else if (data.winner === 'html') {
+ winCounts['HTML']++;
+ } else if (data.winner === 'xds-tailwind') {
+ winCounts['XDS+TW']++;
+ } else {
+ winCounts['Tie']++;
+ }
}
const parts = targets.map(t => `${t.label} wins ${winCounts[t.label]}`);
parts.push(`Ties ${winCounts['Tie']}`);
diff --git a/internal/vibe-tests/src/universal-eval.ts b/internal/vibe-tests/src/universal-eval.ts
index 7b91d2c991..3e85916e55 100644
--- a/internal/vibe-tests/src/universal-eval.ts
+++ b/internal/vibe-tests/src/universal-eval.ts
@@ -130,8 +130,9 @@ function analyzePhantomProps(code: string): UniversalFinding[] {
trimmed.startsWith('//') ||
trimmed.startsWith('*') ||
trimmed.startsWith('import ')
- )
+ ) {
continue;
+ }
// onPress on any element/component — React Native, not DOM
if (/\bonPress\s*[={]/.test(line) && !/onPressedChange/.test(line)) {
@@ -313,9 +314,13 @@ function analyzeAccessibility(code: string): DimensionScore {
const headingLevels: number[] = [];
for (const line of lines) {
const h = line.match(/<h([1-6])\b/i);
- if (h) headingLevels.push(parseInt(h[1]));
+ if (h) {
+ headingLevels.push(parseInt(h[1]));
+ }
const xh = line.match(/level\s*=\s*\{?\s*(\d)\s*\}?/);
- if (xh && line.includes('Heading')) headingLevels.push(parseInt(xh[1]));
+ if (xh && line.includes('Heading')) {
+ headingLevels.push(parseInt(xh[1]));
+ }
}
for (let i = 1; i < headingLevels.length; i++) {
if (headingLevels[i] > headingLevels[i - 1] + 1) {
@@ -394,7 +399,9 @@ function analyzeCodeQuality(code: string): DimensionScore {
}
// Branches
- if (stripped.match(/^(if|else if|else|case|catch)\b/)) branchCount++;
+ if (stripped.match(/^(if|else if|else|case|catch)\b/)) {
+ branchCount++;
+ }
branchCount += (line.match(/\?[^?:]/g) || []).length; // ternaries
// TypeScript any
@@ -486,11 +493,21 @@ function analyzeCodeQuality(code: string): DimensionScore {
* Check if a normalized line is component/prop usage (not real duplication).
*/
function isComponentUsageLine(normalizedLine: string): boolean {
- if (/^<\/?[A-Z]\w*/.test(normalizedLine)) return true;
- if (/^<\/[A-Z]\w*>$/.test(normalizedLine)) return true;
- if (/^<[A-Z]\w*\s.*\/>$/.test(normalizedLine)) return true;
- if (/^\w+=/.test(normalizedLine) && normalizedLine.length < 40) return true;
- if (/^\w+:\s*\w+Vars\[/.test(normalizedLine)) return true;
+ if (/^<\/?[A-Z]\w*/.test(normalizedLine)) {
+ return true;
+ }
+ if (/^<\/[A-Z]\w*>$/.test(normalizedLine)) {
+ return true;
+ }
+ if (/^<[A-Z]\w*\s.*\/>$/.test(normalizedLine)) {
+ return true;
+ }
+ if (/^\w+=/.test(normalizedLine) && normalizedLine.length < 40) {
+ return true;
+ }
+ if (/^\w+:\s*\w+Vars\[/.test(normalizedLine)) {
+ return true;
+ }
return false;
}
@@ -517,10 +534,13 @@ function countElements(code: string): number {
['React', 'Fragment', 'StrictMode', 'Suspense', 'ErrorBoundary'].includes(
tag,
)
- )
+ ) {
continue;
+ }
// Skip wrapper/provider tags
- if (/(Provider|Context|Theme|Wrapper)$/.test(tag)) continue;
+ if (/(Provider|Context|Theme|Wrapper)$/.test(tag)) {
+ continue;
+ }
elements.add(`${tag}-${m.index}`); // unique by position
}
return elements.size;
@@ -611,33 +631,46 @@ function analyzeEfficiency(
stripped.startsWith('*')
) {
commentLines++;
- if (stripped.startsWith('/*')) inComment = true;
- if (stripped.includes('*/')) inComment = false;
+ if (stripped.startsWith('/*')) {
+ inComment = true;
+ }
+ if (stripped.includes('*/')) {
+ inComment = false;
+ }
continue;
}
if (inComment) {
commentLines++;
- if (stripped.includes('*/')) inComment = false;
+ if (stripped.includes('*/')) {
+ inComment = false;
+ }
continue;
}
if (stripped.startsWith('import ')) {
importLines++;
continue;
}
- if (/^(export\s+)?(type|interface)\s/.test(stripped)) inTypeBlock = true;
+ if (/^(export\s+)?(type|interface)\s/.test(stripped)) {
+ inTypeBlock = true;
+ }
if (inTypeBlock) {
typeLines++;
- if (stripped === '}' || stripped === '};') inTypeBlock = false;
+ if (stripped === '}' || stripped === '};') {
+ inTypeBlock = false;
+ }
continue;
}
if (
(target === 'xds' || target === 'xds-tailwind') &&
stripped.includes('stylex.create')
- )
+ ) {
inStyleBlock = true;
+ }
if (inStyleBlock) {
stylingLines++;
- if (stripped === '});') inStyleBlock = false;
+ if (stripped === '});') {
+ inStyleBlock = false;
+ }
continue;
}
if (
@@ -797,8 +830,9 @@ function countMagicAndSemanticValues(
line.trim().startsWith('//') ||
line.trim().startsWith('import') ||
line.trim().startsWith('*')
- )
+ ) {
continue;
+ }
// Hardcoded colors in style contexts
const colorMatches = line.match(
@@ -877,7 +911,9 @@ function measureStateSpread(code: string): number {
}
}
- if (spreads.length === 0) return 0;
+ if (spreads.length === 0) {
+ return 0;
+ }
return Math.round(spreads.reduce((a, b) => a + b, 0) / spreads.length);
}
@@ -1054,7 +1090,9 @@ export function getAverageScore(score: UniversalScore): number {
* Returns null if design score is not present.
*/
export function getFullAverageScore(score: UniversalScore): number | null {
- if (score.design == null) return null;
+ if (score.design == null) {
+ return null;
+ }
const dims = getDimensionNames();
const coreTotal = dims.reduce((sum, d) => sum + (score[d]?.score ?? 0), 0);
const total = coreTotal + score.design.score;
diff --git a/packages/cli/templates/pages/ai-chat-landing/page.tsx b/packages/cli/templates/pages/ai-chat-landing/page.tsx
index ee97a34c3f..c10b0e6ff7 100644
--- a/packages/cli/templates/pages/ai-chat-landing/page.tsx
+++ b/packages/cli/templates/pages/ai-chat-landing/page.tsx
@@ -400,7 +400,9 @@ export default function AIChatTemplate() {
const handleSubmit = useCallback(
(value: string) => {
- if (!value.trim()) return;
+ if (!value.trim()) {
+ return;
+ }
const userMsg: ChatMessage = {
id: Date.now(),
@@ -428,7 +430,9 @@ export default function AIChatTemplate() {
const replaceWithSuggestion = (prompt: string) => {
const input = composerInputRef.current;
- if (!input) return;
+ if (!input) {
+ return;
+ }
input.focus();
// Select all existing content so insertText replaces it
const sel = window.getSelection();
diff --git a/packages/cli/templates/pages/dashboard-portfolio/page.tsx b/packages/cli/templates/pages/dashboard-portfolio/page.tsx
index 05167f00d0..1084921756 100644
--- a/packages/cli/templates/pages/dashboard-portfolio/page.tsx
+++ b/packages/cli/templates/pages/dashboard-portfolio/page.tsx
@@ -87,7 +87,9 @@ const portfolioData = (() => {
const out: Array<{month: number; label: string; value: number}> = [];
let ai = 0;
for (let day = 0; day <= totalDays; day++) {
- while (ai < anchors.length - 2 && day >= anchors[ai + 1][0]) ai++;
+ while (ai < anchors.length - 2 && day >= anchors[ai + 1][0]) {
+ ai++;
+ }
const [d0, v0] = anchors[ai];
const [d1, v1] = anchors[ai + 1];
const t = (day - d0) / (d1 - d0);
@@ -355,7 +357,9 @@ function ChartTooltip({
payload?: Array<{value: number}>;
label?: number;
}) {
- if (!active || !payload?.length) return null;
+ if (!active || !payload?.length) {
+ return null;
+ }
return (
<XDSCard padding={3}>
<XDSText type="supporting">
@@ -750,9 +754,7 @@ export default function DashboardPortfolioTemplate() {
<XDSVStack gap={4}>
<XDSHStack hAlign="between" vAlign="center">
<XDSHeading level={3}>Portfolio Value</XDSHeading>
- <XDSLink href="#">
- View details
- </XDSLink>
+ <XDSLink href="#">View details</XDSLink>
</XDSHStack>
<PortfolioChart />
</XDSVStack>
@@ -763,9 +765,7 @@ export default function DashboardPortfolioTemplate() {
<XDSVStack gap={4}>
<XDSHStack hAlign="between" vAlign="center">
<XDSHeading level={3}>Top Assets</XDSHeading>
- <XDSLink href="#">
- View all
- </XDSLink>
+ <XDSLink href="#">View all</XDSLink>
</XDSHStack>
<XDSList density="spacious">
{topAssets.map(asset => (
diff --git a/packages/cli/templates/pages/dashboard/page.tsx b/packages/cli/templates/pages/dashboard/page.tsx
index 234931cd98..bc12545df3 100644
--- a/packages/cli/templates/pages/dashboard/page.tsx
+++ b/packages/cli/templates/pages/dashboard/page.tsx
@@ -484,7 +484,9 @@ function ChartTooltip({
payload?: Array<{name: string; value: number; color: string}>;
label?: number;
}) {
- if (!active || !payload?.length) return null;
+ if (!active || !payload?.length) {
+ return null;
+ }
const point = activeUsersData.find(d => d.hour === label);
return (
<XDSCard padding={3}>
diff --git a/packages/cli/templates/pages/documentation-design/page.tsx b/packages/cli/templates/pages/documentation-design/page.tsx
index efadd72b60..bcd3a5e23c 100644
--- a/packages/cli/templates/pages/documentation-design/page.tsx
+++ b/packages/cli/templates/pages/documentation-design/page.tsx
@@ -444,13 +444,17 @@ const COMPONENT_DOCS: Record<
function getComponentName(key: string): string {
for (const cat of COMPONENT_CATEGORIES) {
const item = cat.items.find(i => i.key === key);
- if (item) return item.name;
+ if (item) {
+ return item.name;
+ }
}
return key;
}
function getComponentDocs(key: string) {
- if (COMPONENT_DOCS[key]) return COMPONENT_DOCS[key];
+ if (COMPONENT_DOCS[key]) {
+ return COMPONENT_DOCS[key];
+ }
const name = getComponentName(key);
let desc = '';
for (const cat of COMPONENT_CATEGORIES) {
diff --git a/packages/cli/templates/pages/editor/page.tsx b/packages/cli/templates/pages/editor/page.tsx
index d5a5e6ecf8..125f7d8bb9 100644
--- a/packages/cli/templates/pages/editor/page.tsx
+++ b/packages/cli/templates/pages/editor/page.tsx
@@ -690,9 +690,13 @@ export default function EditorPage() {
const moveBlock = useCallback((id: string, dir: -1 | 1) => {
setBlocks(prev => {
const idx = prev.findIndex(b => b.id === id);
- if (idx < 0) return prev;
+ if (idx < 0) {
+ return prev;
+ }
const target = idx + dir;
- if (target < 0 || target >= prev.length) return prev;
+ if (target < 0 || target >= prev.length) {
+ return prev;
+ }
const next = [...prev];
[next[idx], next[target]] = [next[target], next[idx]];
return next;
@@ -702,7 +706,9 @@ export default function EditorPage() {
const deleteBlock = useCallback(
(id: string) => {
setBlocks(prev => prev.filter(b => b.id !== id));
- if (selectedId === id) setSelectedId(null);
+ if (selectedId === id) {
+ setSelectedId(null);
+ }
},
[selectedId],
);
@@ -846,7 +852,9 @@ export default function EditorPage() {
value={pageTitle}
onChange={setPageTitle}
onKeyDown={(e: React.KeyboardEvent) => {
- if (e.key === 'Enter') setIsEditingTitle(false);
+ if (e.key === 'Enter') {
+ setIsEditingTitle(false);
+ }
}}
hasAutoFocus
onBlur={() => setIsEditingTitle(false)}
@@ -859,7 +867,12 @@ export default function EditorPage() {
<XDSButton
label={isPanelCollapsed ? 'Expand panel' : 'Collapse panel'}
icon={
- <XDSIcon icon={isPanelCollapsed ? ChevronDownIcon : ChevronUpIcon} size="sm" />
+ <XDSIcon
+ icon={
+ isPanelCollapsed ? ChevronDownIcon : ChevronUpIcon
+ }
+ size="sm"
+ />
}
variant="ghost"
size="sm"
diff --git a/packages/cli/templates/pages/file-explorer/page.tsx b/packages/cli/templates/pages/file-explorer/page.tsx
index 673dc452ab..8c96c03481 100644
--- a/packages/cli/templates/pages/file-explorer/page.tsx
+++ b/packages/cli/templates/pages/file-explorer/page.tsx
@@ -274,10 +274,14 @@ const styles = stylex.create({
function findItem(items: FileSystemItem[], id: string): FileSystemItem | null {
for (const item of items) {
- if (item.id === id) return item;
+ if (item.id === id) {
+ return item;
+ }
if (item.children) {
const found = findItem(item.children, id);
- if (found) return found;
+ if (found) {
+ return found;
+ }
}
}
return null;
@@ -315,10 +319,14 @@ export default function FileExplorerPage() {
}, [selectedPath]);
const currentFolderName = useMemo(() => {
- if (selectedPath.length === 0) return 'Home';
+ if (selectedPath.length === 0) {
+ return 'Home';
+ }
const lastId = selectedPath[selectedPath.length - 1];
const item = findItem(FILESYSTEM, lastId);
- if (item?.type === 'folder') return item.name;
+ if (item?.type === 'folder') {
+ return item.name;
+ }
if (selectedPath.length >= 2) {
const parent = findItem(
FILESYSTEM,
@@ -330,7 +338,9 @@ export default function FileExplorerPage() {
}, [selectedPath]);
const selectedFile = useMemo(() => {
- if (selectedPath.length === 0) return null;
+ if (selectedPath.length === 0) {
+ return null;
+ }
const lastId = selectedPath[selectedPath.length - 1];
const item = findItem(FILESYSTEM, lastId);
return item?.type === 'file' ? item : null;
diff --git a/packages/cli/templates/pages/library/page.tsx b/packages/cli/templates/pages/library/page.tsx
index e23c85f71e..df67a98c4f 100644
--- a/packages/cli/templates/pages/library/page.tsx
+++ b/packages/cli/templates/pages/library/page.tsx
@@ -57,7 +57,8 @@ const ITEMS: LibraryItem[] = [
'Vertical and horizontal stack layouts with configurable gap and alignment.',
category: 'Layout',
type: 'Component',
- imageUrl: 'https://lookaside.facebook.com/assets/xds_oss/colorful-home-horizontal-1.png',
+ imageUrl:
+ 'https://lookaside.facebook.com/assets/xds_oss/colorful-home-horizontal-1.png',
},
{
id: '2',
@@ -66,7 +67,8 @@ const ITEMS: LibraryItem[] = [
'Responsive grid container with auto-fit columns and gap control.',
category: 'Layout',
type: 'Component',
- imageUrl: 'https://lookaside.facebook.com/assets/xds_oss/illustrative-horizontal-3.jpg',
+ imageUrl:
+ 'https://lookaside.facebook.com/assets/xds_oss/illustrative-horizontal-3.jpg',
},
{
id: '3',
@@ -75,7 +77,8 @@ const ITEMS: LibraryItem[] = [
'Surface container with optional padding, border, and shadow variants.',
category: 'Layout',
type: 'Component',
- imageUrl: 'https://lookaside.facebook.com/assets/xds_oss/light-working-horizontal-2.png',
+ imageUrl:
+ 'https://lookaside.facebook.com/assets/xds_oss/light-working-horizontal-2.png',
},
{
id: '4',
@@ -83,7 +86,8 @@ const ITEMS: LibraryItem[] = [
description: 'Centers its child both horizontally and vertically.',
category: 'Layout',
type: 'Utility',
- imageUrl: 'https://lookaside.facebook.com/assets/xds_oss/moody-scene-horizontal-1.png',
+ imageUrl:
+ 'https://lookaside.facebook.com/assets/xds_oss/moody-scene-horizontal-1.png',
},
{
id: '5',
@@ -91,7 +95,8 @@ const ITEMS: LibraryItem[] = [
description: 'Semantic page section with optional heading and divider.',
category: 'Layout',
type: 'Pattern',
- imageUrl: 'https://lookaside.facebook.com/assets/xds_oss/colorful-lifestyle-horizontal-2.png',
+ imageUrl:
+ 'https://lookaside.facebook.com/assets/xds_oss/colorful-lifestyle-horizontal-2.png',
},
{
id: '6',
@@ -99,7 +104,8 @@ const ITEMS: LibraryItem[] = [
description: 'Expandable region with animated height transition.',
category: 'Layout',
type: 'Component',
- imageUrl: 'https://lookaside.facebook.com/assets/xds_oss/light-scene-horizontal-1.png',
+ imageUrl:
+ 'https://lookaside.facebook.com/assets/xds_oss/light-scene-horizontal-1.png',
},
{
id: '7',
@@ -108,7 +114,8 @@ const ITEMS: LibraryItem[] = [
'Single-line text field with label, placeholder, and validation states.',
category: 'Forms',
type: 'Component',
- imageUrl: 'https://lookaside.facebook.com/assets/xds_oss/moody-working-horizontal-1.png',
+ imageUrl:
+ 'https://lookaside.facebook.com/assets/xds_oss/moody-working-horizontal-1.png',
},
{
id: '8',
@@ -116,7 +123,8 @@ const ITEMS: LibraryItem[] = [
description: 'Multi-line text field with auto-resize and character count.',
category: 'Forms',
type: 'Component',
- imageUrl: 'https://lookaside.facebook.com/assets/xds_oss/colorful-working-horizontal-3.png',
+ imageUrl:
+ 'https://lookaside.facebook.com/assets/xds_oss/colorful-working-horizontal-3.png',
},
{
id: '9',
@@ -124,7 +132,8 @@ const ITEMS: LibraryItem[] = [
description: 'Checkbox with label, indeterminate state, and group support.',
category: 'Forms',
type: 'Component',
- imageUrl: 'https://lookaside.facebook.com/assets/xds_oss/illustrative-horizontal-1.jpg',
+ imageUrl:
+ 'https://lookaside.facebook.com/assets/xds_oss/illustrative-horizontal-1.jpg',
},
{
id: '10',
@@ -132,7 +141,8 @@ const ITEMS: LibraryItem[] = [
description: 'Group of radio buttons with accessible fieldset wrapper.',
category: 'Forms',
type: 'Component',
- imageUrl: 'https://lookaside.facebook.com/assets/xds_oss/light-home-horizontal-1.png',
+ imageUrl:
+ 'https://lookaside.facebook.com/assets/xds_oss/light-home-horizontal-1.png',
},
{
id: '11',
@@ -140,7 +150,8 @@ const ITEMS: LibraryItem[] = [
description: 'Toggle switch for binary on/off settings.',
category: 'Forms',
type: 'Component',
- imageUrl: 'https://lookaside.facebook.com/assets/xds_oss/moody-home-horizontal-2.png',
+ imageUrl:
+ 'https://lookaside.facebook.com/assets/xds_oss/moody-home-horizontal-2.png',
},
{
id: '12',
@@ -149,7 +160,8 @@ const ITEMS: LibraryItem[] = [
'Dropdown or inline option selector with single and multi-select modes.',
category: 'Forms',
type: 'Component',
- imageUrl: 'https://lookaside.facebook.com/assets/xds_oss/colorful-product-1.png',
+ imageUrl:
+ 'https://lookaside.facebook.com/assets/xds_oss/colorful-product-1.png',
},
{
id: '13',
@@ -158,7 +170,8 @@ const ITEMS: LibraryItem[] = [
'Horizontal tab navigation with underline indicator and keyboard support.',
category: 'Navigation',
type: 'Component',
- imageUrl: 'https://lookaside.facebook.com/assets/xds_oss/illustrative-horizontal-5.jpg',
+ imageUrl:
+ 'https://lookaside.facebook.com/assets/xds_oss/illustrative-horizontal-5.jpg',
},
{
id: '14',
@@ -166,7 +179,8 @@ const ITEMS: LibraryItem[] = [
description: 'Application top bar with logo, nav links, and action slots.',
category: 'Navigation',
type: 'Pattern',
- imageUrl: 'https://lookaside.facebook.com/assets/xds_oss/light-working-horizontal-1.png',
+ imageUrl:
+ 'https://lookaside.facebook.com/assets/xds_oss/light-working-horizontal-1.png',
},
{
id: '15',
@@ -175,7 +189,8 @@ const ITEMS: LibraryItem[] = [
'Vertical sidebar navigation with collapsible groups and active states.',
category: 'Navigation',
type: 'Pattern',
- imageUrl: 'https://lookaside.facebook.com/assets/xds_oss/moody-lifestyle-horizontal-1.png',
+ imageUrl:
+ 'https://lookaside.facebook.com/assets/xds_oss/moody-lifestyle-horizontal-1.png',
},
{
id: '16',
@@ -183,7 +198,8 @@ const ITEMS: LibraryItem[] = [
description: 'Path trail navigation with separator and truncation support.',
category: 'Navigation',
type: 'Component',
- imageUrl: 'https://lookaside.facebook.com/assets/xds_oss/colorful-home-horizontal-2.png',
+ imageUrl:
+ 'https://lookaside.facebook.com/assets/xds_oss/colorful-home-horizontal-2.png',
},
{
id: '17',
@@ -192,7 +208,8 @@ const ITEMS: LibraryItem[] = [
'Page navigation with prev/next controls and page count display.',
category: 'Navigation',
type: 'Component',
- imageUrl: 'https://lookaside.facebook.com/assets/xds_oss/colorful-working-horizontal-1.png',
+ imageUrl:
+ 'https://lookaside.facebook.com/assets/xds_oss/colorful-working-horizontal-1.png',
},
{
id: '18',
@@ -201,7 +218,8 @@ const ITEMS: LibraryItem[] = [
'Bottom tab bar for mobile viewports with icon and label slots.',
category: 'Navigation',
type: 'Pattern',
- imageUrl: 'https://lookaside.facebook.com/assets/xds_oss/light-working-horizontal-3.png',
+ imageUrl:
+ 'https://lookaside.facebook.com/assets/xds_oss/light-working-horizontal-3.png',
},
{
id: '19',
@@ -210,7 +228,8 @@ const ITEMS: LibraryItem[] = [
'Compact label for status, count, or category with semantic color variants.',
category: 'Feedback',
type: 'Component',
- imageUrl: 'https://lookaside.facebook.com/assets/xds_oss/moody-working-horizontal-2.png',
+ imageUrl:
+ 'https://lookaside.facebook.com/assets/xds_oss/moody-working-horizontal-2.png',
},
{
id: '20',
@@ -219,7 +238,8 @@ const ITEMS: LibraryItem[] = [
'Full-width alert bar for info, success, warning, and error messages.',
category: 'Feedback',
type: 'Component',
- imageUrl: 'https://lookaside.facebook.com/assets/xds_oss/illustrative-horizontal-2.jpg',
+ imageUrl:
+ 'https://lookaside.facebook.com/assets/xds_oss/illustrative-horizontal-2.jpg',
},
{
id: '21',
@@ -227,7 +247,8 @@ const ITEMS: LibraryItem[] = [
description: 'Animated loading indicator with size and color variants.',
category: 'Feedback',
type: 'Component',
- imageUrl: 'https://lookaside.facebook.com/assets/xds_oss/colorful-lifestyle-horizontal-1.png',
+ imageUrl:
+ 'https://lookaside.facebook.com/assets/xds_oss/colorful-lifestyle-horizontal-1.png',
},
{
id: '22',
@@ -235,7 +256,8 @@ const ITEMS: LibraryItem[] = [
description: 'Horizontal bar indicating task completion percentage.',
category: 'Feedback',
type: 'Component',
- imageUrl: 'https://lookaside.facebook.com/assets/xds_oss/light-lifestyle-horizontal-1.png',
+ imageUrl:
+ 'https://lookaside.facebook.com/assets/xds_oss/light-lifestyle-horizontal-1.png',
},
{
id: '23',
@@ -244,7 +266,8 @@ const ITEMS: LibraryItem[] = [
'Small dot indicator for presence, health, or pipeline status.',
category: 'Feedback',
type: 'Component',
- imageUrl: 'https://lookaside.facebook.com/assets/xds_oss/moody-home-horizontal-1.png',
+ imageUrl:
+ 'https://lookaside.facebook.com/assets/xds_oss/moody-home-horizontal-1.png',
},
{
id: '24',
@@ -253,7 +276,8 @@ const ITEMS: LibraryItem[] = [
'Contextual label that appears on hover with configurable placement.',
category: 'Feedback',
type: 'Component',
- imageUrl: 'https://lookaside.facebook.com/assets/xds_oss/colorful-working-horizontal-2.png',
+ imageUrl:
+ 'https://lookaside.facebook.com/assets/xds_oss/colorful-working-horizontal-2.png',
},
{
id: '25',
@@ -262,7 +286,8 @@ const ITEMS: LibraryItem[] = [
'Feature-rich data table with sorting, selection, and column resizing.',
category: 'Data',
type: 'Component',
- imageUrl: 'https://lookaside.facebook.com/assets/xds_oss/illustrative-horizontal-4.jpg',
+ imageUrl:
+ 'https://lookaside.facebook.com/assets/xds_oss/illustrative-horizontal-4.jpg',
},
{
id: '26',
@@ -271,7 +296,8 @@ const ITEMS: LibraryItem[] = [
'User profile image with fallback initials and status dot support.',
category: 'Data',
type: 'Component',
- imageUrl: 'https://lookaside.facebook.com/assets/xds_oss/light-working-horizontal-4.png',
+ imageUrl:
+ 'https://lookaside.facebook.com/assets/xds_oss/light-working-horizontal-4.png',
},
{
id: '27',
@@ -280,7 +306,8 @@ const ITEMS: LibraryItem[] = [
'Placeholder shimmer for loading states matching content shapes.',
category: 'Data',
type: 'Utility',
- imageUrl: 'https://lookaside.facebook.com/assets/xds_oss/moody-lifestyle-horizontal-2.png',
+ imageUrl:
+ 'https://lookaside.facebook.com/assets/xds_oss/moody-lifestyle-horizontal-2.png',
},
{
id: '28',
@@ -288,7 +315,8 @@ const ITEMS: LibraryItem[] = [
description: 'Rich popover that appears on hover with arbitrary content.',
category: 'Data',
type: 'Component',
- imageUrl: 'https://lookaside.facebook.com/assets/xds_oss/moody-scene-horizontal-2.png',
+ imageUrl:
+ 'https://lookaside.facebook.com/assets/xds_oss/moody-scene-horizontal-2.png',
},
{
id: '29',
@@ -297,7 +325,8 @@ const ITEMS: LibraryItem[] = [
'Command-palette style search with grouped results and keyboard nav.',
category: 'Data',
type: 'Pattern',
- imageUrl: 'https://lookaside.facebook.com/assets/xds_oss/colorful-product-2.png',
+ imageUrl:
+ 'https://lookaside.facebook.com/assets/xds_oss/colorful-product-2.png',
},
{
id: '30',
@@ -306,7 +335,8 @@ const ITEMS: LibraryItem[] = [
'Autocomplete input with async suggestion loading and selection.',
category: 'Data',
type: 'Component',
- imageUrl: 'https://lookaside.facebook.com/assets/xds_oss/moody-working-horizontal-3.png',
+ imageUrl:
+ 'https://lookaside.facebook.com/assets/xds_oss/moody-working-horizontal-3.png',
},
];
@@ -440,11 +470,15 @@ export default function LibraryPage() {
}, [activeTab, search, sortOrder]);
const groupedSections = useMemo(() => {
- if (activeTab !== 'All') return null;
+ if (activeTab !== 'All') {
+ return null;
+ }
const order = CATEGORIES.filter(c => c !== 'All');
const map = new Map<string, LibraryItem[]>();
for (const item of filtered) {
- if (!map.has(item.category)) map.set(item.category, []);
+ if (!map.has(item.category)) {
+ map.set(item.category, []);
+ }
map.get(item.category)!.push(item);
}
return order
@@ -527,7 +561,9 @@ export default function LibraryPage() {
</XDSCenter>
) : (
<XDSVStack gap={6}>
- {(groupedSections ?? [{category: activeTab, items: filtered}]).flatMap(section => [
+ {(
+ groupedSections ?? [{category: activeTab, items: filtered}]
+ ).flatMap(section => [
<XDSDivider key={`d-${section.category}`} />,
<LibrarySection
key={section.category}
diff --git a/packages/cli/templates/pages/login-sso/page.tsx b/packages/cli/templates/pages/login-sso/page.tsx
index de4ea97be2..9e1514a682 100644
--- a/packages/cli/templates/pages/login-sso/page.tsx
+++ b/packages/cli/templates/pages/login-sso/page.tsx
@@ -79,7 +79,9 @@ export default function LoginSSO() {
const emailValid = isValidEmail(email);
const handleContinue = () => {
- if (!emailValid) return;
+ if (!emailValid) {
+ return;
+ }
if (provider) {
setStep('sso-confirm');
} else {
@@ -132,7 +134,9 @@ export default function LoginSSO() {
onChange={setEmail}
size="lg"
onKeyDown={(e: React.KeyboardEvent) => {
- if (e.key === 'Enter') handleContinue();
+ if (e.key === 'Enter') {
+ handleContinue();
+ }
}}
/>
<XDSTextInput
diff --git a/packages/cli/templates/pages/table-grouped/page.tsx b/packages/cli/templates/pages/table-grouped/page.tsx
index 04337acf0d..5638070bc4 100644
--- a/packages/cli/templates/pages/table-grouped/page.tsx
+++ b/packages/cli/templates/pages/table-grouped/page.tsx
@@ -623,14 +623,18 @@ function groupTasks(
const map = new Map<string, TaskRow[]>();
for (const task of tasks) {
const key = String(task[groupBy]) || '—';
- if (!map.has(key)) map.set(key, []);
+ if (!map.has(key)) {
+ map.set(key, []);
+ }
map.get(key)!.push(task);
}
return map;
}
function getGroupLabel(groupBy: GroupByField, key: string): string {
- if (groupBy === 'status') return STATUS_LABEL[key as TaskStatus] ?? key;
+ if (groupBy === 'status') {
+ return STATUS_LABEL[key as TaskStatus] ?? key;
+ }
if (groupBy === 'priority') {
const labels: Record<string, string> = {
urgent: 'Urgent',
@@ -866,7 +870,9 @@ function TaskDetailPanel({
onClose: () => void;
resizable: ResizableProps;
}) {
- if (!task) return null;
+ if (!task) {
+ return null;
+ }
return (
<XDSLayoutPanel
hasDivider
@@ -979,8 +985,9 @@ export default function DataTableTemplate() {
t.subtitle.toLowerCase().includes(q),
);
}
- if (priorityFilter !== 'all')
+ if (priorityFilter !== 'all') {
data = data.filter(t => t.priority === priorityFilter);
+ }
return data;
}, [search, priorityFilter]);
@@ -998,8 +1005,11 @@ export default function DataTableTemplate() {
const toggleGroup = (key: string) => {
setExpandedGroups(prev => {
const next = new Set(prev);
- if (next.has(key)) next.delete(key);
- else next.add(key);
+ if (next.has(key)) {
+ next.delete(key);
+ } else {
+ next.add(key);
+ }
return next;
});
};
@@ -1093,7 +1103,9 @@ export default function DataTableTemplate() {
</colgroup>
{groupKeys.map(key => {
const tasks = grouped.get(key)!;
- if (tasks.length === 0) return null;
+ if (tasks.length === 0) {
+ return null;
+ }
const isExpanded = expandedGroups.has(key);
return (
diff --git a/packages/core/src/AlertDialog/useXDSImperativeAlertDialog.tsx b/packages/core/src/AlertDialog/useXDSImperativeAlertDialog.tsx
index 89e910c0a8..00bbf64270 100644
--- a/packages/core/src/AlertDialog/useXDSImperativeAlertDialog.tsx
+++ b/packages/core/src/AlertDialog/useXDSImperativeAlertDialog.tsx
@@ -68,13 +68,17 @@ export function useXDSImperativeAlertDialog(): XDSImperativeAlertDialogReturn {
}, []);
const element = useMemo(() => {
- if (!options) return null;
+ if (!options) {
+ return null;
+ }
return (
<XDSAlertDialog
{...options}
isOpen={isOpen}
onOpenChange={open => {
- if (!open) setIsOpen(false);
+ if (!open) {
+ setIsOpen(false);
+ }
}}
/>
);
diff --git a/packages/core/src/AppShell/XDSAppShell.test.tsx b/packages/core/src/AppShell/XDSAppShell.test.tsx
index 151751aff1..0e2915bb70 100644
--- a/packages/core/src/AppShell/XDSAppShell.test.tsx
+++ b/packages/core/src/AppShell/XDSAppShell.test.tsx
@@ -78,7 +78,9 @@ function createMockMatchMedia(matches: boolean) {
removeEventListener: vi.fn(
(_event: string, handler: (e: MediaQueryListEvent) => void) => {
const idx = listeners.indexOf(handler);
- if (idx >= 0) listeners.splice(idx, 1);
+ if (idx >= 0) {
+ listeners.splice(idx, 1);
+ }
},
),
addListener: vi.fn(),
diff --git a/packages/core/src/AppShell/XDSAppShell.tsx b/packages/core/src/AppShell/XDSAppShell.tsx
index 5ac2431ce2..b94c644ab1 100644
--- a/packages/core/src/AppShell/XDSAppShell.tsx
+++ b/packages/core/src/AppShell/XDSAppShell.tsx
@@ -558,7 +558,9 @@ export function XDSAppShell({
);
useEffect(() => {
- if (!isAuto || !headerRef.current || !shellRef.current) return;
+ if (!isAuto || !headerRef.current || !shellRef.current) {
+ return;
+ }
const headerEl = headerRef.current;
const shellEl = shellRef.current;
@@ -580,7 +582,9 @@ export function XDSAppShell({
// efficient and does not over-trigger.
// =========================================================================
useEffect(() => {
- if (sideNavBreakpoint === 'none') return;
+ if (sideNavBreakpoint === 'none') {
+ return;
+ }
const breakpointPx = BREAKPOINT_VALUES[sideNavBreakpoint];
const mql = window.matchMedia(`(max-width: ${breakpointPx}px)`);
diff --git a/packages/core/src/AppShell/useXDSSlotPresence.tsx b/packages/core/src/AppShell/useXDSSlotPresence.tsx
index 92c34e6bdc..d633f0b39a 100644
--- a/packages/core/src/AppShell/useXDSSlotPresence.tsx
+++ b/packages/core/src/AppShell/useXDSSlotPresence.tsx
@@ -23,7 +23,9 @@ import {useCallback, useEffect, useRef, useState} from 'react';
function hasChildContent(el: HTMLElement): boolean {
for (let i = 0; i < el.childNodes.length; i++) {
const node = el.childNodes[i];
- if (node.nodeType === Node.ELEMENT_NODE) return true;
+ if (node.nodeType === Node.ELEMENT_NODE) {
+ return true;
+ }
if (
node.nodeType === Node.TEXT_NODE &&
node.textContent &&
diff --git a/packages/core/src/Avatar/XDSAvatar.tsx b/packages/core/src/Avatar/XDSAvatar.tsx
index 72cde772a2..3f46df59c8 100644
--- a/packages/core/src/Avatar/XDSAvatar.tsx
+++ b/packages/core/src/Avatar/XDSAvatar.tsx
@@ -236,8 +236,12 @@ export interface XDSAvatarProps extends XDSBaseProps<HTMLDivElement> {
*/
function getInitials(name: string): string {
const words = name.trim().split(/\s+/);
- if (words.length === 0) return '';
- if (words.length === 1) return words[0].charAt(0).toUpperCase();
+ if (words.length === 0) {
+ return '';
+ }
+ if (words.length === 1) {
+ return words[0].charAt(0).toUpperCase();
+ }
return (words[0].charAt(0) + words[words.length - 1].charAt(0)).toUpperCase();
}
diff --git a/packages/core/src/Breadcrumbs/XDSBreadcrumbItem.tsx b/packages/core/src/Breadcrumbs/XDSBreadcrumbItem.tsx
index c7d739bdfd..c4658ffd30 100644
--- a/packages/core/src/Breadcrumbs/XDSBreadcrumbItem.tsx
+++ b/packages/core/src/Breadcrumbs/XDSBreadcrumbItem.tsx
@@ -180,12 +180,18 @@ export function XDSBreadcrumbItem({
// non-separator item, set aria-current on our content element.
// Runs as useEffect (not layout) — only sets an aria attribute, no visual change.
useEffect(() => {
- if (!isAutoCandidate) return;
+ if (!isAutoCandidate) {
+ return;
+ }
const li = liRef.current;
- if (!li) return;
+ if (!li) {
+ return;
+ }
const ol = li.parentElement;
- if (!ol) return;
+ if (!ol) {
+ return;
+ }
// All breadcrumb items (li without aria-hidden are items, with aria-hidden are separators — but we no longer have separator lis)
const items = Array.from(ol.children) as HTMLElement[];
diff --git a/packages/core/src/ButtonGroup/XDSButtonGroup.tsx b/packages/core/src/ButtonGroup/XDSButtonGroup.tsx
index 42653e4292..c99c9a9ed7 100644
--- a/packages/core/src/ButtonGroup/XDSButtonGroup.tsx
+++ b/packages/core/src/ButtonGroup/XDSButtonGroup.tsx
@@ -139,10 +139,12 @@ export function XDSButtonGroup({
ref={(node: HTMLDivElement | null) => {
(listRef as React.MutableRefObject<HTMLElement | null>).current =
node;
- if (typeof ref === 'function') ref(node);
- else if (ref)
+ if (typeof ref === 'function') {
+ ref(node);
+ } else if (ref) {
(ref as React.MutableRefObject<HTMLDivElement | null>).current =
node;
+ }
}}
role="group"
aria-label={label}
diff --git a/packages/core/src/Calendar/XDSCalendar.test.tsx b/packages/core/src/Calendar/XDSCalendar.test.tsx
index e268be5258..38866bcc26 100644
--- a/packages/core/src/Calendar/XDSCalendar.test.tsx
+++ b/packages/core/src/Calendar/XDSCalendar.test.tsx
@@ -372,7 +372,9 @@ describe('XDSCalendar', () => {
// Click the first outside day
if (outsideDays[0]) {
const button = outsideDays[0].querySelector('button');
- if (button) await user.click(button);
+ if (button) {
+ await user.click(button);
+ }
}
expect(handleChange).not.toHaveBeenCalled();
diff --git a/packages/core/src/Calendar/XDSCalendar.tsx b/packages/core/src/Calendar/XDSCalendar.tsx
index e0c63f667a..2694580303 100644
--- a/packages/core/src/Calendar/XDSCalendar.tsx
+++ b/packages/core/src/Calendar/XDSCalendar.tsx
@@ -226,7 +226,9 @@ export function XDSCalendar({ref, ...props}: XDSCalendarProps) {
// Focus date state (which month is visible)
const [internalFocusDate, setInternalFocusDate] = useState<Date>(() => {
- if (focusDateProp) return parseISO(focusDateProp);
+ if (focusDateProp) {
+ return parseISO(focusDateProp);
+ }
if (effectiveValue) {
if (typeof effectiveValue === 'string') {
return parseISO(effectiveValue);
@@ -289,7 +291,9 @@ export function XDSCalendar({ref, ...props}: XDSCalendarProps) {
// Determine if prev/next navigation is possible based on min/max
const canNavigatePrevious = useMemo(() => {
- if (!min) return true;
+ if (!min) {
+ return true;
+ }
const minDate = parseISO(min);
// Can't go back if min is in the current focus month
return (
@@ -300,7 +304,9 @@ export function XDSCalendar({ref, ...props}: XDSCalendarProps) {
}, [min, baseMonth]);
const canNavigateNext = useMemo(() => {
- if (!max) return true;
+ if (!max) {
+ return true;
+ }
const maxDate = parseISO(max);
// Check against the last visible month, not just baseMonth
const lastVisibleMonth = new Date(baseMonth);
@@ -545,13 +551,19 @@ function MonthGrid({
// Helper to get the focused date from the currently focused element
const getFocusedDate = useCallback((): ISODateString | null => {
const activeElement = document.activeElement as HTMLElement | null;
- if (!activeElement) return null;
+ if (!activeElement) {
+ return null;
+ }
const ariaLabel = activeElement.getAttribute('aria-label');
- if (!ariaLabel) return null;
+ if (!ariaLabel) {
+ return null;
+ }
const parsed = new Date(ariaLabel);
- if (isNaN(parsed.getTime())) return null;
+ if (isNaN(parsed.getTime())) {
+ return null;
+ }
return dateToISO(parsed);
}, []);
@@ -605,7 +617,9 @@ function MonthGrid({
// Handle pending focus after month navigation
useEffect(() => {
- if (!pendingFocus || !gridRef.current) return;
+ if (!pendingFocus || !gridRef.current) {
+ return;
+ }
const buttons = gridRef.current.querySelectorAll<HTMLElement>(
'button:not([disabled])',
diff --git a/packages/core/src/Calendar/hooks/useCalendarConstraints.ts b/packages/core/src/Calendar/hooks/useCalendarConstraints.ts
index 115640776e..64635352de 100644
--- a/packages/core/src/Calendar/hooks/useCalendarConstraints.ts
+++ b/packages/core/src/Calendar/hooks/useCalendarConstraints.ts
@@ -12,7 +12,6 @@
* - /packages/core/src/Calendar/hooks/index.ts
*/
-
import {useCallback, useMemo} from 'react';
import type {ISODateString} from '../XDSCalendar';
@@ -86,15 +85,21 @@ export function useCalendarConstraints(
const isDateDisabled = useCallback(
(date: Date): boolean => {
// Check min bound
- if (minDate && date < minDate) return true;
+ if (minDate && date < minDate) {
+ return true;
+ }
// Check max bound
- if (maxDate && date > maxDate) return true;
+ if (maxDate && date > maxDate) {
+ return true;
+ }
// Check custom constraints
if (dateConstraints) {
for (const constraint of dateConstraints) {
- if (!constraint(date)) return true;
+ if (!constraint(date)) {
+ return true;
+ }
}
}
diff --git a/packages/core/src/Calendar/hooks/useCalendarDays.ts b/packages/core/src/Calendar/hooks/useCalendarDays.ts
index d13bdf66b2..6b3cecd73e 100644
--- a/packages/core/src/Calendar/hooks/useCalendarDays.ts
+++ b/packages/core/src/Calendar/hooks/useCalendarDays.ts
@@ -12,7 +12,6 @@
* - /packages/core/src/Calendar/hooks/index.ts
*/
-
import {useMemo} from 'react';
import type {DayOfWeek, ISODateString} from '../XDSCalendar';
@@ -96,7 +95,9 @@ export function useCalendarDays(
// Calculate starting offset based on weekStartsOn
let startingDayOfWeek = firstDayOfMonth.getDay() - weekStartsOn;
- if (startingDayOfWeek < 0) startingDayOfWeek += 7;
+ if (startingDayOfWeek < 0) {
+ startingDayOfWeek += 7;
+ }
// Calculate total cells
const totalDays = daysInMonth + startingDayOfWeek;
diff --git a/packages/core/src/Calendar/hooks/useCalendarNavigation.ts b/packages/core/src/Calendar/hooks/useCalendarNavigation.ts
index 1f756322d4..03d4bab519 100644
--- a/packages/core/src/Calendar/hooks/useCalendarNavigation.ts
+++ b/packages/core/src/Calendar/hooks/useCalendarNavigation.ts
@@ -12,7 +12,6 @@
* - /packages/core/src/Calendar/hooks/index.ts
*/
-
import {useState, useMemo, useCallback} from 'react';
import type {ISODateString} from '../XDSCalendar';
@@ -112,8 +111,12 @@ export function useCalendarNavigation(
// Internal focus date state
const [internalFocusDate, setInternalFocusDate] = useState<Date>(() => {
- if (focusDateProp) return parseISO(focusDateProp);
- if (initialValue) return parseISO(initialValue);
+ if (focusDateProp) {
+ return parseISO(focusDateProp);
+ }
+ if (initialValue) {
+ return parseISO(initialValue);
+ }
return new Date();
});
diff --git a/packages/core/src/Carousel/XDSCarousel.tsx b/packages/core/src/Carousel/XDSCarousel.tsx
index f96463a30e..214e96a72f 100644
--- a/packages/core/src/Carousel/XDSCarousel.tsx
+++ b/packages/core/src/Carousel/XDSCarousel.tsx
@@ -245,7 +245,9 @@ export function XDSCarousel({
const scrollBy = useCallback((direction: -1 | 1) => {
const el = scrollElRef.current;
- if (!el) return;
+ if (!el) {
+ return;
+ }
const firstChild = el.firstElementChild as HTMLElement | null;
const itemWidth = firstChild ? firstChild.offsetWidth : 0;
const amount = el.clientWidth - itemWidth * 0.5;
@@ -273,10 +275,14 @@ export function XDSCarousel({
return (
<div
ref={(el: HTMLDivElement | null) => {
- if (typeof ref === 'function') ref(el);
- else if (ref)
+ if (typeof ref === 'function') {
+ ref(el);
+ } else if (ref) {
(ref as React.MutableRefObject<HTMLDivElement | null>).current = el;
- if (layer.ref) layer.ref(el as HTMLElement | null);
+ }
+ if (layer.ref) {
+ layer.ref(el as HTMLElement | null);
+ }
}}
data-testid={testId}
role="region"
diff --git a/packages/core/src/Chat/XDSChatComposer.tsx b/packages/core/src/Chat/XDSChatComposer.tsx
index 4557c6875a..55eefcd05d 100644
--- a/packages/core/src/Chat/XDSChatComposer.tsx
+++ b/packages/core/src/Chat/XDSChatComposer.tsx
@@ -305,7 +305,9 @@ export function XDSChatComposer(props: XDSChatComposerProps) {
const handleSubmit = useCallback(() => {
const trimmed = currentValue.trim();
- if (!trimmed || isDisabled) return;
+ if (!trimmed || isDisabled) {
+ return;
+ }
onSubmit(trimmed);
updateValue('');
}, [currentValue, isDisabled, onSubmit, updateValue]);
diff --git a/packages/core/src/Chat/XDSChatComposerDrawer.tsx b/packages/core/src/Chat/XDSChatComposerDrawer.tsx
index 7cbee37c92..f86c16031e 100644
--- a/packages/core/src/Chat/XDSChatComposerDrawer.tsx
+++ b/packages/core/src/Chat/XDSChatComposerDrawer.tsx
@@ -236,7 +236,9 @@ export function XDSChatComposerDrawer({
const toggle = () => {
const next = !isCollapsed;
- if (!isControlled) setInternalCollapsed(next);
+ if (!isControlled) {
+ setInternalCollapsed(next);
+ }
onCollapsedChange?.(next);
};
diff --git a/packages/core/src/Chat/XDSChatComposerInput.tsx b/packages/core/src/Chat/XDSChatComposerInput.tsx
index bfee8e1266..25ddd45dac 100644
--- a/packages/core/src/Chat/XDSChatComposerInput.tsx
+++ b/packages/core/src/Chat/XDSChatComposerInput.tsx
@@ -240,7 +240,9 @@ const styles = stylex.create({
/** Select all text in a contentEditable element. */
function selectAll(el: HTMLElement): void {
const selection = window.getSelection();
- if (!selection) return;
+ if (!selection) {
+ return;
+ }
const range = document.createRange();
range.selectNodeContents(el);
selection.removeAllRanges();
@@ -337,7 +339,9 @@ export function XDSChatComposerInput(props: XDSChatComposerInputProps) {
const cleanupPortalsRef = useRef<(() => void) | null>(null);
const emitChange = useCallback(() => {
- if (!editableRef.current) return;
+ if (!editableRef.current) {
+ return;
+ }
const text = serialize(editableRef.current);
// Browsers may leave a trailing <br> when all content is deleted,
// which serializes to "\n". Treat whitespace-only as empty.
@@ -367,7 +371,9 @@ export function XDSChatComposerInput(props: XDSChatComposerInputProps) {
const insertText = useCallback((text: string) => {
const editable = editableRef.current;
- if (!editable) return;
+ if (!editable) {
+ return;
+ }
insertTextAtCursor(editable, text);
}, []);
@@ -440,9 +446,13 @@ export function XDSChatComposerInput(props: XDSChatComposerInputProps) {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
- if (!editableRef.current) return;
+ if (!editableRef.current) {
+ return;
+ }
const text = serialize(editableRef.current).trim();
- if (!text) return;
+ if (!text) {
+ return;
+ }
if (hasHistory) {
historyRef.current.push(text);
@@ -459,10 +469,14 @@ export function XDSChatComposerInput(props: XDSChatComposerInputProps) {
// History navigation (only when trigger menu is not active)
if (hasHistory && (e.key === 'ArrowUp' || e.key === 'ArrowDown')) {
- if (!editableRef.current) return;
+ if (!editableRef.current) {
+ return;
+ }
const text = serialize(editableRef.current);
const history = historyRef.current;
- if (history.length === 0) return;
+ if (history.length === 0) {
+ return;
+ }
if (e.key === 'ArrowUp') {
if (historyIndexRef.current === -1) {
@@ -482,7 +496,9 @@ export function XDSChatComposerInput(props: XDSChatComposerInputProps) {
if (nextIndex >= history.length) {
historyIndexRef.current = -1;
editableRef.current.textContent = currentDraftRef.current;
- if (currentDraftRef.current) selectAll(editableRef.current);
+ if (currentDraftRef.current) {
+ selectAll(editableRef.current);
+ }
} else {
historyIndexRef.current = nextIndex;
editableRef.current.textContent = history[nextIndex];
@@ -499,7 +515,9 @@ export function XDSChatComposerInput(props: XDSChatComposerInputProps) {
const handlePaste = useCallback(
(e: ClipboardEvent<HTMLDivElement>) => {
const editable = editableRef.current;
- if (!editable) return;
+ if (!editable) {
+ return;
+ }
// Place a caret at the end of the editable if the Selection has
// no Range inside it — programmatic focus alone doesn't create
diff --git a/packages/core/src/Chat/XDSChatLayout.tsx b/packages/core/src/Chat/XDSChatLayout.tsx
index db241fd249..e4c25392c8 100644
--- a/packages/core/src/Chat/XDSChatLayout.tsx
+++ b/packages/core/src/Chat/XDSChatLayout.tsx
@@ -240,14 +240,22 @@ const styles = stylex.create({
// =============================================================================
function getDensity(width: number): Density {
- if (width < 480) return 'compact';
- if (width <= 768) return 'balanced';
+ if (width < 480) {
+ return 'compact';
+ }
+ if (width <= 768) {
+ return 'balanced';
+ }
return 'spacious';
}
function hasVisibleContent(children: ReactNode): boolean {
- if (children == null || children === false) return false;
- if (Array.isArray(children) && children.length === 0) return false;
+ if (children == null || children === false) {
+ return false;
+ }
+ if (Array.isArray(children) && children.length === 0) {
+ return false;
+ }
return true;
}
@@ -314,7 +322,9 @@ export function XDSChatLayout({
// --- Density observer ---
useEffect(() => {
const root = rootRef.current;
- if (!root) return;
+ if (!root) {
+ return;
+ }
observeResize(root, () => {
setDensity(getDensity(root.clientWidth));
});
diff --git a/packages/core/src/Chat/XDSChatMessageList.tsx b/packages/core/src/Chat/XDSChatMessageList.tsx
index 9b732ec9fa..73d4ca8f2c 100644
--- a/packages/core/src/Chat/XDSChatMessageList.tsx
+++ b/packages/core/src/Chat/XDSChatMessageList.tsx
@@ -187,7 +187,9 @@ export function XDSChatMessageList({
// IntersectionObserver for scroll-to-top infinite scroll
useEffect(() => {
const scrollContainer = layoutContext?.scrollContainerRef?.current;
- if (!scrollToTopAction || !sentinelRef.current) return;
+ if (!scrollToTopAction || !sentinelRef.current) {
+ return;
+ }
const observer = new IntersectionObserver(
entries => {
diff --git a/packages/core/src/Chat/XDSChatMessageMetadata.tsx b/packages/core/src/Chat/XDSChatMessageMetadata.tsx
index 9d06e01834..27de50d7aa 100644
--- a/packages/core/src/Chat/XDSChatMessageMetadata.tsx
+++ b/packages/core/src/Chat/XDSChatMessageMetadata.tsx
@@ -119,7 +119,9 @@ export function XDSChatMessageMetadata({
const hasContent =
timestamp != null || footer != null || statusConfig != null;
- if (!hasContent) return null;
+ if (!hasContent) {
+ return null;
+ }
return (
<div
diff --git a/packages/core/src/Chat/XDSChatToolCalls.tsx b/packages/core/src/Chat/XDSChatToolCalls.tsx
index 34f515257e..a202d69dc9 100644
--- a/packages/core/src/Chat/XDSChatToolCalls.tsx
+++ b/packages/core/src/Chat/XDSChatToolCalls.tsx
@@ -419,7 +419,9 @@ function CallRow({call}: {call: XDSChatToolCallItem}) {
</div>
);
- if (!hasDetail) return row;
+ if (!hasDetail) {
+ return row;
+ }
return (
<div>
@@ -478,11 +480,15 @@ export function XDSChatToolCalls(props: XDSChatToolCallsProps) {
const toggle = useCallback(() => {
const next = !isExpanded;
- if (!isControlled) setInternalExpanded(next);
+ if (!isControlled) {
+ setInternalExpanded(next);
+ }
onExpandedChange?.(next);
}, [isExpanded, isControlled, onExpandedChange]);
- if (calls.length === 0) return null;
+ if (calls.length === 0) {
+ return null;
+ }
// Single call: render inline, no group chrome
if (calls.length === 1) {
diff --git a/packages/core/src/Chat/chatComposerSelection.ts b/packages/core/src/Chat/chatComposerSelection.ts
index 91d256165d..570f5e93a8 100644
--- a/packages/core/src/Chat/chatComposerSelection.ts
+++ b/packages/core/src/Chat/chatComposerSelection.ts
@@ -38,7 +38,9 @@
*/
export function ensureCaretInside(editable: HTMLElement): Selection | null {
const selection = window.getSelection();
- if (!selection) return null;
+ if (!selection) {
+ return null;
+ }
if (selection.rangeCount > 0) {
const existing = selection.getRangeAt(0);
@@ -70,7 +72,9 @@ export function insertTextAtCursor(
text: string,
): boolean {
const selection = ensureCaretInside(editable);
- if (!selection || selection.rangeCount === 0) return false;
+ if (!selection || selection.rangeCount === 0) {
+ return false;
+ }
const range = selection.getRangeAt(0);
range.deleteContents();
diff --git a/packages/core/src/Chat/useSpeechRecognition.ts b/packages/core/src/Chat/useSpeechRecognition.ts
index 5bc8abf639..dd0852bebb 100644
--- a/packages/core/src/Chat/useSpeechRecognition.ts
+++ b/packages/core/src/Chat/useSpeechRecognition.ts
@@ -102,7 +102,9 @@ type SpeechRecognitionEvent = {
type SpeechRecognitionConstructor = new () => SpeechRecognitionInstance;
function getSpeechRecognition(): SpeechRecognitionConstructor | null {
- if (typeof window === 'undefined') return null;
+ if (typeof window === 'undefined') {
+ return null;
+ }
return (
(window as unknown as {SpeechRecognition?: SpeechRecognitionConstructor})
.SpeechRecognition ??
@@ -149,13 +151,17 @@ async function createVolumeAnalyser(
calibrationSamples++;
for (let i = 0; i < dataArray.length; i++) {
const val = dataArray[i] / 255;
- if (val > noiseFloor[i]) noiseFloor[i] = val;
+ if (val > noiseFloor[i]) {
+ noiseFloor[i] = val;
+ }
}
}
function getCleanBin(i: number): number {
const raw = dataArray[i] / 255;
- if (calibrationSamples < CALIBRATION_FRAMES) return 0;
+ if (calibrationSamples < CALIBRATION_FRAMES) {
+ return 0;
+ }
return Math.max(0, raw - noiseFloor[i] * 1.1);
}
@@ -163,23 +169,34 @@ async function createVolumeAnalyser(
calibrate,
getVolume: () => {
analyser.getByteFrequencyData(dataArray);
- if (calibrationSamples < CALIBRATION_FRAMES) calibrate();
+ if (calibrationSamples < CALIBRATION_FRAMES) {
+ calibrate();
+ }
let sum = 0;
- for (let i = 0; i < dataArray.length; i++) sum += getCleanBin(i);
+ for (let i = 0; i < dataArray.length; i++) {
+ sum += getCleanBin(i);
+ }
return sum / dataArray.length;
},
getBands: (count: number) => {
analyser.getByteFrequencyData(dataArray);
- if (calibrationSamples < CALIBRATION_FRAMES) calibrate();
+ if (calibrationSamples < CALIBRATION_FRAMES) {
+ calibrate();
+ }
const bands: number[] = [];
const binCount = dataArray.length;
const voiceSplits = [3, 6, 11, 18, binCount];
- const splits = count <= voiceSplits.length ? voiceSplits.slice(0, count) : voiceSplits;
+ const splits =
+ count <= voiceSplits.length
+ ? voiceSplits.slice(0, count)
+ : voiceSplits;
let start = 1;
for (let b = 0; b < splits.length; b++) {
const end = splits[b];
let bandSum = 0;
- for (let i = start; i < end; i++) bandSum += getCleanBin(i);
+ for (let i = start; i < end; i++) {
+ bandSum += getCleanBin(i);
+ }
bands.push(bandSum / (end - start));
start = end;
}
@@ -190,12 +207,17 @@ async function createVolumeAnalyser(
const bands: number[] = [];
const binCount = dataArray.length;
const voiceSplits = [3, 6, 11, 18, binCount];
- const splits = count <= voiceSplits.length ? voiceSplits.slice(0, count) : voiceSplits;
+ const splits =
+ count <= voiceSplits.length
+ ? voiceSplits.slice(0, count)
+ : voiceSplits;
let start = 1;
for (let b = 0; b < splits.length; b++) {
const end = splits[b];
let bandSum = 0;
- for (let i = start; i < end; i++) bandSum += dataArray[i] / 255;
+ for (let i = start; i < end; i++) {
+ bandSum += dataArray[i] / 255;
+ }
bands.push(bandSum / (end - start));
start = end;
}
@@ -203,7 +225,9 @@ async function createVolumeAnalyser(
},
cleanup: () => {
source.disconnect();
- for (const track of stream.getTracks()) track.stop();
+ for (const track of stream.getTracks()) {
+ track.stop();
+ }
},
};
} catch {
@@ -267,9 +291,21 @@ export function useSpeechRecognition(
const rafRef = useRef<number>(0);
const callbacksRef = useRef({
- onTranscript, onResult, onError, onStart, onEnd, transformTranscript,
+ onTranscript,
+ onResult,
+ onError,
+ onStart,
+ onEnd,
+ transformTranscript,
});
- callbacksRef.current = {onTranscript, onResult, onError, onStart, onEnd, transformTranscript};
+ callbacksRef.current = {
+ onTranscript,
+ onResult,
+ onError,
+ onStart,
+ onEnd,
+ transformTranscript,
+ };
useEffect(() => {
const SR = getSpeechRecognition();
@@ -307,7 +343,9 @@ export function useSpeechRecognition(
const start = useCallback(() => {
const SR = getSpeechRecognition();
- if (!SR) return;
+ if (!SR) {
+ return;
+ }
recognitionRef.current?.abort();
const recognition = new SR();
recognition.lang = lang ?? navigator.language;
@@ -318,7 +356,10 @@ export function useSpeechRecognition(
setIsListening(true);
callbacksRef.current.onStart?.();
createVolumeAnalyser(getAudioContextRef.current).then(a => {
- if (a) { analyserRef.current = a; startVolumePolling(); }
+ if (a) {
+ analyserRef.current = a;
+ startVolumePolling();
+ }
});
};
@@ -330,8 +371,12 @@ export function useSpeechRecognition(
callbacksRef.current.onEnd?.();
};
- recognition.onspeechstart = () => { setIsSpeaking(true); };
- recognition.onspeechend = () => { setIsSpeaking(false); };
+ recognition.onspeechstart = () => {
+ setIsSpeaking(true);
+ };
+ recognition.onspeechend = () => {
+ setIsSpeaking(false);
+ };
recognition.onresult = (event: SpeechRecognitionEvent) => {
let interim = '';
@@ -356,18 +401,26 @@ export function useSpeechRecognition(
};
recognition.onerror = event => {
- callbacksRef.current.onError?.({ error: event.error, message: event.message });
+ callbacksRef.current.onError?.({
+ error: event.error,
+ message: event.message,
+ });
};
recognition.onnomatch = () => {
- callbacksRef.current.onError?.({ error: 'no-speech', message: 'No speech was detected.' });
+ callbacksRef.current.onError?.({
+ error: 'no-speech',
+ message: 'No speech was detected.',
+ });
};
recognitionRef.current = recognition;
recognition.start();
}, [lang, continuous, interimResults, startVolumePolling, stopVolumePolling]);
- const stop = useCallback(() => { recognitionRef.current?.stop(); }, []);
+ const stop = useCallback(() => {
+ recognitionRef.current?.stop();
+ }, []);
const abort = useCallback(() => {
recognitionRef.current?.abort();
@@ -375,11 +428,24 @@ export function useSpeechRecognition(
}, [stopVolumePolling]);
const toggle = useCallback(() => {
- if (isListening) stop(); else start();
+ if (isListening) {
+ stop();
+ } else {
+ start();
+ }
}, [isListening, start, stop]);
return {
- isSupported, isListening, isSpeaking, volume, bands, rawBands,
- interimTranscript, start, stop, abort, toggle,
+ isSupported,
+ isListening,
+ isSpeaking,
+ volume,
+ bands,
+ rawBands,
+ interimTranscript,
+ start,
+ stop,
+ abort,
+ toggle,
};
}
diff --git a/packages/core/src/Chat/useTriggerMenu.tsx b/packages/core/src/Chat/useTriggerMenu.tsx
index e07c6ee44d..4679095c3b 100644
--- a/packages/core/src/Chat/useTriggerMenu.tsx
+++ b/packages/core/src/Chat/useTriggerMenu.tsx
@@ -164,11 +164,17 @@ const styles = stylex.create({
function getTextBeforeCursor(editable: HTMLDivElement): string | null {
const selection = window.getSelection();
- if (!selection || selection.rangeCount === 0) return null;
+ if (!selection || selection.rangeCount === 0) {
+ return null;
+ }
const range = selection.getRangeAt(0);
- if (!range.collapsed) return null;
- if (!editable.contains(range.startContainer)) return null;
+ if (!range.collapsed) {
+ return null;
+ }
+ if (!editable.contains(range.startContainer)) {
+ return null;
+ }
const node = range.startContainer;
if (node.nodeType === Node.TEXT_NODE) {
@@ -212,11 +218,15 @@ function deleteTriggerText(
triggerStart: number,
): void {
const selection = window.getSelection();
- if (!selection || selection.rangeCount === 0) return;
+ if (!selection || selection.rangeCount === 0) {
+ return;
+ }
const range = selection.getRangeAt(0);
const node = range.startContainer;
- if (node.nodeType !== Node.TEXT_NODE) return;
+ if (node.nodeType !== Node.TEXT_NODE) {
+ return;
+ }
const text = node.textContent ?? '';
const cursorOffset = range.startOffset;
@@ -317,7 +327,9 @@ export function useTriggerMenu(
// rect — outside the contentEditable to avoid splitting text nodes.
const setAnchor = useCallback(() => {
const editable = editableRef.current;
- if (!editable) return;
+ if (!editable) {
+ return;
+ }
const selection = window.getSelection();
if (!selection || selection.rangeCount === 0) {
@@ -418,10 +430,14 @@ export function useTriggerMenu(
const selectItem = useCallback(
(item: XDSSearchableItem) => {
const trigger = state.activeTrigger;
- if (!trigger) return;
+ if (!trigger) {
+ return;
+ }
const editable = editableRef.current;
- if (!editable) return;
+ if (!editable) {
+ return;
+ }
// Clean up anchor span before modifying DOM — if the span were
// inside the editable it would split text nodes and break offsets.
@@ -452,20 +468,28 @@ export function useTriggerMenu(
);
const handleInput = useCallback(() => {
- if (!triggers || triggers.length === 0) return;
+ if (!triggers || triggers.length === 0) {
+ return;
+ }
const editable = editableRef.current;
- if (!editable) return;
+ if (!editable) {
+ return;
+ }
const textBefore = getTextBeforeCursor(editable);
if (textBefore === null) {
- if (state.isActive) reset();
+ if (state.isActive) {
+ reset();
+ }
return;
}
const found = findActiveTrigger(textBefore, triggers);
if (!found) {
- if (state.isActive) reset();
+ if (state.isActive) {
+ reset();
+ }
return;
}
@@ -501,7 +525,9 @@ export function useTriggerMenu(
const handleKeyDown = useCallback(
(e: React.KeyboardEvent): boolean => {
- if (!state.isActive || !popover.isOpen) return false;
+ if (!state.isActive || !popover.isOpen) {
+ return false;
+ }
switch (e.key) {
case 'ArrowDown': {
@@ -564,7 +590,9 @@ export function useTriggerMenu(
// Scroll highlighted item into view on keyboard navigation
useEffect(() => {
- if (!popover.isOpen || state.highlightedIndex < 0) return;
+ if (!popover.isOpen || state.highlightedIndex < 0) {
+ return;
+ }
const el = document.getElementById(getItemId(state.highlightedIndex));
el?.scrollIntoView({block: 'nearest'});
}, [state.highlightedIndex, popover.isOpen, getItemId]);
diff --git a/packages/core/src/Chat/useXDSChatComposerTokens.ts b/packages/core/src/Chat/useXDSChatComposerTokens.ts
index 59d26b3b80..44141f4bd9 100644
--- a/packages/core/src/Chat/useXDSChatComposerTokens.ts
+++ b/packages/core/src/Chat/useXDSChatComposerTokens.ts
@@ -99,12 +99,16 @@ export function useXDSChatComposerTokens({
const insertToken = useCallback(
(token: XDSChatComposerToken): string | undefined => {
const editable = editableRef.current;
- if (!editable) return;
+ if (!editable) {
+ return;
+ }
// Place a caret at the end of the editable if there's no Range
// inside it (programmatic focus does not create one).
const selection = ensureCaretInside(editable);
- if (!selection || selection.rangeCount === 0) return;
+ if (!selection || selection.rangeCount === 0) {
+ return;
+ }
const range = selection.getRangeAt(0);
@@ -141,7 +145,9 @@ export function useXDSChatComposerTokens({
// --- Backspace near tokens ---
const handleKeyDown = useCallback(
(e: React.KeyboardEvent): boolean => {
- if (e.key !== 'Backspace') return false;
+ if (e.key !== 'Backspace') {
+ return false;
+ }
const selection = window.getSelection();
if (!selection || !selection.isCollapsed || selection.rangeCount === 0) {
@@ -191,10 +197,14 @@ export function useXDSChatComposerTokens({
const handlePaste = useCallback(
(e: React.ClipboardEvent): boolean => {
const editable = editableRef.current;
- if (!editable) return false;
+ if (!editable) {
+ return false;
+ }
const selection = ensureCaretInside(editable);
- if (!selection || selection.rangeCount === 0) return false;
+ if (!selection || selection.rangeCount === 0) {
+ return false;
+ }
const range = selection.getRangeAt(0);
@@ -231,10 +241,14 @@ export function useXDSChatComposerTokens({
const expandToken = useCallback(
(id: string) => {
const editable = editableRef.current;
- if (!editable) return;
+ if (!editable) {
+ return;
+ }
const portal = tokenPortals.find(p => p.id === id);
- if (!portal) return;
+ if (!portal) {
+ return;
+ }
const {span} = portal;
const value = span.getAttribute('data-xds-token-value') ?? '';
diff --git a/packages/core/src/Chat/useXDSChatDictation.ts b/packages/core/src/Chat/useXDSChatDictation.ts
index ba636bd106..47aafb08e3 100644
--- a/packages/core/src/Chat/useXDSChatDictation.ts
+++ b/packages/core/src/Chat/useXDSChatDictation.ts
@@ -107,13 +107,17 @@ async function createVolumeAnalyser(
calibrationSamples++;
for (let i = 0; i < dataArray.length; i++) {
const val = dataArray[i] / 255;
- if (val > noiseFloor[i]) noiseFloor[i] = val;
+ if (val > noiseFloor[i]) {
+ noiseFloor[i] = val;
+ }
}
}
function getCleanBin(i: number): number {
const raw = dataArray[i] / 255;
- if (calibrationSamples < CALIBRATION_FRAMES) return 0;
+ if (calibrationSamples < CALIBRATION_FRAMES) {
+ return 0;
+ }
return Math.max(0, raw - noiseFloor[i] * 1.1);
}
@@ -121,23 +125,34 @@ async function createVolumeAnalyser(
calibrate,
getVolume: () => {
analyser.getByteFrequencyData(dataArray);
- if (calibrationSamples < CALIBRATION_FRAMES) calibrate();
+ if (calibrationSamples < CALIBRATION_FRAMES) {
+ calibrate();
+ }
let sum = 0;
- for (let i = 0; i < dataArray.length; i++) sum += getCleanBin(i);
+ for (let i = 0; i < dataArray.length; i++) {
+ sum += getCleanBin(i);
+ }
return sum / dataArray.length;
},
getBands: (count: number) => {
analyser.getByteFrequencyData(dataArray);
- if (calibrationSamples < CALIBRATION_FRAMES) calibrate();
+ if (calibrationSamples < CALIBRATION_FRAMES) {
+ calibrate();
+ }
const bands: number[] = [];
const binCount = dataArray.length;
const voiceSplits = [3, 6, 11, 18, binCount];
- const splits = count <= voiceSplits.length ? voiceSplits.slice(0, count) : voiceSplits;
+ const splits =
+ count <= voiceSplits.length
+ ? voiceSplits.slice(0, count)
+ : voiceSplits;
let start = 1;
for (let b = 0; b < splits.length; b++) {
const end = splits[b];
let sum = 0;
- for (let i = start; i < end; i++) sum += getCleanBin(i);
+ for (let i = start; i < end; i++) {
+ sum += getCleanBin(i);
+ }
bands.push(sum / (end - start));
start = end;
}
@@ -148,12 +163,17 @@ async function createVolumeAnalyser(
const bands: number[] = [];
const binCount = dataArray.length;
const voiceSplits = [3, 6, 11, 18, binCount];
- const splits = count <= voiceSplits.length ? voiceSplits.slice(0, count) : voiceSplits;
+ const splits =
+ count <= voiceSplits.length
+ ? voiceSplits.slice(0, count)
+ : voiceSplits;
let start = 1;
for (let b = 0; b < splits.length; b++) {
const end = splits[b];
let sum = 0;
- for (let i = start; i < end; i++) sum += dataArray[i] / 255;
+ for (let i = start; i < end; i++) {
+ sum += dataArray[i] / 255;
+ }
bands.push(sum / (end - start));
start = end;
}
@@ -161,7 +181,9 @@ async function createVolumeAnalyser(
},
cleanup: () => {
source.disconnect();
- for (const track of stream.getTracks()) track.stop();
+ for (const track of stream.getTracks()) {
+ track.stop();
+ }
},
};
} catch {
@@ -207,7 +229,10 @@ function playPlop(
osc.frequency.exponentialRampToValueAtTime(freq * 0.93, now + delay + dur);
gain.gain.setValueAtTime(0.001, now);
gain.gain.setValueAtTime(volume, now + delay);
- gain.gain.exponentialRampToValueAtTime(volume * 0.2, now + delay + dur * 0.12);
+ gain.gain.exponentialRampToValueAtTime(
+ volume * 0.2,
+ now + delay + dur * 0.12,
+ );
gain.gain.exponentialRampToValueAtTime(0.001, now + delay + dur);
osc.connect(gain);
gain.connect(ctx.destination);
@@ -219,13 +244,17 @@ function playPlop(
}
function playStartSound(getCtx: () => AudioContext) {
- if (isIOS) return;
+ if (isIOS) {
+ return;
+ }
playPlop(392, 0, getCtx);
playPlop(523, 0.07, getCtx);
}
function playStopSound(getCtx: () => AudioContext) {
- if (isIOS) return;
+ if (isIOS) {
+ return;
+ }
playPlop(523, 0, getCtx);
playPlop(392, 0.07, getCtx);
}
@@ -289,7 +318,9 @@ export function useXDSChatDictation(
setVolume(vol);
const hist = volumeHistoryRef.current;
hist.push(vol);
- if (hist.length > 30) hist.shift();
+ if (hist.length > 30) {
+ hist.shift();
+ }
setBands(analyser.getBands(5));
setRawBands(analyser.getRawBands(5));
}
@@ -320,7 +351,9 @@ export function useXDSChatDictation(
const insertInterimSpan = useCallback(() => {
const editable = getEditable();
- if (!editable) return;
+ if (!editable) {
+ return;
+ }
const span = document.createElement('span');
span.setAttribute('data-xds-dictation-interim', '');
span.contentEditable = 'false';
@@ -336,7 +369,11 @@ export function useXDSChatDictation(
const removeInterimSpan = useCallback(() => {
const span = interimSpanRef.current;
if (span?.isConnected) {
- try { span.remove(); } catch { /* Already removed */ }
+ try {
+ span.remove();
+ } catch {
+ /* Already removed */
+ }
}
interimSpanRef.current = null;
}, []);
@@ -344,11 +381,15 @@ export function useXDSChatDictation(
const transformTranscript = useCallback(
(text: string) => {
let t = text;
- if (userTransform) t = userTransform(t);
+ if (userTransform) {
+ t = userTransform(t);
+ }
const hist = volumeHistoryRef.current;
const avgVolume =
hist.length > 0 ? hist.reduce((a, b) => a + b, 0) / hist.length : 0;
- if (avgVolume >= 0.15 && hist.length >= 10) t = t.toUpperCase();
+ if (avgVolume >= 0.15 && hist.length >= 10) {
+ t = t.toUpperCase();
+ }
return t;
},
[userTransform],
@@ -395,19 +436,25 @@ export function useXDSChatDictation(
onResult: inputRef ? undefined : onResultProp,
onError,
onStart: () => {
- if (hasSounds) playStartSound(getAudioContextRef.current);
+ if (hasSounds) {
+ playStartSound(getAudioContextRef.current);
+ }
createVolumeAnalyser(getAudioContextRef.current).then(analyser => {
if (analyser) {
analyserRef.current = analyser;
startVolumePolling();
}
});
- if (inputRef) insertInterimSpan();
+ if (inputRef) {
+ insertInterimSpan();
+ }
callbacksRef.current.onStartProp?.();
},
onEnd: () => {
stopVolumePolling();
- if (hasSounds) playStopSound(getAudioContextRef.current);
+ if (hasSounds) {
+ playStopSound(getAudioContextRef.current);
+ }
if (inputRef) {
removeInterimSpan();
const editable = getEditable();
diff --git a/packages/core/src/Chat/useXDSChatNewMessages.ts b/packages/core/src/Chat/useXDSChatNewMessages.ts
index f751f84a95..36405a1c89 100644
--- a/packages/core/src/Chat/useXDSChatNewMessages.ts
+++ b/packages/core/src/Chat/useXDSChatNewMessages.ts
@@ -74,7 +74,9 @@ export function useXDSChatNewMessages({
// Observe content for height changes
useEffect(() => {
const el = contentRef.current;
- if (!el) return;
+ if (!el) {
+ return;
+ }
observeResize(el, () => {
// Notify scroll hook of any height change
@@ -82,8 +84,7 @@ export function useXDSChatNewMessages({
// Check if a new message was appended
const messages = el.getElementsByClassName('xds-chat-message');
- const last =
- messages.length > 0 ? messages[messages.length - 1] : null;
+ const last = messages.length > 0 ? messages[messages.length - 1] : null;
if (last && last !== lastMessageRef.current) {
lastMessageRef.current = last;
diff --git a/packages/core/src/Chat/useXDSChatPasteAsToken.ts b/packages/core/src/Chat/useXDSChatPasteAsToken.ts
index dd6034d783..04105e8366 100644
--- a/packages/core/src/Chat/useXDSChatPasteAsToken.ts
+++ b/packages/core/src/Chat/useXDSChatPasteAsToken.ts
@@ -59,9 +59,7 @@ export interface UseXDSChatPasteAsTokenReturn {
function defaultToToken(text: string): XDSChatComposerToken {
const lines = text.split('\n').length;
const chars = text.length;
- const label = lines > 1
- ? `${lines} lines, ${chars} chars`
- : `${chars} chars`;
+ const label = lines > 1 ? `${lines} lines, ${chars} chars` : `${chars} chars`;
return {
value: text,
label,
@@ -80,7 +78,9 @@ export function useXDSChatPasteAsToken({
}: UseXDSChatPasteAsTokenOptions): UseXDSChatPasteAsTokenReturn {
const onPaste = useCallback(
(_event: ClipboardEvent<HTMLDivElement>, text: string): boolean => {
- if (text.length <= threshold) return false;
+ if (text.length <= threshold) {
+ return false;
+ }
const token = toToken(text);
inputRef.current?.insertToken(token);
diff --git a/packages/core/src/Chat/useXDSChatStreamScroll.ts b/packages/core/src/Chat/useXDSChatStreamScroll.ts
index 144ef3d911..56029da316 100644
--- a/packages/core/src/Chat/useXDSChatStreamScroll.ts
+++ b/packages/core/src/Chat/useXDSChatStreamScroll.ts
@@ -190,7 +190,9 @@ export function useXDSChatStreamScroll({
const scrollToMessage = useCallback(
(el: HTMLElement) => {
const container = scrollRef.current;
- if (!container) return;
+ if (!container) {
+ return;
+ }
const containerRect = container.getBoundingClientRect();
const elRect = el.getBoundingClientRect();
const offset = elRect.top - containerRect.top + container.scrollTop;
@@ -202,7 +204,9 @@ export function useXDSChatStreamScroll({
const scrollToLastMessage = useCallback(() => {
const container = scrollRef.current;
- if (!container) return;
+ if (!container) {
+ return;
+ }
const messages = container.getElementsByClassName('xds-chat-message');
const last = messages[messages.length - 1];
if (last instanceof HTMLElement) {
@@ -224,7 +228,9 @@ export function useXDSChatStreamScroll({
}, []);
const scrollIfLocked = useCallback(() => {
- if (!enabled) return;
+ if (!enabled) {
+ return;
+ }
if (lockedRef.current) {
startAnimation();
}
@@ -234,7 +240,9 @@ export function useXDSChatStreamScroll({
useEffect(() => {
const el = scrollRef.current;
- if (!el || !enabled) return;
+ if (!el || !enabled) {
+ return;
+ }
// Initialize tracking values
lastScrollTopRef.current = el.scrollTop;
diff --git a/packages/core/src/CheckboxInput/XDSCheckboxInput.tsx b/packages/core/src/CheckboxInput/XDSCheckboxInput.tsx
index 5c16003bc0..4e25e85538 100644
--- a/packages/core/src/CheckboxInput/XDSCheckboxInput.tsx
+++ b/packages/core/src/CheckboxInput/XDSCheckboxInput.tsx
@@ -359,9 +359,14 @@ export function XDSCheckboxInput({
// Sync the native indeterminate DOM property (can't be set via JSX attribute)
const indeterminateRef = useCallback(
(el: HTMLInputElement | null) => {
- if (el) el.indeterminate = isIndeterminate;
- if (typeof ref === 'function') ref(el);
- else if (ref) ref.current = el;
+ if (el) {
+ el.indeterminate = isIndeterminate;
+ }
+ if (typeof ref === 'function') {
+ ref(el);
+ } else if (ref) {
+ ref.current = el;
+ }
},
[isIndeterminate, ref],
);
@@ -369,8 +374,12 @@ export function XDSCheckboxInput({
// Build aria-describedby from description and status message
// Only include descriptionID when the element actually renders
const describedByParts: string[] = [];
- if (description && !isLabelHidden) describedByParts.push(descriptionID);
- if (status?.message) describedByParts.push(statusMessageID);
+ if (description && !isLabelHidden) {
+ describedByParts.push(descriptionID);
+ }
+ if (status?.message) {
+ describedByParts.push(statusMessageID);
+ }
const ariaDescribedBy =
describedByParts.length > 0 ? describedByParts.join(' ') : undefined;
@@ -398,7 +407,9 @@ export function XDSCheckboxInput({
readOnly={isReadOnly}
required={isRequired}
onChange={e => {
- if (isBusy || isReadOnly) return;
+ if (isBusy || isReadOnly) {
+ return;
+ }
const checked = e.target.checked;
onChange?.(checked, e);
if (changeAction && !e.defaultPrevented) {
diff --git a/packages/core/src/CheckboxList/XDSCheckboxListItem.tsx b/packages/core/src/CheckboxList/XDSCheckboxListItem.tsx
index d4773b4fec..92e4843cf2 100644
--- a/packages/core/src/CheckboxList/XDSCheckboxListItem.tsx
+++ b/packages/core/src/CheckboxList/XDSCheckboxListItem.tsx
@@ -152,7 +152,9 @@ export function XDSCheckboxListItem({
const isInteractive = !effectiveReadOnly && (ctx != null || onCheck != null);
const handleToggle = () => {
- if (effectiveDisabled || effectiveReadOnly || isBusy) return;
+ if (effectiveDisabled || effectiveReadOnly || isBusy) {
+ return;
+ }
if (ctx && ctx.value !== undefined && value !== undefined) {
// Collection mode
diff --git a/packages/core/src/ClickableCard/XDSClickableCard.tsx b/packages/core/src/ClickableCard/XDSClickableCard.tsx
index e607aa32b1..09e2434ea9 100644
--- a/packages/core/src/ClickableCard/XDSClickableCard.tsx
+++ b/packages/core/src/ClickableCard/XDSClickableCard.tsx
@@ -255,9 +255,11 @@ export function XDSClickableCard({
<XDSCard
ref={(node: HTMLDivElement | null) => {
containerRef.current = node;
- if (typeof ref === 'function') ref(node);
- else if (ref != null)
+ if (typeof ref === 'function') {
+ ref(node);
+ } else if (ref != null) {
(ref as MutableRefObject<HTMLDivElement | null>).current = node;
+ }
}}
width={width}
height={height}
diff --git a/packages/core/src/CodeBlock/XDSCodeBlock.tsx b/packages/core/src/CodeBlock/XDSCodeBlock.tsx
index e2c8cef832..4b758b70bb 100644
--- a/packages/core/src/CodeBlock/XDSCodeBlock.tsx
+++ b/packages/core/src/CodeBlock/XDSCodeBlock.tsx
@@ -380,7 +380,9 @@ function hasHighlightAPI(): boolean {
* so we can fall back to spans.
*/
function isSafari(): boolean {
- if (typeof navigator === 'undefined') return false;
+ if (typeof navigator === 'undefined') {
+ return false;
+ }
const ua = navigator.userAgent;
return /AppleWebKit/.test(ua) && !/Chrome/.test(ua);
}
@@ -396,7 +398,9 @@ function useTokenLines(
const [asyncTokens, setAsyncTokens] = useState<TokenLine[] | null>(null);
const syncTokens = useMemo(() => {
- if (code.length >= SYNC_TOKENIZE_THRESHOLD) return null;
+ if (code.length >= SYNC_TOKENIZE_THRESHOLD) {
+ return null;
+ }
if (customTokenizer) {
return flatTokensToLines(customTokenizer(code, language), code);
}
@@ -404,13 +408,17 @@ function useTokenLines(
}, [code, language, customTokenizer]);
useEffect(() => {
- if (code.length < SYNC_TOKENIZE_THRESHOLD) return;
+ if (code.length < SYNC_TOKENIZE_THRESHOLD) {
+ return;
+ }
const abortController = new AbortController();
if (customTokenizer) {
Promise.resolve().then(() => {
- if (abortController.signal.aborted) return;
+ if (abortController.signal.aborted) {
+ return;
+ }
const flat = customTokenizer(code, language);
setAsyncTokens(flatTokensToLines(flat, code));
});
@@ -521,11 +529,15 @@ function RangeCodeContent({
const codeRef = useRef<HTMLElement>(null);
useEffect(() => {
- if (!hasHighlightAPI()) return;
+ if (!hasHighlightAPI()) {
+ return;
+ }
ensureHighlightStyles();
const codeEl = codeRef.current;
- if (!codeEl || tokenLines.length === 0) return;
+ if (!codeEl || tokenLines.length === 0) {
+ return;
+ }
return applyHighlightRangesChunked(codeEl, tokenLines);
}, [tokenLines]);
diff --git a/packages/core/src/CodeBlock/highlightRanges.ts b/packages/core/src/CodeBlock/highlightRanges.ts
index eddd6599ce..7bc6ac9807 100644
--- a/packages/core/src/CodeBlock/highlightRanges.ts
+++ b/packages/core/src/CodeBlock/highlightRanges.ts
@@ -44,18 +44,24 @@ let dynamicStyleSheet: CSSStyleSheet | null = null;
* Built-in types are pre-seeded and never reach this path.
*/
function ensureDynamicHighlightType(tokenType: string): void {
- if (registeredHighlightTypes.has(tokenType)) return;
+ if (registeredHighlightTypes.has(tokenType)) {
+ return;
+ }
registeredHighlightTypes.add(tokenType);
ensureHighlightStyles();
- if (typeof document === 'undefined') return;
+ if (typeof document === 'undefined') {
+ return;
+ }
if (!dynamicStyleSheet) {
const style = document.createElement('style');
style.setAttribute('data-xds-highlight-dynamic', '');
document.head.appendChild(style);
dynamicStyleSheet = style.sheet ?? null;
- if (!dynamicStyleSheet) return;
+ if (!dynamicStyleSheet) {
+ return;
+ }
}
const name = `xds-${tokenType}`;
@@ -78,7 +84,9 @@ function createHighlightResolver(): (tokenType: string) => Highlight {
const cache = new Map<string, Highlight>();
return (tokenType: string): Highlight => {
let highlight = cache.get(tokenType);
- if (highlight) return highlight;
+ if (highlight) {
+ return highlight;
+ }
ensureDynamicHighlightType(tokenType);
@@ -113,17 +121,23 @@ function applyLineRanges(
results: RangeEntry[],
resolve: (tokenType: string) => Highlight,
): void {
- if (tokens.length === 0) return;
+ if (tokens.length === 0) {
+ return;
+ }
// The text node is the first child of the line div.
// In range mode, lines render plain text so this is always a Text node.
const textNode = lineDiv.firstChild;
- if (!textNode || textNode.nodeType !== Node.TEXT_NODE) return;
+ if (!textNode || textNode.nodeType !== Node.TEXT_NODE) {
+ return;
+ }
const textLength = (textNode as Text).length;
for (const token of tokens) {
- if (token.start >= textLength || token.end <= 0) continue;
+ if (token.start >= textLength || token.end <= 0) {
+ continue;
+ }
const start = Math.min(token.start, textLength);
const end = Math.min(token.end, textLength);
@@ -235,7 +249,9 @@ export function applyHighlightRangesChunked(
const listeners = new Map<Element, EventListener>();
function applyChunk(wrapper: Element, index: number) {
- if (chunkRanges.has(wrapper)) return; // already applied
+ if (chunkRanges.has(wrapper)) {
+ return;
+ } // already applied
const ranges = applyRangesToContainer(
wrapper,
tokenLines,
@@ -327,7 +343,9 @@ export function applyHighlightRangesBatch(
for (let i = 0; i < tokenLines.length; i++) {
const divIndex = startLine + i;
- if (divIndex >= lineDivs.length) break;
+ if (divIndex >= lineDivs.length) {
+ break;
+ }
const lineDiv = lineDivs[divIndex];
const tokens = tokenLines[i];
@@ -373,7 +391,9 @@ export function applyHighlightRangesFlat(
current = walker.nextNode();
}
- if (textNodes.length === 0) return () => cleanupRanges(myRanges);
+ if (textNodes.length === 0) {
+ return () => cleanupRanges(myRanges);
+ }
// Convert per-line tokens to absolute offsets.
// The source code string has lines joined by \n, so each line starts
@@ -389,7 +409,9 @@ export function applyHighlightRangesFlat(
const startPos = resolveOffset(textNodes, absStart);
const endPos = resolveOffset(textNodes, absEnd);
- if (!startPos || !endPos) continue;
+ if (!startPos || !endPos) {
+ continue;
+ }
const highlight = resolve(token.type);
try {
diff --git a/packages/core/src/CodeBlock/highlightStyles.ts b/packages/core/src/CodeBlock/highlightStyles.ts
index cb236f5935..6070f020ee 100644
--- a/packages/core/src/CodeBlock/highlightStyles.ts
+++ b/packages/core/src/CodeBlock/highlightStyles.ts
@@ -81,8 +81,12 @@ let inserted = false;
* Safe to call multiple times — only injects once.
*/
export function ensureHighlightStyles(): void {
- if (inserted) return;
- if (typeof document === 'undefined') return;
+ if (inserted) {
+ return;
+ }
+ if (typeof document === 'undefined') {
+ return;
+ }
const style = document.createElement('style');
style.setAttribute('data-xds-highlight-styles', '');
diff --git a/packages/core/src/CodeBlock/tokenizer.ts b/packages/core/src/CodeBlock/tokenizer.ts
index 728736301d..93baf8230f 100644
--- a/packages/core/src/CodeBlock/tokenizer.ts
+++ b/packages/core/src/CodeBlock/tokenizer.ts
@@ -57,7 +57,9 @@ const HACK_KEYWORDS =
function buildLanguage(lang: string): LangDef | null {
const cached = langCache.get(lang);
- if (cached !== undefined) return cached;
+ if (cached !== undefined) {
+ return cached;
+ }
const def = buildLanguageUncached(lang);
langCache.set(lang, def);
@@ -66,7 +68,9 @@ function buildLanguage(lang: string): LangDef | null {
function buildLanguageUncached(lang: string): LangDef | null {
const raw = buildLanguagePatterns(lang);
- if (!raw) return null;
+ if (!raw) {
+ return null;
+ }
return {
defaultType: raw.defaultType,
patterns: raw.patterns.map(p => {
@@ -78,7 +82,10 @@ function buildLanguageUncached(lang: string): LangDef | null {
function buildLanguagePatterns(
lang: string,
-): {patterns: Array<{type: string; regex: RegExp}>; defaultType: string} | null {
+): {
+ patterns: Array<{type: string; regex: RegExp}>;
+ defaultType: string;
+} | null {
switch (lang) {
case 'typescript':
case 'javascript':
@@ -388,7 +395,9 @@ function tokenizeLine(
*/
export function tokenize(code: string, language: string): TokenLine[] {
const langDef = buildLanguage(language);
- if (!langDef) return [];
+ if (!langDef) {
+ return [];
+ }
const result: TokenLine[] = [];
let lineStart = 0;
@@ -413,7 +422,9 @@ export async function tokenizeAsync(
signal?: AbortSignal,
): Promise<TokenLine[]> {
const langDef = buildLanguage(language);
- if (!langDef) return [];
+ if (!langDef) {
+ return [];
+ }
const result: TokenLine[] = [];
let lineStart = 0;
@@ -426,7 +437,9 @@ export async function tokenizeAsync(
lineStart = i + 1;
if (charsInChunk >= ASYNC_CHUNK_SIZE && i < code.length) {
- if (signal?.aborted) return result;
+ if (signal?.aborted) {
+ return result;
+ }
charsInChunk = 0;
await yieldToMain();
}
@@ -448,7 +461,9 @@ export async function tokenizeStreaming(
signal?: AbortSignal,
): Promise<void> {
const langDef = buildLanguage(language);
- if (!langDef) return;
+ if (!langDef) {
+ return;
+ }
let lineStart = 0;
let lineIndex = 0;
@@ -464,7 +479,9 @@ export async function tokenizeStreaming(
lineStart = i + 1;
if (charsInChunk >= ASYNC_CHUNK_SIZE && i < code.length) {
- if (signal?.aborted) return;
+ if (signal?.aborted) {
+ return;
+ }
onBatch(batch, batchStartLine);
batch = [];
batchStartLine = lineIndex;
@@ -490,7 +507,9 @@ export function flatTokensToLines(
): TokenLine[] {
const lineStarts: number[] = [0];
for (let i = 0; i < code.length; i++) {
- if (code[i] === '\n') lineStarts.push(i + 1);
+ if (code[i] === '\n') {
+ lineStarts.push(i + 1);
+ }
}
const result: TokenLine[] = Array.from({length: lineStarts.length}, () => []);
diff --git a/packages/core/src/Collapsible/XDSCollapsibleGroup.tsx b/packages/core/src/Collapsible/XDSCollapsibleGroup.tsx
index 6fe8d8f12a..4eebcdb6a5 100644
--- a/packages/core/src/Collapsible/XDSCollapsibleGroup.tsx
+++ b/packages/core/src/Collapsible/XDSCollapsibleGroup.tsx
@@ -79,7 +79,9 @@ export interface XDSCollapsibleGroupProps {
}
function normalizeToArray(value: string | string[] | undefined): string[] {
- if (value == null) return [];
+ if (value == null) {
+ return [];
+ }
return Array.isArray(value) ? value : [value];
}
diff --git a/packages/core/src/Collapsible/useXDSCollapsible.ts b/packages/core/src/Collapsible/useXDSCollapsible.ts
index 8647c5a76f..94acfc962d 100644
--- a/packages/core/src/Collapsible/useXDSCollapsible.ts
+++ b/packages/core/src/Collapsible/useXDSCollapsible.ts
@@ -92,8 +92,12 @@ export function useXDSCollapsible(
// Internal state for uncontrolled mode
const [internalIsOpen, setInternalIsOpen] = useState(() => {
- if (isControlledByGroup) return true; // group manages this
- if (config?.isOpen !== undefined) return config.isOpen;
+ if (isControlledByGroup) {
+ return true;
+ } // group manages this
+ if (config?.isOpen !== undefined) {
+ return config.isOpen;
+ }
return config?.defaultIsOpen ?? true;
});
diff --git a/packages/core/src/CommandPalette/XDSCommandPalette.tsx b/packages/core/src/CommandPalette/XDSCommandPalette.tsx
index 226d483c68..04d94bd4d3 100644
--- a/packages/core/src/CommandPalette/XDSCommandPalette.tsx
+++ b/packages/core/src/CommandPalette/XDSCommandPalette.tsx
@@ -428,7 +428,9 @@ export function XDSCommandPalette<
return;
}
// Space should type in the input, not trigger selection
- if (e.key === ' ') return;
+ if (e.key === ' ') {
+ return;
+ }
combobox.onKeyDown(e);
},
[combobox, handleClose, selectableItems, selectItem],
@@ -512,8 +514,11 @@ export function XDSCommandPalette<
isOpen={isOpen}
isInline={isInline}
onOpenChange={open => {
- if (!open) handleClose();
- else onOpenChange(true);
+ if (!open) {
+ handleClose();
+ } else {
+ onOpenChange(true);
+ }
}}
width={width}
maxHeight={maxHeight}
diff --git a/packages/core/src/CommandPalette/XDSCommandPaletteInput.tsx b/packages/core/src/CommandPalette/XDSCommandPaletteInput.tsx
index 5e95e6a22f..6badf477d1 100644
--- a/packages/core/src/CommandPalette/XDSCommandPaletteInput.tsx
+++ b/packages/core/src/CommandPalette/XDSCommandPaletteInput.tsx
@@ -205,7 +205,9 @@ export function XDSCommandPaletteInput({
const handleKeyDown = useCallback(
(e: React.KeyboardEvent<HTMLInputElement>) => {
onKeyDown?.(e);
- if (e.defaultPrevented) return;
+ if (e.defaultPrevented) {
+ return;
+ }
// Delegate to useCombobox's keyboard handler from context
ctx?.onKeyDown(e);
},
diff --git a/packages/core/src/CommandPalette/XDSCommandPaletteItem.tsx b/packages/core/src/CommandPalette/XDSCommandPaletteItem.tsx
index 4cba29fb47..9f9d477724 100644
--- a/packages/core/src/CommandPalette/XDSCommandPaletteItem.tsx
+++ b/packages/core/src/CommandPalette/XDSCommandPaletteItem.tsx
@@ -160,7 +160,9 @@ export function XDSCommandPaletteItem({
}, [isHighlighted]);
const handleClick = useCallback(() => {
- if (isDisabled) return;
+ if (isDisabled) {
+ return;
+ }
onSelect?.(value);
if (ctx) {
ctx.selectItem(value);
@@ -169,7 +171,9 @@ export function XDSCommandPaletteItem({
}, [isDisabled, value, onSelect, ctx]);
const handleMouseEnter = useCallback(() => {
- if (isDisabled || !ctx || itemIndex < 0) return;
+ if (isDisabled || !ctx || itemIndex < 0) {
+ return;
+ }
ctx.setHighlightedIndex(itemIndex);
}, [isDisabled, itemIndex, ctx]);
diff --git a/packages/core/src/ContextMenu/XDSContextMenu.tsx b/packages/core/src/ContextMenu/XDSContextMenu.tsx
index b462e0490a..d1a7c0b5eb 100644
--- a/packages/core/src/ContextMenu/XDSContextMenu.tsx
+++ b/packages/core/src/ContextMenu/XDSContextMenu.tsx
@@ -222,7 +222,9 @@ export function XDSContextMenu({
// opening right-click as a dismiss event. Handling it ourselves via
// mousedown avoids that race.
useEffect(() => {
- if (!isOpen) return;
+ if (!isOpen) {
+ return;
+ }
const handleClickOutside = (e: MouseEvent) => {
const menu = listRef.current;
if (menu && !menu.contains(e.target as Node)) {
@@ -252,7 +254,9 @@ export function XDSContextMenu({
const handleContextMenu = useCallback(
(e: React.MouseEvent) => {
- if (isDisabled) return;
+ if (isDisabled) {
+ return;
+ }
e.preventDefault();
positionRef.current = {x: e.clientX, y: e.clientY};
layer.show();
diff --git a/packages/core/src/DateInput/XDSDateInput.tsx b/packages/core/src/DateInput/XDSDateInput.tsx
index 333e75ef82..e766c7de59 100644
--- a/packages/core/src/DateInput/XDSDateInput.tsx
+++ b/packages/core/src/DateInput/XDSDateInput.tsx
@@ -377,7 +377,9 @@ export function XDSDateInput({
// Unified change handler that fires both onChange and changeAction
const fireChange = useCallback(
(newValue: ISODateString | undefined) => {
- if (isBusy) return;
+ if (isBusy) {
+ return;
+ }
onChange?.(newValue);
if (changeAction) {
startTransition(async () => {
diff --git a/packages/core/src/DateRangePicker/XDSDateRangePicker.tsx b/packages/core/src/DateRangePicker/XDSDateRangePicker.tsx
index 987a84b438..c9ec5f683b 100644
--- a/packages/core/src/DateRangePicker/XDSDateRangePicker.tsx
+++ b/packages/core/src/DateRangePicker/XDSDateRangePicker.tsx
@@ -180,7 +180,9 @@ function parseISO(iso: ISODateString): Date {
}
function formatRangeDisplay(range: DateRange | null): string {
- if (!range) return '';
+ if (!range) {
+ return '';
+ }
const startDate = parseISO(range.start);
const endDate = parseISO(range.end);
const currentYear = new Date().getFullYear();
@@ -193,8 +195,12 @@ function formatRangeDisplay(range: DateRange | null): string {
}
function isRangeEqual(a: DateRange | null, b: DateRange | null): boolean {
- if (a === b) return true;
- if (!a || !b) return false;
+ if (a === b) {
+ return true;
+ }
+ if (!a || !b) {
+ return false;
+ }
return a.start === b.start && a.end === b.end;
}
@@ -409,7 +415,9 @@ export function XDSDateRangePicker({
const fireChange = useCallback(
(newValue: DateRange | null) => {
- if (isBusy) return;
+ if (isBusy) {
+ return;
+ }
onChange(newValue);
if (changeAction) {
startTransition(async () => {
diff --git a/packages/core/src/DateTimePicker/XDSDateTimePicker.tsx b/packages/core/src/DateTimePicker/XDSDateTimePicker.tsx
index 44d50f4df5..e0f77f8c80 100644
--- a/packages/core/src/DateTimePicker/XDSDateTimePicker.tsx
+++ b/packages/core/src/DateTimePicker/XDSDateTimePicker.tsx
@@ -306,10 +306,13 @@ function splitDateTime(dt: ISODateTimeString | undefined): {
date: ISODateString | undefined;
time: ISOTimeString | undefined;
} {
- if (!dt) return {date: undefined, time: undefined};
+ if (!dt) {
+ return {date: undefined, time: undefined};
+ }
const tIndex = dt.indexOf('T');
- if (tIndex === -1)
+ if (tIndex === -1) {
return {date: dt as unknown as ISODateString, time: undefined};
+ }
return {
date: dt.slice(0, tIndex) as ISODateString,
time: dt.slice(tIndex + 1) as ISOTimeString,
@@ -320,7 +323,9 @@ function combineDateTime(
date: ISODateString | undefined,
time: ISOTimeString | undefined,
): ISODateTimeString | undefined {
- if (!date || !time) return undefined;
+ if (!date || !time) {
+ return undefined;
+ }
return `${date}T${time}` as ISODateTimeString;
}
@@ -432,12 +437,16 @@ export function XDSDateTimePicker({
// Time constraints change depending on selected date
const timeMin = useMemo(() => {
- if (!minParts.date || !minParts.time || !valueParts.date) return undefined;
+ if (!minParts.date || !minParts.time || !valueParts.date) {
+ return undefined;
+ }
return valueParts.date === minParts.date ? minParts.time : undefined;
}, [minParts.date, minParts.time, valueParts.date]);
const timeMax = useMemo(() => {
- if (!maxParts.date || !maxParts.time || !valueParts.date) return undefined;
+ if (!maxParts.date || !maxParts.time || !valueParts.date) {
+ return undefined;
+ }
return valueParts.date === maxParts.date ? maxParts.time : undefined;
}, [maxParts.date, maxParts.time, valueParts.date]);
@@ -445,7 +454,9 @@ export function XDSDateTimePicker({
const [datePendingInput, setDatePendingInput] = useState<string | null>(null);
useEffect(() => {
- if (valueParts.date === lastFiredDateRef.current) return;
+ if (valueParts.date === lastFiredDateRef.current) {
+ return;
+ }
lastFiredDateRef.current = undefined;
setDatePendingInput(null);
}, [valueParts.date]);
@@ -470,16 +481,22 @@ export function XDSDateTimePicker({
hourFormat === '12h' ? formatDisplayTime12h : formatDisplayTime24h;
const timeDisplayValue = useMemo(() => {
- if (timePendingInput !== null) return timePendingInput;
+ if (timePendingInput !== null) {
+ return timePendingInput;
+ }
return valueParts.time
? formatDisplayTime(valueParts.time, hasSeconds)
: '';
}, [timePendingInput, valueParts.time, formatDisplayTime, hasSeconds]);
const isTimeInputValid = useMemo(() => {
- if (timePendingInput === null || !timePendingInput.trim()) return true;
+ if (timePendingInput === null || !timePendingInput.trim()) {
+ return true;
+ }
const parsed = parseTimeInput(timePendingInput, hasSeconds);
- if (!parsed) return false;
+ if (!parsed) {
+ return false;
+ }
return isTimeInRange(parsed, timeMin, timeMax);
}, [timePendingInput, hasSeconds, timeMin, timeMax]);
@@ -493,7 +510,9 @@ export function XDSDateTimePicker({
// --- Unified change handler ---
const fireChange = useCallback(
(newValue: ISODateTimeString | undefined) => {
- if (isBusy) return;
+ if (isBusy) {
+ return;
+ }
onChange(newValue);
if (changeAction) {
startTransition(async () => {
@@ -577,7 +596,9 @@ export function XDSDateTimePicker({
);
const commitDatePendingInput = useCallback(() => {
- if (datePendingInput === null) return;
+ if (datePendingInput === null) {
+ return;
+ }
if (!datePendingInput.trim()) {
if (value !== undefined) {
@@ -634,7 +655,9 @@ export function XDSDateTimePicker({
) {
if (valueParts.date) {
const combined = combineDateTime(valueParts.date, parsed);
- if (combined) fireChange(combined);
+ if (combined) {
+ fireChange(combined);
+ }
}
}
},
@@ -652,7 +675,9 @@ export function XDSDateTimePicker({
const handleTimeBlur = useCallback(() => {
setIsTimeFocused(false);
- if (timePendingInput === null) return;
+ if (timePendingInput === null) {
+ return;
+ }
if (!timePendingInput.trim()) {
// Empty time: revert display to previous value (don't emit partial datetime)
@@ -664,7 +689,9 @@ export function XDSDateTimePicker({
if (parsed && isTimeInRange(parsed, timeMin, timeMax)) {
if (parsed !== valueParts.time && valueParts.date) {
const combined = combineDateTime(valueParts.date, parsed);
- if (combined) fireChange(combined);
+ if (combined) {
+ fireChange(combined);
+ }
}
}
setTimePendingInput(null);
@@ -693,7 +720,9 @@ export function XDSDateTimePicker({
if (isTimeInRange(newTime, timeMin, timeMax) && valueParts.date) {
const combined = combineDateTime(valueParts.date, newTime);
- if (combined) fireChange(combined);
+ if (combined) {
+ fireChange(combined);
+ }
}
}
},
diff --git a/packages/core/src/Dialog/XDSDialog.tsx b/packages/core/src/Dialog/XDSDialog.tsx
index 58705ab735..847a43c757 100644
--- a/packages/core/src/Dialog/XDSDialog.tsx
+++ b/packages/core/src/Dialog/XDSDialog.tsx
@@ -216,7 +216,9 @@ const dynamicStyles = stylex.create({
* Format position value - numbers become pixels, strings pass through, undefined becomes null
*/
function formatPosition(value: number | string | undefined): string | null {
- if (value === undefined) return null;
+ if (value === undefined) {
+ return null;
+ }
return typeof value === 'number' ? `${value}px` : value;
}
@@ -366,9 +368,13 @@ export function XDSDialog({
// Handle open/close state — skip for inline rendering
useEffect(() => {
- if (isInline) return;
+ if (isInline) {
+ return;
+ }
const dialog = dialogRef.current;
- if (!dialog) return;
+ if (!dialog) {
+ return;
+ }
if (isOpen) {
// Capture the currently focused element as the trigger — used for
@@ -413,9 +419,13 @@ export function XDSDialog({
// Handle Escape key — skip for inline rendering
useEffect(() => {
- if (isInline) return;
+ if (isInline) {
+ return;
+ }
const dialog = dialogRef.current;
- if (!dialog || !isOpen) return;
+ if (!dialog || !isOpen) {
+ return;
+ }
const handleKeyDown = (event: KeyboardEvent) => {
if (event.key === 'Escape') {
@@ -495,7 +505,9 @@ export function XDSDialog({
// --- Inline rendering path (for documentation previews) ---
if (isInline) {
- if (!isOpen) return null;
+ if (!isOpen) {
+ return null;
+ }
return (
<div
diff --git a/packages/core/src/Dialog/useXDSImperativeDialog.tsx b/packages/core/src/Dialog/useXDSImperativeDialog.tsx
index 840e3b9f0c..88df47ce87 100644
--- a/packages/core/src/Dialog/useXDSImperativeDialog.tsx
+++ b/packages/core/src/Dialog/useXDSImperativeDialog.tsx
@@ -63,7 +63,9 @@ export function useXDSImperativeDialog(
const show = useCallback(
(newContent: ReactNode, newOptions?: DialogOptions) => {
setContent(newContent);
- if (newOptions) setOptions(prev => ({...prev, ...newOptions}));
+ if (newOptions) {
+ setOptions(prev => ({...prev, ...newOptions}));
+ }
setIsOpen(true);
},
[],
@@ -78,7 +80,9 @@ export function useXDSImperativeDialog(
<XDSDialog
isOpen={isOpen}
onOpenChange={open => {
- if (!open) setIsOpen(false);
+ if (!open) {
+ setIsOpen(false);
+ }
}}
{...(defaultOptions ?? {})}
{...(options ?? {})}>
diff --git a/packages/core/src/DropdownMenu/XDSDropdownMenuItem.tsx b/packages/core/src/DropdownMenu/XDSDropdownMenuItem.tsx
index 6a1cfb5d90..2600e88c00 100644
--- a/packages/core/src/DropdownMenu/XDSDropdownMenuItem.tsx
+++ b/packages/core/src/DropdownMenu/XDSDropdownMenuItem.tsx
@@ -134,7 +134,9 @@ export function XDSDropdownMenuItem({
const menuSize = ctx?.menuSize ?? 'md';
const handleClick = useCallback(() => {
- if (isDisabled || !onClick) return;
+ if (isDisabled || !onClick) {
+ return;
+ }
onClick();
ctx?.closeMenu();
}, [isDisabled, onClick, ctx]);
diff --git a/packages/core/src/FileInput/XDSFileInput.tsx b/packages/core/src/FileInput/XDSFileInput.tsx
index 554efce1c9..5115c558aa 100644
--- a/packages/core/src/FileInput/XDSFileInput.tsx
+++ b/packages/core/src/FileInput/XDSFileInput.tsx
@@ -48,8 +48,12 @@ import {xdsClassName, mergeProps} from '../utils';
import {XDSBaseProps} from '../XDSBaseProps';
function formatFileSize(bytes: number): string {
- if (bytes < 1024) return `${bytes} B`;
- if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
+ if (bytes < 1024) {
+ return `${bytes} B`;
+ }
+ if (bytes < 1024 * 1024) {
+ return `${(bytes / 1024).toFixed(1)} KB`;
+ }
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
}
@@ -444,7 +448,9 @@ export function XDSFileInput({
const handleFiles = useCallback(
(fileList: File[]) => {
- if (isDisabled) return;
+ if (isDisabled) {
+ return;
+ }
const {valid, errors} = validateFiles(
fileList,
@@ -559,7 +565,9 @@ export function XDSFileInput({
e.preventDefault();
e.stopPropagation();
setIsDragOver(false);
- if (isDisabled || mode !== 'dropzone') return;
+ if (isDisabled || mode !== 'dropzone') {
+ return;
+ }
const fileList = Array.from(e.dataTransfer.files);
if (fileList.length > 0) {
handleFiles(fileList);
diff --git a/packages/core/src/HoverCard/XDSHoverCard.tsx b/packages/core/src/HoverCard/XDSHoverCard.tsx
index 3512278663..7d3204df1c 100644
--- a/packages/core/src/HoverCard/XDSHoverCard.tsx
+++ b/packages/core/src/HoverCard/XDSHoverCard.tsx
@@ -203,13 +203,19 @@ export function XDSHoverCard({
// For element children with display:contents, attach ref to first child
useIsomorphicLayoutEffect(() => {
- if (textOnly) return; // Skip for text-only (ref is on wrapper)
+ if (textOnly) {
+ return;
+ } // Skip for text-only (ref is on wrapper)
const wrapper = wrapperRef.current;
- if (!wrapper) return;
+ if (!wrapper) {
+ return;
+ }
const firstChild = wrapper.firstElementChild as HTMLElement | null;
- if (!firstChild) return;
+ if (!firstChild) {
+ return;
+ }
// Use combined ref for position + interaction
hoverCard.ref(firstChild);
diff --git a/packages/core/src/HoverCard/useXDSHoverCard.tsx b/packages/core/src/HoverCard/useXDSHoverCard.tsx
index 64b4fa3014..d856707dce 100644
--- a/packages/core/src/HoverCard/useXDSHoverCard.tsx
+++ b/packages/core/src/HoverCard/useXDSHoverCard.tsx
@@ -287,7 +287,9 @@ export function useXDSHoverCard(
// Schedule show with delay (suppressed when isOpen is false)
const scheduleShow = useCallback(() => {
- if (!isEnabled || isOpen === false) return;
+ if (!isEnabled || isOpen === false) {
+ return;
+ }
clearTimeouts();
showTimeoutRef.current = setTimeout(() => {
layer.show();
@@ -296,7 +298,9 @@ export function useXDSHoverCard(
// Schedule hide with delay (suppressed when isOpen is true)
const scheduleHide = useCallback(() => {
- if (isOpen === true) return;
+ if (isOpen === true) {
+ return;
+ }
clearTimeouts();
hideTimeoutRef.current = setTimeout(() => {
// Don't hide if hovering content
@@ -316,7 +320,9 @@ export function useXDSHoverCard(
}, [scheduleHide]);
const handleFocusIn = useCallback(() => {
- if (!isEnabled) return;
+ if (!isEnabled) {
+ return;
+ }
// Skip showing if we're in the middle of an Escape dismiss
if (isEscapeDismissingRef.current) {
isEscapeDismissingRef.current = false;
@@ -427,7 +433,9 @@ export function useXDSHoverCard(
// Controlled open state — overrides hover/focus triggers
useEffect(() => {
- if (isOpen === undefined) return;
+ if (isOpen === undefined) {
+ return;
+ }
if (isOpen) {
clearTimeouts();
layer.show();
diff --git a/packages/core/src/Kbd/XDSKbd.tsx b/packages/core/src/Kbd/XDSKbd.tsx
index a2a44a05d6..0736a6a3e0 100644
--- a/packages/core/src/Kbd/XDSKbd.tsx
+++ b/packages/core/src/Kbd/XDSKbd.tsx
@@ -92,7 +92,9 @@ function getKeyDisplay(key: string, isMac: boolean): string {
* falls back to navigator.platform (deprecated but universally supported).
*/
function detectMac(): boolean {
- if (typeof navigator === 'undefined') return false;
+ if (typeof navigator === 'undefined') {
+ return false;
+ }
// Prefer User-Agent Client Hints API (not deprecated)
const uaData = 'userAgentData' in navigator ? navigator.userAgentData : null;
if (uaData && typeof uaData === 'object' && 'platform' in uaData) {
diff --git a/packages/core/src/Layer/useXDSLayer.tsx b/packages/core/src/Layer/useXDSLayer.tsx
index 42deeb082c..10bc6f260e 100644
--- a/packages/core/src/Layer/useXDSLayer.tsx
+++ b/packages/core/src/Layer/useXDSLayer.tsx
@@ -244,14 +244,22 @@ function getPositionArea(
// For above/below, alignment is horizontal
if (placement === 'above' || placement === 'below') {
- if (alignment === 'start') return `${cssPlacement} span-right`;
- if (alignment === 'end') return `${cssPlacement} span-left`;
+ if (alignment === 'start') {
+ return `${cssPlacement} span-right`;
+ }
+ if (alignment === 'end') {
+ return `${cssPlacement} span-left`;
+ }
return cssPlacement; // center
}
// For start/end, alignment is vertical
- if (alignment === 'start') return `${cssPlacement} span-bottom`;
- if (alignment === 'end') return `${cssPlacement} span-top`;
+ if (alignment === 'start') {
+ return `${cssPlacement} span-bottom`;
+ }
+ if (alignment === 'end') {
+ return `${cssPlacement} span-top`;
+ }
return `${cssPlacement} center`;
}
diff --git a/packages/core/src/List/XDSListItem.tsx b/packages/core/src/List/XDSListItem.tsx
index 18cdcf71d8..ca2d052b3a 100644
--- a/packages/core/src/List/XDSListItem.tsx
+++ b/packages/core/src/List/XDSListItem.tsx
@@ -377,10 +377,14 @@ export function XDSListItem({
);
const handleContainerClick = (e: React.MouseEvent) => {
- if (isDisabled) return;
+ if (isDisabled) {
+ return;
+ }
const target = e.target as HTMLElement;
// Don't fire onClick if click originated from an interactive child
- if (target.closest('button, a, input, select, textarea')) return;
+ if (target.closest('button, a, input, select, textarea')) {
+ return;
+ }
onClick?.(e);
};
diff --git a/packages/core/src/Markdown/XDSMarkdown.tsx b/packages/core/src/Markdown/XDSMarkdown.tsx
index b58d5572b3..44b103876d 100644
--- a/packages/core/src/Markdown/XDSMarkdown.tsx
+++ b/packages/core/src/Markdown/XDSMarkdown.tsx
@@ -471,9 +471,14 @@ function countBlockTextLength(nodes: BlockNode[]): number {
}
break;
case 'table':
- for (const h of node.headers) len += countInlineTextLength(h.children);
- for (const row of node.rows)
- for (const cell of row) len += countInlineTextLength(cell.children);
+ for (const h of node.headers) {
+ len += countInlineTextLength(h.children);
+ }
+ for (const row of node.rows) {
+ for (const cell of row) {
+ len += countInlineTextLength(cell.children);
+ }
+ }
break;
}
}
@@ -497,8 +502,12 @@ const DANGEROUS_URL_PATTERN = /^(javascript|data|vbscript):/i;
function sanitizeUrl(url: string): string | null {
const trimmed = url.trim();
- if (trimmed.length === 0) return null;
- if (DANGEROUS_URL_PATTERN.test(trimmed)) return null;
+ if (trimmed.length === 0) {
+ return null;
+ }
+ if (DANGEROUS_URL_PATTERN.test(trimmed)) {
+ return null;
+ }
return trimmed;
}
@@ -544,7 +553,9 @@ function applyInlinePlugins(
let end: number;
if (plugin.getEndIndex) {
const result = plugin.getEndIndex(text, m);
- if (result === false) continue;
+ if (result === false) {
+ continue;
+ }
end = result;
} else {
end = m.index + m[0].length;
@@ -622,7 +633,9 @@ function wrapTextWithFade(
const startOffset = cursor.offset;
cursor.offset += content.length;
- if (!cursor.active) return content;
+ if (!cursor.active) {
+ return content;
+ }
if (startOffset >= cursor.boundary) {
// Entirely new text
return (
@@ -871,10 +884,13 @@ function renderInline(
}
case 'image': {
const safeSrc = sanitizeUrl(node.src);
- if (safeSrc == null) return <span key={index}>[{node.alt}]</span>;
+ if (safeSrc == null) {
+ return <span key={index}>[{node.alt}]</span>;
+ }
const ImageComp = components?.image;
- if (ImageComp)
+ if (ImageComp) {
return <ImageComp key={index} src={safeSrc} alt={node.alt} />;
+ }
return (
<img
key={index}
@@ -987,7 +1003,9 @@ function computeTableColumnMinWidths(node: {
for (const row of node.rows) {
if (row[colIdx]) {
const len = countInlineTextLength(row[colIdx].children);
- if (len > maxLen) maxLen = len;
+ if (len > maxLen) {
+ maxLen = len;
+ }
}
}
return maxLen <= 6 ? 60 : maxLen <= 15 ? 80 : 120;
@@ -1040,12 +1058,13 @@ function renderBlock(
),
);
const HeadingComp = components?.heading;
- if (HeadingComp)
+ if (HeadingComp) {
return (
<HeadingComp key={index} level={level}>
{headingChildren}
</HeadingComp>
);
+ }
const Tag = `h${level}` as const;
return (
<Tag
@@ -1081,8 +1100,9 @@ function renderBlock(
),
);
const ParagraphComp = components?.paragraph;
- if (ParagraphComp)
+ if (ParagraphComp) {
return <ParagraphComp key={index}>{paraChildren}</ParagraphComp>;
+ }
return (
<p
key={index}
@@ -1105,7 +1125,7 @@ function renderBlock(
// Track codeblock content in cursor for accurate character counting
cursor.offset += node.content.length;
const CodeBlockComp = components?.code;
- if (CodeBlockComp)
+ if (CodeBlockComp) {
return (
<CodeBlockComp
key={index}
@@ -1113,6 +1133,7 @@ function renderBlock(
language={node.language}
/>
);
+ }
return (
<div
key={index}
@@ -1459,7 +1480,9 @@ function renderBlock(
}
case 'hr': {
const HrComp = components?.hr;
- if (HrComp) return <HrComp key={index} />;
+ if (HrComp) {
+ return <HrComp key={index} />;
+ }
return (
<hr
key={index}
diff --git a/packages/core/src/Markdown/incremental.test.ts b/packages/core/src/Markdown/incremental.test.ts
index d81e4bc9dc..fe3b76c448 100644
--- a/packages/core/src/Markdown/incremental.test.ts
+++ b/packages/core/src/Markdown/incremental.test.ts
@@ -382,9 +382,14 @@ describe('streaming end-to-end: no raw syntax visible', () => {
}
break;
case 'table':
- for (const h of block.headers) text += extractInlineText(h.children);
- for (const row of block.rows)
- for (const cell of row) text += extractInlineText(cell.children);
+ for (const h of block.headers) {
+ text += extractInlineText(h.children);
+ }
+ for (const row of block.rows) {
+ for (const cell of row) {
+ text += extractInlineText(cell.children);
+ }
+ }
break;
}
}
diff --git a/packages/core/src/Markdown/parser.ts b/packages/core/src/Markdown/parser.ts
index e84527a9b8..82f9127dcb 100644
--- a/packages/core/src/Markdown/parser.ts
+++ b/packages/core/src/Markdown/parser.ts
@@ -49,17 +49,22 @@ export type TableAlignment = 'left' | 'center' | 'right' | null;
function findClosingParen(text: string, start: number): number {
let depth = 1;
for (let index = start; index < text.length; index++) {
- if (text[index] === '(') depth++;
- else if (text[index] === ')') {
+ if (text[index] === '(') {
+ depth++;
+ } else if (text[index] === ')') {
depth--;
- if (depth === 0) return index;
+ if (depth === 0) {
+ return index;
+ }
}
}
return -1;
}
function isWordChar(ch: string | undefined): boolean {
- if (ch == null) return false;
+ if (ch == null) {
+ return false;
+ }
return /\w/.test(ch);
}
@@ -76,11 +81,17 @@ function matchFullwidthCitation(
i: number,
sourceIds: ReadonlySet<string> | undefined,
): {sourceId: string; end: number} | null {
- if (!sourceIds || text[i] !== '\u3010') return null;
+ if (!sourceIds || text[i] !== '\u3010') {
+ return null;
+ }
const closeIndex = text.indexOf('\u3011', i + 1);
- if (closeIndex === -1) return null;
+ if (closeIndex === -1) {
+ return null;
+ }
const id = text.slice(i + 1, closeIndex);
- if (id.length === 0 || !sourceIds.has(id)) return null;
+ if (id.length === 0 || !sourceIds.has(id)) {
+ return null;
+ }
return {sourceId: id, end: closeIndex + 1};
}
@@ -93,12 +104,20 @@ function matchBracketCitation(
i: number,
sourceIds: ReadonlySet<string> | undefined,
): {sourceId: string; end: number} | null {
- if (!sourceIds || text[i] !== '[') return null;
+ if (!sourceIds || text[i] !== '[') {
+ return null;
+ }
const closeIndex = text.indexOf(']', i + 1);
- if (closeIndex === -1) return null;
- if (text[closeIndex + 1] === '(') return null;
+ if (closeIndex === -1) {
+ return null;
+ }
+ if (text[closeIndex + 1] === '(') {
+ return null;
+ }
const id = text.slice(i + 1, closeIndex);
- if (id.length === 0 || !sourceIds.has(id)) return null;
+ if (id.length === 0 || !sourceIds.has(id)) {
+ return null;
+ }
return {sourceId: id, end: closeIndex + 1};
}
@@ -275,7 +294,9 @@ export function parseInline(
// --- Plain text (with line-break detection) ---
let end = i + 1;
- while (end < text.length && !'*_~`[!\\\n\u3010'.includes(text[end])) end++;
+ while (end < text.length && !'*_~`[!\\\n\u3010'.includes(text[end])) {
+ end++;
+ }
const content = text.slice(i, end);
@@ -285,8 +306,11 @@ export function parseInline(
if (content.length - trimmed.length >= 2) {
if (trimmed.length > 0) {
const last = nodes[nodes.length - 1];
- if (last?.type === 'text') last.content += trimmed;
- else nodes.push({type: 'text', content: trimmed});
+ if (last?.type === 'text') {
+ last.content += trimmed;
+ } else {
+ nodes.push({type: 'text', content: trimmed});
+ }
}
nodes.push({type: 'break'});
i = end + 1;
@@ -295,8 +319,11 @@ export function parseInline(
}
const last = nodes[nodes.length - 1];
- if (last?.type === 'text') last.content += content;
- else nodes.push({type: 'text', content});
+ if (last?.type === 'text') {
+ last.content += content;
+ } else {
+ nodes.push({type: 'text', content});
+ }
i = end;
}
return nodes;
@@ -308,27 +335,39 @@ export function parseInline(
function getIndent(line: string): number {
let count = 0;
- while (count < line.length && line[count] === ' ') count++;
+ while (count < line.length && line[count] === ' ') {
+ count++;
+ }
return count;
}
/** HR: 3+ identical markers (-, *, _) optionally separated by spaces. */
function isHorizontalRule(line: string): boolean {
const trimmed = line.trim();
- if (trimmed.length < 3) return false;
+ if (trimmed.length < 3) {
+ return false;
+ }
const stripped = trimmed.replace(/ /g, '');
- if (stripped.length < 3) return false;
+ if (stripped.length < 3) {
+ return false;
+ }
const ch = stripped[0];
- if (ch !== '-' && ch !== '*' && ch !== '_') return false;
+ if (ch !== '-' && ch !== '*' && ch !== '_') {
+ return false;
+ }
for (let idx = 1; idx < stripped.length; idx++) {
- if (stripped[idx] !== ch) return false;
+ if (stripped[idx] !== ch) {
+ return false;
+ }
}
return true;
}
/** GFM separator row: cells contain only dashes/colons. */
function isTableSeparator(line: string): boolean {
- if (!line.includes('|')) return false;
+ if (!line.includes('|')) {
+ return false;
+ }
const cells = line.split('|').map(cell => cell.trim());
const nonEmpty = cells.filter(cell => cell.length > 0);
return nonEmpty.length > 0 && nonEmpty.every(cell => /^:?-+:?$/.test(cell));
@@ -340,13 +379,27 @@ function isTableSeparator(line: string): boolean {
* to avoid ReDoS.
*/
function isBlockStart(line: string): boolean {
- if (/^#{1,6} /.test(line)) return true;
- if (/^(`{3,}|~{3,})/.test(line)) return true;
- if (isHorizontalRule(line)) return true;
- if (line.startsWith('> ') || line === '>') return true;
- if (/^ {0,9}[-*+] /.test(line)) return true;
- if (/^ {0,9}\d+\. /.test(line)) return true;
- if (line.includes('|')) return true;
+ if (/^#{1,6} /.test(line)) {
+ return true;
+ }
+ if (/^(`{3,}|~{3,})/.test(line)) {
+ return true;
+ }
+ if (isHorizontalRule(line)) {
+ return true;
+ }
+ if (line.startsWith('> ') || line === '>') {
+ return true;
+ }
+ if (/^ {0,9}[-*+] /.test(line)) {
+ return true;
+ }
+ if (/^ {0,9}\d+\. /.test(line)) {
+ return true;
+ }
+ if (line.includes('|')) {
+ return true;
+ }
return false;
}
@@ -355,10 +408,16 @@ function splitTableRow(line: string): string[] {
let end = line.length;
if (line[0] === '|') {
start = 1;
- while (start < end && line[start] === ' ') start++;
+ while (start < end && line[start] === ' ') {
+ start++;
+ }
+ }
+ while (end > start && line[end - 1] === ' ') {
+ end--;
+ }
+ if (end > start && line[end - 1] === '|') {
+ end--;
}
- while (end > start && line[end - 1] === ' ') end--;
- if (end > start && line[end - 1] === '|') end--;
return line
.slice(start, end)
.split('|')
@@ -668,7 +727,9 @@ export function trimStreamingArtifacts(input: string): string {
// Find trailing unclosed backticks
let end = tail.length;
- while (end > 0 && tail[end - 1] === '`') end--;
+ while (end > 0 && tail[end - 1] === '`') {
+ end--;
+ }
if (end < tail.length && end > 0) {
// There are trailing backticks — check if they opened inline code
const ticks = tail.length - end;
@@ -682,7 +743,9 @@ export function trimStreamingArtifacts(input: string): string {
// Find trailing unclosed bold/italic markers (*)
// First check trailing stars (no content after them yet):
end = tail.length;
- while (end > 0 && tail[end - 1] === '*') end--;
+ while (end > 0 && tail[end - 1] === '*') {
+ end--;
+ }
if (end < tail.length && end > 0) {
const stars = tail.length - end;
if (stars <= 3) {
@@ -716,7 +779,9 @@ export function trimStreamingArtifacts(input: string): string {
const positions: number[] = [];
while (true) {
const idx = tail.indexOf('~~', searchFrom);
- if (idx === -1) break;
+ if (idx === -1) {
+ break;
+ }
positions.push(idx);
count++;
searchFrom = idx + 2;
diff --git a/packages/core/src/MetadataList/XDSMetadataList.tsx b/packages/core/src/MetadataList/XDSMetadataList.tsx
index b206a803aa..6713c161dd 100644
--- a/packages/core/src/MetadataList/XDSMetadataList.tsx
+++ b/packages/core/src/MetadataList/XDSMetadataList.tsx
@@ -222,7 +222,9 @@ export function XDSMetadataList({
// Determine grid style based on columns and label position
const getGridStyle = () => {
- if (isHorizontal) return styles.horizontal;
+ if (isHorizontal) {
+ return styles.horizontal;
+ }
const isStacked = labelConfig.position === 'top';
if (isStacked) {
return columns === 'single' || columns === 1
diff --git a/packages/core/src/MobileNav/XDSMobileNav.tsx b/packages/core/src/MobileNav/XDSMobileNav.tsx
index c7467e09d1..113b6ed9d2 100644
--- a/packages/core/src/MobileNav/XDSMobileNav.tsx
+++ b/packages/core/src/MobileNav/XDSMobileNav.tsx
@@ -328,7 +328,9 @@ export function XDSMobileNav({
// close() is delayed so the slide-out transition can play.
useEffect(() => {
const dialog = dialogRef.current;
- if (!dialog) return;
+ if (!dialog) {
+ return;
+ }
if (closeTimeoutRef.current) {
clearTimeout(closeTimeoutRef.current);
diff --git a/packages/core/src/MultiSelector/XDSMultiSelector.tsx b/packages/core/src/MultiSelector/XDSMultiSelector.tsx
index 9413e9b480..051d14238f 100644
--- a/packages/core/src/MultiSelector/XDSMultiSelector.tsx
+++ b/packages/core/src/MultiSelector/XDSMultiSelector.tsx
@@ -615,7 +615,9 @@ export function XDSMultiSelector<T extends XDSMultiSelectorOptionType>({
// Filter items by search query
const filteredItems = useMemo(() => {
- if (!searchQuery) return selectableItems;
+ if (!searchQuery) {
+ return selectableItems;
+ }
const query = searchQuery.toLowerCase();
return selectableItems.filter(item =>
(item.label ?? item.value).toLowerCase().includes(query),
@@ -645,7 +647,9 @@ export function XDSMultiSelector<T extends XDSMultiSelectorOptionType>({
let pendingFlat: XDSMultiSelectorOptionData[] = [];
const flushFlat = () => {
- if (pendingFlat.length === 0) return;
+ if (pendingFlat.length === 0) {
+ return;
+ }
const selected = pendingFlat.filter(item => selectedSet.has(item.value));
const unselected = pendingFlat.filter(
item => !selectedSet.has(item.value),
@@ -900,7 +904,9 @@ export function XDSMultiSelector<T extends XDSMultiSelectorOptionType>({
// Render search input
const renderSearch = useCallback(() => {
- if (!hasSearch) return null;
+ if (!hasSearch) {
+ return null;
+ }
return (
<div {...stylex.props(styles.searchWrapper)}>
<input
diff --git a/packages/core/src/MultiSelector/hooks.ts b/packages/core/src/MultiSelector/hooks.ts
index c10466d47a..75f99025c5 100644
--- a/packages/core/src/MultiSelector/hooks.ts
+++ b/packages/core/src/MultiSelector/hooks.ts
@@ -74,7 +74,9 @@ export function useMultiCombobox({
}, [onClose]);
const onTriggerClick = useCallback(() => {
- if (isDisabled) return;
+ if (isDisabled) {
+ return;
+ }
if (isOpen) {
closeAndReset();
} else {
@@ -96,7 +98,9 @@ export function useMultiCombobox({
const onKeyDown = useCallback(
(e: React.KeyboardEvent) => {
- if (isDisabled) return;
+ if (isDisabled) {
+ return;
+ }
const enabledIndices = getEnabledIndices();
diff --git a/packages/core/src/NavMenu/XDSNavHeadingMenuItem.tsx b/packages/core/src/NavMenu/XDSNavHeadingMenuItem.tsx
index a5ca994fbf..a8c8cbb043 100644
--- a/packages/core/src/NavMenu/XDSNavHeadingMenuItem.tsx
+++ b/packages/core/src/NavMenu/XDSNavHeadingMenuItem.tsx
@@ -124,7 +124,9 @@ export function XDSNavHeadingMenuItem({
const size = ctx?.size ?? 'md';
const handleClick = useCallback(() => {
- if (isDisabled) return;
+ if (isDisabled) {
+ return;
+ }
onClick?.();
ctx?.closeMenu();
}, [isDisabled, onClick, ctx]);
diff --git a/packages/core/src/Overlay/XDSOverlay.tsx b/packages/core/src/Overlay/XDSOverlay.tsx
index a04381c155..cd4a541199 100644
--- a/packages/core/src/Overlay/XDSOverlay.tsx
+++ b/packages/core/src/Overlay/XDSOverlay.tsx
@@ -108,9 +108,13 @@ export function XDSOverlay({
// Only the component needs this — hook consumers have their own radius.
useIsomorphicLayoutEffect(() => {
const el = overlay.containerRef.current;
- if (!el) return;
+ if (!el) {
+ return;
+ }
const firstChild = el.firstElementChild as HTMLElement | null;
- if (!firstChild) return;
+ if (!firstChild) {
+ return;
+ }
const radius = getComputedStyle(firstChild).borderRadius;
if (radius && radius !== '0px') {
el.style.borderRadius = radius;
@@ -123,9 +127,11 @@ export function XDSOverlay({
(
overlay.containerRef as React.MutableRefObject<HTMLElement | null>
).current = node;
- if (typeof ref === 'function') ref(node);
- else if (ref != null)
+ if (typeof ref === 'function') {
+ ref(node);
+ } else if (ref != null) {
(ref as React.MutableRefObject<HTMLDivElement | null>).current = node;
+ }
}}
{...mergeProps(
xdsClassName('overlay'),
diff --git a/packages/core/src/Overlay/useXDSOverlay.tsx b/packages/core/src/Overlay/useXDSOverlay.tsx
index e2925e12d7..8cee065a14 100644
--- a/packages/core/src/Overlay/useXDSOverlay.tsx
+++ b/packages/core/src/Overlay/useXDSOverlay.tsx
@@ -42,12 +42,16 @@ import type {
// =============================================================================
function getIsTouchDevice(): boolean {
- if (typeof window === 'undefined') return false;
+ if (typeof window === 'undefined') {
+ return false;
+ }
return window.matchMedia('(hover: none)').matches;
}
function subscribeToHoverChange(callback: () => void): () => void {
- if (typeof window === 'undefined') return () => {};
+ if (typeof window === 'undefined') {
+ return () => {};
+ }
const mql = window.matchMedia('(hover: none)');
mql.addEventListener('change', callback);
return () => mql.removeEventListener('change', callback);
diff --git a/packages/core/src/Pagination/XDSPagination.tsx b/packages/core/src/Pagination/XDSPagination.tsx
index 4bf16350fe..2ae3e7b24e 100644
--- a/packages/core/src/Pagination/XDSPagination.tsx
+++ b/packages/core/src/Pagination/XDSPagination.tsx
@@ -368,7 +368,9 @@ export function XDSPagination({
}
const handlePageChange = (newPage: number) => {
- if (isDisabled || isPending) return;
+ if (isDisabled || isPending) {
+ return;
+ }
onChange(newPage);
if (changeAction) {
startTransition(async () => {
@@ -414,7 +416,9 @@ export function XDSPagination({
const renderIndicator = () => {
switch (variant) {
case 'pages': {
- if (computedTotalPages == null) return null;
+ if (computedTotalPages == null) {
+ return null;
+ }
const pageRange = generatePageRange(
page,
computedTotalPages,
@@ -457,7 +461,9 @@ export function XDSPagination({
}
case 'count': {
- if (totalItems == null) return null;
+ if (totalItems == null) {
+ return null;
+ }
return (
<span {...stylex.props(styles.infoText)}>
<XDSText type="body" size="sm" color="secondary">
@@ -468,7 +474,9 @@ export function XDSPagination({
}
case 'compact': {
- if (computedTotalPages == null) return null;
+ if (computedTotalPages == null) {
+ return null;
+ }
return (
<span {...stylex.props(styles.infoText)}>
<XDSText type="body" size="sm" color="secondary">
@@ -479,7 +487,9 @@ export function XDSPagination({
}
case 'dots': {
- if (computedTotalPages == null) return null;
+ if (computedTotalPages == null) {
+ return null;
+ }
return (
<div
{...stylex.props(styles.dotsContainer)}
diff --git a/packages/core/src/Popover/XDSPopover.tsx b/packages/core/src/Popover/XDSPopover.tsx
index c2b14c62d4..f27de25963 100644
--- a/packages/core/src/Popover/XDSPopover.tsx
+++ b/packages/core/src/Popover/XDSPopover.tsx
@@ -44,7 +44,9 @@ const BUTTON_SELECTOR = 'button, [role="button"]';
* or the first matching descendant.
*/
function findTriggerButton(el: HTMLElement): HTMLElement | null {
- if (el.matches(BUTTON_SELECTOR)) return el;
+ if (el.matches(BUTTON_SELECTOR)) {
+ return el;
+ }
return el.querySelector<HTMLElement>(BUTTON_SELECTOR);
}
@@ -290,10 +292,14 @@ export function XDSPopover({
// Shared handler for click events on the trigger button.
const handleTriggerClick = useCallback(() => {
- if (!isEnabled) return;
+ if (!isEnabled) {
+ return;
+ }
// If the popover was just closed by light dismiss (clicking outside),
// the trigger click fires in the same event — skip re-opening.
- if (Date.now() - lastHideTimeRef.current < 50) return;
+ if (Date.now() - lastHideTimeRef.current < 50) {
+ return;
+ }
popover.toggle();
}, [isEnabled, popover]);
@@ -355,10 +361,14 @@ export function XDSPopover({
// Sibling mode: attach to external anchorRef
useIsomorphicLayoutEffect(() => {
- if (!anchorRef) return;
+ if (!anchorRef) {
+ return;
+ }
const el = anchorRef.current;
- if (!el) return;
+ if (!el) {
+ return;
+ }
const button = findTriggerButton(el);
if (!button) {
@@ -367,7 +377,9 @@ export function XDSPopover({
'The popover trigger implements the button + dialog ARIA pattern.',
);
}
- if (!button) return;
+ if (!button) {
+ return;
+ }
// Set up anchor positioning on the anchorRef element itself
popover.triggerRef(el);
@@ -384,10 +396,14 @@ export function XDSPopover({
// Children mode: use wrapper as CSS anchor, find button inside for
// ARIA + event handlers.
useIsomorphicLayoutEffect(() => {
- if (anchorRef) return; // Skip if using anchorRef mode
+ if (anchorRef) {
+ return;
+ } // Skip if using anchorRef mode
const wrapper = wrapperRef.current;
- if (!wrapper) return;
+ if (!wrapper) {
+ return;
+ }
// Use the wrapper as the CSS anchor — it doesn't receive pressed-state
// transforms, so the anchor position stays stable.
@@ -401,7 +417,9 @@ export function XDSPopover({
'The popover trigger implements the button + dialog ARIA pattern.',
);
}
- if (!button) return;
+ if (!button) {
+ return;
+ }
const detach = attachTrigger(button);
@@ -413,7 +431,9 @@ export function XDSPopover({
// Sync controlled state
useIsomorphicLayoutEffect(() => {
- if (!isControlled) return;
+ if (!isControlled) {
+ return;
+ }
if (isOpen && !popover.isOpen) {
popover.show();
} else if (!isOpen && popover.isOpen) {
diff --git a/packages/core/src/PowerSearch/PowerSearchEditPopover.tsx b/packages/core/src/PowerSearch/PowerSearchEditPopover.tsx
index 4538a99fdf..1a1c5839e9 100644
--- a/packages/core/src/PowerSearch/PowerSearchEditPopover.tsx
+++ b/packages/core/src/PowerSearch/PowerSearchEditPopover.tsx
@@ -126,7 +126,9 @@ function isEditableFilterComplete(
config: InternalConfig,
ef: EditablePartialFilter,
): boolean {
- if (!ef.field || !ef.operator) return false;
+ if (!ef.field || !ef.operator) {
+ return false;
+ }
const op = config.getOperator(ef.field, ef.operator);
if (op?.value.type === 'nested') {
const subs = ef._subFilters ?? [];
@@ -141,7 +143,9 @@ function editableToCompleteFilter(
config: InternalConfig,
ef: EditablePartialFilter,
): PowerSearchFilter | null {
- if (!ef.operator) return null;
+ if (!ef.operator) {
+ return null;
+ }
const op = config.getOperator(ef.field, ef.operator);
if (op?.value.type === 'nested') {
const subs = (ef._subFilters ?? [])
@@ -153,7 +157,9 @@ function editableToCompleteFilter(
value: {type: 'nested', value: subs},
};
}
- if (ef.value == null) return null;
+ if (ef.value == null) {
+ return null;
+ }
return {
field: ef.field,
operator: ef.operator,
@@ -418,7 +424,9 @@ function NestedEditor({
(parentPath: number[]) => {
const fields = config.getVisibleFields();
const defaultField = fields[0];
- if (!defaultField) return;
+ if (!defaultField) {
+ return;
+ }
const defaultOp = config.getDefaultOperator(defaultField.key);
const op = defaultOp
@@ -595,7 +603,9 @@ export function PowerSearchEditPopover({
useEffect(() => {
const frame = requestAnimationFrame(() => {
const container = valueEditorRef.current;
- if (!container) return;
+ if (!container) {
+ return;
+ }
const focusable = container.querySelector<HTMLElement>(
'input:not([disabled]), button:not([disabled]), textarea:not([disabled]), select:not([disabled]), [tabindex]:not([tabindex="-1"])',
);
diff --git a/packages/core/src/PowerSearch/PowerSearchValueEditor.tsx b/packages/core/src/PowerSearch/PowerSearchValueEditor.tsx
index 4bcb8b0fa0..72a757f9bf 100644
--- a/packages/core/src/PowerSearch/PowerSearchValueEditor.tsx
+++ b/packages/core/src/PowerSearch/PowerSearchValueEditor.tsx
@@ -136,7 +136,9 @@ function StringListEditor({
onChange: (value: FilterValue) => void;
}) {
const currentValue: XDSSearchableItem[] = useMemo(() => {
- if (filterValue?.type !== 'string_list') return [];
+ if (filterValue?.type !== 'string_list') {
+ return [];
+ }
return filterValue.value.map(v => ({id: v, label: v}));
}, [filterValue]);
@@ -272,7 +274,9 @@ function DateAbsoluteEditor({
}) {
// Convert unixSeconds to ISO date string for the date input
const currentValue = useMemo(() => {
- if (filterValue?.type !== 'date_absolute') return undefined;
+ if (filterValue?.type !== 'date_absolute') {
+ return undefined;
+ }
const date = new Date(filterValue.unixSeconds * 1000);
return date.toISOString().split('T')[0] as ISODateString;
}, [filterValue]);
@@ -358,7 +362,9 @@ function DateRangeEditor({
onChange: (value: FilterValue) => void;
}) {
const startValue = useMemo(() => {
- if (filterValue?.type !== 'date_range') return undefined;
+ if (filterValue?.type !== 'date_range') {
+ return undefined;
+ }
const part = filterValue.value.start;
if (part.type === 'ABSOLUTE') {
return new Date(part.unixSeconds * 1000)
@@ -369,7 +375,9 @@ function DateRangeEditor({
}, [filterValue]);
const endValue = useMemo(() => {
- if (filterValue?.type !== 'date_range') return undefined;
+ if (filterValue?.type !== 'date_range') {
+ return undefined;
+ }
const part = filterValue.value.end;
if (part.type === 'ABSOLUTE') {
return new Date(part.unixSeconds * 1000)
@@ -486,7 +494,9 @@ function EnumListEditor({
const source = useMemo(() => createStaticSource(items), [items]);
const currentValue: XDSSearchableItem[] = useMemo(() => {
- if (filterValue?.type !== 'enum_list') return [];
+ if (filterValue?.type !== 'enum_list') {
+ return [];
+ }
return filterValue.value.map(v => {
const item = operatorValue.values.find(e => e.value === v);
return {id: v, label: item?.label ?? v};
@@ -533,7 +543,9 @@ function EntityListEditor({
// Preserve photo in auxiliaryData so it round-trips through the tokenizer (#1106).
const currentValue: XDSSearchableItem[] = useMemo(() => {
- if (filterValue?.type !== 'entity_list') return [];
+ if (filterValue?.type !== 'entity_list') {
+ return [];
+ }
return filterValue.value.map((entity: PowerSearchEntity) => ({
id: entity.id,
label: entity.label,
diff --git a/packages/core/src/PowerSearch/XDSPowerSearch.tsx b/packages/core/src/PowerSearch/XDSPowerSearch.tsx
index c7892088fb..fe5ed6bae5 100644
--- a/packages/core/src/PowerSearch/XDSPowerSearch.tsx
+++ b/packages/core/src/PowerSearch/XDSPowerSearch.tsx
@@ -164,7 +164,9 @@ function PowerSearchTokenValue({
case 'string_list': {
const items = filterValue.value;
- if (items.length === 0) return null;
+ if (items.length === 0) {
+ return null;
+ }
if (items.length === 1) {
return (
<span {...stylex.props(tokenValueStyles.value)}>
@@ -189,7 +191,9 @@ function PowerSearchTokenValue({
case 'enum_list': {
const items = filterValue.value;
- if (items.length === 0) return null;
+ if (items.length === 0) {
+ return null;
+ }
if (operatorValue.type === 'enum_list') {
const labels = items.map(v => getEnumLabel(operatorValue.values, v));
if (labels.length === 1) {
@@ -229,7 +233,9 @@ function PowerSearchTokenValue({
case 'entity_list': {
const entities = filterValue.value;
- if (entities.length === 0) return null;
+ if (entities.length === 0) {
+ return null;
+ }
if (entities.length === 1) {
return (
<span {...stylex.props(tokenValueStyles.value)}>
@@ -604,10 +610,14 @@ export function XDSPowerSearch({
) => {
if (change.type === 'add' && change.item) {
const auxData = change.item.auxiliaryData as PowerSearchAuxData;
- if (!auxData) return;
+ if (!auxData) {
+ return;
+ }
const field = config.getField(auxData.fieldKey);
- if (!field) return;
+ if (!field) {
+ return;
+ }
const operator = auxData.operatorKey
? config.getOperator(auxData.fieldKey, auxData.operatorKey)
@@ -660,10 +670,14 @@ export function XDSPowerSearch({
// Handle clicking a token to edit
const handleTokenClick = useCallback(
(index: number) => {
- if (isReadOnly || isDisabled) return;
+ if (isReadOnly || isDisabled) {
+ return;
+ }
const filter = filters[index];
- if (filter.isReadOnly) return;
+ if (filter.isReadOnly) {
+ return;
+ }
setPopoverState({
type: 'editing',
@@ -798,7 +812,9 @@ export function XDSPowerSearch({
const renderItem = useCallback(
(item: PowerSearchItem) => {
const auxData = item.auxiliaryData as PowerSearchAuxData | undefined;
- if (!auxData) return <XDSTypeaheadItem item={item} />;
+ if (!auxData) {
+ return <XDSTypeaheadItem item={item} />;
+ }
const field = config.getField(auxData.fieldKey);
let icon: React.ReactNode = null;
@@ -831,8 +847,9 @@ export function XDSPowerSearch({
// Resolve custom Editor override for the current popover filter
const EditorOverride = useMemo(() => {
- if (!popoverPartialFilter?.field || !popoverPartialFilter?.operator)
+ if (!popoverPartialFilter?.field || !popoverPartialFilter?.operator) {
return undefined;
+ }
const op = config.getOperator(
popoverPartialFilter.field,
popoverPartialFilter.operator,
@@ -842,7 +859,9 @@ export function XDSPowerSearch({
// Render popover content — either custom Editor or default
const popoverContent = useMemo(() => {
- if (!popoverPartialFilter) return null;
+ if (!popoverPartialFilter) {
+ return null;
+ }
const mode = popoverState.type === 'editing' ? 'edit' : 'create';
diff --git a/packages/core/src/PowerSearch/formatFilterValue.ts b/packages/core/src/PowerSearch/formatFilterValue.ts
index 652654cafc..88d101e267 100644
--- a/packages/core/src/PowerSearch/formatFilterValue.ts
+++ b/packages/core/src/PowerSearch/formatFilterValue.ts
@@ -19,7 +19,9 @@ import type {
import type {InternalConfig} from './useInternalConfig';
function truncate(str: string, maxLength: number): string {
- if (str.length <= maxLength) return str;
+ if (str.length <= maxLength) {
+ return str;
+ }
return str.slice(0, maxLength - 1) + '\u2026';
}
@@ -94,33 +96,53 @@ export function formatFilterValue(
case 'string_list': {
const items = filterValue.value;
- if (items.length === 0) return '';
- if (items.length === 1) return truncate(items[0], maxLength);
+ if (items.length === 0) {
+ return '';
+ }
+ if (items.length === 1) {
+ return truncate(items[0], maxLength);
+ }
const joined = items.join(', ');
- if (joined.length <= maxLength) return joined;
+ if (joined.length <= maxLength) {
+ return joined;
+ }
return `${items.length} items`;
}
case 'enum_list': {
const items = filterValue.value;
- if (items.length === 0) return '';
+ if (items.length === 0) {
+ return '';
+ }
if (operatorValue.type === 'enum_list') {
const labels = items.map(v => formatEnumLabel(v, operatorValue.values));
- if (labels.length === 1) return truncate(labels[0], maxLength);
+ if (labels.length === 1) {
+ return truncate(labels[0], maxLength);
+ }
const joined = labels.join(', ');
- if (joined.length <= maxLength) return joined;
+ if (joined.length <= maxLength) {
+ return joined;
+ }
return `${labels.length} items`;
}
- if (items.length === 1) return truncate(items[0], maxLength);
+ if (items.length === 1) {
+ return truncate(items[0], maxLength);
+ }
return `${items.length} items`;
}
case 'entity_list': {
const entities = filterValue.value;
- if (entities.length === 0) return '';
- if (entities.length === 1) return truncate(entities[0].label, maxLength);
+ if (entities.length === 0) {
+ return '';
+ }
+ if (entities.length === 1) {
+ return truncate(entities[0].label, maxLength);
+ }
const joined = entities.map(e => e.label).join(', ');
- if (joined.length <= maxLength) return joined;
+ if (joined.length <= maxLength) {
+ return joined;
+ }
return `${entities.length} entities`;
}
diff --git a/packages/core/src/PowerSearch/useInternalConfig.ts b/packages/core/src/PowerSearch/useInternalConfig.ts
index 077c0fa6ca..5205d2b799 100644
--- a/packages/core/src/PowerSearch/useInternalConfig.ts
+++ b/packages/core/src/PowerSearch/useInternalConfig.ts
@@ -58,7 +58,9 @@ export function useInternalConfig(config: PowerSearchConfig): InternalConfig {
getDefaultOperator(fieldKey: string) {
const field = fieldMap.get(fieldKey);
- if (!field) return undefined;
+ if (!field) {
+ return undefined;
+ }
if (field.defaultOperator) {
return operatorMap.get(fieldKey)?.get(field.defaultOperator);
}
diff --git a/packages/core/src/PowerSearch/usePowerSearchConfig.ts b/packages/core/src/PowerSearch/usePowerSearchConfig.ts
index e8ac264727..f33dc96231 100644
--- a/packages/core/src/PowerSearch/usePowerSearchConfig.ts
+++ b/packages/core/src/PowerSearch/usePowerSearchConfig.ts
@@ -375,9 +375,12 @@ function matchesFilter(
switch (filterValue.type) {
case 'empty': {
- if (operator === BooleanOps.IS_TRUE) return Boolean(fieldValue) === true;
- if (operator === BooleanOps.IS_FALSE)
+ if (operator === BooleanOps.IS_TRUE) {
+ return Boolean(fieldValue) === true;
+ }
+ if (operator === BooleanOps.IS_FALSE) {
return Boolean(fieldValue) === false;
+ }
return true;
}
@@ -408,8 +411,12 @@ function matchesFilter(
case 'date_absolute': {
const ts = toUnixSeconds(fieldValue as Date | number);
- if (operator === DateOps.BEFORE) return ts < filterValue.unixSeconds;
- if (operator === DateOps.AFTER) return ts > filterValue.unixSeconds;
+ if (operator === DateOps.BEFORE) {
+ return ts < filterValue.unixSeconds;
+ }
+ if (operator === DateOps.AFTER) {
+ return ts > filterValue.unixSeconds;
+ }
return true;
}
@@ -424,19 +431,23 @@ function matchesFilter(
}
case 'enum': {
- if (operator === EnumOps.IS)
+ if (operator === EnumOps.IS) {
return String(fieldValue) === filterValue.value;
- if (operator === EnumOps.IS_NOT)
+ }
+ if (operator === EnumOps.IS_NOT) {
return String(fieldValue) !== filterValue.value;
+ }
return true;
}
case 'enum_list': {
const sv = String(fieldValue);
- if (operator === EnumListOps.IS_ANY_OF)
+ if (operator === EnumListOps.IS_ANY_OF) {
return filterValue.value.includes(sv);
- if (operator === EnumListOps.IS_NONE_OF)
+ }
+ if (operator === EnumListOps.IS_NONE_OF) {
return !filterValue.value.includes(sv);
+ }
return true;
}
@@ -520,7 +531,9 @@ export function createPowerSearchConfig<
filters: ReadonlyArray<PowerSearchFilter>,
data: ReadonlyArray<T>,
): Array<T> {
- if (filters.length === 0) return [...data];
+ if (filters.length === 0) {
+ return [...data];
+ }
return data.filter(row =>
filters.every(f => matchesFilter(row as Record<string, unknown>, f)),
);
diff --git a/packages/core/src/PowerSearch/usePowerSearchSource.ts b/packages/core/src/PowerSearch/usePowerSearchSource.ts
index 387e250759..32fd5e8bc6 100644
--- a/packages/core/src/PowerSearch/usePowerSearchSource.ts
+++ b/packages/core/src/PowerSearch/usePowerSearchSource.ts
@@ -26,7 +26,9 @@ export function usePowerSearchSource(
return {
search(query: string): PowerSearchItem[] {
const lower = query.toLowerCase().trim();
- if (lower === '') return allItems;
+ if (lower === '') {
+ return allItems;
+ }
const results: PowerSearchItem[] = [];
const seen = new Set<string>();
@@ -89,7 +91,9 @@ export function usePowerSearchSource(
// and "title contains foobar" → Title contains "foobar"
// and "genre fiction" → Genre is "Fiction"
for (const field of config.getVisibleFields()) {
- if (field.isValueMatchAllowed === false) continue;
+ if (field.isValueMatchAllowed === false) {
+ continue;
+ }
const fieldLabel = field.label.toLowerCase();
diff --git a/packages/core/src/Resizable/XDSResizeHandle.tsx b/packages/core/src/Resizable/XDSResizeHandle.tsx
index ddcdb2e9f5..8c4627afcf 100644
--- a/packages/core/src/Resizable/XDSResizeHandle.tsx
+++ b/packages/core/src/Resizable/XDSResizeHandle.tsx
@@ -42,7 +42,9 @@ function resolveEffectiveSide(
isReversed: boolean,
isCollapsed: boolean,
): 'start' | 'end' | 'center' {
- if (pillPlacement !== 'auto') return pillPlacement;
+ if (pillPlacement !== 'auto') {
+ return pillPlacement;
+ }
const panelSide: 'start' | 'end' = isReversed ? 'end' : 'start';
if (isCollapsed) {
return panelSide === 'start' ? 'end' : 'start';
@@ -55,7 +57,9 @@ function resolveEffectiveSide(
* shifts ~2:1 toward the pill so users can reach the visible grip easily.
*/
function hitAreaBias(effectiveSide: 'start' | 'end' | 'center'): string {
- if (effectiveSide === 'center') return '50%';
+ if (effectiveSide === 'center') {
+ return '50%';
+ }
return effectiveSide === 'start' ? '66.67%' : '33.33%';
}
@@ -326,7 +330,9 @@ export function XDSResizeHandle({
const getRTLMultiplier = useCallback((): number => {
const el = handleRef.current;
- if (!el) return 1;
+ if (!el) {
+ return 1;
+ }
return getComputedStyle(el).direction === 'rtl' ? -1 : 1;
}, []);
@@ -335,7 +341,9 @@ export function XDSResizeHandle({
// --- Pointer drag ---
const handlePointerDown = useCallback(
(e: React.PointerEvent) => {
- if (isDisabled || !resizable) return;
+ if (isDisabled || !resizable) {
+ return;
+ }
e.preventDefault();
e.stopPropagation();
setIsDragging(true);
@@ -378,7 +386,9 @@ export function XDSResizeHandle({
// --- Keyboard ---
const handleKeyDown = useCallback(
(e: React.KeyboardEvent) => {
- if (isDisabled || !resizable) return;
+ if (isDisabled || !resizable) {
+ return;
+ }
const step = e.shiftKey ? KEYBOARD_LARGE_STEP : KEYBOARD_STEP;
const rtl = isHorizontal ? getRTLMultiplier() : 1;
@@ -433,7 +443,9 @@ export function XDSResizeHandle({
// --- Double-click collapse ---
const handleDoubleClick = useCallback(() => {
- if (isDisabled || !resizable || !resizable._collapsible) return;
+ if (isDisabled || !resizable || !resizable._collapsible) {
+ return;
+ }
resizable._onResizeStart();
resizable._onResizeMove(
resizable._isCollapsed ? resizable._minSizePx : -resizable._size,
@@ -464,9 +476,11 @@ export function XDSResizeHandle({
ref={node => {
(handleRef as React.MutableRefObject<HTMLDivElement | null>).current =
node;
- if (typeof ref === 'function') ref(node);
- else if (ref)
+ if (typeof ref === 'function') {
+ ref(node);
+ } else if (ref) {
(ref as React.MutableRefObject<HTMLDivElement | null>).current = node;
+ }
}}
role="separator"
aria-orientation={isHorizontal ? 'vertical' : 'horizontal'}
@@ -517,7 +531,9 @@ export function XDSResizeHandle({
onPointerDown={handlePointerDown}
onPointerEnter={() => setIsHovered(true)}
onPointerLeave={() => {
- if (!isDragging) setIsHovered(false);
+ if (!isDragging) {
+ setIsHovered(false);
+ }
}}
onKeyDown={handleKeyDown}
/>
diff --git a/packages/core/src/Resizable/useXDSResizable.ts b/packages/core/src/Resizable/useXDSResizable.ts
index 0008dbd748..695e317801 100644
--- a/packages/core/src/Resizable/useXDSResizable.ts
+++ b/packages/core/src/Resizable/useXDSResizable.ts
@@ -139,12 +139,16 @@ function clampSize(
}
function loadPersistedSize(key: string): number | null {
- if (typeof window === 'undefined') return null;
+ if (typeof window === 'undefined') {
+ return null;
+ }
try {
const raw = localStorage.getItem(STORAGE_PREFIX + key);
if (raw != null) {
const parsed = JSON.parse(raw);
- if (typeof parsed === 'number') return parsed;
+ if (typeof parsed === 'number') {
+ return parsed;
+ }
}
} catch {
/* ignore */
@@ -153,7 +157,9 @@ function loadPersistedSize(key: string): number | null {
}
function persistSize(key: string, size: number): void {
- if (typeof window === 'undefined') return;
+ if (typeof window === 'undefined') {
+ return;
+ }
try {
localStorage.setItem(STORAGE_PREFIX + key, JSON.stringify(size));
} catch {
@@ -162,8 +168,12 @@ function persistSize(key: string, size: number): void {
}
function resolveDefaultSize(defaultSize: number | string | undefined): number {
- if (defaultSize == null) return 250;
- if (typeof defaultSize === 'number') return defaultSize;
+ if (defaultSize == null) {
+ return 250;
+ }
+ if (typeof defaultSize === 'number') {
+ return defaultSize;
+ }
if (defaultSize.endsWith('%')) {
const pct = parseFloat(defaultSize);
if (!isNaN(pct)) {
@@ -213,7 +223,9 @@ function useSingleResizable(
}, [size, isCollapsed, autoSaveId]);
const collapse = useCallback(() => {
- if (!collapsible) return;
+ if (!collapsible) {
+ return;
+ }
preCollapseSizeRef.current = size;
setIsCollapsed(true);
setSize(0);
diff --git a/packages/core/src/SegmentedControl/XDSSegmentedControl.tsx b/packages/core/src/SegmentedControl/XDSSegmentedControl.tsx
index ebbb91fcf7..436a88adc3 100644
--- a/packages/core/src/SegmentedControl/XDSSegmentedControl.tsx
+++ b/packages/core/src/SegmentedControl/XDSSegmentedControl.tsx
@@ -134,17 +134,23 @@ export function XDSSegmentedControl({
const handleKeyDown = useCallback(
(e: React.KeyboardEvent) => {
- if (isDisabled) return;
+ if (isDisabled) {
+ return;
+ }
const container = containerRef.current;
- if (!container) return;
+ if (!container) {
+ return;
+ }
const items = Array.from(
container.querySelectorAll<HTMLButtonElement>(
'[role="radio"]:not([aria-disabled="true"])',
),
);
- if (items.length === 0) return;
+ if (items.length === 0) {
+ return;
+ }
const currentIndex = items.findIndex(
item => item === document.activeElement,
diff --git a/packages/core/src/SelectableCard/XDSSelectableCard.tsx b/packages/core/src/SelectableCard/XDSSelectableCard.tsx
index 57bce28936..fd607686e8 100644
--- a/packages/core/src/SelectableCard/XDSSelectableCard.tsx
+++ b/packages/core/src/SelectableCard/XDSSelectableCard.tsx
@@ -318,9 +318,11 @@ export function XDSSelectableCard({
<XDSCard
ref={(node: HTMLDivElement | null) => {
containerRef.current = node;
- if (typeof ref === 'function') ref(node);
- else if (ref != null)
+ if (typeof ref === 'function') {
+ ref(node);
+ } else if (ref != null) {
(ref as MutableRefObject<HTMLDivElement | null>).current = node;
+ }
}}
width={width}
height={height}
diff --git a/packages/core/src/Selector/XDSSelector.tsx b/packages/core/src/Selector/XDSSelector.tsx
index 320ba1ab56..7953231004 100644
--- a/packages/core/src/Selector/XDSSelector.tsx
+++ b/packages/core/src/Selector/XDSSelector.tsx
@@ -587,7 +587,9 @@ export function XDSSelector<T extends XDSSelectorOptionType>(
// Filter items by search query
const filteredItems = useMemo(() => {
- if (!searchQuery) return selectableItems;
+ if (!searchQuery) {
+ return selectableItems;
+ }
const query = searchQuery.toLowerCase();
return selectableItems.filter(item =>
(item.label ?? item.value).toLowerCase().includes(query),
@@ -701,7 +703,9 @@ export function XDSSelector<T extends XDSSelectorOptionType>(
// Render search input
const renderSearch = useCallback(() => {
- if (!hasSearch) return null;
+ if (!hasSearch) {
+ return null;
+ }
return (
<div {...stylex.props(styles.searchWrapper)}>
<input
diff --git a/packages/core/src/Selector/hooks.ts b/packages/core/src/Selector/hooks.ts
index 624e3fe7fa..39b87e4e95 100644
--- a/packages/core/src/Selector/hooks.ts
+++ b/packages/core/src/Selector/hooks.ts
@@ -192,7 +192,9 @@ export function useCombobox({
const selectItem = useCallback(
(item: XDSSelectorOptionData) => {
- if (item.disabled) return;
+ if (item.disabled) {
+ return;
+ }
onSelect?.(item.value);
closeAndReset();
},
@@ -200,7 +202,9 @@ export function useCombobox({
);
const onTriggerClick = useCallback(() => {
- if (isDisabled) return;
+ if (isDisabled) {
+ return;
+ }
if (isOpen) {
closeAndReset();
} else {
@@ -223,7 +227,9 @@ export function useCombobox({
const onKeyDown = useCallback(
(e: React.KeyboardEvent) => {
- if (isDisabled) return;
+ if (isDisabled) {
+ return;
+ }
const enabledIndices = getEnabledIndices();
diff --git a/packages/core/src/Selector/utils.ts b/packages/core/src/Selector/utils.ts
index a65ad580e0..9ff3d14c31 100644
--- a/packages/core/src/Selector/utils.ts
+++ b/packages/core/src/Selector/utils.ts
@@ -19,7 +19,9 @@ import type {
export function isOptionData(
option: XDSSelectorOptionType,
): option is XDSSelectorOptionData | string {
- if (typeof option === 'string') return true;
+ if (typeof option === 'string') {
+ return true;
+ }
return !('type' in option);
}
diff --git a/packages/core/src/SideNav/XDSSideNav.tsx b/packages/core/src/SideNav/XDSSideNav.tsx
index 03c2623294..1fbd0b3d78 100644
--- a/packages/core/src/SideNav/XDSSideNav.tsx
+++ b/packages/core/src/SideNav/XDSSideNav.tsx
@@ -456,9 +456,11 @@ export function XDSSideNav({
<nav
ref={node => {
navRef.current = node;
- if (typeof ref === 'function') ref(node);
- else if (ref)
+ if (typeof ref === 'function') {
+ ref(node);
+ } else if (ref) {
(ref as React.MutableRefObject<HTMLElement | null>).current = node;
+ }
}}
role="navigation"
aria-label="Side navigation"
diff --git a/packages/core/src/Slider/XDSSlider.tsx b/packages/core/src/Slider/XDSSlider.tsx
index 692b16a591..fb99acaf33 100644
--- a/packages/core/src/Slider/XDSSlider.tsx
+++ b/packages/core/src/Slider/XDSSlider.tsx
@@ -290,13 +290,17 @@ function clamp(val: number, min: number, max: number): number {
}
function snapToStep(val: number, min: number, step: number): number {
- if (step <= 0) return val;
+ if (step <= 0) {
+ return val;
+ }
const steps = Math.round((val - min) / step);
return min + steps * step;
}
function getPercent(val: number, min: number, max: number): number {
- if (max === min) return 0;
+ if (max === min) {
+ return 0;
+ }
return ((val - min) / (max - min)) * 100;
}
@@ -357,8 +361,12 @@ export function XDSSlider({ref, ...props}: XDSSliderProps) {
// Build aria-describedby
const describedByParts: string[] = [];
- if (description) describedByParts.push(descriptionID);
- if (status?.message) describedByParts.push(statusMessageID);
+ if (description) {
+ describedByParts.push(descriptionID);
+ }
+ if (status?.message) {
+ describedByParts.push(statusMessageID);
+ }
const ariaDescribedBy =
describedByParts.length > 0 ? describedByParts.join(' ') : undefined;
@@ -374,7 +382,9 @@ export function XDSSlider({ref, ...props}: XDSSliderProps) {
const getValueFromPosition = useCallback(
(clientX: number, clientY: number): number => {
const track = trackRef.current;
- if (!track) return min;
+ if (!track) {
+ return min;
+ }
const rect = track.getBoundingClientRect();
let percent: number;
@@ -393,7 +403,9 @@ export function XDSSlider({ref, ...props}: XDSSliderProps) {
const getClosestThumb = useCallback(
(newValue: number): number => {
- if (!isRange) return 0;
+ if (!isRange) {
+ return 0;
+ }
const [v0, v1] = values;
const d0 = Math.abs(newValue - v0);
const d1 = Math.abs(newValue - v1);
@@ -405,7 +417,9 @@ export function XDSSlider({ref, ...props}: XDSSliderProps) {
const updateValue = useCallback(
(thumbIndex: number, newVal: number) => {
- if (isDisabled) return;
+ if (isDisabled) {
+ return;
+ }
const clamped = clamp(snapToStep(newVal, min, step), min, max);
if (isRange) {
@@ -468,7 +482,9 @@ export function XDSSlider({ref, ...props}: XDSSliderProps) {
// Pointer handlers
const handlePointerDown = useCallback(
(e: PointerEvent<HTMLDivElement>) => {
- if (isDisabled) return;
+ if (isDisabled) {
+ return;
+ }
e.preventDefault();
// If the click originated from a mark element, snap to that mark's value
@@ -503,7 +519,9 @@ export function XDSSlider({ref, ...props}: XDSSliderProps) {
const handlePointerMove = useCallback(
(e: PointerEvent<HTMLDivElement>) => {
- if (draggingThumbRef.current === null || isDisabled) return;
+ if (draggingThumbRef.current === null || isDisabled) {
+ return;
+ }
const newVal = getValueFromPosition(e.clientX, e.clientY);
updateValue(draggingThumbRef.current, newVal);
},
@@ -524,7 +542,9 @@ export function XDSSlider({ref, ...props}: XDSSliderProps) {
// Keyboard handler
const handleKeyDown = useCallback(
(thumbIndex: number, e: KeyboardEvent<HTMLDivElement>) => {
- if (isDisabled) return;
+ if (isDisabled) {
+ return;
+ }
const currentVal = values[thumbIndex];
let newVal: number;
@@ -590,7 +610,9 @@ export function XDSSlider({ref, ...props}: XDSSliderProps) {
// Format display value
const displayValue = (val: number): string => {
- if (formatValue) return formatValue(val);
+ if (formatValue) {
+ return formatValue(val);
+ }
return String(val);
};
diff --git a/packages/core/src/Spinner/XDSSpinner.tsx b/packages/core/src/Spinner/XDSSpinner.tsx
index d0eaec4e7b..cd6825460a 100644
--- a/packages/core/src/Spinner/XDSSpinner.tsx
+++ b/packages/core/src/Spinner/XDSSpinner.tsx
@@ -156,10 +156,14 @@ export function XDSSpinner({
useEffect(() => {
const canvas = canvasRef.current;
- if (canvas == null) return;
+ if (canvas == null) {
+ return;
+ }
const context = canvas.getContext('2d');
- if (!context) return;
+ if (!context) {
+ return;
+ }
const {border, diameter} = SIZES[size];
const pixelRatio = window.devicePixelRatio || 1;
diff --git a/packages/core/src/Switch/XDSSwitch.tsx b/packages/core/src/Switch/XDSSwitch.tsx
index a14190ae09..734fbc8f45 100644
--- a/packages/core/src/Switch/XDSSwitch.tsx
+++ b/packages/core/src/Switch/XDSSwitch.tsx
@@ -336,8 +336,12 @@ export function XDSSwitch({
// Build aria-describedby from description and status message
// Only include descriptionID when the element actually renders
const describedByParts: string[] = [];
- if (description && !isLabelHidden) describedByParts.push(descriptionID);
- if (status?.message) describedByParts.push(statusMessageID);
+ if (description && !isLabelHidden) {
+ describedByParts.push(descriptionID);
+ }
+ if (status?.message) {
+ describedByParts.push(statusMessageID);
+ }
const ariaDescribedBy =
describedByParts.length > 0 ? describedByParts.join(' ') : undefined;
@@ -352,7 +356,9 @@ export function XDSSwitch({
disabled={isDisabled}
required={isRequired}
onChange={e => {
- if (isBusy) return;
+ if (isBusy) {
+ return;
+ }
const checked = e.target.checked;
onChange?.(checked, e);
if (changeAction && !e.defaultPrevented) {
diff --git a/packages/core/src/Table/XDSBaseTable.tsx b/packages/core/src/Table/XDSBaseTable.tsx
index ab2d9c34fc..9276138818 100644
--- a/packages/core/src/Table/XDSBaseTable.tsx
+++ b/packages/core/src/Table/XDSBaseTable.tsx
@@ -83,7 +83,9 @@ function applyPlugins<TPlugin, TProps, TArgs extends unknown[]>(
): TProps {
return plugins.reduce<TProps>((acc, plugin, index) => {
const transform = getter(plugin);
- if (!transform) return acc;
+ if (!transform) {
+ return acc;
+ }
try {
return transform(acc, ...args);
} catch (error) {
@@ -108,10 +110,16 @@ const EMPTY_PLUGINS: TablePlugin<Record<string, unknown>>[] = [];
* Used to stabilize the resolved columns array across renders.
*/
function areArraysShallowEqual<T>(a: T[], b: T[]): boolean {
- if (a === b) return true;
- if (a.length !== b.length) return false;
+ if (a === b) {
+ return true;
+ }
+ if (a.length !== b.length) {
+ return false;
+ }
for (let i = 0; i < a.length; i++) {
- if (a[i] !== b[i]) return false;
+ if (a[i] !== b[i]) {
+ return false;
+ }
}
return true;
}
@@ -233,17 +241,33 @@ function areRowPropsEqual<T extends Record<string, unknown>>(
prevProps: TableRowProps<T>,
nextProps: TableRowProps<T>,
): boolean {
- if (prevProps.rowKey !== nextProps.rowKey) return false;
- if (prevProps.rowIndex !== nextProps.rowIndex) return false;
+ if (prevProps.rowKey !== nextProps.rowKey) {
+ return false;
+ }
+ if (prevProps.rowIndex !== nextProps.rowIndex) {
+ return false;
+ }
- if (prevProps.columns !== nextProps.columns) return false;
- if (prevProps.plugins !== nextProps.plugins) return false;
- if (prevProps.textOverflow !== nextProps.textOverflow) return false;
- if (prevProps.RowComponent !== nextProps.RowComponent) return false;
- if (prevProps.CellComponent !== nextProps.CellComponent) return false;
+ if (prevProps.columns !== nextProps.columns) {
+ return false;
+ }
+ if (prevProps.plugins !== nextProps.plugins) {
+ return false;
+ }
+ if (prevProps.textOverflow !== nextProps.textOverflow) {
+ return false;
+ }
+ if (prevProps.RowComponent !== nextProps.RowComponent) {
+ return false;
+ }
+ if (prevProps.CellComponent !== nextProps.CellComponent) {
+ return false;
+ }
// Shallow compare the item - if same reference, skip re-render
- if (prevProps.item === nextProps.item) return true;
+ if (prevProps.item === nextProps.item) {
+ return true;
+ }
// Different object reference - compare values
const prevItem = prevProps.item;
@@ -251,7 +275,9 @@ function areRowPropsEqual<T extends Record<string, unknown>>(
const keys = Object.keys(nextItem);
for (const key of keys) {
- if (prevItem[key] !== nextItem[key]) return false;
+ if (prevItem[key] !== nextItem[key]) {
+ return false;
+ }
}
return true;
diff --git a/packages/core/src/Table/columnUtils.ts b/packages/core/src/Table/columnUtils.ts
index 287ee0e0a9..25ca5d2c50 100644
--- a/packages/core/src/Table/columnUtils.ts
+++ b/packages/core/src/Table/columnUtils.ts
@@ -165,7 +165,9 @@ export function pixel(value: number): PixelWidth {
* Used for auto-generating header text from data keys.
*/
export function capitalize(str: string): string {
- if (str.length === 0) return str;
+ if (str.length === 0) {
+ return str;
+ }
return str.charAt(0).toUpperCase() + str.slice(1);
}
@@ -177,7 +179,9 @@ export function defaultCellRenderer<T extends Record<string, unknown>>(
key: string,
): ReactNode {
const value = item[key];
- if (value == null) return '';
+ if (value == null) {
+ return '';
+ }
return String(value);
}
@@ -187,9 +191,15 @@ export function defaultCellRenderer<T extends Record<string, unknown>>(
* complex types return 0 (fall back to equal proportioning for that cell).
*/
function estimateContentLength(value: unknown): number {
- if (value == null) return 0;
- if (typeof value === 'string') return value.length;
- if (typeof value === 'number' || typeof value === 'boolean') return String(value).length;
+ if (value == null) {
+ return 0;
+ }
+ if (typeof value === 'string') {
+ return value.length;
+ }
+ if (typeof value === 'number' || typeof value === 'boolean') {
+ return String(value).length;
+ }
return 0;
}
@@ -199,14 +209,29 @@ function estimateContentLength(value: unknown): number {
* Only measures string and number values — complex types return 0.
*/
function longestWord(value: unknown): number {
- if (value == null) return 0;
- if (typeof value !== 'string' && typeof value !== 'number' && typeof value !== 'boolean') return 0;
+ if (value == null) {
+ return 0;
+ }
+ if (
+ typeof value !== 'string' &&
+ typeof value !== 'number' &&
+ typeof value !== 'boolean'
+ ) {
+ return 0;
+ }
const str = String(value);
let max = 0;
let current = 0;
for (let i = 0; i <= str.length; i++) {
- if (i === str.length || str[i] === ' ' || str[i] === '\t' || str[i] === '\n') {
- if (current > max) max = current;
+ if (
+ i === str.length ||
+ str[i] === ' ' ||
+ str[i] === '\t' ||
+ str[i] === '\n'
+ ) {
+ if (current > max) {
+ max = current;
+ }
current = 0;
} else {
current++;
@@ -230,7 +255,9 @@ const PX_PER_CHAR = 8;
export function generateColumns<T extends Record<string, unknown>>(
data: T[],
): XDSTableColumn<T>[] {
- if (data.length === 0) return [];
+ if (data.length === 0) {
+ return [];
+ }
const firstItem = data[0];
const keys = Object.keys(firstItem);
@@ -246,10 +273,14 @@ export function generateColumns<T extends Record<string, unknown>>(
for (const row of sampleRows) {
const contentLen = estimateContentLength(row[key]);
- if (contentLen > maxContentLen) maxContentLen = contentLen;
+ if (contentLen > maxContentLen) {
+ maxContentLen = contentLen;
+ }
const wordLen = longestWord(row[key]);
- if (wordLen > maxWordLen) maxWordLen = wordLen;
+ if (wordLen > maxWordLen) {
+ maxWordLen = wordLen;
+ }
}
return {key, headerLen, maxContentLen, maxWordLen};
@@ -260,8 +291,7 @@ export function generateColumns<T extends Record<string, unknown>>(
// 1 = short (≤6 chars: IDs, ages, booleans, status)
// 2 = medium (7–15 chars: names, dates, short strings)
// 3 = long (>15 chars: emails, URLs, descriptions)
- const proportion =
- m.maxContentLen <= 6 ? 1 : m.maxContentLen <= 15 ? 2 : 3;
+ const proportion = m.maxContentLen <= 6 ? 1 : m.maxContentLen <= 15 ? 2 : 3;
// Min-width: enough to fit header or longest word without wrapping
const minWidth = Math.max(
diff --git a/packages/core/src/Table/plugins/columnResize/useXDSTableColumnResize.tsx b/packages/core/src/Table/plugins/columnResize/useXDSTableColumnResize.tsx
index ef3285ebcc..b2dfa03bc4 100644
--- a/packages/core/src/Table/plugins/columnResize/useXDSTableColumnResize.tsx
+++ b/packages/core/src/Table/plugins/columnResize/useXDSTableColumnResize.tsx
@@ -23,7 +23,10 @@ import type {
ColumnWidth,
} from '../../types';
import {DEFAULT_MIN_COLUMN_WIDTH} from '../../columnUtils';
-import {observeResize, unobserveResize} from '../../../utils/sharedResizeObserver';
+import {
+ observeResize,
+ unobserveResize,
+} from '../../../utils/sharedResizeObserver';
// =============================================================================
// Config Type
@@ -104,8 +107,12 @@ function resolveColumnMinWidth(
colWidth: ColumnWidth | undefined,
globalOverride: number | undefined,
): number {
- if (globalOverride != null) return globalOverride;
- if (!colWidth) return DEFAULT_MIN_COLUMN_WIDTH;
+ if (globalOverride != null) {
+ return globalOverride;
+ }
+ if (!colWidth) {
+ return DEFAULT_MIN_COLUMN_WIDTH;
+ }
if (colWidth.type === 'proportional') {
return colWidth.minWidth ?? DEFAULT_MIN_COLUMN_WIDTH;
}
@@ -323,13 +330,19 @@ function ResizeHandle({
const handle = e.currentTarget;
const th = handle.closest('th') as HTMLTableCellElement | null;
- if (!th) return;
+ if (!th) {
+ return;
+ }
const table = th.closest('table');
- if (table) tableRef.current = table;
+ if (table) {
+ tableRef.current = table;
+ }
const headerRow = th.parentElement;
- if (!headerRow) return;
+ if (!headerRow) {
+ return;
+ }
const cols = configRef.current.columns;
const colsByKey = new Map(cols?.map(c => [c.key, c]));
@@ -345,9 +358,13 @@ function ResizeHandle({
const snapshots: ColumnSnapshot[] = [];
for (const cell of allThs) {
const key = cell.getAttribute('data-column-key');
- if (!key) continue;
+ if (!key) {
+ continue;
+ }
const col = colsByKey.get(key);
- if (col?.resizable === false) continue;
+ if (col?.resizable === false) {
+ continue;
+ }
const rendered = cell.getBoundingClientRect().width;
const override = currentWidths[key];
snapshots.push({
@@ -366,7 +383,9 @@ function ResizeHandle({
let neighborIdx: number | null = null;
if (neighborKey) {
const idx = snapshots.findIndex(s => s.key === neighborKey);
- if (idx >= 0) neighborIdx = idx;
+ if (idx >= 0) {
+ neighborIdx = idx;
+ }
}
const drag: DragState = {
@@ -397,7 +416,9 @@ function ResizeHandle({
function onMove(ev: PointerEvent) {
const d = dragStateRef.current;
- if (!d || !isDraggingRef.current) return;
+ if (!d || !isDraggingRef.current) {
+ return;
+ }
const rawDelta =
(ev.clientX - d.startX) *
@@ -415,7 +436,9 @@ function ResizeHandle({
function onUp(ev: PointerEvent) {
cleanup();
const d = dragStateRef.current;
- if (!d || !isDraggingRef.current) return;
+ if (!d || !isDraggingRef.current) {
+ return;
+ }
handle.removeAttribute('data-resizing');
handle.style.removeProperty('--indicator-color');
@@ -433,7 +456,9 @@ function ResizeHandle({
const updates: Record<string, number> = {};
const lastIndex = d.snapshots.length - 1;
d.snapshots.forEach((s, i) => {
- if (i === lastIndex) return;
+ if (i === lastIndex) {
+ return;
+ }
updates[s.key] = widths[i];
});
@@ -450,7 +475,9 @@ function ResizeHandle({
function onCancel() {
cleanup();
const d = dragStateRef.current;
- if (!d || !isDraggingRef.current) return;
+ if (!d || !isDraggingRef.current) {
+ return;
+ }
handle.removeAttribute('data-resizing');
handle.style.removeProperty('--indicator-color');
@@ -500,7 +527,9 @@ function ResizeHandle({
const buildSnapshotAndResize = useCallback(
(th: HTMLTableCellElement, delta: number) => {
const headerRow = th.parentElement;
- if (!headerRow) return;
+ if (!headerRow) {
+ return;
+ }
const cols = configRef.current.columns;
const colsByKey = new Map(cols?.map(c => [c.key, c]));
@@ -513,9 +542,13 @@ function ResizeHandle({
const snapshots: ColumnSnapshot[] = [];
for (const cell of allThs) {
const key = cell.getAttribute('data-column-key');
- if (!key) continue;
+ if (!key) {
+ continue;
+ }
const col = colsByKey.get(key);
- if (col?.resizable === false) continue;
+ if (col?.resizable === false) {
+ continue;
+ }
const rendered = cell.getBoundingClientRect().width;
const override = currentWidths[key];
snapshots.push({
@@ -533,7 +566,9 @@ function ResizeHandle({
let neighborIdx: number | null = null;
if (neighborKey) {
const idx = snapshots.findIndex(s => s.key === neighborKey);
- if (idx >= 0) neighborIdx = idx;
+ if (idx >= 0) {
+ neighborIdx = idx;
+ }
}
const drag: DragState = {
@@ -559,7 +594,9 @@ function ResizeHandle({
const updates: Record<string, number> = {};
const lastIndex = snapshots.length - 1;
snapshots.forEach((s, i) => {
- if (i === lastIndex) return;
+ if (i === lastIndex) {
+ return;
+ }
updates[s.key] = widths[i];
});
@@ -581,10 +618,14 @@ function ResizeHandle({
(e: React.KeyboardEvent<HTMLDivElement>) => {
const handle = e.currentTarget;
const th = handle.closest('th') as HTMLTableCellElement | null;
- if (!th) return;
+ if (!th) {
+ return;
+ }
const table = th.closest('table');
- if (table) tableRef.current = table;
+ if (table) {
+ tableRef.current = table;
+ }
const step = e.shiftKey ? KEYBOARD_LARGE_STEP : KEYBOARD_STEP;
const rtl = getRTLMultiplier(th);
@@ -685,10 +726,14 @@ export function useXDSTableColumnResize<T extends Record<string, unknown>>(
unobserveResize(observedTableRef.current);
observedTableRef.current = null;
}
- if (!el) return;
+ if (!el) {
+ return;
+ }
const table = el.querySelector('table');
- if (table) tableRef.current = table;
+ if (table) {
+ tableRef.current = table;
+ }
if (table && typeof ResizeObserver !== 'undefined') {
observeResize(table, () => {
@@ -722,7 +767,9 @@ export function useXDSTableColumnResize<T extends Record<string, unknown>>(
column: XDSTableColumn<T>,
): HeaderCellRenderProps {
// Skip columns that opt out of resizing
- if (column.resizable === false) return props;
+ if (column.resizable === false) {
+ return props;
+ }
const overrideWidth = columnWidths?.[column.key];
diff --git a/packages/core/src/Table/plugins/columnSettings/useXDSTableColumnSettingsState.tsx b/packages/core/src/Table/plugins/columnSettings/useXDSTableColumnSettingsState.tsx
index 4aae841d6b..05dda3b8c4 100644
--- a/packages/core/src/Table/plugins/columnSettings/useXDSTableColumnSettingsState.tsx
+++ b/packages/core/src/Table/plugins/columnSettings/useXDSTableColumnSettingsState.tsx
@@ -198,7 +198,9 @@ export function useXDSTableColumnSettingsState<
const avSet = new Set(
cfg.columns.filter(c => c.isAlwaysVisible).map(c => c.key),
);
- if (avSet.has(key)) return;
+ if (avSet.has(key)) {
+ return;
+ }
const currentKeys = cfg.activeColumnKeys;
const currentSet = new Set(currentKeys);
diff --git a/packages/core/src/Table/plugins/filtering/useXDSTableFilterState.tsx b/packages/core/src/Table/plugins/filtering/useXDSTableFilterState.tsx
index 50c4a290f9..89e058918c 100644
--- a/packages/core/src/Table/plugins/filtering/useXDSTableFilterState.tsx
+++ b/packages/core/src/Table/plugins/filtering/useXDSTableFilterState.tsx
@@ -61,8 +61,11 @@ export function useXDSTableFilterState(
(key: string, value: XDSTableFilterValue | null) => {
setFilters(prev => {
const next = {...prev};
- if (value == null) delete next[key];
- else next[key] = value;
+ if (value == null) {
+ delete next[key];
+ } else {
+ next[key] = value;
+ }
return next;
});
},
diff --git a/packages/core/src/Table/plugins/filtering/useXDSTableFiltering.tsx b/packages/core/src/Table/plugins/filtering/useXDSTableFiltering.tsx
index 7ece6e2517..520719cd77 100644
--- a/packages/core/src/Table/plugins/filtering/useXDSTableFiltering.tsx
+++ b/packages/core/src/Table/plugins/filtering/useXDSTableFiltering.tsx
@@ -124,10 +124,14 @@ function resolveFilterConfig(
const operatorKey = typeof filter === 'string' ? undefined : filter.operator;
const field = searchConfig.fields.find(f => f.key === fieldKey);
- if (!field) return undefined;
+ if (!field) {
+ return undefined;
+ }
const operator = resolveOperator(field, operatorKey);
- if (!operator) return undefined;
+ if (!operator) {
+ return undefined;
+ }
return operator.value;
}
@@ -158,9 +162,13 @@ export function toSearchFilters<_T extends Record<string, unknown>>(
const result: PowerSearchFilter[] = [];
for (const col of columns) {
- if (!col.filter) continue;
+ if (!col.filter) {
+ continue;
+ }
const value = filters[col.key];
- if (value == null) continue;
+ if (value == null) {
+ continue;
+ }
const fieldKey =
typeof col.filter === 'string' ? col.filter : col.filter.field;
@@ -168,13 +176,19 @@ export function toSearchFilters<_T extends Record<string, unknown>>(
typeof col.filter === 'string' ? undefined : col.filter.operator;
const field = searchConfig.fields.find(f => f.key === fieldKey);
- if (!field) continue;
+ if (!field) {
+ continue;
+ }
const operator = resolveOperator(field, operatorKey);
- if (!operator) continue;
+ if (!operator) {
+ continue;
+ }
const filterValue = tableValueToFilterValue(value, operator.value);
- if (!filterValue) continue;
+ if (!filterValue) {
+ continue;
+ }
result.push({field: fieldKey, operator: operator.key, value: filterValue});
}
@@ -316,10 +330,11 @@ FilterStoreContext.displayName = 'FilterStoreContext';
function useFilterStore(): FilterStore {
const store = use(FilterStoreContext);
- if (!store)
+ if (!store) {
throw new Error(
'useFilterStore must be used within a Table with filtering',
);
+ }
return store;
}
@@ -908,7 +923,9 @@ function PopoverFilterTrigger({
function getHeaderString(
column: XDSTableColumn<Record<string, unknown>>,
): string {
- if (typeof column.header === 'string') return column.header;
+ if (typeof column.header === 'string') {
+ return column.header;
+ }
return column.key;
}
@@ -1078,7 +1095,9 @@ export function useXDSTableFiltering<T extends Record<string, unknown>>(
if (variant === 'popover') {
// No operator value on this column — nothing to render.
- if (!operatorValue) return props;
+ if (!operatorValue) {
+ return props;
+ }
return {
...props,
diff --git a/packages/core/src/Table/plugins/pagination/useXDSTablePagination.test.tsx b/packages/core/src/Table/plugins/pagination/useXDSTablePagination.test.tsx
index 5a6a168b63..ad74402faf 100644
--- a/packages/core/src/Table/plugins/pagination/useXDSTablePagination.test.tsx
+++ b/packages/core/src/Table/plugins/pagination/useXDSTablePagination.test.tsx
@@ -350,8 +350,11 @@ describe('useXDSTablePagination', () => {
getIsItemSelected: item => selectedIds.has(item.id),
onSelectItem: ({item, isSelected}) => {
const next = new Set(selectedIds);
- if (isSelected) next.add(item.id);
- else next.delete(item.id);
+ if (isSelected) {
+ next.add(item.id);
+ } else {
+ next.delete(item.id);
+ }
setSelectedIds(next);
},
onSelectAll: ({isAllSelected}) => {
diff --git a/packages/core/src/Table/plugins/pagination/useXDSTablePagination.tsx b/packages/core/src/Table/plugins/pagination/useXDSTablePagination.tsx
index 93d99d15b3..4e42b76b23 100644
--- a/packages/core/src/Table/plugins/pagination/useXDSTablePagination.tsx
+++ b/packages/core/src/Table/plugins/pagination/useXDSTablePagination.tsx
@@ -242,7 +242,9 @@ export function useXDSTablePagination<T extends Record<string, unknown>>(
paginationProps: props,
align: a,
} = configRef.current;
- if (pos === 'none') return children;
+ if (pos === 'none') {
+ return children;
+ }
// Don't render pagination when there's only one page and no more data.
const resolvedTotalPages =
@@ -251,7 +253,9 @@ export function useXDSTablePagination<T extends Record<string, unknown>>(
? Math.ceil(props.totalItems / props.pageSize)
: undefined);
const isSinglePage = resolvedTotalPages === 1 && props.hasMore !== true;
- if (isSinglePage) return children;
+ if (isSinglePage) {
+ return children;
+ }
const makeWrapper = (side: 'above' | 'below') => (
<div
diff --git a/packages/core/src/Table/plugins/selection/useXDSTableSelection-perf.test.tsx b/packages/core/src/Table/plugins/selection/useXDSTableSelection-perf.test.tsx
index d04b2cbd68..8f7e27c6d8 100644
--- a/packages/core/src/Table/plugins/selection/useXDSTableSelection-perf.test.tsx
+++ b/packages/core/src/Table/plugins/selection/useXDSTableSelection-perf.test.tsx
@@ -249,7 +249,9 @@ describe('Selection plugin render performance', () => {
// Only row-1 should have re-rendered
for (const id of Object.keys(renderCounts)) {
- if (id === 'row-1') continue;
+ if (id === 'row-1') {
+ continue;
+ }
expect(renderCounts[id]).toBe(0);
}
});
diff --git a/packages/core/src/Table/plugins/selection/useXDSTableSelection.tsx b/packages/core/src/Table/plugins/selection/useXDSTableSelection.tsx
index 8b058129e3..dc8aa401b7 100644
--- a/packages/core/src/Table/plugins/selection/useXDSTableSelection.tsx
+++ b/packages/core/src/Table/plugins/selection/useXDSTableSelection.tsx
@@ -175,7 +175,9 @@ function useIsItemSelected<T extends Record<string, unknown>>(
function SelectAllCheckbox() {
const store = use(SelectionStoreContext);
- if (!store) return null;
+ if (!store) {
+ return null;
+ }
return <SelectAllCheckboxInner store={store} />;
}
@@ -202,7 +204,9 @@ function SelectAllCheckboxInner<T extends Record<string, unknown>>({
const getSnapshot = useCallback(() => {
const config = store.getConfig();
const allSelected = config.getIsAllSelected();
- if (allSelected) return SELECT_ALL;
+ if (allSelected) {
+ return SELECT_ALL;
+ }
const indeterminate = config.getIsIndeterminate?.() ?? false;
return indeterminate ? SELECT_INDETERMINATE : SELECT_NONE;
}, [store]);
@@ -234,7 +238,9 @@ function SelectionCellContent<T extends Record<string, unknown>>({
item: T;
}) {
const store = use(SelectionStoreContext);
- if (!store) return null;
+ if (!store) {
+ return null;
+ }
return <SelectionCellContentInner store={store} item={item} />;
}
@@ -251,7 +257,9 @@ function SelectionCellContentInner<T extends Record<string, unknown>>({
const selectable = config.getIsItemSelectable?.(item) ?? true;
const enabled = config.getIsItemEnabled?.(item) ?? true;
- if (!selectable) return null;
+ if (!selectable) {
+ return null;
+ }
return (
<XDSCheckboxInput
@@ -350,7 +358,9 @@ export function useXDSTableSelection<T extends Record<string, unknown>>(
// imperative row styling. Each row manages its own subscription
// and self-cleans when disconnected — no central element tracking.
const selectionRef: React.RefCallback<HTMLTableRowElement> = el => {
- if (!el) return;
+ if (!el) {
+ return;
+ }
// Apply initial style
applyRowSelectionStyle(el, store.getConfig().getIsItemSelected(item));
// Subscribe for future changes
diff --git a/packages/core/src/Table/plugins/selection/useXDSTableSelectionState.tsx b/packages/core/src/Table/plugins/selection/useXDSTableSelectionState.tsx
index 523a944ee9..d2f992953f 100644
--- a/packages/core/src/Table/plugins/selection/useXDSTableSelectionState.tsx
+++ b/packages/core/src/Table/plugins/selection/useXDSTableSelectionState.tsx
@@ -111,7 +111,9 @@ export function useXDSTableSelectionState<T extends Record<string, unknown>>(
const frozenSelectedIDs = useMemo(() => {
const frozen = new Set<string>();
for (const id of selectedKeys) {
- if (!selectableIDs.has(id)) frozen.add(id);
+ if (!selectableIDs.has(id)) {
+ frozen.add(id);
+ }
}
return frozen;
}, [selectedKeys, selectableIDs]);
diff --git a/packages/core/src/Table/plugins/sortable/useXDSTableSortable.tsx b/packages/core/src/Table/plugins/sortable/useXDSTableSortable.tsx
index 7ffaa52955..76298c9f50 100644
--- a/packages/core/src/Table/plugins/sortable/useXDSTableSortable.tsx
+++ b/packages/core/src/Table/plugins/sortable/useXDSTableSortable.tsx
@@ -161,8 +161,12 @@ function resolveSortKey<T extends Record<string, unknown>>(
column: XDSTableColumn<T>,
): string | null {
const {sortable} = column;
- if (!sortable) return null;
- if (sortable === true) return column.key;
+ if (!sortable) {
+ return null;
+ }
+ if (sortable === true) {
+ return column.key;
+ }
return sortable.sortKey ?? column.key;
}
@@ -170,7 +174,9 @@ function getHeaderLabel<T extends Record<string, unknown>>(
column: XDSTableColumn<T>,
): string {
const {header} = column;
- if (typeof header === 'string') return header;
+ if (typeof header === 'string') {
+ return header;
+ }
return column.key;
}
@@ -195,8 +201,12 @@ function getNextDirection(
current: XDSTableSortDirection | null,
allowUnsortedState: boolean,
): XDSTableSortDirection | null {
- if (current == null) return 'ascending';
- if (current === 'ascending') return 'descending';
+ if (current == null) {
+ return 'ascending';
+ }
+ if (current === 'ascending') {
+ return 'descending';
+ }
// current === 'descending'
return allowUnsortedState ? null : 'ascending';
}
@@ -342,7 +352,9 @@ export function useXDSTableSortable<
column: XDSTableColumn<T>,
): HeaderCellRenderProps {
const sortKey = resolveSortKey(column);
- if (sortKey == null) return props;
+ if (sortKey == null) {
+ return props;
+ }
// Find sort entry for this column
const cfg = configRef.current;
diff --git a/packages/core/src/Table/plugins/sortable/useXDSTableSortableState.tsx b/packages/core/src/Table/plugins/sortable/useXDSTableSortableState.tsx
index 8da3d5ba27..50ed7db5b3 100644
--- a/packages/core/src/Table/plugins/sortable/useXDSTableSortableState.tsx
+++ b/packages/core/src/Table/plugins/sortable/useXDSTableSortableState.tsx
@@ -154,9 +154,15 @@ function defaultCompare<T extends Record<string, unknown>>(
const bVal = b[sortKey];
// null/undefined sort to the end
- if (aVal == null && bVal == null) return 0;
- if (aVal == null) return 1;
- if (bVal == null) return -1;
+ if (aVal == null && bVal == null) {
+ return 0;
+ }
+ if (aVal == null) {
+ return 1;
+ }
+ if (bVal == null) {
+ return -1;
+ }
// number fast path
if (typeof aVal === 'number' && typeof bVal === 'number') {
@@ -179,7 +185,9 @@ function sortData<
sortState: XDSTableSortState<TSortKey>,
comparators?: Partial<Record<TSortKey, XDSTableSortComparator<T>>>,
): T[] {
- if (sortState.length === 0) return data;
+ if (sortState.length === 0) {
+ return data;
+ }
return [...data].sort((a, b) => {
for (const entry of sortState) {
diff --git a/packages/core/src/Table/useTableCellStyles.ts b/packages/core/src/Table/useTableCellStyles.ts
index 3777b66e2e..612624f7bb 100644
--- a/packages/core/src/Table/useTableCellStyles.ts
+++ b/packages/core/src/Table/useTableCellStyles.ts
@@ -56,7 +56,9 @@ export function mergeXStyle(
styles: StyleXStyles[],
xstyle: StyleXStyles | StyleXStyles[] | undefined,
): StyleXStyles[] {
- if (!xstyle) return styles;
+ if (!xstyle) {
+ return styles;
+ }
if (Array.isArray(xstyle)) {
return [...styles, ...xstyle];
}
diff --git a/packages/core/src/Table/useXDSBaseTablePlugins.ts b/packages/core/src/Table/useXDSBaseTablePlugins.ts
index 12a1519a3f..18c0e442d8 100644
--- a/packages/core/src/Table/useXDSBaseTablePlugins.ts
+++ b/packages/core/src/Table/useXDSBaseTablePlugins.ts
@@ -217,16 +217,24 @@ function arePluginRecordsEqual<T extends Record<string, unknown>>(
a: Record<string, TablePlugin<T>> | undefined,
b: Record<string, TablePlugin<T>> | undefined,
): boolean {
- if (a === b) return true;
- if (a == null || b == null) return false;
+ if (a === b) {
+ return true;
+ }
+ if (a == null || b == null) {
+ return false;
+ }
const keysA = Object.keys(a);
const keysB = Object.keys(b);
- if (keysA.length !== keysB.length) return false;
+ if (keysA.length !== keysB.length) {
+ return false;
+ }
for (const key of keysA) {
- if (a[key] !== b[key]) return false;
+ if (a[key] !== b[key]) {
+ return false;
+ }
}
return true;
diff --git a/packages/core/src/Text/XDSText.tsx b/packages/core/src/Text/XDSText.tsx
index b56734bf93..bc8f88806f 100644
--- a/packages/core/src/Text/XDSText.tsx
+++ b/packages/core/src/Text/XDSText.tsx
@@ -168,7 +168,9 @@ const defaultColorByType: Record<string, XDSTextColor> = {
* their visual treatment comes from theme CSS overrides (.xds-text.<type>).
*/
function resolveStyleType(type: XDSTextType): XDSBuiltinTextType {
- if (type in sizeByTypeStyles) return type as XDSBuiltinTextType;
+ if (type in sizeByTypeStyles) {
+ return type as XDSBuiltinTextType;
+ }
return 'body';
}
diff --git a/packages/core/src/Timestamp/XDSTimestamp.tsx b/packages/core/src/Timestamp/XDSTimestamp.tsx
index 6d70693d0e..c6a785b36b 100644
--- a/packages/core/src/Timestamp/XDSTimestamp.tsx
+++ b/packages/core/src/Timestamp/XDSTimestamp.tsx
@@ -152,7 +152,9 @@ function getRelativeTimeString(date: Date, now: Date): string {
if (diffSeconds < 0) {
// Future dates
const absDiff = Math.abs(diffSeconds);
- if (absDiff < MINUTE) return 'in a few seconds';
+ if (absDiff < MINUTE) {
+ return 'in a few seconds';
+ }
if (absDiff < HOUR) {
const mins = Math.round(absDiff / MINUTE);
return `in ${mins} ${mins === 1 ? 'minute' : 'minutes'}`;
@@ -173,8 +175,12 @@ function getRelativeTimeString(date: Date, now: Date): string {
return `in ${years} ${years === 1 ? 'year' : 'years'}`;
}
- if (diffSeconds < 10) return 'just now';
- if (diffSeconds < MINUTE) return `${diffSeconds} seconds ago`;
+ if (diffSeconds < 10) {
+ return 'just now';
+ }
+ if (diffSeconds < MINUTE) {
+ return `${diffSeconds} seconds ago`;
+ }
if (diffSeconds < HOUR) {
const mins = Math.round(diffSeconds / MINUTE);
return `${mins} ${mins === 1 ? 'minute' : 'minutes'} ago`;
@@ -183,7 +189,9 @@ function getRelativeTimeString(date: Date, now: Date): string {
const hours = Math.round(diffSeconds / HOUR);
return `${hours} ${hours === 1 ? 'hour' : 'hours'} ago`;
}
- if (diffSeconds < 2 * DAY) return 'yesterday';
+ if (diffSeconds < 2 * DAY) {
+ return 'yesterday';
+ }
if (diffSeconds < MONTH) {
const days = Math.round(diffSeconds / DAY);
return `${days} days ago`;
@@ -271,9 +279,15 @@ function getFullAbsoluteString(date: Date): string {
/** Returns the interval (in ms) at which a relative timestamp should update. */
function getLiveInterval(diffSeconds: number): number {
const absDiff = Math.abs(diffSeconds);
- if (absDiff < MINUTE) return 1000; // every second
- if (absDiff < HOUR) return 30_000; // every 30s
- if (absDiff < DAY) return 60_000; // every minute
+ if (absDiff < MINUTE) {
+ return 1000;
+ } // every second
+ if (absDiff < HOUR) {
+ return 30_000;
+ } // every 30s
+ if (absDiff < DAY) {
+ return 60_000;
+ } // every minute
return 300_000; // every 5 minutes
}
@@ -349,7 +363,9 @@ export function XDSTimestamp({
// Live updates
useEffect(() => {
- if (!isLive || effectiveFormat !== 'relative') return;
+ if (!isLive || effectiveFormat !== 'relative') {
+ return;
+ }
const interval = getLiveInterval(diffSeconds);
const timer = setInterval(() => {
diff --git a/packages/core/src/Toast/XDSToast.tsx b/packages/core/src/Toast/XDSToast.tsx
index cab0a3d774..26176e8d6d 100644
--- a/packages/core/src/Toast/XDSToast.tsx
+++ b/packages/core/src/Toast/XDSToast.tsx
@@ -160,7 +160,9 @@ export function XDSToast({
remainingRef.current = autoHideDuration;
startTimer();
return () => {
- if (timerRef.current) clearTimeout(timerRef.current);
+ if (timerRef.current) {
+ clearTimeout(timerRef.current);
+ }
};
}, [autoHideDuration, startTimer]);
diff --git a/packages/core/src/Toast/XDSToastViewport.tsx b/packages/core/src/Toast/XDSToastViewport.tsx
index c36870c5e1..686394eaa4 100644
--- a/packages/core/src/Toast/XDSToastViewport.tsx
+++ b/packages/core/src/Toast/XDSToastViewport.tsx
@@ -114,7 +114,9 @@ export function XDSToastViewport({
if (uniqueID) {
const existing = prev.find(t => t.options.uniqueID === uniqueID);
if (existing) {
- if (collisionBehavior === 'ignore') return prev;
+ if (collisionBehavior === 'ignore') {
+ return prev;
+ }
return prev.map(t => (t.options.uniqueID === uniqueID ? entry : t));
}
}
@@ -125,9 +127,13 @@ export function XDSToastViewport({
const removeToast = useCallback(
(id: string, reason: XDSToastDismissReason) => {
const entry = toastsRef.current.find(t => t.id === id);
- if (entry) entry.options.onHide?.(reason);
+ if (entry) {
+ entry.options.onHide?.(reason);
+ }
setExitingIds(prev => {
- if (prev.has(id)) return prev;
+ if (prev.has(id)) {
+ return prev;
+ }
return new Set(prev).add(id);
});
},
@@ -136,7 +142,9 @@ export function XDSToastViewport({
const handleExited = useCallback((id: string) => {
setExitingIds(prev => {
- if (!prev.has(id)) return prev;
+ if (!prev.has(id)) {
+ return prev;
+ }
const next = new Set(prev);
next.delete(id);
return next;
@@ -155,15 +163,25 @@ export function XDSToastViewport({
const visibleToasts = toasts.slice(-maxVisible);
const insetStyle: React.CSSProperties = {};
- if (inset?.top) insetStyle.top = inset.top;
- if (inset?.bottom) insetStyle.bottom = inset.bottom;
- if (inset?.start) insetStyle.insetInlineStart = inset.start;
- if (inset?.end) insetStyle.insetInlineEnd = inset.end;
+ if (inset?.top) {
+ insetStyle.top = inset.top;
+ }
+ if (inset?.bottom) {
+ insetStyle.bottom = inset.bottom;
+ }
+ if (inset?.start) {
+ insetStyle.insetInlineStart = inset.start;
+ }
+ if (inset?.end) {
+ insetStyle.insetInlineEnd = inset.end;
+ }
// Show the popover on mount so it enters the top layer
const viewportRef = useRef<HTMLDivElement>(null);
useEffect(() => {
- if (!isTopLayer) return;
+ if (!isTopLayer) {
+ return;
+ }
const el = viewportRef.current;
if (el && typeof el.showPopover === 'function') {
try {
diff --git a/packages/core/src/Toast/useXDSToast.tsx b/packages/core/src/Toast/useXDSToast.tsx
index 500ba67041..b80c74f5ee 100644
--- a/packages/core/src/Toast/useXDSToast.tsx
+++ b/packages/core/src/Toast/useXDSToast.tsx
@@ -19,7 +19,9 @@ let fallbackRoot: ReturnType<typeof createRoot> | null = null;
let fallbackWarned = false;
function getFallbackContext(): XDSToastContextValue {
- if (fallbackContext) return fallbackContext;
+ if (fallbackContext) {
+ return fallbackContext;
+ }
if (typeof document === 'undefined') {
throw new Error(
@@ -74,7 +76,9 @@ function getFallbackContext(): XDSToastContextValue {
} else {
pending.push(entry);
ctxReady.then(ctx => {
- for (const e of pending) ctx.addToast(e);
+ for (const e of pending) {
+ ctx.addToast(e);
+ }
pending.length = 0;
});
}
diff --git a/packages/core/src/ToggleButton/XDSToggleButton.tsx b/packages/core/src/ToggleButton/XDSToggleButton.tsx
index 9ac7f39958..3c25b0cf7e 100644
--- a/packages/core/src/ToggleButton/XDSToggleButton.tsx
+++ b/packages/core/src/ToggleButton/XDSToggleButton.tsx
@@ -248,7 +248,9 @@ export function XDSToggleButton({
const resolvedIcon = isPressed && pressedIcon ? pressedIcon : icon;
const handleClick = useCallback(() => {
- if (isDisabled || isLoading) return;
+ if (isDisabled || isLoading) {
+ return;
+ }
if (group && value != null) {
// Delegate to group context
diff --git a/packages/core/src/Token/XDSToken.tsx b/packages/core/src/Token/XDSToken.tsx
index 9b78a319dc..79c94f78f9 100644
--- a/packages/core/src/Token/XDSToken.tsx
+++ b/packages/core/src/Token/XDSToken.tsx
@@ -402,7 +402,9 @@ export function XDSToken({
if (onClick != null) {
const handleContainerClick = (e: React.MouseEvent) => {
const target = e.target as HTMLElement;
- if (target.closest('button, a')) return;
+ if (target.closest('button, a')) {
+ return;
+ }
onClick(e);
};
diff --git a/packages/core/src/Tokenizer/XDSTokenizer.tsx b/packages/core/src/Tokenizer/XDSTokenizer.tsx
index 23c666ee68..95e97158bf 100644
--- a/packages/core/src/Tokenizer/XDSTokenizer.tsx
+++ b/packages/core/src/Tokenizer/XDSTokenizer.tsx
@@ -322,7 +322,9 @@ const CREATABLE_ID_PREFIX = '__xds_create__';
* value={members}
* onChange={(items, change) => {
* setMembers(items);
- * if (change.type === 'add') console.log('Added:', change.item.label);
+ * if (change.type === 'add') {
+ * console.log('Added:', change.item.label);
+ * }
* }}
* placeholder="Search people..."
* />
@@ -419,12 +421,20 @@ export function XDSTokenizer<T extends XDSSearchableItem>({
// popover content. We track both to decide when focus has truly left.
const isFocusInTokenizer = useCallback(
(target: Node | null): boolean => {
- if (!target) return false;
- if (wrapperRef.current?.contains(target)) return true;
- if (layerContentRef.current?.contains(target)) return true;
+ if (!target) {
+ return false;
+ }
+ if (wrapperRef.current?.contains(target)) {
+ return true;
+ }
+ if (layerContentRef.current?.contains(target)) {
+ return true;
+ }
// Also check the popover element itself (the layer wrapper)
const popoverEl = document.getElementById(layer.id);
- if (popoverEl?.contains(target)) return true;
+ if (popoverEl?.contains(target)) {
+ return true;
+ }
return false;
},
[layer.id],
@@ -517,8 +527,12 @@ export function XDSTokenizer<T extends XDSSearchableItem>({
// Handle adding an item — detect creatable synthetic items
const handleAdd = useCallback(
(item: T | null) => {
- if (!item) return;
- if (isAtMax) return;
+ if (!item) {
+ return;
+ }
+ if (isAtMax) {
+ return;
+ }
// Detect "Create: X" synthetic items from the creatable source
if (
@@ -527,7 +541,9 @@ export function XDSTokenizer<T extends XDSSearchableItem>({
item.id.startsWith(CREATABLE_ID_PREFIX)
) {
const createdValue = item.id.slice(CREATABLE_ID_PREFIX.length);
- if (selectedIds.has(createdValue)) return;
+ if (selectedIds.has(createdValue)) {
+ return;
+ }
const base = {id: createdValue, label: createdValue};
const realItem = base as T;
const newItems = [...value, realItem];
@@ -535,7 +551,9 @@ export function XDSTokenizer<T extends XDSSearchableItem>({
return;
}
- if (selectedIds.has(item.id)) return;
+ if (selectedIds.has(item.id)) {
+ return;
+ }
const newItems = [...value, item];
onChange(newItems, {item, type: 'add'});
},
@@ -554,7 +572,9 @@ export function XDSTokenizer<T extends XDSSearchableItem>({
// Handle clearing all items
const handleClearAll = useCallback(() => {
- if (value.length === 0) return;
+ if (value.length === 0) {
+ return;
+ }
// Report the last item as removed (convention)
const lastItem = value[value.length - 1];
onChange([], {item: lastItem, type: 'remove'});
diff --git a/packages/core/src/Tooltip/XDSTooltip.tsx b/packages/core/src/Tooltip/XDSTooltip.tsx
index 67c26150a9..61a6dc94cd 100644
--- a/packages/core/src/Tooltip/XDSTooltip.tsx
+++ b/packages/core/src/Tooltip/XDSTooltip.tsx
@@ -213,10 +213,14 @@ export function XDSTooltip({
// Sibling mode: attach to external anchorRef
useIsomorphicLayoutEffect(() => {
- if (!anchorRef) return;
+ if (!anchorRef) {
+ return;
+ }
const el = anchorRef.current;
- if (!el) return;
+ if (!el) {
+ return;
+ }
// Use combined ref for position + interaction
tooltip.ref(el);
@@ -240,14 +244,22 @@ export function XDSTooltip({
// For element children with display:contents, attach ref to first child
useIsomorphicLayoutEffect(() => {
- if (anchorRef) return; // Skip if using anchorRef mode
- if (textOnly) return; // Skip for text-only (ref is on wrapper)
+ if (anchorRef) {
+ return;
+ } // Skip if using anchorRef mode
+ if (textOnly) {
+ return;
+ } // Skip for text-only (ref is on wrapper)
const wrapper = wrapperRef.current;
- if (!wrapper) return;
+ if (!wrapper) {
+ return;
+ }
const firstChild = wrapper.firstElementChild as HTMLElement | null;
- if (!firstChild) return;
+ if (!firstChild) {
+ return;
+ }
// Use combined ref for position + interaction
tooltip.ref(firstChild);
diff --git a/packages/core/src/Tooltip/useXDSTooltip.tsx b/packages/core/src/Tooltip/useXDSTooltip.tsx
index 5d010277a7..96731854ab 100644
--- a/packages/core/src/Tooltip/useXDSTooltip.tsx
+++ b/packages/core/src/Tooltip/useXDSTooltip.tsx
@@ -284,7 +284,9 @@ export function useXDSTooltip(
// Schedule show with delay (suppressed when isOpen is false)
const scheduleShow = useCallback(() => {
- if (!isEnabled || isOpen === false) return;
+ if (!isEnabled || isOpen === false) {
+ return;
+ }
clearTimeouts();
showTimeoutRef.current = setTimeout(() => {
layer.show();
@@ -293,7 +295,9 @@ export function useXDSTooltip(
// Schedule hide with delay (suppressed when isOpen is true)
const scheduleHide = useCallback(() => {
- if (isOpen === true) return;
+ if (isOpen === true) {
+ return;
+ }
clearTimeouts();
if (hideDelay > 0) {
hideTimeoutRef.current = setTimeout(() => {
@@ -323,11 +327,15 @@ export function useXDSTooltip(
const handleFocusIn = useCallback(
(e: Event) => {
- if (!isEnabled) return;
+ if (!isEnabled) {
+ return;
+ }
// Only show tooltip for keyboard focus (:focus-visible),
// not programmatic focus (e.g. dialog auto-focus, touch tap)
const target = e.target as HTMLElement;
- if (!target.matches(':focus-visible')) return;
+ if (!target.matches(':focus-visible')) {
+ return;
+ }
clearTimeouts();
layer.show();
},
@@ -402,7 +410,9 @@ export function useXDSTooltip(
// Controlled open state — overrides hover/focus triggers
useEffect(() => {
- if (isOpen === undefined) return;
+ if (isOpen === undefined) {
+ return;
+ }
if (isOpen) {
clearTimeouts();
layer.show();
diff --git a/packages/core/src/TopNav/XDSTopNav.tsx b/packages/core/src/TopNav/XDSTopNav.tsx
index d1fa31ff0b..9f3dcbb13c 100644
--- a/packages/core/src/TopNav/XDSTopNav.tsx
+++ b/packages/core/src/TopNav/XDSTopNav.tsx
@@ -212,7 +212,9 @@ export function XDSTopNav({
// =========================================================================
if (renderMode === 'drawer') {
// Only render if there are collapsible items or extra content
- if (!hasCollapsibleContent && !mobileContent) return null;
+ if (!hasCollapsibleContent && !mobileContent) {
+ return null;
+ }
return (
<XDSMobileNav header={heading}>
diff --git a/packages/core/src/TopNav/XDSTopNavItem.tsx b/packages/core/src/TopNav/XDSTopNavItem.tsx
index c57c13f37c..8119cfb28d 100644
--- a/packages/core/src/TopNav/XDSTopNavItem.tsx
+++ b/packages/core/src/TopNav/XDSTopNavItem.tsx
@@ -199,7 +199,9 @@ export function XDSTopNavItem({
// =========================================================================
if (renderMode === 'drawer') {
const handleDrawerClick = (e: React.MouseEvent) => {
- if (isDisabled) return;
+ if (isDisabled) {
+ return;
+ }
// Forward the original onClick if present
(props as {onClick?: (e: React.MouseEvent) => void}).onClick?.(e);
closeMobileNav();
diff --git a/packages/core/src/TopNav/XDSTopNavMegaMenu.tsx b/packages/core/src/TopNav/XDSTopNavMegaMenu.tsx
index 9bf3b40216..9cbd84e83b 100644
--- a/packages/core/src/TopNav/XDSTopNavMegaMenu.tsx
+++ b/packages/core/src/TopNav/XDSTopNavMegaMenu.tsx
@@ -388,11 +388,15 @@ function DefaultMegaMenu({
}, [clearTimeouts, popover, hideDelay]);
const handleMouseEnter = useCallback(() => {
- if (!clickLockedRef.current) scheduleShow();
+ if (!clickLockedRef.current) {
+ scheduleShow();
+ }
}, [scheduleShow]);
const handleMouseLeave = useCallback(() => {
- if (!clickLockedRef.current) scheduleHide();
+ if (!clickLockedRef.current) {
+ scheduleHide();
+ }
}, [scheduleHide]);
const handleClick = useCallback(() => {
diff --git a/packages/core/src/TreeList/XDSTreeListItem.tsx b/packages/core/src/TreeList/XDSTreeListItem.tsx
index c0daa777c0..ea7347c700 100644
--- a/packages/core/src/TreeList/XDSTreeListItem.tsx
+++ b/packages/core/src/TreeList/XDSTreeListItem.tsx
@@ -294,9 +294,13 @@ export function XDSTreeListItem({
const handleClick = useMemo(() => {
if (onClick != null || (hasChildren && onToggle != null)) {
return (e: React.MouseEvent) => {
- if (isDisabled) return;
+ if (isDisabled) {
+ return;
+ }
const el = e.target as HTMLElement;
- if (el.closest('button, a, input, select, textarea')) return;
+ if (el.closest('button, a, input, select, textarea')) {
+ return;
+ }
if (onClick != null) {
onClick(e);
} else if (hasChildren && onToggle != null) {
diff --git a/packages/core/src/Typeahead/XDSBaseTypeahead.tsx b/packages/core/src/Typeahead/XDSBaseTypeahead.tsx
index 4d5d95683b..0db655ba70 100644
--- a/packages/core/src/Typeahead/XDSBaseTypeahead.tsx
+++ b/packages/core/src/Typeahead/XDSBaseTypeahead.tsx
@@ -395,7 +395,9 @@ export const XDSBaseTypeahead = function XDSBaseTypeahead<
setHasSearched(true);
try {
const searchResults = await searchSource.search(searchQuery);
- if (searchGenRef.current !== gen) return;
+ if (searchGenRef.current !== gen) {
+ return;
+ }
resultsGenRef.current = gen;
setResults(searchResults.slice(0, maxMenuItems));
setHighlightedIndex(searchResults.length > 0 ? 0 : -1);
@@ -403,7 +405,9 @@ export const XDSBaseTypeahead = function XDSBaseTypeahead<
showLayer();
}
} catch {
- if (searchGenRef.current !== gen) return;
+ if (searchGenRef.current !== gen) {
+ return;
+ }
setResults([]);
setHighlightedIndex(-1);
} finally {
@@ -421,7 +425,9 @@ export const XDSBaseTypeahead = function XDSBaseTypeahead<
setIsLoading(true);
try {
const bootstrapResults = await searchSource.bootstrap();
- if (searchGenRef.current !== gen) return;
+ if (searchGenRef.current !== gen) {
+ return;
+ }
resultsGenRef.current = gen;
setResults(bootstrapResults.slice(0, maxMenuItems));
setHighlightedIndex(bootstrapResults.length > 0 ? 0 : -1);
@@ -429,7 +435,9 @@ export const XDSBaseTypeahead = function XDSBaseTypeahead<
showLayer();
}
} catch {
- if (searchGenRef.current !== gen) return;
+ if (searchGenRef.current !== gen) {
+ return;
+ }
setResults([]);
} finally {
if (searchGenRef.current === gen) {
@@ -512,7 +520,9 @@ export const XDSBaseTypeahead = function XDSBaseTypeahead<
// Handle focus
const handleFocus = useCallback(() => {
- if (isDisabled) return;
+ if (isDisabled) {
+ return;
+ }
if (hasEntriesOnFocus && results.length === 0 && query.length === 0) {
performBootstrap();
} else if (
@@ -538,7 +548,9 @@ export const XDSBaseTypeahead = function XDSBaseTypeahead<
const handleKeyDown = useCallback(
(e: React.KeyboardEvent<HTMLInputElement>) => {
externalOnKeyDown?.(e);
- if (e.defaultPrevented) return;
+ if (e.defaultPrevented) {
+ return;
+ }
if (!popover.isOpen) {
if (e.key === 'ArrowDown' && (hasEntriesOnFocus || query.length > 0)) {
diff --git a/packages/core/src/Typeahead/XDSTypeahead.tsx b/packages/core/src/Typeahead/XDSTypeahead.tsx
index b7f42971ad..a32469c735 100644
--- a/packages/core/src/Typeahead/XDSTypeahead.tsx
+++ b/packages/core/src/Typeahead/XDSTypeahead.tsx
@@ -258,7 +258,9 @@ export function XDSTypeahead<T extends XDSSearchableItem>({
// Enter edit mode: remove token visually, populate input with value label
const handleEnterEditMode = useCallback(() => {
- if (isDisabled || !value) return;
+ if (isDisabled || !value) {
+ return;
+ }
setEditingValue(value);
setIsEditing(true);
// The base will receive onChangeQuery with the value's label
@@ -284,7 +286,9 @@ export function XDSTypeahead<T extends XDSSearchableItem>({
const handleBlur = useCallback(
(e: React.FocusEvent) => {
// Don't restore if focus is moving within the wrapper (e.g. to dropdown)
- if (wrapperRef.current?.contains(e.relatedTarget as Node)) return;
+ if (wrapperRef.current?.contains(e.relatedTarget as Node)) {
+ return;
+ }
if (editingValue && isEditing) {
setIsEditing(false);
@@ -340,7 +344,9 @@ export function XDSTypeahead<T extends XDSSearchableItem>({
// Click wrapper to focus input or enter edit mode
const handleWrapperClick = useCallback(() => {
- if (isDisabled) return;
+ if (isDisabled) {
+ return;
+ }
if (showToken) {
handleEnterEditMode();
} else {
diff --git a/packages/core/src/Typeahead/createStaticSource.ts b/packages/core/src/Typeahead/createStaticSource.ts
index b0d8075301..0fb68b253b 100644
--- a/packages/core/src/Typeahead/createStaticSource.ts
+++ b/packages/core/src/Typeahead/createStaticSource.ts
@@ -62,10 +62,14 @@ export function createStaticSource<T extends XDSSearchableItem>(
return {
search(query: string): T[] {
const lower = query.toLowerCase().trim();
- if (lower === '') return items;
+ if (lower === '') {
+ return items;
+ }
return items.filter(item => {
- if (item.label.toLowerCase().includes(lower)) return true;
+ if (item.label.toLowerCase().includes(lower)) {
+ return true;
+ }
if (getKeywords) {
return getKeywords(item).some(kw => kw.toLowerCase().includes(lower));
}
diff --git a/packages/core/src/hooks/useClickableContainer.ts b/packages/core/src/hooks/useClickableContainer.ts
index 401c6fd368..672f102191 100644
--- a/packages/core/src/hooks/useClickableContainer.ts
+++ b/packages/core/src/hooks/useClickableContainer.ts
@@ -44,10 +44,7 @@ const NON_INTERACTIVE_SELECTORS = '[aria-readonly="true"]';
* If the click target is inside a nested button/link/etc., we should NOT
* handle it at the container level.
*/
-function hasInteractiveAncestor(
- el: Element,
- rootEl: Element,
-): boolean {
+function hasInteractiveAncestor(el: Element, rootEl: Element): boolean {
let current: Element | null = el;
while (current != null && current !== rootEl && current !== document.body) {
if (
@@ -138,16 +135,24 @@ export function useClickableContainer({
const onClick = useCallback(
(event: MouseEvent<HTMLElement>) => {
- if (disabled) return;
+ if (disabled) {
+ return;
+ }
const containerEl = containerRef.current;
- if (!containerEl) return;
+ if (!containerEl) {
+ return;
+ }
// Don't trigger on text selection
- if (hasTextSelection(containerEl)) return;
+ if (hasTextSelection(containerEl)) {
+ return;
+ }
const eventTarget = event.target;
- if (!(eventTarget instanceof Element)) return;
+ if (!(eventTarget instanceof Element)) {
+ return;
+ }
// If the click landed on or inside a nested interactive element, bail
if (
@@ -159,7 +164,9 @@ export function useClickableContainer({
// Fire the click handler
onClickProp?.(event);
- if (event.defaultPrevented) return;
+ if (event.defaultPrevented) {
+ return;
+ }
// Navigate if href is provided
if (href != null) {
@@ -196,13 +203,19 @@ export function useClickableContainer({
const onMouseUp = useCallback(
(event: MouseEvent<HTMLElement>) => {
- if (disabled) return;
+ if (disabled) {
+ return;
+ }
const containerEl = containerRef.current;
- if (!containerEl) return;
+ if (!containerEl) {
+ return;
+ }
const eventTarget = event.target;
- if (!(eventTarget instanceof Element)) return;
+ if (!(eventTarget instanceof Element)) {
+ return;
+ }
// Middle-click on href opens in new tab
const isMiddleClick = event.button === 1;
diff --git a/packages/core/src/hooks/useFocusTrap.ts b/packages/core/src/hooks/useFocusTrap.ts
index cd300af1de..38c1849524 100644
--- a/packages/core/src/hooks/useFocusTrap.ts
+++ b/packages/core/src/hooks/useFocusTrap.ts
@@ -15,7 +15,6 @@
* - /packages/core/src/hooks/index.ts
*/
-
import {useCallback, useEffect, useRef} from 'react';
/**
@@ -119,7 +118,9 @@ export interface UseFocusTrapReturn {
* });
*
* useEffect(() => {
- * if (isOpen) focusFirst();
+ * if (isOpen) {
+ * focusFirst();
+ * }
* }, [isOpen, focusFirst]);
*
* <div ref={containerRef}>
@@ -150,11 +151,15 @@ export function useFocusTrap(options: UseFocusTrapOptions): UseFocusTrapReturn {
* Only redirects for keyboard navigation, not mouse clicks.
*/
useEffect(() => {
- if (!isActive) return;
+ if (!isActive) {
+ return;
+ }
const handleFocus = (event: FocusEvent) => {
const container = containerRef.current;
- if (!container) return;
+ if (!container) {
+ return;
+ }
const target = event.target as Node;
@@ -192,11 +197,15 @@ export function useFocusTrap(options: UseFocusTrapOptions): UseFocusTrapReturn {
* Also tracks that keyboard navigation is occurring.
*/
useEffect(() => {
- if (!isActive) return;
+ if (!isActive) {
+ return;
+ }
const handleKeyDown = (event: KeyboardEvent) => {
const container = containerRef.current;
- if (!container) return;
+ if (!container) {
+ return;
+ }
if (event.key === 'Escape' && onEscape) {
event.preventDefault();
@@ -209,7 +218,9 @@ export function useFocusTrap(options: UseFocusTrapOptions): UseFocusTrapReturn {
isKeyboardNavigationRef.current = true;
const focusable = getFocusableElements(container);
- if (focusable.length === 0) return;
+ if (focusable.length === 0) {
+ return;
+ }
const first = focusable[0];
const last = focusable[focusable.length - 1];
diff --git a/packages/core/src/hooks/useGridFocus.ts b/packages/core/src/hooks/useGridFocus.ts
index 5307cc2402..0f2e2f61db 100644
--- a/packages/core/src/hooks/useGridFocus.ts
+++ b/packages/core/src/hooks/useGridFocus.ts
@@ -13,7 +13,6 @@
* - /packages/core/src/hooks/useGridFocus.test.ts
*/
-
import {useCallback, useRef} from 'react';
/**
@@ -129,7 +128,9 @@ export function useGridFocus(options: UseGridFocusOptions): UseGridFocusReturn {
* Get all focusable cells in the grid.
*/
const getCells = useCallback((): HTMLElement[] => {
- if (!gridRef.current) return [];
+ if (!gridRef.current) {
+ return [];
+ }
return Array.from(
gridRef.current.querySelectorAll<HTMLElement>(cellSelector),
);
@@ -153,7 +154,9 @@ export function useGridFocus(options: UseGridFocusOptions): UseGridFocusReturn {
const focusCellInternal = useCallback(
(index: number, currentColumn: number, offset: number) => {
const cells = getCells();
- if (cells.length === 0) return;
+ if (cells.length === 0) {
+ return;
+ }
if (index < 0) {
onNavigateBefore?.(currentColumn, offset);
@@ -175,7 +178,9 @@ export function useGridFocus(options: UseGridFocusOptions): UseGridFocusReturn {
const focusCell = useCallback(
(index: number) => {
const cells = getCells();
- if (cells.length === 0) return;
+ if (cells.length === 0) {
+ return;
+ }
const clampedIndex = Math.max(0, Math.min(index, cells.length - 1));
cells[clampedIndex]?.focus();
},
@@ -204,7 +209,9 @@ export function useGridFocus(options: UseGridFocusOptions): UseGridFocusReturn {
const handleKeyDown = useCallback(
(e: React.KeyboardEvent) => {
const currentIndex = getCurrentIndex();
- if (currentIndex === -1) return;
+ if (currentIndex === -1) {
+ return;
+ }
const cells = getCells();
const currentRow = Math.floor(currentIndex / columns);
diff --git a/packages/core/src/hooks/useImageMode.ts b/packages/core/src/hooks/useImageMode.ts
index cd2f3221b2..56d40fb405 100644
--- a/packages/core/src/hooks/useImageMode.ts
+++ b/packages/core/src/hooks/useImageMode.ts
@@ -120,7 +120,9 @@ export function useImageMode(
const blob = await response.blob();
const bitmap = await createImageBitmap(blob);
- if (cancelled) return;
+ if (cancelled) {
+ return;
+ }
// Determine source region
const sx = region ? Math.round(region.x * bitmap.width) : 0;
@@ -138,7 +140,9 @@ export function useImageMode(
const sampleSize = 10;
const canvas = new OffscreenCanvas(sampleSize, sampleSize);
const ctx = canvas.getContext('2d');
- if (!ctx) return;
+ if (!ctx) {
+ return;
+ }
ctx.drawImage(bitmap, sx, sy, sw, sh, 0, 0, sampleSize, sampleSize);
const imageData = ctx.getImageData(0, 0, sampleSize, sampleSize).data;
@@ -157,13 +161,17 @@ export function useImageMode(
const g = totalG / pixelCount;
const b = totalB / pixelCount;
- if (cancelled) return;
+ if (cancelled) {
+ return;
+ }
const lightness = perceptualLightness(r, g, b);
setMode(lightness > threshold ? 'light' : 'dark');
} catch {
// CORS error, network error, etc. — keep fallback
- if (!cancelled) setMode(fallback);
+ if (!cancelled) {
+ setMode(fallback);
+ }
}
}
diff --git a/packages/core/src/hooks/useInputContainer.ts b/packages/core/src/hooks/useInputContainer.ts
index 68cdb543c1..c6588c5bcf 100644
--- a/packages/core/src/hooks/useInputContainer.ts
+++ b/packages/core/src/hooks/useInputContainer.ts
@@ -80,7 +80,9 @@ export function useInputContainer({
}: UseInputContainerOptions) {
const onClick = useCallback(() => {
const input = inputRef.current;
- if (input == null) return;
+ if (input == null) {
+ return;
+ }
if (
input instanceof HTMLInputElement &&
FOCUS_INPUT_TYPES.has(input.type)
diff --git a/packages/core/src/hooks/useListFocus.ts b/packages/core/src/hooks/useListFocus.ts
index a327b057f5..535d8374c7 100644
--- a/packages/core/src/hooks/useListFocus.ts
+++ b/packages/core/src/hooks/useListFocus.ts
@@ -110,7 +110,9 @@ export function useListFocus(
* Get all focusable items in the list.
*/
const getItems = useCallback((): HTMLElement[] => {
- if (!listRef.current) return [];
+ if (!listRef.current) {
+ return [];
+ }
return Array.from(
listRef.current.querySelectorAll<HTMLElement>(itemSelector),
);
@@ -133,7 +135,9 @@ export function useListFocus(
const focusItem = useCallback(
(index: number) => {
const items = getItems();
- if (items.length === 0) return;
+ if (items.length === 0) {
+ return;
+ }
const clampedIndex = Math.max(0, Math.min(index, items.length - 1));
items[clampedIndex]?.focus();
},
diff --git a/packages/core/src/hooks/useMediaQuery.test.ts b/packages/core/src/hooks/useMediaQuery.test.ts
index a5d909c616..405d8248f8 100644
--- a/packages/core/src/hooks/useMediaQuery.test.ts
+++ b/packages/core/src/hooks/useMediaQuery.test.ts
@@ -28,7 +28,9 @@ function createMockMatchMedia(matches: boolean) {
removeEventListener: vi.fn(
(_event: string, handler: (e: MediaQueryListEvent) => void) => {
const index = listeners.indexOf(handler);
- if (index > -1) listeners.splice(index, 1);
+ if (index > -1) {
+ listeners.splice(index, 1);
+ }
},
),
dispatchEvent: vi.fn(),
diff --git a/packages/core/src/hooks/useOverflow.ts b/packages/core/src/hooks/useOverflow.ts
index a8456bc63d..844486a72c 100644
--- a/packages/core/src/hooks/useOverflow.ts
+++ b/packages/core/src/hooks/useOverflow.ts
@@ -102,7 +102,9 @@ export function useOverflow(
const calculate = useCallback(() => {
const container = containerElRef.current;
const measure = measureElRef.current;
- if (!container || !measure) return;
+ if (!container || !measure) {
+ return;
+ }
let availableWidth: number;
diff --git a/packages/core/src/hooks/useScrollLock.ts b/packages/core/src/hooks/useScrollLock.ts
index 403163471d..a328657bc3 100644
--- a/packages/core/src/hooks/useScrollLock.ts
+++ b/packages/core/src/hooks/useScrollLock.ts
@@ -32,7 +32,9 @@ import {useEffect} from 'react';
*/
export function useScrollLock(isLocked: boolean): void {
useEffect(() => {
- if (!isLocked) return;
+ if (!isLocked) {
+ return;
+ }
const scrollX = window.scrollX;
const scrollY = window.scrollY;
diff --git a/packages/core/src/hooks/useScrollOverflow.ts b/packages/core/src/hooks/useScrollOverflow.ts
index 67ca58e5a0..477b047e9c 100644
--- a/packages/core/src/hooks/useScrollOverflow.ts
+++ b/packages/core/src/hooks/useScrollOverflow.ts
@@ -50,7 +50,9 @@ export function useScrollOverflow() {
const measure = useCallback(() => {
const el = elRef.current;
- if (!el) return;
+ if (!el) {
+ return;
+ }
const tolerance = 1;
const {scrollLeft, scrollWidth, clientWidth} = el;
diff --git a/packages/core/src/hooks/useXDSMenuHover.ts b/packages/core/src/hooks/useXDSMenuHover.ts
index 1601e28335..3884fc05af 100644
--- a/packages/core/src/hooks/useXDSMenuHover.ts
+++ b/packages/core/src/hooks/useXDSMenuHover.ts
@@ -121,7 +121,9 @@ export function useXDSMenuHover(
// Hover: mouseenter activates hover mode and opens
const handleMouseEnter = useCallback(() => {
- if (!hasHover) return;
+ if (!hasHover) {
+ return;
+ }
if (skipNextEnterRef.current) {
skipNextEnterRef.current = false;
return;
@@ -139,7 +141,9 @@ export function useXDSMenuHover(
// Hover: mouseleave only closes if in hover mode
const handleMouseLeave = useCallback(() => {
- if (!hoverModeRef.current) return;
+ if (!hoverModeRef.current) {
+ return;
+ }
clearTimeouts();
hideTimerRef.current = setTimeout(() => {
hide();
diff --git a/packages/core/src/hooks/useXDSStreamingText.ts b/packages/core/src/hooks/useXDSStreamingText.ts
index 3123fe7a42..dd3860da2b 100644
--- a/packages/core/src/hooks/useXDSStreamingText.ts
+++ b/packages/core/src/hooks/useXDSStreamingText.ts
@@ -51,9 +51,13 @@ const FALLBACK_TICK_MS_FAST = 8;
*/
function parseDuration(value: string): number | null {
const ms = value.match(/^([\d.]+)ms$/);
- if (ms) return parseFloat(ms[1]);
+ if (ms) {
+ return parseFloat(ms[1]);
+ }
const s = value.match(/^([\d.]+)s$/);
- if (s) return parseFloat(s[1]) * 1000;
+ if (s) {
+ return parseFloat(s[1]) * 1000;
+ }
return null;
}
@@ -97,7 +101,9 @@ export function useXDSStreamingText(
// fast → half that, floored at 4ms (roughly 2x speed)
const {token} = useXDSTheme();
const tickMs = useMemo(() => {
- if (speed === 'instant') return 0;
+ if (speed === 'instant') {
+ return 0;
+ }
const base = parseDuration(token('--duration-fast-min'));
if (base == null) {
return speed === 'fast' ? FALLBACK_TICK_MS_FAST : FALLBACK_TICK_MS;
@@ -130,7 +136,9 @@ export function useXDSStreamingText(
// Animation loop
useEffect(() => {
- if (!isStreaming || speed === 'instant') return;
+ if (!isStreaming || speed === 'instant') {
+ return;
+ }
function tick(now: number) {
const elapsed = now - lastTickRef.current;
diff --git a/packages/core/src/theme/XDSTheme.tsx b/packages/core/src/theme/XDSTheme.tsx
index 2345135815..dcae5f41a5 100644
--- a/packages/core/src/theme/XDSTheme.tsx
+++ b/packages/core/src/theme/XDSTheme.tsx
@@ -107,10 +107,14 @@ function useThemeStyleInjection(theme: XDSDefinedTheme): void {
useInsertionEffect(() => {
// Built themes have their CSS in a separate file — skip injection
- if (theme.__built) return;
+ if (theme.__built) {
+ return;
+ }
const themeKey = `xds-theme-${theme.name}`;
- if (injectedThemes.has(themeKey)) return;
+ if (injectedThemes.has(themeKey)) {
+ return;
+ }
// One-time perf hint per theme
if (!warnedThemes.has(theme.name)) {
@@ -126,7 +130,9 @@ function useThemeStyleInjection(theme: XDSDefinedTheme): void {
}
const {prose, component} = generateThemeCSS(theme);
- if (!prose && !component) return;
+ if (!prose && !component) {
+ return;
+ }
// Prose defaults go into @layer reset — lowest priority, scoped to
// the theme region. Any class-based style (StyleX, .xds-*) wins.
@@ -188,8 +194,12 @@ function useRootThemeSync(
themeName: string,
): void {
useIsomorphicLayoutEffect(() => {
- if (isNested) return;
- if (typeof document === 'undefined') return;
+ if (isNested) {
+ return;
+ }
+ if (typeof document === 'undefined') {
+ return;
+ }
if (mode === 'light' || mode === 'dark') {
document.documentElement.setAttribute('data-theme', mode);
diff --git a/packages/core/src/theme/defineTheme.ts b/packages/core/src/theme/defineTheme.ts
index fb4f0f9f49..79d4345f48 100644
--- a/packages/core/src/theme/defineTheme.ts
+++ b/packages/core/src/theme/defineTheme.ts
@@ -404,9 +404,15 @@ function deepMergeComponents(
base?: XDSComponentStyleMap,
overrides?: XDSComponentStyleMap,
): XDSComponentStyleMap | undefined {
- if (!base && !overrides) return undefined;
- if (!base) return overrides;
- if (!overrides) return base;
+ if (!base && !overrides) {
+ return undefined;
+ }
+ if (!base) {
+ return overrides;
+ }
+ if (!overrides) {
+ return base;
+ }
const result: XDSComponentStyleMap = {};
@@ -454,9 +460,13 @@ function buildFontFamily(
family?: string,
fallbacks?: string,
): string | undefined {
- if (!family) return undefined;
+ if (!family) {
+ return undefined;
+ }
const quoted = family.includes(' ') ? `"${family}"` : family;
- if (fallbacks) return `${quoted}, ${fallbacks}`;
+ if (fallbacks) {
+ return `${quoted}, ${fallbacks}`;
+ }
return quoted;
}
@@ -490,9 +500,10 @@ export function defineTheme(input: XDSDefineThemeInput): XDSDefinedTheme {
const headingRole = typo.heading;
if (headingRole?.weights) {
for (const [level, w] of Object.entries(headingRole.weights)) {
- if (w)
+ if (w) {
headingWeights[Number(level) as 1 | 2 | 3 | 4 | 5 | 6] =
resolveFontWeight(w);
+ }
}
}
// Default heading weight from role
@@ -509,10 +520,12 @@ export function defineTheme(input: XDSDefineThemeInput): XDSDefinedTheme {
// Text weight overrides from roles
const textWeights: Partial<Record<string, string>> = {};
- if (typo.body?.weight)
+ if (typo.body?.weight) {
textWeights.body = resolveFontWeight(typo.body.weight);
- if (typo.code?.weight)
+ }
+ if (typo.code?.weight) {
textWeights.code = resolveFontWeight(typo.code.weight);
+ }
typeScaleConfig = {
base: typo.scale.base,
@@ -567,9 +580,15 @@ export function defineTheme(input: XDSDefineThemeInput): XDSDefinedTheme {
bodyFamily;
const codeFamily = buildFontFamily(typo.code?.family, typo.code?.fallbacks);
- if (bodyFamily) tokens['--font-family-body'] = bodyFamily;
- if (headingFamily) tokens['--font-family-heading'] = headingFamily;
- if (codeFamily) tokens['--font-family-code'] = codeFamily;
+ if (bodyFamily) {
+ tokens['--font-family-body'] = bodyFamily;
+ }
+ if (headingFamily) {
+ tokens['--font-family-heading'] = headingFamily;
+ }
+ if (codeFamily) {
+ tokens['--font-family-code'] = codeFamily;
+ }
}
// 1e. Apply syntax theme tokens (before explicit overrides)
@@ -1086,7 +1105,9 @@ export function generateOnMediaCSS(theme: XDSDefinedTheme): string {
for (const surface of ['dark', 'light'] as const) {
const onMedia = surface === 'dark' ? theme.__onDark : theme.__onLight;
- if (!onMedia) continue;
+ if (!onMedia) {
+ continue;
+ }
// Token overrides
const tokenEntries = Object.entries(onMedia.tokens);
@@ -1146,7 +1167,9 @@ export function generateOnMediaCSS(theme: XDSDefinedTheme): string {
}
}
- if (parts.length === 0) return '';
+ if (parts.length === 0) {
+ return '';
+ }
const inner = parts.join('\n\n');
return `@scope (${scopeSelector}) to ([data-xds-theme]) {\n${inner}\n}`;
@@ -1188,7 +1211,9 @@ export function generateThemeCSS(theme: XDSDefinedTheme): ThemeCSSOutput {
*/
export function generateThemeCSSFlat(theme: XDSDefinedTheme): string {
const rules = generateThemeRules(theme);
- if (rules.length === 0) return '';
+ if (rules.length === 0) {
+ return '';
+ }
const scopeSelector = `[data-xds-theme="${theme.name}"]`;
const inner = rules.join('\n\n');
return `@scope (${scopeSelector}) to ([data-xds-theme]) {\n${inner}\n}`;
diff --git a/packages/core/src/theme/derivedVarRegistry.test.ts b/packages/core/src/theme/derivedVarRegistry.test.ts
index 0a8c299e09..d20258c2fe 100644
--- a/packages/core/src/theme/derivedVarRegistry.test.ts
+++ b/packages/core/src/theme/derivedVarRegistry.test.ts
@@ -71,14 +71,21 @@ function extractComponentVars(filePath: string): string[] {
/^--(color|spacing|radius|shadow|duration|ease|transition|font|text|size)-/.test(
varName,
)
- )
+ ) {
continue;
+ }
// Skip structural vars
- if (STRUCTURAL_VARS.has(varName)) continue;
+ if (STRUCTURAL_VARS.has(varName)) {
+ continue;
+ }
// Skip vars that start with structural prefixes
- if (/^--(container-|layout-|edge-|component-)/.test(varName)) continue;
+ if (/^--(container-|layout-|edge-|component-)/.test(varName)) {
+ continue;
+ }
// Skip private vars (--_ prefix = internal, not themeable)
- if (varName.startsWith('--_')) continue;
+ if (varName.startsWith('--_')) {
+ continue;
+ }
vars.add(varName);
}
return [...vars];
@@ -120,11 +127,15 @@ function discoverComponents(): ComponentInfo[] {
allVars.add(v);
}
}
- if (allVars.size === 0) continue;
+ if (allVars.size === 0) {
+ continue;
+ }
// Only check component directories (those with a doc file)
const docPath = join(dirPath, `${dir}.doc.mjs`);
- if (!existsSync(docPath)) continue;
+ if (!existsSync(docPath)) {
+ continue;
+ }
let docVars: string[] = [];
let docDerived: any[] = [];
@@ -213,11 +224,17 @@ describe('component CSS vars are documented and themeable', () => {
const missingDerived = docVars.filter(varName => {
// Cross-component vars are handled by the owning component
- if (crossVars.has(varName)) return false;
+ if (crossVars.has(varName)) {
+ return false;
+ }
// Check if this var is covered by a derived entry
- if (derivedVarNames.has(varName)) return false;
+ if (derivedVarNames.has(varName)) {
+ return false;
+ }
// Container expansion covers padding-related vars
- if (hasContainerExpand && varName.includes('padding')) return false;
+ if (hasContainerExpand && varName.includes('padding')) {
+ return false;
+ }
return true;
});
@@ -244,7 +261,9 @@ describe('derivedVarRegistry ↔ doc file consistency', () => {
for (const {dir, docDerived} of components) {
const key = DIR_TO_REGISTRY_KEY[dir];
- if (!key || docDerived.length === 0) continue;
+ if (!key || docDerived.length === 0) {
+ continue;
+ }
it(`${dir} (${key}): registry matches doc derived`, () => {
const registryEntries = derivedVarRegistry[key];
@@ -257,7 +276,9 @@ describe('derivedVarRegistry ↔ doc file consistency', () => {
it('every doc with theming.derived has a registry mapping', () => {
const missing: string[] = [];
for (const {dir, docDerived} of components) {
- if (docDerived.length === 0) continue;
+ if (docDerived.length === 0) {
+ continue;
+ }
const key = DIR_TO_REGISTRY_KEY[dir];
if (!key) {
missing.push(
diff --git a/packages/core/src/theme/derivedVarRegistry.ts b/packages/core/src/theme/derivedVarRegistry.ts
index 683e5710f5..3a037c2f4a 100644
--- a/packages/core/src/theme/derivedVarRegistry.ts
+++ b/packages/core/src/theme/derivedVarRegistry.ts
@@ -72,6 +72,8 @@ export function getDerivedVars(
property: string,
): DerivedVarEntry[] {
const entries = derivedVarRegistry[component];
- if (!entries) return [];
+ if (!entries) {
+ return [];
+ }
return entries.filter(e => e.property === property);
}
diff --git a/packages/core/src/theme/hct.ts b/packages/core/src/theme/hct.ts
index 6382747afb..044f13150b 100644
--- a/packages/core/src/theme/hct.ts
+++ b/packages/core/src/theme/hct.ts
@@ -156,7 +156,9 @@ export function hexToHct(hex: string): HCT {
const hueRad = Math.atan2(bLab, a);
let hue = (hueRad * 180) / Math.PI;
- if (hue < 0) hue += 360;
+ if (hue < 0) {
+ hue += 360;
+ }
const chroma = Math.sqrt(a * a + bLab * bLab);
const tone = L;
@@ -171,8 +173,12 @@ export function hexToHct(hex: string): HCT {
export function hctToHex(hct: HCT): string {
const {hue, chroma, tone} = hct;
- if (tone <= 0) return '#000000';
- if (tone >= 100) return '#FFFFFF';
+ if (tone <= 0) {
+ return '#000000';
+ }
+ if (tone >= 100) {
+ return '#FFFFFF';
+ }
if (chroma < 0.5) {
const gray = toneToGray(tone);
return rgbToHex(gray, gray, gray);
diff --git a/packages/core/src/theme/syntax/XDSSyntaxTheme.tsx b/packages/core/src/theme/syntax/XDSSyntaxTheme.tsx
index 387c87fe25..6ca8cf2e65 100644
--- a/packages/core/src/theme/syntax/XDSSyntaxTheme.tsx
+++ b/packages/core/src/theme/syntax/XDSSyntaxTheme.tsx
@@ -66,7 +66,9 @@ export interface UseXDSSyntaxThemeReturn {
* @example
* function CodeCanvas() {
* const syntax = useXDSSyntaxTheme();
- * if (!syntax) return null;
+ * if (!syntax) {
+ * return null;
+ * }
* ctx.fillStyle = syntax.token('keyword');
* }
*/
@@ -76,7 +78,9 @@ export function useXDSSyntaxTheme(): UseXDSSyntaxThemeReturn | null {
const effectiveMode: 'light' | 'dark' = prefersDark ? 'dark' : 'light';
const tokens = useMemo(() => {
- if (!ctx) return null;
+ if (!ctx) {
+ return null;
+ }
const resolved: Partial<Record<SyntaxThemeTokenKey, string>> = {};
for (const key of ALL_SYNTAX_KEYS) {
resolved[key] = resolveSyntaxTokenForMode(
@@ -87,7 +91,9 @@ export function useXDSSyntaxTheme(): UseXDSSyntaxThemeReturn | null {
return resolved as Record<SyntaxThemeTokenKey, string>;
}, [ctx, effectiveMode]);
- if (!ctx || !tokens) return null;
+ if (!ctx || !tokens) {
+ return null;
+ }
return {
name: ctx.theme.name,
diff --git a/packages/core/src/utils/dateParser.ts b/packages/core/src/utils/dateParser.ts
index c4f3e40d99..7bb0d047de 100644
--- a/packages/core/src/utils/dateParser.ts
+++ b/packages/core/src/utils/dateParser.ts
@@ -40,7 +40,9 @@ export function isLocaleDayFirst(): boolean {
*/
export function parseDateInput(input: string): ISODateString | null {
const trimmed = input.trim();
- if (!trimmed) return null;
+ if (!trimmed) {
+ return null;
+ }
const currentYear = new Date().getFullYear();
@@ -104,7 +106,9 @@ export function parseDateInput(input: string): ISODateString | null {
if (numericWithYearMatch) {
const [, first, sep1, second, sep2, year] = numericWithYearMatch;
// Reject mixed separators (e.g., "1/25.2026")
- if (sep1 !== sep2) return null;
+ if (sep1 !== sep2) {
+ return null;
+ }
return parseNumericDate(+first, +second, +year);
}
diff --git a/packages/core/src/utils/parseStyleKey.ts b/packages/core/src/utils/parseStyleKey.ts
index baef6e616b..48c8587527 100644
--- a/packages/core/src/utils/parseStyleKey.ts
+++ b/packages/core/src/utils/parseStyleKey.ts
@@ -30,7 +30,9 @@
* ```
*/
export function parseStyleKey(key: string): string {
- if (key === 'base') return '';
+ if (key === 'base') {
+ return '';
+ }
return key
.split('+')
diff --git a/packages/core/src/utils/sharedResizeObserver.ts b/packages/core/src/utils/sharedResizeObserver.ts
index 2842e5ffc7..ff75c37b54 100644
--- a/packages/core/src/utils/sharedResizeObserver.ts
+++ b/packages/core/src/utils/sharedResizeObserver.ts
@@ -26,10 +26,12 @@ const callbacks = new Map<Element, ResizeCallback>();
function getObserver(): ResizeObserver {
if (!observer) {
- observer = new ResizeObserver((entries) => {
+ observer = new ResizeObserver(entries => {
for (const entry of entries) {
const cb = callbacks.get(entry.target);
- if (cb) cb(entry);
+ if (cb) {
+ cb(entry);
+ }
}
});
}
diff --git a/packages/core/src/utils/timeParser.ts b/packages/core/src/utils/timeParser.ts
index 82cd797d45..b45b25d95e 100644
--- a/packages/core/src/utils/timeParser.ts
+++ b/packages/core/src/utils/timeParser.ts
@@ -30,7 +30,9 @@ export interface ParsedTime {
*/
export function createISOTimeString(value: string): ISOTimeString | null {
const parsed = parseISOTime(value);
- if (!parsed) return null;
+ if (!parsed) {
+ return null;
+ }
return formatISOTime(parsed, value.split(':').length === 3);
}
@@ -39,10 +41,14 @@ export function createISOTimeString(value: string): ISOTimeString | null {
* Accepts HH:MM or HH:MM:SS format.
*/
export function parseISOTime(time: string): ParsedTime | null {
- if (!time) return null;
+ if (!time) {
+ return null;
+ }
const parts = time.split(':');
- if (parts.length < 2 || parts.length > 3) return null;
+ if (parts.length < 2 || parts.length > 3) {
+ return null;
+ }
const hour = parseInt(parts[0], 10);
const minute = parseInt(parts[1], 10);
@@ -91,10 +97,14 @@ export function formatDisplayTime12h(
time: ISOTimeString | undefined,
includeSeconds: boolean = false,
): string {
- if (!time) return '';
+ if (!time) {
+ return '';
+ }
const parsed = parseISOTime(time);
- if (!parsed) return '';
+ if (!parsed) {
+ return '';
+ }
const hour12 =
parsed.hour === 0 ? 12 : parsed.hour > 12 ? parsed.hour - 12 : parsed.hour;
@@ -117,10 +127,14 @@ export function formatDisplayTime24h(
time: ISOTimeString | undefined,
includeSeconds: boolean = false,
): string {
- if (!time) return '';
+ if (!time) {
+ return '';
+ }
const parsed = parseISOTime(time);
- if (!parsed) return '';
+ if (!parsed) {
+ return '';
+ }
const hh = parsed.hour.toString().padStart(2, '0');
const mm = parsed.minute.toString().padStart(2, '0');
@@ -144,7 +158,9 @@ export function parseTimeInput(
input: string,
includeSeconds: boolean = false,
): ISOTimeString | null {
- if (!input) return null;
+ if (!input) {
+ return null;
+ }
const trimmed = input.trim().toLowerCase();
@@ -161,8 +177,12 @@ export function parseTimeInput(
const hour = parseInt(timeStr, 10);
if (hour >= 1 && hour <= 12 && hasMeridiem) {
let hour24 = hour;
- if (isPM && hour !== 12) hour24 = hour + 12;
- if (isAM && hour === 12) hour24 = 0;
+ if (isPM && hour !== 12) {
+ hour24 = hour + 12;
+ }
+ if (isAM && hour === 12) {
+ hour24 = 0;
+ }
return formatISOTime(
{hour: hour24, minute: 0, second: 0},
includeSeconds,
@@ -209,16 +229,28 @@ export function parseTimeInput(
const minute = parseInt(colonParts[1], 10);
const second = colonParts.length === 3 ? parseInt(colonParts[2], 10) : 0;
- if (isNaN(hour) || isNaN(minute) || isNaN(second)) return null;
- if (minute < 0 || minute > 59 || second < 0 || second > 59) return null;
+ if (isNaN(hour) || isNaN(minute) || isNaN(second)) {
+ return null;
+ }
+ if (minute < 0 || minute > 59 || second < 0 || second > 59) {
+ return null;
+ }
// Convert 12h to 24h if meridiem present
if (hasMeridiem) {
- if (hour < 1 || hour > 12) return null;
- if (isPM && hour !== 12) hour += 12;
- if (isAM && hour === 12) hour = 0;
+ if (hour < 1 || hour > 12) {
+ return null;
+ }
+ if (isPM && hour !== 12) {
+ hour += 12;
+ }
+ if (isAM && hour === 12) {
+ hour = 0;
+ }
} else {
- if (hour < 0 || hour > 23) return null;
+ if (hour < 0 || hour > 23) {
+ return null;
+ }
}
return formatISOTime({hour, minute, second}, includeSeconds);
@@ -237,16 +269,28 @@ export function compareTime(
a: ISOTimeString | undefined,
b: ISOTimeString | undefined,
): number {
- if (!a && !b) return 0;
- if (!a) return -1;
- if (!b) return 1;
+ if (!a && !b) {
+ return 0;
+ }
+ if (!a) {
+ return -1;
+ }
+ if (!b) {
+ return 1;
+ }
const parsedA = parseISOTime(a);
const parsedB = parseISOTime(b);
- if (!parsedA && !parsedB) return 0;
- if (!parsedA) return -1;
- if (!parsedB) return 1;
+ if (!parsedA && !parsedB) {
+ return 0;
+ }
+ if (!parsedA) {
+ return -1;
+ }
+ if (!parsedB) {
+ return 1;
+ }
const totalA = parsedA.hour * 3600 + parsedA.minute * 60 + parsedA.second;
const totalB = parsedB.hour * 3600 + parsedB.minute * 60 + parsedB.second;
@@ -262,8 +306,12 @@ export function isTimeInRange(
min?: ISOTimeString,
max?: ISOTimeString,
): boolean {
- if (min && compareTime(time, min) < 0) return false;
- if (max && compareTime(time, max) > 0) return false;
+ if (min && compareTime(time, min) < 0) {
+ return false;
+ }
+ if (max && compareTime(time, max) > 0) {
+ return false;
+ }
return true;
}
@@ -277,15 +325,21 @@ export function clampTime(
includeSeconds: boolean = false,
): ISOTimeString {
const parsed = parseISOTime(time);
- if (!parsed) return time;
+ if (!parsed) {
+ return time;
+ }
if (min && compareTime(time, min) < 0) {
const parsedMin = parseISOTime(min);
- if (parsedMin) return formatISOTime(parsedMin, includeSeconds);
+ if (parsedMin) {
+ return formatISOTime(parsedMin, includeSeconds);
+ }
}
if (max && compareTime(time, max) > 0) {
const parsedMax = parseISOTime(max);
- if (parsedMax) return formatISOTime(parsedMax, includeSeconds);
+ if (parsedMax) {
+ return formatISOTime(parsedMax, includeSeconds);
+ }
}
return time;
@@ -300,12 +354,16 @@ export function adjustTime(
includeSeconds: boolean = false,
): ISOTimeString {
const parsed = parseISOTime(time);
- if (!parsed) return time;
+ if (!parsed) {
+ return time;
+ }
let totalMinutes = parsed.hour * 60 + parsed.minute + deltaMinutes;
// Wrap around midnight
- while (totalMinutes < 0) totalMinutes += 24 * 60;
+ while (totalMinutes < 0) {
+ totalMinutes += 24 * 60;
+ }
totalMinutes = totalMinutes % (24 * 60);
const newHour = Math.floor(totalMinutes / 60);
diff --git a/packages/core/src/utils/xdsClassName.ts b/packages/core/src/utils/xdsClassName.ts
index 3d1a5a68a8..65240c0043 100644
--- a/packages/core/src/utils/xdsClassName.ts
+++ b/packages/core/src/utils/xdsClassName.ts
@@ -37,7 +37,9 @@ export function xdsClassName(
if (props) {
for (const [prop, value] of Object.entries(props)) {
- if (value == null) continue;
+ if (value == null) {
+ continue;
+ }
const strValue = String(value);
// CSS classes can't start with a digit — prefix with prop name
if (/^\d/.test(strValue)) {
diff --git a/packages/lab/src/Chart/XDSChart.tsx b/packages/lab/src/Chart/XDSChart.tsx
index b66142e61f..36ecfc05dc 100644
--- a/packages/lab/src/Chart/XDSChart.tsx
+++ b/packages/lab/src/Chart/XDSChart.tsx
@@ -109,10 +109,14 @@ export function XDSChart({
const [containerWidth, setContainerWidth] = useState(0);
useLayoutEffect(() => {
- if (!containerRef.current) return;
+ if (!containerRef.current) {
+ return;
+ }
const observer = new ResizeObserver(entries => {
const entry = entries[0];
- if (entry) setContainerWidth(entry.contentRect.width);
+ if (entry) {
+ setContainerWidth(entry.contentRect.width);
+ }
});
observer.observe(containerRef.current);
return () => observer.disconnect();
@@ -122,7 +126,9 @@ export function XDSChart({
// Must be non-passive to actually prevent default on touch events.
useLayoutEffect(() => {
const el = containerRef.current;
- if (!el || !interactive) return;
+ if (!el || !interactive) {
+ return;
+ }
const prevent = (e: TouchEvent) => e.preventDefault();
el.addEventListener('touchstart', prevent, {passive: false});
el.addEventListener('touchmove', prevent, {passive: false});
@@ -154,8 +160,12 @@ export function XDSChart({
let min = Infinity;
let max = -Infinity;
for (const n of nums) {
- if (n < min) min = n;
- if (n > max) max = n;
+ if (n < min) {
+ min = n;
+ }
+ if (n > max) {
+ max = n;
+ }
}
return scaleLinear().domain([min, max]).range([0, innerWidth]).nice();
}
@@ -182,8 +192,12 @@ export function XDSChart({
for (const key of yKeys) {
const v = d[key];
if (typeof v === 'number') {
- if (v < min) min = v;
- if (v > max) max = v;
+ if (v < min) {
+ min = v;
+ }
+ if (v > max) {
+ max = v;
+ }
}
}
}
@@ -193,8 +207,12 @@ export function XDSChart({
min = -abs;
max = abs;
} else if (yBaseline === 'auto') {
- if (min > 0) min = 0;
- if (max < 0) max = 0;
+ if (min > 0) {
+ min = 0;
+ }
+ if (max < 0) {
+ max = 0;
+ }
}
return scaleLinear().domain([min, max]).range([innerHeight, 0]).nice();
@@ -223,7 +241,9 @@ export function XDSChart({
const pointerToData = useCallback(
(e: React.PointerEvent) => {
const svg = svgRef.current;
- if (!svg) return {x: null, y: 0, px: 0, py: 0};
+ if (!svg) {
+ return {x: null, y: 0, px: 0, py: 0};
+ }
const pt = svg.createSVGPoint();
pt.x = e.clientX;
pt.y = e.clientY;
diff --git a/packages/lab/src/Chart/XDSChartArea.tsx b/packages/lab/src/Chart/XDSChartArea.tsx
index 7a9ca2badf..8bc1712a9d 100644
--- a/packages/lab/src/Chart/XDSChartArea.tsx
+++ b/packages/lab/src/Chart/XDSChartArea.tsx
@@ -53,7 +53,9 @@ export function XDSChartArea({
const lowerKey = yLower ?? baseline;
const pathD = useMemo(() => {
- if (!upperKey || !lowerKey) return '';
+ if (!upperKey || !lowerKey) {
+ return '';
+ }
const generator = area<Record<string, unknown>>()
.x(d => xPixel(d, xKey, xScale))
.y0(d => {
@@ -68,7 +70,9 @@ export function XDSChartArea({
return generator(data) ?? '';
}, [data, xKey, xScale, yScale, upperKey, lowerKey]);
- if (!pathD) return null;
+ if (!pathD) {
+ return null;
+ }
return (
<g>
diff --git a/packages/lab/src/Chart/XDSChartAxis.tsx b/packages/lab/src/Chart/XDSChartAxis.tsx
index 064b36236e..10f7bf2d4a 100644
--- a/packages/lab/src/Chart/XDSChartAxis.tsx
+++ b/packages/lab/src/Chart/XDSChartAxis.tsx
@@ -70,7 +70,9 @@ export function XDSChartAxis({
// For the bottom axis, draw the axis line at y=0 when the domain spans negative values
const axisLineY = (() => {
- if (position !== 'bottom') return 0;
+ if (position !== 'bottom') {
+ return 0;
+ }
const domain = yScale.domain();
if (domain[0] < 0 && domain[1] > 0) {
// The axis line should appear at the zero mark relative to the bottom edge
diff --git a/packages/lab/src/Chart/XDSChartBar.tsx b/packages/lab/src/Chart/XDSChartBar.tsx
index 7523ab9669..198b79fcda 100644
--- a/packages/lab/src/Chart/XDSChartBar.tsx
+++ b/packages/lab/src/Chart/XDSChartBar.tsx
@@ -30,7 +30,9 @@ export interface XDSChartBarProps {
export function XDSChartBar({dataKey, color, radius = 4}: XDSChartBarProps) {
const {data, xKey, xScale, yScale} = useChart();
- if (!isBandScale(xScale)) return null;
+ if (!isBandScale(xScale)) {
+ return null;
+ }
// Zero line position — bars grow from here
const zeroY = yScale(0);
@@ -39,7 +41,9 @@ export function XDSChartBar({dataKey, color, radius = 4}: XDSChartBarProps) {
<g>
{data.map((d, i) => {
const xVal = xScale(String(d[xKey]));
- if (xVal == null) return null;
+ if (xVal == null) {
+ return null;
+ }
const yVal =
typeof d[dataKey] === 'number' ? (d[dataKey] as number) : 0;
diff --git a/packages/lab/src/Chart/XDSChartBrush.tsx b/packages/lab/src/Chart/XDSChartBrush.tsx
index 776bea61e5..71e4d42471 100644
--- a/packages/lab/src/Chart/XDSChartBrush.tsx
+++ b/packages/lab/src/Chart/XDSChartBrush.tsx
@@ -62,7 +62,9 @@ function localCoords(e: React.PointerEvent<SVGRectElement>): {
y: number;
} {
const svg = e.currentTarget.ownerSVGElement;
- if (!svg) return {x: 0, y: 0};
+ if (!svg) {
+ return {x: 0, y: 0};
+ }
const pt = svg.createSVGPoint();
pt.x = e.clientX;
pt.y = e.clientY;
@@ -109,7 +111,9 @@ export function XDSChartBrush({
const onPointerMove = useCallback(
(e: React.PointerEvent<SVGRectElement>) => {
- if (!dragging.current) return;
+ if (!dragging.current) {
+ return;
+ }
const {x, y} = localCoords(e);
const {x: sx, y: sy} = startRef.current;
@@ -134,7 +138,9 @@ export function XDSChartBrush({
const onPointerUp = useCallback(() => {
dragging.current = false;
- if (!brush) return;
+ if (!brush) {
+ return;
+ }
const dx = Math.abs(brush.x1 - brush.x0);
const dy = Math.abs(brush.y1 - brush.y0);
@@ -167,7 +173,9 @@ export function XDSChartBrush({
selected = data.filter(d => {
const xv = d[xKey];
- if (typeof xv !== 'number' || xv < xMin || xv > xMax) return false;
+ if (typeof xv !== 'number' || xv < xMin || xv > xMax) {
+ return false;
+ }
// Check all numeric values against y range
return Object.entries(d).some(
([k, v]) =>
diff --git a/packages/lab/src/Chart/XDSChartCandlestick.tsx b/packages/lab/src/Chart/XDSChartCandlestick.tsx
index 77c14a9059..a15e250db1 100644
--- a/packages/lab/src/Chart/XDSChartCandlestick.tsx
+++ b/packages/lab/src/Chart/XDSChartCandlestick.tsx
@@ -77,14 +77,18 @@ export function XDSChartCandlestick({
}: XDSChartCandlestickProps) {
const {data, xKey, xScale, yScale} = useChart();
- if (!isBandScale(xScale)) return null;
+ if (!isBandScale(xScale)) {
+ return null;
+ }
const bw = xScale.bandwidth();
return (
<g>
{data.map((d, i) => {
const xVal = xScale(String(d[xKey]));
- if (xVal == null) return null;
+ if (xVal == null) {
+ return null;
+ }
const hVal = typeof d[high] === 'number' ? (d[high] as number) : 0;
const lVal = typeof d[low] === 'number' ? (d[low] as number) : 0;
diff --git a/packages/lab/src/Chart/XDSChartDotGL.tsx b/packages/lab/src/Chart/XDSChartDotGL.tsx
index 98fb471c5f..76b6e77968 100644
--- a/packages/lab/src/Chart/XDSChartDotGL.tsx
+++ b/packages/lab/src/Chart/XDSChartDotGL.tsx
@@ -88,26 +88,39 @@ export function XDSChartDotGL({
// Mount canvas outside SVG
useEffect(() => {
const marker = markerRef.current;
- if (!marker) return;
- if (!canvasRef.current)
+ if (!marker) {
+ return;
+ }
+ if (!canvasRef.current) {
canvasRef.current = document.createElement('canvas');
+ }
return mountCanvasOverSVG(marker, canvasRef.current, width, height);
}, [width, height]);
// Draw
useEffect(() => {
const canvas = canvasRef.current;
- if (!canvas || width <= 0 || height <= 0) return;
+ if (!canvas || width <= 0 || height <= 0) {
+ return;
+ }
const dpr = sizeCanvas(canvas, width, height);
- if (!glRef.current) glRef.current = getWebGLContext(canvas);
+ if (!glRef.current) {
+ glRef.current = getWebGLContext(canvas);
+ }
const gl = glRef.current;
- if (!gl) return;
+ if (!gl) {
+ return;
+ }
- if (!programRef.current) programRef.current = createProgram(gl, VERT, FRAG);
+ if (!programRef.current) {
+ programRef.current = createProgram(gl, VERT, FRAG);
+ }
const program = programRef.current;
- if (!program) return;
+ if (!program) {
+ return;
+ }
gl.viewport(0, 0, canvas.width, canvas.height);
setupGLState(gl);
@@ -131,6 +144,8 @@ export function XDSChartDotGL({
gl.deleteBuffer(posBuffer);
}, [width, height, color, size, opacity, getPositions]);
- if (width <= 0 || height <= 0) return null;
+ if (width <= 0 || height <= 0) {
+ return null;
+ }
return <g ref={markerRef} />;
}
diff --git a/packages/lab/src/Chart/XDSChartDotGLInteractive.tsx b/packages/lab/src/Chart/XDSChartDotGLInteractive.tsx
index a77579f3a2..548fccfb1e 100644
--- a/packages/lab/src/Chart/XDSChartDotGLInteractive.tsx
+++ b/packages/lab/src/Chart/XDSChartDotGLInteractive.tsx
@@ -55,7 +55,9 @@ function indexToColor(i: number): [number, number, number] {
/** Decode an RGB pixel back to a point index. Returns -1 for background. */
function colorToIndex(r: number, g: number, b: number): number {
- if (r === 0 && g === 0 && b === 0) return -1;
+ if (r === 0 && g === 0 && b === 0) {
+ return -1;
+ }
return ((r << 16) | (g << 8) | b) - 1;
}
@@ -113,7 +115,9 @@ function compileShader(
src: string,
): WebGLShader | null {
const s = gl.createShader(type);
- if (!s) return null;
+ if (!s) {
+ return null;
+ }
gl.shaderSource(s, src);
gl.compileShader(s);
if (!gl.getShaderParameter(s, gl.COMPILE_STATUS)) {
@@ -130,9 +134,13 @@ function linkProgram(
): WebGLProgram | null {
const vs = compileShader(gl, gl.VERTEX_SHADER, vert);
const fs = compileShader(gl, gl.FRAGMENT_SHADER, frag);
- if (!vs || !fs) return null;
+ if (!vs || !fs) {
+ return null;
+ }
const p = gl.createProgram();
- if (!p) return null;
+ if (!p) {
+ return null;
+ }
gl.attachShader(p, vs);
gl.attachShader(p, fs);
gl.linkProgram(p);
@@ -205,7 +213,9 @@ export function XDSChartDotGLInteractive({
// Render both passes
useEffect(() => {
- if (width <= 0 || height <= 0) return;
+ if (width <= 0 || height <= 0) {
+ return;
+ }
const dpr = window.devicePixelRatio || 1;
// --- Visible canvas ---
@@ -221,7 +231,9 @@ export function XDSChartDotGLInteractive({
antialias: true,
});
const prog = gl ? linkProgram(gl, VERT_VIS, FRAG_VIS) : null;
- if (gl && prog) visGLRef.current = {gl, prog};
+ if (gl && prog) {
+ visGLRef.current = {gl, prog};
+ }
}
const vis = visGLRef.current;
@@ -364,10 +376,14 @@ export function XDSChartDotGLInteractive({
// Mouse handler — read pick buffer
const handleMouseMove = useCallback((e: React.MouseEvent<SVGRectElement>) => {
const pick = pickGLRef.current;
- if (!pick) return;
+ if (!pick) {
+ return;
+ }
const svg = e.currentTarget.ownerSVGElement;
- if (!svg) return;
+ if (!svg) {
+ return;
+ }
const pt = svg.createSVGPoint();
pt.x = e.clientX;
pt.y = e.clientY;
@@ -419,7 +435,9 @@ export function XDSChartDotGLInteractive({
</div>
);
- if (width <= 0 || height <= 0) return null;
+ if (width <= 0 || height <= 0) {
+ return null;
+ }
return (
<g>
diff --git a/packages/lab/src/Chart/XDSChartGrid.tsx b/packages/lab/src/Chart/XDSChartGrid.tsx
index 9e4edb60b1..1bffe71784 100644
--- a/packages/lab/src/Chart/XDSChartGrid.tsx
+++ b/packages/lab/src/Chart/XDSChartGrid.tsx
@@ -34,12 +34,16 @@ export function XDSChartGrid({
const {width, height, xScale, yScale} = useChart();
const hLines = useMemo(() => {
- if (!horizontal) return [];
+ if (!horizontal) {
+ return [];
+ }
return yScale.ticks(5).map(tick => yScale(tick));
}, [horizontal, yScale]);
const vLines = useMemo(() => {
- if (!vertical) return [];
+ if (!vertical) {
+ return [];
+ }
if (isBandScale(xScale)) {
return xScale
.domain()
diff --git a/packages/lab/src/Chart/XDSChartHeatmapGL.tsx b/packages/lab/src/Chart/XDSChartHeatmapGL.tsx
index a433eba960..d62d86b1ed 100644
--- a/packages/lab/src/Chart/XDSChartHeatmapGL.tsx
+++ b/packages/lab/src/Chart/XDSChartHeatmapGL.tsx
@@ -53,7 +53,9 @@ function sampleRamp(
t: number,
): [number, number, number] {
const c = Math.max(0, Math.min(1, t));
- if (ramp.length === 1) return ramp[0];
+ if (ramp.length === 1) {
+ return ramp[0];
+ }
const s = c * (ramp.length - 1);
const lo = Math.floor(s);
const hi = Math.min(lo + 1, ramp.length - 1);
@@ -87,14 +89,20 @@ export function XDSChartHeatmapGL({
}, [data, yKey, height]);
const domain = useMemo((): [number, number] => {
- if (domainProp) return domainProp;
+ if (domainProp) {
+ return domainProp;
+ }
let min = Infinity,
max = -Infinity;
for (const d of data) {
const v = d[valueKey];
if (typeof v === 'number') {
- if (v < min) min = v;
- if (v > max) max = v;
+ if (v < min) {
+ min = v;
+ }
+ if (v > max) {
+ max = v;
+ }
}
}
return [min, max];
@@ -103,26 +111,39 @@ export function XDSChartHeatmapGL({
// Mount canvas
useEffect(() => {
const marker = markerRef.current;
- if (!marker) return;
- if (!canvasRef.current)
+ if (!marker) {
+ return;
+ }
+ if (!canvasRef.current) {
canvasRef.current = document.createElement('canvas');
+ }
return mountCanvasOverSVG(marker, canvasRef.current, width, height);
}, [width, height]);
// Draw
useEffect(() => {
const canvas = canvasRef.current;
- if (!canvas || width <= 0 || height <= 0 || !isBandScale(xScale)) return;
+ if (!canvas || width <= 0 || height <= 0 || !isBandScale(xScale)) {
+ return;
+ }
sizeCanvas(canvas, width, height);
- if (!glRef.current) glRef.current = getWebGLContext(canvas);
+ if (!glRef.current) {
+ glRef.current = getWebGLContext(canvas);
+ }
const gl = glRef.current;
- if (!gl) return;
+ if (!gl) {
+ return;
+ }
- if (!programRef.current) programRef.current = createProgram(gl, VERT, FRAG);
+ if (!programRef.current) {
+ programRef.current = createProgram(gl, VERT, FRAG);
+ }
const program = programRef.current;
- if (!program) return;
+ if (!program) {
+ return;
+ }
gl.viewport(0, 0, canvas.width, canvas.height);
setupGLState(gl);
@@ -139,7 +160,9 @@ export function XDSChartHeatmapGL({
for (const d of data) {
const xVal = xScale(String(d[xKey]));
const yVal = yBandScale(String(d[yKey]));
- if (xVal == null || yVal == null) continue;
+ if (xVal == null || yVal == null) {
+ continue;
+ }
const v = typeof d[valueKey] === 'number' ? (d[valueKey] as number) : 0;
const t = (v - dMin) / range;
@@ -151,7 +174,9 @@ export function XDSChartHeatmapGL({
const y1 = yVal + yBW - gap / 2;
positions.push(x0, y0, x1, y0, x0, y1, x1, y0, x1, y1, x0, y1);
- for (let i = 0; i < 6; i++) colors.push(r, g, b);
+ for (let i = 0; i < 6; i++) {
+ colors.push(r, g, b);
+ }
}
const posBuf = gl.createBuffer();
@@ -187,6 +212,8 @@ export function XDSChartHeatmapGL({
cellGap,
]);
- if (width <= 0 || height <= 0) return null;
+ if (width <= 0 || height <= 0) {
+ return null;
+ }
return <g ref={markerRef} />;
}
diff --git a/packages/lab/src/Chart/XDSChartLegend.tsx b/packages/lab/src/Chart/XDSChartLegend.tsx
index 0329c13b6c..d8c238cf6e 100644
--- a/packages/lab/src/Chart/XDSChartLegend.tsx
+++ b/packages/lab/src/Chart/XDSChartLegend.tsx
@@ -37,8 +37,12 @@ export interface XDSChartLegendProps {
/** Build a CSS linear-gradient from an array of color stops */
function toGradientCSS(colors: string[]): string {
- if (colors.length === 0) return 'transparent';
- if (colors.length === 1) return colors[0];
+ if (colors.length === 0) {
+ return 'transparent';
+ }
+ if (colors.length === 1) {
+ return colors[0];
+ }
const stops = colors.map(
(c, i) => `${c} ${(i / (colors.length - 1)) * 100}%`,
);
@@ -136,7 +140,9 @@ export function XDSChartLegend({
}
// Discrete mode
- if (!items || items.length === 0) return null;
+ if (!items || items.length === 0) {
+ return null;
+ }
return (
<foreignObject
diff --git a/packages/lab/src/Chart/XDSChartSelect.tsx b/packages/lab/src/Chart/XDSChartSelect.tsx
index 1592f73d0b..e06c1abd5c 100644
--- a/packages/lab/src/Chart/XDSChartSelect.tsx
+++ b/packages/lab/src/Chart/XDSChartSelect.tsx
@@ -29,7 +29,9 @@ export function XDSChartSelect({
const handlePointerUp = useCallback(
(e: React.PointerEvent<SVGRectElement>) => {
const svg = e.currentTarget.ownerSVGElement;
- if (!svg) return;
+ if (!svg) {
+ return;
+ }
const pt = svg.createSVGPoint();
pt.x = e.clientX;
pt.y = e.clientY;
@@ -51,7 +53,9 @@ export function XDSChartSelect({
closest = i;
}
});
- if (minDist > 30) return;
+ if (minDist > 30) {
+ return;
+ }
onSelect?.(data[closest], closest);
if (onSelectionChange) {
if (e.shiftKey || e.metaKey) {
@@ -80,7 +84,9 @@ export function XDSChartSelect({
onPointerUp={handlePointerUp}
/>
{selected.map(idx => {
- if (idx < 0 || idx >= data.length) return null;
+ if (idx < 0 || idx >= data.length) {
+ return null;
+ }
const d = data[idx];
const px = xPixel(d, xKey, xScale);
const yKey = Object.keys(d).find(
diff --git a/packages/lab/src/Chart/XDSChartStreamGL.tsx b/packages/lab/src/Chart/XDSChartStreamGL.tsx
index 4031b21fad..20a10c9c10 100644
--- a/packages/lab/src/Chart/XDSChartStreamGL.tsx
+++ b/packages/lab/src/Chart/XDSChartStreamGL.tsx
@@ -80,34 +80,53 @@ export const XDSChartStreamGL = forwardRef<
// Mount canvas outside SVG
useEffect(() => {
const marker = markerRef.current;
- if (!marker) return;
- if (!canvasRef.current)
+ if (!marker) {
+ return;
+ }
+ if (!canvasRef.current) {
canvasRef.current = document.createElement('canvas');
+ }
return mountCanvasOverSVG(marker, canvasRef.current, width, height);
}, [width, height]);
// Size canvas
useEffect(() => {
const canvas = canvasRef.current;
- if (!canvas || width <= 0 || height <= 0) return;
+ if (!canvas || width <= 0 || height <= 0) {
+ return;
+ }
sizeCanvas(canvas, width, height);
}, [width, height]);
const draw = useCallback(() => {
const canvas = canvasRef.current;
- if (!canvas) return;
- if (!glRef.current) glRef.current = getWebGLContext(canvas);
+ if (!canvas) {
+ return;
+ }
+ if (!glRef.current) {
+ glRef.current = getWebGLContext(canvas);
+ }
const gl = glRef.current;
- if (!gl) return;
+ if (!gl) {
+ return;
+ }
- if (!programRef.current) programRef.current = createProgram(gl, VERT, FRAG);
+ if (!programRef.current) {
+ programRef.current = createProgram(gl, VERT, FRAG);
+ }
const program = programRef.current;
- if (!program) return;
+ if (!program) {
+ return;
+ }
- if (!bufRef.current) bufRef.current = gl.createBuffer();
+ if (!bufRef.current) {
+ bufRef.current = gl.createBuffer();
+ }
const {data: ringData, head, count} = ring.current;
- if (count < 2) return;
+ if (count < 2) {
+ return;
+ }
const linearX = xScale as (v: number) => number;
const drawBuf = new Float32Array(count * 2);
@@ -162,6 +181,8 @@ export const XDSChartStreamGL = forwardRef<
[bufferSize, draw],
);
- if (width <= 0 || height <= 0) return null;
+ if (width <= 0 || height <= 0) {
+ return null;
+ }
return <g ref={markerRef} />;
});
diff --git a/packages/lab/src/Chart/XDSChartTooltip.tsx b/packages/lab/src/Chart/XDSChartTooltip.tsx
index 570fb338aa..3c98d66119 100644
--- a/packages/lab/src/Chart/XDSChartTooltip.tsx
+++ b/packages/lab/src/Chart/XDSChartTooltip.tsx
@@ -139,7 +139,9 @@ export function XDSChartTooltip({
// and x-only distance for categorical/time series (band x).
const findNearest = useCallback(
(px: number, py: number): {index: number; point: DataPoint} | null => {
- if (data.length === 0) return null;
+ if (data.length === 0) {
+ return null;
+ }
let closestIdx = 0;
let minDist = Infinity;
@@ -163,7 +165,9 @@ export function XDSChartTooltip({
for (const yk of yKeys) {
const yv = datum[yk];
- if (typeof yv !== 'number') continue;
+ if (typeof yv !== 'number') {
+ continue;
+ }
const datumPy = yScale(yv);
const dy = datumPy - py;
const dist = dx * dx + dy * dy; // squared euclidean
@@ -188,7 +192,9 @@ export function XDSChartTooltip({
let bestDist = Infinity;
for (const yk of yKeys) {
const yv = datum[yk];
- if (typeof yv !== 'number') continue;
+ if (typeof yv !== 'number') {
+ continue;
+ }
const dpy = yScale(yv);
const dx = dpx - px;
const dy = dpy - py;
@@ -250,7 +256,9 @@ export function XDSChartTooltip({
// Mouse: hover to show. Touch: drag to scrub (only if active).
const handlePointerMove = useCallback(
(e: React.PointerEvent<SVGRectElement>) => {
- if (e.pointerType !== 'mouse' && !active.current) return;
+ if (e.pointerType !== 'mouse' && !active.current) {
+ return;
+ }
updateTooltip(e);
},
[updateTooltip],
diff --git a/packages/lab/src/Chart/XDSChartZoom.tsx b/packages/lab/src/Chart/XDSChartZoom.tsx
index 9b2f14c2cb..17f777dfb7 100644
--- a/packages/lab/src/Chart/XDSChartZoom.tsx
+++ b/packages/lab/src/Chart/XDSChartZoom.tsx
@@ -111,7 +111,9 @@ export function XDSChartZoom({
} | null>(null);
useEffect(() => {
- if (initialDomainsRef.current) return; // only capture once
+ if (initialDomainsRef.current) {
+ return;
+ } // only capture once
const xDomain = isBandScale(xScale)
? null
: ((xScale as ScaleLinear<number, number>).domain() as [number, number]);
@@ -185,7 +187,9 @@ export function XDSChartZoom({
e.preventDefault();
const svg = e.currentTarget.ownerSVGElement;
- if (!svg) return;
+ if (!svg) {
+ return;
+ }
const pt = svg.createSVGPoint();
pt.x = e.clientX;
pt.y = e.clientY;
@@ -293,14 +297,22 @@ export function XDSChartZoom({
const onPointerUp = useCallback((e: React.PointerEvent<SVGRectElement>) => {
pointersRef.current.delete(e.pointerId);
- if (pointersRef.current.size < 2) pinchRef.current = null;
- if (pointersRef.current.size === 0) dragRef.current = null;
+ if (pointersRef.current.size < 2) {
+ pinchRef.current = null;
+ }
+ if (pointersRef.current.size === 0) {
+ dragRef.current = null;
+ }
}, []);
const handleReset = useCallback(() => {
const init = initialDomainsRef.current;
- if (!init) return;
- if (init.x) onXDomainChange?.(init.x);
+ if (!init) {
+ return;
+ }
+ if (init.x) {
+ onXDomainChange?.(init.x);
+ }
onYDomainChange?.(init.y);
}, [onXDomainChange, onYDomainChange]);
diff --git a/packages/lab/src/Chart/getXDSChartColors.ts b/packages/lab/src/Chart/getXDSChartColors.ts
index 34f1f62a39..6ee0e2c7ac 100644
--- a/packages/lab/src/Chart/getXDSChartColors.ts
+++ b/packages/lab/src/Chart/getXDSChartColors.ts
@@ -90,9 +90,15 @@ const SEQUENTIAL_HUES: SequentialHue[] = [
];
function pickFromRamp(stops: string[], n: number): string[] {
- if (n <= 0) return [];
- if (n >= 5) return stops;
- if (n === 1) return [stops[2]];
+ if (n <= 0) {
+ return [];
+ }
+ if (n >= 5) {
+ return stops;
+ }
+ if (n === 1) {
+ return [stops[2]];
+ }
return Array.from(
{length: n},
(_, i) => stops[Math.round((i * 4) / (n - 1))],
@@ -103,7 +109,9 @@ function hexAlpha(hex: string, opacity: number): string {
const match = hex.match(
/^#?([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})$/,
);
- if (!match) return hex;
+ if (!match) {
+ return hex;
+ }
const r = parseInt(match[1], 16);
const g = parseInt(match[2], 16);
const b = parseInt(match[3], 16);
@@ -134,21 +142,29 @@ export function getXDSChartColorsFromResolver(
n: number,
midpoint: string = gray1,
): string[] {
- if (n <= 0) return [];
- if (n === 1) return [midpoint];
+ if (n <= 0) {
+ return [];
+ }
+ if (n === 1) {
+ return [midpoint];
+ }
const neg = ramp(negHue);
const pos = ramp(posHue);
const half = Math.floor(n / 2);
const hasCenter = n % 2 === 1;
const negSide = pickFromRamp(neg, half);
const posSide = pickFromRamp(pos, half).reverse();
- if (hasCenter) return [...negSide, midpoint, ...posSide];
+ if (hasCenter) {
+ return [...negSide, midpoint, ...posSide];
+ }
return [...negSide, ...posSide];
}
return {
categorical(n: number): string[] {
- if (n <= 0) return [];
+ if (n <= 0) {
+ return [];
+ }
return categorical.slice(0, Math.min(n, categorical.length));
},
@@ -156,7 +172,9 @@ export function getXDSChartColorsFromResolver(
SEQUENTIAL_HUES.map(hue => [
hue,
(n: number): string[] => {
- if (n <= 0) return [];
+ if (n <= 0) {
+ return [];
+ }
return pickFromRamp(ramp(hue), n);
},
]),
@@ -211,7 +229,9 @@ export function getXDSChartColors(
const resolve: TokenResolver = (name: string) => {
// Check theme token overrides first, then fall back to defaults
const raw = theme.tokens?.[name] ?? '';
- if (!raw) return '';
+ if (!raw) {
+ return '';
+ }
// Resolve light-dark() for the given mode
if (raw.startsWith('light-dark(') && raw.endsWith(')')) {
const inner = raw.slice(11, -1);
diff --git a/packages/lab/src/Chart/m4.ts b/packages/lab/src/Chart/m4.ts
index 5945d5772c..bbc022c885 100644
--- a/packages/lab/src/Chart/m4.ts
+++ b/packages/lab/src/Chart/m4.ts
@@ -41,15 +41,21 @@ export function m4Reduce(
width: number,
xDomain?: [number, number],
): M4Point[] {
- if (data.length === 0 || width <= 0) return [];
+ if (data.length === 0 || width <= 0) {
+ return [];
+ }
// If data fits without reduction, return as-is
- if (data.length <= width * 4) return data;
+ if (data.length <= width * 4) {
+ return data;
+ }
const xMin = xDomain ? xDomain[0] : data[0].x;
const xMax = xDomain ? xDomain[1] : data[data.length - 1].x;
const xRange = xMax - xMin;
- if (xRange <= 0) return [data[0]];
+ if (xRange <= 0) {
+ return [data[0]];
+ }
const bucketCount = Math.ceil(width);
@@ -83,8 +89,12 @@ export function m4Reduce(
bucket.max = point;
} else {
bucket.last = point;
- if (point.y < bucket.min!.y) bucket.min = point;
- if (point.y > bucket.max!.y) bucket.max = point;
+ if (point.y < bucket.min!.y) {
+ bucket.min = point;
+ }
+ if (point.y > bucket.max!.y) {
+ bucket.max = point;
+ }
}
}
@@ -93,7 +103,9 @@ export function m4Reduce(
const result: M4Point[] = [];
for (const bucket of buckets) {
- if (!bucket.first) continue;
+ if (!bucket.first) {
+ continue;
+ }
const points = [bucket.first, bucket.min!, bucket.max!, bucket.last!];
diff --git a/packages/lab/src/Chart/webgl.ts b/packages/lab/src/Chart/webgl.ts
index a0905d98e0..390b7e5ca3 100644
--- a/packages/lab/src/Chart/webgl.ts
+++ b/packages/lab/src/Chart/webgl.ts
@@ -19,7 +19,9 @@ export function compileShader(
src: string,
): WebGLShader | null {
const s = gl.createShader(type);
- if (!s) return null;
+ if (!s) {
+ return null;
+ }
gl.shaderSource(s, src);
gl.compileShader(s);
if (!gl.getShaderParameter(s, gl.COMPILE_STATUS)) {
@@ -37,9 +39,13 @@ export function createProgram(
): WebGLProgram | null {
const vs = compileShader(gl, gl.VERTEX_SHADER, vertSrc);
const fs = compileShader(gl, gl.FRAGMENT_SHADER, fragSrc);
- if (!vs || !fs) return null;
+ if (!vs || !fs) {
+ return null;
+ }
const p = gl.createProgram();
- if (!p) return null;
+ if (!p) {
+ return null;
+ }
gl.attachShader(p, vs);
gl.attachShader(p, fs);
gl.linkProgram(p);
@@ -119,9 +125,13 @@ export function mountCanvasOverSVG(
height: number,
): (() => void) | undefined {
const svg = svgMarker.ownerSVGElement;
- if (!svg) return;
+ if (!svg) {
+ return;
+ }
const parent = svg.parentElement;
- if (!parent) return;
+ if (!parent) {
+ return;
+ }
if (getComputedStyle(parent).position === 'static') {
parent.style.position = 'relative';
diff --git a/packages/lab/src/ChartV2/ChartV2Context.ts b/packages/lab/src/ChartV2/ChartV2Context.ts
index fc5179f49d..8909a82976 100644
--- a/packages/lab/src/ChartV2/ChartV2Context.ts
+++ b/packages/lab/src/ChartV2/ChartV2Context.ts
@@ -8,6 +8,8 @@ export const ChartV2Provider = Ctx.Provider;
export function useChartV2(): ChartV2Context {
const ctx = useContext(Ctx);
- if (!ctx) throw new Error('Must be used inside <XDSChart>');
+ if (!ctx) {
+ throw new Error('Must be used inside <XDSChart>');
+ }
return ctx;
}
diff --git a/packages/lab/src/ChartV2/XDSChart.tsx b/packages/lab/src/ChartV2/XDSChart.tsx
index 49dc6108e4..275fbead77 100644
--- a/packages/lab/src/ChartV2/XDSChart.tsx
+++ b/packages/lab/src/ChartV2/XDSChart.tsx
@@ -41,93 +41,164 @@ export interface XDSChartProps {
const DEFAULT_MARGIN: ChartMargin = {top: 16, right: 16, bottom: 32, left: 48};
export function XDSChart({
- data, xKey, series, height = 300, margin: marginOverride,
- grid, axes, legend, interactions, children,
+ data,
+ xKey,
+ series,
+ height = 300,
+ margin: marginOverride,
+ grid,
+ axes,
+ legend,
+ interactions,
+ children,
}: XDSChartProps) {
const containerRef = useRef<HTMLDivElement>(null);
const svgRef = useRef<SVGSVGElement>(null);
const [containerWidth, setContainerWidth] = useState(0);
- const pointerHandlers = useRef<Set<(e: ChartPointerEvent) => void>>(new Set());
+ const pointerHandlers = useRef<Set<(e: ChartPointerEvent) => void>>(
+ new Set(),
+ );
useLayoutEffect(() => {
- if (!containerRef.current) return;
+ if (!containerRef.current) {
+ return;
+ }
const observer = new ResizeObserver(entries => {
const entry = entries[0];
- if (entry) setContainerWidth(entry.contentRect.width);
+ if (entry) {
+ setContainerWidth(entry.contentRect.width);
+ }
});
observer.observe(containerRef.current);
return () => observer.disconnect();
}, []);
- const margin = useMemo(() => ({...DEFAULT_MARGIN, ...marginOverride}), [marginOverride]);
+ const margin = useMemo(
+ () => ({...DEFAULT_MARGIN, ...marginOverride}),
+ [marginOverride],
+ );
const innerWidth = Math.max(0, containerWidth - margin.left - margin.right);
const innerHeight = Math.max(0, height - margin.top - margin.bottom);
// ─── Layout pass ──────────────────────────────────────────────────────
const layout = useMemo(
- () => computeLayout({data, xKey, series, width: innerWidth, height: innerHeight}),
+ () =>
+ computeLayout({
+ data,
+ xKey,
+ series,
+ width: innerWidth,
+ height: innerHeight,
+ }),
[data, xKey, series, innerWidth, innerHeight],
);
- const seriesCtx = useMemo(() => ({
- data, xKey, xScale: layout.xScale, yScale: layout.yScale,
- width: innerWidth, height: innerHeight,
- }), [data, xKey, layout, innerWidth, innerHeight]);
+ const seriesCtx = useMemo(
+ () => ({
+ data,
+ xKey,
+ xScale: layout.xScale,
+ yScale: layout.yScale,
+ width: innerWidth,
+ height: innerHeight,
+ }),
+ [data, xKey, layout, innerWidth, innerHeight],
+ );
// ─── Event dispatch ───────────────────────────────────────────────────
const onPointer = useCallback((handler: (e: ChartPointerEvent) => void) => {
pointerHandlers.current.add(handler);
- return () => { pointerHandlers.current.delete(handler); };
+ return () => {
+ pointerHandlers.current.delete(handler);
+ };
}, []);
const dispatch = useCallback((e: ChartPointerEvent) => {
- for (const handler of pointerHandlers.current) handler(e);
+ for (const handler of pointerHandlers.current) {
+ handler(e);
+ }
}, []);
- const handlePointerMove = useCallback((e: React.PointerEvent<SVGRectElement>) => {
- const svg = svgRef.current;
- if (!svg) return;
- const point = svg.createSVGPoint();
- point.x = e.clientX;
- point.y = e.clientY;
- const ctm = e.currentTarget.getScreenCTM()?.inverse();
- if (!ctm) return;
- const cursor = point.matrixTransform(ctm);
-
- let nearest: ChartPointerEvent['nearest'] = null;
- let bestDist = 40 * 40;
- for (const [seriesKey, points] of layout.resolved) {
- for (const p of points) {
- const dx = p.px - cursor.x;
- const dy = p.py - cursor.y;
- const dist = dx * dx + dy * dy;
- if (dist < bestDist) {
- bestDist = dist;
- nearest = {...p, seriesKey};
+ const handlePointerMove = useCallback(
+ (e: React.PointerEvent<SVGRectElement>) => {
+ const svg = svgRef.current;
+ if (!svg) {
+ return;
+ }
+ const point = svg.createSVGPoint();
+ point.x = e.clientX;
+ point.y = e.clientY;
+ const ctm = e.currentTarget.getScreenCTM()?.inverse();
+ if (!ctm) {
+ return;
+ }
+ const cursor = point.matrixTransform(ctm);
+
+ let nearest: ChartPointerEvent['nearest'] = null;
+ let bestDist = 40 * 40;
+ for (const [seriesKey, points] of layout.resolved) {
+ for (const p of points) {
+ const dx = p.px - cursor.x;
+ const dy = p.py - cursor.y;
+ const dist = dx * dx + dy * dy;
+ if (dist < bestDist) {
+ bestDist = dist;
+ nearest = {...p, seriesKey};
+ }
}
}
- }
- dispatch({x: cursor.x, y: cursor.y, nearest, active: e.buttons > 0});
- }, [layout.resolved, dispatch]);
+ dispatch({x: cursor.x, y: cursor.y, nearest, active: e.buttons > 0});
+ },
+ [layout.resolved, dispatch],
+ );
const handlePointerLeave = useCallback(() => {
dispatch({x: -1, y: -1, nearest: null, active: false});
}, [dispatch]);
// ─── Context for interactions + v1 chrome ─────────────────────────────
- const ctx: ChartV2Context = useMemo(() => ({
- width: innerWidth, height: innerHeight, margin, data, xKey,
- xScale: layout.xScale, yScale: layout.yScale,
- resolved: layout.resolved, onPointer, svgRef,
- }), [innerWidth, innerHeight, margin, data, xKey, layout, onPointer]);
+ const ctx: ChartV2Context = useMemo(
+ () => ({
+ width: innerWidth,
+ height: innerHeight,
+ margin,
+ data,
+ xKey,
+ xScale: layout.xScale,
+ yScale: layout.yScale,
+ resolved: layout.resolved,
+ onPointer,
+ svgRef,
+ }),
+ [innerWidth, innerHeight, margin, data, xKey, layout, onPointer],
+ );
// Bridge v1 context for XDSChartGrid/Axis compatibility
- const v1Ctx = useMemo(() => ({
- width: innerWidth, height: innerHeight, margin, xKey, data,
- xScale: layout.xScale, yScale: layout.yScale, svgRef,
- pointerToData: () => ({x: null as string | number | null, y: 0, px: 0, py: 0}),
- pixelToData: (px: number, py: number) => ({x: null as string | number | null, y: 0, px, py}),
- }), [innerWidth, innerHeight, margin, xKey, data, layout, svgRef]);
+ const v1Ctx = useMemo(
+ () => ({
+ width: innerWidth,
+ height: innerHeight,
+ margin,
+ xKey,
+ data,
+ xScale: layout.xScale,
+ yScale: layout.yScale,
+ svgRef,
+ pointerToData: () => ({
+ x: null as string | number | null,
+ y: 0,
+ px: 0,
+ py: 0,
+ }),
+ pixelToData: (px: number, py: number) => ({
+ x: null as string | number | null,
+ y: 0,
+ px,
+ py,
+ }),
+ }),
+ [innerWidth, innerHeight, margin, xKey, data, layout, svgRef],
+ );
// ─── Render ───────────────────────────────────────────────────────────
if (containerWidth === 0) {
@@ -146,7 +217,9 @@ export function XDSChart({
{/* 2. Marks — each series renders itself */}
{series.map(s => {
const resolved = layout.resolved.get(s.key);
- if (!resolved) return null;
+ if (!resolved) {
+ return null;
+ }
return <g key={s.key}>{s.render(resolved, seriesCtx)}</g>;
})}
@@ -154,10 +227,15 @@ export function XDSChart({
{axes}
{/* 4. Event capture + interactions */}
- <rect x={0} y={0} width={innerWidth} height={innerHeight}
+ <rect
+ x={0}
+ y={0}
+ width={innerWidth}
+ height={innerHeight}
fill="transparent"
onPointerMove={handlePointerMove}
- onPointerLeave={handlePointerLeave} />
+ onPointerLeave={handlePointerLeave}
+ />
{interactions}
{/* 5. Escape hatch */}
diff --git a/packages/lab/src/ChartV2/layout.ts b/packages/lab/src/ChartV2/layout.ts
index 5415296be3..7db23b5394 100644
--- a/packages/lab/src/ChartV2/layout.ts
+++ b/packages/lab/src/ChartV2/layout.ts
@@ -12,7 +12,12 @@
import {scaleLinear, scaleBand} from 'd3-scale';
import {stack as d3Stack, stackOrderNone, stackOffsetNone} from 'd3-shape';
-import type {SeriesDef, ChartScale, ResolvedPoint, SeriesContext} from './types';
+import type {
+ SeriesDef,
+ ChartScale,
+ ResolvedPoint,
+ SeriesContext,
+} from './types';
export interface LayoutInput {
data: Record<string, unknown>[];
@@ -28,25 +33,42 @@ export interface LayoutResult {
resolved: Map<string, ResolvedPoint[]>;
}
-export function computeLayout({data, xKey, series, width, height}: LayoutInput): LayoutResult {
+export function computeLayout({
+ data,
+ xKey,
+ series,
+ width,
+ height,
+}: LayoutInput): LayoutResult {
// ─── 1. X scale ──────────────────────────────────────────────────────
const xValues = data.map(d => d[xKey]);
- const isNumericX = xValues.length > 0 && xValues.every(v => typeof v === 'number');
+ const isNumericX =
+ xValues.length > 0 && xValues.every(v => typeof v === 'number');
let xScale: ChartScale;
if (isNumericX) {
const nums = xValues as number[];
- xScale = scaleLinear().domain([Math.min(...nums), Math.max(...nums)]).range([0, width]).nice();
+ xScale = scaleLinear()
+ .domain([Math.min(...nums), Math.max(...nums)])
+ .range([0, width])
+ .nice();
} else {
- xScale = scaleBand<string>().domain(xValues.map(String)).range([0, width]).padding(0.2);
+ xScale = scaleBand<string>()
+ .domain(xValues.map(String))
+ .range([0, width])
+ .padding(0.2);
}
// ─── 2. Y domain from all series dataKeys ────────────────────────────
const allKeys = new Set<string>();
let includeZero = false;
for (const s of series) {
- for (const k of s.dataKeys) allKeys.add(k);
- if (s.layout.includeZero) includeZero = true;
+ for (const k of s.dataKeys) {
+ allKeys.add(k);
+ }
+ if (s.layout.includeZero) {
+ includeZero = true;
+ }
}
// Collect which keys are stacked together so we can compute stacked extents
@@ -59,38 +81,57 @@ export function computeLayout({data, xKey, series, width, height}: LayoutInput):
}
}
- let yMin = Infinity, yMax = -Infinity;
+ let yMin = Infinity,
+ yMax = -Infinity;
// For stacked series, compute the sum at each data point
const stackedKeys = new Set<string>();
for (const [, keys] of stackGroupKeys) {
- for (const k of keys) stackedKeys.add(k);
+ for (const k of keys) {
+ stackedKeys.add(k);
+ }
for (const d of data) {
let sum = 0;
for (const k of keys) {
const v = d[k];
- if (typeof v === 'number') sum += v;
+ if (typeof v === 'number') {
+ sum += v;
+ }
+ }
+ if (sum > yMax) {
+ yMax = sum;
+ }
+ if (sum < yMin) {
+ yMin = sum;
}
- if (sum > yMax) yMax = sum;
- if (sum < yMin) yMin = sum;
}
}
// For non-stacked series, use individual values
for (const d of data) {
for (const k of allKeys) {
- if (stackedKeys.has(k)) continue; // already handled above
+ if (stackedKeys.has(k)) {
+ continue;
+ } // already handled above
const v = d[k];
if (typeof v === 'number') {
- if (v < yMin) yMin = v;
- if (v > yMax) yMax = v;
+ if (v < yMin) {
+ yMin = v;
+ }
+ if (v > yMax) {
+ yMax = v;
+ }
}
}
}
if (includeZero) {
- if (yMin > 0) yMin = 0;
- if (yMax < 0) yMax = 0;
+ if (yMin > 0) {
+ yMin = 0;
+ }
+ if (yMax < 0) {
+ yMax = 0;
+ }
}
const yScale = scaleLinear().domain([yMin, yMax]).range([height, 0]).nice();
@@ -107,10 +148,15 @@ export function computeLayout({data, xKey, series, width, height}: LayoutInput):
const stackedData = new Map<string, {y0: number; y1: number}[]>();
for (const [, keys] of stackGroups) {
const stackGen = d3Stack<Record<string, unknown>>()
- .keys(keys).order(stackOrderNone).offset(stackOffsetNone);
+ .keys(keys)
+ .order(stackOrderNone)
+ .offset(stackOffsetNone);
const stacked = stackGen(data);
for (const layer of stacked) {
- stackedData.set(layer.key, layer.map(d => ({y0: d[0], y1: d[1]})));
+ stackedData.set(
+ layer.key,
+ layer.map(d => ({y0: d[0], y1: d[1]})),
+ );
}
}
@@ -126,7 +172,9 @@ export function computeLayout({data, xKey, series, width, height}: LayoutInput):
// For grouped stacks: use the stack name as the group slot identifier
// so all series in the same stack share one slot.
const slotKey = s.layout.stack ?? s.key;
- if (!group.includes(slotKey)) group.push(slotKey);
+ if (!group.includes(slotKey)) {
+ group.push(slotKey);
+ }
barGroups.set(s.layout.group, group);
}
}
@@ -139,7 +187,9 @@ export function computeLayout({data, xKey, series, width, height}: LayoutInput):
const stackTopKeys = new Set<string>();
for (const [, keys] of stackGroups) {
// Last key in the stack group is rendered on top
- if (keys.length > 0) stackTopKeys.add(keys[keys.length - 1]);
+ if (keys.length > 0) {
+ stackTopKeys.add(keys[keys.length - 1]);
+ }
}
for (const s of series) {
@@ -158,7 +208,10 @@ export function computeLayout({data, xKey, series, width, height}: LayoutInput):
if (groupKeys) {
// For grouped stacks, the slot key is the stack name
const slotKey = s.layout.stack ?? s.key;
- groupInfo = {index: groupKeys.indexOf(slotKey), count: groupKeys.length};
+ groupInfo = {
+ index: groupKeys.indexOf(slotKey),
+ count: groupKeys.length,
+ };
}
}
diff --git a/packages/lab/src/ChartV2/marks/area.tsx b/packages/lab/src/ChartV2/marks/area.tsx
index 074a1a5ee0..337d9601c4 100644
--- a/packages/lab/src/ChartV2/marks/area.tsx
+++ b/packages/lab/src/ChartV2/marks/area.tsx
@@ -5,12 +5,23 @@
* @output Area series — fill under line with stacking + gradient support
*/
-import {area as d3Area, curveLinear, curveMonotoneX, curveNatural, curveStep} from 'd3-shape';
+import {
+ area as d3Area,
+ curveLinear,
+ curveMonotoneX,
+ curveNatural,
+ curveStep,
+} from 'd3-shape';
import {line as d3Line} from 'd3-shape';
import type {SeriesDef, ResolvedPoint} from '../types';
import type {ScaleBand} from 'd3-scale';
-const CURVES = {linear: curveLinear, monotone: curveMonotoneX, natural: curveNatural, step: curveStep} as const;
+const CURVES = {
+ linear: curveLinear,
+ monotone: curveMonotoneX,
+ natural: curveNatural,
+ step: curveStep,
+} as const;
export interface AreaOptions {
color?: string;
@@ -41,7 +52,9 @@ export function area(dataKey: string, options: AreaOptions = {}): SeriesDef {
const d = data[i];
let px: number;
if ('bandwidth' in xScale) {
- px = ((xScale as ScaleBand<string>)(String(d[xKey])) ?? 0) + (xScale as ScaleBand<string>).bandwidth() / 2;
+ px =
+ ((xScale as ScaleBand<string>)(String(d[xKey])) ?? 0) +
+ (xScale as ScaleBand<string>).bandwidth() / 2;
} else {
px = xScale(d[xKey] as number);
}
@@ -60,15 +73,22 @@ export function area(dataKey: string, options: AreaOptions = {}): SeriesDef {
},
render(resolved) {
- if (resolved.length === 0) return null;
+ if (resolved.length === 0) {
+ return null;
+ }
const curveFactory = CURVES[curve];
const areaGen = d3Area<ResolvedPoint>()
- .x(d => d.px).y0(d => d.py0).y1(d => d.py).curve(curveFactory);
+ .x(d => d.px)
+ .y0(d => d.py0)
+ .y1(d => d.py)
+ .curve(curveFactory);
const pathD = areaGen(resolved) ?? '';
const lineGen = d3Line<ResolvedPoint>()
- .x(d => d.px).y(d => d.py).curve(curveFactory);
+ .x(d => d.px)
+ .y(d => d.py)
+ .curve(curveFactory);
const strokeD = lineGen(resolved) ?? '';
const gradientId = `area-grad-${dataKey}`;
@@ -83,9 +103,15 @@ export function area(dataKey: string, options: AreaOptions = {}): SeriesDef {
</linearGradient>
</defs>
)}
- <path d={pathD} fill={gradient ? `url(#${gradientId})` : color}
- fillOpacity={gradient ? 1 : opacity} stroke="none" />
- {stroke && <path d={strokeD} fill="none" stroke={color} strokeWidth={2} />}
+ <path
+ d={pathD}
+ fill={gradient ? `url(#${gradientId})` : color}
+ fillOpacity={gradient ? 1 : opacity}
+ stroke="none"
+ />
+ {stroke && (
+ <path d={strokeD} fill="none" stroke={color} strokeWidth={2} />
+ )}
</g>
);
},
diff --git a/packages/lab/src/ChartV2/marks/band.tsx b/packages/lab/src/ChartV2/marks/band.tsx
index bf34a2a0fe..d47122f7dd 100644
--- a/packages/lab/src/ChartV2/marks/band.tsx
+++ b/packages/lab/src/ChartV2/marks/band.tsx
@@ -33,23 +33,38 @@ export function band(options: BandOptions): SeriesDef {
const d = data[i];
let px: number;
if ('bandwidth' in xScale) {
- px = ((xScale as ScaleBand<string>)(String(d[xKey])) ?? 0) + (xScale as ScaleBand<string>).bandwidth() / 2;
+ px =
+ ((xScale as ScaleBand<string>)(String(d[xKey])) ?? 0) +
+ (xScale as ScaleBand<string>).bandwidth() / 2;
} else {
px = xScale(d[xKey] as number);
}
- const upper = typeof d[options.upper] === 'number' ? (d[options.upper] as number) : 0;
- const lower = typeof d[options.lower] === 'number' ? (d[options.lower] as number) : 0;
+ const upper =
+ typeof d[options.upper] === 'number'
+ ? (d[options.upper] as number)
+ : 0;
+ const lower =
+ typeof d[options.lower] === 'number'
+ ? (d[options.lower] as number)
+ : 0;
points.push({px, py: yScale(upper), py0: yScale(lower), dataIndex: i});
}
return points;
},
render(resolved) {
- if (resolved.length === 0) return null;
+ if (resolved.length === 0) {
+ return null;
+ }
const areaGen = d3Area<ResolvedPoint>()
- .x(d => d.px).y0(d => d.py0).y1(d => d.py).curve(curveMonotoneX);
+ .x(d => d.px)
+ .y0(d => d.py0)
+ .y1(d => d.py)
+ .curve(curveMonotoneX);
const pathD = areaGen(resolved) ?? '';
- return <path d={pathD} fill={color} fillOpacity={opacity} stroke="none" />;
+ return (
+ <path d={pathD} fill={color} fillOpacity={opacity} stroke="none" />
+ );
},
};
}
diff --git a/packages/lab/src/ChartV2/marks/bar.tsx b/packages/lab/src/ChartV2/marks/bar.tsx
index 5d13f3a543..bb444f5ddd 100644
--- a/packages/lab/src/ChartV2/marks/bar.tsx
+++ b/packages/lab/src/ChartV2/marks/bar.tsx
@@ -87,7 +87,9 @@ export function bar(dataKey: string, options: BarOptions = {}): SeriesDef {
resolve(ctx, stackOffsets, groupInfo) {
const {data, xKey, xScale, yScale} = ctx;
- if (!('bandwidth' in xScale)) return [];
+ if (!('bandwidth' in xScale)) {
+ return [];
+ }
const bandScale = xScale as ScaleBand<string>;
const bw = bandScale.bandwidth();
diff --git a/packages/lab/src/ChartV2/marks/candlestick.tsx b/packages/lab/src/ChartV2/marks/candlestick.tsx
index 05ca9b51d2..49599b9443 100644
--- a/packages/lab/src/ChartV2/marks/candlestick.tsx
+++ b/packages/lab/src/ChartV2/marks/candlestick.tsx
@@ -51,7 +51,9 @@ export function candlestick(options: CandlestickOptions): SeriesDef {
render(resolved, ctx) {
const {data, xScale, yScale} = ctx;
- if (!('bandwidth' in xScale)) return null;
+ if (!('bandwidth' in xScale)) {
+ return null;
+ }
const bw = (xScale as ScaleBand<string>).bandwidth();
const bodyWidth = bw * 0.6;
diff --git a/packages/lab/src/ChartV2/marks/dotGL.tsx b/packages/lab/src/ChartV2/marks/dotGL.tsx
index b356b151e1..1b7d54d065 100644
--- a/packages/lab/src/ChartV2/marks/dotGL.tsx
+++ b/packages/lab/src/ChartV2/marks/dotGL.tsx
@@ -86,26 +86,39 @@ function DotGLCanvas({
// Mount canvas outside SVG
useEffect(() => {
const marker = markerRef.current;
- if (!marker) return;
- if (!canvasRef.current)
+ if (!marker) {
+ return;
+ }
+ if (!canvasRef.current) {
canvasRef.current = document.createElement('canvas');
+ }
return mountCanvasOverSVG(marker, canvasRef.current, width, height);
}, [width, height]);
// Draw
useEffect(() => {
const canvas = canvasRef.current;
- if (!canvas || width <= 0 || height <= 0) return;
+ if (!canvas || width <= 0 || height <= 0) {
+ return;
+ }
const dpr = sizeCanvas(canvas, width, height);
- if (!glRef.current) glRef.current = getWebGLContext(canvas);
+ if (!glRef.current) {
+ glRef.current = getWebGLContext(canvas);
+ }
const gl = glRef.current;
- if (!gl) return;
+ if (!gl) {
+ return;
+ }
- if (!programRef.current) programRef.current = createProgram(gl, VERT, FRAG);
+ if (!programRef.current) {
+ programRef.current = createProgram(gl, VERT, FRAG);
+ }
const program = programRef.current;
- if (!program) return;
+ if (!program) {
+ return;
+ }
gl.viewport(0, 0, canvas.width, canvas.height);
setupGLState(gl);
@@ -129,7 +142,9 @@ function DotGLCanvas({
gl.deleteBuffer(posBuffer);
}, [width, height, color, size, opacity, getPositions]);
- if (width <= 0 || height <= 0) return null;
+ if (width <= 0 || height <= 0) {
+ return null;
+ }
return <g ref={markerRef} />;
}
diff --git a/packages/lab/src/ChartV2/marks/dotGLInteractive.tsx b/packages/lab/src/ChartV2/marks/dotGLInteractive.tsx
index f171843960..9969e71e0b 100644
--- a/packages/lab/src/ChartV2/marks/dotGLInteractive.tsx
+++ b/packages/lab/src/ChartV2/marks/dotGLInteractive.tsx
@@ -40,7 +40,9 @@ function indexToColor(i: number): [number, number, number] {
/** Decode an RGB pixel back to a point index. Returns -1 for background. */
function colorToIndex(r: number, g: number, b: number): number {
- if (r === 0 && g === 0 && b === 0) return -1;
+ if (r === 0 && g === 0 && b === 0) {
+ return -1;
+ }
return ((r << 16) | (g << 8) | b) - 1;
}
@@ -50,7 +52,9 @@ function compileShader(
src: string,
): WebGLShader | null {
const s = gl.createShader(type);
- if (!s) return null;
+ if (!s) {
+ return null;
+ }
gl.shaderSource(s, src);
gl.compileShader(s);
if (!gl.getShaderParameter(s, gl.COMPILE_STATUS)) {
@@ -67,9 +71,13 @@ function linkProgram(
): WebGLProgram | null {
const vs = compileShader(gl, gl.VERTEX_SHADER, vert);
const fs = compileShader(gl, gl.FRAGMENT_SHADER, frag);
- if (!vs || !fs) return null;
+ if (!vs || !fs) {
+ return null;
+ }
const p = gl.createProgram();
- if (!p) return null;
+ if (!p) {
+ return null;
+ }
gl.attachShader(p, vs);
gl.attachShader(p, fs);
gl.linkProgram(p);
@@ -155,10 +163,15 @@ function DotGLInteractiveCanvas({
const [hoverIndex, setHoverIndex] = useState<number>(-1);
const [mousePos, setMousePos] = useState<{x: number; y: number} | null>(null);
- const visGLRef = useRef<{gl: WebGLRenderingContext; prog: WebGLProgram} | null>(null);
+ const visGLRef = useRef<{
+ gl: WebGLRenderingContext;
+ prog: WebGLProgram;
+ } | null>(null);
const pickGLRef = useRef<{
- gl: WebGLRenderingContext; prog: WebGLProgram;
- fb: WebGLFramebuffer; tex: WebGLTexture;
+ gl: WebGLRenderingContext;
+ prog: WebGLProgram;
+ fb: WebGLFramebuffer;
+ tex: WebGLTexture;
} | null>(null);
const positions = useMemo(() => {
@@ -180,7 +193,9 @@ function DotGLInteractiveCanvas({
// Render both passes
useEffect(() => {
- if (width <= 0 || height <= 0) return;
+ if (width <= 0 || height <= 0) {
+ return;
+ }
const dpr = window.devicePixelRatio || 1;
// Visible canvas
@@ -191,10 +206,14 @@ function DotGLInteractiveCanvas({
if (!visGLRef.current) {
const gl = visCanvas.getContext('webgl', {
- alpha: true, premultipliedAlpha: false, antialias: true,
+ alpha: true,
+ premultipliedAlpha: false,
+ antialias: true,
});
const prog = gl ? linkProgram(gl, VERT_VIS, FRAG_VIS) : null;
- if (gl && prog) visGLRef.current = {gl, prog};
+ if (gl && prog) {
+ visGLRef.current = {gl, prog};
+ }
}
const vis = visGLRef.current;
@@ -215,7 +234,11 @@ function DotGLInteractiveCanvas({
gl.vertexAttribPointer(aPos, 2, gl.FLOAT, false, 0, 0);
const [r, g, b] = hexToGL(color);
- gl.uniform2f(gl.getUniformLocation(prog, 'u_resolution'), width, height);
+ gl.uniform2f(
+ gl.getUniformLocation(prog, 'u_resolution'),
+ width,
+ height,
+ );
gl.uniform3f(gl.getUniformLocation(prog, 'u_color'), r, g, b);
gl.uniform1f(gl.getUniformLocation(prog, 'u_size'), size * dpr);
gl.uniform1f(gl.getUniformLocation(prog, 'u_opacity'), opacity);
@@ -233,7 +256,9 @@ function DotGLInteractiveCanvas({
if (!pickGLRef.current) {
const gl = pickCanvas.getContext('webgl', {
- alpha: false, premultipliedAlpha: false, antialias: false,
+ alpha: false,
+ premultipliedAlpha: false,
+ antialias: false,
preserveDrawingBuffer: true,
});
if (gl) {
@@ -242,14 +267,27 @@ function DotGLInteractiveCanvas({
const tex = gl.createTexture();
if (prog && fb && tex) {
gl.bindTexture(gl.TEXTURE_2D, tex);
- gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA,
- pickCanvas.width, pickCanvas.height, 0,
- gl.RGBA, gl.UNSIGNED_BYTE, null);
+ gl.texImage2D(
+ gl.TEXTURE_2D,
+ 0,
+ gl.RGBA,
+ pickCanvas.width,
+ pickCanvas.height,
+ 0,
+ gl.RGBA,
+ gl.UNSIGNED_BYTE,
+ null,
+ );
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
- gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0,
- gl.TEXTURE_2D, tex, 0);
+ gl.framebufferTexture2D(
+ gl.FRAMEBUFFER,
+ gl.COLOR_ATTACHMENT0,
+ gl.TEXTURE_2D,
+ tex,
+ 0,
+ );
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
pickGLRef.current = {gl, prog, fb, tex};
}
@@ -261,9 +299,17 @@ function DotGLInteractiveCanvas({
const {gl, prog, fb, tex} = pick;
gl.bindTexture(gl.TEXTURE_2D, tex);
- gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA,
- pickCanvas.width, pickCanvas.height, 0,
- gl.RGBA, gl.UNSIGNED_BYTE, null);
+ gl.texImage2D(
+ gl.TEXTURE_2D,
+ 0,
+ gl.RGBA,
+ pickCanvas.width,
+ pickCanvas.height,
+ 0,
+ gl.RGBA,
+ gl.UNSIGNED_BYTE,
+ null,
+ );
gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
gl.viewport(0, 0, pickCanvas.width, pickCanvas.height);
@@ -286,7 +332,11 @@ function DotGLInteractiveCanvas({
gl.enableVertexAttribArray(aCol);
gl.vertexAttribPointer(aCol, 3, gl.FLOAT, false, 0, 0);
- gl.uniform2f(gl.getUniformLocation(prog, 'u_resolution'), width, height);
+ gl.uniform2f(
+ gl.getUniformLocation(prog, 'u_resolution'),
+ width,
+ height,
+ );
gl.uniform1f(gl.getUniformLocation(prog, 'u_size'), (size + 4) * dpr);
gl.drawArrays(gl.POINTS, 0, positions.length / 2);
@@ -299,10 +349,14 @@ function DotGLInteractiveCanvas({
const handleMouseMove = useCallback((e: React.MouseEvent<SVGRectElement>) => {
const pick = pickGLRef.current;
- if (!pick) return;
+ if (!pick) {
+ return;
+ }
const svg = e.currentTarget.ownerSVGElement;
- if (!svg) return;
+ if (!svg) {
+ return;
+ }
const pt = svg.createSVGPoint();
pt.x = e.clientX;
pt.y = e.clientY;
@@ -315,7 +369,15 @@ function DotGLInteractiveCanvas({
const {gl, fb} = pick;
gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
const pixel = new Uint8Array(4);
- gl.readPixels(px, gl.canvas.height - py, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, pixel);
+ gl.readPixels(
+ px,
+ gl.canvas.height - py,
+ 1,
+ 1,
+ gl.RGBA,
+ gl.UNSIGNED_BYTE,
+ pixel,
+ );
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
const idx = colorToIndex(pixel[0], pixel[1], pixel[2]);
@@ -328,11 +390,15 @@ function DotGLInteractiveCanvas({
setMousePos(null);
}, []);
- const datum = hoverIndex >= 0 && hoverIndex < data.length ? data[hoverIndex] : null;
+ const datum =
+ hoverIndex >= 0 && hoverIndex < data.length ? data[hoverIndex] : null;
const defaultTooltip = (d: Record<string, unknown>, i: number) => (
- <div style={{display: 'flex', flexDirection: 'column', gap: 2, fontSize: 12}}>
- <div style={{fontWeight: 600, color: 'var(--color-text-primary)'}}>Point {i}</div>
+ <div
+ style={{display: 'flex', flexDirection: 'column', gap: 2, fontSize: 12}}>
+ <div style={{fontWeight: 600, color: 'var(--color-text-primary)'}}>
+ Point {i}
+ </div>
{Object.entries(d).map(([k, v]) => (
<div key={k}>
<span style={{color: 'var(--color-text-secondary)'}}>{k}:</span>{' '}
@@ -344,16 +410,32 @@ function DotGLInteractiveCanvas({
return (
<g>
- <foreignObject x={0} y={0} width={width} height={height} style={{overflow: 'hidden'}}>
- <canvas ref={visCanvasRef} style={{width, height, pointerEvents: 'none'}} />
+ <foreignObject
+ x={0}
+ y={0}
+ width={width}
+ height={height}
+ style={{overflow: 'hidden'}}>
+ <canvas
+ ref={visCanvasRef}
+ style={{width, height, pointerEvents: 'none'}}
+ />
</foreignObject>
- <foreignObject x={0} y={0} width={0} height={0} style={{overflow: 'hidden'}}>
+ <foreignObject
+ x={0}
+ y={0}
+ width={0}
+ height={0}
+ style={{overflow: 'hidden'}}>
<canvas ref={pickCanvasRef} style={{display: 'none'}} />
</foreignObject>
<rect
- x={0} y={0} width={width} height={height}
+ x={0}
+ y={0}
+ width={width}
+ height={height}
fill="transparent"
onMouseMove={handleMouseMove}
onMouseLeave={handleMouseLeave}
@@ -364,7 +446,10 @@ function DotGLInteractiveCanvas({
cx={positions[hoverIndex * 2]}
cy={positions[hoverIndex * 2 + 1]}
r={size / 2 + 3}
- fill="none" stroke={color} strokeWidth={2} strokeOpacity={0.8}
+ fill="none"
+ stroke={color}
+ strokeWidth={2}
+ strokeOpacity={0.8}
pointerEvents="none"
/>
)}
@@ -373,18 +458,20 @@ function DotGLInteractiveCanvas({
<foreignObject
x={mousePos.x + 12}
y={Math.max(0, mousePos.y - 40)}
- width={200} height={120}
+ width={200}
+ height={120}
pointerEvents="none"
style={{overflow: 'visible'}}>
- <div style={{
- background: 'var(--color-background-popover)',
- border: '1px solid var(--color-border)',
- borderRadius: 8,
- padding: '8px 12px',
- boxShadow: 'var(--shadow-med)',
- whiteSpace: 'nowrap',
- width: 'fit-content',
- }}>
+ <div
+ style={{
+ background: 'var(--color-background-popover)',
+ border: '1px solid var(--color-border)',
+ borderRadius: 8,
+ padding: '8px 12px',
+ boxShadow: 'var(--shadow-med)',
+ whiteSpace: 'nowrap',
+ width: 'fit-content',
+ }}>
{renderTooltip
? renderTooltip(datum, hoverIndex)
: defaultTooltip(datum, hoverIndex)}
@@ -407,7 +494,10 @@ function DotGLInteractiveCanvas({
* })]}
* ```
*/
-export function dotGLInteractive(dataKey: string, options: DotGLInteractiveOptions): SeriesDef {
+export function dotGLInteractive(
+ dataKey: string,
+ options: DotGLInteractiveOptions,
+): SeriesDef {
const {color} = options;
const size = options.size ?? 6;
const opacity = options.opacity ?? 0.8;
@@ -426,7 +516,9 @@ export function dotGLInteractive(dataKey: string, options: DotGLInteractiveOptio
const d = data[i];
let px: number;
if ('bandwidth' in xScale) {
- px = ((xScale as ScaleBand<string>)(String(d[xKey])) ?? 0) + (xScale as ScaleBand<string>).bandwidth() / 2;
+ px =
+ ((xScale as ScaleBand<string>)(String(d[xKey])) ?? 0) +
+ (xScale as ScaleBand<string>).bandwidth() / 2;
} else {
px = xScale(d[xKey] as number);
}
diff --git a/packages/lab/src/ChartV2/marks/heatmapGL.tsx b/packages/lab/src/ChartV2/marks/heatmapGL.tsx
index 04b7ab64b0..b46c3fe953 100644
--- a/packages/lab/src/ChartV2/marks/heatmapGL.tsx
+++ b/packages/lab/src/ChartV2/marks/heatmapGL.tsx
@@ -52,7 +52,9 @@ function sampleRamp(
t: number,
): [number, number, number] {
const c = Math.max(0, Math.min(1, t));
- if (ramp.length === 1) return ramp[0];
+ if (ramp.length === 1) {
+ return ramp[0];
+ }
const s = c * (ramp.length - 1);
const lo = Math.floor(s);
const hi = Math.min(lo + 1, ramp.length - 1);
@@ -103,14 +105,20 @@ function HeatmapGLCanvas({
}, [data, yKey, height]);
const domain = useMemo((): [number, number] => {
- if (domainProp) return domainProp;
+ if (domainProp) {
+ return domainProp;
+ }
let min = Infinity,
max = -Infinity;
for (const d of data) {
const v = d[valueKey];
if (typeof v === 'number') {
- if (v < min) min = v;
- if (v > max) max = v;
+ if (v < min) {
+ min = v;
+ }
+ if (v > max) {
+ max = v;
+ }
}
}
return [min, max];
@@ -119,26 +127,39 @@ function HeatmapGLCanvas({
// Mount canvas outside SVG
useEffect(() => {
const marker = markerRef.current;
- if (!marker) return;
- if (!canvasRef.current)
+ if (!marker) {
+ return;
+ }
+ if (!canvasRef.current) {
canvasRef.current = document.createElement('canvas');
+ }
return mountCanvasOverSVG(marker, canvasRef.current, width, height);
}, [width, height]);
// Draw
useEffect(() => {
const canvas = canvasRef.current;
- if (!canvas || width <= 0 || height <= 0) return;
+ if (!canvas || width <= 0 || height <= 0) {
+ return;
+ }
sizeCanvas(canvas, width, height);
- if (!glRef.current) glRef.current = getWebGLContext(canvas);
+ if (!glRef.current) {
+ glRef.current = getWebGLContext(canvas);
+ }
const gl = glRef.current;
- if (!gl) return;
+ if (!gl) {
+ return;
+ }
- if (!programRef.current) programRef.current = createProgram(gl, VERT, FRAG);
+ if (!programRef.current) {
+ programRef.current = createProgram(gl, VERT, FRAG);
+ }
const program = programRef.current;
- if (!program) return;
+ if (!program) {
+ return;
+ }
gl.viewport(0, 0, canvas.width, canvas.height);
setupGLState(gl);
@@ -155,7 +176,9 @@ function HeatmapGLCanvas({
for (const d of data) {
const xVal = xScale(String(d[xKey]));
const yVal = yBandScale(String(d[yKey]));
- if (xVal == null || yVal == null) continue;
+ if (xVal == null || yVal == null) {
+ continue;
+ }
const v = typeof d[valueKey] === 'number' ? (d[valueKey] as number) : 0;
const t = (v - dMin) / range;
@@ -168,7 +191,9 @@ function HeatmapGLCanvas({
// Two triangles per cell
positions.push(x0, y0, x1, y0, x0, y1, x1, y0, x1, y1, x0, y1);
- for (let i = 0; i < 6; i++) colors.push(r, g, b);
+ for (let i = 0; i < 6; i++) {
+ colors.push(r, g, b);
+ }
}
const posBuf = gl.createBuffer();
@@ -204,7 +229,9 @@ function HeatmapGLCanvas({
cellGap,
]);
- if (width <= 0 || height <= 0) return null;
+ if (width <= 0 || height <= 0) {
+ return null;
+ }
return <g ref={markerRef} />;
}
@@ -235,7 +262,9 @@ export function heatmapGL(options: HeatmapGLOptions): SeriesDef {
// the canvas component handles its own cell layout.
const {data, xScale, yScale} = ctx;
const points: ResolvedPoint[] = [];
- if (!('bandwidth' in xScale)) return points;
+ if (!('bandwidth' in xScale)) {
+ return points;
+ }
for (let i = 0; i < data.length; i++) {
const d = data[i];
const px =
@@ -248,7 +277,9 @@ export function heatmapGL(options: HeatmapGLOptions): SeriesDef {
},
render(_resolved, ctx) {
- if (!('bandwidth' in ctx.xScale)) return null;
+ if (!('bandwidth' in ctx.xScale)) {
+ return null;
+ }
return (
<HeatmapGLCanvas
data={ctx.data}
diff --git a/packages/lab/src/ChartV2/marks/line.tsx b/packages/lab/src/ChartV2/marks/line.tsx
index 42fcbf86fd..23a48ce131 100644
--- a/packages/lab/src/ChartV2/marks/line.tsx
+++ b/packages/lab/src/ChartV2/marks/line.tsx
@@ -62,7 +62,9 @@ export function line(dataKey: string, options: LineOptions = {}): SeriesDef {
},
render(resolved) {
- if (resolved.length === 0) return null;
+ if (resolved.length === 0) {
+ return null;
+ }
const curveFactory = CURVES[curve];
const pathGen = d3Line<ResolvedPoint>()
.x(d => d.px)
diff --git a/packages/lab/src/ChartV2/marks/streamGL.tsx b/packages/lab/src/ChartV2/marks/streamGL.tsx
index 747f589fc2..0f921fb9b1 100644
--- a/packages/lab/src/ChartV2/marks/streamGL.tsx
+++ b/packages/lab/src/ChartV2/marks/streamGL.tsx
@@ -95,34 +95,53 @@ function StreamGLCanvas({
// Mount canvas outside SVG
useEffect(() => {
const marker = markerRef.current;
- if (!marker) return;
- if (!canvasRef.current)
+ if (!marker) {
+ return;
+ }
+ if (!canvasRef.current) {
canvasRef.current = document.createElement('canvas');
+ }
return mountCanvasOverSVG(marker, canvasRef.current, width, height);
}, [width, height]);
// Size canvas
useEffect(() => {
const canvas = canvasRef.current;
- if (!canvas || width <= 0 || height <= 0) return;
+ if (!canvas || width <= 0 || height <= 0) {
+ return;
+ }
sizeCanvas(canvas, width, height);
}, [width, height]);
const draw = useCallback(() => {
const canvas = canvasRef.current;
- if (!canvas) return;
- if (!glRef.current) glRef.current = getWebGLContext(canvas);
+ if (!canvas) {
+ return;
+ }
+ if (!glRef.current) {
+ glRef.current = getWebGLContext(canvas);
+ }
const gl = glRef.current;
- if (!gl) return;
+ if (!gl) {
+ return;
+ }
- if (!programRef.current) programRef.current = createProgram(gl, VERT, FRAG);
+ if (!programRef.current) {
+ programRef.current = createProgram(gl, VERT, FRAG);
+ }
const program = programRef.current;
- if (!program) return;
+ if (!program) {
+ return;
+ }
- if (!bufRef.current) bufRef.current = gl.createBuffer();
+ if (!bufRef.current) {
+ bufRef.current = gl.createBuffer();
+ }
const {data: ringData, head, count} = ring.current;
- if (count < 2) return;
+ if (count < 2) {
+ return;
+ }
const linearX = xScale as (v: number) => number;
const drawBuf = new Float32Array(count * 2);
@@ -178,7 +197,9 @@ function StreamGLCanvas({
[bufferSize, draw],
);
- if (width <= 0 || height <= 0) return null;
+ if (width <= 0 || height <= 0) {
+ return null;
+ }
return <g ref={markerRef} />;
}
diff --git a/packages/lab/src/ChatReasoning/XDSChatReasoning.tsx b/packages/lab/src/ChatReasoning/XDSChatReasoning.tsx
index a7d5b5ff20..9e0cf2c945 100644
--- a/packages/lab/src/ChatReasoning/XDSChatReasoning.tsx
+++ b/packages/lab/src/ChatReasoning/XDSChatReasoning.tsx
@@ -247,7 +247,9 @@ export function XDSChatReasoning(props: XDSChatReasoningProps) {
const toggle = useCallback(() => {
const next = !isExpanded;
- if (!isControlled) setInternalExpanded(next);
+ if (!isControlled) {
+ setInternalExpanded(next);
+ }
onExpandedChange?.(next);
}, [isExpanded, isControlled, onExpandedChange]);
diff --git a/packages/lab/src/CodeEditor/XDSCodeEditor.tsx b/packages/lab/src/CodeEditor/XDSCodeEditor.tsx
index 2471bdebe1..26c7f410b3 100644
--- a/packages/lab/src/CodeEditor/XDSCodeEditor.tsx
+++ b/packages/lab/src/CodeEditor/XDSCodeEditor.tsx
@@ -214,7 +214,9 @@ export function XDSCodeEditor({
// Sync textContent with controlled value
useLayoutEffect(() => {
const el = editorRef.current;
- if (!el) return;
+ if (!el) {
+ return;
+ }
if (el.textContent !== value) {
el.textContent = value;
}
@@ -227,33 +229,51 @@ export function XDSCodeEditor({
// Apply CSS Custom Highlight API ranges — small code
useLayoutEffect(() => {
- if (value.length >= SYNC_TOKENIZE_THRESHOLD) return;
- if (!hasHighlightAPI()) return;
+ if (value.length >= SYNC_TOKENIZE_THRESHOLD) {
+ return;
+ }
+ if (!hasHighlightAPI()) {
+ return;
+ }
const el = editorRef.current;
- if (!el) return;
+ if (!el) {
+ return;
+ }
const tok = customTokenizer ?? tokenize;
const tokens = tok(value, language);
- if (tokens.length === 0) return;
+ if (tokens.length === 0) {
+ return;
+ }
return applyHighlightRangesFlat(el, tokens);
}, [value, language, customTokenizer, instanceId]);
// Apply CSS Custom Highlight API ranges — large code (async)
useEffect(() => {
- if (value.length < SYNC_TOKENIZE_THRESHOLD) return;
- if (!hasHighlightAPI()) return;
+ if (value.length < SYNC_TOKENIZE_THRESHOLD) {
+ return;
+ }
+ if (!hasHighlightAPI()) {
+ return;
+ }
const el = editorRef.current;
- if (!el) return;
+ if (!el) {
+ return;
+ }
const abortController = new AbortController();
let cleanup: (() => void) | undefined;
tokenizeAsync(value, language, abortController.signal).then(tokens => {
- if (abortController.signal.aborted) return;
- if (tokens.length === 0) return;
+ if (abortController.signal.aborted) {
+ return;
+ }
+ if (tokens.length === 0) {
+ return;
+ }
cleanup = applyHighlightRangesFlat(el, tokens);
});
@@ -264,22 +284,30 @@ export function XDSCodeEditor({
}, [value, language, customTokenizer, instanceId]);
const handleInput = useCallback(() => {
- if (isComposingRef.current) return;
+ if (isComposingRef.current) {
+ return;
+ }
const el = editorRef.current;
- if (!el) return;
+ if (!el) {
+ return;
+ }
const newValue = el.textContent ?? '';
onChange(newValue);
}, [onChange]);
const handleKeyDown = useCallback(
(e: React.KeyboardEvent<HTMLDivElement>) => {
- if (isReadOnly) return;
+ if (isReadOnly) {
+ return;
+ }
// Tab key: insert 2 spaces
if (e.key === 'Tab') {
e.preventDefault();
const sel = window.getSelection();
- if (!sel || sel.rangeCount === 0) return;
+ if (!sel || sel.rangeCount === 0) {
+ return;
+ }
const range = sel.getRangeAt(0);
range.deleteContents();
const textNode = document.createTextNode(' ');
@@ -289,7 +317,9 @@ export function XDSCodeEditor({
sel.removeAllRanges();
sel.addRange(range);
const el = editorRef.current;
- if (el) onChange(el.textContent ?? '');
+ if (el) {
+ onChange(el.textContent ?? '');
+ }
return;
}
@@ -297,10 +327,14 @@ export function XDSCodeEditor({
if (e.key === 'Enter') {
e.preventDefault();
const sel = window.getSelection();
- if (!sel || sel.rangeCount === 0) return;
+ if (!sel || sel.rangeCount === 0) {
+ return;
+ }
const el = editorRef.current;
- if (!el) return;
+ if (!el) {
+ return;
+ }
const fullText = el.textContent ?? '';
// Find cursor offset
@@ -333,11 +367,15 @@ export function XDSCodeEditor({
const closeChar = AUTO_CLOSE_PAIRS[e.key];
if (closeChar) {
const sel = window.getSelection();
- if (!sel || sel.rangeCount === 0) return;
+ if (!sel || sel.rangeCount === 0) {
+ return;
+ }
const range = sel.getRangeAt(0);
// Only auto-close if no text is selected
- if (!range.collapsed) return;
+ if (!range.collapsed) {
+ return;
+ }
e.preventDefault();
const textNode = document.createTextNode(e.key + closeChar);
@@ -349,7 +387,9 @@ export function XDSCodeEditor({
sel.removeAllRanges();
sel.addRange(range);
const el = editorRef.current;
- if (el) onChange(el.textContent ?? '');
+ if (el) {
+ onChange(el.textContent ?? '');
+ }
}
},
[isReadOnly, onChange],
diff --git a/packages/lab/src/Radial/XDSRadialArea.tsx b/packages/lab/src/Radial/XDSRadialArea.tsx
index 6a7697d924..214105b51c 100644
--- a/packages/lab/src/Radial/XDSRadialArea.tsx
+++ b/packages/lab/src/Radial/XDSRadialArea.tsx
@@ -44,7 +44,9 @@ export function XDSRadialArea({
useRadial();
const points = useMemo(() => {
- if (!axes || !angleByAxis || !radiusScale || !axisDomains) return [];
+ if (!axes || !angleByAxis || !radiusScale || !axisDomains) {
+ return [];
+ }
// Find the data row matching this key
// dataKey matches a value in the first non-axis field, or we use the index
@@ -54,7 +56,9 @@ export function XDSRadialArea({
return Object.values(d).some(v => v === dataKey);
}) ?? data[0];
- if (!datum) return [];
+ if (!datum) {
+ return [];
+ }
return axes.map(key => {
const angle = angleByAxis.get(key)!;
@@ -71,7 +75,9 @@ export function XDSRadialArea({
});
}, [cx, cy, data, dataKey, axes, angleByAxis, radiusScale, axisDomains]);
- if (points.length === 0) return null;
+ if (points.length === 0) {
+ return null;
+ }
const pathPoints = points.map(p => `${p.x},${p.y}`).join(' ');
diff --git a/packages/lab/src/Radial/XDSRadialAxis.tsx b/packages/lab/src/Radial/XDSRadialAxis.tsx
index 56b9f0486f..65613516a0 100644
--- a/packages/lab/src/Radial/XDSRadialAxis.tsx
+++ b/packages/lab/src/Radial/XDSRadialAxis.tsx
@@ -23,7 +23,9 @@ export interface XDSRadialAxisProps {
export function XDSRadialAxis({labelOffset = 16}: XDSRadialAxisProps) {
const {cx, cy, radius, axes, angleByAxis} = useRadial();
- if (!axes || !angleByAxis) return null;
+ if (!axes || !angleByAxis) {
+ return null;
+ }
return (
<g>
diff --git a/packages/lab/src/Radial/XDSRadialChart.tsx b/packages/lab/src/Radial/XDSRadialChart.tsx
index 275350246b..6250bd2474 100644
--- a/packages/lab/src/Radial/XDSRadialChart.tsx
+++ b/packages/lab/src/Radial/XDSRadialChart.tsx
@@ -93,10 +93,14 @@ export function XDSRadialChart({
const [containerWidth, setContainerWidth] = useState(0);
useLayoutEffect(() => {
- if (!containerRef.current) return;
+ if (!containerRef.current) {
+ return;
+ }
const observer = new ResizeObserver(entries => {
const entry = entries[0];
- if (entry) setContainerWidth(entry.contentRect.width);
+ if (entry) {
+ setContainerWidth(entry.contentRect.width);
+ }
});
observer.observe(containerRef.current);
return () => observer.disconnect();
@@ -112,7 +116,9 @@ export function XDSRadialChart({
// Spider: compute axis angles and domains
const spiderCtx = useMemo(() => {
- if (!axes || axes.length === 0) return {};
+ if (!axes || axes.length === 0) {
+ return {};
+ }
const angleByAxis = new Map<string, number>();
const step = (2 * Math.PI) / axes.length;
@@ -129,12 +135,18 @@ export function XDSRadialChart({
for (const d of data) {
const v = d[key];
if (typeof v === 'number') {
- if (v < min) min = v;
- if (v > max) max = v;
+ if (v < min) {
+ min = v;
+ }
+ if (v > max) {
+ max = v;
+ }
}
}
// Include 0 as floor
- if (min > 0) min = 0;
+ if (min > 0) {
+ min = 0;
+ }
axisDomains.set(key, [min, max]);
}
@@ -146,14 +158,18 @@ export function XDSRadialChart({
// Pie: compute slices
const pieCtx = useMemo(() => {
- if (!valueKey) return {};
+ if (!valueKey) {
+ return {};
+ }
const total = data.reduce((sum, d) => {
const v = d[valueKey];
return sum + (typeof v === 'number' ? v : 0);
}, 0);
- if (total === 0) return {slices: []};
+ if (total === 0) {
+ return {slices: []};
+ }
const totalPad = padAngle * data.length;
const available = 2 * Math.PI - totalPad;
diff --git a/packages/lab/src/Radial/XDSRadialGrid.tsx b/packages/lab/src/Radial/XDSRadialGrid.tsx
index adf856e29f..eb1ad95385 100644
--- a/packages/lab/src/Radial/XDSRadialGrid.tsx
+++ b/packages/lab/src/Radial/XDSRadialGrid.tsx
@@ -24,7 +24,9 @@ export function XDSRadialGrid({rings = 5}: XDSRadialGridProps) {
const {cx, cy, radius, innerRadius, axes, angleByAxis, radiusScale} =
useRadial();
- if (!axes || !angleByAxis || !radiusScale) return null;
+ if (!axes || !angleByAxis || !radiusScale) {
+ return null;
+ }
return (
<g>
diff --git a/packages/lab/src/Radial/XDSRadialSlice.tsx b/packages/lab/src/Radial/XDSRadialSlice.tsx
index 29d8b20ad5..02caea6031 100644
--- a/packages/lab/src/Radial/XDSRadialSlice.tsx
+++ b/packages/lab/src/Radial/XDSRadialSlice.tsx
@@ -78,7 +78,9 @@ export function XDSRadialSlice({
}: XDSRadialSliceProps) {
const {cx, cy, radius, innerRadius, slices} = useRadial();
- if (!slices || slices.length === 0) return null;
+ if (!slices || slices.length === 0) {
+ return null;
+ }
return (
<g>
diff --git a/packages/lab/src/Radial/XDSRadialTooltip.tsx b/packages/lab/src/Radial/XDSRadialTooltip.tsx
index cecc5ea497..ab1df54926 100644
--- a/packages/lab/src/Radial/XDSRadialTooltip.tsx
+++ b/packages/lab/src/Radial/XDSRadialTooltip.tsx
@@ -98,16 +98,22 @@ export function XDSRadialTooltip({
const hitTestPie = useCallback(
(localX: number, localY: number): RadialTooltipDatum | null => {
- if (!slices || slices.length === 0) return null;
+ if (!slices || slices.length === 0) {
+ return null;
+ }
const dx = localX - cx;
const dy = localY - cy;
const dist = Math.sqrt(dx * dx + dy * dy);
- if (dist > radius || dist < innerRadius) return null;
+ if (dist > radius || dist < innerRadius) {
+ return null;
+ }
let angle = Math.atan2(dy, dx);
- if (angle < -Math.PI / 2) angle += 2 * Math.PI;
+ if (angle < -Math.PI / 2) {
+ angle += 2 * Math.PI;
+ }
for (let i = 0; i < slices.length; i++) {
const slice = slices[i];
@@ -128,13 +134,17 @@ export function XDSRadialTooltip({
const hitTestSpider = useCallback(
(localX: number, localY: number): RadialTooltipDatum | null => {
- if (!axes || !angleByAxis || !axisDomains) return null;
+ if (!axes || !angleByAxis || !axisDomains) {
+ return null;
+ }
const dx = localX - cx;
const dy = localY - cy;
const dist = Math.sqrt(dx * dx + dy * dy);
- if (dist > radius + 20) return null;
+ if (dist > radius + 20) {
+ return null;
+ }
const angle = Math.atan2(dy, dx);
let nearestAxis = axes[0];
@@ -142,14 +152,18 @@ export function XDSRadialTooltip({
for (const [key, axisAngle] of angleByAxis) {
let diff = Math.abs(angle - axisAngle);
- if (diff > Math.PI) diff = 2 * Math.PI - diff;
+ if (diff > Math.PI) {
+ diff = 2 * Math.PI - diff;
+ }
if (diff < minAngleDist) {
minAngleDist = diff;
nearestAxis = key;
}
}
- if (minAngleDist > Math.PI / axes.length) return null;
+ if (minAngleDist > Math.PI / axes.length) {
+ return null;
+ }
let bestIdx = 0;
let bestVal = 0;
@@ -173,13 +187,17 @@ export function XDSRadialTooltip({
const updateTooltip = useCallback(
(e: React.PointerEvent<SVGCircleElement>) => {
const svg = svgRef.current;
- if (!svg) return;
+ if (!svg) {
+ return;
+ }
const pt = svg.createSVGPoint();
pt.x = e.clientX;
pt.y = e.clientY;
const ctm = svg.getScreenCTM()?.inverse();
- if (!ctm) return;
+ if (!ctm) {
+ return;
+ }
const local = pt.matrixTransform(ctm);
const hit =
@@ -214,7 +232,9 @@ export function XDSRadialTooltip({
// Mouse: hover. Touch: drag (only if active).
const handlePointerMove = useCallback(
(e: React.PointerEvent<SVGCircleElement>) => {
- if (e.pointerType !== 'mouse' && !active.current) return;
+ if (e.pointerType !== 'mouse' && !active.current) {
+ return;
+ }
updateTooltip(e);
},
[updateTooltip],
diff --git a/packages/lab/src/SVGIcon/XDSSVGIcon.tsx b/packages/lab/src/SVGIcon/XDSSVGIcon.tsx
index 124cc09de7..c4c9b1771f 100644
--- a/packages/lab/src/SVGIcon/XDSSVGIcon.tsx
+++ b/packages/lab/src/SVGIcon/XDSSVGIcon.tsx
@@ -168,7 +168,9 @@ function needsMask(
primaryFillShapes: IconShape[],
secondaryShapes: IconShape[],
): boolean {
- if (variation !== 'bold') return false;
+ if (variation !== 'bold') {
+ return false;
+ }
return primaryFillShapes.length > 0 && secondaryShapes.length > 0;
}
@@ -225,7 +227,9 @@ function renderFillRoleShapes(
? iconVars['--icon-layer-primary-opacity']
: iconVars['--icon-layer-secondary-opacity'];
- if (shapes.length === 0) return null;
+ if (shapes.length === 0) {
+ return null;
+ }
return (
<g
@@ -265,7 +269,9 @@ function renderStrokeRoleShapes(shapes: IconShape[], layer: LayerPrefix) {
? iconVars['--icon-layer-primary-stroke-role-width']
: iconVars['--icon-layer-secondary-stroke-role-width'];
- if (shapes.length === 0) return null;
+ if (shapes.length === 0) {
+ return null;
+ }
return (
<g
diff --git a/packages/lab/src/SVGIcon/pathTransforms.ts b/packages/lab/src/SVGIcon/pathTransforms.ts
index 0f018d7007..538fb921f9 100644
--- a/packages/lab/src/SVGIcon/pathTransforms.ts
+++ b/packages/lab/src/SVGIcon/pathTransforms.ts
@@ -241,12 +241,16 @@ function angleBetween(v1: Point, v2: Point): number {
const dot = v1.x * v2.x + v1.y * v2.y;
const mag1 = Math.sqrt(v1.x ** 2 + v1.y ** 2);
const mag2 = Math.sqrt(v2.x ** 2 + v2.y ** 2);
- if (mag1 === 0 || mag2 === 0) return Math.PI;
+ if (mag1 === 0 || mag2 === 0) {
+ return Math.PI;
+ }
return Math.acos(Math.max(-1, Math.min(1, dot / (mag1 * mag2))));
}
function getEndpoint(cmd: PathCommand): Point | null {
- if (cmd.type === 'Z') return null;
+ if (cmd.type === 'Z') {
+ return null;
+ }
return {x: cmd.x, y: cmd.y};
}
@@ -262,7 +266,9 @@ function getEndpoint(cmd: PathCommand): Point | null {
* @returns Modified d-string with rounded corners
*/
export function roundCorners(d: string, cornerRounding: number): string {
- if (cornerRounding <= 0) return d;
+ if (cornerRounding <= 0) {
+ return d;
+ }
cornerRounding = Math.min(1, cornerRounding);
const cmds = parsePath(d);
@@ -282,14 +288,18 @@ export function roundCorners(d: string, cornerRounding: number): string {
if (curr.type === 'Z' && prev && (prev.type === 'L' || prev.type === 'Q')) {
// Find the M that started this subpath
let mIdx = i - 1;
- while (mIdx >= 0 && cmds[mIdx].type !== 'M') mIdx--;
+ while (mIdx >= 0 && cmds[mIdx].type !== 'M') {
+ mIdx--;
+ }
if (mIdx >= 0) {
const mCmd = cmds[mIdx];
const mPt = getEndpoint(mCmd)!;
const prevPt = getEndpoint(prev)!;
// Find the first L after M
let firstL = mIdx + 1;
- while (firstL < cmds.length && cmds[firstL].type !== 'L') firstL++;
+ while (firstL < cmds.length && cmds[firstL].type !== 'L') {
+ firstL++;
+ }
if (firstL < cmds.length) {
const firstLPt = getEndpoint(cmds[firstL])!;
@@ -396,7 +406,9 @@ export function roundCorners(d: string, cornerRounding: number): string {
* @returns Modified d-string with curved segments
*/
export function addCurvature(d: string, curvature: number): string {
- if (curvature <= 0) return d;
+ if (curvature <= 0) {
+ return d;
+ }
curvature = Math.min(1, curvature);
const cmds = parsePath(d);
@@ -461,7 +473,9 @@ export function addCurvature(d: string, curvature: number): string {
* @returns Modified d-string
*/
export function adjustTension(d: string, tension: number): string {
- if (tension === 0.5) return d;
+ if (tension === 0.5) {
+ return d;
+ }
const cmds = parsePath(d);
const result: PathCommand[] = [];
diff --git a/packages/lab/src/Sankey/XDSSankeyChart.tsx b/packages/lab/src/Sankey/XDSSankeyChart.tsx
index 345a0e8b62..4fe5587b54 100644
--- a/packages/lab/src/Sankey/XDSSankeyChart.tsx
+++ b/packages/lab/src/Sankey/XDSSankeyChart.tsx
@@ -61,7 +61,9 @@ function resolveColumnCount(
nodes: SankeyNode[],
links: SankeyLink[],
): number {
- if (columns) return columns.length;
+ if (columns) {
+ return columns.length;
+ }
// Quick topological column count
const inDegree = new Map<string, number>();
const outEdges = new Map<string, string[]>();
@@ -87,7 +89,9 @@ function resolveColumnCount(
for (const tgt of outEdges.get(id) || []) {
colMap.set(tgt, Math.max(colMap.get(tgt) || 0, col + 1));
inDegree.set(tgt, (inDegree.get(tgt) || 0) - 1);
- if (inDegree.get(tgt) === 0) queue.push(tgt);
+ if (inDegree.get(tgt) === 0) {
+ queue.push(tgt);
+ }
}
}
return Math.max(...Array.from(colMap.values()), 0) + 1;
@@ -132,7 +136,9 @@ export function XDSSankeyChart({
useLayoutEffect(() => {
const el = containerRef.current;
- if (!el) return;
+ if (!el) {
+ return;
+ }
const ro = new ResizeObserver(entries => {
const w = entries[0]?.contentRect.width ?? 0;
setContainerWidth(w);
@@ -151,7 +157,9 @@ export function XDSSankeyChart({
const needsScroll = containerWidth > 0 && chartWidth > containerWidth;
const layout = useMemo(() => {
- if (containerWidth === 0) return null;
+ if (containerWidth === 0) {
+ return null;
+ }
return computeLayout(nodes, links, {
width: chartWidth,
height,
@@ -171,7 +179,9 @@ export function XDSSankeyChart({
]);
const ctx = useMemo(() => {
- if (!layout) return null;
+ if (!layout) {
+ return null;
+ }
return {
nodes: layout.nodes,
links: layout.links,
diff --git a/packages/lab/src/Sankey/XDSSankeyLabel.tsx b/packages/lab/src/Sankey/XDSSankeyLabel.tsx
index 4a3c7168b4..ab0008621e 100644
--- a/packages/lab/src/Sankey/XDSSankeyLabel.tsx
+++ b/packages/lab/src/Sankey/XDSSankeyLabel.tsx
@@ -23,8 +23,12 @@ export interface XDSSankeyLabelProps {
}
function defaultFormat(value: number): string {
- if (value >= 10000) return Math.round(value / 1000) + 'k';
- if (value >= 1000) return (value / 1000).toFixed(1) + 'k';
+ if (value >= 10000) {
+ return Math.round(value / 1000) + 'k';
+ }
+ if (value >= 1000) {
+ return (value / 1000).toFixed(1) + 'k';
+ }
return value.toLocaleString();
}
diff --git a/packages/lab/src/Sankey/XDSSankeyLink.tsx b/packages/lab/src/Sankey/XDSSankeyLink.tsx
index 0b56d1059a..e2b1ed4461 100644
--- a/packages/lab/src/Sankey/XDSSankeyLink.tsx
+++ b/packages/lab/src/Sankey/XDSSankeyLink.tsx
@@ -50,9 +50,15 @@ function resolveColor(color: SankeyLinkColor): ResolvedMode {
if (typeof color === 'object' && 'gradient' in color) {
return {type: 'gradient', bias: color.gradient};
}
- if (color === 'gradient') return {type: 'gradient', bias: 0.5};
- if (color === 'source') return {type: 'source'};
- if (color === 'target') return {type: 'target'};
+ if (color === 'gradient') {
+ return {type: 'gradient', bias: 0.5};
+ }
+ if (color === 'source') {
+ return {type: 'source'};
+ }
+ if (color === 'target') {
+ return {type: 'target'};
+ }
return {type: 'flat', value: color};
}
diff --git a/packages/lab/src/Sankey/layout.ts b/packages/lab/src/Sankey/layout.ts
index 9058a074c4..c6fb2a39c0 100644
--- a/packages/lab/src/Sankey/layout.ts
+++ b/packages/lab/src/Sankey/layout.ts
@@ -75,7 +75,9 @@ function autoColumns(
const newCol = col + 1;
colMap.set(tgt, Math.max(colMap.get(tgt) || 0, newCol));
inDegree.set(tgt, (inDegree.get(tgt) || 0) - 1);
- if (inDegree.get(tgt) === 0) queue.push(tgt);
+ if (inDegree.get(tgt) === 0) {
+ queue.push(tgt);
+ }
}
}
@@ -130,7 +132,9 @@ export function computeLayout(
(s, id) => s + (nodeMap.get(id)?.value || 0),
0,
);
- if (total > maxColValue) maxColValue = total;
+ if (total > maxColValue) {
+ maxColValue = total;
+ }
});
const maxNodes = Math.max(...colDefs.map(c => c.ids.length));
@@ -154,7 +158,9 @@ export function computeLayout(
col.ids.forEach(id => {
const node = nodeMap.get(id);
- if (!node) return;
+ if (!node) {
+ return;
+ }
const h = node.value * valueScale;
const color =
node.color || DEFAULT_PALETTE[colorIdx % DEFAULT_PALETTE.length];
diff --git a/packages/lab/src/ThreeD/XDS3DChart.tsx b/packages/lab/src/ThreeD/XDS3DChart.tsx
index c7147cad79..6498e31f5f 100644
--- a/packages/lab/src/ThreeD/XDS3DChart.tsx
+++ b/packages/lab/src/ThreeD/XDS3DChart.tsx
@@ -44,8 +44,12 @@ function computeDomain(
for (const d of data) {
const v = d[key];
if (typeof v === 'number') {
- if (v < min) min = v;
- if (v > max) max = v;
+ if (v < min) {
+ min = v;
+ }
+ if (v > max) {
+ max = v;
+ }
}
}
return [min === Infinity ? 0 : min, max === -Infinity ? 1 : max];
@@ -80,9 +84,13 @@ export function XDS3DChart({
} | null>(null);
useLayoutEffect(() => {
- if (!containerRef.current) return;
+ if (!containerRef.current) {
+ return;
+ }
const obs = new ResizeObserver(e => {
- if (e[0]) setContainerWidth(e[0].contentRect.width);
+ if (e[0]) {
+ setContainerWidth(e[0].contentRect.width);
+ }
});
obs.observe(containerRef.current);
return () => obs.disconnect();
@@ -127,7 +135,9 @@ export function XDS3DChart({
const handleStart = useCallback(
(clientX: number, clientY: number) => {
- if (!interactive) return;
+ if (!interactive) {
+ return;
+ }
dragRef.current = {
startX: clientX,
startY: clientY,
@@ -139,7 +149,9 @@ export function XDS3DChart({
);
const handleMove = useCallback((clientX: number, clientY: number) => {
- if (!dragRef.current) return;
+ if (!dragRef.current) {
+ return;
+ }
const dx = clientX - dragRef.current.startX;
const dy = clientY - dragRef.current.startY;
setCamera({
@@ -157,7 +169,9 @@ export function XDS3DChart({
// Auto-rotation — throttled to ~20fps to avoid overwhelming React with re-renders
useEffect(() => {
- if (autoRotate === 0) return;
+ if (autoRotate === 0) {
+ return;
+ }
let raf: number;
let lastUpdate = 0;
const interval = 50; // ms between React updates (~20fps)
@@ -206,7 +220,15 @@ export function XDS3DChart({
);
return (
- <div ref={containerRef} style={{width: '100%', touchAction: interactive ? 'none' : undefined, userSelect: interactive ? 'none' : undefined} as React.CSSProperties}>
+ <div
+ ref={containerRef}
+ style={
+ {
+ width: '100%',
+ touchAction: interactive ? 'none' : undefined,
+ userSelect: interactive ? 'none' : undefined,
+ } as React.CSSProperties
+ }>
{containerWidth > 0 && (
<svg
width={containerWidth}
@@ -217,7 +239,9 @@ export function XDS3DChart({
onMouseLeave={handleEnd}
onTouchStart={e => {
const t = e.touches[0];
- if (t) handleStart(t.clientX, t.clientY);
+ if (t) {
+ handleStart(t.clientX, t.clientY);
+ }
}}
onTouchMove={e => {
const t = e.touches[0];
diff --git a/packages/lab/src/ThreeD/XDS3DScatterGL.tsx b/packages/lab/src/ThreeD/XDS3DScatterGL.tsx
index a466f3f3c1..d7e7378855 100644
--- a/packages/lab/src/ThreeD/XDS3DScatterGL.tsx
+++ b/packages/lab/src/ThreeD/XDS3DScatterGL.tsx
@@ -80,7 +80,9 @@ function compileShader(
src: string,
): WebGLShader | null {
const s = gl.createShader(type);
- if (!s) return null;
+ if (!s) {
+ return null;
+ }
gl.shaderSource(s, src);
gl.compileShader(s);
if (!gl.getShaderParameter(s, gl.COMPILE_STATUS)) {
@@ -93,9 +95,13 @@ function compileShader(
function createProgram(gl: WebGLRenderingContext): WebGLProgram | null {
const vs = compileShader(gl, gl.VERTEX_SHADER, VERT);
const fs = compileShader(gl, gl.FRAGMENT_SHADER, FRAG);
- if (!vs || !fs) return null;
+ if (!vs || !fs) {
+ return null;
+ }
const p = gl.createProgram();
- if (!p) return null;
+ if (!p) {
+ return null;
+ }
gl.attachShader(p, vs);
gl.attachShader(p, fs);
gl.linkProgram(p);
@@ -144,11 +150,17 @@ export function XDS3DScatterGL({
// Mount canvas as sibling to SVG
useEffect(() => {
const marker = markerRef.current;
- if (!marker) return;
+ if (!marker) {
+ return;
+ }
const svg = marker.ownerSVGElement;
- if (!svg) return;
+ if (!svg) {
+ return;
+ }
const parent = svg.parentElement;
- if (!parent) return;
+ if (!parent) {
+ return;
+ }
// Ensure parent is positioned for absolute child
if (getComputedStyle(parent).position === 'static') {
@@ -170,14 +182,18 @@ export function XDS3DScatterGL({
containerRef.current = parent as HTMLDivElement;
return () => {
- if (canvas.parentElement) canvas.parentElement.removeChild(canvas);
+ if (canvas.parentElement) {
+ canvas.parentElement.removeChild(canvas);
+ }
};
}, []);
// Draw
useEffect(() => {
const canvas = canvasRef.current;
- if (!canvas || width <= 0 || height <= 0) return;
+ if (!canvas || width <= 0 || height <= 0) {
+ return;
+ }
const dpr = (window.devicePixelRatio || 2) * 2; // 2x supersampling + smoothstep for crisp circles // supersampling for crisp circles
canvas.width = width * dpr;
@@ -193,11 +209,17 @@ export function XDS3DScatterGL({
});
}
const gl = glRef.current;
- if (!gl) return;
+ if (!gl) {
+ return;
+ }
- if (!programRef.current) programRef.current = createProgram(gl);
+ if (!programRef.current) {
+ programRef.current = createProgram(gl);
+ }
const program = programRef.current;
- if (!program) return;
+ if (!program) {
+ return;
+ }
const buf = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, buf);
@@ -239,7 +261,9 @@ export function XDS3DScatterGL({
gl.deleteBuffer(buf);
}, [positions, camera, color, size, opacity, width, height, data.length]);
- if (width <= 0 || height <= 0) return null;
+ if (width <= 0 || height <= 0) {
+ return null;
+ }
// Render an invisible SVG marker — the canvas is mounted imperatively as a sibling
return <g ref={markerRef} />;
diff --git a/packages/lab/src/ThreeD/XDS3DSurface.tsx b/packages/lab/src/ThreeD/XDS3DSurface.tsx
index 3ed130aa68..3dcd397b56 100644
--- a/packages/lab/src/ThreeD/XDS3DSurface.tsx
+++ b/packages/lab/src/ThreeD/XDS3DSurface.tsx
@@ -20,7 +20,9 @@ export interface XDS3DSurfaceProps {
function lerpColor(colors: string[], t: number): string {
const clamped = Math.max(0, Math.min(1, t));
- if (colors.length === 1) return colors[0];
+ if (colors.length === 1) {
+ return colors[0];
+ }
const scaled = clamped * (colors.length - 1);
const lo = Math.floor(scaled);
const hi = Math.min(lo + 1, colors.length - 1);
@@ -60,7 +62,9 @@ export function XDS3DSurface({
const cols = xVals.length;
const rows = zVals.length;
- if (cols < 2 || rows < 2) return [];
+ if (cols < 2 || rows < 2) {
+ return [];
+ }
// Build lookup grid
const grid = new Map<string, Record<string, unknown>>();
@@ -79,7 +83,9 @@ export function XDS3DSurface({
grid.get(`${xVals[c]},${zVals[r + 1]}`),
];
- if (corners.some(c => !c)) continue;
+ if (corners.some(c => !c)) {
+ continue;
+ }
const projected = corners.map(d => {
const nx = normalize(d![xKey] as number, xDomain);
diff --git a/packages/vega/src/XDSVegaChart.tsx b/packages/vega/src/XDSVegaChart.tsx
index 64e7e5d9a2..43cec1d2ac 100644
--- a/packages/vega/src/XDSVegaChart.tsx
+++ b/packages/vega/src/XDSVegaChart.tsx
@@ -94,14 +94,18 @@ export function XDSVegaChart({
useEffect(() => {
const container = containerRef.current;
- if (!container) return;
+ if (!container) {
+ return;
+ }
let cancelled = false;
let view: View | null = null;
const fail = (err: unknown) => {
if (!cancelled) {
- onErrorRef.current?.(err instanceof Error ? err : new Error(String(err)));
+ onErrorRef.current?.(
+ err instanceof Error ? err : new Error(String(err)),
+ );
}
};
@@ -161,8 +165,11 @@ export function XDSVegaChart({
<div
ref={node => {
containerRef.current = node;
- if (typeof ref === 'function') ref(node);
- else if (ref) (ref as React.MutableRefObject<HTMLDivElement | null>).current = node;
+ if (typeof ref === 'function') {
+ ref(node);
+ } else if (ref) {
+ (ref as React.MutableRefObject<HTMLDivElement | null>).current = node;
+ }
}}
className={className}
style={style}