|
1 | 1 | /** |
2 | 2 | * WordPress dependencies |
3 | 3 | */ |
4 | | -import { useContext } from '@wordpress/element'; |
5 | | -import { useObservableValue } from '@wordpress/compose'; |
| 4 | +import { useContext, useMemo, useSyncExternalStore } from '@wordpress/element'; |
| 5 | +import type { ObservableMap } from '@wordpress/compose'; |
6 | 6 |
|
7 | 7 | /** |
8 | 8 | * Internal dependencies |
9 | 9 | */ |
10 | 10 | import SlotFillContext from '../context'; |
11 | 11 | import type { SlotKey } from '../types'; |
12 | 12 |
|
| 13 | +function useObservableValueWithSelector< K, V, S >( |
| 14 | + map: ObservableMap< K, V >, |
| 15 | + name: K, |
| 16 | + selector: ( v: V | undefined ) => S |
| 17 | +) { |
| 18 | + const subscribe = useMemo( |
| 19 | + () => ( listener: () => void ) => map.subscribe( name, listener ), |
| 20 | + [ map, name ] |
| 21 | + ); |
| 22 | + const getValue = () => selector( map.get( name ) ); |
| 23 | + return useSyncExternalStore( subscribe, getValue, getValue ); |
| 24 | +} |
| 25 | + |
| 26 | +function getLength< T >( array: T[] | undefined ) { |
| 27 | + return array?.length; |
| 28 | +} |
| 29 | + |
13 | 30 | export default function useSlotFills( name: SlotKey ) { |
14 | 31 | const registry = useContext( SlotFillContext ); |
15 | | - return useObservableValue( registry.fills, name ); |
| 32 | + const length = useObservableValueWithSelector( |
| 33 | + registry.fills, |
| 34 | + name, |
| 35 | + getLength |
| 36 | + ); |
| 37 | + // callers expect an opaque array with length `length`, so create that array |
| 38 | + const fills = useMemo( () => { |
| 39 | + return length !== undefined ? Array.from( { length } ) : undefined; |
| 40 | + }, [ length ] ); |
| 41 | + return fills; |
16 | 42 | } |
0 commit comments