@geee-be/react-utils 1.0.1

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.
@@ -0,0 +1,18 @@
1
+ /** @type { import('@storybook/react-vite').StorybookConfig } */
2
+ const config = {
3
+ stories: ['../src/**/*.mdx', '../src/**/*.stories.@(js|jsx|mjs|ts|tsx)'],
4
+ addons: [
5
+ '@storybook/addon-links',
6
+ '@storybook/addon-essentials',
7
+ '@storybook/addon-onboarding',
8
+ '@storybook/addon-interactions',
9
+ ],
10
+ framework: {
11
+ name: '@storybook/react-vite',
12
+ options: {},
13
+ },
14
+ docs: {
15
+ autodocs: 'tag',
16
+ },
17
+ };
18
+ export default config;
@@ -0,0 +1,14 @@
1
+ /** @type { import('@storybook/react').Preview } */
2
+ const preview = {
3
+ parameters: {
4
+ actions: { argTypesRegex: '^on[A-Z].*' },
5
+ controls: {
6
+ matchers: {
7
+ color: /(background|color)$/i,
8
+ date: /Date$/i,
9
+ },
10
+ },
11
+ },
12
+ };
13
+
14
+ export default preview;
package/CHANGELOG.md ADDED
@@ -0,0 +1,7 @@
1
+ # @geee-be/react-utils
2
+
3
+ ## 1.0.1
4
+
5
+ ### Patch Changes
6
+
7
+ - 68cdda9: Added some hooks for state management
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2022 geee-be
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/package.json ADDED
@@ -0,0 +1,43 @@
1
+ {
2
+ "name": "@geee-be/react-utils",
3
+ "version": "1.0.1",
4
+ "description": "",
5
+ "keywords": [],
6
+ "license": "MIT",
7
+ "author": "Greg Bacchus",
8
+ "type": "module",
9
+ "main": "dist/index.js",
10
+ "types": "src/index.ts",
11
+ "devDependencies": {
12
+ "@storybook/addon-essentials": "^7.6.7",
13
+ "@storybook/addon-interactions": "^7.6.7",
14
+ "@storybook/addon-links": "^7.6.7",
15
+ "@storybook/addon-onboarding": "^1.0.10",
16
+ "@storybook/blocks": "^7.6.7",
17
+ "@storybook/react": "^7.6.7",
18
+ "@storybook/react-vite": "^7.6.7",
19
+ "@storybook/test": "^7.6.7",
20
+ "@types/react": "^18.2.0",
21
+ "@types/react-dom": "^18.2.0",
22
+ "prop-types": "^15.8.1",
23
+ "react": "^18.2.0",
24
+ "react-dom": "^18.2.0",
25
+ "storybook": "^7.6.7"
26
+ },
27
+ "peerDependencies": {
28
+ "react": ">18",
29
+ "react-dom": ">18"
30
+ },
31
+ "scripts": {
32
+ "prebuild": "rimraf dist/*",
33
+ "build": "tsc",
34
+ "build-storybook": "storybook build",
35
+ "lint": "npm run lint:eslint && npm run lint:types && npm run lint:unused-exports",
36
+ "lint:eslint": "eslint src/ --ext .ts,.tsx",
37
+ "lint:types": "tsc --noEmit",
38
+ "lint:unused-exports": "ts-unused-exports tsconfig.unused-exports.json --excludePathsFromReport=src/index.ts",
39
+ "prestart:dev": "rimraf dist/*",
40
+ "start:dev": "tsc --watch",
41
+ "storybook": "storybook dev -p 6006"
42
+ }
43
+ }
@@ -0,0 +1,4 @@
1
+ export * from './use-broadcast-channel.js';
2
+ export * from './use-history-state.js';
3
+ export * from './use-local-state.js';
4
+
@@ -0,0 +1,26 @@
1
+ export interface SerializationOptions<T, S> {
2
+ fromSerializable: (value: S) => T;
3
+ toSerializable: (value: T) => S;
4
+ }
5
+
6
+ export const deserialize = <T, S>(serialized: unknown, fromSerializable?: (value: S) => T): T | undefined => {
7
+ if (!serialized || typeof serialized !== 'string') return undefined;
8
+ try {
9
+ return fromSerializable ? fromSerializable(JSON.parse(serialized) as S) : (JSON.parse(serialized) as T);
10
+ } catch {
11
+ return undefined;
12
+ }
13
+ };
14
+
15
+ export const serialize = <T, S>(value: T, toSerializable?: (value: T) => S): string => {
16
+ try {
17
+ return JSON.stringify(toSerializable ? toSerializable(value) : value);
18
+ } catch {
19
+ return '';
20
+ }
21
+ };
22
+
23
+ export type InitialValue<T> = T | (() => T);
24
+
25
+ export const getInitialValue = <T>(initialValue: InitialValue<T>): T =>
26
+ initialValue instanceof Function ? initialValue() : initialValue;
@@ -0,0 +1,63 @@
1
+ import { useCallback, useEffect, useMemo } from 'react';
2
+
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 = <T = string>(
24
+ channelName: string,
25
+ handleMessage?: (event: MessageEvent) => void,
26
+ handleMessageError?: (event: MessageEvent) => void,
27
+ ): ((data: T) => void) => {
28
+ const channel = useMemo(
29
+ () =>
30
+ typeof window !== 'undefined' && 'BroadcastChannel' in window
31
+ ? new BroadcastChannel(channelName + '-channel')
32
+ : null,
33
+ [channelName],
34
+ );
35
+
36
+ useChannelEventListener(channel, 'message', handleMessage);
37
+ useChannelEventListener(channel, 'messageerror', handleMessageError);
38
+
39
+ useEffect(() => () => channel?.close(), [channel]);
40
+
41
+ return useCallback(
42
+ (data: T) => {
43
+ channel?.postMessage(data);
44
+ },
45
+ [channel],
46
+ );
47
+ };
48
+
49
+ // Helpers
50
+
51
+ /** Hook to subscribe/unsubscribe from channel events. */
52
+ const useChannelEventListener = <K extends keyof BroadcastChannelEventMap>(
53
+ channel: BroadcastChannel | null,
54
+ event: K,
55
+ handler: (e: BroadcastChannelEventMap[K]) => void = () => {},
56
+ ): void => {
57
+ useEffect(() => {
58
+ if (!channel) return;
59
+
60
+ channel.addEventListener(event, handler);
61
+ return () => channel.removeEventListener(event, handler);
62
+ }, [channel, event, handler]);
63
+ };
@@ -0,0 +1,26 @@
1
+ import type { Dispatch, SetStateAction } from 'react';
2
+ import { useEffect, useState } from 'react';
3
+ import type { InitialValue, SerializationOptions } from './state.util.js';
4
+ import { deserialize, getInitialValue, serialize } from './state.util.js';
5
+
6
+ export const useHistoryState = <T, S = T>(
7
+ key: string,
8
+ initialValue: InitialValue<T>,
9
+ replace = true,
10
+ options?: SerializationOptions<T, S>,
11
+ ): [T, Dispatch<SetStateAction<T>>] => {
12
+ const [value, setValue] = useState<T>(
13
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
14
+ () => deserialize(history.state?.[key], options?.fromSerializable) ?? getInitialValue(initialValue),
15
+ );
16
+
17
+ useEffect(() => {
18
+ if (replace) {
19
+ history.replaceState({ ...history.state, [key]: serialize(value, options?.toSerializable) }, '');
20
+ } else {
21
+ history.pushState({ ...history.state, [key]: serialize(value, options?.toSerializable) }, '');
22
+ }
23
+ }, [key, value]);
24
+
25
+ return [value, setValue];
26
+ };
@@ -0,0 +1,22 @@
1
+ import type { Meta, StoryObj } from '@storybook/react';
2
+ import { useLocalState } from './use-local-state.js';
3
+
4
+ const meta: Meta = {
5
+ title: 'hooks/useLocalState',
6
+ };
7
+
8
+ export default meta;
9
+ type Story = StoryObj;
10
+
11
+ export const Primary: Story = {
12
+ render: () => {
13
+ const [value, setValue] = useLocalState('story-use-local-state', { val: 1 });
14
+ console.log('render', value);
15
+ return (
16
+ <div>
17
+ {JSON.stringify(value)}
18
+ <button onClick={() => setValue((prev) => ({ val: prev.val + 1 ?? -2 }))}>Inc</button>
19
+ </div>
20
+ );
21
+ },
22
+ };
@@ -0,0 +1,45 @@
1
+ import type { Dispatch, SetStateAction } from 'react';
2
+ import { useCallback, useEffect, useState } from 'react';
3
+ import type { InitialValue, SerializationOptions } from './state.util.js';
4
+ import { deserialize, getInitialValue, serialize } from './state.util.js';
5
+
6
+ type SetValue<T> = Dispatch<SetStateAction<T>>;
7
+
8
+ // Provides hook that persist the state with local storage with sync'd updates
9
+ // NOTE: this only syncs between different window contexts, it doesn't sync between components in the same window
10
+ export const useLocalState = <T, S = T>(
11
+ key: string,
12
+ initialValue: InitialValue<T>,
13
+ options?: SerializationOptions<T, S>,
14
+ ): [T, SetValue<T>] => {
15
+ const readValue = useCallback((): T => {
16
+ const item = localStorage.getItem(key);
17
+ return deserialize<T, S>(item, options?.fromSerializable) ?? getInitialValue(initialValue);
18
+ }, [key, options?.fromSerializable, initialValue]);
19
+
20
+ const [storedValue, setStoredValue] = useState<T>(readValue);
21
+
22
+ const setValue: SetValue<T> = useCallback(
23
+ (value) => {
24
+ const newValue = value instanceof Function ? value(storedValue) : value;
25
+ setStoredValue(newValue);
26
+ localStorage.setItem(key, serialize<T, S>(newValue, options?.toSerializable));
27
+ },
28
+ [key, options?.toSerializable, storedValue],
29
+ );
30
+
31
+ const storageValueChanged = useCallback(
32
+ (ev: StorageEvent) => {
33
+ if (ev.storageArea !== localStorage || ev.key !== key) return;
34
+ setStoredValue(deserialize<T, S>(ev.newValue, options?.fromSerializable) ?? getInitialValue(initialValue));
35
+ },
36
+ [key, options?.fromSerializable, initialValue],
37
+ );
38
+
39
+ useEffect(() => {
40
+ window.addEventListener('storage', storageValueChanged);
41
+ return () => window.removeEventListener('storage', storageValueChanged);
42
+ }, [storageValueChanged]);
43
+
44
+ return [storedValue, setValue];
45
+ };
package/src/index.ts ADDED
@@ -0,0 +1 @@
1
+ export * from './hooks/index.js';
package/tsconfig.json ADDED
@@ -0,0 +1,7 @@
1
+ {
2
+ "extends": "../create/tsconfig.web.json",
3
+ "compilerOptions": {
4
+ "outDir": "./dist"
5
+ },
6
+ "include": ["./src"]
7
+ }
@@ -0,0 +1,4 @@
1
+ {
2
+ "extends": "./tsconfig.json",
3
+ "exclude": ["**/*.stories.tsx"]
4
+ }