@tolstoy-ai/react-native-sdk 0.2.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.
Files changed (54) hide show
  1. package/README.md +129 -8
  2. package/lib/TolstoyFeed.js +4 -0
  3. package/lib/TolstoyProvider.d.ts +1 -1
  4. package/lib/TolstoyProvider.js +1 -4
  5. package/lib/TolstoyVideoCarousel.js +1 -1
  6. package/lib/analytics.d.ts +5 -3
  7. package/lib/analytics.js +4 -4
  8. package/lib/api.d.ts +10 -0
  9. package/lib/api.js +5 -0
  10. package/lib/bridge.d.ts +1 -0
  11. package/lib/bridge.js +4 -0
  12. package/lib/config.d.ts +5 -0
  13. package/lib/config.js +10 -0
  14. package/lib/index.d.ts +5 -4
  15. package/lib/index.js +3 -2
  16. package/lib/{TolstoyTryOn.js → tryOn/TolstoyTryOn.js} +5 -5
  17. package/lib/tryOn/methods/shopperSignIn.d.ts +12 -0
  18. package/lib/tryOn/methods/shopperSignIn.js +29 -0
  19. package/lib/tryOn/methods/tryOnJob.d.ts +17 -0
  20. package/lib/tryOn/methods/tryOnJob.js +56 -0
  21. package/lib/tryOn/methods/tryOnPhotos.d.ts +19 -0
  22. package/lib/tryOn/methods/tryOnPhotos.js +112 -0
  23. package/lib/tryOn/methods/tryOnProduct.d.ts +169 -0
  24. package/lib/tryOn/methods/tryOnProduct.js +49 -0
  25. package/lib/tryOn/methods/tryOnSession.d.ts +14 -0
  26. package/lib/tryOn/methods/tryOnSession.js +26 -0
  27. package/lib/tryOn/screen/Header.d.ts +9 -0
  28. package/lib/tryOn/screen/Header.js +22 -0
  29. package/lib/tryOn/screen/Icon.d.ts +6 -0
  30. package/lib/tryOn/screen/Icon.js +6 -0
  31. package/lib/tryOn/screen/PhotoStep.d.ts +12 -0
  32. package/lib/tryOn/screen/PhotoStep.js +70 -0
  33. package/lib/tryOn/screen/PillButton.d.ts +10 -0
  34. package/lib/tryOn/screen/PillButton.js +31 -0
  35. package/lib/tryOn/screen/ProgressStep.d.ts +16 -0
  36. package/lib/tryOn/screen/ProgressStep.js +82 -0
  37. package/lib/tryOn/screen/ResultStep.d.ts +12 -0
  38. package/lib/tryOn/screen/ResultStep.js +114 -0
  39. package/lib/tryOn/screen/TolstoyMark.d.ts +4 -0
  40. package/lib/tryOn/screen/TolstoyMark.js +18 -0
  41. package/lib/tryOn/screen/TolstoyTryOnScreen.d.ts +6 -0
  42. package/lib/tryOn/screen/TolstoyTryOnScreen.js +39 -0
  43. package/lib/tryOn/screen/TopImage.d.ts +8 -0
  44. package/lib/tryOn/screen/TopImage.js +22 -0
  45. package/lib/tryOn/screen/icons.d.ts +24 -0
  46. package/lib/tryOn/screen/icons.js +10 -0
  47. package/lib/tryOn/screen/pickPhoto.d.ts +9 -0
  48. package/lib/tryOn/screen/pickPhoto.js +21 -0
  49. package/lib/tryOn/screen/useEstimatedProgress.d.ts +2 -0
  50. package/lib/tryOn/screen/useEstimatedProgress.js +22 -0
  51. package/lib/tryOn/useTolstoyTryOn.d.ts +44 -0
  52. package/lib/tryOn/useTolstoyTryOn.js +194 -0
  53. package/package.json +10 -1
  54. /package/lib/{TolstoyTryOn.d.ts → tryOn/TolstoyTryOn.d.ts} +0 -0
@@ -0,0 +1,112 @@
1
+ import { z } from 'zod';
2
+ import { ENVIRONMENTS } from '../../config';
3
+ import { jsonHeaders, readJson, shopperQuery, TolstoyTryOnError } from './tryOnSession';
4
+ const PhotosSchema = z.object({ images: z.array(z.object({ id: z.string(), url: z.string() })).optional() });
5
+ const StartUploadSchema = z.object({
6
+ uploadUrl: z.string(),
7
+ uploadFields: z.record(z.string(), z.string()),
8
+ media: z.object({ id: z.string() }),
9
+ });
10
+ const SavedPhotoSchema = z.object({
11
+ imageId: z.string(),
12
+ url: z.string(),
13
+ validation: z.object({ isViolating: z.boolean(), violationReason: z.string().optional() }),
14
+ });
15
+ const CONTENT_TYPES = {
16
+ jpg: 'image/jpeg',
17
+ jpeg: 'image/jpeg',
18
+ png: 'image/png',
19
+ webp: 'image/webp',
20
+ heic: 'image/heic',
21
+ heif: 'image/heif',
22
+ };
23
+ function photosUrl(session, path = '') {
24
+ return `${ENVIRONMENTS[session.environment].directApiBase}/shop-assistant-service/api/customer/user-images${path}?${shopperQuery(session)}`;
25
+ }
26
+ function contentTypeOf(file) {
27
+ if (file.type)
28
+ return file.type.toLowerCase();
29
+ const extension = (file.fileName ?? file.uri).split('.').pop()?.toLowerCase() ?? '';
30
+ const type = CONTENT_TYPES[extension];
31
+ if (!type)
32
+ throw new TolstoyTryOnError('Unsupported image type. Use JPG, PNG, WEBP, or HEIC.');
33
+ return type;
34
+ }
35
+ /** The shopper's saved photos, newest first. A signed-in shopper gets the photos of every device they used. */
36
+ export async function getTryOnPhotos(session) {
37
+ const response = await fetch(photosUrl(session), { headers: jsonHeaders(session) });
38
+ if (response.status === 404)
39
+ return [];
40
+ const { images = [] } = await readJson(response, PhotosSchema, 'photo list');
41
+ return images.map(({ id, url }) => ({ id, url }));
42
+ }
43
+ export async function deleteTryOnPhoto(session, photoId) {
44
+ const response = await fetch(photosUrl(session, `/${encodeURIComponent(photoId)}/delete`), {
45
+ method: 'POST',
46
+ headers: jsonHeaders(session),
47
+ body: '{}',
48
+ });
49
+ await readJson(response, z.unknown(), 'photo delete');
50
+ }
51
+ function uploadToStorage(url, fields, file, contentType, onProgress, signal) {
52
+ return new Promise((resolve, reject) => {
53
+ const request = new XMLHttpRequest();
54
+ signal?.addEventListener('abort', () => request.abort());
55
+ request.onabort = () => reject(new Error('Tolstoy photo upload was cancelled'));
56
+ request.upload.onprogress = (event) => {
57
+ if (event.lengthComputable && event.total)
58
+ onProgress?.(Math.round((event.loaded / event.total) * 100));
59
+ };
60
+ request.onload = () => request.status >= 200 && request.status < 300
61
+ ? resolve()
62
+ : reject(new Error(`Tolstoy photo upload failed: ${request.status}`));
63
+ request.onerror = () => reject(new Error('Tolstoy photo upload failed: network error'));
64
+ const form = new FormData();
65
+ for (const [key, value] of Object.entries(fields))
66
+ form.append(key, value);
67
+ // The storage policy reads the file from the last field. React Native sends { uri, type, name } as the file.
68
+ form.append('file', { uri: file.uri, type: contentType, name: file.fileName ?? 'photo' });
69
+ request.open('POST', url);
70
+ if (signal?.aborted)
71
+ request.abort();
72
+ else
73
+ request.send(form);
74
+ });
75
+ }
76
+ /**
77
+ * Uploads a photo and runs the photo check. A photo the check rejects throws a TolstoyTryOnError
78
+ * with the server's reason, for the shopper to read. An aborted signal stops the upload.
79
+ */
80
+ export async function uploadTryOnPhoto(session, file, onProgress, signal) {
81
+ const { serviceApiBase } = ENVIRONMENTS[session.environment];
82
+ const contentType = contentTypeOf(file);
83
+ const post = (path, body) => fetch(`${serviceApiBase}${path}`, {
84
+ method: 'POST',
85
+ headers: jsonHeaders(session),
86
+ body: JSON.stringify(body),
87
+ signal,
88
+ });
89
+ const started = await readJson(await post('/media-db-service/startPublicUpload', {
90
+ appKey: session.appKey,
91
+ media: {
92
+ contentType,
93
+ access: 'private',
94
+ metadata: [
95
+ { key: 'anonId', value: session.anonymousId },
96
+ { key: 'appUrl', value: session.appUrl },
97
+ ],
98
+ },
99
+ }), StartUploadSchema, 'photo upload start');
100
+ await uploadToStorage(started.uploadUrl, started.uploadFields, file, contentType, onProgress, signal);
101
+ await readJson(await post('/media-db-service/finishPublicUpload', { mediaId: started.media.id }), z.unknown(), 'photo upload finish');
102
+ const saved = await readJson(await post('/onyou/saveReferenceImage', {
103
+ appKey: session.appKey,
104
+ appUrl: session.appUrl,
105
+ anonId: session.anonymousId,
106
+ mediaId: started.media.id,
107
+ }), SavedPhotoSchema, 'photo check');
108
+ if (saved.validation.isViolating) {
109
+ throw new TolstoyTryOnError(saved.validation.violationReason || 'Please choose another photo.');
110
+ }
111
+ return { id: saved.imageId, url: saved.url };
112
+ }
@@ -0,0 +1,169 @@
1
+ import { z } from 'zod';
2
+ import type { TolstoyStore } from '../../api';
3
+ declare const VariantSchema: z.ZodObject<{
4
+ id: z.ZodString;
5
+ title: z.ZodString;
6
+ price: z.ZodString;
7
+ imageUrl: z.ZodNullable<z.ZodString>;
8
+ isAvailableForSale: z.ZodBoolean;
9
+ selectedOptions: z.ZodArray<z.ZodObject<{
10
+ name: z.ZodString;
11
+ value: z.ZodString;
12
+ }, "strip", z.ZodTypeAny, {
13
+ name: string;
14
+ value: string;
15
+ }, {
16
+ name: string;
17
+ value: string;
18
+ }>, "many">;
19
+ }, "strip", z.ZodTypeAny, {
20
+ id: string;
21
+ title: string;
22
+ price: string;
23
+ imageUrl: string | null;
24
+ isAvailableForSale: boolean;
25
+ selectedOptions: {
26
+ name: string;
27
+ value: string;
28
+ }[];
29
+ }, {
30
+ id: string;
31
+ title: string;
32
+ price: string;
33
+ imageUrl: string | null;
34
+ isAvailableForSale: boolean;
35
+ selectedOptions: {
36
+ name: string;
37
+ value: string;
38
+ }[];
39
+ }>;
40
+ declare const ProductsSchema: z.ZodObject<{
41
+ products: z.ZodArray<z.ZodObject<{
42
+ externalProductId: z.ZodString;
43
+ title: z.ZodString;
44
+ imageUrl: z.ZodNullable<z.ZodString>;
45
+ currencySymbol: z.ZodNullable<z.ZodString>;
46
+ variants: z.ZodArray<z.ZodObject<{
47
+ id: z.ZodString;
48
+ title: z.ZodString;
49
+ price: z.ZodString;
50
+ imageUrl: z.ZodNullable<z.ZodString>;
51
+ isAvailableForSale: z.ZodBoolean;
52
+ selectedOptions: z.ZodArray<z.ZodObject<{
53
+ name: z.ZodString;
54
+ value: z.ZodString;
55
+ }, "strip", z.ZodTypeAny, {
56
+ name: string;
57
+ value: string;
58
+ }, {
59
+ name: string;
60
+ value: string;
61
+ }>, "many">;
62
+ }, "strip", z.ZodTypeAny, {
63
+ id: string;
64
+ title: string;
65
+ price: string;
66
+ imageUrl: string | null;
67
+ isAvailableForSale: boolean;
68
+ selectedOptions: {
69
+ name: string;
70
+ value: string;
71
+ }[];
72
+ }, {
73
+ id: string;
74
+ title: string;
75
+ price: string;
76
+ imageUrl: string | null;
77
+ isAvailableForSale: boolean;
78
+ selectedOptions: {
79
+ name: string;
80
+ value: string;
81
+ }[];
82
+ }>, "many">;
83
+ }, "strip", z.ZodTypeAny, {
84
+ externalProductId: string;
85
+ title: string;
86
+ imageUrl: string | null;
87
+ currencySymbol: string | null;
88
+ variants: {
89
+ id: string;
90
+ title: string;
91
+ price: string;
92
+ imageUrl: string | null;
93
+ isAvailableForSale: boolean;
94
+ selectedOptions: {
95
+ name: string;
96
+ value: string;
97
+ }[];
98
+ }[];
99
+ }, {
100
+ externalProductId: string;
101
+ title: string;
102
+ imageUrl: string | null;
103
+ currencySymbol: string | null;
104
+ variants: {
105
+ id: string;
106
+ title: string;
107
+ price: string;
108
+ imageUrl: string | null;
109
+ isAvailableForSale: boolean;
110
+ selectedOptions: {
111
+ name: string;
112
+ value: string;
113
+ }[];
114
+ }[];
115
+ }>, "many">;
116
+ }, "strip", z.ZodTypeAny, {
117
+ products: {
118
+ externalProductId: string;
119
+ title: string;
120
+ imageUrl: string | null;
121
+ currencySymbol: string | null;
122
+ variants: {
123
+ id: string;
124
+ title: string;
125
+ price: string;
126
+ imageUrl: string | null;
127
+ isAvailableForSale: boolean;
128
+ selectedOptions: {
129
+ name: string;
130
+ value: string;
131
+ }[];
132
+ }[];
133
+ }[];
134
+ }, {
135
+ products: {
136
+ externalProductId: string;
137
+ title: string;
138
+ imageUrl: string | null;
139
+ currencySymbol: string | null;
140
+ variants: {
141
+ id: string;
142
+ title: string;
143
+ price: string;
144
+ imageUrl: string | null;
145
+ isAvailableForSale: boolean;
146
+ selectedOptions: {
147
+ name: string;
148
+ value: string;
149
+ }[];
150
+ }[];
151
+ }[];
152
+ }>;
153
+ export type TolstoyTryOnVariant = z.infer<typeof VariantSchema>;
154
+ export type TolstoyTryOnProduct = z.infer<typeof ProductsSchema>['products'][number];
155
+ export type TolstoySizeChoice = {
156
+ variantId: string;
157
+ label: string;
158
+ available: boolean;
159
+ };
160
+ /** The product with its variants. Null when the store's catalog has no such product. */
161
+ export declare function getTryOnProduct(store: TolstoyStore, productId: string): Promise<TolstoyTryOnProduct | null>;
162
+ /**
163
+ * The variant to try on: the given one, else the variant whose image is the product's main image, else the first.
164
+ * The try-on and the size choices use the same variant, so a size added to cart has the tried colour.
165
+ */
166
+ export declare function getTryOnVariant(product: TolstoyTryOnProduct, variantId?: string): TolstoyTryOnVariant | null;
167
+ /** The sizes of the tried variant's colour: the variants that share each of its options other than size. */
168
+ export declare function getSizeChoices(product: TolstoyTryOnProduct, triedVariant: TolstoyTryOnVariant | null): TolstoySizeChoice[];
169
+ export {};
@@ -0,0 +1,49 @@
1
+ import { z } from 'zod';
2
+ import { ENVIRONMENTS, toQuery } from '../../config';
3
+ import { readJson } from './tryOnSession';
4
+ const VariantSchema = z.object({
5
+ id: z.string(),
6
+ title: z.string(),
7
+ price: z.string(),
8
+ imageUrl: z.string().nullable(),
9
+ isAvailableForSale: z.boolean(),
10
+ selectedOptions: z.array(z.object({ name: z.string(), value: z.string() })),
11
+ });
12
+ const ProductsSchema = z.object({
13
+ products: z.array(z.object({
14
+ externalProductId: z.string(),
15
+ title: z.string(),
16
+ imageUrl: z.string().nullable(),
17
+ currencySymbol: z.string().nullable(),
18
+ variants: z.array(VariantSchema),
19
+ })),
20
+ });
21
+ const SIZE_OPTION = /size/i;
22
+ /** The product with its variants. Null when the store's catalog has no such product. */
23
+ export async function getTryOnProduct(store, productId) {
24
+ const query = toQuery({ appKey: store.appKey, appUrl: store.appUrl, externalProductIds: JSON.stringify([productId]) });
25
+ const response = await fetch(`${ENVIRONMENTS[store.environment].apiBase}/ai-widgets/v1/media/getProducts?${query}`);
26
+ const { products } = await readJson(response, ProductsSchema, 'product');
27
+ return products.find((product) => product.externalProductId === productId) ?? null;
28
+ }
29
+ /**
30
+ * The variant to try on: the given one, else the variant whose image is the product's main image, else the first.
31
+ * The try-on and the size choices use the same variant, so a size added to cart has the tried colour.
32
+ */
33
+ export function getTryOnVariant(product, variantId) {
34
+ return (product.variants.find((variant) => variant.id === variantId) ??
35
+ product.variants.find((variant) => variant.imageUrl === product.imageUrl) ??
36
+ product.variants[0] ??
37
+ null);
38
+ }
39
+ /** The sizes of the tried variant's colour: the variants that share each of its options other than size. */
40
+ export function getSizeChoices(product, triedVariant) {
41
+ const colourOptions = triedVariant?.selectedOptions.filter((option) => !SIZE_OPTION.test(option.name)) ?? [];
42
+ return product.variants
43
+ .filter((variant) => colourOptions.every((option) => variant.selectedOptions.some(({ name, value }) => name === option.name && value === option.value)))
44
+ .map((variant) => ({
45
+ variantId: variant.id,
46
+ label: variant.selectedOptions.find((option) => SIZE_OPTION.test(option.name))?.value ?? variant.title,
47
+ available: variant.isAvailableForSale,
48
+ }));
49
+ }
@@ -0,0 +1,14 @@
1
+ import { z } from 'zod';
2
+ import type { TolstoyStore } from '../../api';
3
+ export type TolstoyTryOnSession = TolstoyStore & {
4
+ anonymousId: string;
5
+ /** The Tolstoy shopper token from `signInShopper`. Saved photos then follow the shopper's account. */
6
+ shopperToken?: string | null;
7
+ };
8
+ /** A failure whose message the server wrote for the shopper, such as the reason a photo was rejected. */
9
+ export declare class TolstoyTryOnError extends Error {
10
+ name: string;
11
+ }
12
+ export declare function shopperQuery(session: TolstoyTryOnSession, extra?: Record<string, string>): string;
13
+ export declare function jsonHeaders(session: TolstoyTryOnSession): Record<string, string>;
14
+ export declare function readJson<T>(response: Response, schema: z.ZodType<T>, action: string): Promise<T>;
@@ -0,0 +1,26 @@
1
+ import { z } from 'zod';
2
+ import { toQuery } from '../../config';
3
+ /** A failure whose message the server wrote for the shopper, such as the reason a photo was rejected. */
4
+ export class TolstoyTryOnError extends Error {
5
+ constructor() {
6
+ super(...arguments);
7
+ this.name = 'TolstoyTryOnError';
8
+ }
9
+ }
10
+ const ErrorAnswerSchema = z.object({ error: z.string().optional(), message: z.string().optional() });
11
+ export function shopperQuery(session, extra = {}) {
12
+ return toQuery({ appKey: session.appKey, appUrl: session.appUrl, anonId: session.anonymousId, ...extra });
13
+ }
14
+ export function jsonHeaders(session) {
15
+ return {
16
+ 'Content-Type': 'application/json',
17
+ ...(session.shopperToken ? { Authorization: `Bearer ${session.shopperToken}` } : {}),
18
+ };
19
+ }
20
+ export async function readJson(response, schema, action) {
21
+ if (!response.ok) {
22
+ const answer = ErrorAnswerSchema.safeParse(await response.json().catch(() => null)).data;
23
+ throw new Error(`Tolstoy ${action} failed: ${response.status} ${answer?.message ?? answer?.error ?? ''}`.trim());
24
+ }
25
+ return schema.parse(await response.json());
26
+ }
@@ -0,0 +1,9 @@
1
+ type HeaderProps = {
2
+ title: string;
3
+ onBack?: () => void;
4
+ onClose: () => void;
5
+ closeLabel?: string;
6
+ };
7
+ /** The header of the shopper chat's sheets: a title and a close button over a hairline. */
8
+ export declare function Header({ title, onBack, onClose, closeLabel }: HeaderProps): import("react/jsx-runtime").JSX.Element;
9
+ export {};
@@ -0,0 +1,22 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { Pressable, StyleSheet, Text, View } from 'react-native';
3
+ import { Icon } from './Icon';
4
+ /** The header of the shopper chat's sheets: a title and a close button over a hairline. */
5
+ export function Header({ title, onBack, onClose, closeLabel = 'Close' }) {
6
+ return (_jsxs(View, { style: [styles.header, onBack ? styles.withBack : null], children: [onBack ? (_jsx(Pressable, { accessibilityRole: "button", accessibilityLabel: "Back", onPress: onBack, style: styles.iconButton, children: _jsx(Icon, { name: "back", color: "#141414" }) })) : null, _jsx(Text, { style: styles.title, numberOfLines: 1, children: title }), _jsx(Pressable, { accessibilityRole: "button", accessibilityLabel: closeLabel, onPress: onClose, style: styles.iconButton, children: _jsx(Icon, { name: "close", color: "#141414" }) })] }));
7
+ }
8
+ const styles = StyleSheet.create({
9
+ header: {
10
+ minHeight: 52,
11
+ flexDirection: 'row',
12
+ alignItems: 'center',
13
+ gap: 8,
14
+ paddingLeft: 16,
15
+ paddingRight: 8,
16
+ borderBottomWidth: 1,
17
+ borderBottomColor: '#e6e6e4',
18
+ },
19
+ withBack: { paddingLeft: 4 },
20
+ title: { flex: 1, fontSize: 16, fontWeight: '600', color: '#141414' },
21
+ iconButton: { width: 36, height: 36, borderRadius: 18, alignItems: 'center', justifyContent: 'center' },
22
+ });
@@ -0,0 +1,6 @@
1
+ import type { IconName } from './icons';
2
+ export declare function Icon({ name, size, color }: {
3
+ name: IconName;
4
+ size?: number;
5
+ color: string;
6
+ }): import("react/jsx-runtime").JSX.Element;
@@ -0,0 +1,6 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ import { Image } from 'react-native';
3
+ import { ICONS } from './icons';
4
+ export function Icon({ name, size = 20, color }) {
5
+ return _jsx(Image, { source: ICONS[name], style: { width: size, height: size, tintColor: color }, accessibilityIgnoresInvertColors: true });
6
+ }
@@ -0,0 +1,12 @@
1
+ import type { TolstoyTryOnPhoto } from '../methods/tryOnPhotos';
2
+ import type { PhotoSource } from './pickPhoto';
3
+ type PhotoStepProps = {
4
+ productImageUrl: string | null;
5
+ photos: TolstoyTryOnPhoto[] | null;
6
+ error: string | null;
7
+ onPick: (source: PhotoSource) => void;
8
+ onSavedPhoto: (photo: TolstoyTryOnPhoto) => void;
9
+ onClose: () => void;
10
+ };
11
+ export declare function PhotoStep({ productImageUrl, photos, error, onPick, onSavedPhoto, onClose }: PhotoStepProps): import("react/jsx-runtime").JSX.Element;
12
+ export {};
@@ -0,0 +1,70 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { useState } from 'react';
3
+ import { ActivityIndicator, Image, Pressable, ScrollView, StyleSheet, Text, View } from 'react-native';
4
+ import { Header } from './Header';
5
+ import { PillButton } from './PillButton';
6
+ import { TopImage } from './TopImage';
7
+ const GRID_GAP = 10;
8
+ function Stepper() {
9
+ return (_jsxs(View, { style: styles.stepper, accessibilityLabel: "Step 1 of 2", children: [_jsx(View, { style: [styles.stepDot, styles.stepDotActive], children: _jsx(Text, { style: [styles.stepText, styles.stepTextActive], children: "1" }) }), _jsx(View, { style: styles.stepLine }), _jsx(View, { style: styles.stepDot, children: _jsx(Text, { style: styles.stepText, children: "2" }) })] }));
10
+ }
11
+ export function PhotoStep({ productImageUrl, photos, error, onPick, onSavedPhoto, onClose }) {
12
+ const [gridWidth, setGridWidth] = useState(0);
13
+ const hasSaved = !!photos?.length;
14
+ const tileWidth = (gridWidth - GRID_GAP * 2) / 3;
15
+ return (_jsxs(View, { style: styles.screen, children: [_jsx(Header, { title: "Upload Image", onClose: onClose }), _jsxs(ScrollView, { contentContainerStyle: [styles.content, hasSaved ? null : styles.centered], children: [_jsx(Stepper, {}), _jsx(Text, { style: styles.heading, children: hasSaved ? 'Pick a photo' : 'Ready to try it on?' }), _jsx(Text, { style: styles.subheading, children: hasSaved ? 'Tap one of your photos to try it on' : 'Upload your photo and see how it looks on you in seconds' }), error ? (_jsx(View, { accessibilityRole: "alert", style: styles.error, children: _jsx(Text, { style: styles.errorText, children: error }) })) : null, photos === null ? (_jsx(ActivityIndicator, { style: styles.loading, color: "#9ca3af" })) : hasSaved ? (_jsx(View, { style: styles.grid, onLayout: ({ nativeEvent }) => setGridWidth(nativeEvent.layout.width), children: (gridWidth > 0 ? photos : []).map((photo) => (_jsx(Pressable, { accessibilityRole: "button", accessibilityLabel: "Try it on with this photo", onPress: () => onSavedPhoto(photo), style: ({ pressed }) => [styles.tile, { width: tileWidth }, pressed ? styles.tilePressed : null], children: _jsx(Image, { source: { uri: photo.url }, style: styles.fill }) }, photo.id))) })) : (_jsx(View, { style: styles.productCircle, children: productImageUrl ? _jsx(TopImage, { uri: productImageUrl }) : null })), _jsx(View, { style: styles.primaryAction, children: _jsx(PillButton, { kind: "primary", icon: "plus", label: hasSaved ? 'Upload a New Photo' : 'Choose Your Photo', onPress: () => onPick('library') }) }), _jsx(View, { style: styles.secondaryAction, children: _jsx(PillButton, { kind: "secondary", icon: "camera", label: "Take a photo in a mirror", onPress: () => onPick('camera') }) }), _jsx(Text, { style: styles.privacy, children: "Your photo is used only to create your try-on. AI can make mistakes." })] })] }));
16
+ }
17
+ const styles = StyleSheet.create({
18
+ screen: { flex: 1 },
19
+ content: { flexGrow: 1, alignItems: 'center', paddingHorizontal: 24, paddingTop: 32, paddingBottom: 24 },
20
+ centered: { justifyContent: 'center' },
21
+ stepper: { flexDirection: 'row', alignItems: 'center', gap: 12 },
22
+ stepDot: {
23
+ width: 32,
24
+ height: 32,
25
+ borderRadius: 16,
26
+ alignItems: 'center',
27
+ justifyContent: 'center',
28
+ backgroundColor: '#f3f4f6',
29
+ },
30
+ stepDotActive: { backgroundColor: '#000' },
31
+ stepText: { fontSize: 14, fontWeight: '600', color: '#6b7280' },
32
+ stepTextActive: { color: '#fff' },
33
+ stepLine: { width: 48, height: 2, borderRadius: 1, backgroundColor: '#e5e7eb' },
34
+ heading: { marginTop: 20, fontSize: 22, fontWeight: '500', color: '#111827', textAlign: 'center' },
35
+ subheading: { marginTop: 8, maxWidth: 300, fontSize: 15, lineHeight: 20, color: '#6b7280', textAlign: 'center' },
36
+ error: {
37
+ alignSelf: 'stretch',
38
+ marginTop: 20,
39
+ borderRadius: 16,
40
+ backgroundColor: '#fef2f2',
41
+ paddingHorizontal: 16,
42
+ paddingVertical: 12,
43
+ },
44
+ errorText: { fontSize: 14, lineHeight: 20, color: '#b91c1c' },
45
+ loading: { marginTop: 24, height: 96 },
46
+ grid: { alignSelf: 'stretch', marginTop: 24, flexDirection: 'row', flexWrap: 'wrap', gap: GRID_GAP },
47
+ tile: {
48
+ aspectRatio: 3 / 4,
49
+ borderRadius: 16,
50
+ overflow: 'hidden',
51
+ backgroundColor: '#f3f4f6',
52
+ borderWidth: 1,
53
+ borderColor: 'rgba(0,0,0,0.05)',
54
+ },
55
+ tilePressed: { transform: [{ scale: 0.97 }] },
56
+ fill: { width: '100%', height: '100%' },
57
+ productCircle: {
58
+ marginTop: 24,
59
+ width: 96,
60
+ height: 96,
61
+ borderRadius: 48,
62
+ overflow: 'hidden',
63
+ borderWidth: 1,
64
+ borderColor: '#e5e7eb',
65
+ backgroundColor: '#f9fafb',
66
+ },
67
+ primaryAction: { alignSelf: 'stretch', marginTop: 24 },
68
+ secondaryAction: { alignSelf: 'stretch', marginTop: 12 },
69
+ privacy: { marginTop: 20, maxWidth: 300, fontSize: 12, lineHeight: 19, color: '#9ca3af', textAlign: 'center' },
70
+ });
@@ -0,0 +1,10 @@
1
+ import type { IconName } from './icons';
2
+ type PillButtonProps = {
3
+ label: string;
4
+ icon?: IconName;
5
+ kind: 'primary' | 'secondary';
6
+ disabled?: boolean;
7
+ onPress: () => void;
8
+ };
9
+ export declare function PillButton({ label, icon, kind, disabled, onPress }: PillButtonProps): import("react/jsx-runtime").JSX.Element;
10
+ export {};
@@ -0,0 +1,31 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { Pressable, StyleSheet, Text } from 'react-native';
3
+ import { Icon } from './Icon';
4
+ export function PillButton({ label, icon, kind, disabled, onPress }) {
5
+ const primary = kind === 'primary';
6
+ const textColor = disabled ? '#9ca3af' : primary ? '#fff' : '#1f2937';
7
+ return (_jsxs(Pressable, { accessibilityRole: "button", accessibilityState: { disabled }, disabled: disabled, onPress: onPress, style: ({ pressed }) => [
8
+ styles.button,
9
+ primary ? styles.primary : styles.secondary,
10
+ pressed ? (primary ? styles.primaryPressed : styles.secondaryPressed) : null,
11
+ disabled ? (primary ? styles.primaryDisabled : styles.secondaryDisabled) : null,
12
+ ], children: [icon ? _jsx(Icon, { name: icon, size: primary ? 20 : 18, color: textColor }) : null, _jsx(Text, { style: [primary ? styles.primaryText : styles.secondaryText, { color: textColor }], children: label })] }));
13
+ }
14
+ const styles = StyleSheet.create({
15
+ button: {
16
+ width: '100%',
17
+ flexDirection: 'row',
18
+ alignItems: 'center',
19
+ justifyContent: 'center',
20
+ gap: 10,
21
+ borderRadius: 999,
22
+ },
23
+ primary: { height: 56, backgroundColor: '#000' },
24
+ primaryPressed: { backgroundColor: '#1f2937' },
25
+ primaryDisabled: { backgroundColor: '#e5e7eb' },
26
+ secondary: { height: 48, borderWidth: 1, borderColor: '#d1d5db', backgroundColor: '#fff' },
27
+ secondaryPressed: { backgroundColor: '#f9fafb' },
28
+ secondaryDisabled: { borderColor: '#e5e7eb' },
29
+ primaryText: { fontSize: 17, fontWeight: '600' },
30
+ secondaryText: { fontSize: 15, fontWeight: '500' },
31
+ });
@@ -0,0 +1,16 @@
1
+ import type { ProgressPhase } from './useEstimatedProgress';
2
+ type ProgressStepProps = {
3
+ productImageUrl: string | null;
4
+ photoUri: string;
5
+ onClose: () => void;
6
+ } & ({
7
+ phase: ProgressPhase;
8
+ uploadPercent: number;
9
+ } | {
10
+ phase: 'failed';
11
+ error: string;
12
+ onRetry: () => void;
13
+ onChangePhoto: () => void;
14
+ });
15
+ export declare function ProgressStep(props: ProgressStepProps): import("react/jsx-runtime").JSX.Element;
16
+ export {};
@@ -0,0 +1,82 @@
1
+ import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { useEffect, useRef } from 'react';
3
+ import { Animated, Easing, 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
+ import { useEstimatedProgress } from './useEstimatedProgress';
9
+ function stageLabel(phase, percent) {
10
+ if (phase === 'uploading')
11
+ return 'Uploading your photo…';
12
+ if (percent < 30)
13
+ return 'Analyzing your photo…';
14
+ if (percent < 55)
15
+ return 'Understanding body shape…';
16
+ if (percent < 80)
17
+ return 'Fitting it on you…';
18
+ return 'Adding final touches…';
19
+ }
20
+ function Card({ uri, tilt }) {
21
+ return (_jsx(View, { style: [styles.card, { transform: [{ rotate: tilt }] }], children: uri ? _jsx(TopImage, { uri: uri }) : null }));
22
+ }
23
+ function SpinningSwap({ spinning }) {
24
+ const turn = useRef(new Animated.Value(0)).current;
25
+ useEffect(() => {
26
+ if (!spinning)
27
+ return;
28
+ const loop = Animated.loop(Animated.timing(turn, { toValue: 1, duration: 2400, easing: Easing.linear, useNativeDriver: true }));
29
+ loop.start();
30
+ return () => loop.stop();
31
+ }, [spinning, turn]);
32
+ const rotate = turn.interpolate({ inputRange: [0, 1], outputRange: ['0deg', '360deg'] });
33
+ return (_jsx(View, { style: styles.swap, children: _jsx(Animated.View, { style: { transform: [{ rotate }] }, children: _jsx(Icon, { name: "swap", size: 18, color: "#374151" }) }) }));
34
+ }
35
+ function Progress({ phase, uploadPercent }) {
36
+ const percent = useEstimatedProgress(phase, uploadPercent);
37
+ return (_jsxs(_Fragment, { children: [_jsx(Text, { style: styles.label, accessibilityLiveRegion: "polite", children: stageLabel(phase, percent) }), _jsx(View, { style: styles.track, children: _jsx(View, { style: [styles.bar, { width: `${percent}%` }] }) }), _jsxs(Text, { style: styles.percent, children: [percent, "%"] })] }));
38
+ }
39
+ export function ProgressStep(props) {
40
+ const { productImageUrl, photoUri, onClose } = props;
41
+ return (_jsxs(View, { style: styles.screen, children: [_jsx(Header, { title: "See it on you", onClose: onClose, closeLabel: "Cancel" }), _jsxs(View, { style: styles.content, children: [_jsxs(View, { style: styles.cards, children: [_jsx(Card, { uri: productImageUrl, tilt: "-6deg" }), _jsx(SpinningSwap, { spinning: props.phase !== 'failed' }), _jsx(Card, { uri: photoUri, tilt: "6deg" })] }), props.phase === 'failed' ? (_jsxs(_Fragment, { children: [_jsx(Text, { style: styles.failure, accessibilityRole: "alert", children: props.error }), _jsxs(View, { style: styles.actions, children: [_jsx(PillButton, { kind: "primary", icon: "swap", label: "Try again", onPress: props.onRetry }), _jsx(PillButton, { kind: "secondary", label: "Change photo", onPress: props.onChangePhoto })] })] })) : (_jsx(Progress, { phase: props.phase, uploadPercent: props.uploadPercent }))] })] }));
42
+ }
43
+ const styles = StyleSheet.create({
44
+ screen: { flex: 1 },
45
+ content: { flex: 1, alignItems: 'center', justifyContent: 'center', paddingHorizontal: 32 },
46
+ cards: { flexDirection: 'row', alignItems: 'center' },
47
+ card: {
48
+ width: 112,
49
+ height: 144,
50
+ borderRadius: 16,
51
+ borderWidth: 4,
52
+ borderColor: '#fff',
53
+ overflow: 'hidden',
54
+ backgroundColor: '#f3f4f6',
55
+ boxShadow: '0 8px 24px rgba(0,0,0,0.12)',
56
+ },
57
+ swap: {
58
+ zIndex: 1,
59
+ marginHorizontal: -12,
60
+ width: 40,
61
+ height: 40,
62
+ borderRadius: 20,
63
+ alignItems: 'center',
64
+ justifyContent: 'center',
65
+ backgroundColor: '#fff',
66
+ boxShadow: '0 4px 6px rgba(0,0,0,0.1)',
67
+ },
68
+ label: {
69
+ marginTop: 40,
70
+ minHeight: 56,
71
+ fontSize: 22,
72
+ lineHeight: 28,
73
+ fontWeight: '600',
74
+ color: '#111827',
75
+ textAlign: 'center',
76
+ },
77
+ track: { marginTop: 12, width: '100%', maxWidth: 260, height: 4, borderRadius: 2, overflow: 'hidden', backgroundColor: '#f3f4f6' },
78
+ bar: { height: '100%', borderRadius: 2, backgroundColor: '#000' },
79
+ percent: { marginTop: 8, fontSize: 13, color: '#9ca3af', fontVariant: ['tabular-nums'] },
80
+ failure: { marginTop: 40, fontSize: 17, lineHeight: 24, fontWeight: '600', color: '#111827', textAlign: 'center' },
81
+ actions: { alignSelf: 'stretch', marginTop: 24, gap: 12 },
82
+ });