@primereact/hooks 11.0.0-alpha.9 → 11.0.0-rc.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.
- package/LICENSE.md +45 -0
- package/README.md +34 -0
- package/index.d.ts +7 -0
- package/index.mjs +1 -1
- package/index.mjs.map +1 -1
- package/package.json +8 -12
- package/use-controlled-state/index.mjs +1 -1
- package/use-controlled-state/index.mjs.map +1 -1
- package/use-filter/_matchers.d.ts +23 -0
- package/use-filter/index.d.ts +94 -0
- package/use-filter/index.mjs +2 -0
- package/use-filter/index.mjs.map +1 -0
- package/use-is-mobile/index.d.ts +18 -0
- package/use-is-mobile/index.mjs +2 -0
- package/use-is-mobile/index.mjs.map +1 -0
- package/use-local-storage/index.d.ts +56 -0
- package/use-local-storage/index.mjs +2 -0
- package/use-local-storage/index.mjs.map +1 -0
- package/use-mask/index.d.ts +96 -67
- package/use-mask/index.mjs +1 -1
- package/use-mask/index.mjs.map +1 -1
- package/use-mounted/index.d.ts +36 -0
- package/use-mounted/index.mjs +2 -0
- package/use-mounted/index.mjs.map +1 -0
- package/use-number-formatter/index.d.ts +194 -0
- package/use-number-formatter/index.mjs +2 -0
- package/use-number-formatter/index.mjs.map +1 -0
- package/use-number-formatter/index.test.d.ts +0 -0
- package/use-presence/index.d.ts +1 -2
- package/use-presence/index.mjs +1 -1
- package/use-presence/index.mjs.map +1 -1
- package/use-props/index.d.ts +16 -11
- package/use-props/index.mjs +1 -1
- package/use-props/index.mjs.map +1 -1
- package/use-sortable-list/index.d.ts +43 -0
- package/use-sortable-list/index.mjs +2 -0
- package/use-sortable-list/index.mjs.map +1 -0
- package/use-tree-filter/index.d.ts +52 -0
- package/use-tree-filter/index.mjs +2 -0
- package/use-tree-filter/index.mjs.map +1 -0
- package/LICENSE +0 -21
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/use-presence/index.ts"],"sourcesContent":["import * as React from 'react';\n\n/**\n * usePresence hook is used to manage the presence of a component.\n *\n * @param open - The open state.\n * @returns An object containing the present, exiting, mounted, and ref states.\n *\n * @example\n * ```tsx\n * const { present, exiting, mounted, ref } = usePresence(true);\n *\n * return present && (\n * <div className=\"card flex justify-center\"></div>\n * );\n */\n\nexport function usePresence(open: boolean, fallbackMs: number = 500) {\n const [present, setPresent] = React.useState(open);\n const [exiting, setExiting] = React.useState(false);\n const [mounted, setMounted] = React.useState(false);\n const
|
|
1
|
+
{"version":3,"sources":["../../src/use-presence/index.ts"],"sourcesContent":["import * as React from 'react';\n\n/**\n * usePresence hook is used to manage the presence of a component.\n *\n * @param open - The open state.\n * @returns An object containing the present, exiting, mounted, and ref states.\n *\n * @example\n * ```tsx\n * const { present, exiting, mounted, ref } = usePresence(true);\n *\n * return present && (\n * <div className=\"card flex justify-center\"></div>\n * );\n */\n\nexport function usePresence(open: boolean, fallbackMs: number = 500) {\n const [present, setPresent] = React.useState(open);\n const [exiting, setExiting] = React.useState(false);\n const [mounted, setMounted] = React.useState(false);\n const nodeRef = React.useRef<HTMLElement | null>(null);\n const cleanupRef = React.useRef<(() => void) | null>(null);\n const rafCleanupRef = React.useRef<(() => void) | null>(null);\n\n const ref = React.useCallback((node: HTMLElement | null) => {\n nodeRef.current = node;\n }, []);\n\n React.useEffect(() => {\n if (cleanupRef.current) {\n cleanupRef.current();\n cleanupRef.current = null;\n }\n\n if (rafCleanupRef.current) {\n rafCleanupRef.current();\n rafCleanupRef.current = null;\n }\n\n if (open) {\n setPresent(true);\n setExiting(false);\n\n const rafs: number[] = [];\n\n rafs.push(\n requestAnimationFrame(() => {\n rafs.push(\n requestAnimationFrame(() => {\n rafs.push(requestAnimationFrame(() => setMounted(true)));\n })\n );\n })\n );\n\n rafCleanupRef.current = () => {\n rafs.forEach((raf) => cancelAnimationFrame(raf));\n rafs.length = 0;\n };\n } else if (nodeRef.current) {\n setExiting(true);\n setMounted(false);\n const node = nodeRef.current;\n let isHandled = false;\n\n const handleEnd = () => {\n if (isHandled) return;\n\n isHandled = true;\n\n setPresent(false);\n setExiting(false);\n\n node.removeEventListener('transitionend', handleEnd);\n node.removeEventListener('animationend', handleEnd);\n\n cleanupRef.current = null;\n };\n\n node.addEventListener('transitionend', handleEnd, { passive: true });\n node.addEventListener('animationend', handleEnd, { passive: true });\n\n // const fallbackTimeout = setTimeout(() => {\n // if (!isHandled) {\n // handleEnd();\n // }\n // }, fallbackMs);\n\n cleanupRef.current = () => {\n // clearTimeout(fallbackTimeout);\n\n if (!isHandled) {\n node.removeEventListener('transitionend', handleEnd);\n node.removeEventListener('animationend', handleEnd);\n }\n };\n } else {\n setMounted(false);\n setPresent(false);\n setExiting(false);\n }\n }, [open, fallbackMs]);\n\n React.useEffect(() => {\n return () => {\n if (cleanupRef.current) {\n cleanupRef.current();\n }\n\n if (rafCleanupRef.current) {\n rafCleanupRef.current();\n }\n };\n }, []);\n\n return { present, exiting, mounted, ref };\n}\n"],"mappings":"AAAA,UAAYA,MAAW,QAiBhB,SAASC,EAAYC,EAAeC,EAAqB,IAAK,CACjE,GAAM,CAACC,EAASC,CAAU,EAAU,WAASH,CAAI,EAC3C,CAACI,EAASC,CAAU,EAAU,WAAS,EAAK,EAC5C,CAACC,EAASC,CAAU,EAAU,WAAS,EAAK,EAC5CC,EAAgB,SAA2B,IAAI,EAC/CC,EAAmB,SAA4B,IAAI,EACnDC,EAAsB,SAA4B,IAAI,EAEtDC,EAAY,cAAaC,GAA6B,CACxDJ,EAAQ,QAAUI,CACtB,EAAG,CAAC,CAAC,EAEL,OAAM,YAAU,IAAM,CAWlB,GAVIH,EAAW,UACXA,EAAW,QAAQ,EACnBA,EAAW,QAAU,MAGrBC,EAAc,UACdA,EAAc,QAAQ,EACtBA,EAAc,QAAU,MAGxBV,EAAM,CACNG,EAAW,EAAI,EACfE,EAAW,EAAK,EAEhB,IAAMQ,EAAiB,CAAC,EAExBA,EAAK,KACD,sBAAsB,IAAM,CACxBA,EAAK,KACD,sBAAsB,IAAM,CACxBA,EAAK,KAAK,sBAAsB,IAAMN,EAAW,EAAI,CAAC,CAAC,CAC3D,CAAC,CACL,CACJ,CAAC,CACL,EAEAG,EAAc,QAAU,IAAM,CAC1BG,EAAK,QAASC,GAAQ,qBAAqBA,CAAG,CAAC,EAC/CD,EAAK,OAAS,CAClB,CACJ,SAAWL,EAAQ,QAAS,CACxBH,EAAW,EAAI,EACfE,EAAW,EAAK,EAChB,IAAMK,EAAOJ,EAAQ,QACjBO,EAAY,GAEVC,EAAY,IAAM,CAChBD,IAEJA,EAAY,GAEZZ,EAAW,EAAK,EAChBE,EAAW,EAAK,EAEhBO,EAAK,oBAAoB,gBAAiBI,CAAS,EACnDJ,EAAK,oBAAoB,eAAgBI,CAAS,EAElDP,EAAW,QAAU,KACzB,EAEAG,EAAK,iBAAiB,gBAAiBI,EAAW,CAAE,QAAS,EAAK,CAAC,EACnEJ,EAAK,iBAAiB,eAAgBI,EAAW,CAAE,QAAS,EAAK,CAAC,EAQlEP,EAAW,QAAU,IAAM,CAGlBM,IACDH,EAAK,oBAAoB,gBAAiBI,CAAS,EACnDJ,EAAK,oBAAoB,eAAgBI,CAAS,EAE1D,CACJ,MACIT,EAAW,EAAK,EAChBJ,EAAW,EAAK,EAChBE,EAAW,EAAK,CAExB,EAAG,CAACL,EAAMC,CAAU,CAAC,EAEf,YAAU,IACL,IAAM,CACLQ,EAAW,SACXA,EAAW,QAAQ,EAGnBC,EAAc,SACdA,EAAc,QAAQ,CAE9B,EACD,CAAC,CAAC,EAEE,CAAE,QAAAR,EAAS,QAAAE,EAAS,QAAAE,EAAS,IAAAK,CAAI,CAC5C","names":["React","usePresence","open","fallbackMs","present","setPresent","exiting","setExiting","mounted","setMounted","nodeRef","cleanupRef","rafCleanupRef","ref","node","rafs","raf","isHandled","handleEnd"]}
|
package/use-props/index.d.ts
CHANGED
|
@@ -1,26 +1,31 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Used to merge and differentiate incoming props with the default props.
|
|
3
|
-
* - Keys that exist in both `props1` and `props2` are placed in `props`, with values from `
|
|
4
|
-
* - Keys that exist in `
|
|
3
|
+
* - Keys that exist in both `props1` and `props2` are placed in `props`, with values from `props2`.
|
|
4
|
+
* - Keys that exist in `props2` but not in `props1` are placed in `attrs`.
|
|
5
5
|
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
6
|
+
* Uses structural comparison to preserve referential stability — if the computed
|
|
7
|
+
* props and attrs are shallowly equal to the previous result, the same reference is returned.
|
|
8
|
+
* This prevents unnecessary downstream useMemo invalidation even when the parent
|
|
9
|
+
* passes a new props object reference with identical values (e.g., from JSX spread).
|
|
8
10
|
*
|
|
9
|
-
* @
|
|
10
|
-
* @
|
|
11
|
+
* @template P1 The type of the default set of props.
|
|
12
|
+
* @template P2 The type of the incoming set of props.
|
|
13
|
+
*
|
|
14
|
+
* @param props1 The default set of props (e.g., default props).
|
|
15
|
+
* @param props2 The incoming set of props (e.g., user-defined or dynamic props).
|
|
11
16
|
* @returns An object containing:
|
|
12
|
-
* - `props`: A new object containing keys that exist in both `props1` and `props2`, using values from `
|
|
13
|
-
* - `attrs`: A new object containing keys that exist only in `
|
|
17
|
+
* - `props`: A new object containing keys that exist in both `props1` and `props2`, using values from `props2`.
|
|
18
|
+
* - `attrs`: A new object containing keys that exist only in `props2`, excluding any keys from `props1`.
|
|
14
19
|
*
|
|
15
20
|
* @example
|
|
16
21
|
* ```ts
|
|
17
|
-
* const { props, attrs } = useProps({
|
|
22
|
+
* const { props, attrs } = useProps({ className: 'baz' }, { id: 'foo', className: 'bar' });
|
|
18
23
|
*
|
|
19
24
|
* console.log(props); // { className: 'bar' }
|
|
20
25
|
* console.log(attrs); // { id: 'foo' }
|
|
21
26
|
* ```
|
|
22
27
|
*/
|
|
23
28
|
export declare function useProps<P1, P2>(props1?: P1, props2?: P2): {
|
|
24
|
-
props: Pick<P1 & P2, keyof
|
|
25
|
-
attrs: Omit<
|
|
29
|
+
props: Pick<P1 & P2, keyof P1>;
|
|
30
|
+
attrs: Omit<P2, keyof P1>;
|
|
26
31
|
};
|
package/use-props/index.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var
|
|
1
|
+
var k=Object.defineProperty;var l=Object.getOwnPropertySymbols;var g=Object.prototype.hasOwnProperty,w=Object.prototype.propertyIsEnumerable;var R=(r,n,t)=>n in r?k(r,n,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[n]=t,P=(r,n)=>{for(var t in n||(n={}))g.call(n,t)&&R(r,t,n[t]);if(l)for(var t of l(n))w.call(n,t)&&R(r,t,n[t]);return r};import*as u from"react";function f(r,n){if(r===n)return!0;let t=Object.keys(r),o=Object.keys(n);if(t.length!==o.length)return!1;for(let e=0;e<t.length;e++){let s=t[e];if(r[s]!==n[s])return!1}return!0}function d(r={},n={}){let t=u.useRef(null);return u.useMemo(()=>{let o=P({},r),e={};Object.entries(n).forEach(([c,i])=>{c in r?o[c]=i:e[c]=i});let s=t.current;if(s&&f(s.props,o)&&f(s.attrs,e))return s;let a={props:o,attrs:e};return t.current=a,a},[r,n])}export{d as useProps};
|
|
2
2
|
//# sourceMappingURL=index.mjs.map
|
package/use-props/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/use-props/index.ts"],"sourcesContent":["import * as React from 'react';\n\n/**\n * Used to merge and differentiate incoming props with the default props.\n * - Keys that exist in both `props1` and `props2` are placed in `props`, with values from `
|
|
1
|
+
{"version":3,"sources":["../../src/use-props/index.ts"],"sourcesContent":["import * as React from 'react';\n\n/**\n * Performs a shallow comparison of two objects to determine if their values are equal.\n * Returns true if both objects have the same keys with the same values (by reference).\n */\nfunction shallowEqual(objA: Record<string, unknown>, objB: Record<string, unknown>): boolean {\n if (objA === objB) return true;\n\n const keysA = Object.keys(objA);\n const keysB = Object.keys(objB);\n\n if (keysA.length !== keysB.length) return false;\n\n for (let i = 0; i < keysA.length; i++) {\n const key = keysA[i];\n\n if (objA[key] !== objB[key]) return false;\n }\n\n return true;\n}\n\n/**\n * Used to merge and differentiate incoming props with the default props.\n * - Keys that exist in both `props1` and `props2` are placed in `props`, with values from `props2`.\n * - Keys that exist in `props2` but not in `props1` are placed in `attrs`.\n *\n * Uses structural comparison to preserve referential stability — if the computed\n * props and attrs are shallowly equal to the previous result, the same reference is returned.\n * This prevents unnecessary downstream useMemo invalidation even when the parent\n * passes a new props object reference with identical values (e.g., from JSX spread).\n *\n * @template P1 The type of the default set of props.\n * @template P2 The type of the incoming set of props.\n *\n * @param props1 The default set of props (e.g., default props).\n * @param props2 The incoming set of props (e.g., user-defined or dynamic props).\n * @returns An object containing:\n * - `props`: A new object containing keys that exist in both `props1` and `props2`, using values from `props2`.\n * - `attrs`: A new object containing keys that exist only in `props2`, excluding any keys from `props1`.\n *\n * @example\n * ```ts\n * const { props, attrs } = useProps({ className: 'baz' }, { id: 'foo', className: 'bar' });\n *\n * console.log(props); // { className: 'bar' }\n * console.log(attrs); // { id: 'foo' }\n * ```\n */\nexport function useProps<P1, P2>(props1: P1 = {} as P1, props2: P2 = {} as P2) {\n type Props = Pick<P1 & P2, keyof P1>;\n type Attrs = Omit<P2, keyof P1>;\n type Result = { props: Props; attrs: Attrs };\n\n const prevRef = React.useRef<Result | null>(null);\n\n return React.useMemo(() => {\n const newProps = { ...props1 } as Props;\n const newAttrs = {} as Attrs;\n\n Object.entries(props2 as Record<string, unknown>).forEach(([key, value]) => {\n if (key in (props1 as Record<string, unknown>)) {\n (newProps as Record<string, unknown>)[key] = value;\n } else {\n (newAttrs as Record<string, unknown>)[key] = value;\n }\n });\n\n const prev = prevRef.current;\n\n if (prev && shallowEqual(prev.props as Record<string, unknown>, newProps as Record<string, unknown>) && shallowEqual(prev.attrs as Record<string, unknown>, newAttrs as Record<string, unknown>)) {\n return prev;\n }\n\n const result: Result = { props: newProps, attrs: newAttrs };\n\n prevRef.current = result;\n\n return result;\n }, [props1, props2]);\n}\n"],"mappings":"yVAAA,UAAYA,MAAW,QAMvB,SAASC,EAAaC,EAA+BC,EAAwC,CACzF,GAAID,IAASC,EAAM,MAAO,GAE1B,IAAMC,EAAQ,OAAO,KAAKF,CAAI,EACxBG,EAAQ,OAAO,KAAKF,CAAI,EAE9B,GAAIC,EAAM,SAAWC,EAAM,OAAQ,MAAO,GAE1C,QAASC,EAAI,EAAGA,EAAIF,EAAM,OAAQE,IAAK,CACnC,IAAMC,EAAMH,EAAME,CAAC,EAEnB,GAAIJ,EAAKK,CAAG,IAAMJ,EAAKI,CAAG,EAAG,MAAO,EACxC,CAEA,MAAO,EACX,CA6BO,SAASC,EAAiBC,EAAa,CAAC,EAASC,EAAa,CAAC,EAAS,CAK3E,IAAMC,EAAgB,SAAsB,IAAI,EAEhD,OAAa,UAAQ,IAAM,CACvB,IAAMC,EAAWC,EAAA,GAAKJ,GAChBK,EAAW,CAAC,EAElB,OAAO,QAAQJ,CAAiC,EAAE,QAAQ,CAAC,CAACH,EAAKQ,CAAK,IAAM,CACpER,KAAQE,EACPG,EAAqCL,CAAG,EAAIQ,EAE5CD,EAAqCP,CAAG,EAAIQ,CAErD,CAAC,EAED,IAAMC,EAAOL,EAAQ,QAErB,GAAIK,GAAQf,EAAae,EAAK,MAAkCJ,CAAmC,GAAKX,EAAae,EAAK,MAAkCF,CAAmC,EAC3L,OAAOE,EAGX,IAAMC,EAAiB,CAAE,MAAOL,EAAU,MAAOE,CAAS,EAE1D,OAAAH,EAAQ,QAAUM,EAEXA,CACX,EAAG,CAACR,EAAQC,CAAM,CAAC,CACvB","names":["React","shallowEqual","objA","objB","keysA","keysB","i","key","useProps","props1","props2","prevRef","newProps","__spreadValues","newAttrs","value","prev","result"]}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import * as React from 'react';
|
|
2
|
+
export interface SortableListState<TListId extends string = string, TItem = unknown> {
|
|
3
|
+
draggedItems: TItem[];
|
|
4
|
+
draggedIndex: number | null;
|
|
5
|
+
sourceListId: TListId | null;
|
|
6
|
+
dragOverListId: TListId | null;
|
|
7
|
+
dragOverIndex: number | null;
|
|
8
|
+
isDragging: boolean;
|
|
9
|
+
}
|
|
10
|
+
export interface UseSortableListOptions<TListId extends string = string, TItem = unknown> {
|
|
11
|
+
/** Called when items are reordered within the same list */
|
|
12
|
+
onReorder: (listId: TListId, fromIndex: number, toIndex: number) => void;
|
|
13
|
+
/** Called when items are dropped onto a different list */
|
|
14
|
+
onTransfer?: (sourceListId: TListId, targetListId: TListId, items: TItem[], targetIndex?: number) => void;
|
|
15
|
+
/** Whether a transfer from source to target is allowed. Defaults to true. */
|
|
16
|
+
canTransfer?: (sourceListId: TListId, targetListId: TListId) => boolean;
|
|
17
|
+
/** Resolve the set of items to drag. Useful for multi-selection. Defaults to [item]. */
|
|
18
|
+
getSelectedItems?: (listId: TListId, item: TItem) => TItem[];
|
|
19
|
+
}
|
|
20
|
+
export interface UseSortableListReturn<TListId extends string = string, TItem = unknown> {
|
|
21
|
+
dragState: SortableListState<TListId, TItem>;
|
|
22
|
+
/**
|
|
23
|
+
* Drag handlers for the list container.
|
|
24
|
+
* Must be spread onto the list wrapper element — handles both same-list reorder
|
|
25
|
+
* (via dragOverIndexRef) and cross-list transfer in onDrop, so individual items
|
|
26
|
+
* do not need onDrop handlers and CSS transitions on items are safe to use.
|
|
27
|
+
*/
|
|
28
|
+
getListHandlers: (listId: TListId) => {
|
|
29
|
+
onDragOver: (e: React.DragEvent) => void;
|
|
30
|
+
onDrop: (e: React.DragEvent) => void;
|
|
31
|
+
};
|
|
32
|
+
/** Drag handlers for individual items (onDragStart, onDragOver, onDragEnd) */
|
|
33
|
+
getItemHandlers: (listId: TListId, index: number, item: TItem) => {
|
|
34
|
+
draggable: true;
|
|
35
|
+
'data-index': number;
|
|
36
|
+
onDragStart: (e: React.DragEvent) => void;
|
|
37
|
+
onDragOver: (e: React.DragEvent) => void;
|
|
38
|
+
onDragEnd: () => void;
|
|
39
|
+
};
|
|
40
|
+
/** Reset all drag state */
|
|
41
|
+
reset: () => void;
|
|
42
|
+
}
|
|
43
|
+
export declare function useSortableList<TListId extends string = string, TItem = unknown>({ onReorder, onTransfer, canTransfer, getSelectedItems }: UseSortableListOptions<TListId, TItem>): UseSortableListReturn<TListId, TItem>;
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use client";var k=Object.defineProperty,w=Object.defineProperties;var A=Object.getOwnPropertyDescriptors;var D=Object.getOwnPropertySymbols;var C=Object.prototype.hasOwnProperty,H=Object.prototype.propertyIsEnumerable;var S=(d,t,a)=>t in d?k(d,t,{enumerable:!0,configurable:!0,writable:!0,value:a}):d[t]=a,v=(d,t)=>{for(var a in t||(t={}))C.call(t,a)&&S(d,a,t[a]);if(D)for(var a of D(t))H.call(t,a)&&S(d,a,t[a]);return d},b=(d,t)=>w(d,A(t));import*as o from"react";var O={draggedItems:[],draggedIndex:null,sourceListId:null,dragOverListId:null,dragOverIndex:null,isDragging:!1};function h({onReorder:d,onTransfer:t,canTransfer:a,getSelectedItems:f}){let c=o.useRef([]),u=o.useRef(null),I=o.useRef(null),L=o.useRef(null),[x,T]=o.useState(O),g=o.useCallback(()=>{c.current=[],u.current=null,I.current=null,L.current=null,T(O)},[]),l=o.useCallback((e,r)=>t?a?a(e,r):!0:!1,[t,a]),E=o.useCallback(e=>({onDragOver:r=>{r.preventDefault();let i=u.current;i===e?r.dataTransfer.dropEffect="move":i&&(r.dataTransfer.dropEffect=l(i,e)?"move":"none"),T(n=>n.dragOverListId!==e?b(v({},n),{dragOverListId:e,dragOverIndex:null}):n)},onDrop:r=>{r.preventDefault();let i=u.current,n=I.current,s=L.current;i===e?n!==null&&s!==null&&n!==s&&d(e,n,s):i&&c.current.length>0&&l(i,e)&&t(i,e,c.current,s!=null?s:void 0),g()}}),[d,t,l,g]),p=o.useCallback((e,r,i)=>({draggable:!0,"data-index":r,onDragStart:n=>{let s=f?f(e,i):[i];n.dataTransfer.effectAllowed="move",n.dataTransfer.setData("text/plain",""),c.current=s,u.current=e,I.current=r,L.current=r,requestAnimationFrame(()=>{T({draggedItems:s,draggedIndex:r,sourceListId:e,dragOverListId:null,dragOverIndex:null,isDragging:!0})})},onDragOver:n=>{n.preventDefault(),n.stopPropagation();let s=u.current,R=s===e;R?n.dataTransfer.dropEffect="move":s&&(n.dataTransfer.dropEffect=l(s,e)?"move":"none"),!(R&&r===I.current)&&(L.current=r,T(m=>m.dragOverListId!==e||m.dragOverIndex!==r?b(v({},m),{dragOverListId:e,dragOverIndex:r}):m))},onDragEnd:g}),[l,f,g]);return{dragState:x,getListHandlers:E,getItemHandlers:p,reset:g}}export{h as useSortableList};
|
|
2
|
+
//# sourceMappingURL=index.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/use-sortable-list/index.ts"],"sourcesContent":["'use client';\nimport * as React from 'react';\n\nexport interface SortableListState<TListId extends string = string, TItem = unknown> {\n draggedItems: TItem[];\n draggedIndex: number | null;\n sourceListId: TListId | null;\n dragOverListId: TListId | null;\n dragOverIndex: number | null;\n isDragging: boolean;\n}\n\nexport interface UseSortableListOptions<TListId extends string = string, TItem = unknown> {\n /** Called when items are reordered within the same list */\n onReorder: (listId: TListId, fromIndex: number, toIndex: number) => void;\n /** Called when items are dropped onto a different list */\n onTransfer?: (sourceListId: TListId, targetListId: TListId, items: TItem[], targetIndex?: number) => void;\n /** Whether a transfer from source to target is allowed. Defaults to true. */\n canTransfer?: (sourceListId: TListId, targetListId: TListId) => boolean;\n /** Resolve the set of items to drag. Useful for multi-selection. Defaults to [item]. */\n getSelectedItems?: (listId: TListId, item: TItem) => TItem[];\n}\n\nexport interface UseSortableListReturn<TListId extends string = string, TItem = unknown> {\n dragState: SortableListState<TListId, TItem>;\n /**\n * Drag handlers for the list container.\n * Must be spread onto the list wrapper element — handles both same-list reorder\n * (via dragOverIndexRef) and cross-list transfer in onDrop, so individual items\n * do not need onDrop handlers and CSS transitions on items are safe to use.\n */\n getListHandlers: (listId: TListId) => {\n onDragOver: (e: React.DragEvent) => void;\n onDrop: (e: React.DragEvent) => void;\n };\n /** Drag handlers for individual items (onDragStart, onDragOver, onDragEnd) */\n getItemHandlers: (\n listId: TListId,\n index: number,\n item: TItem\n ) => {\n draggable: true;\n 'data-index': number;\n onDragStart: (e: React.DragEvent) => void;\n onDragOver: (e: React.DragEvent) => void;\n onDragEnd: () => void;\n };\n /** Reset all drag state */\n reset: () => void;\n}\n\nconst INITIAL_STATE = {\n draggedItems: [],\n draggedIndex: null,\n sourceListId: null,\n dragOverListId: null,\n dragOverIndex: null,\n isDragging: false\n};\n\nexport function useSortableList<TListId extends string = string, TItem = unknown>({ onReorder, onTransfer, canTransfer, getSelectedItems }: UseSortableListOptions<TListId, TItem>): UseSortableListReturn<TListId, TItem> {\n const draggedItemsRef = React.useRef<TItem[]>([]);\n const dragSourceRef = React.useRef<TListId | null>(null);\n const draggedIndexRef = React.useRef<number | null>(null);\n // Tracks the last hovered item index so list-level onDrop always uses the correct target,\n // regardless of where the cursor is when released (even over a transitioning item).\n const dragOverIndexRef = React.useRef<number | null>(null);\n\n const [dragState, setDragState] = React.useState<SortableListState<TListId, TItem>>(INITIAL_STATE as SortableListState<TListId, TItem>);\n\n const reset = React.useCallback(() => {\n draggedItemsRef.current = [];\n dragSourceRef.current = null;\n draggedIndexRef.current = null;\n dragOverIndexRef.current = null;\n setDragState(INITIAL_STATE as SortableListState<TListId, TItem>);\n }, []);\n\n const isTransferAllowed = React.useCallback(\n (sourceListId: TListId, targetListId: TListId) => {\n if (!onTransfer) return false;\n\n return canTransfer ? canTransfer(sourceListId, targetListId) : true;\n },\n [onTransfer, canTransfer]\n );\n\n const getListHandlers = React.useCallback(\n (listId: TListId) => ({\n onDragOver: (e: React.DragEvent) => {\n e.preventDefault();\n const sourceListId = dragSourceRef.current;\n\n if (sourceListId === listId) {\n e.dataTransfer.dropEffect = 'move';\n } else if (sourceListId) {\n e.dataTransfer.dropEffect = isTransferAllowed(sourceListId, listId) ? 'move' : 'none';\n }\n\n setDragState((prev) => (prev.dragOverListId !== listId ? { ...prev, dragOverListId: listId, dragOverIndex: null } : prev));\n },\n onDrop: (e: React.DragEvent) => {\n e.preventDefault();\n const sourceListId = dragSourceRef.current;\n const fromIndex = draggedIndexRef.current;\n const toIndex = dragOverIndexRef.current;\n\n if (sourceListId === listId) {\n // Same-list reorder using the last committed hover index.\n // Because drop is handled here (not on individual items), CSS transitions\n // on items cannot affect which element receives the drop event.\n if (fromIndex !== null && toIndex !== null && fromIndex !== toIndex) {\n onReorder(listId, fromIndex, toIndex);\n }\n } else if (sourceListId && draggedItemsRef.current.length > 0 && isTransferAllowed(sourceListId, listId)) {\n onTransfer!(sourceListId, listId, draggedItemsRef.current, toIndex ?? undefined);\n }\n\n reset();\n }\n }),\n [onReorder, onTransfer, isTransferAllowed, reset]\n );\n\n const getItemHandlers = React.useCallback(\n (listId: TListId, index: number, item: TItem) => ({\n draggable: true as const,\n 'data-index': index,\n onDragStart: (e: React.DragEvent) => {\n const itemsToDrag = getSelectedItems ? getSelectedItems(listId, item) : [item];\n\n e.dataTransfer.effectAllowed = 'move';\n e.dataTransfer.setData('text/plain', '');\n\n // Set refs immediately so dragOver/drop handlers work from the first event.\n draggedItemsRef.current = itemsToDrag;\n dragSourceRef.current = listId;\n draggedIndexRef.current = index;\n dragOverIndexRef.current = index;\n\n // Defer the state update by one frame so the browser captures the drag\n // ghost image from the element while it is still visible (opacity: 1).\n // React's synchronous batch flush would otherwise hide the element\n // (opacity: 0 in consumer code) before the ghost snapshot is taken.\n requestAnimationFrame(() => {\n setDragState({\n draggedItems: itemsToDrag,\n draggedIndex: index,\n sourceListId: listId,\n dragOverListId: null,\n dragOverIndex: null,\n isDragging: true\n });\n });\n },\n onDragOver: (e: React.DragEvent) => {\n e.preventDefault();\n e.stopPropagation();\n const sourceListId = dragSourceRef.current;\n const isSameList = sourceListId === listId;\n\n if (isSameList) {\n e.dataTransfer.dropEffect = 'move';\n } else if (sourceListId) {\n e.dataTransfer.dropEffect = isTransferAllowed(sourceListId, listId) ? 'move' : 'none';\n }\n\n // The dragged item stays at its original slot (invisible placeholder).\n // Skip dragOverIndex updates for it to prevent the feedback loop where\n // hovering the invisible item resets all visual shifts.\n if (isSameList && index === draggedIndexRef.current) {\n return;\n }\n\n dragOverIndexRef.current = index;\n setDragState((prev) => (prev.dragOverListId !== listId || prev.dragOverIndex !== index ? { ...prev, dragOverListId: listId, dragOverIndex: index } : prev));\n },\n onDragEnd: reset\n }),\n [isTransferAllowed, getSelectedItems, reset]\n );\n\n return { dragState, getListHandlers, getItemHandlers, reset };\n}\n"],"mappings":"0bACA,UAAYA,MAAW,QAkDvB,IAAMC,EAAgB,CAClB,aAAc,CAAC,EACf,aAAc,KACd,aAAc,KACd,eAAgB,KAChB,cAAe,KACf,WAAY,EAChB,EAEO,SAASC,EAAkE,CAAE,UAAAC,EAAW,WAAAC,EAAY,YAAAC,EAAa,iBAAAC,CAAiB,EAAkF,CACvN,IAAMC,EAAwB,SAAgB,CAAC,CAAC,EAC1CC,EAAsB,SAAuB,IAAI,EACjDC,EAAwB,SAAsB,IAAI,EAGlDC,EAAyB,SAAsB,IAAI,EAEnD,CAACC,EAAWC,CAAY,EAAU,WAA4CX,CAAkD,EAEhIY,EAAc,cAAY,IAAM,CAClCN,EAAgB,QAAU,CAAC,EAC3BC,EAAc,QAAU,KACxBC,EAAgB,QAAU,KAC1BC,EAAiB,QAAU,KAC3BE,EAAaX,CAAkD,CACnE,EAAG,CAAC,CAAC,EAECa,EAA0B,cAC5B,CAACC,EAAuBC,IACfZ,EAEEC,EAAcA,EAAYU,EAAcC,CAAY,EAAI,GAFvC,GAI5B,CAACZ,EAAYC,CAAW,CAC5B,EAEMY,EAAwB,cACzBC,IAAqB,CAClB,WAAaC,GAAuB,CAChCA,EAAE,eAAe,EACjB,IAAMJ,EAAeP,EAAc,QAE/BO,IAAiBG,EACjBC,EAAE,aAAa,WAAa,OACrBJ,IACPI,EAAE,aAAa,WAAaL,EAAkBC,EAAcG,CAAM,EAAI,OAAS,QAGnFN,EAAcQ,GAAUA,EAAK,iBAAmB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gB,EAC3Bd,EAAcQ,GAAUA,EAAK,iBAAmBF,GAAUE,EAAK,gBAAkBM,EAAQL,EAAAC,EAAA,GAAKF,GAAL,CAAW,eAAgBF,EAAQ,cAAeQ,CAAM,GAAIN,CAAK,EAC9J,EACA,UAAWP,CACf,GACA,CAACC,EAAmBR,EAAkBO,CAAK,CAC/C,EAEA,MAAO,CAAE,UAAAF,EAAW,gBAAAM,EAAiB,gBAAAQ,EAAiB,MAAAZ,CAAM,CAChE","names":["React","INITIAL_STATE","useSortableList","onReorder","onTransfer","canTransfer","getSelectedItems","draggedItemsRef","dragSourceRef","draggedIndexRef","dragOverIndexRef","dragState","setDragState","reset","isTransferAllowed","sourceListId","targetListId","getListHandlers","listId","e","prev","__spreadProps","__spreadValues","fromIndex","toIndex","getItemHandlers","index","item","itemsToDrag","isSameList"]}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { registerMatcher, unregisterMatcher, type BuiltInMatchMode, type FilterMatcher, type FilterRule } from '@primereact/hooks/use-filter';
|
|
2
|
+
export { registerMatcher, unregisterMatcher };
|
|
3
|
+
export type TreeFilterMode = 'lenient' | 'strict';
|
|
4
|
+
export interface TreeNodeLike {
|
|
5
|
+
key?: string | number;
|
|
6
|
+
data?: Record<string, unknown>;
|
|
7
|
+
children?: TreeNodeLike[];
|
|
8
|
+
}
|
|
9
|
+
export interface UseTreeFilterOptions<TNode extends TreeNodeLike, TMode extends string = BuiltInMatchMode> {
|
|
10
|
+
nodes: TNode[];
|
|
11
|
+
rules?: FilterRule<TMode>[];
|
|
12
|
+
defaultRules?: FilterRule<TMode>[];
|
|
13
|
+
/**
|
|
14
|
+
* Shorthand for the single-field case. When set, the hook synthesizes a single
|
|
15
|
+
* `{ field, value, matchMode }` rule. Ignored when `rules` / `defaultRules` is provided.
|
|
16
|
+
*/
|
|
17
|
+
field?: string | string[];
|
|
18
|
+
/** Controlled value for the shorthand `field`. Omit to let the hook own the state. */
|
|
19
|
+
value?: unknown;
|
|
20
|
+
/** Initial value when the hook owns the state. */
|
|
21
|
+
defaultValue?: unknown;
|
|
22
|
+
/** Fires when the shorthand `value` changes. */
|
|
23
|
+
onValueChange?: (value: unknown) => void;
|
|
24
|
+
/** Match mode for the shorthand `field`. Defaults to `'contains'`. */
|
|
25
|
+
matchMode?: TMode;
|
|
26
|
+
matchers?: Partial<Record<TMode, FilterMatcher>> & Record<string, FilterMatcher>;
|
|
27
|
+
filterMode?: TreeFilterMode;
|
|
28
|
+
filterLocale?: string;
|
|
29
|
+
filterDelay?: number;
|
|
30
|
+
/** When true, `filteredNodes` is returned as-is; the consumer fetches filtered data itself. */
|
|
31
|
+
lazy?: boolean;
|
|
32
|
+
/** Fires after rules settle (honours `filterDelay`). The consumer is expected to fetch filtered tree data. */
|
|
33
|
+
onLazyLoad?: (event: LazyTreeFilterEvent<TMode>) => void;
|
|
34
|
+
onRulesChange?: (rules: FilterRule<TMode>[]) => void;
|
|
35
|
+
}
|
|
36
|
+
export interface LazyTreeFilterEvent<TMode extends string = string> {
|
|
37
|
+
rules: FilterRule<TMode>[];
|
|
38
|
+
filterMode: TreeFilterMode;
|
|
39
|
+
filterLocale?: string;
|
|
40
|
+
}
|
|
41
|
+
export interface UseTreeFilterReturn<TNode extends TreeNodeLike, TMode extends string = string> {
|
|
42
|
+
rules: FilterRule<TMode>[];
|
|
43
|
+
filteredNodes: TNode[];
|
|
44
|
+
isFiltered: boolean;
|
|
45
|
+
setRules: (rules: FilterRule<TMode>[]) => void;
|
|
46
|
+
value: unknown;
|
|
47
|
+
setValue: (value: unknown) => void;
|
|
48
|
+
clearAll: () => void;
|
|
49
|
+
match: (node: TNode) => boolean;
|
|
50
|
+
matchers: Readonly<Record<string, FilterMatcher>>;
|
|
51
|
+
}
|
|
52
|
+
export declare function useTreeFilter<TNode extends TreeNodeLike, TMode extends string = BuiltInMatchMode>(options: UseTreeFilterOptions<TNode, TMode>): UseTreeFilterReturn<TNode, TMode>;
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use client";var K=Object.defineProperty,P=Object.defineProperties;var q=Object.getOwnPropertyDescriptors;var S=Object.getOwnPropertySymbols;var Q=Object.prototype.hasOwnProperty,W=Object.prototype.propertyIsEnumerable;var E=(e,t,r)=>t in e?K(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,u=(e,t)=>{for(var r in t||(t={}))Q.call(t,r)&&E(e,r,t[r]);if(S)for(var r of S(t))W.call(t,r)&&E(e,r,t[r]);return e},T=(e,t)=>P(e,q(t));import{useControlledState as X}from"@primereact/hooks/use-controlled-state";import{BUILT_IN_MATCHERS as Y,getGlobalMatchers as Z,matchRule as $,registerMatcher as oe,ruleHasValue as ee,unregisterMatcher as se}from"@primereact/hooks/use-filter";import{resolveFieldData as U}from"@primeuix/utils/object";import*as n from"react";function te(e,t){let r=e.data!==null&&typeof e.data=="object";if(r&&t in e.data)return e.data[t];if(r){let s=U(e.data,t);if(s!==void 0)return s}return t in e?e[t]:U(e,t)}function re(e){return!e.children||e.children.length===0}function j(e,t,r,s){let d=Array.isArray(t.field)?t.field:[t.field],i={};for(let a of d)i[a]=te(e,a);return $(i,T(u({},t),{field:d}),r,s)}function B(e,t,r,s,d){let i=[];for(let a of e){let N=t.every(R=>j(a,R,r,s)),c=null;if(a.children&&a.children.length>0){let R=B(a.children,t,r,s,d);R.length>0&&(c=R)}d?re(a)?N&&i.push(a):c&&i.push(T(u({},a),{children:c})):N?i.push(a):c&&i.push(T(u({},a),{children:c}))}return i}function ie(e){var C,V,z,A,D;let t=e.field!==void 0&&e.rules===void 0&&e.defaultRules===void 0,r=(C=e.matchMode)!=null?C:"contains",[s,d]=X({value:e.value,defaultValue:e.defaultValue,onChange:e.onValueChange}),i=n.useCallback(l=>d(l),[d]),a=e.rules!==void 0,[N,c]=n.useState((V=e.defaultRules)!=null?V:[]),R=n.useMemo(()=>t?[{field:e.field,value:s,matchMode:r}]:[],[t,e.field,s,r]),f=t?R:a?(z=e.rules)!=null?z:[]:N,m=n.useRef(e.onRulesChange);m.current=e.onRulesChange;let y=n.useCallback(l=>{var o,w,I;t?d((w=(o=l[0])==null?void 0:o.value)!=null?w:null):a||c(l),(I=m.current)==null||I.call(m,l)},[t,a,d]),M=e.filterLocale,v=(A=e.filterDelay)!=null?A:0,g=(D=e.filterMode)!=null?D:"lenient",F=n.useMemo(()=>{var l;return u(u(u({},Y),Z()),(l=e.matchers)!=null?l:{})},[e.matchers]),[O,H]=n.useState(f);n.useEffect(()=>{if(v<=0)return;let l=setTimeout(()=>H(f),v);return()=>clearTimeout(l)},[f,v]);let k=v>0?O:f,h=n.useMemo(()=>k.filter(ee),[k]),_=n.useCallback(l=>h.every(o=>j(l,o,F,M)),[h,F,M]),L=!!e.lazy,p=n.useMemo(()=>L||h.length===0?e.nodes:B(e.nodes,h,F,M,g==="strict"),[L,e.nodes,h,F,M,g]),b=n.useRef(e.onLazyLoad);b.current=e.onLazyLoad;let x=n.useRef(null);n.useEffect(()=>{var o;if(!L)return;let l=JSON.stringify(k)+"|"+g;x.current!==l&&(x.current=l,(o=b.current)==null||o.call(b,{rules:k,filterMode:g,filterLocale:M}))},[L,k,g,M]);let G=n.useCallback(l=>y(l),[y]),J=n.useCallback(()=>{let l=f.map(o=>Array.isArray(o.constraints)?T(u({},o),{constraints:o.constraints.map(w=>T(u({},w),{value:null}))}):T(u({},o),{value:null}));y(l)},[f,y]);return{rules:f,filteredNodes:p,isFiltered:h.length>0,setRules:G,value:s,setValue:i,clearAll:J,match:_,matchers:F}}export{oe as registerMatcher,se as unregisterMatcher,ie as useTreeFilter};
|
|
2
|
+
//# sourceMappingURL=index.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/use-tree-filter/index.ts"],"sourcesContent":["'use client';\nimport { useControlledState } from '@primereact/hooks/use-controlled-state';\nimport { BUILT_IN_MATCHERS, getGlobalMatchers, matchRule, registerMatcher, ruleHasValue, unregisterMatcher, type BuiltInMatchMode, type FilterMatcher, type FilterRule } from '@primereact/hooks/use-filter';\nimport { resolveFieldData } from '@primeuix/utils/object';\nimport * as React from 'react';\n\nexport { registerMatcher, unregisterMatcher };\n\nexport type TreeFilterMode = 'lenient' | 'strict';\n\nexport interface TreeNodeLike {\n key?: string | number;\n data?: Record<string, unknown>;\n children?: TreeNodeLike[];\n}\n\nexport interface UseTreeFilterOptions<TNode extends TreeNodeLike, TMode extends string = BuiltInMatchMode> {\n nodes: TNode[];\n rules?: FilterRule<TMode>[];\n defaultRules?: FilterRule<TMode>[];\n /**\n * Shorthand for the single-field case. When set, the hook synthesizes a single\n * `{ field, value, matchMode }` rule. Ignored when `rules` / `defaultRules` is provided.\n */\n field?: string | string[];\n /** Controlled value for the shorthand `field`. Omit to let the hook own the state. */\n value?: unknown;\n /** Initial value when the hook owns the state. */\n defaultValue?: unknown;\n /** Fires when the shorthand `value` changes. */\n onValueChange?: (value: unknown) => void;\n /** Match mode for the shorthand `field`. Defaults to `'contains'`. */\n matchMode?: TMode;\n matchers?: Partial<Record<TMode, FilterMatcher>> & Record<string, FilterMatcher>;\n filterMode?: TreeFilterMode;\n filterLocale?: string;\n filterDelay?: number;\n /** When true, `filteredNodes` is returned as-is; the consumer fetches filtered data itself. */\n lazy?: boolean;\n /** Fires after rules settle (honours `filterDelay`). The consumer is expected to fetch filtered tree data. */\n onLazyLoad?: (event: LazyTreeFilterEvent<TMode>) => void;\n onRulesChange?: (rules: FilterRule<TMode>[]) => void;\n}\n\nexport interface LazyTreeFilterEvent<TMode extends string = string> {\n rules: FilterRule<TMode>[];\n filterMode: TreeFilterMode;\n filterLocale?: string;\n}\n\nexport interface UseTreeFilterReturn<TNode extends TreeNodeLike, TMode extends string = string> {\n rules: FilterRule<TMode>[];\n filteredNodes: TNode[];\n isFiltered: boolean;\n setRules: (rules: FilterRule<TMode>[]) => void;\n value: unknown;\n setValue: (value: unknown) => void;\n clearAll: () => void;\n match: (node: TNode) => boolean;\n matchers: Readonly<Record<string, FilterMatcher>>;\n}\n\nfunction nodeTarget<TNode extends TreeNodeLike>(node: TNode, field: string): unknown {\n // Prefer `node.data` (DataTable-style node) when it's an object that owns the\n // field, otherwise fall back to the node itself (Tree-style where fields like\n // `label` live at the top level). `node.data` may also be a primitive (string\n // / number) — guard against that before using `in`.\n const dataIsObject = node.data !== null && typeof node.data === 'object';\n\n if (dataIsObject && field in (node.data as object)) {\n return (node.data as Record<string, unknown>)[field];\n }\n\n if (dataIsObject) {\n const fromData = resolveFieldData(node.data as Record<string, unknown>, field);\n\n if (fromData !== undefined) return fromData;\n }\n\n if (field in (node as Record<string, unknown>)) return (node as Record<string, unknown>)[field];\n\n return resolveFieldData(node as unknown as Record<string, unknown>, field);\n}\n\nfunction isLeaf(node: TreeNodeLike): boolean {\n return !node.children || node.children.length === 0;\n}\n\nfunction nodeMatchesDirect<TNode extends TreeNodeLike, TMode extends string>(node: TNode, rule: FilterRule<TMode>, matchers: Record<string, FilterMatcher>, locale: string | undefined): boolean {\n const fields = Array.isArray(rule.field) ? rule.field : [rule.field];\n const projected: Record<string, unknown> = {};\n\n for (const f of fields) projected[f] = nodeTarget(node, f);\n\n return matchRule(projected, { ...rule, field: fields } as FilterRule<TMode>, matchers, locale);\n}\n\nfunction filterTree<TNode extends TreeNodeLike, TMode extends string>(nodes: TNode[], rules: FilterRule<TMode>[], matchers: Record<string, FilterMatcher>, locale: string | undefined, strict: boolean): TNode[] {\n const out: TNode[] = [];\n\n for (const node of nodes) {\n const selfMatch = rules.every((rule) => nodeMatchesDirect(node, rule, matchers, locale));\n\n let childMatched: TNode[] | null = null;\n\n if (node.children && node.children.length > 0) {\n const kidsFiltered = filterTree(node.children as TNode[], rules, matchers, locale, strict);\n\n if (kidsFiltered.length > 0) childMatched = kidsFiltered;\n }\n\n // lenient: self match or any descendant match → keep (all original children)\n // strict: leaf → must self-match; parent → must have a matching descendant\n if (strict) {\n if (isLeaf(node)) {\n if (selfMatch) out.push(node);\n } else if (childMatched) {\n out.push({ ...node, children: childMatched } as TNode);\n }\n } else {\n if (selfMatch) {\n out.push(node);\n } else if (childMatched) {\n out.push({ ...node, children: childMatched } as TNode);\n }\n }\n }\n\n return out;\n}\n\nexport function useTreeFilter<TNode extends TreeNodeLike, TMode extends string = BuiltInMatchMode>(options: UseTreeFilterOptions<TNode, TMode>): UseTreeFilterReturn<TNode, TMode> {\n // ---- Shorthand mode (field / value / matchMode) -------------------------\n // Active only when `field` is provided AND no explicit `rules` / `defaultRules`.\n // `value` can be controlled (parent owns) or uncontrolled (hook owns via defaultValue).\n const isShorthand = options.field !== undefined && options.rules === undefined && options.defaultRules === undefined;\n const shorthandMatchMode = (options.matchMode ?? ('contains' as TMode)) as TMode;\n\n const [shorthandValue, setShorthandValue] = useControlledState<unknown, unknown>({\n value: options.value,\n defaultValue: options.defaultValue,\n onChange: options.onValueChange\n });\n\n const setValue = React.useCallback((next: unknown) => setShorthandValue(next), [setShorthandValue]);\n\n // ---- Rule-array mode (existing API) -------------------------------------\n const isControlled = options.rules !== undefined;\n const [internalRules, setInternalRules] = React.useState<FilterRule<TMode>[]>(options.defaultRules ?? []);\n\n const shorthandRules = React.useMemo<FilterRule<TMode>[]>(() => {\n if (!isShorthand) return [];\n\n return [{ field: options.field as string | string[], value: shorthandValue, matchMode: shorthandMatchMode } as FilterRule<TMode>];\n }, [isShorthand, options.field, shorthandValue, shorthandMatchMode]);\n\n const currentRules = isShorthand ? shorthandRules : isControlled ? (options.rules ?? []) : internalRules;\n\n const onRulesChangeRef = React.useRef(options.onRulesChange);\n\n onRulesChangeRef.current = options.onRulesChange;\n\n const commit = React.useCallback(\n (next: FilterRule<TMode>[]) => {\n if (isShorthand) {\n // In shorthand mode, the only mutable surface is `value`.\n setShorthandValue((next[0] as FilterRule<TMode> | undefined)?.value ?? null);\n } else if (!isControlled) {\n setInternalRules(next);\n }\n\n onRulesChangeRef.current?.(next);\n },\n [isShorthand, isControlled, setShorthandValue]\n );\n\n const filterLocale = options.filterLocale;\n const filterDelay = options.filterDelay ?? 0;\n const filterMode = options.filterMode ?? 'lenient';\n\n const matchers = React.useMemo<Record<string, FilterMatcher>>(() => ({ ...(BUILT_IN_MATCHERS as Record<string, FilterMatcher>), ...getGlobalMatchers(), ...(options.matchers ?? {}) }), [options.matchers]);\n\n const [debouncedRules, setDebouncedRules] = React.useState<FilterRule<TMode>[]>(currentRules);\n\n React.useEffect(() => {\n if (filterDelay <= 0) return;\n\n const t = setTimeout(() => setDebouncedRules(currentRules), filterDelay);\n\n return () => clearTimeout(t);\n }, [currentRules, filterDelay]);\n\n const activeRules = filterDelay > 0 ? debouncedRules : currentRules;\n const activeRulesNonEmpty = React.useMemo(() => activeRules.filter(ruleHasValue), [activeRules]);\n\n const match = React.useCallback((node: TNode) => activeRulesNonEmpty.every((rule) => nodeMatchesDirect(node, rule, matchers, filterLocale)), [activeRulesNonEmpty, matchers, filterLocale]);\n\n const lazy = !!options.lazy;\n\n const filteredNodes = React.useMemo(() => {\n if (lazy) return options.nodes;\n\n if (activeRulesNonEmpty.length === 0) return options.nodes;\n\n return filterTree(options.nodes, activeRulesNonEmpty, matchers, filterLocale, filterMode === 'strict');\n }, [lazy, options.nodes, activeRulesNonEmpty, matchers, filterLocale, filterMode]);\n\n const onLazyLoadRef = React.useRef(options.onLazyLoad);\n\n onLazyLoadRef.current = options.onLazyLoad;\n\n const lastLazyKeyRef = React.useRef<string | null>(null);\n\n React.useEffect(() => {\n if (!lazy) return;\n\n const key = JSON.stringify(activeRules) + '|' + filterMode;\n\n if (lastLazyKeyRef.current === key) return;\n\n lastLazyKeyRef.current = key;\n onLazyLoadRef.current?.({ rules: activeRules, filterMode, filterLocale });\n }, [lazy, activeRules, filterMode, filterLocale]);\n\n const setRules = React.useCallback((next: FilterRule<TMode>[]) => commit(next), [commit]);\n\n const clearAll = React.useCallback(() => {\n const next = currentRules.map((r) =>\n Array.isArray((r as { constraints?: unknown }).constraints) ? { ...r, constraints: (r as { constraints: { value: unknown; matchMode?: TMode }[] }).constraints.map((c) => ({ ...c, value: null })) } : { ...r, value: null }\n ) as FilterRule<TMode>[];\n\n commit(next);\n }, [currentRules, commit]);\n\n return {\n rules: currentRules,\n filteredNodes,\n isFiltered: activeRulesNonEmpty.length > 0,\n setRules,\n value: shorthandValue,\n setValue,\n clearAll,\n match,\n matchers\n };\n}\n"],"mappings":"0bACA,OAAS,sBAAAA,MAA0B,yCACnC,OAAS,qBAAAC,EAAmB,qBAAAC,EAAmB,aAAAC,EAAW,mBAAAC,GAAiB,gBAAAC,GAAc,qBAAAC,OAAqF,+BAC9K,OAAS,oBAAAC,MAAwB,yBACjC,UAAYC,MAAW,QA0DvB,SAASC,GAAuCC,EAAaC,EAAwB,CAKjF,IAAMC,EAAeF,EAAK,OAAS,MAAQ,OAAOA,EAAK,MAAS,SAEhE,GAAIE,GAAgBD,KAAUD,EAAK,KAC/B,OAAQA,EAAK,KAAiCC,CAAK,EAGvD,GAAIC,EAAc,CACd,IAAMC,EAAWC,EAAiBJ,EAAK,KAAiCC,CAAK,EAE7E,GAAIE,IAAa,OAAW,OAAOA,CACvC,CAEA,OAAIF,KAAUD,EAA0CA,EAAiCC,CAAK,EAEvFG,EAAiBJ,EAA4CC,CAAK,CAC7E,CAEA,SAASI,GAAOL,EAA6B,CACzC,MAAO,CAACA,EAAK,UAAYA,EAAK,SAAS,SAAW,CACtD,CAEA,SAASM,EAAoEN,EAAaO,EAAyBC,EAAyCC,EAAqC,CAC7L,IAAMC,EAAS,MAAM,QAAQH,EAAK,KAAK,EAAIA,EAAK,MAAQ,CAACA,EAAK,KAAK,EAC7DI,EAAqC,CAAC,EAE5C,QAAWC,KAAKF,EAAQC,EAAUC,CAAC,EAAIb,GAAWC,EAAMY,CAAC,EAEzD,OAAOC,EAAUF,EAAWG,EAAAC,EAAA,GAAKR,GAAL,CAAW,MAAOG,CAAO,GAAwBF,EAAUC,CAAM,CACjG,CAEA,SAASO,EAA6DC,EAAgBC,EAA4BV,EAAyCC,EAA4BU,EAA0B,CAC7M,IAAMC,EAAe,CAAC,EAEtB,Q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,MAAAP,EACA,SAAAhD,CACJ,CACJ","names":["useControlledState","BUILT_IN_MATCHERS","getGlobalMatchers","matchRule","registerMatcher","ruleHasValue","unregisterMatcher","resolveFieldData","React","nodeTarget","node","field","dataIsObject","fromData","resolveFieldData","isLeaf","nodeMatchesDirect","rule","matchers","locale","fields","projected","f","matchRule","__spreadProps","__spreadValues","filterTree","nodes","rules","strict","out","selfMatch","childMatched","kidsFiltered","useTreeFilter","options","_a","_b","_c","_d","_e","isShorthand","shorthandMatchMode","shorthandValue","setShorthandValue","useControlledState","setValue","next","isControlled","internalRules","setInternalRules","shorthandRules","currentRules","onRulesChangeRef","commit","filterLocale","filterDelay","filterMode","BUILT_IN_MATCHERS","getGlobalMatchers","debouncedRules","setDebouncedRules","t","activeRules","activeRulesNonEmpty","ruleHasValue","match","lazy","filteredNodes","onLazyLoadRef","lastLazyKeyRef","key","setRules","clearAll","r","c"]}
|
package/LICENSE
DELETED
|
@@ -1,21 +0,0 @@
|
|
|
1
|
-
MIT License
|
|
2
|
-
|
|
3
|
-
Copyright (c) 2025 PrimeTek
|
|
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.
|