{"version":3,"file":"useLazyDisposableState.mjs","names":[],"sources":["../src/useLazyDisposableState.ts"],"sourcesContent":["'use strict';\n\nimport type { ItemCleanupPair } from '@isograph/isograph-disposable-types';\nimport { useEffect, useRef } from 'react';\nimport type { ParentCache } from './ParentCache';\nimport { useCachedResponsivePrecommitValue } from './useCachedResponsivePrecommitValue';\nimport { type UnassignedState } from './useUpdatableDisposableState';\n\n/**\n * useLazyDisposableState<T>\n * - Takes a mutable parent cache and a factory function\n * - Returns { state: T }\n *\n * This lazily loads the disposable item using useCachedResponsivePrecommitValue, then\n * (on commit) sets it in state. The item continues to be returned after\n * commit and is disposed when the hook unmounts.\n */\nexport function useLazyDisposableState<T>(\n  parentCache: ParentCache<Exclude<T, UnassignedState>>,\n): {\n  state: T;\n} {\n  const itemCleanupPairRef = useRef<ItemCleanupPair<T> | null>(null);\n\n  const preCommitItem = useCachedResponsivePrecommitValue(\n    parentCache,\n    (pair) => {\n      itemCleanupPairRef.current?.[1]();\n      itemCleanupPairRef.current = pair;\n    },\n  );\n\n  useEffect(() => {\n    return () => {\n      const cleanupFn = itemCleanupPairRef.current?.[1];\n      // TODO confirm useEffect is called in order.\n      if (cleanupFn == null) {\n        throw new Error(\n          'cleanupFn unexpectedly null. This indicates a bug in react-disposable-state.',\n        );\n      }\n      return cleanupFn();\n    };\n  }, []);\n\n  const returnedItem = preCommitItem?.state ?? itemCleanupPairRef.current?.[0];\n\n  if (returnedItem != null) {\n    return { state: returnedItem };\n  }\n\n  // Safety: This can't happen. For renders before the initial commit, preCommitItem\n  // is non-null. During the initial commit, we assign itemCleanupPairRef.current,\n  // so during subsequent renders, itemCleanupPairRef.current is non-null.\n  throw new Error(\n    'returnedItem was unexpectedly null. This indicates a bug in react-disposable-state.',\n  );\n}\n"],"mappings":";;;;;;;;;;;;;AAiBA,SAAgB,uBACd,aAGA;CACA,MAAM,qBAAqB,OAAkC,KAAK;CAElE,MAAM,gBAAgB,kCACpB,cACC,SAAS;AACR,qBAAmB,UAAU,IAAI;AACjC,qBAAmB,UAAU;GAEhC;AAED,iBAAgB;AACd,eAAa;GACX,MAAM,YAAY,mBAAmB,UAAU;AAE/C,OAAI,aAAa,KACf,OAAM,IAAI,MACR,+EACD;AAEH,UAAO,WAAW;;IAEnB,EAAE,CAAC;CAEN,MAAM,eAAe,eAAe,SAAS,mBAAmB,UAAU;AAE1E,KAAI,gBAAgB,KAClB,QAAO,EAAE,OAAO,cAAc;AAMhC,OAAM,IAAI,MACR,sFACD"}