@geee-be/react-utils 1.0.2 → 1.0.4

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/CHANGELOG.md CHANGED
@@ -1,5 +1,17 @@
1
1
  # @geee-be/react-utils
2
2
 
3
+ ## 1.0.4
4
+
5
+ ### Patch Changes
6
+
7
+ - b1b11e7: use client
8
+
9
+ ## 1.0.3
10
+
11
+ ### Patch Changes
12
+
13
+ - ffa9af4: fix: missing output
14
+
3
15
  ## 1.0.2
4
16
 
5
17
  ### Patch Changes
@@ -0,0 +1,3 @@
1
+ export * from './use-broadcast-channel.js';
2
+ export * from './use-history-state.js';
3
+ export * from './use-local-state.js';
@@ -0,0 +1,19 @@
1
+ export const deserialize = (serialized, fromSerializable) => {
2
+ if (!serialized || typeof serialized !== 'string')
3
+ return undefined;
4
+ try {
5
+ return fromSerializable ? fromSerializable(JSON.parse(serialized)) : JSON.parse(serialized);
6
+ }
7
+ catch {
8
+ return undefined;
9
+ }
10
+ };
11
+ export const serialize = (value, toSerializable) => {
12
+ try {
13
+ return JSON.stringify(toSerializable ? toSerializable(value) : value);
14
+ }
15
+ catch {
16
+ return '';
17
+ }
18
+ };
19
+ export const getInitialValue = (initialValue) => initialValue instanceof Function ? initialValue() : initialValue;
@@ -0,0 +1,43 @@
1
+ 'use client';
2
+ import { useCallback, useEffect, useMemo } from 'react';
3
+ /**
4
+ * React hook to create and manage a Broadcast Channel across multiple browser windows.
5
+ *
6
+ * @param channelName Static name of channel used across the browser windows.
7
+ * @param handleMessage Callback to handle the event generated when `message` is received.
8
+ * @param handleMessageError [optional] Callback to handle the event generated when `error` is received.
9
+ * @returns A function to send/post message on the channel.
10
+ * @example
11
+ * ```tsx
12
+ * import {useBroadcastChannel} from 'react-broadcast-channel';
13
+ *
14
+ * function App () {
15
+ * const postUserIdMessage = useBroadcastChannel('userId', (e) => alert(e.data));
16
+ * return (<button onClick={() => postUserIdMessage('ABC123')}>Send UserId</button>);
17
+ * }
18
+ * ```
19
+ * ---
20
+ * Works in browser that support Broadcast Channel API natively. See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Broadcast_Channel_API#browser_compatibility).
21
+ * To support other browsers, install and use [broadcastchannel-polyfill](https://www.npmjs.com/package/broadcastchannel-polyfill).
22
+ */
23
+ export const useBroadcastChannel = (channelName, handleMessage, handleMessageError) => {
24
+ const channel = useMemo(() => typeof window !== 'undefined' && 'BroadcastChannel' in window
25
+ ? new BroadcastChannel(channelName + '-channel')
26
+ : null, [channelName]);
27
+ useChannelEventListener(channel, 'message', handleMessage);
28
+ useChannelEventListener(channel, 'messageerror', handleMessageError);
29
+ useEffect(() => () => channel?.close(), [channel]);
30
+ return useCallback((data) => {
31
+ channel?.postMessage(data);
32
+ }, [channel]);
33
+ };
34
+ // Helpers
35
+ /** Hook to subscribe/unsubscribe from channel events. */
36
+ const useChannelEventListener = (channel, event, handler = () => { }) => {
37
+ useEffect(() => {
38
+ if (!channel)
39
+ return;
40
+ channel.addEventListener(event, handler);
41
+ return () => channel.removeEventListener(event, handler);
42
+ }, [channel, event, handler]);
43
+ };
@@ -0,0 +1,17 @@
1
+ 'use client';
2
+ import { useEffect, useState } from 'react';
3
+ import { deserialize, getInitialValue, serialize } from './state.util.js';
4
+ export const useHistoryState = (key, initialValue, replace = true, options) => {
5
+ const [value, setValue] = useState(
6
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
7
+ () => deserialize(history.state?.[key], options?.fromSerializable) ?? getInitialValue(initialValue));
8
+ useEffect(() => {
9
+ if (replace) {
10
+ history.replaceState({ ...history.state, [key]: serialize(value, options?.toSerializable) }, '');
11
+ }
12
+ else {
13
+ history.pushState({ ...history.state, [key]: serialize(value, options?.toSerializable) }, '');
14
+ }
15
+ }, [key, value]);
16
+ return [value, setValue];
17
+ };
@@ -0,0 +1,27 @@
1
+ 'use client';
2
+ import { useCallback, useEffect, useState } from 'react';
3
+ import { deserialize, getInitialValue, serialize } from './state.util.js';
4
+ // Provides hook that persist the state with local storage with sync'd updates
5
+ // NOTE: this only syncs between different window contexts, it doesn't sync between components in the same window
6
+ export const useLocalState = (key, initialValue, options) => {
7
+ const readValue = useCallback(() => {
8
+ const item = localStorage.getItem(key);
9
+ return deserialize(item, options?.fromSerializable) ?? getInitialValue(initialValue);
10
+ }, [key, options?.fromSerializable, initialValue]);
11
+ const [storedValue, setStoredValue] = useState(readValue);
12
+ const setValue = useCallback((value) => {
13
+ const newValue = value instanceof Function ? value(storedValue) : value;
14
+ setStoredValue(newValue);
15
+ localStorage.setItem(key, serialize(newValue, options?.toSerializable));
16
+ }, [key, options?.toSerializable, storedValue]);
17
+ const storageValueChanged = useCallback((ev) => {
18
+ if (ev.storageArea !== localStorage || ev.key !== key)
19
+ return;
20
+ setStoredValue(deserialize(ev.newValue, options?.fromSerializable) ?? getInitialValue(initialValue));
21
+ }, [key, options?.fromSerializable, initialValue]);
22
+ useEffect(() => {
23
+ window.addEventListener('storage', storageValueChanged);
24
+ return () => window.removeEventListener('storage', storageValueChanged);
25
+ }, [storageValueChanged]);
26
+ return [storedValue, setValue];
27
+ };
@@ -0,0 +1,13 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { useLocalState } from './use-local-state.js';
3
+ const meta = {
4
+ title: 'hooks/useLocalState',
5
+ };
6
+ export default meta;
7
+ export const Primary = {
8
+ render: () => {
9
+ const [value, setValue] = useLocalState('story-use-local-state', { val: 1 });
10
+ console.log('render', value);
11
+ return (_jsxs("div", { children: [JSON.stringify(value), _jsx("button", { onClick: () => setValue((prev) => ({ val: prev.val + 1 ?? -2 })), children: "Inc" })] }));
12
+ },
13
+ };
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ export * from './hooks/index.js';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@geee-be/react-utils",
3
- "version": "1.0.2",
3
+ "version": "1.0.4",
4
4
  "description": "",
5
5
  "keywords": [],
6
6
  "license": "MIT",
@@ -1,3 +1,5 @@
1
+ 'use client';
2
+
1
3
  import { useCallback, useEffect, useMemo } from 'react';
2
4
 
3
5
  /**
@@ -1,3 +1,5 @@
1
+ 'use client';
2
+
1
3
  import type { Dispatch, SetStateAction } from 'react';
2
4
  import { useEffect, useState } from 'react';
3
5
  import type { InitialValue, SerializationOptions } from './state.util.js';
@@ -1,3 +1,5 @@
1
+ 'use client';
2
+
1
3
  import type { Dispatch, SetStateAction } from 'react';
2
4
  import { useCallback, useEffect, useState } from 'react';
3
5
  import type { InitialValue, SerializationOptions } from './state.util.js';
package/tsconfig.json CHANGED
@@ -1,6 +1,7 @@
1
1
  {
2
2
  "extends": "../create/tsconfig.web.json",
3
3
  "compilerOptions": {
4
+ "noEmit": false,
4
5
  "outDir": "./dist"
5
6
  },
6
7
  "include": ["./src"]