@tolstoy-ai/react-native-sdk 0.1.0 → 0.3.0
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 +83 -11
- package/lib/TolstoyFeed.d.ts +3 -1
- package/lib/TolstoyFeed.js +110 -10
- package/lib/TolstoyProvider.d.ts +33 -3
- package/lib/TolstoyProvider.js +26 -2
- package/lib/TolstoyTryOn.js +10 -6
- package/lib/TolstoyVideoCarousel.d.ts +2 -2
- package/lib/TolstoyVideoCarousel.js +19 -9
- package/lib/analytics.d.ts +21 -0
- package/lib/analytics.js +31 -0
- package/lib/api.d.ts +2 -0
- package/lib/api.js +16 -2
- package/lib/bridge.d.ts +13 -13
- package/lib/bridge.js +3 -4
- package/lib/config.d.ts +1 -0
- package/lib/config.js +2 -0
- package/lib/index.d.ts +3 -2
- package/lib/index.js +1 -0
- package/lib/useTolstoyVideos.js +27 -4
- package/package.json +22 -3
package/README.md
CHANGED
|
@@ -3,13 +3,14 @@
|
|
|
3
3
|
Tolstoy shoppable videos and virtual try-on for a bare React Native app. The package does not use Expo.
|
|
4
4
|
|
|
5
5
|
- Video carousels for the home screen and the product screen. The videos play natively with your `react-native-video`.
|
|
6
|
-
- A full-screen video feed with product cards. A tap on a product card calls your `onProductPress(productId, variantId)`.
|
|
6
|
+
- A full-screen video feed with product cards. A tap on a product card calls your `onProductPress(productId, variantId, handle)`.
|
|
7
7
|
- A try-on screen in a WebView. The shopper signs in with your app account or with an email.
|
|
8
|
+
- Video, play, product tap, and add to cart events for your analytics, and a cart attribute that lets Tolstoy attribute app orders to the videos.
|
|
8
9
|
|
|
9
10
|
## Requirements
|
|
10
11
|
|
|
11
12
|
- React Native 0.81 or later, with the New Architecture and Hermes.
|
|
12
|
-
- These peer packages in your app: `react-native-video` (6.16.1 or later) and `react-native-webview` (13.16 or later). Install them and their native parts as their own guides tell you.
|
|
13
|
+
- These peer packages in your app: `react-native-video` (6.16.1 or later) and `react-native-webview` (13.16 or later). Install them and their native parts as their own guides tell you. The package root needs both. `@tolstoy-ai/react-native-sdk/api` needs neither (see "Use your own player").
|
|
13
14
|
|
|
14
15
|
## Install
|
|
15
16
|
|
|
@@ -32,10 +33,13 @@ import {
|
|
|
32
33
|
<TolstoyProvider
|
|
33
34
|
appKey="<your Tolstoy app key>"
|
|
34
35
|
appUrl="<your-store>.myshopify.com"
|
|
35
|
-
|
|
36
|
-
|
|
36
|
+
anonymousId={anonymousId}
|
|
37
|
+
onProductPress={(productId, variantId, handle) => navigation.navigate('Product', { productId, variantId, handle })}
|
|
38
|
+
getAppSession={async () => customerAccessToken ?? null}
|
|
39
|
+
storefrontAccessToken="<your Storefront API public access token>"
|
|
37
40
|
onAddToCart={async (lines) => addToAppCart(lines)}
|
|
38
41
|
onOpenCart={() => navigation.navigate('Cart')}
|
|
42
|
+
onEvent={(event) => analytics.track(`tolstoy_${event.type}`, event)}
|
|
39
43
|
>
|
|
40
44
|
<TolstoyVideoCarousel publishId="<home player publish id>" />
|
|
41
45
|
<TolstoyProductVideos publishId="<product page player publish id>" productId={product.id} />
|
|
@@ -52,24 +56,92 @@ Show the try-on screen full screen, for example in a modal or as its own route:
|
|
|
52
56
|
| --- | --- | --- |
|
|
53
57
|
| `appKey` | `TolstoyProvider` | Your Tolstoy app key. |
|
|
54
58
|
| `appUrl` | `TolstoyProvider` | Your store's `*.myshopify.com` domain. |
|
|
55
|
-
| `
|
|
59
|
+
| `anonymousId` | `TolstoyProvider` | A UUID that names the shopper's device in Tolstoy analytics (see "Anonymous id"). |
|
|
60
|
+
| `onProductPress(productId, variantId?, handle?)` | `TolstoyProvider` | Opens your product screen. The ids are numeric Shopify ids. `handle` is the product handle. A product card always gives it; "View product" in try-on does not. |
|
|
56
61
|
| `getAppSession()` | `TolstoyProvider`, optional | Gives the signed-in shopper's token (see "Token contract"). Give `null` when no shopper is signed in. |
|
|
62
|
+
| `storefrontAccessToken` | `TolstoyProvider`, optional | Your store's Storefront API public access token. Set it when `getAppSession` gives a Storefront API customer access token (see "Token contract"). |
|
|
57
63
|
| `onAddToCart(lines)` | `TolstoyProvider`, optional | Adds lines (`variantId`, `quantity`) to your app's cart. Reject the promise when the add fails. Without this prop, add to cart from try-on shows an error. |
|
|
58
64
|
| `onOpenCart()` | `TolstoyProvider`, optional | Opens your cart screen. |
|
|
65
|
+
| `onEvent(event)` | `TolstoyProvider`, optional | Tells your app what the shopper does (see "Events"). |
|
|
59
66
|
| `environment` | `TolstoyProvider`, optional | `production` (default) or `dev`. |
|
|
60
67
|
| `publishId` | carousels | The publish id of a Tolstoy player. Tolstoy gives it to you. |
|
|
61
68
|
| `productId` | `TolstoyProductVideos`, `TolstoyTryOn` | The numeric Shopify product id. |
|
|
62
69
|
| `widgetId` | `TolstoyTryOn`, optional | Your app's own Tolstoy try-on widget. Tolstoy gives it to you. Without it, try-on uses the store's website try-on widget. |
|
|
63
70
|
|
|
64
|
-
`TolstoyProductVideos` shows nothing when the product has no videos. `useTolstoyVideos(publishId, productId?)` gives the same data for your own UI.
|
|
71
|
+
`TolstoyProductVideos` shows nothing when the product has no videos. `useTolstoyVideos(publishId, productId?)` gives the same data for your own UI. `TolstoyFeed` needs the `publishId` of the player whose videos it shows.
|
|
72
|
+
|
|
73
|
+
## Anonymous id
|
|
74
|
+
|
|
75
|
+
Tolstoy counts viewers by `anonymousId`. The package makes no id of its own. Create a UUID once, keep it on the device in your app's own storage, and pass the same value on every launch. An id that changes on each launch makes each launch a new viewer, and an order no longer matches the events of an earlier launch.
|
|
76
|
+
|
|
77
|
+
```tsx
|
|
78
|
+
const anonymousId = await getOrCreateStoredUuid(); // your code: read the saved UUID, or make one and save it
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
## Videos and product cards
|
|
82
|
+
|
|
83
|
+
- A video plays from its HLS stream when Tolstoy has one, and from its MP4 file when it does not.
|
|
84
|
+
- A product card shows the price of the variant that the video names. When the video names no variant, the card shows the lowest price of the variants that are in stock.
|
|
85
|
+
- When the compare-at price is higher than the price, the card shows the compare-at price struck through.
|
|
86
|
+
- When "Product price" in "Feed product card" is off in the player's design settings in Tolstoy, the cards show no price, as on the website.
|
|
87
|
+
- The video lists stay in memory for the app session. A screen that shows the same player and product again shows the list at once, with no new request. The package saves nothing to device storage. A new app session gets the lists again.
|
|
88
|
+
|
|
89
|
+
## Events
|
|
90
|
+
|
|
91
|
+
`onEvent` gets these events:
|
|
92
|
+
|
|
93
|
+
| `type` | When | Fields |
|
|
94
|
+
| --- | --- | --- |
|
|
95
|
+
| `view` | A carousel shows its videos. | `publishId`, `productId?`, `videoIds` |
|
|
96
|
+
| `play` | A video starts to play in the feed. | `publishId`, `videoId` |
|
|
97
|
+
| `product_press` | The shopper taps a product card. | `publishId`, `videoId`, `productId`, `variantId?`, `handle?` |
|
|
98
|
+
| `add_to_cart` | Your `onAddToCart` added the lines from try-on. | `productId` (the product of the try-on screen), `lines` |
|
|
99
|
+
|
|
100
|
+
The package also sends the views, plays, watch time, and product taps to Tolstoy, as the Tolstoy player on your website does. Your Tolstoy analytics then count them.
|
|
101
|
+
|
|
102
|
+
## Order attribution
|
|
103
|
+
|
|
104
|
+
Tolstoy attributes an order to the videos when the order has the cart attribute of the shopper's Tolstoy id. The website player sets this attribute. In your app, set it on the cart:
|
|
105
|
+
|
|
106
|
+
```tsx
|
|
107
|
+
import { useTolstoy } from '@tolstoy-ai/react-native-sdk';
|
|
108
|
+
|
|
109
|
+
const { cartAttributes } = useTolstoy();
|
|
110
|
+
// [{ key: '__tolstoyAnonymousId', value: '<the anonymousId>' }]
|
|
111
|
+
// Give them as `attributes` to the Storefront API cartCreate, or to cartAttributesUpdate.
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
The value is the `anonymousId` of the provider. Keep the same `anonymousId` across launches, so that the events and the order have the same id.
|
|
115
|
+
|
|
116
|
+
## Use your own player
|
|
117
|
+
|
|
118
|
+
`getVideos` gives the videos of a player with their products, as the carousels show them. Import it from `@tolstoy-ai/react-native-sdk/api`, which needs neither `react-native-video` nor `react-native-webview`. Your app can keep the result with its own cache and play the videos with its own player.
|
|
119
|
+
|
|
120
|
+
```ts
|
|
121
|
+
import { getVideos } from '@tolstoy-ai/react-native-sdk/api';
|
|
122
|
+
|
|
123
|
+
const videos = await getVideos(
|
|
124
|
+
{ appKey: '<your Tolstoy app key>', appUrl: '<your-store>.myshopify.com', environment: 'production' },
|
|
125
|
+
'<player publish id>',
|
|
126
|
+
productId // optional
|
|
127
|
+
);
|
|
128
|
+
// Each video: id, title, videoUrl (MP4), hlsUrl (when there is one), posterUrl, products.
|
|
129
|
+
```
|
|
65
130
|
|
|
66
131
|
## Token contract
|
|
67
132
|
|
|
68
|
-
`getAppSession()`
|
|
133
|
+
`getAppSession()` gives the token of the shopper who is signed in to your app. Tolstoy accepts one of these two tokens:
|
|
69
134
|
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
135
|
+
| Your app signs the shopper in with | `getAppSession()` gives | Also set |
|
|
136
|
+
| --- | --- | --- |
|
|
137
|
+
| The store's Customer Account API (OAuth) | The Customer Account API access token. It starts with `shcat_`. | Nothing |
|
|
138
|
+
| The Storefront API (`customerAccessTokenCreate`) | The Storefront API customer access token | `storefrontAccessToken` on `TolstoyProvider` |
|
|
139
|
+
|
|
140
|
+
- With a Customer Account API token, Tolstoy sends the token to the store's own Customer Account API (`https://<store>/.well-known/customer-account-api` gives its address).
|
|
141
|
+
- With a Storefront API customer access token, Tolstoy sends the token and your `storefrontAccessToken` to the Storefront API of the store that your `appKey` belongs to in Tolstoy. A token or key of another store does not sign the shopper in.
|
|
142
|
+
- Shopify tells Tolstoy the shopper's email. Tolstoy then signs the shopper in to try-on.
|
|
143
|
+
- Tolstoy does not keep the tokens.
|
|
144
|
+
- Do not give an Appbrew token or your own session token. Tolstoy cannot verify them, and the shopper must then sign in with an email.
|
|
73
145
|
- When `getAppSession` is not set, or gives `null`, the shopper signs in with an email on the try-on screen.
|
|
74
146
|
|
|
75
147
|
## How the try-on screen talks to your app
|
|
@@ -79,7 +151,7 @@ The try-on screen is a Tolstoy web page in a WebView. The page sends these messa
|
|
|
79
151
|
| Message | Prop |
|
|
80
152
|
| --- | --- |
|
|
81
153
|
| `product/open` ("View product") | `onProductPress(productId, variantId?)` |
|
|
82
|
-
| `cart/add` | `onAddToCart(lines)` |
|
|
154
|
+
| `cart/add` | `onAddToCart(lines)`, then `onEvent` with `add_to_cart` |
|
|
83
155
|
| `cart/open` | `onOpenCart()` |
|
|
84
156
|
| `go/back` (the shopper closes the chat) | the `onClose` of `TolstoyTryOn` |
|
|
85
157
|
|
package/lib/TolstoyFeed.d.ts
CHANGED
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
import type { TolstoyVideo } from './api';
|
|
2
2
|
export type TolstoyFeedProps = {
|
|
3
|
+
publishId: string;
|
|
4
|
+
productId?: string;
|
|
3
5
|
videos: TolstoyVideo[];
|
|
4
6
|
startIndex: number;
|
|
5
7
|
visible: boolean;
|
|
6
8
|
onClose: () => void;
|
|
7
9
|
};
|
|
8
|
-
export declare function TolstoyFeed({ videos, startIndex, visible, onClose }: TolstoyFeedProps): import("react/jsx-runtime").JSX.Element;
|
|
10
|
+
export declare function TolstoyFeed({ publishId, productId, videos, startIndex, visible, onClose }: TolstoyFeedProps): import("react/jsx-runtime").JSX.Element;
|
package/lib/TolstoyFeed.js
CHANGED
|
@@ -1,26 +1,125 @@
|
|
|
1
1
|
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
2
|
-
import {
|
|
3
|
-
import { FlatList, Image, Modal, Pressable, StyleSheet, Text, View, useWindowDimensions } from 'react-native';
|
|
2
|
+
import { useEffect, useRef, useState } from 'react';
|
|
3
|
+
import { AppState, FlatList, Image, Modal, Pressable, StyleSheet, Text, View, useWindowDimensions } from 'react-native';
|
|
4
4
|
import Video from 'react-native-video';
|
|
5
|
+
import { sendTolstoyEvent } from './analytics';
|
|
5
6
|
import { useTolstoy } from './TolstoyProvider';
|
|
6
7
|
const PLAYERS_AROUND_ACTIVE = 1;
|
|
7
|
-
function ProductCard({ product,
|
|
8
|
-
const
|
|
9
|
-
return (_jsxs(Pressable, { accessibilityRole: "button", style: styles.productCard, onPress: ()
|
|
10
|
-
onOpen();
|
|
11
|
-
onProductPress(product.id, product.variantId);
|
|
12
|
-
}, children: [product.imageUrl ? _jsx(Image, { source: { uri: product.imageUrl }, style: styles.productImage }) : null, _jsxs(View, { style: styles.productText, children: [_jsx(Text, { numberOfLines: 2, style: styles.productTitle, children: product.title }), product.price ? (_jsxs(Text, { style: styles.productPrice, children: [product.currencySymbol, product.price] })) : null] })] }));
|
|
8
|
+
function ProductCard({ product, onPress }) {
|
|
9
|
+
const onSale = Number(product.compareAtPrice) > Number(product.price);
|
|
10
|
+
return (_jsxs(Pressable, { accessibilityRole: "button", style: styles.productCard, onPress: onPress, children: [product.imageUrl ? _jsx(Image, { source: { uri: product.imageUrl }, style: styles.productImage }) : null, _jsxs(View, { style: styles.productText, children: [_jsx(Text, { numberOfLines: 2, style: styles.productTitle, children: product.title }), product.price ? (_jsxs(Text, { style: styles.productPrice, children: [product.currencySymbol, product.price, onSale ? (_jsxs(Text, { style: styles.compareAtPrice, children: [' ', product.currencySymbol, product.compareAtPrice] })) : null] })) : null] })] }));
|
|
13
11
|
}
|
|
14
|
-
export function TolstoyFeed({ videos, startIndex, visible, onClose }) {
|
|
12
|
+
export function TolstoyFeed({ publishId, productId, videos, startIndex, visible, onClose }) {
|
|
13
|
+
const context = useTolstoy();
|
|
14
|
+
const { onProductPress, onEvent } = context;
|
|
15
15
|
const { height, width } = useWindowDimensions();
|
|
16
16
|
const [activeIndex, setActiveIndex] = useState(startIndex);
|
|
17
17
|
const [muted, setMuted] = useState(false);
|
|
18
|
+
const durations = useRef({});
|
|
19
|
+
const played = useRef(null);
|
|
20
|
+
const watch = useRef(null);
|
|
21
|
+
const contextRef = useRef(context);
|
|
22
|
+
contextRef.current = context;
|
|
23
|
+
const productIds = (video) => video.products.map((product) => product.id);
|
|
24
|
+
// Reports attribute an order to the shopper's sessionStart, which the website player sends when it opens.
|
|
25
|
+
useEffect(() => {
|
|
26
|
+
sendTolstoyEvent(contextRef.current, 'sessionStart', {
|
|
27
|
+
publishId,
|
|
28
|
+
currentPageProductId: productId,
|
|
29
|
+
videoId: videos[startIndex]?.id,
|
|
30
|
+
});
|
|
31
|
+
}, []);
|
|
32
|
+
const startPlay = (video) => {
|
|
33
|
+
if (played.current === video.id)
|
|
34
|
+
return;
|
|
35
|
+
played.current = video.id;
|
|
36
|
+
onEvent?.({ type: 'play', publishId, videoId: video.id });
|
|
37
|
+
sendTolstoyEvent(context, 'videoLoaded', {
|
|
38
|
+
publishId,
|
|
39
|
+
currentPageProductId: productId,
|
|
40
|
+
videoId: video.id,
|
|
41
|
+
productIds: productIds(video),
|
|
42
|
+
});
|
|
43
|
+
};
|
|
44
|
+
// Counts the playback position that advanced, as the website player does, so paused time is not watch time.
|
|
45
|
+
const trackProgress = (video, currentTime) => {
|
|
46
|
+
if (watch.current?.video.id !== video.id) {
|
|
47
|
+
watch.current = { video, previousTime: currentTime, watchedTime: 0, loops: 0 };
|
|
48
|
+
}
|
|
49
|
+
const current = watch.current;
|
|
50
|
+
if (currentTime < current.previousTime) {
|
|
51
|
+
current.loops += 1;
|
|
52
|
+
current.watchedTime += currentTime;
|
|
53
|
+
}
|
|
54
|
+
else {
|
|
55
|
+
current.watchedTime += currentTime - current.previousTime;
|
|
56
|
+
}
|
|
57
|
+
current.previousTime = currentTime;
|
|
58
|
+
};
|
|
59
|
+
const flushWatch = () => {
|
|
60
|
+
const current = watch.current;
|
|
61
|
+
if (!current || current.watchedTime < 1)
|
|
62
|
+
return;
|
|
63
|
+
sendTolstoyEvent(contextRef.current, 'videoWatched', {
|
|
64
|
+
publishId,
|
|
65
|
+
currentPageProductId: productId,
|
|
66
|
+
videoId: current.video.id,
|
|
67
|
+
productIds: productIds(current.video),
|
|
68
|
+
videoWatchedTime: Math.round(current.watchedTime * 1000) / 1000,
|
|
69
|
+
videoDuration: durations.current[current.video.id] ?? 0,
|
|
70
|
+
videoLoopCount: current.loops,
|
|
71
|
+
});
|
|
72
|
+
current.watchedTime = 0;
|
|
73
|
+
current.loops = 0;
|
|
74
|
+
};
|
|
75
|
+
// Watch time is sent when the shopper scrolls to another video, closes the feed, or leaves the app.
|
|
76
|
+
useEffect(() => {
|
|
77
|
+
const subscription = AppState.addEventListener('change', (state) => {
|
|
78
|
+
if (state !== 'active')
|
|
79
|
+
flushWatch();
|
|
80
|
+
});
|
|
81
|
+
return () => {
|
|
82
|
+
subscription.remove();
|
|
83
|
+
flushWatch();
|
|
84
|
+
watch.current = null;
|
|
85
|
+
played.current = null;
|
|
86
|
+
};
|
|
87
|
+
}, [activeIndex, publishId, productId]);
|
|
18
88
|
const onViewableItemsChanged = useRef(({ viewableItems }) => {
|
|
19
89
|
const index = viewableItems[0]?.index;
|
|
20
90
|
if (typeof index === 'number')
|
|
21
91
|
setActiveIndex(index);
|
|
22
92
|
}).current;
|
|
23
|
-
const renderItem =
|
|
93
|
+
const renderItem = ({ item, index }) => (_jsxs(View, { style: { height, width }, children: [Math.abs(index - activeIndex) <= PLAYERS_AROUND_ACTIVE ? (_jsx(Video, { source: item.hlsUrl ? { uri: item.hlsUrl, type: 'm3u8' } : { uri: item.videoUrl }, poster: item.posterUrl ? { source: { uri: item.posterUrl }, resizeMode: 'cover' } : undefined, style: StyleSheet.absoluteFill, resizeMode: "cover", paused: index !== activeIndex, muted: muted, repeat: true, playInBackground: false, onLoad: ({ duration }) => {
|
|
94
|
+
durations.current[item.id] = duration;
|
|
95
|
+
}, onPlaybackStateChanged: ({ isPlaying }) => {
|
|
96
|
+
if (index !== activeIndex)
|
|
97
|
+
return;
|
|
98
|
+
if (isPlaying)
|
|
99
|
+
startPlay(item);
|
|
100
|
+
else
|
|
101
|
+
flushWatch();
|
|
102
|
+
}, onProgress: ({ currentTime }) => {
|
|
103
|
+
if (index === activeIndex)
|
|
104
|
+
trackProgress(item, currentTime);
|
|
105
|
+
} })) : item.posterUrl ? (_jsx(Image, { source: { uri: item.posterUrl }, style: StyleSheet.absoluteFill })) : null, _jsx(View, { style: styles.products, children: item.products.map((product) => (_jsx(ProductCard, { product: product, onPress: () => {
|
|
106
|
+
onClose();
|
|
107
|
+
onEvent?.({
|
|
108
|
+
type: 'product_press',
|
|
109
|
+
publishId,
|
|
110
|
+
videoId: item.id,
|
|
111
|
+
productId: product.id,
|
|
112
|
+
variantId: product.variantId,
|
|
113
|
+
handle: product.handle,
|
|
114
|
+
});
|
|
115
|
+
sendTolstoyEvent(context, 'clickViewProduct', {
|
|
116
|
+
publishId,
|
|
117
|
+
currentPageProductId: productId,
|
|
118
|
+
videoId: item.id,
|
|
119
|
+
productIds: [product.id],
|
|
120
|
+
});
|
|
121
|
+
onProductPress(product.id, product.variantId, product.handle);
|
|
122
|
+
} }, product.id))) })] }));
|
|
24
123
|
return (_jsx(Modal, { visible: visible, animationType: "slide", onRequestClose: onClose, supportedOrientations: ['portrait'], children: _jsxs(View, { style: styles.feed, children: [_jsx(FlatList, { data: videos, keyExtractor: (video) => video.id, renderItem: renderItem, pagingEnabled: true, initialScrollIndex: startIndex, getItemLayout: (_, index) => ({ length: height, offset: height * index, index }), onViewableItemsChanged: onViewableItemsChanged, viewabilityConfig: { itemVisiblePercentThreshold: 80 }, showsVerticalScrollIndicator: false, windowSize: 3 }), _jsxs(View, { style: styles.controls, children: [_jsx(Pressable, { accessibilityRole: "button", accessibilityLabel: "Close", onPress: onClose, style: styles.control, children: _jsx(Text, { style: styles.controlText, children: "\u2715" }) }), _jsx(Pressable, { accessibilityRole: "button", accessibilityLabel: muted ? 'Unmute' : 'Mute', onPress: () => setMuted(!muted), style: styles.control, children: _jsx(Text, { style: styles.controlText, children: muted ? '🔇' : '🔊' }) })] })] }) }));
|
|
25
124
|
}
|
|
26
125
|
const styles = StyleSheet.create({
|
|
@@ -48,4 +147,5 @@ const styles = StyleSheet.create({
|
|
|
48
147
|
productText: { flex: 1 },
|
|
49
148
|
productTitle: { fontSize: 14, fontWeight: '600', color: '#111' },
|
|
50
149
|
productPrice: { fontSize: 13, color: '#333', marginTop: 2 },
|
|
150
|
+
compareAtPrice: { color: '#888', textDecorationLine: 'line-through' },
|
|
51
151
|
});
|
package/lib/TolstoyProvider.d.ts
CHANGED
|
@@ -4,18 +4,48 @@ export type TolstoyCartLine = {
|
|
|
4
4
|
variantId: string;
|
|
5
5
|
quantity: number;
|
|
6
6
|
};
|
|
7
|
+
export type TolstoyEvent = {
|
|
8
|
+
type: 'view';
|
|
9
|
+
publishId: string;
|
|
10
|
+
productId?: string;
|
|
11
|
+
videoIds: string[];
|
|
12
|
+
} | {
|
|
13
|
+
type: 'play';
|
|
14
|
+
publishId: string;
|
|
15
|
+
videoId: string;
|
|
16
|
+
} | {
|
|
17
|
+
type: 'product_press';
|
|
18
|
+
publishId: string;
|
|
19
|
+
videoId: string;
|
|
20
|
+
productId: string;
|
|
21
|
+
variantId?: string;
|
|
22
|
+
handle?: string;
|
|
23
|
+
} | {
|
|
24
|
+
type: 'add_to_cart';
|
|
25
|
+
productId: string;
|
|
26
|
+
lines: TolstoyCartLine[];
|
|
27
|
+
};
|
|
28
|
+
export type TolstoyCartAttribute = {
|
|
29
|
+
key: string;
|
|
30
|
+
value: string;
|
|
31
|
+
};
|
|
7
32
|
export type TolstoyProviderProps = {
|
|
8
33
|
appKey: string;
|
|
9
34
|
appUrl: string;
|
|
10
35
|
environment?: TolstoyEnvironment;
|
|
11
|
-
|
|
36
|
+
anonymousId: string;
|
|
37
|
+
onProductPress: (productId: string, variantId?: string, handle?: string) => void;
|
|
12
38
|
getAppSession?: () => Promise<string | null>;
|
|
39
|
+
storefrontAccessToken?: string;
|
|
13
40
|
onAddToCart?: (lines: TolstoyCartLine[]) => Promise<void>;
|
|
14
41
|
onOpenCart?: () => void;
|
|
42
|
+
onEvent?: (event: TolstoyEvent) => void;
|
|
15
43
|
children: ReactNode;
|
|
16
44
|
};
|
|
17
|
-
export type TolstoyContextValue = Omit<TolstoyProviderProps, 'children' | 'environment'> & {
|
|
45
|
+
export type TolstoyContextValue = Omit<TolstoyProviderProps, 'children' | 'environment' | 'anonymousId'> & {
|
|
18
46
|
environment: TolstoyEnvironment;
|
|
47
|
+
anonymousId: string;
|
|
48
|
+
cartAttributes: TolstoyCartAttribute[];
|
|
19
49
|
};
|
|
20
|
-
export declare function TolstoyProvider({ appKey, appUrl, environment, onProductPress, getAppSession, onAddToCart, onOpenCart, children, }: TolstoyProviderProps): import("react/jsx-runtime").JSX.Element;
|
|
50
|
+
export declare function TolstoyProvider({ appKey, appUrl, environment, anonymousId, onProductPress, getAppSession, storefrontAccessToken, onAddToCart, onOpenCart, onEvent, children, }: TolstoyProviderProps): import("react/jsx-runtime").JSX.Element;
|
|
21
51
|
export declare function useTolstoy(): TolstoyContextValue;
|
package/lib/TolstoyProvider.js
CHANGED
|
@@ -1,8 +1,32 @@
|
|
|
1
1
|
import { jsx as _jsx } from "react/jsx-runtime";
|
|
2
2
|
import { createContext, useContext, useMemo } from 'react';
|
|
3
3
|
const TolstoyContext = createContext(null);
|
|
4
|
-
export function TolstoyProvider({ appKey, appUrl, environment = 'production', onProductPress, getAppSession, onAddToCart, onOpenCart, children, }) {
|
|
5
|
-
const value = useMemo(() => ({
|
|
4
|
+
export function TolstoyProvider({ appKey, appUrl, environment = 'production', anonymousId, onProductPress, getAppSession, storefrontAccessToken, onAddToCart, onOpenCart, onEvent, children, }) {
|
|
5
|
+
const value = useMemo(() => ({
|
|
6
|
+
appKey,
|
|
7
|
+
appUrl,
|
|
8
|
+
environment,
|
|
9
|
+
anonymousId,
|
|
10
|
+
// The website sets the same cart attribute, so Tolstoy attributes the order to the shopper's video events.
|
|
11
|
+
cartAttributes: [{ key: '__tolstoyAnonymousId', value: anonymousId }],
|
|
12
|
+
onProductPress,
|
|
13
|
+
getAppSession,
|
|
14
|
+
storefrontAccessToken,
|
|
15
|
+
onAddToCart,
|
|
16
|
+
onOpenCart,
|
|
17
|
+
onEvent,
|
|
18
|
+
}), [
|
|
19
|
+
appKey,
|
|
20
|
+
appUrl,
|
|
21
|
+
environment,
|
|
22
|
+
anonymousId,
|
|
23
|
+
onProductPress,
|
|
24
|
+
getAppSession,
|
|
25
|
+
storefrontAccessToken,
|
|
26
|
+
onAddToCart,
|
|
27
|
+
onOpenCart,
|
|
28
|
+
onEvent,
|
|
29
|
+
]);
|
|
6
30
|
return _jsx(TolstoyContext.Provider, { value: value, children: children });
|
|
7
31
|
}
|
|
8
32
|
export function useTolstoy() {
|
package/lib/TolstoyTryOn.js
CHANGED
|
@@ -7,10 +7,13 @@ import { ENVIRONMENTS, toQuery } from './config';
|
|
|
7
7
|
import { useTolstoy } from './TolstoyProvider';
|
|
8
8
|
const ACTION_HANDLERS = {
|
|
9
9
|
'product/open': ({ data }, { onProductPress }) => onProductPress(data.productId, data.variantId),
|
|
10
|
-
'cart/add': ({ data }, { onAddToCart }, respond) => {
|
|
10
|
+
'cart/add': ({ data }, { onAddToCart, onEvent, productId }, respond) => {
|
|
11
11
|
if (!onAddToCart)
|
|
12
12
|
return respond('error');
|
|
13
|
-
onAddToCart(data.lineItems).then(() =>
|
|
13
|
+
onAddToCart(data.lineItems).then(() => {
|
|
14
|
+
respond('success');
|
|
15
|
+
onEvent?.({ type: 'add_to_cart', productId, lines: data.lineItems });
|
|
16
|
+
}, () => respond('error'));
|
|
14
17
|
},
|
|
15
18
|
'cart/open': (_, { onOpenCart }) => onOpenCart?.(),
|
|
16
19
|
'go/back': (_, { onClose }) => onClose(),
|
|
@@ -21,7 +24,7 @@ function runAction(action, context, respond) {
|
|
|
21
24
|
}
|
|
22
25
|
export function TolstoyTryOn({ productId, widgetId, onClose }) {
|
|
23
26
|
const context = useTolstoy();
|
|
24
|
-
const { appKey, appUrl, environment, getAppSession } = context;
|
|
27
|
+
const { appKey, appUrl, environment, getAppSession, storefrontAccessToken } = context;
|
|
25
28
|
const webView = useRef(null);
|
|
26
29
|
const [session, setSession] = useState(getAppSession ? null : { token: null });
|
|
27
30
|
useEffect(() => {
|
|
@@ -36,7 +39,8 @@ export function TolstoyTryOn({ productId, widgetId, onClose }) {
|
|
|
36
39
|
if (!session) {
|
|
37
40
|
return (_jsx(View, { style: styles.loading, children: _jsx(ActivityIndicator, {}) }));
|
|
38
41
|
}
|
|
39
|
-
const
|
|
42
|
+
const appSession = storefrontAccessToken ? 'shopify-storefront' : 'shopify-customer-account';
|
|
43
|
+
const query = toQuery({ appKey, appUrl, productId, widgetId, appSession });
|
|
40
44
|
const onMessage = ({ nativeEvent }) => {
|
|
41
45
|
const action = parseBridgeAction(nativeEvent.data);
|
|
42
46
|
if (!action)
|
|
@@ -45,9 +49,9 @@ export function TolstoyTryOn({ productId, widgetId, onClose }) {
|
|
|
45
49
|
if (action.id)
|
|
46
50
|
webView.current?.injectJavaScript(respondScript(action.id, result));
|
|
47
51
|
};
|
|
48
|
-
runAction(action, { ...context, onClose }, respond);
|
|
52
|
+
runAction(action, { ...context, productId, onClose }, respond);
|
|
49
53
|
};
|
|
50
|
-
return (_jsx(WebView, { ref: webView, style: styles.webView, source: { uri: `${ENVIRONMENTS[environment].tryOnPage}?${query}` }, injectedJavaScript: appSessionScript(session.token), onMessage: onMessage, allowsInlineMediaPlayback: true, mediaPlaybackRequiresUserAction: false, javaScriptEnabled: true, domStorageEnabled: true }));
|
|
54
|
+
return (_jsx(WebView, { ref: webView, style: styles.webView, source: { uri: `${ENVIRONMENTS[environment].tryOnPage}?${query}` }, injectedJavaScript: appSessionScript(session.token, storefrontAccessToken), onMessage: onMessage, allowsInlineMediaPlayback: true, mediaPlaybackRequiresUserAction: false, javaScriptEnabled: true, domStorageEnabled: true }));
|
|
51
55
|
}
|
|
52
56
|
const styles = StyleSheet.create({
|
|
53
57
|
loading: { flex: 1, alignItems: 'center', justifyContent: 'center' },
|
|
@@ -7,5 +7,5 @@ export type TolstoyVideoCarouselProps = {
|
|
|
7
7
|
export type TolstoyProductVideosProps = TolstoyVideoCarouselProps & {
|
|
8
8
|
productId: string;
|
|
9
9
|
};
|
|
10
|
-
export declare function TolstoyVideoCarousel(
|
|
11
|
-
export declare function TolstoyProductVideos(
|
|
10
|
+
export declare function TolstoyVideoCarousel(props: TolstoyVideoCarouselProps): import("react/jsx-runtime").JSX.Element | null;
|
|
11
|
+
export declare function TolstoyProductVideos(props: TolstoyProductVideosProps): import("react/jsx-runtime").JSX.Element | null;
|
|
@@ -1,23 +1,33 @@
|
|
|
1
1
|
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
2
|
-
import { useState } from 'react';
|
|
2
|
+
import { useEffect, useRef, useState } from 'react';
|
|
3
3
|
import { FlatList, Image, Pressable, StyleSheet, Text, View } from 'react-native';
|
|
4
|
+
import { sendTolstoyEvent } from './analytics';
|
|
4
5
|
import { TolstoyFeed } from './TolstoyFeed';
|
|
6
|
+
import { useTolstoy } from './TolstoyProvider';
|
|
5
7
|
import { useTolstoyVideos } from './useTolstoyVideos';
|
|
6
|
-
function Carousel({ videos, title, style }) {
|
|
8
|
+
function Carousel({ publishId, productId, videos, title, style }) {
|
|
9
|
+
const context = useTolstoy();
|
|
7
10
|
const [openIndex, setOpenIndex] = useState(null);
|
|
8
|
-
|
|
11
|
+
// An app often passes new callbacks on each render; one carousel shown is still one view.
|
|
12
|
+
const contextRef = useRef(context);
|
|
13
|
+
contextRef.current = context;
|
|
14
|
+
useEffect(() => {
|
|
15
|
+
contextRef.current.onEvent?.({ type: 'view', publishId, productId, videoIds: videos.map((video) => video.id) });
|
|
16
|
+
sendTolstoyEvent(contextRef.current, 'embedView', { publishId, currentPageProductId: productId });
|
|
17
|
+
}, [publishId, productId, videos]);
|
|
18
|
+
return (_jsxs(View, { style: style, children: [title ? _jsx(Text, { style: styles.title, children: title }) : null, _jsx(FlatList, { horizontal: true, data: videos, keyExtractor: (video) => video.id, showsHorizontalScrollIndicator: false, contentContainerStyle: styles.list, renderItem: ({ item, index }) => (_jsxs(Pressable, { accessibilityRole: "button", accessibilityLabel: item.title ?? 'Play video', onPress: () => setOpenIndex(index), style: styles.tile, children: [item.posterUrl ? _jsx(Image, { source: { uri: item.posterUrl }, style: styles.poster }) : null, _jsx(Text, { style: styles.play, children: "\u25B6" })] })) }), openIndex !== null ? (_jsx(TolstoyFeed, { publishId: publishId, productId: productId, videos: videos, startIndex: openIndex, visible: true, onClose: () => setOpenIndex(null) })) : null] }));
|
|
9
19
|
}
|
|
10
|
-
export function TolstoyVideoCarousel(
|
|
11
|
-
const state = useTolstoyVideos(publishId);
|
|
20
|
+
export function TolstoyVideoCarousel(props) {
|
|
21
|
+
const state = useTolstoyVideos(props.publishId);
|
|
12
22
|
if (state.status !== 'ready' || !state.videos.length)
|
|
13
23
|
return null;
|
|
14
|
-
return _jsx(Carousel, { videos: state.videos
|
|
24
|
+
return _jsx(Carousel, { ...props, videos: state.videos });
|
|
15
25
|
}
|
|
16
|
-
export function TolstoyProductVideos(
|
|
17
|
-
const state = useTolstoyVideos(publishId, productId);
|
|
26
|
+
export function TolstoyProductVideos(props) {
|
|
27
|
+
const state = useTolstoyVideos(props.publishId, props.productId);
|
|
18
28
|
if (state.status !== 'ready' || !state.videos.length)
|
|
19
29
|
return null;
|
|
20
|
-
return _jsx(Carousel, { videos: state.videos
|
|
30
|
+
return _jsx(Carousel, { ...props, videos: state.videos });
|
|
21
31
|
}
|
|
22
32
|
const styles = StyleSheet.create({
|
|
23
33
|
title: { fontSize: 16, fontWeight: '600', marginHorizontal: 16, marginBottom: 8 },
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import type { TolstoyEnvironment } from './config';
|
|
2
|
+
export type TolstoyAnalyticsStore = {
|
|
3
|
+
appKey: string;
|
|
4
|
+
appUrl: string;
|
|
5
|
+
environment: TolstoyEnvironment;
|
|
6
|
+
anonymousId: string;
|
|
7
|
+
};
|
|
8
|
+
type TolstoyEventName = 'embedView' | 'sessionStart' | 'videoLoaded' | 'videoWatched' | 'clickViewProduct';
|
|
9
|
+
type TolstoyEventFields = {
|
|
10
|
+
publishId: string;
|
|
11
|
+
currentPageProductId?: string;
|
|
12
|
+
videoId?: string;
|
|
13
|
+
productIds?: string[];
|
|
14
|
+
videoWatchedTime?: number;
|
|
15
|
+
videoDuration?: number;
|
|
16
|
+
videoLoopCount?: number;
|
|
17
|
+
};
|
|
18
|
+
export declare function createTolstoyId(): string;
|
|
19
|
+
/** Sends an event to the Tolstoy analytics endpoint of the website player, so the store's reports count it. */
|
|
20
|
+
export declare function sendTolstoyEvent(store: TolstoyAnalyticsStore, eventName: TolstoyEventName, { productIds, ...fields }: TolstoyEventFields): void;
|
|
21
|
+
export {};
|
package/lib/analytics.js
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { ENVIRONMENTS } from './config';
|
|
2
|
+
// The event API keeps only RFC 4122 ids (version 0-5, variant 8-b) in anonymousId.
|
|
3
|
+
export function createTolstoyId() {
|
|
4
|
+
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (char) => {
|
|
5
|
+
const random = Math.floor(Math.random() * 16);
|
|
6
|
+
return (char === 'x' ? random : (random % 4) + 8).toString(16);
|
|
7
|
+
});
|
|
8
|
+
}
|
|
9
|
+
const sessionId = createTolstoyId();
|
|
10
|
+
/** Sends an event to the Tolstoy analytics endpoint of the website player, so the store's reports count it. */
|
|
11
|
+
export function sendTolstoyEvent(store, eventName, { productIds, ...fields }) {
|
|
12
|
+
const event = {
|
|
13
|
+
eventName,
|
|
14
|
+
appKey: store.appKey,
|
|
15
|
+
appUrl: store.appUrl,
|
|
16
|
+
// Reports take the store from the host of parentUrl; an app has no page, so it names the store.
|
|
17
|
+
parentUrl: `https://${store.appUrl}`,
|
|
18
|
+
anonymousId: store.anonymousId,
|
|
19
|
+
sessionId,
|
|
20
|
+
playerType: 'carousel',
|
|
21
|
+
isMobile: 'true',
|
|
22
|
+
timestamp: new Date().toISOString(),
|
|
23
|
+
productIds: productIds && JSON.stringify(productIds),
|
|
24
|
+
...fields,
|
|
25
|
+
};
|
|
26
|
+
fetch(ENVIRONMENTS[store.environment].eventsUrl, {
|
|
27
|
+
method: 'POST',
|
|
28
|
+
headers: { 'Content-Type': 'application/json' },
|
|
29
|
+
body: JSON.stringify(event),
|
|
30
|
+
}).catch((error) => console.warn('Tolstoy analytics event was not sent', eventName, error));
|
|
31
|
+
}
|
package/lib/api.d.ts
CHANGED
|
@@ -2,6 +2,7 @@ import type { TolstoyEnvironment } from './config';
|
|
|
2
2
|
export type TolstoyProduct = {
|
|
3
3
|
id: string;
|
|
4
4
|
variantId?: string;
|
|
5
|
+
handle?: string;
|
|
5
6
|
title?: string;
|
|
6
7
|
imageUrl?: string;
|
|
7
8
|
price?: string;
|
|
@@ -12,6 +13,7 @@ export type TolstoyVideo = {
|
|
|
12
13
|
id: string;
|
|
13
14
|
title?: string;
|
|
14
15
|
videoUrl: string;
|
|
16
|
+
hlsUrl?: string;
|
|
15
17
|
posterUrl?: string;
|
|
16
18
|
products: TolstoyProduct[];
|
|
17
19
|
};
|
package/lib/api.js
CHANGED
|
@@ -8,12 +8,19 @@ const StepSchema = z.object({
|
|
|
8
8
|
});
|
|
9
9
|
const SettingsSchema = z.union([
|
|
10
10
|
z.object({ disabled: z.literal(true) }),
|
|
11
|
-
z.object({
|
|
11
|
+
z.object({
|
|
12
|
+
steps: z.array(StepSchema).optional(),
|
|
13
|
+
mediaAssetsById: z
|
|
14
|
+
.record(z.string(), z.object({ sources: z.object({ hls: z.string().optional() }).optional() }))
|
|
15
|
+
.optional(),
|
|
16
|
+
playerSettings: z.object({ productPriceFeedEnabled: z.boolean().optional() }).optional(),
|
|
17
|
+
}),
|
|
12
18
|
]);
|
|
13
19
|
const VariantSchema = z.object({
|
|
14
20
|
id: z.string().optional(),
|
|
15
21
|
price: z.string().nullish(),
|
|
16
22
|
compareAtPrice: z.string().nullish(),
|
|
23
|
+
isInStock: z.boolean().optional(),
|
|
17
24
|
});
|
|
18
25
|
const ProductsSchema = z.record(z.string(), z.object({
|
|
19
26
|
id: z.string(),
|
|
@@ -29,6 +36,10 @@ async function getJson(url, schema) {
|
|
|
29
36
|
throw new Error(`Tolstoy request failed: ${response.status}`);
|
|
30
37
|
return schema.parse(await response.json());
|
|
31
38
|
}
|
|
39
|
+
function lowestPriceVariant(variants) {
|
|
40
|
+
const inStock = variants.filter((variant) => variant.isInStock !== false);
|
|
41
|
+
return (inStock.length ? inStock : variants).reduce((lowest, variant) => variant.price && (!lowest?.price || Number(variant.price) < Number(lowest.price)) ? variant : lowest, undefined);
|
|
42
|
+
}
|
|
32
43
|
export async function getVideos(store, publishId, productId) {
|
|
33
44
|
const { apiBase } = ENVIRONMENTS[store.environment];
|
|
34
45
|
const settingsQuery = toQuery({ publishId, appKey: store.appKey, productId });
|
|
@@ -46,21 +57,24 @@ export async function getVideos(store, publishId, productId) {
|
|
|
46
57
|
vodAssetIds: steps.map((step) => step.videoId).join(','),
|
|
47
58
|
});
|
|
48
59
|
const products = await getJson(`${apiBase}/mobile-app/config/getMobileProducts?${productsQuery}`, ProductsSchema);
|
|
60
|
+
const showPrice = settings.playerSettings?.productPriceFeedEnabled !== false;
|
|
49
61
|
return steps.map((step) => ({
|
|
50
62
|
id: step.videoId,
|
|
51
63
|
title: step.videoName,
|
|
52
64
|
videoUrl: step.videoUrl,
|
|
65
|
+
hlsUrl: settings.mediaAssetsById?.[step.videoId]?.sources?.hls,
|
|
53
66
|
posterUrl: step.posterUrl,
|
|
54
67
|
products: step.products.flatMap(({ id, variantIds }) => {
|
|
55
68
|
const product = id ? products[id] : undefined;
|
|
56
69
|
if (!product)
|
|
57
70
|
return [];
|
|
58
71
|
const variant = product.variants?.find((candidate) => candidate.id === variantIds?.[0]);
|
|
59
|
-
const shownPrice = variant ?? product.variants
|
|
72
|
+
const shownPrice = showPrice ? (variant ?? lowestPriceVariant(product.variants ?? [])) : undefined;
|
|
60
73
|
return [
|
|
61
74
|
{
|
|
62
75
|
id: product.id,
|
|
63
76
|
variantId: variant?.id,
|
|
77
|
+
handle: product.handle,
|
|
64
78
|
title: product.title,
|
|
65
79
|
imageUrl: product.imageUrl ?? undefined,
|
|
66
80
|
price: shownPrice?.price ?? undefined,
|
package/lib/bridge.d.ts
CHANGED
|
@@ -15,21 +15,21 @@ export declare const BridgeActionSchema: z.ZodDiscriminatedUnion<"name", [z.ZodO
|
|
|
15
15
|
variantId?: string | number | undefined;
|
|
16
16
|
}>;
|
|
17
17
|
}, "strip", z.ZodTypeAny, {
|
|
18
|
+
id?: string | undefined;
|
|
18
19
|
type: "action";
|
|
20
|
+
name: "product/open";
|
|
19
21
|
data: {
|
|
20
22
|
productId: string;
|
|
21
23
|
variantId?: string | undefined;
|
|
22
24
|
};
|
|
23
|
-
name: "product/open";
|
|
24
|
-
id?: string | undefined;
|
|
25
25
|
}, {
|
|
26
|
+
id?: string | undefined;
|
|
26
27
|
type: "action";
|
|
28
|
+
name: "product/open";
|
|
27
29
|
data: {
|
|
28
30
|
productId: string | number;
|
|
29
31
|
variantId?: string | number | undefined;
|
|
30
32
|
};
|
|
31
|
-
name: "product/open";
|
|
32
|
-
id?: string | undefined;
|
|
33
33
|
}>, z.ZodObject<{
|
|
34
34
|
id: z.ZodOptional<z.ZodString>;
|
|
35
35
|
type: z.ZodLiteral<"action">;
|
|
@@ -58,54 +58,54 @@ export declare const BridgeActionSchema: z.ZodDiscriminatedUnion<"name", [z.ZodO
|
|
|
58
58
|
}[];
|
|
59
59
|
}>;
|
|
60
60
|
}, "strip", z.ZodTypeAny, {
|
|
61
|
+
id?: string | undefined;
|
|
61
62
|
type: "action";
|
|
63
|
+
name: "cart/add";
|
|
62
64
|
data: {
|
|
63
65
|
lineItems: {
|
|
64
66
|
variantId: string;
|
|
65
67
|
quantity: number;
|
|
66
68
|
}[];
|
|
67
69
|
};
|
|
68
|
-
name: "cart/add";
|
|
69
|
-
id?: string | undefined;
|
|
70
70
|
}, {
|
|
71
|
+
id?: string | undefined;
|
|
71
72
|
type: "action";
|
|
73
|
+
name: "cart/add";
|
|
72
74
|
data: {
|
|
73
75
|
lineItems: {
|
|
74
76
|
variantId: string | number;
|
|
75
77
|
quantity: number;
|
|
76
78
|
}[];
|
|
77
79
|
};
|
|
78
|
-
name: "cart/add";
|
|
79
|
-
id?: string | undefined;
|
|
80
80
|
}>, z.ZodObject<{
|
|
81
81
|
id: z.ZodOptional<z.ZodString>;
|
|
82
82
|
type: z.ZodLiteral<"action">;
|
|
83
83
|
} & {
|
|
84
84
|
name: z.ZodLiteral<"cart/open">;
|
|
85
85
|
}, "strip", z.ZodTypeAny, {
|
|
86
|
+
id?: string | undefined;
|
|
86
87
|
type: "action";
|
|
87
88
|
name: "cart/open";
|
|
88
|
-
id?: string | undefined;
|
|
89
89
|
}, {
|
|
90
|
+
id?: string | undefined;
|
|
90
91
|
type: "action";
|
|
91
92
|
name: "cart/open";
|
|
92
|
-
id?: string | undefined;
|
|
93
93
|
}>, z.ZodObject<{
|
|
94
94
|
id: z.ZodOptional<z.ZodString>;
|
|
95
95
|
type: z.ZodLiteral<"action">;
|
|
96
96
|
} & {
|
|
97
97
|
name: z.ZodLiteral<"go/back">;
|
|
98
98
|
}, "strip", z.ZodTypeAny, {
|
|
99
|
+
id?: string | undefined;
|
|
99
100
|
type: "action";
|
|
100
101
|
name: "go/back";
|
|
101
|
-
id?: string | undefined;
|
|
102
102
|
}, {
|
|
103
|
+
id?: string | undefined;
|
|
103
104
|
type: "action";
|
|
104
105
|
name: "go/back";
|
|
105
|
-
id?: string | undefined;
|
|
106
106
|
}>]>;
|
|
107
107
|
export type BridgeAction = z.infer<typeof BridgeActionSchema>;
|
|
108
108
|
export type BridgeActionName = BridgeAction['name'];
|
|
109
109
|
export declare function parseBridgeAction(message: string): BridgeAction | null;
|
|
110
|
-
export declare function appSessionScript(customerAccessToken: string | null): string;
|
|
110
|
+
export declare function appSessionScript(customerAccessToken: string | null, storefrontAccessToken?: string): string;
|
|
111
111
|
export declare function respondScript(id: string, result: 'success' | 'error'): string;
|
package/lib/bridge.js
CHANGED
|
@@ -22,12 +22,11 @@ export function parseBridgeAction(message) {
|
|
|
22
22
|
return null;
|
|
23
23
|
}
|
|
24
24
|
}
|
|
25
|
-
export function appSessionScript(customerAccessToken) {
|
|
25
|
+
export function appSessionScript(customerAccessToken, storefrontAccessToken) {
|
|
26
|
+
const customerSession = { customerAccessToken: { access_token: customerAccessToken }, storefrontAccessToken };
|
|
26
27
|
const payload = {
|
|
27
28
|
messageHandlerName: 'ReactNativeWebView',
|
|
28
|
-
variables: {
|
|
29
|
-
customer: customerAccessToken ? { customerSession: { customerAccessToken: { access_token: customerAccessToken } } } : null,
|
|
30
|
-
},
|
|
29
|
+
variables: { customer: customerAccessToken ? { customerSession } : null },
|
|
31
30
|
};
|
|
32
31
|
return `window.Tapcart && window.Tapcart.mobile.load(${JSON.stringify(payload)}); true;`;
|
|
33
32
|
}
|
package/lib/config.d.ts
CHANGED
|
@@ -2,6 +2,7 @@ export type TolstoyEnvironment = 'production' | 'dev';
|
|
|
2
2
|
type EnvironmentHosts = {
|
|
3
3
|
apiBase: string;
|
|
4
4
|
tryOnPage: string;
|
|
5
|
+
eventsUrl: string;
|
|
5
6
|
};
|
|
6
7
|
export declare const ENVIRONMENTS: Record<TolstoyEnvironment, EnvironmentHosts>;
|
|
7
8
|
export declare function toQuery(params: Record<string, string | undefined>): string;
|
package/lib/config.js
CHANGED
|
@@ -2,10 +2,12 @@ export const ENVIRONMENTS = {
|
|
|
2
2
|
production: {
|
|
3
3
|
apiBase: 'https://cf-apilb.gotolstoy.com',
|
|
4
4
|
tryOnPage: 'https://play.gotolstoy.com/widget-v2/index.onyou-fullscreen.html',
|
|
5
|
+
eventsUrl: 'https://analytics-v2.gotolstoy.com/event',
|
|
5
6
|
},
|
|
6
7
|
dev: {
|
|
7
8
|
apiBase: 'https://dev-cf-apilb.gotolstoy.com',
|
|
8
9
|
tryOnPage: 'https://play-dev.gotolstoy.com/widget-v2/index.onyou-fullscreen.html',
|
|
10
|
+
eventsUrl: 'https://analytics-v2-dev.gotolstoy.com/event',
|
|
9
11
|
},
|
|
10
12
|
};
|
|
11
13
|
export function toQuery(params) {
|
package/lib/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
export { TolstoyProvider, useTolstoy } from './TolstoyProvider';
|
|
2
|
-
export type { TolstoyCartLine, TolstoyProviderProps } from './TolstoyProvider';
|
|
2
|
+
export type { TolstoyCartAttribute, TolstoyCartLine, TolstoyEvent, TolstoyProviderProps } from './TolstoyProvider';
|
|
3
3
|
export { TolstoyVideoCarousel, TolstoyProductVideos } from './TolstoyVideoCarousel';
|
|
4
4
|
export type { TolstoyVideoCarouselProps, TolstoyProductVideosProps } from './TolstoyVideoCarousel';
|
|
5
5
|
export { TolstoyFeed } from './TolstoyFeed';
|
|
@@ -8,5 +8,6 @@ export { TolstoyTryOn } from './TolstoyTryOn';
|
|
|
8
8
|
export type { TolstoyTryOnProps } from './TolstoyTryOn';
|
|
9
9
|
export { useTolstoyVideos } from './useTolstoyVideos';
|
|
10
10
|
export type { TolstoyVideosState } from './useTolstoyVideos';
|
|
11
|
-
export
|
|
11
|
+
export { getVideos } from './api';
|
|
12
|
+
export type { TolstoyProduct, TolstoyStore, TolstoyVideo } from './api';
|
|
12
13
|
export type { TolstoyEnvironment } from './config';
|
package/lib/index.js
CHANGED
package/lib/useTolstoyVideos.js
CHANGED
|
@@ -1,16 +1,39 @@
|
|
|
1
1
|
import { useEffect, useState } from 'react';
|
|
2
2
|
import { getVideos } from './api';
|
|
3
3
|
import { useTolstoy } from './TolstoyProvider';
|
|
4
|
+
// In memory for the app session: a screen that mounts again with the same player and product shows the same list.
|
|
5
|
+
const videoLists = new Map();
|
|
6
|
+
function loadVideos(key, store, publishId, productId) {
|
|
7
|
+
const cached = videoLists.get(key);
|
|
8
|
+
if (cached)
|
|
9
|
+
return cached.request;
|
|
10
|
+
const entry = {
|
|
11
|
+
request: getVideos(store, publishId, productId),
|
|
12
|
+
};
|
|
13
|
+
videoLists.set(key, entry);
|
|
14
|
+
entry.request.then((videos) => {
|
|
15
|
+
entry.videos = videos;
|
|
16
|
+
}, () => videoLists.delete(key));
|
|
17
|
+
return entry.request;
|
|
18
|
+
}
|
|
19
|
+
function cachedState(key) {
|
|
20
|
+
const videos = videoLists.get(key)?.videos;
|
|
21
|
+
return videos ? { status: 'ready', videos } : { status: 'loading' };
|
|
22
|
+
}
|
|
4
23
|
export function useTolstoyVideos(publishId, productId) {
|
|
5
24
|
const { appKey, appUrl, environment } = useTolstoy();
|
|
6
|
-
const
|
|
25
|
+
const key = JSON.stringify([environment, appKey, appUrl, publishId, productId]);
|
|
26
|
+
const [state, setState] = useState(() => cachedState(key));
|
|
7
27
|
useEffect(() => {
|
|
28
|
+
const cached = cachedState(key);
|
|
29
|
+
setState((previous) => previous.status === 'ready' && cached.status === 'ready' && previous.videos === cached.videos ? previous : cached);
|
|
30
|
+
if (cached.status === 'ready')
|
|
31
|
+
return;
|
|
8
32
|
let current = true;
|
|
9
|
-
setState({ status: '
|
|
10
|
-
getVideos({ appKey, appUrl, environment }, publishId, productId).then((videos) => current && setState({ status: 'ready', videos }), (error) => current && setState({ status: 'error', error }));
|
|
33
|
+
loadVideos(key, { appKey, appUrl, environment }, publishId, productId).then((videos) => current && setState({ status: 'ready', videos }), (error) => current && setState({ status: 'error', error }));
|
|
11
34
|
return () => {
|
|
12
35
|
current = false;
|
|
13
36
|
};
|
|
14
|
-
}, [appKey, appUrl, environment, publishId, productId]);
|
|
37
|
+
}, [key, appKey, appUrl, environment, publishId, productId]);
|
|
15
38
|
return state;
|
|
16
39
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tolstoy-ai/react-native-sdk",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"description": "Tolstoy shoppable videos and virtual try-on for bare React Native apps",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -10,6 +10,17 @@
|
|
|
10
10
|
"type": "module",
|
|
11
11
|
"main": "lib/index.js",
|
|
12
12
|
"types": "lib/index.d.ts",
|
|
13
|
+
"exports": {
|
|
14
|
+
".": {
|
|
15
|
+
"types": "./lib/index.d.ts",
|
|
16
|
+
"default": "./lib/index.js"
|
|
17
|
+
},
|
|
18
|
+
"./api": {
|
|
19
|
+
"types": "./lib/api.d.ts",
|
|
20
|
+
"default": "./lib/api.js"
|
|
21
|
+
},
|
|
22
|
+
"./package.json": "./package.json"
|
|
23
|
+
},
|
|
13
24
|
"files": [
|
|
14
25
|
"lib"
|
|
15
26
|
],
|
|
@@ -30,12 +41,20 @@
|
|
|
30
41
|
"react-native-video": ">=6.16.1",
|
|
31
42
|
"react-native-webview": ">=13.16.0"
|
|
32
43
|
},
|
|
44
|
+
"peerDependenciesMeta": {
|
|
45
|
+
"react-native-video": {
|
|
46
|
+
"optional": true
|
|
47
|
+
},
|
|
48
|
+
"react-native-webview": {
|
|
49
|
+
"optional": true
|
|
50
|
+
}
|
|
51
|
+
},
|
|
33
52
|
"devDependencies": {
|
|
34
|
-
"@types/react": "
|
|
53
|
+
"@types/react": "catalog:",
|
|
35
54
|
"react": "19.1.4",
|
|
36
55
|
"react-native": "0.81.6",
|
|
37
56
|
"react-native-video": "6.16.1",
|
|
38
57
|
"react-native-webview": "13.16.1",
|
|
39
|
-
"typescript": "
|
|
58
|
+
"typescript": "catalog:"
|
|
40
59
|
}
|
|
41
60
|
}
|