@tolstoy-ai/react-native-sdk 0.3.0 → 0.4.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 +118 -6
- package/lib/TolstoyFeed.js +4 -0
- package/lib/TolstoyVideoCarousel.js +1 -1
- package/lib/analytics.d.ts +5 -3
- package/lib/analytics.js +4 -4
- package/lib/api.d.ts +10 -0
- package/lib/api.js +5 -0
- package/lib/bridge.d.ts +1 -0
- package/lib/bridge.js +4 -0
- package/lib/config.d.ts +5 -0
- package/lib/config.js +10 -0
- package/lib/index.d.ts +5 -4
- package/lib/index.js +3 -2
- package/lib/{TolstoyTryOn.js → tryOn/TolstoyTryOn.js} +5 -5
- package/lib/tryOn/methods/shopperSignIn.d.ts +12 -0
- package/lib/tryOn/methods/shopperSignIn.js +29 -0
- package/lib/tryOn/methods/tryOnJob.d.ts +17 -0
- package/lib/tryOn/methods/tryOnJob.js +56 -0
- package/lib/tryOn/methods/tryOnPhotos.d.ts +19 -0
- package/lib/tryOn/methods/tryOnPhotos.js +112 -0
- package/lib/tryOn/methods/tryOnProduct.d.ts +169 -0
- package/lib/tryOn/methods/tryOnProduct.js +49 -0
- package/lib/tryOn/methods/tryOnSession.d.ts +14 -0
- package/lib/tryOn/methods/tryOnSession.js +26 -0
- package/lib/tryOn/screen/Header.d.ts +9 -0
- package/lib/tryOn/screen/Header.js +22 -0
- package/lib/tryOn/screen/Icon.d.ts +6 -0
- package/lib/tryOn/screen/Icon.js +6 -0
- package/lib/tryOn/screen/PhotoStep.d.ts +12 -0
- package/lib/tryOn/screen/PhotoStep.js +70 -0
- package/lib/tryOn/screen/PillButton.d.ts +10 -0
- package/lib/tryOn/screen/PillButton.js +31 -0
- package/lib/tryOn/screen/ProgressStep.d.ts +16 -0
- package/lib/tryOn/screen/ProgressStep.js +82 -0
- package/lib/tryOn/screen/ResultStep.d.ts +12 -0
- package/lib/tryOn/screen/ResultStep.js +114 -0
- package/lib/tryOn/screen/TolstoyMark.d.ts +4 -0
- package/lib/tryOn/screen/TolstoyMark.js +18 -0
- package/lib/tryOn/screen/TolstoyTryOnScreen.d.ts +6 -0
- package/lib/tryOn/screen/TolstoyTryOnScreen.js +39 -0
- package/lib/tryOn/screen/TopImage.d.ts +8 -0
- package/lib/tryOn/screen/TopImage.js +22 -0
- package/lib/tryOn/screen/icons.d.ts +24 -0
- package/lib/tryOn/screen/icons.js +10 -0
- package/lib/tryOn/screen/pickPhoto.d.ts +9 -0
- package/lib/tryOn/screen/pickPhoto.js +21 -0
- package/lib/tryOn/screen/useEstimatedProgress.d.ts +2 -0
- package/lib/tryOn/screen/useEstimatedProgress.js +22 -0
- package/lib/tryOn/useTolstoyTryOn.d.ts +44 -0
- package/lib/tryOn/useTolstoyTryOn.js +194 -0
- package/package.json +10 -1
- /package/lib/{TolstoyTryOn.d.ts → tryOn/TolstoyTryOn.d.ts} +0 -0
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { TolstoySizeChoice } from '../methods/tryOnProduct';
|
|
2
|
+
type ResultStepProps = {
|
|
3
|
+
imageUrl: string;
|
|
4
|
+
productTitle: string | null;
|
|
5
|
+
productImageUrl: string | null;
|
|
6
|
+
sizes: TolstoySizeChoice[];
|
|
7
|
+
addToCart: (variantId: string) => Promise<void>;
|
|
8
|
+
onChangePhoto: () => void;
|
|
9
|
+
onClose: () => void;
|
|
10
|
+
};
|
|
11
|
+
export declare function ResultStep({ imageUrl, productTitle, productImageUrl, sizes, addToCart, onChangePhoto, onClose, }: ResultStepProps): import("react/jsx-runtime").JSX.Element;
|
|
12
|
+
export {};
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
2
|
+
import { useState } from 'react';
|
|
3
|
+
import { Pressable, StyleSheet, Text, View } from 'react-native';
|
|
4
|
+
import { Header } from './Header';
|
|
5
|
+
import { Icon } from './Icon';
|
|
6
|
+
import { PillButton } from './PillButton';
|
|
7
|
+
import { TopImage } from './TopImage';
|
|
8
|
+
export function ResultStep({ imageUrl, productTitle, productImageUrl, sizes, addToCart, onChangePhoto, onClose, }) {
|
|
9
|
+
const [loaded, setLoaded] = useState(false);
|
|
10
|
+
const [sheetOpen, setSheetOpen] = useState(false);
|
|
11
|
+
const [cart, setCart] = useState({ name: 'idle' });
|
|
12
|
+
const anyAvailable = sizes.some((size) => size.available);
|
|
13
|
+
// One variant has no size to choose, so it adds at once; otherwise the shopper chooses a size first.
|
|
14
|
+
const needsSize = sizes.length > 1;
|
|
15
|
+
const add = async (size) => {
|
|
16
|
+
setSheetOpen(false);
|
|
17
|
+
setCart({ name: 'adding' });
|
|
18
|
+
try {
|
|
19
|
+
await addToCart(size.variantId);
|
|
20
|
+
setCart({ name: 'added', label: size.label });
|
|
21
|
+
}
|
|
22
|
+
catch (error) {
|
|
23
|
+
console.error('Tolstoy try-on add to cart failed', error);
|
|
24
|
+
setCart({ name: 'error', message: 'Could not add to cart. Please try again.' });
|
|
25
|
+
}
|
|
26
|
+
};
|
|
27
|
+
const cartLabel = cart.name === 'adding'
|
|
28
|
+
? 'Adding…'
|
|
29
|
+
: cart.name === 'added'
|
|
30
|
+
? `Added${needsSize ? ` · ${cart.label}` : ''}`
|
|
31
|
+
: !anyAvailable && sizes.length > 0
|
|
32
|
+
? 'Sold out'
|
|
33
|
+
: needsSize
|
|
34
|
+
? 'Choose Size'
|
|
35
|
+
: 'Add to Cart';
|
|
36
|
+
return (_jsxs(View, { style: styles.screen, children: [_jsx(Header, { title: "See it on you", onBack: onChangePhoto, onClose: onClose }), _jsxs(View, { style: styles.body, children: [_jsxs(View, { style: styles.content, children: [_jsxs(View, { style: styles.imageCard, children: [loaded ? null : _jsx(View, { style: styles.placeholder }), _jsx(TopImage, { uri: imageUrl, onLoad: () => setLoaded(true), accessibilityLabel: productTitle ? `You wearing ${productTitle}` : 'Your try-on' }), _jsxs(View, { style: styles.caption, children: [productImageUrl ? (_jsx(View, { style: styles.thumb, children: _jsx(TopImage, { uri: productImageUrl }) })) : null, _jsx(Text, { style: styles.captionTitle, numberOfLines: 1, children: productTitle }), _jsx(Text, { style: styles.badge, children: "AI GENERATED" })] })] }), _jsxs(View, { style: styles.actions, children: [_jsx(PillButton, { kind: "primary", icon: "bag", label: cartLabel, disabled: !anyAvailable || cart.name === 'adding', onPress: () => {
|
|
37
|
+
const [onlySize] = sizes;
|
|
38
|
+
if (needsSize)
|
|
39
|
+
setSheetOpen(true);
|
|
40
|
+
else if (onlySize)
|
|
41
|
+
void add(onlySize);
|
|
42
|
+
} }), _jsx(PillButton, { kind: "secondary", icon: "swap", label: "Change photo", onPress: onChangePhoto })] }), cart.name === 'error' ? _jsx(Text, { style: styles.cartError, children: cart.message }) : null, _jsx(Text, { style: styles.disclaimer, children: "AI can make mistakes." })] }), sheetOpen ? (_jsx(Pressable, { style: styles.backdrop, onPress: () => setSheetOpen(false), accessibilityLabel: "Close sizes", children: _jsxs(Pressable, { style: styles.sheet, accessibilityViewIsModal: true, onPress: () => undefined, children: [_jsxs(View, { style: styles.sheetHeader, children: [_jsx(Text, { style: styles.sheetTitle, children: "Choose your size" }), _jsx(Pressable, { accessibilityRole: "button", accessibilityLabel: "Close sizes", onPress: () => setSheetOpen(false), style: styles.sheetClose, children: _jsx(Icon, { name: "close", color: "#141414" }) })] }), _jsx(View, { style: styles.sizes, children: sizes.map((size) => (_jsx(Pressable, { accessibilityRole: "button", accessibilityState: { disabled: !size.available }, disabled: !size.available, onPress: () => void add(size), style: ({ pressed }) => [
|
|
43
|
+
styles.size,
|
|
44
|
+
pressed ? styles.sizePressed : null,
|
|
45
|
+
size.available ? null : styles.sizeUnavailable,
|
|
46
|
+
], children: _jsx(Text, { numberOfLines: 1, style: [styles.sizeText, size.available ? null : styles.sizeTextUnavailable], children: size.label }) }, size.variantId))) })] }) })) : null] })] }));
|
|
47
|
+
}
|
|
48
|
+
const styles = StyleSheet.create({
|
|
49
|
+
screen: { flex: 1 },
|
|
50
|
+
body: { flex: 1 },
|
|
51
|
+
content: { flex: 1, paddingHorizontal: 20, paddingTop: 16, paddingBottom: 20 },
|
|
52
|
+
imageCard: { flex: 1, borderRadius: 24, overflow: 'hidden', backgroundColor: '#f3f4f6' },
|
|
53
|
+
placeholder: { ...StyleSheet.absoluteFillObject, backgroundColor: '#e5e7eb' },
|
|
54
|
+
caption: {
|
|
55
|
+
position: 'absolute',
|
|
56
|
+
left: 0,
|
|
57
|
+
right: 0,
|
|
58
|
+
bottom: 0,
|
|
59
|
+
flexDirection: 'row',
|
|
60
|
+
alignItems: 'center',
|
|
61
|
+
gap: 12,
|
|
62
|
+
paddingHorizontal: 16,
|
|
63
|
+
paddingBottom: 16,
|
|
64
|
+
paddingTop: 56,
|
|
65
|
+
experimental_backgroundImage: 'linear-gradient(to top, rgba(0,0,0,0.7), rgba(0,0,0,0))',
|
|
66
|
+
},
|
|
67
|
+
thumb: { width: 48, height: 48, borderRadius: 8, overflow: 'hidden', backgroundColor: '#fff' },
|
|
68
|
+
captionTitle: { flex: 1, fontSize: 15, fontWeight: '600', color: '#fff' },
|
|
69
|
+
badge: {
|
|
70
|
+
overflow: 'hidden',
|
|
71
|
+
borderRadius: 999,
|
|
72
|
+
paddingHorizontal: 8,
|
|
73
|
+
paddingVertical: 2,
|
|
74
|
+
backgroundColor: 'rgba(0,0,0,0.5)',
|
|
75
|
+
fontSize: 10,
|
|
76
|
+
fontWeight: '600',
|
|
77
|
+
letterSpacing: 1,
|
|
78
|
+
color: 'rgba(255,255,255,0.8)',
|
|
79
|
+
},
|
|
80
|
+
actions: { marginTop: 16, gap: 12 },
|
|
81
|
+
cartError: { marginTop: 8, fontSize: 13, color: '#dc2626', textAlign: 'center' },
|
|
82
|
+
disclaimer: { marginTop: 12, fontSize: 12, color: '#9ca3af', textAlign: 'center' },
|
|
83
|
+
backdrop: {
|
|
84
|
+
...StyleSheet.absoluteFillObject,
|
|
85
|
+
justifyContent: 'flex-end',
|
|
86
|
+
backgroundColor: 'rgba(0,0,0,0.4)',
|
|
87
|
+
},
|
|
88
|
+
sheet: {
|
|
89
|
+
borderTopLeftRadius: 24,
|
|
90
|
+
borderTopRightRadius: 24,
|
|
91
|
+
backgroundColor: '#fff',
|
|
92
|
+
paddingHorizontal: 20,
|
|
93
|
+
paddingTop: 16,
|
|
94
|
+
paddingBottom: 24,
|
|
95
|
+
},
|
|
96
|
+
sheetHeader: { flexDirection: 'row', alignItems: 'center', marginBottom: 16 },
|
|
97
|
+
sheetTitle: { flex: 1, fontSize: 16, fontWeight: '600', color: '#141414' },
|
|
98
|
+
sheetClose: { width: 36, height: 36, borderRadius: 18, alignItems: 'center', justifyContent: 'center' },
|
|
99
|
+
sizes: { flexDirection: 'row', flexWrap: 'wrap', gap: 8 },
|
|
100
|
+
size: {
|
|
101
|
+
width: '23%',
|
|
102
|
+
height: 48,
|
|
103
|
+
alignItems: 'center',
|
|
104
|
+
justifyContent: 'center',
|
|
105
|
+
borderRadius: 12,
|
|
106
|
+
borderWidth: 1,
|
|
107
|
+
borderColor: '#d1d5db',
|
|
108
|
+
paddingHorizontal: 4,
|
|
109
|
+
},
|
|
110
|
+
sizePressed: { borderColor: '#000', backgroundColor: '#f3f4f6' },
|
|
111
|
+
sizeUnavailable: { backgroundColor: '#f9fafb' },
|
|
112
|
+
sizeText: { fontSize: 15, fontWeight: '600', color: '#000' },
|
|
113
|
+
sizeTextUnavailable: { color: '#d1d5db', textDecorationLine: 'line-through' },
|
|
114
|
+
});
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { jsx as _jsx } from "react/jsx-runtime";
|
|
2
|
+
import { Image, Linking, Pressable, StyleSheet } from 'react-native';
|
|
3
|
+
import { toQuery } from '../../config';
|
|
4
|
+
import { ICONS } from './icons';
|
|
5
|
+
/** The Tolstoy mark at the bottom of the shopper chat's sheets. */
|
|
6
|
+
export function TolstoyMark({ appKey }) {
|
|
7
|
+
const url = `https://www.gotolstoy.com/?${toQuery({
|
|
8
|
+
utm_source: 'watermark',
|
|
9
|
+
utm_medium: 'tolstoy-ai-shopper',
|
|
10
|
+
utm_campaign: 'logo',
|
|
11
|
+
utm_term: appKey,
|
|
12
|
+
})}`;
|
|
13
|
+
return (_jsx(Pressable, { accessibilityRole: "link", accessibilityLabel: "Go to Tolstoy website", onPress: () => Linking.openURL(url).catch((error) => console.warn('Tolstoy link did not open', error)), style: styles.mark, children: _jsx(Image, { source: ICONS.tolstoy, style: styles.logo }) }));
|
|
14
|
+
}
|
|
15
|
+
const styles = StyleSheet.create({
|
|
16
|
+
mark: { alignSelf: 'center', minWidth: 32, minHeight: 32, alignItems: 'center', justifyContent: 'center', marginBottom: 4 },
|
|
17
|
+
logo: { width: 20, height: 14, tintColor: '#141414' },
|
|
18
|
+
});
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { UseTolstoyTryOnOptions } from '../useTolstoyTryOn';
|
|
2
|
+
export type TolstoyTryOnScreenProps = UseTolstoyTryOnOptions & {
|
|
3
|
+
onClose: () => void;
|
|
4
|
+
};
|
|
5
|
+
/** The native try-on screen: pick a photo, see it on you, add to cart. Its look is fixed. */
|
|
6
|
+
export declare function TolstoyTryOnScreen({ productId, variantId, onClose }: TolstoyTryOnScreenProps): import("react/jsx-runtime").JSX.Element;
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
2
|
+
import { useState } from 'react';
|
|
3
|
+
import { StyleSheet, View } from 'react-native';
|
|
4
|
+
import { useTolstoy } from '../../TolstoyProvider';
|
|
5
|
+
import { PhotoStep } from './PhotoStep';
|
|
6
|
+
import { pickPhoto } from './pickPhoto';
|
|
7
|
+
import { ProgressStep } from './ProgressStep';
|
|
8
|
+
import { ResultStep } from './ResultStep';
|
|
9
|
+
import { TolstoyMark } from './TolstoyMark';
|
|
10
|
+
import { useTolstoyTryOn } from '../useTolstoyTryOn';
|
|
11
|
+
/** The native try-on screen: pick a photo, see it on you, add to cart. Its look is fixed. */
|
|
12
|
+
export function TolstoyTryOnScreen({ productId, variantId, onClose }) {
|
|
13
|
+
const { appKey } = useTolstoy();
|
|
14
|
+
const tryOn = useTolstoyTryOn({ productId, variantId });
|
|
15
|
+
const { step } = tryOn;
|
|
16
|
+
const [pickerError, setPickerError] = useState(null);
|
|
17
|
+
const productImageUrl = tryOn.triedVariant?.imageUrl ?? tryOn.product?.imageUrl ?? null;
|
|
18
|
+
const pick = async (source) => {
|
|
19
|
+
setPickerError(null);
|
|
20
|
+
const picked = await pickPhoto(source);
|
|
21
|
+
if (!picked)
|
|
22
|
+
return;
|
|
23
|
+
if ('error' in picked)
|
|
24
|
+
setPickerError(picked.error);
|
|
25
|
+
else
|
|
26
|
+
tryOn.tryOnFile(picked.file);
|
|
27
|
+
};
|
|
28
|
+
const close = () => {
|
|
29
|
+
tryOn.backToPhotos();
|
|
30
|
+
onClose();
|
|
31
|
+
};
|
|
32
|
+
return (_jsxs(View, { style: styles.screen, children: [step.name === 'photo' ? (_jsx(PhotoStep, { productImageUrl: productImageUrl, photos: tryOn.photos, error: pickerError ?? step.error, onPick: (source) => void pick(source), onSavedPhoto: (photo) => {
|
|
33
|
+
setPickerError(null);
|
|
34
|
+
tryOn.tryOnPhoto(photo);
|
|
35
|
+
}, onClose: close })) : step.name === 'result' ? (_jsx(ResultStep, { imageUrl: step.imageUrl, productTitle: tryOn.product?.title ?? null, productImageUrl: productImageUrl, sizes: tryOn.sizes, addToCart: tryOn.addToCart, onChangePhoto: tryOn.backToPhotos, onClose: close })) : step.name === 'failed' ? (_jsx(ProgressStep, { phase: "failed", productImageUrl: productImageUrl, photoUri: step.photoUri, error: step.error, onRetry: tryOn.retry, onChangePhoto: tryOn.backToPhotos, onClose: close })) : (_jsx(ProgressStep, { phase: step.name, uploadPercent: step.name === 'uploading' ? step.percent : 100, productImageUrl: productImageUrl, photoUri: step.photoUri, onClose: close })), _jsx(TolstoyMark, { appKey: appKey })] }));
|
|
36
|
+
}
|
|
37
|
+
const styles = StyleSheet.create({
|
|
38
|
+
screen: { flex: 1, backgroundColor: '#fff' },
|
|
39
|
+
});
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
type TopImageProps = {
|
|
2
|
+
uri: string;
|
|
3
|
+
accessibilityLabel?: string;
|
|
4
|
+
onLoad?: () => void;
|
|
5
|
+
};
|
|
6
|
+
/** Fills its box like resizeMode cover but keeps the image's top, as CSS object-top does, so a person keeps their head. */
|
|
7
|
+
export declare function TopImage({ uri, accessibilityLabel, onLoad }: TopImageProps): import("react/jsx-runtime").JSX.Element;
|
|
8
|
+
export {};
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { jsx as _jsx } from "react/jsx-runtime";
|
|
2
|
+
import { useState } from 'react';
|
|
3
|
+
import { Image, StyleSheet, View } from 'react-native';
|
|
4
|
+
/** Fills its box like resizeMode cover but keeps the image's top, as CSS object-top does, so a person keeps their head. */
|
|
5
|
+
export function TopImage({ uri, accessibilityLabel, onLoad }) {
|
|
6
|
+
const [box, setBox] = useState(null);
|
|
7
|
+
const [image, setImage] = useState(null);
|
|
8
|
+
return (_jsx(View, { style: styles.box, onLayout: ({ nativeEvent: { layout } }) => setBox(layout), children: _jsx(Image, { source: { uri }, accessibilityLabel: accessibilityLabel, onLoad: ({ nativeEvent: { source } }) => {
|
|
9
|
+
setImage(source);
|
|
10
|
+
onLoad?.();
|
|
11
|
+
}, style: box && image ? coverFromTop(box, image) : styles.loading }) }));
|
|
12
|
+
}
|
|
13
|
+
function coverFromTop(box, image) {
|
|
14
|
+
const scale = Math.max(box.width / image.width, box.height / image.height);
|
|
15
|
+
const width = image.width * scale;
|
|
16
|
+
return { position: 'absolute', top: 0, left: (box.width - width) / 2, width, height: image.height * scale };
|
|
17
|
+
}
|
|
18
|
+
const styles = StyleSheet.create({
|
|
19
|
+
box: { width: '100%', height: '100%', overflow: 'hidden' },
|
|
20
|
+
// An image laid out at zero size never loads.
|
|
21
|
+
loading: { width: '100%', height: '100%', opacity: 0 },
|
|
22
|
+
});
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
export declare const ICONS: {
|
|
2
|
+
close: {
|
|
3
|
+
uri: string;
|
|
4
|
+
};
|
|
5
|
+
back: {
|
|
6
|
+
uri: string;
|
|
7
|
+
};
|
|
8
|
+
plus: {
|
|
9
|
+
uri: string;
|
|
10
|
+
};
|
|
11
|
+
camera: {
|
|
12
|
+
uri: string;
|
|
13
|
+
};
|
|
14
|
+
swap: {
|
|
15
|
+
uri: string;
|
|
16
|
+
};
|
|
17
|
+
bag: {
|
|
18
|
+
uri: string;
|
|
19
|
+
};
|
|
20
|
+
tolstoy: {
|
|
21
|
+
uri: string;
|
|
22
|
+
};
|
|
23
|
+
};
|
|
24
|
+
export type IconName = keyof typeof ICONS;
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
// The try-on widget's icons (24 px line icons and the Tolstoy mark) as PNGs, so the screen needs no SVG package.
|
|
2
|
+
export const ICONS = {
|
|
3
|
+
close: { uri: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEgAAABICAQAAAD/5HvMAAABAUlEQVRo3u2YSxKDIBBEO1loTi93ycLKpfQEqcJNyopGDTB8etHPtT2vAAUGEEIIIYSgosOAGTMGdBQ5cPCfZ0SfnNJjXHOcTWhag9KVvnU8pnxCaUpbHbOQ24TFK+11zFP2GxijZHv7hA7PXegLj8JvFgkuppMWXlQnvkBxnbgiVXTCC1XTCStWVed/weo610Wb6JwXbqYDHG8JBTYJ2yg1G50QpQY6V0qNdICjtWReO3eTkMf7IPHWanzIpoxsUZN99mQ/RrKtg2xzJTt+kB3QyI6wZId8smsQ2UWR7CpN1myga8c4Y2D2hhVdS4+u6emyzH7GtjBd41wIIYQQIjML11RspVW2CdMAAAAASUVORK5CYII=' },
|
|
4
|
+
back: { uri: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEgAAABICAQAAAD/5HvMAAAAmUlEQVRo3u3YQQ6CQBAF0YqLwcuLd2FBvBRcARe4YTS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ZpiEI3MpiLSsU1TIVqM+1yGLrGoZWKa5mO0Wo0LUFokUsrExcxZqDVpNnvRfPo9YQk4h4jrUaT9E6zU76IufiAsVaj6XCilcz6AkOc4SBlBuKXIvEcpQvow4jgIE2siNDWiLQazY0supn5mOhX6kPFnWLxCHkZ9LFRvDUb99QnsVizDaCYlGG8PUBdbqHVNCvgEIsMZ28j13zXdhrPfWdVKeCwAGiiznNlnZW4TFHILgGQRwcrXVdWW4nLFdUhUyasSjntGhdaiROKajF0lqWO0ayVGMV2MbPGtaaTtuIKC2rf/xCvtaB2o3L9IStvCn5b/QFszd0iP+D1Et8+KpZYPXFlrjfHCwt+XAkXU7aKHf0eC/69soAAihz9Ln6K+QFb8XJHf9q9pzCq54ofVuLvrtF1xkT0DG8UX6zE457HaBTR/aSU8FmzNeoZP6FNQD8AuGSxCv+wynczRZchPU0CoNZC/CrwcyhukTagb2fi+UZHD3e7Gvol1sXuwByb2zahdp6qiN8vwTkGIug7C9HK2M2tu/UaTJ8S9nKSzz426d6xdAu0aWqMZ6//hHHUHdjAhLG4XbBsvOL7/sgxQ+1w5GEmWvyM/KDQFQNtki0CrVv8Nnw/2hKjHRdqneJ+CqKCJ5gM1b52vPxl4jQ3XfvSwCqhO2BxfeM8i8XajPgDe0zjFVygjxGmmOAd96iPf96Q6uR42LnsL3KmXLR59DIHAAAAAElFTkSuQmCC' },
|
|
10
|
+
};
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { TolstoyPhotoFile } from '../methods/tryOnPhotos';
|
|
2
|
+
export type PhotoSource = 'library' | 'camera';
|
|
3
|
+
export type PickedPhoto = {
|
|
4
|
+
file: TolstoyPhotoFile;
|
|
5
|
+
} | {
|
|
6
|
+
error: string;
|
|
7
|
+
} | null;
|
|
8
|
+
/** Null when the shopper cancels. */
|
|
9
|
+
export declare function pickPhoto(source: PhotoSource): Promise<PickedPhoto>;
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { launchCamera, launchImageLibrary } from 'react-native-image-picker';
|
|
2
|
+
const PICKER_ERRORS = {
|
|
3
|
+
camera_unavailable: 'The camera is not available on this device.',
|
|
4
|
+
permission: 'Allow access in Settings to choose or take a photo.',
|
|
5
|
+
};
|
|
6
|
+
/** Null when the shopper cancels. */
|
|
7
|
+
export async function pickPhoto(source) {
|
|
8
|
+
const response = source === 'library'
|
|
9
|
+
? await launchImageLibrary({ mediaType: 'photo', selectionLimit: 1 })
|
|
10
|
+
: await launchCamera({ mediaType: 'photo', cameraType: 'back' });
|
|
11
|
+
if (response.didCancel)
|
|
12
|
+
return null;
|
|
13
|
+
const asset = response.assets?.[0];
|
|
14
|
+
if (response.errorCode || !asset?.uri) {
|
|
15
|
+
const known = PICKER_ERRORS[response.errorCode ?? ''];
|
|
16
|
+
if (!known)
|
|
17
|
+
console.warn('Tolstoy photo picker failed', response.errorCode, response.errorMessage);
|
|
18
|
+
return { error: known ?? 'The photo could not be opened. Please try another one.' };
|
|
19
|
+
}
|
|
20
|
+
return { file: { uri: asset.uri, type: asset.type, fileName: asset.fileName } };
|
|
21
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { useEffect, useState } from 'react';
|
|
2
|
+
// The server sends no progress, so the bar is an estimate, as in the try-on widget: the real upload percent fills
|
|
3
|
+
// the first part, then a curve driven by elapsed time approaches 99% and reaches about 90% at a typical 30 s render.
|
|
4
|
+
const UPLOAD_CEILING = 15;
|
|
5
|
+
const GENERATE_ASYMPTOTE = 99;
|
|
6
|
+
const EXPECTED_GENERATE_MS = 30000;
|
|
7
|
+
const GAP = GENERATE_ASYMPTOTE - UPLOAD_CEILING;
|
|
8
|
+
const TAU_MS = -EXPECTED_GENERATE_MS / Math.log((GENERATE_ASYMPTOTE - 90) / GAP);
|
|
9
|
+
const TICK_MS = 120;
|
|
10
|
+
export function useEstimatedProgress(phase, uploadPercent) {
|
|
11
|
+
const [generatedPercent, setGeneratedPercent] = useState(UPLOAD_CEILING);
|
|
12
|
+
useEffect(() => {
|
|
13
|
+
if (phase !== 'generating')
|
|
14
|
+
return;
|
|
15
|
+
const startedAt = Date.now();
|
|
16
|
+
setGeneratedPercent(UPLOAD_CEILING);
|
|
17
|
+
const tick = setInterval(() => setGeneratedPercent(GENERATE_ASYMPTOTE - GAP * Math.exp(-(Date.now() - startedAt) / TAU_MS)), TICK_MS);
|
|
18
|
+
return () => clearInterval(tick);
|
|
19
|
+
}, [phase]);
|
|
20
|
+
const percent = phase === 'generating' ? generatedPercent : (Math.min(Math.max(uploadPercent, 0), 100) / 100) * UPLOAD_CEILING;
|
|
21
|
+
return Math.round(percent);
|
|
22
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import type { TolstoyPhotoFile, TolstoyTryOnPhoto } from './methods/tryOnPhotos';
|
|
2
|
+
import type { TolstoySizeChoice, TolstoyTryOnProduct, TolstoyTryOnVariant } from './methods/tryOnProduct';
|
|
3
|
+
export type UseTolstoyTryOnOptions = {
|
|
4
|
+
productId: string;
|
|
5
|
+
/** The variant the shopper chose in the app. Its colour is tried on. Without it, the main image's colour is. */
|
|
6
|
+
variantId?: string;
|
|
7
|
+
};
|
|
8
|
+
export type TolstoyTryOnStep = {
|
|
9
|
+
name: 'photo';
|
|
10
|
+
error: string | null;
|
|
11
|
+
} | {
|
|
12
|
+
name: 'uploading';
|
|
13
|
+
photoUri: string;
|
|
14
|
+
percent: number;
|
|
15
|
+
} | {
|
|
16
|
+
name: 'generating';
|
|
17
|
+
photoUri: string;
|
|
18
|
+
} | {
|
|
19
|
+
name: 'failed';
|
|
20
|
+
photoUri: string;
|
|
21
|
+
error: string;
|
|
22
|
+
} | {
|
|
23
|
+
name: 'result';
|
|
24
|
+
imageUrl: string;
|
|
25
|
+
};
|
|
26
|
+
export type TolstoyTryOnState = {
|
|
27
|
+
/** Null until the product loads, and when the store's catalog has no such product. */
|
|
28
|
+
product: TolstoyTryOnProduct | null;
|
|
29
|
+
triedVariant: TolstoyTryOnVariant | null;
|
|
30
|
+
/** The sizes of the tried colour. */
|
|
31
|
+
sizes: TolstoySizeChoice[];
|
|
32
|
+
/** The shopper's saved photos, newest first. Null while they load. */
|
|
33
|
+
photos: TolstoyTryOnPhoto[] | null;
|
|
34
|
+
step: TolstoyTryOnStep;
|
|
35
|
+
tryOnPhoto: (photo: TolstoyTryOnPhoto) => void;
|
|
36
|
+
tryOnFile: (file: TolstoyPhotoFile) => void;
|
|
37
|
+
/** Runs the failed try-on again with the same photo. */
|
|
38
|
+
retry: () => void;
|
|
39
|
+
backToPhotos: () => void;
|
|
40
|
+
deletePhoto: (photo: TolstoyTryOnPhoto) => Promise<void>;
|
|
41
|
+
/** Adds one of the variant through the provider's `onAddToCart`. Rejects when the add fails. */
|
|
42
|
+
addToCart: (variantId: string) => Promise<void>;
|
|
43
|
+
};
|
|
44
|
+
export declare function useTolstoyTryOn({ productId, variantId }: UseTolstoyTryOnOptions): TolstoyTryOnState;
|
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
|
2
|
+
import { sendTolstoyEvent } from '../analytics';
|
|
3
|
+
import { signInShopper } from './methods/shopperSignIn';
|
|
4
|
+
import { useTolstoy } from '../TolstoyProvider';
|
|
5
|
+
import { runTryOn } from './methods/tryOnJob';
|
|
6
|
+
import { deleteTryOnPhoto, getTryOnPhotos, uploadTryOnPhoto } from './methods/tryOnPhotos';
|
|
7
|
+
import { getSizeChoices, getTryOnProduct, getTryOnVariant } from './methods/tryOnProduct';
|
|
8
|
+
import { TolstoyTryOnError } from './methods/tryOnSession';
|
|
9
|
+
const GENERIC_ERROR = 'Something went wrong. Please try again.';
|
|
10
|
+
// In memory for the app session: a try-on opened again does not exchange the same customer token again.
|
|
11
|
+
const shopperTokens = new Map();
|
|
12
|
+
function readCustomerToken(getAppSession) {
|
|
13
|
+
return (getAppSession ? getAppSession() : Promise.resolve(null)).catch((error) => {
|
|
14
|
+
console.error('Tolstoy getAppSession failed. Try-on shows the photos of this device only.', error);
|
|
15
|
+
return null;
|
|
16
|
+
});
|
|
17
|
+
}
|
|
18
|
+
async function getShopperToken(session, customerAccessToken, storefrontAccessToken) {
|
|
19
|
+
if (!customerAccessToken)
|
|
20
|
+
return null;
|
|
21
|
+
const key = JSON.stringify([session.environment, session.appKey, session.anonymousId, customerAccessToken]);
|
|
22
|
+
const cached = shopperTokens.get(key);
|
|
23
|
+
if (cached)
|
|
24
|
+
return cached;
|
|
25
|
+
const request = signInShopper(session, { customerAccessToken, storefrontAccessToken });
|
|
26
|
+
shopperTokens.set(key, request);
|
|
27
|
+
request.catch(() => shopperTokens.delete(key));
|
|
28
|
+
return request;
|
|
29
|
+
}
|
|
30
|
+
export function useTolstoyTryOn({ productId, variantId }) {
|
|
31
|
+
const context = useTolstoy();
|
|
32
|
+
const { appKey, appUrl, environment, anonymousId, getAppSession, storefrontAccessToken } = context;
|
|
33
|
+
// The cart callbacks are read when the shopper adds to cart; an app may pass new ones on each render.
|
|
34
|
+
const contextRef = useRef(context);
|
|
35
|
+
contextRef.current = context;
|
|
36
|
+
const [product, setProduct] = useState(null);
|
|
37
|
+
const [photos, setPhotos] = useState(null);
|
|
38
|
+
const [step, setStep] = useState({ name: 'photo', error: null });
|
|
39
|
+
const runRef = useRef(null);
|
|
40
|
+
const attemptRef = useRef(null);
|
|
41
|
+
const store = useMemo(() => ({ appKey, appUrl, environment, anonymousId }), [appKey, appUrl, environment, anonymousId]);
|
|
42
|
+
// The shopper changes when getAppSession gives another token (sign-out, another account), not when the app
|
|
43
|
+
// passes a new callback on a render. Then the earlier shopper's photos go and a running try-on stops.
|
|
44
|
+
const [customerToken, setCustomerToken] = useState(() => readCustomerToken(getAppSession));
|
|
45
|
+
const tokenSourceRef = useRef(getAppSession);
|
|
46
|
+
useEffect(() => {
|
|
47
|
+
if (tokenSourceRef.current === getAppSession)
|
|
48
|
+
return;
|
|
49
|
+
tokenSourceRef.current = getAppSession;
|
|
50
|
+
let current = true;
|
|
51
|
+
void Promise.all([customerToken, readCustomerToken(getAppSession)]).then(([shown, latest]) => {
|
|
52
|
+
if (current && latest !== shown)
|
|
53
|
+
setCustomerToken(Promise.resolve(latest));
|
|
54
|
+
});
|
|
55
|
+
return () => {
|
|
56
|
+
current = false;
|
|
57
|
+
};
|
|
58
|
+
}, [getAppSession, customerToken]);
|
|
59
|
+
const sessionRequest = useMemo(() => customerToken
|
|
60
|
+
.then((token) => getShopperToken(store, token, storefrontAccessToken))
|
|
61
|
+
.then((shopperToken) => ({ ...store, shopperToken }), (error) => {
|
|
62
|
+
console.error('Tolstoy shopper sign-in failed. Try-on shows the photos of this device only.', error);
|
|
63
|
+
return store;
|
|
64
|
+
}), [store, customerToken, storefrontAccessToken]);
|
|
65
|
+
const sessionRef = useRef(sessionRequest);
|
|
66
|
+
sessionRef.current = sessionRequest;
|
|
67
|
+
const productRequest = useMemo(() => getTryOnProduct(store, productId).catch((error) => {
|
|
68
|
+
console.error('Tolstoy try-on product did not load. Try-on uses the main image.', error);
|
|
69
|
+
return null;
|
|
70
|
+
}), [store, productId]);
|
|
71
|
+
const loadPhotos = useCallback(() => sessionRequest.then(getTryOnPhotos).then((loaded) => {
|
|
72
|
+
if (sessionRef.current === sessionRequest)
|
|
73
|
+
setPhotos(loaded);
|
|
74
|
+
}, (error) => {
|
|
75
|
+
console.error('Tolstoy saved photos did not load', error);
|
|
76
|
+
if (sessionRef.current === sessionRequest)
|
|
77
|
+
setPhotos((current) => current ?? []);
|
|
78
|
+
}), [sessionRequest]);
|
|
79
|
+
useEffect(() => {
|
|
80
|
+
let current = true;
|
|
81
|
+
productRequest.then((loaded) => current && setProduct(loaded));
|
|
82
|
+
return () => {
|
|
83
|
+
current = false;
|
|
84
|
+
};
|
|
85
|
+
}, [productRequest]);
|
|
86
|
+
useEffect(() => {
|
|
87
|
+
setPhotos(null);
|
|
88
|
+
setStep((current) => (current.name === 'photo' ? current : { name: 'photo', error: null }));
|
|
89
|
+
void loadPhotos();
|
|
90
|
+
return () => runRef.current?.abort();
|
|
91
|
+
}, [loadPhotos]);
|
|
92
|
+
const track = useCallback((eventName, params = {}) => sendTolstoyEvent(store, eventName, { currentPageProductId: productId, customParams: { productId, ...params } }), [store, productId]);
|
|
93
|
+
useEffect(() => {
|
|
94
|
+
sendTolstoyEvent(store, 'pageView', { currentPageProductId: productId });
|
|
95
|
+
sendTolstoyEvent(store, 'embedView', { currentPageProductId: productId });
|
|
96
|
+
track('tryon.panel.open');
|
|
97
|
+
}, [store, productId, track]);
|
|
98
|
+
useEffect(() => {
|
|
99
|
+
if (step.name === 'result')
|
|
100
|
+
track('tryon.result.view');
|
|
101
|
+
}, [step, track]);
|
|
102
|
+
const triedVariant = product ? getTryOnVariant(product, variantId) : null;
|
|
103
|
+
const sizes = useMemo(() => (product ? getSizeChoices(product, triedVariant) : []), [product, triedVariant]);
|
|
104
|
+
const run = (attempt) => {
|
|
105
|
+
runRef.current?.abort();
|
|
106
|
+
const controller = new AbortController();
|
|
107
|
+
runRef.current = controller;
|
|
108
|
+
attemptRef.current = attempt;
|
|
109
|
+
const isCurrent = () => !controller.signal.aborted;
|
|
110
|
+
setStep(attempt.photoUrl
|
|
111
|
+
? { name: 'generating', photoUri: attempt.photoUri }
|
|
112
|
+
: { name: 'uploading', photoUri: attempt.photoUri, percent: 0 });
|
|
113
|
+
void (async () => {
|
|
114
|
+
let uploading = !attempt.photoUrl;
|
|
115
|
+
try {
|
|
116
|
+
const session = await sessionRequest;
|
|
117
|
+
if (!isCurrent())
|
|
118
|
+
return;
|
|
119
|
+
if (attempt.file && !attempt.photoUrl) {
|
|
120
|
+
const uploaded = await uploadTryOnPhoto(session, attempt.file, (percent) => {
|
|
121
|
+
if (isCurrent())
|
|
122
|
+
setStep({ name: 'uploading', photoUri: attempt.photoUri, percent });
|
|
123
|
+
}, controller.signal);
|
|
124
|
+
attempt.photoUrl = uploaded.url;
|
|
125
|
+
if (!isCurrent())
|
|
126
|
+
return;
|
|
127
|
+
track('tryon.upload.success');
|
|
128
|
+
void loadPhotos();
|
|
129
|
+
}
|
|
130
|
+
uploading = false;
|
|
131
|
+
const photoUrl = attempt.photoUrl;
|
|
132
|
+
if (!photoUrl || !isCurrent())
|
|
133
|
+
return;
|
|
134
|
+
setStep({ name: 'generating', photoUri: attempt.photoUri });
|
|
135
|
+
const loaded = await productRequest;
|
|
136
|
+
const variant = loaded ? getTryOnVariant(loaded, variantId) : null;
|
|
137
|
+
track('tryon.generate.start', { variantId: variant?.id ?? '' });
|
|
138
|
+
const result = await runTryOn(session, { productId, variantId: variant?.id ?? null, variantImageUrl: variant?.imageUrl ?? loaded?.imageUrl ?? null, photoUrl }, controller.signal);
|
|
139
|
+
if (!isCurrent())
|
|
140
|
+
return;
|
|
141
|
+
track('tryon.generate.success', { variantId: variant?.id ?? '' });
|
|
142
|
+
setStep({ name: 'result', imageUrl: result.imageUrl });
|
|
143
|
+
}
|
|
144
|
+
catch (error) {
|
|
145
|
+
if (!isCurrent())
|
|
146
|
+
return;
|
|
147
|
+
const forShopper = error instanceof TolstoyTryOnError;
|
|
148
|
+
// A message the server wrote for the shopper is an answer, not a fault; only other errors go to the app's logs.
|
|
149
|
+
if (!forShopper)
|
|
150
|
+
console.error('Tolstoy try-on failed', error);
|
|
151
|
+
const rejected = uploading && forShopper;
|
|
152
|
+
track(rejected ? 'tryon.photo.reject' : uploading ? 'tryon.upload.error' : 'tryon.generate.error');
|
|
153
|
+
const message = forShopper ? error.message : GENERIC_ERROR;
|
|
154
|
+
// The photo check rejected the photo: only another photo can work.
|
|
155
|
+
if (rejected)
|
|
156
|
+
setStep({ name: 'photo', error: message });
|
|
157
|
+
else
|
|
158
|
+
setStep({ name: 'failed', photoUri: attempt.photoUri, error: message });
|
|
159
|
+
}
|
|
160
|
+
})();
|
|
161
|
+
};
|
|
162
|
+
const deletePhoto = async (photo) => {
|
|
163
|
+
await deleteTryOnPhoto(await sessionRequest, photo.id);
|
|
164
|
+
setPhotos((current) => current?.filter((saved) => saved.id !== photo.id) ?? null);
|
|
165
|
+
};
|
|
166
|
+
const addToCart = async (cartVariantId) => {
|
|
167
|
+
const { onAddToCart, onEvent } = contextRef.current;
|
|
168
|
+
if (!onAddToCart)
|
|
169
|
+
throw new Error('Set onAddToCart on TolstoyProvider to add to cart from try-on.');
|
|
170
|
+
const lines = [{ variantId: cartVariantId, quantity: 1 }];
|
|
171
|
+
await onAddToCart(lines);
|
|
172
|
+
onEvent?.({ type: 'add_to_cart', productId, lines });
|
|
173
|
+
track('tryon.cart.add', { productTitle: product?.title ?? '', variantId: cartVariantId, quantity: 1 });
|
|
174
|
+
};
|
|
175
|
+
return {
|
|
176
|
+
product,
|
|
177
|
+
triedVariant,
|
|
178
|
+
sizes,
|
|
179
|
+
photos,
|
|
180
|
+
step,
|
|
181
|
+
tryOnPhoto: (photo) => run({ photoUri: photo.url, photoUrl: photo.url }),
|
|
182
|
+
tryOnFile: (file) => run({ photoUri: file.uri, file }),
|
|
183
|
+
retry: () => {
|
|
184
|
+
if (attemptRef.current)
|
|
185
|
+
run(attemptRef.current);
|
|
186
|
+
},
|
|
187
|
+
backToPhotos: () => {
|
|
188
|
+
runRef.current?.abort();
|
|
189
|
+
setStep({ name: 'photo', error: null });
|
|
190
|
+
},
|
|
191
|
+
deletePhoto,
|
|
192
|
+
addToCart,
|
|
193
|
+
};
|
|
194
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tolstoy-ai/react-native-sdk",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.0",
|
|
4
4
|
"description": "Tolstoy shoppable videos and virtual try-on for bare React Native apps",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -19,6 +19,10 @@
|
|
|
19
19
|
"types": "./lib/api.d.ts",
|
|
20
20
|
"default": "./lib/api.js"
|
|
21
21
|
},
|
|
22
|
+
"./try-on-screen": {
|
|
23
|
+
"types": "./lib/tryOn/screen/TolstoyTryOnScreen.d.ts",
|
|
24
|
+
"default": "./lib/tryOn/screen/TolstoyTryOnScreen.js"
|
|
25
|
+
},
|
|
22
26
|
"./package.json": "./package.json"
|
|
23
27
|
},
|
|
24
28
|
"files": [
|
|
@@ -38,10 +42,14 @@
|
|
|
38
42
|
"peerDependencies": {
|
|
39
43
|
"react": ">=19.1.0",
|
|
40
44
|
"react-native": ">=0.81.0",
|
|
45
|
+
"react-native-image-picker": ">=8.3.0",
|
|
41
46
|
"react-native-video": ">=6.16.1",
|
|
42
47
|
"react-native-webview": ">=13.16.0"
|
|
43
48
|
},
|
|
44
49
|
"peerDependenciesMeta": {
|
|
50
|
+
"react-native-image-picker": {
|
|
51
|
+
"optional": true
|
|
52
|
+
},
|
|
45
53
|
"react-native-video": {
|
|
46
54
|
"optional": true
|
|
47
55
|
},
|
|
@@ -53,6 +61,7 @@
|
|
|
53
61
|
"@types/react": "catalog:",
|
|
54
62
|
"react": "19.1.4",
|
|
55
63
|
"react-native": "0.81.6",
|
|
64
|
+
"react-native-image-picker": "8.3.0",
|
|
56
65
|
"react-native-video": "6.16.1",
|
|
57
66
|
"react-native-webview": "13.16.1",
|
|
58
67
|
"typescript": "catalog:"
|
|
File without changes
|