An open source design system that's fully customizable and agent ready
TypeScript
fix(Button, Tab, Tokenizer and more): slots follow isRenderable; no truthy-guard baseline (#9501)
Cindy Zhang322c0d6e66a8
diff --git a/.changeset/controls-slot-presence.md b/.changeset/controls-slot-presence.mdnew file mode 100644index 0000000000..cce16107ae--- /dev/null+++ b/.changeset/controls-slot-presence.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] Avatar, BreadcrumbItem, Button, Lightbox, SegmentedControlItem, Tab, Tokenizer: a slot whose value is `0` showed a stray "0" beside its slot, or, in SegmentedControlItem's and Tab's icons and Tab's end content, was dropped. That covers `startIcon`, `icon`, `endContent`, a Lightbox `caption` and `selectedIcon`. Now each slot follows the shared presence check. Empty values (`null`, `false`, `''`) render no slot, as an omitted one does, and `0` renders inside its slot as content. A Tab whose `selectedIcon` is `0` shows it while selected instead of falling back to `icon`. An Avatar whose `status` is `0` no longer shows a stray "0"; its status slot still renders only for a truthy value.++@cixzhangdiff --git a/docs/architecture/react-component-runtime.md b/docs/architecture/react-component-runtime.mdindex ede1028a2c..56838fde56 100644--- a/docs/architecture/react-component-runtime.md+++ b/docs/architecture/react-component-runtime.md@@ -319,8 +319,7 @@ those contracts.different emptiness test for one slot, such as an empty-state rule, governsthat slot; numeric counts and plain string fields are not slots. (Knownimplementation gaps include: Core slots that still test presence with a- truthiness guard (the `no-truthy-jsx-guard` baseline lists the inline ones;- a converted guard such as `!!value` or `Boolean(value)` is not listed), a+ converted truthiness guard such as `!!value` or `Boolean(value)`, abare nullish check, or a `??` default replacement do not yet follow thisclause: they may draw a wrapper or lane for `''`, `false`, or `true`, drop`0` or render it as a stray `0` outside its slot, or show nothing instead@@ -473,18 +472,18 @@ observable-behavior predicates require review or runtime evidence. Likewise, afocused test proves only its named behavior and mutation expectation; a greencomponent suite is not blanket conformance with every invariant.-| Invariant | Evidence | Failure signal |-| --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |-| INV1–INV2 | Initial-render and interaction tests | Output flashes a known-wrong state, or one action is delayed or repeated through an Effect |-| INV3, INV5 | StrictMode setup/cleanup and dependency-change tests | Duplicate callback, leaked work, stale subscription, or missing resynchronization |-| INV1, INV4, INV6 | Ref attach/null/replacement, DOM-in-state rejection, and old-node cleanup-before-new-attach mutations | A DOM node or collection enters state, old node remains active, cleanup misses replacement, or ref mutation changes semantics silently |-| INV7 | Real-browser geometry plus N-consumer observer-instance/subscription mutations | Geometry is invalid, observer instances grow with repeated consumers, one unsubscribe silences peers, or cleanup removes another subscriber |-| INV8 | Owner-observable behavior across documented composition replacement; optional focused internal mechanism tests | Behavior disappears or changes owner when a documented subpart is replaced |-| INV9 | Provider/external-store identity and render-count tests | Unchanged semantic payload changes identity, or snapshot identity creates a render loop |-| INV10 | Shared test over every adopter of the announcement module | An adopter holding its own Effect, observer, timer, or listener for its own-content announcement |-| INV11 | Source boundary check plus hook tests across StrictMode replay and unmount | A second keyboard listener or measurement in Core; a consumer reading a CSS custom property on the root or a shared ancestor for the height; an export of the hook; a component outside Core measuring by a rule other than AST-099 FR2, or riding the keyboard; a listener left after unmount; a Core rider driven by JavaScript per frame or by its own transition; or more than one layout read per keyboard change |-| INV12 | Source boundary check plus real-browser tests on a throttled phone profile over a 10-level by 50-sibling tree and two changes in one frame | A per-frame height or layout, a walk past the area or into a subtree other than `display: contents`, an element moved twice for one frame, an added element other than a swap's one transient copy, that copy left after the swap ends, or an exported reporting function fails |-| INV13 | Source boundary check plus bundle analysis of a page with several touch components, and real-browser tests on a throttled phone profile, under a fine pointer, and on a hybrid device | A second copy of a touch module on one page, a component bundling its own copy of a module's primitive, an `import()` of a module in a component other than `Item`'s released loader for its deprecated swipe props, a swipe module (the gesture core, the animator, the panels' rendering, the row's gesture code) imported by `Item` or `ListItem`, swipe code in `Item` other than its deprecated path (that loader, the released row style, the role gate, the `commit` warning, the bridge, the click guard, the event forwarders, and the coexistence diagnostic), or any of it outside the deprecated path, a public export or doc entry for the modules, an install call or installed check in the public API, a gesture listener in a component that uses no gesture, or an idle document listener outside a press other than the one shared press controller and the one stray-click swallower, an import of `@astryxdesign/core/internal/*` outside Core and Lab, a class outside the recognizer family, an `instanceof` check on a recognizer, an internal factory with a public factory's name, or a direct module import for a job the public layer covers fails |-| INV15 | Unit tests of the animator's value mode and real-browser proofs of its adopters | A value off its motion role, a count past the component's swap size, a count or cross-fade under reduced motion with a coarse or a fine pointer, an intermediate value announced, or a public export fails |-| INV16 | Review of each Core component that handles a concern Core owns in a shared hook or utility | A Core component that keeps its own effect, listener, or tracker for that concern fails, whether or not it also calls the hook or utility |-| INV16 (slot presence) | `no-nullish-jsx-guard` strict lint over Core and RichText, with no baseline, and `no-truthy-jsx-guard` strict lint over Core, whose baseline (`no-truthy-jsx-guard.baseline.json`) lists the truthiness guards that predate it and only shrinks; both catch inline guards only, so review also checks for a presence test hoisted into a variable, converted (`!!value`, `Boolean(value)`), made by an early return or a `??` default, or passed through a prop spread, which the lints pass; empty-slot tests that pass `''`, `false`, `true`, and `null` and compare with an omitted slot, plus `0` as content, in Item, MetadataList, ChatSystemMessage, TreeList, TopNavMegaMenu, RichTextEditor, and RichTextEditorToolbar | A slot given `''`, `true`, or `false` draws a wrapper, lane, border, or separator that an omitted slot does not, an element loses the name it has without the slot, `0` does not render, or a new bare nullish or truthiness presence test, inline or hoisted, a truthiness guard past the baseline, a baseline entry added, or a hand-written copy of the check lands |+| Invariant | Evidence | Failure signal |+| --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |+| INV1–INV2 | Initial-render and interaction tests | Output flashes a known-wrong state, or one action is delayed or repeated through an Effect |+| INV3, INV5 | StrictMode setup/cleanup and dependency-change tests | Duplicate callback, leaked work, stale subscription, or missing resynchronization |+| INV1, INV4, INV6 | Ref attach/null/replacement, DOM-in-state rejection, and old-node cleanup-before-new-attach mutations | A DOM node or collection enters state, old node remains active, cleanup misses replacement, or ref mutation changes semantics silently |+| INV7 | Real-browser geometry plus N-consumer observer-instance/subscription mutations | Geometry is invalid, observer instances grow with repeated consumers, one unsubscribe silences peers, or cleanup removes another subscriber |+| INV8 | Owner-observable behavior across documented composition replacement; optional focused internal mechanism tests | Behavior disappears or changes owner when a documented subpart is replaced |+| INV9 | Provider/external-store identity and render-count tests | Unchanged semantic payload changes identity, or snapshot identity creates a render loop |+| INV10 | Shared test over every adopter of the announcement module | An adopter holding its own Effect, observer, timer, or listener for its own-content announcement |+| INV11 | Source boundary check plus hook tests across StrictMode replay and unmount | A second keyboard listener or measurement in Core; a consumer reading a CSS custom property on the root or a shared ancestor for the height; an export of the hook; a component outside Core measuring by a rule other than AST-099 FR2, or riding the keyboard; a listener left after unmount; a Core rider driven by JavaScript per frame or by its own transition; or more than one layout read per keyboard change |+| INV12 | Source boundary check plus real-browser tests on a throttled phone profile over a 10-level by 50-sibling tree and two changes in one frame | A per-frame height or layout, a walk past the area or into a subtree other than `display: contents`, an element moved twice for one frame, an added element other than a swap's one transient copy, that copy left after the swap ends, or an exported reporting function fails |+| INV13 | Source boundary check plus bundle analysis of a page with several touch components, and real-browser tests on a throttled phone profile, under a fine pointer, and on a hybrid device | A second copy of a touch module on one page, a component bundling its own copy of a module's primitive, an `import()` of a module in a component other than `Item`'s released loader for its deprecated swipe props, a swipe module (the gesture core, the animator, the panels' rendering, the row's gesture code) imported by `Item` or `ListItem`, swipe code in `Item` other than its deprecated path (that loader, the released row style, the role gate, the `commit` warning, the bridge, the click guard, the event forwarders, and the coexistence diagnostic), or any of it outside the deprecated path, a public export or doc entry for the modules, an install call or installed check in the public API, a gesture listener in a component that uses no gesture, or an idle document listener outside a press other than the one shared press controller and the one stray-click swallower, an import of `@astryxdesign/core/internal/*` outside Core and Lab, a class outside the recognizer family, an `instanceof` check on a recognizer, an internal factory with a public factory's name, or a direct module import for a job the public layer covers fails |+| INV15 | Unit tests of the animator's value mode and real-browser proofs of its adopters | A value off its motion role, a count past the component's swap size, a count or cross-fade under reduced motion with a coarse or a fine pointer, an intermediate value announced, or a public export fails |+| INV16 | Review of each Core component that handles a concern Core owns in a shared hook or utility | A Core component that keeps its own effect, listener, or tracker for that concern fails, whether or not it also calls the hook or utility |+| INV16 (slot presence) | `no-nullish-jsx-guard` strict lint over Core and RichText, with no baseline, and `no-truthy-jsx-guard` strict lint over Core, with no baseline; both catch inline guards only, so review also checks for a presence test hoisted into a variable, converted (`!!value`, `Boolean(value)`), made by an early return or a `??` default, or passed through a prop spread, which the lints pass; empty-slot tests that pass `''`, `false`, `true`, and `null` and compare with an omitted slot, plus `0` as content, in Item, MetadataList, ChatSystemMessage, TreeList, TopNavMegaMenu, RichTextEditor, and RichTextEditorToolbar | A slot given `''`, `true`, or `false` draws a wrapper, lane, border, or separator that an omitted slot does not, an element loses the name it has without the slot, `0` does not render, or a new bare nullish or truthiness presence test, inline or hoisted, a truthiness guard past the baseline, a baseline entry added, or a hand-written copy of the check lands |diff --git a/eslint.config.js b/eslint.config.jsindex cd49431d24..2c4f5ec82e 100644--- a/eslint.config.js+++ b/eslint.config.js@@ -49,19 +49,6 @@ const internalBarrelBaseline = JSON.parse(),);-// Truthiness guards on ReactNode values that existed when-// `@astryx/no-truthy-jsx-guard` arrived, by repo-relative file, once per-// guard. The list only shrinks.-const truthyGuardBaseline = JSON.parse(- readFileSync(- path.join(- import.meta.dirname,- 'internal/eslint-plugin-astryx/no-truthy-jsx-guard.baseline.json',- ),- 'utf8',- ),-);-// Private `data-astryx-*` attributes written by hand before// `@astryx/no-raw-private-attribute` arrived, by repo-relative file, once per// site. The list only shrinks.@@ -963,8 +950,7 @@ export default defineConfig(// renders a stray "0" (`&&`) or drops the slot (`? :`), so a slot's// presence is decided by `isRenderable` here too. The rule reads types, so// its scope is core, which the type-aware block above parses with the- // project service. The guards that predate the rule are listed in the- // baseline, once per guard; one more is reported (an error in strict mode).+ // project service. Every guard is reported (an error in strict mode).{files: truthyGuardScope.files,ignores: truthyGuardScope.ignores,@@ -972,10 +958,7 @@ export default defineConfig('@astryx': astryxEslintPlugin,},rules: {- '@astryx/no-truthy-jsx-guard': [- reactSeverity,- {baseline: truthyGuardBaseline, root: import.meta.dirname},- ],+ '@astryx/no-truthy-jsx-guard': reactSeverity,},},// A private `data-astryx-*` attribute is written once, in its owner modulediff --git a/internal/eslint-plugin-astryx/README.md b/internal/eslint-plugin-astryx/README.mdindex 08690d811f..12f4c270d1 100644--- a/internal/eslint-plugin-astryx/README.md+++ b/internal/eslint-plugin-astryx/README.md@@ -685,7 +685,7 @@ import {isRenderable} from '@astryxdesign/core/utils';}```-The rule needs type information (`parserOptions.projectService`) and stops with an error without it, so it is not in the presets. The repository config enforces it in core, where it is an error in strict mode. Other packages read core's types from core's build output, so a core type there is `any` before a build and real after it; the rule would give a different result per build state, so they are out of scope. The guards that predate it are listed in `no-truthy-jsx-guard.baseline.json`, once per guard, and that many stay allowed until they move to `isRenderable`; one more is reported. Regenerate the list with `node internal/eslint-plugin-astryx/no-truthy-jsx-guard.baseline.mjs` (`--check` verifies it). A guard that is right as written says so with `// eslint-disable-next-line @astryx/no-truthy-jsx-guard -- <reason>`. The rule also provides an ESLint suggestion that wraps the guard in `isRenderable(value)` (add the import manually).+The rule needs type information (`parserOptions.projectService`) and stops with an error without it, so it is not in the presets. The repository config enforces it in core, where it is an error in strict mode. Other packages read core's types from core's build output, so a core type there is `any` before a build and real after it; the rule would give a different result per build state, so they are out of scope. Core has no baseline: every guard is reported. A guard that is right as written says so with `// eslint-disable-next-line @astryx/no-truthy-jsx-guard -- <reason>`. The rule also provides an ESLint suggestion that wraps the guard in `isRenderable(value)` (add the import manually).### `@astryx/focus-outline-keyboard-only`diff --git a/internal/eslint-plugin-astryx/no-truthy-jsx-guard.baseline.json b/internal/eslint-plugin-astryx/no-truthy-jsx-guard.baseline.jsondeleted file mode 100644index 347e9bf30c..0000000000--- a/internal/eslint-plugin-astryx/no-truthy-jsx-guard.baseline.json+++ /dev/null@@ -1,9 +0,0 @@-{- "packages/core/src/Avatar/Avatar.tsx": ["status"],- "packages/core/src/Breadcrumbs/BreadcrumbItem.tsx": ["startIcon"],- "packages/core/src/Button/Button.tsx": ["endContent", "icon"],- "packages/core/src/Lightbox/Lightbox.tsx": ["currentItem.caption"],- "packages/core/src/SegmentedControl/SegmentedControlItem.tsx": ["icon"],- "packages/core/src/TabList/Tab.tsx": ["displayIcon", "endContent"],- "packages/core/src/Tokenizer/Tokenizer.tsx": ["startIcon", "startIcon"]-}diff --git a/internal/eslint-plugin-astryx/no-truthy-jsx-guard.baseline.mjs b/internal/eslint-plugin-astryx/no-truthy-jsx-guard.baseline.mjsdeleted file mode 100644index 2affdaddac..0000000000--- a/internal/eslint-plugin-astryx/no-truthy-jsx-guard.baseline.mjs+++ /dev/null@@ -1,29 +0,0 @@-// Copyright (c) Meta Platforms, Inc. and affiliates.--/**- * @file no-truthy-jsx-guard.baseline.mjs- * @description Writes (or, with --check, verifies) the baseline that- * `@astryx/no-truthy-jsx-guard` allows: each guarded ReactNode value, per- * file, once per truthiness guard that predates the rule. Run it after- * moving guards to `isRenderable`, or after merging main into a branch that- * changes the rule, so the list only names guards that still exist.- *- * node internal/eslint-plugin-astryx/no-truthy-jsx-guard.baseline.mjs [--check]- */--import path from 'node:path';-import {scope} from './no-truthy-jsx-guard.js';-import {runRuleBaseline} from './rule-baseline.mjs';--await runRuleBaseline({- ruleId: '@astryx/no-truthy-jsx-guard',- scope,- targets: ['packages/core/src'],- baselineFile: path.join(- import.meta.dirname,- 'no-truthy-jsx-guard.baseline.json',- ),- entryFromMessage: message => /^`([^`]*)`/.exec(message)?.[1] ?? null,- unique: false,- noun: 'truthiness guards',-});diff --git a/packages/core/src/Avatar/Avatar.tsx b/packages/core/src/Avatar/Avatar.tsxindex 2e143bbcb3..482278f9c8 100644--- a/packages/core/src/Avatar/Avatar.tsx+++ b/packages/core/src/Avatar/Avatar.tsx@@ -824,7 +824,9 @@ export function Avatar({</div>)}</div>- {status && (+ {/* The status slot renders for a truthy value only. A falsy one, 0+ included, renders nothing, not a stray "0". */}+ {Boolean(status) && (<div{...stylex.props(styles.status,diff --git a/packages/core/src/Breadcrumbs/BreadcrumbItem.tsx b/packages/core/src/Breadcrumbs/BreadcrumbItem.tsxindex f566909628..0f280210fb 100644--- a/packages/core/src/Breadcrumbs/BreadcrumbItem.tsx+++ b/packages/core/src/Breadcrumbs/BreadcrumbItem.tsx@@ -73,6 +73,7 @@ import type {DropdownMenuOption} from '../DropdownMenu/DropdownMenu';import {useMergedRefs} from '../hooks/useMergedRefs';import {useInteractionModalityTracking} from '../utils/interactionModality';+import {isRenderable} from '../utils/isRenderable';// =============================================================================// Props// =============================================================================@@ -373,7 +374,9 @@ export function BreadcrumbItem({const content = (<>- {startIcon && <span {...stylex.props(itemStyles.icon)}>{startIcon}</span>}+ {isRenderable(startIcon) && (+ <span {...stylex.props(itemStyles.icon)}>{startIcon}</span>+ )}{children}</>);diff --git a/packages/core/src/Button/Button.tsx b/packages/core/src/Button/Button.tsxindex 493eaaef7f..5fba526295 100644--- a/packages/core/src/Button/Button.tsx+++ b/packages/core/src/Button/Button.tsx@@ -71,6 +71,7 @@ import {useComponentTranslator,} from '../i18n/useComponentTranslator';import english from '../i18n/generated-english/Button/Button.generated';+import {isRenderable} from '../utils/isRenderable';registerEnglishFallback(english);@@ -803,7 +804,7 @@ export function Button({: loadingStyles.hiddenContent),)}aria-hidden={isLoadingState || undefined}>- {icon && (+ {isRenderable(icon) && (<span{...stylex.props(styles.iconWrapper, iconBoxSizeStyles[iconSize])}><IconDefaultSizeProvider value={iconSize}>@@ -814,7 +815,7 @@ export function Button({{isIconOnly ? null : (<span {...stylex.props(styles.labelText)}>{children ?? label}</span>)}- {!isIconOnly && endContent && (+ {!isIconOnly && isRenderable(endContent) && (<span {...stylex.props(styles.endContentWrapper)}>{endContent}</span>)}</span>diff --git a/packages/core/src/Lightbox/Lightbox.tsx b/packages/core/src/Lightbox/Lightbox.tsxindex 34ac76bcf4..9a0e117ffd 100644--- a/packages/core/src/Lightbox/Lightbox.tsx+++ b/packages/core/src/Lightbox/Lightbox.tsx@@ -54,6 +54,7 @@ import {useComponentTranslator,} from '../i18n/useComponentTranslator';import english from '../i18n/generated-english/Lightbox/Lightbox.generated';+import {isRenderable} from '../utils/isRenderable';registerEnglishFallback(english);/**@@ -762,7 +763,7 @@ export function Lightbox({)}</div>- {currentItem.caption && (+ {isRenderable(currentItem.caption) && (<div {...stylex.props(styles.caption)}>{currentItem.caption}</div>diff --git a/packages/core/src/SegmentedControl/SegmentedControlItem.tsx b/packages/core/src/SegmentedControl/SegmentedControlItem.tsxindex fe02152e51..744909149a 100644--- a/packages/core/src/SegmentedControl/SegmentedControlItem.tsx+++ b/packages/core/src/SegmentedControl/SegmentedControlItem.tsx@@ -37,6 +37,7 @@ import {themeProps} from '../utils/themeProps';import {focusOutlineProps} from '../utils/focusOutline.stylex';import {interactionOverlayStyles} from '../utils/interactionOverlay.stylex';import {usePressFeedback} from '../hooks/usePressFeedback';+import {isRenderable} from '../utils/isRenderable';export interface SegmentedControlItemProps extends BaseProps<HTMLButtonElement> {ref?: React.Ref<HTMLButtonElement>;@@ -219,7 +220,7 @@ export function SegmentedControlItem({},);- const iconElement = icon ? (+ const iconElement = isRenderable(icon) ? (<span {...stylex.props(styles.icon, iconSizeStyles[size])}>{icon}</span>) : null;diff --git a/packages/core/src/TabList/Tab.tsx b/packages/core/src/TabList/Tab.tsxindex 9b00b1108f..6d7937b772 100644--- a/packages/core/src/TabList/Tab.tsx+++ b/packages/core/src/TabList/Tab.tsx@@ -42,6 +42,7 @@ import {useDevWarning} from '../hooks/useDevWarning';import {EDGE_COMP_ATTR} from '../Layout/edgeCompensation.stylex';import {themeProps} from '../utils/themeProps';import {focusOutlineProps} from '../utils/focusOutline.stylex';+import {isRenderable} from '../utils/isRenderable';export interface TabProps extends BaseProps<HTMLButtonElement> {/**@@ -304,7 +305,8 @@ export function Tab({const isTabsPattern = tabListCtx.pattern === 'tabs';const isLink = href != null && !isTabsPattern;const isTabRole = isTabsPattern && !isLink;- const displayIcon = isSelected && selectedIcon ? selectedIcon : icon;+ const displayIcon =+ isSelected && isRenderable(selectedIcon) ? selectedIcon : icon;const hasVisibleLabel = !isLabelHidden && label !== '';const isDisabled =@@ -353,7 +355,7 @@ export function Tab({!isTabsPattern && panelId != null,);- const iconElement = displayIcon ? (+ const iconElement = isRenderable(displayIcon) ? (<span {...stylex.props(styles.icon, iconSizeStyles[size])}>{displayIcon}</span>@@ -439,7 +441,7 @@ export function Tab({</span>) : null;- const endContentElement = endContent ? (+ const endContentElement = isRenderable(endContent) ? (<span {...stylex.props(styles.endContentWrapper)}>{endContent}</span>) : null;diff --git a/packages/core/src/Tokenizer/Tokenizer.tsx b/packages/core/src/Tokenizer/Tokenizer.tsxindex 9116c3bbcf..a22b621fbd 100644--- a/packages/core/src/Tokenizer/Tokenizer.tsx+++ b/packages/core/src/Tokenizer/Tokenizer.tsx@@ -103,6 +103,7 @@ import {useComponentTranslator,} from '../i18n/useComponentTranslator';import english from '../i18n/generated-english/Tokenizer/Tokenizer.generated';+import {isRenderable} from '../utils/isRenderable';registerEnglishFallback(english);@@ -1414,7 +1415,7 @@ export function Tokenizer<T extends SearchableItem>({controlClassName,controlStyle,)}>- {startIcon && (+ {isRenderable(startIcon as ReactNode) && (<span {...stylex.props(value.length > 0 && styles.startIconWithTokens)}>{renderIconSlot(startIcon, {size: 'sm', color: 'secondary'})}</span>@@ -1647,7 +1648,7 @@ export function Tokenizer<T extends SearchableItem>({controlClassName,controlStyle,)}>- {startIcon && (+ {isRenderable(startIcon as ReactNode) && (<span{...stylex.props(value.length > 0 && styles.startIconWithTokens)}>{renderIconSlot(startIcon, {size: 'sm', color: 'secondary'})}@@ -1751,7 +1752,7 @@ export function Tokenizer<T extends SearchableItem>({)}>{isTruncated && (<>- {startIcon &&+ {isRenderable(startIcon as ReactNode) &&renderIconSlot(startIcon, {size: 'sm',color: 'secondary',diff --git a/packages/core/src/__tests__/slotPresence.controls.test.tsx b/packages/core/src/__tests__/slotPresence.controls.test.tsxnew file mode 100644index 0000000000..20d8160ade--- /dev/null+++ b/packages/core/src/__tests__/slotPresence.controls.test.tsx@@ -0,0 +1,216 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file slotPresence.controls.test.tsx+ * @input BreadcrumbItem, Button, Lightbox, SegmentedControlItem, Tab+ * and Tokenizer slots+ * @output Proves each slot's presence follows the shared `isRenderable` check+ * @position Tests for `architecture:react-component-runtime` INV16+ *+ * An empty value (`null`, `false`, `''`) renders no slot wrapper, as an+ * omitted slot does. `0` is content: it renders inside the slot's wrapper,+ * never as a stray "0" beside it, and a slot that was dropped for `0` shows.+ */++import {beforeAll, describe, it, expect} from 'vitest';+import {render} from '@testing-library/react';+import {Avatar} from '../Avatar/Avatar';+import type {ReactNode} from 'react';+import {Breadcrumbs} from '../Breadcrumbs/Breadcrumbs';+import {BreadcrumbItem} from '../Breadcrumbs/BreadcrumbItem';+import {Button} from '../Button/Button';+import {Lightbox} from '../Lightbox/Lightbox';+import {SegmentedControl} from '../SegmentedControl/SegmentedControl';+import {SegmentedControlItem} from '../SegmentedControl/SegmentedControlItem';+import {TabList} from '../TabList/TabList';+import {Tab} from '../TabList/Tab';+import {Tokenizer} from '../Tokenizer/Tokenizer';++// jsdom does not implement showModal/close on <dialog>; Lightbox uses them.+beforeAll(() => {+ HTMLDialogElement.prototype.showModal ||= function (this: HTMLDialogElement) {+ this.setAttribute('open', '');+ };+ HTMLDialogElement.prototype.close ||= function (this: HTMLDialogElement) {+ this.removeAttribute('open');+ };+});++const EMPTY_VALUES = [+ ['null', null],+ ['false', false],+ ['an empty string', ''],+] as const;++/** The element whose own text is exactly "0", if any. */+function zeroParent(): HTMLElement | null {+ const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT);+ for (let node = walker.nextNode(); node; node = walker.nextNode()) {+ if (node.textContent === '0') {+ return node.parentElement;+ }+ }+ return null;+}++/** Whether the "0" sits inside an element whose class names `style`. */+function zeroIsInside(style: string): boolean {+ return zeroParent()?.closest(`[class*="${style}"]`) != null;+}++/** One slot: how to render it with a value, and its wrapper's class. */+type SlotCase = [string, (value: ReactNode) => ReactNode, string];++const SLOTS: ReadonlyArray<SlotCase> = [+ [+ 'BreadcrumbItem startIcon',+ value => (+ <Breadcrumbs>+ <BreadcrumbItem href="/home" startIcon={value}>+ Home+ </BreadcrumbItem>+ <BreadcrumbItem>Page</BreadcrumbItem>+ </Breadcrumbs>+ ),+ 'itemStyles.icon',+ ],+ [+ 'Button icon',+ value => <Button label="Save" icon={value} />,+ 'styles.iconWrapper',+ ],+ [+ 'Button endContent',+ value => <Button label="Save" endContent={value} />,+ 'styles.endContentWrapper',+ ],+ [+ 'Lightbox caption',+ value => (+ <Lightbox+ isOpen+ onOpenChange={() => {}}+ media={{src: '/photo.jpg', alt: 'Photo', caption: value}}+ />+ ),+ 'styles.caption',+ ],+ [+ 'SegmentedControlItem icon',+ value => (+ <SegmentedControl label="View" value="list" onChange={() => {}}>+ <SegmentedControlItem value="list" label="List" icon={value} />+ </SegmentedControl>+ ),+ 'styles.icon',+ ],+ [+ 'Tab icon',+ value => (+ <TabList value="a" onChange={() => {}}>+ <Tab value="a" label="Overview" icon={value} />+ </TabList>+ ),+ 'styles.icon',+ ],+ [+ 'Tab selectedIcon',+ value => (+ <TabList value="a" onChange={() => {}}>+ <Tab value="a" label="Overview" icon="x" selectedIcon={value} />+ </TabList>+ ),+ 'styles.icon',+ ],+ [+ 'Tab endContent',+ value => (+ <TabList value="a" onChange={() => {}}>+ <Tab value="a" label="Overview" endContent={value} />+ </TabList>+ ),+ 'styles.endContentWrapper',+ ],+];++describe.each(SLOTS)('%s follows isRenderable', (_slot, renderWith, style) => {+ it.each(EMPTY_VALUES)('renders no slot for %s', (_label, value) => {+ render(renderWith(value));+ // Tab selectedIcon falls back to the icon "x", which is not this check.+ if (_slot !== 'Tab selectedIcon') {+ expect(document.querySelector(`[class*="${style}"]`)).toBeNull();+ }+ expect(zeroParent()).toBeNull();+ });++ it('renders 0 inside its slot', () => {+ render(renderWith(0));+ expect(zeroIsInside(style)).toBe(true);+ });+});++describe('Tokenizer startIcon follows isRenderable', () => {+ const source = {search: () => [], bootstrap: () => []};+ const token = {id: 'ada', label: 'Ada'};+ const cases: ReadonlyArray<[string, Record<string, unknown>]> = [+ ['an empty field', {value: []}],+ ['a field with collapsed tokens', {value: [token]}],+ [+ 'a field whose tokens expand in a layer',+ {value: [token], tokenOverflowBehavior: 'unfocusedLayer'},+ ],+ [+ 'the bottom-sheet trigger',+ {value: [token], experimental: {presentation: 'bottom-sheet'}},+ ],+ ];++ describe.each(cases)('in %s', (_case, props) => {+ const renderWith = (startIcon: ReactNode) =>+ render(+ <Tokenizer+ label="People"+ searchSource={source}+ onChange={() => {}}+ value={[]}+ startIcon={startIcon}+ {...props}+ />,+ );++ it.each(EMPTY_VALUES)('renders no start icon for %s', (_label, value) => {+ renderWith(value);+ expect(zeroParent()).toBeNull();+ });++ it('renders 0 as the start icon', () => {+ renderWith(0);+ const parent = zeroParent();+ expect(parent).not.toBeNull();+ // Where the start icon has a wrapper span, the 0 renders inside it,+ // never as a bare text node of the field's control box. The expanded+ // layer renders the icon with no wrapper, so 0 is its content there.+ if (props.tokenOverflowBehavior !== 'unfocusedLayer') {+ expect(parent?.tagName).toBe('SPAN');+ }+ });+ });+});++// Avatar's status slot has its own emptiness test: a truthy value renders it,+// and a falsy one, 0 included, renders nothing.+describe('Avatar status renders for a truthy value only', () => {+ it.each([...EMPTY_VALUES, ['0', 0] as const])(+ 'renders no status slot and no stray "0" for %s',+ (_label, value) => {+ render(<Avatar name="Ada Lovelace" status={value} />);+ expect(document.querySelector('[class*="styles.status"]')).toBeNull();+ expect(zeroParent()).toBeNull();+ },+ );++ it('renders the status slot for a truthy value', () => {+ render(<Avatar name="Ada Lovelace" status={<span>Online</span>} />);+ expect(document.querySelector('[class*="styles.status"]')).not.toBeNull();+ });+});