@sanity/ui 2.9.0-canary.3 → 2.9.0-canary.5

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": "2.9.0-canary.3",
3
+ "version": "2.9.0-canary.5",
4
4
  "keywords": [
5
5
  "sanity",
6
6
  "ui",
@@ -14,19 +14,21 @@ export interface MenuProps extends ResponsivePaddingProps {
14
14
  /**
15
15
  * @deprecated Use `shouldFocus="first"` instead.
16
16
  */
17
- focusFirst?: boolean
17
+ 'focusFirst'?: boolean
18
18
  /**
19
19
  * @deprecated Use `shouldFocus="last"` instead.
20
20
  */
21
- focusLast?: boolean
22
- onClickOutside?: (event: MouseEvent) => void
23
- onEscape?: () => void
24
- onItemClick?: () => void
25
- onItemSelect?: (index: number) => void
26
- originElement?: HTMLElement | null
27
- registerElement?: (el: HTMLElement) => () => void
28
- shouldFocus?: 'first' | 'last' | null
29
- space?: number | number[]
21
+ 'focusLast'?: boolean
22
+ 'onClickOutside'?: (event: MouseEvent) => void
23
+ 'onEscape'?: () => void
24
+ 'onItemClick'?: () => void
25
+ 'onItemSelect'?: (index: number) => void
26
+ 'originElement'?: HTMLElement | null
27
+ 'registerElement'?: (el: HTMLElement) => () => void
28
+ 'shouldFocus'?: 'first' | 'last' | null
29
+ 'space'?: number | number[]
30
+ 'aria-labelledby'?: string
31
+ 'onBlurCapture'?: (event: FocusEvent) => void
30
32
  }
31
33
 
32
34
  const Root = styled(Box)`
@@ -169,7 +169,7 @@ export const MenuButton = forwardRef(function MenuButton(
169
169
  }, [buttonElement, disableRestoreFocusOnClose])
170
170
 
171
171
  const handleBlur = useCallback(
172
- (event: React.FocusEvent<HTMLButtonElement>) => {
172
+ (event: FocusEvent) => {
173
173
  const target = event.relatedTarget
174
174
 
175
175
  if (!(target instanceof Node)) {
@@ -199,32 +199,19 @@ export const MenuButton = forwardRef(function MenuButton(
199
199
  return () => setChildMenuElements((els) => els.filter((_el) => _el !== el))
200
200
  }, [])
201
201
 
202
- const menuProps: MenuProps = useMemo(
203
- () => ({
204
- 'aria-labelledby': id,
205
- 'onBlurCapture': handleBlur,
206
- 'onClickOutside': handleMenuClickOutside,
207
- 'onEscape': handleMenuEscape,
208
- 'onItemClick': handleItemClick,
209
- 'originElement': buttonElement,
210
- registerElement,
211
- shouldFocus,
212
- }),
213
- [
214
- buttonElement,
215
- handleMenuClickOutside,
216
- handleMenuEscape,
217
- handleItemClick,
218
- id,
219
- handleBlur,
220
- registerElement,
221
- shouldFocus,
222
- ],
223
- )
202
+ const menuProps: MenuProps = {
203
+ 'aria-labelledby': id,
204
+ 'onBlurCapture': handleBlur,
205
+ 'onClickOutside': handleMenuClickOutside,
206
+ 'onEscape': handleMenuEscape,
207
+ 'onItemClick': handleItemClick,
208
+ 'originElement': buttonElement,
209
+ registerElement,
210
+ shouldFocus,
211
+ }
224
212
 
225
213
  const menu = menuProp && cloneElement(menuProp, menuProps)
226
214
 
227
- const ref = useRef<HTMLButtonElement | null>(null)
228
215
  const button = useMemo(
229
216
  () =>
230
217
  buttonProp &&
@@ -236,7 +223,7 @@ export const MenuButton = forwardRef(function MenuButton(
236
223
  'onMouseDown': handleMouseDown,
237
224
  'aria-haspopup': true,
238
225
  'aria-expanded': open,
239
- 'ref': ref,
226
+ 'ref': setButtonElement,
240
227
  'selected': buttonProp.props.selected ?? open,
241
228
  }),
242
229
  [buttonProp, handleButtonClick, handleButtonKeyDown, handleMouseDown, id, open],
@@ -245,19 +232,10 @@ export const MenuButton = forwardRef(function MenuButton(
245
232
  // Forward button ref to parent
246
233
  useImperativeHandle<HTMLButtonElement | null, HTMLButtonElement | null>(
247
234
  forwardedRef,
248
- () => ref.current,
235
+ () => buttonElement,
236
+ [buttonElement],
249
237
  )
250
238
 
251
- // If there's a button then we need to set the reference element to the cloned button ref
252
- // and if button changes we make sure to update or remove the reference element.
253
- useEffect(() => {
254
- if (!button) return undefined
255
-
256
- setButtonElement(ref.current)
257
-
258
- return () => setButtonElement(null)
259
- }, [button])
260
-
261
239
  const popoverProps: MenuButtonProps['popover'] = useMemo(
262
240
  () => ({
263
241
  boundaryElement: deprecated_boundaryElement,
@@ -1,4 +1,4 @@
1
- import {cloneElement, forwardRef, useCallback, useMemo, useState} from 'react'
1
+ import {cloneElement, forwardRef, useCallback, useState, Children, isValidElement} from 'react'
2
2
  import {styled} from 'styled-components'
3
3
  import {Inline, InlineProps} from '../../primitives'
4
4
 
@@ -9,10 +9,6 @@ export interface TabListProps extends Omit<InlineProps, 'as' | 'height'> {
9
9
  children: Array<React.ReactElement | null | undefined | false>
10
10
  }
11
11
 
12
- function _isReactElement(node: unknown): node is React.ReactElement {
13
- return Boolean(node)
14
- }
15
-
16
12
  //Limits the width of tabs in tablist
17
13
  const CustomInline = styled(Inline)`
18
14
  & > div {
@@ -33,22 +29,18 @@ export const TabList = forwardRef(function TabList(
33
29
  const {children: childrenProp, ...restProps} = props
34
30
  const [focusedIndex, setFocusedIndex] = useState(-1)
35
31
 
36
- const children = useMemo(() => childrenProp.filter(_isReactElement), [childrenProp])
32
+ const children: React.ReactElement[] = Children.toArray(childrenProp).filter(isValidElement)
37
33
 
38
34
  const tabs = children.map((child, childIndex) =>
39
35
  cloneElement(child, {
40
36
  focused: focusedIndex === childIndex,
41
37
  key: childIndex,
42
- onFocus: () => handleTabFocus(childIndex),
38
+ onFocus: () => setFocusedIndex(childIndex),
43
39
  }),
44
40
  )
45
41
 
46
42
  const numTabs = tabs.length
47
43
 
48
- const handleTabFocus = useCallback((tabIdx: number) => {
49
- setFocusedIndex(tabIdx)
50
- }, [])
51
-
52
44
  const handleKeyDown = useCallback(
53
45
  (event: React.KeyboardEvent<HTMLDivElement>) => {
54
46
  if (event.key === 'ArrowLeft') {
@@ -8,6 +8,7 @@ import {Box} from '../../primitives'
8
8
  import {Layer} from '../../utils'
9
9
  import {Toast} from './toast'
10
10
  import {ToastContext} from './toastContext'
11
+ import {generateToastId} from './toastState'
11
12
  import {ToastContextValue, ToastParams} from './types'
12
13
 
13
14
  type ToastState = {
@@ -45,8 +46,6 @@ const ToastContainer = styled.div`
45
46
  width: 100%;
46
47
  `
47
48
 
48
- let toastId = 0
49
-
50
49
  /**
51
50
  * @public
52
51
  */
@@ -60,20 +59,20 @@ export function ToastProvider(props: ToastProviderProps): React.ReactElement {
60
59
  () => ({
61
60
  initial: {
62
61
  opacity: 0,
63
- [POPOVER_MOTION_CONTENT_OPACITY_PROPERTY as string]: 0,
62
+ [POPOVER_MOTION_CONTENT_OPACITY_PROPERTY]: 0,
64
63
  y: 32,
65
64
  scale: 0.25,
66
65
  willChange: 'transform',
67
66
  },
68
67
  animate: {
69
68
  opacity: [0, 1, 1],
70
- [POPOVER_MOTION_CONTENT_OPACITY_PROPERTY as string]: [0, 0, 1],
69
+ [POPOVER_MOTION_CONTENT_OPACITY_PROPERTY]: [0, 0, 1],
71
70
  y: 0,
72
71
  scale: 1,
73
72
  },
74
73
  exit: {
75
74
  opacity: [1, 1, 0],
76
- [POPOVER_MOTION_CONTENT_OPACITY_PROPERTY as string]: [1, 0, 0],
75
+ [POPOVER_MOTION_CONTENT_OPACITY_PROPERTY]: [1, 0, 0],
77
76
  scale: 0.5,
78
77
  transition: prefersReducedMotion ? {duration: 0} : {duration: 0.2},
79
78
  },
@@ -86,7 +85,7 @@ export function ToastProvider(props: ToastProviderProps): React.ReactElement {
86
85
  // Wrap setState in startTransition to allow React to give input state updates higher priority
87
86
  const setState: typeof _setState = (state) => startTransition(() => _setState(state))
88
87
 
89
- const id = params.id || String(toastId++)
88
+ const id = params.id || generateToastId()
90
89
  const duration = params.duration || 5000
91
90
 
92
91
  const dismiss = () => {
@@ -0,0 +1,6 @@
1
+ let toastId = 0
2
+
3
+ /** @internal */
4
+ export function generateToastId(): string {
5
+ return String(toastId++)
6
+ }
@@ -70,8 +70,11 @@ export const TreeItem = memo(function TreeItem(
70
70
  const {path, registerItem, setExpanded, setFocusedElement} = tree
71
71
  const _id = useId()
72
72
  const id = idProp || _id
73
- const itemPath = useMemo(() => path.concat([id || '']), [id, path])
74
- const itemKey = itemPath.join('/')
73
+ const [itemPath, itemKey] = useMemo(() => {
74
+ const result = path.concat([id || ''])
75
+
76
+ return [result, result.join('/')]
77
+ }, [id, path])
75
78
  const itemState = tree.state[itemKey]
76
79
  const focused = tree.focusedElement === rootElement
77
80
  const expanded = itemState?.expanded === undefined ? expandedProp : itemState?.expanded || false
@@ -1,6 +1,5 @@
1
1
  /* eslint-disable @typescript-eslint/no-explicit-any */
2
2
  import {
3
- Middleware,
4
3
  RootBoundary,
5
4
  arrow,
6
5
  autoUpdate,
@@ -171,7 +170,7 @@ export const Popover = memo(
171
170
  const widthArrayProp = useArrayProp(widthProp)
172
171
  const zOffset = useArrayProp(zOffsetProp)
173
172
  const ref = useRef<HTMLDivElement | null>(null)
174
- const arrowRef = useRef<HTMLDivElement | null>(null)
173
+ const [arrowElement, setArrowElement] = useState<HTMLDivElement | null>(null)
175
174
  const rootBoundary: RootBoundary = 'viewport'
176
175
 
177
176
  useImperativeHandle<HTMLDivElement | null, HTMLDivElement | null>(
@@ -182,94 +181,70 @@ export const Popover = memo(
182
181
  const mediaIndex = useMediaIndex()
183
182
  const boundaryWidth = constrainSize || preventOverflow ? boundarySize?.width : undefined
184
183
 
185
- // Update width when
186
- // - media index changes
187
- // - `width` property changes
188
- const width = calcCurrentWidth({
189
- container,
190
- mediaIndex,
191
- width: widthArrayProp,
192
- })
193
- const widthRef = useRef(width)
194
-
195
- useEffect(() => {
196
- widthRef.current = width
197
- }, [width])
198
-
199
- // Update max width when
200
- // - boundary width changes
201
- // - `width` property changes
202
- const maxWidth = calcMaxWidth({boundaryWidth, currentWidth: width})
203
- const maxWidthRef = useRef(maxWidth)
204
-
205
- useEffect(() => {
206
- maxWidthRef.current = maxWidth
207
- }, [maxWidth])
208
-
209
- // Keep track of reference element width (see `size` middleware below)
210
- const referenceWidthRef = useRef<number>()
211
-
212
184
  // Force apply width & max width to floating element
213
185
  useLayoutEffect(() => {
214
186
  const floatingElement = ref.current
215
187
 
216
- if (!open || !floatingElement) return
188
+ // If constrainSize or matchReferenceWidth is true, then the styles are set by the `size` middleware
189
+ if (!open || !floatingElement || constrainSize || matchReferenceWidth) return
217
190
 
218
- const referenceWidth = referenceWidthRef.current
191
+ const currentWidth = calcCurrentWidth({
192
+ container,
193
+ mediaIndex,
194
+ width: widthArrayProp,
195
+ })
196
+ const maxWidth = calcMaxWidth({boundaryWidth, currentWidth})
219
197
 
220
- if (matchReferenceWidth) {
221
- if (referenceWidthRef.current !== undefined) {
222
- floatingElement.style.width = `${referenceWidth}px`
223
- }
224
- } else if (width !== undefined) {
225
- floatingElement.style.width = `${width}px`
198
+ if (currentWidth !== undefined) {
199
+ floatingElement.style.width = `${currentWidth}px`
226
200
  }
227
201
 
228
202
  if (typeof maxWidth === 'number') {
229
203
  floatingElement.style.maxWidth = `${maxWidth}px`
230
204
  }
231
- }, [width, matchReferenceWidth, maxWidth, open])
232
-
233
- const middleware = useMemo(() => {
234
- const ret: Middleware[] = []
205
+ }, [
206
+ boundaryWidth,
207
+ constrainSize,
208
+ container,
209
+ matchReferenceWidth,
210
+ mediaIndex,
211
+ open,
212
+ widthArrayProp,
213
+ ])
235
214
 
236
- // Flip the floating element when leaving the boundary box
237
- if (constrainSize || preventOverflow) {
238
- ret.push(
215
+ const {x, y, middlewareData, placement, refs, strategy, update} = useFloating({
216
+ middleware: [
217
+ // Flip the floating element when leaving the boundary box
218
+ (constrainSize || preventOverflow) &&
239
219
  flip({
240
220
  boundary: floatingBoundary || undefined,
241
221
  fallbackPlacements,
242
222
  padding: DEFAULT_POPOVER_PADDING,
243
223
  rootBoundary,
244
224
  }),
245
- )
246
- }
247
-
248
- // Define distance between reference and floating element
249
- ret.push(offset({mainAxis: DEFAULT_POPOVER_DISTANCE}))
250
-
251
- // Track sizes
252
- if (constrainSize || matchReferenceWidth) {
253
- ret.push(
225
+ // Define distance between reference and floating element
226
+ offset({mainAxis: DEFAULT_POPOVER_DISTANCE}),
227
+ // Track sizes
228
+ (constrainSize || matchReferenceWidth) &&
254
229
  size({
255
230
  apply({availableWidth, availableHeight, elements, referenceWidth}) {
256
- // not fresh, so use refs
257
-
258
- referenceWidthRef.current = referenceWidth
259
-
260
- const _currentWidth = widthRef.current
261
- const _maxWidth = maxWidthRef.current
231
+ const currentWidth = calcCurrentWidth({
232
+ container,
233
+ mediaIndex,
234
+ width: widthArrayProp,
235
+ })
236
+ const maxWidth = calcMaxWidth({boundaryWidth, currentWidth})
262
237
 
263
238
  if (matchReferenceWidth) {
264
239
  elements.floating.style.width = `${referenceWidth}px`
265
- } else if (_currentWidth !== undefined) {
266
- elements.floating.style.width = `${_currentWidth}px`
240
+ } else if (currentWidth !== undefined) {
241
+ elements.floating.style.width = `${currentWidth}px`
267
242
  }
268
243
 
269
244
  if (constrainSize) {
270
245
  elements.floating.style.maxWidth = `${Math.min(
271
246
  availableWidth,
272
- _maxWidth ?? Infinity,
247
+ maxWidth ?? Infinity,
273
248
  )}px`
274
249
 
275
250
  elements.floating.style.maxHeight = `${availableHeight}px`
@@ -281,59 +256,28 @@ export const Popover = memo(
281
256
  matchReferenceWidth,
282
257
  padding: DEFAULT_POPOVER_PADDING,
283
258
  }),
284
- )
285
- }
286
-
287
- // Shift the popover so its sits within the boundary element
288
- if (preventOverflow) {
289
- ret.push(
259
+ // Shift the popover so its sits within the boundary element
260
+ preventOverflow &&
290
261
  shift({
291
262
  boundary: floatingBoundary || undefined,
292
263
  rootBoundary,
293
264
  padding: DEFAULT_POPOVER_PADDING,
294
265
  }),
295
- )
296
- }
297
-
298
- // Place arrow
299
- if (arrowProp) {
300
- ret.push(
266
+ // Place arrow
267
+ arrowProp &&
301
268
  arrow({
302
- element: arrowRef,
269
+ element: arrowElement,
303
270
  padding: DEFAULT_POPOVER_PADDING,
304
271
  }),
305
- )
306
- }
307
-
308
- // Determine the origin to scale from.
309
- // Must be placed after `@sanity/ui/size` and `shift` middleware.
310
- if (animate) {
311
- ret.push(origin)
312
- }
313
-
314
- ret.push(
272
+ // Determine the origin to scale from.
273
+ // Must be placed after `@sanity/ui/size` and `shift` middleware.
274
+ animate && origin,
315
275
  hide({
316
276
  boundary: referenceBoundary || undefined,
317
277
  padding: DEFAULT_POPOVER_PADDING,
318
278
  strategy: 'referenceHidden',
319
279
  }),
320
- )
321
-
322
- return ret
323
- }, [
324
- animate,
325
- arrowProp,
326
- constrainSize,
327
- fallbackPlacements,
328
- floatingBoundary,
329
- margins,
330
- matchReferenceWidth,
331
- preventOverflow,
332
- referenceBoundary,
333
- ])
334
-
335
- const {x, y, middlewareData, placement, refs, strategy, update} = useFloating({
336
- middleware,
280
+ ],
337
281
  placement: placementProp,
338
282
  whileElementsMounted: autoUpdate,
339
283
  })
@@ -346,10 +290,6 @@ export const Popover = memo(
346
290
  const originX = middlewareData['@sanity/ui/origin']?.originX
347
291
  const originY = middlewareData['@sanity/ui/origin']?.originY
348
292
 
349
- const setArrow = useCallback((arrowEl: HTMLDivElement | null) => {
350
- arrowRef.current = arrowEl
351
- }, [])
352
-
353
293
  const setFloating = useCallback(
354
294
  (node: HTMLDivElement | null) => {
355
295
  ref.current = node
@@ -393,7 +333,7 @@ export const Popover = memo(
393
333
  __unstable_margins={margins}
394
334
  animate={animate}
395
335
  arrow={arrowProp}
396
- arrowRef={setArrow}
336
+ arrowRef={setArrowElement}
397
337
  arrowX={arrowX}
398
338
  arrowY={arrowY}
399
339
  hidden={referenceHidden}
@@ -408,7 +348,6 @@ export const Popover = memo(
408
348
  originY={originY}
409
349
  strategy={strategy}
410
350
  tone={tone}
411
- width={matchReferenceWidth ? referenceWidthRef.current : width}
412
351
  x={x}
413
352
  y={y}
414
353
  >
@@ -51,7 +51,6 @@ export const PopoverCard = memo(
51
51
  shadow?: number | number[]
52
52
  strategy: Strategy
53
53
  tone: CardTone
54
- width: number | undefined
55
54
  x: number | null
56
55
  y: number | null
57
56
  } & Omit<React.HTMLProps<HTMLDivElement>, 'as' | 'height' | 'width'>,
@@ -76,7 +75,6 @@ export const PopoverCard = memo(
76
75
  strategy,
77
76
  style,
78
77
  tone,
79
- width,
80
78
  x: xProp,
81
79
  y: yProp,
82
80
  ...restProps
@@ -101,12 +99,11 @@ export const PopoverCard = memo(
101
99
  originY,
102
100
  position: strategy,
103
101
  top: y,
104
- width,
105
102
  zIndex,
106
103
  willChange: animate ? 'transform' : undefined,
107
104
  ...style,
108
105
  }),
109
- [animate, originX, originY, strategy, style, width, x, y, zIndex],
106
+ [animate, originX, originY, strategy, style, x, y, zIndex],
110
107
  )
111
108
 
112
109
  const arrowStyle: CSSProperties = useMemo(
@@ -1,4 +1,4 @@
1
- import {forwardRef, useCallback, useImperativeHandle, useMemo, useRef, useState} from 'react'
1
+ import {forwardRef, useImperativeHandle, useMemo, useState} from 'react'
2
2
  import {useElementSize} from '../../hooks'
3
3
  import {useTheme_v2} from '../../theme'
4
4
  import {findMaxBreakpoints, findMinBreakpoints} from './helpers'
@@ -24,29 +24,27 @@ export const ElementQuery = forwardRef(function ElementQuery(
24
24
  const {children, media: _media, ...restProps} = props
25
25
  const media = _media ?? theme.media
26
26
 
27
- const ref = useRef<HTMLDivElement | null>(null)
28
27
  const [element, setElement] = useState<HTMLDivElement | null>(null)
29
28
  const elementSize = useElementSize(element)
30
29
  const width = useMemo(() => elementSize?.border.width ?? window.innerWidth, [elementSize])
31
30
 
32
- const max = useMemo(() => findMaxBreakpoints(media, width), [media, width])
33
- const min = useMemo(() => findMinBreakpoints(media, width), [media, width])
31
+ const max = useMemo(() => {
32
+ const eq = findMaxBreakpoints(media, width)
34
33
 
35
- useImperativeHandle<HTMLDivElement | null, HTMLDivElement | null>(forwardedRef, () => ref.current)
34
+ return eq.length ? eq.join(' ') : undefined
35
+ }, [media, width])
36
+ const min = useMemo(() => {
37
+ const eq = findMinBreakpoints(media, width)
36
38
 
37
- const setRef = useCallback((el: HTMLDivElement | null) => {
38
- ref.current = el
39
- setElement(el)
40
- }, [])
39
+ return eq.length ? eq.join(' ') : undefined
40
+ }, [media, width])
41
+
42
+ useImperativeHandle<HTMLDivElement | null, HTMLDivElement | null>(forwardedRef, () => element, [
43
+ element,
44
+ ])
41
45
 
42
46
  return (
43
- <div
44
- data-ui="ElementQuery"
45
- {...restProps}
46
- data-eq-max={max.length ? max.join(' ') : undefined}
47
- data-eq-min={min.length ? min.join(' ') : undefined}
48
- ref={setRef}
49
- >
47
+ <div data-ui="ElementQuery" {...restProps} data-eq-max={max} data-eq-min={min} ref={setElement}>
50
48
  {children}
51
49
  </div>
52
50
  )
@@ -85,7 +85,7 @@ export function LayerProvider(props: LayerProviderProps): React.ReactElement {
85
85
  parentDispose?.()
86
86
  }
87
87
  },
88
- [parentRegisterChild],
88
+ [parentRegisterChild, setSize, setChildLayers],
89
89
  )
90
90
 
91
91
  // Register this layer on mount