Skip to content

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

TypeScript

chore(core): standardize dev-time console warnings (#4307)

Cindy Zhang8e7f0566f6b4
diff --git a/packages/core/src/CheckboxList/CheckboxListItem.tsx b/packages/core/src/CheckboxList/CheckboxListItem.tsx
index 37ec776d69..f76366274b 100644
--- a/packages/core/src/CheckboxList/CheckboxListItem.tsx
+++ b/packages/core/src/CheckboxList/CheckboxListItem.tsx
@@ -16,12 +16,13 @@
* - /packages/cli/templates/blocks/components/CheckboxList/ (showcase blocks)
*/
-import {use, useEffect, useRef, type MouseEvent, type ReactNode} from 'react';
+import {use, type MouseEvent, type ReactNode} from 'react';
import * as stylex from '@stylexjs/stylex';
import type {StyleXStyles} from '@stylexjs/stylex';
import {colorVars} from '../theme/tokens.stylex';
import type {BaseProps} from '../BaseProps';
import {composeEventHandlers} from '../utils';
+import {useDevWarning} from '../hooks/useDevWarning';
import {CheckboxInput} from '../CheckboxInput/CheckboxInput';
import {ListItem} from '../List/ListItem';
import {ListContext} from '../List/ListContext';
@@ -171,24 +172,15 @@ export function CheckboxListItem({
: t('@astryx.checkboxList.item.checkbox'));
// Dev-time guardrail: a rich label without `aria-label` leaves the
- // checkbox with the generic name "Checkbox". Warn once per item instance
- // (in an effect) rather than on every render.
- const warnedUnnamedCheckboxRef = useRef(false);
- useEffect(() => {
- if (
- typeof label !== 'string' &&
- ariaLabel == null &&
- !warnedUnnamedCheckboxRef.current
- ) {
- warnedUnnamedCheckboxRef.current = true;
- console.warn(
- 'CheckboxListItem: `label` is a ReactNode, so the checkbox falls ' +
- 'back to the generic accessible name "Checkbox". Pass ' +
- '`aria-label` with a concise string equivalent of the visible ' +
- 'label so screen readers can tell items apart.',
- );
- }
- }, [label, ariaLabel]);
+ // checkbox with the generic name "Checkbox".
+ useDevWarning(
+ 'CheckboxListItem',
+ '`label` is a ReactNode, so the checkbox falls ' +
+ 'back to the generic accessible name "Checkbox". Pass ' +
+ '`aria-label` with a concise string equivalent of the visible ' +
+ 'label so screen readers can tell items apart.',
+ typeof label !== 'string' && ariaLabel == null,
+ );
// Density from list context for checkbox sizing
const listCtx = use(ListContext);
diff --git a/packages/core/src/Dialog/Dialog.tsx b/packages/core/src/Dialog/Dialog.tsx
index d4c2695b55..5fee3c1a3d 100644
--- a/packages/core/src/Dialog/Dialog.tsx
+++ b/packages/core/src/Dialog/Dialog.tsx
@@ -46,6 +46,7 @@ import {
} from '../Layout/padding.stylex';
import type {SpacingStep} from '../utils/types';
import {mergeProps, mergeRefs} from '../utils';
+import {devWarn} from '../utils/devWarning';
import {DialogContext} from './DialogContext';
import {themeProps} from '../utils/themeProps';
@@ -494,8 +495,8 @@ export function Dialog({
}, [isOpen, isInline, allowEscape, onOpenChange]);
// Dev-time guardrail: an open modal should always have an accessible name.
- // Warn once per component instance (in an effect) rather than on every
- // render — mirrors the unnamed-dialog warning in usePopover.
+ // The header-title check reads the DOM, so this stays in an effect; the ref
+ // keeps it to one warning per component instance.
const warnedUnnamedDialogRef = useRef(false);
useEffect(() => {
const hasHeaderTitle =
@@ -508,8 +509,9 @@ export function Dialog({
!warnedUnnamedDialogRef.current
) {
warnedUnnamedDialogRef.current = true;
- console.warn(
- 'Dialog: open dialog has no accessible name. Add a DialogHeader ' +
+ devWarn(
+ 'Dialog',
+ 'open dialog has no accessible name. Add a DialogHeader ' +
'with a `title`, or pass `aria-label`/`aria-labelledby`.',
);
}
diff --git a/packages/core/src/Field/Field.tsx b/packages/core/src/Field/Field.tsx
index 983fedb6e5..aa8f73bb1d 100644
--- a/packages/core/src/Field/Field.tsx
+++ b/packages/core/src/Field/Field.tsx
@@ -25,6 +25,7 @@ import {FieldStatus} from '../FieldStatus/FieldStatus';
import {spacingVars, borderVars} from '../theme/tokens.stylex';
import type {IconType} from '../Icon';
import {mergeProps} from '../utils';
+import {useDevWarning} from '../hooks/useDevWarning';
import {FormLayoutContext} from '../FormLayout/FormLayoutContext';
import {Text} from '../Text';
import {themeProps} from '../utils/themeProps';
@@ -215,11 +216,11 @@ export function Field({
const resolvedMessageID =
status?.messageID ?? (status?.message ? `${inputID}-status` : undefined);
- if (isOptional && isRequired) {
- console.warn(
- 'Field: isOptional and isRequired are mutually exclusive. isOptional takes precedence.',
- );
- }
+ useDevWarning(
+ 'Field',
+ 'isOptional and isRequired are mutually exclusive. isOptional takes precedence.',
+ isOptional && isRequired,
+ );
const labelNode = (
<FieldLabel
diff --git a/packages/core/src/Popover/Popover.tsx b/packages/core/src/Popover/Popover.tsx
index b4cfff6d55..4bce0691b9 100644
--- a/packages/core/src/Popover/Popover.tsx
+++ b/packages/core/src/Popover/Popover.tsx
@@ -26,6 +26,7 @@ import React, {
import {useIsomorphicLayoutEffect} from '../hooks/useIsomorphicLayoutEffect';
import * as stylex from '@stylexjs/stylex';
import {mergeProps} from '../utils';
+import {devWarn} from '../utils/devWarning';
import type {BaseProps} from '../BaseProps';
import {usePopover} from './usePopover';
import type {LayerAlignment, LayerPlacement} from '../Layer/useLayer';
@@ -410,8 +411,9 @@ export function Popover({
const button = findTriggerButton(el);
if (!button) {
- console.warn(
- 'Popover: anchorRef must reference a <button> or [role="button"] element. ' +
+ devWarn(
+ 'Popover',
+ 'anchorRef must reference a <button> or [role="button"] element. ' +
'The popover trigger implements the button + dialog ARIA pattern.',
);
}
@@ -453,8 +455,9 @@ export function Popover({
// Find the button inside the wrapper
const button = findTriggerButton(wrapper);
if (!button) {
- console.warn(
- 'Popover: children must contain a <button> or [role="button"] element. ' +
+ devWarn(
+ 'Popover',
+ 'children must contain a <button> or [role="button"] element. ' +
'The popover trigger implements the button + dialog ARIA pattern.',
);
}
diff --git a/packages/core/src/Popover/usePopover.tsx b/packages/core/src/Popover/usePopover.tsx
index 6fba59f8f8..a137938d36 100644
--- a/packages/core/src/Popover/usePopover.tsx
+++ b/packages/core/src/Popover/usePopover.tsx
@@ -28,6 +28,7 @@ import {
} from '../theme/tokens.stylex';
import {Button} from '../Button';
import {useTranslator} from '../i18n';
+import {useDevWarning} from '../hooks/useDevWarning';
const styles = stylex.create({
// Default popover surface — background, radius, shadow.
@@ -391,19 +392,14 @@ export function usePopover(options: UsePopoverOptions = {}): UsePopoverReturn {
'aria-controls': layer.id,
};
- // Dev-time guardrail: a dialog popover should always be labeled. Warn once
- // per hook instance (in an effect) rather than on every render.
- const warnedUnnamedDialogRef = useRef(false);
- useEffect(() => {
- if (role === 'dialog' && !dialogLabel && !warnedUnnamedDialogRef.current) {
- warnedUnnamedDialogRef.current = true;
- console.warn(
- 'usePopover: role="dialog" without a `dialogLabel` renders an unnamed ' +
- 'dialog. Pass `dialogLabel`, or use `role: "none"` for listbox/menu ' +
- 'popups whose content already carries its own role.',
- );
- }
- }, [role, dialogLabel]);
+ // Dev-time guardrail: a dialog popover should always be labeled.
+ useDevWarning(
+ 'usePopover',
+ 'role="dialog" without a `dialogLabel` renders an unnamed ' +
+ 'dialog. Pass `dialogLabel`, or use `role: "none"` for listbox/menu ' +
+ 'popups whose content already carries its own role.',
+ role === 'dialog' && !dialogLabel,
+ );
// Wrapped render function that includes surface styles and optional hidden close button
const render = useCallback(
diff --git a/packages/core/src/Table/BaseTable.tsx b/packages/core/src/Table/BaseTable.tsx
index a8040a4e96..71eabed3f7 100644
--- a/packages/core/src/Table/BaseTable.tsx
+++ b/packages/core/src/Table/BaseTable.tsx
@@ -42,6 +42,7 @@ import {TableHeaderCell} from './TableHeaderCell';
import {TableHeader} from './TableHeader';
import {TableBody} from './TableBody';
import {mergeProps} from '../utils';
+import {devError} from '../utils/devWarning';
import {EmptyState} from '../EmptyState';
import {Text} from '../Text';
import {themeProps} from '../utils/themeProps';
@@ -92,10 +93,7 @@ function applyPlugins<TPlugin, TProps, TArgs extends unknown[]>(
try {
return transform(acc, ...args);
} catch (error) {
- console.error(
- `[Table] Plugin at index ${index} threw in transform:`,
- error,
- );
+ devError('Table', `Plugin at index ${index} threw in transform:`, error);
return acc;
}
}, initial);
@@ -593,7 +591,7 @@ function BaseTableInner<T extends Record<string, unknown>>({
try {
tableElement = plugin.transformTableContext(tableElement);
} catch (error) {
- console.error('[Table] Plugin threw in transformTableContext:', error);
+ devError('Table', 'Plugin threw in transformTableContext:', error);
}
}
}
diff --git a/packages/core/src/Table/useBaseTablePlugins.ts b/packages/core/src/Table/useBaseTablePlugins.ts
index 613e67e3a1..2463024715 100644
--- a/packages/core/src/Table/useBaseTablePlugins.ts
+++ b/packages/core/src/Table/useBaseTablePlugins.ts
@@ -38,6 +38,7 @@
import {useRef} from 'react';
import type {TablePlugin} from './types';
+import {devWarn} from '../utils/devWarning';
// ======================================================================// Canonical Plugin Order
// ======================================================================
@@ -112,8 +113,9 @@ function validatePlugin<T extends Record<string, unknown>>(
// Warn about unknown keys (likely misspelled transform names)
for (const key of keys) {
if (!VALID_TRANSFORM_KEYS.has(key)) {
- console.warn(
- `[Table] Plugin "${name}" has unknown key "${key}". ` +
+ devWarn(
+ 'Table',
+ `Plugin "${name}" has unknown key "${key}". ` +
`Valid keys: ${[...VALID_TRANSFORM_KEYS].join(', ')}. ` +
`This key will be ignored.`,
);
@@ -125,8 +127,9 @@ function validatePlugin<T extends Record<string, unknown>>(
if (VALID_TRANSFORM_KEYS.has(key)) {
const value = (plugin as Record<string, unknown>)[key];
if (value != null && typeof value !== 'function') {
- console.warn(
- `[Table] Plugin "${name}" has non-function value for "${key}" ` +
+ devWarn(
+ 'Table',
+ `Plugin "${name}" has non-function value for "${key}" ` +
`(got ${typeof value}). Transform will be skipped.`,
);
}
@@ -140,8 +143,9 @@ function validatePlugin<T extends Record<string, unknown>>(
typeof (plugin as Record<string, unknown>)[key] === 'function',
);
if (!hasTransforms) {
- console.warn(
- `[Table] Plugin "${name}" has no transform methods. ` +
+ devWarn(
+ 'Table',
+ `Plugin "${name}" has no transform methods. ` +
`It will be included in the pipeline but won't do anything.`,
);
}
diff --git a/packages/core/src/Thumbnail/Thumbnail.tsx b/packages/core/src/Thumbnail/Thumbnail.tsx
index af5d8f8b02..e610a34d34 100644
--- a/packages/core/src/Thumbnail/Thumbnail.tsx
+++ b/packages/core/src/Thumbnail/Thumbnail.tsx
@@ -25,7 +25,6 @@
* - /packages/cli/templates/blocks/components/Thumbnail/ (showcase blocks)
*/
-import {useEffect, useRef} from 'react';
import * as stylex from '@stylexjs/stylex';
import {
colorVars,
@@ -42,6 +41,7 @@ import {Spinner} from '../Spinner';
import {Tooltip} from '../Tooltip/Tooltip';
import {MediaTheme} from '../theme/MediaTheme';
import {useImageMode} from '../hooks/useImageMode';
+import {useDevWarning} from '../hooks/useDevWarning';
import type {BaseProps} from '../BaseProps';
import type {Elevation} from '../utils/types';
import {mergeProps} from '../utils';
@@ -313,26 +313,21 @@ export function Thumbnail({
// technology. That is fine when the thumbnail is otherwise named — `label`
// (or a consumer-provided aria name) becomes the group's accessible name —
// but with no name source at all the group falls back to a generic
- // "thumbnail". Warn once per component instance (in an effect) rather than
- // on every render.
+ // "thumbnail".
const hasNameSource =
alt != null ||
label != null ||
props['aria-label'] != null ||
props['aria-labelledby'] != null;
- const warnedUnnamedImageRef = useRef(false);
- useEffect(() => {
- if (hasSrc && !hasNameSource && !warnedUnnamedImageRef.current) {
- warnedUnnamedImageRef.current = true;
- console.warn(
- 'Thumbnail: `src` is set without `alt` or `label`. The image is ' +
- 'treated as decorative and hidden from assistive technology, and ' +
- 'the thumbnail falls back to a generic "thumbnail" name. Pass ' +
- '`alt` to describe the image content, or `label` (file name) to ' +
- 'name the thumbnail.',
- );
- }
- }, [hasSrc, hasNameSource]);
+ useDevWarning(
+ 'Thumbnail',
+ '`src` is set without `alt` or `label`. The image is ' +
+ 'treated as decorative and hidden from assistive technology, and ' +
+ 'the thumbnail falls back to a generic "thumbnail" name. Pass ' +
+ '`alt` to describe the image content, or `label` (file name) to ' +
+ 'name the thumbnail.',
+ hasSrc && !hasNameSource,
+ );
const imageContent = (
<>
diff --git a/packages/core/src/Timestamp/Timestamp.tsx b/packages/core/src/Timestamp/Timestamp.tsx
index d4bd34fefa..c45b07f361 100644
--- a/packages/core/src/Timestamp/Timestamp.tsx
+++ b/packages/core/src/Timestamp/Timestamp.tsx
@@ -21,6 +21,7 @@ import * as stylex from '@stylexjs/stylex';
import {Text} from '../Text';
import type {TextType, TextSize, TextColor, TextWeight} from '../theme/types';
import {mergeProps, mergeRefs} from '../utils';
+import {useDevWarning} from '../hooks/useDevWarning';
import type {BaseProps} from '../BaseProps';
import {themeProps} from '../utils/themeProps';
import {colorVars} from '../theme/tokens.stylex';
@@ -415,11 +416,14 @@ export function Timestamp({
return () => clearInterval(timer);
}, [isLive, isValidDate, effectiveFormat, diffSeconds]);
+ useDevWarning(
+ 'Timestamp',
+ `could not parse value ${JSON.stringify(value)} as a date. Rendering nothing.`,
+ !isValidDate,
+ );
+
// Placed after all hooks so the hook order stays stable across renders.
if (!isValidDate) {
- console.warn(
- `Timestamp: could not parse value ${JSON.stringify(value)} as a date. Rendering nothing.`,
- );
return null;
}
diff --git a/packages/core/src/Toast/useToast.tsx b/packages/core/src/Toast/useToast.tsx
index 2d03ec994f..87b61bb604 100644
--- a/packages/core/src/Toast/useToast.tsx
+++ b/packages/core/src/Toast/useToast.tsx
@@ -7,6 +7,7 @@ import {createRoot} from 'react-dom/client';
import {dataAttr} from '../naming';
import {ToastContext, type ToastContextValue} from './ToastContext';
import {ToastViewport} from './ToastViewport';
+import {warnOnce} from '../utils/devWarning';
import type {
ToastOptions,
ToastDismissFn,
@@ -17,7 +18,6 @@ import type {
// Fallback singleton
let fallbackContext: ToastContextValue | null = null;
let fallbackRoot: ReturnType<typeof createRoot> | null = null;
-let fallbackWarned = false;
const ROOT_THEME_ATTRS = ['data-theme', dataAttr('theme')] as const;
@@ -70,13 +70,12 @@ function getFallbackContext(): ToastContextValue {
);
}
- if (!fallbackWarned) {
- fallbackWarned = true;
- console.warn(
- 'useToast: No LayerProvider found. Using fallback viewport. ' +
- 'Wrap your app with <LayerProvider> or <AppShell> for full control.',
- );
- }
+ warnOnce(
+ 'toast-fallback-viewport',
+ 'useToast',
+ 'No LayerProvider found. Using fallback viewport. ' +
+ 'Wrap your app with <LayerProvider> or <AppShell> for full control.',
+ );
const container = document.createElement('div');
container.setAttribute('data-astryx-toast-fallback', '');
diff --git a/packages/core/src/hooks/index.ts b/packages/core/src/hooks/index.ts
index db4b32a05c..5303684933 100644
--- a/packages/core/src/hooks/index.ts
+++ b/packages/core/src/hooks/index.ts
@@ -84,3 +84,5 @@ export type {
export {useLongPress} from './useLongPress';
export type {UseLongPressOptions, UseLongPressHandlers} from './useLongPress';
+
+export {useDevWarning} from './useDevWarning';
diff --git a/packages/core/src/hooks/useDevWarning.test.tsx b/packages/core/src/hooks/useDevWarning.test.tsx
new file mode 100644
index 0000000000..056b73b313
--- /dev/null
+++ b/packages/core/src/hooks/useDevWarning.test.tsx
@@ -0,0 +1,45 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import {afterEach, describe, expect, it, vi} from 'vitest';
+import {render} from '@testing-library/react';
+import {useDevWarning} from './useDevWarning';
+
+afterEach(() => {
+ vi.restoreAllMocks();
+});
+
+function Probe({
+ condition,
+ message = 'boom',
+}: {
+ condition: boolean;
+ message?: string;
+}) {
+ useDevWarning('TestComponent', message, condition);
+ return null;
+}
+
+describe('useDevWarning', () => {
+ it('warns once, in the standardized format, when the condition is true', () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ const {rerender} = render(<Probe condition={true} />);
+ rerender(<Probe condition={true} />);
+ rerender(<Probe condition={true} />);
+ expect(warn).toHaveBeenCalledTimes(1);
+ expect(warn).toHaveBeenCalledWith('TestComponent: boom');
+ });
+
+ it('does not warn when the condition is false', () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ render(<Probe condition={false} />);
+ expect(warn).not.toHaveBeenCalled();
+ });
+
+ it('warns after the condition flips from false to true', () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ const {rerender} = render(<Probe condition={false} />);
+ expect(warn).not.toHaveBeenCalled();
+ rerender(<Probe condition={true} />);
+ expect(warn).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/packages/core/src/hooks/useDevWarning.ts b/packages/core/src/hooks/useDevWarning.ts
new file mode 100644
index 0000000000..cc141e2fc7
--- /dev/null
+++ b/packages/core/src/hooks/useDevWarning.ts
@@ -0,0 +1,54 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file useDevWarning.ts
+ * @input A component name, a message, and a boolean condition
+ * @output Fires a dev-only `Component: message` warning once per mount
+ * @position Core hook; the render-safe way to warn the builder from a component
+ *
+ * The right way to surface a dev guardrail from inside a component. A naive
+ * `if (condition) console.warn(...)` in the render body repeats on every
+ * render, and reaching for `useState` to gate it adds needless state and
+ * re-renders. This hook uses a ref + effect: the warning fires once per mount
+ * when the condition holds, never during render, and never triggers a
+ * re-render. Messages use the standardized `Component: message` format.
+ *
+ * SYNC: When modified, update:
+ * - /packages/core/src/hooks/index.ts
+ * - /packages/core/src/utils/devWarning.ts (the imperative counterpart)
+ */
+
+import {useEffect, useRef} from 'react';
+import {devWarn} from '../utils/devWarning';
+
+/**
+ * Fire a dev-only warning once per mount while `condition` is true.
+ *
+ * @param component - Component or hook name (message prefix)
+ * @param message - What went wrong and how to fix it
+ * @param condition - Whether to warn; defaults to `true`
+ *
+ * @example
+ * ```
+ * useDevWarning(
+ * 'Field',
+ * 'isOptional and isRequired are mutually exclusive. isOptional takes precedence.',
+ * isOptional && isRequired,
+ * );
+ * ```
+ */
+export function useDevWarning(
+ component: string,
+ message: string,
+ condition: boolean = true,
+): void {
+ const hasWarnedRef = useRef(false);
+ useEffect(() => {
+ if (condition && !hasWarnedRef.current) {
+ hasWarnedRef.current = true;
+ devWarn(component, message);
+ }
+ }, [component, message, condition]);
+}
diff --git a/packages/core/src/hooks/useOverflow.ts b/packages/core/src/hooks/useOverflow.ts
index 14d9e17f84..d5853ec15a 100644
--- a/packages/core/src/hooks/useOverflow.ts
+++ b/packages/core/src/hooks/useOverflow.ts
@@ -23,6 +23,7 @@ import {useState, useCallback, useRef} from 'react';
import {useIsomorphicLayoutEffect} from './useIsomorphicLayoutEffect';
import {observeResize, unobserveResize} from '../utils/sharedResizeObserver';
import {computeOverflow} from './computeOverflow';
+import {useDevWarning} from './useDevWarning';
export interface UseOverflowOptions {
/**
@@ -119,17 +120,13 @@ export function useOverflow(
behavior = 'observeSelf',
} = options;
- if (
- process.env.NODE_ENV !== 'production' &&
- maxVisibleItems != null &&
- maxVisibleItems < minVisibleItems
- ) {
- console.warn(
- `useOverflow: maxVisibleItems (${maxVisibleItems}) is less than ` +
- `minVisibleItems (${minVisibleItems}); the floor wins and ` +
- `minVisibleItems items will be shown.`,
- );
- }
+ useDevWarning(
+ 'useOverflow',
+ `maxVisibleItems (${maxVisibleItems}) is less than ` +
+ `minVisibleItems (${minVisibleItems}); the floor wins and ` +
+ `minVisibleItems items will be shown.`,
+ maxVisibleItems != null && maxVisibleItems < minVisibleItems,
+ );
const observeParent = behavior === 'observeParent';
diff --git a/packages/core/src/i18n/resolve.ts b/packages/core/src/i18n/resolve.ts
index 52e5ea3821..d759408684 100644
--- a/packages/core/src/i18n/resolve.ts
+++ b/packages/core/src/i18n/resolve.ts
@@ -22,6 +22,7 @@
import IntlMessageFormat from 'intl-messageformat';
import type {Catalog, Locale, MessagesByLocale, Overrides} from './types';
import enSource from '../../locales/en.json' with {type: 'json'};
+import {warnOnce, __resetDevWarnings} from '../utils/devWarning';
const EN_CATALOG = enSource as Catalog;
@@ -72,23 +73,6 @@ export function resolveLocaleChain(locale: Locale): Locale[] {
return chain;
}
-/**
- * Missing-key warn-once tracking. Fires ONLY when a key is missing from
- * every source including the shipped `en` catalog — that's a real bug
- * (typo, stale catalog, deleted key). Fallback to `en` from a non-en
- * locale is expected and silent, matching the FormatJS / i18next default
- * of not spamming the console when a translation simply hasn't been
- * written yet.
- */
-const warnedMissing = new Set<string>();
-
-function warnOnce(bucket: Set<string>, key: string, message: string): void {
- if (!bucket.has(key)) {
- bucket.add(key);
- console.warn(message);
- }
-}
-
function lookup(
key: string,
locale: Locale,
@@ -135,10 +119,14 @@ export function resolve(
const result = lookup(key, locale, messages, overrides);
if (result === null) {
+ // Fires ONLY when a key is missing from every source including the
+ // shipped `en` catalog — a real bug (typo, stale catalog, deleted key).
+ // Fallback to `en` from a non-en locale is expected and stays silent,
+ // matching the FormatJS / i18next default.
warnOnce(
- warnedMissing,
- `${locale}::${key}`,
- `[astryx-i18n] missing key: ${key} (locale: ${locale})`,
+ `astryx-i18n:${locale}::${key}`,
+ 'astryx-i18n',
+ `missing key: ${key} (locale: ${locale})`,
);
return key;
}
@@ -161,5 +149,5 @@ export function resolve(
*/
export function __resetForTests(): void {
formatterCache.clear();
- warnedMissing.clear();
+ __resetDevWarnings();
}
diff --git a/packages/core/src/theme/Theme.tsx b/packages/core/src/theme/Theme.tsx
index 3c76f3f9c8..885305a7f9 100644
--- a/packages/core/src/theme/Theme.tsx
+++ b/packages/core/src/theme/Theme.tsx
@@ -45,6 +45,7 @@ import {registerIcons} from '../Icon/globalIconRegistry';
import {generateThemeCSS, type DefinedTheme} from './defineTheme';
import {dataAttr} from '../naming';
import {ThemeContext} from './useTheme';
+import {warnOnce} from '../utils/devWarning';
/**
* Theme provider props
@@ -97,9 +98,6 @@ ThemeNestingContext.displayName = 'ThemeNestingContext';
/** Track which themes have already been injected */
const injectedThemes = new Set<string>();
-/** Track which themes have already logged the perf warning */
-const warnedThemes = new Set<string>();
-
/**
* Hook to inject theme CSS into the document.
* Built themes (from `astryx theme build`) skip injection — their CSS
@@ -120,17 +118,16 @@ function useThemeStyleInjection(theme: DefinedTheme): void {
}
// One-time perf hint per theme
- if (!warnedThemes.has(theme.name)) {
- warnedThemes.add(theme.name);
- console.warn(
- `[Astryx] Theme "${theme.name}" is using runtime style injection. ` +
- `For better performance, use the pre-built theme:\n\n` +
- ` import {${theme.name}Theme} from '@astryxdesign/theme-${theme.name}/built';\n` +
- ` import '@astryxdesign/theme-${theme.name}/theme.css';\n\n` +
- `For custom themes, run \`npx @astryxdesign/cli theme build <file>\` to generate ` +
- `the built artifacts.`,
- );
- }
+ warnOnce(
+ `theme-injection:${theme.name}`,
+ 'Theme',
+ `"${theme.name}" is using runtime style injection. ` +
+ `For better performance, use the pre-built theme:\n\n` +
+ ` import {${theme.name}Theme} from '@astryxdesign/theme-${theme.name}/built';\n` +
+ ` import '@astryxdesign/theme-${theme.name}/theme.css';\n\n` +
+ `For custom themes, run \`npx @astryxdesign/cli theme build <file>\` to generate ` +
+ `the built artifacts.`,
+ );
const {prose, component} = generateThemeCSS(theme);
if (!prose && !component) {
diff --git a/packages/core/src/theme/syntax/defineSyntaxTheme.ts b/packages/core/src/theme/syntax/defineSyntaxTheme.ts
index 036f954221..c7dc9973e7 100644
--- a/packages/core/src/theme/syntax/defineSyntaxTheme.ts
+++ b/packages/core/src/theme/syntax/defineSyntaxTheme.ts
@@ -12,6 +12,7 @@
*/
import {syntaxTokenDefaults, type SyntaxTokenName} from './tokens';
+import {devWarn} from '../../utils/devWarning';
// =============================================================================
// Types
@@ -139,12 +140,10 @@ export function defineSyntaxTheme(
): SyntaxThemeDefinition {
const missing = ALL_SYNTAX_KEYS.filter(key => !(key in input.tokens));
if (missing.length > 0) {
- console.warn(
- '[Astryx] defineSyntaxTheme("' +
- input.name +
- '"): missing tokens: ' +
- missing.join(', ') +
- '. All 14 syntax tokens are required.',
+ devWarn(
+ 'defineSyntaxTheme',
+ `"${input.name}": missing tokens: ${missing.join(', ')}. ` +
+ `All 14 syntax tokens are required.`,
);
}
diff --git a/packages/core/src/utils/devWarning.test.ts b/packages/core/src/utils/devWarning.test.ts
new file mode 100644
index 0000000000..a21ee25876
--- /dev/null
+++ b/packages/core/src/utils/devWarning.test.ts
@@ -0,0 +1,56 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import {afterEach, describe, expect, it, vi} from 'vitest';
+import {
+ devWarn,
+ devError,
+ warnOnce,
+ formatDevMessage,
+ __resetDevWarnings,
+} from './devWarning';
+
+afterEach(() => {
+ __resetDevWarnings();
+ vi.restoreAllMocks();
+});
+
+describe('formatDevMessage', () => {
+ it('formats as "Component: message"', () => {
+ expect(formatDevMessage('Field', 'oops')).toBe('Field: oops');
+ });
+});
+
+describe('devWarn', () => {
+ it('warns in the standardized format and forwards extra args', () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ const detail = {a: 1};
+ devWarn('Popover', 'no button', detail);
+ expect(warn).toHaveBeenCalledWith('Popover: no button', detail);
+ });
+});
+
+describe('devError', () => {
+ it('errors in the standardized format', () => {
+ const error = vi.spyOn(console, 'error').mockImplementation(() => {});
+ const err = new Error('boom');
+ devError('Table', 'plugin threw:', err);
+ expect(error).toHaveBeenCalledWith('Table: plugin threw:', err);
+ });
+});
+
+describe('warnOnce', () => {
+ it('fires at most once per key', () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ warnOnce('k', 'Theme', 'runtime injection');
+ warnOnce('k', 'Theme', 'runtime injection');
+ expect(warn).toHaveBeenCalledTimes(1);
+ expect(warn).toHaveBeenCalledWith('Theme: runtime injection');
+ });
+
+ it('fires again for a different key', () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ warnOnce('a', 'Theme', 'one');
+ warnOnce('b', 'Theme', 'two');
+ expect(warn).toHaveBeenCalledTimes(2);
+ });
+});
diff --git a/packages/core/src/utils/devWarning.ts b/packages/core/src/utils/devWarning.ts
new file mode 100644
index 0000000000..0ce68590cf
--- /dev/null
+++ b/packages/core/src/utils/devWarning.ts
@@ -0,0 +1,102 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file devWarning.ts
+ * @input A component/hook name and a message
+ * @output Standardized `Component: message` console warnings and errors
+ * @position Shared dev-logging utility used across components and hooks
+ *
+ * Standardizes how the design system surfaces information to the builder:
+ * every message reads `Component: message` (e.g. `Field: isOptional and
+ * isRequired are mutually exclusive.`), so the source is always obvious in
+ * the console.
+ *
+ * Prefer the `useDevWarning` hook inside components — it guards against
+ * repeating a warning on every render. These imperative helpers exist for
+ * the non-render contexts a hook can't cover: plain functions, module
+ * initialization, and inside effects.
+ *
+ * SYNC: When modified, update:
+ * - /packages/core/src/utils/index.ts
+ * - /packages/core/src/hooks/useDevWarning.ts (the render-path counterpart)
+ */
+
+const isDev = process.env.NODE_ENV !== 'production';
+
+/** Format a message as `Component: message`. */
+export function formatDevMessage(component: string, message: string): string {
+ return `${component}: ${message}`;
+}
+
+/**
+ * Dev-only `console.warn` in the standardized `Component: message` format.
+ * A no-op in production — warnings are builder guardrails, not shipped noise.
+ * Extra args (e.g. an offending value) are forwarded to `console.warn`.
+ *
+ * @example
+ * ```
+ * devWarn('Popover', 'children must contain a <button>.');
+ * ```
+ */
+export function devWarn(
+ component: string,
+ message: string,
+ ...args: unknown[]
+): void {
+ if (!isDev) {
+ return;
+ }
+ console.warn(formatDevMessage(component, message), ...args);
+}
+
+/**
+ * `console.error` in the standardized `Component: message` format. Unlike
+ * {@link devWarn}, this runs in production too: it reports real runtime
+ * failures (e.g. a thrown callback) that should reach error telemetry.
+ *
+ * @example
+ * ```
+ * devError('Table', 'Plugin at index 0 threw in transform:', error);
+ * ```
+ */
+export function devError(
+ component: string,
+ message: string,
+ ...args: unknown[]
+): void {
+ console.error(formatDevMessage(component, message), ...args);
+}
+
+const warnedKeys = new Set<string>();
+
+/**
+ * Dev-only warning that fires at most once per `key` for the lifetime of the
+ * app. Use for singleton warnings that aren't tied to a component instance —
+ * a missing translation key, a per-theme perf hint, a one-time fallback.
+ * For per-component-instance warnings, use the `useDevWarning` hook instead.
+ *
+ * @example
+ * ```
+ * warnOnce(`theme:${name}`, 'Theme', `"${name}" uses runtime injection.`);
+ * ```
+ */
+export function warnOnce(
+ key: string,
+ component: string,
+ message: string,
+ ...args: unknown[]
+): void {
+ if (!isDev || warnedKeys.has(key)) {
+ return;
+ }
+ warnedKeys.add(key);
+ console.warn(formatDevMessage(component, message), ...args);
+}
+
+/**
+ * Clear `warnOnce` dedup state. Test-only.
+ * @internal
+ */
+export function __resetDevWarnings(): void {
+ warnedKeys.clear();
+}
diff --git a/packages/core/src/utils/index.ts b/packages/core/src/utils/index.ts
index 69c61f7b44..2ec626ad52 100644
--- a/packages/core/src/utils/index.ts
+++ b/packages/core/src/utils/index.ts
@@ -92,3 +92,5 @@ export {
toGLFloats,
} from './color';
export type {RGBA} from './color';
+
+export {devWarn, devError, warnOnce, formatDevMessage} from './devWarning';
diff --git a/packages/lab/src/Drawer/Drawer.test.tsx b/packages/lab/src/Drawer/Drawer.test.tsx
index 31e2496e06..fe10e6b537 100644
--- a/packages/lab/src/Drawer/Drawer.test.tsx
+++ b/packages/lab/src/Drawer/Drawer.test.tsx
@@ -483,8 +483,8 @@ describe('Drawer', () => {
});
it('dev-warns and ignores isCollapsed on a modal drawer', () => {
- const consoleError = vi
- .spyOn(console, 'error')
+ const consoleWarn = vi
+ .spyOn(console, 'warn')
.mockImplementation(() => {});
try {
render(
@@ -497,20 +497,20 @@ describe('Drawer', () => {
Content
</Drawer>,
);
- expect(consoleError).toHaveBeenCalledWith(
- expect.stringContaining('[Drawer]'),
+ expect(consoleWarn).toHaveBeenCalledWith(
+ expect.stringContaining('Drawer:'),
);
expect(
screen.queryByRole('button', {name: 'Expand Inspector'}),
).not.toBeInTheDocument();
} finally {
- consoleError.mockRestore();
+ consoleWarn.mockRestore();
}
});
it('dev-warns and ignores isCollapsed on a sheet', () => {
- const consoleError = vi
- .spyOn(console, 'error')
+ const consoleWarn = vi
+ .spyOn(console, 'warn')
.mockImplementation(() => {});
try {
render(
@@ -525,14 +525,14 @@ describe('Drawer', () => {
Content
</Drawer>,
);
- expect(consoleError).toHaveBeenCalledWith(
- expect.stringContaining('[Drawer]'),
+ expect(consoleWarn).toHaveBeenCalledWith(
+ expect.stringContaining('Drawer:'),
);
expect(
screen.queryByRole('button', {name: 'Expand Inspector'}),
).not.toBeInTheDocument();
} finally {
- consoleError.mockRestore();
+ consoleWarn.mockRestore();
}
});
});
diff --git a/packages/lab/src/Drawer/Drawer.tsx b/packages/lab/src/Drawer/Drawer.tsx
index 248bac4328..14b6ff304e 100644
--- a/packages/lab/src/Drawer/Drawer.tsx
+++ b/packages/lab/src/Drawer/Drawer.tsx
@@ -56,7 +56,7 @@ import {
} from '@astryxdesign/core/theme/tokens.stylex';
import {Icon} from '@astryxdesign/core/Icon';
import {IconButton} from '@astryxdesign/core/IconButton';
-import {useScrollLock} from '@astryxdesign/core/hooks';
+import {useScrollLock, useDevWarning} from '@astryxdesign/core/hooks';
import {mergeProps, mergeRefs, themeProps} from '@astryxdesign/core/utils';
// =============================================================================
@@ -494,18 +494,14 @@ export function Drawer({
const collapsed = canCollapse && isCollapsed === true;
const showCloseButton = hasCloseButton ?? hasScrim;
- // Dev warning for unsupported collapse combinations (repo idiom:
- // console.error, see BaseTable plugin errors).
- const hasInvalidCollapse = isCollapsed != null && !canCollapse;
- useEffect(() => {
- if (hasInvalidCollapse) {
- console.error(
- '[Drawer] `isCollapsed` is only supported for non-modal drawers ' +
- '(hasScrim={false}) with side="start" or side="end". The prop is ' +
- 'ignored.',
- );
- }
- }, [hasInvalidCollapse]);
+ // Dev warning for unsupported collapse combinations.
+ useDevWarning(
+ 'Drawer',
+ '`isCollapsed` is only supported for non-modal drawers ' +
+ '(hasScrim={false}) with side="start" or side="end". The prop is ' +
+ 'ignored.',
+ isCollapsed != null && !canCollapse,
+ );
// Open/close the native dialog. close() is delayed so the slide-out
// transition can play; focus restore happens after close() because a