Skip to content

Commit 0564c74

Browse files
perf(mosaic): re-render only the list options whose highlight changes (#10621)
1 parent d75b38c commit 0564c74

13 files changed

Lines changed: 1192 additions & 193 deletions
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'@clerk/mosaic': patch
3+
---
4+
5+
Reduce option re-renders in `Combobox`, `Autocomplete` and `Select`.

‎packages/mosaic/src/primitives/autocomplete/autocomplete-context.ts‎

Lines changed: 32 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,6 @@ export interface AutocompleteContextValue {
1919
placement: Placement;
2020
getReferenceProps: UseInteractionsReturn['getReferenceProps'];
2121
getFloatingProps: UseInteractionsReturn['getFloatingProps'];
22-
getItemProps: UseInteractionsReturn['getItemProps'];
2322
activeIndex: number | null;
2423
selectedIndex: number | null;
2524
elementsRef: React.MutableRefObject<Array<HTMLElement | null>>;
@@ -30,7 +29,6 @@ export interface AutocompleteContextValue {
3029
setInlineMode: React.Dispatch<React.SetStateAction<boolean>>;
3130
handleSelect: (value: string, index: number, label: string) => void;
3231
handleInputChange: (value: string) => void;
33-
registerSelectedIndex: (index: number, value: string) => void;
3432
mounted: boolean;
3533
transitionProps: TransitionProps;
3634
}
@@ -44,3 +42,35 @@ export function useAutocompleteContext() {
4442
}
4543
return ctx;
4644
}
45+
46+
export interface AutocompleteHighlightContextValue {
47+
activeIndex: number | null;
48+
selectedValue: string | undefined;
49+
}
50+
export const AutocompleteHighlightContext = createContext<AutocompleteHighlightContextValue | null>(null);
51+
52+
export function useAutocompleteHighlightContext() {
53+
const ctx = useContext(AutocompleteHighlightContext);
54+
if (!ctx) {
55+
throw new Error('Autocomplete.Option must be used within <Autocomplete>');
56+
}
57+
return ctx;
58+
}
59+
60+
export interface AutocompleteOptionsContextValue {
61+
getItemProps: UseInteractionsReturn['getItemProps'];
62+
handleSelect: (value: string, index: number, label: string) => void;
63+
refs: ExtendedRefs<ReferenceType>;
64+
valuesByIndexRef: React.MutableRefObject<Map<number, string>>;
65+
registerSelectedIndex: (index: number, selected: boolean) => void;
66+
}
67+
68+
export const AutocompleteOptionsContext = createContext<AutocompleteOptionsContextValue | null>(null);
69+
70+
export function useAutocompleteOptionsContext() {
71+
const ctx = useContext(AutocompleteOptionsContext);
72+
if (!ctx) {
73+
throw new Error('Autocomplete.Option must be used within <Autocomplete>');
74+
}
75+
return ctx;
76+
}

‎packages/mosaic/src/primitives/autocomplete/autocomplete-option.tsx‎

Lines changed: 79 additions & 60 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ import { useListItem } from '@floating-ui/react';
44
import React, { useEffect, useId } from 'react';
55

66
import { type ComponentProps, type DefaultProps, isHTMLElement, mergeProps, useRender } from '../utils';
7-
import { useAutocompleteContext } from './autocomplete-context';
7+
import { useAutocompleteHighlightContext, useAutocompleteOptionsContext } from './autocomplete-context';
88

99
export interface AutocompleteOptionProps extends ComponentProps<'div'> {
1010
value: string;
@@ -14,72 +14,91 @@ export interface AutocompleteOptionProps extends ComponentProps<'div'> {
1414

1515
export const AutocompleteOption = React.forwardRef<HTMLDivElement, AutocompleteOptionProps>(
1616
function AutocompleteOption(props, ref) {
17-
const { render, value, label, disabled, ...otherProps } = props;
18-
const { activeIndex, selectedValue, getItemProps, handleSelect, valuesByIndexRef, registerSelectedIndex, refs } =
19-
useAutocompleteContext();
17+
const { activeIndex, selectedValue } = useAutocompleteHighlightContext();
18+
const { ref: itemRef, index } = useListItem({ label: props.label ?? props.value });
19+
return (
20+
<AutocompleteOptionBody
21+
{...props}
22+
forwardedRef={ref}
23+
listItemRef={itemRef}
24+
index={index}
25+
isActive={activeIndex === index}
26+
isSelected={selectedValue === props.value}
27+
/>
28+
);
29+
},
30+
);
2031

21-
const id = useId();
22-
const displayLabel = label ?? value;
23-
const { ref: itemRef, index } = useListItem({ label: displayLabel });
32+
interface AutocompleteOptionBodyProps extends AutocompleteOptionProps {
33+
forwardedRef: React.ForwardedRef<HTMLDivElement>;
34+
listItemRef: (node: HTMLElement | null) => void;
35+
index: number;
36+
isActive: boolean;
37+
isSelected: boolean;
38+
}
2439

25-
const isSelected = selectedValue === value;
26-
const isActive = activeIndex === index;
40+
const AutocompleteOptionBody = React.memo(function AutocompleteOptionBody(bodyProps: AutocompleteOptionBodyProps) {
41+
const { forwardedRef: ref, listItemRef: itemRef, index, isActive, isSelected, ...props } = bodyProps;
42+
const { render, value, label, disabled, ...otherProps } = props;
43+
const { getItemProps, handleSelect, valuesByIndexRef, registerSelectedIndex, refs } = useAutocompleteOptionsContext();
2744

28-
useEffect(() => {
29-
const map = valuesByIndexRef.current;
30-
if (!disabled) {
31-
map.set(index, value);
32-
}
33-
registerSelectedIndex(index, value);
34-
return () => {
35-
map.delete(index);
36-
};
37-
}, [index, value, disabled, valuesByIndexRef, registerSelectedIndex]);
45+
const id = useId();
46+
const displayLabel = label ?? value;
3847

39-
const state = {
40-
selected: isSelected,
41-
active: isActive,
42-
disabled: !!disabled,
48+
useEffect(() => {
49+
const map = valuesByIndexRef.current;
50+
if (!disabled) {
51+
map.set(index, value);
52+
}
53+
registerSelectedIndex(index, isSelected);
54+
return () => {
55+
map.delete(index);
4356
};
57+
}, [index, value, disabled, isSelected, valuesByIndexRef, registerSelectedIndex]);
4458

45-
const ownProps = {
46-
id,
47-
role: 'option',
48-
'aria-selected': isSelected,
49-
'aria-disabled': disabled || undefined,
50-
} satisfies DefaultProps<'div'>;
59+
const state = {
60+
selected: isSelected,
61+
active: isActive,
62+
disabled: !!disabled,
63+
};
5164

52-
const defaultProps = {
53-
...ownProps,
54-
...getItemProps({
55-
onClick() {
56-
if (!disabled) {
57-
handleSelect(value, index, displayLabel);
58-
const reference = refs.domReference.current;
59-
if (isHTMLElement(reference)) {
60-
reference.focus();
61-
}
65+
const ownProps = {
66+
id,
67+
role: 'option',
68+
'aria-selected': isSelected,
69+
'aria-disabled': disabled || undefined,
70+
} satisfies DefaultProps<'div'>;
71+
72+
const defaultProps = {
73+
...ownProps,
74+
...getItemProps({
75+
onClick() {
76+
if (!disabled) {
77+
handleSelect(value, index, displayLabel);
78+
const reference = refs.domReference.current;
79+
if (isHTMLElement(reference)) {
80+
reference.focus();
6281
}
63-
},
64-
}),
65-
};
82+
}
83+
},
84+
}),
85+
};
6686

67-
const merged = mergeProps<'div'>(defaultProps, otherProps);
68-
// The option id is owned by the primitive and drives the input's
69-
// aria-activedescendant linkage: a consumer-supplied id must not override it.
70-
merged.id = id;
87+
const merged = mergeProps<'div'>(defaultProps, otherProps);
88+
// The option id is owned by the primitive and drives the input's
89+
// aria-activedescendant linkage: a consumer-supplied id must not override it.
90+
merged.id = id;
7191

72-
return useRender({
73-
defaultTagName: 'div',
74-
render,
75-
ref: [itemRef, ref],
76-
state,
77-
stateAttributesMapping: {
78-
selected: (v: boolean) => (v ? { 'data-selected': '' } : null),
79-
active: (v: boolean) => (v ? { 'data-active': '' } : null),
80-
disabled: (v: boolean) => (v ? { 'data-disabled': '' } : null),
81-
},
82-
props: merged,
83-
});
84-
},
85-
);
92+
return useRender({
93+
defaultTagName: 'div',
94+
render,
95+
ref: [itemRef, ref],
96+
state,
97+
stateAttributesMapping: {
98+
selected: (v: boolean) => (v ? { 'data-selected': '' } : null),
99+
active: (v: boolean) => (v ? { 'data-active': '' } : null),
100+
disabled: (v: boolean) => (v ? { 'data-disabled': '' } : null),
101+
},
102+
props: merged,
103+
});
104+
});

‎packages/mosaic/src/primitives/autocomplete/autocomplete-root.tsx‎

Lines changed: 36 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,14 @@ import { type ReactNode, useCallback, useEffect, useMemo, useRef, useState } fro
2222
import { useControllableState } from '../hooks/use-controllable-state';
2323
import { useTransition } from '../hooks/use-transition';
2424
import { cssVars } from '../utils/css-vars';
25-
import { AutocompleteContext, type AutocompleteContextValue } from './autocomplete-context';
25+
import {
26+
AutocompleteContext,
27+
type AutocompleteContextValue,
28+
AutocompleteHighlightContext,
29+
type AutocompleteHighlightContextValue,
30+
AutocompleteOptionsContext,
31+
type AutocompleteOptionsContextValue,
32+
} from './autocomplete-context';
2633

2734
export interface AutocompleteProps {
2835
/** Controlled input text. */
@@ -65,14 +72,11 @@ function AutocompleteInner(props: AutocompleteProps) {
6572
const arrowRef = useRef<SVGSVGElement | null>(null);
6673
const popupRef = useRef<HTMLDivElement | null>(null);
6774
const valuesByIndexRef = useRef<Map<number, string>>(new Map());
68-
const registerSelectedIndex = useCallback(
69-
(index: number, value: string) => {
70-
if (value === selectedValue) {
71-
setSelectedIndex(index);
72-
}
73-
},
74-
[selectedValue],
75-
);
75+
const registerSelectedIndex = useCallback((index: number, selected: boolean) => {
76+
if (selected) {
77+
setSelectedIndex(index);
78+
}
79+
}, []);
7680

7781
const previousOpenRef = useRef(open);
7882
useEffect(() => {
@@ -178,7 +182,6 @@ function AutocompleteInner(props: AutocompleteProps) {
178182
placement,
179183
getReferenceProps,
180184
getFloatingProps,
181-
getItemProps,
182185
activeIndex,
183186
selectedIndex,
184187
elementsRef,
@@ -189,7 +192,6 @@ function AutocompleteInner(props: AutocompleteProps) {
189192
setInlineMode,
190193
handleSelect,
191194
handleInputChange,
192-
registerSelectedIndex,
193195
mounted,
194196
transitionProps,
195197
}),
@@ -203,20 +205,40 @@ function AutocompleteInner(props: AutocompleteProps) {
203205
placement,
204206
getReferenceProps,
205207
getFloatingProps,
206-
getItemProps,
207208
activeIndex,
208209
selectedIndex,
209210
handleSelect,
210211
handleInputChange,
211-
registerSelectedIndex,
212212
mounted,
213213
transitionProps,
214214
],
215215
);
216216

217+
const optionsContextValue = useMemo<AutocompleteOptionsContextValue>(
218+
() => ({
219+
getItemProps,
220+
handleSelect,
221+
refs,
222+
valuesByIndexRef,
223+
registerSelectedIndex,
224+
}),
225+
[getItemProps, handleSelect, refs, registerSelectedIndex],
226+
);
227+
228+
const highlightContextValue = useMemo<AutocompleteHighlightContextValue>(
229+
() => ({ activeIndex, selectedValue }),
230+
[activeIndex, selectedValue],
231+
);
232+
217233
return (
218234
<FloatingNode id={nodeId}>
219-
<AutocompleteContext.Provider value={contextValue}>{children}</AutocompleteContext.Provider>
235+
<AutocompleteContext.Provider value={contextValue}>
236+
<AutocompleteOptionsContext.Provider value={optionsContextValue}>
237+
<AutocompleteHighlightContext.Provider value={highlightContextValue}>
238+
{children}
239+
</AutocompleteHighlightContext.Provider>
240+
</AutocompleteOptionsContext.Provider>
241+
</AutocompleteContext.Provider>
220242
</FloatingNode>
221243
);
222244
}

0 commit comments

Comments
 (0)