@tonar/react-kit 0.1.0-beta.2 → 0.2.7

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.
@@ -0,0 +1,3 @@
1
+ import { i as Carousel, n as AsyncCustomShow, r as CustomShow, t as ErrorBoundary } from "./js/components.whU5kkGn.js";
2
+
3
+ export { AsyncCustomShow, Carousel, CustomShow, ErrorBoundary };
@@ -0,0 +1,139 @@
1
+ .carousel__5vdU-W {
2
+ width: 100%;
3
+ height: 100%;
4
+ position: relative;
5
+ overflow: hidden;
6
+ }
7
+
8
+ .carousel__5vdU-W[style*="--wrapperWidth"] {
9
+ width: calc(var(--wrapperWidth) * 1px);
10
+ }
11
+
12
+ .carousel__5vdU-W[style*="--wrapperHeight"] {
13
+ height: calc(var(--wrapperHeight) * 1px);
14
+ }
15
+
16
+ .carousel__5vdU-W:not([style*="--cardHeight"]) .wrapper__5vdU-W .inner__5vdU-W {
17
+ height: 100%;
18
+ }
19
+
20
+ .carousel__5vdU-W[style*="--cardWidth"] .wrapper__5vdU-W {
21
+ width: calc(var(--cardWidth) * 1px);
22
+ }
23
+
24
+ .carousel__5vdU-W[style*="--cardWidth"] .wrapper__5vdU-W .inner__5vdU-W {
25
+ transform: translateX(calc(var(--index) * (var(--cardWidth) + var(--gapSize, 0)) * -1px));
26
+ }
27
+
28
+ .carousel__5vdU-W[style*="--cardWidth"] .wrapper__5vdU-W .inner__5vdU-W > * {
29
+ flex: 0 0 calc(var(--cardWidth) * 1px);
30
+ height: 100%;
31
+ }
32
+
33
+ .carousel__5vdU-W:not([style*="--cardWidth"]) .wrapper__5vdU-W {
34
+ width: 100%;
35
+ }
36
+
37
+ .carousel__5vdU-W:not([style*="--cardWidth"]) .wrapper__5vdU-W .inner__5vdU-W {
38
+ transform: translateX(calc((-100% + var(--gapSize, 0) * -1px) * var(--index)));
39
+ }
40
+
41
+ .carousel__5vdU-W:not([style*="--cardWidth"]) .wrapper__5vdU-W .inner__5vdU-W > * {
42
+ flex: 0 0 100%;
43
+ height: 100%;
44
+ }
45
+
46
+ .carousel__5vdU-W:hover > .arrow__5vdU-W.hover {
47
+ display: block;
48
+ }
49
+
50
+ .carousel__5vdU-W > .arrow__5vdU-W.hover {
51
+ display: none;
52
+ }
53
+
54
+ .carousel__5vdU-W > .arrow__5vdU-W.none {
55
+ display: none;
56
+ }
57
+
58
+ .carousel__5vdU-W > .arrow__5vdU-W.always, .carousel__5vdU-W > .arrow__5vdU-W.auto {
59
+ display: block;
60
+ }
61
+
62
+ .carousel__5vdU-W > .arrow__5vdU-W .left__5vdU-W, .carousel__5vdU-W > .arrow__5vdU-W .right__5vdU-W {
63
+ z-index: 9;
64
+ cursor: pointer;
65
+ background: #fff url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMjEiIGhlaWdodD0iMjAiIHZpZXdCb3g9IjAgMCAyMSAyMCIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPGcgaWQ9ImRvd24iPgo8cGF0aCBpZD0iVW5pb24iIGZpbGwtcnVsZT0iZXZlbm9kZCIgY2xpcC1ydWxlPSJldmVub2RkIiBkPSJNNi43OTE4MiA1Ljc2ODY1QzYuNDAyNzMgNS4zNzk1NiA2LjQwMjczIDQuNzQ4NzEgNi43OTE4MiA0LjM1OTYyTDcuNDk2MzQgMy42NTUxQzcuODg1NDMgMy4yNjYwMSA4LjUxNjI4IDMuMjY2MDEgOC45MDUzNyAzLjY1NTFMMTQuNTQxNSA5LjI5MTI0QzE0LjczNzEgOS40ODY4MyAxNC44MzQ0IDkuNzQzNSAxNC44MzMzIDkuOTk5ODVDMTQuODM0NCAxMC4yNTYyIDE0LjczNzEgMTAuNTEyOSAxNC41NDE1IDEwLjcwODVMOC45MDUzNyAxNi4zNDQ2QzguNTE2MjggMTYuNzMzNyA3Ljg4NTQzIDE2LjczMzcgNy40OTYzNCAxNi4zNDQ2TDYuNzkxODIgMTUuNjQwMUM2LjQwMjczIDE1LjI1MSA2LjQwMjczIDE0LjYyMDEgNi43OTE4MiAxNC4yMzExTDExLjAyMyA5Ljk5OTg1TDYuNzkxODIgNS43Njg2NVoiIGZpbGw9IiMwMDY2RkMiLz4KPC9nPgo8L3N2Zz4K") center / contain no-repeat content-box border-box;
66
+ border: 1px solid #dde2e9;
67
+ border-radius: 50%;
68
+ width: 20px;
69
+ height: 20px;
70
+ padding: 14px;
71
+ display: none;
72
+ position: absolute;
73
+ top: 50%;
74
+ transform: translateY(-50%);
75
+ box-shadow: 0 15px 35px -2px #0000000d, 0 5px 15px #0000000d;
76
+ }
77
+
78
+ .carousel__5vdU-W > .arrow__5vdU-W > .show {
79
+ display: block;
80
+ }
81
+
82
+ .carousel__5vdU-W > .arrow__5vdU-W .left__5vdU-W {
83
+ left: 12px;
84
+ transform: translateY(-50%) rotate(180deg);
85
+ }
86
+
87
+ .carousel__5vdU-W > .arrow__5vdU-W .right__5vdU-W {
88
+ right: 12px;
89
+ }
90
+
91
+ .carousel__5vdU-W .wrapper__5vdU-W {
92
+ height: 100%;
93
+ }
94
+
95
+ .carousel__5vdU-W .wrapper__5vdU-W .inner__5vdU-W {
96
+ gap: calc(var(--gapSize) * 1px);
97
+ height: calc(var(--cardHeight) * 1px);
98
+ transition: transform .3s;
99
+ display: flex;
100
+ }
101
+
102
+ .indicator__5vdU-W {
103
+ z-index: 9;
104
+ border-radius: 8px;
105
+ gap: 8px;
106
+ display: flex;
107
+ position: absolute;
108
+ bottom: -17px;
109
+ left: 50%;
110
+ transform: translateX(-50%);
111
+ }
112
+
113
+ .indicator__5vdU-W.none {
114
+ display: none;
115
+ }
116
+
117
+ .indicator__5vdU-W.line > i {
118
+ background-color: var(--Gray-3, #e5e8ef);
119
+ cursor: pointer;
120
+ border-radius: 8px;
121
+ width: 40px;
122
+ height: 5px;
123
+ }
124
+
125
+ .indicator__5vdU-W.line > i.active {
126
+ background: var(--byte-plus-blue-brand-primary-60, #0066fc);
127
+ }
128
+
129
+ .indicator__5vdU-W.dot > i {
130
+ background-color: var(--Gray-3, #e5e8ef);
131
+ cursor: pointer;
132
+ border-radius: 50%;
133
+ width: 6px;
134
+ height: 6px;
135
+ }
136
+
137
+ .indicator__5vdU-W.dot > i.active {
138
+ background: var(--byte-plus-blue-brand-primary-60, #0066fc);
139
+ }
@@ -0,0 +1,369 @@
1
+ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
2
+ import { clearRAfInterval, rAfInterval } from "@tonar/utils";
3
+
4
+ //#region src/hooks/state/index.ts
5
+ function useStaticState(initialValue) {
6
+ const ref = useRef(initialValue);
7
+ return [
8
+ useCallback(() => ref.current, []),
9
+ useCallback((t) => ref.current = t, []),
10
+ useCallback((t) => t === void 0 ? ref.current : ref.current = t, [])
11
+ ];
12
+ }
13
+ /**
14
+ * @author sonion
15
+ * @description 创建最新的回调函数,不触发重新执行,同时避免闭包问题。
16
+ * 作用类似 React 19 的 useEffectEvent,但原理不同。
17
+ * @param {T} cb - 依赖函数、依赖函数数组、依赖函数对象
18
+ * @returns {T} - 返回稳定的函数引用,始终调用最新的 cb
19
+ */
20
+ const useLatestCallback = (cb) => {
21
+ const ref = useRef(cb);
22
+ ref.current !== cb && (ref.current = cb);
23
+ return useCallback((...args) => ref.current?.(...args), []);
24
+ };
25
+ function useDistinctState({ initialValue, onChange, hasDiff = (prev, next) => prev !== next, onlyEvent }) {
26
+ const prevRef = useRef(void 0);
27
+ const initial = () => prevRef.current = typeof initialValue === "function" ? initialValue() : initialValue;
28
+ const [value, setValue] = useState(initial);
29
+ const latestOnChange = useLatestCallback(onChange);
30
+ const setValueDistinct = useCallback((val) => {
31
+ const value = typeof val === "function" ? val(prevRef.current) : val;
32
+ if ((hasDiff ?? ((prev, next) => prev !== next))(prevRef.current, value)) {
33
+ latestOnChange?.(value);
34
+ prevRef.current = value;
35
+ onlyEvent || setValue(value);
36
+ }
37
+ }, [
38
+ latestOnChange,
39
+ onlyEvent,
40
+ setValue,
41
+ !!hasDiff
42
+ ]);
43
+ return [
44
+ onlyEvent ? void 0 : value,
45
+ setValueDistinct,
46
+ useCallback(() => prevRef.current, [])
47
+ ];
48
+ }
49
+ /**
50
+ * @author sonion
51
+ * @description 创建安全的Ref引用
52
+ * @param {(oldNode?: T, newNode?: T) => boolean} [hasDiff] - 对比函数,返回true变更生效。默认对比引用是否不相同。
53
+ */
54
+ const useCreateSafeRef = (hasDiff) => {
55
+ const [el, setEl] = useState();
56
+ const isReadyRef = useRef(false);
57
+ return [
58
+ el,
59
+ useCallback((node) => {
60
+ if (node && (hasDiff ?? ((oldNode, newNode) => oldNode !== newNode))(el, node)) {
61
+ isReadyRef.current = true;
62
+ setEl(node);
63
+ }
64
+ }, [el, !!hasDiff]),
65
+ isReadyRef
66
+ ];
67
+ };
68
+
69
+ //#endregion
70
+ //#region src/hooks/timer/index.ts
71
+ /**
72
+ * @author sonion
73
+ * @description 自管理定时器的interval
74
+ * @param {()=>void} cb - 回调函数
75
+ * @param {number} duration - 时间间隔
76
+ * @returns {[() => void, () => void]} - [启动函数, 清除函数]
77
+ */
78
+ const useInterval = (cb, duration) => {
79
+ const [, , withTimer] = useStaticState(void 0);
80
+ const latestCallback = useLatestCallback(cb);
81
+ const run = useCallback(() => {
82
+ clearTimeout(withTimer());
83
+ withTimer(setTimeout(() => {
84
+ try {
85
+ latestCallback?.();
86
+ } catch (err) {
87
+ console.error("useInterval error", err);
88
+ }
89
+ run?.();
90
+ }, duration));
91
+ }, [
92
+ duration,
93
+ latestCallback,
94
+ withTimer
95
+ ]);
96
+ return [run, useCallback(() => clearTimeout(withTimer()), [withTimer])];
97
+ };
98
+ /**
99
+ * @author sonion
100
+ * @description 自管理定时器的rAfInterval
101
+ * @param {()=>void} cb - 回调函数
102
+ * @param {number} duration - 时间间隔
103
+ * @returns {[() => void, () => void]} - [启动函数, 清除函数]
104
+ */
105
+ const useRAfInterval = (cb, duration) => {
106
+ const [, , withTimer] = useStaticState(void 0);
107
+ return [useCallback(() => {
108
+ clearRAfInterval(withTimer());
109
+ withTimer(rAfInterval(cb, duration));
110
+ }, [
111
+ cb,
112
+ duration,
113
+ withTimer
114
+ ]), useCallback(() => clearRAfInterval(withTimer()), [withTimer])];
115
+ };
116
+
117
+ //#endregion
118
+ //#region src/hooks/observer/index.ts
119
+ /**
120
+ * @author sonion
121
+ * @description dom变化观察器hook
122
+ * @param {MutationObserverCallback} callback - 回调函数,参数为 MutationRecord[]
123
+ * @param {boolean} [once] - 是否只观察一次,默认false
124
+ */
125
+ const useMutationObserver = (callback, once = false) => {
126
+ const observerRef = useRef();
127
+ const latestCallback = useLatestCallback(callback);
128
+ useEffect(() => () => {
129
+ observerRef.current?.disconnect?.();
130
+ observerRef.current = void 0;
131
+ }, []);
132
+ return {
133
+ /** 开始观察 因重新生成观察器observe不会更新,故不可以observe是否更新做依赖依据 */
134
+ observe: useCallback((el, options) => {
135
+ if (!el) return;
136
+ observerRef.current ?? (observerRef.current = new MutationObserver((mutations, observer) => {
137
+ latestCallback?.(mutations, observer);
138
+ once && observer.disconnect();
139
+ }));
140
+ observerRef.current?.observe?.(el, options);
141
+ }, [once, latestCallback]),
142
+ /** 获取所有未处理的观察记录 */
143
+ takeRecords: useCallback(() => observerRef.current?.takeRecords?.(), []),
144
+ /** 取消所有观察,用observe重新启用 */
145
+ disconnect: useCallback(() => observerRef.current?.disconnect?.(), [])
146
+ };
147
+ };
148
+ /**
149
+ * @author sonion
150
+ * @description 视口交叉观察器hook
151
+ * @param {IntersectionObserverParams} params - 观察器初始化参数
152
+ * @param {IntersectionObserverCallback} params.callback - 加载回调。
153
+ * @param {number} [params.rootMargin] - 提前多少px触发
154
+ * @param {number} [params.threshold] - 被观察目标与观察区交叉多少触发,0-1
155
+ * @param {boolean} [params.once] - 是否只触发一次
156
+ */
157
+ const useIntersectionObserver = ({ callback, rootMargin = 100, threshold = 0, once = false }) => {
158
+ const observerRef = useRef();
159
+ const [rootRef, setRootRef] = useCreateSafeRef();
160
+ const latestCallback = useLatestCallback(callback);
161
+ const options = useMemo(() => ({
162
+ root: rootRef,
163
+ rootMargin: `${rootMargin}px`,
164
+ threshold
165
+ }), [
166
+ rootRef,
167
+ rootMargin,
168
+ threshold
169
+ ]);
170
+ const [, , withPrevOptions] = useStaticState(options);
171
+ useEffect(() => () => {
172
+ observerRef.current?.disconnect?.();
173
+ observerRef.current = void 0;
174
+ }, [options]);
175
+ const observe = useCallback((el) => {
176
+ if (!el) return;
177
+ if (withPrevOptions() !== options) {
178
+ observerRef.current?.disconnect?.();
179
+ observerRef.current = void 0;
180
+ withPrevOptions(options);
181
+ }
182
+ observerRef.current ?? (observerRef.current = new IntersectionObserver((entries, observer) => {
183
+ entries.forEach((entry) => {
184
+ if (entry.isIntersecting) {
185
+ latestCallback?.(entry.target, rootRef, observer);
186
+ once && observer.unobserve?.(entry.target);
187
+ }
188
+ });
189
+ }, options));
190
+ observerRef.current?.unobserve?.(el);
191
+ observerRef.current?.observe?.(el);
192
+ }, [
193
+ options,
194
+ once,
195
+ latestCallback,
196
+ withPrevOptions
197
+ ]);
198
+ const unobserve = useCallback((el) => el && observerRef.current?.unobserve?.(el), []);
199
+ const takeRecords = useCallback(() => observerRef.current?.takeRecords?.(), []);
200
+ return {
201
+ rootRef,
202
+ /** 设置观察区域 */
203
+ setRootRef,
204
+ /** 开始观察 */
205
+ observe,
206
+ /** 取消观察 */
207
+ unobserve,
208
+ /** 取消所有观察,用observe重新启用 */
209
+ disconnect: useCallback(() => observerRef.current?.disconnect?.(), []),
210
+ /** 获取 未触发回调前,所有未处理的观察记录,触发后清空 */
211
+ takeRecords
212
+ };
213
+ };
214
+ /**
215
+ * @author sonion
216
+ * @description 元素尺寸变化观察器hook
217
+ * @param {ResizeObserverCallback} callback - 回调函数,参数为ResizeObserverEntry
218
+ * @param {boolean} [once] - 是否只观察一次,默认false
219
+ */
220
+ const useResizeObserver = (callback, once = false) => {
221
+ const observerRef = useRef();
222
+ const latestCallback = useLatestCallback(callback);
223
+ useEffect(() => () => {
224
+ observerRef.current?.disconnect?.();
225
+ observerRef.current = void 0;
226
+ }, []);
227
+ return {
228
+ /** 开始观察 因重新生成观察器observe不会更新,故不可以observe是否更新做依赖依据 */
229
+ observe: useCallback((el, options) => {
230
+ if (!el) return;
231
+ observerRef.current ?? (observerRef.current = new ResizeObserver((entries, observer) => {
232
+ entries.forEach((entry) => {
233
+ latestCallback?.(entry, observer);
234
+ });
235
+ once && observer.disconnect();
236
+ }));
237
+ observerRef.current?.unobserve?.(el);
238
+ observerRef.current?.observe?.(el, options);
239
+ }, [once, latestCallback]),
240
+ /** 取消观察 */
241
+ unobserve: useCallback((el) => el && observerRef.current?.unobserve?.(el), []),
242
+ /** 取消所有观察,用observe重新启用 */
243
+ disconnect: useCallback(() => observerRef.current?.disconnect?.(), [])
244
+ };
245
+ };
246
+
247
+ //#endregion
248
+ //#region src/hooks/storage/index.ts
249
+ /**
250
+ * @author sonion
251
+ * @description 本地储存
252
+ * @param params - 参数对象
253
+ * @param params.key - 储存的key
254
+ * @param params.defaultValue - 默认值
255
+ * @param [params.hasDiff] - 对比函数,默认对比引用是否不相同。
256
+ * @param params.onChange - 变化回调
257
+ * @param [params.storage] - 储存类型。 localStorage 或 sessionStorage
258
+ * @param [params.checkType] - 初始化类型检查函数,检查不通过使用初始值。可避免类型不对引起的错误
259
+ * @param [params.beforeunload] - tab关闭前的回调。
260
+ */
261
+ const useStorage = ({ key, defaultValue, hasDiff, onChange, storage = localStorage, checkType = () => true, beforeunload }) => {
262
+ const normalizedValue = useLatestCallback((val) => {
263
+ try {
264
+ const saved = val ? JSON.parse(val) : defaultValue;
265
+ return checkType(saved) ? saved : defaultValue;
266
+ } catch (err) {
267
+ console.warn("规范化出错,已使用默认值", err);
268
+ return defaultValue;
269
+ }
270
+ });
271
+ const [storedValue, setStoredValue] = useDistinctState({
272
+ initialValue: () => normalizedValue(storage.getItem(key) ?? ""),
273
+ hasDiff,
274
+ onChange
275
+ });
276
+ const selfDispatchedEventsRef = useRef(/* @__PURE__ */ new WeakSet());
277
+ const setValue = useCallback((value) => {
278
+ try {
279
+ setStoredValue((old) => {
280
+ const valueToStore = value instanceof Function ? value(old) : value;
281
+ const newValue = JSON.stringify(valueToStore);
282
+ storage.setItem(key, newValue);
283
+ const event = new StorageEvent("storage", {
284
+ key,
285
+ newValue,
286
+ storageArea: storage
287
+ });
288
+ selfDispatchedEventsRef.current.add(event);
289
+ window.dispatchEvent(event);
290
+ return valueToStore;
291
+ });
292
+ } catch (error) {
293
+ console.error("持久化储存错误", error);
294
+ }
295
+ }, [
296
+ key,
297
+ storage,
298
+ setStoredValue
299
+ ]);
300
+ const handleStorageChange = useLatestCallback((event) => {
301
+ if (selfDispatchedEventsRef.current.has(event) || event.storageArea !== storage || event.key !== key) return;
302
+ try {
303
+ const newValue = normalizedValue(event.newValue ?? "");
304
+ setStoredValue(newValue);
305
+ } catch (error) {
306
+ console.error("storage事件处理出错", error);
307
+ }
308
+ });
309
+ useEffect(() => {
310
+ window.addEventListener("storage", handleStorageChange);
311
+ return () => window.removeEventListener("storage", handleStorageChange);
312
+ }, [handleStorageChange]);
313
+ const handleBeforeunload = useLatestCallback(() => beforeunload?.(key, storedValue, storage));
314
+ useEffect(() => {
315
+ beforeunload && window.addEventListener("beforeunload", handleBeforeunload);
316
+ }, []);
317
+ return [
318
+ storedValue,
319
+ setValue,
320
+ () => window.removeEventListener("storage", handleStorageChange),
321
+ () => beforeunload && window.removeEventListener("beforeunload", handleBeforeunload)
322
+ ];
323
+ };
324
+
325
+ //#endregion
326
+ //#region src/hooks/async-guard/index.ts
327
+ /**
328
+ * @author sonion
329
+ * @description 异步操作锁,防止重复调用。通过返回的 Promise 确定是否执行中,执行中不可重复触发。
330
+ * @param {(...args: T)=>Promise<R>} asyncAction - 异步方法,需返回Promise
331
+ * @param {(isPending: boolean, ...args: T) => void} [onPendingChange] - 状态变化回调
332
+ * @param {string} [msg] - 警告信息
333
+ * @returns {[boolean, (...args: T) => Promise<R | void>]} - 返回是否执行中,执行方法
334
+ */
335
+ const useAsyncActionLock = (asyncAction, onPendingChange, msg) => {
336
+ const [isPending, setIsPending] = useState(false);
337
+ const [, , withSyncPending] = useStaticState(isPending);
338
+ const latestOnPendingChange = useLatestCallback(onPendingChange);
339
+ const setPending = useCallback((val, ...args) => {
340
+ withSyncPending(val);
341
+ setIsPending(val);
342
+ latestOnPendingChange?.(val, ...args);
343
+ }, [latestOnPendingChange, withSyncPending]);
344
+ const latestAsyncAction = useLatestCallback(asyncAction);
345
+ return [isPending, useCallback((...args) => {
346
+ if (withSyncPending()) {
347
+ console.log(msg || "正在提交中,请稍后再试");
348
+ return Promise.resolve();
349
+ }
350
+ setPending(true, ...args);
351
+ return new Promise((resolve, reject) => {
352
+ try {
353
+ resolve(latestAsyncAction?.(...args));
354
+ } catch (err) {
355
+ reject(err);
356
+ }
357
+ }).finally(() => {
358
+ setPending(false, ...args);
359
+ });
360
+ }, [
361
+ latestAsyncAction,
362
+ msg,
363
+ setPending,
364
+ withSyncPending
365
+ ])];
366
+ };
367
+
368
+ //#endregion
369
+ export { useAsyncActionLock, useCreateSafeRef, useDistinctState, useIntersectionObserver, useInterval, useLatestCallback, useMutationObserver, useRAfInterval, useResizeObserver, useStaticState, useStorage };
@@ -0,0 +1,4 @@
1
+ import { useAsyncActionLock, useCreateSafeRef, useDistinctState, useIntersectionObserver, useInterval, useLatestCallback, useMutationObserver, useRAfInterval, useResizeObserver, useStaticState, useStorage } from "./hooks.es.js";
2
+ import { i as Carousel, n as AsyncCustomShow, r as CustomShow, t as ErrorBoundary } from "./js/components.whU5kkGn.js";
3
+
4
+ export { AsyncCustomShow, Carousel, CustomShow, ErrorBoundary, useAsyncActionLock, useCreateSafeRef, useDistinctState, useIntersectionObserver, useInterval, useLatestCallback, useMutationObserver, useRAfInterval, useResizeObserver, useStaticState, useStorage };