@shopbb/helium 0.2.0 → 0.3.0-alpha.1

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 (36) hide show
  1. package/dist/components/AddToCartButton.d.ts +41 -0
  2. package/dist/components/AddToCartButton.d.ts.map +1 -0
  3. package/dist/components/AddToCartButton.js +51 -0
  4. package/dist/components/AddToCartButton.js.map +1 -0
  5. package/dist/components/CartLineQuantityAdjustButton.d.ts +40 -0
  6. package/dist/components/CartLineQuantityAdjustButton.d.ts.map +1 -0
  7. package/dist/components/CartLineQuantityAdjustButton.js +58 -0
  8. package/dist/components/CartLineQuantityAdjustButton.js.map +1 -0
  9. package/dist/components/Image.d.ts +39 -0
  10. package/dist/components/Image.d.ts.map +1 -0
  11. package/dist/components/Image.js +28 -0
  12. package/dist/components/Image.js.map +1 -0
  13. package/dist/components/Money.d.ts +41 -0
  14. package/dist/components/Money.d.ts.map +1 -0
  15. package/dist/components/Money.js +48 -0
  16. package/dist/components/Money.js.map +1 -0
  17. package/dist/components/ProductPrice.d.ts +28 -0
  18. package/dist/components/ProductPrice.d.ts.map +1 -0
  19. package/dist/components/ProductPrice.js +10 -0
  20. package/dist/components/ProductPrice.js.map +1 -0
  21. package/dist/components/VariantSelector.d.ts +80 -0
  22. package/dist/components/VariantSelector.d.ts.map +1 -0
  23. package/dist/components/VariantSelector.js +87 -0
  24. package/dist/components/VariantSelector.js.map +1 -0
  25. package/dist/components/index.d.ts +24 -0
  26. package/dist/components/index.d.ts.map +1 -0
  27. package/dist/components/index.js +18 -0
  28. package/dist/components/index.js.map +1 -0
  29. package/package.json +12 -4
  30. package/src/components/AddToCartButton.tsx +90 -0
  31. package/src/components/CartLineQuantityAdjustButton.tsx +119 -0
  32. package/src/components/Image.tsx +93 -0
  33. package/src/components/Money.tsx +106 -0
  34. package/src/components/ProductPrice.tsx +61 -0
  35. package/src/components/VariantSelector.tsx +148 -0
  36. package/src/components/index.ts +33 -0
@@ -0,0 +1,24 @@
1
+ /**
2
+ * @shopbb/helium/components — 商家用 React 组件
3
+ *
4
+ * 用法:
5
+ * import { Money, Image, ProductPrice, AddToCartButton } from '@shopbb/helium/components';
6
+ *
7
+ * 设计原则:
8
+ * - 无样式:组件只管行为 + 语义化 DOM,样式商家自己写
9
+ * - data-* 钩子:方便选择器
10
+ * - 对齐 Shopify Hydrogen 同名组件的 API,迁移成本低
11
+ */
12
+ export { Money } from './Money';
13
+ export type { MoneyProps, MoneyData, MoneyMeasurement } from './Money';
14
+ export { Image } from './Image';
15
+ export type { ImageProps, ImageData } from './Image';
16
+ export { ProductPrice } from './ProductPrice';
17
+ export type { ProductPriceProps } from './ProductPrice';
18
+ export { AddToCartButton } from './AddToCartButton';
19
+ export type { AddToCartButtonProps } from './AddToCartButton';
20
+ export { CartLineQuantityAdjustButton } from './CartLineQuantityAdjustButton';
21
+ export type { CartLineQuantityAdjustButtonProps } from './CartLineQuantityAdjustButton';
22
+ export { VariantSelector } from './VariantSelector';
23
+ export type { VariantSelectorProps, VariantSelectorRenderProps, VariantOption, } from './VariantSelector';
24
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/components/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,EAAE,KAAK,EAAE,MAAM,SAAS,CAAC;AAChC,YAAY,EAAE,UAAU,EAAE,SAAS,EAAE,gBAAgB,EAAE,MAAM,SAAS,CAAC;AAEvE,OAAO,EAAE,KAAK,EAAE,MAAM,SAAS,CAAC;AAChC,YAAY,EAAE,UAAU,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AAErD,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAC9C,YAAY,EAAE,iBAAiB,EAAE,MAAM,gBAAgB,CAAC;AAExD,OAAO,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AACpD,YAAY,EAAE,oBAAoB,EAAE,MAAM,mBAAmB,CAAC;AAE9D,OAAO,EAAE,4BAA4B,EAAE,MAAM,gCAAgC,CAAC;AAC9E,YAAY,EAAE,iCAAiC,EAAE,MAAM,gCAAgC,CAAC;AAExF,OAAO,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AACpD,YAAY,EACV,oBAAoB,EACpB,0BAA0B,EAC1B,aAAa,GACd,MAAM,mBAAmB,CAAC"}
@@ -0,0 +1,18 @@
1
+ /**
2
+ * @shopbb/helium/components — 商家用 React 组件
3
+ *
4
+ * 用法:
5
+ * import { Money, Image, ProductPrice, AddToCartButton } from '@shopbb/helium/components';
6
+ *
7
+ * 设计原则:
8
+ * - 无样式:组件只管行为 + 语义化 DOM,样式商家自己写
9
+ * - data-* 钩子:方便选择器
10
+ * - 对齐 Shopify Hydrogen 同名组件的 API,迁移成本低
11
+ */
12
+ export { Money } from './Money';
13
+ export { Image } from './Image';
14
+ export { ProductPrice } from './ProductPrice';
15
+ export { AddToCartButton } from './AddToCartButton';
16
+ export { CartLineQuantityAdjustButton } from './CartLineQuantityAdjustButton';
17
+ export { VariantSelector } from './VariantSelector';
18
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/components/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,EAAE,KAAK,EAAE,MAAM,SAAS,CAAC;AAGhC,OAAO,EAAE,KAAK,EAAE,MAAM,SAAS,CAAC;AAGhC,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAG9C,OAAO,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AAGpD,OAAO,EAAE,4BAA4B,EAAE,MAAM,gCAAgC,CAAC;AAG9E,OAAO,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC"}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@shopbb/helium",
3
- "version": "0.2.0",
4
- "description": "shopbb storefront framework — GraphQL client, cart handler, cache helpers, and React SSR for Cloudflare Workers",
3
+ "version": "0.3.0-alpha.1",
4
+ "description": "shopbb storefront framework — components, React SSR, GraphQL client, cart handler, cache for Cloudflare Workers",
5
5
  "license": "MIT",
6
6
  "type": "module",
7
7
  "sideEffects": false,
@@ -20,6 +20,10 @@
20
20
  "./client": {
21
21
  "types": "./dist/client.d.ts",
22
22
  "import": "./dist/client.js"
23
+ },
24
+ "./components": {
25
+ "types": "./dist/components/index.d.ts",
26
+ "import": "./dist/components/index.js"
23
27
  }
24
28
  },
25
29
  "files": [
@@ -48,8 +52,12 @@
48
52
  "react-dom": ">=18"
49
53
  },
50
54
  "peerDependenciesMeta": {
51
- "react": { "optional": true },
52
- "react-dom": { "optional": true }
55
+ "react": {
56
+ "optional": true
57
+ },
58
+ "react-dom": {
59
+ "optional": true
60
+ }
53
61
  },
54
62
  "devDependencies": {
55
63
  "@cloudflare/workers-types": "^4.20240117.0",
@@ -0,0 +1,90 @@
1
+ /**
2
+ * <AddToCartButton> — 加入购物车按钮
3
+ *
4
+ * 对齐 @shopify/hydrogen <AddToCartButton>:
5
+ * - 内置 loading 态、disabled、error 处理
6
+ * - 支持 onAdd 回调(实际加购逻辑由外部 cart hook 提供)
7
+ * - 触发 analytics 事件钩子
8
+ * - 不带样式,商家自己控制
9
+ *
10
+ * 用法(Phase 1,需要传 onAdd):
11
+ * const { addLine } = useCart();
12
+ * <AddToCartButton
13
+ * variantId={selectedVariant.id}
14
+ * quantity={1}
15
+ * disabled={!selectedVariant.availableForSale}
16
+ * onAdd={(vid, qty) => addLine(vid, qty)}
17
+ * >
18
+ * 加入购物车
19
+ * </AddToCartButton>
20
+ *
21
+ * Phase 2 后:组件会自动从 <CartProvider> 拿,无需 onAdd 也能用。
22
+ */
23
+
24
+ import * as React from 'react';
25
+
26
+ export interface AddToCartButtonProps extends Omit<React.ButtonHTMLAttributes<HTMLButtonElement>, 'onClick' | 'onError'> {
27
+ /** 必传:variant 的 GID(gid://shopbb/ProductVariant/...) */
28
+ variantId: string;
29
+ /** 数量,默认 1 */
30
+ quantity?: number;
31
+ /** 实际加购回调。Phase 1 必传;Phase 2 后可从 Provider 自动获取 */
32
+ onAdd?: (variantId: string, quantity: number) => Promise<void>;
33
+ /** 加购成功回调(如导航到 /cart) */
34
+ onAdded?: () => void;
35
+ /** 加购失败回调 */
36
+ onError?: (err: Error) => void;
37
+ /** 加购中显示的文本,默认 "加入中..." */
38
+ loadingText?: React.ReactNode;
39
+ /** 不可用时显示的文本,默认 "缺货" */
40
+ unavailableText?: React.ReactNode;
41
+ }
42
+
43
+ export function AddToCartButton(props: AddToCartButtonProps) {
44
+ const {
45
+ variantId,
46
+ quantity = 1,
47
+ onAdd,
48
+ onAdded,
49
+ onError,
50
+ loadingText = '加入中...',
51
+ unavailableText = '缺货',
52
+ children = '加入购物车',
53
+ disabled: disabledProp,
54
+ ...rest
55
+ } = props;
56
+
57
+ const [adding, setAdding] = React.useState(false);
58
+
59
+ const handleClick = async (e: React.MouseEvent<HTMLButtonElement>) => {
60
+ e.preventDefault();
61
+ if (adding || disabledProp) return;
62
+ if (!onAdd) {
63
+ console.warn('[AddToCartButton] onAdd not provided; this button does nothing in Phase 1');
64
+ return;
65
+ }
66
+ setAdding(true);
67
+ try {
68
+ await onAdd(variantId, quantity);
69
+ onAdded?.();
70
+ } catch (err: any) {
71
+ console.error('[AddToCartButton] add failed:', err);
72
+ onError?.(err instanceof Error ? err : new Error(String(err)));
73
+ } finally {
74
+ setAdding(false);
75
+ }
76
+ };
77
+
78
+ return (
79
+ <button
80
+ type="button"
81
+ {...rest}
82
+ data-add-to-cart
83
+ data-loading={adding ? '' : undefined}
84
+ disabled={disabledProp || adding}
85
+ onClick={handleClick}
86
+ >
87
+ {adding ? loadingText : disabledProp ? unavailableText : children}
88
+ </button>
89
+ );
90
+ }
@@ -0,0 +1,119 @@
1
+ /**
2
+ * <CartLineQuantityAdjustButton> — cart 行数量加减按钮
3
+ *
4
+ * 对齐 @shopify/hydrogen <CartLineQuantityAdjustButton>:
5
+ * - +/- 按钮调用 onChange
6
+ * - 防抖(300ms)避免点快导致多次请求
7
+ * - min/max 校验
8
+ * - 移除时弹确认(可选)
9
+ *
10
+ * 用法:
11
+ * const { updateLine, removeLine } = useCart();
12
+ * <CartLineQuantityAdjustButton
13
+ * line={line}
14
+ * onUpdate={(newQty) => updateLine(line.id, newQty)}
15
+ * onRemove={() => removeLine(line.id)}
16
+ * />
17
+ */
18
+
19
+ import * as React from 'react';
20
+
21
+ export interface CartLineQuantityAdjustButtonProps {
22
+ /** line 的当前数量 */
23
+ quantity: number;
24
+ /** 最小值,默认 1(小于此值改成 remove) */
25
+ min?: number;
26
+ /** 最大值,默认 99 */
27
+ max?: number;
28
+ /** 数量变化回调 */
29
+ onUpdate?: (newQuantity: number) => Promise<void> | void;
30
+ /** 数量降到 0 时触发 remove */
31
+ onRemove?: () => Promise<void> | void;
32
+ /** 防抖延迟(ms),默认 300 */
33
+ debounceMs?: number;
34
+ /** 自定义包装容器 className */
35
+ className?: string;
36
+ /** 减号按钮 props 透传 */
37
+ decreaseProps?: React.ButtonHTMLAttributes<HTMLButtonElement>;
38
+ /** 加号按钮 props 透传 */
39
+ increaseProps?: React.ButtonHTMLAttributes<HTMLButtonElement>;
40
+ }
41
+
42
+ export function CartLineQuantityAdjustButton(props: CartLineQuantityAdjustButtonProps) {
43
+ const {
44
+ quantity,
45
+ min = 1,
46
+ max = 99,
47
+ onUpdate,
48
+ onRemove,
49
+ debounceMs = 300,
50
+ className,
51
+ decreaseProps,
52
+ increaseProps,
53
+ } = props;
54
+
55
+ // optimistic 显示的 quantity
56
+ const [optimistic, setOptimistic] = React.useState(quantity);
57
+ React.useEffect(() => setOptimistic(quantity), [quantity]);
58
+
59
+ const [pending, setPending] = React.useState(false);
60
+ const timerRef = React.useRef<ReturnType<typeof setTimeout> | null>(null);
61
+
62
+ const flushUpdate = React.useCallback(
63
+ (target: number) => {
64
+ if (timerRef.current) clearTimeout(timerRef.current);
65
+ timerRef.current = setTimeout(async () => {
66
+ setPending(true);
67
+ try {
68
+ if (target < min) {
69
+ await onRemove?.();
70
+ } else {
71
+ await onUpdate?.(target);
72
+ }
73
+ } finally {
74
+ setPending(false);
75
+ }
76
+ }, debounceMs);
77
+ },
78
+ [min, onRemove, onUpdate, debounceMs],
79
+ );
80
+
81
+ const handleAdjust = (delta: number) => {
82
+ const next = optimistic + delta;
83
+ if (next > max) return;
84
+ setOptimistic(next);
85
+ flushUpdate(next);
86
+ };
87
+
88
+ React.useEffect(() => () => {
89
+ if (timerRef.current) clearTimeout(timerRef.current);
90
+ }, []);
91
+
92
+ return (
93
+ <div className={className} data-quantity-adjust style={{ display: 'inline-flex', alignItems: 'center' }}>
94
+ <button
95
+ type="button"
96
+ {...decreaseProps}
97
+ aria-label="减少"
98
+ data-quantity-decrease
99
+ onClick={() => handleAdjust(-1)}
100
+ disabled={pending && optimistic <= min}
101
+ >
102
+ {decreaseProps?.children ?? '−'}
103
+ </button>
104
+ <span data-quantity-value aria-live="polite" style={{ margin: '0 0.5em', minWidth: '1.5em', textAlign: 'center' }}>
105
+ {optimistic}
106
+ </span>
107
+ <button
108
+ type="button"
109
+ {...increaseProps}
110
+ aria-label="增加"
111
+ data-quantity-increase
112
+ onClick={() => handleAdjust(1)}
113
+ disabled={pending && optimistic >= max}
114
+ >
115
+ {increaseProps?.children ?? '+'}
116
+ </button>
117
+ </div>
118
+ );
119
+ }
@@ -0,0 +1,93 @@
1
+ /**
2
+ * <Image> — 响应式商品图片
3
+ *
4
+ * 对齐 @shopify/hydrogen 的 <Image>:
5
+ * - 自动生成 srcset(5 个分辨率档:375 / 750 / 1024 / 1536 / 1920)
6
+ * - sizes 媒体查询
7
+ * - loading="lazy" 默认(首屏可关)
8
+ * - decoding="async"
9
+ * - aspectRatio 占位(不抖)
10
+ * - 自动 alt
11
+ *
12
+ * srcset 里的 url 通过 ?width= query 表达,服务端可忽略或接 cdn-cgi/image。
13
+ *
14
+ * 用法:
15
+ * <Image data={{ url, altText, width, height }} sizes="(min-width: 768px) 50vw, 100vw" />
16
+ * <Image data={...} aspectRatio="1/1" />
17
+ * <Image data={...} loading="eager" /> // 首屏
18
+ */
19
+
20
+ import * as React from 'react';
21
+
22
+ export interface ImageData {
23
+ url: string;
24
+ altText?: string | null;
25
+ width?: number | null;
26
+ height?: number | null;
27
+ }
28
+
29
+ export interface ImageProps extends Omit<React.ImgHTMLAttributes<HTMLImageElement>, 'src' | 'srcSet' | 'loading'> {
30
+ /** 必传:图片对象 */
31
+ data: ImageData;
32
+ /** 媒体查询 sizes,例如 (min-width: 768px) 50vw, 100vw */
33
+ sizes?: string;
34
+ /** 强制宽高比,例如 '1/1' '4/3' '16/9' */
35
+ aspectRatio?: string;
36
+ /** lazy(默认) / eager(首屏图用) */
37
+ loading?: 'lazy' | 'eager';
38
+ /** 自定义 srcset 档位 */
39
+ widths?: number[];
40
+ }
41
+
42
+ // 默认 srcset 档位
43
+ const DEFAULT_WIDTHS = [375, 750, 1024, 1536, 1920];
44
+
45
+ /** 给 url 加 ?width=N query */
46
+ function withWidth(url: string, width: number): string {
47
+ try {
48
+ const u = new URL(url);
49
+ u.searchParams.set('width', String(width));
50
+ return u.toString();
51
+ } catch {
52
+ // 不是绝对 URL,按相对路径处理
53
+ const sep = url.includes('?') ? '&' : '?';
54
+ return `${url}${sep}width=${width}`;
55
+ }
56
+ }
57
+
58
+ export function Image(props: ImageProps) {
59
+ const {
60
+ data,
61
+ sizes,
62
+ aspectRatio,
63
+ loading = 'lazy',
64
+ widths = DEFAULT_WIDTHS,
65
+ style,
66
+ alt: altProp,
67
+ ...rest
68
+ } = props;
69
+
70
+ const srcset = widths.map((w) => `${withWidth(data.url, w)} ${w}w`).join(', ');
71
+ // src 用中间档位
72
+ const src = withWidth(data.url, widths[Math.floor(widths.length / 2)]);
73
+
74
+ const finalStyle: React.CSSProperties = {
75
+ ...(aspectRatio ? { aspectRatio, objectFit: 'cover' as const } : null),
76
+ ...style,
77
+ };
78
+
79
+ return (
80
+ <img
81
+ {...rest}
82
+ src={src}
83
+ srcSet={srcset}
84
+ sizes={sizes}
85
+ alt={altProp ?? data.altText ?? ''}
86
+ loading={loading}
87
+ decoding="async"
88
+ width={data.width || undefined}
89
+ height={data.height || undefined}
90
+ style={finalStyle}
91
+ />
92
+ );
93
+ }
@@ -0,0 +1,106 @@
1
+ /**
2
+ * <Money> — 货币格式化
3
+ *
4
+ * 对齐 @shopify/hydrogen 的 <Money>。
5
+ * - 自动按 currencyCode + locale 用 Intl.NumberFormat 格式化
6
+ * - 支持 withoutCurrency / withoutTrailingZeros
7
+ * - 支持 as 渲染成任意元素(默认 <span>)
8
+ * - 支持 measurement(unit price,例如 ¥9.99/100g)
9
+ *
10
+ * 用法:
11
+ * <Money data={{ amount: '9.99', currencyCode: 'CNY' }} />
12
+ * <Money data={{ ... }} withoutCurrency />
13
+ * <Money data={{ ... }} as="div" measurement={{ referenceUnit: 'kg', quantity: 0.1 }} />
14
+ */
15
+
16
+ import * as React from 'react';
17
+
18
+ export interface MoneyData {
19
+ amount: string;
20
+ currencyCode: string;
21
+ }
22
+
23
+ export interface MoneyMeasurement {
24
+ /** 比如 'kg' / '100g' / 'l' */
25
+ referenceUnit: string;
26
+ /** 比如 0.1 表示每 100g */
27
+ quantity?: number;
28
+ }
29
+
30
+ export interface MoneyProps extends React.HTMLAttributes<HTMLElement> {
31
+ /** 必传:金额对象 */
32
+ data: MoneyData;
33
+ /** 不显示货币符号,只显示数字 */
34
+ withoutCurrency?: boolean;
35
+ /** 整数时不显示 .00 */
36
+ withoutTrailingZeros?: boolean;
37
+ /** locale 字符串(zh-CN / en-US / ...)。默认按 currencyCode 推断 */
38
+ locale?: string;
39
+ /** 渲染元素,默认 span */
40
+ as?: keyof JSX.IntrinsicElements;
41
+ /** unit price:渲染 ¥99.00/100g */
42
+ measurement?: MoneyMeasurement;
43
+ }
44
+
45
+ // currencyCode → 默认 locale 推断
46
+ const DEFAULT_LOCALE_BY_CURRENCY: Record<string, string> = {
47
+ CNY: 'zh-CN',
48
+ USD: 'en-US',
49
+ EUR: 'de-DE',
50
+ GBP: 'en-GB',
51
+ JPY: 'ja-JP',
52
+ KRW: 'ko-KR',
53
+ };
54
+
55
+ export function Money(props: MoneyProps) {
56
+ const {
57
+ data,
58
+ withoutCurrency,
59
+ withoutTrailingZeros,
60
+ locale: localeProp,
61
+ as,
62
+ measurement,
63
+ ...rest
64
+ } = props;
65
+
66
+ const Tag: any = as || 'span';
67
+ const locale = localeProp || DEFAULT_LOCALE_BY_CURRENCY[data.currencyCode] || 'en-US';
68
+ const amount = Number(data.amount);
69
+
70
+ let formatted: string;
71
+ try {
72
+ const opts: Intl.NumberFormatOptions = withoutCurrency
73
+ ? {
74
+ minimumFractionDigits: withoutTrailingZeros && Number.isInteger(amount) ? 0 : 2,
75
+ maximumFractionDigits: 2,
76
+ }
77
+ : {
78
+ style: 'currency',
79
+ currency: data.currencyCode,
80
+ minimumFractionDigits: withoutTrailingZeros && Number.isInteger(amount) ? 0 : 2,
81
+ maximumFractionDigits: 2,
82
+ };
83
+ formatted = new Intl.NumberFormat(locale, opts).format(amount);
84
+ } catch {
85
+ // Fallback:Intl 不支持的 currencyCode
86
+ formatted = withoutCurrency ? amount.toFixed(2) : `${data.currencyCode} ${amount.toFixed(2)}`;
87
+ }
88
+
89
+ // measurement suffix(unit price)
90
+ let suffix = '';
91
+ if (measurement) {
92
+ const q = measurement.quantity ?? 1;
93
+ if (q === 1) {
94
+ suffix = `/${measurement.referenceUnit}`;
95
+ } else {
96
+ suffix = `/${q}${measurement.referenceUnit}`;
97
+ }
98
+ }
99
+
100
+ return (
101
+ <Tag {...rest} data-money={data.amount} data-money-currency={data.currencyCode}>
102
+ {formatted}
103
+ {suffix}
104
+ </Tag>
105
+ );
106
+ }
@@ -0,0 +1,61 @@
1
+ /**
2
+ * <ProductPrice> — 商品价格
3
+ *
4
+ * 对齐 @shopify/hydrogen <ProductPrice>:
5
+ * - 渲染当前价
6
+ * - 当 compareAtPrice > price 时自动显示划线对比价
7
+ * - 支持 unit price 模式
8
+ * - 可定制 className / 容器
9
+ *
10
+ * 用法:
11
+ * <ProductPrice price={{ amount: '99', currencyCode: 'CNY' }} />
12
+ * <ProductPrice price={...} compareAtPrice={{ amount: '129', ... }} />
13
+ */
14
+
15
+ import * as React from 'react';
16
+ import { Money, type MoneyData, type MoneyMeasurement } from './Money';
17
+
18
+ export interface ProductPriceProps extends React.HTMLAttributes<HTMLElement> {
19
+ price: MoneyData;
20
+ compareAtPrice?: MoneyData | null;
21
+ /** unit price,例如每 100g */
22
+ measurement?: MoneyMeasurement;
23
+ /** locale 透传 */
24
+ locale?: string;
25
+ /** 划线价的额外 className */
26
+ compareAtClassName?: string;
27
+ as?: keyof JSX.IntrinsicElements;
28
+ }
29
+
30
+ export function ProductPrice(props: ProductPriceProps) {
31
+ const {
32
+ price,
33
+ compareAtPrice,
34
+ measurement,
35
+ locale,
36
+ compareAtClassName,
37
+ as,
38
+ ...rest
39
+ } = props;
40
+
41
+ const Tag: any = as || 'div';
42
+ const hasDiscount =
43
+ compareAtPrice &&
44
+ Number(compareAtPrice.amount) > Number(price.amount);
45
+
46
+ return (
47
+ <Tag {...rest} data-product-price>
48
+ <Money data={price} locale={locale} measurement={measurement} />
49
+ {hasDiscount && compareAtPrice && (
50
+ <Money
51
+ data={compareAtPrice}
52
+ locale={locale}
53
+ as="s"
54
+ className={compareAtClassName}
55
+ data-compare-at="true"
56
+ style={{ marginLeft: '0.5em', opacity: 0.6 }}
57
+ />
58
+ )}
59
+ </Tag>
60
+ );
61
+ }