@weser/storage 0.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2022-present Robin Weser
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/README.md ADDED
@@ -0,0 +1,22 @@
1
+ # @weser/storage
2
+
3
+ <img alt="npm version" src="https://badge.fury.io/js/@weser%2Fstorage.svg"> <img alt="npm downloads" src="https://img.shields.io/npm/dm/@weser/storage.svg"> <a href="https://bundlephobia.com/result?p=@weser/storage@latest"><img alt="Bundlephobia" src="https://img.shields.io/bundlephobia/minzip/@weser/storage.svg"></a>
4
+
5
+ ## Installation
6
+
7
+ ```sh
8
+ # npm
9
+ npm i --save @weser/storage
10
+ # yarn
11
+ yarn add @weser/storage
12
+ # pnpm
13
+ pnpm add @weser/storage
14
+ ```
15
+
16
+ ## Documentation
17
+
18
+ ## License
19
+
20
+ @weser/storage is licensed under the [MIT License](http://opensource.org/licenses/MIT).<br>
21
+ Documentation is licensed under [Creative Common License](http://creativecommons.org/licenses/by/4.0/).<br>
22
+ Created with ♥ by [@robinweser](http://weser.io).
@@ -0,0 +1,6 @@
1
+ export default function createIndexedStorage(database: string, table: string): {
2
+ setItem: (key: string, value: any) => Promise<void>;
3
+ getItem: (key: string) => Promise<any>;
4
+ removeItem: (key: string) => Promise<void>;
5
+ clear: () => Promise<void>;
6
+ };
@@ -0,0 +1,32 @@
1
+ import { openDB } from 'idb';
2
+ export default function createIndexedStorage(database, table) {
3
+ const dbPromise = openDB(database, 1, {
4
+ upgrade(db) {
5
+ if (!db.objectStoreNames.contains(table)) {
6
+ db.createObjectStore(table);
7
+ }
8
+ },
9
+ });
10
+ async function setItem(key, value) {
11
+ const db = await dbPromise;
12
+ await db.put(table, value, key);
13
+ }
14
+ async function getItem(key) {
15
+ const db = await dbPromise;
16
+ return await db.get(table, key);
17
+ }
18
+ async function removeItem(key) {
19
+ const db = await dbPromise;
20
+ await db.delete(table, key);
21
+ }
22
+ async function clear() {
23
+ const db = await dbPromise;
24
+ await db.clear(table);
25
+ }
26
+ return {
27
+ setItem,
28
+ getItem,
29
+ removeItem,
30
+ clear,
31
+ };
32
+ }
@@ -0,0 +1,5 @@
1
+ export { default as useStorage } from './useStorage.js';
2
+ export { default as useLocalStorage } from './useLocalStorage.js';
3
+ export { default as useSessionStorage } from './useSessionStorage.js';
4
+ export { default as useIndexedStorage } from './useIndexedStorage.js';
5
+ export { default as createIndexedStorage } from './createIndexedStorage.js';
package/dist/index.js ADDED
@@ -0,0 +1,5 @@
1
+ export { default as useStorage } from './useStorage.js';
2
+ export { default as useLocalStorage } from './useLocalStorage.js';
3
+ export { default as useSessionStorage } from './useSessionStorage.js';
4
+ export { default as useIndexedStorage } from './useIndexedStorage.js';
5
+ export { default as createIndexedStorage } from './createIndexedStorage.js';
@@ -0,0 +1,2 @@
1
+ import { RefObject } from 'react';
2
+ export default function useClickAway(ref: RefObject<HTMLElement | null>, callback: () => void, active?: boolean): void;
@@ -0,0 +1,19 @@
1
+ import { useEffect } from 'react';
2
+ export default function useClickAway(ref, callback, active = true) {
3
+ useEffect(() => {
4
+ const onClickAway = (e) => {
5
+ if (active && ref.current) {
6
+ const isClickOnInner = ref.current.contains(e.target);
7
+ if (!isClickOnInner) {
8
+ setTimeout(callback, 0);
9
+ }
10
+ }
11
+ };
12
+ document.addEventListener('mousedown', onClickAway);
13
+ document.addEventListener('touchstart', onClickAway);
14
+ return () => {
15
+ document.removeEventListener('mousedown', onClickAway);
16
+ document.removeEventListener('touchstart', onClickAway);
17
+ };
18
+ }, [ref, active, callback]);
19
+ }
@@ -0,0 +1 @@
1
+ export default function useClientSide(): boolean;
@@ -0,0 +1,6 @@
1
+ import { useEffect, useState } from 'react';
2
+ export default function useClientSide() {
3
+ const [isClientSide, setClientSide] = useState(false);
4
+ useEffect(() => setClientSide(true), []);
5
+ return isClientSide;
6
+ }
@@ -0,0 +1,16 @@
1
+ export default function useDisclosure(defaultExpanded?: boolean): {
2
+ toggleProps: {
3
+ id: string;
4
+ onClick: void;
5
+ type: string;
6
+ 'aria-expanded': boolean;
7
+ 'aria-controls': string;
8
+ };
9
+ contentProps: {
10
+ id: string;
11
+ 'aria-hidden': boolean;
12
+ 'aria-labelledby': string;
13
+ };
14
+ isExpanded: boolean;
15
+ toggle: void;
16
+ };
@@ -0,0 +1,25 @@
1
+ import { useState, useEffect, useId } from 'react';
2
+ export default function useDisclosure(defaultExpanded = false) {
3
+ const [isExpanded, setExpanded] = useState(defaultExpanded);
4
+ const id = useId();
5
+ useEffect(() => setExpanded(defaultExpanded), [defaultExpanded]);
6
+ const toggle = setExpanded((isExpanded) => !isExpanded);
7
+ const toggleProps = {
8
+ id: id + '-toggle',
9
+ onClick: toggle,
10
+ type: 'button',
11
+ 'aria-expanded': isExpanded,
12
+ 'aria-controls': id + '-content',
13
+ };
14
+ const contentProps = {
15
+ id: id + '-content',
16
+ 'aria-hidden': !isExpanded,
17
+ 'aria-labelledby': id + '-toggle',
18
+ };
19
+ return {
20
+ toggleProps,
21
+ contentProps,
22
+ isExpanded,
23
+ toggle,
24
+ };
25
+ }
@@ -0,0 +1,7 @@
1
+ import { RefObject } from 'react';
2
+ type Config = {
3
+ visible?: boolean;
4
+ autoFocus?: boolean;
5
+ };
6
+ export default function useFocusTrap(ref: RefObject<HTMLElement | null>, active: boolean, config?: Config): void;
7
+ export {};
@@ -0,0 +1,77 @@
1
+ import { useEffect } from 'react';
2
+ import useKeyDown from './useKeyDown.js';
3
+ const focusableSelector = `:is(
4
+ a[href],
5
+ area[href],
6
+ input:not([disabled]),
7
+ select:not([disabled]),
8
+ textarea:not([disabled]),
9
+ button:not([disabled]),
10
+ [tabindex]:not([tabindex="-1"]),
11
+ [contenteditable]
12
+ )`;
13
+ export default function useFocusTrap(ref, active, config = {}) {
14
+ const { visible, autoFocus = true } = config;
15
+ useKeyDown('Tab', (e) => {
16
+ const element = ref.current;
17
+ if (!active || !element) {
18
+ return;
19
+ }
20
+ const focusables = [
21
+ ...element.querySelectorAll(focusableSelector),
22
+ ].filter((el) => el.hasAttribute('tabindex')
23
+ ? el.getAttribute('tabindex') !== '-1'
24
+ : true);
25
+ const firstFocusable = focusables[0];
26
+ const lastFocusable = focusables[focusables.length - 1];
27
+ const activeElement = document.activeElement;
28
+ let nextElement;
29
+ if (activeElement && focusables.includes(activeElement)) {
30
+ const index = focusables.indexOf(activeElement);
31
+ if (e.shiftKey) {
32
+ if (index === 0) {
33
+ nextElement = lastFocusable;
34
+ }
35
+ }
36
+ else {
37
+ if (index === focusables.length - 1) {
38
+ nextElement = firstFocusable;
39
+ }
40
+ }
41
+ }
42
+ else {
43
+ if (e.shiftKey) {
44
+ nextElement = lastFocusable;
45
+ }
46
+ else {
47
+ nextElement = firstFocusable;
48
+ }
49
+ }
50
+ if (nextElement) {
51
+ ;
52
+ nextElement.focus();
53
+ e.preventDefault();
54
+ }
55
+ }, {
56
+ active,
57
+ });
58
+ useEffect(() => {
59
+ const element = ref.current;
60
+ if (!autoFocus || !visible || !element) {
61
+ return;
62
+ }
63
+ const autoFocusElement = element.querySelector('[data-autofocus="true"]' + focusableSelector);
64
+ if (autoFocusElement) {
65
+ // @ts-ignore
66
+ autoFocusElement.focus();
67
+ return;
68
+ }
69
+ const nodeList = element.querySelectorAll(focusableSelector);
70
+ const elements = Array.from(nodeList);
71
+ const focusableElements = elements.filter((element) => !element.hasAttribute('tabindex') ||
72
+ element.getAttribute('tabindex') === '0');
73
+ // 1. focus the first focusable
74
+ // @ts-ignore, TODO: fix typing
75
+ focusableElements[0]?.focus();
76
+ }, [visible, ref, autoFocus]);
77
+ }
@@ -0,0 +1,3 @@
1
+ /// <reference types="react" />
2
+ import { Config } from './useStorage.js';
3
+ export default function useIndexedStorage<T>(database: string, table: string, key: string, initialState: T, config?: Config<T>): [T, import("react").Dispatch<import("react").SetStateAction<T>>, boolean];
@@ -0,0 +1,6 @@
1
+ import useStorage from './useStorage.js';
2
+ import createIndexedStorage from './createIndexedStorage.js';
3
+ export default function useIndexedStorage(database, table, key, initialState, config) {
4
+ const storage = createIndexedStorage(database, table);
5
+ return useStorage(() => storage, key, initialState, config);
6
+ }
@@ -0,0 +1,7 @@
1
+ import { RefObject } from 'react';
2
+ type Options = {
3
+ target?: RefObject<HTMLElement>;
4
+ active?: boolean;
5
+ };
6
+ export default function useKeyDown(keyCode: string | Array<string>, callback: (e: KeyboardEvent) => void, options?: Options): void;
7
+ export {};
@@ -0,0 +1,22 @@
1
+ import { useEffect } from 'react';
2
+ export default function useKeyDown(keyCode, callback, options = {}) {
3
+ const { active = true, target } = options;
4
+ const keyCodes = [].concat(keyCode);
5
+ useEffect(() => {
6
+ if (!active || target === null || target?.current === null) {
7
+ return;
8
+ }
9
+ const hasRef = target && target.current;
10
+ const element = hasRef ? target.current : document;
11
+ if (element) {
12
+ const handleKeyDown = (e) => {
13
+ if (keyCodes.includes(e.code) &&
14
+ (!hasRef || (hasRef && document.activeElement === element))) {
15
+ callback(e);
16
+ }
17
+ };
18
+ element.addEventListener('keydown', handleKeyDown);
19
+ return () => element.removeEventListener('keydown', handleKeyDown);
20
+ }
21
+ }, [target, callback, active, keyCode]);
22
+ }
@@ -0,0 +1,3 @@
1
+ /// <reference types="react" />
2
+ import { Config } from './useStorage';
3
+ export default function useLocalStorage<T = any>(key: string, initialState: T, config?: Config<T>): [T, import("react").Dispatch<import("react").SetStateAction<T>>, boolean];
@@ -0,0 +1,4 @@
1
+ import useStorage from './useStorage';
2
+ export default function useLocalStorage(key, initialState, config) {
3
+ return useStorage(() => localStorage, key, initialState, config);
4
+ }
@@ -0,0 +1,3 @@
1
+ type FunctionalSetState<T> = (previousState: T) => T;
2
+ export default function useOptimisticState<T>(initialState: T): [T, (newState: T | FunctionalSetState<T>) => void];
3
+ export {};
@@ -0,0 +1,11 @@
1
+ import { useOptimistic } from 'react';
2
+ export default function useOptimisticState(initialState) {
3
+ const [state, setState] = useOptimistic(initialState, (_, update) => update);
4
+ function setFunctionalState(newState) {
5
+ if (newState instanceof Function) {
6
+ return setState(newState(state));
7
+ }
8
+ return setState(newState);
9
+ }
10
+ return [state, setFunctionalState];
11
+ }
@@ -0,0 +1 @@
1
+ export default function useRouteChange(onRouteChange: (path: string) => void, pathname?: string): void;
@@ -0,0 +1,19 @@
1
+ import { useEffect } from 'react';
2
+ export default function useRouteChange(onRouteChange, pathname) {
3
+ useEffect(() => {
4
+ if (pathname) {
5
+ onRouteChange(pathname);
6
+ }
7
+ }, [pathname]);
8
+ // track clicks on links with the current path
9
+ useEffect(() => {
10
+ const onClick = (e) => {
11
+ const target = e.target;
12
+ if (target.tagName === 'A' && target.href === pathname) {
13
+ onRouteChange(pathname);
14
+ }
15
+ };
16
+ window.addEventListener('click', onClick);
17
+ return () => window.removeEventListener('click', onClick);
18
+ }, []);
19
+ }
@@ -0,0 +1 @@
1
+ export default function useScrollBlocking(active: boolean): void;
@@ -0,0 +1,28 @@
1
+ import { useEffect } from 'react';
2
+ let scrollTop;
3
+ function blockScrolling(scrollElement) {
4
+ scrollTop = window.scrollY;
5
+ scrollElement.style.overflow = 'hidden';
6
+ scrollElement.style.position = 'fixed';
7
+ scrollElement.style.width = '100%';
8
+ scrollElement.style.top = -scrollTop + 'px';
9
+ }
10
+ function enableScrolling(scrollElement) {
11
+ scrollElement.style.removeProperty('position');
12
+ scrollElement.style.removeProperty('overflow');
13
+ scrollElement.style.removeProperty('top');
14
+ scrollElement.style.removeProperty('width');
15
+ window.scrollTo(0, scrollTop);
16
+ }
17
+ function toggleScrolling(isBlocked) {
18
+ const scrollElement = document.scrollingElement;
19
+ if (isBlocked) {
20
+ blockScrolling(scrollElement);
21
+ }
22
+ else {
23
+ enableScrolling(scrollElement);
24
+ }
25
+ }
26
+ export default function useScrollBlocking(active) {
27
+ useEffect(() => toggleScrolling(active), [active]);
28
+ }
@@ -0,0 +1,3 @@
1
+ /// <reference types="react" />
2
+ import { Config } from './useStorage';
3
+ export default function useSessionStorage<T = any>(key: string, initialState: T, config?: Config<T>): [T, import("react").Dispatch<import("react").SetStateAction<T>>, boolean];
@@ -0,0 +1,4 @@
1
+ import useStorage from './useStorage';
2
+ export default function useSessionStorage(key, initialState, config) {
3
+ return useStorage(() => sessionStorage, key, initialState, config);
4
+ }
@@ -0,0 +1,12 @@
1
+ import { Dispatch, SetStateAction } from 'react';
2
+ type SyntheticStorage<T = any> = {
3
+ getItem: (key: string) => T | Promise<T>;
4
+ setItem: (key: string, value: T) => void | Promise<void>;
5
+ };
6
+ export type Config<T> = {
7
+ onHydrated?: (value?: T) => void;
8
+ encode?: (value: T) => any;
9
+ decode?: (value: any) => T;
10
+ };
11
+ export default function useStorage<T = any>(getStorage: () => Storage | SyntheticStorage, key: string, initialState: T, config?: Config<T>): [T, Dispatch<SetStateAction<T>>, boolean];
12
+ export {};
@@ -0,0 +1,56 @@
1
+ 'use client';
2
+ import { useEffect, useState } from 'react';
3
+ export default function useStorage(getStorage, key, initialState, config = {}) {
4
+ const { onHydrated, encode = JSON.stringify, decode = JSON.parse } = config;
5
+ const [isLoading, setLoading] = useState(true);
6
+ // @ts-ignore
7
+ const [state, setState] = useState(initialState);
8
+ useEffect(() => {
9
+ if (!isLoading) {
10
+ return;
11
+ }
12
+ const storage = getStorage();
13
+ if (storage) {
14
+ const isAsync = storage.getItem.constructor.name === 'AsyncFunction';
15
+ async function getStorageValue() {
16
+ if (isAsync) {
17
+ return await storage.getItem(key);
18
+ }
19
+ else {
20
+ return storage.getItem(key);
21
+ }
22
+ }
23
+ async function hydrate() {
24
+ const data = await getStorageValue();
25
+ let parsedValue;
26
+ if (data) {
27
+ try {
28
+ parsedValue = decode(data);
29
+ setState(parsedValue);
30
+ }
31
+ catch (e) { }
32
+ }
33
+ setLoading(false);
34
+ if (onHydrated) {
35
+ onHydrated(parsedValue);
36
+ }
37
+ }
38
+ hydrate();
39
+ }
40
+ else {
41
+ setLoading(false);
42
+ }
43
+ }, []);
44
+ useEffect(() => {
45
+ if (!isLoading) {
46
+ const storage = getStorage();
47
+ if (storage) {
48
+ try {
49
+ storage.setItem(key, encode(state));
50
+ }
51
+ catch (e) { }
52
+ }
53
+ }
54
+ }, [isLoading, state]);
55
+ return [state, setState, isLoading];
56
+ }
@@ -0,0 +1,7 @@
1
+ import { RefObject } from 'react';
2
+ type Props = {
3
+ defaultVisible?: boolean;
4
+ getTrigger?: () => HTMLElement | null;
5
+ };
6
+ export default function useTrigger({ defaultVisible, getTrigger, }?: Props): [boolean, (visible: boolean) => void, RefObject<HTMLElement>];
7
+ export {};
@@ -0,0 +1,24 @@
1
+ import { useEffect, useRef, useState } from 'react';
2
+ export default function useTrigger({ defaultVisible = false, getTrigger, } = {}) {
3
+ const triggerRef = useRef(null);
4
+ const [isVisible, _setVisible] = useState(false);
5
+ function getTriggerElement() {
6
+ if (getTrigger) {
7
+ return getTrigger();
8
+ }
9
+ return triggerRef.current;
10
+ }
11
+ function setVisible(visible) {
12
+ if (isVisible !== visible) {
13
+ _setVisible(visible);
14
+ if (!visible) {
15
+ const trigger = getTriggerElement();
16
+ if (trigger) {
17
+ trigger.focus();
18
+ }
19
+ }
20
+ }
21
+ }
22
+ useEffect(() => _setVisible(defaultVisible), [defaultVisible]);
23
+ return [isVisible, setVisible, triggerRef];
24
+ }
package/package.json ADDED
@@ -0,0 +1,64 @@
1
+ {
2
+ "name": "@weser/storage",
3
+ "version": "0.0.3",
4
+ "description": "React hooks for working with persisted state",
5
+ "author": "Robin Weser <robin@weser.io>",
6
+ "license": "MIT",
7
+ "homepage": "https://github.com/robinweser/weser.git",
8
+ "repository": "https://github.com/robinweser/weser.git",
9
+ "type": "module",
10
+ "main": "dist/index.js",
11
+ "module": "dist/index.js",
12
+ "types": "dist/index.d.ts",
13
+ "sideEffects": false,
14
+ "publishConfig": {
15
+ "access": "public"
16
+ },
17
+ "files": [
18
+ "LICENSE",
19
+ "README.md",
20
+ "dist/**"
21
+ ],
22
+ "browserslist": [
23
+ "IE >= 11",
24
+ "Firefox >= 60",
25
+ "Safari >= 11.1",
26
+ "Chrome >= 66",
27
+ "ChromeAndroid >= 66",
28
+ "iOS >= 11.3",
29
+ "Edge >= 15"
30
+ ],
31
+ "scripts": {
32
+ "setup": "pnpm build",
33
+ "clean": "rimraf dist",
34
+ "build": "tsc -b",
35
+ "dev": "pnpm build -w",
36
+ "test": "echo 1"
37
+ },
38
+ "keywords": [
39
+ "react",
40
+ "react-hook",
41
+ "react hooks",
42
+ "hooks",
43
+ "persisted state",
44
+ "storage",
45
+ "local storage",
46
+ "session storage",
47
+ "indexed db",
48
+ "utils"
49
+ ],
50
+ "dependencies": {
51
+ "idb": "^8.0.1"
52
+ },
53
+ "peerDependencies": {
54
+ "react": ">19.0.0"
55
+ },
56
+ "devDependencies": {
57
+ "@types/react": "^19.0.0",
58
+ "ava": "^6.1.3",
59
+ "react": "^19.0.0",
60
+ "rimraf": "^3.0.2",
61
+ "typescript": "^5.4.5"
62
+ },
63
+ "gitHead": "de1f00e9f6100c1e0ccfdb8145af827e027c280a"
64
+ }