@taskon/widget-react 0.0.1-beta.6 → 0.0.1-beta.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.
Files changed (32) hide show
  1. package/README.md +48 -43
  2. package/dist/EligibilityInfo.css +2 -33
  3. package/dist/TaskOnProvider.css +287 -0
  4. package/dist/ThemeProvider.css +227 -0
  5. package/dist/UserCenterWidget2.css +32 -290
  6. package/dist/WidgetShell.css +0 -227
  7. package/dist/chunks/{CommunityTaskList-Hde2OKHH.js → CommunityTaskList-D0uVD8wD.js} +37 -58
  8. package/dist/chunks/{EligibilityInfo-BV0Z2TgY.js → EligibilityInfo-Cf6hx9-a.js} +17 -209
  9. package/dist/chunks/{LeaderboardWidget-BNGRD5Bu.js → LeaderboardWidget-DyoiiNS6.js} +10 -9
  10. package/dist/chunks/{PageBuilder-C5DSHiW9.js → PageBuilder-DoAFPm6-.js} +5 -5
  11. package/dist/chunks/{Quest-DG9zfXJo.js → Quest-ySZlYd4u.js} +6 -11
  12. package/dist/chunks/TaskOnProvider-CxtFIs3n.js +2072 -0
  13. package/dist/chunks/{WidgetShell-D7yC894Y.js → ThemeProvider-CulHkqqY.js} +1354 -617
  14. package/dist/chunks/UserCenterWidget-BJsc_GSZ.js +3246 -0
  15. package/dist/chunks/{UserCenterWidget-D5ttw4hO.js → UserCenterWidget-STq8kpV4.js} +162 -365
  16. package/dist/chunks/WidgetShell-8xn-Jivw.js +659 -0
  17. package/dist/chunks/useIsMobile-D6Ybur-6.js +30 -0
  18. package/dist/chunks/useToast-BGJhd3BX.js +93 -0
  19. package/dist/community-task.js +1 -1
  20. package/dist/core.d.ts +9 -15
  21. package/dist/core.js +3 -3
  22. package/dist/index.d.ts +64 -15
  23. package/dist/index.js +15 -10
  24. package/dist/leaderboard.js +1 -1
  25. package/dist/page-builder.js +1 -1
  26. package/dist/quest.js +1 -1
  27. package/dist/user-center.js +1 -1
  28. package/package.json +1 -1
  29. package/dist/chunks/TaskOnProvider-BhamHIyY.js +0 -1260
  30. package/dist/chunks/ThemeProvider-mXLdLSkq.js +0 -1397
  31. package/dist/chunks/UserCenterWidget-jDO5zTN1.js +0 -3297
  32. package/dist/chunks/useToast-CaRkylKe.js +0 -304
@@ -1,1260 +0,0 @@
1
- import { p as preloadWidgetLocale, b as useWidgetLocale, e as createLocaleLoader, j as createContextScope, k as useComposedRefs, l as createSlot, P as Primitive, B as Branch, m as useControllableState, n as Presence, o as composeEventHandlers, q as useCallbackRef, R as Root, r as Portal, s as useLayoutEffect2, t as dispatchDiscreteCustomEvent, v as TaskOnContext } from "./ThemeProvider-mXLdLSkq.js";
2
- import { jsx, jsxs, Fragment } from "react/jsx-runtime";
3
- import * as React from "react";
4
- import React__default, { useState, useRef, useEffect, useMemo, useCallback } from "react";
5
- import { createTaskOnClient, createUserApi, createChainApi, createCommunityTaskApi } from "@taskon/core";
6
- import { c as createEthereumAdapter, W as WalletContext, b as useToastState, T as ToastContext } from "./useToast-CaRkylKe.js";
7
- import * as ReactDOM from "react-dom";
8
- import '../TaskOnProvider.css';const TOKEN_STORAGE_KEY = "taskon_user_token";
9
- function isBrowser() {
10
- return typeof window !== "undefined";
11
- }
12
- function getStoredToken() {
13
- if (!isBrowser()) {
14
- return null;
15
- }
16
- try {
17
- return localStorage.getItem(TOKEN_STORAGE_KEY);
18
- } catch {
19
- return null;
20
- }
21
- }
22
- function setStoredToken(token) {
23
- if (!isBrowser()) {
24
- return;
25
- }
26
- try {
27
- localStorage.setItem(TOKEN_STORAGE_KEY, token);
28
- } catch {
29
- }
30
- }
31
- function removeStoredToken() {
32
- if (!isBrowser()) {
33
- return;
34
- }
35
- try {
36
- localStorage.removeItem(TOKEN_STORAGE_KEY);
37
- } catch {
38
- }
39
- }
40
- function useClientInit({
41
- apiKey,
42
- baseURL,
43
- setUserInfo,
44
- setUserToken
45
- }) {
46
- const [client, setClient] = useState(null);
47
- const userApiRef = useRef(null);
48
- const [isInitializing, setIsInitializing] = useState(true);
49
- const [isSessionReady, setIsSessionReady] = useState(false);
50
- const isInitializedRef = useRef(false);
51
- const configRef = useRef({ apiKey, baseURL });
52
- configRef.current = { apiKey, baseURL };
53
- const settersRef = useRef({ setUserInfo, setUserToken });
54
- settersRef.current = { setUserInfo, setUserToken };
55
- useEffect(() => {
56
- if (isInitializedRef.current) {
57
- return;
58
- }
59
- isInitializedRef.current = true;
60
- const init = async () => {
61
- try {
62
- const { apiKey: apiKey2, baseURL: baseURL2 } = configRef.current;
63
- const { setUserInfo: setUserInfo2, setUserToken: setUserToken2 } = settersRef.current;
64
- const taskOnClient = createTaskOnClient({
65
- apiKey: apiKey2,
66
- baseURL: baseURL2,
67
- // Unified auth error handler - called when any API returns auth error
68
- onAuthError: () => {
69
- taskOnClient.setUserToken(null);
70
- settersRef.current.setUserInfo(null);
71
- settersRef.current.setUserToken(null);
72
- removeStoredToken();
73
- }
74
- });
75
- const userApi = createUserApi(taskOnClient);
76
- setClient(taskOnClient);
77
- userApiRef.current = userApi;
78
- const storedToken = getStoredToken();
79
- if (storedToken) {
80
- taskOnClient.setUserToken(storedToken);
81
- setIsSessionReady(true);
82
- try {
83
- const info = await userApi.getInfo();
84
- setUserInfo2(info);
85
- setUserToken2(storedToken);
86
- } catch {
87
- taskOnClient.setUserToken(null);
88
- }
89
- } else {
90
- setIsSessionReady(true);
91
- }
92
- } finally {
93
- setIsInitializing(false);
94
- }
95
- };
96
- init();
97
- }, []);
98
- return {
99
- client,
100
- userApiRef,
101
- isSessionReady,
102
- isInitializing
103
- };
104
- }
105
- const registry = /* @__PURE__ */ new Map();
106
- const builtInLocaleImports = {
107
- CommunityTask: {
108
- ko: () => import("./communitytask-ko-Bf24PQKI.js").then((module) => ({
109
- default: module.default
110
- })),
111
- ja: () => import("./communitytask-ja-GRf9cbdx.js").then((module) => ({
112
- default: module.default
113
- })),
114
- ru: () => import("./communitytask-ru-CZm2CPoV.js").then((module) => ({
115
- default: module.default
116
- })),
117
- es: () => import("./communitytask-es-CBNnS4o2.js").then((module) => ({
118
- default: module.default
119
- }))
120
- },
121
- Quest: {
122
- ko: () => import("./quest-ko-BMu3uRQJ.js").then((module) => ({
123
- default: module.default
124
- })),
125
- ja: () => import("./quest-ja-Depog33y.js").then((module) => ({
126
- default: module.default
127
- })),
128
- ru: () => import("./quest-ru-xne814Rw.js").then((module) => ({
129
- default: module.default
130
- })),
131
- es: () => import("./quest-es-Dyyy0zaw.js").then((module) => ({
132
- default: module.default
133
- }))
134
- },
135
- TaskWidget: {
136
- ko: () => import("./taskwidget-ko-EHgXFV4B.js").then((module) => ({
137
- default: module.default
138
- })),
139
- ja: () => import("./taskwidget-ja-CqSu-yWA.js").then((module) => ({
140
- default: module.default
141
- })),
142
- ru: () => import("./taskwidget-ru-CMbLQDK4.js").then((module) => ({
143
- default: module.default
144
- })),
145
- es: () => import("./taskwidget-es-Do9b3Mqw.js").then((module) => ({
146
- default: module.default
147
- }))
148
- },
149
- LeaderboardWidget: {
150
- ko: () => import("./leaderboardwidget-ko-CG6SWgxf.js").then((module) => ({
151
- default: module.default
152
- })),
153
- ja: () => import("./leaderboardwidget-ja-Q6u0HxKG.js").then((module) => ({
154
- default: module.default
155
- })),
156
- ru: () => import("./leaderboardwidget-ru-DCcHcJGz.js").then((module) => ({
157
- default: module.default
158
- })),
159
- es: () => import("./leaderboardwidget-es-vKjrjQaz.js").then((module) => ({
160
- default: module.default
161
- }))
162
- },
163
- UserCenterWidget: {
164
- ko: () => import("./usercenter-ko-Dtpkn2qb.js").then((module) => ({
165
- default: module.default
166
- })),
167
- ja: () => import("./usercenter-ja-CKE4DJC6.js").then((module) => ({
168
- default: module.default
169
- })),
170
- ru: () => import("./usercenter-ru-DnBGee45.js").then((module) => ({
171
- default: module.default
172
- })),
173
- es: () => import("./usercenter-es-Dz3Wp2vV.js").then((module) => ({
174
- default: module.default
175
- }))
176
- }
177
- };
178
- async function preloadBuiltInWidgetLocale(widget, locale) {
179
- if (locale === "en") return;
180
- const localeLoader = builtInLocaleImports[widget][locale];
181
- if (!localeLoader) return;
182
- await preloadWidgetLocale(widget, locale, () => localeLoader());
183
- }
184
- const builtInPreloaders = {
185
- CommunityTask: (locale) => preloadBuiltInWidgetLocale("CommunityTask", locale),
186
- Quest: (locale) => preloadBuiltInWidgetLocale("Quest", locale),
187
- TaskWidget: (locale) => preloadBuiltInWidgetLocale("TaskWidget", locale),
188
- LeaderboardWidget: (locale) => preloadBuiltInWidgetLocale("LeaderboardWidget", locale),
189
- UserCenterWidget: (locale) => preloadBuiltInWidgetLocale("UserCenterWidget", locale)
190
- };
191
- async function preloadWidgets(widgets, locale) {
192
- const preloadPromises = widgets.map((name) => {
193
- const preloadFn = registry.get(name) ?? builtInPreloaders[name];
194
- if (!preloadFn) {
195
- if (process.env.NODE_ENV !== "production") {
196
- console.warn(
197
- `[widget-react] Widget "${name}" not found in registry. Make sure this widget has a preload loader configured.`
198
- );
199
- }
200
- return null;
201
- }
202
- return preloadFn(locale);
203
- }).filter(Boolean);
204
- await Promise.all(preloadPromises);
205
- }
206
- const loading = "Loading...";
207
- const error = "Something went wrong";
208
- const retry = "Retry";
209
- const success = "Success";
210
- const cancel = "Cancel";
211
- const confirm = "Confirm";
212
- const enMessages = {
213
- loading,
214
- error,
215
- retry,
216
- success,
217
- cancel,
218
- confirm
219
- };
220
- const loadMessages = createLocaleLoader(enMessages, {
221
- ko: () => import("./common-ko-80ezXsMG.js").then((m) => ({ default: m.default })),
222
- ja: () => import("./common-ja-DWhTaFHb.js").then((m) => ({ default: m.default }))
223
- });
224
- function useCommonLocale() {
225
- return useWidgetLocale({
226
- widgetId: "Common",
227
- defaultMessages: enMessages,
228
- loadMessages
229
- });
230
- }
231
- const SUPPORTED_LOCALES = ["en", "ko", "ja", "ru", "es"];
232
- const DEFAULT_LOCALE = "en";
233
- function detectLocale() {
234
- if (typeof window === "undefined") {
235
- return DEFAULT_LOCALE;
236
- }
237
- const browserLang = navigator.language.split("-")[0];
238
- if (SUPPORTED_LOCALES.includes(browserLang)) {
239
- return browserLang;
240
- }
241
- return DEFAULT_LOCALE;
242
- }
243
- function useLocaleManager({
244
- configLocale,
245
- preloadLocales
246
- }) {
247
- const [isPreloading, setIsPreloading] = useState(
248
- () => preloadLocales !== void 0 && preloadLocales.length > 0
249
- );
250
- const preloadLocalesRef = useRef(preloadLocales);
251
- preloadLocalesRef.current = preloadLocales;
252
- const locale = useMemo(() => {
253
- return configLocale ?? detectLocale();
254
- }, [configLocale]);
255
- useEffect(() => {
256
- const widgets = preloadLocalesRef.current;
257
- if (!widgets || widgets.length === 0) {
258
- setIsPreloading(false);
259
- return;
260
- }
261
- if (locale === "en") {
262
- setIsPreloading(false);
263
- return;
264
- }
265
- let isMounted = true;
266
- preloadWidgets(widgets, locale).finally(() => {
267
- if (isMounted) {
268
- setIsPreloading(false);
269
- }
270
- });
271
- return () => {
272
- isMounted = false;
273
- };
274
- }, [locale]);
275
- return {
276
- locale,
277
- isPreloading
278
- };
279
- }
280
- const LOGIN_METHOD_MAP = {
281
- evm_wallet: {
282
- apiMethod: "loginWithEvm",
283
- buildParams: (value, sign, timestamp) => ({ address: value, sign, timestamp })
284
- },
285
- email: {
286
- apiMethod: "loginWithEmail",
287
- buildParams: (value, sign, timestamp) => ({ email: value, sign, timestamp })
288
- },
289
- discord: {
290
- apiMethod: "loginWithSns",
291
- buildParams: (value, sign, timestamp) => ({ type: "Discord", token: value, sign, timestamp })
292
- },
293
- twitter: {
294
- apiMethod: "loginWithSns",
295
- buildParams: (value, sign, timestamp) => ({ type: "Twitter", token: value, sign, timestamp })
296
- },
297
- telegram: {
298
- apiMethod: "loginWithSns",
299
- buildParams: (value, sign, timestamp) => ({ type: "Telegram", token: value, sign, timestamp })
300
- }
301
- };
302
- function useAuth({
303
- client,
304
- userApiRef,
305
- setUserInfo,
306
- setUserToken
307
- }) {
308
- const setToken = useCallback(
309
- (token) => {
310
- if (!client) {
311
- throw new Error("TaskOn client not initialized");
312
- }
313
- client.setUserToken(token);
314
- setUserToken(token);
315
- setStoredToken(token);
316
- },
317
- [client, setUserToken]
318
- );
319
- const login = useCallback(
320
- async (params) => {
321
- const userApi = userApiRef.current;
322
- if (!userApi) {
323
- throw new Error("TaskOn client not initialized");
324
- }
325
- const { method, value, sign, timestamp } = params;
326
- const methodConfig = LOGIN_METHOD_MAP[method];
327
- if (!methodConfig) {
328
- throw new Error(`Unsupported login method: ${method}`);
329
- }
330
- const apiParams = methodConfig.buildParams(value, sign, timestamp);
331
- const result = await userApi[methodConfig.apiMethod](apiParams);
332
- setToken(result.token);
333
- try {
334
- const info = await userApi.getInfo();
335
- setUserInfo(info);
336
- } catch {
337
- }
338
- },
339
- [userApiRef, setToken, setUserInfo]
340
- );
341
- const logout = useCallback(() => {
342
- if (client) {
343
- client.setUserToken(null);
344
- }
345
- setUserInfo(null);
346
- setUserToken(null);
347
- removeStoredToken();
348
- }, [client, setUserInfo, setUserToken]);
349
- return { login, logout };
350
- }
351
- function WalletProvider({
352
- children,
353
- config
354
- }) {
355
- const [state, setState] = useState({
356
- adapter: (config == null ? void 0 : config.evmAdapter) ?? null,
357
- address: null,
358
- chainId: null
359
- });
360
- useEffect(() => {
361
- if ((config == null ? void 0 : config.evmAdapter) || (config == null ? void 0 : config.disableAutoDetect)) return;
362
- const ethereumAdapter = createEthereumAdapter();
363
- if (ethereumAdapter) {
364
- setState((prev) => ({
365
- ...prev,
366
- adapter: ethereumAdapter
367
- }));
368
- }
369
- }, [config == null ? void 0 : config.evmAdapter, config == null ? void 0 : config.disableAutoDetect]);
370
- const contextValue = useMemo(
371
- () => ({
372
- evmAdapter: state.adapter,
373
- evmAddress: state.address,
374
- evmChainId: state.chainId,
375
- isEvmConnected: state.address !== null,
376
- isDetecting: false,
377
- // Actions - delegate to adapter
378
- connectEvm: async () => {
379
- if (!state.adapter) return null;
380
- try {
381
- const address = await state.adapter.connect();
382
- setState((prev) => {
383
- var _a, _b;
384
- return {
385
- ...prev,
386
- address,
387
- chainId: ((_b = (_a = state.adapter) == null ? void 0 : _a.getChainId) == null ? void 0 : _b.call(_a)) ?? null
388
- };
389
- });
390
- return address;
391
- } catch {
392
- return null;
393
- }
394
- },
395
- disconnectEvm: async () => {
396
- var _a;
397
- await ((_a = state.adapter) == null ? void 0 : _a.disconnect());
398
- setState((prev) => ({
399
- ...prev,
400
- address: null
401
- }));
402
- },
403
- signEvmMessage: async (message) => {
404
- if (!state.adapter) return null;
405
- try {
406
- return await state.adapter.signMessage(message);
407
- } catch {
408
- return null;
409
- }
410
- }
411
- }),
412
- [state]
413
- );
414
- return /* @__PURE__ */ jsx(WalletContext.Provider, { value: contextValue, children });
415
- }
416
- function createCollection(name) {
417
- const PROVIDER_NAME2 = name + "CollectionProvider";
418
- const [createCollectionContext, createCollectionScope2] = createContextScope(PROVIDER_NAME2);
419
- const [CollectionProviderImpl, useCollectionContext] = createCollectionContext(
420
- PROVIDER_NAME2,
421
- { collectionRef: { current: null }, itemMap: /* @__PURE__ */ new Map() }
422
- );
423
- const CollectionProvider = (props) => {
424
- const { scope, children } = props;
425
- const ref = React__default.useRef(null);
426
- const itemMap = React__default.useRef(/* @__PURE__ */ new Map()).current;
427
- return /* @__PURE__ */ jsx(CollectionProviderImpl, { scope, itemMap, collectionRef: ref, children });
428
- };
429
- CollectionProvider.displayName = PROVIDER_NAME2;
430
- const COLLECTION_SLOT_NAME = name + "CollectionSlot";
431
- const CollectionSlotImpl = createSlot(COLLECTION_SLOT_NAME);
432
- const CollectionSlot = React__default.forwardRef(
433
- (props, forwardedRef) => {
434
- const { scope, children } = props;
435
- const context = useCollectionContext(COLLECTION_SLOT_NAME, scope);
436
- const composedRefs = useComposedRefs(forwardedRef, context.collectionRef);
437
- return /* @__PURE__ */ jsx(CollectionSlotImpl, { ref: composedRefs, children });
438
- }
439
- );
440
- CollectionSlot.displayName = COLLECTION_SLOT_NAME;
441
- const ITEM_SLOT_NAME = name + "CollectionItemSlot";
442
- const ITEM_DATA_ATTR = "data-radix-collection-item";
443
- const CollectionItemSlotImpl = createSlot(ITEM_SLOT_NAME);
444
- const CollectionItemSlot = React__default.forwardRef(
445
- (props, forwardedRef) => {
446
- const { scope, children, ...itemData } = props;
447
- const ref = React__default.useRef(null);
448
- const composedRefs = useComposedRefs(forwardedRef, ref);
449
- const context = useCollectionContext(ITEM_SLOT_NAME, scope);
450
- React__default.useEffect(() => {
451
- context.itemMap.set(ref, { ref, ...itemData });
452
- return () => void context.itemMap.delete(ref);
453
- });
454
- return /* @__PURE__ */ jsx(CollectionItemSlotImpl, { ...{ [ITEM_DATA_ATTR]: "" }, ref: composedRefs, children });
455
- }
456
- );
457
- CollectionItemSlot.displayName = ITEM_SLOT_NAME;
458
- function useCollection2(scope) {
459
- const context = useCollectionContext(name + "CollectionConsumer", scope);
460
- const getItems = React__default.useCallback(() => {
461
- const collectionNode = context.collectionRef.current;
462
- if (!collectionNode) return [];
463
- const orderedNodes = Array.from(collectionNode.querySelectorAll(`[${ITEM_DATA_ATTR}]`));
464
- const items = Array.from(context.itemMap.values());
465
- const orderedItems = items.sort(
466
- (a, b) => orderedNodes.indexOf(a.ref.current) - orderedNodes.indexOf(b.ref.current)
467
- );
468
- return orderedItems;
469
- }, [context.collectionRef, context.itemMap]);
470
- return getItems;
471
- }
472
- return [
473
- { Provider: CollectionProvider, Slot: CollectionSlot, ItemSlot: CollectionItemSlot },
474
- useCollection2,
475
- createCollectionScope2
476
- ];
477
- }
478
- var VISUALLY_HIDDEN_STYLES = Object.freeze({
479
- // See: https://github.com/twbs/bootstrap/blob/main/scss/mixins/_visually-hidden.scss
480
- position: "absolute",
481
- border: 0,
482
- width: 1,
483
- height: 1,
484
- padding: 0,
485
- margin: -1,
486
- overflow: "hidden",
487
- clip: "rect(0, 0, 0, 0)",
488
- whiteSpace: "nowrap",
489
- wordWrap: "normal"
490
- });
491
- var NAME = "VisuallyHidden";
492
- var VisuallyHidden = React.forwardRef(
493
- (props, forwardedRef) => {
494
- return /* @__PURE__ */ jsx(
495
- Primitive.span,
496
- {
497
- ...props,
498
- ref: forwardedRef,
499
- style: { ...VISUALLY_HIDDEN_STYLES, ...props.style }
500
- }
501
- );
502
- }
503
- );
504
- VisuallyHidden.displayName = NAME;
505
- var PROVIDER_NAME = "ToastProvider";
506
- var [Collection, useCollection, createCollectionScope] = createCollection("Toast");
507
- var [createToastContext] = createContextScope("Toast", [createCollectionScope]);
508
- var [ToastProviderProvider, useToastProviderContext] = createToastContext(PROVIDER_NAME);
509
- var ToastProvider$1 = (props) => {
510
- const {
511
- __scopeToast,
512
- label = "Notification",
513
- duration = 5e3,
514
- swipeDirection = "right",
515
- swipeThreshold = 50,
516
- children
517
- } = props;
518
- const [viewport, setViewport] = React.useState(null);
519
- const [toastCount, setToastCount] = React.useState(0);
520
- const isFocusedToastEscapeKeyDownRef = React.useRef(false);
521
- const isClosePausedRef = React.useRef(false);
522
- if (!label.trim()) {
523
- console.error(
524
- `Invalid prop \`label\` supplied to \`${PROVIDER_NAME}\`. Expected non-empty \`string\`.`
525
- );
526
- }
527
- return /* @__PURE__ */ jsx(Collection.Provider, { scope: __scopeToast, children: /* @__PURE__ */ jsx(
528
- ToastProviderProvider,
529
- {
530
- scope: __scopeToast,
531
- label,
532
- duration,
533
- swipeDirection,
534
- swipeThreshold,
535
- toastCount,
536
- viewport,
537
- onViewportChange: setViewport,
538
- onToastAdd: React.useCallback(() => setToastCount((prevCount) => prevCount + 1), []),
539
- onToastRemove: React.useCallback(() => setToastCount((prevCount) => prevCount - 1), []),
540
- isFocusedToastEscapeKeyDownRef,
541
- isClosePausedRef,
542
- children
543
- }
544
- ) });
545
- };
546
- ToastProvider$1.displayName = PROVIDER_NAME;
547
- var VIEWPORT_NAME = "ToastViewport";
548
- var VIEWPORT_DEFAULT_HOTKEY = ["F8"];
549
- var VIEWPORT_PAUSE = "toast.viewportPause";
550
- var VIEWPORT_RESUME = "toast.viewportResume";
551
- var ToastViewport$1 = React.forwardRef(
552
- (props, forwardedRef) => {
553
- const {
554
- __scopeToast,
555
- hotkey = VIEWPORT_DEFAULT_HOTKEY,
556
- label = "Notifications ({hotkey})",
557
- ...viewportProps
558
- } = props;
559
- const context = useToastProviderContext(VIEWPORT_NAME, __scopeToast);
560
- const getItems = useCollection(__scopeToast);
561
- const wrapperRef = React.useRef(null);
562
- const headFocusProxyRef = React.useRef(null);
563
- const tailFocusProxyRef = React.useRef(null);
564
- const ref = React.useRef(null);
565
- const composedRefs = useComposedRefs(forwardedRef, ref, context.onViewportChange);
566
- const hotkeyLabel = hotkey.join("+").replace(/Key/g, "").replace(/Digit/g, "");
567
- const hasToasts = context.toastCount > 0;
568
- React.useEffect(() => {
569
- const handleKeyDown = (event) => {
570
- var _a;
571
- const isHotkeyPressed = hotkey.length !== 0 && hotkey.every((key) => event[key] || event.code === key);
572
- if (isHotkeyPressed) (_a = ref.current) == null ? void 0 : _a.focus();
573
- };
574
- document.addEventListener("keydown", handleKeyDown);
575
- return () => document.removeEventListener("keydown", handleKeyDown);
576
- }, [hotkey]);
577
- React.useEffect(() => {
578
- const wrapper = wrapperRef.current;
579
- const viewport = ref.current;
580
- if (hasToasts && wrapper && viewport) {
581
- const handlePause = () => {
582
- if (!context.isClosePausedRef.current) {
583
- const pauseEvent = new CustomEvent(VIEWPORT_PAUSE);
584
- viewport.dispatchEvent(pauseEvent);
585
- context.isClosePausedRef.current = true;
586
- }
587
- };
588
- const handleResume = () => {
589
- if (context.isClosePausedRef.current) {
590
- const resumeEvent = new CustomEvent(VIEWPORT_RESUME);
591
- viewport.dispatchEvent(resumeEvent);
592
- context.isClosePausedRef.current = false;
593
- }
594
- };
595
- const handleFocusOutResume = (event) => {
596
- const isFocusMovingOutside = !wrapper.contains(event.relatedTarget);
597
- if (isFocusMovingOutside) handleResume();
598
- };
599
- const handlePointerLeaveResume = () => {
600
- const isFocusInside = wrapper.contains(document.activeElement);
601
- if (!isFocusInside) handleResume();
602
- };
603
- wrapper.addEventListener("focusin", handlePause);
604
- wrapper.addEventListener("focusout", handleFocusOutResume);
605
- wrapper.addEventListener("pointermove", handlePause);
606
- wrapper.addEventListener("pointerleave", handlePointerLeaveResume);
607
- window.addEventListener("blur", handlePause);
608
- window.addEventListener("focus", handleResume);
609
- return () => {
610
- wrapper.removeEventListener("focusin", handlePause);
611
- wrapper.removeEventListener("focusout", handleFocusOutResume);
612
- wrapper.removeEventListener("pointermove", handlePause);
613
- wrapper.removeEventListener("pointerleave", handlePointerLeaveResume);
614
- window.removeEventListener("blur", handlePause);
615
- window.removeEventListener("focus", handleResume);
616
- };
617
- }
618
- }, [hasToasts, context.isClosePausedRef]);
619
- const getSortedTabbableCandidates = React.useCallback(
620
- ({ tabbingDirection }) => {
621
- const toastItems = getItems();
622
- const tabbableCandidates = toastItems.map((toastItem) => {
623
- const toastNode = toastItem.ref.current;
624
- const toastTabbableCandidates = [toastNode, ...getTabbableCandidates(toastNode)];
625
- return tabbingDirection === "forwards" ? toastTabbableCandidates : toastTabbableCandidates.reverse();
626
- });
627
- return (tabbingDirection === "forwards" ? tabbableCandidates.reverse() : tabbableCandidates).flat();
628
- },
629
- [getItems]
630
- );
631
- React.useEffect(() => {
632
- const viewport = ref.current;
633
- if (viewport) {
634
- const handleKeyDown = (event) => {
635
- var _a, _b, _c;
636
- const isMetaKey = event.altKey || event.ctrlKey || event.metaKey;
637
- const isTabKey = event.key === "Tab" && !isMetaKey;
638
- if (isTabKey) {
639
- const focusedElement = document.activeElement;
640
- const isTabbingBackwards = event.shiftKey;
641
- const targetIsViewport = event.target === viewport;
642
- if (targetIsViewport && isTabbingBackwards) {
643
- (_a = headFocusProxyRef.current) == null ? void 0 : _a.focus();
644
- return;
645
- }
646
- const tabbingDirection = isTabbingBackwards ? "backwards" : "forwards";
647
- const sortedCandidates = getSortedTabbableCandidates({ tabbingDirection });
648
- const index = sortedCandidates.findIndex((candidate) => candidate === focusedElement);
649
- if (focusFirst(sortedCandidates.slice(index + 1))) {
650
- event.preventDefault();
651
- } else {
652
- isTabbingBackwards ? (_b = headFocusProxyRef.current) == null ? void 0 : _b.focus() : (_c = tailFocusProxyRef.current) == null ? void 0 : _c.focus();
653
- }
654
- }
655
- };
656
- viewport.addEventListener("keydown", handleKeyDown);
657
- return () => viewport.removeEventListener("keydown", handleKeyDown);
658
- }
659
- }, [getItems, getSortedTabbableCandidates]);
660
- return /* @__PURE__ */ jsxs(
661
- Branch,
662
- {
663
- ref: wrapperRef,
664
- role: "region",
665
- "aria-label": label.replace("{hotkey}", hotkeyLabel),
666
- tabIndex: -1,
667
- style: { pointerEvents: hasToasts ? void 0 : "none" },
668
- children: [
669
- hasToasts && /* @__PURE__ */ jsx(
670
- FocusProxy,
671
- {
672
- ref: headFocusProxyRef,
673
- onFocusFromOutsideViewport: () => {
674
- const tabbableCandidates = getSortedTabbableCandidates({
675
- tabbingDirection: "forwards"
676
- });
677
- focusFirst(tabbableCandidates);
678
- }
679
- }
680
- ),
681
- /* @__PURE__ */ jsx(Collection.Slot, { scope: __scopeToast, children: /* @__PURE__ */ jsx(Primitive.ol, { tabIndex: -1, ...viewportProps, ref: composedRefs }) }),
682
- hasToasts && /* @__PURE__ */ jsx(
683
- FocusProxy,
684
- {
685
- ref: tailFocusProxyRef,
686
- onFocusFromOutsideViewport: () => {
687
- const tabbableCandidates = getSortedTabbableCandidates({
688
- tabbingDirection: "backwards"
689
- });
690
- focusFirst(tabbableCandidates);
691
- }
692
- }
693
- )
694
- ]
695
- }
696
- );
697
- }
698
- );
699
- ToastViewport$1.displayName = VIEWPORT_NAME;
700
- var FOCUS_PROXY_NAME = "ToastFocusProxy";
701
- var FocusProxy = React.forwardRef(
702
- (props, forwardedRef) => {
703
- const { __scopeToast, onFocusFromOutsideViewport, ...proxyProps } = props;
704
- const context = useToastProviderContext(FOCUS_PROXY_NAME, __scopeToast);
705
- return /* @__PURE__ */ jsx(
706
- VisuallyHidden,
707
- {
708
- tabIndex: 0,
709
- ...proxyProps,
710
- ref: forwardedRef,
711
- style: { position: "fixed" },
712
- onFocus: (event) => {
713
- var _a;
714
- const prevFocusedElement = event.relatedTarget;
715
- const isFocusFromOutsideViewport = !((_a = context.viewport) == null ? void 0 : _a.contains(prevFocusedElement));
716
- if (isFocusFromOutsideViewport) onFocusFromOutsideViewport();
717
- }
718
- }
719
- );
720
- }
721
- );
722
- FocusProxy.displayName = FOCUS_PROXY_NAME;
723
- var TOAST_NAME = "Toast";
724
- var TOAST_SWIPE_START = "toast.swipeStart";
725
- var TOAST_SWIPE_MOVE = "toast.swipeMove";
726
- var TOAST_SWIPE_CANCEL = "toast.swipeCancel";
727
- var TOAST_SWIPE_END = "toast.swipeEnd";
728
- var Toast = React.forwardRef(
729
- (props, forwardedRef) => {
730
- const { forceMount, open: openProp, defaultOpen, onOpenChange, ...toastProps } = props;
731
- const [open, setOpen] = useControllableState({
732
- prop: openProp,
733
- defaultProp: defaultOpen ?? true,
734
- onChange: onOpenChange,
735
- caller: TOAST_NAME
736
- });
737
- return /* @__PURE__ */ jsx(Presence, { present: forceMount || open, children: /* @__PURE__ */ jsx(
738
- ToastImpl,
739
- {
740
- open,
741
- ...toastProps,
742
- ref: forwardedRef,
743
- onClose: () => setOpen(false),
744
- onPause: useCallbackRef(props.onPause),
745
- onResume: useCallbackRef(props.onResume),
746
- onSwipeStart: composeEventHandlers(props.onSwipeStart, (event) => {
747
- event.currentTarget.setAttribute("data-swipe", "start");
748
- }),
749
- onSwipeMove: composeEventHandlers(props.onSwipeMove, (event) => {
750
- const { x, y } = event.detail.delta;
751
- event.currentTarget.setAttribute("data-swipe", "move");
752
- event.currentTarget.style.setProperty("--radix-toast-swipe-move-x", `${x}px`);
753
- event.currentTarget.style.setProperty("--radix-toast-swipe-move-y", `${y}px`);
754
- }),
755
- onSwipeCancel: composeEventHandlers(props.onSwipeCancel, (event) => {
756
- event.currentTarget.setAttribute("data-swipe", "cancel");
757
- event.currentTarget.style.removeProperty("--radix-toast-swipe-move-x");
758
- event.currentTarget.style.removeProperty("--radix-toast-swipe-move-y");
759
- event.currentTarget.style.removeProperty("--radix-toast-swipe-end-x");
760
- event.currentTarget.style.removeProperty("--radix-toast-swipe-end-y");
761
- }),
762
- onSwipeEnd: composeEventHandlers(props.onSwipeEnd, (event) => {
763
- const { x, y } = event.detail.delta;
764
- event.currentTarget.setAttribute("data-swipe", "end");
765
- event.currentTarget.style.removeProperty("--radix-toast-swipe-move-x");
766
- event.currentTarget.style.removeProperty("--radix-toast-swipe-move-y");
767
- event.currentTarget.style.setProperty("--radix-toast-swipe-end-x", `${x}px`);
768
- event.currentTarget.style.setProperty("--radix-toast-swipe-end-y", `${y}px`);
769
- setOpen(false);
770
- })
771
- }
772
- ) });
773
- }
774
- );
775
- Toast.displayName = TOAST_NAME;
776
- var [ToastInteractiveProvider, useToastInteractiveContext] = createToastContext(TOAST_NAME, {
777
- onClose() {
778
- }
779
- });
780
- var ToastImpl = React.forwardRef(
781
- (props, forwardedRef) => {
782
- const {
783
- __scopeToast,
784
- type = "foreground",
785
- duration: durationProp,
786
- open,
787
- onClose,
788
- onEscapeKeyDown,
789
- onPause,
790
- onResume,
791
- onSwipeStart,
792
- onSwipeMove,
793
- onSwipeCancel,
794
- onSwipeEnd,
795
- ...toastProps
796
- } = props;
797
- const context = useToastProviderContext(TOAST_NAME, __scopeToast);
798
- const [node, setNode] = React.useState(null);
799
- const composedRefs = useComposedRefs(forwardedRef, (node2) => setNode(node2));
800
- const pointerStartRef = React.useRef(null);
801
- const swipeDeltaRef = React.useRef(null);
802
- const duration = durationProp || context.duration;
803
- const closeTimerStartTimeRef = React.useRef(0);
804
- const closeTimerRemainingTimeRef = React.useRef(duration);
805
- const closeTimerRef = React.useRef(0);
806
- const { onToastAdd, onToastRemove } = context;
807
- const handleClose = useCallbackRef(() => {
808
- var _a;
809
- const isFocusInToast = node == null ? void 0 : node.contains(document.activeElement);
810
- if (isFocusInToast) (_a = context.viewport) == null ? void 0 : _a.focus();
811
- onClose();
812
- });
813
- const startTimer = React.useCallback(
814
- (duration2) => {
815
- if (!duration2 || duration2 === Infinity) return;
816
- window.clearTimeout(closeTimerRef.current);
817
- closeTimerStartTimeRef.current = (/* @__PURE__ */ new Date()).getTime();
818
- closeTimerRef.current = window.setTimeout(handleClose, duration2);
819
- },
820
- [handleClose]
821
- );
822
- React.useEffect(() => {
823
- const viewport = context.viewport;
824
- if (viewport) {
825
- const handleResume = () => {
826
- startTimer(closeTimerRemainingTimeRef.current);
827
- onResume == null ? void 0 : onResume();
828
- };
829
- const handlePause = () => {
830
- const elapsedTime = (/* @__PURE__ */ new Date()).getTime() - closeTimerStartTimeRef.current;
831
- closeTimerRemainingTimeRef.current = closeTimerRemainingTimeRef.current - elapsedTime;
832
- window.clearTimeout(closeTimerRef.current);
833
- onPause == null ? void 0 : onPause();
834
- };
835
- viewport.addEventListener(VIEWPORT_PAUSE, handlePause);
836
- viewport.addEventListener(VIEWPORT_RESUME, handleResume);
837
- return () => {
838
- viewport.removeEventListener(VIEWPORT_PAUSE, handlePause);
839
- viewport.removeEventListener(VIEWPORT_RESUME, handleResume);
840
- };
841
- }
842
- }, [context.viewport, duration, onPause, onResume, startTimer]);
843
- React.useEffect(() => {
844
- if (open && !context.isClosePausedRef.current) startTimer(duration);
845
- }, [open, duration, context.isClosePausedRef, startTimer]);
846
- React.useEffect(() => {
847
- onToastAdd();
848
- return () => onToastRemove();
849
- }, [onToastAdd, onToastRemove]);
850
- const announceTextContent = React.useMemo(() => {
851
- return node ? getAnnounceTextContent(node) : null;
852
- }, [node]);
853
- if (!context.viewport) return null;
854
- return /* @__PURE__ */ jsxs(Fragment, { children: [
855
- announceTextContent && /* @__PURE__ */ jsx(
856
- ToastAnnounce,
857
- {
858
- __scopeToast,
859
- role: "status",
860
- "aria-live": type === "foreground" ? "assertive" : "polite",
861
- children: announceTextContent
862
- }
863
- ),
864
- /* @__PURE__ */ jsx(ToastInteractiveProvider, { scope: __scopeToast, onClose: handleClose, children: ReactDOM.createPortal(
865
- /* @__PURE__ */ jsx(Collection.ItemSlot, { scope: __scopeToast, children: /* @__PURE__ */ jsx(
866
- Root,
867
- {
868
- asChild: true,
869
- onEscapeKeyDown: composeEventHandlers(onEscapeKeyDown, () => {
870
- if (!context.isFocusedToastEscapeKeyDownRef.current) handleClose();
871
- context.isFocusedToastEscapeKeyDownRef.current = false;
872
- }),
873
- children: /* @__PURE__ */ jsx(
874
- Primitive.li,
875
- {
876
- tabIndex: 0,
877
- "data-state": open ? "open" : "closed",
878
- "data-swipe-direction": context.swipeDirection,
879
- ...toastProps,
880
- ref: composedRefs,
881
- style: { userSelect: "none", touchAction: "none", ...props.style },
882
- onKeyDown: composeEventHandlers(props.onKeyDown, (event) => {
883
- if (event.key !== "Escape") return;
884
- onEscapeKeyDown == null ? void 0 : onEscapeKeyDown(event.nativeEvent);
885
- if (!event.nativeEvent.defaultPrevented) {
886
- context.isFocusedToastEscapeKeyDownRef.current = true;
887
- handleClose();
888
- }
889
- }),
890
- onPointerDown: composeEventHandlers(props.onPointerDown, (event) => {
891
- if (event.button !== 0) return;
892
- pointerStartRef.current = { x: event.clientX, y: event.clientY };
893
- }),
894
- onPointerMove: composeEventHandlers(props.onPointerMove, (event) => {
895
- if (!pointerStartRef.current) return;
896
- const x = event.clientX - pointerStartRef.current.x;
897
- const y = event.clientY - pointerStartRef.current.y;
898
- const hasSwipeMoveStarted = Boolean(swipeDeltaRef.current);
899
- const isHorizontalSwipe = ["left", "right"].includes(context.swipeDirection);
900
- const clamp = ["left", "up"].includes(context.swipeDirection) ? Math.min : Math.max;
901
- const clampedX = isHorizontalSwipe ? clamp(0, x) : 0;
902
- const clampedY = !isHorizontalSwipe ? clamp(0, y) : 0;
903
- const moveStartBuffer = event.pointerType === "touch" ? 10 : 2;
904
- const delta = { x: clampedX, y: clampedY };
905
- const eventDetail = { originalEvent: event, delta };
906
- if (hasSwipeMoveStarted) {
907
- swipeDeltaRef.current = delta;
908
- handleAndDispatchCustomEvent(TOAST_SWIPE_MOVE, onSwipeMove, eventDetail, {
909
- discrete: false
910
- });
911
- } else if (isDeltaInDirection(delta, context.swipeDirection, moveStartBuffer)) {
912
- swipeDeltaRef.current = delta;
913
- handleAndDispatchCustomEvent(TOAST_SWIPE_START, onSwipeStart, eventDetail, {
914
- discrete: false
915
- });
916
- event.target.setPointerCapture(event.pointerId);
917
- } else if (Math.abs(x) > moveStartBuffer || Math.abs(y) > moveStartBuffer) {
918
- pointerStartRef.current = null;
919
- }
920
- }),
921
- onPointerUp: composeEventHandlers(props.onPointerUp, (event) => {
922
- const delta = swipeDeltaRef.current;
923
- const target = event.target;
924
- if (target.hasPointerCapture(event.pointerId)) {
925
- target.releasePointerCapture(event.pointerId);
926
- }
927
- swipeDeltaRef.current = null;
928
- pointerStartRef.current = null;
929
- if (delta) {
930
- const toast = event.currentTarget;
931
- const eventDetail = { originalEvent: event, delta };
932
- if (isDeltaInDirection(delta, context.swipeDirection, context.swipeThreshold)) {
933
- handleAndDispatchCustomEvent(TOAST_SWIPE_END, onSwipeEnd, eventDetail, {
934
- discrete: true
935
- });
936
- } else {
937
- handleAndDispatchCustomEvent(
938
- TOAST_SWIPE_CANCEL,
939
- onSwipeCancel,
940
- eventDetail,
941
- {
942
- discrete: true
943
- }
944
- );
945
- }
946
- toast.addEventListener("click", (event2) => event2.preventDefault(), {
947
- once: true
948
- });
949
- }
950
- })
951
- }
952
- )
953
- }
954
- ) }),
955
- context.viewport
956
- ) })
957
- ] });
958
- }
959
- );
960
- var ToastAnnounce = (props) => {
961
- const { __scopeToast, children, ...announceProps } = props;
962
- const context = useToastProviderContext(TOAST_NAME, __scopeToast);
963
- const [renderAnnounceText, setRenderAnnounceText] = React.useState(false);
964
- const [isAnnounced, setIsAnnounced] = React.useState(false);
965
- useNextFrame(() => setRenderAnnounceText(true));
966
- React.useEffect(() => {
967
- const timer = window.setTimeout(() => setIsAnnounced(true), 1e3);
968
- return () => window.clearTimeout(timer);
969
- }, []);
970
- return isAnnounced ? null : /* @__PURE__ */ jsx(Portal, { asChild: true, children: /* @__PURE__ */ jsx(VisuallyHidden, { ...announceProps, children: renderAnnounceText && /* @__PURE__ */ jsxs(Fragment, { children: [
971
- context.label,
972
- " ",
973
- children
974
- ] }) }) });
975
- };
976
- var TITLE_NAME = "ToastTitle";
977
- var ToastTitle = React.forwardRef(
978
- (props, forwardedRef) => {
979
- const { __scopeToast, ...titleProps } = props;
980
- return /* @__PURE__ */ jsx(Primitive.div, { ...titleProps, ref: forwardedRef });
981
- }
982
- );
983
- ToastTitle.displayName = TITLE_NAME;
984
- var DESCRIPTION_NAME = "ToastDescription";
985
- var ToastDescription = React.forwardRef(
986
- (props, forwardedRef) => {
987
- const { __scopeToast, ...descriptionProps } = props;
988
- return /* @__PURE__ */ jsx(Primitive.div, { ...descriptionProps, ref: forwardedRef });
989
- }
990
- );
991
- ToastDescription.displayName = DESCRIPTION_NAME;
992
- var ACTION_NAME = "ToastAction";
993
- var ToastAction = React.forwardRef(
994
- (props, forwardedRef) => {
995
- const { altText, ...actionProps } = props;
996
- if (!altText.trim()) {
997
- console.error(
998
- `Invalid prop \`altText\` supplied to \`${ACTION_NAME}\`. Expected non-empty \`string\`.`
999
- );
1000
- return null;
1001
- }
1002
- return /* @__PURE__ */ jsx(ToastAnnounceExclude, { altText, asChild: true, children: /* @__PURE__ */ jsx(ToastClose, { ...actionProps, ref: forwardedRef }) });
1003
- }
1004
- );
1005
- ToastAction.displayName = ACTION_NAME;
1006
- var CLOSE_NAME = "ToastClose";
1007
- var ToastClose = React.forwardRef(
1008
- (props, forwardedRef) => {
1009
- const { __scopeToast, ...closeProps } = props;
1010
- const interactiveContext = useToastInteractiveContext(CLOSE_NAME, __scopeToast);
1011
- return /* @__PURE__ */ jsx(ToastAnnounceExclude, { asChild: true, children: /* @__PURE__ */ jsx(
1012
- Primitive.button,
1013
- {
1014
- type: "button",
1015
- ...closeProps,
1016
- ref: forwardedRef,
1017
- onClick: composeEventHandlers(props.onClick, interactiveContext.onClose)
1018
- }
1019
- ) });
1020
- }
1021
- );
1022
- ToastClose.displayName = CLOSE_NAME;
1023
- var ToastAnnounceExclude = React.forwardRef((props, forwardedRef) => {
1024
- const { __scopeToast, altText, ...announceExcludeProps } = props;
1025
- return /* @__PURE__ */ jsx(
1026
- Primitive.div,
1027
- {
1028
- "data-radix-toast-announce-exclude": "",
1029
- "data-radix-toast-announce-alt": altText || void 0,
1030
- ...announceExcludeProps,
1031
- ref: forwardedRef
1032
- }
1033
- );
1034
- });
1035
- function getAnnounceTextContent(container) {
1036
- const textContent = [];
1037
- const childNodes = Array.from(container.childNodes);
1038
- childNodes.forEach((node) => {
1039
- if (node.nodeType === node.TEXT_NODE && node.textContent) textContent.push(node.textContent);
1040
- if (isHTMLElement(node)) {
1041
- const isHidden = node.ariaHidden || node.hidden || node.style.display === "none";
1042
- const isExcluded = node.dataset.radixToastAnnounceExclude === "";
1043
- if (!isHidden) {
1044
- if (isExcluded) {
1045
- const altText = node.dataset.radixToastAnnounceAlt;
1046
- if (altText) textContent.push(altText);
1047
- } else {
1048
- textContent.push(...getAnnounceTextContent(node));
1049
- }
1050
- }
1051
- }
1052
- });
1053
- return textContent;
1054
- }
1055
- function handleAndDispatchCustomEvent(name, handler, detail, { discrete }) {
1056
- const currentTarget = detail.originalEvent.currentTarget;
1057
- const event = new CustomEvent(name, { bubbles: true, cancelable: true, detail });
1058
- if (handler) currentTarget.addEventListener(name, handler, { once: true });
1059
- if (discrete) {
1060
- dispatchDiscreteCustomEvent(currentTarget, event);
1061
- } else {
1062
- currentTarget.dispatchEvent(event);
1063
- }
1064
- }
1065
- var isDeltaInDirection = (delta, direction, threshold = 0) => {
1066
- const deltaX = Math.abs(delta.x);
1067
- const deltaY = Math.abs(delta.y);
1068
- const isDeltaX = deltaX > deltaY;
1069
- if (direction === "left" || direction === "right") {
1070
- return isDeltaX && deltaX > threshold;
1071
- } else {
1072
- return !isDeltaX && deltaY > threshold;
1073
- }
1074
- };
1075
- function useNextFrame(callback = () => {
1076
- }) {
1077
- const fn = useCallbackRef(callback);
1078
- useLayoutEffect2(() => {
1079
- let raf1 = 0;
1080
- let raf2 = 0;
1081
- raf1 = window.requestAnimationFrame(() => raf2 = window.requestAnimationFrame(fn));
1082
- return () => {
1083
- window.cancelAnimationFrame(raf1);
1084
- window.cancelAnimationFrame(raf2);
1085
- };
1086
- }, [fn]);
1087
- }
1088
- function isHTMLElement(node) {
1089
- return node.nodeType === node.ELEMENT_NODE;
1090
- }
1091
- function getTabbableCandidates(container) {
1092
- const nodes = [];
1093
- const walker = document.createTreeWalker(container, NodeFilter.SHOW_ELEMENT, {
1094
- acceptNode: (node) => {
1095
- const isHiddenInput = node.tagName === "INPUT" && node.type === "hidden";
1096
- if (node.disabled || node.hidden || isHiddenInput) return NodeFilter.FILTER_SKIP;
1097
- return node.tabIndex >= 0 ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_SKIP;
1098
- }
1099
- });
1100
- while (walker.nextNode()) nodes.push(walker.currentNode);
1101
- return nodes;
1102
- }
1103
- function focusFirst(candidates) {
1104
- const previouslyFocusedElement = document.activeElement;
1105
- return candidates.some((candidate) => {
1106
- if (candidate === previouslyFocusedElement) return true;
1107
- candidate.focus();
1108
- return document.activeElement !== previouslyFocusedElement;
1109
- });
1110
- }
1111
- var Provider = ToastProvider$1;
1112
- var Viewport = ToastViewport$1;
1113
- var Root2 = Toast;
1114
- var Description = ToastDescription;
1115
- function getToastIcon(type) {
1116
- switch (type) {
1117
- case "success":
1118
- return "✓";
1119
- case "error":
1120
- return "✕";
1121
- case "warning":
1122
- return "⚠";
1123
- case "info":
1124
- default:
1125
- return "ℹ";
1126
- }
1127
- }
1128
- function ToastItem({ toast, onOpenChange }) {
1129
- return /* @__PURE__ */ jsxs(
1130
- Root2,
1131
- {
1132
- className: `taskon-toast taskon-toast--${toast.type}`,
1133
- duration: toast.duration ?? 3e3,
1134
- onOpenChange,
1135
- children: [
1136
- /* @__PURE__ */ jsx("div", { className: "taskon-toast-icon", children: getToastIcon(toast.type) }),
1137
- /* @__PURE__ */ jsx(Description, { className: "taskon-toast-message", children: toast.message })
1138
- ]
1139
- }
1140
- );
1141
- }
1142
- function ToastViewport({
1143
- toasts,
1144
- onRemove
1145
- }) {
1146
- return /* @__PURE__ */ jsxs(Fragment, { children: [
1147
- toasts.map((toast) => /* @__PURE__ */ jsx(
1148
- ToastItem,
1149
- {
1150
- toast,
1151
- onOpenChange: (open) => {
1152
- if (!open) {
1153
- onRemove(toast.id);
1154
- }
1155
- }
1156
- },
1157
- toast.id
1158
- )),
1159
- /* @__PURE__ */ jsx(Viewport, { className: "taskon-toast-viewport" })
1160
- ] });
1161
- }
1162
- const ToastProvider = Provider;
1163
- function TaskOnProvider({
1164
- config,
1165
- children,
1166
- preloadLocales
1167
- }) {
1168
- const [userInfo, setUserInfo] = useState(null);
1169
- const [userToken, setUserToken] = useState(null);
1170
- const [chains, setChains] = useState([]);
1171
- const [communityInfo, setCommunityInfo] = useState(null);
1172
- const toastState = useToastState();
1173
- const { locale } = useLocaleManager({
1174
- configLocale: config.locale,
1175
- preloadLocales
1176
- });
1177
- const { client, userApiRef, isInitializing, isSessionReady } = useClientInit({
1178
- apiKey: config.apiKey,
1179
- baseURL: config.baseURL,
1180
- setUserInfo,
1181
- setUserToken
1182
- });
1183
- const { login, logout } = useAuth({
1184
- client,
1185
- userApiRef,
1186
- setUserInfo,
1187
- setUserToken
1188
- });
1189
- const requestLogin = useCallback(() => {
1190
- var _a;
1191
- (_a = config.onRequestLogin) == null ? void 0 : _a.call(config);
1192
- }, [config]);
1193
- const refreshUserInfo = useCallback(async () => {
1194
- const userApi = userApiRef.current;
1195
- if (!userApi) return;
1196
- try {
1197
- const info = await userApi.getInfo();
1198
- setUserInfo(info);
1199
- } catch {
1200
- }
1201
- }, [userApiRef]);
1202
- useEffect(() => {
1203
- if (!client) return;
1204
- const loadChains = async () => {
1205
- try {
1206
- const chainApi = createChainApi(client);
1207
- const chainList = await chainApi.getChainInfo();
1208
- setChains(chainList);
1209
- } catch {
1210
- }
1211
- };
1212
- loadChains();
1213
- }, [client]);
1214
- useEffect(() => {
1215
- if (!client) return;
1216
- const loadCommunityInfo = async () => {
1217
- try {
1218
- const communityTaskApi = createCommunityTaskApi(client);
1219
- const info = await communityTaskApi.getCommunityInfo();
1220
- setCommunityInfo(info);
1221
- } catch {
1222
- }
1223
- };
1224
- loadCommunityInfo();
1225
- }, [client]);
1226
- const contextValue = useMemo(
1227
- () => ({
1228
- config,
1229
- client,
1230
- isInitializing,
1231
- isSessionReady,
1232
- locale,
1233
- userId: (userInfo == null ? void 0 : userInfo.id) ?? null,
1234
- userInfo,
1235
- userToken,
1236
- isLoggedIn: userInfo !== null && userToken !== null,
1237
- login,
1238
- logout,
1239
- requestLogin,
1240
- refreshUserInfo,
1241
- chains,
1242
- communityInfo
1243
- }),
1244
- [config, client, isInitializing, isSessionReady, locale, userInfo, userToken, login, logout, requestLogin, refreshUserInfo, chains, communityInfo]
1245
- );
1246
- return /* @__PURE__ */ jsx(TaskOnContext.Provider, { value: contextValue, children: /* @__PURE__ */ jsx(ToastContext.Provider, { value: toastState, children: /* @__PURE__ */ jsxs(ToastProvider, { children: [
1247
- /* @__PURE__ */ jsx(WalletProvider, { config: config.walletConfig, children }),
1248
- /* @__PURE__ */ jsx(
1249
- ToastViewport,
1250
- {
1251
- toasts: toastState.toasts,
1252
- onRemove: toastState.removeToast
1253
- }
1254
- )
1255
- ] }) }) });
1256
- }
1257
- export {
1258
- TaskOnProvider as T,
1259
- useCommonLocale as u
1260
- };