An open source design system that's fully customizable and agent ready
TypeScript
feat(lab): add ListInput (#4740)
Ernest6cc77984eaeb
diff --git a/apps/storybook/stories/ListInput.stories.tsx b/apps/storybook/stories/ListInput.stories.tsxnew file mode 100644index 0000000000..e5d1f56d61--- /dev/null+++ b/apps/storybook/stories/ListInput.stories.tsx@@ -0,0 +1,907 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file ListInput.stories.tsx+ * @input Uses ListInput with controlled data, Astryx field controls, column width helpers, React, and StyleX+ * @output Storybook examples spanning realistic use cases, validation scopes, density, responsiveness, tokenized collection motion, and reordering+ * @position Lab component stories; documents the consumer-facing ListInput API+ */++import * as stylex from '@stylexjs/stylex';+import type {Meta, StoryObj} from '@storybook/react';+import {useCallback, useMemo, useState} from 'react';+import type {ISODateString} from '@astryxdesign/core/Calendar';+import {DateInput} from '@astryxdesign/core/DateInput';+import {NumberInput} from '@astryxdesign/core/NumberInput';+import {Selector} from '@astryxdesign/core/Selector';+import {pixel, proportional} from '@astryxdesign/core/Table';+import {TextInput} from '@astryxdesign/core/TextInput';+import {ListInput, type ListInputColumn} from '@astryxdesign/lab';+const storyStyles = stylex.create({+ canvas: {+ width: 680,+ maxWidth: '100%',+ },+ responsiveCanvas: {+ width: 600,+ maxWidth: '100%',+ },+ narrowCanvas: {+ width: 360,+ maxWidth: '100%',+ },+});++const meta: Meta<typeof ListInput> = {+ title: 'Lab/ListInput',+ component: ListInput,+ tags: ['autodocs'],+ parameters: {+ layout: 'centered',+ },+ decorators: [+ Story => (+ <div {...stylex.props(storyStyles.canvas)}>+ <Story />+ </div>+ ),+ ],+};++export default meta;+type Story = StoryObj<typeof ListInput>;++type TagOption = {+ id: string;+ color: string;+ label: string;+};++const COLOR_OPTIONS = [+ {value: 'blue', label: 'Blue'},+ {value: 'green', label: 'Green'},+ {value: 'amber', label: 'Amber'},+ {value: 'red', label: 'Red'},+ {value: 'purple', label: 'Purple'},+];++const INITIAL_TAGS: TagOption[] = [+ {id: 'tag-new', color: 'blue', label: 'New'},+ {id: 'tag-blocked', color: 'green', label: 'Blocked'},+ {id: 'tag-empty', color: 'amber', label: ''},+ {id: 'tag-review', color: 'purple', label: 'In review'},+];++function hasInvalidCombination(tag: TagOption): boolean {+ const label = tag.label.trim().toLowerCase();+ return (+ (tag.color === 'green' && label === 'blocked') ||+ (tag.color === 'red' && label === 'success')+ );+}+function useTouchedFields() {+ const [touchedFields, setTouchedFields] = useState<ReadonlySet<string>>(+ () => new Set(),+ );+ const markFieldTouched = useCallback((itemID: string, columnKey: string) => {+ const touchedFieldKey = fieldKey(itemID, columnKey);+ setTouchedFields(current => {+ if (current.has(touchedFieldKey)) {+ return current;+ }+ const next = new Set(current);+ next.add(touchedFieldKey);+ return next;+ });+ }, []);+ const isFieldTouched = useCallback(+ (itemID: string, columnKey: string) =>+ touchedFields.has(fieldKey(itemID, columnKey)),+ [touchedFields],+ );++ return {isFieldTouched, markFieldTouched};+}++function fieldKey(itemID: string, columnKey: string): string {+ return JSON.stringify([itemID, columnKey]);+}++function createTagColumns(+ onFieldBlur: (itemID: string, columnKey: string) => void,+): ListInputColumn<TagOption>[] {+ return [+ {+ key: 'color',+ header: 'Color',+ width: proportional(1, {minWidth: 120}),+ renderInput: ({+ item,+ label,+ isLabelHidden,+ status,+ statusVariant,+ isDisabled,+ updateItem,+ }) => (+ <Selector+ label={label}+ isLabelHidden={isLabelHidden}+ options={COLOR_OPTIONS}+ value={item.color}+ onChange={color => updateItem({...item, color}, 'color')}+ status={status}+ statusVariant={statusVariant}+ isDisabled={isDisabled}+ onBlur={() => onFieldBlur(item.id, 'color')}+ />+ ),+ },+ {+ key: 'label',+ header: 'Label',+ width: proportional(2, {minWidth: 200}),+ renderInput: ({+ item,+ label,+ isLabelHidden,+ status,+ statusVariant,+ isDisabled,+ isLoading,+ updateItem,+ }) => (+ <TextInput+ label={label}+ isLabelHidden={isLabelHidden}+ value={item.label}+ onChange={nextLabel =>+ updateItem({...item, label: nextLabel}, 'label')+ }+ status={status}+ statusVariant={statusVariant}+ isDisabled={isDisabled}+ isLoading={isLoading}+ onBlur={() => onFieldBlur(item.id, 'label')}+ />+ ),+ },+ ];+}++function TagOptionsExample({isReorderable}: {isReorderable?: boolean}) {+ const [tags, setTags] = useState(INITIAL_TAGS);+ const {isFieldTouched, markFieldTouched} = useTouchedFields();+ const columns = useMemo(+ () => createTagColumns(markFieldTouched),+ [markFieldTouched],+ );++ return (+ <ListInput<TagOption>+ label="Tag options"+ description={+ isReorderable+ ? 'Add at least five tags and drag rows to set their order. Field errors appear after the first blur.'+ : 'Add at least five tags. Items remain in the order they were added; field errors appear after the first blur.'+ }+ value={tags}+ onChange={setTags}+ getItemKey={tag => tag.id}+ createItem={() => ({+ id: crypto.randomUUID(),+ color: 'blue',+ label: '',+ })}+ columns={columns}+ itemName="tag"+ status={+ tags.length < 5+ ? {type: 'error', message: 'Add at least five tag options.'}+ : undefined+ }+ getItemStatus={tag =>+ hasInvalidCombination(tag)+ ? {+ type: 'error',+ message: `“${tag.label}” cannot use ${tag.color}.`,+ }+ : undefined+ }+ getFieldStatus={(tag, columnKey) =>+ isFieldTouched(tag.id, columnKey) &&+ columnKey === 'label' &&+ tag.label.trim() === ''+ ? {type: 'error', message: 'Enter a label.'}+ : undefined+ }+ isReorderable={isReorderable || undefined}+ />+ );+}++/** Controlled tag options with validation at list, item, and field scope. */+export const TagOptions: Story = {+ render: () => <TagOptionsExample isReorderable />,+ parameters: {+ docs: {+ description: {+ story:+ 'Pointer-activate Add near the bottom of the viewport to keep the action under the pointer while available scroll containers absorb the inserted row from nearest to outermost. The new row receives focus and uses a live translate entrance. Remove one to see stable-size survivors close the gap; reduced-motion preferences use an instant change.',+ },+ },+ },+};++/** Editable tag options using the default fixed insertion order. */+export const NonReorderable: Story = {+ name: 'Non-reorderable',+ render: () => <TagOptionsExample />,+};++type Subscriber = {+ id: string;+ email: string;+};++function isValidEmail(email: string): boolean {+ const normalizedEmail = email.trim();+ const atIndex = normalizedEmail.indexOf('@');+ const dotIndex = normalizedEmail.lastIndexOf('.');+ return (+ atIndex > 0 &&+ dotIndex > atIndex + 1 &&+ dotIndex < normalizedEmail.length - 1+ );+}++function MailingListExample() {+ const [subscribers, setSubscribers] = useState<Subscriber[]>([]);+ const [hasChanged, setHasChanged] = useState(false);+ const {isFieldTouched, markFieldTouched} = useTouchedFields();+ const columns = useMemo<ListInputColumn<Subscriber>[]>(+ () => [+ {+ key: 'email',+ header: 'Email address',+ width: proportional(1, {minWidth: 240}),+ renderInput: ({+ item,+ label,+ isLabelHidden,+ status,+ statusVariant,+ isDisabled,+ isLoading,+ updateItem,+ }) => (+ <TextInput+ type="email"+ label={label}+ isLabelHidden={isLabelHidden}+ value={item.email}+ placeholder="[email protected]"+ onChange={email => updateItem({...item, email}, 'email')}+ onBlur={() => markFieldTouched(item.id, 'email')}+ status={status}+ statusVariant={statusVariant}+ isDisabled={isDisabled}+ isLoading={isLoading}+ />+ ),+ },+ ],+ [markFieldTouched],+ );++ const handleChange = useCallback((nextSubscribers: Subscriber[]) => {+ setSubscribers(nextSubscribers);+ setHasChanged(true);+ }, []);++ return (+ <ListInput<Subscriber>+ label="Mailing list"+ description="Start empty, add up to six addresses, and remove the final row to exercise focus restoration and required-list validation."+ value={subscribers}+ onChange={handleChange}+ getItemKey={subscriber => subscriber.id}+ createItem={() => ({id: crypto.randomUUID(), email: ''})}+ columns={columns}+ itemName="subscriber"+ status={+ hasChanged && subscribers.length === 0+ ? {type: 'error', message: 'Add at least one subscriber.'}+ : undefined+ }+ getItemStatus={subscriber => {+ const email = subscriber.email.trim().toLowerCase();+ const isDuplicate =+ email !== '' &&+ subscribers.some(+ candidate =>+ candidate.id !== subscriber.id &&+ candidate.email.trim().toLowerCase() === email,+ );+ return isDuplicate+ ? {type: 'error', message: 'This address is already in the list.'}+ : undefined;+ }}+ getFieldStatus={(subscriber, columnKey) => {+ if (+ columnKey !== 'email' ||+ !isFieldTouched(subscriber.id, columnKey)+ ) {+ return undefined;+ }+ if (subscriber.email.trim() === '') {+ return {type: 'error', message: 'Enter an email address.'};+ }+ return isValidEmail(subscriber.email)+ ? undefined+ : {type: 'error', message: 'Enter a valid email address.'};+ }}+ isRequired+ maxItems={6}+ />+ );+}++/** A one-column collection that starts empty and validates fields after blur. */+export const EmptyMailingList: Story = {+ render: () => <MailingListExample />,+ parameters: {+ docs: {+ description: {+ story:+ 'Exercises the empty state, add autofocus, one-column layout, duplicate records, blur validation, removing the last item, and the six-item boundary.',+ },+ },+ },+};++type Allocation = {+ id: string;+ team: string;+ percent: number | null;+};++const TEAM_OPTIONS = [+ {value: 'design', label: 'Design'},+ {value: 'engineering', label: 'Engineering'},+ {value: 'marketing', label: 'Marketing'},+ {value: 'operations', label: 'Operations'},+];++const INITIAL_ALLOCATIONS: Allocation[] = [+ {id: 'allocation-design', team: 'design', percent: 35},+ {id: 'allocation-engineering', team: 'engineering', percent: 40},+ {id: 'allocation-marketing', team: 'marketing', percent: 15},+];++function ExpenseAllocationsExample() {+ const [allocations, setAllocations] = useState(INITIAL_ALLOCATIONS);+ const {isFieldTouched, markFieldTouched} = useTouchedFields();+ const total = allocations.reduce(+ (sum, allocation) => sum + (allocation.percent ?? 0),+ 0,+ );+ const columns = useMemo<ListInputColumn<Allocation>[]>(+ () => [+ {+ key: 'team',+ header: 'Team',+ width: proportional(2, {minWidth: 180}),+ renderInput: ({+ item,+ label,+ isLabelHidden,+ status,+ statusVariant,+ isDisabled,+ isLoading,+ updateItem,+ }) => (+ <Selector+ label={label}+ isLabelHidden={isLabelHidden}+ options={TEAM_OPTIONS}+ value={item.team}+ placeholder="Choose a team"+ onChange={team => updateItem({...item, team}, 'team')}+ onBlur={() => markFieldTouched(item.id, 'team')}+ status={status}+ statusVariant={statusVariant}+ isDisabled={isDisabled || isLoading}+ />+ ),+ },+ {+ key: 'percent',+ header: 'Allocation',+ width: pixel(132),+ renderInput: ({+ item,+ label,+ isLabelHidden,+ status,+ statusVariant,+ isDisabled,+ isLoading,+ updateItem,+ }) => (+ <NumberInput+ label={label}+ isLabelHidden={isLabelHidden}+ value={item.percent}+ onChange={percent => updateItem({...item, percent}, 'percent')}+ onBlur={() => markFieldTouched(item.id, 'percent')}+ status={status}+ statusVariant={statusVariant}+ isDisabled={isDisabled || isLoading}+ min={0}+ max={100}+ units="%"+ isIntegerOnly+ />+ ),+ },+ ],+ [markFieldTouched],+ );++ return (+ <ListInput<Allocation>+ label="Quarterly budget allocation"+ description="Assign each team once. The percentages across every row must total 100%."+ value={allocations}+ onChange={setAllocations}+ getItemKey={allocation => allocation.id}+ createItem={() => ({+ id: crypto.randomUUID(),+ team: '',+ percent: null,+ })}+ columns={columns}+ itemName="allocation"+ status={+ total === 100+ ? undefined+ : {+ type: 'error',+ message: `Allocations must total 100%. Current total: ${total}%.`,+ }+ }+ getItemStatus={allocation => {+ const isDuplicate =+ allocation.team !== '' &&+ allocations.some(+ candidate =>+ candidate.id !== allocation.id &&+ candidate.team === allocation.team,+ );+ return isDuplicate+ ? {type: 'error', message: 'Each team can only appear once.'}+ : undefined;+ }}+ getFieldStatus={(allocation, columnKey) => {+ if (!isFieldTouched(allocation.id, columnKey)) {+ return undefined;+ }+ if (columnKey === 'team' && allocation.team === '') {+ return {type: 'error', message: 'Choose a team.'};+ }+ if (columnKey === 'percent' && allocation.percent == null) {+ return {type: 'error', message: 'Enter an allocation.'};+ }+ if (+ columnKey === 'percent' &&+ allocation.percent != null &&+ (allocation.percent < 0 || allocation.percent > 100)+ ) {+ return {type: 'error', message: 'Use a value from 0 to 100.'};+ }+ return undefined;+ }}+ isRequired+ maxItems={4}+ />+ );+}++/** Mixed control types with item-level uniqueness and cross-list totals. */+export const ExpenseAllocations: Story = {+ render: () => <ExpenseAllocationsExample />,+ parameters: {+ docs: {+ description: {+ story:+ 'Exercises Selector and NumberInput alignment, fixed and proportional column widths, duplicate-item errors, field tooltips, and a collection-wide total.',+ },+ },+ },+};++type FamilyMember = {+ id: string;+ fullName: string;+ relationship: string;+ dateOfBirth: ISODateString | undefined;+};++const RELATIONSHIP_OPTIONS = [+ {value: 'spouse-or-partner', label: 'Spouse or partner'},+ {value: 'child', label: 'Child'},+ {value: 'parent', label: 'Parent'},+ {value: 'sibling', label: 'Sibling'},+ {value: 'other-dependent', label: 'Other dependent'},+];++const DECLARATION_DATE: ISODateString = '2026-08-05';++const INITIAL_FAMILY_MEMBERS: FamilyMember[] = [+ {+ id: 'member-jordan',+ fullName: 'Jordan Lee',+ relationship: 'spouse-or-partner',+ dateOfBirth: '1988-11-02',+ },+ {+ id: 'member-alexandria',+ fullName: 'Alexandria María de la Cruz',+ relationship: 'child',+ dateOfBirth: '2012-06-24',+ },+ {+ id: 'member-noah',+ fullName: 'Noah Lee',+ relationship: 'child',+ dateOfBirth: '2018-09-08',+ },+ {+ id: 'member-grace',+ fullName: 'Grace Lee',+ relationship: 'parent',+ dateOfBirth: '1958-04-17',+ },+];++function FamilyMemberDeclarationExample() {+ const [members, setMembers] = useState(INITIAL_FAMILY_MEMBERS);+ const {isFieldTouched, markFieldTouched} = useTouchedFields();+ const columns = useMemo<ListInputColumn<FamilyMember>[]>(+ () => [+ {+ key: 'fullName',+ header: 'Full legal name',+ width: proportional(2, {minWidth: 200}),+ renderInput: ({+ item,+ label,+ isLabelHidden,+ status,+ statusVariant,+ isDisabled,+ isLoading,+ updateItem,+ }) => (+ <TextInput+ label={label}+ isLabelHidden={isLabelHidden}+ value={item.fullName}+ onChange={fullName => updateItem({...item, fullName}, 'fullName')}+ onBlur={() => markFieldTouched(item.id, 'fullName')}+ status={status}+ statusVariant={statusVariant}+ isDisabled={isDisabled}+ isLoading={isLoading}+ />+ ),+ },+ {+ key: 'relationship',+ header: 'Relationship',+ width: proportional(1.25, {minWidth: 160}),+ renderInput: ({+ item,+ label,+ isLabelHidden,+ status,+ statusVariant,+ isDisabled,+ isLoading,+ updateItem,+ }) => (+ <Selector+ label={label}+ isLabelHidden={isLabelHidden}+ options={RELATIONSHIP_OPTIONS}+ value={item.relationship}+ placeholder="Choose relationship"+ onChange={relationship =>+ updateItem({...item, relationship}, 'relationship')+ }+ onBlur={() => markFieldTouched(item.id, 'relationship')}+ status={status}+ statusVariant={statusVariant}+ isDisabled={isDisabled || isLoading}+ />+ ),+ },+ {+ key: 'dateOfBirth',+ header: 'Date of birth',+ width: pixel(176),+ renderInput: ({+ item,+ label,+ isLabelHidden,+ status,+ statusVariant,+ isDisabled,+ isLoading,+ updateItem,+ }) => (+ <DateInput+ label={label}+ isLabelHidden={isLabelHidden}+ value={item.dateOfBirth}+ onChange={dateOfBirth =>+ updateItem({...item, dateOfBirth}, 'dateOfBirth')+ }+ onBlur={() => markFieldTouched(item.id, 'dateOfBirth')}+ status={status}+ statusVariant={statusVariant}+ isDisabled={isDisabled}+ isLoading={isLoading}+ max={DECLARATION_DATE}+ />+ ),+ },+ ],+ [markFieldTouched],+ );++ return (+ <ListInput<FamilyMember>+ label="Family member declaration"+ description="Declare each immediate family member, their relationship to you, and their date of birth."+ value={members}+ onChange={setMembers}+ getItemKey={member => member.id}+ createItem={() => ({+ id: crypto.randomUUID(),+ fullName: '',+ relationship: '',+ dateOfBirth: undefined,+ })}+ columns={columns}+ itemName="family member"+ getItemStatus={(member, index) => {+ if (member.fullName.trim() === '' || member.dateOfBirth == null) {+ return undefined;+ }+ const normalizedName = member.fullName.trim().toLowerCase();+ const firstMatchingIndex = members.findIndex(+ candidate =>+ candidate.fullName.trim().toLowerCase() === normalizedName &&+ candidate.dateOfBirth === member.dateOfBirth,+ );+ return firstMatchingIndex !== index+ ? {+ type: 'error',+ message: 'This family member appears more than once.',+ }+ : undefined;+ }}+ getFieldStatus={(member, columnKey) => {+ if (!isFieldTouched(member.id, columnKey)) {+ return undefined;+ }+ if (columnKey === 'fullName' && member.fullName.trim() === '') {+ return {type: 'error', message: 'Enter a full legal name.'};+ }+ if (columnKey === 'relationship' && member.relationship === '') {+ return {type: 'error', message: 'Choose a relationship.'};+ }+ if (columnKey === 'dateOfBirth' && member.dateOfBirth == null) {+ return {type: 'error', message: 'Choose a date of birth.'};+ }+ if (+ columnKey === 'dateOfBirth' &&+ member.dateOfBirth != null &&+ member.dateOfBirth > DECLARATION_DATE+ ) {+ return {+ type: 'error',+ message: 'Date of birth cannot be in the future.',+ };+ }+ return undefined;+ }}+ isRequired+ />+ );+}++/** Three simple fields per record in a declaration where order is immaterial. */+export const FamilyMemberDeclaration: Story = {+ render: () => <FamilyMemberDeclarationExample />,+ parameters: {+ docs: {+ description: {+ story:+ 'Exercises the intended three-field ceiling, TextInput, Selector, and DateInput alignment, a long international name, blur validation, duplicate-record validation, and non-reorderable semantics.',+ },+ },+ },+};++/** Three fields at an intermediate width that must stack without overflow. */+export const ResponsiveFamilyMemberDeclaration: Story = {+ render: () => (+ <div {...stylex.props(storyStyles.responsiveCanvas)}>+ <FamilyMemberDeclarationExample />+ </div>+ ),+ parameters: {+ docs: {+ description: {+ story:+ 'Exercises the 640px stacking breakpoint at a 600px container with all three field types, repeated labels, and non-reorderable top-aligned remove actions.',+ },+ },+ },+};++type TripLeg = {+ id: string;+ destination: string;+ departureDate: ISODateString | undefined;+};++const INITIAL_TRIP_LEGS: TripLeg[] = [+ {+ id: 'leg-montreal',+ destination: 'Montréal–Pierre Elliott Trudeau International Airport',+ departureDate: '2026-09-12',+ },+ {+ id: 'leg-reykjavik',+ destination: 'Reykjavík',+ departureDate: '2026-09-16',+ },+ {+ id: 'leg-copenhagen',+ destination: 'Copenhagen',+ departureDate: '2026-09-20',+ },+];++function ResponsiveItineraryExample() {+ const [legs, setLegs] = useState(INITIAL_TRIP_LEGS);+ const {isFieldTouched, markFieldTouched} = useTouchedFields();+ const columns = useMemo<ListInputColumn<TripLeg>[]>(+ () => [+ {+ key: 'destination',+ header: 'Destination',+ width: proportional(3, {minWidth: 200}),+ renderInput: ({+ item,+ label,+ isLabelHidden,+ status,+ statusVariant,+ isDisabled,+ isLoading,+ updateItem,+ }) => (+ <TextInput+ label={label}+ isLabelHidden={isLabelHidden}+ value={item.destination}+ onChange={destination =>+ updateItem({...item, destination}, 'destination')+ }+ onBlur={() => markFieldTouched(item.id, 'destination')}+ status={status}+ statusVariant={statusVariant}+ isDisabled={isDisabled}+ isLoading={isLoading}+ />+ ),+ },+ {+ key: 'departureDate',+ header: 'Departure',+ width: proportional(2, {minWidth: 180}),+ renderInput: ({+ item,+ label,+ isLabelHidden,+ status,+ statusVariant,+ isDisabled,+ isLoading,+ updateItem,+ }) => (+ <DateInput+ label={label}+ isLabelHidden={isLabelHidden}+ value={item.departureDate}+ onChange={departureDate =>+ updateItem({...item, departureDate}, 'departureDate')+ }+ onBlur={() => markFieldTouched(item.id, 'departureDate')}+ status={status}+ statusVariant={statusVariant}+ isDisabled={isDisabled}+ isLoading={isLoading}+ min="2026-09-01"+ max="2026-12-31"+ />+ ),+ },+ ],+ [markFieldTouched],+ );++ return (+ <div {...stylex.props(storyStyles.narrowCanvas)}>+ <ListInput<TripLeg>+ label="Multi-city itinerary"+ description="At this width, each leg stacks its two fields while keeping reorder and remove controls available."+ value={legs}+ onChange={setLegs}+ getItemKey={leg => leg.id}+ createItem={() => ({+ id: crypto.randomUUID(),+ destination: '',+ departureDate: undefined,+ })}+ columns={columns}+ itemName="leg"+ getItemStatus={(leg, index) => {+ const previousDate = legs[index - 1]?.departureDate;+ return index > 0 &&+ previousDate != null &&+ leg.departureDate != null &&+ leg.departureDate < previousDate+ ? {+ type: 'error',+ message: 'Departure dates must follow the itinerary order.',+ }+ : undefined;+ }}+ getFieldStatus={(leg, columnKey) => {+ if (!isFieldTouched(leg.id, columnKey)) {+ return undefined;+ }+ if (columnKey === 'destination' && leg.destination.trim() === '') {+ return {type: 'error', message: 'Enter a destination.'};+ }+ if (columnKey === 'departureDate' && leg.departureDate == null) {+ return {type: 'error', message: 'Choose a departure date.'};+ }+ return undefined;+ }}+ isReorderable+ isRequired+ />+ </div>+ );+}++/** The two-column editor at the component's narrow stacking breakpoint. */+export const ResponsiveItinerary: Story = {+ render: () => <ResponsiveItineraryExample />,+ parameters: {+ docs: {+ description: {+ story:+ 'Exercises the 640px container breakpoint, 32px separation between stacked record groups, repeated labels, a long value, DateInput popovers, item-order validation, and reorder/remove controls aligned beside each record’s first field.',+ },+ },+ },+};diff --git a/packages/lab/src/ListInput/ListInput.doc.mjs b/packages/lab/src/ListInput/ListInput.doc.mjsnew file mode 100644index 0000000000..31f4bfd6f2--- /dev/null+++ b/packages/lab/src/ListInput/ListInput.doc.mjs@@ -0,0 +1,375 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').ComponentDoc} */++export const docs = {+ name: 'ListInput',+ displayName: 'List Input',+ group: 'ListInput',+ category: 'Data Input',+ keywords: [+ 'listinput',+ 'list input',+ 'editable list',+ 'repeatable fields',+ 'field array',+ 'collection input',+ 'reorder',+ 'guest list',+ 'traveler details',+ ],+ props: [+ {+ name: 'label',+ type: 'string',+ description:+ 'Visible label that names the collection. It also provides the accessible name for the complete input.',+ required: true,+ },+ {+ name: 'value',+ type: 'T[]',+ description:+ 'Current ordered records. ListInput is controlled and never mutates this array or its records.',+ required: true,+ },+ {+ name: 'onChange',+ type: '(next: T[], change: ListInputChange<T>) => void',+ description:+ 'Called with the next array after an add, update, remove, or reorder action. The change argument identifies the action and affected record.',+ required: true,+ },+ {+ name: 'getItemKey',+ type: '(item: T) => React.Key',+ description:+ 'Returns a stable, unique key for each record. Stable identity preserves focus and announcements when records move.',+ required: true,+ },+ {+ name: 'createItem',+ type: '() => T',+ description:+ 'Creates the initial record inserted by the built-in add action. Return a new record with its stable key already assigned.',+ required: true,+ },+ {+ name: 'columns',+ type: 'ListInputColumn<T>[]',+ description:+ 'Consistent simple fields shown for every record. Use each column width with proportional() or pixel() from @astryxdesign/core/Table to tune the width spread. ListInput owns the visible primary-tone column labels while renderer labels remain semantically available to assistive technology. At 640px or narrower, fields stack, every record shows its field labels, record groups use 32px vertical separation, and row actions align beside the first field. Renderers receive isLabelHidden, complete scoped validation status, statusVariant, and updateItem.',+ required: true,+ },+ {+ name: 'itemName',+ type: 'string',+ description:+ 'Singular noun used in built-in action labels and live announcements, such as "guest" in "Add guest".',+ },+ {+ name: 'description',+ type: 'string',+ description:+ 'Supporting text displayed between the collection label and its records.',+ },+ {+ name: 'status',+ type: 'InputStatus',+ description:+ 'List-level validation status displayed for the complete collection. An error marks the collection invalid and associates its message with the input.',+ },+ {+ name: 'getItemStatus',+ type: '(item: T, index: number) => InputStatus | undefined',+ description:+ 'Returns validation status for a complete record, such as an invalid combination of otherwise valid fields.',+ },+ {+ name: 'getFieldStatus',+ type: '(item: T, columnKey: string, index: number) => InputStatus | undefined',+ description:+ 'Returns validation status for one field. The renderer receives the complete status plus statusVariant="tooltip" and should forward both to its Astryx input so the native status affordance owns styling, description, keyboard access, and tooltip behavior without changing row height.',+ },+ {+ name: 'isReorderable',+ type: 'boolean',+ description:+ 'Shows a trailing vertical grip after the Remove action. During pointer reordering, list rows stay stationary while the source row and a free-moving duplicate that follows the pointer on both axes appear at 50% opacity as a temporary drag-only state; full opacity returns immediately on drop or cancel. Vertical pointer position determines the accent insertion line and final list placement. The controlled order commits and affected rows animate with Astryx motion tokens only on release. When the grip is focused, Arrow Up or Arrow Down immediately moves the record one position. Space or Enter starts lift mode for Arrow, Home, or End previewing; Space or Enter drops and Escape cancels. Focus and live announcements are preserved.',+ default: 'false',+ },+ {+ name: 'isDisabled',+ type: 'boolean',+ description:+ 'Disables the collection and all built-in actions. The disabled state is also passed to each column renderer.',+ default: 'false',+ },+ {+ name: 'isLoading',+ type: 'boolean',+ description:+ 'Marks the collection busy and prevents changes while work is pending. The loading state is also passed to each column renderer.',+ default: 'false',+ },+ {+ name: 'maxItems',+ type: 'number',+ description:+ 'Maximum number of records that can be added. Once the value reaches this limit, the built-in add action is unavailable.',+ },+ {+ name: 'isLabelHidden',+ type: 'boolean',+ description:+ 'Visually hides the collection label while keeping it available to assistive technology.',+ default: 'false',+ },+ {+ name: 'isOptional',+ type: 'boolean',+ description:+ 'Displays an optional indicator beside the collection label. Mutually exclusive with isRequired.',+ default: 'false',+ },+ {+ name: 'isRequired',+ type: 'boolean',+ description:+ 'Displays a required indicator beside the collection label and exposes the requirement to assistive technology. Mutually exclusive with isOptional.',+ default: 'false',+ },+ ],+ usage: {+ description:+ 'ListInput edits a compact, ordered collection of records with consistent fields, built-in add and remove actions, and optional reordering. Standard Astryx controls rendered in its columns inherit the medium control size so inputs align with the Add, remove, reorder, and validation affordances; an explicit field size still takes precedence. Pointer activation measures Add before pointer-down blur or validation can change layout, then keeps it at that viewport position by adjusting available vertical scroll containers from nearest to outermost. The correction is interaction-scoped and rechecked for one animation frame without persistent scroll or resize observation. Added rows enter with tokenized translate motion; after removal, surviving rows animate into their new positions when their geometry stays stable. Motion never delays onChange, focus handoff, or the announcement, while reduced-motion preferences and unsupported browsers use an instant change. Use it for lists with fewer than seven records and up to three simple fields per record, such as guests, travelers, or tag options. Use a Table for larger collections and a card or step-based form when records need many, complex, or inconsistent fields.',+ bestPractices: [+ {+ guidance: true,+ description:+ 'Use stable record keys and consistent columns so focus, validation, and reorder announcements remain attached to the correct record.',+ },+ {+ guidance: true,+ description:+ 'Keep validation timing application-owned. Track touched fields by stable item and column keys when errors should appear after blur, while allowing submit or server errors to display immediately.',+ },+ {+ guidance: true,+ description:+ 'Place validation at the narrowest useful level: field status for one value, item status for a record-wide problem, and list status for collection-wide requirements.',+ },+ {+ guidance: true,+ description:+ 'Forward both status and statusVariant from every column renderer to the rendered Astryx input so field messages use the control’s native accessible tooltip pattern.',+ },+ {+ guidance: true,+ description:+ 'Let the floating pointer preview follow both axes while using vertical position alone for insertion. Keep list rows stationary and commit the controlled value once on release. Focused handles move immediately with Arrow Up or Arrow Down while preserving lift, move, drop, and cancel behavior.',+ },+ {+ guidance: true,+ description:+ 'Keep collection motion informational and non-blocking. Added live rows translate into place; removed rows disappear immediately while stable-size survivors close the gap. onChange, focus, and announcements run without waiting, and reduced-motion preferences remain instant.',+ },+ {+ guidance: true,+ description:+ 'Keep repeated pointer adding spatially stable by measuring Add before pointer-down blur or validation changes layout, then preserving that viewport position from the nearest vertical scroll container outward. Slight field clipping should not move Add away from the pointer; a meaningfully hidden focused field still takes priority. Keyboard activation follows the normal focus flow.',+ },+ {+ guidance: false,+ description:+ 'Use for seven or more records or more than three simple fields per record; use a Table or a dedicated editing flow instead.',+ },+ {+ guidance: false,+ description:+ 'Prevent removal solely to enforce a minimum count; allow the action and explain the resulting requirement with list-level validation.',+ },+ ],+ anatomy: [+ {+ name: 'Label and description',+ required: true,+ description:+ 'Names the complete collection and optionally explains what records to add.',+ },+ {+ name: 'First-record field labels',+ required: true,+ description:+ 'ListInput renders primary-tone column labels without separate table chrome and keeps each rendered control’s own label visually hidden but semantically associated. At wider widths, repeated labels are visually hidden; when fields stack at 640px or narrower, every record shows its field labels.',+ },+ {+ name: 'Record fields',+ required: true,+ description:+ 'Consumer-rendered inputs that receive scoped record state, complete validation status, the native tooltip status variant, and update behavior. When stacked responsively, label-to-input spacing is smallest, field spacing is larger, and record groups use 32px separation so each object remains visually distinct.',+ },+ {+ name: 'Remove action',+ required: true,+ description:+ 'Removes its record immediately, moves focus to a predictable neighboring control, and animates surviving rows into their new positions when supported. In the stacked layout, it aligns beside the first field at the top of the record.',+ },+ {+ name: 'Reorder handle',+ required: false,+ description:+ 'A trailing vertical grip positioned after Remove, with an accessible label and no hover tooltip. In the stacked layout, both actions align beside the first field at the top of the record. Pointer dragging keeps the list stationary, fades both source and duplicate preview to 50%, lets the duplicate follow freely on both axes, and uses vertical position for the insertion line before committing and animating on release. A focused grip moves one position with Arrow Up or Arrow Down; Space or Enter also enables lift mode with Arrow, Home, End, drop, and Escape controls.',+ },+ {+ name: 'Empty state',+ required: false,+ description:+ 'When no records exist, a centered compact EmptyState names the empty collection and directs users to the Add action.',+ },+ {+ name: 'Add action',+ required: true,+ description:+ 'Fills the record-fields width, uses the inherited medium control size shared by ListInput fields and actions, and immediately appends a new record created by createItem unless maxItems has been reached. On pointer activation, available vertical scroll containers offset the inserted height from nearest to outermost so the action remains under the pointer; keyboard activation keeps the normal focus behavior, and newly focused field visibility always wins. The live row uses tokenized translate entrance motion when supported, and focus moves to its first field without waiting for the animation.',+ },+ {+ name: 'Validation messages',+ required: false,+ description:+ 'Explain field-, item-, or list-level errors, warnings, and success states. Field messages use each input’s native tooltip status affordance and do not change row height. Item messages align to the record fields without extending under reorder or remove controls.',+ },+ ],+ },+ examples: [+ {+ label: 'Controlled guest list',+ code: `import {proportional} from '@astryxdesign/core/Table';++type Guest = {id: string; name: string; email: string};++const columns = [+ {+ key: 'name',+ header: 'Name',+ width: proportional(1),+ renderInput: ({item, label, isLabelHidden, status, statusVariant, isDisabled, isLoading, updateItem}) => (+ <TextInput+ label={label}+ isLabelHidden={isLabelHidden}+ value={item.name}+ onChange={name => updateItem({...item, name}, 'name')}+ status={status}+ statusVariant={statusVariant}+ isDisabled={isDisabled}+ isLoading={isLoading}+ />+ ),+ },+ {+ key: 'email',+ header: 'Email',+ width: proportional(2),+ renderInput: ({item, label, isLabelHidden, status, statusVariant, isDisabled, isLoading, updateItem}) => (+ <TextInput+ type="email"+ label={label}+ isLabelHidden={isLabelHidden}+ value={item.email}+ onChange={email => updateItem({...item, email}, 'email')}+ status={status}+ statusVariant={statusVariant}+ isDisabled={isDisabled}+ isLoading={isLoading}+ />+ ),+ },+] satisfies ListInputColumn<Guest>[];++<ListInput+ label="Guests"+ itemName="guest"+ value={guests}+ onChange={setGuests}+ getItemKey={guest => guest.id}+ createItem={() => ({id: crypto.randomUUID(), name: '', email: ''})}+ columns={columns}+ isReorderable+ maxItems={6}+ getFieldStatus={(guest, key) =>+ key === 'email' && guest.email === ''+ ? {type: 'error', message: 'Enter an email address'}+ : undefined+ }+ status={+ guests.length === 0+ ? {type: 'error', message: 'Add at least one guest'}+ : undefined+ }+/>`,+ },+ ],+};++/** @type {import('@astryxdesign/cli/authoring').ComponentTranslationDoc} */+export const docsDense = {+ description:+ 'Controlled compact-record input with typed columns, tokenized non-blocking add/remove motion, optional reorder, and field/item/list validation.',+ propDescriptions: {+ label: 'Collection label and accessible name.',+ value: 'Controlled ordered records.',+ onChange: 'Emits next records plus add/update/remove/reorder metadata.',+ getItemKey: 'Required stable unique record identity.',+ createItem: 'Creates a new keyed record for Add.',+ columns:+ 'Typed simple fields: key, header, optional proportional/pixel width, and renderInput. ListInput owns visible column labels; narrow records stack with repeated labels, stronger separation, and top-aligned row actions. Renderers forward status and statusVariant.',+ itemName: 'Singular noun for actions and announcements.',+ description: 'Supporting text below the label.',+ status: 'List-level InputStatus.',+ getItemStatus: 'Per-record InputStatus resolver.',+ getFieldStatus:+ 'Per-field resolver; complete status plus tooltip variant are forwarded to the rendered input.',+ isReorderable:+ 'Adds a trailing grip without a tooltip. During the temporary drag state, source and free-moving preview use 50% opacity while the list stays stationary; full opacity returns on drop/cancel and tokenized motion animates the committed order. Vertical position controls insertion. Focused Arrow Up/Down moves immediately, and keyboard lift/move/drop/cancel is also supported.',+ isDisabled: 'Disables collection, actions, and rendered inputs.',+ isLoading: 'Marks busy and prevents changes.',+ maxItems: 'Makes Add unavailable at the limit.',+ isLabelHidden: 'Visually hides label only.',+ isOptional: 'Shows Optional; exclusive with isRequired.',+ isRequired:+ 'Shows Required + accessible requirement; exclusive with isOptional.',+ },+ usage: {+ description:+ 'Use for compact ordered records: fewer than 7 items and up to 3 simple consistent fields. Add/remove motion does not delay onChange or focus and becomes instant under reduced motion. Use Table or a dedicated flow for larger or complex data.',+ bestPractices: [+ {+ guidance: true,+ description: 'Use stable keys and consistent columns.',+ },+ {+ guidance: true,+ description: 'Validate at field, item, or list scope as appropriate.',+ },+ {+ guidance: true,+ description:+ 'Follow pointer X and Y in the floating preview, use Y for insertion, and commit once on release; focused Arrow Up/Down moves immediately, with lift mode available for extended keyboard control.',+ },+ {+ guidance: true,+ description:+ 'Keep add/remove motion non-blocking and instant under reduced motion.',+ },+ {+ guidance: false,+ description: 'Use for long datasets or complex/inconsistent records.',+ },+ {+ guidance: false,+ description:+ 'Block removal to enforce a minimum; report a list error instead.',+ },+ ],+ },+};diff --git a/packages/lab/src/ListInput/ListInput.test.tsx b/packages/lab/src/ListInput/ListInput.test.tsxnew file mode 100644index 0000000000..791cbbb181--- /dev/null+++ b/packages/lab/src/ListInput/ListInput.test.tsx@@ -0,0 +1,1110 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file ListInput.test.tsx+ * @input Uses Vitest, Testing Library, and the controlled ListInput API+ * @output Behavioral coverage for list editing, pointer-stable adding, tokenized mutation motion, validation, focus, and free-floating stationary-list reordering+ * @position Lab tests; validates ListInput.tsx+ *+ * SYNC: When ListInput.tsx behavior changes, update these tests.+ */++import {afterEach, describe, expect, it, vi} from 'vitest';+import {useState} from 'react';+import {fireEvent, render, screen, within} from '@testing-library/react';+import {TextInput} from '@astryxdesign/core/TextInput';+import {+ ListInput,+ type ListInputColumn,+ type ListInputProps,+} from './ListInput';++type Guest = {+ id: string;+ name: string;+};++const guests: Guest[] = [+ {id: 'ada', name: 'Ada'},+ {id: 'grace', name: 'Grace'},+];++const createdGuest: Guest = {id: 'linus', name: 'Linus'};++const columns = [+ {+ key: 'name',+ header: 'Name',+ renderInput: ({+ item,+ label,+ isLabelHidden,+ status,+ statusVariant,+ isDisabled,+ isLoading,+ updateItem,+ }) => (+ <label>+ <span hidden={isLabelHidden}>{label}</span>+ <input+ aria-invalid={status?.type === 'error' || undefined}+ aria-label={label}+ data-label-hidden={String(isLabelHidden)}+ data-status-type={status?.type}+ data-status-message={status?.message}+ data-status-variant={statusVariant}+ disabled={isDisabled || isLoading}+ value={item.name}+ onChange={event =>+ updateItem({...item, name: event.currentTarget.value}, 'name')+ }+ />+ </label>+ ),+ },+] satisfies ListInputColumn<Guest>[];++const nativeStatusColumns = [+ {+ key: 'name',+ header: 'Name',+ renderInput: ({+ item,+ label,+ isLabelHidden,+ status,+ statusVariant,+ isDisabled,+ isLoading,+ updateItem,+ }) => (+ <TextInput+ label={label}+ isLabelHidden={isLabelHidden}+ value={item.name}+ status={status}+ statusVariant={statusVariant}+ isDisabled={isDisabled}+ isLoading={isLoading}+ onChange={name => updateItem({...item, name}, 'name')}+ />+ ),+ },+] satisfies ListInputColumn<Guest>[];++function renderListInput(overrides: Partial<ListInputProps<Guest>> = {}) {+ const props: ListInputProps<Guest> = {+ label: 'Guests',+ itemName: 'guest',+ value: guests,+ onChange: () => {},+ getItemKey: guest => guest.id,+ createItem: () => createdGuest,+ columns,+ ...overrides,+ };++ return render(<ListInput<Guest> {...props} />);+}++const originalAnimateDescriptor = Object.getOwnPropertyDescriptor(+ HTMLElement.prototype,+ 'animate',+);+const originalScrollIntoViewDescriptor = Object.getOwnPropertyDescriptor(+ HTMLElement.prototype,+ 'scrollIntoView',+);++function createRect(top: number): DOMRect {+ return {+ x: 0,+ y: top,+ top,+ right: 400,+ bottom: top + 40,+ left: 0,+ width: 400,+ height: 40,+ toJSON: () => {},+ };+}++function mockMutationAnimations(events: string[] = []) {+ const animate = vi.fn(function (+ this: HTMLElement,+ _keyframes: Keyframe[],+ _options?: number | KeyframeAnimationOptions,+ ) {+ events.push('animate');+ return {+ cancel: vi.fn(),+ finished: new Promise(() => {}),+ } as unknown as Animation;+ });+ Object.defineProperty(HTMLElement.prototype, 'animate', {+ configurable: true,+ value: animate,+ });+ vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockImplementation(+ function (this: HTMLElement) {+ if (this.dataset.listInputMotionKey == null) {+ return createRect(0);+ }+ const group = this.closest('[role="group"]');+ const motionElements = Array.from(+ group?.querySelectorAll<HTMLElement>('[data-list-input-motion-key]') ??+ [],+ ).filter(candidate => candidate.closest('[role="group"]') === group);+ return createRect(Math.max(0, motionElements.indexOf(this)) * 40);+ },+ );+ return animate;+}++afterEach(() => {+ vi.restoreAllMocks();+ if (originalAnimateDescriptor == null) {+ Reflect.deleteProperty(HTMLElement.prototype, 'animate');+ } else {+ Object.defineProperty(+ HTMLElement.prototype,+ 'animate',+ originalAnimateDescriptor,+ );+ }+ if (originalScrollIntoViewDescriptor == null) {+ Reflect.deleteProperty(HTMLElement.prototype, 'scrollIntoView');+ } else {+ Object.defineProperty(+ HTMLElement.prototype,+ 'scrollIntoView',+ originalScrollIntoViewDescriptor,+ );+ }+});++describe('ListInput', () => {+ it('uses list semantics and shows field labels only on the first record', () => {+ renderListInput();++ expect(screen.queryByRole('table')).not.toBeInTheDocument();+ expect(screen.queryByRole('columnheader')).not.toBeInTheDocument();+ expect(screen.getByRole('list')).toBeInTheDocument();++ const inputs = screen.getAllByRole('textbox');+ expect(inputs[0]).toHaveAttribute('data-label-hidden', 'true');+ expect(inputs[0]).toHaveAccessibleName('Name');+ expect(inputs[1]).toHaveAttribute('data-label-hidden', 'true');+ expect(inputs[1]).toHaveAccessibleName('Name, guest 2 of 2');+ expect(inputs[0]).toHaveAttribute('data-status-variant', 'tooltip');+ const primaryLabel = document.querySelector(+ '[data-list-input-column-label="primary"]',+ );+ const responsiveLabel = document.querySelector(+ '[data-list-input-column-label="responsive"]',+ );+ expect(primaryLabel).toHaveTextContent('Name');+ expect(primaryLabel).toHaveAttribute('aria-hidden', 'true');+ expect(responsiveLabel).toHaveTextContent('Name');+ expect(responsiveLabel).toHaveAttribute('aria-hidden', 'true');+ expect(primaryLabel?.closest('[data-list-input-cell]')).toContainElement(+ inputs[0],+ );+ expect(responsiveLabel?.closest('[data-list-input-cell]')).toContainElement(+ inputs[1],+ );+ });++ it('renders a compact centered EmptyState and keeps Add available', () => {+ const {container} = renderListInput({value: []});++ const emptyState = container.querySelector<HTMLElement>(+ '.astryx-empty-state',+ );+ expect(emptyState).toBeInTheDocument();+ expect(emptyState).toHaveClass('astryx-empty-state', 'compact');+ expect(emptyState).toHaveAttribute('data-variant', 'compact');+ expect(getComputedStyle(emptyState!).alignItems).toBe('center');+ expect(getComputedStyle(emptyState!).justifyContent).toBe('center');+ expect(getComputedStyle(emptyState!).textAlign).toBe('center');+ expect(+ screen.getByRole('heading', {name: 'No guests yet'}),+ ).toBeInTheDocument();+ expect(screen.getByText('Add a guest to get started.')).toBeInTheDocument();+ expect(screen.getByRole('button', {name: 'Add guest'})).toBeEnabled();+ });++ it('emits add and remove changes with the affected item and index', () => {+ const onChange = vi.fn();+ renderListInput({onChange});++ fireEvent.click(screen.getByRole('button', {name: 'Add guest'}));+ expect(onChange).toHaveBeenCalledWith([...guests, createdGuest], {+ type: 'add',+ item: createdGuest,+ index: 2,+ });++ onChange.mockClear();+ fireEvent.click(screen.getByRole('button', {name: 'Remove guest 1'}));+ expect(onChange).toHaveBeenCalledWith([guests[1]], {+ type: 'remove',+ item: guests[0],+ index: 0,+ });+ });++ it('keeps Add under the pointer in the nearest newly scrollable container', () => {+ function ScrollAnchoredList() {+ const [value, setValue] = useState(guests);+ return (+ <div data-outer-scroll="" style={{height: 240, overflowY: 'auto'}}>+ <div+ data-inner-scroll=""+ style={{+ height: 160,+ overflowY: 'auto',+ scrollBehavior: 'smooth',+ }}>+ <ListInput<Guest>+ label="Guests"+ itemName="guest"+ value={value}+ onChange={setValue}+ getItemKey={guest => guest.id}+ createItem={() => createdGuest}+ columns={columns}+ />+ </div>+ </div>+ );+ }++ const {container} = render(<ScrollAnchoredList />);+ const outerScroll = container.querySelector<HTMLElement>(+ '[data-outer-scroll]',+ )!;+ const innerScroll = container.querySelector<HTMLElement>(+ '[data-inner-scroll]',+ )!;+ Object.defineProperties(outerScroll, {+ clientHeight: {configurable: true, value: 240},+ scrollHeight: {configurable: true, value: 400},+ });+ Object.defineProperties(innerScroll, {+ clientHeight: {configurable: true, value: 160},+ scrollHeight: {+ configurable: true,+ get: () => (screen.getAllByRole('listitem').length >= 3 ? 180 : 160),+ },+ });+ let innerScrollTop = 0;+ Object.defineProperty(innerScroll, 'scrollTop', {+ configurable: true,+ get: () => innerScrollTop,+ set: (nextScrollTop: number) => {+ const maxScrollTop =+ screen.getAllByRole('listitem').length >= 3 ? 20 : 0;+ innerScrollTop = Math.max(0, Math.min(nextScrollTop, maxScrollTop));+ },+ });+ outerScroll.scrollTop = 10;+ const setScrollStyle = vi.spyOn(innerScroll.style, 'setProperty');++ const addButton = screen.getByRole('button', {name: 'Add guest'});+ const addAction = addButton.closest<HTMLElement>(+ '[data-list-input-motion-key="action:add"]',+ )!;+ let anchorFrame: FrameRequestCallback | undefined;+ vi.spyOn(window, 'requestAnimationFrame').mockImplementation(callback => {+ anchorFrame = callback;+ return 1;+ });+ vi.spyOn(addAction, 'getBoundingClientRect').mockImplementation(() =>+ createRect(+ screen.getAllByRole('listitem').length * 40 -+ innerScroll.scrollTop -+ outerScroll.scrollTop,+ ),+ );+ const initialTop = addAction.getBoundingClientRect().top;++ fireEvent.click(addButton, {detail: 1});++ expect(innerScroll.scrollTop).toBe(20);+ expect(outerScroll.scrollTop).toBe(30);+ expect(setScrollStyle).toHaveBeenCalledWith(+ 'scroll-behavior',+ 'auto',+ 'important',+ );+ expect(innerScroll.style.scrollBehavior).toBe('smooth');+ expect(addAction.getBoundingClientRect().top).toBe(initialTop);+ expect(screen.getByDisplayValue('Linus')).toHaveFocus();++ outerScroll.scrollTop = 25;+ expect(addAction.getBoundingClientRect().top).toBe(initialTop + 5);+ anchorFrame?.(0);+ expect(outerScroll.scrollTop).toBe(30);+ expect(addAction.getBoundingClientRect().top).toBe(initialTop);+ });++ it('anchors from pointer down before blur-driven validation changes layout', () => {+ function BlurGrowingList() {+ const [value, setValue] = useState([guests[0]]);+ const [isTouched, setIsTouched] = useState(false);+ const blurColumns = [+ {+ key: 'name',+ header: 'Name',+ renderInput: ({item, label, updateItem}) => (+ <input+ aria-label={label}+ value={item.name}+ onChange={event =>+ updateItem({...item, name: event.currentTarget.value}, 'name')+ }+ onBlur={() => setIsTouched(true)}+ />+ ),+ },+ ] satisfies ListInputColumn<Guest>[];+ return (+ <div data-blur-scroll="" style={{height: 100, overflowY: 'auto'}}>+ <ListInput<Guest>+ label="Guests"+ itemName="guest"+ value={value}+ onChange={setValue}+ getItemKey={guest => guest.id}+ createItem={() => createdGuest}+ columns={blurColumns}+ getItemStatus={guest =>+ isTouched && guest.id === 'ada'+ ? {type: 'error', message: 'Review this guest'}+ : undefined+ }+ />+ </div>+ );+ }++ const {container} = render(<BlurGrowingList />);+ const scrollRoot =+ container.querySelector<HTMLElement>('[data-blur-scroll]')!;+ Object.defineProperties(scrollRoot, {+ clientHeight: {configurable: true, value: 100},+ scrollHeight: {configurable: true, value: 400},+ });+ const addButton = screen.getByRole('button', {name: 'Add guest'});+ const addAction = addButton.closest<HTMLElement>(+ '[data-list-input-motion-key="action:add"]',+ )!;+ vi.spyOn(addAction, 'getBoundingClientRect').mockImplementation(() =>+ createRect(+ screen.getAllByRole('listitem').length * 40 ++ (screen.queryByText('Review this guest') == null ? 0 : 20) -+ scrollRoot.scrollTop,+ ),+ );+ const initialTop = addAction.getBoundingClientRect().top;+ const firstInput = screen.getByDisplayValue('Ada');+ firstInput.focus();++ fireEvent.pointerDown(addButton, {+ button: 0,+ isPrimary: true,+ pointerId: 21,+ });+ fireEvent.blur(firstInput);+ expect(screen.getByText('Review this guest')).toBeInTheDocument();+ expect(addAction.getBoundingClientRect().top).toBe(initialTop + 20);+ fireEvent.click(addButton, {detail: 1});++ expect(scrollRoot.scrollTop).toBe(60);+ expect(addAction.getBoundingClientRect().top).toBe(initialTop);+ expect(screen.getByDisplayValue('Linus')).toHaveFocus();+ });++ it('checks every clipping ancestor before preserving focused-field visibility', () => {+ function NestedClippingList() {+ const [value, setValue] = useState(guests);+ return (+ <div data-outer-clip="" style={{height: 80, overflowY: 'auto'}}>+ <div data-inner-clip="" style={{height: 160, overflowY: 'auto'}}>+ <ListInput<Guest>+ label="Guests"+ itemName="guest"+ value={value}+ onChange={setValue}+ getItemKey={guest => guest.id}+ createItem={() => createdGuest}+ columns={columns}+ />+ </div>+ </div>+ );+ }++ const {container} = render(<NestedClippingList />);+ const outerClip =+ container.querySelector<HTMLElement>('[data-outer-clip]')!;+ const innerClip =+ container.querySelector<HTMLElement>('[data-inner-clip]')!;+ Object.defineProperties(outerClip, {+ clientHeight: {configurable: true, value: 80},+ scrollHeight: {configurable: true, value: 400},+ });+ Object.defineProperties(innerClip, {+ clientHeight: {configurable: true, value: 160},+ scrollHeight: {configurable: true, value: 400},+ });+ vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockImplementation(+ function (this: HTMLElement) {+ return this instanceof HTMLInputElement && this.value === 'Linus'+ ? createRect(100)+ : createRect(0);+ },+ );+ const scrollIntoView = vi.fn();+ Object.defineProperty(HTMLElement.prototype, 'scrollIntoView', {+ configurable: true,+ value: scrollIntoView,+ });++ fireEvent.click(screen.getByRole('button', {name: 'Add guest'}), {+ detail: 1,+ });++ expect(scrollIntoView).toHaveBeenCalledWith({+ block: 'nearest',+ inline: 'nearest',+ });+ });++ it('animates live add and removal reflow after the controlled change', () => {+ const events: string[] = [];+ const animate = mockMutationAnimations(events);++ function ControlledList() {+ const [value, setValue] = useState(guests);+ return (+ <ListInput<Guest>+ label="Guests"+ itemName="guest"+ value={value}+ onChange={(nextValue, change) => {+ events.push(`change:${change.type}`);+ setValue(nextValue);+ }}+ getItemKey={guest => guest.id}+ createItem={() => createdGuest}+ columns={columns}+ />+ );+ }++ render(<ControlledList />);+ fireEvent.click(screen.getByRole('button', {name: 'Add guest'}));++ expect(events[0]).toBe('change:add');+ expect(screen.getByDisplayValue('Linus')).toHaveFocus();+ expect(screen.getAllByRole('listitem')).toHaveLength(3);+ const addedRow = screen+ .getByDisplayValue('Linus')+ .closest<HTMLElement>('li')!;+ const addedAnimationIndex = animate.mock.contexts.indexOf(addedRow);+ expect(addedAnimationIndex).toBeGreaterThanOrEqual(0);+ expect(animate).toHaveBeenCalledTimes(1);+ expect(animate.mock.calls[addedAnimationIndex]).toEqual([+ [{transform: 'translateY(8px)'}, {transform: 'translateY(0)'}],+ {+ duration: 230,+ easing: 'cubic-bezier(0.24, 1, 0.4, 1)',+ },+ ]);+ expect(+ Array.from(document.querySelectorAll('[aria-live="polite"]')).some(+ node => node.textContent === 'Added guest 3.',+ ),+ ).toBe(true);++ const removeEventStart = events.length;+ const animationCountBeforeRemove = animate.mock.calls.length;+ fireEvent.click(screen.getByRole('button', {name: 'Remove guest 1'}));++ expect(events[removeEventStart]).toBe('change:remove');+ expect(animate.mock.calls.length).toBeGreaterThan(+ animationCountBeforeRemove,+ );+ expect(screen.queryByDisplayValue('Ada')).not.toBeInTheDocument();+ expect(screen.getByRole('button', {name: 'Remove guest 1'})).toHaveFocus();+ expect(+ animate.mock.calls+ .slice(animationCountBeforeRemove)+ .some(([keyframes], index) => {+ const context = animate.mock.contexts[+ animationCountBeforeRemove + index+ ] as HTMLElement;+ return (+ context.querySelector('input')?.value === 'Grace' &&+ (keyframes as Keyframe[])[0]?.transform === 'translate(0px, 40px)'+ );+ }),+ ).toBe(true);+ expect(+ Array.from(document.querySelectorAll('[aria-live="polite"]')).some(+ node => node.textContent === 'Removed guest 1.',+ ),+ ).toBe(true);+ });++ it('uses instant add and remove changes when reduced motion is requested', () => {+ const animate = mockMutationAnimations();+ vi.spyOn(window, 'matchMedia').mockImplementation(+ query =>+ ({+ matches: query === '(prefers-reduced-motion: reduce)',+ media: query,+ onchange: null,+ addListener: () => {},+ removeListener: () => {},+ addEventListener: () => {},+ removeEventListener: () => {},+ dispatchEvent: () => false,+ }) as MediaQueryList,+ );++ function ReducedMotionList() {+ const [value, setValue] = useState([guests[0]]);+ return (+ <ListInput<Guest>+ label="Guests"+ itemName="guest"+ value={value}+ onChange={setValue}+ getItemKey={guest => guest.id}+ createItem={() => createdGuest}+ columns={columns}+ />+ );+ }++ render(<ReducedMotionList />);+ fireEvent.click(screen.getByRole('button', {name: 'Remove guest 1'}));++ expect(animate).not.toHaveBeenCalled();+ expect(screen.queryByDisplayValue('Ada')).not.toBeInTheDocument();+ expect(screen.getByRole('button', {name: 'Add guest'})).toHaveFocus();+ expect(+ Array.from(document.querySelectorAll('[aria-live="polite"]')).some(+ node => node.textContent === 'Removed guest 1.',+ ),+ ).toBe(true);++ fireEvent.click(screen.getByRole('button', {name: 'Add guest'}));+ expect(animate).not.toHaveBeenCalled();+ expect(screen.getByDisplayValue('Linus')).toHaveFocus();+ });++ it('renders list/item messages and presents field messages in a tooltip', () => {+ renderListInput({+ columns: nativeStatusColumns,+ status: {type: 'error', message: 'Add at least three guests'},+ getItemStatus: guest =>+ guest.id === 'ada'+ ? {type: 'error', message: 'This guest is duplicated'}+ : undefined,+ getFieldStatus: (guest, columnKey) =>+ guest.id === 'ada' && columnKey === 'name'+ ? {type: 'error', message: 'Enter a different name'}+ : undefined,+ });++ expect(screen.getByText('Add at least three guests')).toBeInTheDocument();+ expect(screen.getByText('This guest is duplicated')).toBeInTheDocument();+ const firstInput = screen.getAllByRole('textbox')[0];+ expect(firstInput).toHaveAttribute('aria-invalid', 'true');+ const tooltip = screen+ .getAllByRole('tooltip', {hidden: true})+ .find(node => node.textContent === 'Enter a different name');+ expect(tooltip).toBeDefined();+ expect(tooltip).toHaveTextContent('Enter a different name');+ expect(firstInput.getAttribute('aria-describedby')).toContain(tooltip!.id);+ const fieldCell = firstInput.closest('[data-list-input-cell]');+ expect(fieldCell?.querySelector('.astryx-field-status')).toBeNull();+ expect(+ within(fieldCell as HTMLElement).getByRole('button', {+ name: /error details/i,+ }),+ ).toBeInTheDocument();+ expect(+ firstInput.closest('[role="group"][aria-invalid="true"]'),+ ).toBeNull();++ const itemStatus = screen+ .getByText('This guest is duplicated')+ .closest('[data-list-input-item-status]');+ const itemRow = document.querySelector('[data-list-input-row="ada"]');+ expect(itemStatus).toBeDefined();+ expect(itemStatus?.parentElement).toBe(itemRow);+ expect(+ screen.getAllByRole('listitem')[0].getAttribute('aria-describedby'),+ ).toContain(itemStatus?.id);+ });++ it('fills the fields track with Add and omits reorder handles by default', () => {+ const {container} = renderListInput({columns: nativeStatusColumns});++ const addContent = container.querySelector('[data-list-input-add-content]');+ const addButton = screen.getByRole('button', {name: 'Add guest'});+ const removeButton = screen.getByRole('button', {+ name: 'Remove guest 1',+ });+ const textInput = container.querySelector('.astryx-text-input');+ expect(addContent).toContainElement(addButton);+ expect(addButton).toHaveAttribute('data-size', 'md');+ expect(removeButton).toHaveAttribute('data-size', 'md');+ expect(textInput).toHaveAttribute('data-size', 'md');+ expect(+ screen.queryByRole('button', {name: 'Reorder guest 1'}),+ ).not.toBeInTheDocument();+ });++ it('supports consumer-owned validation that appears after blur', () => {+ function BlurValidatedList() {+ const [value, setValue] = useState<Guest[]>([guests[0]]);+ const [touchedItems, setTouchedItems] = useState<ReadonlySet<string>>(+ () => new Set(),+ );+ const blurColumns = [+ {+ key: 'name',+ header: 'Name',+ renderInput: ({+ item,+ label,+ isLabelHidden,+ status,+ statusVariant,+ updateItem,+ }) => (+ <TextInput+ label={label}+ isLabelHidden={isLabelHidden}+ value={item.name}+ status={status}+ statusVariant={statusVariant}+ onChange={name => updateItem({...item, name}, 'name')}+ onBlur={() =>+ setTouchedItems(current => {+ const next = new Set(current);+ next.add(item.id);+ return next;+ })+ }+ />+ ),+ },+ ] satisfies ListInputColumn<Guest>[];++ return (+ <ListInput<Guest>+ label="Guests"+ itemName="guest"+ value={value}+ onChange={nextValue => setValue(nextValue)}+ getItemKey={guest => guest.id}+ createItem={() => ({id: 'blank', name: ''})}+ columns={blurColumns}+ getFieldStatus={(guest, columnKey) =>+ touchedItems.has(guest.id) &&+ columnKey === 'name' &&+ guest.name.trim() === ''+ ? {type: 'error', message: 'Enter a name'}+ : undefined+ }+ />+ );+ }++ render(<BlurValidatedList />);+ fireEvent.click(screen.getByRole('button', {name: 'Add guest'}));++ const addedInput = screen.getByRole('textbox', {+ name: 'Name, guest 2 of 2',+ });+ expect(addedInput).toHaveFocus();+ expect(addedInput).not.toHaveAttribute('aria-invalid');+ expect(+ screen+ .queryAllByRole('tooltip', {hidden: true})+ .some(node => node.textContent === 'Enter a name'),+ ).toBe(false);++ fireEvent.blur(addedInput);++ expect(+ screen.getByRole('textbox', {name: 'Name, guest 2 of 2'}),+ ).toHaveAttribute('aria-invalid', 'true');+ expect(+ screen+ .getAllByRole('tooltip', {hidden: true})+ .some(node => node.textContent === 'Enter a name'),+ ).toBe(true);+ });++ it('disables Add at maxItems while keeping removal available', () => {+ const onChange = vi.fn();++ renderListInput({maxItems: 2, onChange});++ expect(screen.getByRole('button', {name: 'Add guest'})).toBeDisabled();+ const remove = screen.getByRole('button', {name: 'Remove guest 1'});+ expect(remove).toBeEnabled();++ fireEvent.click(remove);+ expect(onChange).toHaveBeenCalledWith([guests[1]], {+ type: 'remove',+ item: guests[0],+ index: 0,+ });+ });++ it('moves a focused handle with arrow keys without showing a tooltip', () => {+ const onChange = vi.fn();++ function ArrowReorderList() {+ const [value, setValue] = useState(guests);+ return (+ <ListInput<Guest>+ label="Guests"+ itemName="guest"+ value={value}+ onChange={(nextValue, change) => {+ onChange(nextValue, change);+ setValue(nextValue);+ }}+ getItemKey={guest => guest.id}+ createItem={() => createdGuest}+ columns={columns}+ isReorderable+ />+ );+ }++ render(<ArrowReorderList />);+ const handle = screen.getByRole('button', {name: 'Reorder guest 1'});+ expect(handle).toHaveAttribute('data-size', 'md');+ expect(+ screen+ .queryAllByRole('tooltip', {hidden: true})+ .some(tooltip => tooltip.textContent === 'Reorder guest 1'),+ ).toBe(false);+ expect(handle).toHaveAccessibleDescription(+ 'Use Arrow Up or Arrow Down to move this item one position. Press Space or Enter to pick it up for extended keyboard reordering.',+ );++ handle.focus();+ fireEvent.keyDown(handle, {key: 'ArrowDown', altKey: true});+ expect(onChange).not.toHaveBeenCalled();++ fireEvent.keyDown(handle, {key: 'ArrowUp'});+ expect(onChange).not.toHaveBeenCalled();++ fireEvent.keyDown(handle, {key: 'ArrowDown'});+ expect(onChange).toHaveBeenCalledTimes(1);+ expect(onChange).toHaveBeenCalledWith([guests[1], guests[0]], {+ type: 'reorder',+ item: guests[0],+ fromIndex: 0,+ toIndex: 1,+ });+ expect(+ screen+ .getAllByRole('textbox')+ .map(input => (input as HTMLInputElement).value),+ ).toEqual(['Grace', 'Ada']);+ expect(handle).toHaveFocus();+ expect(handle).toHaveAccessibleName('Reorder guest 2');+ expect(+ document.querySelector('[data-list-input-reorder-source]'),+ ).not.toBeInTheDocument();+ });++ it('commits a keyboard reorder with change metadata', () => {+ const onChange = vi.fn();+ renderListInput({isReorderable: true, onChange});+ const handle = screen.getByRole('button', {name: 'Reorder guest 1'});+ expect(handle.querySelectorAll('circle')).toHaveLength(6);++ handle.focus();+ fireEvent.keyDown(handle, {key: ' ', code: 'Space'});+ let source = document.querySelector('[data-list-input-reorder-source]');+ expect(source?.closest('li')).toHaveAttribute('aria-posinset', '1');+ expect(source?.querySelector('input')).toHaveValue('Ada');++ fireEvent.keyDown(handle, {key: 'ArrowDown'});+ source = document.querySelector('[data-list-input-reorder-source]');+ expect(source?.closest('li')).toHaveAttribute('aria-posinset', '2');+ expect(source?.querySelector('input')).toHaveValue('Ada');++ fireEvent.keyDown(handle, {key: 'Enter'});++ expect(onChange).toHaveBeenCalledWith([guests[1], guests[0]], {+ type: 'reorder',+ item: guests[0],+ fromIndex: 0,+ toIndex: 1,+ });+ expect(+ document.querySelector('[data-list-input-reorder-source]'),+ ).not.toBeInTheDocument();+ });++ it('keeps pointer order stationary, follows both pointer axes, and commits once', () => {+ const onChange = vi.fn();+ const {container} = renderListInput({+ isReorderable: true,+ onChange,+ value: [...guests, createdGuest],+ });+ const rows = container.querySelectorAll<HTMLElement>(+ '[data-list-input-row]',+ );+ vi.spyOn(rows[0], 'getBoundingClientRect').mockReturnValue({+ x: 0,+ y: 0,+ top: 0,+ right: 400,+ bottom: 40,+ left: 0,+ width: 400,+ height: 40,+ toJSON: () => {},+ });+ vi.spyOn(rows[1], 'getBoundingClientRect').mockReturnValue({+ x: 0,+ y: 40,+ top: 40,+ right: 400,+ bottom: 80,+ left: 0,+ width: 400,+ height: 40,+ toJSON: () => {},+ });+ vi.spyOn(rows[2], 'getBoundingClientRect').mockReturnValue({+ x: 0,+ y: 80,+ top: 80,+ right: 400,+ bottom: 120,+ left: 0,+ width: 400,+ height: 40,+ toJSON: () => {},+ });+ const remove = screen.getByRole('button', {name: 'Remove guest 2'});+ const handle = screen.getByRole('button', {name: 'Reorder guest 2'});+ expect(within(rows[1]).getAllByRole('button')).toEqual([remove, handle]);++ fireEvent.pointerDown(handle, {+ button: 0,+ pointerId: 7,+ clientX: 300,+ clientY: 50,+ });++ const source = container.querySelector<HTMLElement>(+ '[data-list-input-reorder-source]',+ );+ const preview = document.querySelector<HTMLElement>(+ '[data-list-input-drag-preview]',+ );+ const previewLayer = preview?.closest<HTMLElement>('[popover="manual"]');+ expect(source).toBe(rows[1]);+ expect(getComputedStyle(source!).opacity).toBe('0.5');+ expect(container).toContainElement(preview);+ expect(preview).toBeInTheDocument();+ expect(previewLayer).toBeInTheDocument();+ expect(getComputedStyle(previewLayer!).opacity).toBe('0.5');+ expect(preview).toHaveAttribute('aria-hidden', 'true');+ expect(preview?.querySelector('input')).toHaveValue('Grace');+ expect(previewLayer!.style.getPropertyValue('--x-transform')).toBe(+ 'translate3d(0px, 40px, 0)',+ );+ expect(+ container.querySelector('[data-list-input-drop-target]'),+ ).not.toBeInTheDocument();++ fireEvent.pointerMove(handle, {pointerId: 7, clientX: 345, clientY: 5});+ expect(previewLayer!.style.getPropertyValue('--x-transform')).toBe(+ 'translate3d(45px, -5px, 0)',+ );+ expect([+ ...container.querySelectorAll<HTMLElement>('[data-list-input-row]'),+ ]).toEqual([...rows]);+ expect(+ screen+ .getAllByRole('textbox')+ .map(input => (input as HTMLInputElement).value),+ ).toEqual(['Ada', 'Grace', 'Linus']);+ expect(onChange).not.toHaveBeenCalled();+ expect(rows[0].closest('li')).toHaveAttribute(+ 'data-list-input-drop-target',+ 'before',+ );++ fireEvent.pointerMove(handle, {pointerId: 7, clientX: 245, clientY: 115});+ expect(previewLayer!.style.getPropertyValue('--x-transform')).toBe(+ 'translate3d(-55px, 105px, 0)',+ );+ expect(rows[0].closest('li')).not.toHaveAttribute(+ 'data-list-input-drop-target',+ );+ expect(rows[2].closest('li')).toHaveAttribute(+ 'data-list-input-drop-target',+ 'after',+ );+ expect([+ ...container.querySelectorAll<HTMLElement>('[data-list-input-row]'),+ ]).toEqual([...rows]);+ expect(onChange).not.toHaveBeenCalled();++ fireEvent.pointerUp(handle, {pointerId: 7, clientX: 245, clientY: 115});+ expect(onChange).toHaveBeenCalledTimes(1);+ expect(onChange).toHaveBeenCalledWith(+ [guests[0], createdGuest, guests[1]],+ {+ type: 'reorder',+ item: guests[1],+ fromIndex: 1,+ toIndex: 2,+ },+ );+ expect(+ document.querySelector('[data-list-input-drop-target]'),+ ).not.toBeInTheDocument();+ expect(+ document.querySelector('[data-list-input-drag-preview]'),+ ).not.toBeInTheDocument();+ });++ it('clears a sub-threshold pointer drag without reordering', () => {+ const onChange = vi.fn();+ const {container} = renderListInput({isReorderable: true, onChange});+ const handle = screen.getByRole('button', {name: 'Reorder guest 1'});++ fireEvent.pointerDown(handle, {+ button: 0,+ pointerId: 8,+ clientX: 10,+ clientY: 10,+ });+ expect(+ fireEvent.pointerMove(handle, {+ pointerId: 8,+ clientX: 14,+ clientY: 10,+ }),+ ).toBe(true);++ expect(+ container.querySelector('[data-list-input-reorder-source]'),+ ).toBeInTheDocument();+ expect(+ document.querySelector('[data-list-input-drag-preview]'),+ ).toBeInTheDocument();+ expect(+ container.querySelector('[data-list-input-drop-target]'),+ ).not.toBeInTheDocument();++ fireEvent.pointerUp(handle, {pointerId: 8, clientX: 14, clientY: 10});++ expect(onChange).not.toHaveBeenCalled();+ expect(+ container.querySelector('[data-list-input-reorder-source]'),+ ).not.toBeInTheDocument();+ expect(+ document.querySelector('[data-list-input-drag-preview]'),+ ).not.toBeInTheDocument();+ });++ it('activates a pointer drag after horizontal threshold movement', () => {+ const onChange = vi.fn();+ renderListInput({isReorderable: true, onChange});+ const rows = document.querySelectorAll<HTMLElement>(+ '[data-list-input-row]',+ );+ vi.spyOn(rows[1], 'getBoundingClientRect').mockReturnValue({+ x: 0,+ y: 40,+ top: 40,+ right: 400,+ bottom: 80,+ left: 0,+ width: 400,+ height: 40,+ toJSON: () => {},+ });++ const handle = screen.getByRole('button', {name: 'Reorder guest 1'});++ fireEvent.pointerDown(handle, {+ button: 0,+ pointerId: 9,+ clientX: 10,+ clientY: 10,+ });++ expect(+ fireEvent.pointerMove(handle, {+ pointerId: 9,+ clientX: 15,+ clientY: 10,+ }),+ ).toBe(false);++ fireEvent.pointerUp(handle, {pointerId: 9, clientX: 15, clientY: 10});++ expect(onChange).not.toHaveBeenCalled();+ expect(+ screen.getByText('guest returned to position 1.'),+ ).toBeInTheDocument();+ });++ it('cancels a keyboard reorder with Escape', () => {+ const onChange = vi.fn();+ renderListInput({isReorderable: true, onChange});+ const handle = screen.getByRole('button', {name: 'Reorder guest 1'});++ handle.focus();+ fireEvent.keyDown(handle, {key: 'Enter'});+ fireEvent.keyDown(handle, {key: 'ArrowDown'});+ fireEvent.keyDown(handle, {key: 'Escape'});++ expect(onChange).not.toHaveBeenCalled();+ expect(+ document.querySelector('[data-list-input-reorder-source]'),+ ).not.toBeInTheDocument();+ expect(+ screen+ .getAllByRole('textbox')+ .map(input => (input as HTMLInputElement).value),+ ).toEqual(['Ada', 'Grace']);+ });++ it('warns in development when getItemKey returns a duplicate key', () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ renderListInput({+ value: [guests[0], {...guests[1], id: guests[0].id}],+ });++ expect(warn.mock.calls.flat().join(' ')).toContain(+ 'ListInput: getItemKey returned duplicate key',+ );+ });+});diff --git a/packages/lab/src/ListInput/ListInput.tsx b/packages/lab/src/ListInput/ListInput.tsxnew file mode 100644index 0000000000..918ae5054d--- /dev/null+++ b/packages/lab/src/ListInput/ListInput.tsx@@ -0,0 +1,1800 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file ListInput.tsx+ * @input React, StyleX, Astryx field/list/button/icon/layer/empty-state primitives, compact size context, browser scroll geometry, programmatic theme tokens, and shared Lab reorder styles+ * @output Exports ListInput and its controlled data, column, renderer, and change types+ * @position Lab experiment (RFC facebook/astryx#4531) for editing compact repeated records+ *+ * SYNC: When modified, update these files to stay in sync:+ * - /packages/lab/src/ListInput/ListInput.doc.mjs+ * - /packages/lab/src/ListInput/ListInput.test.tsx+ * - /packages/lab/src/ListInput/index.ts+ * - /apps/storybook/stories/ListInput.stories.tsx+ */++import {+ useEffect,+ useId,+ useLayoutEffect,+ useMemo,+ useRef,+ useState,+ type Key,+ type ReactNode,+ type SVGProps,+} from 'react';+import * as stylex from '@stylexjs/stylex';+import {flushSync} from 'react-dom';+import type {BaseProps} from '@astryxdesign/core';+import {Button} from '@astryxdesign/core/Button';+import {EmptyState} from '@astryxdesign/core/EmptyState';+import {Field, type InputStatus} from '@astryxdesign/core/Field';+import {FieldStatus} from '@astryxdesign/core/FieldStatus';+import {Icon} from '@astryxdesign/core/Icon';+import {useMediaQuery} from '@astryxdesign/core/hooks';+import {IconButton} from '@astryxdesign/core/IconButton';+import {useLayer} from '@astryxdesign/core/Layer';+import {SizeProvider} from '@astryxdesign/core/SizeContext';+import type {ColumnWidth} from '@astryxdesign/core/Table';+import {useTheme} from '@astryxdesign/core/theme';+import {VisuallyHidden} from '@astryxdesign/core/VisuallyHidden';+import {+ colorVars,+ fontWeightVars,+ sizeVars,+ spacingVars,+ typeScaleVars,+} from '@astryxdesign/core/theme/tokens.stylex';+import {mergeProps, themeProps} from '@astryxdesign/core/utils';+import {reorderStyles} from '../reorderStyles';++export type ListInputChange<T> =+ | {type: 'add'; item: T; index: number}+ | {+ type: 'update';+ item: T;+ previousItem: T;+ index: number;+ columnKey?: string;+ }+ | {type: 'remove'; item: T; index: number}+ | {type: 'reorder'; item: T; fromIndex: number; toIndex: number};++export interface ListInputValueContext<T> {+ /** Current record. */+ item: T;+ /** Current visual position. */+ index: number;+ /** Accessible cell label, including the record position. */+ label: string;+ /** True because ListInput owns the visible column label. */+ isLabelHidden: boolean;+}++export interface ListInputRenderContext<T> extends ListInputValueContext<T> {+ /** Complete validation status scoped to this field. */+ status?: InputStatus;+ /** Forward to the rendered Astryx control so status uses its native tooltip. */+ statusVariant: 'tooltip';+ /** Whether the rendered control should be disabled. */+ isDisabled: boolean;+ /** Whether an asynchronous list operation is in progress. */+ isLoading: boolean;+ /** Replace this record in the controlled list. */+ updateItem: (nextItem: T, columnKey?: string) => void;+}++export interface ListInputColumn<T> {+ /** Stable column identifier, also passed to getFieldStatus. */+ key: string;+ /** Field label shown on the first record and repeated when rows stack. */+ header: string;+ /**+ * Column sizing. Use proportional() or pixel() from @astryxdesign/core/Table+ * to tune the width ratio. Defaults to a proportional column with a 140px floor.+ */+ width?: ColumnWidth;+ /** Renders the editable control for one cell. */+ renderInput: (context: ListInputRenderContext<T>) => ReactNode;+}++export interface ListInputProps<T> extends Omit<+ BaseProps<HTMLDivElement>,+ 'onChange'+> {+ /** Ref forwarded to the outer field element. */+ ref?: React.Ref<HTMLDivElement>;+ /** Visible and accessible label for the list. */+ label: string;+ /** Optional supporting text. */+ description?: string;+ /** Controlled records. */+ value: T[];+ /** Called for every record mutation with the next value and mutation detail. */+ onChange: (nextValue: T[], change: ListInputChange<T>) => void;+ /** Returns a stable key for focus preservation and reordering. */+ getItemKey: (item: T) => Key;+ /** Creates a new record when the Add action is used. */+ createItem: () => T;+ /** Column definitions and cell renderers. */+ columns: ListInputColumn<T>[];+ /** Singular name used in action labels and announcements. @default 'item' */+ itemName?: string;+ /** Validation status for the whole list. */+ status?: InputStatus;+ /** Returns a validation status displayed across one record. */+ getItemStatus?: (item: T, index: number) => InputStatus | undefined;+ /** Returns a validation status passed to one field renderer. */+ getFieldStatus?: (+ item: T,+ columnKey: string,+ index: number,+ ) => InputStatus | undefined;+ /** Enables handle-only pointer and keyboard reordering. @default false */+ isReorderable?: boolean;+ /** Disables fields and mutation controls. @default false */+ isDisabled?: boolean;+ /** Marks the list busy and prevents mutations. @default false */+ isLoading?: boolean;+ /** Maximum record count. Reaching it disables, but does not remove, Add. */+ maxItems?: number;+ /** Visually hides the list label while preserving its accessible name. */+ isLabelHidden?: boolean;+ /** Marks the list optional. */+ isOptional?: boolean;+ /** Marks the list required. */+ isRequired?: boolean;+}++interface ReorderState<T> {+ itemKey: Key;+ fromIndex: number;+ toIndex: number;+ originalValue: T[];+ mode: 'keyboard' | 'pointer';+ pointerId?: number;+ pointerStartX?: number;+ pointerStartY?: number;+ pointerOffsetX?: number;+ pointerOffsetY?: number;+ pointerClientX?: number;+ pointerClientY?: number;+ previewWidth?: number;+ hasPointerMoved?: boolean;+}++interface PendingFocus {+ itemKey?: string;+ target: 'first-field' | 'remove' | 'add';+}++interface PendingAddScrollAnchor {+ addTop: number;+ expectedKeys: string[];+ itemKey: string;+}++interface LayoutSnapshot {+ element: HTMLElement;+ rect: DOMRect;+}++interface PendingMutationMotion<T> {+ before: Map<string, LayoutSnapshot>;+ duration: number;+ easing: string;+ entryOffset: string;+ matchesValue: (nextValue: T[]) => boolean;+}++const styles = stylex.create({+ group: {+ display: 'flex',+ flexDirection: 'column',+ minWidth: 0,+ overflowAnchor: 'none',+ width: '100%',+ containerType: 'inline-size',+ containerName: 'list-input',+ },+ list: {+ display: 'flex',+ flexDirection: 'column',+ gap: {+ default: spacingVars['--spacing-2'],+ '@container list-input (max-width: 640px)': spacingVars['--spacing-8'],+ },+ listStyleType: 'none',+ margin: 0,+ padding: 0,+ },+ item: {+ display: 'flex',+ flexDirection: 'column',+ minWidth: 0,+ position: 'relative',+ },+ row: {+ display: 'grid',+ alignItems: 'end',+ columnGap: spacingVars['--spacing-1'],+ rowGap: {+ default: 0,+ '@container list-input (max-width: 640px)': spacingVars['--spacing-2'],+ },+ minWidth: 0,+ },+ rowFieldsOnly: {+ gridTemplateColumns: 'minmax(0, 1fr)',+ },+ rowWithReorder: {+ gridTemplateColumns: `minmax(0, 1fr) ${sizeVars['--size-element-md']}`,+ },+ rowWithRemove: {+ gridTemplateColumns: `minmax(0, 1fr) ${sizeVars['--size-element-md']}`,+ },+ rowWithBothControls: {+ gridTemplateColumns: `minmax(0, 1fr) ${sizeVars['--size-element-md']} ${sizeVars['--size-element-md']}`,+ },+ fields: {+ display: {+ default: 'grid',+ '@container list-input (max-width: 640px)': 'contents',+ },+ alignItems: 'end',+ gap: {+ default: spacingVars['--spacing-1'],+ '@container list-input (max-width: 640px)': spacingVars['--spacing-2'],+ },+ minWidth: 0,+ },+ fieldCell: {+ gridColumn: {+ default: 'auto',+ '@container list-input (max-width: 640px)': '1',+ },+ },+ contentOnly: {gridColumn: '1 / -1'},+ contentBeforeOneControl: {gridColumn: '1 / -2'},+ contentBeforeBothControls: {gridColumn: '1 / -3'},+ itemStatus: {+ gridRow: {+ default: '2',+ '@container list-input (max-width: 640px)': 'auto',+ },+ marginBlockStart: {+ default: spacingVars['--spacing-1'],+ '@container list-input (max-width: 640px)': 0,+ },+ minWidth: 0,+ },+ actionRow: {+ display: 'grid',+ alignItems: 'center',+ columnGap: spacingVars['--spacing-1'],+ marginBlockStart: spacingVars['--spacing-2'],+ },+ actionContent: {+ minWidth: 0,+ },+ columnLabel: {+ display: 'block',+ marginBlockEnd: {+ default: spacingVars['--spacing-0-5'],+ '@container list-input (max-width: 640px)': spacingVars['--spacing-1'],+ },+ color: colorVars['--color-text-primary'],+ fontSize: typeScaleVars['--text-label-size'],+ lineHeight: typeScaleVars['--text-label-leading'],+ fontWeight: fontWeightVars['--font-weight-medium'],+ },+ repeatedColumnLabel: {+ display: {+ default: 'none',+ '@container list-input (max-width: 640px)': 'block',+ },+ },+ cellContent: {minWidth: 0},+ controlCell: {+ display: 'flex',+ alignItems: 'center',+ alignSelf: 'end',+ justifyContent: 'center',+ minHeight: sizeVars['--size-element-md'],+ },+ removeControlCell: {+ gridColumn: {+ default: 'auto',+ '@container list-input (max-width: 640px)': '2',+ },+ gridRow: {+ default: 'auto',+ '@container list-input (max-width: 640px)': '1',+ },+ },+ reorderControlCell: {+ gridColumn: {+ default: 'auto',+ '@container list-input (max-width: 640px)': '3',+ },+ gridRow: {+ default: 'auto',+ '@container list-input (max-width: 640px)': '1',+ },+ },+ emptyItem: {+ width: '100%',+ },+ dragPreviewContainer: {+ containerType: 'inline-size',+ containerName: 'list-input',+ width: '100%',+ },+});++const dynamicStyles = stylex.create({+ fields: (gridTemplateColumns: string) => ({+ gridTemplateColumns: {+ default: gridTemplateColumns,+ '@container list-input (max-width: 640px)': 'minmax(0, 1fr)',+ },+ }),+ dragPreview: (x: number, y: number, width: number) => ({+ width,+ transform: `translate3d(${x}px, ${y}px, 0)`,+ }),+ rowTransition: (name: string) => ({viewTransitionName: name}),+});++function GripVerticalIcon(props: SVGProps<SVGSVGElement>) {+ return (+ <svg viewBox="0 0 24 24" fill="none" {...props}>+ <circle cx="9" cy="6" r="1.5" fill="currentColor" />+ <circle cx="15" cy="6" r="1.5" fill="currentColor" />+ <circle cx="9" cy="12" r="1.5" fill="currentColor" />+ <circle cx="15" cy="12" r="1.5" fill="currentColor" />+ <circle cx="9" cy="18" r="1.5" fill="currentColor" />+ <circle cx="15" cy="18" r="1.5" fill="currentColor" />+ </svg>+ );+}++function resolveColumnTrack(width?: ColumnWidth): string {+ if (width?.type === 'pixel') {+ return `${width.value}px`;+ }+ const proportion = width?.value ?? 1;+ const minWidth = width?.minWidth ?? 140;+ return `minmax(${minWidth}px, ${proportion}fr)`;+}++function moveItem<T>(value: T[], fromIndex: number, toIndex: number): T[] {+ if (fromIndex === toIndex) {+ return value.slice();+ }+ const nextValue = value.slice();+ const [item] = nextValue.splice(fromIndex, 1);+ nextValue.splice(toIndex, 0, item);+ return nextValue;+}++function joinIDs(...ids: Array<string | undefined>): string | undefined {+ const resolved = ids.filter(Boolean);+ return resolved.length > 0 ? resolved.join(' ') : undefined;+}++const focusableFieldSelector =+ '[data-list-input-cell] input, [data-list-input-cell] select, [data-list-input-cell] textarea, [data-list-input-cell] button, [data-list-input-cell] [tabindex]:not([tabindex="-1"])';++function getScrollableAncestors(element: HTMLElement): HTMLElement[] {+ const scrollRoots: HTMLElement[] = [];+ let current = element.parentElement;++ while (current != null) {+ const overflowY = window.getComputedStyle(current).overflowY;+ const isScrollable =+ (overflowY === 'auto' ||+ overflowY === 'scroll' ||+ overflowY === 'overlay') &&+ current.scrollHeight > current.clientHeight;++ if (isScrollable) {+ scrollRoots.push(current);+ }+ current = current.parentElement;+ }++ return scrollRoots;+}++function isVerticallyPerceivable(element: HTMLElement): boolean {+ const elementBounds = element.getBoundingClientRect();+ const viewportBottom =+ window.innerHeight || document.documentElement.clientHeight;+ let visibleTop = 0;+ let visibleBottom = viewportBottom;+ let current = element.parentElement;++ while (current != null) {+ const overflowY = window.getComputedStyle(current).overflowY;+ if (+ overflowY === 'auto' ||+ overflowY === 'scroll' ||+ overflowY === 'overlay' ||+ overflowY === 'hidden' ||+ overflowY === 'clip'+ ) {+ const bounds = current.getBoundingClientRect();+ const contentTop = bounds.top + current.clientTop;+ visibleTop = Math.max(visibleTop, contentTop);+ visibleBottom = Math.min(+ visibleBottom,+ contentTop + current.clientHeight,+ );+ }+ current = current.parentElement;+ }++ const elementCenter = (elementBounds.top + elementBounds.bottom) / 2;+ return elementCenter >= visibleTop && elementCenter <= visibleBottom;+}++function scrollByInstantly(+ scrollRoot: HTMLElement | null,+ delta: number,+): void {+ const styleTarget = scrollRoot ?? document.documentElement;+ const previousBehavior =+ styleTarget.style.getPropertyValue('scroll-behavior');+ const previousPriority =+ styleTarget.style.getPropertyPriority('scroll-behavior');+ styleTarget.style.setProperty('scroll-behavior', 'auto', 'important');++ try {+ if (scrollRoot != null) {+ scrollRoot.scrollTop += delta;+ } else {+ window.scrollBy(0, delta);+ }+ } finally {+ if (previousBehavior === '') {+ styleTarget.style.removeProperty('scroll-behavior');+ } else {+ styleTarget.style.setProperty(+ 'scroll-behavior',+ previousBehavior,+ previousPriority,+ );+ }+ }+}++const viewTransitionRootClassNames =+ stylex+ .props(reorderStyles.viewTransitionRoot)+ .className?.split(/\s+/)+ .filter(Boolean) ?? [];+let activeViewTransitionCount = 0;++function addViewTransitionRootStyles(): void {+ if (activeViewTransitionCount === 0) {+ document.documentElement.classList.add(...viewTransitionRootClassNames);+ }+ activeViewTransitionCount += 1;+}++function removeViewTransitionRootStyles(): void {+ activeViewTransitionCount = Math.max(0, activeViewTransitionCount - 1);+ if (activeViewTransitionCount === 0) {+ document.documentElement.classList.remove(...viewTransitionRootClassNames);+ }+}++function animateControlledUpdate(update: () => void): void {+ const prefersReducedMotion = window.matchMedia?.(+ '(prefers-reduced-motion: reduce)',+ ).matches;+ if (+ !prefersReducedMotion &&+ typeof document.startViewTransition === 'function'+ ) {+ addViewTransitionRootStyles();+ try {+ const transition = document.startViewTransition(() => flushSync(update));+ void transition.finished.then(+ removeViewTransitionRootStyles,+ removeViewTransitionRootStyles,+ );+ } catch {+ removeViewTransitionRootStyles();+ update();+ }+ return;+ }+ update();+}++function transitionName(scope: string, key: Key): string {+ return `${scope}-${String(key)}`.replace(/[^a-zA-Z0-9_-]/g, '-');+}++function parseDuration(value: string): number {+ const normalizedValue = value.trim();+ const duration = Number.parseFloat(normalizedValue);+ if (!Number.isFinite(duration)) {+ return 0;+ }+ if (normalizedValue.endsWith('ms')) {+ return duration;+ }+ return normalizedValue.endsWith('s') ? duration * 1000 : 0;+}++function captureMutationLayout(+ root: HTMLElement,+ activeAnimations: Map<HTMLElement, Animation>,+): Map<string, LayoutSnapshot> {+ const snapshots = new Map<string, LayoutSnapshot>();+ const elements: HTMLElement[] = [];+ for (const child of root.children) {+ if (!(child instanceof HTMLElement)) {+ continue;+ }+ if (child.tagName === 'OL') {+ for (const item of child.children) {+ if (+ item instanceof HTMLElement &&+ item.dataset.listInputMotionKey != null+ ) {+ elements.push(item);+ }+ }+ } else if (child.dataset.listInputMotionKey != null) {+ elements.push(child);+ }+ }+ for (const element of elements) {+ const key = element.dataset.listInputMotionKey;+ if (key == null) {+ continue;+ }+ const rect = element.getBoundingClientRect();+ activeAnimations.get(element)?.cancel();+ activeAnimations.delete(element);+ snapshots.set(key, {element, rect});+ }+ return snapshots;+}++function startMutationAnimation(+ element: HTMLElement,+ keyframes: Keyframe[],+ options: KeyframeAnimationOptions,+ activeAnimations: Map<HTMLElement, Animation>,+): void {+ try {+ const animation = element.animate(keyframes, options);+ activeAnimations.set(element, animation);+ void animation.finished.then(+ () => {+ if (activeAnimations.get(element) === animation) {+ activeAnimations.delete(element);+ }+ },+ () => {+ if (activeAnimations.get(element) === animation) {+ activeAnimations.delete(element);+ }+ },+ );+ } catch {+ // Motion is progressive enhancement; the controlled update already ran.+ }+}++/**+ * A compact editor for short collections of consistent, simple records.+ *+ * ListInput owns list semantics, add/remove controls, handle-only reordering,+ * live collection motion, focus restoration, announcements, and list/item/+ * field validation placement. Consumers keep ownership of the controlled data+ * and render each field with standard Astryx inputs.+ *+ * @example+ * ```+ * <ListInput+ * label="Guests"+ * value={guests}+ * onChange={setGuests}+ * getItemKey={guest => guest.id}+ * createItem={() => ({id: crypto.randomUUID(), name: '', email: ''})}+ * columns={columns}+ * itemName="guest"+ * isReorderable+ * />+ * ```+ */+export function ListInput<T>({+ label,+ description,+ value,+ onChange,+ getItemKey,+ createItem,+ columns,+ itemName = 'item',+ status,+ getItemStatus,+ getFieldStatus,+ isReorderable = false,+ isDisabled = false,+ isLoading = false,+ maxItems,+ isLabelHidden = false,+ isOptional = false,+ isRequired = false,+ ref,+ ...rest+}: ListInputProps<T>): ReactNode {+ const generatedID = useId();+ const groupID = `list-input-${generatedID}`;+ const labelID = `${groupID}-label`;+ const descriptionID = description ? `${groupID}-description` : undefined;+ const statusID = status?.message ? `${groupID}-status` : undefined;+ const reorderInstructionsID = `${groupID}-reorder-instructions`;+ const rowRefs = useRef(new Map<string, HTMLDivElement>());+ const groupRef = useRef<HTMLDivElement>(null);+ const addActionRef = useRef<HTMLDivElement>(null);+ const addButtonRef = useRef<HTMLButtonElement>(null);+ const addPointerAnchorTopRef = useRef<number | null>(null);+ const addAnchorFrameRef = useRef<number | null>(null);+ const pendingFocusRef = useRef<PendingFocus | null>(null);+ const pendingAddScrollAnchorRef = useRef<PendingAddScrollAnchor | null>(null);+ const pendingMutationMotionRef = useRef<PendingMutationMotion<T> | null>(+ null,+ );+ const activeMutationAnimationsRef = useRef(new Map<HTMLElement, Animation>());+ const dragPreviewRef = useRef<HTMLDivElement>(null);+ const reorderStateRef = useRef<ReorderState<T> | null>(null);+ const [reorderState, setReorderStateState] = useState<ReorderState<T> | null>(+ null,+ );+ const [announcement, setAnnouncement] = useState('');+ const {tokens: themeTokens} = useTheme();+ const mutationDuration = parseDuration(+ themeTokens['--duration-fast-max'] ?? '',+ );+ const mutationEasing = themeTokens['--ease-standard'] ?? 'linear';+ const mutationEntryOffset = themeTokens['--spacing-2'] ?? '8px';+ const prefersReducedMotion = useMediaQuery(+ '(prefers-reduced-motion: reduce)',+ );+ const {+ render: renderDragPreviewLayer,+ show: showDragPreviewLayer,+ hide: hideDragPreviewLayer,+ } = useLayer({mode: 'fixed'});++ const setReorderState = (nextState: ReorderState<T> | null) => {+ reorderStateRef.current = nextState;+ setReorderStateState(nextState);+ };++ const displayValue = useMemo(() => {+ if (reorderState == null) {+ return value;+ }+ if (reorderState.mode === 'pointer') {+ return reorderState.originalValue;+ }+ return moveItem(+ reorderState.originalValue,+ reorderState.fromIndex,+ reorderState.toIndex,+ );+ }, [reorderState, value]);+ const showReorderColumn = isReorderable;+ const showRemoveColumn = true;+ const fieldGridTemplate = useMemo(+ () => columns.map(column => resolveColumnTrack(column.width)).join(' '),+ [columns],+ );++ const pointerPlacement = useMemo(() => {+ if (+ reorderState?.mode !== 'pointer' ||+ !reorderState.hasPointerMoved ||+ reorderState.toIndex === reorderState.fromIndex+ ) {+ return null;+ }+ const remainingItems = reorderState.originalValue.filter(+ (_, index) => index !== reorderState.fromIndex,+ );+ const beforeItem = remainingItems[reorderState.toIndex];+ if (beforeItem != null) {+ return {+ position: 'before' as const,+ itemKey: String(getItemKey(beforeItem)),+ };+ }+ const afterItem = remainingItems.at(-1);+ return afterItem == null+ ? null+ : {+ position: 'after' as const,+ itemKey: String(getItemKey(afterItem)),+ };+ }, [getItemKey, reorderState]);+ const previewCloneKey =+ reorderState?.mode === 'pointer' ? String(reorderState.itemKey) : null;++ useEffect(() => {+ if (process.env.NODE_ENV === 'production') {+ return;+ }+ const itemKeys = new Set<string>();+ for (const item of value) {+ const key = String(getItemKey(item));+ if (itemKeys.has(key)) {+ console.warn(+ `ListInput: getItemKey returned duplicate key "${key}". Keys must be unique and stable.`,+ );+ break;+ }+ itemKeys.add(key);+ }+ const columnKeys = new Set<string>();+ for (const column of columns) {+ if (columnKeys.has(column.key)) {+ console.warn(+ `ListInput: columns contains duplicate key "${column.key}". Column keys must be unique.`,+ );+ break;+ }+ columnKeys.add(column.key);+ }+ }, [columns, getItemKey, value]);++ useEffect(() => {+ if ((isDisabled || isLoading) && reorderStateRef.current) {+ setReorderState(null);+ setAnnouncement('Reordering cancelled.');+ }+ }, [isDisabled, isLoading]);++ useEffect(() => {+ const activeAnimations = activeMutationAnimationsRef.current;+ return () => {+ if (addAnchorFrameRef.current != null) {+ window.cancelAnimationFrame(addAnchorFrameRef.current);+ }+ for (const animation of activeAnimations.values()) {+ animation.cancel();+ }+ activeAnimations.clear();+ };+ }, []);++ useEffect(() => {+ if (!prefersReducedMotion) {+ return;+ }+ for (const animation of activeMutationAnimationsRef.current.values()) {+ animation.cancel();+ }+ activeMutationAnimationsRef.current.clear();+ pendingMutationMotionRef.current = null;+ }, [prefersReducedMotion]);++ useLayoutEffect(() => {+ const pendingAnchor = pendingAddScrollAnchorRef.current;+ if (pendingAnchor == null) {+ return;+ }+ const matchesValue =+ value.length === pendingAnchor.expectedKeys.length &&+ value.every(+ (item, index) =>+ String(getItemKey(item)) === pendingAnchor.expectedKeys[index],+ );+ if (!matchesValue) {+ pendingAddScrollAnchorRef.current = null;+ return;+ }+ pendingAddScrollAnchorRef.current = null;++ const addAction = addActionRef.current;+ if (addAction == null) {+ return;+ }+ const pendingFocus = pendingFocusRef.current;+ const addedRow = rowRefs.current.get(pendingAnchor.itemKey);+ const focusTarget =+ pendingFocus?.target === 'first-field' &&+ pendingFocus.itemKey === pendingAnchor.itemKey+ ? (addedRow?.querySelector<HTMLElement>(focusableFieldSelector) ?? null)+ : null;+ if (focusTarget != null) {+ focusTarget.focus({preventScroll: true});+ pendingFocusRef.current = null;+ }++ // Resolve after insertion: the new record may make a nearer overflow+ // container scrollable for the first time. Cascade any clamped remainder+ // outward so a partially growing inner container does not displace Add.+ const preserveAddPosition = () => {+ const scrollRoots = getScrollableAncestors(addAction);+ for (const scrollRoot of scrollRoots) {+ const scrollDelta =+ addAction.getBoundingClientRect().top - pendingAnchor.addTop;+ if (Math.abs(scrollDelta) < 0.5) {+ break;+ }+ scrollByInstantly(scrollRoot, scrollDelta);+ }+ const viewportDelta =+ addAction.getBoundingClientRect().top - pendingAnchor.addTop;+ if (Math.abs(viewportDelta) >= 0.5) {+ scrollByInstantly(null, viewportDelta);+ }+ };+ preserveAddPosition();++ // Slight clipping should not move Add away from an active pointer. Only a+ // meaningfully hidden target takes priority over pointer anchoring.+ if (focusTarget != null && !isVerticallyPerceivable(focusTarget)) {+ focusTarget.scrollIntoView?.({block: 'nearest', inline: 'nearest'});+ } else {+ // Recheck once after the browser's native anchoring/focus phase. This is+ // interaction-scoped work, not a persistent scroll or resize observer.+ if (addAnchorFrameRef.current != null) {+ window.cancelAnimationFrame(addAnchorFrameRef.current);+ }+ addAnchorFrameRef.current = window.requestAnimationFrame(() => {+ addAnchorFrameRef.current = null;+ if (addAction.isConnected) {+ preserveAddPosition();+ }+ });+ }+ }, [getItemKey, value]);++ useLayoutEffect(() => {+ const pendingMotion = pendingMutationMotionRef.current;+ if (pendingMotion == null) {+ return;+ }+ if (!pendingMotion.matchesValue(value)) {+ pendingMutationMotionRef.current = null;+ return;+ }+ pendingMutationMotionRef.current = null;+ const root = groupRef.current;+ if (root == null) {+ return;+ }++ const activeAnimations = activeMutationAnimationsRef.current;+ const after = captureMutationLayout(root, activeAnimations);+ const options: KeyframeAnimationOptions = {+ duration: pendingMotion.duration,+ easing: pendingMotion.easing,+ };+ const hasSizeChange = Array.from(after).some(([key, nextSnapshot]) => {+ const previousSnapshot = pendingMotion.before.get(key);+ return (+ previousSnapshot != null &&+ (Math.abs(previousSnapshot.rect.width - nextSnapshot.rect.width) >=+ 0.5 ||+ Math.abs(previousSnapshot.rect.height - nextSnapshot.rect.height) >=+ 0.5)+ );+ });+ const hasEnteringParticipant = Array.from(after.keys()).some(+ key => !pendingMotion.before.has(key),+ );+ for (const [key, nextSnapshot] of after) {+ const previousSnapshot = pendingMotion.before.get(key);+ if (previousSnapshot == null) {+ startMutationAnimation(+ nextSnapshot.element,+ [+ {transform: `translateY(${pendingMotion.entryOffset})`},+ {transform: 'translateY(0)'},+ ],+ options,+ activeAnimations,+ );+ continue;+ }+ // Appended rows already carry the orientation cue; moving the Add action+ // from beneath them would temporarily overlap the new live controls.+ if (hasSizeChange || hasEnteringParticipant) {+ continue;+ }++ const deltaX = previousSnapshot.rect.left - nextSnapshot.rect.left;+ const deltaY = previousSnapshot.rect.top - nextSnapshot.rect.top;+ if (Math.abs(deltaX) < 0.5 && Math.abs(deltaY) < 0.5) {+ continue;+ }+ startMutationAnimation(+ nextSnapshot.element,+ [+ {transform: `translate(${deltaX}px, ${deltaY}px)`},+ {transform: 'translate(0, 0)'},+ ],+ options,+ activeAnimations,+ );+ }+ }, [value]);++ useLayoutEffect(() => {+ const pendingFocus = pendingFocusRef.current;+ if (pendingFocus == null) {+ return;+ }+ let target: HTMLElement | null = null;+ if (pendingFocus.target === 'add') {+ target = addButtonRef.current;+ } else if (pendingFocus.itemKey != null) {+ const row = rowRefs.current.get(pendingFocus.itemKey);+ const selector =+ pendingFocus.target === 'remove'+ ? '[data-list-input-remove]'+ : focusableFieldSelector;+ target = row?.querySelector<HTMLElement>(selector) ?? null;+ }+ if (target != null) {+ target.focus();+ pendingFocusRef.current = null;+ }+ }, [value]);++ useLayoutEffect(() => {+ const previewHost = dragPreviewRef.current;+ if (previewHost == null || previewCloneKey == null) {+ return;+ }+ const sourceRow = rowRefs.current.get(previewCloneKey);+ if (sourceRow == null) {+ return;+ }+ const clone = sourceRow.cloneNode(true) as HTMLElement;+ previewHost.style.direction = getComputedStyle(sourceRow).direction;+ clone.style.opacity = '1';+ clone.removeAttribute('data-list-input-reorder-source');+ clone.removeAttribute('data-list-input-drop-target');+ clone.removeAttribute('data-list-input-reorder');+ clone.removeAttribute('data-list-input-remove');+ clone.removeAttribute('data-list-input-row');+ clone.setAttribute('aria-hidden', 'true');+ const clonedElements = [clone, ...clone.querySelectorAll<HTMLElement>('*')];+ for (const element of clonedElements) {+ element.removeAttribute('id');+ element.removeAttribute('aria-describedby');+ element.removeAttribute('aria-labelledby');+ element.removeAttribute('name');+ element.removeAttribute('data-list-input-reorder-source');+ element.removeAttribute('data-list-input-drop-target');+ element.removeAttribute('data-list-input-reorder');+ element.removeAttribute('data-list-input-remove');+ element.setAttribute('tabindex', '-1');+ element.style.viewTransitionName = 'none';+ }+ previewHost.replaceChildren(clone);+ showDragPreviewLayer();+ return () => {+ hideDragPreviewLayer();+ previewHost.replaceChildren();+ previewHost.style.removeProperty('direction');+ };+ }, [hideDragPreviewLayer, previewCloneKey, showDragPreviewLayer]);++ const mutationsDisabled = isDisabled || isLoading;+ const hasReachedMax = maxItems != null && value.length >= maxItems;++ const cancelMutationAnimations = () => {+ for (const animation of activeMutationAnimationsRef.current.values()) {+ animation.cancel();+ }+ activeMutationAnimationsRef.current.clear();+ };++ const settleReorderBeforeMutation = () => {+ if (reorderState == null && reorderStateRef.current == null) {+ return;+ }+ flushSync(() => setReorderState(null));+ };++ const prepareMutationMotion = (nextValue: T[]) => {+ const root = groupRef.current;+ if (+ root == null ||+ prefersReducedMotion ||+ mutationDuration <= 0 ||+ typeof root.animate !== 'function'+ ) {+ pendingMutationMotionRef.current = null;+ return;+ }++ const expectedKeys = nextValue.map(item => String(getItemKey(item)));+ const pendingMotion: PendingMutationMotion<T> = {+ before: captureMutationLayout(root, activeMutationAnimationsRef.current),+ duration: mutationDuration,+ easing: mutationEasing,+ entryOffset: mutationEntryOffset,+ matchesValue: candidate =>+ candidate.length === expectedKeys.length &&+ candidate.every(+ (item, index) => String(getItemKey(item)) === expectedKeys[index],+ ),+ };+ pendingMutationMotionRef.current = pendingMotion;+ window.setTimeout(() => {+ // Delayed controlled updates cannot safely reuse viewport measurements+ // from the originating interaction. Synchronous updates consume the+ // snapshot in the layout effect before the next task.+ if (pendingMutationMotionRef.current === pendingMotion) {+ pendingMutationMotionRef.current = null;+ }+ }, 0);+ };++ const prepareAddScrollAnchor = (+ nextValue: T[],+ itemKey: string,+ pointerDownTop?: number,+ ) => {+ const addAction = addActionRef.current;+ if (addAction == null) {+ pendingAddScrollAnchorRef.current = null;+ return;+ }++ const pendingAnchor: PendingAddScrollAnchor = {+ addTop: pointerDownTop ?? addAction.getBoundingClientRect().top,+ expectedKeys: nextValue.map(item => String(getItemKey(item))),+ itemKey,+ };+ pendingAddScrollAnchorRef.current = pendingAnchor;+ window.setTimeout(() => {+ // Controlled updates that arrive in a later task cannot safely reuse a+ // pointer position captured during the originating click.+ if (pendingAddScrollAnchorRef.current === pendingAnchor) {+ pendingAddScrollAnchorRef.current = null;+ }+ }, 0);+ };++ const handleAddPointerDown = (+ event: React.PointerEvent<HTMLButtonElement>,+ ) => {+ if (+ event.button !== 0 ||+ !event.isPrimary ||+ mutationsDisabled ||+ hasReachedMax+ ) {+ addPointerAnchorTopRef.current = null;+ return;+ }+ addPointerAnchorTopRef.current =+ addActionRef.current?.getBoundingClientRect().top ?? null;+ };++ const handleAdd = (event: React.MouseEvent<HTMLButtonElement>) => {+ if (mutationsDisabled || hasReachedMax) {+ return;+ }+ settleReorderBeforeMutation();+ const item = createItem();+ const nextValue = [...value, item];+ const itemKey = String(getItemKey(item));+ pendingFocusRef.current = {+ itemKey,+ target: 'first-field',+ };+ if (event.detail > 0) {+ prepareAddScrollAnchor(+ nextValue,+ itemKey,+ addPointerAnchorTopRef.current ?? undefined,+ );+ } else {+ pendingAddScrollAnchorRef.current = null;+ }+ addPointerAnchorTopRef.current = null;+ prepareMutationMotion(nextValue);+ onChange(nextValue, {type: 'add', item, index: value.length});+ setAnnouncement(`Added ${itemName} ${value.length + 1}.`);+ };++ const handleUpdate = (+ item: T,+ index: number,+ nextItem: T,+ columnKey?: string,+ ) => {+ if (mutationsDisabled) {+ return;+ }+ const nextValue = value.slice();+ nextValue[index] = nextItem;+ onChange(nextValue, {+ type: 'update',+ item: nextItem,+ previousItem: item,+ index,+ columnKey,+ });+ };++ const handleRemove = (item: T) => {+ if (mutationsDisabled) {+ return;+ }+ settleReorderBeforeMutation();+ const itemKey = String(getItemKey(item));+ const index = value.findIndex(+ candidate => String(getItemKey(candidate)) === itemKey,+ );+ if (index < 0) {+ return;+ }+ const removedItem = value[index];+ const nextValue = value.filter((_, itemIndex) => itemIndex !== index);+ const nextFocusItem = nextValue[Math.min(index, nextValue.length - 1)];+ pendingFocusRef.current =+ nextFocusItem == null+ ? {target: 'add'}+ : {itemKey: String(getItemKey(nextFocusItem)), target: 'remove'};+ prepareMutationMotion(nextValue);+ onChange(nextValue, {type: 'remove', item: removedItem, index});+ setAnnouncement(`Removed ${itemName} ${index + 1}.`);+ };++ const startReorder = (+ item: T,+ index: number,+ mode: 'keyboard' | 'pointer',+ pointerId?: number,+ pointerGeometry?: Pick<+ ReorderState<T>,+ | 'pointerStartX'+ | 'pointerStartY'+ | 'pointerOffsetX'+ | 'pointerOffsetY'+ | 'pointerClientX'+ | 'pointerClientY'+ | 'previewWidth'+ >,+ ) => {+ if (mutationsDisabled || !isReorderable) {+ return;+ }+ cancelMutationAnimations();+ setReorderState({+ itemKey: getItemKey(item),+ fromIndex: index,+ toIndex: index,+ originalValue: value.slice(),+ mode,+ pointerId,+ ...pointerGeometry,+ hasPointerMoved: false,+ });+ setAnnouncement(+ `${itemName} ${index + 1} grabbed. Use arrow keys to move, Space or Enter to drop, and Escape to cancel.`,+ );+ };++ const previewReorder = (toIndex: number) => {+ const currentState = reorderStateRef.current;+ if (currentState == null) {+ return;+ }+ const boundedIndex = Math.max(+ 0,+ Math.min(toIndex, currentState.originalValue.length - 1),+ );+ if (boundedIndex === currentState.toIndex) {+ return;+ }+ setReorderState({...currentState, toIndex: boundedIndex});+ setAnnouncement(+ `${itemName} moved to position ${boundedIndex + 1} of ${currentState.originalValue.length}.`,+ );+ };++ const cancelReorder = () => {+ if (reorderStateRef.current == null) {+ return;+ }+ setReorderState(null);+ setAnnouncement('Reordering cancelled.');+ };++ const commitReorder = () => {+ const currentState = reorderStateRef.current;+ if (currentState == null) {+ return;+ }+ if (currentState.mode === 'pointer' && !currentState.hasPointerMoved) {+ setReorderState(null);+ return;+ }++ const nextValue = moveItem(+ currentState.originalValue,+ currentState.fromIndex,+ currentState.toIndex,+ );+ const item = currentState.originalValue[currentState.fromIndex];+ const hasChanged = currentState.fromIndex !== currentState.toIndex;+ if (currentState.mode === 'pointer') {+ flushSync(() => setReorderState(null));+ } else {+ setReorderState(null);+ }+ if (!hasChanged) {+ setAnnouncement(+ `${itemName} returned to position ${currentState.fromIndex + 1}.`,+ );+ return;+ }+ const commit = () =>+ onChange(nextValue, {+ type: 'reorder',+ item,+ fromIndex: currentState.fromIndex,+ toIndex: currentState.toIndex,+ });+ if (currentState.mode === 'pointer') {+ animateControlledUpdate(commit);+ } else {+ commit();+ }+ setAnnouncement(+ `${itemName} dropped at position ${currentState.toIndex + 1} of ${currentState.originalValue.length}.`,+ );+ };+ const moveWithArrowKey = (item: T, fromIndex: number, offset: -1 | 1) => {+ cancelMutationAnimations();+ const toIndex = Math.max(0, Math.min(fromIndex + offset, value.length - 1));+ if (toIndex === fromIndex) {+ setAnnouncement(+ `This ${itemName} is already ${offset < 0 ? 'first' : 'last'}.`,+ );+ return;+ }+ const nextValue = moveItem(value, fromIndex, toIndex);+ animateControlledUpdate(() =>+ onChange(nextValue, {+ type: 'reorder',+ item,+ fromIndex,+ toIndex,+ }),+ );+ setAnnouncement(+ `${itemName} moved to position ${toIndex + 1} of ${value.length}.`,+ );+ };++ const handleReorderKeyDown = (+ event: React.KeyboardEvent<HTMLButtonElement>,+ item: T,+ index: number,+ ) => {+ if (event.altKey || event.ctrlKey || event.metaKey) {+ return;+ }+ const activeState = reorderStateRef.current;+ const isActivationKey = event.key === ' ' || event.key === 'Enter';+ if (activeState == null) {+ if (event.key === 'ArrowUp') {+ event.preventDefault();+ moveWithArrowKey(item, index, -1);+ return;+ }+ if (event.key === 'ArrowDown') {+ event.preventDefault();+ moveWithArrowKey(item, index, 1);+ return;+ }+ if (isActivationKey) {+ event.preventDefault();+ startReorder(item, index, 'keyboard');+ }+ return;+ }+ if (String(activeState.itemKey) !== String(getItemKey(item))) {+ return;+ }+ if (isActivationKey) {+ event.preventDefault();+ commitReorder();+ } else if (event.key === 'Escape') {+ event.preventDefault();+ cancelReorder();+ } else if (event.key === 'ArrowUp') {+ event.preventDefault();+ previewReorder(activeState.toIndex - 1);+ } else if (event.key === 'ArrowDown') {+ event.preventDefault();+ previewReorder(activeState.toIndex + 1);+ } else if (event.key === 'Home') {+ event.preventDefault();+ previewReorder(0);+ } else if (event.key === 'End') {+ event.preventDefault();+ previewReorder(activeState.originalValue.length - 1);+ }+ };++ const handlePointerMove = (event: React.PointerEvent<HTMLButtonElement>) => {+ const activeState = reorderStateRef.current;+ if (+ activeState == null ||+ activeState.mode !== 'pointer' ||+ activeState.pointerId !== event.pointerId+ ) {+ return;+ }+ const horizontalDistance =+ event.clientX - (activeState.pointerStartX ?? event.clientX);+ const verticalDistance =+ event.clientY - (activeState.pointerStartY ?? event.clientY);+ const hasCrossedThreshold =+ activeState.hasPointerMoved ||+ Math.hypot(horizontalDistance, verticalDistance) >= 5;+ const remainingItems = activeState.originalValue.filter(+ (_, index) => index !== activeState.fromIndex,+ );+ let targetIndex = activeState.fromIndex;+ if (hasCrossedThreshold) {+ event.preventDefault();+ targetIndex = remainingItems.length;+ for (let index = 0; index < remainingItems.length; index++) {+ const row = rowRefs.current.get(+ String(getItemKey(remainingItems[index])),+ );+ if (row == null) {+ continue;+ }+ const bounds = row.getBoundingClientRect();+ if (event.clientY < bounds.top + bounds.height / 2) {+ targetIndex = index;+ break;+ }+ }+ }+ const nextState = {+ ...activeState,+ pointerClientX: event.clientX,+ pointerClientY: event.clientY,+ hasPointerMoved: hasCrossedThreshold,+ toIndex: targetIndex,+ };+ if (+ activeState.pointerClientX === nextState.pointerClientX &&+ activeState.pointerClientY === nextState.pointerClientY &&+ activeState.hasPointerMoved === nextState.hasPointerMoved &&+ activeState.toIndex === nextState.toIndex+ ) {+ return;+ }+ setReorderState(nextState);+ if (hasCrossedThreshold && activeState.toIndex !== targetIndex) {+ setAnnouncement(+ `${itemName} moved to position ${targetIndex + 1} of ${activeState.originalValue.length}.`,+ );+ }+ };++ const rowLayoutStyle = showReorderColumn+ ? showRemoveColumn+ ? styles.rowWithBothControls+ : styles.rowWithReorder+ : showRemoveColumn+ ? styles.rowWithRemove+ : styles.rowFieldsOnly;+ const contentGridStyle = showReorderColumn+ ? styles.contentBeforeBothControls+ : showRemoveColumn+ ? styles.contentBeforeOneControl+ : styles.contentOnly;+ const dragPreviewPosition =+ reorderState?.mode === 'pointer' &&+ reorderState.pointerClientX != null &&+ reorderState.pointerClientY != null &&+ reorderState.pointerOffsetX != null &&+ reorderState.pointerOffsetY != null &&+ reorderState.previewWidth != null+ ? {+ x: reorderState.pointerClientX - reorderState.pointerOffsetX,+ y: reorderState.pointerClientY - reorderState.pointerOffsetY,+ width: reorderState.previewWidth,+ }+ : null;++ return (+ <SizeProvider value="md">+ <Field+ ref={ref}+ label={label}+ description={description}+ inputID={groupID}+ labelID={labelID}+ descriptionID={descriptionID}+ isGroupLabel+ isLabelHidden={isLabelHidden}+ isOptional={isOptional}+ isRequired={isRequired}+ isDisabled={isDisabled}+ status={status == null ? undefined : {...status, messageID: statusID}}+ statusVariant="detached"+ {...rest}>+ <div+ ref={groupRef}+ id={groupID}+ role="group"+ aria-labelledby={labelID}+ aria-describedby={joinIDs(descriptionID, statusID)}+ aria-disabled={isDisabled || undefined}+ aria-required={isRequired || undefined}+ aria-busy={isLoading || undefined}+ {...mergeProps(+ themeProps('list-input', {+ state: isLoading+ ? 'loading'+ : isDisabled+ ? 'disabled'+ : undefined,+ reorderable: isReorderable ? 'true' : undefined,+ }),+ stylex.props(styles.group),+ )}>+ <ol+ role="list"+ aria-labelledby={labelID}+ aria-describedby={joinIDs(descriptionID, statusID)}+ {...stylex.props(styles.list)}>+ {displayValue.length === 0 ? (+ <li+ data-list-input-motion-key="state:empty"+ {...stylex.props(styles.emptyItem)}>+ <EmptyState+ title={`No ${itemName}s yet`}+ description={`Add a ${itemName} to get started.`}+ isCompact+ />+ </li>+ ) : (+ displayValue.map((item, index) => {+ const itemKey = getItemKey(item);+ const itemKeyString = String(itemKey);+ const isActiveReorder =+ reorderState != null &&+ String(reorderState.itemKey) === itemKeyString;+ const dropPosition =+ pointerPlacement?.itemKey === itemKeyString+ ? pointerPlacement.position+ : null;+ const isPointerReorderSource =+ isActiveReorder && reorderState?.mode === 'pointer';+ const itemStatus = getItemStatus?.(item, index);+ const itemStatusID = itemStatus?.message+ ? `${groupID}-item-${index}-status`+ : undefined;+ return (+ <li+ key={itemKey}+ data-list-input-motion-key={`item:${itemKeyString}`}+ data-list-input-drop-target={dropPosition ?? undefined}+ aria-describedby={itemStatusID}+ aria-invalid={itemStatus?.type === 'error' || undefined}+ aria-posinset={index + 1}+ aria-setsize={displayValue.length}+ {...stylex.props(+ styles.item,+ dropPosition === 'before' && reorderStyles.dropBefore,+ dropPosition === 'after' && reorderStyles.dropAfter,+ )}>+ <div+ data-list-input-reorder-source={+ isActiveReorder || undefined+ }+ ref={node => {+ if (node == null) {+ rowRefs.current.delete(itemKeyString);+ } else {+ rowRefs.current.set(itemKeyString, node);+ }+ }}+ data-list-input-row={itemKeyString}+ {...stylex.props(+ styles.row,+ rowLayoutStyle,+ dynamicStyles.rowTransition(+ transitionName(groupID, itemKey),+ ),+ isPointerReorderSource && reorderStyles.source,+ )}>+ <div+ {...stylex.props(+ styles.fields,+ dynamicStyles.fields(fieldGridTemplate),+ )}>+ {columns.map((column, columnIndex) => {+ const fieldStatus = getFieldStatus?.(+ item,+ column.key,+ index,+ );+ const isRepeatedLabel = index !== 0;+ const cellLabel = isRepeatedLabel+ ? `${column.header}, ${itemName} ${index + 1} of ${displayValue.length}`+ : column.header;+ const valueContext: ListInputValueContext<T> = {+ item,+ index,+ label: cellLabel,+ isLabelHidden: true,+ };+ const content = column.renderInput({+ ...valueContext,+ status: fieldStatus,+ statusVariant: 'tooltip',+ isDisabled: isDisabled || isLoading,+ isLoading,+ updateItem: (nextItem, changeColumnKey) =>+ handleUpdate(+ item,+ index,+ nextItem,+ changeColumnKey ?? column.key,+ ),+ });+ return (+ <div+ key={column.key}+ data-list-input-cell={String(columnIndex)}+ {...stylex.props(+ styles.cellContent,+ styles.fieldCell,+ )}>+ <span+ aria-hidden="true"+ data-list-input-column-label={+ isRepeatedLabel ? 'responsive' : 'primary'+ }+ {...stylex.props(+ styles.columnLabel,+ isRepeatedLabel && styles.repeatedColumnLabel,+ )}>+ {column.header}+ </span>+ <div {...stylex.props(styles.cellContent)}>+ {content}+ </div>+ </div>+ );+ })}+ </div>+ {showRemoveColumn ? (+ <div+ {...stylex.props(+ styles.controlCell,+ styles.removeControlCell,+ )}>+ <IconButton+ label={`Remove ${itemName} ${index + 1}`}+ tooltip={`Remove ${itemName} ${index + 1}`}+ icon={<Icon icon="close" size="sm" />}+ variant="ghost"+ size="md"+ isDisabled={isDisabled || isLoading}+ data-list-input-remove=""+ onClick={() => handleRemove(item)}+ />+ </div>+ ) : null}+ {showReorderColumn ? (+ <div+ {...stylex.props(+ styles.controlCell,+ styles.reorderControlCell,+ )}>+ <IconButton+ label={`Reorder ${itemName} ${index + 1}`}+ icon={<Icon icon={GripVerticalIcon} size="sm" />}+ variant="ghost"+ size="md"+ isDisabled={isDisabled || isLoading}+ aria-describedby={reorderInstructionsID}+ aria-pressed={isActiveReorder || undefined}+ data-list-input-reorder=""+ xstyle={[+ reorderStyles.handle,+ isActiveReorder && reorderStyles.handleActive,+ ]}+ onKeyDown={event =>+ handleReorderKeyDown(event, item, index)+ }+ onBlur={() => {+ const activeState = reorderStateRef.current;+ if (+ activeState?.mode === 'keyboard' &&+ String(activeState.itemKey) === itemKeyString+ ) {+ cancelReorder();+ }+ }}+ onPointerDown={event => {+ if (+ event.button !== 0 ||+ isDisabled ||+ isLoading+ ) {+ return;+ }+ const sourceRow =+ rowRefs.current.get(itemKeyString);+ if (sourceRow == null) {+ return;+ }+ const bounds = sourceRow.getBoundingClientRect();+ event.currentTarget.setPointerCapture?.(+ event.pointerId,+ );+ startReorder(+ item,+ index,+ 'pointer',+ event.pointerId,+ {+ pointerStartX: event.clientX,+ pointerStartY: event.clientY,+ pointerOffsetX: event.clientX - bounds.left,+ pointerOffsetY: event.clientY - bounds.top,+ pointerClientX: event.clientX,+ pointerClientY: event.clientY,+ previewWidth: bounds.width,+ },+ );+ }}+ onPointerMove={handlePointerMove}+ onPointerUp={event => {+ const activeState = reorderStateRef.current;+ if (+ activeState?.mode === 'pointer' &&+ activeState.pointerId === event.pointerId+ ) {+ commitReorder();+ if (+ event.currentTarget.hasPointerCapture?.(+ event.pointerId,+ )+ ) {+ event.currentTarget.releasePointerCapture?.(+ event.pointerId,+ );+ }+ }+ }}+ onPointerCancel={event => {+ const activeState = reorderStateRef.current;+ if (+ activeState?.mode === 'pointer' &&+ activeState.pointerId === event.pointerId+ ) {+ cancelReorder();+ if (+ event.currentTarget.hasPointerCapture?.(+ event.pointerId,+ )+ ) {+ event.currentTarget.releasePointerCapture?.(+ event.pointerId,+ );+ }+ }+ }}+ onLostPointerCapture={event => {+ const activeState = reorderStateRef.current;+ if (+ activeState?.mode === 'pointer' &&+ activeState.pointerId === event.pointerId+ ) {+ cancelReorder();+ }+ }}+ />+ </div>+ ) : null}+ {itemStatus?.message ? (+ <FieldStatus+ id={itemStatusID}+ type={itemStatus.type}+ message={itemStatus.message}+ variant="detached"+ data-list-input-item-status=""+ xstyle={[styles.itemStatus, contentGridStyle]}+ />+ ) : null}+ </div>+ </li>+ );+ })+ )}+ </ol>+ <div+ ref={addActionRef}+ data-list-input-motion-key="action:add"+ {...stylex.props(styles.actionRow, rowLayoutStyle)}>+ <div+ data-list-input-add-content=""+ {...stylex.props(styles.actionContent, contentGridStyle)}>+ <Button+ ref={addButtonRef}+ label={`Add ${itemName}`}+ variant="secondary"+ size="md"+ width="100%"+ isDisabled={isDisabled || hasReachedMax}+ isLoading={isLoading}+ onPointerDown={handleAddPointerDown}+ onPointerCancel={() => {+ addPointerAnchorTopRef.current = null;+ }}+ onClick={handleAdd}+ />+ </div>+ </div>+ {showReorderColumn ? (+ <VisuallyHidden as="div" id={reorderInstructionsID}>+ Use Arrow Up or Arrow Down to move this item one position. Press+ Space or Enter to pick it up for extended keyboard reordering.+ </VisuallyHidden>+ ) : null}+ <VisuallyHidden as="div" aria-live="polite" aria-atomic="true">+ {announcement}+ </VisuallyHidden>+ </div>+ </Field>+ {dragPreviewPosition != null+ ? renderDragPreviewLayer(+ <div+ ref={dragPreviewRef}+ aria-hidden="true"+ data-list-input-drag-preview=""+ {...stylex.props(styles.dragPreviewContainer)}+ />,+ {+ x: 0,+ y: 0,+ xstyle: [+ reorderStyles.preview,+ dynamicStyles.dragPreview(+ dragPreviewPosition.x,+ dragPreviewPosition.y,+ dragPreviewPosition.width,+ ),+ ],+ },+ )+ : null}+ </SizeProvider>+ );+}++ListInput.displayName = 'ListInput';diff --git a/packages/lab/src/ListInput/index.ts b/packages/lab/src/ListInput/index.tsnew file mode 100644index 0000000000..c4fdbbab6e--- /dev/null+++ b/packages/lab/src/ListInput/index.ts@@ -0,0 +1,21 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file index.ts+ * @input Imports ListInput and public types from ListInput.tsx+ * @output Public ListInput entry point for @astryxdesign/lab+ * @position Component barrel; re-exported by /packages/lab/src/index.ts+ *+ * SYNC: When modified, update /packages/lab/src/ListInput/ListInput.tsx.+ */++export {ListInput} from './ListInput';+export type {+ ListInputChange,+ ListInputColumn,+ ListInputProps,+ ListInputRenderContext,+ ListInputValueContext,+} from './ListInput';diff --git a/packages/lab/src/index.ts b/packages/lab/src/index.tsindex c66b16d7fd..6188f41778 100644--- a/packages/lab/src/index.ts+++ b/packages/lab/src/index.ts@@ -235,6 +235,9 @@ export {export * from './Stepper';export * from './CircularProgress';+// ListInput — compact editor for short collections of simple records+export * from './ListInput';+// LogStream — experimental streaming log viewerexport {LogStream,diff --git a/packages/lab/src/reorderStyles.ts b/packages/lab/src/reorderStyles.tsnew file mode 100644index 0000000000..2d84f0be42--- /dev/null+++ b/packages/lab/src/reorderStyles.ts@@ -0,0 +1,76 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file reorderStyles.ts+ * @input StyleX and Astryx semantic color, motion, radius, and spacing tokens+ * @output Shared internal visual states for reorderable Lab components+ * @position Lab-internal drag-and-drop style contract; API arbitration required before public export+ */++import * as stylex from '@stylexjs/stylex';+import {+ colorVars,+ durationVars,+ easeVars,+ radiusVars,+ spacingVars,+} from '@astryxdesign/core/theme/tokens.stylex';++const indicatorBase = {+ content: '""',+ position: 'absolute' as const,+ insetInline: 0,+ height: spacingVars['--spacing-0-5'],+ borderRadius: radiusVars['--radius-full'],+ backgroundColor: colorVars['--color-accent'],+ pointerEvents: 'none' as const,+ zIndex: 2,+};++/**+ * Default Lab reorder visuals. Keep interaction behavior component-owned until+ * vertical, horizontal, grid, and cross-list reorder APIs are reconciled.+ */+export const reorderStyles = stylex.create({+ source: {+ opacity: 0.5,+ userSelect: 'none',+ },+ preview: {+ opacity: 0.5,+ pointerEvents: 'none',+ userSelect: 'none',+ willChange: 'transform',+ },+ viewTransitionRoot: {+ '::view-transition-group(*)': {+ animationDuration: {+ default: durationVars['--duration-fast'],+ '@media (prefers-reduced-motion: reduce)': '0s',+ },+ animationTimingFunction: easeVars['--ease-standard'],+ },+ },+ dropBefore: {+ position: 'relative',+ '::before': {+ ...indicatorBase,+ insetBlockStart: `calc(-1 * ${spacingVars['--spacing-0-5']})`,+ },+ },+ dropAfter: {+ position: 'relative',+ '::after': {+ ...indicatorBase,+ insetBlockEnd: `calc(-1 * ${spacingVars['--spacing-0-5']})`,+ },+ },+ handle: {+ cursor: 'grab',+ touchAction: 'none',+ },+ handleActive: {+ cursor: 'grabbing',+ touchAction: 'none',+ },+});