@shopbb/helium 0.1.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.
- package/dist/client.d.ts +48 -0
- package/dist/client.d.ts.map +1 -0
- package/dist/client.js +64 -0
- package/dist/client.js.map +1 -0
- package/dist/components/AddToCartButton.d.ts +41 -0
- package/dist/components/AddToCartButton.d.ts.map +1 -0
- package/dist/components/AddToCartButton.js +51 -0
- package/dist/components/AddToCartButton.js.map +1 -0
- package/dist/components/CartLineQuantityAdjustButton.d.ts +40 -0
- package/dist/components/CartLineQuantityAdjustButton.d.ts.map +1 -0
- package/dist/components/CartLineQuantityAdjustButton.js +58 -0
- package/dist/components/CartLineQuantityAdjustButton.js.map +1 -0
- package/dist/components/Image.d.ts +39 -0
- package/dist/components/Image.d.ts.map +1 -0
- package/dist/components/Image.js +28 -0
- package/dist/components/Image.js.map +1 -0
- package/dist/components/Money.d.ts +41 -0
- package/dist/components/Money.d.ts.map +1 -0
- package/dist/components/Money.js +48 -0
- package/dist/components/Money.js.map +1 -0
- package/dist/components/ProductPrice.d.ts +28 -0
- package/dist/components/ProductPrice.d.ts.map +1 -0
- package/dist/components/ProductPrice.js +10 -0
- package/dist/components/ProductPrice.js.map +1 -0
- package/dist/components/VariantSelector.d.ts +80 -0
- package/dist/components/VariantSelector.d.ts.map +1 -0
- package/dist/components/VariantSelector.js +87 -0
- package/dist/components/VariantSelector.js.map +1 -0
- package/dist/components/index.d.ts +24 -0
- package/dist/components/index.d.ts.map +1 -0
- package/dist/components/index.js +18 -0
- package/dist/components/index.js.map +1 -0
- package/dist/react.d.ts +98 -0
- package/dist/react.d.ts.map +1 -0
- package/dist/react.js +168 -0
- package/dist/react.js.map +1 -0
- package/package.json +33 -3
- package/src/client.tsx +103 -0
- package/src/components/AddToCartButton.tsx +90 -0
- package/src/components/CartLineQuantityAdjustButton.tsx +119 -0
- package/src/components/Image.tsx +93 -0
- package/src/components/Money.tsx +106 -0
- package/src/components/ProductPrice.tsx +61 -0
- package/src/components/VariantSelector.tsx +148 -0
- package/src/components/index.ts +33 -0
- package/src/react.tsx +296 -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
|
+
}
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* <VariantSelector> — 商品 variant 选择器
|
|
3
|
+
*
|
|
4
|
+
* 对齐 @shopify/hydrogen <VariantSelector>:
|
|
5
|
+
* - 自动解析 variants 的 selectedOptions 维度(颜色 / 尺寸 等)
|
|
6
|
+
* - 渲染每个维度的选项按钮
|
|
7
|
+
* - 不可购买组合 disabled
|
|
8
|
+
* - URL 同步(可选)
|
|
9
|
+
* - 默认选第一个 availableForSale
|
|
10
|
+
*
|
|
11
|
+
* 设计:组件用 render prop,把每个 option 的选项交给商家渲染。
|
|
12
|
+
*
|
|
13
|
+
* 用法:
|
|
14
|
+
* <VariantSelector
|
|
15
|
+
* product={product}
|
|
16
|
+
* value={selectedVariantId}
|
|
17
|
+
* onChange={setSelectedVariantId}
|
|
18
|
+
* >
|
|
19
|
+
* {({ option, value, onSelect }) => (
|
|
20
|
+
* <div>
|
|
21
|
+
* <h4>{option.name}</h4>
|
|
22
|
+
* {option.values.map((v) => (
|
|
23
|
+
* <button
|
|
24
|
+
* key={v.value}
|
|
25
|
+
* disabled={!v.available}
|
|
26
|
+
* onClick={() => onSelect(v.value)}
|
|
27
|
+
* aria-pressed={v.value === value}
|
|
28
|
+
* >
|
|
29
|
+
* {v.value}
|
|
30
|
+
* </button>
|
|
31
|
+
* ))}
|
|
32
|
+
* </div>
|
|
33
|
+
* )}
|
|
34
|
+
* </VariantSelector>
|
|
35
|
+
*/
|
|
36
|
+
|
|
37
|
+
import * as React from 'react';
|
|
38
|
+
|
|
39
|
+
interface SelectedOption {
|
|
40
|
+
name: string;
|
|
41
|
+
value: string;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
interface ProductVariant {
|
|
45
|
+
id: string;
|
|
46
|
+
availableForSale: boolean;
|
|
47
|
+
selectedOptions?: SelectedOption[];
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
interface ProductLike {
|
|
51
|
+
options?: Array<{ name: string; values: string[] }>;
|
|
52
|
+
variants: { nodes: ProductVariant[] };
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export interface VariantOption {
|
|
56
|
+
name: string;
|
|
57
|
+
values: Array<{ value: string; available: boolean }>;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export interface VariantSelectorRenderProps {
|
|
61
|
+
option: VariantOption;
|
|
62
|
+
/** 当前已选择的 value(在这个 option 维度上) */
|
|
63
|
+
value: string | undefined;
|
|
64
|
+
/** 选择 value,触发 onChange 更新 selectedVariantId */
|
|
65
|
+
onSelect: (value: string) => void;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export interface VariantSelectorProps {
|
|
69
|
+
product: ProductLike;
|
|
70
|
+
/** 当前选中 variant 的 GID */
|
|
71
|
+
value: string;
|
|
72
|
+
/** variant 切换时调用 */
|
|
73
|
+
onChange?: (variantId: string) => void;
|
|
74
|
+
/** 每个 option 的渲染函数 */
|
|
75
|
+
children: (renderProps: VariantSelectorRenderProps) => React.ReactNode;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export function VariantSelector(props: VariantSelectorProps) {
|
|
79
|
+
const { product, value, onChange, children } = props;
|
|
80
|
+
|
|
81
|
+
const variants = product.variants.nodes;
|
|
82
|
+
const currentVariant = variants.find((v) => v.id === value) || variants[0];
|
|
83
|
+
|
|
84
|
+
// 推断 options(如果 product.options 没传,从 variants.selectedOptions 提取)
|
|
85
|
+
const options: VariantOption[] = React.useMemo(() => {
|
|
86
|
+
if (product.options && product.options.length > 0) {
|
|
87
|
+
return product.options.map((opt) => ({
|
|
88
|
+
name: opt.name,
|
|
89
|
+
values: opt.values.map((v) => ({
|
|
90
|
+
value: v,
|
|
91
|
+
available: variants.some(
|
|
92
|
+
(variant) =>
|
|
93
|
+
variant.availableForSale &&
|
|
94
|
+
variant.selectedOptions?.some((so) => so.name === opt.name && so.value === v),
|
|
95
|
+
),
|
|
96
|
+
})),
|
|
97
|
+
}));
|
|
98
|
+
}
|
|
99
|
+
// 从 variants.selectedOptions 反推
|
|
100
|
+
const dimMap = new Map<string, Set<string>>();
|
|
101
|
+
for (const v of variants) {
|
|
102
|
+
for (const so of v.selectedOptions ?? []) {
|
|
103
|
+
if (!dimMap.has(so.name)) dimMap.set(so.name, new Set());
|
|
104
|
+
dimMap.get(so.name)!.add(so.value);
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
return Array.from(dimMap.entries()).map(([name, values]) => ({
|
|
108
|
+
name,
|
|
109
|
+
values: Array.from(values).map((v) => ({
|
|
110
|
+
value: v,
|
|
111
|
+
available: variants.some(
|
|
112
|
+
(variant) =>
|
|
113
|
+
variant.availableForSale &&
|
|
114
|
+
variant.selectedOptions?.some((so) => so.name === name && so.value === v),
|
|
115
|
+
),
|
|
116
|
+
})),
|
|
117
|
+
}));
|
|
118
|
+
}, [product, variants]);
|
|
119
|
+
|
|
120
|
+
// 切换某 option 的 value:找一个匹配的 variant
|
|
121
|
+
const handleSelect = (optionName: string, optionValue: string) => {
|
|
122
|
+
const currentSelected = new Map<string, string>(
|
|
123
|
+
(currentVariant?.selectedOptions ?? []).map((so) => [so.name, so.value]),
|
|
124
|
+
);
|
|
125
|
+
currentSelected.set(optionName, optionValue);
|
|
126
|
+
// 找最匹配 + available 的 variant
|
|
127
|
+
const target = variants.find((v) =>
|
|
128
|
+
Array.from(currentSelected.entries()).every(([n, val]) =>
|
|
129
|
+
v.selectedOptions?.some((so) => so.name === n && so.value === val),
|
|
130
|
+
),
|
|
131
|
+
);
|
|
132
|
+
if (target) onChange?.(target.id);
|
|
133
|
+
};
|
|
134
|
+
|
|
135
|
+
return (
|
|
136
|
+
<>
|
|
137
|
+
{options.map((option) => (
|
|
138
|
+
<React.Fragment key={option.name}>
|
|
139
|
+
{children({
|
|
140
|
+
option,
|
|
141
|
+
value: currentVariant?.selectedOptions?.find((so) => so.name === option.name)?.value,
|
|
142
|
+
onSelect: (val) => handleSelect(option.name, val),
|
|
143
|
+
})}
|
|
144
|
+
</React.Fragment>
|
|
145
|
+
))}
|
|
146
|
+
</>
|
|
147
|
+
);
|
|
148
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
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
|
+
|
|
13
|
+
export { Money } from './Money';
|
|
14
|
+
export type { MoneyProps, MoneyData, MoneyMeasurement } from './Money';
|
|
15
|
+
|
|
16
|
+
export { Image } from './Image';
|
|
17
|
+
export type { ImageProps, ImageData } from './Image';
|
|
18
|
+
|
|
19
|
+
export { ProductPrice } from './ProductPrice';
|
|
20
|
+
export type { ProductPriceProps } from './ProductPrice';
|
|
21
|
+
|
|
22
|
+
export { AddToCartButton } from './AddToCartButton';
|
|
23
|
+
export type { AddToCartButtonProps } from './AddToCartButton';
|
|
24
|
+
|
|
25
|
+
export { CartLineQuantityAdjustButton } from './CartLineQuantityAdjustButton';
|
|
26
|
+
export type { CartLineQuantityAdjustButtonProps } from './CartLineQuantityAdjustButton';
|
|
27
|
+
|
|
28
|
+
export { VariantSelector } from './VariantSelector';
|
|
29
|
+
export type {
|
|
30
|
+
VariantSelectorProps,
|
|
31
|
+
VariantSelectorRenderProps,
|
|
32
|
+
VariantOption,
|
|
33
|
+
} from './VariantSelector';
|