@yh-ui/hooks 0.1.17 → 0.1.21

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/dist/index.mjs CHANGED
@@ -1,1427 +1,15 @@
1
- import { inject, ref, unref, computed, watch, useId as useId$1, shallowRef, onMounted, onBeforeUnmount, isRef, onUnmounted } from 'vue';
2
- import { zhCn } from '@yh-ui/locale';
3
- import * as _dayjs from 'dayjs';
4
- import 'dayjs/locale/en';
5
-
6
- const defaultNamespace = "yh";
7
- const statePrefix = "is-";
8
- const namespaceContextKey = Symbol("namespaceContextKey");
9
- const useGlobalNamespace = () => {
10
- return inject(namespaceContextKey, ref(defaultNamespace));
11
- };
12
- const useNamespace = (block) => {
13
- const namespace = useGlobalNamespace();
14
- const b = (blockSuffix = "") => {
15
- const ns = unref(namespace);
16
- return blockSuffix ? `${ns}-${block}-${blockSuffix}` : `${ns}-${block}`;
17
- };
18
- const e = (element) => {
19
- return element ? `${b()}__${element}` : "";
20
- };
21
- const m = (modifier) => {
22
- return modifier ? `${b()}--${modifier}` : "";
23
- };
24
- const bem = (blockSuffix, element, modifier) => {
25
- let cls = b(blockSuffix);
26
- if (element) cls += `__${element}`;
27
- if (modifier) cls += `--${modifier}`;
28
- return cls;
29
- };
30
- const em = (element, modifier) => {
31
- return element && modifier ? `${b()}__${element}--${modifier}` : "";
32
- };
33
- function is(state, value) {
34
- if (arguments.length === 1) {
35
- return `${statePrefix}${state}`;
36
- }
37
- return value ? `${statePrefix}${state}` : "";
38
- }
39
- const cssVar = (name) => {
40
- return `--${unref(namespace)}-${block}-${name}`;
41
- };
42
- const cssVarObj = (vars) => {
43
- const obj = {};
44
- Object.entries(vars).forEach(([key, value]) => {
45
- obj[cssVar(key)] = value;
46
- });
47
- return obj;
48
- };
49
- const cssVarBlock = (name) => {
50
- return `--${unref(namespace)}-${name}`;
51
- };
52
- const cssVarBlockObj = (vars) => {
53
- const obj = {};
54
- Object.entries(vars).forEach(([key, value]) => {
55
- obj[cssVarBlock(key)] = value;
56
- });
57
- return obj;
58
- };
59
- return {
60
- namespace,
61
- b,
62
- e,
63
- m,
64
- bem,
65
- em,
66
- is,
67
- cssVar,
68
- cssVarObj,
69
- cssVarBlock,
70
- cssVarBlockObj
71
- };
72
- };
73
-
74
- const defaultInitialZIndex = 2e3;
75
- const zIndexContextKey = Symbol("zIndexContextKey");
76
- const zIndexCounterKey = Symbol("zIndexCounterKey");
77
- const getNextZIndex = () => {
78
- if (typeof window !== "undefined") {
79
- const windowContext = window;
80
- if (windowContext.__YH_Z_INDEX__ === void 0) {
81
- windowContext.__YH_Z_INDEX__ = defaultInitialZIndex;
82
- }
83
- return ++windowContext.__YH_Z_INDEX__;
84
- }
85
- return defaultInitialZIndex;
86
- };
87
- const resetZIndex = (value = defaultInitialZIndex) => {
88
- if (typeof window !== "undefined") {
89
- window.__YH_Z_INDEX__ = value;
90
- }
91
- };
92
- const createZIndexCounter = (initialValue = defaultInitialZIndex) => {
93
- return { current: initialValue };
94
- };
95
- const useZIndex = (zIndexOverrides) => {
96
- const injectedZIndex = inject(zIndexContextKey, void 0);
97
- const appCounter = inject(zIndexCounterKey, null);
98
- const initialZIndex = computed(() => {
99
- const override = unref(zIndexOverrides);
100
- return override ?? unref(injectedZIndex) ?? defaultInitialZIndex;
101
- });
102
- const currentZIndex = computed(() => initialZIndex.value);
103
- const nextZIndex = () => {
104
- const override = unref(zIndexOverrides);
105
- if (override !== void 0) return override;
106
- if (appCounter) {
107
- return ++appCounter.current;
108
- }
109
- return getNextZIndex();
110
- };
111
- return {
112
- initialZIndex,
113
- currentZIndex,
114
- nextZIndex
115
- };
116
- };
117
-
118
- const configProviderContextKey = Symbol(
119
- "configProviderContextKey"
120
- );
121
- const useConfig = () => {
122
- const configRef = inject(configProviderContextKey, null);
123
- const globalSize = computed(() => {
124
- const config = unref(configRef);
125
- return config?.size || "default";
126
- });
127
- const globalZIndex = computed(() => {
128
- const config = unref(configRef);
129
- return config?.zIndex || 2e3;
130
- });
131
- const globalLocale = computed(() => {
132
- const config = unref(configRef);
133
- return config?.locale;
134
- });
135
- return {
136
- config: configRef,
137
- globalSize,
138
- globalZIndex,
139
- globalLocale
140
- };
141
- };
142
-
143
- const dayjs = _dayjs.default || _dayjs;
144
- const dayjsLocales = import.meta.glob(
145
- ["../../../../node_modules/dayjs/locale/*.js", "!../../../../node_modules/dayjs/locale/en.js"],
146
- { eager: false }
147
- );
148
- const loadedLocales = /* @__PURE__ */ new Set(["en"]);
149
- const localeMapping = {
150
- "zh-cn": "zh-cn",
151
- "zh-tw": "zh-tw",
152
- "zh-hk": "zh-hk",
153
- "zh-mo": "zh-tw",
154
- en: "en",
155
- ja: "ja",
156
- ko: "ko",
157
- de: "de",
158
- fr: "fr",
159
- es: "es",
160
- pt: "pt",
161
- "pt-br": "pt-br",
162
- ru: "ru",
163
- ar: "ar",
164
- "ar-eg": "ar",
165
- tr: "tr",
166
- it: "it",
167
- nl: "nl",
168
- pl: "pl",
169
- th: "th",
170
- vi: "vi",
171
- id: "id",
172
- ms: "ms",
173
- da: "da",
174
- sv: "sv",
175
- fi: "fi",
176
- no: "nb",
177
- "nb-NO": "nb",
178
- cs: "cs",
179
- sk: "sk",
180
- uk: "uk",
181
- hu: "hu",
182
- ro: "ro",
183
- bg: "bg",
184
- az: "az",
185
- fa: "fa",
186
- hi: "hi",
187
- pa: "pa-in",
188
- el: "el",
189
- ca: "ca",
190
- tk: "tk",
191
- ta: "ta",
192
- lv: "lv",
193
- af: "af",
194
- et: "et",
195
- sl: "sl",
196
- he: "he",
197
- lo: "lo",
198
- lt: "lt",
199
- mn: "mn",
200
- kk: "kk",
201
- ku: "ku",
202
- ckb: "ku",
203
- "ug-cn": "ug-cn",
204
- km: "km",
205
- sr: "sr",
206
- eu: "eu",
207
- ky: "ky",
208
- "hy-am": "hy-am",
209
- hr: "hr",
210
- eo: "eo",
211
- bn: "bn",
212
- mg: "mg",
213
- sw: "sw",
214
- "uz-uz": "uz",
215
- my: "my",
216
- te: "te"
217
- };
218
- const getDayjsLocale = (localeCode) => {
219
- return localeMapping[localeCode] || "en";
220
- };
221
- const setDayjsLocale = async (localeCode) => {
222
- const dayjsLocale = getDayjsLocale(localeCode);
223
- if (loadedLocales.has(dayjsLocale)) {
224
- dayjs.locale(dayjsLocale);
225
- return;
226
- }
227
- if (dayjsLocale === "en") {
228
- dayjs.locale("en");
229
- return;
230
- }
231
- const path = `../../../../node_modules/dayjs/locale/${dayjsLocale}.js`;
232
- const loader = dayjsLocales[path];
233
- if (loader) {
234
- try {
235
- await loader();
236
- loadedLocales.add(dayjsLocale);
237
- dayjs.locale(dayjsLocale);
238
- } catch {
239
- dayjs.locale("en");
240
- }
241
- } else {
242
- dayjs.locale("en");
243
- }
244
- };
245
- const setDayjsLocaleSync = (localeCode) => {
246
- const dayjsLocale = getDayjsLocale(localeCode);
247
- if (loadedLocales.has(dayjsLocale)) {
248
- dayjs.locale(dayjsLocale);
249
- } else {
250
- dayjs.locale("en");
251
- setDayjsLocale(localeCode);
252
- }
253
- };
254
- const updateDayjsMonths = (localeCode, months) => {
255
- const dayjsLocale = getDayjsLocale(localeCode);
256
- const monthsArray = [
257
- months.jan,
258
- months.feb,
259
- months.mar,
260
- months.apr,
261
- months.may,
262
- months.jun,
263
- months.jul,
264
- months.aug,
265
- months.sep,
266
- months.oct,
267
- months.nov,
268
- months.dec
269
- ];
270
- try {
271
- if (dayjs.updateLocale) {
272
- dayjs.updateLocale(dayjsLocale, {
273
- months: monthsArray,
274
- monthsShort: monthsArray
275
- });
276
- }
277
- } catch {
278
- }
279
- };
280
-
281
- const useLocale = (localeOverrides) => {
282
- const { globalLocale } = useConfig();
283
- const locale = computed(() => {
284
- return unref(localeOverrides) ?? unref(globalLocale) ?? zhCn;
285
- });
286
- const lang = computed(() => locale.value.name);
287
- watch(
288
- lang,
289
- (newLang) => {
290
- setDayjsLocale(newLang);
291
- },
292
- { immediate: true }
293
- );
294
- const t = (path, options) => {
295
- const keys = path.split(".");
296
- let result = locale.value.yh;
297
- for (const key of keys) {
298
- if (result && typeof result === "object") {
299
- result = result[key];
300
- } else {
301
- result = void 0;
302
- }
303
- if (result === void 0) return path;
304
- }
305
- if (typeof result !== "string") return path;
306
- if (options) {
307
- return result.replace(/\{(\w+)\}/g, (_match, key) => {
308
- const val = options[key];
309
- return val !== void 0 ? String(val) : `{${key}}`;
310
- });
311
- }
312
- return result;
313
- };
314
- const tRaw = (path) => {
315
- const keys = path.split(".");
316
- let result = locale.value.yh;
317
- for (const key of keys) {
318
- if (result && typeof result === "object") {
319
- result = result[key];
320
- } else {
321
- result = void 0;
322
- }
323
- if (result === void 0) return path;
324
- }
325
- return result;
326
- };
327
- return {
328
- locale,
329
- lang,
330
- t,
331
- tRaw
332
- };
333
- };
334
-
335
- const idInjectionKey = Symbol("idInjectionKey");
336
- const useId = (idOverrides) => {
337
- const injectedId = inject(idInjectionKey, void 0);
338
- const nativeId = useId$1();
339
- const id = computed(() => {
340
- const override = unref(idOverrides);
341
- if (override) return override;
342
- const injected = unref(injectedId);
343
- if (injected) return injected;
344
- return nativeId;
345
- });
346
- return id;
347
- };
348
- const useIdInjection = () => {
349
- return {
350
- prefix: computed(() => `yh-${Date.now()}`),
351
- current: 0
352
- // No longer using counter
353
- };
354
- };
355
-
356
- const FormContextKey = Symbol("FormContextKey");
357
- const FormItemContextKey = Symbol("FormItemContextKey");
358
- const useFormItem = () => {
359
- const form = inject(FormContextKey, void 0);
360
- const formItem = inject(FormItemContextKey, void 0);
361
- return {
362
- form,
363
- formItem,
364
- // 触发校验
365
- validate: (trigger) => {
366
- if (formItem) {
367
- return formItem.validate(trigger).catch(() => {
368
- return false;
369
- });
370
- }
371
- return Promise.resolve(true);
372
- }
373
- };
374
- };
375
-
376
- function useVirtualScroll(options) {
377
- const { itemHeight, containerHeight, overscan = 3 } = options;
378
- const containerRef = ref(null);
379
- const scrollTop = ref(0);
380
- const itemsRef = computed(() => {
381
- const items = options.items;
382
- return Array.isArray(items) ? items : items.value;
383
- });
384
- const totalHeight = computed(() => itemsRef.value.length * itemHeight);
385
- const visibleCount = computed(() => Math.ceil(containerHeight / itemHeight));
386
- const startIndex = computed(() => {
387
- const items = itemsRef.value;
388
- if (items.length === 0) return 0;
389
- const start = Math.floor(scrollTop.value / itemHeight);
390
- return Math.max(0, start - overscan);
391
- });
392
- const endIndex = computed(() => {
393
- const items = itemsRef.value;
394
- if (items.length === 0) return 0;
395
- const start = Math.floor(scrollTop.value / itemHeight);
396
- const end = start + visibleCount.value;
397
- return Math.min(items.length, end + overscan);
398
- });
399
- const visibleItems = computed(() => {
400
- const items = itemsRef.value;
401
- if (items.length === 0) return [];
402
- return items.slice(startIndex.value, endIndex.value);
403
- });
404
- const offsetY = computed(() => startIndex.value * itemHeight);
405
- const onScroll = (event) => {
406
- const target = event.target;
407
- scrollTop.value = target.scrollTop;
408
- };
409
- const scrollToIndex = (index) => {
410
- if (containerRef.value) {
411
- const targetScrollTop = index * itemHeight;
412
- containerRef.value.scrollTop = targetScrollTop;
413
- scrollTop.value = targetScrollTop;
414
- }
415
- };
416
- return {
417
- visibleItems,
418
- totalHeight,
419
- offsetY,
420
- startIndex: computed(() => startIndex.value),
421
- endIndex: computed(() => endIndex.value),
422
- onScroll,
423
- scrollToIndex,
424
- containerRef
425
- };
426
- }
427
-
428
- function useCache(key, fetcher) {
429
- const data = shallowRef(null);
430
- const execute = async () => {
431
- try {
432
- data.value = await fetcher();
433
- } catch (err) {
434
- console.error(`[YH-UI] Cache fetcher error for key ${key}:`, err);
435
- }
436
- };
437
- return {
438
- data,
439
- execute
440
- };
441
- }
442
-
443
- function useEventListener(target, event, handler, options) {
444
- if (typeof window === "undefined") return;
445
- const getTarget = () => {
446
- if (typeof target === "function") {
447
- return target();
448
- }
449
- return unref(target);
450
- };
451
- const add = () => {
452
- const el = getTarget();
453
- if (el) {
454
- el.addEventListener(event, handler, options);
455
- }
456
- };
457
- const remove = () => {
458
- const el = getTarget();
459
- if (el) {
460
- el.removeEventListener(event, handler, options);
461
- }
462
- };
463
- onMounted(add);
464
- onBeforeUnmount(remove);
465
- if (isRef(target)) {
466
- watch(target, (newVal, oldVal) => {
467
- if (oldVal) {
468
- oldVal.removeEventListener(event, handler, options);
469
- }
470
- if (newVal) {
471
- newVal.addEventListener(event, handler, options);
472
- }
473
- });
474
- }
475
- }
476
-
477
- const useScrollLock = (trigger) => {
478
- const isLocked = ref(false);
479
- let initialHtmlStyle = { overflow: "", paddingRight: "" };
480
- let initialBodyStyle = { overflow: "", paddingRight: "" };
481
- const getScrollbarWidth = () => {
482
- return window.innerWidth - document.documentElement.clientWidth;
483
- };
484
- const lock = () => {
485
- if (isLocked.value) return;
486
- const width = getScrollbarWidth();
487
- const html = document.documentElement;
488
- const body = document.body;
489
- initialHtmlStyle = {
490
- overflow: html.style.overflow,
491
- paddingRight: html.style.paddingRight
492
- };
493
- initialBodyStyle = {
494
- overflow: body.style.overflow,
495
- paddingRight: body.style.paddingRight
496
- };
497
- if (width > 0) {
498
- const scrollbarWidth = `${width}px`;
499
- html.style.setProperty("--yh-scrollbar-width", scrollbarWidth);
500
- const computedBodyPadding = window.getComputedStyle(body).paddingRight;
501
- body.style.paddingRight = `calc(${computedBodyPadding} + ${scrollbarWidth})`;
502
- }
503
- html.style.overflow = "hidden";
504
- body.style.overflow = "hidden";
505
- html.classList.add("yh-popup-parent--hidden");
506
- isLocked.value = true;
507
- };
508
- const unlock = () => {
509
- if (!isLocked.value) return;
510
- const html = document.documentElement;
511
- const body = document.body;
512
- html.style.overflow = initialHtmlStyle.overflow;
513
- html.style.paddingRight = initialHtmlStyle.paddingRight;
514
- body.style.overflow = initialBodyStyle.overflow;
515
- body.style.paddingRight = initialBodyStyle.paddingRight;
516
- html.classList.remove("yh-popup-parent--hidden");
517
- setTimeout(() => {
518
- if (!html.classList.contains("yh-popup-parent--hidden")) {
519
- html.style.removeProperty("--yh-scrollbar-width");
520
- }
521
- }, 400);
522
- isLocked.value = false;
523
- };
524
- watch(trigger, (val) => {
525
- if (val) {
526
- lock();
527
- } else {
528
- unlock();
529
- }
530
- });
531
- onUnmounted(unlock);
532
- return {
533
- isLocked
534
- };
535
- };
536
-
537
- function useClickOutside(target, handler) {
538
- if (typeof window === "undefined") return;
539
- const listener = (event) => {
540
- const el = unref(target);
541
- if (!el) return;
542
- const path = event.composedPath();
543
- if (path.includes(el)) return;
544
- handler(event);
545
- };
546
- useEventListener(window, "mousedown", listener, true);
547
- useEventListener(window, "touchstart", listener, true);
548
- }
549
-
550
- const openaiParser = (raw) => {
551
- const lines = raw.split("\n");
552
- let text = "";
553
- for (const line of lines) {
554
- if (!line.startsWith("data: ")) continue;
555
- const data = line.slice(6).trim();
556
- if (data === "[DONE]") break;
557
- try {
558
- const json = JSON.parse(data);
559
- const delta = json?.choices?.[0]?.delta?.content;
560
- if (delta) text += delta;
561
- } catch {
562
- }
563
- }
564
- return text || null;
565
- };
566
- const ernieParser = (raw) => {
567
- const lines = raw.split("\n");
568
- let text = "";
569
- for (const line of lines) {
570
- if (!line.startsWith("data: ")) continue;
571
- const data = line.slice(6).trim();
572
- try {
573
- const json = JSON.parse(data);
574
- if (json?.result) text += json.result;
575
- } catch {
576
- }
577
- }
578
- return text || null;
579
- };
580
- const qwenParser = (raw) => {
581
- const lines = raw.split("\n");
582
- let text = "";
583
- for (const line of lines) {
584
- if (!line.startsWith("data: ")) continue;
585
- const data = line.slice(6).trim();
586
- try {
587
- const json = JSON.parse(data);
588
- const t = json?.output?.text;
589
- if (t) text += t;
590
- } catch {
591
- }
592
- }
593
- return text || null;
594
- };
595
- const claudeParser = (raw) => {
596
- const lines = raw.split("\n");
597
- let text = "";
598
- for (const line of lines) {
599
- if (!line.startsWith("data: ")) continue;
600
- const data = line.slice(6).trim();
601
- try {
602
- const json = JSON.parse(data);
603
- if (json?.type === "content_block_delta" && json?.delta?.text) {
604
- text += json.delta.text;
605
- }
606
- } catch {
607
- }
608
- }
609
- return text || null;
610
- };
611
- const geminiParser = (raw) => {
612
- const lines = raw.split("\n");
613
- let text = "";
614
- for (const line of lines) {
615
- const content = line.startsWith("data: ") ? line.slice(6).trim() : line.trim();
616
- if (!content) continue;
617
- try {
618
- const json = JSON.parse(content);
619
- const part = json?.candidates?.[0]?.content?.parts?.[0]?.text;
620
- if (part) text += part;
621
- } catch {
622
- }
623
- }
624
- return text || null;
625
- };
626
- const plainTextParser = (raw) => raw || null;
627
- class TypewriterThrottle {
628
- queue = [];
629
- rafId = null;
630
- onUpdate;
631
- charsPerFrame;
632
- constructor(onUpdate, charsPerFrame = 3) {
633
- this.onUpdate = onUpdate;
634
- this.charsPerFrame = charsPerFrame;
635
- }
636
- push(text) {
637
- this.queue.push(...text.split(""));
638
- if (this.rafId === null) {
639
- this.schedule();
640
- }
641
- }
642
- schedule() {
643
- this.rafId = requestAnimationFrame(() => {
644
- this.rafId = null;
645
- if (this.queue.length === 0) return;
646
- const batch = this.queue.splice(0, this.charsPerFrame).join("");
647
- this.onUpdate(batch);
648
- if (this.queue.length > 0) {
649
- this.schedule();
650
- }
651
- });
652
- }
653
- flush() {
654
- if (this.rafId !== null) {
655
- cancelAnimationFrame(this.rafId);
656
- this.rafId = null;
657
- }
658
- if (this.queue.length > 0) {
659
- const remaining = this.queue.splice(0).join("");
660
- this.onUpdate(remaining);
661
- }
662
- }
663
- cancel() {
664
- if (this.rafId !== null) {
665
- cancelAnimationFrame(this.rafId);
666
- this.rafId = null;
667
- }
668
- this.queue = [];
669
- }
670
- }
671
- function useAiStream(options) {
672
- const isStreaming = ref(false);
673
- const currentContent = ref("");
674
- let abortController = new AbortController();
675
- let typewriter = null;
676
- const parser = options.parser ?? plainTextParser;
677
- const enableTypewriter = options.typewriter !== false;
678
- const charsPerFrame = options.charsPerFrame ?? 3;
679
- const stop = () => {
680
- if (isStreaming.value) {
681
- abortController.abort();
682
- isStreaming.value = false;
683
- typewriter?.flush();
684
- }
685
- };
686
- const fetchStream = async (query, ...args) => {
687
- isStreaming.value = true;
688
- currentContent.value = "";
689
- abortController = new AbortController();
690
- if (enableTypewriter) {
691
- typewriter = new TypewriterThrottle((chunk) => {
692
- currentContent.value += chunk;
693
- options.onUpdate?.(chunk, currentContent.value);
694
- }, charsPerFrame);
695
- }
696
- const pushText = (text) => {
697
- if (!text) return;
698
- if (enableTypewriter && typewriter) {
699
- typewriter.push(text);
700
- } else {
701
- currentContent.value += text;
702
- options.onUpdate?.(text, currentContent.value);
703
- }
704
- };
705
- try {
706
- const response = await options.request(query, ...args);
707
- if (typeof response === "object" && response !== null && Symbol.asyncIterator in response) {
708
- for await (const chunk of response) {
709
- if (abortController.signal.aborted) break;
710
- const parsed = parser(chunk);
711
- if (parsed) pushText(parsed);
712
- }
713
- } else if (response instanceof Response && response.body) {
714
- const reader = response.body.getReader();
715
- const decoder = new TextDecoder("utf-8");
716
- while (true) {
717
- if (abortController.signal.aborted) {
718
- reader.cancel();
719
- break;
720
- }
721
- const { done, value } = await reader.read();
722
- if (done) break;
723
- const chunkStr = decoder.decode(value, { stream: true });
724
- const parsed = parser(chunkStr);
725
- if (parsed) pushText(parsed);
726
- }
727
- }
728
- if (!abortController.signal.aborted) {
729
- if (enableTypewriter && typewriter) {
730
- typewriter.flush();
731
- }
732
- isStreaming.value = false;
733
- options.onFinish?.(currentContent.value);
734
- }
735
- } catch (e) {
736
- if (e.name !== "AbortError") {
737
- options.onError?.(e);
738
- }
739
- typewriter?.cancel();
740
- isStreaming.value = false;
741
- }
742
- };
743
- return {
744
- isStreaming,
745
- currentContent,
746
- fetchStream,
747
- stop,
748
- // 暴露解析器供测试/自定义使用
749
- parsers: {
750
- openaiParser,
751
- ernieParser,
752
- qwenParser,
753
- claudeParser,
754
- geminiParser,
755
- plainTextParser
756
- }
757
- };
758
- }
759
-
760
- function createTypewriter(onChar, charsPerFrame) {
761
- const queue = [];
762
- let rafId = null;
763
- const schedule = () => {
764
- rafId = requestAnimationFrame(() => {
765
- rafId = null;
766
- if (queue.length === 0) return;
767
- const batch = queue.splice(0, charsPerFrame).join("");
768
- onChar(batch);
769
- if (queue.length > 0) schedule();
770
- });
771
- };
772
- return {
773
- push(text) {
774
- queue.push(...text.split(""));
775
- if (rafId === null) schedule();
776
- },
777
- flush() {
778
- if (rafId !== null) {
779
- cancelAnimationFrame(rafId);
780
- rafId = null;
781
- }
782
- if (queue.length > 0) {
783
- onChar(queue.splice(0).join(""));
784
- }
785
- },
786
- cancel() {
787
- if (rafId !== null) {
788
- cancelAnimationFrame(rafId);
789
- rafId = null;
790
- }
791
- queue.length = 0;
792
- }
793
- };
794
- }
795
- function useAiChat(options = {}) {
796
- const {
797
- idGenerator = () => Math.random().toString(36).substring(2, 9),
798
- parser = plainTextParser,
799
- typewriter: enableTypewriter = true,
800
- charsPerFrame = 3,
801
- systemPrompt
802
- } = options;
803
- const messages = ref(options.initialMessages ?? []);
804
- const isGenerating = ref(false);
805
- const isSending = computed(() => isGenerating.value);
806
- let abortController = null;
807
- const stop = () => {
808
- if (abortController && isGenerating.value) {
809
- abortController.abort();
810
- isGenerating.value = false;
811
- const lastMsg = messages.value[messages.value.length - 1];
812
- if (lastMsg?.role === "assistant" && lastMsg.status === "generating") {
813
- lastMsg.status = "stopped";
814
- }
815
- }
816
- };
817
- const clear = () => {
818
- stop();
819
- messages.value = [];
820
- };
821
- const removeMessage = (id) => {
822
- const idx = messages.value.findIndex((m) => m.id === id);
823
- if (idx !== -1) messages.value.splice(idx, 1);
824
- };
825
- const updateMessage = (id, patch) => {
826
- const msg = messages.value.find((m) => m.id === id);
827
- if (msg) Object.assign(msg, patch);
828
- };
829
- const sendMessage = async (content) => {
830
- if (!content.trim() || isGenerating.value) return;
831
- messages.value.push({
832
- id: idGenerator(),
833
- role: "user",
834
- content,
835
- createAt: Date.now(),
836
- status: "success"
837
- });
838
- if (!options.request) return;
839
- const assId = idGenerator();
840
- const assistantMsg = {
841
- id: assId,
842
- role: "assistant",
843
- content: "",
844
- createAt: Date.now(),
845
- status: "loading"
846
- };
847
- messages.value.push(assistantMsg);
848
- isGenerating.value = true;
849
- abortController = new AbortController();
850
- const history = [];
851
- if (systemPrompt) {
852
- history.push({
853
- id: "system",
854
- role: "system",
855
- content: systemPrompt,
856
- createAt: 0,
857
- status: "success"
858
- });
859
- }
860
- history.push(...messages.value.slice(0, -2));
861
- try {
862
- const response = await options.request(content, history, abortController.signal);
863
- const targetMsg = messages.value.find((m) => m.id === assId);
864
- targetMsg.status = "generating";
865
- let typewriterInstance = null;
866
- if (enableTypewriter && typeof requestAnimationFrame !== "undefined") {
867
- typewriterInstance = createTypewriter((chars) => {
868
- targetMsg.content += chars;
869
- }, charsPerFrame);
870
- }
871
- const pushChunk = (text) => {
872
- if (!text) return;
873
- if (typewriterInstance) {
874
- typewriterInstance.push(text);
875
- } else {
876
- targetMsg.content += text;
877
- }
878
- };
879
- if (typeof response === "object" && response !== null && Symbol.asyncIterator in response) {
880
- for await (const chunk of response) {
881
- if (abortController.signal.aborted) break;
882
- const parsed = parser(chunk);
883
- if (parsed) pushChunk(parsed);
884
- }
885
- } else if (response instanceof Response && response.body) {
886
- const reader = response.body.getReader();
887
- const decoder = new TextDecoder("utf-8");
888
- while (true) {
889
- if (abortController.signal.aborted) {
890
- reader.cancel();
891
- break;
892
- }
893
- const { done, value } = await reader.read();
894
- if (done) break;
895
- const chunkStr = decoder.decode(value, { stream: true });
896
- const parsed = parser(chunkStr);
897
- if (parsed) pushChunk(parsed);
898
- }
899
- } else if (typeof response === "string") {
900
- pushChunk(response);
901
- }
902
- if (typewriterInstance) {
903
- typewriterInstance.flush();
904
- }
905
- if (!abortController.signal.aborted) {
906
- targetMsg.status = "success";
907
- options.onFinish?.(targetMsg);
908
- }
909
- } catch (e) {
910
- if (e.name !== "AbortError") {
911
- const targetMsg = messages.value.find((m) => m.id === assId);
912
- if (targetMsg) targetMsg.status = "error";
913
- options.onError?.(e);
914
- }
915
- } finally {
916
- if (isGenerating.value) {
917
- isGenerating.value = false;
918
- }
919
- }
920
- };
921
- return {
922
- /** 会话历史 */
923
- messages,
924
- /** 是否正在生成(等同 isSending,别名友好) */
925
- isGenerating,
926
- /** 同 isGenerating,语义别名 */
927
- isSending,
928
- /** 触发发送(自动处理流、打字机) */
929
- sendMessage,
930
- /** 停止/中断当前生成 */
931
- stop,
932
- /** 移除单条消息 */
933
- removeMessage,
934
- /** 修改单条消息内容 */
935
- updateMessage,
936
- /** 重置清空所有会话 */
937
- clear
938
- };
939
- }
940
-
941
- const localStorageAdapter = {
942
- getItem: (key) => {
943
- try {
944
- return localStorage.getItem(key);
945
- } catch {
946
- return null;
947
- }
948
- },
949
- setItem: (key, value) => {
950
- try {
951
- localStorage.setItem(key, value);
952
- } catch {
953
- }
954
- },
955
- removeItem: (key) => {
956
- try {
957
- localStorage.removeItem(key);
958
- } catch {
959
- }
960
- }
961
- };
962
- class IndexedDBAdapter {
963
- db = null;
964
- dbName;
965
- storeName = "ai_conversations";
966
- ready;
967
- constructor(dbName = "yh-ui-ai") {
968
- this.dbName = dbName;
969
- this.ready = this.init();
970
- }
971
- init() {
972
- return new Promise((resolve, reject) => {
973
- if (typeof indexedDB === "undefined") {
974
- resolve();
975
- return;
976
- }
977
- const req = indexedDB.open(this.dbName, 1);
978
- req.onupgradeneeded = () => {
979
- req.result.createObjectStore(this.storeName);
980
- };
981
- req.onsuccess = () => {
982
- this.db = req.result;
983
- resolve();
984
- };
985
- req.onerror = () => reject(req.error);
986
- });
987
- }
988
- async getItem(key) {
989
- await this.ready;
990
- if (!this.db) return null;
991
- return new Promise((resolve) => {
992
- const tx = this.db.transaction(this.storeName, "readonly");
993
- const req = tx.objectStore(this.storeName).get(key);
994
- req.onsuccess = () => resolve(req.result ?? null);
995
- req.onerror = () => resolve(null);
996
- });
997
- }
998
- async setItem(key, value) {
999
- await this.ready;
1000
- if (!this.db) return;
1001
- return new Promise((resolve) => {
1002
- const tx = this.db.transaction(this.storeName, "readwrite");
1003
- tx.objectStore(this.storeName).put(value, key);
1004
- tx.oncomplete = () => resolve();
1005
- });
1006
- }
1007
- async removeItem(key) {
1008
- await this.ready;
1009
- if (!this.db) return;
1010
- return new Promise((resolve) => {
1011
- const tx = this.db.transaction(this.storeName, "readwrite");
1012
- tx.objectStore(this.storeName).delete(key);
1013
- tx.oncomplete = () => resolve();
1014
- });
1015
- }
1016
- }
1017
- function getGroupLabel(updatedAt) {
1018
- const now = Date.now();
1019
- const diff = now - updatedAt;
1020
- const oneDay = 864e5;
1021
- if (diff < oneDay) return "today";
1022
- if (diff < 7 * oneDay) return "last7Days";
1023
- if (diff < 30 * oneDay) return "last30Days";
1024
- return "earlier";
1025
- }
1026
- const GROUP_ORDER = ["today", "last7Days", "last30Days", "earlier"];
1027
- function useAiConversations(options = {}) {
1028
- const {
1029
- idGenerator = () => Math.random().toString(36).substring(2, 9),
1030
- storage = "localStorage",
1031
- storageKey = "yh-ui-ai-conversations",
1032
- pageSize = 20
1033
- } = options;
1034
- let adapter = null;
1035
- if (storage === "localStorage") {
1036
- adapter = localStorageAdapter;
1037
- } else if (storage === "indexedDB") {
1038
- adapter = new IndexedDBAdapter();
1039
- } else if (storage && typeof storage === "object") {
1040
- adapter = storage;
1041
- }
1042
- const conversations = ref([]);
1043
- const page = ref(1);
1044
- const isLoadingMore = ref(false);
1045
- const initPromise = (async () => {
1046
- let stored = [];
1047
- if (adapter) {
1048
- try {
1049
- const raw = await adapter.getItem(storageKey);
1050
- if (raw) stored = JSON.parse(raw);
1051
- } catch {
1052
- stored = [];
1053
- }
1054
- }
1055
- const init = options.initialConversations ?? [];
1056
- const merged = [...init];
1057
- for (const s of stored) {
1058
- if (!merged.find((c) => c.id === s.id)) {
1059
- merged.push(s);
1060
- }
1061
- }
1062
- conversations.value = merged.sort((a, b) => {
1063
- if (a.pinned !== b.pinned) return a.pinned ? -1 : 1;
1064
- return b.updatedAt - a.updatedAt;
1065
- });
1066
- })();
1067
- const persist = async () => {
1068
- if (!adapter) return;
1069
- try {
1070
- await adapter.setItem(storageKey, JSON.stringify(conversations.value));
1071
- } catch {
1072
- }
1073
- };
1074
- const groupedConversations = computed(() => {
1075
- const groups = {
1076
- today: [],
1077
- last7Days: [],
1078
- last30Days: [],
1079
- earlier: []
1080
- };
1081
- for (const c of conversations.value) {
1082
- if (c.pinned) continue;
1083
- const key = getGroupLabel(c.updatedAt);
1084
- groups[key].push(c);
1085
- }
1086
- const result = [];
1087
- const pinned = conversations.value.filter((c) => c.pinned);
1088
- if (pinned.length > 0) {
1089
- result.push({ label: "pinned", items: pinned });
1090
- }
1091
- for (const key of GROUP_ORDER) {
1092
- if (groups[key].length > 0) {
1093
- result.push({ label: key, items: groups[key] });
1094
- }
1095
- }
1096
- return result;
1097
- });
1098
- const pagedConversations = computed(() => {
1099
- return conversations.value.slice(0, page.value * pageSize);
1100
- });
1101
- const hasMore = computed(() => {
1102
- return pagedConversations.value.length < conversations.value.length;
1103
- });
1104
- const loadMore = async () => {
1105
- if (!hasMore.value || isLoadingMore.value) return;
1106
- isLoadingMore.value = true;
1107
- await new Promise((r) => setTimeout(r, 300));
1108
- page.value++;
1109
- isLoadingMore.value = false;
1110
- };
1111
- const createConversation = async (title, meta) => {
1112
- const newConv = {
1113
- id: idGenerator(),
1114
- title,
1115
- updatedAt: Date.now(),
1116
- meta
1117
- };
1118
- conversations.value.unshift(newConv);
1119
- await persist();
1120
- return newConv;
1121
- };
1122
- const removeConversation = async (id) => {
1123
- const idx = conversations.value.findIndex((c) => c.id === id);
1124
- if (idx !== -1) {
1125
- conversations.value.splice(idx, 1);
1126
- await persist();
1127
- }
1128
- };
1129
- const updateConversation = async (id, updates) => {
1130
- const idx = conversations.value.findIndex((c) => c.id === id);
1131
- if (idx !== -1) {
1132
- conversations.value[idx] = {
1133
- ...conversations.value[idx],
1134
- ...updates,
1135
- updatedAt: Date.now()
1136
- };
1137
- await persist();
1138
- }
1139
- };
1140
- const pinConversation = async (id, pinned = true) => {
1141
- await updateConversation(id, { pinned });
1142
- conversations.value.sort((a, b) => {
1143
- if (a.pinned !== b.pinned) return a.pinned ? -1 : 1;
1144
- return b.updatedAt - a.updatedAt;
1145
- });
1146
- await persist();
1147
- };
1148
- const clear = async () => {
1149
- conversations.value = [];
1150
- if (adapter) {
1151
- await adapter.removeItem(storageKey);
1152
- }
1153
- };
1154
- return {
1155
- /** 完整会话列表 */
1156
- conversations,
1157
- /** 按时间分组后的列表(置顶 / 今天 / 最近 7 天 / 更早) */
1158
- groupedConversations,
1159
- /** 分页后的列表 */
1160
- pagedConversations,
1161
- /** 是否还有更多数据 */
1162
- hasMore,
1163
- /** 加载更多 */
1164
- loadMore,
1165
- /** 加载更多状态 */
1166
- isLoadingMore,
1167
- /** 等待初始化完成(SSR 场景使用) */
1168
- ready: initPromise,
1169
- /** 新建会话 */
1170
- createConversation,
1171
- /** 删除会话 */
1172
- removeConversation,
1173
- /** 更新会话属性 */
1174
- updateConversation,
1175
- /** 置顶/取消置顶 */
1176
- pinConversation,
1177
- /** 清空全部 */
1178
- clear
1179
- };
1180
- }
1181
-
1182
- function useAiRequest(options) {
1183
- const loading = ref(false);
1184
- const data = ref("");
1185
- const error = ref(null);
1186
- const send = async (query, ...args) => {
1187
- loading.value = true;
1188
- error.value = null;
1189
- try {
1190
- const result = await options.request(query, ...args);
1191
- data.value = result;
1192
- options.onSuccess?.(result);
1193
- return result;
1194
- } catch (e) {
1195
- const err = e instanceof Error ? e : new Error(String(e));
1196
- error.value = err;
1197
- options.onError?.(err);
1198
- throw err;
1199
- } finally {
1200
- loading.value = false;
1201
- }
1202
- };
1203
- return {
1204
- loading,
1205
- data,
1206
- error,
1207
- send
1208
- };
1209
- }
1210
-
1211
- function useAiVoice(options = {}) {
1212
- const {
1213
- language = "zh-CN",
1214
- interimResults = true,
1215
- continuous = false,
1216
- vad = true,
1217
- vadThreshold = 2e3,
1218
- volumeThreshold = 0.05,
1219
- waveCount = 20,
1220
- useSTT = true
1221
- } = options;
1222
- const isRecording = ref(false);
1223
- const transcript = ref("");
1224
- const interimTranscript = ref("");
1225
- const volume = ref(0);
1226
- const amplitudes = ref(new Array(waveCount).fill(5));
1227
- const audioBlob = ref(null);
1228
- const recognition = shallowRef(null);
1229
- const audioContext = shallowRef(null);
1230
- const analyser = shallowRef(null);
1231
- const stream = shallowRef(null);
1232
- const mediaRecorder = shallowRef(null);
1233
- let chunks = [];
1234
- let animationId = null;
1235
- let silenceStart = null;
1236
- const _window = typeof window !== "undefined" ? window : null;
1237
- const SpeechRecognition = _window?.SpeechRecognition || _window?.webkitSpeechRecognition;
1238
- const sttSupported = !!SpeechRecognition;
1239
- const initMediaRecorder = (mediaStream) => {
1240
- chunks = [];
1241
- const recorder = new MediaRecorder(mediaStream);
1242
- recorder.ondataavailable = (e) => {
1243
- if (e.data.size > 0) chunks.push(e.data);
1244
- };
1245
- recorder.onstop = () => {
1246
- const blob = chunks.length > 0 ? new Blob(chunks, { type: "audio/webm" }) : null;
1247
- audioBlob.value = blob;
1248
- if (!isRecording.value) {
1249
- options.onStop?.(transcript.value, blob);
1250
- }
1251
- };
1252
- mediaRecorder.value = recorder;
1253
- };
1254
- const initRecognition = () => {
1255
- if (!sttSupported || !useSTT) return;
1256
- const recognitionInstance = new SpeechRecognition();
1257
- recognitionInstance.lang = language;
1258
- recognitionInstance.interimResults = interimResults;
1259
- recognitionInstance.continuous = continuous;
1260
- recognitionInstance.onresult = (event) => {
1261
- let currentInterim = "";
1262
- for (let i = event.resultIndex; i < event.results.length; ++i) {
1263
- if (event.results[i].isFinal) {
1264
- transcript.value += event.results[i][0].transcript;
1265
- options.onResult?.(transcript.value);
1266
- } else {
1267
- currentInterim += event.results[i][0].transcript;
1268
- }
1269
- }
1270
- interimTranscript.value = currentInterim;
1271
- options.onPartialResult?.(currentInterim);
1272
- };
1273
- recognitionInstance.onerror = (event) => {
1274
- if (event.error !== "no-speech" && event.error !== "aborted") {
1275
- options.onError?.(event);
1276
- }
1277
- };
1278
- recognition.value = recognitionInstance;
1279
- };
1280
- const initAudioAnalyzer = async (mediaStream) => {
1281
- try {
1282
- const AudioCtx = window.AudioContext || window.webkitAudioContext;
1283
- audioContext.value = new AudioCtx();
1284
- if (audioContext.value.state === "suspended") {
1285
- await audioContext.value.resume();
1286
- }
1287
- analyser.value = audioContext.value.createAnalyser();
1288
- analyser.value.fftSize = 256;
1289
- const source = audioContext.value.createMediaStreamSource(mediaStream);
1290
- source.connect(analyser.value);
1291
- const bufferLength = analyser.value.frequencyBinCount;
1292
- const dataArray = new Uint8Array(bufferLength);
1293
- const process = () => {
1294
- if (!isRecording.value) {
1295
- amplitudes.value = new Array(waveCount).fill(5);
1296
- volume.value = 0;
1297
- return;
1298
- }
1299
- animationId = requestAnimationFrame(process);
1300
- analyser.value.getByteFrequencyData(dataArray);
1301
- let total = 0;
1302
- for (let i = 0; i < bufferLength; i++) total += dataArray[i];
1303
- const avg = total / bufferLength;
1304
- volume.value = Math.min(100, avg / 128 * 100);
1305
- const step = Math.floor(bufferLength / waveCount);
1306
- const newAmps = [];
1307
- for (let i = 0; i < waveCount; i++) {
1308
- const val = dataArray[i * step];
1309
- newAmps.push(6 + val / 255 * 34);
1310
- }
1311
- amplitudes.value = newAmps;
1312
- if (vad) {
1313
- const normalizedVol = avg / 255;
1314
- if (normalizedVol < volumeThreshold) {
1315
- if (silenceStart === null) silenceStart = Date.now();
1316
- else if (Date.now() - silenceStart > vadThreshold) {
1317
- stop();
1318
- }
1319
- } else {
1320
- silenceStart = null;
1321
- }
1322
- }
1323
- };
1324
- process();
1325
- } catch (err) {
1326
- options.onError?.(err);
1327
- }
1328
- };
1329
- const start = async () => {
1330
- if (stream.value) return;
1331
- try {
1332
- transcript.value = "";
1333
- interimTranscript.value = "";
1334
- audioBlob.value = null;
1335
- silenceStart = null;
1336
- stream.value = await navigator.mediaDevices.getUserMedia({ audio: true });
1337
- isRecording.value = true;
1338
- initMediaRecorder(stream.value);
1339
- initRecognition();
1340
- await initAudioAnalyzer(stream.value);
1341
- mediaRecorder.value?.start(1e3);
1342
- recognition.value?.start();
1343
- options.onStart?.();
1344
- } catch (err) {
1345
- isRecording.value = false;
1346
- if (stream.value) {
1347
- stream.value.getTracks().forEach((t) => t.stop());
1348
- stream.value = null;
1349
- }
1350
- console.error("[yh-ui/hooks] useAiVoice start failed:", err);
1351
- options.onError?.(err);
1352
- }
1353
- };
1354
- const stop = () => {
1355
- if (!stream.value) return;
1356
- isRecording.value = false;
1357
- if (mediaRecorder.value && mediaRecorder.value.state !== "inactive") {
1358
- try {
1359
- mediaRecorder.value.stop();
1360
- } catch {
1361
- }
1362
- }
1363
- if (recognition.value) {
1364
- try {
1365
- recognition.value.stop();
1366
- } catch {
1367
- }
1368
- }
1369
- if (stream.value) {
1370
- stream.value.getTracks().forEach((track) => track.stop());
1371
- stream.value = null;
1372
- }
1373
- cleanup();
1374
- };
1375
- const cancel = () => {
1376
- if (!isRecording.value && !stream.value) return;
1377
- isRecording.value = false;
1378
- if (recognition.value) {
1379
- try {
1380
- recognition.value.abort();
1381
- } catch {
1382
- }
1383
- }
1384
- if (mediaRecorder.value && mediaRecorder.value.state !== "inactive") {
1385
- try {
1386
- mediaRecorder.value.stop();
1387
- } catch {
1388
- }
1389
- }
1390
- if (stream.value) {
1391
- stream.value.getTracks().forEach((track) => track.stop());
1392
- stream.value = null;
1393
- }
1394
- cleanup();
1395
- };
1396
- const cleanup = () => {
1397
- if (animationId) {
1398
- cancelAnimationFrame(animationId);
1399
- animationId = null;
1400
- }
1401
- if (audioContext.value && audioContext.value.state !== "closed") {
1402
- audioContext.value.close().catch((_err) => {
1403
- });
1404
- audioContext.value = null;
1405
- }
1406
- amplitudes.value = new Array(waveCount).fill(5);
1407
- volume.value = 0;
1408
- };
1409
- onUnmounted(() => {
1410
- if (isRecording.value) stop();
1411
- else cleanup();
1412
- });
1413
- return {
1414
- isRecording,
1415
- transcript,
1416
- interimTranscript,
1417
- amplitudes,
1418
- volume,
1419
- audioBlob,
1420
- start,
1421
- stop,
1422
- cancel,
1423
- sttSupported
1424
- };
1425
- }
1426
-
1427
- export { FormContextKey, FormItemContextKey, IndexedDBAdapter, claudeParser, configProviderContextKey, createZIndexCounter, defaultNamespace, ernieParser, geminiParser, getDayjsLocale, getNextZIndex, idInjectionKey, localStorageAdapter, namespaceContextKey, openaiParser, plainTextParser, qwenParser, resetZIndex, setDayjsLocale, setDayjsLocaleSync, updateDayjsMonths, useAiChat, useAiConversations, useAiRequest, useAiStream, useAiVoice, useCache, useClickOutside, useConfig, useEventListener, useFormItem, useGlobalNamespace, useId, useIdInjection, useLocale, useNamespace, useScrollLock, useVirtualScroll, useZIndex, zIndexContextKey, zIndexCounterKey };
1
+ export * from "./use-namespace/index.mjs";
2
+ export * from "./use-z-index/index.mjs";
3
+ export * from "./use-sku/index.mjs";
4
+ export * from "./use-countdown/index.mjs";
5
+ export * from "./use-locale/index.mjs";
6
+ export * from "./use-id/index.mjs";
7
+ export * from "./use-form-item/index.mjs";
8
+ export * from "./use-virtual-scroll/index.mjs";
9
+ export * from "./use-cache/index.mjs";
10
+ export * from "./use-event-listener/index.mjs";
11
+ export * from "./use-scroll-lock/index.mjs";
12
+ export * from "./use-click-outside/index.mjs";
13
+ export * from "./use-config/index.mjs";
14
+ export * from "./use-ai/index.mjs";
15
+ export * from "./storage/index.mjs";