Repository navigation
SlotFill: unify registry and fill implementation #68056
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
This file was deleted.
This file was deleted.
This file was deleted.
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,16 +1,42 @@ | ||
| /** | ||
| * WordPress dependencies | ||
| */ | ||
| import { useContext } from '@wordpress/element'; | ||
| import { useObservableValue } from '@wordpress/compose'; | ||
| import { useContext, useMemo, useSyncExternalStore } from '@wordpress/element'; | ||
| import type { ObservableMap } from '@wordpress/compose'; | ||
|
|
||
| /** | ||
| * Internal dependencies | ||
| */ | ||
| import SlotFillContext from './slot-fill-context'; | ||
| import SlotFillContext from '../context'; | ||
| import type { SlotKey } from '../types'; | ||
|
|
||
| function useObservableValueWithSelector< K, V, S >( | ||
| map: ObservableMap< K, V >, | ||
| name: K, | ||
| selector: ( v: V | undefined ) => S | ||
| ) { | ||
| const subscribe = useMemo( | ||
| () => ( listener: () => void ) => map.subscribe( name, listener ), | ||
| [ map, name ] | ||
| ); | ||
| const getValue = () => selector( map.get( name ) ); | ||
| return useSyncExternalStore( subscribe, getValue, getValue ); | ||
| } | ||
|
|
||
| function getLength< T >( array: T[] | undefined ) { | ||
| return array?.length; | ||
| } | ||
|
|
||
| export default function useSlotFills( name: SlotKey ) { | ||
| const registry = useContext( SlotFillContext ); | ||
| return useObservableValue( registry.fills, name ); | ||
| const length = useObservableValueWithSelector( | ||
| registry.fills, | ||
| name, | ||
| getLength | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Is observing the array length enough? Any concerns if the fills change but have the same length?
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Yes, the If you review usages of |
||
| ); | ||
| // callers expect an opaque array with length `length`, so create that array | ||
| const fills = useMemo( () => { | ||
| return length !== undefined ? Array.from( { length } ) : undefined; | ||
| }, [ length ] ); | ||
|
Comment on lines
+38
to
+40
|
||
| return fills; | ||
| } | ||
Uh oh!
There was an error while loading. Please reload this page.