UNPKG

@lobehub/ui

Version:

Lobe UI is an open-source UI component library for building AIGC web apps

1 lines • 1.82 kB
{"version":3,"file":"useStoreSelector.mjs","names":[],"sources":["../../../src/base-ui/FormKit/useStoreSelector.ts"],"sourcesContent":["import { useCallback, useRef, useSyncExternalStore } from 'react';\n\nimport type { FormEngine } from './engine/types';\n\nexport const shallowEqual = (a: unknown, b: unknown) => {\n if (Object.is(a, b)) return true;\n if (typeof a !== 'object' || typeof b !== 'object' || a === null || b === null) return false;\n const keysA = Object.keys(a);\n if (keysA.length !== Object.keys(b).length) return false;\n return keysA.every((key) => Object.is((a as any)[key], (b as any)[key]));\n};\n\nexport const useStoreSelector = <S>(engine: FormEngine, select: (engine: FormEngine) => S): S => {\n const selectRef = useRef(select);\n selectRef.current = select;\n const cache = useRef<{ value: S } | null>(null);\n\n const getSnapshot = useCallback(() => {\n const next = selectRef.current(engine);\n if (cache.current && shallowEqual(cache.current.value, next)) return cache.current.value;\n cache.current = { value: next };\n return next;\n }, [engine]);\n\n return useSyncExternalStore(engine.subscribe, getSnapshot, getSnapshot);\n};\n"],"mappings":";;AAIA,MAAa,gBAAgB,GAAY,MAAe;CACtD,IAAI,OAAO,GAAG,GAAG,CAAC,GAAG,OAAO;CAC5B,IAAI,OAAO,MAAM,YAAY,OAAO,MAAM,YAAY,MAAM,QAAQ,MAAM,MAAM,OAAO;CACvF,MAAM,QAAQ,OAAO,KAAK,CAAC;CAC3B,IAAI,MAAM,WAAW,OAAO,KAAK,CAAC,CAAC,CAAC,QAAQ,OAAO;CACnD,OAAO,MAAM,OAAO,QAAQ,OAAO,GAAI,EAAU,MAAO,EAAU,IAAI,CAAC;AACzE;AAEA,MAAa,oBAAuB,QAAoB,WAAyC;CAC/F,MAAM,YAAY,OAAO,MAAM;CAC/B,UAAU,UAAU;CACpB,MAAM,QAAQ,OAA4B,IAAI;CAE9C,MAAM,cAAc,kBAAkB;EACpC,MAAM,OAAO,UAAU,QAAQ,MAAM;EACrC,IAAI,MAAM,WAAW,aAAa,MAAM,QAAQ,OAAO,IAAI,GAAG,OAAO,MAAM,QAAQ;EACnF,MAAM,UAAU,EAAE,OAAO,KAAK;EAC9B,OAAO;CACT,GAAG,CAAC,MAAM,CAAC;CAEX,OAAO,qBAAqB,OAAO,WAAW,aAAa,WAAW;AACxE"}