@wasto/cms-components 1.5.10 → 1.5.11

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 (98) hide show
  1. package/README.md +47 -47
  2. package/dist/index.d.mts +103 -2
  3. package/dist/index.d.ts +103 -2
  4. package/dist/index.js +2861 -2442
  5. package/dist/index.mjs +3651 -3227
  6. package/package.json +2 -2
  7. package/src/components/announcement-modal/AnnouncementModal.tsx +183 -183
  8. package/src/components/article/Article.tsx +21 -21
  9. package/src/components/article/ArticleCard.tsx +81 -81
  10. package/src/components/article/ArticleExcerpts.tsx +80 -80
  11. package/src/components/article/ArticleList.tsx +114 -114
  12. package/src/components/article/ArticleMarkdown.tsx +170 -170
  13. package/src/components/article/ArticleReaderModal.tsx +93 -93
  14. package/src/components/article/ArticleSingle.tsx +57 -57
  15. package/src/components/bottom-tab/BottomTab.tsx +392 -392
  16. package/src/components/button/Button.tsx +154 -154
  17. package/src/components/challenge/Badges.tsx +84 -84
  18. package/src/components/challenge/BadgesModal.tsx +166 -166
  19. package/src/components/challenge/Challenge.tsx +380 -380
  20. package/src/components/challenge/ChallengeModal.tsx +231 -231
  21. package/src/components/challenge/ChallengeVignette.tsx +249 -249
  22. package/src/components/challenge/ChallengesModal.tsx +243 -243
  23. package/src/components/challenge/QuizModal.tsx +381 -381
  24. package/src/components/challenge/ResultModal.tsx +144 -144
  25. package/src/components/chat/Chat.tsx +928 -928
  26. package/src/components/collection-calendar/CollectionCalendar.tsx +274 -274
  27. package/src/components/columns/Columns.tsx +33 -33
  28. package/src/components/consignes-modal/ConsignesModal.tsx +267 -267
  29. package/src/components/content-inset/ContentInset.tsx +33 -33
  30. package/src/components/header/Header.tsx +391 -391
  31. package/src/components/image/Image.tsx +15 -15
  32. package/src/components/image/ImageFrame.tsx +102 -102
  33. package/src/components/image/ImageMedia.tsx +31 -31
  34. package/src/components/image/ImageUrl.tsx +30 -30
  35. package/src/components/locations-map/LocationSheet.tsx +417 -417
  36. package/src/components/locations-map/LocationsMap.native.tsx +260 -260
  37. package/src/components/locations-map/LocationsMap.tsx +13 -13
  38. package/src/components/locations-map/LocationsMap.web.tsx +10 -10
  39. package/src/components/locations-map/LocationsMapShell.tsx +527 -527
  40. package/src/components/locations-map/LocationsMapView.tsx +108 -108
  41. package/src/components/locations-map/LocationsMapView.web.tsx +331 -331
  42. package/src/components/nav-button/NavButton.tsx +59 -59
  43. package/src/components/next-collection/NextCollection.tsx +636 -621
  44. package/src/components/notifications/NotificationsScreen.tsx +247 -247
  45. package/src/components/page/Page.tsx +102 -64
  46. package/src/components/parapraph/Paragraph.tsx +67 -67
  47. package/src/components/profile/ProfileScreen.tsx +236 -236
  48. package/src/components/recycling-info/RecyclingInfo.tsx +189 -189
  49. package/src/components/safe-area/OptionalSafeAreaProvider.tsx +17 -17
  50. package/src/components/search/Search.tsx +320 -320
  51. package/src/components/select-street-modal/SelectStreetModal.tsx +475 -475
  52. package/src/components/title/Title.tsx +100 -100
  53. package/src/components/vision/Vision.tsx +447 -447
  54. package/src/components/vision/VisionActionCard.tsx +117 -117
  55. package/src/components/vision/VisionCapture.tsx +30 -30
  56. package/src/components/vision/VisionTapOverlay.tsx +122 -122
  57. package/src/contexts/AnnouncementsContext.tsx +171 -171
  58. package/src/contexts/AppDataContext.tsx +458 -0
  59. package/src/contexts/ChallengesContext.tsx +182 -182
  60. package/src/contexts/LocalContext.tsx +227 -227
  61. package/src/contexts/ThemeContext.tsx +37 -37
  62. package/src/contexts/WastoContext.tsx +130 -127
  63. package/src/helpers/blogPost.ts +72 -72
  64. package/src/helpers/generateQuizQuestions.ts +247 -247
  65. package/src/helpers/getContrastColor.ts +18 -18
  66. package/src/helpers/haptics.ts +20 -20
  67. package/src/helpers/hoursSchedule.ts +230 -230
  68. package/src/helpers/htmlContentToMarkdown.ts +114 -114
  69. package/src/helpers/layout.ts +54 -54
  70. package/src/helpers/loadLinearGradient.ts +22 -22
  71. package/src/helpers/mapLocations.ts +170 -0
  72. package/src/helpers/maquetteTheme.ts +76 -76
  73. package/src/helpers/markdownUnderlinePlugin.ts +32 -32
  74. package/src/helpers/nextCollection.ts +122 -0
  75. package/src/helpers/normalizeWasteTypeRecyclingInfo.ts +80 -80
  76. package/src/helpers/publicMediaUrl.ts +8 -8
  77. package/src/helpers/resolveApiAssetUrl.ts +21 -21
  78. package/src/helpers/systemRoutes.ts +7 -7
  79. package/src/helpers/themeStyles.ts +114 -114
  80. package/src/helpers/ttlCache.ts +41 -0
  81. package/src/helpers/useSafeAreaPadding.ts +14 -14
  82. package/src/hooks/useBadges.ts +100 -100
  83. package/src/hooks/useBlogPosts.ts +109 -105
  84. package/src/hooks/useChallenges.ts +110 -110
  85. package/src/hooks/useCities.ts +56 -56
  86. package/src/hooks/useCityAnnouncements.ts +118 -118
  87. package/src/hooks/useCollectionCalendar.ts +421 -421
  88. package/src/hooks/useColumns.ts +19 -19
  89. package/src/hooks/useConsignes.ts +62 -62
  90. package/src/hooks/useLocations.ts +120 -248
  91. package/src/hooks/useNextCollection.ts +163 -238
  92. package/src/hooks/useRecyclingInfo.ts +90 -90
  93. package/src/hooks/useWastoClient.ts +16 -16
  94. package/src/index.ts +149 -142
  95. package/src/navigation/NavigationContext.tsx +56 -56
  96. package/src/sentry/initSentry.ts +120 -120
  97. package/src/types/Theme.ts +72 -72
  98. package/src/types/css-modules.d.ts +1 -1
@@ -1,447 +1,447 @@
1
- /**
2
- * Bloc CMS Vision — parcours Lens : photo → tap → carte post-scan (ADR-003 / Phase 6).
3
- * WebRTC /offer n’est pas utilisé (MVP).
4
- */
5
- import { useCallback, useState } from "react";
6
- import {
7
- ActivityIndicator,
8
- Modal,
9
- Platform,
10
- StyleSheet,
11
- Text,
12
- View,
13
- } from "react-native";
14
- import { useTheme } from "../../contexts/ThemeContext";
15
- import { useLocal } from "../../contexts/LocalContext";
16
- import { useWastoClient } from "../../hooks/useWastoClient";
17
- import { Button } from "../button/Button";
18
- import { cardStyle, resolveTheme } from "../../helpers/themeStyles";
19
- import { SPACE } from "../../helpers/layout";
20
- import { VisionCapture } from "./VisionCapture";
21
- import { VisionTapOverlay } from "./VisionTapOverlay";
22
- import { VisionActionCard, type VisionSuggestion } from "./VisionActionCard";
23
-
24
- const DEFAULT_TITLE = "Wast’O Scan";
25
- const DEFAULT_DESCRIPTION =
26
- "Photographiez un déchet, touchez-le sur la photo, puis suivez la consigne locale.";
27
- const TIPS =
28
- "Astuce : bonne lumière, objet centré, un déchet à la fois si possible.";
29
-
30
- const MIN_CARD_HEIGHT = 120;
31
- const MAX_CARD_HEIGHT = 800;
32
- const DEFAULT_CARD_HEIGHT = 280;
33
-
34
- const VISION_SESSION_START_PATH = "/public/vision/sessions/start";
35
-
36
- const LOG_TAG = "[Vision]";
37
-
38
- function visionDebug(...args: unknown[]) {
39
- if (__DEV__) console.log(LOG_TAG, ...args);
40
- }
41
-
42
- function visionWarn(message: string, detail?: unknown) {
43
- if (detail !== undefined) console.warn(LOG_TAG, message, detail);
44
- else console.warn(LOG_TAG, message);
45
- }
46
-
47
- export type VisionCaptureResult = {
48
- uri: string;
49
- };
50
-
51
- export type VisionProps = {
52
- /** URL POST /detect (sinon fournie par startSession). */
53
- detectUrl?: string;
54
- /** @deprecated conservé pour compat CMS ; non utilisé en parcours Lens. */
55
- offerUrl?: string;
56
- title?: string;
57
- description?: string;
58
- height?: number;
59
- /** Override ville ; sinon LocalContext.selectedCityId. */
60
- cityId?: string;
61
- /**
62
- * Capture custom (sinon expo-image-picker si installé dans l’app hôte).
63
- */
64
- onRequestCapture?: () => Promise<VisionCaptureResult | null>;
65
- };
66
-
67
- type Phase = "idle" | "capture" | "tap" | "loading" | "card" | "error";
68
-
69
- type SessionUrls = {
70
- sessionId: string;
71
- detectUrl: string;
72
- };
73
-
74
- function clampHeight(h: number | undefined): number {
75
- if (typeof h !== "number" || !Number.isFinite(h)) return DEFAULT_CARD_HEIGHT;
76
- return Math.max(MIN_CARD_HEIGHT, Math.min(MAX_CARD_HEIGHT, h));
77
- }
78
-
79
- async function defaultCapturePhoto(): Promise<VisionCaptureResult | null> {
80
- try {
81
- // Peer optional — app hôte doit installer expo-image-picker
82
- // eslint-disable-next-line @typescript-eslint/no-require-imports
83
- const ImagePicker = require("expo-image-picker") as {
84
- requestCameraPermissionsAsync: () => Promise<{ status: string }>;
85
- launchCameraAsync: (opts: Record<string, unknown>) => Promise<{
86
- canceled: boolean;
87
- assets?: Array<{ uri: string }>;
88
- }>;
89
- };
90
- const perm = await ImagePicker.requestCameraPermissionsAsync();
91
- if (perm.status !== "granted") {
92
- throw new Error("Permission caméra refusée.");
93
- }
94
- const result = await ImagePicker.launchCameraAsync({
95
- quality: 0.85,
96
- exif: false,
97
- });
98
- if (result.canceled || !result.assets?.[0]?.uri) return null;
99
- return { uri: result.assets[0].uri };
100
- } catch (e) {
101
- visionWarn("expo-image-picker indisponible", e);
102
- throw new Error(
103
- "Installez expo-image-picker dans l’app, ou fournissez onRequestCapture.",
104
- );
105
- }
106
- }
107
-
108
- export function Vision({
109
- detectUrl: detectUrlProp = "",
110
- title,
111
- description,
112
- height: heightProp,
113
- cityId: cityIdProp,
114
- onRequestCapture,
115
- }: VisionProps) {
116
- const { theme } = useTheme();
117
- const t = resolveTheme(theme);
118
- const { selectedCityId } = useLocal();
119
- const client = useWastoClient();
120
- const cityId = cityIdProp?.trim() || selectedCityId || undefined;
121
-
122
- const [modalVisible, setModalVisible] = useState(false);
123
- const [phase, setPhase] = useState<Phase>("idle");
124
- const [errorMessage, setErrorMessage] = useState<string | null>(null);
125
- const [imageUri, setImageUri] = useState<string | null>(null);
126
- const [tap, setTap] = useState<{ x: number; y: number } | null>(null);
127
- const [session, setSession] = useState<SessionUrls | null>(null);
128
- const [suggestions, setSuggestions] = useState<VisionSuggestion[]>([]);
129
- const [primaryLabel, setPrimaryLabel] = useState<string | null>(null);
130
- const [confidence, setConfidence] = useState<number | null>(null);
131
- const [requireConfirm, setRequireConfirm] = useState(true);
132
- const [busy, setBusy] = useState(false);
133
-
134
- const cardMinHeight = clampHeight(heightProp);
135
- const displayTitle = (title && title.trim()) || DEFAULT_TITLE;
136
- const displayDescription =
137
- (description && description.trim()) || DEFAULT_DESCRIPTION;
138
-
139
- const resetFlow = useCallback(() => {
140
- setPhase("capture");
141
- setErrorMessage(null);
142
- setImageUri(null);
143
- setTap(null);
144
- setSuggestions([]);
145
- setPrimaryLabel(null);
146
- setConfidence(null);
147
- setBusy(false);
148
- }, []);
149
-
150
- const ensureSession = useCallback(async (): Promise<SessionUrls> => {
151
- if (session?.detectUrl && session.sessionId) return session;
152
-
153
- const propDetect = detectUrlProp.trim();
154
- const res = (await client.request(VISION_SESSION_START_PATH, {
155
- method: "POST",
156
- body: JSON.stringify({
157
- cityId: cityId || undefined,
158
- }),
159
- })) as {
160
- sessionId: string;
161
- detectUrl?: string;
162
- offerUrl?: string;
163
- };
164
-
165
- const detect =
166
- propDetect ||
167
- res.detectUrl?.trim() ||
168
- (res.offerUrl ? res.offerUrl.replace(/\/offer\/?$/, "/detect") : "");
169
-
170
- if (!res.sessionId || !detect) {
171
- throw new Error(
172
- "Session vision incomplète (sessionId / detectUrl). Vérifiez WASTO_VISION_URL.",
173
- );
174
- }
175
-
176
- const next = { sessionId: res.sessionId, detectUrl: detect };
177
- setSession(next);
178
- return next;
179
- }, [session, detectUrlProp, client, cityId]);
180
-
181
- const openScan = useCallback(() => {
182
- setModalVisible(true);
183
- resetFlow();
184
- }, [resetFlow]);
185
-
186
- const closeModal = useCallback(() => {
187
- setModalVisible(false);
188
- setPhase("idle");
189
- setBusy(false);
190
- }, []);
191
-
192
- const handleCapture = useCallback(async () => {
193
- setBusy(true);
194
- setErrorMessage(null);
195
- try {
196
- const capture = onRequestCapture
197
- ? await onRequestCapture()
198
- : await defaultCapturePhoto();
199
- if (!capture?.uri) {
200
- setBusy(false);
201
- return;
202
- }
203
- setImageUri(capture.uri);
204
- setTap(null);
205
- setPhase("tap");
206
- } catch (e: unknown) {
207
- const msg = e instanceof Error ? e.message : String(e);
208
- setErrorMessage(msg);
209
- setPhase("error");
210
- } finally {
211
- setBusy(false);
212
- }
213
- }, [onRequestCapture]);
214
-
215
- const runDetectAndFinalize = useCallback(
216
- async (tapCoords: { x: number; y: number } | null) => {
217
- if (!imageUri) return;
218
- setBusy(true);
219
- setPhase("loading");
220
- setErrorMessage(null);
221
- try {
222
- const sess = await ensureSession();
223
-
224
- const form = new FormData();
225
- form.append("image", {
226
- uri: imageUri,
227
- name: "scan.jpg",
228
- type: "image/jpeg",
229
- } as unknown as Blob);
230
- if (tapCoords) {
231
- form.append("tapX", String(tapCoords.x));
232
- form.append("tapY", String(tapCoords.y));
233
- }
234
-
235
- visionDebug("POST detect", { detectUrl: sess.detectUrl, tap: tapCoords });
236
- const detectRes = await fetch(sess.detectUrl, {
237
- method: "POST",
238
- body: form,
239
- });
240
- const detectText = await detectRes.text();
241
- if (!detectRes.ok) {
242
- throw new Error(detectText || `Detect HTTP ${detectRes.status}`);
243
- }
244
- const detectJson = JSON.parse(detectText) as {
245
- detections?: Array<{
246
- label: string;
247
- confidence: number;
248
- bbox?: number[];
249
- tap?: { x: number; y: number };
250
- ts?: number;
251
- }>;
252
- };
253
-
254
- const finalizePath = `/public/vision/sessions/${sess.sessionId}/finalize`;
255
- const finalized = (await client.request(finalizePath, {
256
- method: "POST",
257
- body: JSON.stringify({
258
- detections: detectJson.detections ?? [],
259
- cityId: cityId || undefined,
260
- tap: tapCoords ?? undefined,
261
- }),
262
- })) as {
263
- suggestions?: VisionSuggestion[];
264
- primaryLabel?: string | null;
265
- confidence?: number | null;
266
- requireUserConfirm?: boolean;
267
- };
268
-
269
- setSuggestions(finalized.suggestions ?? []);
270
- setPrimaryLabel(finalized.primaryLabel ?? null);
271
- setConfidence(finalized.confidence ?? null);
272
- setRequireConfirm(finalized.requireUserConfirm !== false);
273
- setPhase("card");
274
- } catch (e: unknown) {
275
- const msg = e instanceof Error ? e.message : String(e);
276
- visionWarn("detect/finalize failed", e);
277
- setErrorMessage(msg);
278
- setPhase("error");
279
- } finally {
280
- setBusy(false);
281
- }
282
- },
283
- [imageUri, ensureSession, client, cityId],
284
- );
285
-
286
- const handleConfirm = useCallback(async () => {
287
- if (!session?.sessionId) return;
288
- setBusy(true);
289
- try {
290
- await client.request(`/public/vision/sessions/${session.sessionId}/report`, {
291
- method: "POST",
292
- body: JSON.stringify({
293
- userConfirmed: true,
294
- label: primaryLabel ?? undefined,
295
- confidence: confidence ?? undefined,
296
- actionKind: suggestions.find((s) => s.kind === "SORT_BIN")?.kind,
297
- }),
298
- });
299
- closeModal();
300
- } catch (e: unknown) {
301
- const msg = e instanceof Error ? e.message : String(e);
302
- setErrorMessage(msg);
303
- setPhase("error");
304
- } finally {
305
- setBusy(false);
306
- }
307
- }, [session, client, primaryLabel, confidence, suggestions, closeModal]);
308
-
309
- const handleWrong = useCallback(async () => {
310
- if (session?.sessionId) {
311
- try {
312
- await client.request(`/public/vision/sessions/${session.sessionId}/report`, {
313
- method: "POST",
314
- body: JSON.stringify({
315
- userConfirmed: false,
316
- metadata: { feedback: "wrong_detection" },
317
- }),
318
- });
319
- } catch (e) {
320
- visionWarn("report wrong failed", e);
321
- }
322
- }
323
- resetFlow();
324
- }, [session, client, resetFlow]);
325
-
326
- return (
327
- <View
328
- style={[
329
- cardStyle(theme),
330
- styles.card,
331
- { minHeight: cardMinHeight },
332
- ]}
333
- >
334
- <Text style={[styles.cardTitle, { color: t.colors.onSurface }]}>
335
- {displayTitle}
336
- </Text>
337
- <Text style={[styles.cardDescription, { color: t.colors.muted }]}>
338
- {displayDescription}
339
- </Text>
340
- {errorMessage && !modalVisible ? (
341
- <Text style={[styles.errorInline, { color: t.colors.error }]}>
342
- {errorMessage}
343
- </Text>
344
- ) : null}
345
- <Button onPress={openScan}>Scanner un déchet</Button>
346
-
347
- <Modal
348
- visible={modalVisible}
349
- animationType="fade"
350
- presentationStyle={Platform.OS === "ios" ? "fullScreen" : undefined}
351
- statusBarTranslucent
352
- onRequestClose={closeModal}
353
- >
354
- <View style={[styles.modalRoot, { backgroundColor: t.colors.background }]}>
355
- <View style={styles.modalHeader}>
356
- <Text style={[styles.modalTitle, { color: t.colors.onSurface }]}>
357
- {displayTitle}
358
- </Text>
359
- <Button variant="ghost" onPress={closeModal}>
360
- Fermer
361
- </Button>
362
- </View>
363
-
364
- <View style={styles.modalBody}>
365
- {phase === "capture" ? (
366
- <VisionCapture
367
- tips={TIPS}
368
- onCapture={() => void handleCapture()}
369
- busy={busy}
370
- />
371
- ) : null}
372
-
373
- {phase === "tap" && imageUri ? (
374
- <VisionTapOverlay
375
- imageUri={imageUri}
376
- tap={tap}
377
- onTap={setTap}
378
- onAnalyzeFull={() => void runDetectAndFinalize(null)}
379
- onConfirmTap={() => void runDetectAndFinalize(tap)}
380
- onRetake={resetFlow}
381
- busy={busy}
382
- />
383
- ) : null}
384
-
385
- {phase === "loading" ? (
386
- <View style={styles.center}>
387
- <ActivityIndicator size="large" color={t.colors.primary} />
388
- <Text style={{ color: t.colors.muted, marginTop: 12 }}>
389
- Analyse en cours…
390
- </Text>
391
- </View>
392
- ) : null}
393
-
394
- {phase === "card" ? (
395
- <VisionActionCard
396
- suggestions={suggestions}
397
- primaryLabel={primaryLabel}
398
- confidence={confidence}
399
- requireConfirm={requireConfirm}
400
- onConfirm={() => void handleConfirm()}
401
- onRetake={resetFlow}
402
- onWrong={() => void handleWrong()}
403
- busy={busy}
404
- />
405
- ) : null}
406
-
407
- {phase === "error" ? (
408
- <View style={styles.center}>
409
- <Text style={{ color: t.colors.error, fontWeight: "700" }}>
410
- Impossible d’analyser
411
- </Text>
412
- <Text style={{ color: t.colors.muted, marginTop: 8 }}>
413
- {errorMessage}
414
- </Text>
415
- <Button onPress={resetFlow} style={styles.retry}>
416
- Réessayer
417
- </Button>
418
- </View>
419
- ) : null}
420
- </View>
421
- </View>
422
- </Modal>
423
- </View>
424
- );
425
- }
426
-
427
- const styles = StyleSheet.create({
428
- card: {
429
- padding: SPACE.cardPad,
430
- gap: 10,
431
- },
432
- cardTitle: { fontSize: 18, fontWeight: "700" },
433
- cardDescription: { fontSize: 14, lineHeight: 20 },
434
- errorInline: { fontSize: 13 },
435
- modalRoot: { flex: 1, paddingTop: Platform.OS === "ios" ? 56 : 24 },
436
- modalHeader: {
437
- flexDirection: "row",
438
- justifyContent: "space-between",
439
- alignItems: "center",
440
- paddingHorizontal: SPACE.pageX,
441
- marginBottom: 8,
442
- },
443
- modalTitle: { fontSize: 18, fontWeight: "700", flex: 1 },
444
- modalBody: { flex: 1, padding: SPACE.pageX },
445
- center: { flex: 1, alignItems: "center", justifyContent: "center", gap: 8 },
446
- retry: { marginTop: 16, alignSelf: "center", minWidth: 140 },
447
- });
1
+ /**
2
+ * Bloc CMS Vision — parcours Lens : photo → tap → carte post-scan (ADR-003 / Phase 6).
3
+ * WebRTC /offer n’est pas utilisé (MVP).
4
+ */
5
+ import { useCallback, useState } from "react";
6
+ import {
7
+ ActivityIndicator,
8
+ Modal,
9
+ Platform,
10
+ StyleSheet,
11
+ Text,
12
+ View,
13
+ } from "react-native";
14
+ import { useTheme } from "../../contexts/ThemeContext";
15
+ import { useLocal } from "../../contexts/LocalContext";
16
+ import { useWastoClient } from "../../hooks/useWastoClient";
17
+ import { Button } from "../button/Button";
18
+ import { cardStyle, resolveTheme } from "../../helpers/themeStyles";
19
+ import { SPACE } from "../../helpers/layout";
20
+ import { VisionCapture } from "./VisionCapture";
21
+ import { VisionTapOverlay } from "./VisionTapOverlay";
22
+ import { VisionActionCard, type VisionSuggestion } from "./VisionActionCard";
23
+
24
+ const DEFAULT_TITLE = "Wast’O Scan";
25
+ const DEFAULT_DESCRIPTION =
26
+ "Photographiez un déchet, touchez-le sur la photo, puis suivez la consigne locale.";
27
+ const TIPS =
28
+ "Astuce : bonne lumière, objet centré, un déchet à la fois si possible.";
29
+
30
+ const MIN_CARD_HEIGHT = 120;
31
+ const MAX_CARD_HEIGHT = 800;
32
+ const DEFAULT_CARD_HEIGHT = 280;
33
+
34
+ const VISION_SESSION_START_PATH = "/public/vision/sessions/start";
35
+
36
+ const LOG_TAG = "[Vision]";
37
+
38
+ function visionDebug(...args: unknown[]) {
39
+ if (__DEV__) console.log(LOG_TAG, ...args);
40
+ }
41
+
42
+ function visionWarn(message: string, detail?: unknown) {
43
+ if (detail !== undefined) console.warn(LOG_TAG, message, detail);
44
+ else console.warn(LOG_TAG, message);
45
+ }
46
+
47
+ export type VisionCaptureResult = {
48
+ uri: string;
49
+ };
50
+
51
+ export type VisionProps = {
52
+ /** URL POST /detect (sinon fournie par startSession). */
53
+ detectUrl?: string;
54
+ /** @deprecated conservé pour compat CMS ; non utilisé en parcours Lens. */
55
+ offerUrl?: string;
56
+ title?: string;
57
+ description?: string;
58
+ height?: number;
59
+ /** Override ville ; sinon LocalContext.selectedCityId. */
60
+ cityId?: string;
61
+ /**
62
+ * Capture custom (sinon expo-image-picker si installé dans l’app hôte).
63
+ */
64
+ onRequestCapture?: () => Promise<VisionCaptureResult | null>;
65
+ };
66
+
67
+ type Phase = "idle" | "capture" | "tap" | "loading" | "card" | "error";
68
+
69
+ type SessionUrls = {
70
+ sessionId: string;
71
+ detectUrl: string;
72
+ };
73
+
74
+ function clampHeight(h: number | undefined): number {
75
+ if (typeof h !== "number" || !Number.isFinite(h)) return DEFAULT_CARD_HEIGHT;
76
+ return Math.max(MIN_CARD_HEIGHT, Math.min(MAX_CARD_HEIGHT, h));
77
+ }
78
+
79
+ async function defaultCapturePhoto(): Promise<VisionCaptureResult | null> {
80
+ try {
81
+ // Peer optional — app hôte doit installer expo-image-picker
82
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
83
+ const ImagePicker = require("expo-image-picker") as {
84
+ requestCameraPermissionsAsync: () => Promise<{ status: string }>;
85
+ launchCameraAsync: (opts: Record<string, unknown>) => Promise<{
86
+ canceled: boolean;
87
+ assets?: Array<{ uri: string }>;
88
+ }>;
89
+ };
90
+ const perm = await ImagePicker.requestCameraPermissionsAsync();
91
+ if (perm.status !== "granted") {
92
+ throw new Error("Permission caméra refusée.");
93
+ }
94
+ const result = await ImagePicker.launchCameraAsync({
95
+ quality: 0.85,
96
+ exif: false,
97
+ });
98
+ if (result.canceled || !result.assets?.[0]?.uri) return null;
99
+ return { uri: result.assets[0].uri };
100
+ } catch (e) {
101
+ visionWarn("expo-image-picker indisponible", e);
102
+ throw new Error(
103
+ "Installez expo-image-picker dans l’app, ou fournissez onRequestCapture.",
104
+ );
105
+ }
106
+ }
107
+
108
+ export function Vision({
109
+ detectUrl: detectUrlProp = "",
110
+ title,
111
+ description,
112
+ height: heightProp,
113
+ cityId: cityIdProp,
114
+ onRequestCapture,
115
+ }: VisionProps) {
116
+ const { theme } = useTheme();
117
+ const t = resolveTheme(theme);
118
+ const { selectedCityId } = useLocal();
119
+ const client = useWastoClient();
120
+ const cityId = cityIdProp?.trim() || selectedCityId || undefined;
121
+
122
+ const [modalVisible, setModalVisible] = useState(false);
123
+ const [phase, setPhase] = useState<Phase>("idle");
124
+ const [errorMessage, setErrorMessage] = useState<string | null>(null);
125
+ const [imageUri, setImageUri] = useState<string | null>(null);
126
+ const [tap, setTap] = useState<{ x: number; y: number } | null>(null);
127
+ const [session, setSession] = useState<SessionUrls | null>(null);
128
+ const [suggestions, setSuggestions] = useState<VisionSuggestion[]>([]);
129
+ const [primaryLabel, setPrimaryLabel] = useState<string | null>(null);
130
+ const [confidence, setConfidence] = useState<number | null>(null);
131
+ const [requireConfirm, setRequireConfirm] = useState(true);
132
+ const [busy, setBusy] = useState(false);
133
+
134
+ const cardMinHeight = clampHeight(heightProp);
135
+ const displayTitle = (title && title.trim()) || DEFAULT_TITLE;
136
+ const displayDescription =
137
+ (description && description.trim()) || DEFAULT_DESCRIPTION;
138
+
139
+ const resetFlow = useCallback(() => {
140
+ setPhase("capture");
141
+ setErrorMessage(null);
142
+ setImageUri(null);
143
+ setTap(null);
144
+ setSuggestions([]);
145
+ setPrimaryLabel(null);
146
+ setConfidence(null);
147
+ setBusy(false);
148
+ }, []);
149
+
150
+ const ensureSession = useCallback(async (): Promise<SessionUrls> => {
151
+ if (session?.detectUrl && session.sessionId) return session;
152
+
153
+ const propDetect = detectUrlProp.trim();
154
+ const res = (await client.request(VISION_SESSION_START_PATH, {
155
+ method: "POST",
156
+ body: JSON.stringify({
157
+ cityId: cityId || undefined,
158
+ }),
159
+ })) as {
160
+ sessionId: string;
161
+ detectUrl?: string;
162
+ offerUrl?: string;
163
+ };
164
+
165
+ const detect =
166
+ propDetect ||
167
+ res.detectUrl?.trim() ||
168
+ (res.offerUrl ? res.offerUrl.replace(/\/offer\/?$/, "/detect") : "");
169
+
170
+ if (!res.sessionId || !detect) {
171
+ throw new Error(
172
+ "Session vision incomplète (sessionId / detectUrl). Vérifiez WASTO_VISION_URL.",
173
+ );
174
+ }
175
+
176
+ const next = { sessionId: res.sessionId, detectUrl: detect };
177
+ setSession(next);
178
+ return next;
179
+ }, [session, detectUrlProp, client, cityId]);
180
+
181
+ const openScan = useCallback(() => {
182
+ setModalVisible(true);
183
+ resetFlow();
184
+ }, [resetFlow]);
185
+
186
+ const closeModal = useCallback(() => {
187
+ setModalVisible(false);
188
+ setPhase("idle");
189
+ setBusy(false);
190
+ }, []);
191
+
192
+ const handleCapture = useCallback(async () => {
193
+ setBusy(true);
194
+ setErrorMessage(null);
195
+ try {
196
+ const capture = onRequestCapture
197
+ ? await onRequestCapture()
198
+ : await defaultCapturePhoto();
199
+ if (!capture?.uri) {
200
+ setBusy(false);
201
+ return;
202
+ }
203
+ setImageUri(capture.uri);
204
+ setTap(null);
205
+ setPhase("tap");
206
+ } catch (e: unknown) {
207
+ const msg = e instanceof Error ? e.message : String(e);
208
+ setErrorMessage(msg);
209
+ setPhase("error");
210
+ } finally {
211
+ setBusy(false);
212
+ }
213
+ }, [onRequestCapture]);
214
+
215
+ const runDetectAndFinalize = useCallback(
216
+ async (tapCoords: { x: number; y: number } | null) => {
217
+ if (!imageUri) return;
218
+ setBusy(true);
219
+ setPhase("loading");
220
+ setErrorMessage(null);
221
+ try {
222
+ const sess = await ensureSession();
223
+
224
+ const form = new FormData();
225
+ form.append("image", {
226
+ uri: imageUri,
227
+ name: "scan.jpg",
228
+ type: "image/jpeg",
229
+ } as unknown as Blob);
230
+ if (tapCoords) {
231
+ form.append("tapX", String(tapCoords.x));
232
+ form.append("tapY", String(tapCoords.y));
233
+ }
234
+
235
+ visionDebug("POST detect", { detectUrl: sess.detectUrl, tap: tapCoords });
236
+ const detectRes = await fetch(sess.detectUrl, {
237
+ method: "POST",
238
+ body: form,
239
+ });
240
+ const detectText = await detectRes.text();
241
+ if (!detectRes.ok) {
242
+ throw new Error(detectText || `Detect HTTP ${detectRes.status}`);
243
+ }
244
+ const detectJson = JSON.parse(detectText) as {
245
+ detections?: Array<{
246
+ label: string;
247
+ confidence: number;
248
+ bbox?: number[];
249
+ tap?: { x: number; y: number };
250
+ ts?: number;
251
+ }>;
252
+ };
253
+
254
+ const finalizePath = `/public/vision/sessions/${sess.sessionId}/finalize`;
255
+ const finalized = (await client.request(finalizePath, {
256
+ method: "POST",
257
+ body: JSON.stringify({
258
+ detections: detectJson.detections ?? [],
259
+ cityId: cityId || undefined,
260
+ tap: tapCoords ?? undefined,
261
+ }),
262
+ })) as {
263
+ suggestions?: VisionSuggestion[];
264
+ primaryLabel?: string | null;
265
+ confidence?: number | null;
266
+ requireUserConfirm?: boolean;
267
+ };
268
+
269
+ setSuggestions(finalized.suggestions ?? []);
270
+ setPrimaryLabel(finalized.primaryLabel ?? null);
271
+ setConfidence(finalized.confidence ?? null);
272
+ setRequireConfirm(finalized.requireUserConfirm !== false);
273
+ setPhase("card");
274
+ } catch (e: unknown) {
275
+ const msg = e instanceof Error ? e.message : String(e);
276
+ visionWarn("detect/finalize failed", e);
277
+ setErrorMessage(msg);
278
+ setPhase("error");
279
+ } finally {
280
+ setBusy(false);
281
+ }
282
+ },
283
+ [imageUri, ensureSession, client, cityId],
284
+ );
285
+
286
+ const handleConfirm = useCallback(async () => {
287
+ if (!session?.sessionId) return;
288
+ setBusy(true);
289
+ try {
290
+ await client.request(`/public/vision/sessions/${session.sessionId}/report`, {
291
+ method: "POST",
292
+ body: JSON.stringify({
293
+ userConfirmed: true,
294
+ label: primaryLabel ?? undefined,
295
+ confidence: confidence ?? undefined,
296
+ actionKind: suggestions.find((s) => s.kind === "SORT_BIN")?.kind,
297
+ }),
298
+ });
299
+ closeModal();
300
+ } catch (e: unknown) {
301
+ const msg = e instanceof Error ? e.message : String(e);
302
+ setErrorMessage(msg);
303
+ setPhase("error");
304
+ } finally {
305
+ setBusy(false);
306
+ }
307
+ }, [session, client, primaryLabel, confidence, suggestions, closeModal]);
308
+
309
+ const handleWrong = useCallback(async () => {
310
+ if (session?.sessionId) {
311
+ try {
312
+ await client.request(`/public/vision/sessions/${session.sessionId}/report`, {
313
+ method: "POST",
314
+ body: JSON.stringify({
315
+ userConfirmed: false,
316
+ metadata: { feedback: "wrong_detection" },
317
+ }),
318
+ });
319
+ } catch (e) {
320
+ visionWarn("report wrong failed", e);
321
+ }
322
+ }
323
+ resetFlow();
324
+ }, [session, client, resetFlow]);
325
+
326
+ return (
327
+ <View
328
+ style={[
329
+ cardStyle(theme),
330
+ styles.card,
331
+ { minHeight: cardMinHeight },
332
+ ]}
333
+ >
334
+ <Text style={[styles.cardTitle, { color: t.colors.onSurface }]}>
335
+ {displayTitle}
336
+ </Text>
337
+ <Text style={[styles.cardDescription, { color: t.colors.muted }]}>
338
+ {displayDescription}
339
+ </Text>
340
+ {errorMessage && !modalVisible ? (
341
+ <Text style={[styles.errorInline, { color: t.colors.error }]}>
342
+ {errorMessage}
343
+ </Text>
344
+ ) : null}
345
+ <Button onPress={openScan}>Scanner un déchet</Button>
346
+
347
+ <Modal
348
+ visible={modalVisible}
349
+ animationType="fade"
350
+ presentationStyle={Platform.OS === "ios" ? "fullScreen" : undefined}
351
+ statusBarTranslucent
352
+ onRequestClose={closeModal}
353
+ >
354
+ <View style={[styles.modalRoot, { backgroundColor: t.colors.background }]}>
355
+ <View style={styles.modalHeader}>
356
+ <Text style={[styles.modalTitle, { color: t.colors.onSurface }]}>
357
+ {displayTitle}
358
+ </Text>
359
+ <Button variant="ghost" onPress={closeModal}>
360
+ Fermer
361
+ </Button>
362
+ </View>
363
+
364
+ <View style={styles.modalBody}>
365
+ {phase === "capture" ? (
366
+ <VisionCapture
367
+ tips={TIPS}
368
+ onCapture={() => void handleCapture()}
369
+ busy={busy}
370
+ />
371
+ ) : null}
372
+
373
+ {phase === "tap" && imageUri ? (
374
+ <VisionTapOverlay
375
+ imageUri={imageUri}
376
+ tap={tap}
377
+ onTap={setTap}
378
+ onAnalyzeFull={() => void runDetectAndFinalize(null)}
379
+ onConfirmTap={() => void runDetectAndFinalize(tap)}
380
+ onRetake={resetFlow}
381
+ busy={busy}
382
+ />
383
+ ) : null}
384
+
385
+ {phase === "loading" ? (
386
+ <View style={styles.center}>
387
+ <ActivityIndicator size="large" color={t.colors.primary} />
388
+ <Text style={{ color: t.colors.muted, marginTop: 12 }}>
389
+ Analyse en cours…
390
+ </Text>
391
+ </View>
392
+ ) : null}
393
+
394
+ {phase === "card" ? (
395
+ <VisionActionCard
396
+ suggestions={suggestions}
397
+ primaryLabel={primaryLabel}
398
+ confidence={confidence}
399
+ requireConfirm={requireConfirm}
400
+ onConfirm={() => void handleConfirm()}
401
+ onRetake={resetFlow}
402
+ onWrong={() => void handleWrong()}
403
+ busy={busy}
404
+ />
405
+ ) : null}
406
+
407
+ {phase === "error" ? (
408
+ <View style={styles.center}>
409
+ <Text style={{ color: t.colors.error, fontWeight: "700" }}>
410
+ Impossible d’analyser
411
+ </Text>
412
+ <Text style={{ color: t.colors.muted, marginTop: 8 }}>
413
+ {errorMessage}
414
+ </Text>
415
+ <Button onPress={resetFlow} style={styles.retry}>
416
+ Réessayer
417
+ </Button>
418
+ </View>
419
+ ) : null}
420
+ </View>
421
+ </View>
422
+ </Modal>
423
+ </View>
424
+ );
425
+ }
426
+
427
+ const styles = StyleSheet.create({
428
+ card: {
429
+ padding: SPACE.cardPad,
430
+ gap: 10,
431
+ },
432
+ cardTitle: { fontSize: 18, fontWeight: "700" },
433
+ cardDescription: { fontSize: 14, lineHeight: 20 },
434
+ errorInline: { fontSize: 13 },
435
+ modalRoot: { flex: 1, paddingTop: Platform.OS === "ios" ? 56 : 24 },
436
+ modalHeader: {
437
+ flexDirection: "row",
438
+ justifyContent: "space-between",
439
+ alignItems: "center",
440
+ paddingHorizontal: SPACE.pageX,
441
+ marginBottom: 8,
442
+ },
443
+ modalTitle: { fontSize: 18, fontWeight: "700", flex: 1 },
444
+ modalBody: { flex: 1, padding: SPACE.pageX },
445
+ center: { flex: 1, alignItems: "center", justifyContent: "center", gap: 8 },
446
+ retry: { marginTop: 16, alignSelf: "center", minWidth: 140 },
447
+ });