@siberiacancode/reactuse 0.2.1 → 0.2.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/helpers/createContext/createContext.cjs +1 -1
- package/dist/cjs/helpers/createContext/createContext.cjs.map +1 -1
- package/dist/cjs/helpers/createReactiveContext/createReactiveContext.cjs +1 -1
- package/dist/cjs/helpers/createReactiveContext/createReactiveContext.cjs.map +1 -1
- package/dist/esm/helpers/createContext/createContext.mjs +3 -3
- package/dist/esm/helpers/createContext/createContext.mjs.map +1 -1
- package/dist/esm/helpers/createReactiveContext/createReactiveContext.mjs +6 -6
- package/dist/esm/helpers/createReactiveContext/createReactiveContext.mjs.map +1 -1
- package/dist/types/helpers/createContext/createContext.d.ts +1 -1
- package/dist/types/helpers/createReactiveContext/createReactiveContext.d.ts +2 -0
- package/package.json +13 -12
- package/LICENSE +0 -21
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const v=require("react/jsx-runtime"),n=require("react"),
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const v=require("react/jsx-runtime"),n=require("react"),x=(s=void 0,o={})=>{const t=n.createContext({value:s,set:()=>{}});t.displayName=o.name;function c(r){const e=n.useContext(t);if(!e&&o.strict)throw new Error(`Context hook ${o.name} must be used inside a Provider`);return r?r(e.value):e}return{useSelect:c,instance:t,Provider:({children:r,initialValue:e})=>{const[u,i]=n.useState(e??s),a=n.useMemo(()=>({value:u,set:i}),[u]);return v.jsx(t,{value:a,children:r})}}};exports.createContext=x;
|
|
2
2
|
//# sourceMappingURL=createContext.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createContext.cjs","sources":["../../../../src/helpers/createContext/createContext.tsx"],"sourcesContent":["import type { JSX, ReactNode } from 'react';\n\nimport { createContext as createReactContext,
|
|
1
|
+
{"version":3,"file":"createContext.cjs","sources":["../../../../src/helpers/createContext/createContext.tsx"],"sourcesContent":["import type { JSX, ReactNode } from 'react';\n\nimport { createContext as createReactContext, useContext, useMemo, useState } from 'react';\n\n/** The create context options type */\nexport interface CreateContextOptions {\n /** Display name for the context (useful for debugging) */\n name?: string;\n /** Whether to throw an error if context is used outside of Provider */\n strict?: boolean;\n}\n\n/** The context value type */\nexport interface ContextValue<Value> {\n /** The context value */\n value: Value | undefined;\n /** The context set function */\n set: (value: Value) => void;\n}\n\n/** The provider props type */\nexport interface ProviderProps<Value> {\n /** The children */\n children?: ReactNode;\n /** The initial value */\n initialValue?: Value;\n}\n\n/** The create context return type */\nexport interface CreateContextReturn<Value> {\n /** The context instance */\n instance: React.Context<ContextValue<Value>>;\n /** The provider component */\n Provider: (props: ProviderProps<Value>) => JSX.Element;\n /** The selector hook */\n useSelect: {\n <Selected>(selector: (value: Value) => Selected): Selected;\n (): ContextValue<Value>;\n };\n}\n\n/**\n * @name createContext\n * @description - Creates a typed context with additional utilities\n * @category Helpers\n *\n * @template Value - The type of value that will be stored in the context\n * @param {Value | undefined} [defaultValue] - Default value for the context\n * @param {CreateContextOptions<Value>} [options] - Additional options for context creation\n * @returns {CreateContextReturn<Value>} Object containing context utilities and components\n *\n * @example\n * const { useSelect, instance, Provider } = createContext<number>(0);\n */\nexport const createContext = <Value,>(\n defaultValue: Value | undefined = undefined,\n options: CreateContextOptions = {}\n): CreateContextReturn<Value> => {\n const Context = createReactContext<{\n value: Value | undefined;\n set: (value: Value) => void;\n }>({\n value: defaultValue,\n set: () => {}\n });\n\n Context.displayName = options.name;\n\n function useSelect(): ContextValue<Value>;\n function useSelect<Selected>(selector: (value: Value) => Selected): Selected;\n function useSelect<Selected>(selector?: (value: Value) => Selected) {\n const context = useContext(Context);\n\n if (!context && options.strict) {\n throw new Error(`Context hook ${options.name} must be used inside a Provider`);\n }\n\n if (!selector) {\n return context;\n }\n\n return selector(context.value as Value);\n }\n\n const Provider = ({ children, initialValue }: ProviderProps<Value>) => {\n const [profile, setProfile] = useState<Value | undefined>(initialValue ?? defaultValue);\n\n const value = useMemo(\n () => ({\n value: profile,\n set: setProfile\n }),\n [profile]\n );\n\n return <Context value={value}>{children}</Context>;\n };\n\n return {\n useSelect,\n instance: Context,\n Provider\n } as const;\n};\n"],"names":["createContext","defaultValue","options","Context","createReactContext","useSelect","selector","context","useContext","children","initialValue","profile","setProfile","useState","value","useMemo","jsx"],"mappings":"wIAsDaA,EAAgB,CAC3BC,EAAkC,OAClCC,EAAgC,CAAA,IACD,CAC/B,MAAMC,EAAUC,EAAAA,cAGb,CACD,MAAOH,EACP,IAAK,IAAM,CAAA,CAAC,CACb,EAEDE,EAAQ,YAAcD,EAAQ,KAI9B,SAASG,EAAoBC,EAAuC,CAC5D,MAAAC,EAAUC,aAAWL,CAAO,EAE9B,GAAA,CAACI,GAAWL,EAAQ,OACtB,MAAM,IAAI,MAAM,gBAAgBA,EAAQ,IAAI,iCAAiC,EAG/E,OAAKI,EAIEA,EAASC,EAAQ,KAAc,EAH7BA,CAG6B,CAiBjC,MAAA,CACL,UAAAF,EACA,SAAUF,EACV,SAjBe,CAAC,CAAE,SAAAM,EAAU,aAAAC,KAAyC,CACrE,KAAM,CAACC,EAASC,CAAU,EAAIC,EAAAA,SAA4BH,GAAgBT,CAAY,EAEhFa,EAAQC,EAAA,QACZ,KAAO,CACL,MAAOJ,EACP,IAAKC,CAAA,GAEP,CAACD,CAAO,CACV,EAEO,OAAAK,EAAA,IAACb,EAAQ,CAAA,MAAAW,EAAe,SAAAL,CAAS,CAAA,CAC1C,CAMA,CACF"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const r=require("react"),v=require("../../hooks/useIsomorphicLayoutEffect/useIsomorphicLayoutEffect.cjs"),d=require("../../hooks/useEvent/useEvent.cjs"),f=s=>e=>{const t=r.useRef(e.value),c=r.useMemo(()=>({value:t,listeners:new Set}),[]);return v.useIsomorphicLayoutEffect(()=>{Object.is(t.current,e.value)||(t.current=e.value,r.startTransition(()=>{c.listeners.forEach(u=>{u(t.current)})}))},[e.value]),r.createElement(s,{value:c},e.children)},m=(s,n,e={})=>{const t=r.
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const r=require("react"),v=require("../../hooks/useIsomorphicLayoutEffect/useIsomorphicLayoutEffect.cjs"),d=require("../../hooks/useEvent/useEvent.cjs"),f=s=>e=>{const t=r.useRef(e.value),c=r.useMemo(()=>({value:t,listeners:new Set}),[]);return v.useIsomorphicLayoutEffect(()=>{Object.is(t.current,e.value)||(t.current=e.value,r.startTransition(()=>{c.listeners.forEach(u=>{u(t.current)})}))},[e.value]),r.createElement(s,{value:c},e.children)},m=(s,n,e={})=>{const t=r.useContext(s);if(!t&&e.strict)throw new Error(`Context hook ${e.name} must be used inside a Provider`);const[c,u]=r.useState({selected:n(t.value.current),value:t.value.current}),o=d.useEvent(a=>{u(i=>{if(Object.is(i.value,a))return i;const l=n(a);return Object.is(i.selected,l)?i:{value:a,selected:l}})});return v.useIsomorphicLayoutEffect(()=>(t.listeners.add(o),()=>{t.listeners.delete(o)}),[t.listeners]),c.selected},x=(s=void 0,n={})=>{const e=r.createContext({value:{current:s},listeners:new Set}),t=f(e.Provider);e.displayName=n.name;function c(u){return m(e,u??(o=>o),n)}return{instance:e,Provider:t,useSelector:c}};exports.createReactiveContext=x;
|
|
2
2
|
//# sourceMappingURL=createReactiveContext.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createReactiveContext.cjs","sources":["../../../../src/helpers/createReactiveContext/createReactiveContext.ts"],"sourcesContent":["import type { Context, FC, Provider, ProviderProps, RefObject } from 'react';\n\nimport {\n createContext,\n createElement,\n startTransition,\n
|
|
1
|
+
{"version":3,"file":"createReactiveContext.cjs","sources":["../../../../src/helpers/createReactiveContext/createReactiveContext.ts"],"sourcesContent":["import type { Context, FC, Provider, ProviderProps, RefObject } from 'react';\n\nimport {\n createContext,\n createElement,\n startTransition,\n useContext,\n useMemo,\n useRef,\n useState\n} from 'react';\n\nimport { useEvent, useIsomorphicLayoutEffect } from '@/hooks';\n\n/** The create reactive context options type */\nexport interface CreateReactiveContextOptions {\n /** Display name for the context (useful for debugging) */\n name?: string;\n /** Whether to throw an error if context is used outside of Provider */\n strict?: boolean;\n}\n\n/** The create reactive context return type */\nexport interface CreateReactiveContextReturn<Value> {\n /** The context instance */\n instance: Context<ReactiveContextValue<Value>>;\n /** The Provider component for the context */\n Provider: Provider<Value>;\n /** A hook to select a part of the context state */\n useSelector: <Selected>(selector?: (state: Value) => Selected) => Selected;\n}\n\ntype ContextListener<Value> = (value: Value) => void;\n\ninterface ReactiveContextValue<Value> {\n /** The listeners for the context */\n listeners: Set<ContextListener<Value>>;\n /** The value for the context */\n value: RefObject<Value>;\n}\n\nconst createProvider = <Value>(originalProvider: Provider<ReactiveContextValue<Value>>) => {\n const Provider: FC<ProviderProps<Value>> = (props) => {\n const valueRef = useRef(props.value);\n const contextValue = useMemo<ReactiveContextValue<Value>>(\n () => ({\n value: valueRef,\n listeners: new Set()\n }),\n []\n );\n\n useIsomorphicLayoutEffect(() => {\n if (!Object.is(valueRef.current, props.value)) {\n valueRef.current = props.value;\n\n startTransition(() => {\n contextValue.listeners.forEach((listener) => {\n listener(valueRef.current);\n });\n });\n }\n }, [props.value]);\n\n return createElement(originalProvider, { value: contextValue }, props.children);\n };\n\n return Provider as unknown as Provider<ReactiveContextValue<Value>>;\n};\n\nconst createReactiveContextSelector = <Value, Selected>(\n Context: Context<ReactiveContextValue<Value>>,\n selector: (state: Value) => Selected,\n options: CreateReactiveContextOptions = {}\n) => {\n const context = useContext(Context);\n\n if (!context && options.strict) {\n throw new Error(`Context hook ${options.name} must be used inside a Provider`);\n }\n\n const [value, setValue] = useState({\n selected: selector(context.value.current),\n value: context.value.current\n });\n\n const dispatch = useEvent((newValue: Value) => {\n setValue((prevValue) => {\n if (Object.is(prevValue.value, newValue)) return prevValue;\n\n const newSelected = selector(newValue);\n if (Object.is(prevValue.selected, newSelected)) return prevValue;\n\n return { value: newValue, selected: newSelected };\n });\n });\n\n useIsomorphicLayoutEffect(() => {\n context.listeners.add(dispatch);\n return () => {\n context.listeners.delete(dispatch);\n };\n }, [context.listeners]);\n\n return value.selected;\n};\n\n/**\n * @name createReactiveContext\n * @description - Creates a typed context selector with optimized updates for state selection\n * @category Helpers\n *\n * @warning - For complex interfaces, we strongly recommend using state management solutions outside of React like createStore, reatom, effector, or zustand instead of context\n *\n * @template Value - The type of value that will be stored in the context\n * @param {Value | undefined} [defaultValue] - Default value for the context\n * @param {CreateReactiveContextOptions<Value>} [options] - Additional options for context creation\n * @returns {CreateReactiveContextReturn<Value>} Object containing context utilities and components\n *\n * @example\n * const { Provider, useSelector, instance } = createReactiveContext<number>(0);\n */\nexport const createReactiveContext = <Value extends Record<string, any>>(\n defaultValue: Value | undefined = undefined,\n options: CreateReactiveContextOptions = {}\n) => {\n const Context = createContext<ReactiveContextValue<Value>>({\n value: { current: defaultValue as Value },\n listeners: new Set()\n });\n\n const Provider = createProvider(Context.Provider) as unknown as Provider<Value>;\n\n Context.displayName = options.name;\n\n function useSelector(): Value;\n function useSelector<SelectedValue>(selector: (state: Value) => SelectedValue): SelectedValue;\n function useSelector<SelectedValue>(selector?: (state: Value) => SelectedValue) {\n return createReactiveContextSelector(\n Context as unknown as Context<ReactiveContextValue<Value>>,\n selector ?? ((state) => state as unknown as SelectedValue),\n options\n );\n }\n\n return { instance: Context, Provider, useSelector };\n};\n"],"names":["createProvider","originalProvider","props","valueRef","useRef","contextValue","useMemo","useIsomorphicLayoutEffect","startTransition","listener","createElement","createReactiveContextSelector","Context","selector","options","context","useContext","value","setValue","useState","dispatch","useEvent","newValue","prevValue","newSelected","createReactiveContext","defaultValue","createContext","Provider","useSelector","state"],"mappings":"yOAyCMA,EAAyBC,GACeC,GAAU,CAC9C,MAAAC,EAAWC,EAAAA,OAAOF,EAAM,K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D,MAAO,CAAE,QAASD,CAAsB,EACxC,cAAe,GAAI,CACpB,EAEKE,EAAW5B,EAAeY,EAAQ,QAAQ,EAEhDA,EAAQ,YAAcE,EAAQ,KAI9B,SAASe,EAA2BhB,EAA4C,CACvE,OAAAF,EACLC,EACAC,IAAciB,GAAUA,GACxBhB,CACF,CAAA,CAGF,MAAO,CAAE,SAAUF,EAAS,SAAAgB,EAAU,YAAAC,CAAY,CACpD"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { jsx as u } from "react/jsx-runtime";
|
|
2
|
-
import { createContext as m,
|
|
2
|
+
import { createContext as m, useContext as x, useState as v, useMemo as d } from "react";
|
|
3
3
|
const P = (n = void 0, o = {}) => {
|
|
4
4
|
const t = m({
|
|
5
5
|
value: n,
|
|
@@ -8,7 +8,7 @@ const P = (n = void 0, o = {}) => {
|
|
|
8
8
|
});
|
|
9
9
|
t.displayName = o.name;
|
|
10
10
|
function i(r) {
|
|
11
|
-
const e =
|
|
11
|
+
const e = x(t);
|
|
12
12
|
if (!e && o.strict)
|
|
13
13
|
throw new Error(`Context hook ${o.name} must be used inside a Provider`);
|
|
14
14
|
return r ? r(e.value) : e;
|
|
@@ -17,7 +17,7 @@ const P = (n = void 0, o = {}) => {
|
|
|
17
17
|
useSelect: i,
|
|
18
18
|
instance: t,
|
|
19
19
|
Provider: ({ children: r, initialValue: e }) => {
|
|
20
|
-
const [s, a] =
|
|
20
|
+
const [s, a] = v(e ?? n), c = d(
|
|
21
21
|
() => ({
|
|
22
22
|
value: s,
|
|
23
23
|
set: a
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createContext.mjs","sources":["../../../../src/helpers/createContext/createContext.tsx"],"sourcesContent":["import type { JSX, ReactNode } from 'react';\n\nimport { createContext as createReactContext,
|
|
1
|
+
{"version":3,"file":"createContext.mjs","sources":["../../../../src/helpers/createContext/createContext.tsx"],"sourcesContent":["import type { JSX, ReactNode } from 'react';\n\nimport { createContext as createReactContext, useContext, useMemo, useState } from 'react';\n\n/** The create context options type */\nexport interface CreateContextOptions {\n /** Display name for the context (useful for debugging) */\n name?: string;\n /** Whether to throw an error if context is used outside of Provider */\n strict?: boolean;\n}\n\n/** The context value type */\nexport interface ContextValue<Value> {\n /** The context value */\n value: Value | undefined;\n /** The context set function */\n set: (value: Value) => void;\n}\n\n/** The provider props type */\nexport interface ProviderProps<Value> {\n /** The children */\n children?: ReactNode;\n /** The initial value */\n initialValue?: Value;\n}\n\n/** The create context return type */\nexport interface CreateContextReturn<Value> {\n /** The context instance */\n instance: React.Context<ContextValue<Value>>;\n /** The provider component */\n Provider: (props: ProviderProps<Value>) => JSX.Element;\n /** The selector hook */\n useSelect: {\n <Selected>(selector: (value: Value) => Selected): Selected;\n (): ContextValue<Value>;\n };\n}\n\n/**\n * @name createContext\n * @description - Creates a typed context with additional utilities\n * @category Helpers\n *\n * @template Value - The type of value that will be stored in the context\n * @param {Value | undefined} [defaultValue] - Default value for the context\n * @param {CreateContextOptions<Value>} [options] - Additional options for context creation\n * @returns {CreateContextReturn<Value>} Object containing context utilities and components\n *\n * @example\n * const { useSelect, instance, Provider } = createContext<number>(0);\n */\nexport const createContext = <Value,>(\n defaultValue: Value | undefined = undefined,\n options: CreateContextOptions = {}\n): CreateContextReturn<Value> => {\n const Context = createReactContext<{\n value: Value | undefined;\n set: (value: Value) => void;\n }>({\n value: defaultValue,\n set: () => {}\n });\n\n Context.displayName = options.name;\n\n function useSelect(): ContextValue<Value>;\n function useSelect<Selected>(selector: (value: Value) => Selected): Selected;\n function useSelect<Selected>(selector?: (value: Value) => Selected) {\n const context = useContext(Context);\n\n if (!context && options.strict) {\n throw new Error(`Context hook ${options.name} must be used inside a Provider`);\n }\n\n if (!selector) {\n return context;\n }\n\n return selector(context.value as Value);\n }\n\n const Provider = ({ children, initialValue }: ProviderProps<Value>) => {\n const [profile, setProfile] = useState<Value | undefined>(initialValue ?? defaultValue);\n\n const value = useMemo(\n () => ({\n value: profile,\n set: setProfile\n }),\n [profile]\n );\n\n return <Context value={value}>{children}</Context>;\n };\n\n return {\n useSelect,\n instance: Context,\n Provider\n } as const;\n};\n"],"names":["createContext","defaultValue","options","Context","createReactContext","useSelect","selector","context","useContext","children","initialValue","profile","setProfile","useState","value","useMemo","jsx"],"mappings":";;AAsDO,MAAMA,IAAgB,CAC3BC,IAAkC,QAClCC,IAAgC,CAAA,MACD;AAC/B,QAAMC,IAAUC,EAGb;AAAA,IACD,OAAOH;AAAA,IACP,KAAK,MAAM;AAAA,IAAA;AAAA,EAAC,CACb;AAED,EAAAE,EAAQ,cAAcD,EAAQ;AAI9B,WAASG,EAAoBC,GAAuC;AAC5D,UAAAC,IAAUC,EAAWL,CAAO;AAE9B,QAAA,CAACI,KAAWL,EAAQ;AACtB,YAAM,IAAI,MAAM,gBAAgBA,EAAQ,IAAI,iCAAiC;AAG/E,WAAKI,IAIEA,EAASC,EAAQ,KAAc,IAH7BA;AAAA,EAG6B;AAiBjC,SAAA;AAAA,IACL,WAAAF;AAAA,IACA,UAAUF;AAAA,IACV,UAjBe,CAAC,EAAE,UAAAM,GAAU,cAAAC,QAAyC;AACrE,YAAM,CAACC,GAASC,CAAU,IAAIC,EAA4BH,KAAgBT,CAAY,GAEhFa,IAAQC;AAAA,QACZ,OAAO;AAAA,UACL,OAAOJ;AAAA,UACP,KAAKC;AAAA,QAAA;AAAA,QAEP,CAACD,CAAO;AAAA,MACV;AAEO,aAAA,gBAAAK,EAACb,GAAQ,EAAA,OAAAW,GAAe,UAAAL,EAAS,CAAA;AAAA,IAC1C;AAAA,EAMA;AACF;"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { createContext as v, useRef as d, useMemo as f, startTransition as m, createElement as x,
|
|
1
|
+
import { createContext as v, useRef as d, useMemo as f, startTransition as m, createElement as x, useContext as h, useState as C } from "react";
|
|
2
2
|
import { useIsomorphicLayoutEffect as l } from "../../hooks/useIsomorphicLayoutEffect/useIsomorphicLayoutEffect.mjs";
|
|
3
|
-
import { useEvent as
|
|
4
|
-
const
|
|
3
|
+
import { useEvent as P } from "../../hooks/useEvent/useEvent.mjs";
|
|
4
|
+
const S = (c) => (e) => {
|
|
5
5
|
const t = d(e.value), n = f(
|
|
6
6
|
() => ({
|
|
7
7
|
value: t,
|
|
@@ -20,10 +20,10 @@ const C = (c) => (e) => {
|
|
|
20
20
|
const t = h(c);
|
|
21
21
|
if (!t && e.strict)
|
|
22
22
|
throw new Error(`Context hook ${e.name} must be used inside a Provider`);
|
|
23
|
-
const [n, s] =
|
|
23
|
+
const [n, s] = C({
|
|
24
24
|
selected: r(t.value.current),
|
|
25
25
|
value: t.value.current
|
|
26
|
-
}), o =
|
|
26
|
+
}), o = P((i) => {
|
|
27
27
|
s((u) => {
|
|
28
28
|
if (Object.is(u.value, i)) return u;
|
|
29
29
|
const a = r(i);
|
|
@@ -37,7 +37,7 @@ const C = (c) => (e) => {
|
|
|
37
37
|
const e = v({
|
|
38
38
|
value: { current: c },
|
|
39
39
|
listeners: /* @__PURE__ */ new Set()
|
|
40
|
-
}), t =
|
|
40
|
+
}), t = S(e.Provider);
|
|
41
41
|
e.displayName = r.name;
|
|
42
42
|
function n(s) {
|
|
43
43
|
return E(
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createReactiveContext.mjs","sources":["../../../../src/helpers/createReactiveContext/createReactiveContext.ts"],"sourcesContent":["import type { Context, FC, Provider, ProviderProps, RefObject } from 'react';\n\nimport {\n createContext,\n createElement,\n startTransition,\n
|
|
1
|
+
{"version":3,"file":"createReactiveContext.mjs","sources":["../../../../src/helpers/createReactiveContext/createReactiveContext.ts"],"sourcesContent":["import type { Context, FC, Provider, ProviderProps, RefObject } from 'react';\n\nimport {\n createContext,\n createElement,\n startTransition,\n useContext,\n useMemo,\n useRef,\n useState\n} from 'react';\n\nimport { useEvent, useIsomorphicLayoutEffect } from '@/hooks';\n\n/** The create reactive context options type */\nexport interface CreateReactiveContextOptions {\n /** Display name for the context (useful for debugging) */\n name?: string;\n /** Whether to throw an error if context is used outside of Provider */\n strict?: boolean;\n}\n\n/** The create reactive context return type */\nexport interface CreateReactiveContextReturn<Value> {\n /** The context instance */\n instance: Context<ReactiveContextValue<Value>>;\n /** The Provider component for the context */\n Provider: Provider<Value>;\n /** A hook to select a part of the context state */\n useSelector: <Selected>(selector?: (state: Value) => Selected) => Selected;\n}\n\ntype ContextListener<Value> = (value: Value) => void;\n\ninterface ReactiveContextValue<Value> {\n /** The listeners for the context */\n listeners: Set<ContextListener<Value>>;\n /** The value for the context */\n value: RefObject<Value>;\n}\n\nconst createProvider = <Value>(originalProvider: Provider<ReactiveContextValue<Value>>) => {\n const Provider: FC<ProviderProps<Value>> = (props) => {\n const valueRef = useRef(props.value);\n const contextValue = useMemo<ReactiveContextValue<Value>>(\n () => ({\n value: valueRef,\n listeners: new Set()\n }),\n []\n );\n\n useIsomorphicLayoutEffect(() => {\n if (!Object.is(valueRef.current, props.value)) {\n valueRef.current = props.value;\n\n startTransition(() => {\n contextValue.listeners.forEach((listener) => {\n listener(valueRef.current);\n });\n });\n }\n }, [props.value]);\n\n return createElement(originalProvider, { value: contextValue }, props.children);\n };\n\n return Provider as unknown as Provider<ReactiveContextValue<Value>>;\n};\n\nconst createReactiveContextSelector = <Value, Selected>(\n Context: Context<ReactiveContextValue<Value>>,\n selector: (state: Value) => Selected,\n options: CreateReactiveContextOptions = {}\n) => {\n const context = useContext(Context);\n\n if (!context && options.strict) {\n throw new Error(`Context hook ${options.name} must be used inside a Provider`);\n }\n\n const [value, setValue] = useState({\n selected: selector(context.value.current),\n value: context.value.current\n });\n\n const dispatch = useEvent((newValue: Value) => {\n setValue((prevValue) => {\n if (Object.is(prevValue.value, newValue)) return prevValue;\n\n const newSelected = selector(newValue);\n if (Object.is(prevValue.selected, newSelected)) return prevValue;\n\n return { value: newValue, selected: newSelected };\n });\n });\n\n useIsomorphicLayoutEffect(() => {\n context.listeners.add(dispatch);\n return () => {\n context.listeners.delete(dispatch);\n };\n }, [context.listeners]);\n\n return value.selected;\n};\n\n/**\n * @name createReactiveContext\n * @description - Creates a typed context selector with optimized updates for state selection\n * @category Helpers\n *\n * @warning - For complex interfaces, we strongly recommend using state management solutions outside of React like createStore, reatom, effector, or zustand instead of context\n *\n * @template Value - The type of value that will be stored in the context\n * @param {Value | undefined} [defaultValue] - Default value for the context\n * @param {CreateReactiveContextOptions<Value>} [options] - Additional options for context creation\n * @returns {CreateReactiveContextReturn<Value>} Object containing context utilities and components\n *\n * @example\n * const { Provider, useSelector, instance } = createReactiveContext<number>(0);\n */\nexport const createReactiveContext = <Value extends Record<string, any>>(\n defaultValue: Value | undefined = undefined,\n options: CreateReactiveContextOptions = {}\n) => {\n const Context = createContext<ReactiveContextValue<Value>>({\n value: { current: defaultValue as Value },\n listeners: new Set()\n });\n\n const Provider = createProvider(Context.Provider) as unknown as Provider<Value>;\n\n Context.displayName = options.name;\n\n function useSelector(): Value;\n function useSelector<SelectedValue>(selector: (state: Value) => SelectedValue): SelectedValue;\n function useSelector<SelectedValue>(selector?: (state: Value) => SelectedValue) {\n return createReactiveContextSelector(\n Context as unknown as Context<ReactiveContextValue<Value>>,\n selector ?? ((state) => state as unknown as SelectedValue),\n options\n );\n }\n\n return { instance: Context, Provider, useSelector };\n};\n"],"names":["createProvider","originalProvider","props","valueRef","useRef","contextValue","useMemo","useIsomorphicLayoutEffect","startTransition","listener","createElement","createReactiveContextSelector","Context","selector","options","context","useContext","value","setValue","useState","dispatch","useEvent","newValue","prevValue","newSelected","createReactiveContext","defaultValue","createContext","Provider","useSelector","state"],"mappings":";;;AAyCA,MAAMA,IAAiB,CAAQC,MACc,CAACC,MAAU;AAC9C,QAAAC,IAAWC,EAAOF,EAAM,KAAK,GAC7BG,IAAeC;AAAA,IACnB,OAAO;AAAA,MACL,OAAOH;AAAA,MACP,+BAAe,IAAI;AAAA,IAAA;AAAA,IAErB,CAAA;AAAA,EACF;AAEA,SAAAI,EAA0B,MAAM;AAC9B,IAAK,OAAO,GAAGJ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GAEKE,IAAW5B,EAAeY,EAAQ,QAAQ;AAEhD,EAAAA,EAAQ,cAAcE,EAAQ;AAI9B,WAASe,EAA2BhB,GAA4C;AACvE,WAAAF;AAAA,MACLC;AAAA,MACAC,MAAa,CAACiB,MAAUA;AAAA,MACxBhB;AAAA,IACF;AAAA,EAAA;AAGF,SAAO,EAAE,UAAUF,GAAS,UAAAgB,GAAU,aAAAC,EAAY;AACpD;"}
|
|
@@ -27,6 +27,8 @@ interface ReactiveContextValue<Value> {
|
|
|
27
27
|
* @description - Creates a typed context selector with optimized updates for state selection
|
|
28
28
|
* @category Helpers
|
|
29
29
|
*
|
|
30
|
+
* @warning - For complex interfaces, we strongly recommend using state management solutions outside of React like createStore, reatom, effector, or zustand instead of context
|
|
31
|
+
*
|
|
30
32
|
* @template Value - The type of value that will be stored in the context
|
|
31
33
|
* @param {Value | undefined} [defaultValue] - Default value for the context
|
|
32
34
|
* @param {CreateReactiveContextOptions<Value>} [options] - Additional options for context creation
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@siberiacancode/reactuse",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.3",
|
|
4
4
|
"description": "The ultimate collection of react hooks",
|
|
5
5
|
"author": {
|
|
6
6
|
"name": "SIBERIA CAN CODE 🧊",
|
|
@@ -39,6 +39,17 @@
|
|
|
39
39
|
"publishConfig": {
|
|
40
40
|
"access": "public"
|
|
41
41
|
},
|
|
42
|
+
"scripts": {
|
|
43
|
+
"prepublishOnly": "pnpm unit-test run && pnpm build",
|
|
44
|
+
"build": "shx rm -rf dist && vite build",
|
|
45
|
+
"build:js": "tsc --project tsconfig.build.json && prettier --write src/bundle",
|
|
46
|
+
"lint": "eslint . --fix",
|
|
47
|
+
"lint-inspector": "npx @eslint/config-inspector@latest",
|
|
48
|
+
"format": "prettier --write .",
|
|
49
|
+
"pretty": "pnpm lint && pnpm format",
|
|
50
|
+
"unit-test": "vitest",
|
|
51
|
+
"lint-staged": "lint-staged"
|
|
52
|
+
},
|
|
42
53
|
"peerDependencies": {
|
|
43
54
|
"@types/react": "^18",
|
|
44
55
|
"react": "^17 || ^18 || ^19",
|
|
@@ -74,15 +85,5 @@
|
|
|
74
85
|
"eslint --fix",
|
|
75
86
|
"prettier --write"
|
|
76
87
|
]
|
|
77
|
-
},
|
|
78
|
-
"scripts": {
|
|
79
|
-
"build": "shx rm -rf dist && vite build",
|
|
80
|
-
"build:js": "tsc --project tsconfig.build.json && prettier --write src/bundle",
|
|
81
|
-
"lint": "eslint . --fix",
|
|
82
|
-
"lint-inspector": "npx @eslint/config-inspector@latest",
|
|
83
|
-
"format": "prettier --write .",
|
|
84
|
-
"pretty": "pnpm lint && pnpm format",
|
|
85
|
-
"unit-test": "vitest",
|
|
86
|
-
"lint-staged": "lint-staged"
|
|
87
88
|
}
|
|
88
|
-
}
|
|
89
|
+
}
|
package/LICENSE
DELETED
|
@@ -1,21 +0,0 @@
|
|
|
1
|
-
MIT License
|
|
2
|
-
|
|
3
|
-
Copyright (c) 2024 siberiacancode
|
|
4
|
-
|
|
5
|
-
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
-
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
-
in the Software without restriction, including without limitation the rights
|
|
8
|
-
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
-
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
-
furnished to do so, subject to the following conditions:
|
|
11
|
-
|
|
12
|
-
The above copyright notice and this permission notice shall be included in all
|
|
13
|
-
copies or substantial portions of the Software.
|
|
14
|
-
|
|
15
|
-
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
-
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
-
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
-
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
-
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
-
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
-
SOFTWARE.
|