@tolstoy-ai/react-native-sdk 0.0.0-stage → 0.2.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 +148 -2
- package/lib/TolstoyFeed.d.ts +10 -0
- package/lib/TolstoyFeed.js +151 -0
- package/lib/TolstoyProvider.d.ts +51 -0
- package/lib/TolstoyProvider.js +40 -0
- package/lib/TolstoyTryOn.d.ts +6 -0
- package/lib/TolstoyTryOn.js +59 -0
- package/lib/TolstoyVideoCarousel.d.ts +11 -0
- package/lib/TolstoyVideoCarousel.js +46 -0
- package/lib/analytics.d.ts +21 -0
- package/lib/analytics.js +31 -0
- package/lib/api.d.ts +25 -0
- package/lib/api.js +87 -0
- package/lib/bridge.d.ts +111 -0
- package/lib/bridge.js +35 -0
- package/lib/config.d.ts +9 -0
- package/lib/config.js +17 -0
- package/lib/index.d.ts +13 -0
- package/lib/index.js +6 -0
- package/lib/useTolstoyVideos.d.ts +11 -0
- package/lib/useTolstoyVideos.js +39 -0
- package/package.json +58 -4
package/README.md
CHANGED
|
@@ -1,3 +1,149 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @tolstoy-ai/react-native-sdk
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Tolstoy shoppable videos and virtual try-on for a bare React Native app. The package does not use Expo.
|
|
4
|
+
|
|
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, handle)`.
|
|
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.
|
|
9
|
+
|
|
10
|
+
## Requirements
|
|
11
|
+
|
|
12
|
+
- React Native 0.81 or later, with the New Architecture and Hermes.
|
|
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").
|
|
14
|
+
|
|
15
|
+
## Install
|
|
16
|
+
|
|
17
|
+
```sh
|
|
18
|
+
npm install @tolstoy-ai/react-native-sdk
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
## Use
|
|
22
|
+
|
|
23
|
+
Put `TolstoyProvider` around the screens that show Tolstoy parts.
|
|
24
|
+
|
|
25
|
+
```tsx
|
|
26
|
+
import {
|
|
27
|
+
TolstoyProvider,
|
|
28
|
+
TolstoyVideoCarousel,
|
|
29
|
+
TolstoyProductVideos,
|
|
30
|
+
TolstoyTryOn,
|
|
31
|
+
} from '@tolstoy-ai/react-native-sdk';
|
|
32
|
+
|
|
33
|
+
<TolstoyProvider
|
|
34
|
+
appKey="<your Tolstoy app key>"
|
|
35
|
+
appUrl="<your-store>.myshopify.com"
|
|
36
|
+
onProductPress={(productId, variantId, handle) => navigation.navigate('Product', { productId, variantId, handle })}
|
|
37
|
+
getAppSession={async () => customerAccessToken ?? null}
|
|
38
|
+
storefrontAccessToken="<your Storefront API public access token>"
|
|
39
|
+
onAddToCart={async (lines) => addToAppCart(lines)}
|
|
40
|
+
onOpenCart={() => navigation.navigate('Cart')}
|
|
41
|
+
onEvent={(event) => analytics.track(`tolstoy_${event.type}`, event)}
|
|
42
|
+
>
|
|
43
|
+
<TolstoyVideoCarousel publishId="<home player publish id>" />
|
|
44
|
+
<TolstoyProductVideos publishId="<product page player publish id>" productId={product.id} />
|
|
45
|
+
</TolstoyProvider>
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
Show the try-on screen full screen, for example in a modal or as its own route:
|
|
49
|
+
|
|
50
|
+
```tsx
|
|
51
|
+
<TolstoyTryOn productId={product.id} onClose={() => navigation.goBack()} />
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
| Prop | Where | Description |
|
|
55
|
+
| --- | --- | --- |
|
|
56
|
+
| `appKey` | `TolstoyProvider` | Your Tolstoy app key. |
|
|
57
|
+
| `appUrl` | `TolstoyProvider` | Your store's `*.myshopify.com` domain. |
|
|
58
|
+
| `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. |
|
|
59
|
+
| `getAppSession()` | `TolstoyProvider`, optional | Gives the signed-in shopper's token (see "Token contract"). Give `null` when no shopper is signed in. |
|
|
60
|
+
| `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"). |
|
|
61
|
+
| `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. |
|
|
62
|
+
| `onOpenCart()` | `TolstoyProvider`, optional | Opens your cart screen. |
|
|
63
|
+
| `onEvent(event)` | `TolstoyProvider`, optional | Tells your app what the shopper does (see "Events"). |
|
|
64
|
+
| `anonymousId` | `TolstoyProvider`, optional | A UUID that names the shopper's device in Tolstoy analytics. Without it, the package makes one for each app session. |
|
|
65
|
+
| `environment` | `TolstoyProvider`, optional | `production` (default) or `dev`. |
|
|
66
|
+
| `publishId` | carousels | The publish id of a Tolstoy player. Tolstoy gives it to you. |
|
|
67
|
+
| `productId` | `TolstoyProductVideos`, `TolstoyTryOn` | The numeric Shopify product id. |
|
|
68
|
+
| `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. |
|
|
69
|
+
|
|
70
|
+
`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.
|
|
71
|
+
|
|
72
|
+
## Videos and product cards
|
|
73
|
+
|
|
74
|
+
- A video plays from its HLS stream when Tolstoy has one, and from its MP4 file when it does not.
|
|
75
|
+
- 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.
|
|
76
|
+
- When the compare-at price is higher than the price, the card shows the compare-at price struck through.
|
|
77
|
+
- 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.
|
|
78
|
+
- 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.
|
|
79
|
+
|
|
80
|
+
## Events
|
|
81
|
+
|
|
82
|
+
`onEvent` gets these events:
|
|
83
|
+
|
|
84
|
+
| `type` | When | Fields |
|
|
85
|
+
| --- | --- | --- |
|
|
86
|
+
| `view` | A carousel shows its videos. | `publishId`, `productId?`, `videoIds` |
|
|
87
|
+
| `play` | A video starts to play in the feed. | `publishId`, `videoId` |
|
|
88
|
+
| `product_press` | The shopper taps a product card. | `publishId`, `videoId`, `productId`, `variantId?`, `handle?` |
|
|
89
|
+
| `add_to_cart` | Your `onAddToCart` added the lines from try-on. | `productId` (the product of the try-on screen), `lines` |
|
|
90
|
+
|
|
91
|
+
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.
|
|
92
|
+
|
|
93
|
+
## Order attribution
|
|
94
|
+
|
|
95
|
+
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:
|
|
96
|
+
|
|
97
|
+
```tsx
|
|
98
|
+
import { useTolstoy } from '@tolstoy-ai/react-native-sdk';
|
|
99
|
+
|
|
100
|
+
const { cartAttributes } = useTolstoy();
|
|
101
|
+
// [{ key: '__tolstoyAnonymousId', value: '<the anonymousId>' }]
|
|
102
|
+
// Give them as `attributes` to the Storefront API cartCreate, or to cartAttributesUpdate.
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
The value is the `anonymousId` of the provider. Use the same `anonymousId` for the whole app session, so that the events and the order have the same id.
|
|
106
|
+
|
|
107
|
+
## Use your own player
|
|
108
|
+
|
|
109
|
+
`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.
|
|
110
|
+
|
|
111
|
+
```ts
|
|
112
|
+
import { getVideos } from '@tolstoy-ai/react-native-sdk/api';
|
|
113
|
+
|
|
114
|
+
const videos = await getVideos(
|
|
115
|
+
{ appKey: '<your Tolstoy app key>', appUrl: '<your-store>.myshopify.com', environment: 'production' },
|
|
116
|
+
'<player publish id>',
|
|
117
|
+
productId // optional
|
|
118
|
+
);
|
|
119
|
+
// Each video: id, title, videoUrl (MP4), hlsUrl (when there is one), posterUrl, products.
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
## Token contract
|
|
123
|
+
|
|
124
|
+
`getAppSession()` gives the token of the shopper who is signed in to your app. Tolstoy accepts one of these two tokens:
|
|
125
|
+
|
|
126
|
+
| Your app signs the shopper in with | `getAppSession()` gives | Also set |
|
|
127
|
+
| --- | --- | --- |
|
|
128
|
+
| The store's Customer Account API (OAuth) | The Customer Account API access token. It starts with `shcat_`. | Nothing |
|
|
129
|
+
| The Storefront API (`customerAccessTokenCreate`) | The Storefront API customer access token | `storefrontAccessToken` on `TolstoyProvider` |
|
|
130
|
+
|
|
131
|
+
- 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).
|
|
132
|
+
- 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.
|
|
133
|
+
- Shopify tells Tolstoy the shopper's email. Tolstoy then signs the shopper in to try-on.
|
|
134
|
+
- Tolstoy does not keep the tokens.
|
|
135
|
+
- 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.
|
|
136
|
+
- When `getAppSession` is not set, or gives `null`, the shopper signs in with an email on the try-on screen.
|
|
137
|
+
|
|
138
|
+
## How the try-on screen talks to your app
|
|
139
|
+
|
|
140
|
+
The try-on screen is a Tolstoy web page in a WebView. The page sends these messages to the package, and the package calls your props:
|
|
141
|
+
|
|
142
|
+
| Message | Prop |
|
|
143
|
+
| --- | --- |
|
|
144
|
+
| `product/open` ("View product") | `onProductPress(productId, variantId?)` |
|
|
145
|
+
| `cart/add` | `onAddToCart(lines)`, then `onEvent` with `add_to_cart` |
|
|
146
|
+
| `cart/open` | `onOpenCart()` |
|
|
147
|
+
| `go/back` (the shopper closes the chat) | the `onClose` of `TolstoyTryOn` |
|
|
148
|
+
|
|
149
|
+
Try-on works only for a store that has the Tolstoy shopper chat switched on.
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { TolstoyVideo } from './api';
|
|
2
|
+
export type TolstoyFeedProps = {
|
|
3
|
+
publishId: string;
|
|
4
|
+
productId?: string;
|
|
5
|
+
videos: TolstoyVideo[];
|
|
6
|
+
startIndex: number;
|
|
7
|
+
visible: boolean;
|
|
8
|
+
onClose: () => void;
|
|
9
|
+
};
|
|
10
|
+
export declare function TolstoyFeed({ publishId, productId, videos, startIndex, visible, onClose }: TolstoyFeedProps): import("react/jsx-runtime").JSX.Element;
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
2
|
+
import { useEffect, useRef, useState } from 'react';
|
|
3
|
+
import { AppState, FlatList, Image, Modal, Pressable, StyleSheet, Text, View, useWindowDimensions } from 'react-native';
|
|
4
|
+
import Video from 'react-native-video';
|
|
5
|
+
import { sendTolstoyEvent } from './analytics';
|
|
6
|
+
import { useTolstoy } from './TolstoyProvider';
|
|
7
|
+
const PLAYERS_AROUND_ACTIVE = 1;
|
|
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] })] }));
|
|
11
|
+
}
|
|
12
|
+
export function TolstoyFeed({ publishId, productId, videos, startIndex, visible, onClose }) {
|
|
13
|
+
const context = useTolstoy();
|
|
14
|
+
const { onProductPress, onEvent } = context;
|
|
15
|
+
const { height, width } = useWindowDimensions();
|
|
16
|
+
const [activeIndex, setActiveIndex] = useState(startIndex);
|
|
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]);
|
|
88
|
+
const onViewableItemsChanged = useRef(({ viewableItems }) => {
|
|
89
|
+
const index = viewableItems[0]?.index;
|
|
90
|
+
if (typeof index === 'number')
|
|
91
|
+
setActiveIndex(index);
|
|
92
|
+
}).current;
|
|
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))) })] }));
|
|
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 ? '🔇' : '🔊' }) })] })] }) }));
|
|
124
|
+
}
|
|
125
|
+
const styles = StyleSheet.create({
|
|
126
|
+
feed: { flex: 1, backgroundColor: '#000' },
|
|
127
|
+
controls: { position: 'absolute', top: 56, right: 16, gap: 12 },
|
|
128
|
+
control: {
|
|
129
|
+
width: 40,
|
|
130
|
+
height: 40,
|
|
131
|
+
borderRadius: 20,
|
|
132
|
+
backgroundColor: 'rgba(0,0,0,0.45)',
|
|
133
|
+
alignItems: 'center',
|
|
134
|
+
justifyContent: 'center',
|
|
135
|
+
},
|
|
136
|
+
controlText: { color: '#fff', fontSize: 18 },
|
|
137
|
+
products: { position: 'absolute', left: 16, right: 16, bottom: 48, gap: 8 },
|
|
138
|
+
productCard: {
|
|
139
|
+
flexDirection: 'row',
|
|
140
|
+
alignItems: 'center',
|
|
141
|
+
gap: 12,
|
|
142
|
+
padding: 8,
|
|
143
|
+
borderRadius: 12,
|
|
144
|
+
backgroundColor: 'rgba(255,255,255,0.95)',
|
|
145
|
+
},
|
|
146
|
+
productImage: { width: 48, height: 48, borderRadius: 8 },
|
|
147
|
+
productText: { flex: 1 },
|
|
148
|
+
productTitle: { fontSize: 14, fontWeight: '600', color: '#111' },
|
|
149
|
+
productPrice: { fontSize: 13, color: '#333', marginTop: 2 },
|
|
150
|
+
compareAtPrice: { color: '#888', textDecorationLine: 'line-through' },
|
|
151
|
+
});
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import type { ReactNode } from 'react';
|
|
2
|
+
import type { TolstoyEnvironment } from './config';
|
|
3
|
+
export type TolstoyCartLine = {
|
|
4
|
+
variantId: string;
|
|
5
|
+
quantity: number;
|
|
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
|
+
};
|
|
32
|
+
export type TolstoyProviderProps = {
|
|
33
|
+
appKey: string;
|
|
34
|
+
appUrl: string;
|
|
35
|
+
environment?: TolstoyEnvironment;
|
|
36
|
+
anonymousId?: string;
|
|
37
|
+
onProductPress: (productId: string, variantId?: string, handle?: string) => void;
|
|
38
|
+
getAppSession?: () => Promise<string | null>;
|
|
39
|
+
storefrontAccessToken?: string;
|
|
40
|
+
onAddToCart?: (lines: TolstoyCartLine[]) => Promise<void>;
|
|
41
|
+
onOpenCart?: () => void;
|
|
42
|
+
onEvent?: (event: TolstoyEvent) => void;
|
|
43
|
+
children: ReactNode;
|
|
44
|
+
};
|
|
45
|
+
export type TolstoyContextValue = Omit<TolstoyProviderProps, 'children' | 'environment' | 'anonymousId'> & {
|
|
46
|
+
environment: TolstoyEnvironment;
|
|
47
|
+
anonymousId: string;
|
|
48
|
+
cartAttributes: TolstoyCartAttribute[];
|
|
49
|
+
};
|
|
50
|
+
export declare function TolstoyProvider({ appKey, appUrl, environment, anonymousId, onProductPress, getAppSession, storefrontAccessToken, onAddToCart, onOpenCart, onEvent, children, }: TolstoyProviderProps): import("react/jsx-runtime").JSX.Element;
|
|
51
|
+
export declare function useTolstoy(): TolstoyContextValue;
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { jsx as _jsx } from "react/jsx-runtime";
|
|
2
|
+
import { createContext, useContext, useMemo } from 'react';
|
|
3
|
+
import { createTolstoyId } from './analytics';
|
|
4
|
+
// Without an anonymousId from the app, the shopper is one Tolstoy visitor for the app session.
|
|
5
|
+
const sessionAnonymousId = createTolstoyId();
|
|
6
|
+
const TolstoyContext = createContext(null);
|
|
7
|
+
export function TolstoyProvider({ appKey, appUrl, environment = 'production', anonymousId = sessionAnonymousId, onProductPress, getAppSession, storefrontAccessToken, onAddToCart, onOpenCart, onEvent, children, }) {
|
|
8
|
+
const value = useMemo(() => ({
|
|
9
|
+
appKey,
|
|
10
|
+
appUrl,
|
|
11
|
+
environment,
|
|
12
|
+
anonymousId,
|
|
13
|
+
// The website sets the same cart attribute, so Tolstoy attributes the order to the shopper's video events.
|
|
14
|
+
cartAttributes: [{ key: '__tolstoyAnonymousId', value: anonymousId }],
|
|
15
|
+
onProductPress,
|
|
16
|
+
getAppSession,
|
|
17
|
+
storefrontAccessToken,
|
|
18
|
+
onAddToCart,
|
|
19
|
+
onOpenCart,
|
|
20
|
+
onEvent,
|
|
21
|
+
}), [
|
|
22
|
+
appKey,
|
|
23
|
+
appUrl,
|
|
24
|
+
environment,
|
|
25
|
+
anonymousId,
|
|
26
|
+
onProductPress,
|
|
27
|
+
getAppSession,
|
|
28
|
+
storefrontAccessToken,
|
|
29
|
+
onAddToCart,
|
|
30
|
+
onOpenCart,
|
|
31
|
+
onEvent,
|
|
32
|
+
]);
|
|
33
|
+
return _jsx(TolstoyContext.Provider, { value: value, children: children });
|
|
34
|
+
}
|
|
35
|
+
export function useTolstoy() {
|
|
36
|
+
const value = useContext(TolstoyContext);
|
|
37
|
+
if (!value)
|
|
38
|
+
throw new Error('Put Tolstoy components inside <TolstoyProvider>.');
|
|
39
|
+
return value;
|
|
40
|
+
}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { jsx as _jsx } from "react/jsx-runtime";
|
|
2
|
+
import { useEffect, useRef, useState } from 'react';
|
|
3
|
+
import { ActivityIndicator, StyleSheet, View } from 'react-native';
|
|
4
|
+
import { WebView } from 'react-native-webview';
|
|
5
|
+
import { appSessionScript, parseBridgeAction, respondScript } from './bridge';
|
|
6
|
+
import { ENVIRONMENTS, toQuery } from './config';
|
|
7
|
+
import { useTolstoy } from './TolstoyProvider';
|
|
8
|
+
const ACTION_HANDLERS = {
|
|
9
|
+
'product/open': ({ data }, { onProductPress }) => onProductPress(data.productId, data.variantId),
|
|
10
|
+
'cart/add': ({ data }, { onAddToCart, onEvent, productId }, respond) => {
|
|
11
|
+
if (!onAddToCart)
|
|
12
|
+
return respond('error');
|
|
13
|
+
onAddToCart(data.lineItems).then(() => {
|
|
14
|
+
respond('success');
|
|
15
|
+
onEvent?.({ type: 'add_to_cart', productId, lines: data.lineItems });
|
|
16
|
+
}, () => respond('error'));
|
|
17
|
+
},
|
|
18
|
+
'cart/open': (_, { onOpenCart }) => onOpenCart?.(),
|
|
19
|
+
'go/back': (_, { onClose }) => onClose(),
|
|
20
|
+
};
|
|
21
|
+
function runAction(action, context, respond) {
|
|
22
|
+
const handler = ACTION_HANDLERS[action.name];
|
|
23
|
+
handler(action, context, respond);
|
|
24
|
+
}
|
|
25
|
+
export function TolstoyTryOn({ productId, widgetId, onClose }) {
|
|
26
|
+
const context = useTolstoy();
|
|
27
|
+
const { appKey, appUrl, environment, getAppSession, storefrontAccessToken } = context;
|
|
28
|
+
const webView = useRef(null);
|
|
29
|
+
const [session, setSession] = useState(getAppSession ? null : { token: null });
|
|
30
|
+
useEffect(() => {
|
|
31
|
+
if (!getAppSession)
|
|
32
|
+
return;
|
|
33
|
+
let current = true;
|
|
34
|
+
getAppSession().then((token) => current && setSession({ token }), () => current && setSession({ token: null }));
|
|
35
|
+
return () => {
|
|
36
|
+
current = false;
|
|
37
|
+
};
|
|
38
|
+
}, [getAppSession]);
|
|
39
|
+
if (!session) {
|
|
40
|
+
return (_jsx(View, { style: styles.loading, children: _jsx(ActivityIndicator, {}) }));
|
|
41
|
+
}
|
|
42
|
+
const appSession = storefrontAccessToken ? 'shopify-storefront' : 'shopify-customer-account';
|
|
43
|
+
const query = toQuery({ appKey, appUrl, productId, widgetId, appSession });
|
|
44
|
+
const onMessage = ({ nativeEvent }) => {
|
|
45
|
+
const action = parseBridgeAction(nativeEvent.data);
|
|
46
|
+
if (!action)
|
|
47
|
+
return;
|
|
48
|
+
const respond = (result) => {
|
|
49
|
+
if (action.id)
|
|
50
|
+
webView.current?.injectJavaScript(respondScript(action.id, result));
|
|
51
|
+
};
|
|
52
|
+
runAction(action, { ...context, productId, onClose }, respond);
|
|
53
|
+
};
|
|
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 }));
|
|
55
|
+
}
|
|
56
|
+
const styles = StyleSheet.create({
|
|
57
|
+
loading: { flex: 1, alignItems: 'center', justifyContent: 'center' },
|
|
58
|
+
webView: { flex: 1 },
|
|
59
|
+
});
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { StyleProp, ViewStyle } from 'react-native';
|
|
2
|
+
export type TolstoyVideoCarouselProps = {
|
|
3
|
+
publishId: string;
|
|
4
|
+
title?: string;
|
|
5
|
+
style?: StyleProp<ViewStyle>;
|
|
6
|
+
};
|
|
7
|
+
export type TolstoyProductVideosProps = TolstoyVideoCarouselProps & {
|
|
8
|
+
productId: string;
|
|
9
|
+
};
|
|
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;
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
2
|
+
import { useEffect, useRef, useState } from 'react';
|
|
3
|
+
import { FlatList, Image, Pressable, StyleSheet, Text, View } from 'react-native';
|
|
4
|
+
import { sendTolstoyEvent } from './analytics';
|
|
5
|
+
import { TolstoyFeed } from './TolstoyFeed';
|
|
6
|
+
import { useTolstoy } from './TolstoyProvider';
|
|
7
|
+
import { useTolstoyVideos } from './useTolstoyVideos';
|
|
8
|
+
function Carousel({ publishId, productId, videos, title, style }) {
|
|
9
|
+
const context = useTolstoy();
|
|
10
|
+
const [openIndex, setOpenIndex] = useState(null);
|
|
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] }));
|
|
19
|
+
}
|
|
20
|
+
export function TolstoyVideoCarousel(props) {
|
|
21
|
+
const state = useTolstoyVideos(props.publishId);
|
|
22
|
+
if (state.status !== 'ready' || !state.videos.length)
|
|
23
|
+
return null;
|
|
24
|
+
return _jsx(Carousel, { ...props, videos: state.videos });
|
|
25
|
+
}
|
|
26
|
+
export function TolstoyProductVideos(props) {
|
|
27
|
+
const state = useTolstoyVideos(props.publishId, props.productId);
|
|
28
|
+
if (state.status !== 'ready' || !state.videos.length)
|
|
29
|
+
return null;
|
|
30
|
+
return _jsx(Carousel, { ...props, videos: state.videos });
|
|
31
|
+
}
|
|
32
|
+
const styles = StyleSheet.create({
|
|
33
|
+
title: { fontSize: 16, fontWeight: '600', marginHorizontal: 16, marginBottom: 8 },
|
|
34
|
+
list: { paddingHorizontal: 16, gap: 8 },
|
|
35
|
+
tile: {
|
|
36
|
+
width: 120,
|
|
37
|
+
height: 213,
|
|
38
|
+
borderRadius: 12,
|
|
39
|
+
overflow: 'hidden',
|
|
40
|
+
backgroundColor: '#eee',
|
|
41
|
+
alignItems: 'center',
|
|
42
|
+
justifyContent: 'center',
|
|
43
|
+
},
|
|
44
|
+
poster: { ...StyleSheet.absoluteFillObject },
|
|
45
|
+
play: { color: '#fff', fontSize: 28, textShadowColor: 'rgba(0,0,0,0.5)', textShadowRadius: 6 },
|
|
46
|
+
});
|
|
@@ -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
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import type { TolstoyEnvironment } from './config';
|
|
2
|
+
export type TolstoyProduct = {
|
|
3
|
+
id: string;
|
|
4
|
+
variantId?: string;
|
|
5
|
+
handle?: string;
|
|
6
|
+
title?: string;
|
|
7
|
+
imageUrl?: string;
|
|
8
|
+
price?: string;
|
|
9
|
+
compareAtPrice?: string;
|
|
10
|
+
currencySymbol?: string;
|
|
11
|
+
};
|
|
12
|
+
export type TolstoyVideo = {
|
|
13
|
+
id: string;
|
|
14
|
+
title?: string;
|
|
15
|
+
videoUrl: string;
|
|
16
|
+
hlsUrl?: string;
|
|
17
|
+
posterUrl?: string;
|
|
18
|
+
products: TolstoyProduct[];
|
|
19
|
+
};
|
|
20
|
+
export type TolstoyStore = {
|
|
21
|
+
appKey: string;
|
|
22
|
+
appUrl: string;
|
|
23
|
+
environment: TolstoyEnvironment;
|
|
24
|
+
};
|
|
25
|
+
export declare function getVideos(store: TolstoyStore, publishId: string, productId?: string): Promise<TolstoyVideo[]>;
|
package/lib/api.js
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import { ENVIRONMENTS, toQuery } from './config';
|
|
3
|
+
const StepSchema = z.object({
|
|
4
|
+
videoId: z.string().optional(),
|
|
5
|
+
videoName: z.string().optional(),
|
|
6
|
+
products: z.array(z.object({ id: z.string().optional(), variantIds: z.array(z.string()).optional() })).optional(),
|
|
7
|
+
stockAsset: z.object({ videoUrl: z.string().optional(), posterUrl: z.string().optional() }).optional(),
|
|
8
|
+
});
|
|
9
|
+
const SettingsSchema = z.union([
|
|
10
|
+
z.object({ disabled: z.literal(true) }),
|
|
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
|
+
}),
|
|
18
|
+
]);
|
|
19
|
+
const VariantSchema = z.object({
|
|
20
|
+
id: z.string().optional(),
|
|
21
|
+
price: z.string().nullish(),
|
|
22
|
+
compareAtPrice: z.string().nullish(),
|
|
23
|
+
isInStock: z.boolean().optional(),
|
|
24
|
+
});
|
|
25
|
+
const ProductsSchema = z.record(z.string(), z.object({
|
|
26
|
+
id: z.string(),
|
|
27
|
+
title: z.string().optional(),
|
|
28
|
+
imageUrl: z.string().nullish(),
|
|
29
|
+
currencySymbol: z.string().nullish(),
|
|
30
|
+
handle: z.string().optional(),
|
|
31
|
+
variants: z.array(VariantSchema).optional(),
|
|
32
|
+
}));
|
|
33
|
+
async function getJson(url, schema) {
|
|
34
|
+
const response = await fetch(url);
|
|
35
|
+
if (!response.ok)
|
|
36
|
+
throw new Error(`Tolstoy request failed: ${response.status}`);
|
|
37
|
+
return schema.parse(await response.json());
|
|
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
|
+
}
|
|
43
|
+
export async function getVideos(store, publishId, productId) {
|
|
44
|
+
const { apiBase } = ENVIRONMENTS[store.environment];
|
|
45
|
+
const settingsQuery = toQuery({ publishId, appKey: store.appKey, productId });
|
|
46
|
+
const settings = await getJson(`${apiBase}/mobile-app/config/getMobileSettings?${settingsQuery}`, SettingsSchema);
|
|
47
|
+
if ('disabled' in settings)
|
|
48
|
+
return [];
|
|
49
|
+
const steps = (settings.steps ?? []).flatMap(({ videoId, videoName, products, stockAsset }) => videoId && stockAsset?.videoUrl
|
|
50
|
+
? [{ videoId, videoName, products: products ?? [], videoUrl: stockAsset.videoUrl, posterUrl: stockAsset.posterUrl }]
|
|
51
|
+
: []);
|
|
52
|
+
if (!steps.length)
|
|
53
|
+
return [];
|
|
54
|
+
const productsQuery = toQuery({
|
|
55
|
+
appUrl: store.appUrl,
|
|
56
|
+
appKey: store.appKey,
|
|
57
|
+
vodAssetIds: steps.map((step) => step.videoId).join(','),
|
|
58
|
+
});
|
|
59
|
+
const products = await getJson(`${apiBase}/mobile-app/config/getMobileProducts?${productsQuery}`, ProductsSchema);
|
|
60
|
+
const showPrice = settings.playerSettings?.productPriceFeedEnabled !== false;
|
|
61
|
+
return steps.map((step) => ({
|
|
62
|
+
id: step.videoId,
|
|
63
|
+
title: step.videoName,
|
|
64
|
+
videoUrl: step.videoUrl,
|
|
65
|
+
hlsUrl: settings.mediaAssetsById?.[step.videoId]?.sources?.hls,
|
|
66
|
+
posterUrl: step.posterUrl,
|
|
67
|
+
products: step.products.flatMap(({ id, variantIds }) => {
|
|
68
|
+
const product = id ? products[id] : undefined;
|
|
69
|
+
if (!product)
|
|
70
|
+
return [];
|
|
71
|
+
const variant = product.variants?.find((candidate) => candidate.id === variantIds?.[0]);
|
|
72
|
+
const shownPrice = showPrice ? (variant ?? lowestPriceVariant(product.variants ?? [])) : undefined;
|
|
73
|
+
return [
|
|
74
|
+
{
|
|
75
|
+
id: product.id,
|
|
76
|
+
variantId: variant?.id,
|
|
77
|
+
handle: product.handle,
|
|
78
|
+
title: product.title,
|
|
79
|
+
imageUrl: product.imageUrl ?? undefined,
|
|
80
|
+
price: shownPrice?.price ?? undefined,
|
|
81
|
+
compareAtPrice: shownPrice?.compareAtPrice ?? undefined,
|
|
82
|
+
currencySymbol: product.currencySymbol ?? undefined,
|
|
83
|
+
},
|
|
84
|
+
];
|
|
85
|
+
}),
|
|
86
|
+
}));
|
|
87
|
+
}
|
package/lib/bridge.d.ts
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
export declare const BridgeActionSchema: z.ZodDiscriminatedUnion<"name", [z.ZodObject<{
|
|
3
|
+
id: z.ZodOptional<z.ZodString>;
|
|
4
|
+
type: z.ZodLiteral<"action">;
|
|
5
|
+
} & {
|
|
6
|
+
name: z.ZodLiteral<"product/open">;
|
|
7
|
+
data: z.ZodObject<{
|
|
8
|
+
productId: z.ZodEffects<z.ZodUnion<[z.ZodString, z.ZodNumber]>, string, string | number>;
|
|
9
|
+
variantId: z.ZodOptional<z.ZodEffects<z.ZodUnion<[z.ZodString, z.ZodNumber]>, string, string | number>>;
|
|
10
|
+
}, "strip", z.ZodTypeAny, {
|
|
11
|
+
productId: string;
|
|
12
|
+
variantId?: string | undefined;
|
|
13
|
+
}, {
|
|
14
|
+
productId: string | number;
|
|
15
|
+
variantId?: string | number | undefined;
|
|
16
|
+
}>;
|
|
17
|
+
}, "strip", z.ZodTypeAny, {
|
|
18
|
+
id?: string | undefined;
|
|
19
|
+
type: "action";
|
|
20
|
+
name: "product/open";
|
|
21
|
+
data: {
|
|
22
|
+
productId: string;
|
|
23
|
+
variantId?: string | undefined;
|
|
24
|
+
};
|
|
25
|
+
}, {
|
|
26
|
+
id?: string | undefined;
|
|
27
|
+
type: "action";
|
|
28
|
+
name: "product/open";
|
|
29
|
+
data: {
|
|
30
|
+
productId: string | number;
|
|
31
|
+
variantId?: string | number | undefined;
|
|
32
|
+
};
|
|
33
|
+
}>, z.ZodObject<{
|
|
34
|
+
id: z.ZodOptional<z.ZodString>;
|
|
35
|
+
type: z.ZodLiteral<"action">;
|
|
36
|
+
} & {
|
|
37
|
+
name: z.ZodLiteral<"cart/add">;
|
|
38
|
+
data: z.ZodObject<{
|
|
39
|
+
lineItems: z.ZodArray<z.ZodObject<{
|
|
40
|
+
variantId: z.ZodEffects<z.ZodUnion<[z.ZodString, z.ZodNumber]>, string, string | number>;
|
|
41
|
+
quantity: z.ZodNumber;
|
|
42
|
+
}, "strip", z.ZodTypeAny, {
|
|
43
|
+
variantId: string;
|
|
44
|
+
quantity: number;
|
|
45
|
+
}, {
|
|
46
|
+
variantId: string | number;
|
|
47
|
+
quantity: number;
|
|
48
|
+
}>, "many">;
|
|
49
|
+
}, "strip", z.ZodTypeAny, {
|
|
50
|
+
lineItems: {
|
|
51
|
+
variantId: string;
|
|
52
|
+
quantity: number;
|
|
53
|
+
}[];
|
|
54
|
+
}, {
|
|
55
|
+
lineItems: {
|
|
56
|
+
variantId: string | number;
|
|
57
|
+
quantity: number;
|
|
58
|
+
}[];
|
|
59
|
+
}>;
|
|
60
|
+
}, "strip", z.ZodTypeAny, {
|
|
61
|
+
id?: string | undefined;
|
|
62
|
+
type: "action";
|
|
63
|
+
name: "cart/add";
|
|
64
|
+
data: {
|
|
65
|
+
lineItems: {
|
|
66
|
+
variantId: string;
|
|
67
|
+
quantity: number;
|
|
68
|
+
}[];
|
|
69
|
+
};
|
|
70
|
+
}, {
|
|
71
|
+
id?: string | undefined;
|
|
72
|
+
type: "action";
|
|
73
|
+
name: "cart/add";
|
|
74
|
+
data: {
|
|
75
|
+
lineItems: {
|
|
76
|
+
variantId: string | number;
|
|
77
|
+
quantity: number;
|
|
78
|
+
}[];
|
|
79
|
+
};
|
|
80
|
+
}>, z.ZodObject<{
|
|
81
|
+
id: z.ZodOptional<z.ZodString>;
|
|
82
|
+
type: z.ZodLiteral<"action">;
|
|
83
|
+
} & {
|
|
84
|
+
name: z.ZodLiteral<"cart/open">;
|
|
85
|
+
}, "strip", z.ZodTypeAny, {
|
|
86
|
+
id?: string | undefined;
|
|
87
|
+
type: "action";
|
|
88
|
+
name: "cart/open";
|
|
89
|
+
}, {
|
|
90
|
+
id?: string | undefined;
|
|
91
|
+
type: "action";
|
|
92
|
+
name: "cart/open";
|
|
93
|
+
}>, z.ZodObject<{
|
|
94
|
+
id: z.ZodOptional<z.ZodString>;
|
|
95
|
+
type: z.ZodLiteral<"action">;
|
|
96
|
+
} & {
|
|
97
|
+
name: z.ZodLiteral<"go/back">;
|
|
98
|
+
}, "strip", z.ZodTypeAny, {
|
|
99
|
+
id?: string | undefined;
|
|
100
|
+
type: "action";
|
|
101
|
+
name: "go/back";
|
|
102
|
+
}, {
|
|
103
|
+
id?: string | undefined;
|
|
104
|
+
type: "action";
|
|
105
|
+
name: "go/back";
|
|
106
|
+
}>]>;
|
|
107
|
+
export type BridgeAction = z.infer<typeof BridgeActionSchema>;
|
|
108
|
+
export type BridgeActionName = BridgeAction['name'];
|
|
109
|
+
export declare function parseBridgeAction(message: string): BridgeAction | null;
|
|
110
|
+
export declare function appSessionScript(customerAccessToken: string | null, storefrontAccessToken?: string): string;
|
|
111
|
+
export declare function respondScript(id: string, result: 'success' | 'error'): string;
|
package/lib/bridge.js
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
const SHOPIFY_GID = /^gid:\/\/shopify\/\w+\/(\d+)$/;
|
|
3
|
+
const ShopifyId = z.union([z.string(), z.number()]).transform((id) => `${id}`.replace(SHOPIFY_GID, '$1'));
|
|
4
|
+
const ActionBase = z.object({ id: z.string().optional(), type: z.literal('action') });
|
|
5
|
+
export const BridgeActionSchema = z.discriminatedUnion('name', [
|
|
6
|
+
ActionBase.extend({
|
|
7
|
+
name: z.literal('product/open'),
|
|
8
|
+
data: z.object({ productId: ShopifyId, variantId: ShopifyId.optional() }),
|
|
9
|
+
}),
|
|
10
|
+
ActionBase.extend({
|
|
11
|
+
name: z.literal('cart/add'),
|
|
12
|
+
data: z.object({ lineItems: z.array(z.object({ variantId: ShopifyId, quantity: z.number().int().positive() })) }),
|
|
13
|
+
}),
|
|
14
|
+
ActionBase.extend({ name: z.literal('cart/open') }),
|
|
15
|
+
ActionBase.extend({ name: z.literal('go/back') }),
|
|
16
|
+
]);
|
|
17
|
+
export function parseBridgeAction(message) {
|
|
18
|
+
try {
|
|
19
|
+
return BridgeActionSchema.safeParse(JSON.parse(message)).data ?? null;
|
|
20
|
+
}
|
|
21
|
+
catch {
|
|
22
|
+
return null;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
export function appSessionScript(customerAccessToken, storefrontAccessToken) {
|
|
26
|
+
const customerSession = { customerAccessToken: { access_token: customerAccessToken }, storefrontAccessToken };
|
|
27
|
+
const payload = {
|
|
28
|
+
messageHandlerName: 'ReactNativeWebView',
|
|
29
|
+
variables: { customer: customerAccessToken ? { customerSession } : null },
|
|
30
|
+
};
|
|
31
|
+
return `window.Tapcart && window.Tapcart.mobile.load(${JSON.stringify(payload)}); true;`;
|
|
32
|
+
}
|
|
33
|
+
export function respondScript(id, result) {
|
|
34
|
+
return `window.Tapcart && window.Tapcart.mobile.respond(${JSON.stringify(id)}, ${JSON.stringify(result)}); true;`;
|
|
35
|
+
}
|
package/lib/config.d.ts
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export type TolstoyEnvironment = 'production' | 'dev';
|
|
2
|
+
type EnvironmentHosts = {
|
|
3
|
+
apiBase: string;
|
|
4
|
+
tryOnPage: string;
|
|
5
|
+
eventsUrl: string;
|
|
6
|
+
};
|
|
7
|
+
export declare const ENVIRONMENTS: Record<TolstoyEnvironment, EnvironmentHosts>;
|
|
8
|
+
export declare function toQuery(params: Record<string, string | undefined>): string;
|
|
9
|
+
export {};
|
package/lib/config.js
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
export const ENVIRONMENTS = {
|
|
2
|
+
production: {
|
|
3
|
+
apiBase: 'https://cf-apilb.gotolstoy.com',
|
|
4
|
+
tryOnPage: 'https://play.gotolstoy.com/widget-v2/index.onyou-fullscreen.html',
|
|
5
|
+
eventsUrl: 'https://analytics-v2.gotolstoy.com/event',
|
|
6
|
+
},
|
|
7
|
+
dev: {
|
|
8
|
+
apiBase: 'https://dev-cf-apilb.gotolstoy.com',
|
|
9
|
+
tryOnPage: 'https://play-dev.gotolstoy.com/widget-v2/index.onyou-fullscreen.html',
|
|
10
|
+
eventsUrl: 'https://analytics-v2-dev.gotolstoy.com/event',
|
|
11
|
+
},
|
|
12
|
+
};
|
|
13
|
+
export function toQuery(params) {
|
|
14
|
+
return Object.entries(params)
|
|
15
|
+
.flatMap(([key, value]) => (value === undefined ? [] : [`${encodeURIComponent(key)}=${encodeURIComponent(value)}`]))
|
|
16
|
+
.join('&');
|
|
17
|
+
}
|
package/lib/index.d.ts
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
export { TolstoyProvider, useTolstoy } from './TolstoyProvider';
|
|
2
|
+
export type { TolstoyCartAttribute, TolstoyCartLine, TolstoyEvent, TolstoyProviderProps } from './TolstoyProvider';
|
|
3
|
+
export { TolstoyVideoCarousel, TolstoyProductVideos } from './TolstoyVideoCarousel';
|
|
4
|
+
export type { TolstoyVideoCarouselProps, TolstoyProductVideosProps } from './TolstoyVideoCarousel';
|
|
5
|
+
export { TolstoyFeed } from './TolstoyFeed';
|
|
6
|
+
export type { TolstoyFeedProps } from './TolstoyFeed';
|
|
7
|
+
export { TolstoyTryOn } from './TolstoyTryOn';
|
|
8
|
+
export type { TolstoyTryOnProps } from './TolstoyTryOn';
|
|
9
|
+
export { useTolstoyVideos } from './useTolstoyVideos';
|
|
10
|
+
export type { TolstoyVideosState } from './useTolstoyVideos';
|
|
11
|
+
export { getVideos } from './api';
|
|
12
|
+
export type { TolstoyProduct, TolstoyStore, TolstoyVideo } from './api';
|
|
13
|
+
export type { TolstoyEnvironment } from './config';
|
package/lib/index.js
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export { TolstoyProvider, useTolstoy } from './TolstoyProvider';
|
|
2
|
+
export { TolstoyVideoCarousel, TolstoyProductVideos } from './TolstoyVideoCarousel';
|
|
3
|
+
export { TolstoyFeed } from './TolstoyFeed';
|
|
4
|
+
export { TolstoyTryOn } from './TolstoyTryOn';
|
|
5
|
+
export { useTolstoyVideos } from './useTolstoyVideos';
|
|
6
|
+
export { getVideos } from './api';
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { TolstoyVideo } from './api';
|
|
2
|
+
export type TolstoyVideosState = {
|
|
3
|
+
status: 'loading';
|
|
4
|
+
} | {
|
|
5
|
+
status: 'ready';
|
|
6
|
+
videos: TolstoyVideo[];
|
|
7
|
+
} | {
|
|
8
|
+
status: 'error';
|
|
9
|
+
error: Error;
|
|
10
|
+
};
|
|
11
|
+
export declare function useTolstoyVideos(publishId: string, productId?: string): TolstoyVideosState;
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { useEffect, useState } from 'react';
|
|
2
|
+
import { getVideos } from './api';
|
|
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
|
+
}
|
|
23
|
+
export function useTolstoyVideos(publishId, productId) {
|
|
24
|
+
const { appKey, appUrl, environment } = useTolstoy();
|
|
25
|
+
const key = JSON.stringify([environment, appKey, appUrl, publishId, productId]);
|
|
26
|
+
const [state, setState] = useState(() => cachedState(key));
|
|
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;
|
|
32
|
+
let current = true;
|
|
33
|
+
loadVideos(key, { appKey, appUrl, environment }, publishId, productId).then((videos) => current && setState({ status: 'ready', videos }), (error) => current && setState({ status: 'error', error }));
|
|
34
|
+
return () => {
|
|
35
|
+
current = false;
|
|
36
|
+
};
|
|
37
|
+
}, [key, appKey, appUrl, environment, publishId, productId]);
|
|
38
|
+
return state;
|
|
39
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,60 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tolstoy-ai/react-native-sdk",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "Tolstoy shoppable videos and virtual try-on for bare React Native apps",
|
|
5
|
+
"repository": {
|
|
6
|
+
"type": "git",
|
|
7
|
+
"url": "git+https://github.com/GoTolstoy/tolstoy-backend-cdk.git",
|
|
8
|
+
"directory": "packages/front/packages/react-native-sdk"
|
|
9
|
+
},
|
|
10
|
+
"type": "module",
|
|
11
|
+
"main": "lib/index.js",
|
|
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
|
+
},
|
|
24
|
+
"files": [
|
|
25
|
+
"lib"
|
|
26
|
+
],
|
|
27
|
+
"publishConfig": {
|
|
28
|
+
"access": "public"
|
|
29
|
+
},
|
|
30
|
+
"scripts": {
|
|
31
|
+
"build": "rm -rf lib && tsc -p tsconfig.build.json",
|
|
32
|
+
"lint": "biome check --max-diagnostics=none .",
|
|
33
|
+
"typecheck:fast": "tsc --noEmit -p tsconfig.json"
|
|
34
|
+
},
|
|
35
|
+
"dependencies": {
|
|
36
|
+
"zod": "^3.25.67"
|
|
37
|
+
},
|
|
38
|
+
"peerDependencies": {
|
|
39
|
+
"react": ">=19.1.0",
|
|
40
|
+
"react-native": ">=0.81.0",
|
|
41
|
+
"react-native-video": ">=6.16.1",
|
|
42
|
+
"react-native-webview": ">=13.16.0"
|
|
43
|
+
},
|
|
44
|
+
"peerDependenciesMeta": {
|
|
45
|
+
"react-native-video": {
|
|
46
|
+
"optional": true
|
|
47
|
+
},
|
|
48
|
+
"react-native-webview": {
|
|
49
|
+
"optional": true
|
|
50
|
+
}
|
|
51
|
+
},
|
|
52
|
+
"devDependencies": {
|
|
53
|
+
"@types/react": "catalog:",
|
|
54
|
+
"react": "19.1.4",
|
|
55
|
+
"react-native": "0.81.6",
|
|
56
|
+
"react-native-video": "6.16.1",
|
|
57
|
+
"react-native-webview": "13.16.1",
|
|
58
|
+
"typescript": "catalog:"
|
|
59
|
+
}
|
|
60
|
+
}
|