UNPKG

@workday/canvas-kit-react

Version:

The parent module that contains all Workday Canvas Kit React components

74 lines (73 loc) 3.28 kB
import React from 'react'; import { useMountLayout, createElemPropsHook, useLocalRef, useForkRef, slugify, } from '@workday/canvas-kit-react/common'; import { useListModel } from './useListModel'; /** * This elemProps hook is the base of all item component hooks. It registers an item with a * collection and sets the `data-id` that is used by other hooks. It should always be the last * defined hook when using `composeHooks` (`composeHooks` executes hooks right to left and merges * props left to right). It is used by `ListBox.Item` and all `*.Item` subcomponents. * * ```ts * const useMyItem = composeHooks( * useListItemSelect, // additional hooks go here * useListItemRegister // always last * ); * ``` */ export const useListItemRegister = createElemPropsHook(useListModel)(({ state, events }, ref, elemProps = {}) => { var _a, _b; const [localId, setLocalId] = React.useState(elemProps['data-id'] || ((_a = elemProps.item) === null || _a === void 0 ? void 0 : _a.id) || ''); const { localRef, elementRef } = useLocalRef(useForkRef(ref, (_b = elemProps.virtual) === null || _b === void 0 ? void 0 : _b.measureRef)); // if the list is virtual, force the correct styling. Without this, weird things happen... const style = elemProps.virtual ? { position: 'absolute', top: 0, left: 0, transform: `translateY(${elemProps.virtual.start}px)`, } : {}; useMountLayout(() => { var _a, _b; if (((_a = elemProps.virtual) === null || _a === void 0 ? void 0 : _a.index) === 0 && ((_b = localRef.current) === null || _b === void 0 ? void 0 : _b.clientHeight)) { // TODO: This update doesn't seem to be working correctly // events.updateItemHeight?.(localRef.current!.clientHeight); } // if an item is already provided, there's nothing left to do if (elemProps.item) { return; } const defaultId = state.indexRef.current; const itemId = localId || String(defaultId); // TODO: Better lookup that using `items.find`. We need a more generic collection to handle seeing if an item already exists // bail early if item already exists. This happens if items were already provided. if (state.items.find(item => item.id === itemId)) { return; } events.registerItem({ item: { id: itemId, }, textValue: elemProps['data-text'] ? elemProps['data-text'] : typeof elemProps.children === 'string' ? elemProps.children : '', }); setLocalId(itemId); return () => { events.unregisterItem({ id: itemId }); }; }); return { ref: elementRef, 'data-id': localId, disabled: elemProps.disabled || state.nonInteractiveIds.includes(localId) ? true : undefined, item: null, virtual: null, 'aria-setsize': elemProps.virtual ? state.UNSTABLE_virtual.totalSize : undefined, 'aria-posinset': elemProps.virtual ? elemProps.item.index + 1 : undefined, style, id: slugify(`${state.id}-${localId}`), }; });