{"version":3,"file":"collection.mjs","sources":["../src/collection/Collection.ts"],"sourcesContent":["import { createContext, type MutableRefObject } from '../hooks/index.ts'\n\nexport const DATA_COLLECTION_ITEM = 'data-radix-collection-item'\n\nexport interface CollectionItemAttrs {\n  [DATA_COLLECTION_ITEM]: true\n}\n\nexport type CollectionItemWithData<E extends HTMLElement, D> = E & {\n  $$rcid: D\n}\n\nexport interface CollectionContext {\n  collectionRef: MutableRefObject<HTMLElement | undefined>\n}\n\nexport function createCollection<ItemElement extends HTMLElement, ItemData extends Record<string, any> = Record<string, any>>(name: string) {\n  const [_provideCollectionContext, useCollectionContext] = createContext<CollectionContext>(`${name}CollectionProvider`)\n\n  type CollectionItem = CollectionItemWithData<ItemElement, ItemData>\n\n  function provideCollectionContext(collectionRef: MutableRefObject<HTMLElement | undefined>, provide = true) {\n    const context = {\n      collectionRef,\n    }\n\n    if (provide)\n      _provideCollectionContext(context)\n\n    return context\n  }\n\n  function useCollectionItem<K extends keyof ItemData>(currentElement: ItemElement | undefined, attrs: ItemData[K], key: K) {\n    if (!key)\n      return\n\n    const unrefElement = currentElement as Record<string, any> | CollectionItem | undefined\n    if (!unrefElement)\n      return\n\n    if ('$$rcid' in unrefElement) {\n      if (key in unrefElement.$$rcid)\n        return\n\n      unrefElement.$$rcid[key] = attrs\n    }\n    else {\n      unrefElement.$$rcid = {\n        [key]: attrs,\n      }\n    }\n  }\n\n  function useCollection(thereContext?: CollectionContext) {\n    const context = thereContext || useCollectionContext(`${name}CollectionConsumer`)\n\n    function getItems(): CollectionItem[] {\n      if (!context.collectionRef.value)\n        return []\n\n      const orderedNodes = Array.from(context.collectionRef.value.querySelectorAll(`[${DATA_COLLECTION_ITEM}]:not([data-disabled])`))\n\n      return orderedNodes as CollectionItem[]\n    }\n\n    return getItems\n  }\n\n  return [\n    {\n      provideCollectionContext,\n      useCollectionContext,\n      useCollectionItem,\n    },\n    useCollection,\n  ] as const\n}\n"],"names":[],"mappings":";;AAEO,MAAM,oBAAuB,GA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