@tonar/react-kit 0.0.1-canary

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 sonion
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,75 @@
1
+ # @tonar/react-kit
2
+
3
+ `@tonar/react-kit` 是 Tonar 的 React 18 组件和 Hooks 包,提供轮播、条件渲染、错误边界、状态辅助、观察器、存储、定时器和异步操作锁等能力。
4
+
5
+ `@tonar/react-kit` is Tonar's React 18 component and hooks package for carousel, conditional rendering, error boundaries, state helpers, observers, storage, timers, and async action locking.
6
+
7
+ - ✅ 支持 React 18+
8
+ - ✅ TypeScript 类型支持
9
+ - ✅ 仅支持 ESM(不支持 CommonJS)
10
+ - ✅ 支持 Tree-shaking
11
+
12
+ ## 📦 Installation / 安装
13
+
14
+ ```bash
15
+ npm install @tonar/react-kit@latest
16
+ pnpm add @tonar/react-kit
17
+ yarn add @tonar/react-kit
18
+ ```
19
+
20
+ ## 🚀 Usage / 使用方法
21
+
22
+ ```tsx
23
+ import React from 'react';
24
+ import { Carousel, ErrorBoundary } from '@tonar/react-kit/components';
25
+ import { useDistinctState } from '@tonar/react-kit/hooks';
26
+
27
+ export default function App() {
28
+ const [count, setCount] = useDistinctState({ initialValue: 0 });
29
+
30
+ return (
31
+ <ErrorBoundary fallback={<div>Something went wrong</div>}>
32
+ <button onClick={() => setCount(count + 1)}>Click Me ({count})</button>
33
+ <Carousel cardWidth={200} cardHeight={120}>
34
+ <div style={{ background: 'lightblue' }}>Slide 1</div>
35
+ <div style={{ background: 'lightgreen' }}>Slide 2</div>
36
+ <div style={{ background: 'lightpink' }}>Slide 3</div>
37
+ </Carousel>
38
+ </ErrorBoundary>
39
+ );
40
+ }
41
+ ```
42
+
43
+ ## 🧩 Components / 组件
44
+
45
+ - `Carousel`:轮播组件,支持自动播放、无缝轮播、指示器、自定义箭头、非循环结束回调等
46
+ - `CustomShow`:条件展示组件,替代常见三目运算和短路规则条件渲染
47
+ - `AsyncCustomShow`:异步条件展示组件,根据 Promise 结果展示内容或 fallback
48
+ - `ErrorBoundary`:错误边界组件,用于捕获子组件错误并显示自定义回退内容
49
+
50
+ ## 🔗 Hooks / 钩子函数
51
+
52
+ - `useDistinctState`:差异才更新的状态,支持 `onChange` 事件和自定义差异对比函数
53
+ - `useStaticState`:静态状态,不触发 React 更新
54
+ - `useCreateSafeRef`:安全引用,相同节点不更新,改变时可触发更新,支持自定义差异对比函数
55
+ - `useLatestCallback`:保持稳定的最新回调,解决稳定函数引用和闭包获取新值不可兼得的问题
56
+ - `useAsyncActionLock`:异步操作锁,根据传入异步函数确定是否可再触发,并提供运行中状态
57
+ - `useIntersectionObserver`:交叉观察器 Hook
58
+ - `useMutationObserver`:节点变化观察器 Hook
59
+ - `useResizeObserver`:尺寸变化观察器 Hook
60
+ - `useInterval`:自管理定时器 Hook
61
+ - `useRAfInterval`:基于 `requestAnimationFrame` 的定时器 Hook
62
+ - `useStorage`:支持事件同步的本地存储 Hook
63
+
64
+ ## 📚 TypeScript tips / 类型导入提示
65
+
66
+ ```ts
67
+ import type { CarouselProps } from '@tonar/react-kit/components';
68
+ ```
69
+
70
+ ## 📝 License / 许可证
71
+
72
+ MIT © Sonion
73
+
74
+ 欢迎 [Pull Requests](https://github.com/sonion028/gonar/pulls) 和 [Issues](https://github.com/sonion028/gonar/issues)
75
+ 源码仓库:[https://github.com/sonion028/gonar](https://github.com/sonion028/gonar)
@@ -0,0 +1,2 @@
1
+ import { i as e, n as t, r as n, t as r } from "./js/components.CLeQ5flK.js";
2
+ export { t as AsyncCustomShow, e as Carousel, n as CustomShow, r as ErrorBoundary };
@@ -0,0 +1 @@
1
+ ._carousel_1ryaf_1{width:100%;height:100%;position:relative;overflow:hidden}._carousel_1ryaf_1[style*=--wrapperWidth]{width:calc(var(--wrapperWidth) * 1px)}._carousel_1ryaf_1[style*=--wrapperHeight]{height:calc(var(--wrapperHeight) * 1px)}._carousel_1ryaf_1:not([style*=--cardHeight]) ._wrapper_1ryaf_13 ._inner_1ryaf_13{height:100%}._carousel_1ryaf_1[style*=--cardWidth] ._wrapper_1ryaf_13{width:calc(var(--cardWidth) * 1px)}._carousel_1ryaf_1[style*=--cardWidth] ._wrapper_1ryaf_13 ._inner_1ryaf_13{transform:translateX(calc(var(--index) * (var(--cardWidth) + var(--gapSize,0)) * -1px))}._carousel_1ryaf_1[style*=--cardWidth] ._wrapper_1ryaf_13 ._inner_1ryaf_13>*{flex:0 0 calc(var(--cardWidth) * 1px);height:100%}._carousel_1ryaf_1:not([style*=--cardWidth]) ._wrapper_1ryaf_13{width:100%}._carousel_1ryaf_1:not([style*=--cardWidth]) ._wrapper_1ryaf_13 ._inner_1ryaf_13{transform:translateX(calc((-100% + var(--gapSize,0) * -1px) * var(--index)))}._carousel_1ryaf_1:not([style*=--cardWidth]) ._wrapper_1ryaf_13 ._inner_1ryaf_13>*{flex:0 0 100%;height:100%}._carousel_1ryaf_1:hover>._arrow_1ryaf_36.hover{display:block}._carousel_1ryaf_1>._arrow_1ryaf_36.hover,._carousel_1ryaf_1>._arrow_1ryaf_36.none{display:none}._carousel_1ryaf_1>._arrow_1ryaf_36.always,._carousel_1ryaf_1>._arrow_1ryaf_36.auto{display:block}._carousel_1ryaf_1>._arrow_1ryaf_36 ._left_1ryaf_48,._carousel_1ryaf_1>._arrow_1ryaf_36 ._right_1ryaf_49{z-index:9;cursor:pointer;background:#fff url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMjEiIGhlaWdodD0iMjAiIHZpZXdCb3g9IjAgMCAyMSAyMCIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPGcgaWQ9ImRvd24iPgo8cGF0aCBpZD0iVW5pb24iIGZpbGwtcnVsZT0iZXZlbm9kZCIgY2xpcC1ydWxlPSJldmVub2RkIiBkPSJNNi43OTE4MiA1Ljc2ODY1QzYuNDAyNzMgNS4zNzk1NiA2LjQwMjczIDQuNzQ4NzEgNi43OTE4MiA0LjM1OTYyTDcuNDk2MzQgMy42NTUxQzcuODg1NDMgMy4yNjYwMSA4LjUxNjI4IDMuMjY2MDEgOC45MDUzNyAzLjY1NTFMMTQuNTQxNSA5LjI5MTI0QzE0LjczNzEgOS40ODY4MyAxNC44MzQ0IDkuNzQzNSAxNC44MzMzIDkuOTk5ODVDMTQuODM0NCAxMC4yNTYyIDE0LjczNzEgMTAuNTEyOSAxNC41NDE1IDEwLjcwODVMOC45MDUzNyAxNi4zNDQ2QzguNTE2MjggMTYuNzMzNyA3Ljg4NTQzIDE2LjczMzcgNy40OTYzNCAxNi4zNDQ2TDYuNzkxODIgMTUuNjQwMUM2LjQwMjczIDE1LjI1MSA2LjQwMjczIDE0LjYyMDEgNi43OTE4MiAxNC4yMzExTDExLjAyMyA5Ljk5OTg1TDYuNzkxODIgNS43Njg2NVoiIGZpbGw9IiMwMDY2RkMiLz4KPC9nPgo8L3N2Zz4K) 50%/contain no-repeat content-box border-box;border:1px solid #dde2e9;border-radius:50%;width:20px;height:20px;padding:14px;display:none;position:absolute;top:50%;transform:translateY(-50%);box-shadow:0 15px 35px -2px #0000000d,0 5px 15px #0000000d}._carousel_1ryaf_1>._arrow_1ryaf_36>.show{display:block}._carousel_1ryaf_1>._arrow_1ryaf_36 ._left_1ryaf_48{left:12px;transform:translateY(-50%)rotate(180deg)}._carousel_1ryaf_1>._arrow_1ryaf_36 ._right_1ryaf_49{right:12px}._carousel_1ryaf_1 ._wrapper_1ryaf_13{height:100%}._carousel_1ryaf_1 ._wrapper_1ryaf_13 ._inner_1ryaf_13{gap:calc(var(--gapSize) * 1px);height:calc(var(--cardHeight) * 1px);transition:transform .3s;display:flex}._indicator_1ryaf_85{z-index:9;border-radius:8px;gap:8px;display:flex;position:absolute;bottom:-17px;left:50%;transform:translate(-50%)}._indicator_1ryaf_85.none{display:none}._indicator_1ryaf_85.line>i{background-color:var(--Gray-3,#e5e8ef);cursor:pointer;border-radius:8px;width:40px;height:5px}._indicator_1ryaf_85.line>i.active{background:var(--byte-plus-blue-brand-primary-60,#0066fc)}._indicator_1ryaf_85.dot>i{background-color:var(--Gray-3,#e5e8ef);cursor:pointer;border-radius:50%;width:6px;height:6px}._indicator_1ryaf_85.dot>i.active{background:var(--byte-plus-blue-brand-primary-60,#0066fc)}
@@ -0,0 +1,184 @@
1
+ import { useCallback as e, useEffect as t, useMemo as n, useRef as r, useState as i } from "react";
2
+ import { clearRAfInterval as a, rAfInterval as o } from "@tonar/utils";
3
+ //#region src/hooks/state/index.ts
4
+ function s(t) {
5
+ let n = r(t);
6
+ return [
7
+ e(() => n.current, []),
8
+ e((e) => n.current = e, []),
9
+ e((e) => e === void 0 ? n.current : n.current = e, [])
10
+ ];
11
+ }
12
+ var c = (t) => {
13
+ let n = r(t);
14
+ return n.current !== t && (n.current = t), e((...e) => n.current?.(...e), []);
15
+ };
16
+ function l({ initialValue: t, onChange: n, hasDiff: a = (e, t) => e !== t, onlyEvent: o }) {
17
+ let s = r(void 0), [l, u] = i(() => s.current = typeof t == "function" ? t() : t), d = c(n), f = e((e) => {
18
+ let t = typeof e == "function" ? e(s.current) : e;
19
+ (a ?? ((e, t) => e !== t))(s.current, t) && (d?.(t), s.current = t, o || u(t));
20
+ }, [
21
+ d,
22
+ o,
23
+ u,
24
+ !!a
25
+ ]);
26
+ return [
27
+ o ? void 0 : l,
28
+ f,
29
+ e(() => s.current, [])
30
+ ];
31
+ }
32
+ var u = (t) => {
33
+ let [n, a] = i(), o = r(!1);
34
+ return [
35
+ n,
36
+ e((e) => {
37
+ e && (t ?? ((e, t) => e !== t))(n, e) && (o.current = !0, a(e));
38
+ }, [n, !!t]),
39
+ o
40
+ ];
41
+ }, d = (t, n) => {
42
+ let i = r(void 0), a = c(t), o = e(() => {
43
+ clearTimeout(i.current), i.current = setTimeout(() => {
44
+ try {
45
+ a?.();
46
+ } catch (e) {
47
+ console.error("useInterval error", e);
48
+ }
49
+ o?.();
50
+ }, n);
51
+ }, [n, a]);
52
+ return [o, e(() => clearTimeout(i.current), [i])];
53
+ }, f = (t, n) => {
54
+ let i = r(void 0);
55
+ return [e(() => {
56
+ a(i.current), i.current = o(t, n);
57
+ }, [t, n]), e(() => a(i.current), [i])];
58
+ }, p = (n, i = !1) => {
59
+ let a = r(), o = c(n);
60
+ return t(() => () => {
61
+ a.current?.disconnect?.(), a.current = void 0;
62
+ }, []), {
63
+ observe: e((e, t) => {
64
+ e && (a.current ?? (a.current = new MutationObserver((e, t) => {
65
+ o?.(e, t), i && t.disconnect();
66
+ })), a.current?.observe?.(e, t));
67
+ }, [i, o]),
68
+ takeRecords: e(() => a.current?.takeRecords?.(), []),
69
+ disconnect: e(() => a.current?.disconnect?.(), [])
70
+ };
71
+ }, m = ({ callback: i, rootMargin: a = 100, threshold: o = 0, once: s = !1 }) => {
72
+ let l = r(), [d, f] = u(), p = c(i), m = n(() => ({
73
+ root: d,
74
+ rootMargin: `${a}px`,
75
+ threshold: o
76
+ }), [
77
+ d,
78
+ a,
79
+ o
80
+ ]), h = r(m);
81
+ t(() => () => {
82
+ l.current?.disconnect?.(), l.current = void 0;
83
+ }, [m]);
84
+ let g = e((e) => {
85
+ e && (h.current !== m && (l.current?.disconnect?.(), l.current = void 0, h.current = m), l.current ?? (l.current = new IntersectionObserver((e, t) => {
86
+ e.forEach((e) => {
87
+ e.isIntersecting && (p?.(e.target, d, t), s && t.unobserve?.(e.target));
88
+ });
89
+ }, m)), l.current?.unobserve?.(e), l.current?.observe?.(e));
90
+ }, [
91
+ m,
92
+ s,
93
+ p
94
+ ]), _ = e((e) => e && l.current?.unobserve?.(e), []), v = e(() => l.current?.takeRecords?.(), []);
95
+ return {
96
+ rootRef: d,
97
+ setRootRef: f,
98
+ observe: g,
99
+ unobserve: _,
100
+ disconnect: e(() => l.current?.disconnect?.(), []),
101
+ takeRecords: v
102
+ };
103
+ }, h = (n, i = !1) => {
104
+ let a = r(), o = c(n);
105
+ return t(() => () => {
106
+ a.current?.disconnect?.(), a.current = void 0;
107
+ }, []), {
108
+ observe: e((e, t) => {
109
+ e && (a.current ?? (a.current = new ResizeObserver((e, t) => {
110
+ e.forEach((e) => {
111
+ o?.(e, t);
112
+ }), i && t.disconnect();
113
+ })), a.current?.unobserve?.(e), a.current?.observe?.(e, t));
114
+ }, [i, o]),
115
+ unobserve: e((e) => e && a.current?.unobserve?.(e), []),
116
+ disconnect: e(() => a.current?.disconnect?.(), [])
117
+ };
118
+ }, g = ({ key: n, initialValue: r, hasDiff: i, onChange: a, storage: o = localStorage, checkType: s = () => !0, beforeunload: c }) => {
119
+ let [u, d] = l({
120
+ initialValue: () => {
121
+ try {
122
+ let e = o.getItem(n), t = e ? JSON.parse(e) : r;
123
+ return s(t) ? t : r;
124
+ } catch (e) {
125
+ return console.warn("初始化出错,已使用默认值", e), r;
126
+ }
127
+ },
128
+ hasDiff: i,
129
+ onChange: a
130
+ }), f = e((e) => {
131
+ try {
132
+ d((t) => {
133
+ let r = e instanceof Function ? e(t) : e, i = JSON.stringify(r);
134
+ return o.setItem(n, i), window.dispatchEvent(new StorageEvent("storage", {
135
+ key: n,
136
+ newValue: i,
137
+ storageArea: o
138
+ })), r;
139
+ });
140
+ } catch (e) {
141
+ console.error("持久化储存错误", e);
142
+ }
143
+ }, [
144
+ n,
145
+ o,
146
+ d
147
+ ]);
148
+ return t(() => {
149
+ let e = (e) => {
150
+ if (!(e.storageArea !== o || e.key !== n)) try {
151
+ d(e.newValue ? JSON.parse(e.newValue) : r);
152
+ } catch (e) {
153
+ console.error("storage事件处理出错", e);
154
+ }
155
+ };
156
+ return window.addEventListener("storage", e), () => window.removeEventListener("storage", e);
157
+ }, [
158
+ n,
159
+ o,
160
+ r,
161
+ d
162
+ ]), t(() => {
163
+ c && window.addEventListener("beforeunload", c);
164
+ }, []), [u, f];
165
+ }, _ = (t, n, a) => {
166
+ let [o, s] = i(!1), l = r(o), u = c(n), d = e((e, ...t) => {
167
+ l.current = e, s(e), u?.(e, ...t);
168
+ }, [u]), f = c(t);
169
+ return [o, e((...e) => l.current ? (console.log(a || "正在提交中,请稍后再试"), Promise.resolve()) : (d(!0, ...e), new Promise((t, n) => {
170
+ try {
171
+ t(f?.(...e));
172
+ } catch (e) {
173
+ n(e);
174
+ }
175
+ }).finally(() => {
176
+ d(!1, ...e);
177
+ })), [
178
+ f,
179
+ a,
180
+ d
181
+ ])];
182
+ };
183
+ //#endregion
184
+ export { _ as useAsyncActionLock, u as useCreateSafeRef, l as useDistinctState, m as useIntersectionObserver, d as useInterval, c as useLatestCallback, p as useMutationObserver, f as useRAfInterval, h as useResizeObserver, s as useStaticState, g as useStorage };
@@ -0,0 +1,3 @@
1
+ import { useAsyncActionLock as e, useCreateSafeRef as t, useDistinctState as n, useIntersectionObserver as r, useInterval as i, useLatestCallback as a, useMutationObserver as o, useRAfInterval as s, useResizeObserver as c, useStaticState as l, useStorage as u } from "./hooks.esm.js";
2
+ import { i as d, n as f, r as p, t as m } from "./js/components.CLeQ5flK.js";
3
+ export { f as AsyncCustomShow, d as Carousel, p as CustomShow, m as ErrorBoundary, e as useAsyncActionLock, t as useCreateSafeRef, n as useDistinctState, r as useIntersectionObserver, i as useInterval, a as useLatestCallback, o as useMutationObserver, s as useRAfInterval, c as useResizeObserver, l as useStaticState, u as useStorage };
@@ -0,0 +1,235 @@
1
+ import { useCreateSafeRef as e, useRAfInterval as t } from "../hooks.esm.js";
2
+ import { Component as n, cloneElement as r, forwardRef as i, useCallback as a, useEffect as o, useImperativeHandle as s, useMemo as c, useRef as l, useState as u } from "react";
3
+ import { Fragment as d, jsx as f, jsxs as p } from "react/jsx-runtime";
4
+ import '../css/components.C24nnsjt.css';//#region src/components/carousel/hooks/index.ts
5
+ var m = (e, t) => {
6
+ e.style.cssText = `transition-duration: 0s; --index: ${t}`, e.clientLeft, e.style.cssText = "";
7
+ }, h = (e, t) => {
8
+ let n = e.previousElementSibling;
9
+ if (!n) return;
10
+ let [r, i] = t;
11
+ n.children[0]?.classList.toggle("show", r), n.children[1]?.classList.toggle("show", i);
12
+ }, g = (e, t, n) => {
13
+ e.style.setProperty("--index", `${t}`);
14
+ let r = e.parentElement;
15
+ if (!r) return;
16
+ let i = r.parentElement?.nextElementSibling;
17
+ i && (i.querySelector(".active")?.classList.remove("active"), i.children[t >= i.children.length ? 0 : t]?.classList.add("active")), h(r, n);
18
+ }, _ = ({ showArrow: e, length: t, cardWidth: n, wrapperRef: r }) => {
19
+ let i = c(() => {
20
+ let e = (r?.parentElement?.parentElement?.clientWidth || n) ?? 0;
21
+ return n ? Math.floor(e / n) : 1;
22
+ }, [r, n]);
23
+ return a((n) => {
24
+ if (e !== "auto") return [!0, !0];
25
+ let r;
26
+ return r = t > i ? n + i - 1 < t - 1 : !1, [n > 0, r];
27
+ }, [
28
+ i,
29
+ t,
30
+ e
31
+ ]);
32
+ }, v = ({ length: t, loop: n, showArrow: r, cardWidth: i, onNonLoopEnd: s, offsetOnEnd: c = 0 }) => {
33
+ let u = t, d = l(0), [f, p, v] = e();
34
+ c = ~~c, c = c < 0 || c >= t ? 0 : c;
35
+ let y = _({
36
+ showArrow: r,
37
+ length: t,
38
+ cardWidth: i,
39
+ wrapperRef: f
40
+ });
41
+ o(() => {
42
+ let e = f?.parentElement;
43
+ r !== "auto" || !e || h(e, y(d.current));
44
+ }, [t]);
45
+ let b = a((e) => {
46
+ if (!f) return;
47
+ n && (d.current >= u && e !== "prev" ? (d.current = 0, m(f, d.current)) : d.current <= 0 && e === "prev" && (d.current = u, m(f, d.current))), e === "prev" ? d.current-- : d.current++;
48
+ let r = y(d.current);
49
+ g(f, d.current, r), !n && s && d.current === t - c - 1 && s(e ?? "next", d.current, t, c);
50
+ }, [
51
+ t,
52
+ n,
53
+ f,
54
+ y,
55
+ c,
56
+ s,
57
+ u
58
+ ]), x = a((e) => {
59
+ let r = d.current;
60
+ d.current = e < 0 ? 0 : e > t ? t : e;
61
+ let i = y(d.current);
62
+ if (f && g(f, d.current, i), !n && s) {
63
+ let e = r < d.current ? "next" : "prev", n = t - c - 1;
64
+ (d.current >= n && r < n || d.current <= n && r > n) && s(e, d.current, t, c);
65
+ }
66
+ }, [
67
+ t,
68
+ n,
69
+ f,
70
+ y,
71
+ c,
72
+ s
73
+ ]), S = a(() => d.current, []);
74
+ return o(() => x(d.current), [f]), [
75
+ p,
76
+ b,
77
+ x,
78
+ S,
79
+ v
80
+ ];
81
+ }, y = (() => {
82
+ let e = Math.random().toString(36).slice(2), t = 0;
83
+ return () => `${e}-${++t}`;
84
+ })(), b = (e, t, n) => c(() => {
85
+ if (!Array.isArray(e) || !e.length) throw Error("Carousel children must be an array");
86
+ if (t) {
87
+ let t = e[0], n = [...e];
88
+ return n.push(r(t, { key: y() })), n;
89
+ }
90
+ return e;
91
+ }, [n === "child" ? e : e?.length, t]), x = {
92
+ carousel: "_carousel_1ryaf_1",
93
+ wrapper: "_wrapper_1ryaf_13",
94
+ inner: "_inner_1ryaf_13",
95
+ arrow: "_arrow_1ryaf_36",
96
+ left: "_left_1ryaf_48",
97
+ right: "_right_1ryaf_49",
98
+ indicator: "_indicator_1ryaf_85"
99
+ }, S = i(({ cardWidth: e, cardHeight: n, wrapperWidth: r, wrapperHeight: i, gapSize: a, loop: c = !0, duration: l = 6e3, autoPlay: u = !0, showArrow: m = "always", indicatorType: h = "line", className: g, style: _, children: y, rerender: S = "length", onNonLoopEnd: C, offsetOnEnd: w = 0, arrows: T }, E) => {
100
+ let D = b(y, c, S), [O, k, A, j] = v({
101
+ length: y.length,
102
+ loop: c,
103
+ showArrow: m,
104
+ cardWidth: e,
105
+ onNonLoopEnd: C,
106
+ offsetOnEnd: w
107
+ }), [M, N] = t(k, l);
108
+ return o(() => (u && M(), N), [
109
+ M,
110
+ N,
111
+ u
112
+ ]), s(E, () => ({
113
+ run: M,
114
+ stop: N,
115
+ stepChange: k,
116
+ jumpChange: A,
117
+ getCurrentIndex: j
118
+ }), [
119
+ M,
120
+ N,
121
+ k,
122
+ A,
123
+ j
124
+ ]), /* @__PURE__ */ p(d, { children: [/* @__PURE__ */ p("div", {
125
+ className: `${x.carousel} ${g ?? ""}`,
126
+ style: {
127
+ ..._,
128
+ "--wrapperWidth": r,
129
+ "--wrapperHeight": i,
130
+ "--cardWidth": e,
131
+ "--cardHeight": n,
132
+ "--gapSize": a
133
+ },
134
+ onMouseEnter: N,
135
+ onMouseLeave: u ? M : void 0,
136
+ children: [/* @__PURE__ */ p("div", {
137
+ className: `${x.arrow} ${m}`,
138
+ children: [T?.[0] ? T[0]({
139
+ onClick: () => k("prev"),
140
+ className: x.left
141
+ }) : /* @__PURE__ */ f("i", {
142
+ className: x.left,
143
+ onClick: () => k("prev")
144
+ }), T?.[1] ? T[1]({
145
+ onClick: () => k(),
146
+ className: x.right
147
+ }) : /* @__PURE__ */ f("i", {
148
+ className: x.right,
149
+ onClick: () => k()
150
+ })]
151
+ }), /* @__PURE__ */ f("div", {
152
+ className: x.wrapper,
153
+ children: /* @__PURE__ */ f("div", {
154
+ className: x.inner,
155
+ ref: O,
156
+ children: D
157
+ })
158
+ })]
159
+ }), /* @__PURE__ */ f("div", {
160
+ className: `${x.indicator} ${h}`,
161
+ children: y.map((e, t) => /* @__PURE__ */ f("i", { onClick: (e) => {
162
+ e.stopPropagation(), A(t);
163
+ } }, t))
164
+ })] });
165
+ });
166
+ S.displayName = "Carousel";
167
+ //#endregion
168
+ //#region src/components/custom-show/index.tsx
169
+ function C({ when: e, fallback: t = void 0, children: n }) {
170
+ return /* @__PURE__ */ f(d, { children: e ? n : t });
171
+ }
172
+ //#endregion
173
+ //#region src/components/async-custom-show/index.tsx
174
+ function w({ when: e, fallback: t, children: n }) {
175
+ let [r, i] = u(void 0);
176
+ return o(() => {
177
+ e && Promise.resolve(e).then(i);
178
+ }, [e]), /* @__PURE__ */ f(d, { children: r ? n(r) : t });
179
+ }
180
+ //#endregion
181
+ //#region \0@oxc-project+runtime@0.133.0/helpers/esm/typeof.js
182
+ function T(e) {
183
+ "@babel/helpers - typeof";
184
+ return T = typeof Symbol == "function" && typeof Symbol.iterator == "symbol" ? function(e) {
185
+ return typeof e;
186
+ } : function(e) {
187
+ return e && typeof Symbol == "function" && e.constructor === Symbol && e !== Symbol.prototype ? "symbol" : typeof e;
188
+ }, T(e);
189
+ }
190
+ //#endregion
191
+ //#region \0@oxc-project+runtime@0.133.0/helpers/esm/toPrimitive.js
192
+ function E(e, t) {
193
+ if (T(e) != "object" || !e) return e;
194
+ var n = e[Symbol.toPrimitive];
195
+ if (n !== void 0) {
196
+ var r = n.call(e, t || "default");
197
+ if (T(r) != "object") return r;
198
+ throw TypeError("@@toPrimitive must return a primitive value.");
199
+ }
200
+ return (t === "string" ? String : Number)(e);
201
+ }
202
+ //#endregion
203
+ //#region \0@oxc-project+runtime@0.133.0/helpers/esm/toPropertyKey.js
204
+ function D(e) {
205
+ var t = E(e, "string");
206
+ return T(t) == "symbol" ? t : t + "";
207
+ }
208
+ //#endregion
209
+ //#region \0@oxc-project+runtime@0.133.0/helpers/esm/defineProperty.js
210
+ function O(e, t, n) {
211
+ return (t = D(t)) in e ? Object.defineProperty(e, t, {
212
+ value: n,
213
+ enumerable: !0,
214
+ configurable: !0,
215
+ writable: !0
216
+ }) : e[t] = n, e;
217
+ }
218
+ //#endregion
219
+ //#region src/components/error-boundary/index.tsx
220
+ var k = class extends n {
221
+ constructor(...e) {
222
+ super(...e), O(this, "state", { hasError: !1 }), O(this, "msg", this.props.msg ?? "组件加载失败");
223
+ }
224
+ static getDerivedStateFromError() {
225
+ return { hasError: !0 };
226
+ }
227
+ componentDidCatch(e, t) {
228
+ console.error(`${this.msg}:`, e, t);
229
+ }
230
+ render() {
231
+ return this.state.hasError ? this.props.fallback : this.props.children;
232
+ }
233
+ };
234
+ //#endregion
235
+ export { S as i, w as n, C as r, k as t };
@@ -0,0 +1,22 @@
1
+ import { FC, ReactNode, JSX } from 'react';
2
+ export type AsyncCustomShowProps<T> = {
3
+ /** 异步判断 Promise */
4
+ when: Promise<T> | undefined | null | false;
5
+ /** 异步失败时的展示 */
6
+ fallback?: ReactNode;
7
+ /** 异步成功时的展示 */
8
+ children: (value: T | undefined | null | false) => ReactNode;
9
+ };
10
+ export interface AsyncCustomShowType<T> extends FC<AsyncCustomShowProps<T>> {
11
+ (props: AsyncCustomShowProps<T>): JSX.Element;
12
+ }
13
+ /**
14
+ * @author sonion
15
+ * @description 异步展示组件
16
+ * @param {AsyncCustomShowProps<T>} props - 组件属性
17
+ * @param {Promise<T> | undefined | null | false} props.when 异步判断 Promise
18
+ * @param {ReactNode} [props.fallback] 异步失败时的展示
19
+ * @param {(value: T | undefined | null | false) => ReactNode} props.children 异步成功时的展示
20
+ */
21
+ declare function AsyncCustomShow<T>({ when, fallback, children, }: AsyncCustomShowProps<T>): JSX.Element;
22
+ export default AsyncCustomShow;
@@ -0,0 +1,74 @@
1
+ import { ReactElement } from 'react';
2
+ export type ShowArrowType = 'always' | 'auto' | 'hover' | 'none';
3
+ type ShowArrowHookParams = {
4
+ /** 箭头类型 */
5
+ showArrow: ShowArrowType;
6
+ /** 轮播图数量 */
7
+ length: number;
8
+ /** 轮播图宽度 */
9
+ cardWidth?: number;
10
+ /** 轮播图容器 */
11
+ wrapperRef?: HTMLElement;
12
+ };
13
+ /**
14
+ * @author sonion
15
+ * @description 计算是否显示左右箭头
16
+ * @param {ShowArrowHookParams} params - hook参数
17
+ * @param {ShowArrowType} params.showArrow - 箭头类型
18
+ * @param {number} params.length - 轮播图数量
19
+ * @param {number} params.cardWidth - 轮播图宽度
20
+ * @param {HTMLElement} params.wrapperRef - 轮播图容器
21
+ * @returns {(index: number)=>[boolean, boolean]} - 计算是否显示左右箭头的函数
22
+ */
23
+ export declare const useShowArrow: ({ showArrow, length, cardWidth, wrapperRef, }: ShowArrowHookParams) => (index: number) => [boolean, boolean];
24
+ export type NonLoopEndFuncType = (
25
+ /** 切换方向 */
26
+ direction: 'prev' | 'next',
27
+ /** 当前索引 */
28
+ current: number,
29
+ /** 轮播图数量 */
30
+ total: number,
31
+ /** 非循环轮播结束时的偏移量 */
32
+ offset: number) => void;
33
+ type PlayControlHookParams = {
34
+ /** 轮播图数量 */
35
+ length: number;
36
+ /** 是否无缝轮播 */
37
+ loop: boolean;
38
+ /** 箭头类型 */
39
+ showArrow: ShowArrowType;
40
+ /** 轮播图宽度 */
41
+ cardWidth?: number;
42
+ /** 非循环轮播结束时的回调 */
43
+ onNonLoopEnd?: NonLoopEndFuncType;
44
+ /** 非循环轮播结束时的偏移量 */
45
+ offsetOnEnd?: number;
46
+ };
47
+ /**
48
+ * @author sonion
49
+ * @description 播放轮播图控制
50
+ * @param {PlayControlHookParams} params - hook参数
51
+ * @param {number} params.length - 轮播图数量
52
+ * @param {boolean} params.loop - 是否无缝轮播
53
+ * @param {ShowArrowType} params.showArrow - 箭头类型
54
+ * @param {number} params.cardWidth - 轮播图宽度
55
+ * @param {NonLoopEndFuncType} params.onNonLoopEnd - 非循环轮播结束回调
56
+ * @param {number} params.offsetOnEnd - 非循环轮播结束时的偏移量
57
+ */
58
+ export declare const usePlayControl: ({ length, loop, showArrow, cardWidth, onNonLoopEnd, offsetOnEnd, }: PlayControlHookParams) => readonly [(node: HTMLElement | null) => void, (direction?: "prev" | "next") => void, (index: number) => void, () => number, import('react').MutableRefObject<boolean>];
59
+ /**
60
+ * 子元素重渲染的依赖的类型
61
+ * length 依赖 children的数量
62
+ * child 依赖 children本身的变化
63
+ */
64
+ export type RerenderType = 'length' | 'child';
65
+ /**
66
+ * @author sonion
67
+ * @description 创建无缝轮播结构
68
+ * @param {ReactElement} children - 轮播列表
69
+ * @param {boolean} loop - 是否无缝轮播
70
+ * @param {RerenderType} rerender - 子元素重渲染的依赖类型
71
+ * @returns {ReactElement[]} - 无缝轮播结构
72
+ */
73
+ export declare const useLoopChildren: (children: ReactElement[], loop: boolean, rerender: RerenderType) => ReactElement<any, string | import('react').JSXElementConstructor<any>>[];
74
+ export {};
@@ -0,0 +1,88 @@
1
+ import { FC, CSSProperties, ReactElement } from 'react';
2
+ import { ShowArrowType, RerenderType, NonLoopEndFuncType } from './hooks';
3
+ type IndicatorType = 'line' | 'dot' | 'none';
4
+ export type CarouselProps = {
5
+ /** 单个轮播项的宽度 */
6
+ cardWidth?: number;
7
+ /** 单个轮播项的高度 */
8
+ cardHeight?: number;
9
+ /** 轮播容器的宽度 */
10
+ wrapperWidth?: number;
11
+ /** 轮播容器的高度 */
12
+ wrapperHeight?: number;
13
+ /** 轮播项之间的间隔 */
14
+ gapSize?: number;
15
+ /** 是否无缝轮播 */
16
+ loop?: boolean;
17
+ /** 切换时间(毫秒) */
18
+ duration?: number;
19
+ /** 是否自动播放 */
20
+ autoPlay?: boolean;
21
+ /** 箭头类型 */
22
+ showArrow?: ShowArrowType;
23
+ /** 指示器类型 */
24
+ indicatorType?: IndicatorType;
25
+ /** 主轮播类名,不包括指示器 */
26
+ className?: string;
27
+ /** 主轮播样式,不包括指示器 */
28
+ style?: CSSProperties;
29
+ /** 轮播项 */
30
+ children: ReactElement[];
31
+ /** 轮播项更新依赖方式 */
32
+ rerender?: RerenderType;
33
+ /** 非循环模式下,轮播结束回调 */
34
+ onNonLoopEnd?: NonLoopEndFuncType;
35
+ /** 非循环模式下,轮播结束时的偏移量。就是提前第几张就算结束。暂不支持延后。 */
36
+ offsetOnEnd?: number;
37
+ /** 自定义渲染箭头 */
38
+ arrows?: [
39
+ /** 自定义渲染上一个箭头 */
40
+ FC<{
41
+ onClick: () => void;
42
+ className?: string;
43
+ }>,
44
+ /** 自定义渲染下一个箭头 */
45
+ FC<{
46
+ onClick: () => void;
47
+ className?: string;
48
+ }>
49
+ ];
50
+ };
51
+ export type CarouselRef = {
52
+ /** 开始播放 */
53
+ run: () => void;
54
+ /** 停止播放 */
55
+ stop: () => void;
56
+ /** 切换到上一个或下一个 */
57
+ stepChange: (arg: 'prev' | 'next') => void;
58
+ /** 跳转到指定索引 */
59
+ jumpChange: (arg: number) => void;
60
+ /** 获取当前索引 */
61
+ getCurrentIndex: () => number;
62
+ };
63
+ /**
64
+ * @author sonion
65
+ * @description 轮播组件,用于展示多个轮播项
66
+ * @param {CarouselProps} props - 组件的属性
67
+ * @param {number} [props.cardWidth] - 单个轮播项的宽度
68
+ * @param {number} [props.cardHeight] - 单个轮播项的高度
69
+ * @param {number} [props.wrapperWidth] - 轮播容器的宽度
70
+ * @param {number} [props.wrapperHeight] - 轮播容器的高度
71
+ * @param {number} [props.gapSize] - 轮播项之间的间隔
72
+ * @param {boolean} [props.loop] - 是否无缝循环
73
+ * @param {number} [props.duration=6000] - 切换时间(毫秒)
74
+ * @param {boolean} [props.autoPlay=true] - 是否自动播放
75
+ * @param {ShowArrowType} [props.showArrow='always'] - 箭头类型
76
+ * @param {IndicatorType} [props.indicatorType='line'] - 指示器类型
77
+ * @param {string} [props.className] - 主轮播类名,不包括指示器
78
+ * @param {CSSProperties} [props.style] - 主轮播样式,不包括指示器
79
+ * @param {ReactElement[]} children - 轮播项
80
+ * @param {RerenderType} [props.rerender='length'] - 轮播项更新依赖方式
81
+ * @param {(direction: 'prev' | 'next', current: number, total: number, offset: number) => void} [props.onNonLoopEnd] - 非循环模式下,轮播结束回调。
82
+ * @param {number} [props.offsetOnEnd=0] - 非循环模式下,轮播结束时的偏移量。就是提前第几张就算结束。暂不支持延后。
83
+ * @param {[FC<{ onClick: () => void; className?: string }>, FC<{ onClick: () => void; className?: string }>]} [props.arrows] - 自定义渲染箭头
84
+ */
85
+ declare const Carousel: import('react').ForwardRefExoticComponent<CarouselProps & import('react').RefAttributes<CarouselRef>>;
86
+ type CarouselType = typeof Carousel;
87
+ export type { ShowArrowType, RerenderType, CarouselType };
88
+ export default Carousel;
@@ -0,0 +1,21 @@
1
+ import { FC, ReactNode, JSX, PropsWithChildren } from 'react';
2
+ export type CustomShowProps<T> = PropsWithChildren<{
3
+ /** 判断条件 */
4
+ when: T | null | undefined | false;
5
+ /** 不满足条件时的渲染内容 */
6
+ fallback?: ReactNode;
7
+ }>;
8
+ export interface CustomShowType<T> extends FC<CustomShowProps<T>> {
9
+ (props: CustomShowProps<T>): JSX.Element;
10
+ }
11
+ /**
12
+ * @author sonion
13
+ * @description 根据条件渲染内容,替代用三目运算和短路规则条件渲染
14
+ * @param {CustomShowProps<T>} props 组件属性
15
+ * @param {T | null | undefined | false} props.when 条件
16
+ * @param {ReactNode} props.fallback 不满足条件时的渲染内容
17
+ * @param {(value: T | null | undefined | false) => ReactNode} props.children 满足条件时的渲染内容
18
+ * @returns {JSX.Element} - 组件节点
19
+ */
20
+ declare function CustomShow<T>({ when, fallback, children, }: CustomShowProps<T>): JSX.Element;
21
+ export default CustomShow;
@@ -0,0 +1,31 @@
1
+ import { Component, ErrorInfo, ReactNode } from 'react';
2
+ export interface ErrorBoundaryProps {
3
+ /** 正常展示 */
4
+ children: ReactNode;
5
+ /** 错误发生时显示的回退内容 */
6
+ fallback: ReactNode;
7
+ /** 错误信息的提示文本 */
8
+ msg?: string;
9
+ }
10
+ interface State {
11
+ hasError: boolean;
12
+ }
13
+ /**
14
+ * @author sonion
15
+ * @description 错误边界组件,用于捕获子组件的错误并显示自定义的回退内容
16
+ * @param {ErrorBoundaryProps} props - 组件的属性
17
+ * @param {ReactNode} props.fallback - 错误发生时显示的回退内容
18
+ * @param {string} [props.msg='组件加载失败'] - 错误信息的提示文本
19
+ * @param {ReactNode} props.children - 子组件,可能会触发错误
20
+ * @returns {import('react').JSX.Element} - 组件节点
21
+ */
22
+ declare class ErrorBoundary extends Component<ErrorBoundaryProps, State> {
23
+ state: State;
24
+ private msg;
25
+ static getDerivedStateFromError(): State;
26
+ componentDidCatch(error: Error, errorInfo: ErrorInfo): void;
27
+ render(): ReactNode;
28
+ }
29
+ type ErrorBoundaryType = typeof ErrorBoundary;
30
+ export type { ErrorBoundaryType };
31
+ export default ErrorBoundary;
@@ -0,0 +1,8 @@
1
+ export * from './carousel';
2
+ export { default as Carousel } from './carousel';
3
+ export * from './custom-show';
4
+ export { default as CustomShow } from './custom-show';
5
+ export * from './async-custom-show';
6
+ export { default as AsyncCustomShow } from './async-custom-show';
7
+ export * from './error-boundary';
8
+ export { default as ErrorBoundary } from './error-boundary';
@@ -0,0 +1,9 @@
1
+ /**
2
+ * @author sonion
3
+ * @description 异步操作锁,防止重复调用。通过返回的 Promise 确定是否执行中,执行中不可重复触发。
4
+ * @param {(...args: T)=>Promise<R>} asyncAction - 异步方法,需返回Promise
5
+ * @param {(isPending: boolean, ...args: T) => void} [onPendingChange] - 状态变化回调
6
+ * @param {string} [msg] - 警告信息
7
+ * @returns {[boolean, (...args: T) => Promise<R | void>]} - 返回是否执行中,执行方法
8
+ */
9
+ export declare const useAsyncActionLock: <T extends unknown[], R>(asyncAction: (...args: T) => Promise<R>, onPendingChange?: (isPending: boolean, ...args: T) => void, msg?: string) => readonly [boolean, (...args: T) => Promise<R | void>];
@@ -0,0 +1,5 @@
1
+ export * from './state';
2
+ export * from './timer';
3
+ export * from './observer';
4
+ export * from './storage';
5
+ export * from './async-guard';
@@ -0,0 +1,70 @@
1
+ type MutationObserverCallback = (entry: MutationRecord[], observer: MutationObserver) => void;
2
+ /**
3
+ * @author sonion
4
+ * @description dom变化观察器hook
5
+ * @param {MutationObserverCallback} callback - 回调函数,参数为 MutationRecord[]
6
+ * @param {boolean} [once] - 是否只观察一次,默认false
7
+ */
8
+ export declare const useMutationObserver: (callback: MutationObserverCallback, once?: boolean) => {
9
+ /** 开始观察 因重新生成观察器observe不会更新,故不可以observe是否更新做依赖依据 */
10
+ observe: (el: Node | null, options?: MutationObserverInit) => void;
11
+ /** 获取所有未处理的观察记录 */
12
+ takeRecords: () => MutationRecord[] | undefined;
13
+ /** 取消所有观察,用observe重新启用 */
14
+ disconnect: () => void | undefined;
15
+ };
16
+ type IntersectionObserverCallback = (
17
+ /** 交叉目标 */
18
+ target: Element,
19
+ /** 交叉目标的根元素 */
20
+ root: Element | undefined,
21
+ /** 交叉观察器实例 */
22
+ observer: IntersectionObserver) => void;
23
+ type IntersectionObserverParams = {
24
+ callback: IntersectionObserverCallback;
25
+ rootMargin?: number;
26
+ threshold?: number;
27
+ once?: boolean;
28
+ };
29
+ /**
30
+ * @author sonion
31
+ * @description 视口交叉观察器hook
32
+ * @param {IntersectionObserverParams} params - 观察器初始化参数
33
+ * @param {IntersectionObserverCallback} params.callback - 加载回调。
34
+ * @param {number} [params.rootMargin] - 提前多少px触发
35
+ * @param {number} [params.threshold] - 被观察目标与观察区交叉多少触发,0-1
36
+ * @param {boolean} [params.once] - 是否只触发一次
37
+ */
38
+ export declare const useIntersectionObserver: ({ callback, rootMargin, threshold, once, }: IntersectionObserverParams) => {
39
+ rootRef: Element | undefined;
40
+ /** 设置观察区域 */
41
+ setRootRef: (node: Element | null) => void;
42
+ /** 开始观察 */
43
+ observe: (el: Element | null) => void;
44
+ /** 取消观察 */
45
+ unobserve: (el: Element | null) => void | null | undefined;
46
+ /** 取消所有观察,用observe重新启用 */
47
+ disconnect: () => void | undefined;
48
+ /** 获取 未触发回调前,所有未处理的观察记录,触发后清空 */
49
+ takeRecords: () => IntersectionObserverEntry[] | undefined;
50
+ };
51
+ type ResizeObserverCallback = (
52
+ /** 变化记录 */
53
+ entry: ResizeObserverEntry,
54
+ /** 观察器实例 */
55
+ observer: ResizeObserver) => void;
56
+ /**
57
+ * @author sonion
58
+ * @description 元素尺寸变化观察器hook
59
+ * @param {ResizeObserverCallback} callback - 回调函数,参数为ResizeObserverEntry
60
+ * @param {boolean} [once] - 是否只观察一次,默认false
61
+ */
62
+ export declare const useResizeObserver: (callback: ResizeObserverCallback, once?: boolean) => {
63
+ /** 开始观察 因重新生成观察器observe不会更新,故不可以observe是否更新做依赖依据 */
64
+ observe: (el: Element | null, options?: ResizeObserverOptions) => void;
65
+ /** 取消观察 */
66
+ unobserve: (el: Element | null) => void | null | undefined;
67
+ /** 取消所有观察,用observe重新启用 */
68
+ disconnect: () => void | undefined;
69
+ };
70
+ export {};
@@ -0,0 +1,48 @@
1
+ import { SetStateAction } from 'react';
2
+ /**
3
+ * @author sonion
4
+ * @description 创建静态的state, 不会触发组件重新渲染
5
+ * @param {T} initialValue - 初始值
6
+ */
7
+ export declare function useStaticState<T>(initialValue: T): [() => T, (t: T) => void, (t?: T) => T];
8
+ export declare function useStaticState<T>(initialValue?: undefined): [() => T | undefined, (t: T) => void, (t?: T) => T | undefined];
9
+ interface UseLatestCallbackType {
10
+ <T extends (...args: never[]) => unknown>(cb: T): T;
11
+ <T extends (...args: never[]) => unknown>(cb?: T | undefined): T | undefined;
12
+ }
13
+ /**
14
+ * @author sonion
15
+ * @description 创建最新的回调函数,不触发重新执行,同时避免闭包问题。
16
+ * 作用类似 React 19 的 useEffectEvent,但原理不同。
17
+ * @param {T} cb - 依赖函数、依赖函数数组、依赖函数对象
18
+ * @returns {T} - 返回稳定的函数引用,始终调用最新的 cb
19
+ */
20
+ export declare const useLatestCallback: UseLatestCallbackType;
21
+ /**
22
+ * @author sonion
23
+ * @description 创建相同值不触发组件重新渲染的state。和useCreateSafeRef类似,但useCreateSafeRef更专注于ref
24
+ * @param params - 参数对象
25
+ * @param {T} params.initialValue - 初始值
26
+ * @param {(val: T) => void} [params.onChange] - 变化回调
27
+ * @param {(prev: T, next: T) => boolean} [params.hasDiff] - 对比函数,返回true变更生效。默认对比引用是否不相同。
28
+ * @param {boolean} [params.onlyEvent] - 是否仅触发事件,不更新值,避免重渲染
29
+ */
30
+ export declare function useDistinctState<T>(params: {
31
+ initialValue: T | (() => T);
32
+ onChange?: (val: T) => void;
33
+ hasDiff?: (prev?: T, next?: T) => boolean;
34
+ onlyEvent: true;
35
+ }): [undefined, (val: SetStateAction<T>) => void, () => T];
36
+ export declare function useDistinctState<T>(params: {
37
+ initialValue: T | (() => T);
38
+ onChange?: (val: T) => void;
39
+ hasDiff?: (prev?: T, next?: T) => boolean;
40
+ onlyEvent?: false;
41
+ }): [T, (val: SetStateAction<T>) => void, () => T];
42
+ /**
43
+ * @author sonion
44
+ * @description 创建安全的Ref引用
45
+ * @param {(oldNode?: T, newNode?: T) => boolean} [hasDiff] - 对比函数,返回true变更生效。默认对比引用是否不相同。
46
+ */
47
+ export declare const useCreateSafeRef: <T extends object = HTMLElement>(hasDiff?: (oldNode?: T, newNode?: T) => boolean) => readonly [T | undefined, (node: T | null) => void, import('react').MutableRefObject<boolean>];
48
+ export {};
@@ -0,0 +1,25 @@
1
+ import { useDistinctState } from '../state';
2
+ type StorageParams<T> = Omit<Parameters<typeof useDistinctState<T>>[0], 'onlyEvent'> & {
3
+ /** 储存的key */
4
+ key: string;
5
+ /** 储存类型。 localStorage 或 sessionStorage */
6
+ storage?: typeof localStorage | typeof sessionStorage;
7
+ /** 初始化类型检查函数,检查不通过使用初始值。可避免类型不对引起的错误 */
8
+ checkType?: (val: T) => boolean;
9
+ /** tab关闭前的回调, 相同key的不同回调只有初始生效。 */
10
+ beforeunload?: () => void;
11
+ };
12
+ /**
13
+ * @author sonion
14
+ * @description 本地储存
15
+ * @param params - 参数对象
16
+ * @param params.key - 储存的key
17
+ * @param params.initialValue - 初始值
18
+ * @param [params.hasDiff] - 对比函数,默认对比引用是否不相同。
19
+ * @param params.onChange - 变化回调
20
+ * @param [params.storage] - 储存类型。 localStorage 或 sessionStorage
21
+ * @param [params.checkType] - 初始化类型检查函数,检查不通过使用初始值。可避免类型不对引起的错误
22
+ * @param [params.beforeunload] - tab关闭前的回调, 相同key的不同回调只有初始生效。
23
+ */
24
+ export declare const useStorage: <T>({ key, initialValue, hasDiff, onChange, storage, checkType, beforeunload, }: StorageParams<T>) => readonly [T, (value: T | ((val: T) => T)) => void];
25
+ export {};
@@ -0,0 +1,16 @@
1
+ /**
2
+ * @author sonion
3
+ * @description 自管理定时器的interval
4
+ * @param {()=>void} cb - 回调函数
5
+ * @param {number} duration - 时间间隔
6
+ * @returns {[() => void, () => void]} - [启动函数, 清除函数]
7
+ */
8
+ export declare const useInterval: (cb: () => void, duration: number) => readonly [() => void, () => void];
9
+ /**
10
+ * @author sonion
11
+ * @description 自管理定时器的rAfInterval
12
+ * @param {()=>void} cb - 回调函数
13
+ * @param {number} duration - 时间间隔
14
+ * @returns {[() => void, () => void]} - [启动函数, 清除函数]
15
+ */
16
+ export declare const useRAfInterval: (cb: () => void, duration: number) => readonly [() => void, () => void];
@@ -0,0 +1,2 @@
1
+ export * from './components';
2
+ export * from './hooks';
package/package.json ADDED
@@ -0,0 +1,73 @@
1
+ {
2
+ "name": "@tonar/react-kit",
3
+ "version": "0.0.1-canary",
4
+ "private": false,
5
+ "description": "@tonar/react-kit: React 18 components and hooks for carousels, conditional rendering, error boundaries, state helpers, observers, storage, timers, and async action locking.",
6
+ "keywords": [
7
+ "components",
8
+ "hooks",
9
+ "react"
10
+ ],
11
+ "bugs": "https://github.com/sonion028/gonar/issues",
12
+ "license": "MIT",
13
+ "author": "sonion",
14
+ "repository": {
15
+ "type": "git",
16
+ "url": "https://github.com/sonion028/gonar"
17
+ },
18
+ "files": [
19
+ "dist",
20
+ "package.json",
21
+ "README.md",
22
+ "LICENSE"
23
+ ],
24
+ "type": "module",
25
+ "sideEffects": [
26
+ "**/*.css"
27
+ ],
28
+ "module": "dist/index.esm.js",
29
+ "types": "dist/types/index.d.ts",
30
+ "exports": {
31
+ ".": {
32
+ "import": "./dist/index.esm.js",
33
+ "types": "./dist/types/index.d.ts"
34
+ },
35
+ "./hooks": {
36
+ "import": "./dist/hooks.esm.js",
37
+ "types": "./dist/types/hooks.d.ts"
38
+ },
39
+ "./components": {
40
+ "import": "./dist/components.esm.js",
41
+ "types": "./dist/types/components.d.ts"
42
+ }
43
+ },
44
+ "dependencies": {
45
+ "@tonar/utils": "0.0.1-canary"
46
+ },
47
+ "devDependencies": {
48
+ "@testing-library/react": "^16.3.2",
49
+ "@types/react": "^18.3.31",
50
+ "@types/react-dom": "^18.3.7",
51
+ "@vitejs/plugin-react": "^6.0.2",
52
+ "jsdom": "^29.1.1",
53
+ "react": "^18.3.1",
54
+ "react-dom": "^18.3.1",
55
+ "sass-embedded": "^1.100.0",
56
+ "vite-plugin-lib-inject-css": "^2.2.2",
57
+ "vitest": "^4.1.8"
58
+ },
59
+ "peerDependencies": {
60
+ "react": "^18.0.0",
61
+ "react-dom": "^18.0.0"
62
+ },
63
+ "devEngines": {
64
+ "packageManager": {
65
+ "name": "pnpm",
66
+ "onFail": "error"
67
+ }
68
+ },
69
+ "scripts": {
70
+ "build": "rimraf dist && vite build",
71
+ "test": "vitest --run"
72
+ }
73
+ }