@ohos-ports/hooks 0.0.0-stage → 11.2.0-beta.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.
Files changed (62) hide show
  1. package/LICENSE.md +45 -0
  2. package/README.md +50 -2
  3. package/index.d.ts +27 -0
  4. package/index.mjs +3 -0
  5. package/package.json +40 -4
  6. package/use-attr-selector/index.d.ts +13 -0
  7. package/use-attr-selector/index.mjs +1 -0
  8. package/use-controlled-state/index.d.ts +59 -0
  9. package/use-controlled-state/index.mjs +1 -0
  10. package/use-direction/index.d.ts +19 -0
  11. package/use-direction/index.mjs +1 -0
  12. package/use-escape-listener/index.d.ts +71 -0
  13. package/use-escape-listener/index.mjs +1 -0
  14. package/use-event-listener/index.d.ts +75 -0
  15. package/use-event-listener/index.mjs +1 -0
  16. package/use-filter/_matchers.d.ts +23 -0
  17. package/use-filter/index.d.ts +94 -0
  18. package/use-filter/index.mjs +3 -0
  19. package/use-hot-key/index.d.ts +25 -0
  20. package/use-hot-key/index.mjs +1 -0
  21. package/use-id/index.d.ts +19 -0
  22. package/use-id/index.mjs +1 -0
  23. package/use-intersection-observer/index.d.ts +58 -0
  24. package/use-intersection-observer/index.mjs +1 -0
  25. package/use-is-mobile/index.d.ts +18 -0
  26. package/use-is-mobile/index.mjs +1 -0
  27. package/use-key-filter/index.d.ts +42 -0
  28. package/use-key-filter/index.mjs +1 -0
  29. package/use-local-storage/index.d.ts +56 -0
  30. package/use-local-storage/index.mjs +1 -0
  31. package/use-mask/index.d.ts +138 -0
  32. package/use-mask/index.mjs +1 -0
  33. package/use-match-media/index.d.ts +16 -0
  34. package/use-match-media/index.mjs +1 -0
  35. package/use-mount-effect/index.d.ts +18 -0
  36. package/use-mount-effect/index.mjs +1 -0
  37. package/use-mounted/index.d.ts +36 -0
  38. package/use-mounted/index.mjs +1 -0
  39. package/use-number-formatter/index.d.ts +194 -0
  40. package/use-number-formatter/index.mjs +1 -0
  41. package/use-presence/index.d.ts +20 -0
  42. package/use-presence/index.mjs +1 -0
  43. package/use-previous/index.d.ts +19 -0
  44. package/use-previous/index.mjs +1 -0
  45. package/use-props/index.d.ts +31 -0
  46. package/use-props/index.mjs +1 -0
  47. package/use-queue-task/index.d.ts +1 -0
  48. package/use-queue-task/index.mjs +1 -0
  49. package/use-scrolltop/index.d.ts +59 -0
  50. package/use-scrolltop/index.mjs +1 -0
  51. package/use-sortable-list/index.d.ts +43 -0
  52. package/use-sortable-list/index.mjs +3 -0
  53. package/use-tree-filter/index.d.ts +52 -0
  54. package/use-tree-filter/index.mjs +3 -0
  55. package/use-unmount-effect/index.d.ts +18 -0
  56. package/use-unmount-effect/index.mjs +1 -0
  57. package/use-update-effect/index.d.ts +19 -0
  58. package/use-update-effect/index.mjs +1 -0
  59. package/use-view-transition/index.d.ts +20 -0
  60. package/use-view-transition/index.mjs +1 -0
  61. package/use-visibility-change/index.d.ts +14 -0
  62. package/use-visibility-change/index.mjs +1 -0
@@ -0,0 +1,194 @@
1
+ /**
2
+ * The options for the `useNumberFormatter` hook.
3
+ */
4
+ export interface UseNumberFormatterOptions {
5
+ /**
6
+ * The numeric value to be formatted.
7
+ */
8
+ value?: number | string | null | undefined;
9
+ /**
10
+ * Locale to be used in formatting.
11
+ */
12
+ locale?: string;
13
+ /**
14
+ * The locale matching algorithm to use. Possible values are 'lookup' and 'best fit'.
15
+ * @default 'best fit'
16
+ */
17
+ localeMatcher?: 'lookup' | 'best fit';
18
+ /**
19
+ * Defines the behavior of the component.
20
+ * @default 'decimal'
21
+ */
22
+ mode?: 'decimal' | 'currency';
23
+ /**
24
+ * The currency to use in currency formatting (ISO 4217 currency codes).
25
+ */
26
+ currency?: string;
27
+ /**
28
+ * How to display the currency in currency formatting.
29
+ */
30
+ currencyDisplay?: 'symbol' | 'narrowSymbol' | 'code' | 'name';
31
+ /**
32
+ * Whether to use grouping separators, such as thousands separators.
33
+ * @default true
34
+ */
35
+ useGrouping?: boolean;
36
+ /**
37
+ * The minimum number of fraction digits to use.
38
+ */
39
+ minFractionDigits?: number;
40
+ /**
41
+ * The maximum number of fraction digits to use.
42
+ */
43
+ maxFractionDigits?: number;
44
+ /**
45
+ * How decimals should be rounded.
46
+ */
47
+ roundingMode?: 'ceil' | 'floor' | 'expand' | 'trunc' | 'halfCeil' | 'halfFloor' | 'halfExpand' | 'halfTrunc' | 'halfEven';
48
+ /**
49
+ * Text to display before the value.
50
+ */
51
+ prefix?: string;
52
+ /**
53
+ * Text to display after the value.
54
+ */
55
+ suffix?: string;
56
+ /**
57
+ * Minimum boundary value (used to determine if minus sign is allowed).
58
+ */
59
+ min?: number;
60
+ /**
61
+ * Whether to format the value.
62
+ * @default true
63
+ */
64
+ format?: boolean;
65
+ }
66
+ /**
67
+ * The exposes for the `useNumberFormatter` hook.
68
+ */
69
+ export interface UseNumberFormatterExposes {
70
+ /**
71
+ * The formatted value based on the provided value and options.
72
+ */
73
+ formattedValue: string;
74
+ /**
75
+ * Formats a numeric value to a localized string.
76
+ * @param value - The value to format
77
+ * @returns The formatted string
78
+ */
79
+ formatValue: (value: number | string | null | undefined) => string;
80
+ /**
81
+ * Parses a formatted string back to a numeric value.
82
+ * @param text - The text to parse
83
+ * @returns The parsed number, '-' for minus sign only, or null if invalid
84
+ */
85
+ parseValue: (text: string) => number | string | null;
86
+ /**
87
+ * Adds two numbers with floating-point precision handling.
88
+ * @param base - The base number
89
+ * @param increment - The increment to add
90
+ * @returns The sum with proper precision
91
+ */
92
+ addWithPrecision: (base: number, increment: number) => number;
93
+ /**
94
+ * Checks if the mode is decimal.
95
+ * @returns True if mode is 'decimal'
96
+ */
97
+ isDecimalMode: () => boolean;
98
+ /**
99
+ * Checks if a character is a numeral character (digit, decimal, group separator, or minus sign).
100
+ * @param char - The character to check
101
+ * @returns True if the character is a numeral character
102
+ */
103
+ isNumeralChar: (char: string) => boolean;
104
+ /**
105
+ * Checks if a character is a minus sign.
106
+ * @param char - The character to check
107
+ * @returns True if the character is a minus sign
108
+ */
109
+ isMinusSign: (char: string) => boolean;
110
+ /**
111
+ * Checks if a character is a decimal sign.
112
+ * @param char - The character to check
113
+ * @returns True if the character is a decimal sign
114
+ */
115
+ isDecimalSign: (char: string) => boolean;
116
+ /**
117
+ * Checks if minus sign is allowed based on min value.
118
+ * @returns True if minus sign is allowed
119
+ */
120
+ allowMinusSign: () => boolean;
121
+ /**
122
+ * Gets the decimal character indexes in a value string.
123
+ * @param val - The value string to analyze
124
+ * @returns Object with decimalCharIndex and decimalCharIndexWithoutPrefix
125
+ */
126
+ getDecimalCharIndexes: (val: string) => {
127
+ decimalCharIndex: number;
128
+ decimalCharIndexWithoutPrefix: number;
129
+ };
130
+ /**
131
+ * Gets various character indexes (decimal, minus, suffix, currency) in a value string.
132
+ * @param val - The value string to analyze
133
+ * @returns Object with character indexes
134
+ */
135
+ getCharIndexes: (val: string) => {
136
+ decimalCharIndex: number;
137
+ minusCharIndex: number;
138
+ suffixCharIndex: number;
139
+ currencyCharIndex: number;
140
+ };
141
+ /**
142
+ * Gets the length of decimal part in a formatted value.
143
+ * @param value - The formatted value string
144
+ * @returns The decimal length
145
+ */
146
+ getDecimalLength: (value: string) => number;
147
+ /**
148
+ * Concatenates two value strings, handling decimal positions.
149
+ * @param val1 - The first value
150
+ * @param val2 - The second value
151
+ * @returns The concatenated result
152
+ */
153
+ concatValues: (val1: string, val2: string) => string;
154
+ /**
155
+ * The group character used for thousands separator.
156
+ */
157
+ groupChar: string | null;
158
+ /**
159
+ * The prefix character/string.
160
+ */
161
+ prefixChar: string | null;
162
+ /**
163
+ * The suffix character/string.
164
+ */
165
+ suffixChar: string | null;
166
+ /**
167
+ * The resolved Intl.NumberFormat options.
168
+ */
169
+ resolvedOptions: () => Intl.ResolvedNumberFormatOptions | undefined;
170
+ /**
171
+ * Reinitializes the parser (call when options change).
172
+ */
173
+ constructParser: () => void;
174
+ }
175
+ /**
176
+ * useNumberFormatter hook is used to format and parse numbers using Intl.NumberFormat.
177
+ *
178
+ * @param {UseNumberFormatterOptions} options - The options for the number formatter.
179
+ * @returns {UseNumberFormatterExposes} - The exposed methods for the number formatter.
180
+ *
181
+ * @example
182
+ * ```tsx
183
+ * const formatter = useNumberFormatter({
184
+ * value: 1234.56,
185
+ * locale: 'en-US',
186
+ * mode: 'currency',
187
+ * currency: 'USD'
188
+ * });
189
+ *
190
+ * const formatted = formatter.formatValue(1234.56); // "$1,234.56"
191
+ * const parsed = formatter.parseValue("$1,234.56"); // 1234.56
192
+ * ```
193
+ */
194
+ export declare function useNumberFormatter(options?: UseNumberFormatterOptions): UseNumberFormatterExposes;
@@ -0,0 +1 @@
1
+ import*as i from"react";function ue(W={}){let{value:j,locale:c,localeMatcher:S,mode:g="decimal",currency:o,currencyDisplay:p,useGrouping:V=!0,minFractionDigits:P,maxFractionDigits:$,roundingMode:R,prefix:d,suffix:x,min:C,format:L=!0}=W,G=i.useRef(null),E=i.useRef(null),I=i.useRef(null),h=i.useRef(null),a=i.useRef(null),m=i.useRef(null),s=i.useRef(null),f=i.useRef(null),t=i.useRef(null),l=i.useRef(null),b=i.useRef(null),y=i.useRef(null),w=()=>({localeMatcher:S,style:g,currency:o,currencyDisplay:p,useGrouping:V,minimumFractionDigits:P??void 0,maximumFractionDigits:$??void 0,roundingMode:R}),F=e=>e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),T=()=>{let e=new Intl.NumberFormat(c,{...w(),useGrouping:!1});return new RegExp(`[${e.format(1.1).replace(f.current??"","").trim().replace(a.current??"","")}]`,"g")},k=()=>{let e=new Intl.NumberFormat(c,{useGrouping:!0});return E.current=e.format(1e6).trim().replace(a.current??"","").charAt(0),new RegExp(`[${E.current}]`,"g")},A=()=>{let e=new Intl.NumberFormat(c,{useGrouping:!1});return new RegExp(`[${e.format(-1).trim().replace(a.current??"","")}]`,"g")},q=()=>{if(o){let e=new Intl.NumberFormat(c,{style:"currency",currency:o,currencyDisplay:p,minimumFractionDigits:0,maximumFractionDigits:0,roundingMode:R});return new RegExp(`[${e.format(1).replace(/\s/g,"").replace(a.current??"","").replace(m.current??"","")}]`,"g")}return new RegExp("[]","g")},z=()=>{if(d)b.current=new RegExp(F(d),"g");else{let r=new Intl.NumberFormat(c,{style:g,currency:o,currencyDisplay:p}).format(1).split("1")[0];b.current=new RegExp(F(r),"g")}return b.current},B=()=>{if(x)l.current=new RegExp(F(x),"g");else{let r=new Intl.NumberFormat(c,{style:g,currency:o,currencyDisplay:p,minimumFractionDigits:0,maximumFractionDigits:0,roundingMode:R}).format(1).split("1")[1];l.current=new RegExp(F(r),"g")}return l.current},_=()=>{G.current=new Intl.NumberFormat(c,w());let e=[...new Intl.NumberFormat(c,{useGrouping:!1}).format(9876543210)].reverse(),r=new Map(e.map((n,u)=>[n,u]));if(a.current=new RegExp(`[${e.join("")}]`,"g"),m.current=k(),s.current=A(),f.current=q(),t.current=T(),l.current=B(),b.current=z(),y.current=n=>r.get(n),d)I.current=d;else{let n=new Intl.NumberFormat(c,{style:g,currency:o,currencyDisplay:p});I.current=n.format(1).split("1")[0]}if(x)h.current=x;else{let n=new Intl.NumberFormat(c,{style:g,currency:o,currencyDisplay:p,minimumFractionDigits:0,maximumFractionDigits:0,roundingMode:R});h.current=n.format(1).split("1")[1]}},O=e=>{if(e!=null){if(typeof e=="string"&&e==="-")return e;if(L){let r=new Intl.NumberFormat(c,w()),n=typeof e=="string"?Number(e):e,u=r.format(n);return d&&(u=d+u),x&&(u=u+x),u}return e.toString()}return""},H=e=>{let r=e.replace(l.current||"","").replace(b.current||"","").trim().replace(/\s/g,"").replace(f.current||"","");if(t.current&&s.current&&a.current){let n=new RegExp(`[${[...new Intl.NumberFormat(c,{useGrouping:!1}).format(9876543210)].reverse().join("")}${new Intl.NumberFormat(c).format(1.1).replace(/[0-9]/g,"")}${new Intl.NumberFormat(c).format(-1).replace(/[0-9]/g,"")}]`,"g");r=r.match(n)?.join("")||""}if(m.current&&(r=r.replace(m.current,"")),s.current&&(r=r.replace(s.current,"-")),t.current&&(r=r.replace(t.current,".")),a.current&&y.current&&(r=r.replace(a.current,n=>{let u=y.current?y.current(n):void 0;return u!==void 0?u.toString():""})),r){if(r==="-")return r;let n=+r;return isNaN(n)?null:n}return null},J=(e,r)=>{let n=e.toString(),u=r.toString(),N=n.includes(".")?n.split(".")[1].length:0,M=u.includes(".")?u.split(".")[1].length:0,D=Math.max(N,M),U=Math.pow(10,D);return Math.round((e+r)*U)/U},K=()=>g==="decimal",Q=()=>{a.current&&(a.current.lastIndex=0),t.current&&(t.current.lastIndex=0),m.current&&(m.current.lastIndex=0),s.current&&(s.current.lastIndex=0)},X=e=>e.length===1&&(a.current&&a.current.test(e)||t.current&&t.current.test(e)||m.current&&m.current.test(e)||s.current&&s.current.test(e))?(Q(),!0):!1,Y=e=>s.current&&s.current.test(e)||e==="-"?(s.current&&(s.current.lastIndex=0),!0):!1,Z=e=>c?.includes("fr")&&[".",","].includes(e)||t.current&&t.current.test(e)?(t.current&&(t.current.lastIndex=0),!0):!1,v=()=>C==null||C<0,ee=e=>{let r=t.current?e.search(t.current):-1;t.current&&(t.current.lastIndex=0);let n=e.replace(b.current||"","").trim().replace(/\s/g,"").replace(f.current||"",""),u=t.current?n.search(t.current):-1;return t.current&&(t.current.lastIndex=0),{decimalCharIndex:r,decimalCharIndexWithoutPrefix:u}},re=e=>{let r=D=>{D&&(D.lastIndex=0)},n=t.current?e.search(t.current):-1;r(t.current);let u=s.current?e.search(s.current):-1;r(s.current);let N=l.current?e.search(l.current):-1;r(l.current);let M=f.current?e.search(f.current):-1;return r(f.current),{decimalCharIndex:n,minusCharIndex:u,suffixCharIndex:N,currencyCharIndex:M}},ne=e=>{if(e){let r=e.split(t.current??"");if(r.length===2)return r[1].replace(l.current??"","").trim().replace(/\s/g,"").replace(f.current??"","").length}return 0},te=(e,r)=>{if(e&&r){let n=t.current,u=n?r.search(n):-1;if(n&&(n.lastIndex=0),h.current)return u!==-1?e.replace(h.current,"").split(n??"")[0]+r.replace(h.current,"").slice(u)+h.current:e;if(I.current)return u!==-1?e.split(n??"")[0]+r.slice(u):e}return e};return i.useEffect(()=>{_()},[c,S,g,o,p,V,P,$,R,d,x]),{formattedValue:O(j),formatValue:O,parseValue:H,addWithPrecision:J,isDecimalMode:K,isNumeralChar:X,isMinusSign:Y,isDecimalSign:Z,allowMinusSign:v,getDecimalCharIndexes:ee,getCharIndexes:re,getDecimalLength:ne,concatValues:te,groupChar:E.current,prefixChar:I.current,suffixChar:h.current,resolvedOptions:()=>G.current?.resolvedOptions(),constructParser:_}}export{ue as useNumberFormatter};
@@ -0,0 +1,20 @@
1
+ /**
2
+ * usePresence hook is used to manage the presence of a component.
3
+ *
4
+ * @param open - The open state.
5
+ * @returns An object containing the present, exiting, mounted, and ref states.
6
+ *
7
+ * @example
8
+ * ```tsx
9
+ * const { present, exiting, mounted, ref } = usePresence(true);
10
+ *
11
+ * return present && (
12
+ * <div className="card flex justify-center"></div>
13
+ * );
14
+ */
15
+ export declare function usePresence(open: boolean, fallbackMs?: number): {
16
+ present: boolean;
17
+ exiting: boolean;
18
+ mounted: boolean;
19
+ ref: (node: HTMLElement | null) => void;
20
+ };
@@ -0,0 +1 @@
1
+ import*as n from"react";function E(c,f=500){let[m,i]=n.useState(c),[d,a]=n.useState(!1),[R,l]=n.useState(!1),o=n.useRef(null),t=n.useRef(null),r=n.useRef(null),v=n.useCallback(e=>{o.current=e},[]);return n.useEffect(()=>{if(t.current&&(t.current(),t.current=null),r.current&&(r.current(),r.current=null),c){i(!0),a(!1);let e=[];e.push(requestAnimationFrame(()=>{e.push(requestAnimationFrame(()=>{e.push(requestAnimationFrame(()=>l(!0)))}))})),r.current=()=>{e.forEach(u=>cancelAnimationFrame(u)),e.length=0}}else if(o.current){a(!0),l(!1);let e=o.current,u=!1,s=()=>{u||(u=!0,i(!1),a(!1),e.removeEventListener("transitionend",s),e.removeEventListener("animationend",s),t.current=null)};e.addEventListener("transitionend",s,{passive:!0}),e.addEventListener("animationend",s,{passive:!0}),t.current=()=>{u||(e.removeEventListener("transitionend",s),e.removeEventListener("animationend",s))}}else l(!1),i(!1),a(!1)},[c,f]),n.useEffect(()=>()=>{t.current&&t.current(),r.current&&r.current()},[]),{present:m,exiting:d,mounted:R,ref:v}}export{E as usePresence};
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Returns the previous value of the provided value.
3
+ *
4
+ * @param value - The value to track.
5
+ * @returns The previous value of the provided value.
6
+ *
7
+ * @example
8
+ * ```tsx
9
+ * const [count, setCount] = React.useState(5);
10
+ * const prevCount = usePrevious(count);
11
+ *
12
+ * console.log(prevCount); // undefined
13
+ *
14
+ * setCount(10);
15
+ *
16
+ * console.log(prevCount); // 5
17
+ * ```
18
+ */
19
+ export declare function usePrevious<T>(value: T): T | null | undefined;
@@ -0,0 +1 @@
1
+ import*as e from"react";function u(n){let r=e.useRef(null);return e.useEffect(()=>(r.current=n,()=>{r.current=null}),[n]),r.current}export{u as usePrevious};
@@ -0,0 +1,31 @@
1
+ /**
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 `props2`.
4
+ * - Keys that exist in `props2` but not in `props1` are placed in `attrs`.
5
+ *
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).
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).
16
+ * @returns An object containing:
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`.
19
+ *
20
+ * @example
21
+ * ```ts
22
+ * const { props, attrs } = useProps({ className: 'baz' }, { id: 'foo', className: 'bar' });
23
+ *
24
+ * console.log(props); // { className: 'bar' }
25
+ * console.log(attrs); // { id: 'foo' }
26
+ * ```
27
+ */
28
+ export declare function useProps<P1, P2>(props1?: P1, props2?: P2): {
29
+ props: Pick<P1 & P2, keyof P1>;
30
+ attrs: Omit<P2, keyof P1>;
31
+ };
@@ -0,0 +1 @@
1
+ import*as u from"react";function l(n,e){if(n===e)return!0;let s=Object.keys(n),o=Object.keys(e);if(s.length!==o.length)return!1;for(let t=0;t<s.length;t++){let r=s[t];if(n[r]!==e[r])return!1}return!0}function R(n={},e={}){let s=u.useRef(null);return u.useMemo(()=>{let o={...n},t={};Object.entries(e).forEach(([c,i])=>{c in n?o[c]=i:t[c]=i});let r=s.current;if(r&&l(r.props,o)&&l(r.attrs,t))return r;let a={props:o,attrs:t};return s.current=a,a},[n,e])}export{R as useProps};
@@ -0,0 +1 @@
1
+ export declare const useQueueTask: () => (id: string | number, task: () => void) => void;
@@ -0,0 +1 @@
1
+ import*as e from"react";var a=()=>{let t=e.useRef(new Map),r=e.useRef(!1),u=e.useCallback(()=>{r.current=!1;let s=t.current;t.current=new Map,s.forEach(c=>c())},[]);return e.useCallback((s,c)=>{t.current.set(s,c),r.current||(r.current=!0,queueMicrotask(u))},[u])};export{a as useQueueTask};
@@ -0,0 +1,59 @@
1
+ /**
2
+ * The options for the `useScrollTop` hook.
3
+ */
4
+ export interface UseScrollTopOptions {
5
+ /**
6
+ * Reference to the target element.
7
+ * @default window
8
+ */
9
+ target?: Window | Element | null;
10
+ /**
11
+ * Defines the threshold value of the vertical scroll position of the target to toggle the visibility.
12
+ * @default 400
13
+ */
14
+ threshold?: number;
15
+ /**
16
+ * Defines the scrolling behaviour, 'smooth' adds an animation and 'auto' scrolls with a jump.
17
+ * @default smooth
18
+ */
19
+ behavior?: ScrollBehavior;
20
+ }
21
+ /**
22
+ * The exposes for the `useScrollTop` hook.
23
+ */
24
+ export interface UseScrollTopExposes {
25
+ /**
26
+ * Current visible state as a boolean.
27
+ * @default false
28
+ */
29
+ visible: boolean;
30
+ /**
31
+ * Scrolls the target element to the top.
32
+ */
33
+ scrollToTop: () => void;
34
+ }
35
+ /**
36
+ * useScrollTop hook is used to enter input in a certain format such as numeric, date, currency, email and phone.
37
+ *
38
+ * @param {UseScrollTopOptions} options - The options for the scroll top behavior.
39
+ * @returns {UseScrollTopExposes} - The exposed methods for the scroll top behavior.
40
+ *
41
+ * @example
42
+ * ```tsx
43
+ * const { scrollToTop, visible } = useScrollTop({
44
+ * target: elementRef.current,
45
+ * threshold: 400,
46
+ * behavior: 'smooth'
47
+ * });
48
+ *
49
+ * return (
50
+ * <div ref={elementRef}>
51
+ * {visible && (
52
+ * <Button onClick={scrollToTop}>
53
+ * <i className="pi pi-arrow-up" />
54
+ * </Button>
55
+ * )}
56
+ * </div>
57
+ * );
58
+ */
59
+ export declare function useScrollTop(options?: UseScrollTopOptions): UseScrollTopExposes;
@@ -0,0 +1 @@
1
+ import{getWindowScrollTop as f}from"@primeuix/utils";import*as e from"react";function d(n){let{target:o=typeof window<"u"?window:null,threshold:r=400,behavior:i="smooth"}=n||{},[c,t]=e.useState(!1),p=()=>{o?.scroll({top:0,behavior:i})};return e.useEffect(()=>{if(!o)return;let a=l=>{l>r?t(!0):t(!1)},s=()=>{let l=o===window?f():o.scrollTop;a(l)};return o.addEventListener("scroll",s),()=>{o.removeEventListener("scroll",s)}},[o,r]),{visible:c,scrollToTop:p}}export{d as useScrollTop};
@@ -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,3 @@
1
+ 'use client';
2
+
3
+ "use client";import*as n from"react";var b={draggedItems:[],draggedIndex:null,sourceListId:null,dragOverListId:null,dragOverIndex:null,isDragging:!1};function x({onReorder:f,onTransfer:u,canTransfer:T,getSelectedItems:m}){let g=n.useRef([]),d=n.useRef(null),l=n.useRef(null),c=n.useRef(null),[R,I]=n.useState(b),o=n.useCallback(()=>{g.current=[],d.current=null,l.current=null,c.current=null,I(b)},[]),i=n.useCallback((e,t)=>u?T?T(e,t):!0:!1,[u,T]),D=n.useCallback(e=>({onDragOver:t=>{t.preventDefault();let a=d.current;a===e?t.dataTransfer.dropEffect="move":a&&(t.dataTransfer.dropEffect=i(a,e)?"move":"none"),I(r=>r.dragOverListId!==e?{...r,dragOverListId:e,dragOverIndex:null}:r)},onDrop:t=>{t.preventDefault();let a=d.current,r=l.current,s=c.current;a===e?r!==null&&s!==null&&r!==s&&f(e,r,s):a&&g.current.length>0&&i(a,e)&&u(a,e,g.current,s??void 0),o()}}),[f,u,i,o]),S=n.useCallback((e,t,a)=>({draggable:!0,"data-index":t,onDragStart:r=>{let s=m?m(e,a):[a];r.dataTransfer.effectAllowed="move",r.dataTransfer.setData("text/plain",""),g.current=s,d.current=e,l.current=t,c.current=t,requestAnimationFrame(()=>{I({draggedItems:s,draggedIndex:t,sourceListId:e,dragOverListId:null,dragOverIndex:null,isDragging:!0})})},onDragOver:r=>{r.preventDefault(),r.stopPropagation();let s=d.current,v=s===e;v?r.dataTransfer.dropEffect="move":s&&(r.dataTransfer.dropEffect=i(s,e)?"move":"none"),!(v&&t===l.current)&&(c.current=t,I(L=>L.dragOverListId!==e||L.dragOverIndex!==t?{...L,dragOverListId:e,dragOverIndex:t}:L))},onDragEnd:o}),[i,m,o]);return{dragState:R,getListHandlers:D,getItemHandlers:S,reset:o}}export{x as useSortableList};
@@ -0,0 +1,52 @@
1
+ import { registerMatcher, unregisterMatcher, type BuiltInMatchMode, type FilterMatcher, type FilterRule } from '@ohos-ports/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,3 @@
1
+ 'use client';
2
+
3
+ "use client";import{useControlledState as E}from"@ohos-ports/hooks/use-controlled-state";import{BUILT_IN_MATCHERS as U,getGlobalMatchers as j,matchRule as B,registerMatcher as K,ruleHasValue as O,unregisterMatcher as P}from"@ohos-ports/hooks/use-filter";import{resolveFieldData as b}from"@primeuix/utils/object";import*as t from"react";function H(e,r){let o=e.data!==null&&typeof e.data=="object";if(o&&r in e.data)return e.data[r];if(o){let a=b(e.data,r);if(a!==void 0)return a}return r in e?e[r]:b(e,r)}function _(e){return!e.children||e.children.length===0}function w(e,r,o,a){let s=Array.isArray(r.field)?r.field:[r.field],d={};for(let n of s)d[n]=H(e,n);return B(d,{...r,field:s},o,a)}function x(e,r,o,a,s){let d=[];for(let n of e){let M=r.every(i=>w(n,i,o,a)),u=null;if(n.children&&n.children.length>0){let i=x(n.children,r,o,a,s);i.length>0&&(u=i)}s?_(n)?M&&d.push(n):u&&d.push({...n,children:u}):M?d.push(n):u&&d.push({...n,children:u})}return d}function q(e){let r=e.field!==void 0&&e.rules===void 0&&e.defaultRules===void 0,o=e.matchMode??"contains",[a,s]=E({value:e.value,defaultValue:e.defaultValue??null,onChange:e.onValueChange}),d=t.useCallback(l=>s(l),[s]),n=e.rules!==void 0,[M,u]=t.useState(e.defaultRules??[]),i=t.useMemo(()=>r?[{field:e.field,value:a,matchMode:o}]:[],[r,e.field,a,o]),c=t.useMemo(()=>r?i:n?e.rules??[]:M,[r,i,n,e.rules,M]),y=t.useRef(e.onRulesChange);y.current=e.onRulesChange;let k=t.useCallback(l=>{r?s(l[0]?.value??null):n||u(l),y.current?.(l)},[r,n,s]),f=e.filterLocale,N=e.filterDelay??0,h=e.filterMode??"lenient",g=t.useMemo(()=>({...U,...j(),...e.matchers??{}}),[e.matchers]),[C,z]=t.useState(c);t.useEffect(()=>{if(N<=0)return;let l=setTimeout(()=>z(c),N);return()=>clearTimeout(l)},[c,N]);let F=N>0?C:c,R=t.useMemo(()=>F.filter(O),[F]),V=t.useCallback(l=>R.every(T=>w(l,T,g,f)),[R,g,f]),m=!!e.lazy,A=t.useMemo(()=>m||R.length===0?e.nodes:x(e.nodes,R,g,f,h==="strict"),[m,e.nodes,R,g,f,h]),v=t.useRef(e.onLazyLoad);v.current=e.onLazyLoad;let L=t.useRef(null);t.useEffect(()=>{if(!m)return;let l=JSON.stringify(F)+"|"+h;L.current!==l&&(L.current=l,v.current?.({rules:F,filterMode:h,filterLocale:f}))},[m,F,h,f]);let D=t.useCallback(l=>k(l),[k]),I=t.useCallback(()=>{let l=c.map(T=>Array.isArray(T.constraints)?{...T,constraints:T.constraints.map(S=>({...S,value:null}))}:{...T,value:null});k(l)},[c,k]);return{rules:c,filteredNodes:A,isFiltered:R.length>0,setRules:D,value:a,setValue:d,clearAll:I,match:V,matchers:g}}export{K as registerMatcher,P as unregisterMatcher,q as useTreeFilter};
@@ -0,0 +1,18 @@
1
+ import * as React from 'react';
2
+ /**
3
+ * Custom hook that runs an unmount effect only once.
4
+ * This is similar to `useEffect`, but it only runs on unmount.
5
+ *
6
+ * @param {React.EffectCallback} effect the callback function
7
+ * @returns {void}
8
+ *
9
+ * @example
10
+ * ```tsx
11
+ * const Component = () => {
12
+ * useUnmountEffect(() => {
13
+ * console.log('Unmounted');
14
+ * });
15
+ * };
16
+ * ```
17
+ */
18
+ export declare function useUnmountEffect(effect: React.EffectCallback): void;
@@ -0,0 +1 @@
1
+ import*as t from"react";function c(e){t.useEffect(()=>()=>{e?.()},[])}export{c as useUnmountEffect};
@@ -0,0 +1,19 @@
1
+ import * as React from 'react';
2
+ /**
3
+ * Custom hook that runs an update effect whenever dependencies change.
4
+ * This is similar to `useEffect`, but it does not run on mount.
5
+ *
6
+ * @param {React.EffectCallback} effect the callback function
7
+ * @param {React.DependencyList} dependencies the dependencies
8
+ * @returns {void}
9
+ *
10
+ * @example
11
+ * ```tsx
12
+ * const Component = ({ value }) => {
13
+ * useUpdateEffect(() => {
14
+ * console.log('Updated');
15
+ * }, [value]);
16
+ * };
17
+ * ```
18
+ */
19
+ export declare function useUpdateEffect(effect: React.EffectCallback, dependencies?: React.DependencyList): void;
@@ -0,0 +1 @@
1
+ import*as e from"react";function a(c,r){let t=e.useRef(!1);e.useEffect(()=>{if(!t.current){t.current=!0;return}return c?.()},r)}export{a as useUpdateEffect};
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Starts a view transition.
3
+ *
4
+ * @returns A function that starts a view transition.
5
+ *
6
+ * @example
7
+ * ```tsx
8
+ * const Component = () => {
9
+ * const startTransition = useViewTransition();
10
+ *
11
+ * const handleClick = () => {
12
+ * startTransition(() => {
13
+ * // Perform some work
14
+ * });
15
+ * };
16
+ *
17
+ * return <button onClick={handleClick}>Click me</button>;
18
+ * };
19
+ */
20
+ export declare function useViewTransition(): (callback: () => void) => void;
@@ -0,0 +1 @@
1
+ import*as i from"react";function r(){return i.useCallback(t=>{document.startViewTransition?document.startViewTransition(()=>{t()}):t()},[])}export{r as useViewTransition};
@@ -0,0 +1,14 @@
1
+ /**
2
+ * useVisibilityChange hook is used to check if the document is visible.
3
+ *
4
+ * @returns A boolean indicating whether the document is visible.
5
+ *
6
+ * @example
7
+ * ```tsx
8
+ * const Component = () => {
9
+ * const isVisible = useVisibilityChange();
10
+ *
11
+ * return <div>{isVisible ? 'Visible' : 'Hidden'}</div>;
12
+ * };
13
+ */
14
+ export declare function useVisibilityChange(): boolean;
@@ -0,0 +1 @@
1
+ import*as e from"react";function s(){let[t,n]=e.useState(!0);return e.useEffect(()=>{let i=()=>{n(!document.hidden)};return i(),document.addEventListener("visibilitychange",i),()=>{document.removeEventListener("visibilitychange",i)}},[]),t}export{s as useVisibilityChange};