Skip to content

Commit

Permalink
Fix useId updater overwrite (adobe#6788)
Browse files Browse the repository at this point in the history
  • Loading branch information
snowystinger committed Sep 6, 2024
1 parent 17ad099 commit 4980928
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 8 deletions.
21 changes: 13 additions & 8 deletions packages/@react-aria/utils/src/useId.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ let canUseDOM = Boolean(
window.document.createElement
);

let idsUpdaterMap: Map<string, (v: string) => void> = new Map();
let idsUpdaterMap: Map<string, Array<(v: string) => void>> = new Map();

/**
* If a default is not provided, generate an id.
Expand All @@ -39,7 +39,12 @@ export function useId(defaultId?: string): string {
}, []);

if (canUseDOM) {
idsUpdaterMap.set(res, updateValue);
// TS not smart enough to know that `has` means the value exists
if (idsUpdaterMap.has(res) && !idsUpdaterMap.get(res)!.includes(updateValue)) {
idsUpdaterMap.set(res, [...idsUpdaterMap.get(res)!, updateValue]);
} else {
idsUpdaterMap.set(res, [updateValue]);
}
}

useLayoutEffect(() => {
Expand Down Expand Up @@ -71,15 +76,15 @@ export function mergeIds(idA: string, idB: string): string {
return idA;
}

let setIdA = idsUpdaterMap.get(idA);
if (setIdA) {
setIdA(idB);
let setIdsA = idsUpdaterMap.get(idA);
if (setIdsA) {
setIdsA.forEach(fn => fn(idB));
return idB;
}

let setIdB = idsUpdaterMap.get(idB);
if (setIdB) {
setIdB(idA);
let setIdsB = idsUpdaterMap.get(idB);
if (setIdsB) {
setIdsB.forEach(fn => fn(idA));
return idA;
}

Expand Down
19 changes: 19 additions & 0 deletions packages/react-aria-components/test/TextField.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -238,5 +238,24 @@ describe('TextField', () => {
expect(outerEl[0]).not.toHaveAttribute('id');
expect(input).toHaveAttribute('id', 'name');
});

it('should link an id on the input to the label htmlFor', async () => {
let {getAllByTestId, getByRole, getByText} = render(
<TextField defaultValue="test" data-testid="text-field-test" data-foo="bar">
<Label>Test</Label>
<Input id="name" />
<Text slot="description">Description</Text>
<Text slot="errorMessage">Error</Text>
</TextField>
);
let outerEl = getAllByTestId('text-field-test');
let input = getByRole('textbox');
let label = getByText('Test');

expect(outerEl).toHaveLength(1);
expect(outerEl[0]).not.toHaveAttribute('id');
expect(input).toHaveAttribute('id', 'name');
expect(label).toHaveAttribute('for', 'name');
});
});
});

0 comments on commit 4980928

Please sign in to comment.