@weser/tree 1.0.0

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.
Files changed (78) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +3 -0
  3. package/dist/addNode.d.ts +2 -0
  4. package/dist/addNode.js +9 -0
  5. package/dist/arrayEach.d.ts +1 -0
  6. package/dist/arrayEach.js +5 -0
  7. package/dist/arrayFilter.d.ts +1 -0
  8. package/dist/arrayFilter.js +10 -0
  9. package/dist/arrayGroupBy.d.ts +1 -0
  10. package/dist/arrayGroupBy.js +8 -0
  11. package/dist/arrayMap.d.ts +1 -0
  12. package/dist/arrayMap.js +7 -0
  13. package/dist/arrayReduce.d.ts +1 -0
  14. package/dist/arrayReduce.js +6 -0
  15. package/dist/cloneNode.d.ts +2 -0
  16. package/dist/cloneNode.js +22 -0
  17. package/dist/createNode.d.ts +2 -0
  18. package/dist/createNode.js +7 -0
  19. package/dist/findAllNode.d.ts +2 -0
  20. package/dist/findAllNode.js +12 -0
  21. package/dist/findNode.d.ts +2 -0
  22. package/dist/findNode.js +14 -0
  23. package/dist/getNode.d.ts +2 -0
  24. package/dist/getNode.js +14 -0
  25. package/dist/getParentNode.d.ts +2 -0
  26. package/dist/getParentNode.js +4 -0
  27. package/dist/index.d.ts +14 -0
  28. package/dist/index.js +14 -0
  29. package/dist/insertNode.d.ts +2 -0
  30. package/dist/insertNode.js +17 -0
  31. package/dist/invariant.d.ts +1 -0
  32. package/dist/invariant.js +5 -0
  33. package/dist/moveNode.d.ts +2 -0
  34. package/dist/moveNode.js +12 -0
  35. package/dist/objectEach.d.ts +1 -0
  36. package/dist/objectEach.js +5 -0
  37. package/dist/objectFilter.d.ts +1 -0
  38. package/dist/objectFilter.js +11 -0
  39. package/dist/objectFind.d.ts +1 -0
  40. package/dist/objectFind.js +7 -0
  41. package/dist/objectKeys.d.ts +1 -0
  42. package/dist/objectKeys.js +3 -0
  43. package/dist/objectMap.d.ts +1 -0
  44. package/dist/objectMap.js +8 -0
  45. package/dist/objectMergeDeep.d.ts +1 -0
  46. package/dist/objectMergeDeep.js +20 -0
  47. package/dist/objectReduce.d.ts +1 -0
  48. package/dist/objectReduce.js +6 -0
  49. package/dist/removeNode.d.ts +2 -0
  50. package/dist/removeNode.js +14 -0
  51. package/dist/replaceNode.d.ts +2 -0
  52. package/dist/replaceNode.js +21 -0
  53. package/dist/traverse.d.ts +2 -0
  54. package/dist/traverse.js +12 -0
  55. package/dist/tsconfig.tsbuildinfo +1 -0
  56. package/dist/types.d.ts +7 -0
  57. package/dist/types.js +1 -0
  58. package/dist/updateNode.d.ts +2 -0
  59. package/dist/updateNode.js +12 -0
  60. package/dist/useAction.d.ts +12 -0
  61. package/dist/useAction.js +40 -0
  62. package/dist/useClickAway.d.ts +2 -0
  63. package/dist/useClickAway.js +19 -0
  64. package/dist/useClientOnly.d.ts +1 -0
  65. package/dist/useClientOnly.js +6 -0
  66. package/dist/useDisclosure.d.ts +16 -0
  67. package/dist/useDisclosure.js +25 -0
  68. package/dist/useFocusTrap.d.ts +7 -0
  69. package/dist/useFocusTrap.js +77 -0
  70. package/dist/useKeyDown.d.ts +7 -0
  71. package/dist/useKeyDown.js +22 -0
  72. package/dist/useRouteChange.d.ts +1 -0
  73. package/dist/useRouteChange.js +19 -0
  74. package/dist/useScrollBlocking.d.ts +1 -0
  75. package/dist/useScrollBlocking.js +28 -0
  76. package/dist/useTrigger.d.ts +7 -0
  77. package/dist/useTrigger.js +24 -0
  78. package/package.json +52 -0
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,3 @@
1
+ # @weser/loops
2
+
3
+ [Documentation](https://packages.weser.io/loops)
@@ -0,0 +1,2 @@
1
+ import { type BaseNode } from './types.js';
2
+ export default function addNode<T extends BaseNode<T>>(rootNode: T, id: string, newNode: T): T;
@@ -0,0 +1,9 @@
1
+ import getNode from './getNode.js';
2
+ import insertNode from './insertNode.js';
3
+ export default function addNode(rootNode, id, newNode) {
4
+ const parentNode = getNode(rootNode, id);
5
+ if (!parentNode || !parentNode.children) {
6
+ return rootNode;
7
+ }
8
+ return insertNode(rootNode, id, parentNode.children.length, newNode);
9
+ }
@@ -0,0 +1 @@
1
+ export default function arrayEach<T>(arr: Array<T>, iterator: (value: T, index: number, length: number, array: Array<T>) => void): void;
@@ -0,0 +1,5 @@
1
+ export default function arrayEach(arr, iterator) {
2
+ for (let i = 0, len = arr.length; i < len; ++i) {
3
+ iterator(arr[i], i, len, arr);
4
+ }
5
+ }
@@ -0,0 +1 @@
1
+ export default function arrayFilter<T>(arr: Array<T>, filter: (value: T, index: number, length: number, array: Array<T>) => boolean): T[];
@@ -0,0 +1,10 @@
1
+ export default function arrayFilter(arr, filter) {
2
+ const filteredArr = [];
3
+ for (let i = 0, len = arr.length; i < len; ++i) {
4
+ const value = arr[i];
5
+ if (filter(value, i, len, arr)) {
6
+ filteredArr.push(value);
7
+ }
8
+ }
9
+ return filteredArr;
10
+ }
@@ -0,0 +1 @@
1
+ export default function arrayGroupBy<T extends Record<string, any>>(arr: Array<T>, key: keyof T | ((item: T) => string)): Record<string, T[]>;
@@ -0,0 +1,8 @@
1
+ export default function arrayGroupBy(arr, key) {
2
+ return arr.reduce((grouped, item) => {
3
+ const group = typeof key === 'function' ? key(item) : item[key];
4
+ grouped[group] = grouped[group] || [];
5
+ grouped[group].push(item);
6
+ return grouped;
7
+ }, {});
8
+ }
@@ -0,0 +1 @@
1
+ export default function arrayMap<T>(arr: Array<T>, mapper: (value: T, index: number, length: number, array: Array<T>) => any): any[];
@@ -0,0 +1,7 @@
1
+ export default function arrayMap(arr, mapper) {
2
+ const mappedArr = [];
3
+ for (let i = 0, len = arr.length; i < len; ++i) {
4
+ mappedArr.push(mapper(arr[i], i, len, arr));
5
+ }
6
+ return mappedArr;
7
+ }
@@ -0,0 +1 @@
1
+ export default function arrayReduce<T, B>(arr: Array<T>, reducer: (accumulator: B, value: T, index: number, length: number, array: Array<T>) => B, initialValue: B): B;
@@ -0,0 +1,6 @@
1
+ export default function arrayReduce(arr, reducer, initialValue) {
2
+ for (let i = 0, len = arr.length; i < len; ++i) {
3
+ initialValue = reducer(initialValue, arr[i], i, len, arr);
4
+ }
5
+ return initialValue;
6
+ }
@@ -0,0 +1,2 @@
1
+ import { BaseNode } from './types';
2
+ export default function cloneNode<T extends BaseNode<T>>(rootNode: T, id: string): T | null;
@@ -0,0 +1,22 @@
1
+ import getNode from './getNode';
2
+ export default function cloneNode(rootNode, id) {
3
+ const node = getNode(rootNode, id);
4
+ if (!node) {
5
+ return null;
6
+ }
7
+ return cloneNodeById(node);
8
+ }
9
+ function cloneNodeById(node) {
10
+ if (!node.children || node.children.length === 0) {
11
+ return {
12
+ ...node,
13
+ id: crypto.randomUUID(),
14
+ };
15
+ }
16
+ const newChildren = node.children.map(cloneNodeById);
17
+ return {
18
+ ...node,
19
+ id: crypto.randomUUID(),
20
+ children: newChildren,
21
+ };
22
+ }
@@ -0,0 +1,2 @@
1
+ import { type BaseNode, type BaseNodeInput } from './types.js';
2
+ export default function createNode<T extends BaseNode<T>>(node: BaseNodeInput<T>): T;
@@ -0,0 +1,7 @@
1
+ export default function createNode(node) {
2
+ const id = crypto.randomUUID();
3
+ return {
4
+ ...node,
5
+ id,
6
+ };
7
+ }
@@ -0,0 +1,2 @@
1
+ import { type BaseNode } from './types.js';
2
+ export default function findAllNode<T extends BaseNode<T>>(rootNode: T, condition: (node: T) => boolean): Array<T>;
@@ -0,0 +1,12 @@
1
+ export default function findAllNode(rootNode, condition) {
2
+ const nodes = [];
3
+ if (condition(rootNode)) {
4
+ nodes.push(rootNode);
5
+ }
6
+ if (rootNode.children) {
7
+ for (const node of rootNode.children) {
8
+ nodes.push(...findAllNode(node, condition));
9
+ }
10
+ }
11
+ return nodes;
12
+ }
@@ -0,0 +1,2 @@
1
+ import { type BaseNode } from './types.js';
2
+ export default function findNode<T extends BaseNode<T>>(rootNode: T, condition: (node: T) => boolean): T | null;
@@ -0,0 +1,14 @@
1
+ export default function findNode(rootNode, condition) {
2
+ if (condition(rootNode)) {
3
+ return rootNode;
4
+ }
5
+ if (rootNode.children) {
6
+ for (const node of rootNode.children) {
7
+ const result = findNode(node, condition);
8
+ if (result) {
9
+ return result;
10
+ }
11
+ }
12
+ }
13
+ return null;
14
+ }
@@ -0,0 +1,2 @@
1
+ import { type BaseNode } from './types.js';
2
+ export default function getNode<T extends BaseNode<T>>(rootNode: T, id: string): T | null;
@@ -0,0 +1,14 @@
1
+ export default function getNode(rootNode, id) {
2
+ if (rootNode.id === id) {
3
+ return rootNode;
4
+ }
5
+ if (rootNode.children) {
6
+ for (const node of rootNode.children) {
7
+ const result = getNode(node, id);
8
+ if (result) {
9
+ return result;
10
+ }
11
+ }
12
+ }
13
+ return null;
14
+ }
@@ -0,0 +1,2 @@
1
+ import { type BaseNode } from './types.js';
2
+ export default function getParentNode<T extends BaseNode<T>>(rootNode: T, id: string): T | null;
@@ -0,0 +1,4 @@
1
+ import findNode from './findNode.js';
2
+ export default function getParentNode(rootNode, id) {
3
+ return findNode(rootNode, (node) => Boolean(node.children && node.children.find((node) => node.id === id)));
4
+ }
@@ -0,0 +1,14 @@
1
+ export { default as addNode } from './addNode.js';
2
+ export { default as cloneNode } from './cloneNode.js';
3
+ export { default as createNode } from './createNode.js';
4
+ export { default as findNode } from './findNode.js';
5
+ export { default as findAllNode } from './findAllNode.js';
6
+ export { default as getNode } from './getNode.js';
7
+ export { default as getParentNode } from './getParentNode.js';
8
+ export { default as insertNode } from './insertNode.js';
9
+ export { default as moveNode } from './moveNode.js';
10
+ export { default as removeNode } from './removeNode.js';
11
+ export { default as replaceNode } from './replaceNode.js';
12
+ export { default as traverse } from './traverse.js';
13
+ export { default as updateNode } from './updateNode.js';
14
+ export * from './types.js';
package/dist/index.js ADDED
@@ -0,0 +1,14 @@
1
+ export { default as addNode } from './addNode.js';
2
+ export { default as cloneNode } from './cloneNode.js';
3
+ export { default as createNode } from './createNode.js';
4
+ export { default as findNode } from './findNode.js';
5
+ export { default as findAllNode } from './findAllNode.js';
6
+ export { default as getNode } from './getNode.js';
7
+ export { default as getParentNode } from './getParentNode.js';
8
+ export { default as insertNode } from './insertNode.js';
9
+ export { default as moveNode } from './moveNode.js';
10
+ export { default as removeNode } from './removeNode.js';
11
+ export { default as replaceNode } from './replaceNode.js';
12
+ export { default as traverse } from './traverse.js';
13
+ export { default as updateNode } from './updateNode.js';
14
+ export * from './types.js';
@@ -0,0 +1,2 @@
1
+ import { type BaseNode } from './types.js';
2
+ export default function insertNode<T extends BaseNode<T>>(rootNode: T, id: string, index: number, newNode: T): T;
@@ -0,0 +1,17 @@
1
+ import getNode from './getNode.js';
2
+ import replaceNode from './replaceNode.js';
3
+ export default function insertNode(rootNode, id, index, newNode) {
4
+ const parentNode = getNode(rootNode, id);
5
+ if (!parentNode || !parentNode.children) {
6
+ return rootNode;
7
+ }
8
+ const children = [
9
+ ...parentNode.children.slice(0, index),
10
+ newNode,
11
+ ...parentNode.children.slice(index),
12
+ ];
13
+ return replaceNode(rootNode, id, {
14
+ ...parentNode,
15
+ children,
16
+ });
17
+ }
@@ -0,0 +1 @@
1
+ export default function invariant(condition: boolean, message: string): void;
@@ -0,0 +1,5 @@
1
+ export default function invariant(condition, message) {
2
+ if (!condition) {
3
+ throw new Error(message);
4
+ }
5
+ }
@@ -0,0 +1,2 @@
1
+ import { type BaseNode } from './types.js';
2
+ export default function moveNode<T extends BaseNode<T>>(rootNode: T, id: string, parentId: string, index?: number): T;
@@ -0,0 +1,12 @@
1
+ import getNode from './getNode.js';
2
+ import insertNode from './insertNode.js';
3
+ import removeNode from './removeNode.js';
4
+ export default function moveNode(rootNode, id, parentId, index) {
5
+ const node = getNode(rootNode, id);
6
+ const parentNode = getNode(rootNode, parentId);
7
+ if (!node || !parentNode || !parentNode.children) {
8
+ return rootNode;
9
+ }
10
+ const removedNode = removeNode(rootNode, id);
11
+ return insertNode(removedNode, parentId, index ?? parentNode.children.length, node);
12
+ }
@@ -0,0 +1 @@
1
+ export default function objectEach<T extends Record<PropertyKey, any>>(obj: T, iterator: (value: T[keyof T], key: keyof T, obj: T) => void): void;
@@ -0,0 +1,5 @@
1
+ export default function objectEach(obj, iterator) {
2
+ for (const key in obj) {
3
+ iterator(obj[key], key, obj);
4
+ }
5
+ }
@@ -0,0 +1 @@
1
+ export default function objectFilter<T extends Record<PropertyKey, any>>(obj: T, filter: (value: T[keyof T], key: keyof T, obj: T) => boolean): {};
@@ -0,0 +1,11 @@
1
+ export default function objectFilter(obj, filter) {
2
+ const filteredObj = {};
3
+ for (const key in obj) {
4
+ const value = obj[key];
5
+ if (filter(value, key, obj)) {
6
+ // @ts-ignore
7
+ filteredObj[key] = value;
8
+ }
9
+ }
10
+ return filteredObj;
11
+ }
@@ -0,0 +1 @@
1
+ export default function objectFind<T extends Record<PropertyKey, any>>(obj: T, query: (value: T[keyof T], key: keyof T, obj: T) => boolean): Extract<keyof T, string> | undefined;
@@ -0,0 +1,7 @@
1
+ export default function objectFind(obj, query) {
2
+ for (const key in obj) {
3
+ if (query(obj[key], key, obj)) {
4
+ return key;
5
+ }
6
+ }
7
+ }
@@ -0,0 +1 @@
1
+ export default function objectKeys<T extends Record<string, any>>(object: T): Array<keyof T>;
@@ -0,0 +1,3 @@
1
+ export default function objectKeys(object) {
2
+ return Object.keys(object);
3
+ }
@@ -0,0 +1 @@
1
+ export default function objectMap<T extends Record<PropertyKey, any>, R>(obj: T, mapper: <K extends keyof T>(value: T[K], key: K, obj: T) => R): Record<keyof T, R>;
@@ -0,0 +1,8 @@
1
+ export default function objectMap(obj, mapper) {
2
+ const mappedObj = {};
3
+ for (const key in obj) {
4
+ // @ts-ignore
5
+ mappedObj[key] = mapper(obj[key], key, obj);
6
+ }
7
+ return mappedObj;
8
+ }
@@ -0,0 +1 @@
1
+ export default function objectMergeDeep<T extends Record<PropertyKey, any>>(base: T, ...objs: Array<T>): T;
@@ -0,0 +1,20 @@
1
+ export default function objectMergeDeep(base, ...objs) {
2
+ for (let i = 0, len = objs.length; i < len; ++i) {
3
+ const obj = objs[i];
4
+ for (const key in obj) {
5
+ // see https://github.com/robinweser/fast-loops/issues/18
6
+ if (key === '__proto__' || key === 'constructor' || key === 'prototype') {
7
+ continue;
8
+ }
9
+ const value = obj[key];
10
+ if (typeof value === 'object' &&
11
+ !Array.isArray(value) &&
12
+ value !== null) {
13
+ base[key] = objectMergeDeep(base[key], value);
14
+ continue;
15
+ }
16
+ base[key] = value;
17
+ }
18
+ }
19
+ return base;
20
+ }
@@ -0,0 +1 @@
1
+ export default function objectReduce<T extends Record<PropertyKey, any>, B>(obj: T, reducer: (accumulator: B, value: T[keyof T], key: keyof T, obj: T) => B, initialValue: B): B;
@@ -0,0 +1,6 @@
1
+ export default function objectReduce(obj, reducer, initialValue) {
2
+ for (const key in obj) {
3
+ initialValue = reducer(initialValue, obj[key], key, obj);
4
+ }
5
+ return initialValue;
6
+ }
@@ -0,0 +1,2 @@
1
+ import { type BaseNode } from './types.js';
2
+ export default function removeNode<T extends BaseNode<T>>(rootNode: T, id: string): T;
@@ -0,0 +1,14 @@
1
+ import { arrayMap, arrayFilter } from '@weser/loops';
2
+ export default function removeNode(rootNode, id) {
3
+ return removeNodeById(rootNode, id);
4
+ }
5
+ function removeNodeById(rootNode, id) {
6
+ if (!rootNode.children || rootNode.children.length === 0) {
7
+ return rootNode;
8
+ }
9
+ const children = arrayMap(arrayFilter(rootNode.children, (node) => node.id !== id), (node) => removeNodeById(node, id));
10
+ return {
11
+ ...rootNode,
12
+ children,
13
+ };
14
+ }
@@ -0,0 +1,2 @@
1
+ import { type BaseNode } from './types.js';
2
+ export default function replaceNode<T extends BaseNode<T>>(rootNode: T, id: string, newNode: T): T;
@@ -0,0 +1,21 @@
1
+ import getNode from './getNode.js';
2
+ export default function replaceNode(rootNode, id, newNode) {
3
+ const node = getNode(rootNode, id);
4
+ if (!node) {
5
+ return rootNode;
6
+ }
7
+ return replaceNodeById(rootNode, id, newNode);
8
+ }
9
+ function replaceNodeById(rootNode, id, newNode) {
10
+ if (rootNode.id === id) {
11
+ return newNode;
12
+ }
13
+ if (!rootNode.children || rootNode.children.length === 0) {
14
+ return rootNode;
15
+ }
16
+ const children = rootNode.children.map((node) => replaceNodeById(node, id, newNode));
17
+ return {
18
+ ...rootNode,
19
+ children,
20
+ };
21
+ }
@@ -0,0 +1,2 @@
1
+ import { type BaseNode } from './types.js';
2
+ export default function traverse<T extends BaseNode<T>>(rootNode: T, callback: (node: T) => void, type?: 'top-down' | 'bottom-up'): void;
@@ -0,0 +1,12 @@
1
+ import { arrayEach } from '@weser/loops';
2
+ export default function traverse(rootNode, callback, type = 'top-down') {
3
+ if (type === 'top-down') {
4
+ callback(rootNode);
5
+ }
6
+ if (rootNode.children) {
7
+ arrayEach(rootNode.children, (node) => traverse(node, callback, type));
8
+ }
9
+ if (type === 'bottom-up') {
10
+ callback(rootNode);
11
+ }
12
+ }
@@ -0,0 +1 @@
1
+ {"root":["../src/addnode.ts","../src/clonenode.ts","../src/createnode.ts","../src/findallnode.ts","../src/findnode.ts","../src/getnode.ts","../src/getparentnode.ts","../src/index.ts","../src/insertnode.ts","../src/movenode.ts","../src/removenode.ts","../src/replacenode.ts","../src/traverse.ts","../src/types.ts","../src/updatenode.ts"],"version":"5.9.2"}
@@ -0,0 +1,7 @@
1
+ type DistributiveOmit<T, K extends PropertyKey> = T extends any ? Omit<T, K> : never;
2
+ export type BaseNode<T> = {
3
+ id: string;
4
+ children: Array<T> | null;
5
+ };
6
+ export type BaseNodeInput<T> = DistributiveOmit<T, 'id'>;
7
+ export {};
package/dist/types.js ADDED
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,2 @@
1
+ import { type BaseNode, type BaseNodeInput } from './types.js';
2
+ export default function updateNode<T extends BaseNode<T>>(rootNode: T, id: string, newNode: Partial<BaseNodeInput<T>>): T;
@@ -0,0 +1,12 @@
1
+ import getNode from './getNode.js';
2
+ import replaceNode from './replaceNode.js';
3
+ export default function updateNode(rootNode, id, newNode) {
4
+ const node = getNode(rootNode, id);
5
+ if (!node) {
6
+ return rootNode;
7
+ }
8
+ return replaceNode(rootNode, id, {
9
+ ...node,
10
+ ...newNode,
11
+ });
12
+ }
@@ -0,0 +1,12 @@
1
+ export type T_ActionResponse<T = any> = T extends any ? [string] | [null, T?] : [string] | [null, T];
2
+ type State<T> = {
3
+ loading: boolean;
4
+ data?: T | null;
5
+ error: string | null;
6
+ };
7
+ type T_ActionConfig<T> = {
8
+ onSuccess?: (data?: T) => void;
9
+ onError?: (error: string) => void;
10
+ };
11
+ export default function useAction<T, P extends Array<any>>(action: (...payload: P) => Promise<T_ActionResponse<T>>, config?: T_ActionConfig<T>): [State<T>, (...payload: P) => void];
12
+ export {};
@@ -0,0 +1,40 @@
1
+ import { useState } from 'react';
2
+ const initialState = {
3
+ loading: false,
4
+ data: null,
5
+ error: null,
6
+ };
7
+ export default function useAction(action, config = {}) {
8
+ const { onSuccess, onError } = config;
9
+ const [state, setState] = useState(initialState);
10
+ async function run(...payload) {
11
+ setState({
12
+ ...state,
13
+ loading: true,
14
+ });
15
+ const [error, data] = await action(...payload);
16
+ if (error !== null) {
17
+ if (onError) {
18
+ onError(error);
19
+ }
20
+ setState({
21
+ ...state,
22
+ error,
23
+ data: null,
24
+ loading: false,
25
+ });
26
+ }
27
+ else {
28
+ if (onSuccess) {
29
+ onSuccess(data);
30
+ }
31
+ setState({
32
+ ...state,
33
+ error: null,
34
+ data,
35
+ loading: false,
36
+ });
37
+ }
38
+ }
39
+ return [state, run];
40
+ }
@@ -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,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 @@
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,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,52 @@
1
+ {
2
+ "name": "@weser/tree",
3
+ "version": "1.0.0",
4
+ "description": "Tiny helpers for working with tree data structure",
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
+ "tree",
40
+ "data structure",
41
+ "utils"
42
+ ],
43
+ "dependencies": {
44
+ "@weser/loops": "^1.0.0"
45
+ },
46
+ "devDependencies": {
47
+ "ava": "^6.1.3",
48
+ "rimraf": "^3.0.2",
49
+ "typescript": "^5.4.5"
50
+ },
51
+ "gitHead": "afc0628ca4aeaba255eef9716652640fdc5b50c4"
52
+ }