@mantine/store
Version:
A library to sync external React state updates
1 lines • 2.19 kB
Source Map (JSON)
{"version":3,"file":"store.cjs","names":[],"sources":["../src/store.ts"],"sourcesContent":["import { useSyncExternalStore } from 'react';\n\nexport type MantineStoreSubscriber<Value> = (value: Value) => void;\ntype SetStateCallback<Value> = (value: Value) => Value;\n\nexport interface MantineStore<Value> {\n getState: () => Value;\n setState: (value: Value | SetStateCallback<Value>) => void;\n updateState: (value: Value | SetStateCallback<Value>) => void;\n initialize: (value: Value) => void;\n subscribe: (callback: MantineStoreSubscriber<Value>) => () => void;\n}\n\nexport type MantineStoreValue<Store extends MantineStore<any>> = ReturnType<Store['getState']>;\n\nexport function createStore<Value extends Record<string, any>>(\n initialState: Value\n): MantineStore<Value> {\n let state = initialState;\n let initialized = false;\n const listeners = new Set<MantineStoreSubscriber<Value>>();\n\n return {\n getState() {\n return state;\n },\n\n updateState(value) {\n state = typeof value === 'function' ? value(state) : value;\n },\n\n setState(value) {\n this.updateState(value);\n listeners.forEach((listener) => listener(state));\n },\n\n initialize(value) {\n if (!initialized) {\n state = value;\n initialized = true;\n }\n },\n\n subscribe(callback) {\n listeners.add(callback);\n return () => listeners.delete(callback);\n },\n };\n}\n\nexport function useStore<Store extends MantineStore<any>>(store: Store) {\n return useSyncExternalStore<MantineStoreValue<Store>>(\n store.subscribe,\n () => store.getState(),\n () => store.getState()\n );\n}\n"],"mappings":";;;AAeA,SAAgB,YACd,cACqB;CACrB,IAAI,QAAQ;CACZ,IAAI,cAAc;CAClB,MAAM,4BAAY,IAAI,IAAmC;CAEzD,OAAO;EACL,WAAW;GACT,OAAO;EACT;EAEA,YAAY,OAAO;GACjB,QAAQ,OAAO,UAAU,aAAa,MAAM,KAAK,IAAI;EACvD;EAEA,SAAS,OAAO;GACd,KAAK,YAAY,KAAK;GACtB,UAAU,SAAS,aAAa,SAAS,KAAK,CAAC;EACjD;EAEA,WAAW,OAAO;GAChB,IAAI,CAAC,aAAa;IAChB,QAAQ;IACR,cAAc;GAChB;EACF;EAEA,UAAU,UAAU;GAClB,UAAU,IAAI,QAAQ;GACtB,aAAa,UAAU,OAAO,QAAQ;EACxC;CACF;AACF;AAEA,SAAgB,SAA0C,OAAc;CACtE,QAAA,GAAA,MAAA,sBACE,MAAM,iBACA,MAAM,SAAS,SACf,MAAM,SAAS,CACvB;AACF"}