@shopify/shop-minis-react 0.2.9 → 0.3.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.
@@ -0,0 +1,131 @@
1
+ /**
2
+ * ESLint rule to prefer SDK hooks over native browser APIs
3
+ * @fileoverview Enforce using Shop Minis SDK hooks instead of native browser APIs
4
+ */
5
+
6
+ module.exports = {
7
+ meta: {
8
+ type: 'suggestion',
9
+ docs: {
10
+ description:
11
+ 'Prefer Shop Minis SDK hooks over native browser APIs for better compatibility and functionality',
12
+ category: 'Best Practices',
13
+ recommended: true,
14
+ },
15
+ messages: {
16
+ preferAsyncStorage:
17
+ 'Use useAsyncStorage from @shopify/shop-minis-react instead of localStorage. The SDK hook provides async storage that works reliably in the Shop mini-app environment.',
18
+ preferSecureStorage:
19
+ 'Use useSecureStorage from @shopify/shop-minis-react instead of localStorage for sensitive data. The SDK hook provides encrypted storage.',
20
+ },
21
+ schema: [
22
+ {
23
+ type: 'object',
24
+ properties: {
25
+ apis: {
26
+ type: 'object',
27
+ description: 'Map of native APIs to SDK hooks',
28
+ additionalProperties: {
29
+ type: 'string',
30
+ },
31
+ },
32
+ },
33
+ additionalProperties: false,
34
+ },
35
+ ],
36
+ },
37
+
38
+ create(context) {
39
+ // Default API mappings
40
+ const defaultApis = {
41
+ localStorage: 'useAsyncStorage',
42
+ sessionStorage: 'useAsyncStorage',
43
+ // Future additions will go here:
44
+ // navigator.geolocation: 'useGeolocation',
45
+ // window.history: 'useNavigation',
46
+ }
47
+
48
+ // Get user configuration or use defaults
49
+ const options = context.options[0] || {}
50
+ const apiMap = {
51
+ ...defaultApis,
52
+ ...(options.apis || {}),
53
+ }
54
+
55
+ return {
56
+ MemberExpression(node) {
57
+ // Check for direct access: localStorage.getItem()
58
+ if (node.object.type === 'Identifier' && apiMap[node.object.name]) {
59
+ const apiName = node.object.name
60
+ const sdkHook = apiMap[apiName]
61
+
62
+ context.report({
63
+ node: node.object,
64
+ messageId: 'preferAsyncStorage',
65
+ data: {
66
+ nativeApi: apiName,
67
+ sdkHook,
68
+ },
69
+ })
70
+ return
71
+ }
72
+
73
+ // Check for global access: window.localStorage or globalThis.localStorage
74
+ if (
75
+ node.object.type === 'MemberExpression' &&
76
+ node.object.object.type === 'Identifier' &&
77
+ (node.object.object.name === 'window' ||
78
+ node.object.object.name === 'globalThis') &&
79
+ node.object.property.type === 'Identifier' &&
80
+ apiMap[node.object.property.name]
81
+ ) {
82
+ const apiName = node.object.property.name
83
+ const sdkHook = apiMap[apiName]
84
+
85
+ context.report({
86
+ node: node.object,
87
+ messageId: 'preferAsyncStorage',
88
+ data: {
89
+ nativeApi: apiName,
90
+ sdkHook,
91
+ },
92
+ })
93
+ }
94
+ },
95
+
96
+ // Also catch direct references to localStorage/sessionStorage
97
+ Identifier(node) {
98
+ // Only flag if it's being used, not just referenced in imports
99
+ const parent = node.parent
100
+
101
+ // Skip if it's part of an import statement
102
+ if (
103
+ parent.type === 'ImportSpecifier' ||
104
+ parent.type === 'ImportDefaultSpecifier'
105
+ ) {
106
+ return
107
+ }
108
+
109
+ // Skip if it's already part of a MemberExpression (handled above)
110
+ if (parent.type === 'MemberExpression' && parent.object === node) {
111
+ return
112
+ }
113
+
114
+ // Check if this is a direct reference to localStorage/sessionStorage
115
+ if (!apiMap[node.name]) {
116
+ return
117
+ }
118
+
119
+ // Skip if it's being declared as a variable
120
+ if (parent.type === 'VariableDeclarator' && parent.init === node) {
121
+ return
122
+ }
123
+
124
+ context.report({
125
+ node,
126
+ messageId: 'preferAsyncStorage',
127
+ })
128
+ },
129
+ }
130
+ },
131
+ }
@@ -116,10 +116,6 @@
116
116
  "useShop": [
117
117
  "GET_SHOP"
118
118
  ],
119
- "useShopCartActions": [
120
- "ADD_TO_CART",
121
- "BUY_PRODUCT"
122
- ],
123
119
  "useShopNavigation": [
124
120
  "NAVIGATE_TO_PRODUCT",
125
121
  "NAVIGATE_TO_SHOP",
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@shopify/shop-minis-react",
3
3
  "license": "SEE LICENSE IN LICENSE.txt",
4
- "version": "0.2.9",
4
+ "version": "0.3.1",
5
5
  "sideEffects": false,
6
6
  "type": "module",
7
7
  "engines": {
@@ -43,26 +43,27 @@
43
43
  "typescript": ">=5.0.0"
44
44
  },
45
45
  "dependencies": {
46
- "@shopify/shop-minis-platform": "0.7.0",
46
+ "@shopify/shop-minis-platform": "0.8.0",
47
47
  "@tailwindcss/vite": "4.1.8",
48
48
  "@types/color": "3.0.6",
49
49
  "@types/lodash": "4.17.20",
50
50
  "@types/react-window": "1.8.8",
51
51
  "@types/url-parse": "1.4.9",
52
52
  "@types/video.js": "7.3.58",
53
+ "@typescript-eslint/parser": "^7.0.0",
53
54
  "@vitejs/plugin-react": "4.5.1",
54
55
  "class-variance-authority": "0.7.1",
55
56
  "clsx": "2.1.1",
56
57
  "color": "4.2.3",
57
58
  "embla-carousel-react": "8.6.0",
59
+ "eslint": "^8.57.0",
60
+ "eslint-plugin-react": "^7.37.5",
58
61
  "js-base64": "3.7.7",
59
62
  "lodash": "4.17.21",
60
63
  "lucide-react": "0.513.0",
61
64
  "motion": "12.17.3",
62
65
  "next-themes": "0.4.6",
63
66
  "radix-ui": "1.4.2",
64
- "eslint": "^8.57.0",
65
- "@typescript-eslint/parser": "^7.0.0",
66
67
  "react-intersection-observer": "9.13.1",
67
68
  "react-resizable-panels": "3.0.2",
68
69
  "react-router": "7.7.0",
@@ -1,20 +1,72 @@
1
+ import {Product} from '@shopify/shop-minis-platform'
1
2
  import {describe, expect, it, vi} from 'vitest'
2
3
 
3
- import {render, screen, mockMinisSDK, resetAllMocks} from '../../test-utils'
4
+ import {
5
+ render,
6
+ screen,
7
+ mockMinisSDK,
8
+ resetAllMocks,
9
+ userEvent,
10
+ } from '../../test-utils'
4
11
 
5
12
  import {AddToCartButton} from './add-to-cart'
6
13
 
7
14
  // Mock hooks
8
- vi.mock('../../hooks/shop/useShopCartActions', () => ({
15
+ vi.mock('../../internal/useShopCartActions', () => ({
9
16
  useShopCartActions: () => ({
10
17
  addToCart: mockMinisSDK.addToCart,
11
18
  buyProduct: mockMinisSDK.buyProduct,
12
19
  }),
13
20
  }))
14
21
 
22
+ vi.mock('../../hooks', () => ({
23
+ useShopNavigation: () => ({
24
+ navigateToProduct: mockMinisSDK.navigateToProduct,
25
+ }),
26
+ useErrorToast: () => ({
27
+ showErrorToast: vi.fn(),
28
+ }),
29
+ }))
30
+
15
31
  describe('AddToCartButton', () => {
32
+ const mockProduct: Product = {
33
+ id: 'gid://shopify/Product/123',
34
+ title: 'Test Product',
35
+ reviewAnalytics: {
36
+ averageRating: null,
37
+ reviewCount: null,
38
+ },
39
+ shop: {
40
+ id: 'gid://shopify/Shop/1',
41
+ name: 'Test Shop',
42
+ },
43
+ defaultVariantId: 'gid://shopify/ProductVariant/456',
44
+ isFavorited: false,
45
+ price: {
46
+ amount: '10.00',
47
+ currencyCode: 'USD',
48
+ },
49
+ variants: [
50
+ {
51
+ id: 'gid://shopify/ProductVariant/456',
52
+ title: 'Default',
53
+ isFavorited: false,
54
+ price: {
55
+ amount: '10.00',
56
+ currencyCode: 'USD',
57
+ },
58
+ image: {
59
+ url: 'https://example.com/variant-image.jpg',
60
+ altText: null,
61
+ width: null,
62
+ height: null,
63
+ },
64
+ },
65
+ ],
66
+ }
67
+
16
68
  const defaultProps = {
17
- productId: 'gid://shopify/Product/123',
69
+ product: mockProduct,
18
70
  productVariantId: 'gid://shopify/ProductVariant/456',
19
71
  }
20
72
 
@@ -70,4 +122,167 @@ describe('AddToCartButton', () => {
70
122
 
71
123
  expect(screen.getByRole('button')).toBeInTheDocument()
72
124
  })
125
+
126
+ it('calls addToCart when clicked and not a referral product', async () => {
127
+ const user = userEvent.setup()
128
+ mockMinisSDK.addToCart.mockResolvedValueOnce({ok: true})
129
+
130
+ render(<AddToCartButton {...defaultProps} />)
131
+
132
+ const button = screen.getByRole('button')
133
+ await user.click(button)
134
+
135
+ expect(mockMinisSDK.addToCart).toHaveBeenCalledWith({
136
+ productId: mockProduct.id,
137
+ productVariantId: defaultProps.productVariantId,
138
+ quantity: 1,
139
+ discountCodes: undefined,
140
+ variantImageUrl: 'https://example.com/variant-image.jpg',
141
+ })
142
+ })
143
+
144
+ it('navigates to product page when product is referral', async () => {
145
+ const user = userEvent.setup()
146
+ const referralProduct: Product = {...mockProduct, referral: true}
147
+
148
+ render(<AddToCartButton {...defaultProps} product={referralProduct} />)
149
+
150
+ const button = screen.getByRole('button')
151
+ await user.click(button)
152
+
153
+ expect(mockMinisSDK.navigateToProduct).toHaveBeenCalledWith({
154
+ productId: referralProduct.id,
155
+ })
156
+ expect(mockMinisSDK.addToCart).not.toHaveBeenCalled()
157
+ })
158
+
159
+ it('shows success animation after adding to cart', async () => {
160
+ const user = userEvent.setup()
161
+ mockMinisSDK.addToCart.mockResolvedValueOnce({ok: true})
162
+
163
+ render(<AddToCartButton {...defaultProps} />)
164
+
165
+ const button = screen.getByRole('button')
166
+ await user.click(button)
167
+
168
+ // Check for success state (Added to cart text)
169
+ await screen.findByText('Added to cart')
170
+ })
171
+
172
+ it('handles add to cart error gracefully', async () => {
173
+ const user = userEvent.setup()
174
+ mockMinisSDK.addToCart.mockRejectedValueOnce(new Error('Failed'))
175
+
176
+ render(<AddToCartButton {...defaultProps} />)
177
+
178
+ const button = screen.getByRole('button')
179
+ await user.click(button)
180
+
181
+ expect(mockMinisSDK.addToCart).toHaveBeenCalled()
182
+ })
183
+
184
+ it('does not call addToCart when disabled', async () => {
185
+ const user = userEvent.setup()
186
+
187
+ render(<AddToCartButton {...defaultProps} disabled />)
188
+
189
+ const button = screen.getByRole('button')
190
+ await user.click(button)
191
+
192
+ expect(mockMinisSDK.addToCart).not.toHaveBeenCalled()
193
+ })
194
+
195
+ it('handles product without variants array', async () => {
196
+ const user = userEvent.setup()
197
+ mockMinisSDK.addToCart.mockResolvedValueOnce({ok: true})
198
+
199
+ const productWithoutVariants: Product = {
200
+ ...mockProduct,
201
+ variants: undefined,
202
+ }
203
+
204
+ render(
205
+ <AddToCartButton
206
+ product={productWithoutVariants}
207
+ productVariantId="gid://shopify/ProductVariant/456"
208
+ />
209
+ )
210
+
211
+ const button = screen.getByRole('button')
212
+ await user.click(button)
213
+
214
+ expect(mockMinisSDK.addToCart).toHaveBeenCalledWith({
215
+ productId: productWithoutVariants.id,
216
+ productVariantId: 'gid://shopify/ProductVariant/456',
217
+ quantity: 1,
218
+ discountCodes: undefined,
219
+ variantImageUrl: undefined,
220
+ })
221
+ })
222
+
223
+ it('handles product without matching variant in array', async () => {
224
+ const user = userEvent.setup()
225
+ mockMinisSDK.addToCart.mockResolvedValueOnce({ok: true})
226
+
227
+ const productWithDifferentVariant: Product = {
228
+ ...mockProduct,
229
+ variants: [
230
+ {
231
+ id: 'gid://shopify/ProductVariant/999',
232
+ title: 'Different',
233
+ isFavorited: false,
234
+ price: {
235
+ amount: '15.00',
236
+ currencyCode: 'USD',
237
+ },
238
+ },
239
+ ],
240
+ }
241
+
242
+ render(
243
+ <AddToCartButton
244
+ product={productWithDifferentVariant}
245
+ productVariantId="gid://shopify/ProductVariant/456"
246
+ />
247
+ )
248
+
249
+ const button = screen.getByRole('button')
250
+ await user.click(button)
251
+
252
+ expect(mockMinisSDK.addToCart).toHaveBeenCalledWith({
253
+ productId: productWithDifferentVariant.id,
254
+ productVariantId: 'gid://shopify/ProductVariant/456',
255
+ quantity: 1,
256
+ discountCodes: undefined,
257
+ variantImageUrl: undefined,
258
+ })
259
+ })
260
+
261
+ it('handles product without shop data', async () => {
262
+ const user = userEvent.setup()
263
+ mockMinisSDK.addToCart.mockResolvedValueOnce({ok: true})
264
+
265
+ const productWithoutShop: Product = {
266
+ ...mockProduct,
267
+ shop: undefined as any,
268
+ }
269
+
270
+ render(
271
+ <AddToCartButton
272
+ product={productWithoutShop}
273
+ productVariantId="gid://shopify/ProductVariant/456"
274
+ />
275
+ )
276
+
277
+ const button = screen.getByRole('button')
278
+ await user.click(button)
279
+
280
+ expect(mockMinisSDK.addToCart).toHaveBeenCalledWith({
281
+ productId: productWithoutShop.id,
282
+ productVariantId: 'gid://shopify/ProductVariant/456',
283
+ quantity: 1,
284
+ discountCodes: undefined,
285
+ variantImageUrl: 'https://example.com/variant-image.jpg',
286
+ })
287
+ })
73
288
  })
@@ -1,10 +1,12 @@
1
1
  import * as React from 'react'
2
2
  import {useState, useCallback} from 'react'
3
3
 
4
+ import {Product} from '@shopify/shop-minis-platform'
4
5
  import {CheckIcon} from 'lucide-react'
5
6
  import {motion, AnimatePresence} from 'motion/react'
6
7
 
7
- import {useErrorToast, useShopCartActions} from '../../hooks'
8
+ import {useErrorToast, useShopNavigation} from '../../hooks'
9
+ import {useShopCartActions} from '../../internal/useShopCartActions'
8
10
  import {cn} from '../../lib/utils'
9
11
  import {Button} from '../atoms/button'
10
12
 
@@ -16,42 +18,58 @@ interface AddToCartButtonProps {
16
18
  * The discount codes to apply to the cart.
17
19
  */
18
20
  discountCodes?: string[]
19
- /**
20
- * The GID of the product. E.g. `gid://shopify/Product/123`.
21
- */
22
- productId: string
23
21
  /**
24
22
  * The GID of the product variant. E.g. `gid://shopify/ProductVariant/456`.
25
23
  */
26
24
  productVariantId: string
25
+
26
+ /**
27
+ * The product to add to the cart.
28
+ */
29
+ product?: Product
27
30
  }
28
31
 
29
32
  export function AddToCartButton({
30
33
  disabled = false,
31
34
  className,
32
35
  size = 'default',
33
- productId,
34
36
  productVariantId,
35
37
  discountCodes,
38
+ product,
36
39
  }: AddToCartButtonProps) {
37
40
  const {addToCart} = useShopCartActions()
41
+ const {navigateToProduct} = useShopNavigation()
38
42
  const [isAdded, setIsAdded] = useState(false)
39
43
  const timeoutRef = React.useRef<number | undefined>(undefined)
44
+ const {id, referral, variants} = product ?? {}
45
+
46
+ const variantImageUrl = variants?.find(
47
+ variant => variant.id === productVariantId
48
+ )?.image?.url
40
49
 
41
50
  const {showErrorToast} = useErrorToast()
42
51
 
43
52
  const handleClick = useCallback(async () => {
44
- if (isAdded || disabled) return
53
+ if (disabled) return
54
+
55
+ if (id && referral) {
56
+ navigateToProduct({
57
+ productId: id,
58
+ })
59
+
60
+ return
61
+ }
62
+
63
+ if (isAdded) return
45
64
 
46
65
  try {
47
- // Call the callback if provided
48
- if (productId && productVariantId) {
49
- // Optimistic update with error toast
66
+ if (id && productVariantId) {
50
67
  addToCart({
51
- productId,
68
+ productId: id,
52
69
  productVariantId,
53
70
  quantity: 1,
54
71
  discountCodes,
72
+ variantImageUrl,
55
73
  })
56
74
  .then(() => {})
57
75
  .catch(() => {
@@ -77,12 +95,15 @@ export function AddToCartButton({
77
95
  console.error('Failed to add to cart:', error)
78
96
  }
79
97
  }, [
80
- isAdded,
81
98
  disabled,
82
- addToCart,
83
- productId,
99
+ id,
100
+ referral,
101
+ isAdded,
102
+ navigateToProduct,
84
103
  productVariantId,
104
+ addToCart,
85
105
  discountCodes,
106
+ variantImageUrl,
86
107
  showErrorToast,
87
108
  ])
88
109
 
@@ -95,6 +116,9 @@ export function AddToCartButton({
95
116
  }
96
117
  }, [])
97
118
 
119
+ const addToCartText = isAdded ? 'Added to cart' : 'Add to cart'
120
+ const buttonText = referral ? 'View product' : addToCartText
121
+
98
122
  return (
99
123
  <Button
100
124
  onClick={handleClick}
@@ -116,7 +140,7 @@ export function AddToCartButton({
116
140
  duration: 0.4,
117
141
  ease: [0.175, 0.885, 0.32, 1.275], // bounce effect
118
142
  }}
119
- className="absolute left-0"
143
+ className="absolute left-2"
120
144
  style={{x: -8}}
121
145
  >
122
146
  <CheckIcon className="size-4" />
@@ -124,7 +148,7 @@ export function AddToCartButton({
124
148
  )}
125
149
  </AnimatePresence>
126
150
  <span className={cn(isAdded && 'pl-5', 'transition-all duration-300')}>
127
- {isAdded ? 'Added to cart' : 'Add to cart'}
151
+ {buttonText}
128
152
  </span>
129
153
  </div>
130
154
  </Button>