Skip to content

packages/core/src/lib/hooks/use-event-target.ts

Read as Markdown

This is the source snapshot used to build these API details. View this revision on GitHub.

Back to reference

1 import type {
2   PibblEventHandlers,
3   PibblEventTargetOptions,
4   PibblEventTargetSnapshot,
5 } from '../events/types.js';
6 import {
7   createTarget,
8   releaseTarget,
9   updateTarget,
10   type PibblEventTargetRegistration,
11 } from '../events/registrations.js';
12 import { GLOBAL_STATE } from '../global-state.js';
13 import { requireHookContext, useHookSlot } from './hook-slot.js';
14 
15 const UNFOCUSED_SNAPSHOT: PibblEventTargetSnapshot = Object.freeze({
16   isFocused: false,
17   isFocusVisible: false,
18 });
19 
20 /**
21  * Registers a logical event target and returns its current focus and interaction snapshot.
22  *
23  * @param handlers - Handlers for this logical event target. See {@link PibblEventHandlers}.
24  * @param options - Hit geometry, focus, and target participation options. See
25  * {@link PibblEventTargetOptions} .
26  * @returns The registered target's snapshot. See {@link PibblEventTargetSnapshot}.
27  *
28  * @see {@link PibblEventHandlers}
29  * @see {@link PibblEventTargetOptions}
30  * @see {@link PibblEventTargetSnapshot}
31  */
32 export function useEventTarget(
33   handlers: PibblEventHandlers,
34   options: PibblEventTargetOptions,
35 ): PibblEventTargetSnapshot {
36   const { componentRefs, pibblInstance } = requireHookContext();
37   const hookIndex = GLOBAL_STATE.componentHookIndex;
38   const slot = useHookSlot<PibblEventTargetRegistration>(
39     'eventTarget',
40     teardowns => {
41       const target = createTarget(pibblInstance, componentRefs, hookIndex);
42       teardowns.add(() => releaseTarget(target));
43       return target;
44     },
45   );
46   const target = slot.value;
47   updateTarget(target, handlers, options);
48   return pibblInstance.eventRoot.focusPolicy?.snapshot(target) ??
49     UNFOCUSED_SNAPSHOT;
50 }
51 

Documentation built with @pibbl/core 0.0.2, revision 272a94a. ALPHA — NOT FOR PRODUCTION USE.