@liberfi.io/hooks 0.1.22 → 0.1.23

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/index.d.mts CHANGED
@@ -1,8 +1,5 @@
1
- import * as React$1 from 'react';
2
- import React__default, { RefObject, useLayoutEffect } from 'react';
3
- import { EventEmitter, SimpleDI } from '@liberfi.io/core';
4
- export { default as useConstant } from 'use-constant';
5
- export * from 'use-debounce';
1
+ import { RefObject, useLayoutEffect } from 'react';
2
+ import EventEmitter from 'eventemitter3';
6
3
 
7
4
  declare global {
8
5
  interface Window {
@@ -11,7 +8,7 @@ declare global {
11
8
  };
12
9
  }
13
10
  }
14
- declare const _default: "0.1.22";
11
+ declare const _default: "0.1.23";
15
12
 
16
13
  type UseBooleanReturn = [
17
14
  /** current state */
@@ -51,7 +48,7 @@ declare function useCallbackRef<T extends (...args: any[]) => any>(fn: T | undef
51
48
  declare function useIsMounted(): () => boolean;
52
49
 
53
50
  /** The size of the observed element. */
54
- type Size = {
51
+ type Size$1 = {
55
52
  /** The width of the observed element. */
56
53
  width: number | undefined;
57
54
  /** The height of the observed element. */
@@ -65,7 +62,7 @@ type UseResizeObserverOptions<T extends HTMLElement = HTMLElement> = {
65
62
  * When using `onResize`, the hook doesn't re-render on element size changes; it delegates handling to the provided callback.
66
63
  * @default undefined
67
64
  */
68
- onResize?: (size: Size) => void;
65
+ onResize?: (size: Size$1) => void;
69
66
  /**
70
67
  * The box model to use for the ResizeObserver.
71
68
  * @default 'content-box'
@@ -87,7 +84,7 @@ type UseResizeObserverOptions<T extends HTMLElement = HTMLElement> = {
87
84
  * <div ref={myRef}>Hello, world!</div>
88
85
  * ```
89
86
  */
90
- declare function useResizeObserver<T extends HTMLElement = HTMLElement>(options: UseResizeObserverOptions<T>): Size;
87
+ declare function useResizeObserver<T extends HTMLElement = HTMLElement>(options: UseResizeObserverOptions<T>): Size$1;
91
88
 
92
89
  declare const useSafeLayoutEffect: typeof useLayoutEffect;
93
90
 
@@ -120,46 +117,18 @@ declare function useTickAge(birthday?: number | Date, interval?: number): number
120
117
  */
121
118
  declare function useValueRef<T>(value: T): RefObject<T>;
122
119
 
123
- type NotFunction<T> = T extends (...args: any[]) => any ? never : T;
124
- declare const useUpdatedRef: <T>(val: NotFunction<T>) => React$1.RefObject<T>;
125
-
126
- type noop = (this: any, ...args: any[]) => any;
127
- type PickFunction<T extends noop> = (this: ThisParameterType<T>, ...args: Parameters<T>) => ReturnType<T>;
128
- declare const useMemoizedFn: <T extends noop>(fn: T) => PickFunction<T>;
129
-
130
- interface AudioPlayerOptions {
131
- volume?: number;
132
- loop?: boolean;
133
- autoPlay?: boolean;
134
- }
135
- declare const useAudioPlayer: (src: string, options?: AudioPlayerOptions) => readonly [React__default.DetailedReactHTMLElement<{
136
- controls: boolean;
137
- ref: React__default.RefObject<HTMLAudioElement | null>;
138
- autoPlay: boolean | undefined;
139
- src: string;
140
- style: {
141
- display: "none";
142
- };
143
- onPlay: () => void;
144
- onPlaying: () => void;
145
- onPause: () => void;
146
- onEnded: () => void;
147
- onError: () => void;
148
- }, HTMLAudioElement>, React__default.RefObject<HTMLAudioElement | null>, "idle" | "play" | "playing" | "paused" | "ended" | "error"];
120
+ /** The size of the observed element. */
121
+ type Size = {
122
+ /** The width of the observed element. */
123
+ width: number | undefined;
124
+ /** The height of the observed element. */
125
+ height: number | undefined;
126
+ };
127
+ type UseThrottledResizeObserverOptions<T extends HTMLElement = HTMLElement> = Pick<UseResizeObserverOptions<T>, "ref" | "box"> & {
128
+ throttleMs?: number;
129
+ };
130
+ declare function useThrottledResizeObserver<T extends HTMLElement = HTMLElement>(options: UseThrottledResizeObserverOptions<T>): Size;
149
131
 
150
132
  declare const useEventEmitter: () => EventEmitter<string | symbol, any>;
151
133
 
152
- declare function useSessionStorage<T>(key: string, initialValue: T): [T, (data: any) => void];
153
-
154
- declare function parseJSON<T>(value: string | null): T | undefined;
155
-
156
- declare function useLocalStorage<T>(key: string, initialValue: T, options?: {
157
- parseJSON: typeof parseJSON;
158
- }): [any, (value: T) => void];
159
-
160
- declare const useSimpleDI: <T>() => {
161
- get: (name: string) => T;
162
- register: typeof SimpleDI.register;
163
- };
164
-
165
- export { type TickCallback, type TickEvent, type UnsubscribeTick, type UseBooleanReturn, type UseResizeObserverOptions, parseJSON, useAudioPlayer, useBoolean, useCallbackRef, useEventEmitter, useIsMounted, useLocalStorage, useMemoizedFn, useResizeObserver, useSafeLayoutEffect, useSessionStorage, useSimpleDI, useTick, useTickAge, useUpdatedRef, useValueRef, _default as version };
134
+ export { type TickCallback, type TickEvent, type UnsubscribeTick, type UseBooleanReturn, type UseResizeObserverOptions, type UseThrottledResizeObserverOptions, useBoolean, useCallbackRef, useEventEmitter, useIsMounted, useResizeObserver, useSafeLayoutEffect, useThrottledResizeObserver, useTick, useTickAge, useValueRef, _default as version };
package/dist/index.d.ts CHANGED
@@ -1,8 +1,5 @@
1
- import * as React$1 from 'react';
2
- import React__default, { RefObject, useLayoutEffect } from 'react';
3
- import { EventEmitter, SimpleDI } from '@liberfi.io/core';
4
- export { default as useConstant } from 'use-constant';
5
- export * from 'use-debounce';
1
+ import { RefObject, useLayoutEffect } from 'react';
2
+ import EventEmitter from 'eventemitter3';
6
3
 
7
4
  declare global {
8
5
  interface Window {
@@ -11,7 +8,7 @@ declare global {
11
8
  };
12
9
  }
13
10
  }
14
- declare const _default: "0.1.22";
11
+ declare const _default: "0.1.23";
15
12
 
16
13
  type UseBooleanReturn = [
17
14
  /** current state */
@@ -51,7 +48,7 @@ declare function useCallbackRef<T extends (...args: any[]) => any>(fn: T | undef
51
48
  declare function useIsMounted(): () => boolean;
52
49
 
53
50
  /** The size of the observed element. */
54
- type Size = {
51
+ type Size$1 = {
55
52
  /** The width of the observed element. */
56
53
  width: number | undefined;
57
54
  /** The height of the observed element. */
@@ -65,7 +62,7 @@ type UseResizeObserverOptions<T extends HTMLElement = HTMLElement> = {
65
62
  * When using `onResize`, the hook doesn't re-render on element size changes; it delegates handling to the provided callback.
66
63
  * @default undefined
67
64
  */
68
- onResize?: (size: Size) => void;
65
+ onResize?: (size: Size$1) => void;
69
66
  /**
70
67
  * The box model to use for the ResizeObserver.
71
68
  * @default 'content-box'
@@ -87,7 +84,7 @@ type UseResizeObserverOptions<T extends HTMLElement = HTMLElement> = {
87
84
  * <div ref={myRef}>Hello, world!</div>
88
85
  * ```
89
86
  */
90
- declare function useResizeObserver<T extends HTMLElement = HTMLElement>(options: UseResizeObserverOptions<T>): Size;
87
+ declare function useResizeObserver<T extends HTMLElement = HTMLElement>(options: UseResizeObserverOptions<T>): Size$1;
91
88
 
92
89
  declare const useSafeLayoutEffect: typeof useLayoutEffect;
93
90
 
@@ -120,46 +117,18 @@ declare function useTickAge(birthday?: number | Date, interval?: number): number
120
117
  */
121
118
  declare function useValueRef<T>(value: T): RefObject<T>;
122
119
 
123
- type NotFunction<T> = T extends (...args: any[]) => any ? never : T;
124
- declare const useUpdatedRef: <T>(val: NotFunction<T>) => React$1.RefObject<T>;
125
-
126
- type noop = (this: any, ...args: any[]) => any;
127
- type PickFunction<T extends noop> = (this: ThisParameterType<T>, ...args: Parameters<T>) => ReturnType<T>;
128
- declare const useMemoizedFn: <T extends noop>(fn: T) => PickFunction<T>;
129
-
130
- interface AudioPlayerOptions {
131
- volume?: number;
132
- loop?: boolean;
133
- autoPlay?: boolean;
134
- }
135
- declare const useAudioPlayer: (src: string, options?: AudioPlayerOptions) => readonly [React__default.DetailedReactHTMLElement<{
136
- controls: boolean;
137
- ref: React__default.RefObject<HTMLAudioElement | null>;
138
- autoPlay: boolean | undefined;
139
- src: string;
140
- style: {
141
- display: "none";
142
- };
143
- onPlay: () => void;
144
- onPlaying: () => void;
145
- onPause: () => void;
146
- onEnded: () => void;
147
- onError: () => void;
148
- }, HTMLAudioElement>, React__default.RefObject<HTMLAudioElement | null>, "idle" | "play" | "playing" | "paused" | "ended" | "error"];
120
+ /** The size of the observed element. */
121
+ type Size = {
122
+ /** The width of the observed element. */
123
+ width: number | undefined;
124
+ /** The height of the observed element. */
125
+ height: number | undefined;
126
+ };
127
+ type UseThrottledResizeObserverOptions<T extends HTMLElement = HTMLElement> = Pick<UseResizeObserverOptions<T>, "ref" | "box"> & {
128
+ throttleMs?: number;
129
+ };
130
+ declare function useThrottledResizeObserver<T extends HTMLElement = HTMLElement>(options: UseThrottledResizeObserverOptions<T>): Size;
149
131
 
150
132
  declare const useEventEmitter: () => EventEmitter<string | symbol, any>;
151
133
 
152
- declare function useSessionStorage<T>(key: string, initialValue: T): [T, (data: any) => void];
153
-
154
- declare function parseJSON<T>(value: string | null): T | undefined;
155
-
156
- declare function useLocalStorage<T>(key: string, initialValue: T, options?: {
157
- parseJSON: typeof parseJSON;
158
- }): [any, (value: T) => void];
159
-
160
- declare const useSimpleDI: <T>() => {
161
- get: (name: string) => T;
162
- register: typeof SimpleDI.register;
163
- };
164
-
165
- export { type TickCallback, type TickEvent, type UnsubscribeTick, type UseBooleanReturn, type UseResizeObserverOptions, parseJSON, useAudioPlayer, useBoolean, useCallbackRef, useEventEmitter, useIsMounted, useLocalStorage, useMemoizedFn, useResizeObserver, useSafeLayoutEffect, useSessionStorage, useSimpleDI, useTick, useTickAge, useUpdatedRef, useValueRef, _default as version };
134
+ export { type TickCallback, type TickEvent, type UnsubscribeTick, type UseBooleanReturn, type UseResizeObserverOptions, type UseThrottledResizeObserverOptions, useBoolean, useCallbackRef, useEventEmitter, useIsMounted, useResizeObserver, useSafeLayoutEffect, useThrottledResizeObserver, useTick, useTickAge, useValueRef, _default as version };
package/dist/index.js CHANGED
@@ -1,13 +1,14 @@
1
1
  'use strict';
2
2
 
3
- var React = require('react');
3
+ var react = require('react');
4
+ var lodashEs = require('lodash-es');
5
+ var EventEmitter = require('eventemitter3');
4
6
  var useConstant = require('use-constant');
5
- var core = require('@liberfi.io/core');
6
- var useDebounce = require('use-debounce');
7
+ var utils = require('@liberfi.io/utils');
7
8
 
8
9
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
9
10
 
10
- var React__default = /*#__PURE__*/_interopDefault(React);
11
+ var EventEmitter__default = /*#__PURE__*/_interopDefault(EventEmitter);
11
12
  var useConstant__default = /*#__PURE__*/_interopDefault(useConstant);
12
13
 
13
14
  var __defProp = Object.defineProperty;
@@ -17,35 +18,35 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
17
18
  // src/version.ts
18
19
  if (typeof window !== "undefined") {
19
20
  window.__LIBERFI_VERSION__ = window.__LIBERFI_VERSION__ || {};
20
- window.__LIBERFI_VERSION__["@liberfi.io/hooks"] = "0.1.22";
21
+ window.__LIBERFI_VERSION__["@liberfi.io/hooks"] = "0.1.23";
21
22
  }
22
- var version_default = "0.1.22";
23
+ var version_default = "0.1.23";
23
24
  var useBoolean = (initialValue = false) => {
24
- const [value, setValue] = React.useState(initialValue);
25
- const setTrue = React.useCallback(() => setValue(true), []);
26
- const setFalse = React.useCallback(() => setValue(false), []);
27
- const toggle = React.useCallback(() => setValue((v) => !v), []);
25
+ const [value, setValue] = react.useState(initialValue);
26
+ const setTrue = react.useCallback(() => setValue(true), []);
27
+ const setFalse = react.useCallback(() => setValue(false), []);
28
+ const toggle = react.useCallback(() => setValue((v) => !v), []);
28
29
  return [value, { setTrue, setFalse, toggle }];
29
30
  };
30
- var useSafeLayoutEffect = globalThis?.document ? React.useLayoutEffect : React.useEffect;
31
+ var useSafeLayoutEffect = globalThis?.document ? react.useLayoutEffect : react.useEffect;
31
32
 
32
33
  // src/useCallbackRef.ts
33
34
  function useCallbackRef(fn, deps = []) {
34
- const ref = React.useRef(fn);
35
+ const ref = react.useRef(fn);
35
36
  useSafeLayoutEffect(() => {
36
37
  ref.current = fn;
37
38
  });
38
- return React.useCallback(((...args) => ref.current?.(...args)), deps);
39
+ return react.useCallback(((...args) => ref.current?.(...args)), deps);
39
40
  }
40
41
  function useIsMounted() {
41
- const isMounted = React.useRef(false);
42
- React.useEffect(() => {
42
+ const isMounted = react.useRef(false);
43
+ react.useEffect(() => {
43
44
  isMounted.current = true;
44
45
  return () => {
45
46
  isMounted.current = false;
46
47
  };
47
48
  }, []);
48
- return React.useCallback(() => isMounted.current, []);
49
+ return react.useCallback(() => isMounted.current, []);
49
50
  }
50
51
  var initialSize = {
51
52
  width: void 0,
@@ -53,12 +54,12 @@ var initialSize = {
53
54
  };
54
55
  function useResizeObserver(options) {
55
56
  const { ref, box = "content-box" } = options;
56
- const [{ width, height }, setSize] = React.useState(initialSize);
57
+ const [{ width, height }, setSize] = react.useState(initialSize);
57
58
  const isMounted = useIsMounted();
58
- const previousSize = React.useRef({ ...initialSize });
59
- const onResize = React.useRef(void 0);
59
+ const previousSize = react.useRef({ ...initialSize });
60
+ const onResize = react.useRef(void 0);
60
61
  onResize.current = options.onResize;
61
- React.useEffect(() => {
62
+ react.useEffect(() => {
62
63
  if (!ref.current) return;
63
64
  if (typeof window === "undefined" || !("ResizeObserver" in window)) return;
64
65
  const observer = new ResizeObserver(([entry]) => {
@@ -170,18 +171,18 @@ __publicField(_GlobalTimer, "instance");
170
171
  var GlobalTimer = _GlobalTimer;
171
172
  function useTick(callback, interval = 1e3) {
172
173
  const callbackRef = useCallbackRef(callback);
173
- React.useEffect(
174
+ react.useEffect(
174
175
  () => GlobalTimer.getInstance().subscribe(callbackRef, interval),
175
176
  [interval]
176
177
  );
177
178
  }
178
179
  function useTickAge(birthday = Date.now(), interval = 1e3) {
179
- const birthdayRef = React.useRef(
180
+ const birthdayRef = react.useRef(
180
181
  birthday instanceof Date ? birthday.getTime() : birthday
181
182
  );
182
183
  birthdayRef.current = birthday instanceof Date ? birthday.getTime() : birthday;
183
- const [age, setAge] = React.useState(Math.max(0, Date.now() - birthdayRef.current));
184
- const tickAge = React.useCallback(
184
+ const [age, setAge] = react.useState(Math.max(0, Date.now() - birthdayRef.current));
185
+ const tickAge = react.useCallback(
185
186
  ({ now }) => setAge(Math.max(0, now - birthdayRef.current)),
186
187
  []
187
188
  );
@@ -189,216 +190,118 @@ function useTickAge(birthday = Date.now(), interval = 1e3) {
189
190
  return age;
190
191
  }
191
192
  function useValueRef(value) {
192
- const valueRef = React.useRef(value);
193
+ const valueRef = react.useRef(value);
193
194
  valueRef.current = value;
194
195
  return valueRef;
195
196
  }
196
- var useUpdatedRef = (val) => {
197
- const latestRef = React.useRef(val);
198
- latestRef.current = val;
199
- return latestRef;
200
- };
201
- var useMemoizedFn = (fn) => {
202
- const fnRef = React.useRef(fn);
203
- fnRef.current = React.useMemo(() => fn, [fn]);
204
- const memoizedFn = React.useRef(void 0);
205
- if (!memoizedFn.current) {
206
- memoizedFn.current = function(...args) {
207
- return fnRef.current.apply(this, args);
208
- };
197
+ function useThrottledResizeObserver(options) {
198
+ const { ref, box, throttleMs = 50 } = options;
199
+ const [size, setSize] = react.useState({
200
+ width: void 0,
201
+ height: void 0
202
+ });
203
+ const onResize = react.useMemo(
204
+ () => lodashEs.throttle(setSize, throttleMs, { leading: true, trailing: true }),
205
+ [throttleMs, setSize]
206
+ );
207
+ useResizeObserver({ ref, box, onResize });
208
+ return size;
209
+ }
210
+
211
+ // src/internal/di/container.ts
212
+ var Container = class {
213
+ constructor(services = {}) {
214
+ this.services = services;
209
215
  }
210
- return memoizedFn.current;
211
- };
212
- var useAudioPlayer = (src, options = {}) => {
213
- const { volume = 1, loop, autoPlay } = options;
214
- const audioRef = React.useRef(null);
215
- const [status, setStatus] = React.useState("idle");
216
- const onPlay = () => {
217
- setStatus("play");
218
- };
219
- const onPlaying = () => {
220
- setStatus("playing");
221
- };
222
- const onPause = () => {
223
- setStatus("paused");
224
- };
225
- const onEnded = () => {
226
- setStatus("ended");
227
- };
228
- const onError = () => {
229
- setStatus("error");
230
- };
231
- const element = React.useMemo(() => {
232
- return React__default.default.createElement("audio", {
233
- controls: false,
234
- ref: audioRef,
235
- autoPlay,
236
- src,
237
- style: { display: "none" },
238
- onPlay,
239
- onPlaying,
240
- onPause,
241
- onEnded,
242
- onError
216
+ register(...serviceClasses) {
217
+ serviceClasses.forEach((serviceClass) => {
218
+ let service = serviceClass;
219
+ if (service instanceof Function) {
220
+ service = new serviceClass();
221
+ }
222
+ this.add(service);
243
223
  });
244
- }, [autoPlay, src, onPlay, onPlaying, onPause, onEnded, onError]);
245
- React.useEffect(() => {
246
- const el = audioRef.current;
247
- if (!el) {
248
- return;
224
+ }
225
+ registerByName(name, serviceClass) {
226
+ let service = serviceClass;
227
+ if (service instanceof Function) {
228
+ service = new serviceClass();
249
229
  }
250
- el.loop = loop ?? false;
251
- el.volume = Math.max(0, Math.min(1, volume));
252
- return () => {
253
- audioRef.current?.pause();
254
- audioRef.current = null;
255
- };
256
- }, [loop, volume]);
257
- return [element, audioRef, status];
230
+ this.addByName(name, service);
231
+ }
232
+ get(name) {
233
+ return this.services[name];
234
+ }
235
+ getAll() {
236
+ return Object.assign({}, this.services);
237
+ }
238
+ add(service) {
239
+ return this.addByName(service.constructor.name, service);
240
+ }
241
+ addByName(name, service) {
242
+ this.services[name] = service;
243
+ this.services[name.toLowerCase()] = service;
244
+ this.services[name.toUpperCase()] = service;
245
+ return this.get(name);
246
+ }
247
+ };
248
+
249
+ // src/internal/di/simpleDI.ts
250
+ var _SimpleDI = class _SimpleDI {
251
+ static getContainer() {
252
+ if (!_SimpleDI.container) {
253
+ utils.getGlobalObject()[_SimpleDI.KEY] = _SimpleDI.container = new Container();
254
+ }
255
+ return _SimpleDI.container;
256
+ }
257
+ static register(...serviceClasses) {
258
+ _SimpleDI.getContainer().register(...serviceClasses);
259
+ }
260
+ static registerByName(name, serviceClass) {
261
+ _SimpleDI.getContainer().registerByName(name, serviceClass);
262
+ }
263
+ static get(name) {
264
+ return _SimpleDI.getContainer().get(name);
265
+ }
266
+ static getOr(name, instance) {
267
+ const s = _SimpleDI.getContainer().get(name);
268
+ if (!s) {
269
+ _SimpleDI.registerByName(name, instance);
270
+ }
271
+ return instance;
272
+ }
273
+ static getAll() {
274
+ return _SimpleDI.getContainer().getAll();
275
+ }
276
+ constructor() {
277
+ }
258
278
  };
279
+ __publicField(_SimpleDI, "KEY", "__LIBERFI_CONTAINER__");
280
+ __publicField(_SimpleDI, "container", utils.getGlobalObject()[_SimpleDI.KEY] || null);
281
+ var SimpleDI = _SimpleDI;
282
+
283
+ // src/useEventEmitter.ts
259
284
  var useEventEmitter = () => {
260
285
  return useConstant__default.default(() => {
261
- let ee = core.SimpleDI.get("EE");
286
+ let ee = SimpleDI.get("EE");
262
287
  if (!ee) {
263
- ee = new core.EventEmitter();
264
- core.SimpleDI.registerByName("EE", ee);
288
+ ee = new EventEmitter__default.default();
289
+ SimpleDI.registerByName("EE", ee);
265
290
  }
266
291
  return ee;
267
292
  });
268
293
  };
269
294
 
270
- // src/utils/json.ts
271
- function parseJSON(value) {
272
- try {
273
- return value === "undefined" ? void 0 : JSON.parse(value ?? "");
274
- } catch {
275
- return void 0;
276
- }
277
- }
278
-
279
- // src/useSessionStorage.ts
280
- function useSessionStorage(key, initialValue) {
281
- const readValue = React.useCallback(() => {
282
- if (typeof window === "undefined") {
283
- return initialValue;
284
- }
285
- try {
286
- const item = window.sessionStorage.getItem(key);
287
- return item ? parseJSON(item) : initialValue;
288
- } catch (error) {
289
- return initialValue;
290
- }
291
- }, [initialValue, key]);
292
- const [storedValue, setStoredValue] = React.useState(readValue);
293
- const setValue = (value) => {
294
- try {
295
- const newValue = value instanceof Function ? value(storedValue) : value;
296
- window.sessionStorage.setItem(key, JSON.stringify(newValue));
297
- setStoredValue(newValue);
298
- } catch (error) {
299
- }
300
- };
301
- React.useEffect(() => {
302
- setStoredValue(readValue());
303
- }, []);
304
- React.useEffect(() => {
305
- if (typeof window == "undefined") {
306
- return;
307
- }
308
- window.addEventListener?.("storage", handleStorageChange);
309
- return () => {
310
- window.removeEventListener?.("storage", handleStorageChange);
311
- };
312
- });
313
- const handleStorageChange = React.useCallback(
314
- (event) => {
315
- if (event?.key && event.key !== key) {
316
- return;
317
- }
318
- setStoredValue(readValue());
319
- },
320
- [key, readValue]
321
- );
322
- return [storedValue, setValue];
323
- }
324
- function useLocalStorage(key, initialValue, options = {
325
- parseJSON
326
- }) {
327
- const readValue = React.useCallback(() => {
328
- if (typeof window === "undefined") {
329
- return initialValue;
330
- }
331
- try {
332
- const item = window.localStorage.getItem(key);
333
- return item ? options.parseJSON(item) : initialValue;
334
- } catch (error) {
335
- return initialValue;
336
- }
337
- }, [initialValue, key]);
338
- const [storedValue, setStoredValue] = React.useState(readValue);
339
- const setValue = React.useCallback(
340
- (value) => {
341
- try {
342
- const newValue = value instanceof Function ? value(storedValue) : value;
343
- window.localStorage.setItem(key, JSON.stringify(newValue));
344
- window.dispatchEvent(new Event("storage"));
345
- setStoredValue(() => newValue);
346
- } catch (error) {
347
- }
348
- },
349
- [storedValue]
350
- );
351
- React.useEffect(() => {
352
- setStoredValue(readValue());
353
- }, []);
354
- React.useEffect(() => {
355
- const handleStorageChange = (event) => {
356
- if (event?.key && event.key !== key) {
357
- return;
358
- }
359
- setStoredValue(readValue());
360
- };
361
- window?.addEventListener?.("storage", handleStorageChange);
362
- return () => {
363
- window?.removeEventListener?.("storage", handleStorageChange);
364
- };
365
- }, [key]);
366
- return [storedValue, setValue];
367
- }
368
- var useSimpleDI = () => {
369
- return {
370
- get: core.SimpleDI.get,
371
- // getOr: SimpleDI.getOr<T>(name, SimpleDI.get<T>(name)),
372
- register: core.SimpleDI.register
373
- };
374
- };
375
-
376
- Object.defineProperty(exports, "useConstant", {
377
- enumerable: true,
378
- get: function () { return useConstant__default.default; }
379
- });
380
- exports.parseJSON = parseJSON;
381
- exports.useAudioPlayer = useAudioPlayer;
382
295
  exports.useBoolean = useBoolean;
383
296
  exports.useCallbackRef = useCallbackRef;
384
297
  exports.useEventEmitter = useEventEmitter;
385
298
  exports.useIsMounted = useIsMounted;
386
- exports.useLocalStorage = useLocalStorage;
387
- exports.useMemoizedFn = useMemoizedFn;
388
299
  exports.useResizeObserver = useResizeObserver;
389
300
  exports.useSafeLayoutEffect = useSafeLayoutEffect;
390
- exports.useSessionStorage = useSessionStorage;
391
- exports.useSimpleDI = useSimpleDI;
301
+ exports.useThrottledResizeObserver = useThrottledResizeObserver;
392
302
  exports.useTick = useTick;
393
303
  exports.useTickAge = useTickAge;
394
- exports.useUpdatedRef = useUpdatedRef;
395
304
  exports.useValueRef = useValueRef;
396
305
  exports.version = version_default;
397
- Object.keys(useDebounce).forEach(function (k) {
398
- if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, {
399
- enumerable: true,
400
- get: function () { return useDebounce[k]; }
401
- });
402
- });
403
306
  //# sourceMappingURL=index.js.map
404
307
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/version.ts","../src/useBoolean.ts","../src/useSafeLayoutEffect.ts","../src/useCallbackRef.ts","../src/useIsMounted.ts","../src/useResizeObserver.ts","../src/useTick.ts","../src/useTickAge.ts","../src/useValueRef.ts","../src/shared/useUpdatedRef.ts","../src/shared/useMemoizedFn.ts","../src/shared/useAudio.tsx","../src/useEventEmitter.ts","../src/utils/json.ts","../src/useSessionStorage.ts","../src/useLocalStorage.ts","../src/useSimpleDI.ts"],"names":["useState","useCallback","useLayoutEffect","useEffect","useRef","useMemo","React","useConstant","SimpleDI","EventEmitter"],"mappings":";;;;;;;;;;;;;;;;;AAOA,IAAI,OAAO,WAAW,WAAA,EAAa;AACjC,EAAA,MAAA,CAAO,mBAAA,GAAsB,MAAA,CAAO,mBAAA,IAAuB,EAAC;AAC5D,EAAA,MAAA,CAAO,mBAAA,CAAoB,mBAAmB,CAAA,GAAI,QAAA;AACpD;AAEA,IAAO,eAAA,GAAQ;ACQR,IAAM,UAAA,GAAa,CAAC,YAAA,GAAe,KAAA,KAA4B;AACpE,EAAA,MAAM,CAAC,KAAA,EAAO,QAAQ,CAAA,GAAIA,eAAS,YAAY,CAAA;AAC/C,EAAA,MAAM,UAAUC,iBAAA,CAAY,MAAM,SAAS,IAAI,CAAA,EAAG,EAAE,CAAA;AACpD,EA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AAA,IAAQ,KAAA,CAAuB,GAAA,KAAQ,GAAA,EAAK;AACvE,QAAA;AAAA,MACF;AACA,MAAA,cAAA,CAAe,WAAW,CAAA;AAAA,IAC5B,CAAA;AAEA,IAAA,MAAA,EAAQ,gBAAA,GAAmB,WAAW,mBAAmB,CAAA;AAEzD,IAAA,OAAO,MAAM;AACX,MAAA,MAAA,EAAQ,mBAAA,GAAsB,WAAW,mBAAmB,CAAA;AAAA,IAC9D,CAAA;AAAA,EACF,CAAA,EAAG,CAAC,GAAG,CAAC,CAAA;AAER,EAAA,OAAO,CAAC,aAAa,QAAQ,CAAA;AAC/B;ACrFO,IAAM,cAAc,MAAS;AAClC,EAAA,OAAO;AAAA,IACL,KAAKK,aAAAA,CAAS,GAAA;AAAA;AAAA,IAEd,UAAUA,aAAAA,CAAS;AAAA,GACrB;AACF","file":"index.js","sourcesContent":["declare global {\n interface Window {\n __LIBERFI_VERSION__?: {\n [key: string]: string;\n };\n }\n}\nif (typeof window !== \"undefined\") {\n window.__LIBERFI_VERSION__ = window.__LIBERFI_VERSION__ || {};\n window.__LIBERFI_VERSION__[\"@liberfi.io/hooks\"] = \"0.1.22\";\n}\n\nexport default \"0.1.22\";\n","import { useCallback, useState } from \"react\";\n\nexport type UseBooleanReturn = [\n /** current state */\n boolean,\n {\n /** set state to true */\n setTrue: () => void;\n /** set state to false */\n setFalse: () => void;\n /** toggle state */\n toggle: () => void;\n },\n];\n\n/**\n * Hook to manage a boolean state\n * @param initialValue Initial value of the boolean\n * @returns\n */\nexport const useBoolean = (initialValue = false): UseBooleanReturn => {\n const [value, setValue] = useState(initialValue);\n const setTrue = useCallback(() => setValue(true), []);\n const setFalse = useCallback(() => setValue(false), []);\n const toggle = useCallback(() => setValue((v) => !v), []);\n return [value, { setTrue, setFalse, toggle }];\n};\n","import { useEffect, useLayoutEffect } from \"react\";\n\nexport const useSafeLayoutEffect = globalThis?.document\n ? useLayoutEffect\n : useEffect;\n","/* eslint-disable @typescript-eslint/no-explicit-any */\n/**\n * Part of this code is taken from @chakra-ui/system ❤️\n */\nimport { useCallback, useRef } from \"react\";\nimport { useSafeLayoutEffect } from \"./useSafeLayoutEffect\";\n\n/**\n * React hook to persist any value between renders,\n * but keeps it up-to-date if it changes.\n * @param fn the function to persist\n * @param deps the function dependency list\n */\nexport function useCallbackRef<T extends (...args: any[]) => any>(\n fn: T | undefined,\n deps: React.DependencyList = [],\n): T {\n const ref = useRef(fn);\n\n useSafeLayoutEffect(() => {\n ref.current = fn;\n });\n\n return useCallback(((...args) => ref.current?.(...args)) as T, deps);\n}\n","import { useCallback, useEffect, useRef } from \"react\";\n\n/**\n * Custom hook that determines if the component is currently mounted.\n * @example\n * ```tsx\n * const isComponentMounted = useIsMounted();\n * // Use isComponentMounted() to check if the component is currently mounted before performing certain actions.\n * ```\n */\nexport function useIsMounted(): () => boolean {\n const isMounted = useRef(false);\n\n useEffect(() => {\n isMounted.current = true;\n\n return () => {\n isMounted.current = false;\n };\n }, []);\n\n return useCallback(() => isMounted.current, []);\n}\n","import type { RefObject } from \"react\";\nimport { useEffect, useRef, useState } from \"react\";\nimport { useIsMounted } from \"./useIsMounted\";\n\n/** The size of the observed element. */\ntype Size = {\n /** The width of the observed element. */\n width: number | undefined;\n /** The height of the observed element. */\n height: number | undefined;\n};\n\n/** The options for the ResizeObserver. */\nexport type UseResizeObserverOptions<T extends HTMLElement = HTMLElement> = {\n /** The ref of the element to observe. */\n ref: RefObject<T | null>;\n /**\n * When using `onResize`, the hook doesn't re-render on element size changes; it delegates handling to the provided callback.\n * @default undefined\n */\n onResize?: (size: Size) => void;\n /**\n * The box model to use for the ResizeObserver.\n * @default 'content-box'\n */\n box?: \"border-box\" | \"content-box\" | \"device-pixel-content-box\";\n};\n\nconst initialSize: Size = {\n width: undefined,\n height: undefined,\n};\n\n/**\n * Custom hook that observes the size of an element using the [`ResizeObserver API`](https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserver).\n * @template T - The type of the element to observe.\n * @see [Documentation](https://usehooks-ts.com/react-hook/use-resize-observer)\n * @example\n * ```tsx\n * const myRef = useRef(null);\n * const { width = 0, height = 0 } = useResizeObserver({\n * ref: myRef,\n * box: 'content-box',\n * });\n *\n * <div ref={myRef}>Hello, world!</div>\n * ```\n */\nexport function useResizeObserver<T extends HTMLElement = HTMLElement>(\n options: UseResizeObserverOptions<T>,\n): Size {\n const { ref, box = \"content-box\" } = options;\n const [{ width, height }, setSize] = useState<Size>(initialSize);\n const isMounted = useIsMounted();\n const previousSize = useRef<Size>({ ...initialSize });\n const onResize = useRef<((size: Size) => void) | undefined>(undefined);\n onResize.current = options.onResize;\n\n useEffect(() => {\n if (!ref.current) return;\n\n if (typeof window === \"undefined\" || !(\"ResizeObserver\" in window)) return;\n\n const observer = new ResizeObserver(([entry]) => {\n const boxProp =\n box === \"border-box\"\n ? \"borderBoxSize\"\n : box === \"device-pixel-content-box\"\n ? \"devicePixelContentBoxSize\"\n : \"contentBoxSize\";\n\n const newWidth = extractSize(entry, boxProp, \"inlineSize\");\n const newHeight = extractSize(entry, boxProp, \"blockSize\");\n\n const hasChanged =\n previousSize.current.width !== newWidth ||\n previousSize.current.height !== newHeight;\n\n if (hasChanged) {\n const newSize: Size = { width: newWidth, height: newHeight };\n previousSize.current.width = newWidth;\n previousSize.current.height = newHeight;\n\n if (onResize.current) {\n onResize.current(newSize);\n } else {\n if (isMounted()) {\n setSize(newSize);\n }\n }\n }\n });\n\n observer.observe(ref.current, { box });\n\n return () => {\n observer.disconnect();\n };\n }, [box, ref, isMounted]);\n\n return { width, height };\n}\n\ntype BoxSizesKey = keyof Pick<\n ResizeObserverEntry,\n \"borderBoxSize\" | \"contentBoxSize\" | \"devicePixelContentBoxSize\"\n>;\n\nfunction extractSize(\n entry: ResizeObserverEntry,\n box: BoxSizesKey,\n sizeType: keyof ResizeObserverSize,\n): number | undefined {\n if (!entry[box]) {\n if (box === \"contentBoxSize\") {\n return entry.contentRect[sizeType === \"inlineSize\" ? \"width\" : \"height\"];\n }\n return undefined;\n }\n const boxSize = (\n Array.isArray(entry[box]) ? entry[box][0] : entry[box]\n ) as ResizeObserverSize;\n return boxSize[sizeType];\n}\n","import { useEffect } from \"react\";\nimport { useCallbackRef } from \"./useCallbackRef\";\n\nexport type TickEvent = {\n /** delta time in milliseconds since last tick */\n delta: number;\n /** current timestamp in milliseconds */\n now: number;\n};\n\nexport type TickCallback = (event: TickEvent) => void;\n\nexport type UnsubscribeTick = () => void;\n\ntype TickSubscription = {\n /** interval in milliseconds to execute the callback */\n interval: number;\n /** last executed timestamp in milliseconds */\n lastExecuted: number;\n};\n\n/**\n * Global timer singleton using setTimeout for better performance\n */\nclass GlobalTimer {\n /** singleton instance */\n private static instance: GlobalTimer;\n\n /** setTimeout id */\n private timeoutId: ReturnType<typeof setTimeout> | null = null;\n\n /** subscription map */\n private subscribers: Map<TickCallback, TickSubscription> = new Map();\n\n /** is timer running */\n private isRunning = false;\n\n /** internal update interval for smoothness */\n private readonly internalInterval = 200;\n\n /**\n * Get the singleton instance of the timer\n * @returns Timer instance\n */\n static getInstance(): GlobalTimer {\n if (!GlobalTimer.instance) {\n GlobalTimer.instance = new GlobalTimer();\n }\n return GlobalTimer.instance;\n }\n\n /**\n * Subscribe to the timer\n * @param callback tick callback\n * @param interval interval in milliseconds to execute the callback\n * @returns unsubscribe function\n */\n subscribe(callback: TickCallback, interval: number = 1000): UnsubscribeTick {\n this.subscribers.set(callback, {\n interval,\n lastExecuted: Date.now(),\n });\n\n // start timer if this is the first subscriber\n if (!this.isRunning) {\n this.start();\n }\n\n // return unsubscribe function\n return () => {\n this.subscribers.delete(callback);\n // stop timer if no more subscribers\n if (this.subscribers.size === 0) {\n this.stop();\n }\n };\n }\n\n private start(): void {\n if (this.isRunning) return;\n this.isRunning = true;\n this.scheduleNext();\n }\n\n private scheduleNext(): void {\n this.timeoutId = setTimeout(() => {\n const now = Date.now();\n\n // check each subscriber and execute if their interval has passed\n this.subscribers.forEach((config, callback) => {\n if (now - config.lastExecuted >= config.interval) {\n callback({ delta: now - config.lastExecuted, now });\n config.lastExecuted = now;\n }\n });\n\n // schedule next tick if still running\n if (this.isRunning) {\n this.scheduleNext();\n }\n }, this.internalInterval);\n }\n\n private stop(): void {\n this.isRunning = false;\n if (this.timeoutId) {\n clearTimeout(this.timeoutId);\n this.timeoutId = null;\n }\n }\n}\n\n/**\n * Hook to call a callback at specified interval\n * @param callback Function to call at specified interval\n * @param interval Interval in milliseconds (default: 1000ms)\n * @returns\n */\nexport function useTick(callback: TickCallback, interval: number = 1000) {\n const callbackRef = useCallbackRef(callback);\n useEffect(\n () => GlobalTimer.getInstance().subscribe(callbackRef, interval),\n [interval],\n );\n}\n","import { useCallback, useRef, useState } from \"react\";\nimport { TickEvent, useTick } from \"./useTick\";\n\n/**\n * Hook to get the age in milliseconds since birthday in every tick\n * @param birthday Timestamp in milliseconds or Date object (default: now)\n * @param interval Tick interval in milliseconds (default: 1000ms)\n * @returns age in milliseconds since birthday\n */\nexport function useTickAge(\n birthday: number | Date = Date.now(),\n interval: number = 1000,\n) {\n const birthdayRef = useRef(\n birthday instanceof Date ? birthday.getTime() : birthday,\n );\n // keep ref updated\n birthdayRef.current =\n birthday instanceof Date ? birthday.getTime() : birthday;\n\n const [age, setAge] = useState(Math.max(0, Date.now() - birthdayRef.current));\n\n const tickAge = useCallback(\n ({ now }: TickEvent) => setAge(Math.max(0, now - birthdayRef.current)),\n [],\n );\n\n useTick(tickAge, interval);\n\n return age;\n}\n","import { RefObject, useRef } from \"react\";\n\n/**\n * Returns an always updated ref to value\n */\nexport function useValueRef<T>(value: T): RefObject<T> {\n const valueRef = useRef<T>(value);\n valueRef.current = value;\n return valueRef;\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { useRef } from \"react\";\n\ntype NotFunction<T> = T extends (...args: any[]) => any ? never : T;\n\nexport const useUpdatedRef = <T>(val: NotFunction<T>) => {\n const latestRef = useRef<T>(val);\n latestRef.current = val;\n return latestRef;\n};\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { useMemo, useRef } from \"react\";\n\ntype noop = (this: any, ...args: any[]) => any;\n\ntype PickFunction<T extends noop> = (\n this: ThisParameterType<T>,\n ...args: Parameters<T>\n) => ReturnType<T>;\n\nexport const useMemoizedFn = <T extends noop>(fn: T) => {\n if (typeof fn !== \"function\") {\n console.error(\n `useMemoizedFn expected parameter a function, got ${typeof fn}`,\n );\n }\n\n const fnRef = useRef<T>(fn);\n\n fnRef.current = useMemo<T>(() => fn, [fn]);\n\n const memoizedFn = useRef<PickFunction<T>>(undefined);\n\n if (!memoizedFn.current) {\n memoizedFn.current = function (this, ...args) {\n return fnRef.current.apply(this, args);\n };\n }\n\n return memoizedFn.current;\n};\n","import React, { useEffect, useMemo, useRef, useState } from \"react\";\n\nexport interface AudioPlayerOptions {\n volume?: number;\n loop?: boolean;\n autoPlay?: boolean;\n}\n\nexport const useAudioPlayer = (\n src: string,\n options: AudioPlayerOptions = {},\n) => {\n const { volume = 1, loop, autoPlay } = options;\n\n const audioRef = useRef<HTMLAudioElement | null>(null);\n\n const [status, setStatus] = useState<\n \"idle\" | \"play\" | \"playing\" | \"paused\" | \"ended\" | \"error\"\n >(\"idle\");\n\n const onPlay = () => {\n setStatus(\"play\");\n };\n\n const onPlaying = () => {\n setStatus(\"playing\");\n };\n\n const onPause = () => {\n setStatus(\"paused\");\n };\n\n const onEnded = () => {\n setStatus(\"ended\");\n };\n\n const onError = () => {\n setStatus(\"error\");\n };\n\n const element = useMemo(() => {\n return React.createElement(\"audio\", {\n controls: false,\n ref: audioRef,\n autoPlay: autoPlay,\n src: src,\n style: { display: \"none\" },\n onPlay: onPlay,\n onPlaying: onPlaying,\n onPause: onPause,\n onEnded: onEnded,\n onError: onError,\n });\n }, [autoPlay, src, onPlay, onPlaying, onPause, onEnded, onError]);\n\n useEffect(() => {\n const el = audioRef.current;\n if (!el) {\n return;\n }\n el.loop = loop ?? false;\n el.volume = Math.max(0, Math.min(1, volume));\n return () => {\n audioRef.current?.pause();\n audioRef.current = null;\n };\n }, [loop, volume]);\n\n return [element, audioRef, status] as const;\n};\n","import useConstant from \"use-constant\";\nimport { EventEmitter, SimpleDI } from \"@liberfi.io/core\";\n\nexport const useEventEmitter = () => {\n return useConstant(() => {\n let ee = SimpleDI.get<EventEmitter>(\"EE\");\n if (!ee) {\n ee = new EventEmitter();\n SimpleDI.registerByName(\"EE\", ee);\n }\n return ee;\n });\n};\n","export function parseJSON<T>(value: string | null): T | undefined {\n try {\n return value === \"undefined\" ? undefined : JSON.parse(value ?? \"\");\n } catch {\n return undefined;\n }\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { useCallback, useEffect, useState } from \"react\";\nimport { parseJSON } from \"./utils/json\";\n\nexport function useSessionStorage<T>(\n key: string,\n initialValue: T,\n): [T, (data: any) => void] {\n // Get from session storage then\n // parse stored json or return initialValue\n const readValue = useCallback((): T => {\n // Prevent build error \"window is undefined\" but keep keep working\n if (typeof window === \"undefined\") {\n return initialValue;\n }\n\n try {\n const item = window.sessionStorage.getItem(key);\n return item ? (parseJSON(item) as T) : initialValue;\n } catch (error) {\n console.warn(`Error reading sessionStorage key “${key}”:`, error);\n return initialValue;\n }\n }, [initialValue, key]);\n const [storedValue, setStoredValue] = useState<T>(readValue);\n\n const setValue: React.Dispatch<T> = (value: any) => {\n // Prevent build error \"window is undefined\" but keeps working\n if (typeof window == \"undefined\") {\n console.warn(\n `Tried setting sessionStorage key “${key}” even though environment is not a client`,\n );\n }\n\n try {\n // Allow value to be a function so we have the same API as useState\n const newValue = value instanceof Function ? value(storedValue) : value;\n\n // Save to session storage\n window.sessionStorage.setItem(key, JSON.stringify(newValue));\n\n // Save state\n setStoredValue(newValue);\n\n // We dispatch a custom event so every useSessionStorage hook are notified\n // window.dispatchEvent(new Event(\"session-storage\"));\n } catch (error) {\n console.warn(`Error setting sessionStorage key “${key}”:`, error);\n }\n };\n\n useEffect(() => {\n setStoredValue(readValue());\n }, []);\n\n useEffect(() => {\n if (typeof window == \"undefined\") {\n return;\n }\n window.addEventListener?.(\"storage\", handleStorageChange);\n\n return () => {\n window.removeEventListener?.(\"storage\", handleStorageChange);\n };\n });\n\n const handleStorageChange = useCallback(\n (event: StorageEvent | CustomEvent) => {\n if ((event as StorageEvent)?.key && (event as StorageEvent).key !== key) {\n return;\n }\n setStoredValue(readValue());\n },\n [key, readValue],\n );\n\n return [storedValue, setValue];\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\n// https://usehooks-ts.com/react-hook/use-local-storage\nimport { useCallback, useEffect, useState } from \"react\";\nimport { parseJSON } from \"./utils/json\";\n\nexport function useLocalStorage<T>(\n key: string,\n initialValue: T,\n options: {\n parseJSON: typeof parseJSON;\n } = {\n parseJSON: parseJSON,\n },\n): [any, (value: T) => void] {\n // Get from local storage then\n // parse stored json or return initialValue\n const readValue = useCallback((): T => {\n // Prevent build error \"window is undefined\" but keeps working\n if (typeof window === \"undefined\") {\n return initialValue;\n }\n\n try {\n const item = window.localStorage.getItem(key);\n return item ? (options.parseJSON(item) as T) : initialValue;\n } catch (error) {\n console.warn(`Error reading localStorage key “${key}”:`, error);\n return initialValue;\n }\n }, [initialValue, key]);\n\n // State to store our value\n // Pass initial state function to useState so logic is only executed once\n const [storedValue, setStoredValue] = useState<T>(readValue);\n\n // Return a wrapped version of useState's setter function that ...\n // ... persists the new value to localStorage.\n const setValue: React.Dispatch<T> = useCallback(\n (value: T) => {\n // Prevent build error \"window is undefined\" but keeps working\n if (typeof window === \"undefined\") {\n console.warn(\n `Tried setting localStorage key “${key}” even though environment is not a client`,\n );\n }\n\n try {\n // Allow value to be a function so we have the same API as useState\n const newValue = value instanceof Function ? value(storedValue) : value;\n\n // Save to local storage\n window.localStorage.setItem(key, JSON.stringify(newValue));\n // dispath event\n window.dispatchEvent(new Event(\"storage\"));\n\n // Save state\n setStoredValue(() => newValue);\n\n // We dispatch a custom event so every useLocalStorage hook are notified\n // window.dispatchEvent(new Event('local-storage'))\n } catch (error) {\n console.warn(`Error setting localStorage key “${key}”:`, error);\n }\n },\n [storedValue],\n );\n\n useEffect(() => {\n setStoredValue(readValue());\n }, []);\n\n useEffect(() => {\n const handleStorageChange = (event: StorageEvent | CustomEvent) => {\n if ((event as StorageEvent)?.key && (event as StorageEvent).key !== key) {\n return;\n }\n setStoredValue(readValue());\n };\n\n window?.addEventListener?.(\"storage\", handleStorageChange);\n\n return () => {\n window?.removeEventListener?.(\"storage\", handleStorageChange);\n };\n }, [key]);\n\n return [storedValue, setValue];\n}\n","import { SimpleDI } from \"@liberfi.io/core\";\n\nexport const useSimpleDI = <T>() => {\n return {\n get: SimpleDI.get<T>,\n // getOr: SimpleDI.getOr<T>(name, SimpleDI.get<T>(name)),\n register: SimpleDI.register,\n };\n};\n"]}
1
+ {"version":3,"sources":["../src/version.ts","../src/useBoolean.ts","../src/useSafeLayoutEffect.ts","../src/useCallbackRef.ts","../src/useIsMounted.ts","../src/useResizeObserver.ts","../src/useTick.ts","../src/useTickAge.ts","../src/useValueRef.ts","../src/useThrottledResizeObserver.ts","../src/internal/di/container.ts","../src/internal/di/simpleDI.ts","../src/useEventEmitter.ts"],"names":["useState","useCallback","useLayoutEffect","useEffect","useRef","useMemo","throttle","getGlobalObject","useConstant","EventEmitter"],"mappings":";;;;;;;;;;;;;;;;;;AAOA,IAAI,OAAO,WAAW,WAAA,EAAa;AACjC,EAAA,MAAA,CAAO,mBAAA,GAAsB,MAAA,CAAO,mBAAA,IAAuB,EAAC;AAC5D,EAAA,MAAA,CAAO,mBAAA,CAAoB,mBAAmB,CAAA,GAAI,QAAA;AACpD;AAEA,IAAO,eAAA,GAAQ;ACQR,IAAM,UAAA,GAAa,CAAC,YAAA,GAAe,KAAA,KAA4B;AACpE,EAAA,MAAM,CAAC,KAAA,EAAO,QAAQ,CAAA,GAAIA,eAAS,YAAY,CAAA;AAC/C,EAAA,MAAM,UAAUC,iBAAA,CAAY,MAAM,SAAS,IAAI,CAAA,EAAG,EAAE,CAAA;AACpD,EAAA,MAAM,WA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AI;AACP,MAAA,EAAA,GAAK,IAAIC,6BAAA,EAAa;AACtB,MAAA,QAAA,CAAS,cAAA,CAAe,MAAM,EAAE,CAAA;AAAA,IAClC;AACA,IAAA,OAAO,EAAA;AAAA,EACT,CAAC,CAAA;AACH","file":"index.js","sourcesContent":["declare global {\n interface Window {\n __LIBERFI_VERSION__?: {\n [key: string]: string;\n };\n }\n}\nif (typeof window !== \"undefined\") {\n window.__LIBERFI_VERSION__ = window.__LIBERFI_VERSION__ || {};\n window.__LIBERFI_VERSION__[\"@liberfi.io/hooks\"] = \"0.1.23\";\n}\n\nexport default \"0.1.23\";\n","import { useCallback, useState } from \"react\";\n\nexport type UseBooleanReturn = [\n /** current state */\n boolean,\n {\n /** set state to true */\n setTrue: () => void;\n /** set state to false */\n setFalse: () => void;\n /** toggle state */\n toggle: () => void;\n },\n];\n\n/**\n * Hook to manage a boolean state\n * @param initialValue Initial value of the boolean\n * @returns\n */\nexport const useBoolean = (initialValue = false): UseBooleanReturn => {\n const [value, setValue] = useState(initialValue);\n const setTrue = useCallback(() => setValue(true), []);\n const setFalse = useCallback(() => setValue(false), []);\n const toggle = useCallback(() => setValue((v) => !v), []);\n return [value, { setTrue, setFalse, toggle }];\n};\n","import { useEffect, useLayoutEffect } from \"react\";\n\nexport const useSafeLayoutEffect = globalThis?.document\n ? useLayoutEffect\n : useEffect;\n","/* eslint-disable @typescript-eslint/no-explicit-any */\n/**\n * Part of this code is taken from @chakra-ui/system ❤️\n */\nimport { useCallback, useRef } from \"react\";\nimport { useSafeLayoutEffect } from \"./useSafeLayoutEffect\";\n\n/**\n * React hook to persist any value between renders,\n * but keeps it up-to-date if it changes.\n * @param fn the function to persist\n * @param deps the function dependency list\n */\nexport function useCallbackRef<T extends (...args: any[]) => any>(\n fn: T | undefined,\n deps: React.DependencyList = [],\n): T {\n const ref = useRef(fn);\n\n useSafeLayoutEffect(() => {\n ref.current = fn;\n });\n\n return useCallback(((...args) => ref.current?.(...args)) as T, deps);\n}\n","import { useCallback, useEffect, useRef } from \"react\";\n\n/**\n * Custom hook that determines if the component is currently mounted.\n * @example\n * ```tsx\n * const isComponentMounted = useIsMounted();\n * // Use isComponentMounted() to check if the component is currently mounted before performing certain actions.\n * ```\n */\nexport function useIsMounted(): () => boolean {\n const isMounted = useRef(false);\n\n useEffect(() => {\n isMounted.current = true;\n\n return () => {\n isMounted.current = false;\n };\n }, []);\n\n return useCallback(() => isMounted.current, []);\n}\n","import type { RefObject } from \"react\";\nimport { useEffect, useRef, useState } from \"react\";\nimport { useIsMounted } from \"./useIsMounted\";\n\n/** The size of the observed element. */\ntype Size = {\n /** The width of the observed element. */\n width: number | undefined;\n /** The height of the observed element. */\n height: number | undefined;\n};\n\n/** The options for the ResizeObserver. */\nexport type UseResizeObserverOptions<T extends HTMLElement = HTMLElement> = {\n /** The ref of the element to observe. */\n ref: RefObject<T | null>;\n /**\n * When using `onResize`, the hook doesn't re-render on element size changes; it delegates handling to the provided callback.\n * @default undefined\n */\n onResize?: (size: Size) => void;\n /**\n * The box model to use for the ResizeObserver.\n * @default 'content-box'\n */\n box?: \"border-box\" | \"content-box\" | \"device-pixel-content-box\";\n};\n\nconst initialSize: Size = {\n width: undefined,\n height: undefined,\n};\n\n/**\n * Custom hook that observes the size of an element using the [`ResizeObserver API`](https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserver).\n * @template T - The type of the element to observe.\n * @see [Documentation](https://usehooks-ts.com/react-hook/use-resize-observer)\n * @example\n * ```tsx\n * const myRef = useRef(null);\n * const { width = 0, height = 0 } = useResizeObserver({\n * ref: myRef,\n * box: 'content-box',\n * });\n *\n * <div ref={myRef}>Hello, world!</div>\n * ```\n */\nexport function useResizeObserver<T extends HTMLElement = HTMLElement>(\n options: UseResizeObserverOptions<T>,\n): Size {\n const { ref, box = \"content-box\" } = options;\n const [{ width, height }, setSize] = useState<Size>(initialSize);\n const isMounted = useIsMounted();\n const previousSize = useRef<Size>({ ...initialSize });\n const onResize = useRef<((size: Size) => void) | undefined>(undefined);\n onResize.current = options.onResize;\n\n useEffect(() => {\n if (!ref.current) return;\n\n if (typeof window === \"undefined\" || !(\"ResizeObserver\" in window)) return;\n\n const observer = new ResizeObserver(([entry]) => {\n const boxProp =\n box === \"border-box\"\n ? \"borderBoxSize\"\n : box === \"device-pixel-content-box\"\n ? \"devicePixelContentBoxSize\"\n : \"contentBoxSize\";\n\n const newWidth = extractSize(entry, boxProp, \"inlineSize\");\n const newHeight = extractSize(entry, boxProp, \"blockSize\");\n\n const hasChanged =\n previousSize.current.width !== newWidth ||\n previousSize.current.height !== newHeight;\n\n if (hasChanged) {\n const newSize: Size = { width: newWidth, height: newHeight };\n previousSize.current.width = newWidth;\n previousSize.current.height = newHeight;\n\n if (onResize.current) {\n onResize.current(newSize);\n } else {\n if (isMounted()) {\n setSize(newSize);\n }\n }\n }\n });\n\n observer.observe(ref.current, { box });\n\n return () => {\n observer.disconnect();\n };\n }, [box, ref, isMounted]);\n\n return { width, height };\n}\n\ntype BoxSizesKey = keyof Pick<\n ResizeObserverEntry,\n \"borderBoxSize\" | \"contentBoxSize\" | \"devicePixelContentBoxSize\"\n>;\n\nfunction extractSize(\n entry: ResizeObserverEntry,\n box: BoxSizesKey,\n sizeType: keyof ResizeObserverSize,\n): number | undefined {\n if (!entry[box]) {\n if (box === \"contentBoxSize\") {\n return entry.contentRect[sizeType === \"inlineSize\" ? \"width\" : \"height\"];\n }\n return undefined;\n }\n const boxSize = (\n Array.isArray(entry[box]) ? entry[box][0] : entry[box]\n ) as ResizeObserverSize;\n return boxSize[sizeType];\n}\n","import { useEffect } from \"react\";\nimport { useCallbackRef } from \"./useCallbackRef\";\n\nexport type TickEvent = {\n /** delta time in milliseconds since last tick */\n delta: number;\n /** current timestamp in milliseconds */\n now: number;\n};\n\nexport type TickCallback = (event: TickEvent) => void;\n\nexport type UnsubscribeTick = () => void;\n\ntype TickSubscription = {\n /** interval in milliseconds to execute the callback */\n interval: number;\n /** last executed timestamp in milliseconds */\n lastExecuted: number;\n};\n\n/**\n * Global timer singleton using setTimeout for better performance\n */\nclass GlobalTimer {\n /** singleton instance */\n private static instance: GlobalTimer;\n\n /** setTimeout id */\n private timeoutId: ReturnType<typeof setTimeout> | null = null;\n\n /** subscription map */\n private subscribers: Map<TickCallback, TickSubscription> = new Map();\n\n /** is timer running */\n private isRunning = false;\n\n /** internal update interval for smoothness */\n private readonly internalInterval = 200;\n\n /**\n * Get the singleton instance of the timer\n * @returns Timer instance\n */\n static getInstance(): GlobalTimer {\n if (!GlobalTimer.instance) {\n GlobalTimer.instance = new GlobalTimer();\n }\n return GlobalTimer.instance;\n }\n\n /**\n * Subscribe to the timer\n * @param callback tick callback\n * @param interval interval in milliseconds to execute the callback\n * @returns unsubscribe function\n */\n subscribe(callback: TickCallback, interval: number = 1000): UnsubscribeTick {\n this.subscribers.set(callback, {\n interval,\n lastExecuted: Date.now(),\n });\n\n // start timer if this is the first subscriber\n if (!this.isRunning) {\n this.start();\n }\n\n // return unsubscribe function\n return () => {\n this.subscribers.delete(callback);\n // stop timer if no more subscribers\n if (this.subscribers.size === 0) {\n this.stop();\n }\n };\n }\n\n private start(): void {\n if (this.isRunning) return;\n this.isRunning = true;\n this.scheduleNext();\n }\n\n private scheduleNext(): void {\n this.timeoutId = setTimeout(() => {\n const now = Date.now();\n\n // check each subscriber and execute if their interval has passed\n this.subscribers.forEach((config, callback) => {\n if (now - config.lastExecuted >= config.interval) {\n callback({ delta: now - config.lastExecuted, now });\n config.lastExecuted = now;\n }\n });\n\n // schedule next tick if still running\n if (this.isRunning) {\n this.scheduleNext();\n }\n }, this.internalInterval);\n }\n\n private stop(): void {\n this.isRunning = false;\n if (this.timeoutId) {\n clearTimeout(this.timeoutId);\n this.timeoutId = null;\n }\n }\n}\n\n/**\n * Hook to call a callback at specified interval\n * @param callback Function to call at specified interval\n * @param interval Interval in milliseconds (default: 1000ms)\n * @returns\n */\nexport function useTick(callback: TickCallback, interval: number = 1000) {\n const callbackRef = useCallbackRef(callback);\n useEffect(\n () => GlobalTimer.getInstance().subscribe(callbackRef, interval),\n [interval],\n );\n}\n","import { useCallback, useRef, useState } from \"react\";\nimport { TickEvent, useTick } from \"./useTick\";\n\n/**\n * Hook to get the age in milliseconds since birthday in every tick\n * @param birthday Timestamp in milliseconds or Date object (default: now)\n * @param interval Tick interval in milliseconds (default: 1000ms)\n * @returns age in milliseconds since birthday\n */\nexport function useTickAge(\n birthday: number | Date = Date.now(),\n interval: number = 1000,\n) {\n const birthdayRef = useRef(\n birthday instanceof Date ? birthday.getTime() : birthday,\n );\n // keep ref updated\n birthdayRef.current =\n birthday instanceof Date ? birthday.getTime() : birthday;\n\n const [age, setAge] = useState(Math.max(0, Date.now() - birthdayRef.current));\n\n const tickAge = useCallback(\n ({ now }: TickEvent) => setAge(Math.max(0, now - birthdayRef.current)),\n [],\n );\n\n useTick(tickAge, interval);\n\n return age;\n}\n","import { RefObject, useRef } from \"react\";\n\n/**\n * Returns an always updated ref to value\n */\nexport function useValueRef<T>(value: T): RefObject<T> {\n const valueRef = useRef<T>(value);\n valueRef.current = value;\n return valueRef;\n}\n","import { useMemo, useState } from \"react\";\nimport { throttle } from \"lodash-es\";\nimport { useResizeObserver } from \"./useResizeObserver\";\nimport type { UseResizeObserverOptions } from \"./useResizeObserver\";\n\n/** The size of the observed element. */\ntype Size = {\n /** The width of the observed element. */\n width: number | undefined;\n /** The height of the observed element. */\n height: number | undefined;\n};\n\nexport type UseThrottledResizeObserverOptions<\n T extends HTMLElement = HTMLElement,\n> = Pick<UseResizeObserverOptions<T>, \"ref\" | \"box\"> & {\n throttleMs?: number;\n};\n\nexport function useThrottledResizeObserver<T extends HTMLElement = HTMLElement>(\n options: UseThrottledResizeObserverOptions<T>,\n): Size {\n const { ref, box, throttleMs = 50 } = options;\n\n const [size, setSize] = useState<Size>({\n width: undefined,\n height: undefined,\n });\n\n const onResize = useMemo(\n () => throttle(setSize, throttleMs, { leading: true, trailing: true }),\n [throttleMs, setSize],\n );\n\n useResizeObserver({ ref, box, onResize });\n\n return size;\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nexport class Container {\n public constructor(private services: { [name: string]: any } = {}) {}\n\n register(...serviceClasses: any[]): void {\n serviceClasses.forEach((serviceClass) => {\n let service = serviceClass;\n if (service instanceof Function) {\n service = new serviceClass();\n }\n this.add(service);\n });\n }\n\n registerByName(name: string, serviceClass: any): void {\n let service = serviceClass;\n if (service instanceof Function) {\n service = new serviceClass();\n }\n this.addByName(name, service);\n }\n\n get<T = any>(name: string): T {\n return this.services[name];\n }\n\n getAll(): { [name: string]: any } {\n return Object.assign({}, this.services);\n }\n\n private add(service: any): any {\n return this.addByName(service.constructor.name, service);\n }\n\n private addByName(name: string, service: any): any {\n this.services[name] = service;\n this.services[name.toLowerCase()] = service;\n this.services[name.toUpperCase()] = service;\n return this.get(name);\n }\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { getGlobalObject } from \"@liberfi.io/utils\";\nimport { Container } from \"./container\";\n\n/**\n * Global Dependency Injection Container\n */\nexport class SimpleDI {\n private static KEY = \"__LIBERFI_CONTAINER__\";\n private static container: Container =\n (getGlobalObject() as any)[SimpleDI.KEY] || null;\n\n private static getContainer(): Container {\n if (!SimpleDI.container) {\n (getGlobalObject() as any)[SimpleDI.KEY] = SimpleDI.container =\n new Container();\n }\n return SimpleDI.container;\n }\n\n static register(...serviceClasses: any[]): void {\n SimpleDI.getContainer().register(...serviceClasses);\n }\n\n static registerByName(name: string, serviceClass: any): void {\n SimpleDI.getContainer().registerByName(name, serviceClass);\n }\n\n static get<T = any>(name: string): T {\n return SimpleDI.getContainer().get<T>(name);\n }\n\n static getOr<T = any>(name: string, instance: T): T {\n const s = SimpleDI.getContainer().get<T>(name);\n if (!s) {\n SimpleDI.registerByName(name, instance);\n }\n return instance;\n }\n\n static getAll(): { [name: string]: any } {\n return SimpleDI.getContainer().getAll();\n }\n\n private constructor() {}\n}\n","import EventEmitter from \"eventemitter3\";\nimport useConstant from \"use-constant\";\nimport { SimpleDI } from \"./internal/di\";\n\nexport const useEventEmitter = () => {\n return useConstant(() => {\n let ee = SimpleDI.get<EventEmitter>(\"EE\");\n if (!ee) {\n ee = new EventEmitter();\n SimpleDI.registerByName(\"EE\", ee);\n }\n return ee;\n });\n};\n"]}
package/dist/index.mjs CHANGED
@@ -1,8 +1,8 @@
1
- import React, { useLayoutEffect, useEffect, useState, useCallback, useRef, useMemo } from 'react';
1
+ import { useLayoutEffect, useEffect, useState, useCallback, useRef, useMemo } from 'react';
2
+ import { throttle } from 'lodash-es';
3
+ import EventEmitter from 'eventemitter3';
2
4
  import useConstant from 'use-constant';
3
- export { default as useConstant } from 'use-constant';
4
- import { SimpleDI, EventEmitter } from '@liberfi.io/core';
5
- export * from 'use-debounce';
5
+ import { getGlobalObject } from '@liberfi.io/utils';
6
6
 
7
7
  var __defProp = Object.defineProperty;
8
8
  var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
@@ -11,9 +11,9 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
11
11
  // src/version.ts
12
12
  if (typeof window !== "undefined") {
13
13
  window.__LIBERFI_VERSION__ = window.__LIBERFI_VERSION__ || {};
14
- window.__LIBERFI_VERSION__["@liberfi.io/hooks"] = "0.1.22";
14
+ window.__LIBERFI_VERSION__["@liberfi.io/hooks"] = "0.1.23";
15
15
  }
16
- var version_default = "0.1.22";
16
+ var version_default = "0.1.23";
17
17
  var useBoolean = (initialValue = false) => {
18
18
  const [value, setValue] = useState(initialValue);
19
19
  const setTrue = useCallback(() => setValue(true), []);
@@ -187,69 +187,93 @@ function useValueRef(value) {
187
187
  valueRef.current = value;
188
188
  return valueRef;
189
189
  }
190
- var useUpdatedRef = (val) => {
191
- const latestRef = useRef(val);
192
- latestRef.current = val;
193
- return latestRef;
194
- };
195
- var useMemoizedFn = (fn) => {
196
- const fnRef = useRef(fn);
197
- fnRef.current = useMemo(() => fn, [fn]);
198
- const memoizedFn = useRef(void 0);
199
- if (!memoizedFn.current) {
200
- memoizedFn.current = function(...args) {
201
- return fnRef.current.apply(this, args);
202
- };
190
+ function useThrottledResizeObserver(options) {
191
+ const { ref, box, throttleMs = 50 } = options;
192
+ const [size, setSize] = useState({
193
+ width: void 0,
194
+ height: void 0
195
+ });
196
+ const onResize = useMemo(
197
+ () => throttle(setSize, throttleMs, { leading: true, trailing: true }),
198
+ [throttleMs, setSize]
199
+ );
200
+ useResizeObserver({ ref, box, onResize });
201
+ return size;
202
+ }
203
+
204
+ // src/internal/di/container.ts
205
+ var Container = class {
206
+ constructor(services = {}) {
207
+ this.services = services;
203
208
  }
204
- return memoizedFn.current;
205
- };
206
- var useAudioPlayer = (src, options = {}) => {
207
- const { volume = 1, loop, autoPlay } = options;
208
- const audioRef = useRef(null);
209
- const [status, setStatus] = useState("idle");
210
- const onPlay = () => {
211
- setStatus("play");
212
- };
213
- const onPlaying = () => {
214
- setStatus("playing");
215
- };
216
- const onPause = () => {
217
- setStatus("paused");
218
- };
219
- const onEnded = () => {
220
- setStatus("ended");
221
- };
222
- const onError = () => {
223
- setStatus("error");
224
- };
225
- const element = useMemo(() => {
226
- return React.createElement("audio", {
227
- controls: false,
228
- ref: audioRef,
229
- autoPlay,
230
- src,
231
- style: { display: "none" },
232
- onPlay,
233
- onPlaying,
234
- onPause,
235
- onEnded,
236
- onError
209
+ register(...serviceClasses) {
210
+ serviceClasses.forEach((serviceClass) => {
211
+ let service = serviceClass;
212
+ if (service instanceof Function) {
213
+ service = new serviceClass();
214
+ }
215
+ this.add(service);
237
216
  });
238
- }, [autoPlay, src, onPlay, onPlaying, onPause, onEnded, onError]);
239
- useEffect(() => {
240
- const el = audioRef.current;
241
- if (!el) {
242
- return;
217
+ }
218
+ registerByName(name, serviceClass) {
219
+ let service = serviceClass;
220
+ if (service instanceof Function) {
221
+ service = new serviceClass();
243
222
  }
244
- el.loop = loop ?? false;
245
- el.volume = Math.max(0, Math.min(1, volume));
246
- return () => {
247
- audioRef.current?.pause();
248
- audioRef.current = null;
249
- };
250
- }, [loop, volume]);
251
- return [element, audioRef, status];
223
+ this.addByName(name, service);
224
+ }
225
+ get(name) {
226
+ return this.services[name];
227
+ }
228
+ getAll() {
229
+ return Object.assign({}, this.services);
230
+ }
231
+ add(service) {
232
+ return this.addByName(service.constructor.name, service);
233
+ }
234
+ addByName(name, service) {
235
+ this.services[name] = service;
236
+ this.services[name.toLowerCase()] = service;
237
+ this.services[name.toUpperCase()] = service;
238
+ return this.get(name);
239
+ }
252
240
  };
241
+
242
+ // src/internal/di/simpleDI.ts
243
+ var _SimpleDI = class _SimpleDI {
244
+ static getContainer() {
245
+ if (!_SimpleDI.container) {
246
+ getGlobalObject()[_SimpleDI.KEY] = _SimpleDI.container = new Container();
247
+ }
248
+ return _SimpleDI.container;
249
+ }
250
+ static register(...serviceClasses) {
251
+ _SimpleDI.getContainer().register(...serviceClasses);
252
+ }
253
+ static registerByName(name, serviceClass) {
254
+ _SimpleDI.getContainer().registerByName(name, serviceClass);
255
+ }
256
+ static get(name) {
257
+ return _SimpleDI.getContainer().get(name);
258
+ }
259
+ static getOr(name, instance) {
260
+ const s = _SimpleDI.getContainer().get(name);
261
+ if (!s) {
262
+ _SimpleDI.registerByName(name, instance);
263
+ }
264
+ return instance;
265
+ }
266
+ static getAll() {
267
+ return _SimpleDI.getContainer().getAll();
268
+ }
269
+ constructor() {
270
+ }
271
+ };
272
+ __publicField(_SimpleDI, "KEY", "__LIBERFI_CONTAINER__");
273
+ __publicField(_SimpleDI, "container", getGlobalObject()[_SimpleDI.KEY] || null);
274
+ var SimpleDI = _SimpleDI;
275
+
276
+ // src/useEventEmitter.ts
253
277
  var useEventEmitter = () => {
254
278
  return useConstant(() => {
255
279
  let ee = SimpleDI.get("EE");
@@ -261,112 +285,6 @@ var useEventEmitter = () => {
261
285
  });
262
286
  };
263
287
 
264
- // src/utils/json.ts
265
- function parseJSON(value) {
266
- try {
267
- return value === "undefined" ? void 0 : JSON.parse(value ?? "");
268
- } catch {
269
- return void 0;
270
- }
271
- }
272
-
273
- // src/useSessionStorage.ts
274
- function useSessionStorage(key, initialValue) {
275
- const readValue = useCallback(() => {
276
- if (typeof window === "undefined") {
277
- return initialValue;
278
- }
279
- try {
280
- const item = window.sessionStorage.getItem(key);
281
- return item ? parseJSON(item) : initialValue;
282
- } catch (error) {
283
- return initialValue;
284
- }
285
- }, [initialValue, key]);
286
- const [storedValue, setStoredValue] = useState(readValue);
287
- const setValue = (value) => {
288
- try {
289
- const newValue = value instanceof Function ? value(storedValue) : value;
290
- window.sessionStorage.setItem(key, JSON.stringify(newValue));
291
- setStoredValue(newValue);
292
- } catch (error) {
293
- }
294
- };
295
- useEffect(() => {
296
- setStoredValue(readValue());
297
- }, []);
298
- useEffect(() => {
299
- if (typeof window == "undefined") {
300
- return;
301
- }
302
- window.addEventListener?.("storage", handleStorageChange);
303
- return () => {
304
- window.removeEventListener?.("storage", handleStorageChange);
305
- };
306
- });
307
- const handleStorageChange = useCallback(
308
- (event) => {
309
- if (event?.key && event.key !== key) {
310
- return;
311
- }
312
- setStoredValue(readValue());
313
- },
314
- [key, readValue]
315
- );
316
- return [storedValue, setValue];
317
- }
318
- function useLocalStorage(key, initialValue, options = {
319
- parseJSON
320
- }) {
321
- const readValue = useCallback(() => {
322
- if (typeof window === "undefined") {
323
- return initialValue;
324
- }
325
- try {
326
- const item = window.localStorage.getItem(key);
327
- return item ? options.parseJSON(item) : initialValue;
328
- } catch (error) {
329
- return initialValue;
330
- }
331
- }, [initialValue, key]);
332
- const [storedValue, setStoredValue] = useState(readValue);
333
- const setValue = useCallback(
334
- (value) => {
335
- try {
336
- const newValue = value instanceof Function ? value(storedValue) : value;
337
- window.localStorage.setItem(key, JSON.stringify(newValue));
338
- window.dispatchEvent(new Event("storage"));
339
- setStoredValue(() => newValue);
340
- } catch (error) {
341
- }
342
- },
343
- [storedValue]
344
- );
345
- useEffect(() => {
346
- setStoredValue(readValue());
347
- }, []);
348
- useEffect(() => {
349
- const handleStorageChange = (event) => {
350
- if (event?.key && event.key !== key) {
351
- return;
352
- }
353
- setStoredValue(readValue());
354
- };
355
- window?.addEventListener?.("storage", handleStorageChange);
356
- return () => {
357
- window?.removeEventListener?.("storage", handleStorageChange);
358
- };
359
- }, [key]);
360
- return [storedValue, setValue];
361
- }
362
- var useSimpleDI = () => {
363
- return {
364
- get: SimpleDI.get,
365
- // getOr: SimpleDI.getOr<T>(name, SimpleDI.get<T>(name)),
366
- register: SimpleDI.register
367
- };
368
- };
369
-
370
- export { parseJSON, useAudioPlayer, useBoolean, useCallbackRef, useEventEmitter, useIsMounted, useLocalStorage, useMemoizedFn, useResizeObserver, useSafeLayoutEffect, useSessionStorage, useSimpleDI, useTick, useTickAge, useUpdatedRef, useValueRef, version_default as version };
288
+ export { useBoolean, useCallbackRef, useEventEmitter, useIsMounted, useResizeObserver, useSafeLayoutEffect, useThrottledResizeObserver, useTick, useTickAge, useValueRef, version_default as version };
371
289
  //# sourceMappingURL=index.mjs.map
372
290
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/version.ts","../src/useBoolean.ts","../src/useSafeLayoutEffect.ts","../src/useCallbackRef.ts","../src/useIsMounted.ts","../src/useResizeObserver.ts","../src/useTick.ts","../src/useTickAge.ts","../src/useValueRef.ts","../src/shared/useUpdatedRef.ts","../src/shared/useMemoizedFn.ts","../src/shared/useAudio.tsx","../src/useEventEmitter.ts","../src/utils/json.ts","../src/useSessionStorage.ts","../src/useLocalStorage.ts","../src/useSimpleDI.ts"],"names":["useCallback","useRef","useEffect","useState","useMemo","SimpleDI"],"mappings":";;;;;;;;;;;AAOA,IAAI,OAAO,WAAW,WAAA,EAAa;AACjC,EAAA,MAAA,CAAO,mBAAA,GAAsB,MAAA,CAAO,mBAAA,IAAuB,EAAC;AAC5D,EAAA,MAAA,CAAO,mBAAA,CAAoB,mBAAmB,CAAA,GAAI,QAAA;AACpD;AAEA,IAAO,eAAA,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U,MAAM;AACd,IAAA,cAAA,CAAe,WAAW,CAAA;AAAA,EAC5B,CAAA,EAAG,EAAE,CAAA;AAEL,EAAAA,UAAU,MAAM;AACd,IAAA,MAAM,mBAAA,GAAsB,CAAC,KAAA,KAAsC;AACjE,MAAA,IAAK,KAAA,EAAwB,GAAA,IAAQ,KAAA,CAAuB,GAAA,KAAQ,GAAA,EAAK;AACvE,QAAA;AAAA,MACF;AACA,MAAA,cAAA,CAAe,WAAW,CAAA;AAAA,IAC5B,CAAA;AAEA,IAAA,MAAA,EAAQ,gBAAA,GAAmB,WAAW,mBAAmB,CAAA;AAEzD,IAAA,OAAO,MAAM;AACX,MAAA,MAAA,EAAQ,mBAAA,GAAsB,WAAW,mBAAmB,CAAA;AAAA,IAC9D,CAAA;AAAA,EACF,CAAA,EAAG,CAAC,GAAG,CAAC,CAAA;AAER,EAAA,OAAO,CAAC,aAAa,QAAQ,CAAA;AAC/B;ACrFO,IAAM,cAAc,MAAS;AAClC,EAAA,OAAO;AAAA,IACL,KAAKG,QAAAA,CAAS,GAAA;AAAA;AAAA,IAEd,UAAUA,QAAAA,CAAS;AAAA,GACrB;AACF","file":"index.mjs","sourcesContent":["declare global {\n interface Window {\n __LIBERFI_VERSION__?: {\n [key: string]: string;\n };\n }\n}\nif (typeof window !== \"undefined\") {\n window.__LIBERFI_VERSION__ = window.__LIBERFI_VERSION__ || {};\n window.__LIBERFI_VERSION__[\"@liberfi.io/hooks\"] = \"0.1.22\";\n}\n\nexport default \"0.1.22\";\n","import { useCallback, useState } from \"react\";\n\nexport type UseBooleanReturn = [\n /** current state */\n boolean,\n {\n /** set state to true */\n setTrue: () => void;\n /** set state to false */\n setFalse: () => void;\n /** toggle state */\n toggle: () => void;\n },\n];\n\n/**\n * Hook to manage a boolean state\n * @param initialValue Initial value of the boolean\n * @returns\n */\nexport const useBoolean = (initialValue = false): UseBooleanReturn => {\n const [value, setValue] = useState(initialValue);\n const setTrue = useCallback(() => setValue(true), []);\n const setFalse = useCallback(() => setValue(false), []);\n const toggle = useCallback(() => setValue((v) => !v), []);\n return [value, { setTrue, setFalse, toggle }];\n};\n","import { useEffect, useLayoutEffect } from \"react\";\n\nexport const useSafeLayoutEffect = globalThis?.document\n ? useLayoutEffect\n : useEffect;\n","/* eslint-disable @typescript-eslint/no-explicit-any */\n/**\n * Part of this code is taken from @chakra-ui/system ❤️\n */\nimport { useCallback, useRef } from \"react\";\nimport { useSafeLayoutEffect } from \"./useSafeLayoutEffect\";\n\n/**\n * React hook to persist any value between renders,\n * but keeps it up-to-date if it changes.\n * @param fn the function to persist\n * @param deps the function dependency list\n */\nexport function useCallbackRef<T extends (...args: any[]) => any>(\n fn: T | undefined,\n deps: React.DependencyList = [],\n): T {\n const ref = useRef(fn);\n\n useSafeLayoutEffect(() => {\n ref.current = fn;\n });\n\n return useCallback(((...args) => ref.current?.(...args)) as T, deps);\n}\n","import { useCallback, useEffect, useRef } from \"react\";\n\n/**\n * Custom hook that determines if the component is currently mounted.\n * @example\n * ```tsx\n * const isComponentMounted = useIsMounted();\n * // Use isComponentMounted() to check if the component is currently mounted before performing certain actions.\n * ```\n */\nexport function useIsMounted(): () => boolean {\n const isMounted = useRef(false);\n\n useEffect(() => {\n isMounted.current = true;\n\n return () => {\n isMounted.current = false;\n };\n }, []);\n\n return useCallback(() => isMounted.current, []);\n}\n","import type { RefObject } from \"react\";\nimport { useEffect, useRef, useState } from \"react\";\nimport { useIsMounted } from \"./useIsMounted\";\n\n/** The size of the observed element. */\ntype Size = {\n /** The width of the observed element. */\n width: number | undefined;\n /** The height of the observed element. */\n height: number | undefined;\n};\n\n/** The options for the ResizeObserver. */\nexport type UseResizeObserverOptions<T extends HTMLElement = HTMLElement> = {\n /** The ref of the element to observe. */\n ref: RefObject<T | null>;\n /**\n * When using `onResize`, the hook doesn't re-render on element size changes; it delegates handling to the provided callback.\n * @default undefined\n */\n onResize?: (size: Size) => void;\n /**\n * The box model to use for the ResizeObserver.\n * @default 'content-box'\n */\n box?: \"border-box\" | \"content-box\" | \"device-pixel-content-box\";\n};\n\nconst initialSize: Size = {\n width: undefined,\n height: undefined,\n};\n\n/**\n * Custom hook that observes the size of an element using the [`ResizeObserver API`](https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserver).\n * @template T - The type of the element to observe.\n * @see [Documentation](https://usehooks-ts.com/react-hook/use-resize-observer)\n * @example\n * ```tsx\n * const myRef = useRef(null);\n * const { width = 0, height = 0 } = useResizeObserver({\n * ref: myRef,\n * box: 'content-box',\n * });\n *\n * <div ref={myRef}>Hello, world!</div>\n * ```\n */\nexport function useResizeObserver<T extends HTMLElement = HTMLElement>(\n options: UseResizeObserverOptions<T>,\n): Size {\n const { ref, box = \"content-box\" } = options;\n const [{ width, height }, setSize] = useState<Size>(initialSize);\n const isMounted = useIsMounted();\n const previousSize = useRef<Size>({ ...initialSize });\n const onResize = useRef<((size: Size) => void) | undefined>(undefined);\n onResize.current = options.onResize;\n\n useEffect(() => {\n if (!ref.current) return;\n\n if (typeof window === \"undefined\" || !(\"ResizeObserver\" in window)) return;\n\n const observer = new ResizeObserver(([entry]) => {\n const boxProp =\n box === \"border-box\"\n ? \"borderBoxSize\"\n : box === \"device-pixel-content-box\"\n ? \"devicePixelContentBoxSize\"\n : \"contentBoxSize\";\n\n const newWidth = extractSize(entry, boxProp, \"inlineSize\");\n const newHeight = extractSize(entry, boxProp, \"blockSize\");\n\n const hasChanged =\n previousSize.current.width !== newWidth ||\n previousSize.current.height !== newHeight;\n\n if (hasChanged) {\n const newSize: Size = { width: newWidth, height: newHeight };\n previousSize.current.width = newWidth;\n previousSize.current.height = newHeight;\n\n if (onResize.current) {\n onResize.current(newSize);\n } else {\n if (isMounted()) {\n setSize(newSize);\n }\n }\n }\n });\n\n observer.observe(ref.current, { box });\n\n return () => {\n observer.disconnect();\n };\n }, [box, ref, isMounted]);\n\n return { width, height };\n}\n\ntype BoxSizesKey = keyof Pick<\n ResizeObserverEntry,\n \"borderBoxSize\" | \"contentBoxSize\" | \"devicePixelContentBoxSize\"\n>;\n\nfunction extractSize(\n entry: ResizeObserverEntry,\n box: BoxSizesKey,\n sizeType: keyof ResizeObserverSize,\n): number | undefined {\n if (!entry[box]) {\n if (box === \"contentBoxSize\") {\n return entry.contentRect[sizeType === \"inlineSize\" ? \"width\" : \"height\"];\n }\n return undefined;\n }\n const boxSize = (\n Array.isArray(entry[box]) ? entry[box][0] : entry[box]\n ) as ResizeObserverSize;\n return boxSize[sizeType];\n}\n","import { useEffect } from \"react\";\nimport { useCallbackRef } from \"./useCallbackRef\";\n\nexport type TickEvent = {\n /** delta time in milliseconds since last tick */\n delta: number;\n /** current timestamp in milliseconds */\n now: number;\n};\n\nexport type TickCallback = (event: TickEvent) => void;\n\nexport type UnsubscribeTick = () => void;\n\ntype TickSubscription = {\n /** interval in milliseconds to execute the callback */\n interval: number;\n /** last executed timestamp in milliseconds */\n lastExecuted: number;\n};\n\n/**\n * Global timer singleton using setTimeout for better performance\n */\nclass GlobalTimer {\n /** singleton instance */\n private static instance: GlobalTimer;\n\n /** setTimeout id */\n private timeoutId: ReturnType<typeof setTimeout> | null = null;\n\n /** subscription map */\n private subscribers: Map<TickCallback, TickSubscription> = new Map();\n\n /** is timer running */\n private isRunning = false;\n\n /** internal update interval for smoothness */\n private readonly internalInterval = 200;\n\n /**\n * Get the singleton instance of the timer\n * @returns Timer instance\n */\n static getInstance(): GlobalTimer {\n if (!GlobalTimer.instance) {\n GlobalTimer.instance = new GlobalTimer();\n }\n return GlobalTimer.instance;\n }\n\n /**\n * Subscribe to the timer\n * @param callback tick callback\n * @param interval interval in milliseconds to execute the callback\n * @returns unsubscribe function\n */\n subscribe(callback: TickCallback, interval: number = 1000): UnsubscribeTick {\n this.subscribers.set(callback, {\n interval,\n lastExecuted: Date.now(),\n });\n\n // start timer if this is the first subscriber\n if (!this.isRunning) {\n this.start();\n }\n\n // return unsubscribe function\n return () => {\n this.subscribers.delete(callback);\n // stop timer if no more subscribers\n if (this.subscribers.size === 0) {\n this.stop();\n }\n };\n }\n\n private start(): void {\n if (this.isRunning) return;\n this.isRunning = true;\n this.scheduleNext();\n }\n\n private scheduleNext(): void {\n this.timeoutId = setTimeout(() => {\n const now = Date.now();\n\n // check each subscriber and execute if their interval has passed\n this.subscribers.forEach((config, callback) => {\n if (now - config.lastExecuted >= config.interval) {\n callback({ delta: now - config.lastExecuted, now });\n config.lastExecuted = now;\n }\n });\n\n // schedule next tick if still running\n if (this.isRunning) {\n this.scheduleNext();\n }\n }, this.internalInterval);\n }\n\n private stop(): void {\n this.isRunning = false;\n if (this.timeoutId) {\n clearTimeout(this.timeoutId);\n this.timeoutId = null;\n }\n }\n}\n\n/**\n * Hook to call a callback at specified interval\n * @param callback Function to call at specified interval\n * @param interval Interval in milliseconds (default: 1000ms)\n * @returns\n */\nexport function useTick(callback: TickCallback, interval: number = 1000) {\n const callbackRef = useCallbackRef(callback);\n useEffect(\n () => GlobalTimer.getInstance().subscribe(callbackRef, interval),\n [interval],\n );\n}\n","import { useCallback, useRef, useState } from \"react\";\nimport { TickEvent, useTick } from \"./useTick\";\n\n/**\n * Hook to get the age in milliseconds since birthday in every tick\n * @param birthday Timestamp in milliseconds or Date object (default: now)\n * @param interval Tick interval in milliseconds (default: 1000ms)\n * @returns age in milliseconds since birthday\n */\nexport function useTickAge(\n birthday: number | Date = Date.now(),\n interval: number = 1000,\n) {\n const birthdayRef = useRef(\n birthday instanceof Date ? birthday.getTime() : birthday,\n );\n // keep ref updated\n birthdayRef.current =\n birthday instanceof Date ? birthday.getTime() : birthday;\n\n const [age, setAge] = useState(Math.max(0, Date.now() - birthdayRef.current));\n\n const tickAge = useCallback(\n ({ now }: TickEvent) => setAge(Math.max(0, now - birthdayRef.current)),\n [],\n );\n\n useTick(tickAge, interval);\n\n return age;\n}\n","import { RefObject, useRef } from \"react\";\n\n/**\n * Returns an always updated ref to value\n */\nexport function useValueRef<T>(value: T): RefObject<T> {\n const valueRef = useRef<T>(value);\n valueRef.current = value;\n return valueRef;\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { useRef } from \"react\";\n\ntype NotFunction<T> = T extends (...args: any[]) => any ? never : T;\n\nexport const useUpdatedRef = <T>(val: NotFunction<T>) => {\n const latestRef = useRef<T>(val);\n latestRef.current = val;\n return latestRef;\n};\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { useMemo, useRef } from \"react\";\n\ntype noop = (this: any, ...args: any[]) => any;\n\ntype PickFunction<T extends noop> = (\n this: ThisParameterType<T>,\n ...args: Parameters<T>\n) => ReturnType<T>;\n\nexport const useMemoizedFn = <T extends noop>(fn: T) => {\n if (typeof fn !== \"function\") {\n console.error(\n `useMemoizedFn expected parameter a function, got ${typeof fn}`,\n );\n }\n\n const fnRef = useRef<T>(fn);\n\n fnRef.current = useMemo<T>(() => fn, [fn]);\n\n const memoizedFn = useRef<PickFunction<T>>(undefined);\n\n if (!memoizedFn.current) {\n memoizedFn.current = function (this, ...args) {\n return fnRef.current.apply(this, args);\n };\n }\n\n return memoizedFn.current;\n};\n","import React, { useEffect, useMemo, useRef, useState } from \"react\";\n\nexport interface AudioPlayerOptions {\n volume?: number;\n loop?: boolean;\n autoPlay?: boolean;\n}\n\nexport const useAudioPlayer = (\n src: string,\n options: AudioPlayerOptions = {},\n) => {\n const { volume = 1, loop, autoPlay } = options;\n\n const audioRef = useRef<HTMLAudioElement | null>(null);\n\n const [status, setStatus] = useState<\n \"idle\" | \"play\" | \"playing\" | \"paused\" | \"ended\" | \"error\"\n >(\"idle\");\n\n const onPlay = () => {\n setStatus(\"play\");\n };\n\n const onPlaying = () => {\n setStatus(\"playing\");\n };\n\n const onPause = () => {\n setStatus(\"paused\");\n };\n\n const onEnded = () => {\n setStatus(\"ended\");\n };\n\n const onError = () => {\n setStatus(\"error\");\n };\n\n const element = useMemo(() => {\n return React.createElement(\"audio\", {\n controls: false,\n ref: audioRef,\n autoPlay: autoPlay,\n src: src,\n style: { display: \"none\" },\n onPlay: onPlay,\n onPlaying: onPlaying,\n onPause: onPause,\n onEnded: onEnded,\n onError: onError,\n });\n }, [autoPlay, src, onPlay, onPlaying, onPause, onEnded, onError]);\n\n useEffect(() => {\n const el = audioRef.current;\n if (!el) {\n return;\n }\n el.loop = loop ?? false;\n el.volume = Math.max(0, Math.min(1, volume));\n return () => {\n audioRef.current?.pause();\n audioRef.current = null;\n };\n }, [loop, volume]);\n\n return [element, audioRef, status] as const;\n};\n","import useConstant from \"use-constant\";\nimport { EventEmitter, SimpleDI } from \"@liberfi.io/core\";\n\nexport const useEventEmitter = () => {\n return useConstant(() => {\n let ee = SimpleDI.get<EventEmitter>(\"EE\");\n if (!ee) {\n ee = new EventEmitter();\n SimpleDI.registerByName(\"EE\", ee);\n }\n return ee;\n });\n};\n","export function parseJSON<T>(value: string | null): T | undefined {\n try {\n return value === \"undefined\" ? undefined : JSON.parse(value ?? \"\");\n } catch {\n return undefined;\n }\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { useCallback, useEffect, useState } from \"react\";\nimport { parseJSON } from \"./utils/json\";\n\nexport function useSessionStorage<T>(\n key: string,\n initialValue: T,\n): [T, (data: any) => void] {\n // Get from session storage then\n // parse stored json or return initialValue\n const readValue = useCallback((): T => {\n // Prevent build error \"window is undefined\" but keep keep working\n if (typeof window === \"undefined\") {\n return initialValue;\n }\n\n try {\n const item = window.sessionStorage.getItem(key);\n return item ? (parseJSON(item) as T) : initialValue;\n } catch (error) {\n console.warn(`Error reading sessionStorage key “${key}”:`, error);\n return initialValue;\n }\n }, [initialValue, key]);\n const [storedValue, setStoredValue] = useState<T>(readValue);\n\n const setValue: React.Dispatch<T> = (value: any) => {\n // Prevent build error \"window is undefined\" but keeps working\n if (typeof window == \"undefined\") {\n console.warn(\n `Tried setting sessionStorage key “${key}” even though environment is not a client`,\n );\n }\n\n try {\n // Allow value to be a function so we have the same API as useState\n const newValue = value instanceof Function ? value(storedValue) : value;\n\n // Save to session storage\n window.sessionStorage.setItem(key, JSON.stringify(newValue));\n\n // Save state\n setStoredValue(newValue);\n\n // We dispatch a custom event so every useSessionStorage hook are notified\n // window.dispatchEvent(new Event(\"session-storage\"));\n } catch (error) {\n console.warn(`Error setting sessionStorage key “${key}”:`, error);\n }\n };\n\n useEffect(() => {\n setStoredValue(readValue());\n }, []);\n\n useEffect(() => {\n if (typeof window == \"undefined\") {\n return;\n }\n window.addEventListener?.(\"storage\", handleStorageChange);\n\n return () => {\n window.removeEventListener?.(\"storage\", handleStorageChange);\n };\n });\n\n const handleStorageChange = useCallback(\n (event: StorageEvent | CustomEvent) => {\n if ((event as StorageEvent)?.key && (event as StorageEvent).key !== key) {\n return;\n }\n setStoredValue(readValue());\n },\n [key, readValue],\n );\n\n return [storedValue, setValue];\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\n// https://usehooks-ts.com/react-hook/use-local-storage\nimport { useCallback, useEffect, useState } from \"react\";\nimport { parseJSON } from \"./utils/json\";\n\nexport function useLocalStorage<T>(\n key: string,\n initialValue: T,\n options: {\n parseJSON: typeof parseJSON;\n } = {\n parseJSON: parseJSON,\n },\n): [any, (value: T) => void] {\n // Get from local storage then\n // parse stored json or return initialValue\n const readValue = useCallback((): T => {\n // Prevent build error \"window is undefined\" but keeps working\n if (typeof window === \"undefined\") {\n return initialValue;\n }\n\n try {\n const item = window.localStorage.getItem(key);\n return item ? (options.parseJSON(item) as T) : initialValue;\n } catch (error) {\n console.warn(`Error reading localStorage key “${key}”:`, error);\n return initialValue;\n }\n }, [initialValue, key]);\n\n // State to store our value\n // Pass initial state function to useState so logic is only executed once\n const [storedValue, setStoredValue] = useState<T>(readValue);\n\n // Return a wrapped version of useState's setter function that ...\n // ... persists the new value to localStorage.\n const setValue: React.Dispatch<T> = useCallback(\n (value: T) => {\n // Prevent build error \"window is undefined\" but keeps working\n if (typeof window === \"undefined\") {\n console.warn(\n `Tried setting localStorage key “${key}” even though environment is not a client`,\n );\n }\n\n try {\n // Allow value to be a function so we have the same API as useState\n const newValue = value instanceof Function ? value(storedValue) : value;\n\n // Save to local storage\n window.localStorage.setItem(key, JSON.stringify(newValue));\n // dispath event\n window.dispatchEvent(new Event(\"storage\"));\n\n // Save state\n setStoredValue(() => newValue);\n\n // We dispatch a custom event so every useLocalStorage hook are notified\n // window.dispatchEvent(new Event('local-storage'))\n } catch (error) {\n console.warn(`Error setting localStorage key “${key}”:`, error);\n }\n },\n [storedValue],\n );\n\n useEffect(() => {\n setStoredValue(readValue());\n }, []);\n\n useEffect(() => {\n const handleStorageChange = (event: StorageEvent | CustomEvent) => {\n if ((event as StorageEvent)?.key && (event as StorageEvent).key !== key) {\n return;\n }\n setStoredValue(readValue());\n };\n\n window?.addEventListener?.(\"storage\", handleStorageChange);\n\n return () => {\n window?.removeEventListener?.(\"storage\", handleStorageChange);\n };\n }, [key]);\n\n return [storedValue, setValue];\n}\n","import { SimpleDI } from \"@liberfi.io/core\";\n\nexport const useSimpleDI = <T>() => {\n return {\n get: SimpleDI.get<T>,\n // getOr: SimpleDI.getOr<T>(name, SimpleDI.get<T>(name)),\n register: SimpleDI.register,\n };\n};\n"]}
1
+ {"version":3,"sources":["../src/version.ts","../src/useBoolean.ts","../src/useSafeLayoutEffect.ts","../src/useCallbackRef.ts","../src/useIsMounted.ts","../src/useResizeObserver.ts","../src/useTick.ts","../src/useTickAge.ts","../src/useValueRef.ts","../src/useThrottledResizeObserver.ts","../src/internal/di/container.ts","../src/internal/di/simpleDI.ts","../src/useEventEmitter.ts"],"names":["useCallback","useRef","useEffect","useState"],"mappings":";;;;;;;;;;;AAOA,IAAI,OAAO,WAAW,WAAA,EAAa;AACjC,EAAA,MAAA,CAAO,mBAAA,GAAsB,MAAA,CAAO,mBAAA,IAAuB,EAAC;AAC5D,EAAA,MAAA,CAAO,mBAAA,CAAoB,mBAAmB,CAAA,GAAI,QAAA;AACpD;AAEA,IAAO,eAAA,GAAQ;ACQR,IAAM,UAAA,GAAa,CAAC,YAAA,GAAe,KAAA,KAA4B;AACpE,EAAA,MAAM,CAAC,KAAA,EAAO,QAA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AY,MAAM;AACvB,IAAA,IAAI,EAAA,GAAK,QAAA,CAAS,GAAA,CAAkB,IAAI,CAAA;AACxC,IAAA,IAAI,CAAC,EAAA,EAAI;AACP,MAAA,EAAA,GAAK,IAAI,YAAA,EAAa;AACtB,MAAA,QAAA,CAAS,cAAA,CAAe,MAAM,EAAE,CAAA;AAAA,IAClC;AACA,IAAA,OAAO,EAAA;AAAA,EACT,CAAC,CAAA;AACH","file":"index.mjs","sourcesContent":["declare global {\n interface Window {\n __LIBERFI_VERSION__?: {\n [key: string]: string;\n };\n }\n}\nif (typeof window !== \"undefined\") {\n window.__LIBERFI_VERSION__ = window.__LIBERFI_VERSION__ || {};\n window.__LIBERFI_VERSION__[\"@liberfi.io/hooks\"] = \"0.1.23\";\n}\n\nexport default \"0.1.23\";\n","import { useCallback, useState } from \"react\";\n\nexport type UseBooleanReturn = [\n /** current state */\n boolean,\n {\n /** set state to true */\n setTrue: () => void;\n /** set state to false */\n setFalse: () => void;\n /** toggle state */\n toggle: () => void;\n },\n];\n\n/**\n * Hook to manage a boolean state\n * @param initialValue Initial value of the boolean\n * @returns\n */\nexport const useBoolean = (initialValue = false): UseBooleanReturn => {\n const [value, setValue] = useState(initialValue);\n const setTrue = useCallback(() => setValue(true), []);\n const setFalse = useCallback(() => setValue(false), []);\n const toggle = useCallback(() => setValue((v) => !v), []);\n return [value, { setTrue, setFalse, toggle }];\n};\n","import { useEffect, useLayoutEffect } from \"react\";\n\nexport const useSafeLayoutEffect = globalThis?.document\n ? useLayoutEffect\n : useEffect;\n","/* eslint-disable @typescript-eslint/no-explicit-any */\n/**\n * Part of this code is taken from @chakra-ui/system ❤️\n */\nimport { useCallback, useRef } from \"react\";\nimport { useSafeLayoutEffect } from \"./useSafeLayoutEffect\";\n\n/**\n * React hook to persist any value between renders,\n * but keeps it up-to-date if it changes.\n * @param fn the function to persist\n * @param deps the function dependency list\n */\nexport function useCallbackRef<T extends (...args: any[]) => any>(\n fn: T | undefined,\n deps: React.DependencyList = [],\n): T {\n const ref = useRef(fn);\n\n useSafeLayoutEffect(() => {\n ref.current = fn;\n });\n\n return useCallback(((...args) => ref.current?.(...args)) as T, deps);\n}\n","import { useCallback, useEffect, useRef } from \"react\";\n\n/**\n * Custom hook that determines if the component is currently mounted.\n * @example\n * ```tsx\n * const isComponentMounted = useIsMounted();\n * // Use isComponentMounted() to check if the component is currently mounted before performing certain actions.\n * ```\n */\nexport function useIsMounted(): () => boolean {\n const isMounted = useRef(false);\n\n useEffect(() => {\n isMounted.current = true;\n\n return () => {\n isMounted.current = false;\n };\n }, []);\n\n return useCallback(() => isMounted.current, []);\n}\n","import type { RefObject } from \"react\";\nimport { useEffect, useRef, useState } from \"react\";\nimport { useIsMounted } from \"./useIsMounted\";\n\n/** The size of the observed element. */\ntype Size = {\n /** The width of the observed element. */\n width: number | undefined;\n /** The height of the observed element. */\n height: number | undefined;\n};\n\n/** The options for the ResizeObserver. */\nexport type UseResizeObserverOptions<T extends HTMLElement = HTMLElement> = {\n /** The ref of the element to observe. */\n ref: RefObject<T | null>;\n /**\n * When using `onResize`, the hook doesn't re-render on element size changes; it delegates handling to the provided callback.\n * @default undefined\n */\n onResize?: (size: Size) => void;\n /**\n * The box model to use for the ResizeObserver.\n * @default 'content-box'\n */\n box?: \"border-box\" | \"content-box\" | \"device-pixel-content-box\";\n};\n\nconst initialSize: Size = {\n width: undefined,\n height: undefined,\n};\n\n/**\n * Custom hook that observes the size of an element using the [`ResizeObserver API`](https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserver).\n * @template T - The type of the element to observe.\n * @see [Documentation](https://usehooks-ts.com/react-hook/use-resize-observer)\n * @example\n * ```tsx\n * const myRef = useRef(null);\n * const { width = 0, height = 0 } = useResizeObserver({\n * ref: myRef,\n * box: 'content-box',\n * });\n *\n * <div ref={myRef}>Hello, world!</div>\n * ```\n */\nexport function useResizeObserver<T extends HTMLElement = HTMLElement>(\n options: UseResizeObserverOptions<T>,\n): Size {\n const { ref, box = \"content-box\" } = options;\n const [{ width, height }, setSize] = useState<Size>(initialSize);\n const isMounted = useIsMounted();\n const previousSize = useRef<Size>({ ...initialSize });\n const onResize = useRef<((size: Size) => void) | undefined>(undefined);\n onResize.current = options.onResize;\n\n useEffect(() => {\n if (!ref.current) return;\n\n if (typeof window === \"undefined\" || !(\"ResizeObserver\" in window)) return;\n\n const observer = new ResizeObserver(([entry]) => {\n const boxProp =\n box === \"border-box\"\n ? \"borderBoxSize\"\n : box === \"device-pixel-content-box\"\n ? \"devicePixelContentBoxSize\"\n : \"contentBoxSize\";\n\n const newWidth = extractSize(entry, boxProp, \"inlineSize\");\n const newHeight = extractSize(entry, boxProp, \"blockSize\");\n\n const hasChanged =\n previousSize.current.width !== newWidth ||\n previousSize.current.height !== newHeight;\n\n if (hasChanged) {\n const newSize: Size = { width: newWidth, height: newHeight };\n previousSize.current.width = newWidth;\n previousSize.current.height = newHeight;\n\n if (onResize.current) {\n onResize.current(newSize);\n } else {\n if (isMounted()) {\n setSize(newSize);\n }\n }\n }\n });\n\n observer.observe(ref.current, { box });\n\n return () => {\n observer.disconnect();\n };\n }, [box, ref, isMounted]);\n\n return { width, height };\n}\n\ntype BoxSizesKey = keyof Pick<\n ResizeObserverEntry,\n \"borderBoxSize\" | \"contentBoxSize\" | \"devicePixelContentBoxSize\"\n>;\n\nfunction extractSize(\n entry: ResizeObserverEntry,\n box: BoxSizesKey,\n sizeType: keyof ResizeObserverSize,\n): number | undefined {\n if (!entry[box]) {\n if (box === \"contentBoxSize\") {\n return entry.contentRect[sizeType === \"inlineSize\" ? \"width\" : \"height\"];\n }\n return undefined;\n }\n const boxSize = (\n Array.isArray(entry[box]) ? entry[box][0] : entry[box]\n ) as ResizeObserverSize;\n return boxSize[sizeType];\n}\n","import { useEffect } from \"react\";\nimport { useCallbackRef } from \"./useCallbackRef\";\n\nexport type TickEvent = {\n /** delta time in milliseconds since last tick */\n delta: number;\n /** current timestamp in milliseconds */\n now: number;\n};\n\nexport type TickCallback = (event: TickEvent) => void;\n\nexport type UnsubscribeTick = () => void;\n\ntype TickSubscription = {\n /** interval in milliseconds to execute the callback */\n interval: number;\n /** last executed timestamp in milliseconds */\n lastExecuted: number;\n};\n\n/**\n * Global timer singleton using setTimeout for better performance\n */\nclass GlobalTimer {\n /** singleton instance */\n private static instance: GlobalTimer;\n\n /** setTimeout id */\n private timeoutId: ReturnType<typeof setTimeout> | null = null;\n\n /** subscription map */\n private subscribers: Map<TickCallback, TickSubscription> = new Map();\n\n /** is timer running */\n private isRunning = false;\n\n /** internal update interval for smoothness */\n private readonly internalInterval = 200;\n\n /**\n * Get the singleton instance of the timer\n * @returns Timer instance\n */\n static getInstance(): GlobalTimer {\n if (!GlobalTimer.instance) {\n GlobalTimer.instance = new GlobalTimer();\n }\n return GlobalTimer.instance;\n }\n\n /**\n * Subscribe to the timer\n * @param callback tick callback\n * @param interval interval in milliseconds to execute the callback\n * @returns unsubscribe function\n */\n subscribe(callback: TickCallback, interval: number = 1000): UnsubscribeTick {\n this.subscribers.set(callback, {\n interval,\n lastExecuted: Date.now(),\n });\n\n // start timer if this is the first subscriber\n if (!this.isRunning) {\n this.start();\n }\n\n // return unsubscribe function\n return () => {\n this.subscribers.delete(callback);\n // stop timer if no more subscribers\n if (this.subscribers.size === 0) {\n this.stop();\n }\n };\n }\n\n private start(): void {\n if (this.isRunning) return;\n this.isRunning = true;\n this.scheduleNext();\n }\n\n private scheduleNext(): void {\n this.timeoutId = setTimeout(() => {\n const now = Date.now();\n\n // check each subscriber and execute if their interval has passed\n this.subscribers.forEach((config, callback) => {\n if (now - config.lastExecuted >= config.interval) {\n callback({ delta: now - config.lastExecuted, now });\n config.lastExecuted = now;\n }\n });\n\n // schedule next tick if still running\n if (this.isRunning) {\n this.scheduleNext();\n }\n }, this.internalInterval);\n }\n\n private stop(): void {\n this.isRunning = false;\n if (this.timeoutId) {\n clearTimeout(this.timeoutId);\n this.timeoutId = null;\n }\n }\n}\n\n/**\n * Hook to call a callback at specified interval\n * @param callback Function to call at specified interval\n * @param interval Interval in milliseconds (default: 1000ms)\n * @returns\n */\nexport function useTick(callback: TickCallback, interval: number = 1000) {\n const callbackRef = useCallbackRef(callback);\n useEffect(\n () => GlobalTimer.getInstance().subscribe(callbackRef, interval),\n [interval],\n );\n}\n","import { useCallback, useRef, useState } from \"react\";\nimport { TickEvent, useTick } from \"./useTick\";\n\n/**\n * Hook to get the age in milliseconds since birthday in every tick\n * @param birthday Timestamp in milliseconds or Date object (default: now)\n * @param interval Tick interval in milliseconds (default: 1000ms)\n * @returns age in milliseconds since birthday\n */\nexport function useTickAge(\n birthday: number | Date = Date.now(),\n interval: number = 1000,\n) {\n const birthdayRef = useRef(\n birthday instanceof Date ? birthday.getTime() : birthday,\n );\n // keep ref updated\n birthdayRef.current =\n birthday instanceof Date ? birthday.getTime() : birthday;\n\n const [age, setAge] = useState(Math.max(0, Date.now() - birthdayRef.current));\n\n const tickAge = useCallback(\n ({ now }: TickEvent) => setAge(Math.max(0, now - birthdayRef.current)),\n [],\n );\n\n useTick(tickAge, interval);\n\n return age;\n}\n","import { RefObject, useRef } from \"react\";\n\n/**\n * Returns an always updated ref to value\n */\nexport function useValueRef<T>(value: T): RefObject<T> {\n const valueRef = useRef<T>(value);\n valueRef.current = value;\n return valueRef;\n}\n","import { useMemo, useState } from \"react\";\nimport { throttle } from \"lodash-es\";\nimport { useResizeObserver } from \"./useResizeObserver\";\nimport type { UseResizeObserverOptions } from \"./useResizeObserver\";\n\n/** The size of the observed element. */\ntype Size = {\n /** The width of the observed element. */\n width: number | undefined;\n /** The height of the observed element. */\n height: number | undefined;\n};\n\nexport type UseThrottledResizeObserverOptions<\n T extends HTMLElement = HTMLElement,\n> = Pick<UseResizeObserverOptions<T>, \"ref\" | \"box\"> & {\n throttleMs?: number;\n};\n\nexport function useThrottledResizeObserver<T extends HTMLElement = HTMLElement>(\n options: UseThrottledResizeObserverOptions<T>,\n): Size {\n const { ref, box, throttleMs = 50 } = options;\n\n const [size, setSize] = useState<Size>({\n width: undefined,\n height: undefined,\n });\n\n const onResize = useMemo(\n () => throttle(setSize, throttleMs, { leading: true, trailing: true }),\n [throttleMs, setSize],\n );\n\n useResizeObserver({ ref, box, onResize });\n\n return size;\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nexport class Container {\n public constructor(private services: { [name: string]: any } = {}) {}\n\n register(...serviceClasses: any[]): void {\n serviceClasses.forEach((serviceClass) => {\n let service = serviceClass;\n if (service instanceof Function) {\n service = new serviceClass();\n }\n this.add(service);\n });\n }\n\n registerByName(name: string, serviceClass: any): void {\n let service = serviceClass;\n if (service instanceof Function) {\n service = new serviceClass();\n }\n this.addByName(name, service);\n }\n\n get<T = any>(name: string): T {\n return this.services[name];\n }\n\n getAll(): { [name: string]: any } {\n return Object.assign({}, this.services);\n }\n\n private add(service: any): any {\n return this.addByName(service.constructor.name, service);\n }\n\n private addByName(name: string, service: any): any {\n this.services[name] = service;\n this.services[name.toLowerCase()] = service;\n this.services[name.toUpperCase()] = service;\n return this.get(name);\n }\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { getGlobalObject } from \"@liberfi.io/utils\";\nimport { Container } from \"./container\";\n\n/**\n * Global Dependency Injection Container\n */\nexport class SimpleDI {\n private static KEY = \"__LIBERFI_CONTAINER__\";\n private static container: Container =\n (getGlobalObject() as any)[SimpleDI.KEY] || null;\n\n private static getContainer(): Container {\n if (!SimpleDI.container) {\n (getGlobalObject() as any)[SimpleDI.KEY] = SimpleDI.container =\n new Container();\n }\n return SimpleDI.container;\n }\n\n static register(...serviceClasses: any[]): void {\n SimpleDI.getContainer().register(...serviceClasses);\n }\n\n static registerByName(name: string, serviceClass: any): void {\n SimpleDI.getContainer().registerByName(name, serviceClass);\n }\n\n static get<T = any>(name: string): T {\n return SimpleDI.getContainer().get<T>(name);\n }\n\n static getOr<T = any>(name: string, instance: T): T {\n const s = SimpleDI.getContainer().get<T>(name);\n if (!s) {\n SimpleDI.registerByName(name, instance);\n }\n return instance;\n }\n\n static getAll(): { [name: string]: any } {\n return SimpleDI.getContainer().getAll();\n }\n\n private constructor() {}\n}\n","import EventEmitter from \"eventemitter3\";\nimport useConstant from \"use-constant\";\nimport { SimpleDI } from \"./internal/di\";\n\nexport const useEventEmitter = () => {\n return useConstant(() => {\n let ee = SimpleDI.get<EventEmitter>(\"EE\");\n if (!ee) {\n ee = new EventEmitter();\n SimpleDI.registerByName(\"EE\", ee);\n }\n return ee;\n });\n};\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@liberfi.io/hooks",
3
- "version": "0.1.22",
3
+ "version": "0.1.23",
4
4
  "description": "",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.mjs",
@@ -14,11 +14,11 @@
14
14
  "react-dom": ">=18"
15
15
  },
16
16
  "dependencies": {
17
+ "eventemitter3": "^5.0.1",
18
+ "lodash-es": "^4.17.21",
17
19
  "use-constant": "^2.0.0",
18
- "use-debounce": "^10.0.6",
19
- "@liberfi.io/core": "0.1.21",
20
- "@liberfi.io/types": "0.1.25",
21
- "@liberfi.io/utils": "0.1.22"
20
+ "@liberfi.io/types": "0.1.26",
21
+ "@liberfi.io/utils": "0.1.23"
22
22
  },
23
23
  "devDependencies": {
24
24
  "@babel/core": "^7.22.9",
@@ -32,6 +32,7 @@
32
32
  "@testing-library/dom": "^10.4.1",
33
33
  "@testing-library/react": "^16.3.0",
34
34
  "@types/jest": "^29.5.3",
35
+ "@types/lodash-es": "^4.17.12",
35
36
  "@types/react": "^19.1.13",
36
37
  "@types/react-dom": "^19.1.9",
37
38
  "babel-jest": "^29.6.1",
@@ -45,7 +46,7 @@
45
46
  "tsup": "^8.5.0",
46
47
  "typedoc": "^0.28.12",
47
48
  "typescript": "^5.9.2",
48
- "tsconfig": "0.1.13"
49
+ "tsconfig": "0.1.14"
49
50
  },
50
51
  "publishConfig": {
51
52
  "access": "public"