@blocklet/payment-react 1.18.3 → 1.18.4

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 (43) hide show
  1. package/es/checkout/donate.d.ts +5 -3
  2. package/es/checkout/donate.js +109 -36
  3. package/es/contexts/donate.d.ts +41 -0
  4. package/es/contexts/donate.js +164 -0
  5. package/es/contexts/payment.js +3 -16
  6. package/es/index.d.ts +2 -0
  7. package/es/index.js +2 -0
  8. package/es/libs/cache.d.ts +14 -0
  9. package/es/libs/cache.js +23 -0
  10. package/es/libs/cached-request.d.ts +17 -0
  11. package/es/libs/cached-request.js +79 -0
  12. package/es/libs/util.d.ts +2 -0
  13. package/es/libs/util.js +13 -0
  14. package/es/locales/en.js +8 -1
  15. package/es/locales/zh.js +8 -1
  16. package/es/payment/skeleton/donation.js +1 -1
  17. package/lib/checkout/donate.d.ts +5 -3
  18. package/lib/checkout/donate.js +107 -36
  19. package/lib/contexts/donate.d.ts +41 -0
  20. package/lib/contexts/donate.js +181 -0
  21. package/lib/contexts/payment.js +7 -22
  22. package/lib/index.d.ts +2 -0
  23. package/lib/index.js +24 -0
  24. package/lib/libs/cache.d.ts +14 -0
  25. package/lib/libs/cache.js +29 -0
  26. package/lib/libs/cached-request.d.ts +17 -0
  27. package/lib/libs/cached-request.js +90 -0
  28. package/lib/libs/util.d.ts +2 -0
  29. package/lib/libs/util.js +12 -0
  30. package/lib/locales/en.js +8 -1
  31. package/lib/locales/zh.js +8 -1
  32. package/lib/payment/skeleton/donation.js +1 -1
  33. package/package.json +6 -6
  34. package/src/checkout/donate.tsx +135 -45
  35. package/src/contexts/donate.tsx +226 -0
  36. package/src/contexts/payment.tsx +5 -20
  37. package/src/index.ts +2 -0
  38. package/src/libs/cache.ts +33 -0
  39. package/src/libs/cached-request.ts +103 -0
  40. package/src/libs/util.ts +15 -0
  41. package/src/locales/en.tsx +7 -0
  42. package/src/locales/zh.tsx +7 -0
  43. package/src/payment/skeleton/donation.tsx +1 -1
@@ -0,0 +1,79 @@
1
+ import { globalCache } from "./cache.js";
2
+ export class CachedRequest {
3
+ cacheKey;
4
+ fetchData;
5
+ options;
6
+ constructor(cacheKey, fetchData, options = {}) {
7
+ this.cacheKey = cacheKey;
8
+ this.fetchData = fetchData;
9
+ this.options = {
10
+ strategy: "session",
11
+ ttl: 0,
12
+ ...options
13
+ };
14
+ }
15
+ getCache() {
16
+ const { strategy } = this.options;
17
+ switch (strategy) {
18
+ case "local":
19
+ return localStorage;
20
+ case "memory":
21
+ return globalCache;
22
+ case "session":
23
+ default:
24
+ return sessionStorage;
25
+ }
26
+ }
27
+ getCachedData() {
28
+ const cache = this.getCache();
29
+ const data = this.options.strategy === "memory" ? cache.get(this.cacheKey) : cache.getItem(this.cacheKey);
30
+ if (!data)
31
+ return null;
32
+ const parsed = JSON.parse(data);
33
+ if (this.options.ttl && parsed.timestamp) {
34
+ const isExpired = Date.now() - parsed.timestamp > this.options.ttl;
35
+ if (isExpired) {
36
+ this.clearCache();
37
+ return null;
38
+ }
39
+ }
40
+ return parsed.data;
41
+ }
42
+ setCachedData(data) {
43
+ const cache = this.getCache();
44
+ const value = JSON.stringify({
45
+ data,
46
+ timestamp: Date.now()
47
+ });
48
+ if (this.options.strategy === "memory") {
49
+ cache.set(this.cacheKey, value);
50
+ } else {
51
+ cache.setItem(this.cacheKey, value);
52
+ }
53
+ }
54
+ clearCache() {
55
+ const cache = this.getCache();
56
+ if (this.options.strategy === "memory") {
57
+ cache.delete(this.cacheKey);
58
+ } else {
59
+ cache.removeItem(this.cacheKey);
60
+ }
61
+ }
62
+ fetch(forceRefresh = false) {
63
+ const cachedData = !forceRefresh && this.getCachedData();
64
+ if (cachedData)
65
+ return Promise.resolve(cachedData);
66
+ const globalItem = globalCache.get(this.cacheKey);
67
+ if (globalItem?.promise) {
68
+ return globalItem.promise;
69
+ }
70
+ const newPromise = this.fetchData().then(({ data }) => {
71
+ this.setCachedData(data);
72
+ return data;
73
+ }).finally(() => {
74
+ globalCache.delete(this.cacheKey);
75
+ });
76
+ globalCache.set(this.cacheKey, { promise: newPromise });
77
+ return newPromise;
78
+ }
79
+ }
package/es/libs/util.d.ts CHANGED
@@ -111,3 +111,5 @@ export declare function getInvoiceDescriptionAndReason(invoice: TInvoiceExpanded
111
111
  reason: string;
112
112
  type: string;
113
113
  };
114
+ export declare function getPaymentKitComponent(): any;
115
+ export declare function openDonationSettings(openInNewTab?: boolean): void;
package/es/libs/util.js CHANGED
@@ -913,3 +913,16 @@ export function getInvoiceDescriptionAndReason(invoice, locale = "en") {
913
913
  type: invoiceType
914
914
  };
915
915
  }
916
+ export function getPaymentKitComponent() {
917
+ const paymentKit = window.blocklet?.componentMountPoints?.find((c) => c.did === PAYMENT_KIT_DID);
918
+ return paymentKit || null;
919
+ }
920
+ export function openDonationSettings(openInNewTab = false) {
921
+ const paymentKit = getPaymentKitComponent();
922
+ if (paymentKit) {
923
+ window.open(
924
+ `${window.location.origin}${paymentKit.mountPoint === "/" ? "" : paymentKit.mountPoint}/integrations/donations`,
925
+ openInNewTab ? "_blank" : "_self"
926
+ );
927
+ }
928
+ }
package/es/locales/en.js CHANGED
@@ -134,7 +134,14 @@ export default flat({
134
134
  one: "{name} will receive all tips",
135
135
  multiple: "Tips will be distributed to {count} beneficiaries",
136
136
  view: "Click to view details"
137
- }
137
+ },
138
+ inactive: "Donation feature is not enabled",
139
+ enable: "Enable Donation",
140
+ enableSuccess: "Enable Success",
141
+ configPrompt: "Donation feature is enabled, you can configure donation options in Payment Kit",
142
+ configNow: "Configure Now",
143
+ later: "Configure Later",
144
+ configTip: "Configure donation settings in Payment Kit"
138
145
  },
139
146
  cardPay: "{action} with card",
140
147
  empty: "No thing to pay",
package/es/locales/zh.js CHANGED
@@ -134,7 +134,14 @@ export default flat({
134
134
  one: "{name} \u5C06\u83B7\u5F97\u5168\u90E8\u6253\u8D4F",
135
135
  multiple: "\u6253\u8D4F\u5C06\u6309\u6BD4\u4F8B\u5206\u914D\u7ED9 {count} \u4F4D\u53D7\u76CA\u4EBA",
136
136
  view: "\u70B9\u51FB\u67E5\u770B\u8BE6\u60C5"
137
- }
137
+ },
138
+ inactive: "\u6253\u8D4F\u529F\u80FD\u6682\u672A\u5F00\u542F",
139
+ enable: "\u542F\u7528\u6253\u8D4F",
140
+ enableSuccess: "\u542F\u7528\u6210\u529F",
141
+ configPrompt: "\u6253\u8D4F\u529F\u80FD\u5DF2\u542F\u7528\uFF0C\u60A8\u53EF\u4EE5\u524D\u5F80 Payment Kit \u8FDB\u4E00\u6B65\u914D\u7F6E\u6253\u8D4F\u9009\u9879",
142
+ configNow: "\u7ACB\u5373\u914D\u7F6E",
143
+ later: "\u7A0D\u540E\u914D\u7F6E",
144
+ configTip: "\u524D\u5F80 Payment Kit \u914D\u7F6E\u6253\u8D4F\u9009\u9879"
138
145
  },
139
146
  cardPay: "\u4F7F\u7528\u5361\u7247{action}",
140
147
  empty: "\u6CA1\u6709\u53EF\u652F\u4ED8\u7684\u9879\u76EE",
@@ -3,7 +3,7 @@ import { Box, Divider, Fade, Skeleton, Stack } from "@mui/material";
3
3
  export default function DonationSkeleton() {
4
4
  return /* @__PURE__ */ jsx(Fade, { in: true, children: /* @__PURE__ */ jsxs(Stack, { direction: "column", children: [
5
5
  /* @__PURE__ */ jsx(Skeleton, { variant: "text", sx: { fontSize: "2rem", width: "40%" } }),
6
- /* @__PURE__ */ jsx(Skeleton, { sx: { mt: 2 }, variant: "rounded", height: 80 }),
6
+ /* @__PURE__ */ jsx(Skeleton, { sx: { mt: 2 }, variant: "rounded", height: 40 }),
7
7
  /* @__PURE__ */ jsx(
8
8
  Divider,
9
9
  {
@@ -7,12 +7,14 @@ export type DonateHistory = {
7
7
  method: TPaymentMethod;
8
8
  totalAmount: string;
9
9
  };
10
+ export type RequiredDonationSettings = Pick<DonationSettings, 'target' | 'title' | 'description' | 'reference' | 'beneficiaries'>;
11
+ type OptionalDonationSettings = Partial<Omit<DonationSettings, keyof RequiredDonationSettings>>;
10
12
  export interface ButtonType extends Omit<MUIButtonProps, 'text' | 'icon'> {
11
- text: string | React.ReactNode;
13
+ text?: string | React.ReactNode;
12
14
  icon: React.ReactNode;
13
15
  }
14
16
  export type DonateProps = Pick<CheckoutProps, 'onPaid' | 'onError'> & {
15
- settings: DonationSettings;
17
+ settings: RequiredDonationSettings & OptionalDonationSettings;
16
18
  livemode?: boolean;
17
19
  timeout?: number;
18
20
  mode?: 'inline' | 'default' | 'custom';
@@ -20,7 +22,7 @@ export type DonateProps = Pick<CheckoutProps, 'onPaid' | 'onError'> & {
20
22
  button?: ButtonType;
21
23
  };
22
24
  theme?: 'default' | 'inherit' | PaymentThemeOptions;
23
- children?: (openDialog: () => void, donateTotalAmount: string, supporters: DonateHistory, loading?: boolean) => React.ReactNode;
25
+ children?: (openDialog: () => void, donateTotalAmount: string, supporters: DonateHistory, loading?: boolean, donateSettings?: DonationSettings) => React.ReactNode;
24
26
  };
25
27
  declare function CheckoutDonate(props: DonateProps): import("react").JSX.Element;
26
28
  declare namespace CheckoutDonate {
@@ -12,6 +12,7 @@ var _ahooks = require("ahooks");
12
12
  var _omit = _interopRequireDefault(require("lodash/omit"));
13
13
  var _unionBy = _interopRequireDefault(require("lodash/unionBy"));
14
14
  var _react = require("react");
15
+ var _iconsMaterial = require("@mui/icons-material");
15
16
  var _tx = _interopRequireDefault(require("../components/blockchain/tx"));
16
17
  var _api = _interopRequireDefault(require("../libs/api"));
17
18
  var _util = require("../libs/util");
@@ -20,6 +21,7 @@ var _theme = require("../theme");
20
21
  var _payment = require("../contexts/payment");
21
22
  var _livemode = _interopRequireDefault(require("../components/livemode"));
22
23
  var _mobile = require("../hooks/mobile");
24
+ var _donate = require("../contexts/donate");
23
25
  function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
24
26
  const donationCache = {};
25
27
  const createOrUpdateDonation = (settings, livemode = true) => {
@@ -256,13 +258,43 @@ function SupporterSimple({
256
258
  })]
257
259
  });
258
260
  }
261
+ const defaultDonateAmount = {
262
+ presets: ["1", "5", "10"],
263
+ preset: "1",
264
+ minimum: "0.01",
265
+ maximum: "100",
266
+ custom: true
267
+ };
259
268
  function useDonation(settings, livemode, mode = "default") {
260
269
  const [state, setState] = (0, _ahooks.useSetState)({
261
270
  open: false,
262
271
  supporterLoaded: false,
263
272
  exist: false
264
273
  });
265
- const donation = (0, _ahooks.useRequest)(() => createOrUpdateDonation(settings, livemode), {
274
+ const donateContext = (0, _donate.useDonateContext)();
275
+ const {
276
+ isMobile
277
+ } = (0, _mobile.useMobile)();
278
+ const {
279
+ settings: donateConfig = {}
280
+ } = donateContext || {};
281
+ const donateSettings = {
282
+ ...settings,
283
+ amount: settings.amount || donateConfig?.settings?.amount || defaultDonateAmount,
284
+ appearance: {
285
+ button: {
286
+ ...(settings?.appearance?.button || {}),
287
+ text: settings?.appearance?.button?.text || donateConfig?.settings?.btnText || "Donate",
288
+ icon: settings?.appearance?.button?.icon || donateConfig?.settings?.icon || null
289
+ },
290
+ history: {
291
+ variant: settings?.appearance?.history?.variant || donateConfig?.settings?.historyType || "avatar"
292
+ }
293
+ }
294
+ };
295
+ const hasRequestedRef = (0, _react.useRef)(false);
296
+ const containerRef = (0, _react.useRef)(null);
297
+ const donation = (0, _ahooks.useRequest)(() => createOrUpdateDonation(donateSettings, livemode), {
266
298
  manual: true,
267
299
  loadingDelay: 300
268
300
  });
@@ -270,14 +302,26 @@ function useDonation(settings, livemode, mode = "default") {
270
302
  manual: true,
271
303
  loadingDelay: 300
272
304
  });
273
- (0, _ahooks.useMount)(() => {
274
- if (mode !== "inline") {
275
- (0, _util.lazyLoad)(() => {
276
- donation.run();
277
- supporters.run();
278
- });
279
- }
280
- });
305
+ const rootMargin = isMobile ? "50px" : `${Math.min(window.innerHeight / 2, 300)}px`;
306
+ (0, _react.useEffect)(() => {
307
+ if (mode === "inline") return;
308
+ const element = containerRef.current;
309
+ if (!element) return;
310
+ const observer = new IntersectionObserver(([entry]) => {
311
+ if (entry.isIntersecting && !hasRequestedRef.current) {
312
+ hasRequestedRef.current = true;
313
+ (0, _util.lazyLoad)(() => {
314
+ donation.run();
315
+ supporters.run();
316
+ });
317
+ }
318
+ }, {
319
+ threshold: 0,
320
+ rootMargin
321
+ });
322
+ observer.observe(element);
323
+ return () => observer.unobserve(element);
324
+ }, [mode]);
281
325
  (0, _react.useEffect)(() => {
282
326
  if (donation.data && state.supporterLoaded === false) {
283
327
  setState({
@@ -287,10 +331,13 @@ function useDonation(settings, livemode, mode = "default") {
287
331
  }
288
332
  }, [donation.data]);
289
333
  return {
334
+ containerRef,
290
335
  donation,
291
336
  supporters,
292
337
  state,
293
- setState
338
+ setState,
339
+ donateSettings,
340
+ supportUpdateSettings: !!donateContext
294
341
  };
295
342
  }
296
343
  function CheckoutDonateInner({
@@ -305,10 +352,13 @@ function CheckoutDonateInner({
305
352
  children
306
353
  }) {
307
354
  const {
355
+ containerRef,
308
356
  state,
309
357
  setState,
310
358
  donation,
311
- supporters
359
+ supporters,
360
+ donateSettings,
361
+ supportUpdateSettings
312
362
  } = useDonation(settings, livemode, mode);
313
363
  const customers = (0, _unionBy.default)(supporters?.data?.supporters || [], "customer_did");
314
364
  const {
@@ -320,7 +370,8 @@ function CheckoutDonateInner({
320
370
  isMobile
321
371
  } = (0, _mobile.useMobile)();
322
372
  const {
323
- connect
373
+ connect,
374
+ session
324
375
  } = (0, _payment.usePaymentContext)();
325
376
  const handlePaid = (...args) => {
326
377
  if (onPaid) {
@@ -353,23 +404,24 @@ function CheckoutDonateInner({
353
404
  open: true
354
405
  });
355
406
  };
407
+ const inlineText = inlineOptions?.button?.text || donateSettings.appearance.button.text;
356
408
  const inlineRender = /* @__PURE__ */(0, _jsxRuntime.jsxs)(_jsxRuntime.Fragment, {
357
409
  children: [/* @__PURE__ */(0, _jsxRuntime.jsx)(_material.Button, {
358
- size: settings.appearance?.button?.size || "medium",
359
- color: settings.appearance?.button?.color || "primary",
360
- variant: settings.appearance?.button?.variant || "contained",
361
- ...settings.appearance?.button,
410
+ size: donateSettings.appearance?.button?.size || "medium",
411
+ color: donateSettings.appearance?.button?.color || "primary",
412
+ variant: donateSettings.appearance?.button?.variant || "contained",
413
+ ...donateSettings.appearance?.button,
362
414
  onClick: handlePopoverOpen,
363
415
  children: /* @__PURE__ */(0, _jsxRuntime.jsxs)(_material.Stack, {
364
416
  direction: "row",
365
417
  alignItems: "center",
366
418
  spacing: 0.5,
367
- children: [settings.appearance.button.icon, typeof settings.appearance.button.text === "string" ? /* @__PURE__ */(0, _jsxRuntime.jsx)(_material.Typography, {
419
+ children: [donateSettings.appearance.button.icon, typeof donateSettings.appearance.button.text === "string" ? /* @__PURE__ */(0, _jsxRuntime.jsx)(_material.Typography, {
368
420
  sx: {
369
421
  whiteSpace: "nowrap"
370
422
  },
371
- children: settings.appearance.button.text
372
- }) : settings.appearance.button.text]
423
+ children: donateSettings.appearance.button.text
424
+ }) : donateSettings.appearance.button.text]
373
425
  })
374
426
  }), /* @__PURE__ */(0, _jsxRuntime.jsx)(_material.Popover, {
375
427
  id: "mouse-over-popper",
@@ -414,12 +466,12 @@ function CheckoutDonateInner({
414
466
  direction: "row",
415
467
  alignItems: "center",
416
468
  spacing: 0.5,
417
- children: [inlineOptions?.button?.icon, typeof inlineOptions?.button?.text === "string" ? /* @__PURE__ */(0, _jsxRuntime.jsx)(_material.Typography, {
469
+ children: [inlineOptions?.button?.icon, typeof inlineText === "string" ? /* @__PURE__ */(0, _jsxRuntime.jsx)(_material.Typography, {
418
470
  sx: {
419
471
  whiteSpace: "nowrap"
420
472
  },
421
- children: inlineOptions?.button?.text
422
- }) : inlineOptions?.button?.text]
473
+ children: inlineText
474
+ }) : inlineText]
423
475
  })
424
476
  }), /* @__PURE__ */(0, _jsxRuntime.jsx)(SupporterSimple, {
425
477
  ...supporters.data
@@ -442,22 +494,22 @@ function CheckoutDonateInner({
442
494
  sm: 2
443
495
  },
444
496
  children: [/* @__PURE__ */(0, _jsxRuntime.jsx)(_material.Button, {
445
- size: settings.appearance?.button?.size || "medium",
446
- color: settings.appearance?.button?.color || "primary",
447
- variant: settings.appearance?.button?.variant || "contained",
448
- ...settings.appearance?.button,
497
+ size: donateSettings.appearance?.button?.size || "medium",
498
+ color: donateSettings.appearance?.button?.color || "primary",
499
+ variant: donateSettings.appearance?.button?.variant || "contained",
500
+ ...donateSettings.appearance?.button,
449
501
  onClick: () => startDonate(),
450
502
  children: /* @__PURE__ */(0, _jsxRuntime.jsxs)(_material.Stack, {
451
503
  direction: "row",
452
504
  alignItems: "center",
453
505
  spacing: 0.5,
454
- children: [settings.appearance.button.icon, typeof settings.appearance.button.text === "string" ? /* @__PURE__ */(0, _jsxRuntime.jsx)(_material.Typography, {
455
- children: settings.appearance.button.text
456
- }) : settings.appearance.button.text]
506
+ children: [donateSettings.appearance.button.icon, typeof donateSettings.appearance.button.text === "string" ? /* @__PURE__ */(0, _jsxRuntime.jsx)(_material.Typography, {
507
+ children: donateSettings.appearance.button.text
508
+ }) : donateSettings.appearance.button.text]
457
509
  })
458
- }), supporters.data && settings.appearance.history.variant === "avatar" && /* @__PURE__ */(0, _jsxRuntime.jsx)(SupporterAvatar, {
510
+ }), supporters.data && donateSettings.appearance.history.variant === "avatar" && /* @__PURE__ */(0, _jsxRuntime.jsx)(SupporterAvatar, {
459
511
  ...supporters.data
460
- }), supporters.data && settings.appearance.history.variant === "table" && /* @__PURE__ */(0, _jsxRuntime.jsx)(SupporterTable, {
512
+ }), supporters.data && donateSettings.appearance.history.variant === "table" && /* @__PURE__ */(0, _jsxRuntime.jsx)(SupporterTable, {
461
513
  ...supporters.data
462
514
  })]
463
515
  });
@@ -467,7 +519,7 @@ function CheckoutDonateInner({
467
519
  }
468
520
  if (mode === "custom") {
469
521
  return children && typeof children === "function" ? /* @__PURE__ */(0, _jsxRuntime.jsx)(_jsxRuntime.Fragment, {
470
- children: children(startDonate, `${(0, _util.formatAmount)(supporters.data?.totalAmount || "0", supporters.data?.currency?.decimal)} ${supporters.data?.currency?.symbol}`, supporters.data || {}, !!supporters.loading)
522
+ children: children(startDonate, `${(0, _util.formatAmount)(supporters.data?.totalAmount || "0", supporters.data?.currency?.decimal)} ${supporters.data?.currency?.symbol}`, supporters.data || {}, !!supporters.loading, donateSettings)
471
523
  }) : /* @__PURE__ */(0, _jsxRuntime.jsxs)(_material.Typography, {
472
524
  children: ["Please provide a valid render function ", /* @__PURE__ */(0, _jsxRuntime.jsx)("pre", {
473
525
  children: "(openDonate, donateTotalAmount, supporters) => ReactNode"
@@ -476,7 +528,9 @@ function CheckoutDonateInner({
476
528
  }
477
529
  return defaultRender;
478
530
  };
479
- return /* @__PURE__ */(0, _jsxRuntime.jsxs)(_jsxRuntime.Fragment, {
531
+ const isAdmin = ["owner", "admin"].includes(session?.user?.role);
532
+ return /* @__PURE__ */(0, _jsxRuntime.jsxs)("div", {
533
+ ref: containerRef,
480
534
  children: [renderInnerView(), donation.data && /* @__PURE__ */(0, _jsxRuntime.jsx)(_Dialog.default, {
481
535
  open: state.open,
482
536
  title: /* @__PURE__ */(0, _jsxRuntime.jsxs)(_material.Box, {
@@ -490,10 +544,27 @@ function CheckoutDonateInner({
490
544
  textOverflow: "ellipsis",
491
545
  overflow: "hidden"
492
546
  },
493
- children: settings.title
547
+ children: donateSettings.title
548
+ }), supportUpdateSettings && isAdmin && /* @__PURE__ */(0, _jsxRuntime.jsx)(_material.Tooltip, {
549
+ title: t("payment.checkout.donation.configTip"),
550
+ placement: "bottom",
551
+ children: /* @__PURE__ */(0, _jsxRuntime.jsx)(_material.IconButton, {
552
+ size: "small",
553
+ onClick: e => {
554
+ e.stopPropagation();
555
+ (0, _util.openDonationSettings)(true);
556
+ },
557
+ children: /* @__PURE__ */(0, _jsxRuntime.jsx)(_iconsMaterial.Settings, {
558
+ fontSize: "small",
559
+ sx: {
560
+ ml: -0.5
561
+ }
562
+ })
563
+ })
494
564
  }), !donation.data.livemode && /* @__PURE__ */(0, _jsxRuntime.jsx)(_livemode.default, {
495
565
  sx: {
496
- width: "fit-content"
566
+ width: "fit-content",
567
+ ml: 0.5
497
568
  }
498
569
  })]
499
570
  }),
@@ -551,7 +622,7 @@ function CheckoutDonateInner({
551
622
  id: donation.data?.id,
552
623
  onPaid: handlePaid,
553
624
  onError,
554
- action: settings.appearance?.button?.text,
625
+ action: donateSettings.appearance?.button?.text,
555
626
  mode: "inline",
556
627
  theme,
557
628
  formType: "donation",
@@ -0,0 +1,41 @@
1
+ import type { TSetting } from '@blocklet/payment-types';
2
+ import type { Axios } from 'axios';
3
+ export interface DonateConfigSettings {
4
+ amount?: {
5
+ presets?: string[];
6
+ preset?: string;
7
+ custom: boolean;
8
+ minimum?: string;
9
+ maximum?: string;
10
+ };
11
+ btnText?: string;
12
+ historyType?: 'table' | 'avatar';
13
+ }
14
+ export type DonateContextType = {
15
+ settings: TSetting;
16
+ refresh: (forceRefresh?: boolean) => void;
17
+ updateSettings: (newSettings: DonateConfigSettings) => Promise<void>;
18
+ api: Axios;
19
+ };
20
+ export type DonateContextProps = {
21
+ mountLocation: string;
22
+ description: string;
23
+ defaultSettings?: DonateConfigSettings;
24
+ children: any;
25
+ active?: boolean;
26
+ enableDonate?: boolean;
27
+ };
28
+ declare const DonateContext: import("react").Context<DonateContextType>;
29
+ declare const Consumer: import("react").Consumer<DonateContextType>;
30
+ declare function DonateProvider({ mountLocation, description, defaultSettings, children, active, enableDonate, }: DonateContextProps): import("react").JSX.Element | null;
31
+ declare namespace DonateProvider {
32
+ var defaultProps: {
33
+ defaultSettings: {};
34
+ active: boolean;
35
+ enableDonate: boolean;
36
+ };
37
+ }
38
+ declare function useDonateContext(): DonateContextType;
39
+ export declare const clearDonateCache: (mountLocation: string) => void;
40
+ export declare const clearDonateSettings: (mountLocation: string) => Promise<void>;
41
+ export { DonateContext, DonateProvider, Consumer as DonateConsumer, useDonateContext };
@@ -0,0 +1,181 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.DonateContext = exports.DonateConsumer = void 0;
7
+ exports.DonateProvider = DonateProvider;
8
+ exports.clearDonateSettings = exports.clearDonateCache = void 0;
9
+ exports.useDonateContext = useDonateContext;
10
+ var _jsxRuntime = require("react/jsx-runtime");
11
+ var _ahooks = require("ahooks");
12
+ var _react = require("react");
13
+ var _Toast = _interopRequireDefault(require("@arcblock/ux/lib/Toast"));
14
+ var _context = require("@arcblock/ux/lib/Locale/context");
15
+ var _material = require("@mui/material");
16
+ var _api = _interopRequireDefault(require("../libs/api"));
17
+ var _util = require("../libs/util");
18
+ var _cachedRequest = require("../libs/cached-request");
19
+ var _confirm = _interopRequireDefault(require("../components/confirm"));
20
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
21
+ const DonateContext = exports.DonateContext = (0, _react.createContext)({
22
+ api: _api.default
23
+ });
24
+ const {
25
+ Provider,
26
+ Consumer
27
+ } = DonateContext;
28
+ exports.DonateConsumer = Consumer;
29
+ const fetchDonateSetting = (params, forceRefresh = false) => {
30
+ const livemode = localStorage.getItem("livemode") !== "false";
31
+ const cacheKey = `donate-settings-${params.mountLocation}-${livemode}`;
32
+ const cachedRequest = new _cachedRequest.CachedRequest(cacheKey, () => _api.default.post("/api/settings", {
33
+ ...params,
34
+ type: "donate",
35
+ livemode,
36
+ settings: params.defaultSettings
37
+ }), {
38
+ ttl: 1e3 * 60 * 60,
39
+ strategy: "local"
40
+ });
41
+ return cachedRequest.fetch(forceRefresh);
42
+ };
43
+ function DonateProvider({
44
+ mountLocation,
45
+ description,
46
+ defaultSettings = {},
47
+ children,
48
+ active = true,
49
+ enableDonate = false
50
+ }) {
51
+ const {
52
+ t
53
+ } = (0, _context.useLocaleContext)();
54
+ const [showConfirm, setShowConfirm] = (0, _react.useState)(false);
55
+ const {
56
+ data = {
57
+ settings: {},
58
+ active: true
59
+ },
60
+ error,
61
+ run,
62
+ loading
63
+ } = (0, _ahooks.useRequest)(forceRender => fetchDonateSetting({
64
+ mountLocation,
65
+ description,
66
+ defaultSettings,
67
+ active,
68
+ componentDid: window.blocklet?.componentId?.split("/").pop()
69
+ }, forceRender), {
70
+ refreshDeps: [mountLocation],
71
+ onError: err => {
72
+ _Toast.default.error((0, _util.formatError)(err));
73
+ }
74
+ });
75
+ const updateSettings = async newSettings => {
76
+ try {
77
+ const livemode = localStorage.getItem("livemode") !== "false";
78
+ await _api.default.put(`/api/settings/${mountLocation}`, {
79
+ livemode,
80
+ settings: newSettings
81
+ });
82
+ run(true);
83
+ _Toast.default.success(t("common.saved"));
84
+ } catch (err) {
85
+ _Toast.default.error((0, _util.formatError)(err));
86
+ throw err;
87
+ }
88
+ };
89
+ const supportPaymentKit = (0, _util.getPaymentKitComponent)();
90
+ const handleEnable = async () => {
91
+ if (!enableDonate || !data || data?.active) return;
92
+ try {
93
+ await _api.default.put(`/api/settings/${data.id}`, {
94
+ active: true
95
+ });
96
+ if (supportPaymentKit) {
97
+ setShowConfirm(true);
98
+ } else {
99
+ _Toast.default.success(t("payment.checkout.donation.enableSuccess"));
100
+ run(true);
101
+ }
102
+ } catch (err) {
103
+ _Toast.default.error((0, _util.formatError)(err));
104
+ }
105
+ };
106
+ if (loading || error) {
107
+ return null;
108
+ }
109
+ return /* @__PURE__ */(0, _jsxRuntime.jsx)(Provider, {
110
+ value: {
111
+ settings: data,
112
+ refresh: run,
113
+ updateSettings,
114
+ api: _api.default
115
+ },
116
+ children: data?.active === false ? /* @__PURE__ */(0, _jsxRuntime.jsxs)(_jsxRuntime.Fragment, {
117
+ children: [enableDonate && /* @__PURE__ */(0, _jsxRuntime.jsxs)(_material.Stack, {
118
+ spacing: 1,
119
+ sx: {
120
+ p: 2,
121
+ bgcolor: "background.neutral",
122
+ borderRadius: 1
123
+ },
124
+ children: [/* @__PURE__ */(0, _jsxRuntime.jsx)(_material.Typography, {
125
+ color: "text.secondary",
126
+ children: t("payment.checkout.donation.inactive")
127
+ }), /* @__PURE__ */(0, _jsxRuntime.jsx)(_material.Button, {
128
+ size: "small",
129
+ variant: "outlined",
130
+ color: "primary",
131
+ onClick: handleEnable,
132
+ children: t("payment.checkout.donation.enable")
133
+ })]
134
+ }), showConfirm && /* @__PURE__ */(0, _jsxRuntime.jsx)(_confirm.default, {
135
+ title: t("payment.checkout.donation.enableSuccess"),
136
+ message: t("payment.checkout.donation.configPrompt"),
137
+ cancel: t("payment.checkout.donation.later"),
138
+ confirm: t("payment.checkout.donation.configNow"),
139
+ onCancel: () => {
140
+ setShowConfirm(false);
141
+ run(true);
142
+ },
143
+ color: "primary",
144
+ onConfirm: () => {
145
+ run(true);
146
+ (0, _util.openDonationSettings)(false);
147
+ setShowConfirm(false);
148
+ }
149
+ })]
150
+ }) : children
151
+ });
152
+ }
153
+ function useDonateContext() {
154
+ const context = (0, _react.useContext)(DonateContext);
155
+ return context;
156
+ }
157
+ DonateProvider.defaultProps = {
158
+ defaultSettings: {},
159
+ active: true,
160
+ enableDonate: false
161
+ };
162
+ const clearDonateCache = mountLocation => {
163
+ const livemode = localStorage.getItem("livemode") !== "false";
164
+ const cacheKey = `donate-settings-${mountLocation}-${livemode}`;
165
+ localStorage.removeItem(cacheKey);
166
+ };
167
+ exports.clearDonateCache = clearDonateCache;
168
+ const clearDonateSettings = async mountLocation => {
169
+ try {
170
+ const livemode = localStorage.getItem("livemode") !== "false";
171
+ await _api.default.delete(`/api/settings/${mountLocation}`, {
172
+ params: {
173
+ livemode
174
+ }
175
+ });
176
+ clearDonateCache(mountLocation);
177
+ } catch (err) {
178
+ _Toast.default.error((0, _util.formatError)(err));
179
+ }
180
+ };
181
+ exports.clearDonateSettings = clearDonateSettings;