ui.shipaid.com 0.3.23 → 0.3.24
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/README.md +200 -200
- package/dist/widget.es.js +40 -18
- package/dist/widget.iife.js +3 -3
- package/dist/widget.umd.js +3 -3
- package/dist-types/common/shopify/index.d.ts +6 -6
- package/dist-types/common/shopify/protection.d.ts +6 -6
- package/dist-types/common/shopify/types/ShopifyCart.d.ts +28 -28
- package/dist-types/common/shopify/types/ShopifyProduct.d.ts +7 -7
- package/dist-types/common/types/ShipAid.d.ts +53 -52
- package/dist-types/widget/src/assets/icons.d.ts +8 -8
- package/dist-types/widget/src/assets/learn-more-styles.d.ts +2 -2
- package/dist-types/widget/src/assets/styles.d.ts +2 -2
- package/dist-types/widget/src/components/learn-more-popup.d.ts +8 -8
- package/dist-types/widget/src/shipaid-widget.d.ts +108 -108
- package/dist-types/widget/types/shipaid.d.ts +10 -10
- package/dist-types/widget/types/shopify.d.ts +28 -28
- package/dist-types/widget/types/widget.d.ts +13 -13
- package/package.json +43 -43
package/README.md
CHANGED
|
@@ -1,200 +1,200 @@
|
|
|
1
|
-
# ShipAid Shopify Widget
|
|
2
|
-
|
|
3
|
-
This is the repository for the ShipAid Shopify (and possibly others in future) widget. It uses the [Lit](https://lit.dev/) web components library, so it is recommended to become familiar with it before contributing to this repository.
|
|
4
|
-
|
|
5
|
-
Using Lit provides a framework that allows us to build a reactive UI, using JSX-like syntax - no need to use JQuery etc. And it can easily be installed in a page by using the custom web component name:
|
|
6
|
-
```html
|
|
7
|
-
<shipaid-widget>Fallback Content</shipaid-widget>
|
|
8
|
-
```
|
|
9
|
-
|
|
10
|
-
## Overview
|
|
11
|
-
|
|
12
|
-
This widget provides an interface where a user can choose to add or remove ShipAid protection - this is actually a product in their store that can be added to cart. When the component is loaded, we immediately run a request to fetch the ShipAid protection product details from our API, as well as the customers current cart from the [Shopify AJAX API](https://shopify.dev/api/ajax/reference/cart).
|
|
13
|
-
Once we have this data, we can check whether the customer currently has the ShipAid product in their cart, and show either the add or remove product buttons based on this.
|
|
14
|
-
|
|
15
|
-
We also emit various [custom events](https://developer.mozilla.org/en-US/docs/Web/Events/Creating_and_triggering_events#adding_custom_data_%E2%80%93_customevent) when we add or remove the ShipAid product from the cart, so other developers can listen to these events, and update AJAX carts.
|
|
16
|
-
|
|
17
|
-
### Installation
|
|
18
|
-
|
|
19
|
-
Add the script tag to the theme - if the theme has an ajax cart, you'll likely want to add this to the `theme.liquid` file, otherwise if the store has only a cart page (`/cart`), then you can add it to just that page, to save it being unecessarily loaded when it isn't needed.
|
|
20
|
-
As we don't want to affect a stores speed at all, you should add it to the bottom of the page just before the ending body tag (`</body>`), rather than inside the `<head>` block.
|
|
21
|
-
|
|
22
|
-
```html
|
|
23
|
-
<!-- ShipAid Widget -->
|
|
24
|
-
<script src="https://unpkg.com/ui.shipaid.com/dist/widget.es.js" type="module"></script>
|
|
25
|
-
```
|
|
26
|
-
Then add the widget element where needed:
|
|
27
|
-
|
|
28
|
-
```html
|
|
29
|
-
<shipaid-widget></shipaid-widget>
|
|
30
|
-
|
|
31
|
-
<!-- Disable polling example -->
|
|
32
|
-
<shipaid-widget disablePolling></shipaid-widget>
|
|
33
|
-
|
|
34
|
-
<!-- With customised text -->
|
|
35
|
-
<shipaid-widget>
|
|
36
|
-
<p slot="loading">Loading ShipAid Protection</p>
|
|
37
|
-
</shipaid-widget>
|
|
38
|
-
```
|
|
39
|
-
|
|
40
|
-
#### Test Mode
|
|
41
|
-
|
|
42
|
-
Sometimes, a store won't have activated their subscription before you install the widget - in this case, the widget does not display (you will notice a message in the console reflecting this). So to force the widget to show while you are installing and testing it, you can add this query param to the page URL: `shipaid-test`.
|
|
43
|
-
For example: `https://some-store.myshopify.com/cart?shipaid-text`
|
|
44
|
-
|
|
45
|
-
### Slots
|
|
46
|
-
|
|
47
|
-
Slots, with the syntax `slot="<slot name>"`, can be used to customise the widgets content - for example, a merchant may want to add a custom subtitle, which can be done like so:
|
|
48
|
-
```html
|
|
49
|
-
<shipaid-widget>
|
|
50
|
-
<p slot="subtitle">Shipping protection is required to be able to return or refunds items.</p>
|
|
51
|
-
</shipaid-widget>
|
|
52
|
-
```
|
|
53
|
-
|
|
54
|
-
The default content will be replaced by any slot content. You can also add inline styles to the slots, if you need to change the font size/weight for example - but color changes should be handled by CSS variables:
|
|
55
|
-
```html
|
|
56
|
-
<span slot="title" style="font-weight: 500;">Package Protection</span>
|
|
57
|
-
```
|
|
58
|
-
|
|
59
|
-
| Name | Description |
|
|
60
|
-
|--------|-------------|
|
|
61
|
-
| `loading` | Replaces the text that is shown whilst the widget is loading - I.e. fetching content from the Shopify or ShipAid API's. |
|
|
62
|
-
| `title` | Replaces the default title. |
|
|
63
|
-
| `subtitle` | Replaces the default subtitle. |
|
|
64
|
-
|
|
65
|
-
### Props
|
|
66
|
-
|
|
67
|
-
This is a list of props that can be used to configure the widget:
|
|
68
|
-
|
|
69
|
-
| Prop | Description | Value/Type |
|
|
70
|
-
|--------|-------------|---------|
|
|
71
|
-
| `disablePolling` | Sets whether the cart should disable polling (enabled by default) - should be disabled if integrating manually with an ajax cart. | `boolean` |
|
|
72
|
-
| `pollingInterval` | If polling is enabled, it sets the interval (in ms) between API updates. | `number` in milliseconds |
|
|
73
|
-
| `disableRefresh ` | Sets whether the store cart should be updated when the protection item is added/removed. Add if you want to initially hide the protection product from the cart, even if it has just been added. | `boolean` |
|
|
74
|
-
| `customerId ` | Passes the information of the customer to the widget. Add if merchant wants to disable auto opt-in for some customers based on the customer tags. | `boolean` |
|
|
75
|
-
| `lang ` | Sets the widget language (see the translations section below). This value can be any supported [ISO 639-1 code](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes). | `string` defaults to `en` |
|
|
76
|
-
| `refreshCart` | Refresh the page if shipaid product quantity is greater than one to sync product qty at checkout | `boolean` |
|
|
77
|
-
| `persistPopup` | Use local storage to show popup so that popup don't re-render on script refresh | `boolean` |
|
|
78
|
-
|
|
79
|
-
### Events
|
|
80
|
-
|
|
81
|
-
This is a list of the events emitted by the widget. You can listen to these events like so:
|
|
82
|
-
```js
|
|
83
|
-
document.addEventListener('shipaid-protection-status', ({ detail }) => {
|
|
84
|
-
console.log(detail.cart) // ShopifyCart
|
|
85
|
-
})
|
|
86
|
-
```
|
|
87
|
-
|
|
88
|
-
| Event | Description | Payload |
|
|
89
|
-
|-------|-------------|---------|
|
|
90
|
-
| `shipaid-loaded` | Dispatched when the widget has finished fetching data from the API, and has successfully rendered. | Contains the data from the ShipAid API: [`ShipAidStore`](/types/shipaid.ts) |
|
|
91
|
-
| `shipaid-protection-status` | Dispatched when a user either adds or removes the protection product from their cart. | `{ protection: boolean, cart: ShopifyCart, lineItem: ShopifyCartItem }` |
|
|
92
|
-
|
|
93
|
-
### Methods
|
|
94
|
-
|
|
95
|
-
This is a list of public methods available on the widget HTMLElement that can be used to change protection settings. These can be used by querying the element:
|
|
96
|
-
|
|
97
|
-
```js
|
|
98
|
-
const shipAidEl = document.querySelector('shipaid-widget')
|
|
99
|
-
if (shipAidEl) await shipAidEl.updateCart()
|
|
100
|
-
```
|
|
101
|
-
|
|
102
|
-
| Method | Description | Payload |
|
|
103
|
-
|--------|-------------|---------|
|
|
104
|
-
| `hasProtection` | Returns a boolean which indicates whether the protection item is currently in the cart. | |
|
|
105
|
-
| `updateCart` | Updates the internal cart, and triggers any protection product updates - use this method with with ajax carts, to update protection state without needing to reload the page. | Optional - the cart object from the ajax API. |
|
|
106
|
-
| `addProtection` | Adds the relevant protection item to cart. | |
|
|
107
|
-
| `removeProtection` | Removes the protection item from the cart. | |
|
|
108
|
-
|
|
109
|
-
### Styles
|
|
110
|
-
|
|
111
|
-
If you need to change any of the widget colors to suit a specific theme, there are various CSS variables you can use to do so. These should be added to the style attribute on the widget element:
|
|
112
|
-
|
|
113
|
-
```html
|
|
114
|
-
<shipaid-widget
|
|
115
|
-
style="
|
|
116
|
-
--shipaid-text: #fff;
|
|
117
|
-
--shipaid-prompt-actions-price-color: #fff;
|
|
118
|
-
"
|
|
119
|
-
>
|
|
120
|
-
</shipaid-widget>
|
|
121
|
-
```
|
|
122
|
-
|
|
123
|
-
| Variable | Description | Default |
|
|
124
|
-
|----------|-------------|---------|
|
|
125
|
-
| `--shipaid-text` | Changes the global text color. | `#000000` |
|
|
126
|
-
| `--shipaid-text-muted` | Changes the global muted text color. | `#aaaaaa` |
|
|
127
|
-
| `--shipaid-prompt-margin` | Changes the margins of the main container element. | `2rem 0px 4rem auto` |
|
|
128
|
-
| `--shipaid-prompt-width` | Changes the width of the main container element. | `400px` |
|
|
129
|
-
| `--shipaid-prompt-width-mobile` | Changes the mobile width of the main container element. | `100%` |
|
|
130
|
-
| `--shipaid-prompt-actions-price-color` | Changes the color of the price element. | `var(--shipaid-text-muted)` |
|
|
131
|
-
| `--shipaid-prompt-actions-button-color` | Changes the color of the add/remove button element. | `var(--shipaid-primary)` |
|
|
132
|
-
| `--shipaid-prompt-badge-background-color` | Changes the background color of the learn more button element. | `var(--shipaid-light-grey)` |
|
|
133
|
-
| `--shipaid-prompt-badge-text-color` | Changes the color of the learn more button element. | `var(--shipaid-text)` |
|
|
134
|
-
| `--shipaid-logo-height` | Changes the height of ShipAid logo. | `var(--shipaid-logo-height, 35px)` |
|
|
135
|
-
| `--shipaid-logo-max-height` | Changes the max height of ShipAid logo. | `var(--shipaid-logo-max-height, 35px)` |
|
|
136
|
-
| `--shipaid-logo-width` | Changes the width of ShipAid logo. | `var(--shipaid-logo-width, auto)` |
|
|
137
|
-
| `--shipaid-logo-max-width` | Changes the max width of ShipAid logo. | `var(--shipaid-logo-max-width, 50px)` |
|
|
138
|
-
| `--shipaid-prompt-footer-button-size` | Changes the height of info button in footer. | `var(--shipaid-prompt-footer-button-size, 10px)` |
|
|
139
|
-
| `--shipaid-prompt-badge-border-radius` | Changes border radius of footer | `var(--shipaid-prompt-badge-border-radius, 30px)` |
|
|
140
|
-
| `--shipaid-footer-badge-logo-height` | Changes the height of logo in footer. | `var(--shipaid-footer-badge-logo-height, 9px)` |
|
|
141
|
-
| `--shipaid-prompt-footer-location` | Changes the position of footer badge | `var(--shipaid-prompt-footer-location, flex-start)` |
|
|
142
|
-
| `--shipaid-prompt-product-actions-content` | Changes the spaces between price and add/remove button | `var(--shipaid-prompt-product-actions-content, space-between)` |
|
|
143
|
-
| `--shipaid-prompt-footer-topMargin` | Changes margin between header and badge footer | `var(--shipaid-prompt-footer-topMargin, 0px)` |
|
|
144
|
-
| `-shipaid-prompt-footer-display` | Changes the display option for footer | `var(-shipaid-prompt-footer-display, flex)` |
|
|
145
|
-
|
|
146
|
-
Other variables can be found [here](/widget/src/assets/styles.ts) (`/widget/src/assets/styles.ts`).
|
|
147
|
-
|
|
148
|
-
### Translations
|
|
149
|
-
|
|
150
|
-
This widget also supports multiple languages, using the `lit-translate` plugin. The widget language can be configured using an attribute and would usally be static, but supports reactively swapping the language if a theme needs - i.e. if a user switches the language using a select option in the theme, then the widget language could be updated at the same time by selecting the widget element, and setting the `lang` attribute.
|
|
151
|
-
|
|
152
|
-
To create lang files, you should copy the default `/lang/en.json` file, and rename it to an [ISO 639-1 code](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) - for example `cp /src/lang/en.json /src/lang/fs.json`. You can then go through each key, and translate the existing text to the relevant language. This should be all you need to do - the widget automatically (and lazily, to save bundle size) imports the relevant lang file when it is specified. It will also fallback to the default `en.json` lang file if a certain language doesn't exist yet.
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
## Contributing
|
|
156
|
-
|
|
157
|
-
### Requirements
|
|
158
|
-
|
|
159
|
-
- Node v16+
|
|
160
|
-
- PNPM
|
|
161
|
-
- Development Shopify store (with the ShipAid app installed)
|
|
162
|
-
- ShipAid API development/staging instance
|
|
163
|
-
|
|
164
|
-
### Development
|
|
165
|
-
|
|
166
|
-
You will need to make sure your development store has the ShipAid app installed, so the store and its protection product is added to the DB. You will also need to ensure the Shopify app you are testing this with has an app proxy added, and pointed towards an API instance.
|
|
167
|
-
|
|
168
|
-
```sh
|
|
169
|
-
pnpm install
|
|
170
|
-
pnpm run develop
|
|
171
|
-
```
|
|
172
|
-
|
|
173
|
-
Once the project is running, add the below to your development Shopify store `theme.liquid`:
|
|
174
|
-
|
|
175
|
-
```html
|
|
176
|
-
<!-- Dev -->
|
|
177
|
-
<script src="http://localhost:3000/src/shipaid-widget.ts"type="module" ></script>
|
|
178
|
-
|
|
179
|
-
<!-- Prod -->
|
|
180
|
-
<!-- ShipAid Widget -->
|
|
181
|
-
<script src="https://unpkg.com/ui.shipaid.com/dist/widget.es.js" type="module"></script>
|
|
182
|
-
```
|
|
183
|
-
And add the widget element where needed:
|
|
184
|
-
|
|
185
|
-
```html
|
|
186
|
-
<shipaid-widget>
|
|
187
|
-
<p>Loading ShipAid Protection</p>
|
|
188
|
-
</shipaid-widget>
|
|
189
|
-
```
|
|
190
|
-
|
|
191
|
-
### Build
|
|
192
|
-
|
|
193
|
-
Once the project has been built, you can publish the project to NPM, and users can add the script to their store using a package CDN (I.e. [Unpkg](https://unpkg.com/)).
|
|
194
|
-
|
|
195
|
-
```sh
|
|
196
|
-
pnpm install
|
|
197
|
-
pnpm run lint
|
|
198
|
-
pnpm run build
|
|
199
|
-
pnpm publish
|
|
200
|
-
```
|
|
1
|
+
# ShipAid Shopify Widget
|
|
2
|
+
|
|
3
|
+
This is the repository for the ShipAid Shopify (and possibly others in future) widget. It uses the [Lit](https://lit.dev/) web components library, so it is recommended to become familiar with it before contributing to this repository.
|
|
4
|
+
|
|
5
|
+
Using Lit provides a framework that allows us to build a reactive UI, using JSX-like syntax - no need to use JQuery etc. And it can easily be installed in a page by using the custom web component name:
|
|
6
|
+
```html
|
|
7
|
+
<shipaid-widget>Fallback Content</shipaid-widget>
|
|
8
|
+
```
|
|
9
|
+
|
|
10
|
+
## Overview
|
|
11
|
+
|
|
12
|
+
This widget provides an interface where a user can choose to add or remove ShipAid protection - this is actually a product in their store that can be added to cart. When the component is loaded, we immediately run a request to fetch the ShipAid protection product details from our API, as well as the customers current cart from the [Shopify AJAX API](https://shopify.dev/api/ajax/reference/cart).
|
|
13
|
+
Once we have this data, we can check whether the customer currently has the ShipAid product in their cart, and show either the add or remove product buttons based on this.
|
|
14
|
+
|
|
15
|
+
We also emit various [custom events](https://developer.mozilla.org/en-US/docs/Web/Events/Creating_and_triggering_events#adding_custom_data_%E2%80%93_customevent) when we add or remove the ShipAid product from the cart, so other developers can listen to these events, and update AJAX carts.
|
|
16
|
+
|
|
17
|
+
### Installation
|
|
18
|
+
|
|
19
|
+
Add the script tag to the theme - if the theme has an ajax cart, you'll likely want to add this to the `theme.liquid` file, otherwise if the store has only a cart page (`/cart`), then you can add it to just that page, to save it being unecessarily loaded when it isn't needed.
|
|
20
|
+
As we don't want to affect a stores speed at all, you should add it to the bottom of the page just before the ending body tag (`</body>`), rather than inside the `<head>` block.
|
|
21
|
+
|
|
22
|
+
```html
|
|
23
|
+
<!-- ShipAid Widget -->
|
|
24
|
+
<script src="https://unpkg.com/ui.shipaid.com/dist/widget.es.js" type="module"></script>
|
|
25
|
+
```
|
|
26
|
+
Then add the widget element where needed:
|
|
27
|
+
|
|
28
|
+
```html
|
|
29
|
+
<shipaid-widget></shipaid-widget>
|
|
30
|
+
|
|
31
|
+
<!-- Disable polling example -->
|
|
32
|
+
<shipaid-widget disablePolling></shipaid-widget>
|
|
33
|
+
|
|
34
|
+
<!-- With customised text -->
|
|
35
|
+
<shipaid-widget>
|
|
36
|
+
<p slot="loading">Loading ShipAid Protection</p>
|
|
37
|
+
</shipaid-widget>
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
#### Test Mode
|
|
41
|
+
|
|
42
|
+
Sometimes, a store won't have activated their subscription before you install the widget - in this case, the widget does not display (you will notice a message in the console reflecting this). So to force the widget to show while you are installing and testing it, you can add this query param to the page URL: `shipaid-test`.
|
|
43
|
+
For example: `https://some-store.myshopify.com/cart?shipaid-text`
|
|
44
|
+
|
|
45
|
+
### Slots
|
|
46
|
+
|
|
47
|
+
Slots, with the syntax `slot="<slot name>"`, can be used to customise the widgets content - for example, a merchant may want to add a custom subtitle, which can be done like so:
|
|
48
|
+
```html
|
|
49
|
+
<shipaid-widget>
|
|
50
|
+
<p slot="subtitle">Shipping protection is required to be able to return or refunds items.</p>
|
|
51
|
+
</shipaid-widget>
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
The default content will be replaced by any slot content. You can also add inline styles to the slots, if you need to change the font size/weight for example - but color changes should be handled by CSS variables:
|
|
55
|
+
```html
|
|
56
|
+
<span slot="title" style="font-weight: 500;">Package Protection</span>
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
| Name | Description |
|
|
60
|
+
|--------|-------------|
|
|
61
|
+
| `loading` | Replaces the text that is shown whilst the widget is loading - I.e. fetching content from the Shopify or ShipAid API's. |
|
|
62
|
+
| `title` | Replaces the default title. |
|
|
63
|
+
| `subtitle` | Replaces the default subtitle. |
|
|
64
|
+
|
|
65
|
+
### Props
|
|
66
|
+
|
|
67
|
+
This is a list of props that can be used to configure the widget:
|
|
68
|
+
|
|
69
|
+
| Prop | Description | Value/Type |
|
|
70
|
+
|--------|-------------|---------|
|
|
71
|
+
| `disablePolling` | Sets whether the cart should disable polling (enabled by default) - should be disabled if integrating manually with an ajax cart. | `boolean` |
|
|
72
|
+
| `pollingInterval` | If polling is enabled, it sets the interval (in ms) between API updates. | `number` in milliseconds |
|
|
73
|
+
| `disableRefresh ` | Sets whether the store cart should be updated when the protection item is added/removed. Add if you want to initially hide the protection product from the cart, even if it has just been added. | `boolean` |
|
|
74
|
+
| `customerId ` | Passes the information of the customer to the widget. Add if merchant wants to disable auto opt-in for some customers based on the customer tags. | `boolean` |
|
|
75
|
+
| `lang ` | Sets the widget language (see the translations section below). This value can be any supported [ISO 639-1 code](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes). | `string` defaults to `en` |
|
|
76
|
+
| `refreshCart` | Refresh the page if shipaid product quantity is greater than one to sync product qty at checkout | `boolean` |
|
|
77
|
+
| `persistPopup` | Use local storage to show popup so that popup don't re-render on script refresh | `boolean` |
|
|
78
|
+
|
|
79
|
+
### Events
|
|
80
|
+
|
|
81
|
+
This is a list of the events emitted by the widget. You can listen to these events like so:
|
|
82
|
+
```js
|
|
83
|
+
document.addEventListener('shipaid-protection-status', ({ detail }) => {
|
|
84
|
+
console.log(detail.cart) // ShopifyCart
|
|
85
|
+
})
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
| Event | Description | Payload |
|
|
89
|
+
|-------|-------------|---------|
|
|
90
|
+
| `shipaid-loaded` | Dispatched when the widget has finished fetching data from the API, and has successfully rendered. | Contains the data from the ShipAid API: [`ShipAidStore`](/types/shipaid.ts) |
|
|
91
|
+
| `shipaid-protection-status` | Dispatched when a user either adds or removes the protection product from their cart. | `{ protection: boolean, cart: ShopifyCart, lineItem: ShopifyCartItem }` |
|
|
92
|
+
|
|
93
|
+
### Methods
|
|
94
|
+
|
|
95
|
+
This is a list of public methods available on the widget HTMLElement that can be used to change protection settings. These can be used by querying the element:
|
|
96
|
+
|
|
97
|
+
```js
|
|
98
|
+
const shipAidEl = document.querySelector('shipaid-widget')
|
|
99
|
+
if (shipAidEl) await shipAidEl.updateCart()
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
| Method | Description | Payload |
|
|
103
|
+
|--------|-------------|---------|
|
|
104
|
+
| `hasProtection` | Returns a boolean which indicates whether the protection item is currently in the cart. | |
|
|
105
|
+
| `updateCart` | Updates the internal cart, and triggers any protection product updates - use this method with with ajax carts, to update protection state without needing to reload the page. | Optional - the cart object from the ajax API. |
|
|
106
|
+
| `addProtection` | Adds the relevant protection item to cart. | |
|
|
107
|
+
| `removeProtection` | Removes the protection item from the cart. | |
|
|
108
|
+
|
|
109
|
+
### Styles
|
|
110
|
+
|
|
111
|
+
If you need to change any of the widget colors to suit a specific theme, there are various CSS variables you can use to do so. These should be added to the style attribute on the widget element:
|
|
112
|
+
|
|
113
|
+
```html
|
|
114
|
+
<shipaid-widget
|
|
115
|
+
style="
|
|
116
|
+
--shipaid-text: #fff;
|
|
117
|
+
--shipaid-prompt-actions-price-color: #fff;
|
|
118
|
+
"
|
|
119
|
+
>
|
|
120
|
+
</shipaid-widget>
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
| Variable | Description | Default |
|
|
124
|
+
|----------|-------------|---------|
|
|
125
|
+
| `--shipaid-text` | Changes the global text color. | `#000000` |
|
|
126
|
+
| `--shipaid-text-muted` | Changes the global muted text color. | `#aaaaaa` |
|
|
127
|
+
| `--shipaid-prompt-margin` | Changes the margins of the main container element. | `2rem 0px 4rem auto` |
|
|
128
|
+
| `--shipaid-prompt-width` | Changes the width of the main container element. | `400px` |
|
|
129
|
+
| `--shipaid-prompt-width-mobile` | Changes the mobile width of the main container element. | `100%` |
|
|
130
|
+
| `--shipaid-prompt-actions-price-color` | Changes the color of the price element. | `var(--shipaid-text-muted)` |
|
|
131
|
+
| `--shipaid-prompt-actions-button-color` | Changes the color of the add/remove button element. | `var(--shipaid-primary)` |
|
|
132
|
+
| `--shipaid-prompt-badge-background-color` | Changes the background color of the learn more button element. | `var(--shipaid-light-grey)` |
|
|
133
|
+
| `--shipaid-prompt-badge-text-color` | Changes the color of the learn more button element. | `var(--shipaid-text)` |
|
|
134
|
+
| `--shipaid-logo-height` | Changes the height of ShipAid logo. | `var(--shipaid-logo-height, 35px)` |
|
|
135
|
+
| `--shipaid-logo-max-height` | Changes the max height of ShipAid logo. | `var(--shipaid-logo-max-height, 35px)` |
|
|
136
|
+
| `--shipaid-logo-width` | Changes the width of ShipAid logo. | `var(--shipaid-logo-width, auto)` |
|
|
137
|
+
| `--shipaid-logo-max-width` | Changes the max width of ShipAid logo. | `var(--shipaid-logo-max-width, 50px)` |
|
|
138
|
+
| `--shipaid-prompt-footer-button-size` | Changes the height of info button in footer. | `var(--shipaid-prompt-footer-button-size, 10px)` |
|
|
139
|
+
| `--shipaid-prompt-badge-border-radius` | Changes border radius of footer | `var(--shipaid-prompt-badge-border-radius, 30px)` |
|
|
140
|
+
| `--shipaid-footer-badge-logo-height` | Changes the height of logo in footer. | `var(--shipaid-footer-badge-logo-height, 9px)` |
|
|
141
|
+
| `--shipaid-prompt-footer-location` | Changes the position of footer badge | `var(--shipaid-prompt-footer-location, flex-start)` |
|
|
142
|
+
| `--shipaid-prompt-product-actions-content` | Changes the spaces between price and add/remove button | `var(--shipaid-prompt-product-actions-content, space-between)` |
|
|
143
|
+
| `--shipaid-prompt-footer-topMargin` | Changes margin between header and badge footer | `var(--shipaid-prompt-footer-topMargin, 0px)` |
|
|
144
|
+
| `-shipaid-prompt-footer-display` | Changes the display option for footer | `var(-shipaid-prompt-footer-display, flex)` |
|
|
145
|
+
|
|
146
|
+
Other variables can be found [here](/widget/src/assets/styles.ts) (`/widget/src/assets/styles.ts`).
|
|
147
|
+
|
|
148
|
+
### Translations
|
|
149
|
+
|
|
150
|
+
This widget also supports multiple languages, using the `lit-translate` plugin. The widget language can be configured using an attribute and would usally be static, but supports reactively swapping the language if a theme needs - i.e. if a user switches the language using a select option in the theme, then the widget language could be updated at the same time by selecting the widget element, and setting the `lang` attribute.
|
|
151
|
+
|
|
152
|
+
To create lang files, you should copy the default `/lang/en.json` file, and rename it to an [ISO 639-1 code](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) - for example `cp /src/lang/en.json /src/lang/fs.json`. You can then go through each key, and translate the existing text to the relevant language. This should be all you need to do - the widget automatically (and lazily, to save bundle size) imports the relevant lang file when it is specified. It will also fallback to the default `en.json` lang file if a certain language doesn't exist yet.
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
## Contributing
|
|
156
|
+
|
|
157
|
+
### Requirements
|
|
158
|
+
|
|
159
|
+
- Node v16+
|
|
160
|
+
- PNPM
|
|
161
|
+
- Development Shopify store (with the ShipAid app installed)
|
|
162
|
+
- ShipAid API development/staging instance
|
|
163
|
+
|
|
164
|
+
### Development
|
|
165
|
+
|
|
166
|
+
You will need to make sure your development store has the ShipAid app installed, so the store and its protection product is added to the DB. You will also need to ensure the Shopify app you are testing this with has an app proxy added, and pointed towards an API instance.
|
|
167
|
+
|
|
168
|
+
```sh
|
|
169
|
+
pnpm install
|
|
170
|
+
pnpm run develop
|
|
171
|
+
```
|
|
172
|
+
|
|
173
|
+
Once the project is running, add the below to your development Shopify store `theme.liquid`:
|
|
174
|
+
|
|
175
|
+
```html
|
|
176
|
+
<!-- Dev -->
|
|
177
|
+
<script src="http://localhost:3000/src/shipaid-widget.ts"type="module" ></script>
|
|
178
|
+
|
|
179
|
+
<!-- Prod -->
|
|
180
|
+
<!-- ShipAid Widget -->
|
|
181
|
+
<script src="https://unpkg.com/ui.shipaid.com/dist/widget.es.js" type="module"></script>
|
|
182
|
+
```
|
|
183
|
+
And add the widget element where needed:
|
|
184
|
+
|
|
185
|
+
```html
|
|
186
|
+
<shipaid-widget>
|
|
187
|
+
<p>Loading ShipAid Protection</p>
|
|
188
|
+
</shipaid-widget>
|
|
189
|
+
```
|
|
190
|
+
|
|
191
|
+
### Build
|
|
192
|
+
|
|
193
|
+
Once the project has been built, you can publish the project to NPM, and users can add the script to their store using a package CDN (I.e. [Unpkg](https://unpkg.com/)).
|
|
194
|
+
|
|
195
|
+
```sh
|
|
196
|
+
pnpm install
|
|
197
|
+
pnpm run lint
|
|
198
|
+
pnpm run build
|
|
199
|
+
pnpm publish
|
|
200
|
+
```
|
package/dist/widget.es.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
function calculateProtectionTotal(store, protectionProduct, cart) {
|
|
2
|
-
var _a, _b
|
|
2
|
+
var _a, _b;
|
|
3
3
|
if (!store)
|
|
4
4
|
throw new Error("Missing store settings.");
|
|
5
5
|
if (!protectionProduct)
|
|
@@ -10,23 +10,34 @@ function calculateProtectionTotal(store, protectionProduct, cart) {
|
|
|
10
10
|
if (!settings) {
|
|
11
11
|
throw new Error("Tried to find protection variant, but protection settings for this store are missing.");
|
|
12
12
|
}
|
|
13
|
-
const excludedProductSkus = Array.isArray(store == null ? void 0 : store.excludedProductSkus) ? store
|
|
14
|
-
const
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
13
|
+
const excludedProductSkus = Array.isArray(store == null ? void 0 : store.excludedProductSkus) ? store.excludedProductSkus.map((sku) => sku.trim()) : [];
|
|
14
|
+
const excludedProductIds = Array.isArray(store == null ? void 0 : store.excludedProductsVariantsId) ? store.excludedProductsVariantsId.map((id) => {
|
|
15
|
+
var _a2;
|
|
16
|
+
return parseInt(((_a2 = id.match(/\d+/)) == null ? void 0 : _a2[0]) || "", 10);
|
|
17
|
+
}) : [];
|
|
18
|
+
const isItemExcluded = (item) => {
|
|
19
|
+
if (item.sku && excludedProductSkus.includes(item.sku.trim())) {
|
|
20
|
+
return true;
|
|
21
|
+
} else if (item.variant_id && excludedProductIds.includes(item.variant_id)) {
|
|
22
|
+
return true;
|
|
23
|
+
}
|
|
24
|
+
return false;
|
|
25
|
+
};
|
|
26
|
+
const itemTotal = (cart.items || []).reduce((total, item) => {
|
|
27
|
+
return isItemExcluded(item) ? total - item.final_line_price : total;
|
|
28
|
+
}, cart.total_price || 0);
|
|
29
|
+
const protectionVariantsInCart = ((_a = cart.items) == null ? void 0 : _a.filter((item) => {
|
|
21
30
|
var _a2;
|
|
22
31
|
return (_a2 = protectionProduct == null ? void 0 : protectionProduct.variants) == null ? void 0 : _a2.some((variant) => variant.id === item.variant_id);
|
|
23
32
|
})) ?? [];
|
|
24
33
|
const protectionVariantsInCartTotal = protectionVariantsInCart.reduce((total, item) => total + item.final_line_price, 0);
|
|
25
34
|
const cartTotal = itemTotal - protectionVariantsInCartTotal;
|
|
35
|
+
if (cartTotal === 0)
|
|
36
|
+
return cartTotal;
|
|
26
37
|
if (settings.protectionType === "FIXED") {
|
|
27
38
|
if (typeof settings.defaultFee !== "number")
|
|
28
39
|
throw new Error("Missing default fee amount.");
|
|
29
|
-
if (!((
|
|
40
|
+
if (!((_b = settings.rules) == null ? void 0 : _b.length))
|
|
30
41
|
return settings.defaultFee;
|
|
31
42
|
const formattedCartTotal = cartTotal / 100;
|
|
32
43
|
const sortedRules = settings.rules.sort((a2, b) => {
|
|
@@ -1854,7 +1865,7 @@ let ShipAidWidget = class extends s$1 {
|
|
|
1854
1865
|
this._apiEndpoint = "/apps/shipaid";
|
|
1855
1866
|
this._storeDomain = ((_a = window.Shopify) == null ? void 0 : _a.shop) ?? ((_c = (_b = window.Shopify) == null ? void 0 : _b.Checkout) == null ? void 0 : _c.apiHost);
|
|
1856
1867
|
this._hasFinishedSetup = false;
|
|
1857
|
-
this._shouldShowWidget =
|
|
1868
|
+
this._shouldShowWidget = false;
|
|
1858
1869
|
this._hasProtectionInCart = false;
|
|
1859
1870
|
this.hasLoadedStrings = false;
|
|
1860
1871
|
this.intervalId = 0;
|
|
@@ -2314,7 +2325,6 @@ let ShipAidWidget = class extends s$1 {
|
|
|
2314
2325
|
return;
|
|
2315
2326
|
}
|
|
2316
2327
|
this._hasFinishedSetup = true;
|
|
2317
|
-
this._shouldShowWidget = true;
|
|
2318
2328
|
this._dispatchEvent(Events.LOADED, this._store);
|
|
2319
2329
|
setTimeout(async () => {
|
|
2320
2330
|
var _a2, _b2, _c2, _d2;
|
|
@@ -2368,7 +2378,7 @@ let ShipAidWidget = class extends s$1 {
|
|
|
2368
2378
|
useEffect(
|
|
2369
2379
|
this,
|
|
2370
2380
|
async () => {
|
|
2371
|
-
var _a, _b, _c;
|
|
2381
|
+
var _a, _b, _c, _d;
|
|
2372
2382
|
this._cartLastUpdated = /* @__PURE__ */ new Date();
|
|
2373
2383
|
if (!((_a = this._cart) == null ? void 0 : _a.items))
|
|
2374
2384
|
return;
|
|
@@ -2380,7 +2390,10 @@ let ShipAidWidget = class extends s$1 {
|
|
|
2380
2390
|
});
|
|
2381
2391
|
const protectionCartItem = (_c = this._cart) == null ? void 0 : _c.items[protectionCartItemIndex];
|
|
2382
2392
|
this._hasProtectionInCart = !!protectionCartItem;
|
|
2383
|
-
if (this.
|
|
2393
|
+
if (!this._store)
|
|
2394
|
+
return;
|
|
2395
|
+
const protectionFee = await this.calculateProtectionTotal(this._cart);
|
|
2396
|
+
if (this._cart.item_count > 0 && !!protectionCartItem && (this._cart.total_price === protectionCartItem.final_line_price || !protectionFee)) {
|
|
2384
2397
|
const removePayload = {
|
|
2385
2398
|
id: protectionCartItem.key,
|
|
2386
2399
|
quantity: 0
|
|
@@ -2392,16 +2405,25 @@ let ShipAidWidget = class extends s$1 {
|
|
|
2392
2405
|
sessionStorage.removeItem(LOCAL_STORAGE_KEY);
|
|
2393
2406
|
return await this._handleRefresh(cart2);
|
|
2394
2407
|
}
|
|
2395
|
-
if (!this._store)
|
|
2396
|
-
return;
|
|
2397
|
-
const protectionFee = await this.calculateProtectionTotal(this._cart);
|
|
2398
2408
|
const protectionVariant = this._findProtectionVariant(protectionFee);
|
|
2399
|
-
|
|
2409
|
+
if (!protectionFee) {
|
|
2410
|
+
this._protectionVariant = {
|
|
2411
|
+
id: 0,
|
|
2412
|
+
price: "0"
|
|
2413
|
+
};
|
|
2414
|
+
} else {
|
|
2415
|
+
this._protectionVariant = protectionVariant;
|
|
2416
|
+
this._shouldShowWidget = true;
|
|
2417
|
+
}
|
|
2400
2418
|
if (!(protectionVariant == null ? void 0 : protectionVariant.id)) {
|
|
2401
2419
|
this._shouldShowWidget = false;
|
|
2402
2420
|
logger.error("No matching protection variant found.");
|
|
2403
2421
|
return;
|
|
2404
2422
|
}
|
|
2423
|
+
if (!((_d = this._protectionVariant) == null ? void 0 : _d.id)) {
|
|
2424
|
+
this._shouldShowWidget = false;
|
|
2425
|
+
return;
|
|
2426
|
+
}
|
|
2405
2427
|
if (!protectionCartItem)
|
|
2406
2428
|
return;
|
|
2407
2429
|
if (protectionVariant.id === protectionCartItem.variant_id) {
|
package/dist/widget.iife.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var ShipAidWidget=function(t){"use strict";const e={calculateProtectionTotal:function(t,e,i){var o,r
|
|
1
|
+
var ShipAidWidget=function(t){"use strict";const e={calculateProtectionTotal:function(t,e,i){var o,r;if(!t)throw new Error("Missing store settings.");if(!e)throw new Error("Missing protectionProduct.");if(!i)throw new Error("Missing Shopify cart.");const s=null==t?void 0:t.protectionSettings;if(!s)throw new Error("Tried to find protection variant, but protection settings for this store are missing.");const n=Array.isArray(null==t?void 0:t.excludedProductSkus)?t.excludedProductSkus.map((t=>t.trim())):[],a=Array.isArray(null==t?void 0:t.excludedProductsVariantsId)?t.excludedProductsVariantsId.map((t=>{var e;return parseInt((null==(e=t.match(/\d+/))?void 0:e[0])||"",10)})):[],d=(i.items||[]).reduce(((t,e)=>(t=>!(!t.sku||!n.includes(t.sku.trim()))||!(!t.variant_id||!a.includes(t.variant_id)))(e)?t-e.final_line_price:t),i.total_price||0)-((null==(o=i.items)?void 0:o.filter((t=>{var i;return null==(i=null==e?void 0:e.variants)?void 0:i.some((e=>e.id===t.variant_id))})))??[]).reduce(((t,e)=>t+e.final_line_price),0);if(0===d)return d;if("FIXED"===s.protectionType){if("number"!=typeof s.defaultFee)throw new Error("Missing default fee amount.");if(!(null==(r=s.rules)?void 0:r.length))return s.defaultFee;const t=d/100,e=s.rules.sort(((t,e)=>t.rangeLower&&e.rangeLower?t.rangeLower-e.rangeLower:0)).find((e=>{const i=Boolean(e.rangeLower&&e.rangeLower<t);return e.rangeUpper?i&&e.rangeUpper>=t:i}));return"number"==typeof(null==e?void 0:e.fee)?e.fee:s.defaultFee}if("PERCENTAGE"===s.protectionType){const t=d*s.percentage/100;return t>=s.minimumFee?t:s.minimumFee}throw new Error("No protection type handler found for this store.")},findProtectionVariant:function(t,e,i){var o;if(!(null==t?void 0:t.protectionSettings)||!(null==(o=null==e?void 0:e.variants)?void 0:o.length))throw new Error("Missing product and variants from protection settings.");const r=null==e?void 0:e.variants.flatMap((t=>{if(!(null==t?void 0:t.price))return[];const e=Number(t.price);return[{...t,formattedPrice:e}]})).sort(((t,e)=>t.formattedPrice-e.formattedPrice)),s=r.find((t=>t.formattedPrice>=i));return s||r[r.length-1]}},i=t=>e=>{return"function"==typeof e?(i=t,o=e,customElements.define(i,o),o):((t,e)=>{const{kind:i,elements:o}=e;return{kind:i,elements:o,finisher(e){customElements.define(t,e)}}})(t,e);
|
|
2
2
|
/**
|
|
3
3
|
* @license
|
|
4
4
|
* Copyright 2017 Google LLC
|
|
@@ -792,7 +792,7 @@ function It(t,e,i){return t?e():null==i?void 0:i()}const Ot=u`
|
|
|
792
792
|
.shipaid-prompt .prompt-footer .prompt-footer-badge svg {
|
|
793
793
|
height:var(--shipaid-footer-badge-logo-height, 9px);
|
|
794
794
|
}
|
|
795
|
-
`;var oe=(t=>(t.LOADED="shipaid-loaded",t.STATUS_UPDATE="shipaid-protection-status",t))(oe||{}),re=Object.defineProperty,se=Object.getOwnPropertyDescriptor,ne=(t,e,i,o)=>{for(var r,s=o>1?void 0:o?se(e,i):e,n=t.length-1;n>=0;n--)(r=t[n])&&(s=(o?r(e,i,s):r(s))||s);return o&&s&&re(e,i,s),s};const ae=async(t,e)=>{try{const i=await fetch(t,e);if(!i.ok)throw new Error(await i.text());return await i.json()}catch(i){throw console.error(i),new Error("Failed to complete fetch request.")}},de=t=>console.warn(`[ShipAid] ${t}`),pe=t=>console.error(`[ShipAid] ${t}`),le="shipaid-protection",ce="shipaid-protection-popup-show",he=Object.assign({"./lang/de.json":()=>Promise.resolve().then((()=>be)).then((t=>t.default)),"./lang/en.json":()=>Promise.resolve().then((()=>ee)).then((t=>t.default)),"./lang/es.json":()=>Promise.resolve().then((()=>Le)).then((t=>t.default)),"./lang/fr.json":()=>Promise.resolve().then((()=>Te)).then((t=>t.default)),"./lang/it.json":()=>Promise.resolve().then((()=>We)).then((t=>t.default)),"./lang/pt.json":()=>Promise.resolve().then((()=>Ge)).then((t=>t.default))});var ue;ue={loader:async t=>{if("en"===t)return te;const e=Reflect.get(he,`./lang/${t}.json`);return e?await e():te}},_t=Object.assign(Object.assign({},_t),ue),t.ShipAidWidget=class extends ht{constructor(){var t,e,i;super(...arguments),this.disablePolling=!1,this.disableActions=!1,this.pollingInterval=2500,this.disableRefresh=!1,this.refreshCart=!1,this.persistPopup=!1,this.defaultToggleButton=!1,this.lang="en",this.currency=void 0,this.customerId=void 0,this._apiEndpoint="/apps/shipaid",this._storeDomain=(null==(t=window.Shopify)?void 0:t.shop)??(null==(i=null==(e=window.Shopify)?void 0:e.Checkout)?void 0:i.apiHost),this._hasFinishedSetup=!1,this._shouldShowWidget=!
|
|
795
|
+
`;var oe=(t=>(t.LOADED="shipaid-loaded",t.STATUS_UPDATE="shipaid-protection-status",t))(oe||{}),re=Object.defineProperty,se=Object.getOwnPropertyDescriptor,ne=(t,e,i,o)=>{for(var r,s=o>1?void 0:o?se(e,i):e,n=t.length-1;n>=0;n--)(r=t[n])&&(s=(o?r(e,i,s):r(s))||s);return o&&s&&re(e,i,s),s};const ae=async(t,e)=>{try{const i=await fetch(t,e);if(!i.ok)throw new Error(await i.text());return await i.json()}catch(i){throw console.error(i),new Error("Failed to complete fetch request.")}},de=t=>console.warn(`[ShipAid] ${t}`),pe=t=>console.error(`[ShipAid] ${t}`),le="shipaid-protection",ce="shipaid-protection-popup-show",he=Object.assign({"./lang/de.json":()=>Promise.resolve().then((()=>be)).then((t=>t.default)),"./lang/en.json":()=>Promise.resolve().then((()=>ee)).then((t=>t.default)),"./lang/es.json":()=>Promise.resolve().then((()=>Le)).then((t=>t.default)),"./lang/fr.json":()=>Promise.resolve().then((()=>Te)).then((t=>t.default)),"./lang/it.json":()=>Promise.resolve().then((()=>We)).then((t=>t.default)),"./lang/pt.json":()=>Promise.resolve().then((()=>Ge)).then((t=>t.default))});var ue;ue={loader:async t=>{if("en"===t)return te;const e=Reflect.get(he,`./lang/${t}.json`);return e?await e():te}},_t=Object.assign(Object.assign({},_t),ue),t.ShipAidWidget=class extends ht{constructor(){var t,e,i;super(...arguments),this.disablePolling=!1,this.disableActions=!1,this.pollingInterval=2500,this.disableRefresh=!1,this.refreshCart=!1,this.persistPopup=!1,this.defaultToggleButton=!1,this.lang="en",this.currency=void 0,this.customerId=void 0,this._apiEndpoint="/apps/shipaid",this._storeDomain=(null==(t=window.Shopify)?void 0:t.shop)??(null==(i=null==(e=window.Shopify)?void 0:e.Checkout)?void 0:i.apiHost),this._hasFinishedSetup=!1,this._shouldShowWidget=!1,this._hasProtectionInCart=!1,this.hasLoadedStrings=!1,this.intervalId=0,this._state={loading:!1,success:null,error:!1},this._popup=null,this._fetch={get:t=>ae(t),post:(t,e)=>ae(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}}shouldUpdate(t){return this.hasLoadedStrings&&super.shouldUpdate(t)}shouldPersistPopup(){return"true"===localStorage.getItem(`${ce}`)?"learn-more":null}setPopupKey(){this.persistPopup&&localStorage.setItem(`${ce}`,"true")}get shouldRefreshOnUpdate(){return!this.disablePolling&&!this.disableRefresh}get planActive(){var t,e;const{searchParams:i}=new URL(window.location.href);return(null==(t=window.Shopify)?void 0:t.designMode)||i.has("shipaid-test")?(de("Currently in preview mode."),!0):!!(null==(e=this._store)?void 0:e.planActive)}_currencyFormat(t){var e,i,o;return new Intl.NumberFormat(void 0,{currency:this.currency||(null==(i=null==(e=window.Shopify)?void 0:e.currency)?void 0:i.active)||(null==(o=this._store)?void 0:o.currency)||"USD",style:"currency"}).format(Number(t))}_dispatchEvent(t,e={}){this.dispatchEvent(new CustomEvent(t,{bubbles:!0,composed:!0,detail:e}))}_handleRefreshCart(){if(this.refreshCart)return window.location.reload()}async _handleRefresh(t){const e=Reflect.has(t,"items");if(this.shouldRefreshOnUpdate)return window.location.reload();e||await this.updateCart(),this._dispatchEvent(oe.STATUS_UPDATE,{protection:this._hasProtectionInCart,cart:e?t:this._cart,lineItem:e?this._protectionCartItem:t})}async calculateProtectionTotal(t){if(t||(t=await this._fetchCart()),!t)throw new Error("Could not fetch cart.");if(!this._store)throw new Error("Missing ShipAid store");if(!this._protectionProduct)throw new Error("Missing Shopify protection product");return e.calculateProtectionTotal(this._store,this._protectionProduct,t)}_findProtectionVariant(t){if(!this._store)throw new Error("Missing ShipAid store");if(!this._protectionProduct)throw new Error("Missing Shopify protection product");return e.findProtectionVariant(this._store,this._protectionProduct,t)}_setState(t,e){this._state={loading:"loading"===t,success:"success"===t,error:"error"===t&&(e||!0)}}async _updateProtection(){return this._hasProtectionInCart?this.removeProtection():this.addProtection()}async _fetchShipAidData(){var t,e,i,o,r;const s=(null==(t=window.Shopify)?void 0:t.shop)??(null==(i=null==(e=window.Shopify)?void 0:e.Checkout)?void 0:i.apiHost);if(!s)throw new Error("No shop found in Shopify object.");try{const t=new URL(window.location.href);t.pathname=this._apiEndpoint;const e={query:"query StoreByDomain ($store: String!) {\n store: storeByDomain (input: {store: $store}) {\n currency\n planActive\n store\n widgetAutoOptIn\n widgetPollProtection\n widgetShowCart\n excludedProductSkus\n excludedCustomersIdsAutoOptIn\n protectionSettings\n widgetConfigurations\n }\n}",variables:{store:s}},i=await this._fetch.post(t.toString(),e);if(!i)throw new Error("Missing response for store query.");if(null==(o=i.errors)?void 0:o.length)throw new Error(i.errors[0].message);if(!(null==(r=i.data)?void 0:r.store))throw new Error("Missing store from store query response.");return i.data.store}catch(n){throw console.error(n),new Error(`Could not find a store for ${this._storeDomain}`)}}async _fetchCart(){try{return await this._fetch.get("/cart.js")}catch(t){throw pe(t.message),new Error("Could not fetch cart for current domain.")}}async _fetchProduct(){try{const{product:t}=await this._fetch.get("/products/shipaid-protection.json");return t}catch(t){throw pe(t.message),new Error("Could not fetch protection product for current domain.")}}hasProtection(){return this._hasProtectionInCart}async updateCart(t){t||(t=await this._fetchCart()),this._cart=t}async addProtection(){var t,e;try{if(!this._store)throw new Error("Store has not been loaded.");if(!(null==(t=this._cart)?void 0:t.items))throw new Error("Cart has not been loaded.");if(!(null==(e=this._protectionVariant)?void 0:e.id))throw new Error("No protection variant found.");this._setState("loading");const i={quantity:1,id:this._protectionVariant.id},o=await this._fetch.post("/cart/add.js",i);await this._handleRefresh(o),this._setState("success")}catch(i){pe(i.message)}finally{this._cart=await this._fetchCart(),this._setState("success")}}async removeProtection(){try{if(!this._store)throw new Error("Store has not been loaded.");if(!this._protectionCartItem)throw new Error("Protection product not found.");this._setState("loading");const t={quantity:0,id:this._protectionCartItem.key},e=await this._fetch.post("/cart/change.js",t);await this._handleRefresh(e),this._cart=e,this._setState("success")}catch(t){pe(t.message)}finally{this._cart=await this._fetchCart(),this._setState("success")}}async attemptAddProtection(){var t,e,i,o,r,s;if(!(null==(t=this._store)?void 0:t.widgetAutoOptIn))return;if(!(null==(e=this._cart)?void 0:e.items)||!(null==(i=this._cart)?void 0:i.item_count))return;const n=null==(o=this._cart.items)?void 0:o.findIndex((t=>{var e,i;return null==(i=null==(e=this._protectionProduct)?void 0:e.variants)?void 0:i.some((e=>e.id===t.variant_id))})),a=null==(r=this._cart)?void 0:r.items[n];if(this._hasProtectionInCart=!!a,1===this._cart.item_count&&a)return;!!sessionStorage.getItem(le)||(sessionStorage.setItem(le,JSON.stringify({loaded:!0})),!this._hasProtectionInCart&&(null==(s=this._cart)?void 0:s.item_count)&&this._store.widgetShowCart&&await this.addProtection())}async handleMultipleProtectionVariants(){var t,e,i,o,r;if(!(null==(t=this._cart)?void 0:t.items)||!(null==(e=this._cart)?void 0:e.item_count))return;let s=0;if(null==(i=this._cart.items)||i.forEach((t=>{var e,i;(null==(i=null==(e=this._protectionProduct)?void 0:e.variants)?void 0:i.some((e=>e.id===t.variant_id)))&&s++})),s>1){const t=null==(o=this._cart.items)?void 0:o.findIndex((t=>{var e,i;return null==(i=null==(e=this._protectionProduct)?void 0:e.variants)?void 0:i.some((e=>e.id===t.variant_id))})),e={id:(null==(r=this._cart)?void 0:r.items[t]).key,quantity:0},i=await this._fetch.post("/cart/change.js",e);return await this._handleRefresh(i)}}learnMorePopupTemplate(){return this.persistPopup&&(this._popup=this.shouldPersistPopup()),B`
|
|
796
796
|
<shipaid-popup-learn-more
|
|
797
797
|
?active=${"learn-more"===this._popup}
|
|
798
798
|
@close=${()=>{this.persistPopup&&localStorage.removeItem(`${ce}`),this._popup=null}}
|
|
@@ -848,7 +848,7 @@ function It(t,e,i){return t?e():null==i?void 0:i()}const Ot=u`
|
|
|
848
848
|
</a>
|
|
849
849
|
</div>
|
|
850
850
|
</div>
|
|
851
|
-
`}async connectedCallback(){super.connectedCallback(),await async function(t,e=_t){const i=await e.loader(t,e);e.translationCache={},yt(t,i,e)}(this.lang),this.hasLoadedStrings=!0}render(){return Tt(this,(async()=>{var t,e,i,o,r,s;const n=document.createElement("link");n.setAttribute("href","https://fonts.googleapis.com/css2?family=Lato&display=swap"),n.setAttribute("rel","stylesheet"),document.head.appendChild(n);try{const[t,e,i]=await Promise.all([this._fetchShipAidData(),this._fetchCart(),this._fetchProduct()]);this._store=t,this._cart=e,this._protectionProduct=i}catch(a){return pe(a.message),this._hasFinishedSetup=!0,void(this._shouldShowWidget=!1)}return this.planActive?(null==(e=null==(t=this._store)?void 0:t.protectionSettings)?void 0:e.protectionType)?this._protectionProduct?(this._hasFinishedSetup=!0,this.
|
|
851
|
+
`}async connectedCallback(){super.connectedCallback(),await async function(t,e=_t){const i=await e.loader(t,e);e.translationCache={},yt(t,i,e)}(this.lang),this.hasLoadedStrings=!0}render(){return Tt(this,(async()=>{var t,e,i,o,r,s;const n=document.createElement("link");n.setAttribute("href","https://fonts.googleapis.com/css2?family=Lato&display=swap"),n.setAttribute("rel","stylesheet"),document.head.appendChild(n);try{const[t,e,i]=await Promise.all([this._fetchShipAidData(),this._fetchCart(),this._fetchProduct()]);this._store=t,this._cart=e,this._protectionProduct=i}catch(a){return pe(a.message),this._hasFinishedSetup=!0,void(this._shouldShowWidget=!1)}return this.planActive?(null==(e=null==(t=this._store)?void 0:t.protectionSettings)?void 0:e.protectionType)?this._protectionProduct?(this._hasFinishedSetup=!0,this._dispatchEvent(oe.LOADED,this._store),setTimeout((async()=>{var t,e,i,o;(null==(t=this._store)?void 0:t.widgetAutoOptIn)&&(null==(e=this._cart)?void 0:e.item_count)&&(this.customerId&&this._store.excludedCustomersIdsAutoOptIn&&(null==(i=this._store.excludedCustomersIdsAutoOptIn)?void 0:i.length)&&this._store.excludedCustomersIdsAutoOptIn.includes(`gid://shopify/Customer/${this.customerId}`)||sessionStorage.getItem(le)||(sessionStorage.setItem(le,JSON.stringify({loaded:!0})),!this._hasProtectionInCart&&(null==(o=this._cart)?void 0:o.item_count)&&this._store.widgetShowCart&&await this.addProtection()))}),500),void(this.disablePolling||(setInterval((async()=>{const t=this._cartLastUpdated;t&&(new Date).getTime()-t.getTime()<this.pollingInterval||await this.updateCart()}),this.pollingInterval),(null==(i=this._store)?void 0:i.widgetPollProtection)&&!this.intervalId&&(this.intervalId=setInterval((async()=>{await this.attemptAddProtection()}),400),localStorage.setItem(`polling-shipaid-protection_${this.intervalId}`,`${this.intervalId}`)),(null==(s=null==(r=null==(o=this._store)?void 0:o.widgetConfigurations)?void 0:r.widget)?void 0:s.pollVariantsCheck)&&setInterval((async()=>{await this.handleMultipleProtectionVariants()}),400)))):(de("No protection settings product for this store - skipping setup."),this._hasFinishedSetup=!0,void(this._shouldShowWidget=!1)):(de("No protection settings for this store - skipping setup."),this._hasFinishedSetup=!0,void(this._shouldShowWidget=!1)):(de("No plan is active for this store - skipping setup."),this._hasFinishedSetup=!0,void(this._shouldShowWidget=!1))}),[]),Tt(this,(async()=>{var t,e,i,o;if(this._cartLastUpdated=new Date,!(null==(t=this._cart)?void 0:t.items))return;const r=null==(e=this._cart.items)?void 0:e.findIndex((t=>{var e,i;return null==(i=null==(e=this._protectionProduct)?void 0:e.variants)?void 0:i.some((e=>e.id===t.variant_id))})),s=null==(i=this._cart)?void 0:i.items[r];if(this._hasProtectionInCart=!!s,!this._store)return;const n=await this.calculateProtectionTotal(this._cart);if(this._cart.item_count>0&&s&&(this._cart.total_price===s.final_line_price||!n)){const t={id:s.key,quantity:0},e=await this._fetch.post("/cart/change.js",t);return sessionStorage.removeItem(le),await this._handleRefresh(e)}const a=this._findProtectionVariant(n);if(n?(this._protectionVariant=a,this._shouldShowWidget=!0):this._protectionVariant={id:0,price:"0"},!(null==a?void 0:a.id))return this._shouldShowWidget=!1,void pe("No matching protection variant found.");if(!(null==(o=this._protectionVariant)?void 0:o.id))return void(this._shouldShowWidget=!1);if(!s)return;if(a.id===s.variant_id){if(this._protectionCartItem={...s,index:r,position:r+1},1===s.quantity)return;const t={id:s.key,quantity:1},e=await this._fetch.post("/cart/change.js",t);return this._handleRefreshCart(),await this._handleRefresh(e)}const d={updates:{[s.variant_id]:0,[a.id]:1}},p=await this._fetch.post("/cart/update.js",d);await this._handleRefresh(p)}),[this._store,this._cart]),pt(this.learnMorePopupTemplate(),document.body),B`
|
|
852
852
|
<style>
|
|
853
853
|
:host {
|
|
854
854
|
--shipaid-primary: #002bd6;
|