@wordpress/compose 5.5.0 → 5.8.0

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.
Files changed (56) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/README.md +35 -9
  3. package/build/hooks/use-copy-to-clipboard/index.js +1 -1
  4. package/build/hooks/use-copy-to-clipboard/index.js.map +1 -1
  5. package/build/hooks/use-disabled/index.js +114 -42
  6. package/build/hooks/use-disabled/index.js.map +1 -1
  7. package/build/hooks/use-focus-on-mount/index.js +6 -1
  8. package/build/hooks/use-focus-on-mount/index.js.map +1 -1
  9. package/build/hooks/use-ref-effect/index.js.map +1 -1
  10. package/build/hooks/use-resize-observer/index.js +224 -13
  11. package/build/hooks/use-resize-observer/index.js.map +1 -1
  12. package/build/hooks/use-resize-observer/index.native.js +0 -2
  13. package/build/hooks/use-resize-observer/index.native.js.map +1 -1
  14. package/build/index.js +6 -6
  15. package/build/index.js.map +1 -1
  16. package/build/index.native.js +8 -0
  17. package/build/index.native.js.map +1 -1
  18. package/build-module/hooks/use-copy-to-clipboard/index.js +1 -1
  19. package/build-module/hooks/use-copy-to-clipboard/index.js.map +1 -1
  20. package/build-module/hooks/use-disabled/index.js +110 -40
  21. package/build-module/hooks/use-disabled/index.js.map +1 -1
  22. package/build-module/hooks/use-focus-on-mount/index.js +6 -1
  23. package/build-module/hooks/use-focus-on-mount/index.js.map +1 -1
  24. package/build-module/hooks/use-ref-effect/index.js.map +1 -1
  25. package/build-module/hooks/use-resize-observer/index.js +226 -9
  26. package/build-module/hooks/use-resize-observer/index.js.map +1 -1
  27. package/build-module/hooks/use-resize-observer/index.native.js +0 -2
  28. package/build-module/hooks/use-resize-observer/index.native.js.map +1 -1
  29. package/build-module/index.js +1 -1
  30. package/build-module/index.js.map +1 -1
  31. package/build-module/index.native.js +1 -0
  32. package/build-module/index.native.js.map +1 -1
  33. package/build-types/higher-order/if-condition/index.d.ts +0 -1
  34. package/build-types/higher-order/if-condition/index.d.ts.map +1 -1
  35. package/build-types/higher-order/with-instance-id/index.d.ts +0 -1
  36. package/build-types/higher-order/with-instance-id/index.d.ts.map +1 -1
  37. package/build-types/hooks/use-disabled/index.d.ts +7 -3
  38. package/build-types/hooks/use-disabled/index.d.ts.map +1 -1
  39. package/build-types/hooks/use-focus-on-mount/index.d.ts.map +1 -1
  40. package/build-types/hooks/use-ref-effect/index.d.ts +1 -1
  41. package/build-types/hooks/use-ref-effect/index.d.ts.map +1 -1
  42. package/build-types/hooks/use-resize-observer/index.d.ts +32 -2
  43. package/build-types/hooks/use-resize-observer/index.d.ts.map +1 -1
  44. package/build-types/index.d.ts +1 -1
  45. package/package.json +8 -9
  46. package/src/hooks/use-copy-to-clipboard/index.js +1 -1
  47. package/src/hooks/use-disabled/index.js +141 -51
  48. package/src/hooks/use-focus-on-mount/index.js +6 -1
  49. package/src/hooks/use-ref-effect/index.ts +2 -2
  50. package/src/hooks/use-resize-observer/index.native.js +0 -2
  51. package/src/hooks/use-resize-observer/index.tsx +362 -0
  52. package/src/index.js +1 -1
  53. package/src/index.native.js +1 -0
  54. package/tsconfig.json +2 -4
  55. package/tsconfig.tsbuildinfo +1 -1
  56. package/src/hooks/use-resize-observer/index.js +0 -31
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wordpress/compose",
3
- "version": "5.5.0",
3
+ "version": "5.8.0",
4
4
  "description": "WordPress higher-order components (HOCs).",
5
5
  "author": "The WordPress Contributors",
6
6
  "license": "GPL-2.0-or-later",
@@ -32,16 +32,15 @@
32
32
  "@babel/runtime": "^7.16.0",
33
33
  "@types/lodash": "^4.14.172",
34
34
  "@types/mousetrap": "^1.6.8",
35
- "@wordpress/deprecated": "^3.7.0",
36
- "@wordpress/dom": "^3.7.0",
37
- "@wordpress/element": "^4.5.0",
38
- "@wordpress/is-shallow-equal": "^4.7.0",
39
- "@wordpress/keycodes": "^3.7.0",
40
- "@wordpress/priority-queue": "^2.7.0",
35
+ "@wordpress/deprecated": "^3.10.0",
36
+ "@wordpress/dom": "^3.10.0",
37
+ "@wordpress/element": "^4.8.0",
38
+ "@wordpress/is-shallow-equal": "^4.10.0",
39
+ "@wordpress/keycodes": "^3.10.0",
40
+ "@wordpress/priority-queue": "^2.10.0",
41
41
  "clipboard": "^2.0.8",
42
42
  "lodash": "^4.17.21",
43
43
  "mousetrap": "^1.6.5",
44
- "react-resize-aware": "^3.1.0",
45
44
  "use-memo-one": "^1.1.1"
46
45
  },
47
46
  "peerDependencies": {
@@ -50,5 +49,5 @@
50
49
  "publishConfig": {
51
50
  "access": "public"
52
51
  },
53
- "gitHead": "1ba52312b56db563df2d8d4fba5b00613fb46d8c"
52
+ "gitHead": "a3e0b62091e8a8bdf5e2518e42d60d7098af48cc"
54
53
  }
@@ -35,7 +35,7 @@ function useUpdatedRef( value ) {
35
35
  * @return {import('react').Ref<TElementType>} A ref to assign to the target element.
36
36
  */
37
37
  export default function useCopyToClipboard( text, onSuccess ) {
38
- // Store the dependencies as refs and continuesly update them so they're
38
+ // Store the dependencies as refs and continuously update them so they're
39
39
  // fresh when the callback is called.
40
40
  const textRef = useUpdatedRef( text );
41
41
  const onSuccessRef = useUpdatedRef( onSuccess );
@@ -6,9 +6,13 @@ import { includes, debounce } from 'lodash';
6
6
  /**
7
7
  * WordPress dependencies
8
8
  */
9
- import { useCallback, useLayoutEffect, useRef } from '@wordpress/element';
10
9
  import { focus } from '@wordpress/dom';
11
10
 
11
+ /**
12
+ * Internal dependencies
13
+ */
14
+ import useRefEffect from '../use-ref-effect';
15
+
12
16
  /**
13
17
  * Names of control nodes which qualify for disabled behavior.
14
18
  *
@@ -33,11 +37,13 @@ const DISABLED_ELIGIBLE_NODE_NAMES = [
33
37
  * (input fields, links, buttons, etc.) need to be disabled. This hook adds the
34
38
  * behavior to disable nested DOM elements to the returned ref.
35
39
  *
36
- * @return {import('react').RefObject<HTMLElement>} Element Ref.
40
+ * @param {Object} config Configuration object.
41
+ * @param {boolean=} config.isDisabled Whether the element should be disabled.
42
+ * @return {import('react').RefCallback<HTMLElement>} Element Ref.
37
43
  *
38
44
  * @example
39
45
  * ```js
40
- * import { __experimentalUseDisabled as useDisabled } from '@wordpress/compose';
46
+ * import { useDisabled } from '@wordpress/compose';
41
47
  * const DisabledExample = () => {
42
48
  * const disabledRef = useDisabled();
43
49
  * return (
@@ -49,65 +55,149 @@ const DISABLED_ELIGIBLE_NODE_NAMES = [
49
55
  * };
50
56
  * ```
51
57
  */
52
- export default function useDisabled() {
53
- /** @type {import('react').RefObject<HTMLElement>} */
54
- const node = useRef( null );
58
+ export default function useDisabled( {
59
+ isDisabled: isDisabledProp = false,
60
+ } = {} ) {
61
+ return useRefEffect(
62
+ ( node ) => {
63
+ if ( isDisabledProp ) {
64
+ return;
65
+ }
55
66
 
56
- const disable = () => {
57
- if ( ! node.current ) {
58
- return;
59
- }
67
+ /** A variable keeping track of the previous updates in order to restore them. */
68
+ /** @type {Function[]} */
69
+ const updates = [];
60
70
 
61
- focus.focusable.find( node.current ).forEach( ( focusable ) => {
62
- if (
63
- includes( DISABLED_ELIGIBLE_NODE_NAMES, focusable.nodeName )
64
- ) {
65
- focusable.setAttribute( 'disabled', '' );
66
- }
71
+ const disable = () => {
72
+ if ( node.style.getPropertyValue( 'user-select' ) !== 'none' ) {
73
+ const previousValue = node.style.getPropertyValue(
74
+ 'user-select'
75
+ );
76
+ node.style.setProperty( 'user-select', 'none' );
77
+ node.style.setProperty( '-webkit-user-select', 'none' );
78
+ updates.push( () => {
79
+ if ( ! node.isConnected ) {
80
+ return;
81
+ }
82
+ node.style.setProperty( 'user-select', previousValue );
83
+ node.style.setProperty(
84
+ '-webkit-user-select',
85
+ previousValue
86
+ );
87
+ } );
88
+ }
67
89
 
68
- if ( focusable.nodeName === 'A' ) {
69
- focusable.setAttribute( 'tabindex', '-1' );
70
- }
90
+ focus.focusable.find( node ).forEach( ( focusable ) => {
91
+ if (
92
+ includes(
93
+ DISABLED_ELIGIBLE_NODE_NAMES,
94
+ focusable.nodeName
95
+ ) &&
96
+ // @ts-ignore
97
+ ! focusable.disabled
98
+ ) {
99
+ focusable.setAttribute( 'disabled', '' );
100
+ updates.push( () => {
101
+ if ( ! focusable.isConnected ) {
102
+ return;
103
+ }
104
+ // @ts-ignore
105
+ focusable.disabled = false;
106
+ } );
107
+ }
71
108
 
72
- const tabIndex = focusable.getAttribute( 'tabindex' );
73
- if ( tabIndex !== null && tabIndex !== '-1' ) {
74
- focusable.removeAttribute( 'tabindex' );
75
- }
109
+ if (
110
+ focusable.nodeName === 'A' &&
111
+ focusable.getAttribute( 'tabindex' ) !== '-1'
112
+ ) {
113
+ const previousValue = focusable.getAttribute(
114
+ 'tabindex'
115
+ );
116
+ focusable.setAttribute( 'tabindex', '-1' );
117
+ updates.push( () => {
118
+ if ( ! focusable.isConnected ) {
119
+ return;
120
+ }
121
+ if ( ! previousValue ) {
122
+ focusable.removeAttribute( 'tabindex' );
123
+ } else {
124
+ focusable.setAttribute(
125
+ 'tabindex',
126
+ previousValue
127
+ );
128
+ }
129
+ } );
130
+ }
76
131
 
77
- if ( focusable.hasAttribute( 'contenteditable' ) ) {
78
- focusable.setAttribute( 'contenteditable', 'false' );
79
- }
80
- } );
81
- };
132
+ const tabIndex = focusable.getAttribute( 'tabindex' );
133
+ if ( tabIndex !== null && tabIndex !== '-1' ) {
134
+ focusable.removeAttribute( 'tabindex' );
135
+ updates.push( () => {
136
+ if ( ! focusable.isConnected ) {
137
+ return;
138
+ }
139
+ focusable.setAttribute( 'tabindex', tabIndex );
140
+ } );
141
+ }
82
142
 
83
- // Debounce re-disable since disabling process itself will incur
84
- // additional mutations which should be ignored.
85
- const debouncedDisable = useCallback(
86
- debounce( disable, undefined, { leading: true } ),
87
- []
88
- );
143
+ if (
144
+ focusable.hasAttribute( 'contenteditable' ) &&
145
+ focusable.getAttribute( 'contenteditable' ) !== 'false'
146
+ ) {
147
+ focusable.setAttribute( 'contenteditable', 'false' );
148
+ updates.push( () => {
149
+ if ( ! focusable.isConnected ) {
150
+ return;
151
+ }
152
+ focusable.setAttribute( 'contenteditable', 'true' );
153
+ } );
154
+ }
89
155
 
90
- useLayoutEffect( () => {
91
- disable();
156
+ if (
157
+ node.ownerDocument.defaultView?.HTMLElement &&
158
+ focusable instanceof
159
+ node.ownerDocument.defaultView.HTMLElement
160
+ ) {
161
+ const previousValue = focusable.style.getPropertyValue(
162
+ 'pointer-events'
163
+ );
164
+ focusable.style.setProperty( 'pointer-events', 'none' );
165
+ updates.push( () => {
166
+ if ( ! focusable.isConnected ) {
167
+ return;
168
+ }
169
+ focusable.style.setProperty(
170
+ 'pointer-events',
171
+ previousValue
172
+ );
173
+ } );
174
+ }
175
+ } );
176
+ };
177
+
178
+ // Debounce re-disable since disabling process itself will incur
179
+ // additional mutations which should be ignored.
180
+ const debouncedDisable = debounce( disable, undefined, {
181
+ leading: true,
182
+ } );
183
+ disable();
92
184
 
93
- /** @type {MutationObserver | undefined} */
94
- let observer;
95
- if ( node.current ) {
96
- observer = new window.MutationObserver( debouncedDisable );
97
- observer.observe( node.current, {
185
+ /** @type {MutationObserver | undefined} */
186
+ const observer = new window.MutationObserver( debouncedDisable );
187
+ observer.observe( node, {
98
188
  childList: true,
99
189
  attributes: true,
100
190
  subtree: true,
101
191
  } );
102
- }
103
192
 
104
- return () => {
105
- if ( observer ) {
106
- observer.disconnect();
107
- }
108
- debouncedDisable.cancel();
109
- };
110
- }, [] );
111
-
112
- return node;
193
+ return () => {
194
+ if ( observer ) {
195
+ observer.disconnect();
196
+ }
197
+ debouncedDisable.cancel();
198
+ updates.forEach( ( update ) => update() );
199
+ };
200
+ },
201
+ [ isDisabledProp ]
202
+ );
113
203
  }
@@ -50,6 +50,11 @@ export default function useFocusOnMount( focusOnMount = 'firstElement' ) {
50
50
  }
51
51
  }
52
52
 
53
- target.focus();
53
+ target.focus( {
54
+ // When focusing newly mounted dialogs,
55
+ // the position of the popover is often not right on the first render
56
+ // This prevents the layout shifts when focusing the dialogs.
57
+ preventScroll: true,
58
+ } );
54
59
  }, [] );
55
60
  }
@@ -28,10 +28,10 @@ import { useCallback, useRef } from '@wordpress/element';
28
28
  * @return Ref callback.
29
29
  */
30
30
  export default function useRefEffect< TElement = Node >(
31
- callback: ( node: TElement ) => ( () => void ) | undefined,
31
+ callback: ( node: TElement ) => ( () => void ) | void,
32
32
  dependencies: DependencyList
33
33
  ): RefCallback< TElement | null > {
34
- const cleanup = useRef< ( () => void ) | undefined >();
34
+ const cleanup = useRef< ( () => void ) | void >();
35
35
  return useCallback( ( node: TElement | null ) => {
36
36
  if ( node ) {
37
37
  cleanup.current = callback( node );
@@ -10,8 +10,6 @@ import { useState, useCallback } from '@wordpress/element';
10
10
  /**
11
11
  * Hook which allows to listen the resize event of any target element when it changes sizes.
12
12
  *
13
- * @return {[JSX.Element, { width: number, height: number } | null]} An array of {Element} `resizeListener` and {?Object} `sizes` with properties `width` and `height`
14
- *
15
13
  * @example
16
14
  *
17
15
  * ```js
@@ -0,0 +1,362 @@
1
+ /**
2
+ * External dependencies
3
+ */
4
+ import type { RefCallback, RefObject } from 'react';
5
+
6
+ /**
7
+ * WordPress dependencies
8
+ */
9
+ import {
10
+ useMemo,
11
+ useRef,
12
+ useCallback,
13
+ useEffect,
14
+ useState,
15
+ } from '@wordpress/element';
16
+ import type { WPElement } from '@wordpress/element';
17
+
18
+ type SubscriberCleanup = () => void;
19
+ type SubscriberResponse = SubscriberCleanup | void;
20
+
21
+ // This of course could've been more streamlined with internal state instead of
22
+ // refs, but then host hooks / components could not opt out of renders.
23
+ // This could've been exported to its own module, but the current build doesn't
24
+ // seem to work with module imports and I had no more time to spend on this...
25
+ function useResolvedElement< T extends HTMLElement >(
26
+ subscriber: ( element: T ) => SubscriberResponse,
27
+ refOrElement?: T | RefObject< T > | null
28
+ ): RefCallback< T > {
29
+ const callbackRefElement = useRef< T | null >( null );
30
+ const lastReportRef = useRef< {
31
+ reporter: () => void;
32
+ element: T | null;
33
+ } | null >( null );
34
+ const cleanupRef = useRef< SubscriberResponse | null >();
35
+
36
+ const callSubscriber = useCallback( () => {
37
+ let element = null;
38
+ if ( callbackRefElement.current ) {
39
+ element = callbackRefElement.current;
40
+ } else if ( refOrElement ) {
41
+ if ( refOrElement instanceof HTMLElement ) {
42
+ element = refOrElement;
43
+ } else {
44
+ element = refOrElement.current;
45
+ }
46
+ }
47
+
48
+ if (
49
+ lastReportRef.current &&
50
+ lastReportRef.current.element === element &&
51
+ lastReportRef.current.reporter === callSubscriber
52
+ ) {
53
+ return;
54
+ }
55
+
56
+ if ( cleanupRef.current ) {
57
+ cleanupRef.current();
58
+ // Making sure the cleanup is not called accidentally multiple times.
59
+ cleanupRef.current = null;
60
+ }
61
+ lastReportRef.current = {
62
+ reporter: callSubscriber,
63
+ element,
64
+ };
65
+
66
+ // Only calling the subscriber, if there's an actual element to report.
67
+ if ( element ) {
68
+ cleanupRef.current = subscriber( element );
69
+ }
70
+ }, [ refOrElement, subscriber ] );
71
+
72
+ // On each render, we check whether a ref changed, or if we got a new raw
73
+ // element.
74
+ useEffect( () => {
75
+ // With this we're *technically* supporting cases where ref objects' current value changes, but only if there's a
76
+ // render accompanying that change as well.
77
+ // To guarantee we always have the right element, one must use the ref callback provided instead, but we support
78
+ // RefObjects to make the hook API more convenient in certain cases.
79
+ callSubscriber();
80
+ }, [ callSubscriber ] );
81
+
82
+ return useCallback< RefCallback< T > >(
83
+ ( element ) => {
84
+ callbackRefElement.current = element;
85
+ callSubscriber();
86
+ },
87
+ [ callSubscriber ]
88
+ );
89
+ }
90
+
91
+ type ObservedSize = {
92
+ width: number | undefined;
93
+ height: number | undefined;
94
+ };
95
+
96
+ type ResizeHandler = ( size: ObservedSize ) => void;
97
+
98
+ type HookResponse< T extends HTMLElement > = {
99
+ ref: RefCallback< T >;
100
+ } & ObservedSize;
101
+
102
+ // Declaring my own type here instead of using the one provided by TS (available since 4.2.2), because this way I'm not
103
+ // forcing consumers to use a specific TS version.
104
+ type ResizeObserverBoxOptions =
105
+ | 'border-box'
106
+ | 'content-box'
107
+ | 'device-pixel-content-box';
108
+
109
+ declare global {
110
+ interface ResizeObserverEntry {
111
+ readonly devicePixelContentBoxSize: ReadonlyArray< ResizeObserverSize >;
112
+ }
113
+ }
114
+
115
+ // We're only using the first element of the size sequences, until future versions of the spec solidify on how
116
+ // exactly it'll be used for fragments in multi-column scenarios:
117
+ // From the spec:
118
+ // > The box size properties are exposed as FrozenArray in order to support elements that have multiple fragments,
119
+ // > which occur in multi-column scenarios. However the current definitions of content rect and border box do not
120
+ // > mention how those boxes are affected by multi-column layout. In this spec, there will only be a single
121
+ // > ResizeObserverSize returned in the FrozenArray, which will correspond to the dimensions of the first column.
122
+ // > A future version of this spec will extend the returned FrozenArray to contain the per-fragment size information.
123
+ // (https://drafts.csswg.org/resize-observer/#resize-observer-entry-interface)
124
+ //
125
+ // Also, testing these new box options revealed that in both Chrome and FF everything is returned in the callback,
126
+ // regardless of the "box" option.
127
+ // The spec states the following on this:
128
+ // > This does not have any impact on which box dimensions are returned to the defined callback when the event
129
+ // > is fired, it solely defines which box the author wishes to observe layout changes on.
130
+ // (https://drafts.csswg.org/resize-observer/#resize-observer-interface)
131
+ // I'm not exactly clear on what this means, especially when you consider a later section stating the following:
132
+ // > This section is non-normative. An author may desire to observe more than one CSS box.
133
+ // > In this case, author will need to use multiple ResizeObservers.
134
+ // (https://drafts.csswg.org/resize-observer/#resize-observer-interface)
135
+ // Which is clearly not how current browser implementations behave, and seems to contradict the previous quote.
136
+ // For this reason I decided to only return the requested size,
137
+ // even though it seems we have access to results for all box types.
138
+ // This also means that we get to keep the current api, being able to return a simple { width, height } pair,
139
+ // regardless of box option.
140
+ const extractSize = (
141
+ entry: ResizeObserverEntry,
142
+ boxProp: 'borderBoxSize' | 'contentBoxSize' | 'devicePixelContentBoxSize',
143
+ sizeType: keyof ResizeObserverSize
144
+ ): number | undefined => {
145
+ if ( ! entry[ boxProp ] ) {
146
+ if ( boxProp === 'contentBoxSize' ) {
147
+ // The dimensions in `contentBoxSize` and `contentRect` are equivalent according to the spec.
148
+ // See the 6th step in the description for the RO algorithm:
149
+ // https://drafts.csswg.org/resize-observer/#create-and-populate-resizeobserverentry-h
150
+ // > Set this.contentRect to logical this.contentBoxSize given target and observedBox of "content-box".
151
+ // In real browser implementations of course these objects differ, but the width/height values should be equivalent.
152
+ return entry.contentRect[
153
+ sizeType === 'inlineSize' ? 'width' : 'height'
154
+ ];
155
+ }
156
+
157
+ return undefined;
158
+ }
159
+
160
+ // A couple bytes smaller than calling Array.isArray() and just as effective here.
161
+ return entry[ boxProp ][ 0 ]
162
+ ? entry[ boxProp ][ 0 ][ sizeType ]
163
+ : // TS complains about this, because the RO entry type follows the spec and does not reflect Firefox's current
164
+ // behaviour of returning objects instead of arrays for `borderBoxSize` and `contentBoxSize`.
165
+ // @ts-ignore
166
+ entry[ boxProp ][ sizeType ];
167
+ };
168
+
169
+ type RoundingFunction = ( n: number ) => number;
170
+
171
+ function useResizeObserver< T extends HTMLElement >(
172
+ opts: {
173
+ ref?: RefObject< T > | T | null | undefined;
174
+ onResize?: ResizeHandler;
175
+ box?: ResizeObserverBoxOptions;
176
+ round?: RoundingFunction;
177
+ } = {}
178
+ ): HookResponse< T > {
179
+ // Saving the callback as a ref. With this, I don't need to put onResize in the
180
+ // effect dep array, and just passing in an anonymous function without memoising
181
+ // will not reinstantiate the hook's ResizeObserver.
182
+ const onResize = opts.onResize;
183
+ const onResizeRef = useRef< ResizeHandler | undefined >( undefined );
184
+ onResizeRef.current = onResize;
185
+ const round = opts.round || Math.round;
186
+
187
+ // Using a single instance throughout the hook's lifetime
188
+ const resizeObserverRef = useRef< {
189
+ box?: ResizeObserverBoxOptions;
190
+ round?: RoundingFunction;
191
+ instance: ResizeObserver;
192
+ } >();
193
+
194
+ const [ size, setSize ] = useState< {
195
+ width?: number;
196
+ height?: number;
197
+ } >( {
198
+ width: undefined,
199
+ height: undefined,
200
+ } );
201
+
202
+ // In certain edge cases the RO might want to report a size change just after
203
+ // the component unmounted.
204
+ const didUnmount = useRef( false );
205
+ useEffect( () => {
206
+ return () => {
207
+ didUnmount.current = true;
208
+ };
209
+ }, [] );
210
+
211
+ // Using a ref to track the previous width / height to avoid unnecessary renders.
212
+ const previous: {
213
+ current: {
214
+ width?: number;
215
+ height?: number;
216
+ };
217
+ } = useRef( {
218
+ width: undefined,
219
+ height: undefined,
220
+ } );
221
+
222
+ // This block is kinda like a useEffect, only it's called whenever a new
223
+ // element could be resolved based on the ref option. It also has a cleanup
224
+ // function.
225
+ const refCallback = useResolvedElement< T >(
226
+ useCallback(
227
+ ( element ) => {
228
+ // We only use a single Resize Observer instance, and we're instantiating it on demand, only once there's something to observe.
229
+ // This instance is also recreated when the `box` option changes, so that a new observation is fired if there was a previously observed element with a different box option.
230
+ if (
231
+ ! resizeObserverRef.current ||
232
+ resizeObserverRef.current.box !== opts.box ||
233
+ resizeObserverRef.current.round !== round
234
+ ) {
235
+ resizeObserverRef.current = {
236
+ box: opts.box,
237
+ round,
238
+ instance: new ResizeObserver( ( entries ) => {
239
+ const entry = entries[ 0 ];
240
+
241
+ let boxProp:
242
+ | 'borderBoxSize'
243
+ | 'contentBoxSize'
244
+ | 'devicePixelContentBoxSize' = 'borderBoxSize';
245
+ if ( opts.box === 'border-box' ) {
246
+ boxProp = 'borderBoxSize';
247
+ } else {
248
+ boxProp =
249
+ opts.box === 'device-pixel-content-box'
250
+ ? 'devicePixelContentBoxSize'
251
+ : 'contentBoxSize';
252
+ }
253
+
254
+ const reportedWidth = extractSize(
255
+ entry,
256
+ boxProp,
257
+ 'inlineSize'
258
+ );
259
+ const reportedHeight = extractSize(
260
+ entry,
261
+ boxProp,
262
+ 'blockSize'
263
+ );
264
+
265
+ const newWidth = reportedWidth
266
+ ? round( reportedWidth )
267
+ : undefined;
268
+ const newHeight = reportedHeight
269
+ ? round( reportedHeight )
270
+ : undefined;
271
+
272
+ if (
273
+ previous.current.width !== newWidth ||
274
+ previous.current.height !== newHeight
275
+ ) {
276
+ const newSize = {
277
+ width: newWidth,
278
+ height: newHeight,
279
+ };
280
+ previous.current.width = newWidth;
281
+ previous.current.height = newHeight;
282
+ if ( onResizeRef.current ) {
283
+ onResizeRef.current( newSize );
284
+ } else if ( ! didUnmount.current ) {
285
+ setSize( newSize );
286
+ }
287
+ }
288
+ } ),
289
+ };
290
+ }
291
+
292
+ resizeObserverRef.current.instance.observe( element, {
293
+ box: opts.box,
294
+ } );
295
+
296
+ return () => {
297
+ if ( resizeObserverRef.current ) {
298
+ resizeObserverRef.current.instance.unobserve( element );
299
+ }
300
+ };
301
+ },
302
+ [ opts.box, round ]
303
+ ),
304
+ opts.ref
305
+ );
306
+
307
+ return useMemo(
308
+ () => ( {
309
+ ref: refCallback,
310
+ width: size.width,
311
+ height: size.height,
312
+ } ),
313
+ [ refCallback, size ? size.width : null, size ? size.height : null ]
314
+ );
315
+ }
316
+
317
+ /**
318
+ * Hook which allows to listen the resize event of any target element when it changes sizes.
319
+ * _Note: `useResizeObserver` will report `null` until after first render.
320
+ *
321
+ * @example
322
+ *
323
+ * ```js
324
+ * const App = () => {
325
+ * const [ resizeListener, sizes ] = useResizeObserver();
326
+ *
327
+ * return (
328
+ * <div>
329
+ * { resizeListener }
330
+ * Your content here
331
+ * </div>
332
+ * );
333
+ * };
334
+ * ```
335
+ */
336
+ export default function useResizeAware(): [
337
+ WPElement,
338
+ { width: number | null; height: number | null }
339
+ ] {
340
+ const { ref, width, height } = useResizeObserver();
341
+ const sizes = useMemo( () => {
342
+ return { width: width ?? null, height: height ?? null };
343
+ }, [ width, height ] );
344
+ const resizeListener = (
345
+ <div
346
+ style={ {
347
+ position: 'absolute',
348
+ top: 0,
349
+ left: 0,
350
+ right: 0,
351
+ bottom: 0,
352
+ pointerEvents: 'none',
353
+ opacity: 0,
354
+ overflow: 'hidden',
355
+ zIndex: -1,
356
+ } }
357
+ aria-hidden="true"
358
+ ref={ ref }
359
+ />
360
+ );
361
+ return [ resizeListener, sizes ];
362
+ }
package/src/index.js CHANGED
@@ -17,7 +17,7 @@ export { default as useConstrainedTabbing } from './hooks/use-constrained-tabbin
17
17
  export { default as useCopyOnClick } from './hooks/use-copy-on-click';
18
18
  export { default as useCopyToClipboard } from './hooks/use-copy-to-clipboard';
19
19
  export { default as __experimentalUseDialog } from './hooks/use-dialog';
20
- export { default as __experimentalUseDisabled } from './hooks/use-disabled';
20
+ export { default as useDisabled } from './hooks/use-disabled';
21
21
  export { default as __experimentalUseDragging } from './hooks/use-dragging';
22
22
  export { default as useFocusOnMount } from './hooks/use-focus-on-mount';
23
23
  export { default as __experimentalUseFocusOutside } from './hooks/use-focus-outside';