@sanity/ui 5.0.0-alpha.25 → 5.0.0-alpha.27

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sanity/ui",
3
- "version": "5.0.0-alpha.25",
3
+ "version": "5.0.0-alpha.27",
4
4
  "description": "Sanity UI Library",
5
5
  "keywords": [
6
6
  "components",
@@ -51,7 +51,7 @@
51
51
  }
52
52
  },
53
53
  "dependencies": {
54
- "@sanity-labs/design-tokens": "0.0.2-alpha.11",
54
+ "@sanity-labs/design-tokens": "0.0.2-alpha.12",
55
55
  "@sanity/icons": "^5.2.1",
56
56
  "clsx": "^2.1.1",
57
57
  "comment-json": "^5.0.0",
@@ -3,6 +3,7 @@ import {RemoveIcon} from '@sanity/icons/Remove'
3
3
  import clsx from 'clsx'
4
4
  import {useEffect, useRef} from 'react'
5
5
 
6
+ import {composeRefs} from '../../utils/composeRefs'
6
7
  import {getProps} from '../../utils/getProps'
7
8
  import {suffixClassName} from '../../utils/suffixClassName'
8
9
  import {Box} from '../box/Box'
@@ -12,7 +13,7 @@ const checkboxClassName = suffixClassName('sui-Checkbox')
12
13
  const checkboxInputClassName = suffixClassName('sui-CheckboxInput')
13
14
 
14
15
  /** @beta */
15
- export function Checkbox(props: CheckboxProps) {
16
+ export function Checkbox({ref, ...props}: CheckboxProps) {
16
17
  const inputRef = useRef<HTMLInputElement>(null)
17
18
  const {className, style, hasError, indeterminate, ...rest} = getProps(props, checkboxProps)
18
19
 
@@ -38,7 +39,7 @@ export function Checkbox(props: CheckboxProps) {
38
39
  <input
39
40
  type="checkbox"
40
41
  className={checkboxInputClassName}
41
- ref={inputRef}
42
+ ref={composeRefs(inputRef, ref)}
42
43
  aria-invalid={hasError || undefined}
43
44
  {...rest}
44
45
  />
@@ -2,6 +2,7 @@ import {CloseIcon} from '@sanity/icons/Close'
2
2
  import clsx from 'clsx'
3
3
  import {useEffect, useId, useRef} from 'react'
4
4
 
5
+ import {composeRefs} from '../../utils/composeRefs'
5
6
  import {getProps} from '../../utils/getProps'
6
7
  import {suffixClassName} from '../../utils/suffixClassName'
7
8
  import {Box} from '../box/Box'
@@ -19,7 +20,7 @@ const dialogClassName = suffixClassName('sui-Dialog')
19
20
  const dialogContentClassName = suffixClassName('sui-DialogContent')
20
21
  const dialogFooterClassName = suffixClassName('sui-DialogFooter')
21
22
 
22
- function DialogRoot({open = false, size = 0, ...props}: DialogProps) {
23
+ function DialogRoot({open = false, size = 0, ref, ...props}: DialogProps) {
23
24
  const {children, className, style, header, onClose, ...rest} = getProps(
24
25
  {size, ...props},
25
26
  dialogProps,
@@ -61,7 +62,7 @@ function DialogRoot({open = false, size = 0, ...props}: DialogProps) {
61
62
  return (
62
63
  <dialog
63
64
  {...rest}
64
- ref={dialogRef}
65
+ ref={composeRefs(dialogRef, ref)}
65
66
  closedby="any"
66
67
  aria-labelledby={header ? headerId : undefined}
67
68
  onClose={onClose}
@@ -24,6 +24,7 @@
24
24
  @import './popover/popover.css';
25
25
  @import './press-area/press-area.css';
26
26
  @import './radio/radio.css';
27
+ @import './search-input/search-input.css';
27
28
  @import './select/select.css';
28
29
  @import './spinner/spinner.css';
29
30
  @import './skip-to-content/skip-to-content.css';
@@ -0,0 +1,90 @@
1
+ import CloseIcon from '@sanity/icons/Close'
2
+ import SearchIcon from '@sanity/icons/Search'
3
+ import clsx from 'clsx'
4
+ import {useId, useRef} from 'react'
5
+
6
+ import {composeRefs} from '../../utils/composeRefs'
7
+ import {getProps} from '../../utils/getProps'
8
+ import {suffixClassName} from '../../utils/suffixClassName'
9
+ import {Icon} from '../icon/Icon'
10
+ import {PressArea} from '../press-area/PressArea'
11
+ import {Spinner} from '../spinner/Spinner'
12
+ import {type SearchInputProps, searchInputProps} from './searchInput.props'
13
+
14
+ const searchInputClassName = suffixClassName('sui-SearchInput')
15
+ const searchInputClearClassName = suffixClassName('sui-SearchInput-Clear')
16
+ const searchInputIconClassName = suffixClassName('sui-SearchInput-Icon')
17
+
18
+ /** @public */
19
+ export function SearchInput({
20
+ density = 'regular',
21
+ loading,
22
+ // A non-null placeholder to ensure that, if no placeholder is passed, the custom clear button's display logic still works (see search-input.css)
23
+ placeholder = ' ',
24
+ ref,
25
+ ...props
26
+ }: SearchInputProps) {
27
+ const {className, style, ...rest} = getProps({density, ...props}, searchInputProps)
28
+
29
+ const searchInputClasses = clsx(searchInputClassName, 'sui-radius2', 'sui-width-full', className)
30
+ const iconClasses = `sui-position-absolute sui-display-flex sui-align-items-center sui-px1`
31
+
32
+ const anchorId = useId()
33
+ const anchorName = `--anchor-${anchorId}`
34
+
35
+ const inputRef = useRef<HTMLInputElement>(null)
36
+
37
+ // Custom 'clear input' handler:
38
+ // Gets the input's native value setter, resets to an empty string with that setter,
39
+ // and dispatches an `input` event to notify React of the change. See:
40
+ // https://github.com/facebook/react/issues/10135#issuecomment-401496776
41
+ function handleClear() {
42
+ const input = inputRef.current
43
+ if (!input) return
44
+
45
+ // oxlint-disable-next-line typescript/unbound-method -- called with an explicit `this` below
46
+ const set = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(input), 'value')?.set
47
+ set?.call(input, '')
48
+ input.dispatchEvent(new Event('input', {bubbles: true}))
49
+ // Focus the input after clearing, as native clear does
50
+ input.focus()
51
+ }
52
+
53
+ return (
54
+ <>
55
+ <input
56
+ className={searchInputClasses}
57
+ style={{anchorName, ...style}}
58
+ {...rest}
59
+ aria-busy={loading}
60
+ data-ui="SearchInput"
61
+ type="search"
62
+ placeholder={placeholder}
63
+ ref={composeRefs(inputRef, ref)}
64
+ />
65
+ <div
66
+ className={clsx(searchInputIconClassName, iconClasses)}
67
+ data-ui="Search-Icon"
68
+ style={{positionAnchor: anchorName}}
69
+ >
70
+ {loading ? <Spinner size={1} /> : <Icon icon={SearchIcon} size={1} />}
71
+ </div>
72
+ <div
73
+ className={clsx(searchInputClearClassName, iconClasses)}
74
+ data-ui="Search-Clear"
75
+ style={{positionAnchor: anchorName}}
76
+ >
77
+ <PressArea
78
+ type="button"
79
+ onClick={handleClear}
80
+ aria-label="Clear search query"
81
+ className="sui-display-inline-flex sui-align-items-center sui-justify-content-center"
82
+ >
83
+ <Icon icon={CloseIcon} size={0} />
84
+ </PressArea>
85
+ </div>
86
+ </>
87
+ )
88
+ }
89
+
90
+ export type {SearchInputProps}
@@ -0,0 +1,125 @@
1
+ .sui-SearchInput {
2
+ --background-color: var(--backdrop);
3
+ --border-color: var(--separator-high);
4
+ --color: var(--foreground-high);
5
+ background-color: var(--background-color);
6
+ border: 1px solid var(--border-color);
7
+ font: var(--form-element-text);
8
+ color: var(--color);
9
+ /* Use text-indent to clear the search icon */
10
+ text-indent: var(--space-4);
11
+ }
12
+
13
+ .sui-SearchInput::placeholder {
14
+ color: oklch(from var(--color) l c h / var(--placeholder-opacity));
15
+ }
16
+
17
+ /* Hide webkit default clear button */
18
+ .sui-SearchInput::-webkit-search-cancel-button,
19
+ .sui-SearchInput::-webkit-search-decoration {
20
+ -webkit-appearance: none;
21
+ appearance: none;
22
+ }
23
+
24
+ /**
25
+ * Search icon
26
+ */
27
+ .sui-SearchInput-Icon {
28
+ pointer-events: none;
29
+ top: calc(anchor(top));
30
+ bottom: calc(anchor(bottom));
31
+ left: calc(anchor(left) + 1px);
32
+ }
33
+
34
+ .sui-SearchInput-Icon svg {
35
+ --background-color: var(--backdrop);
36
+ background-color: var(--background-color);
37
+ }
38
+
39
+ /* Shift search icon's left inset when SearchInput uses loose density */
40
+ .sui-SearchInput.sui-px3 + .sui-SearchInput-Icon {
41
+ left: calc(anchor(left) + 3px);
42
+ }
43
+
44
+ /**
45
+ * Loading icon (replaces search icon in icon slot when loading)
46
+ */
47
+ .sui-SearchInput[aria-busy="true"] + .sui-SearchInput-Icon svg {
48
+ background: transparent;
49
+ }
50
+
51
+ /**
52
+ * Custom clear button
53
+ */
54
+ .sui-SearchInput-Clear {
55
+ top: calc(anchor(top));
56
+ bottom: calc(anchor(bottom));
57
+ right: calc(anchor(right) - 3px);
58
+ }
59
+
60
+ /* Hide clear button when SearchInput has no value (placeholder shown) or is read-only */
61
+ .sui-SearchInput:is(:placeholder-shown, :read-only) + .sui-SearchInput-Icon + .sui-SearchInput-Clear {
62
+ display: none;
63
+ }
64
+
65
+ /* Override SearchInput’s padding-right (set by the density prop) so input value clears
66
+ * the space occupied by the clear button when shown */
67
+ .sui-SearchInput:not(:placeholder-shown, :read-only) {
68
+ padding-right: 25px;
69
+ }
70
+
71
+ .sui-SearchInput-Clear [data-ui="PressArea"] {
72
+ inline-size: 25px;
73
+ aspect-ratio: 1;
74
+ border-radius: var(--radius-1);
75
+ }
76
+
77
+ .sui-SearchInput-Clear [data-ui="PressArea"] svg {
78
+ --background-color: var(--backdrop);
79
+ background-color: var(--background-color);
80
+ border-radius: var(--radius-2);
81
+ }
82
+
83
+ .sui-SearchInput-Clear [data-ui="PressArea"]:hover svg {
84
+ --background-color: var(--background-high);
85
+ }
86
+
87
+ .sui-SearchInput-Clear [data-ui="PressArea"]:focus-visible {
88
+ outline: var(--focus-outline);
89
+ outline-offset: var(--focus-offset);
90
+ }
91
+
92
+ /**
93
+ * Hover - uses relative border/background colours to darken/lighten
94
+ */
95
+ .sui-SearchInput:hover {
96
+ border-color: light-dark(
97
+ oklch(from var(--border-color) calc(l - var(--hover-lightness-delta)) c h),
98
+ oklch(from var(--border-color) calc(l + var(--hover-lightness-delta)) c h)
99
+ );
100
+ }
101
+
102
+ /**
103
+ * Disabled, read only
104
+ */
105
+ .sui-SearchInput:is(:disabled, :read-only) {
106
+ --background-color: var(--inert-background);
107
+ --border-color: var(--separator-low);
108
+ }
109
+
110
+ .sui-SearchInput:disabled {
111
+ --color: var(--inert-foreground);
112
+ }
113
+
114
+ .sui-SearchInput:is(:disabled, :read-only) + .sui-SearchInput-Icon svg {
115
+ --background-color: transparent;
116
+ color: var(--inert-foreground);
117
+ }
118
+
119
+ /**
120
+ * Focus
121
+ */
122
+ .sui-SearchInput:focus-visible {
123
+ outline: var(--focus-outline);
124
+ outline-offset: var(--focus-offset);
125
+ }
@@ -0,0 +1,18 @@
1
+ import type {ComponentProps} from 'react'
2
+
3
+ import {formElementDensityProps, type FormElementDensityProps} from '../../props/formElement'
4
+ import {type PropDef} from '../../types/PropDef'
5
+
6
+ /** @public */
7
+ export interface SearchInputProps
8
+ extends FormElementDensityProps, Omit<ComponentProps<'input'>, 'type'> {
9
+ /* True when search results are pending */
10
+ loading?: boolean
11
+ }
12
+
13
+ export const searchInputProps: Record<string, PropDef> = {
14
+ loading: {
15
+ type: 'boolean',
16
+ },
17
+ ...formElementDensityProps,
18
+ }
@@ -8,6 +8,7 @@ import {Icon} from '../icon/Icon'
8
8
  import {type SelectProps, selectProps} from './select.props'
9
9
 
10
10
  const selectClassName = suffixClassName('sui-Select')
11
+ const selectIconClassName = suffixClassName('sui-Select-Icon')
11
12
 
12
13
  /** @public */
13
14
  export function Select({density = 'regular', hasError = false, ...props}: SelectProps) {
@@ -31,7 +32,11 @@ export function Select({density = 'regular', hasError = false, ...props}: Select
31
32
  >
32
33
  {children}
33
34
  </select>
34
- <div className={iconClasses} data-ui="Select-icon" style={{positionAnchor: anchorName}}>
35
+ <div
36
+ className={clsx(selectIconClassName, iconClasses)}
37
+ data-ui="Select-Icon"
38
+ style={{positionAnchor: anchorName}}
39
+ >
35
40
  <Icon icon={SelectIcon} size={1} />
36
41
  </div>
37
42
  </>
@@ -8,16 +8,17 @@
8
8
  color: var(--color);
9
9
  }
10
10
 
11
- [data-ui="Select-icon"] {
12
- --background-color: var(--backdrop);
13
- background-color: var(--background-color);
11
+ .sui-Select-Icon {
14
12
  pointer-events: none;
15
- /* reduce block size by 1px at each end and inset from right to not interrupt Select’s border */
16
- top: calc(anchor(top) + 1px);
17
- bottom: calc(anchor(bottom) + 1px);
13
+ top: calc(anchor(top));
14
+ bottom: calc(anchor(bottom));
18
15
  right: calc(anchor(right) + 2px);
19
16
  }
20
17
 
18
+ .sui-Select-Icon svg {
19
+ --background-color: var(--backdrop);
20
+ background-color: var(--background-color);
21
+ }
21
22
  /**
22
23
  * Error
23
24
  */
@@ -26,7 +27,7 @@
26
27
  --color: var(--error-foreground);
27
28
  }
28
29
 
29
- .sui-Select[aria-invalid="true"] + [data-ui="Select-icon"] svg {
30
+ .sui-Select[aria-invalid="true"] + .sui-Select-Icon svg {
30
31
  color: var(--error-foreground);
31
32
  }
32
33
 
@@ -50,11 +51,8 @@
50
51
  pointer-events: none;
51
52
  }
52
53
 
53
- .sui-Select:disabled + [data-ui="Select-icon"] {
54
- --background-color: var(--inert-background);
55
- }
56
-
57
- .sui-Select:disabled + [data-ui="Select-icon"] svg {
54
+ .sui-Select:disabled + .sui-Select-Icon svg {
55
+ --background-color: transparent;
58
56
  color: var(--inert-foreground);
59
57
  }
60
58
 
@@ -29,6 +29,6 @@
29
29
  }
30
30
 
31
31
  .sui-Tabs [role="tab"][aria-selected="true"] {
32
- --background-color: var(--background-low);
32
+ --background-color: var(--background-high);
33
33
  --foreground-color: var(--foreground-high);
34
34
  }
@@ -1,6 +1,7 @@
1
1
  import clsx from 'clsx'
2
2
  import {type ElementType, useRef, useState} from 'react'
3
3
 
4
+ import {composeRefs} from '../../utils/composeRefs'
4
5
  import {getProps} from '../../utils/getProps'
5
6
  import {suffixClassName} from '../../utils/suffixClassName'
6
7
  import {type TooltipGroupProps, tooltipGroupProps} from './tooltipGroup.props'
@@ -9,9 +10,9 @@ const tooltipGroupClassName = suffixClassName('sui-TooltipGroup')
9
10
 
10
11
  /** @public */
11
12
  export function TooltipGroup<T extends ElementType = 'div'>(props: TooltipGroupProps<T>) {
12
- const {as, children, className, style, ...rest} = getProps(props, tooltipGroupProps)
13
+ const {as, children, className, style, ref, ...rest} = getProps(props, tooltipGroupProps)
13
14
  const Component = as || 'div'
14
- const ref = useRef<HTMLElement>(null)
15
+ const tooltipGroupRef = useRef<HTMLElement>(null)
15
16
  const [isActive, setIsActive] = useState(false)
16
17
 
17
18
  const handleTransitionEnd = (e: TransitionEvent) => {
@@ -31,7 +32,7 @@ export function TooltipGroup<T extends ElementType = 'div'>(props: TooltipGroupP
31
32
  }
32
33
 
33
34
  const handleBlur = (e: FocusEvent) => {
34
- if (ref.current && ref.current.contains(e.relatedTarget as Node)) {
35
+ if (tooltipGroupRef.current && tooltipGroupRef.current.contains(e.relatedTarget as Node)) {
35
36
  return
36
37
  }
37
38
 
@@ -47,12 +48,12 @@ export function TooltipGroup<T extends ElementType = 'div'>(props: TooltipGroupP
47
48
  '--tooltip-delay-group': '0ms',
48
49
  }),
49
50
  }}
51
+ {...rest}
50
52
  data-ui="TooltipGroup"
51
- ref={ref}
53
+ ref={composeRefs(tooltipGroupRef, ref)}
52
54
  onTransitionEnd={handleTransitionEnd}
53
55
  onMouseLeave={handleMouseLeave}
54
56
  onBlur={handleBlur}
55
- {...rest}
56
57
  >
57
58
  {children}
58
59
  </Component>
@@ -24,6 +24,6 @@ export const visuallyHiddenProps: Record<string, PropDef> = {
24
24
  },
25
25
  visibleOnFocus: {
26
26
  type: 'boolean',
27
- className: 'sui-visually-hidden-visible',
27
+ className: 'visually-hidden-visible',
28
28
  },
29
29
  }
package/src/index.ts CHANGED
@@ -73,3 +73,4 @@ export type {Space, SpaceAuto, SpaceAutoNegative, SpaceInherit} from './types/Sp
73
73
  export type {TextSize} from './types/Text'
74
74
  export type {TextAlign} from './types/TextAlign'
75
75
  export type {Tone} from './types/Tone'
76
+ export * from './components/search-input/SearchInput'
package/src/types/Tone.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  export const TONE = ['neutral', 'positive', 'suggest', 'caution', 'critical'] as const
2
- export const TONE_WITH_DEFAULT = ['default', ...TONE]
2
+ export const TONE_WITH_DEFAULT = ['default', ...TONE] as const
3
3
  /** @public */
4
4
  export type Tone = (typeof TONE)[number]
5
5
  export type ToneWithDefault = (typeof TONE_WITH_DEFAULT)[number]
@@ -0,0 +1,130 @@
1
+ import {createRef} from 'react'
2
+ import {describe, expect, it, vi} from 'vitest'
3
+
4
+ import {composeRefs} from './composeRefs'
5
+
6
+ type Node = {id: string}
7
+
8
+ const node: Node = {id: 'node'}
9
+
10
+ describe('composeRefs', () => {
11
+ it('sets ref objects to the node', () => {
12
+ const refA = createRef<Node>()
13
+ const refB = createRef<Node>()
14
+
15
+ composeRefs(refA, refB)(node)
16
+
17
+ expect(refA.current).toBe(node)
18
+ expect(refB.current).toBe(node)
19
+ })
20
+
21
+ it('calls callback refs with the node', () => {
22
+ const callbackA = vi.fn()
23
+ const callbackB = vi.fn()
24
+
25
+ composeRefs<Node>(callbackA, callbackB)(node)
26
+
27
+ expect(callbackA).toHaveBeenCalledExactlyOnceWith(node)
28
+ expect(callbackB).toHaveBeenCalledExactlyOnceWith(node)
29
+ })
30
+
31
+ it('sets ref objects and calls callback refs together', () => {
32
+ const ref = createRef<Node>()
33
+ const callback = vi.fn()
34
+
35
+ composeRefs<Node>(ref, callback)(node)
36
+
37
+ expect(ref.current).toBe(node)
38
+ expect(callback).toHaveBeenCalledExactlyOnceWith(node)
39
+ })
40
+
41
+ it('ignores null and undefined refs', () => {
42
+ const ref = createRef<Node>()
43
+
44
+ expect(() => composeRefs<Node>(null, undefined, ref)(node)).not.toThrow()
45
+ expect(ref.current).toBe(node)
46
+ })
47
+
48
+ it('returns a cleanup function', () => {
49
+ const cleanup = composeRefs(createRef<Node>())(node)
50
+
51
+ expect(cleanup).toBeTypeOf('function')
52
+ })
53
+
54
+ it('returns a cleanup function when no refs are given', () => {
55
+ const cleanup = composeRefs<Node>()(node)
56
+
57
+ expect(cleanup).toBeTypeOf('function')
58
+ expect(() => (cleanup as () => void)()).not.toThrow()
59
+ })
60
+
61
+ describe('cleanup', () => {
62
+ it('sets ref objects to null', () => {
63
+ const ref = createRef<Node>()
64
+ const cleanup = composeRefs(ref)(node) as () => void
65
+
66
+ cleanup()
67
+
68
+ expect(ref.current).toBeNull()
69
+ })
70
+
71
+ it('calls callback refs with null if they do not return a cleanup function', () => {
72
+ const callback = vi.fn()
73
+ const cleanup = composeRefs<Node>(callback)(node) as () => void
74
+
75
+ cleanup()
76
+
77
+ expect(callback).toHaveBeenCalledTimes(2)
78
+ expect(callback).toHaveBeenLastCalledWith(null)
79
+ })
80
+
81
+ it('calls the cleanup function of a callback ref in place of calling the ref with null', () => {
82
+ const callbackCleanup = vi.fn()
83
+ const callback = vi.fn(() => callbackCleanup)
84
+ const cleanup = composeRefs<Node>(callback)(node) as () => void
85
+
86
+ cleanup()
87
+
88
+ expect(callbackCleanup).toHaveBeenCalledOnce()
89
+ expect(callback).toHaveBeenCalledExactlyOnceWith(node)
90
+ })
91
+
92
+ it('handles a mix of ref objects, callback refs, and callback refs with cleanup functions', () => {
93
+ const ref = createRef<Node>()
94
+ const callback = vi.fn()
95
+ const callbackCleanup = vi.fn()
96
+ const callbackWithCleanup = vi.fn(() => callbackCleanup)
97
+
98
+ const cleanup = composeRefs<Node>(
99
+ ref,
100
+ callback,
101
+ callbackWithCleanup,
102
+ null,
103
+ )(node) as () => void
104
+ cleanup()
105
+
106
+ expect(ref.current).toBeNull()
107
+ expect(callback).toHaveBeenLastCalledWith(null)
108
+ expect(callbackCleanup).toHaveBeenCalledOnce()
109
+ expect(callbackWithCleanup).toHaveBeenCalledExactlyOnceWith(node)
110
+ })
111
+
112
+ it('runs cleanups in the same order as the refs', () => {
113
+ const calls: string[] = []
114
+ const callbackA = () => () => {
115
+ calls.push('a')
116
+ }
117
+ const callbackB = (value: Node | null) => {
118
+ if (value === null) calls.push('b')
119
+ }
120
+ const callbackC = () => () => {
121
+ calls.push('c')
122
+ }
123
+
124
+ const cleanup = composeRefs<Node>(callbackA, callbackB, callbackC)(node) as () => void
125
+ cleanup()
126
+
127
+ expect(calls).toEqual(['a', 'b', 'c'])
128
+ })
129
+ })
130
+ })
@@ -0,0 +1,52 @@
1
+ /**
2
+ * Based on `@radix-ui/react-compose-refs` by WorkOS (MIT License):
3
+ * https://github.com/radix-ui/primitives/blob/main/packages/react/compose-refs/src/compose-refs.tsx
4
+ *
5
+ * Changes from the original:
6
+ * - React 19+ only. The composed callback ref always returns a cleanup function, so React never
7
+ * calls it with `null` on detach.
8
+ * - No `useComposedRefs` hook. The React Compiler memoizes `composeRefs(...)` calls in components,
9
+ * so the composed ref stays the same between renders while its refs stay the same.
10
+ */
11
+ import {type Ref, type RefCallback} from 'react'
12
+
13
+ type PossibleRef<T> = Ref<T> | undefined
14
+
15
+ /**
16
+ * Sets a ref to a value. Returns the cleanup function of a callback ref, if it returns one.
17
+ */
18
+ function setRef<T>(ref: PossibleRef<T>, value: T | null) {
19
+ if (typeof ref === 'function') {
20
+ return ref(value)
21
+ }
22
+
23
+ if (ref !== null && ref !== undefined) {
24
+ ref.current = value
25
+ }
26
+
27
+ return undefined
28
+ }
29
+
30
+ /**
31
+ * Composes multiple refs (callback refs and ref objects) into one callback ref.
32
+ *
33
+ * On detach, the composed ref calls the cleanup function of each callback ref that returned one.
34
+ * It sets all other refs to `null`.
35
+ */
36
+ export function composeRefs<T>(...refs: PossibleRef<T>[]): RefCallback<T> {
37
+ return (node) => {
38
+ const cleanups = refs.map((ref) => setRef(ref, node))
39
+
40
+ return () => {
41
+ for (let i = 0; i < refs.length; i++) {
42
+ const cleanup = cleanups[i]
43
+
44
+ if (typeof cleanup === 'function') {
45
+ cleanup()
46
+ } else {
47
+ setRef(refs[i], null)
48
+ }
49
+ }
50
+ }
51
+ }
52
+ }