@zean-chat/react-native 0.1.14 → 0.1.16

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/dist/index.js CHANGED
@@ -28,7 +28,7 @@ __export(index_exports, {
28
28
  module.exports = __toCommonJS(index_exports);
29
29
 
30
30
  // src/components/ZeanChat.tsx
31
- var import_react17 = require("react");
31
+ var import_react18 = require("react");
32
32
 
33
33
  // ../shared/src/constants/app.ts
34
34
  var APP_NAME = "Zean";
@@ -40,6 +40,8 @@ var SUPPORTED_LOCALES = ["fr", "en"];
40
40
  var DEFAULT_LOCALE = "fr";
41
41
 
42
42
  // ../shared/src/constants/conversations.ts
43
+ var CONVERSATION_STATUSES = ["open", "resolved"];
44
+ var INBOX_TABS = [...CONVERSATION_STATUSES, "spam"];
43
45
  var INBOX_FILTERS = ["all", "mine", "unassigned"];
44
46
  var INBOX_VIEWS = [...INBOX_FILTERS, "unread"];
45
47
  var CONTACT_ID_MAX_LENGTH = 200;
@@ -67,9 +69,16 @@ var RESERVED_CONTACT_ATTRIBUTES = [
67
69
  ];
68
70
  var MISSED_REPLY_DELAY_MS = 60 * 6e4;
69
71
  var MAX_MESSAGE_LENGTH = 5e3;
72
+ var EDIT_WINDOW_MS = 30 * 6e4;
73
+ var DELETE_WINDOW_MS = 60 * 6e4;
74
+ var DRAFT_TTL_MS = 30 * 24 * 60 * 6e4;
70
75
  var TEST_DEVICE_MAX_AGE_MS = 24 * 60 * 60 * 1e3;
76
+ var QUOTE_HIGHLIGHT_MS = 1600;
71
77
 
72
78
  // ../shared/src/constants/widget.ts
79
+ var APP_PLATFORMS = ["web", "react_native"];
80
+ var DEVICE_TYPES = ["phone", "tablet", "computer"];
81
+ var DEVICE_DETAIL_MAX_LENGTH = 80;
73
82
  var EXPO_GO_BUNDLE_ID = "host.exp.exponent";
74
83
  var DEFAULT_WIDGET_TEXTS = {
75
84
  fr: {
@@ -138,23 +147,23 @@ function cleanContactUser(value) {
138
147
  if (typeof id !== "string" || !id.trim() || id.trim().length > CONTACT_ID_MAX_LENGTH) return { user: null, dropped: [] };
139
148
  const user = { id: id.trim() };
140
149
  const dropped = [];
141
- const text = (key) => {
150
+ const text2 = (key) => {
142
151
  const raw = input[key];
143
152
  if (raw === void 0 || raw === null) return null;
144
153
  const cleaned = typeof raw === "string" ? squashSpaces(raw) : "";
145
154
  if (!cleaned) dropped.push(key);
146
155
  return cleaned || null;
147
156
  };
148
- const name = text("name");
157
+ const name = text2("name");
149
158
  if (name !== null && name.length <= CONTACT_NAME_MAX_LENGTH) user.name = name;
150
159
  else if (name !== null) dropped.push("name");
151
- const email = text("email");
160
+ const email = text2("email");
152
161
  if (email !== null && isEmail(normaliseEmail(email))) user.email = normaliseEmail(email);
153
162
  else if (email !== null) dropped.push("email");
154
- const phone = text("phone");
163
+ const phone = text2("phone");
155
164
  if (phone !== null && phone.length <= CONTACT_PHONE_MAX_LENGTH && PHONE_PATTERN.test(phone)) user.phone = phone;
156
165
  else if (phone !== null) dropped.push("phone");
157
- const language = text("language");
166
+ const language = text2("language");
158
167
  if (language !== null && LANGUAGE_TAG_PATTERN.test(language)) user.language = languageTag(language);
159
168
  else if (language !== null) dropped.push("language");
160
169
  return { user, dropped };
@@ -184,8 +193,8 @@ function isWithinBusinessHours(hours, at) {
184
193
  const { weekday, minutes } = clockIn(hours.timeZone, at);
185
194
  return hours.days.some((day) => day.weekday === weekday && minutesOf(day.opens) <= minutes && minutes < minutesOf(day.closes));
186
195
  }
187
- function pickText(text, locale, defaultLocale, fallback) {
188
- return text?.[locale]?.trim() || text?.[defaultLocale]?.trim() || fallback[locale];
196
+ function pickText(text2, locale, defaultLocale, fallback) {
197
+ return text2?.[locale]?.trim() || text2?.[defaultLocale]?.trim() || fallback[locale];
189
198
  }
190
199
  function clockIn(timeZone, at) {
191
200
  let parts;
@@ -221,6 +230,7 @@ var KEPT_MESSAGES = 100;
221
230
  var KEPT_VERSION = 1;
222
231
  var LIVE_AFTER_CLOSE_MS = 2 * 6e4;
223
232
  var ADVANCE_AFTER = WIDGET_PAGE_SIZE / 2;
233
+ var QUIET_CALLS = /* @__PURE__ */ new Set(["start", "reportInstall", "setTyping", "setPushToken", "markRead", "signOut"]);
224
234
  function emailKey(offer) {
225
235
  return `${offer.kind}:${offer.email}`;
226
236
  }
@@ -229,6 +239,7 @@ function createChatStore(backend, options) {
229
239
  const outboxKey = `zean:${options.appKey}:outbox`;
230
240
  const attributesKey = `zean:${options.appKey}:attributes`;
231
241
  const keptKey = `zean:${options.appKey}:conversation`;
242
+ const draftKey = `zean:${options.appKey}:draft`;
232
243
  const keep = options.keep === true;
233
244
  const listeners2 = /* @__PURE__ */ new Set();
234
245
  const stops = [];
@@ -245,6 +256,7 @@ function createChatStore(backend, options) {
245
256
  let keptHasOlder = false;
246
257
  let keptHistory = null;
247
258
  let askedAfter;
259
+ let syncedAt;
248
260
  let windowed = false;
249
261
  let open2 = false;
250
262
  let liveTimer = null;
@@ -253,9 +265,12 @@ function createChatStore(backend, options) {
253
265
  let lastTypingSignal = 0;
254
266
  let connected = false;
255
267
  let outbox = [];
268
+ let draft2 = null;
269
+ let people = 0;
256
270
  let heldAttributes = {};
257
271
  let started = false;
258
272
  let reported = false;
273
+ let shared = null;
259
274
  let user = null;
260
275
  let idCode = null;
261
276
  let idCodeDismissed = false;
@@ -269,7 +284,7 @@ function createChatStore(backend, options) {
269
284
  let identifying = null;
270
285
  let identified = false;
271
286
  let identifiedKnown = false;
272
- let watchers = [];
287
+ let sessionWatch = null;
273
288
  let pushToken2;
274
289
  let pushSent = null;
275
290
  let destroyed = false;
@@ -292,8 +307,7 @@ function createChatStore(backend, options) {
292
307
  const device = () => ({
293
308
  locale: state.locale,
294
309
  ...deviceLanguage ? { language: deviceLanguage } : {},
295
- browser: options.browser,
296
- os: options.os,
310
+ ...options.deviceDetails ? { details: options.deviceDetails() } : {},
297
311
  timeZone
298
312
  });
299
313
  const deviceWaiters = [];
@@ -309,6 +323,7 @@ function createChatStore(backend, options) {
309
323
  useSecret(secret);
310
324
  outbox = await loadOutbox();
311
325
  heldAttributes = { ...await loadAttributes(), ...heldAttributes };
326
+ draft2 = await loadDraft();
312
327
  if (keep) await loadKept();
313
328
  if (destroyed) return;
314
329
  emit2();
@@ -323,14 +338,56 @@ function createChatStore(backend, options) {
323
338
  stops.push(() => clearInterval(clock));
324
339
  })();
325
340
  function watchAll() {
326
- watchers = [
327
- backend.watch("session", args(), handleSession, () => {
341
+ watchSession();
342
+ if (!keep || open2) watchLive();
343
+ }
344
+ function sessionLive() {
345
+ return !keep || open2 || session !== null && historyOf(session) !== null;
346
+ }
347
+ function watchSession() {
348
+ sessionWatch?.stop();
349
+ const live = sessionLive();
350
+ let stopped = false;
351
+ let stop = null;
352
+ const entry = {
353
+ live,
354
+ // Once: the Convex client throws on a second unsubscribe.
355
+ stop: () => {
356
+ if (stopped) return;
357
+ stopped = true;
358
+ stop?.();
359
+ }
360
+ };
361
+ sessionWatch = entry;
362
+ stop = backend.watch(
363
+ "session",
364
+ args(),
365
+ (result) => {
366
+ handleSession(result);
367
+ if (!live && sessionWatch === entry) entry.stop();
368
+ },
369
+ () => {
328
370
  failedToLoad = true;
329
371
  emit2();
330
- })
331
- ];
332
- if (!keep || open2) watchLive();
372
+ }
373
+ );
374
+ if (stopped) stop();
375
+ }
376
+ function updateSessionLive() {
377
+ if (!sessionWatch || sessionWatch.live === sessionLive()) return;
378
+ if (sessionLive()) watchSession();
379
+ else {
380
+ sessionWatch.stop();
381
+ sessionWatch = { live: false, stop: () => {
382
+ } };
383
+ }
333
384
  }
385
+ function rereadSession() {
386
+ if (sessionWatch && !sessionWatch.live && deviceSecret && !destroyed) watchSession();
387
+ }
388
+ const call = (name, input) => backend.call(name, input).finally(() => {
389
+ if (!QUIET_CALLS.has(name)) rereadSession();
390
+ });
334
391
  function watchLive() {
335
392
  watchMessages();
336
393
  stopTyping?.();
@@ -366,8 +423,7 @@ function createChatStore(backend, options) {
366
423
  function serverMessages() {
367
424
  if (kept.length === 0) return page.messages;
368
425
  if (page.messages.length === 0) return kept;
369
- const keptIds = new Set(kept.map((message) => message.id));
370
- return [...kept, ...page.messages.filter((message) => !keptIds.has(message.id))];
426
+ return [...kept, ...page.messages];
371
427
  }
372
428
  function serverHasOlder() {
373
429
  return kept.length > 0 ? keptHasOlder : page.hasOlder;
@@ -381,7 +437,7 @@ function createChatStore(backend, options) {
381
437
  if (mine !== generation || destroyed || !deviceSecret) return;
382
438
  identifiedKnown = state.known;
383
439
  try {
384
- const result = await backend.call("identify", { ...args(), user: person, device: device() });
440
+ const result = await call("identify", { ...args(), user: person, device: device() });
385
441
  if (mine !== generation) return;
386
442
  idCode = result.state === "code_available" ? { email: result.email, sent: idCode?.sent ?? false } : null;
387
443
  identified = true;
@@ -405,15 +461,17 @@ function createChatStore(backend, options) {
405
461
  session = result;
406
462
  failedToLoad = false;
407
463
  if (keep) checkKept(result);
464
+ checkDraft(result);
408
465
  emit2();
409
466
  if ("report" in result && result.report && !reported) {
410
467
  reported = true;
411
- backend.call("reportInstall", args()).catch(() => {
468
+ call("reportInstall", args()).catch(() => {
412
469
  });
413
470
  }
414
471
  startOnce();
415
472
  if (state.known && !state.verified && !identifiedKnown && user && !identifying) void sendIdentity();
416
473
  if (state.known && Object.keys(heldAttributes).length > 0) void sendAttributes();
474
+ updateSessionLive();
417
475
  }
418
476
  async function sendAttributes() {
419
477
  if (identifying) await identifying;
@@ -422,7 +480,7 @@ function createChatStore(backend, options) {
422
480
  heldAttributes = {};
423
481
  saveAttributes();
424
482
  try {
425
- await backend.call("setAttributes", { ...args(), attributes: attributes2 });
483
+ await call("setAttributes", { ...args(), attributes: attributes2 });
426
484
  return { ok: true };
427
485
  } catch (error) {
428
486
  if (codeOf(error) === "invalid_attributes")
@@ -435,7 +493,7 @@ function createChatStore(backend, options) {
435
493
  if (pushSent?.deviceSecret === deviceSecret && pushSent.token === pushToken2) return;
436
494
  const sent = { deviceSecret, token: pushToken2 };
437
495
  pushSent = sent;
438
- backend.call("setPushToken", { ...args(), token: pushToken2 }).catch((error) => {
496
+ call("setPushToken", { ...args(), token: pushToken2 }).catch((error) => {
439
497
  if (pushSent === sent) pushSent = null;
440
498
  if (codeOf(error) === "invalid_push_token") console.warn(`${APP_NAME}: the push token was refused: it is too long.`);
441
499
  });
@@ -443,7 +501,7 @@ function createChatStore(backend, options) {
443
501
  function startOnce() {
444
502
  if (started || state.status === "loading" || state.status === "hidden") return;
445
503
  started = true;
446
- if (state.known || devLoad) backend.call("start", { ...args(), device: device() }).catch(() => {
504
+ if (state.known || devLoad) call("start", { ...args(), device: device() }).catch(() => {
447
505
  });
448
506
  for (const entry of outbox) if (entry.error === null) deliver(entry);
449
507
  }
@@ -455,7 +513,7 @@ function createChatStore(backend, options) {
455
513
  }
456
514
  function watchMessages() {
457
515
  stopMessages?.();
458
- const after = !windowed && kept.length > 0 ? kept.at(-1).createdAt : void 0;
516
+ const after = !windowed && kept.length > 0 ? rereadFrom(kept.at(-1).createdAt, syncedAt) : void 0;
459
517
  askedAfter = after;
460
518
  stopMessages = backend.watch(
461
519
  "messages",
@@ -465,8 +523,10 @@ function createChatStore(backend, options) {
465
523
  if (after === void 0 || windowed) {
466
524
  kept = [];
467
525
  keptHasOlder = false;
468
- }
526
+ } else kept = kept.filter((message) => message.createdAt <= after);
469
527
  page = result;
528
+ const now = Date.now();
529
+ syncedAt = now;
470
530
  pageLoaded = true;
471
531
  loadingOlder = false;
472
532
  const stored = new Set(result.messages.map((message) => message.clientId));
@@ -474,7 +534,8 @@ function createChatStore(backend, options) {
474
534
  outbox = outbox.filter((entry) => !stored.has(entry.clientId));
475
535
  saveOutbox();
476
536
  }
477
- if (after !== void 0 && !windowed && result.messages.length >= ADVANCE_AFTER) {
537
+ const settled = result.messages.filter((message) => message.createdAt <= now - DELETE_WINDOW_MS);
538
+ if (after !== void 0 && !windowed && settled.length >= ADVANCE_AFTER) {
478
539
  kept = serverMessages();
479
540
  page = { messages: [], hasOlder: false, seen: result.seen };
480
541
  watchMessages();
@@ -492,7 +553,7 @@ function createChatStore(backend, options) {
492
553
  );
493
554
  }
494
555
  function deliver(entry) {
495
- backend.call("send", {
556
+ call("send", {
496
557
  ...args(),
497
558
  body: entry.body,
498
559
  ...entry.attachments ? { attachments: entry.attachments } : {},
@@ -546,22 +607,24 @@ function createChatStore(backend, options) {
546
607
  const verified = session !== null && "identity" in session && session.identity === "verified";
547
608
  const shown = serverMessages();
548
609
  const hasOlder = serverHasOlder();
549
- const stored = new Set(shown.map((message) => message.clientId));
550
- const pending = outbox.filter((entry) => !stored.has(entry.clientId)).map(fromOutbox);
610
+ const previous = shared;
611
+ const messages = previous && previous.kept === kept && previous.pageMessages === page.messages && previous.outbox === outbox ? previous.messages : derivedMessages(shown);
612
+ const appState = previous && previous.sessionApp === app ? previous.app : app ? {
613
+ name: app.name,
614
+ color: app.color,
615
+ logoUrl: app.logoUrl,
616
+ launcher: app.launcher,
617
+ showBadge: app.showBadge,
618
+ hiddenPages: app.hiddenPages
619
+ } : null;
620
+ shared = { sessionApp: app, app: appState, kept, pageMessages: page.messages, outbox, messages };
551
621
  return {
552
622
  status,
553
- app: app ? {
554
- name: app.name,
555
- color: app.color,
556
- logoUrl: app.logoUrl,
557
- launcher: app.launcher,
558
- showBadge: app.showBadge,
559
- hiddenPages: app.hiddenPages
560
- } : null,
623
+ app: appState,
561
624
  locale,
562
625
  texts: { header: textOf("header"), welcome: textOf("welcome"), away: textOf("away") },
563
626
  online: app ? app.teamOnline && isWithinBusinessHours(app.hours, /* @__PURE__ */ new Date()) : false,
564
- messages: [...shown.map(fromServer), ...pending],
627
+ messages,
565
628
  // Past the most the widget holds, older messages stay in the dashboard.
566
629
  hasOlder: hasOlder && Math.max(limit, shown.length) < WIDGET_MAX_MESSAGES,
567
630
  atStart: !hasOlder,
@@ -575,9 +638,16 @@ function createChatStore(backend, options) {
575
638
  emailGiven,
576
639
  verified,
577
640
  contactCode: codeOffer(verified),
578
- connected
641
+ connected,
642
+ personKey: people
579
643
  };
580
644
  }
645
+ function derivedMessages(shown) {
646
+ const stored = new Set(shown.map((message) => message.clientId));
647
+ const shownIds = new Map(shown.map((message) => [message.id, message.clientId ?? message.id]));
648
+ const pending = outbox.filter((entry) => !stored.has(entry.clientId)).map(fromOutbox);
649
+ return [...shown.map((message) => fromServer(message, shownIds)), ...pending];
650
+ }
581
651
  function codeOffer(verified) {
582
652
  if (idCode && !verified) return idCodeDismissed ? null : { kind: "id", ...idCode };
583
653
  const offer = session && "emailCode" in session ? session.emailCode : null;
@@ -585,7 +655,7 @@ function createChatStore(backend, options) {
585
655
  return { ...offer, sent: emailKey(offer) === emailCodeSent };
586
656
  }
587
657
  function checkKept(result) {
588
- const history = "contact" in result ? result.contact?.historyKey ?? null : null;
658
+ const history = historyOf(result);
589
659
  if (history !== keptHistory) {
590
660
  keptHistory = history;
591
661
  dropKept();
@@ -596,6 +666,12 @@ function createChatStore(backend, options) {
596
666
  stopLiveLater();
597
667
  } else saveKept();
598
668
  }
669
+ function checkDraft(result) {
670
+ if (!draft2) return;
671
+ const history = historyOf(result);
672
+ if (draft2.history === history) return;
673
+ writeDraft(draft2.history === null ? { ...draft2, history } : null);
674
+ }
599
675
  async function loadKept() {
600
676
  try {
601
677
  const saved = JSON.parse(await options.storage.getItem(keptKey) || "null");
@@ -604,6 +680,7 @@ function createChatStore(backend, options) {
604
680
  kept = saved.messages;
605
681
  keptHasOlder = saved.hasOlder;
606
682
  keptHistory = saved.session.contact?.historyKey ?? null;
683
+ syncedAt = saved.syncedAt;
607
684
  page = { messages: [], hasOlder: false, seen: saved.seen };
608
685
  pageLoaded = kept.length > 0 || !saved.session.contact?.historyKey;
609
686
  } catch {
@@ -619,7 +696,8 @@ function createChatStore(backend, options) {
619
696
  session: { ...current, report: false },
620
697
  messages: shown.slice(-KEPT_MESSAGES),
621
698
  hasOlder: shown.length > KEPT_MESSAGES || serverHasOlder(),
622
- seen: page.seen
699
+ seen: page.seen,
700
+ ...syncedAt === void 0 ? {} : { syncedAt }
623
701
  };
624
702
  quietly(() => options.storage.setItem(keptKey, JSON.stringify(value)));
625
703
  }
@@ -682,24 +760,53 @@ function createChatStore(backend, options) {
682
760
  function saveAttributes() {
683
761
  void options.storage.setItem(attributesKey, JSON.stringify(heldAttributes));
684
762
  }
763
+ async function loadDraft() {
764
+ try {
765
+ const saved = JSON.parse(await options.storage.getItem(draftKey) || "null");
766
+ if (typeof saved?.text !== "string" || !Array.isArray(saved.files) || typeof saved.updatedAt !== "number") return null;
767
+ return saved.updatedAt > Date.now() - DRAFT_TTL_MS ? saved : null;
768
+ } catch {
769
+ return null;
770
+ }
771
+ }
772
+ function forgetDraft() {
773
+ writeDraft(null);
774
+ people += 1;
775
+ }
776
+ function writeDraft(next) {
777
+ draft2 = next;
778
+ quietly(() => options.storage.setItem(draftKey, next ? JSON.stringify(next) : ""));
779
+ }
685
780
  return {
686
781
  getState: () => state,
782
+ draft: () => draft2 ? { text: draft2.text, files: draft2.files } : null,
783
+ saveDraft(given) {
784
+ const text2 = given.text;
785
+ const files = given.files.map((file) => file.uri && /^https?:/i.test(file.uri) ? { ...file, uri: null } : file);
786
+ if (!text2.trim() && files.length === 0) {
787
+ writeDraft(null);
788
+ return;
789
+ }
790
+ if (draft2 && JSON.stringify({ text: text2, files }) === JSON.stringify({ text: draft2.text, files: draft2.files })) return;
791
+ writeDraft({ text: text2, files, history: session ? historyOf(session) : null, updatedAt: Date.now() });
792
+ },
687
793
  subscribe(listener) {
688
794
  listeners2.add(listener);
689
795
  return () => listeners2.delete(listener);
690
796
  },
691
797
  send(body, attachments = []) {
692
- const text = body.trim();
693
- if (!text && attachments.length === 0 || !deviceSecret) return;
798
+ const text2 = body.trim();
799
+ if (!text2 && attachments.length === 0 || !deviceSecret) return;
694
800
  const entry = {
695
801
  clientId: newClientId(),
696
- body: text,
802
+ body: text2,
697
803
  ...attachments.length > 0 ? { attachments } : {},
698
804
  createdAt: Date.now(),
699
805
  error: null
700
806
  };
701
807
  outbox = [...outbox, entry];
702
808
  saveOutbox();
809
+ writeDraft(null);
703
810
  wroteHere = true;
704
811
  emit2();
705
812
  if (started) deliver(entry);
@@ -734,26 +841,27 @@ function createChatStore(backend, options) {
734
841
  if (open2 === value) return;
735
842
  open2 = value;
736
843
  if (!keep) return;
844
+ updateSessionLive();
737
845
  keepLive();
738
846
  if (!value) stopLiveLater();
739
847
  else if (!stopMessages && deviceSecret) watchLive();
740
848
  },
741
849
  markRead() {
742
850
  if (state.unread === 0 || !deviceSecret) return;
743
- backend.call("markRead", args()).catch(() => {
851
+ call("markRead", args()).catch(() => {
744
852
  });
745
853
  },
746
854
  typing() {
747
855
  const now = Date.now();
748
856
  if (state.status !== "ready" || !state.known || now - lastTypingSignal < TYPING_SIGNAL_MS) return;
749
857
  lastTypingSignal = now;
750
- backend.call("setTyping", args()).catch(() => {
858
+ call("setTyping", args()).catch(() => {
751
859
  });
752
860
  },
753
861
  async setEmail(email) {
754
862
  if (!deviceSecret) return { ok: false, code: "not_found" };
755
863
  try {
756
- await backend.call("setEmail", { ...args(), email });
864
+ await call("setEmail", { ...args(), email });
757
865
  emailGiven = true;
758
866
  emit2();
759
867
  return { ok: true };
@@ -788,6 +896,7 @@ function createChatStore(backend, options) {
788
896
  heldAttributes = {};
789
897
  saveAttributes();
790
898
  forgetKept();
899
+ forgetDraft();
791
900
  emit2();
792
901
  }
793
902
  if (user?.id !== person.id) {
@@ -806,10 +915,10 @@ function createChatStore(backend, options) {
806
915
  if (!deviceSecret || !offer || offer.kind === "id" && !person) return { ok: false, code: "not_found" };
807
916
  try {
808
917
  if (offer.kind !== "id") {
809
- await backend.call("requestEmailCode", args());
918
+ await call("requestEmailCode", args());
810
919
  emailCodeSent = emailKey(offer);
811
920
  } else {
812
- await backend.call("requestCode", { ...args(), userId: person.id });
921
+ await call("requestCode", { ...args(), userId: person.id });
813
922
  if (idCode && user === person) idCode = { ...idCode, sent: true };
814
923
  }
815
924
  emit2();
@@ -824,13 +933,13 @@ function createChatStore(backend, options) {
824
933
  if (!deviceSecret || !offer || offer.kind === "id" && !person) return { ok: false, code: "not_found" };
825
934
  try {
826
935
  if (offer.kind !== "id") {
827
- const result2 = await backend.call("confirmEmailCode", { ...args(), code: code2 });
936
+ const result2 = await call("confirmEmailCode", { ...args(), code: code2 });
828
937
  if (!result2.ok) return result2;
829
938
  emailCodeSent = null;
830
939
  emit2();
831
940
  return { ok: true };
832
941
  }
833
- const result = await backend.call("confirmCode", { ...args(), userId: person.id, code: code2 });
942
+ const result = await call("confirmCode", { ...args(), userId: person.id, code: code2 });
834
943
  if (!result.ok) return result;
835
944
  idCode = null;
836
945
  emit2();
@@ -846,7 +955,7 @@ function createChatStore(backend, options) {
846
955
  if (offer.kind === "id") idCodeDismissed = true;
847
956
  else {
848
957
  emailCodeDismissed = emailKey(offer);
849
- backend.call("dismissEmailCode", args()).catch(() => {
958
+ call("dismissEmailCode", args()).catch(() => {
850
959
  });
851
960
  }
852
961
  emit2();
@@ -865,12 +974,13 @@ function createChatStore(backend, options) {
865
974
  emailGiven = false;
866
975
  identifying = null;
867
976
  identifiedKnown = false;
868
- if (deviceSecret) backend.call("signOut", args()).catch(() => {
977
+ if (deviceSecret) call("signOut", args()).catch(() => {
869
978
  });
870
- for (const stop of watchers) stop();
871
- watchers = [];
979
+ sessionWatch?.stop();
980
+ sessionWatch = null;
872
981
  stopLive();
873
982
  forgetKept();
983
+ forgetDraft();
874
984
  keepLive();
875
985
  deviceSecret = null;
876
986
  outbox = [];
@@ -898,7 +1008,7 @@ function createChatStore(backend, options) {
898
1008
  await starting;
899
1009
  await deviceKnown();
900
1010
  if (destroyed || !deviceSecret) return;
901
- await backend.call("joinWithPass", { ...args(), pass }).catch(() => {
1011
+ await call("joinWithPass", { ...args(), pass }).catch(() => {
902
1012
  });
903
1013
  },
904
1014
  destroy() {
@@ -906,7 +1016,7 @@ function createChatStore(backend, options) {
906
1016
  for (const resolve of deviceWaiters.splice(0)) resolve();
907
1017
  stopMessages?.();
908
1018
  stopTyping?.();
909
- for (const stop of watchers) stop();
1019
+ sessionWatch?.stop();
910
1020
  for (const stop of stops) stop();
911
1021
  if (typingTimer) clearTimeout(typingTimer);
912
1022
  keepLive();
@@ -916,6 +1026,9 @@ function createChatStore(backend, options) {
916
1026
  }
917
1027
  };
918
1028
  }
1029
+ function rereadFrom(newest, syncedAt = newest) {
1030
+ return Math.min(newest, syncedAt - DELETE_WINDOW_MS);
1031
+ }
919
1032
  function localeOf(languages, fallback) {
920
1033
  for (const language of languages) {
921
1034
  const base = language.slice(0, 2).toLowerCase();
@@ -924,8 +1037,15 @@ function localeOf(languages, fallback) {
924
1037
  }
925
1038
  return fallback;
926
1039
  }
927
- function fromServer({ clientId, ...message }) {
928
- return { ...message, id: clientId ?? message.id, status: "sent", error: null };
1040
+ function fromServer({ clientId, replyTo, ...message }, shownIds) {
1041
+ return {
1042
+ ...message,
1043
+ id: clientId ?? message.id,
1044
+ status: "sent",
1045
+ error: null,
1046
+ // Kept on the device before quotes came: none.
1047
+ replyTo: replyTo ? { ...replyTo, id: shownIds.get(replyTo.id) ?? replyTo.id, loaded: shownIds.has(replyTo.id) } : null
1048
+ };
929
1049
  }
930
1050
  function fromOutbox(entry) {
931
1051
  return {
@@ -936,7 +1056,8 @@ function fromOutbox(entry) {
936
1056
  attachments: entry.attachments ?? [],
937
1057
  createdAt: entry.createdAt,
938
1058
  status: entry.error === null ? "sending" : "failed",
939
- error: entry.error
1059
+ error: entry.error,
1060
+ replyTo: null
940
1061
  };
941
1062
  }
942
1063
  function bundleWarning(bundle) {
@@ -945,6 +1066,9 @@ function bundleWarning(bundle) {
945
1066
  const field = bundle.os === "ios" ? "Bundle ID" : "Package name";
946
1067
  return `${APP_NAME}: ${bundle.id} is not the App's ${field}. Set it in the App settings.`;
947
1068
  }
1069
+ function historyOf(result) {
1070
+ return "contact" in result ? result.contact?.historyKey ?? null : null;
1071
+ }
948
1072
  function hidesChat(result) {
949
1073
  return result.state === "not_found" || result.state === "domain_not_allowed" || result.state === "bundle_id_not_allowed";
950
1074
  }
@@ -4406,9 +4530,9 @@ var markNames = [
4406
4530
  "convexFirstMessageReceived"
4407
4531
  ];
4408
4532
  function mark(name, sessionId) {
4409
- const detail = { sessionId };
4533
+ const detail2 = { sessionId };
4410
4534
  if (typeof performance === "undefined" || !performance.mark) return;
4411
- performance.mark(name, { detail });
4535
+ performance.mark(name, { detail: detail2 });
4412
4536
  }
4413
4537
  function performanceMarkToJson(mark2) {
4414
4538
  let name = mark2.name.slice("convex".length);
@@ -6302,6 +6426,18 @@ function withCode(error) {
6302
6426
  return Object.assign(error instanceof Error ? error : new Error(String(error)), { code: code2 });
6303
6427
  }
6304
6428
 
6429
+ // ../sdk-core/src/quotes.ts
6430
+ function quoteAuthorOf(quote, you, appName) {
6431
+ return quote.from === "contact" ? you : quote.sender?.name ?? appName;
6432
+ }
6433
+ function quoteStepOf(state, replyId) {
6434
+ const quote = state.messages.find((message) => message.id === replyId)?.replyTo;
6435
+ if (!quote || quote.deleted) return { kind: "none" };
6436
+ if (quote.loaded) return { kind: "go", id: quote.id };
6437
+ if (state.loadingOlder) return { kind: "wait" };
6438
+ return state.hasOlder ? { kind: "older" } : { kind: "none" };
6439
+ }
6440
+
6305
6441
  // ../sdk-core/src/index.ts
6306
6442
  function createChat(options) {
6307
6443
  return createChatStore(convexBackend(options.backendUrl), options);
@@ -6407,10 +6543,99 @@ var MAX_ATTACHMENTS = 6;
6407
6543
  var MAX_IMAGE_SIDE = 1600;
6408
6544
  var IMAGE_TYPES = ["image/jpeg", "image/png", "image/webp"];
6409
6545
 
6546
+ // ../shared/src/utils/devices.ts
6547
+ var BROWSERS = [
6548
+ [/Edg(?:A|iOS)?\/(\d+)/, "Edge"],
6549
+ [/OPR\/(\d+)/, "Opera"],
6550
+ [/SamsungBrowser\/(\d+)/, "Samsung Internet"],
6551
+ [/(?:Firefox|FxiOS)\/(\d+)/, "Firefox"],
6552
+ [/(?:Chrome|CriOS)\/(\d+)/, "Chrome"],
6553
+ [/Version\/(\d+)[^ ]* (?:Mobile\/\S+ )?Safari/, "Safari"]
6554
+ ];
6555
+ var ANDROID_BRANDS = [
6556
+ [/^(?:SM-|Galaxy)/i, "Samsung"],
6557
+ [/^Pixel/i, "Google"],
6558
+ [/^(?:Redmi|POCO|Mi |M2\d)/i, "Xiaomi"],
6559
+ [/^moto/i, "Motorola"],
6560
+ [/^(?:ONEPLUS|CPH)/i, "OnePlus"],
6561
+ [/^(?:TECNO)/i, "Tecno"],
6562
+ [/^(?:Infinix)/i, "Infinix"],
6563
+ [/^(?:itel)/i, "itel"],
6564
+ [/^(?:HUAWEI)/i, "Huawei"],
6565
+ [/^Nokia/i, "Nokia"]
6566
+ ];
6567
+ var HIDDEN_MODELS = /* @__PURE__ */ new Set(["K", "wv", "Mobile", "Tablet"]);
6568
+ var SCREEN_MAX = 2e4;
6569
+ function detailsFromUserAgent(userAgent, touchPoints = 0) {
6570
+ const browser = browserOf(userAgent);
6571
+ const details = { platform: "web", ...browser ? { browser } : {} };
6572
+ const ios = /(iPhone|iPad|iPod)[^)]*?OS (\d+)[_.](\d+)/.exec(userAgent) ?? /(iPhone|iPad|iPod)/.exec(userAgent);
6573
+ if (ios) {
6574
+ const model = ios[1] === "iPod" ? "iPod touch" : ios[1];
6575
+ const version2 = ios[2] ? ` ${ios[2]}.${ios[3]}` : "";
6576
+ return { ...details, type: ios[1] === "iPad" ? "tablet" : "phone", brand: "Apple", model, os: `iOS${version2}` };
6577
+ }
6578
+ const android = /Android (\d+(?:\.\d+)?)(?:; ([^;)]+?))?(?: Build\/[^;)]*)?[;)]/.exec(userAgent);
6579
+ if (android) {
6580
+ const named = android[2]?.trim();
6581
+ const model = named && !HIDDEN_MODELS.has(named) ? named : void 0;
6582
+ const brand = model && brandOf(model);
6583
+ return {
6584
+ ...details,
6585
+ type: /Mobile/.test(userAgent) ? "phone" : "tablet",
6586
+ ...brand ? { brand } : {},
6587
+ ...model ? { model } : {},
6588
+ os: `Android ${android[1]}`
6589
+ };
6590
+ }
6591
+ if (/Macintosh|Mac OS X/.test(userAgent)) {
6592
+ if (touchPoints > 1) return { ...details, type: "tablet", brand: "Apple", model: "iPad", os: "iOS" };
6593
+ return { ...details, type: "computer", brand: "Apple", model: "Mac", os: "macOS" };
6594
+ }
6595
+ const computer = [
6596
+ [/Windows/, "Windows"],
6597
+ [/CrOS/, "ChromeOS"],
6598
+ [/Linux/, "Linux"]
6599
+ ].find(([pattern]) => pattern.test(userAgent));
6600
+ return computer ? { ...details, type: "computer", os: computer[1] } : details;
6601
+ }
6602
+ function uprightScreen(screen, type) {
6603
+ if (!(screen.width > 0 && screen.height > 0)) return void 0;
6604
+ if (type === "computer") return { width: screen.width, height: screen.height };
6605
+ return { width: Math.min(screen.width, screen.height), height: Math.max(screen.width, screen.height) };
6606
+ }
6607
+ function cleanDeviceDetails(details) {
6608
+ const texts = ["brand", "model", "os", "browser", "appVersion", "appBuild"].flatMap((key) => {
6609
+ const value = details[key]?.trim().slice(0, DEVICE_DETAIL_MAX_LENGTH);
6610
+ return value ? [[key, value]] : [];
6611
+ });
6612
+ const width = Math.round(details.screen?.width ?? 0);
6613
+ const height = Math.round(details.screen?.height ?? 0);
6614
+ const screen = width > 0 && height > 0 && width <= SCREEN_MAX && height <= SCREEN_MAX ? { width, height } : null;
6615
+ return {
6616
+ ...details.platform && APP_PLATFORMS.includes(details.platform) ? { platform: details.platform } : {},
6617
+ ...details.type && DEVICE_TYPES.includes(details.type) ? { type: details.type } : {},
6618
+ ...Object.fromEntries(texts),
6619
+ ...screen ? { screen } : {}
6620
+ };
6621
+ }
6622
+ function browserOf(userAgent) {
6623
+ for (const [pattern, name] of BROWSERS) {
6624
+ const match = pattern.exec(userAgent);
6625
+ if (match) return `${name} ${match[1]}`;
6626
+ }
6627
+ return void 0;
6628
+ }
6629
+ function brandOf(model) {
6630
+ return ANDROID_BRANDS.find(([pattern]) => pattern.test(model))?.[1];
6631
+ }
6632
+
6410
6633
  // src/models/sdk.constants.ts
6411
6634
  var OFFLINE_NOTICE_MS = 3e3;
6412
6635
  var ANDROID_NAVIGATION_BAR = 48;
6413
6636
  var DEFAULT_MAX_PHOTOS = 4;
6637
+ var ANDROID_TABLET_SIDE = 600;
6638
+ var EXPO_DEVICE_TYPES = { 1: "phone", 2: "tablet", 3: "computer" };
6414
6639
  var CHAT_STORAGE_ID = "zean-chat";
6415
6640
  var LINK_RETRY_MS = 1500;
6416
6641
  var LINK_RETRIES = 5;
@@ -6482,7 +6707,7 @@ function deviceLanguages() {
6482
6707
  }
6483
6708
  function appBundle() {
6484
6709
  if (import_react_native.Platform.OS !== "ios" && import_react_native.Platform.OS !== "android") return void 0;
6485
- const id = expoApplicationId() ?? deviceInfoBundleId();
6710
+ const id = text(expoApplication()?.applicationId) ?? text(detail(deviceInfo()?.getBundleId));
6486
6711
  return id ? { os: import_react_native.Platform.OS, id } : void 0;
6487
6712
  }
6488
6713
  function chatStorage(storage) {
@@ -6549,23 +6774,38 @@ function isKeyValue(value) {
6549
6774
  const { getItem, setItem } = value;
6550
6775
  return typeof getItem === "function" && typeof setItem === "function";
6551
6776
  }
6552
- function expoApplicationId() {
6777
+ function expoApplication() {
6778
+ try {
6779
+ return require("expo-application");
6780
+ } catch {
6781
+ return null;
6782
+ }
6783
+ }
6784
+ function expoDevice() {
6553
6785
  try {
6554
- const expo = require("expo-application");
6555
- return typeof expo?.applicationId === "string" ? expo.applicationId : null;
6786
+ return require("expo-device");
6556
6787
  } catch {
6557
6788
  return null;
6558
6789
  }
6559
6790
  }
6560
- function deviceInfoBundleId() {
6791
+ function deviceInfo() {
6561
6792
  try {
6562
6793
  const module2 = require("react-native-device-info");
6563
- const getBundleId = module2?.getBundleId ?? module2?.default?.getBundleId;
6564
- return typeof getBundleId === "function" ? getBundleId() : null;
6794
+ return module2 && { ...module2.default, ...module2 };
6565
6795
  } catch {
6566
6796
  return null;
6567
6797
  }
6568
6798
  }
6799
+ function detail(read) {
6800
+ try {
6801
+ return read?.();
6802
+ } catch {
6803
+ return void 0;
6804
+ }
6805
+ }
6806
+ function text(value) {
6807
+ return typeof value === "string" && value.trim() !== "" && value !== "unknown" ? value : void 0;
6808
+ }
6569
6809
  function isDevBuild() {
6570
6810
  return typeof __DEV__ !== "undefined" && __DEV__;
6571
6811
  }
@@ -6587,10 +6827,57 @@ function objectOf(data) {
6587
6827
  }
6588
6828
  return typeof value === "object" && value !== null ? value : null;
6589
6829
  }
6590
- function deviceOs() {
6591
- if (import_react_native.Platform.OS === "ios") return `iOS ${import_react_native.Platform.Version}`;
6592
- if (import_react_native.Platform.OS === "android") return `Android ${import_react_native.Platform.constants.Release}`;
6593
- return void 0;
6830
+ function deviceDetails() {
6831
+ const screen = import_react_native.Dimensions.get("screen");
6832
+ const system = systemDetails(screen);
6833
+ const installed = import_react_native.Platform.OS === "web" ? {} : installedDetails();
6834
+ const type = installed.type ?? system.type;
6835
+ return cleanDeviceDetails({
6836
+ ...system,
6837
+ platform: "react_native",
6838
+ type,
6839
+ brand: installed.brand ?? system.brand,
6840
+ model: installed.model ?? system.model,
6841
+ screen: uprightScreen(screen, type),
6842
+ appVersion: installed.appVersion,
6843
+ appBuild: installed.appBuild
6844
+ });
6845
+ }
6846
+ function systemDetails(screen) {
6847
+ if (import_react_native.Platform.OS === "ios") {
6848
+ const pad = import_react_native.Platform.isPad;
6849
+ return { type: pad ? "tablet" : "phone", brand: "Apple", model: pad ? "iPad" : "iPhone", os: `iOS ${import_react_native.Platform.Version}` };
6850
+ }
6851
+ if (import_react_native.Platform.OS === "android") {
6852
+ const { Release, Brand, Manufacturer, Model } = import_react_native.Platform.constants;
6853
+ const tablet = Math.min(screen.width, screen.height) >= ANDROID_TABLET_SIDE;
6854
+ return { type: tablet ? "tablet" : "phone", brand: brandName(Brand || Manufacturer), model: Model, os: `Android ${Release}` };
6855
+ }
6856
+ if (import_react_native.Platform.OS === "web") {
6857
+ const { userAgent, maxTouchPoints } = globalThis.navigator;
6858
+ return detailsFromUserAgent(userAgent, maxTouchPoints);
6859
+ }
6860
+ return {};
6861
+ }
6862
+ function installedDetails() {
6863
+ const device = expoDevice();
6864
+ const application = expoApplication();
6865
+ const info = deviceInfo();
6866
+ const tablet = detail(info?.isTablet);
6867
+ const infoType = typeof tablet === "boolean" ? tablet ? "tablet" : "phone" : void 0;
6868
+ return {
6869
+ type: EXPO_DEVICE_TYPES[Number(device?.deviceType)] ?? infoType,
6870
+ brand: brandName(text(device?.brand) ?? text(detail(info?.getBrand))),
6871
+ model: text(device?.modelName) ?? text(detail(info?.getModel)),
6872
+ appVersion: text(application?.nativeApplicationVersion) ?? text(detail(info?.getVersion)),
6873
+ appBuild: text(application?.nativeBuildVersion) ?? text(detail(info?.getBuildNumber))
6874
+ };
6875
+ }
6876
+ function brandName(brand) {
6877
+ if (!brand) return void 0;
6878
+ const shouted = brand.length > 3 && brand === brand.toUpperCase();
6879
+ if (brand !== brand.toLowerCase() && !shouted) return brand;
6880
+ return brand.charAt(0).toUpperCase() + brand.slice(1).toLowerCase();
6594
6881
  }
6595
6882
  function screenInsets() {
6596
6883
  if (import_react_native.Platform.OS === "android") {
@@ -6715,8 +7002,8 @@ function subscribeChatView(listener) {
6715
7002
  }
6716
7003
 
6717
7004
  // src/components/ChatModal.tsx
6718
- var import_react16 = require("react");
6719
- var import_react_native23 = require("react-native");
7005
+ var import_react17 = require("react");
7006
+ var import_react_native24 = require("react-native");
6720
7007
 
6721
7008
  // src/hooks/use-app-active.ts
6722
7009
  var import_react = require("react");
@@ -6742,7 +7029,6 @@ function useChatContext() {
6742
7029
  // src/i18n/en.ts
6743
7030
  var en = {
6744
7031
  ai: "AI",
6745
- request_human: "Talk to a Member",
6746
7032
  close_chat: "Close chat",
6747
7033
  online: "Online",
6748
7034
  away: "Away for now",
@@ -6755,6 +7041,10 @@ var en = {
6755
7041
  seen: "Seen",
6756
7042
  not_sent: "Not sent.",
6757
7043
  rate_limited: "Too many messages at once. Wait a moment.",
7044
+ you: "You",
7045
+ photo: "Photo",
7046
+ message_deleted: "Message deleted",
7047
+ show_quoted: "Show the quoted message",
6758
7048
  retry: "Retry",
6759
7049
  team: "The team",
6760
7050
  typing: "{name} is typing\u2026",
@@ -6798,7 +7088,6 @@ var en = {
6798
7088
  // src/i18n/fr.ts
6799
7089
  var fr = {
6800
7090
  ai: "IA",
6801
- request_human: "Parler \xE0 un membre",
6802
7091
  close_chat: "Fermer le chat",
6803
7092
  online: "En ligne",
6804
7093
  away: "Absents pour le moment",
@@ -6811,6 +7100,10 @@ var fr = {
6811
7100
  seen: "Vu",
6812
7101
  not_sent: "Non envoy\xE9.",
6813
7102
  rate_limited: "Trop de messages \xE0 la fois. Patientez un instant.",
7103
+ you: "Vous",
7104
+ photo: "Photo",
7105
+ message_deleted: "Message supprim\xE9",
7106
+ show_quoted: "Voir le message cit\xE9",
6814
7107
  retry: "R\xE9essayer",
6815
7108
  team: "L'\xE9quipe",
6816
7109
  typing: "{name} \xE9crit\u2026",
@@ -6948,8 +7241,8 @@ var styles = import_react_native4.StyleSheet.create({
6948
7241
  });
6949
7242
 
6950
7243
  // src/components/ChatScreen.tsx
6951
- var import_react15 = require("react");
6952
- var import_react_native22 = require("react-native");
7244
+ var import_react16 = require("react");
7245
+ var import_react_native23 = require("react-native");
6953
7246
 
6954
7247
  // src/hooks/use-connection-lost.ts
6955
7248
  var import_react4 = require("react");
@@ -7214,11 +7507,96 @@ function isImage(type) {
7214
7507
  return IMAGE_TYPES.includes(type);
7215
7508
  }
7216
7509
 
7510
+ // src/models/conversation.utils.ts
7511
+ function authorOf(message) {
7512
+ if (message.from === "contact") return "contact";
7513
+ return `team:${message.sender?.name ?? ""}:${message.sender?.image ?? ""}`;
7514
+ }
7515
+ function startOfDay(timestamp) {
7516
+ const day = new Date(timestamp);
7517
+ day.setHours(0, 0, 0, 0);
7518
+ return day.getTime();
7519
+ }
7520
+ function sameDay(left, right) {
7521
+ return startOfDay(left) === startOfDay(right);
7522
+ }
7523
+ function joins(older, newer) {
7524
+ return older.status !== "failed" && authorOf(older) === authorOf(newer) && newer.createdAt - older.createdAt < RUN_GAP_MS && sameDay(older.createdAt, newer.createdAt);
7525
+ }
7526
+ function conversationRows(messages, seen, welcome) {
7527
+ const all = welcome ? [welcome, ...messages] : [...messages];
7528
+ const lastReply = all.findLastIndex((message) => message.from === "team" && message.sender !== null);
7529
+ return all.map((message, index) => {
7530
+ const older = all[index - 1];
7531
+ const newer = all[index + 1];
7532
+ const isWelcome = message === welcome;
7533
+ return {
7534
+ message,
7535
+ startsRun: !older || !joins(older, message),
7536
+ endsRun: !newer || !joins(message, newer),
7537
+ // Alone, the welcome has no day: there is nothing to date.
7538
+ startsDay: isWelcome ? messages.length > 0 : !older || !sameDay(older.createdAt, message.createdAt),
7539
+ receipt: receiptOf(message, seen || index < lastReply),
7540
+ welcome: isWelcome
7541
+ };
7542
+ });
7543
+ }
7544
+ function receiptOf(message, seen) {
7545
+ if (message.from === "team" || message.status === "failed") return null;
7546
+ if (message.status === "sending") return "sending";
7547
+ return seen ? "seen" : "sent";
7548
+ }
7549
+ var DATE_STYLES = {
7550
+ time: { hour: "2-digit", minute: "2-digit" },
7551
+ weekday: { weekday: "long" },
7552
+ day: { day: "numeric", month: "short" },
7553
+ dayYear: { day: "numeric", month: "short", year: "numeric" }
7554
+ };
7555
+ var formats = /* @__PURE__ */ new Map();
7556
+ function formatDate(timestamp, locale, style) {
7557
+ const key = `${locale}:${style}`;
7558
+ let format2 = formats.get(key);
7559
+ if (!format2) {
7560
+ format2 = new Intl.DateTimeFormat(locale, DATE_STYLES[style]);
7561
+ formats.set(key, format2);
7562
+ }
7563
+ return format2.format(timestamp);
7564
+ }
7565
+ function messageTime(timestamp, locale) {
7566
+ return formatDate(timestamp, locale, "time");
7567
+ }
7568
+ function dayLabel(timestamp, now, locale, t) {
7569
+ const today = startOfDay(now);
7570
+ const day = startOfDay(timestamp);
7571
+ if (day === today) return t.today;
7572
+ if (day === startOfDay(today - 1)) return t.yesterday;
7573
+ const weekAgo = new Date(today);
7574
+ weekAgo.setDate(weekAgo.getDate() - 6);
7575
+ if (day >= weekAgo.getTime()) return formatDate(timestamp, locale, "weekday");
7576
+ const sameYear = new Date(timestamp).getFullYear() === new Date(now).getFullYear();
7577
+ return formatDate(timestamp, locale, sameYear ? "day" : "dayYear");
7578
+ }
7579
+ function pendingPhotosOfDraft(files, newId) {
7580
+ return files.flatMap(
7581
+ ({ uri, name, type, width, height, attachment }) => uri ? [{ id: newId(), uri, name, type, width, height, status: attachment ? "ready" : "picked", attachment }] : []
7582
+ );
7583
+ }
7584
+ function draftFilesOf(photos) {
7585
+ return photos.map(({ name, type, attachment, uri, width, height }) => ({
7586
+ name,
7587
+ type,
7588
+ attachment,
7589
+ uri,
7590
+ ...width && height ? { width, height } : {}
7591
+ }));
7592
+ }
7593
+
7217
7594
  // src/hooks/use-pending-photos.ts
7218
7595
  var lastId = 0;
7596
+ var nextId = () => `photo_${++lastId}`;
7219
7597
  function usePendingPhotos() {
7220
7598
  const { chat: chat2, t, maxPhotos } = useChatContext();
7221
- const [photos, setPhotos] = (0, import_react7.useState)([]);
7599
+ const [photos, setPhotos] = (0, import_react7.useState)(() => pendingPhotosOfDraft(chat2.draft()?.files ?? [], nextId));
7222
7600
  const [problem, setProblem] = (0, import_react7.useState)(null);
7223
7601
  const [sending, setSending] = (0, import_react7.useState)(false);
7224
7602
  const tooMany = maxPhotos === 1 ? t.too_many_one : format(t.too_many, { count: maxPhotos });
@@ -7263,9 +7641,8 @@ function usePendingPhotos() {
7263
7641
  setProblem(format(t.photo_size, { name: photo.name }));
7264
7642
  continue;
7265
7643
  }
7266
- lastId += 1;
7267
7644
  const { uri, name, type, width, height } = photo;
7268
- added.push({ id: `photo_${lastId}`, uri, name, type, width, height, status: "picked", attachment: null });
7645
+ added.push({ id: nextId(), uri, name, type, width, height, status: "picked", attachment: null });
7269
7646
  }
7270
7647
  setPhotos((current) => [...current, ...added]);
7271
7648
  };
@@ -7279,8 +7656,10 @@ function usePendingPhotos() {
7279
7656
  setPhotos([]);
7280
7657
  return attachments;
7281
7658
  };
7659
+ const draftFiles = (0, import_react7.useMemo)(() => draftFilesOf(photos), [photos]);
7282
7660
  return {
7283
7661
  photos,
7662
+ draftFiles,
7284
7663
  problem,
7285
7664
  /** Photos that still fit in the message. */
7286
7665
  room: maxPhotos - photos.length,
@@ -7422,11 +7801,11 @@ var styles6 = import_react_native10.StyleSheet.create({
7422
7801
  var import_jsx_runtime8 = require("react/jsx-runtime");
7423
7802
  function Composer() {
7424
7803
  const { chat: chat2, t, colors } = useChatContext();
7425
- const [text, setText] = (0, import_react8.useState)("");
7426
- const typed = (0, import_react8.useRef)("");
7804
+ const [text2, setText] = (0, import_react8.useState)(() => chat2.draft()?.text ?? "");
7805
+ const typed = (0, import_react8.useRef)(text2);
7427
7806
  const pending = usePendingPhotos();
7428
7807
  const picker = photoPicker();
7429
- const canSend = !pending.sending && (text.trim().length > 0 || pending.photos.length > 0);
7808
+ const canSend = !pending.sending && (text2.trim().length > 0 || pending.photos.length > 0);
7430
7809
  const draft2 = (0, import_react8.useSyncExternalStore)(subscribeChatView, chatDraft);
7431
7810
  const changeText = (value) => {
7432
7811
  typed.current = value;
@@ -7437,6 +7816,9 @@ function Composer() {
7437
7816
  changeText(draft2);
7438
7817
  clearDraft();
7439
7818
  }, [draft2]);
7819
+ (0, import_react8.useEffect)(() => {
7820
+ chat2.saveDraft({ text: text2, files: pending.draftFiles });
7821
+ }, [chat2, text2, pending.draftFiles]);
7440
7822
  const handleSend = async () => {
7441
7823
  const attachments = pending.photos.length > 0 ? await pending.send() : [];
7442
7824
  if (!attachments) return;
@@ -7474,7 +7856,7 @@ function Composer() {
7474
7856
  /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(
7475
7857
  import_react_native11.TextInput,
7476
7858
  {
7477
- value: text,
7859
+ value: text2,
7478
7860
  onChangeText: (value) => {
7479
7861
  changeText(value);
7480
7862
  chat2.typing();
@@ -7533,78 +7915,8 @@ var styles7 = import_react_native11.StyleSheet.create({
7533
7915
  });
7534
7916
 
7535
7917
  // src/components/MessageList.tsx
7536
- var import_react14 = require("react");
7537
- var import_react_native20 = require("react-native");
7538
-
7539
- // src/models/conversation.utils.ts
7540
- function authorOf(message) {
7541
- if (message.from === "contact") return "contact";
7542
- return `team:${message.sender?.name ?? ""}:${message.sender?.image ?? ""}`;
7543
- }
7544
- function startOfDay(timestamp) {
7545
- const day = new Date(timestamp);
7546
- day.setHours(0, 0, 0, 0);
7547
- return day.getTime();
7548
- }
7549
- function sameDay(left, right) {
7550
- return startOfDay(left) === startOfDay(right);
7551
- }
7552
- function joins(older, newer) {
7553
- return older.status !== "failed" && authorOf(older) === authorOf(newer) && newer.createdAt - older.createdAt < RUN_GAP_MS && sameDay(older.createdAt, newer.createdAt);
7554
- }
7555
- function conversationRows(messages, seen, welcome) {
7556
- const all = welcome ? [welcome, ...messages] : [...messages];
7557
- const lastReply = all.findLastIndex((message) => message.from === "team" && message.sender !== null);
7558
- return all.map((message, index) => {
7559
- const older = all[index - 1];
7560
- const newer = all[index + 1];
7561
- const isWelcome = message === welcome;
7562
- return {
7563
- message,
7564
- startsRun: !older || !joins(older, message),
7565
- endsRun: !newer || !joins(message, newer),
7566
- // Alone, the welcome has no day: there is nothing to date.
7567
- startsDay: isWelcome ? messages.length > 0 : !older || !sameDay(older.createdAt, message.createdAt),
7568
- receipt: receiptOf(message, seen || index < lastReply),
7569
- welcome: isWelcome
7570
- };
7571
- });
7572
- }
7573
- function receiptOf(message, seen) {
7574
- if (message.from === "team" || message.status === "failed") return null;
7575
- if (message.status === "sending") return "sending";
7576
- return seen ? "seen" : "sent";
7577
- }
7578
- var DATE_STYLES = {
7579
- time: { hour: "2-digit", minute: "2-digit" },
7580
- weekday: { weekday: "long" },
7581
- day: { day: "numeric", month: "short" },
7582
- dayYear: { day: "numeric", month: "short", year: "numeric" }
7583
- };
7584
- var formats = /* @__PURE__ */ new Map();
7585
- function formatDate(timestamp, locale, style) {
7586
- const key = `${locale}:${style}`;
7587
- let format2 = formats.get(key);
7588
- if (!format2) {
7589
- format2 = new Intl.DateTimeFormat(locale, DATE_STYLES[style]);
7590
- formats.set(key, format2);
7591
- }
7592
- return format2.format(timestamp);
7593
- }
7594
- function messageTime(timestamp, locale) {
7595
- return formatDate(timestamp, locale, "time");
7596
- }
7597
- function dayLabel(timestamp, now, locale, t) {
7598
- const today = startOfDay(now);
7599
- const day = startOfDay(timestamp);
7600
- if (day === today) return t.today;
7601
- if (day === startOfDay(today - 1)) return t.yesterday;
7602
- const weekAgo = new Date(today);
7603
- weekAgo.setDate(weekAgo.getDate() - 6);
7604
- if (day >= weekAgo.getTime()) return formatDate(timestamp, locale, "weekday");
7605
- const sameYear = new Date(timestamp).getFullYear() === new Date(now).getFullYear();
7606
- return formatDate(timestamp, locale, sameYear ? "day" : "dayYear");
7607
- }
7918
+ var import_react15 = require("react");
7919
+ var import_react_native21 = require("react-native");
7608
7920
 
7609
7921
  // src/components/EmailForm.tsx
7610
7922
  var import_react9 = require("react");
@@ -7677,7 +7989,8 @@ var styles8 = import_react_native12.StyleSheet.create({
7677
7989
  });
7678
7990
 
7679
7991
  // src/components/MessageBubble.tsx
7680
- var import_react_native18 = require("react-native");
7992
+ var import_react13 = require("react");
7993
+ var import_react_native19 = require("react-native");
7681
7994
 
7682
7995
  // src/hooks/use-rise-in.ts
7683
7996
  var import_react10 = require("react");
@@ -7710,6 +8023,8 @@ var signed = /* @__PURE__ */ new Map();
7710
8023
  function useAttachmentLinks(chat2, keys, stored) {
7711
8024
  const [links, setLinks] = (0, import_react11.useState)(() => cachedLinks(keys));
7712
8025
  const [attempt, setAttempt] = (0, import_react11.useState)(0);
8026
+ const connected = (0, import_react11.useSyncExternalStore)(chat2.subscribe, () => chat2.getState().connected);
8027
+ const failed = (0, import_react11.useRef)(false);
7713
8028
  const wanted = keys.join("|");
7714
8029
  (0, import_react11.useEffect)(() => {
7715
8030
  if (!stored) return;
@@ -7721,19 +8036,27 @@ function useAttachmentLinks(chat2, keys, stored) {
7721
8036
  }
7722
8037
  let cancelled = false;
7723
8038
  let retry;
8039
+ const askAgain = () => {
8040
+ if (!cancelled && attempt < LINK_RETRIES) retry = setTimeout(() => setAttempt(attempt + 1), LINK_RETRY_MS);
8041
+ };
7724
8042
  chat2.attachmentLinks(missing).then((fresh) => {
8043
+ failed.current = false;
7725
8044
  for (const link of fresh) signed.set(link.key, { url: link.url, until: Date.now() + LINK_LIFETIME_MS });
7726
8045
  if (cancelled) return;
7727
8046
  setLinks(cachedLinks(list));
7728
- if (fresh.length < missing.length && attempt < LINK_RETRIES)
7729
- retry = setTimeout(() => setAttempt(attempt + 1), LINK_RETRY_MS);
8047
+ if (fresh.length < missing.length) askAgain();
7730
8048
  }).catch(() => {
8049
+ failed.current = true;
8050
+ askAgain();
7731
8051
  });
7732
8052
  return () => {
7733
8053
  cancelled = true;
7734
8054
  clearTimeout(retry);
7735
8055
  };
7736
8056
  }, [chat2, wanted, attempt, stored]);
8057
+ (0, import_react11.useEffect)(() => {
8058
+ if (connected && failed.current) setAttempt((current) => current + 1);
8059
+ }, [connected]);
7737
8060
  return links;
7738
8061
  }
7739
8062
  function cachedLinks(keys) {
@@ -7885,37 +8208,104 @@ var styles10 = import_react_native16.StyleSheet.create({
7885
8208
  retry: { fontWeight: "600", textDecorationLine: "underline" }
7886
8209
  });
7887
8210
 
7888
- // src/components/TeamAvatar.tsx
8211
+ // src/components/MessageQuote.tsx
7889
8212
  var import_react_native17 = require("react-native");
8213
+
8214
+ // ../shared/src/utils/quotes.ts
8215
+ function quoteImageOf(quote) {
8216
+ return !quote.deleted && quote.attachment && isImage(quote.attachment.type) ? quote.attachment : null;
8217
+ }
8218
+ function quoteLineOf(quote, labels) {
8219
+ if (quote.deleted) return labels.deleted;
8220
+ if (quote.text) return quote.text;
8221
+ if (!quote.attachment) return "";
8222
+ return quoteImageOf(quote) ? labels.photo : quote.attachment.name;
8223
+ }
8224
+
8225
+ // src/components/MessageQuote.tsx
7890
8226
  var import_jsx_runtime13 = require("react/jsx-runtime");
8227
+ function MessageQuote({ quote, app, onQuote }) {
8228
+ const { chat: chat2, t, colors } = useChatContext();
8229
+ const image = quoteImageOf(quote);
8230
+ const links = useAttachmentLinks(chat2, image ? [image.key] : [], true);
8231
+ const url = image && links.get(image.key);
8232
+ const text2 = quoteLineOf(quote, { deleted: t.message_deleted, photo: t.photo });
8233
+ const { deleted } = quote;
8234
+ return /* @__PURE__ */ (0, import_jsx_runtime13.jsxs)(
8235
+ import_react_native17.Pressable,
8236
+ {
8237
+ disabled: deleted,
8238
+ onPress: onQuote,
8239
+ accessibilityRole: "button",
8240
+ accessibilityLabel: t.show_quoted,
8241
+ accessibilityState: { disabled: deleted },
8242
+ style: ({ pressed }) => [
8243
+ styles11.quote,
8244
+ { backgroundColor: colors.background, borderLeftColor: colors.primary },
8245
+ pressed && styles11.pressed
8246
+ ],
8247
+ children: [
8248
+ /* @__PURE__ */ (0, import_jsx_runtime13.jsxs)(import_react_native17.View, { style: styles11.lines, children: [
8249
+ /* @__PURE__ */ (0, import_jsx_runtime13.jsx)(import_react_native17.Text, { style: [styles11.name, { color: colors.primaryText }], numberOfLines: 1, children: quoteAuthorOf(quote, t.you, app.name) }),
8250
+ /* @__PURE__ */ (0, import_jsx_runtime13.jsx)(import_react_native17.Text, { style: [styles11.text, { color: colors.muted }, quote.deleted && styles11.deleted], numberOfLines: 1, children: text2 })
8251
+ ] }),
8252
+ image && (url ? /* @__PURE__ */ (0, import_jsx_runtime13.jsx)(import_react_native17.Image, { source: { uri: url }, style: [styles11.thumb, { borderColor: colors.border }], accessibilityIgnoresInvertColors: true }) : /* @__PURE__ */ (0, import_jsx_runtime13.jsx)(Skeleton, { style: [styles11.thumb, { borderColor: colors.border }] }))
8253
+ ]
8254
+ }
8255
+ );
8256
+ }
8257
+ var THUMB = 36;
8258
+ var styles11 = import_react_native17.StyleSheet.create({
8259
+ quote: {
8260
+ flexDirection: "row",
8261
+ alignItems: "center",
8262
+ gap: 8,
8263
+ alignSelf: "stretch",
8264
+ borderRadius: 10,
8265
+ borderLeftWidth: 3,
8266
+ paddingVertical: 6,
8267
+ paddingLeft: 8,
8268
+ paddingRight: 6
8269
+ },
8270
+ pressed: { opacity: 0.6 },
8271
+ lines: { flexShrink: 1, flexGrow: 1 },
8272
+ name: { fontSize: 13, fontWeight: "600" },
8273
+ text: { fontSize: 13, lineHeight: 18 },
8274
+ deleted: { fontStyle: "italic" },
8275
+ thumb: { width: THUMB, height: THUMB, borderRadius: 6, borderWidth: 1 }
8276
+ });
8277
+
8278
+ // src/components/TeamAvatar.tsx
8279
+ var import_react_native18 = require("react-native");
8280
+ var import_jsx_runtime14 = require("react/jsx-runtime");
7891
8281
  function TeamAvatar({ app, sender, ai = false }) {
7892
8282
  const { colors } = useChatContext();
7893
8283
  if (ai) {
7894
- return /* @__PURE__ */ (0, import_jsx_runtime13.jsx)(
7895
- import_react_native17.View,
8284
+ return /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(
8285
+ import_react_native18.View,
7896
8286
  {
7897
- style: [styles11.avatar, { backgroundColor: colors.primaryTint }],
8287
+ style: [styles12.avatar, { backgroundColor: colors.primaryTint }],
7898
8288
  accessibilityElementsHidden: true,
7899
8289
  importantForAccessibility: "no-hide-descendants",
7900
- children: /* @__PURE__ */ (0, import_jsx_runtime13.jsx)(Icon, { name: "sparkles", color: colors.primaryText, size: 14 })
8290
+ children: /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(Icon, { name: "sparkles", color: colors.primaryText, size: 14 })
7901
8291
  }
7902
8292
  );
7903
8293
  }
7904
8294
  const image = sender ? sender.image : app.logoUrl;
7905
8295
  if (image) {
7906
- return /* @__PURE__ */ (0, import_jsx_runtime13.jsx)(import_react_native17.Image, { source: { uri: image }, style: [styles11.avatar, { borderColor: colors.border }], accessibilityIgnoresInvertColors: true });
8296
+ return /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(import_react_native18.Image, { source: { uri: image }, style: [styles12.avatar, { borderColor: colors.border }], accessibilityIgnoresInvertColors: true });
7907
8297
  }
7908
- return /* @__PURE__ */ (0, import_jsx_runtime13.jsx)(
7909
- import_react_native17.View,
8298
+ return /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(
8299
+ import_react_native18.View,
7910
8300
  {
7911
- style: [styles11.avatar, { backgroundColor: sender ? colors.primaryTint : colors.primary }],
8301
+ style: [styles12.avatar, { backgroundColor: sender ? colors.primaryTint : colors.primary }],
7912
8302
  accessibilityElementsHidden: true,
7913
8303
  importantForAccessibility: "no-hide-descendants",
7914
- children: /* @__PURE__ */ (0, import_jsx_runtime13.jsx)(import_react_native17.Text, { style: [styles11.initials, { color: sender ? colors.primaryText : colors.primaryForeground }], children: initialsOf(sender?.name ?? app.name) })
8304
+ children: /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(import_react_native18.Text, { style: [styles12.initials, { color: sender ? colors.primaryText : colors.primaryForeground }], children: initialsOf(sender?.name ?? app.name) })
7915
8305
  }
7916
8306
  );
7917
8307
  }
7918
- var styles11 = import_react_native17.StyleSheet.create({
8308
+ var styles12 = import_react_native18.StyleSheet.create({
7919
8309
  avatar: {
7920
8310
  width: 28,
7921
8311
  height: 28,
@@ -7930,57 +8320,79 @@ var styles11 = import_react_native17.StyleSheet.create({
7930
8320
  });
7931
8321
 
7932
8322
  // src/components/MessageBubble.tsx
7933
- var import_jsx_runtime14 = require("react/jsx-runtime");
7934
- function MessageBubble({ row, app, onRetry }) {
8323
+ var import_jsx_runtime15 = require("react/jsx-runtime");
8324
+ var MessageBubble = (0, import_react13.memo)(function MessageBubble2({ row, app, onRetry, onQuote, highlighted }) {
7935
8325
  const { chat: chat2, t, locale, colors, openedAt } = useChatContext();
7936
8326
  const { message, startsRun, endsRun, startsDay } = row;
7937
8327
  const own = message.from === "contact";
8328
+ const handleRetry = () => onRetry(message.id);
7938
8329
  const rise = useRiseIn(message.createdAt > openedAt && (!own || message.status === "sending"));
7939
8330
  const corner = startsRun ? RADII.group : RADII.inner;
7940
- return /* @__PURE__ */ (0, import_jsx_runtime14.jsxs)(import_react_native18.Animated.View, { style: [styles12.row, { paddingTop: startsRun ? 14 : 3 }, rise], children: [
7941
- startsDay && /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(import_react_native18.Text, { style: [styles12.day, { backgroundColor: colors.surface, color: colors.muted }], accessibilityRole: "header", children: dayLabel(message.createdAt, openedAt, locale, t) }),
7942
- own ? /* @__PURE__ */ (0, import_jsx_runtime14.jsxs)(import_react_native18.View, { style: styles12.own, children: [
7943
- message.body !== "" && /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(
7944
- import_react_native18.Text,
7945
- {
7946
- selectable: true,
7947
- style: [
7948
- styles12.bubble,
7949
- { borderTopRightRadius: corner, borderBottomRightRadius: RADII.inner },
7950
- { backgroundColor: colors.primary, color: colors.primaryForeground }
7951
- ],
7952
- children: message.body
7953
- }
7954
- ),
7955
- /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(MessageFiles, { attachments: message.attachments, own: true, stored: message.status === "sent" }),
7956
- endsRun && /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(MessageMeta, { row, onRetry })
7957
- ] }) : /* @__PURE__ */ (0, import_jsx_runtime14.jsxs)(import_react_native18.View, { style: styles12.team, children: [
7958
- (startsRun || message.ai) && /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(import_react_native18.Text, { style: [styles12.name, { color: colors.muted }], numberOfLines: 1, children: message.ai ? t.ai : message.sender?.name ?? app.name }),
7959
- /* @__PURE__ */ (0, import_jsx_runtime14.jsxs)(import_react_native18.View, { style: styles12.teamRow, children: [
7960
- /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(import_react_native18.View, { style: styles12.avatar, children: endsRun && /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(TeamAvatar, { app, sender: message.sender, ai: message.ai }) }),
7961
- /* @__PURE__ */ (0, import_jsx_runtime14.jsxs)(import_react_native18.View, { style: styles12.teamColumn, children: [
7962
- message.body !== "" && /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(
7963
- import_react_native18.Text,
8331
+ return /* @__PURE__ */ (0, import_jsx_runtime15.jsxs)(
8332
+ import_react_native19.Animated.View,
8333
+ {
8334
+ style: [styles13.row, { paddingTop: startsRun ? 14 : 3 }, highlighted && { backgroundColor: colors.primaryTint }, rise],
8335
+ children: [
8336
+ startsDay && /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(import_react_native19.Text, { style: [styles13.day, { backgroundColor: colors.surface, color: colors.muted }], accessibilityRole: "header", children: dayLabel(message.createdAt, openedAt, locale, t) }),
8337
+ own ? /* @__PURE__ */ (0, import_jsx_runtime15.jsxs)(import_react_native19.View, { style: styles13.own, children: [
8338
+ message.body !== "" && /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(
8339
+ import_react_native19.Text,
7964
8340
  {
7965
8341
  selectable: true,
7966
8342
  style: [
7967
- styles12.bubble,
7968
- { borderTopLeftRadius: corner, borderBottomLeftRadius: RADII.inner },
7969
- { backgroundColor: colors.surface, color: colors.text }
8343
+ styles13.bubble,
8344
+ styles13.text,
8345
+ { borderTopRightRadius: corner, borderBottomRightRadius: RADII.inner },
8346
+ { backgroundColor: colors.primary, color: colors.primaryForeground }
7970
8347
  ],
7971
8348
  children: message.body
7972
8349
  }
7973
8350
  ),
7974
- /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(MessageFiles, { attachments: message.attachments, own: false, stored: true })
8351
+ /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(MessageFiles, { attachments: message.attachments, own: true, stored: message.status === "sent" }),
8352
+ endsRun && /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(MessageMeta, { row, onRetry: handleRetry })
8353
+ ] }) : /* @__PURE__ */ (0, import_jsx_runtime15.jsxs)(import_react_native19.View, { style: styles13.team, children: [
8354
+ (startsRun || message.ai) && /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(import_react_native19.Text, { style: [styles13.name, { color: colors.muted }], numberOfLines: 1, children: message.ai ? t.ai : message.sender?.name ?? app.name }),
8355
+ /* @__PURE__ */ (0, import_jsx_runtime15.jsxs)(import_react_native19.View, { style: styles13.teamRow, children: [
8356
+ /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(import_react_native19.View, { style: styles13.avatar, children: endsRun && /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(TeamAvatar, { app, sender: message.sender, ai: message.ai }) }),
8357
+ /* @__PURE__ */ (0, import_jsx_runtime15.jsxs)(import_react_native19.View, { style: styles13.teamColumn, children: [
8358
+ message.replyTo ? /* @__PURE__ */ (0, import_jsx_runtime15.jsxs)(
8359
+ import_react_native19.View,
8360
+ {
8361
+ style: [
8362
+ styles13.bubble,
8363
+ styles13.quoted,
8364
+ { borderTopLeftRadius: corner, borderBottomLeftRadius: RADII.inner },
8365
+ { backgroundColor: colors.surface }
8366
+ ],
8367
+ children: [
8368
+ /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(MessageQuote, { quote: message.replyTo, app, onQuote: () => onQuote(message.id) }),
8369
+ message.body !== "" && /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(import_react_native19.Text, { selectable: true, style: [styles13.text, styles13.quotedText, { color: colors.text }], children: message.body })
8370
+ ]
8371
+ }
8372
+ ) : message.body !== "" && /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(
8373
+ import_react_native19.Text,
8374
+ {
8375
+ selectable: true,
8376
+ style: [
8377
+ styles13.bubble,
8378
+ styles13.text,
8379
+ { borderTopLeftRadius: corner, borderBottomLeftRadius: RADII.inner },
8380
+ { backgroundColor: colors.surface, color: colors.text }
8381
+ ],
8382
+ children: message.body
8383
+ }
8384
+ ),
8385
+ /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(MessageFiles, { attachments: message.attachments, own: false, stored: true })
8386
+ ] })
8387
+ ] }),
8388
+ endsRun && !row.welcome && /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(import_react_native19.View, { style: styles13.teamMeta, children: /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(MessageMeta, { row, onRetry: handleRetry }) })
7975
8389
  ] })
7976
- ] }),
7977
- message.ai && /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(import_react_native18.Pressable, { accessibilityRole: "button", onPress: () => chat2.send(t.request_human), hitSlop: 8, style: styles12.teamMeta, children: /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(import_react_native18.Text, { style: [styles12.human, { color: colors.primaryText }], children: t.request_human }) }),
7978
- endsRun && !row.welcome && /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(import_react_native18.View, { style: styles12.teamMeta, children: /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(MessageMeta, { row, onRetry }) })
7979
- ] })
7980
- ] });
7981
- }
8390
+ ]
8391
+ }
8392
+ );
8393
+ });
7982
8394
  var AVATAR = 28;
7983
- var styles12 = import_react_native18.StyleSheet.create({
8395
+ var styles13 = import_react_native19.StyleSheet.create({
7984
8396
  row: { paddingHorizontal: 12 },
7985
8397
  day: {
7986
8398
  alignSelf: "center",
@@ -8001,34 +8413,35 @@ var styles12 = import_react_native18.StyleSheet.create({
8001
8413
  avatar: { width: AVATAR },
8002
8414
  teamColumn: { flexShrink: 1, alignItems: "flex-start", gap: 4 },
8003
8415
  teamMeta: { marginLeft: AVATAR + 8 },
8004
- human: { fontSize: 13, fontWeight: "600", textDecorationLine: "underline", paddingVertical: 8 },
8005
8416
  bubble: {
8006
8417
  borderRadius: RADII.group,
8007
8418
  paddingHorizontal: 14,
8008
8419
  paddingVertical: 10,
8009
- fontSize: 16,
8010
- lineHeight: 22,
8011
8420
  overflow: "hidden"
8012
- }
8421
+ },
8422
+ text: { fontSize: 16, lineHeight: 22 },
8423
+ // A reply with its quote: the quote above the text, inside the bubble.
8424
+ quoted: { gap: 6, paddingTop: 8, paddingHorizontal: 8 },
8425
+ quotedText: { paddingHorizontal: 6 }
8013
8426
  });
8014
8427
 
8015
8428
  // src/components/TypingBubble.tsx
8016
- var import_react13 = require("react");
8017
- var import_react_native19 = require("react-native");
8018
- var import_jsx_runtime15 = require("react/jsx-runtime");
8429
+ var import_react14 = require("react");
8430
+ var import_react_native20 = require("react-native");
8431
+ var import_jsx_runtime16 = require("react/jsx-runtime");
8019
8432
  function TypingBubble({ app, sender }) {
8020
8433
  const { t, colors } = useChatContext();
8021
8434
  const rise = useRiseIn(true);
8022
- const dots = (0, import_react13.useRef)([0, 1, 2].map(() => new import_react_native19.Animated.Value(0))).current;
8023
- (0, import_react13.useEffect)(() => {
8024
- const bounce = import_react_native19.Animated.loop(
8025
- import_react_native19.Animated.stagger(
8435
+ const dots = (0, import_react14.useRef)([0, 1, 2].map(() => new import_react_native20.Animated.Value(0))).current;
8436
+ (0, import_react14.useEffect)(() => {
8437
+ const bounce = import_react_native20.Animated.loop(
8438
+ import_react_native20.Animated.stagger(
8026
8439
  150,
8027
8440
  dots.map(
8028
- (dot) => import_react_native19.Animated.sequence([
8029
- import_react_native19.Animated.timing(dot, { toValue: 1, duration: 300, useNativeDriver: true }),
8030
- import_react_native19.Animated.timing(dot, { toValue: 0, duration: 300, useNativeDriver: true }),
8031
- import_react_native19.Animated.delay(300)
8441
+ (dot) => import_react_native20.Animated.sequence([
8442
+ import_react_native20.Animated.timing(dot, { toValue: 1, duration: 300, useNativeDriver: true }),
8443
+ import_react_native20.Animated.timing(dot, { toValue: 0, duration: 300, useNativeDriver: true }),
8444
+ import_react_native20.Animated.delay(300)
8032
8445
  ])
8033
8446
  )
8034
8447
  )
@@ -8036,13 +8449,13 @@ function TypingBubble({ app, sender }) {
8036
8449
  bounce.start();
8037
8450
  return () => bounce.stop();
8038
8451
  }, [dots]);
8039
- return /* @__PURE__ */ (0, import_jsx_runtime15.jsxs)(import_react_native19.Animated.View, { style: [styles13.row, rise], accessible: true, accessibilityLabel: format(t.typing, { name: sender?.name ?? t.team }), children: [
8040
- /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(TeamAvatar, { app, sender }),
8041
- /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(import_react_native19.View, { style: [styles13.bubble, { backgroundColor: colors.surface }], children: dots.map((dot, index) => /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(
8042
- import_react_native19.Animated.View,
8452
+ return /* @__PURE__ */ (0, import_jsx_runtime16.jsxs)(import_react_native20.Animated.View, { style: [styles14.row, rise], accessible: true, accessibilityLabel: format(t.typing, { name: sender?.name ?? t.team }), children: [
8453
+ /* @__PURE__ */ (0, import_jsx_runtime16.jsx)(TeamAvatar, { app, sender }),
8454
+ /* @__PURE__ */ (0, import_jsx_runtime16.jsx)(import_react_native20.View, { style: [styles14.bubble, { backgroundColor: colors.surface }], children: dots.map((dot, index) => /* @__PURE__ */ (0, import_jsx_runtime16.jsx)(
8455
+ import_react_native20.Animated.View,
8043
8456
  {
8044
8457
  style: [
8045
- styles13.dot,
8458
+ styles14.dot,
8046
8459
  {
8047
8460
  backgroundColor: colors.muted,
8048
8461
  opacity: dot.interpolate({ inputRange: [0, 1], outputRange: [0.35, 1] }),
@@ -8054,7 +8467,7 @@ function TypingBubble({ app, sender }) {
8054
8467
  )) })
8055
8468
  ] });
8056
8469
  }
8057
- var styles13 = import_react_native19.StyleSheet.create({
8470
+ var styles14 = import_react_native20.StyleSheet.create({
8058
8471
  row: { flexDirection: "row", alignItems: "flex-end", gap: 8, paddingHorizontal: 12, paddingTop: 14 },
8059
8472
  bubble: {
8060
8473
  flexDirection: "row",
@@ -8069,15 +8482,17 @@ var styles13 = import_react_native19.StyleSheet.create({
8069
8482
  });
8070
8483
 
8071
8484
  // src/components/MessageList.tsx
8072
- var import_jsx_runtime16 = require("react/jsx-runtime");
8485
+ var import_jsx_runtime17 = require("react/jsx-runtime");
8073
8486
  function MessageList({ state }) {
8074
8487
  const { chat: chat2, t, colors, openedAt } = useChatContext();
8075
- const listRef = (0, import_react14.useRef)(null);
8076
- const [scrolledUp, setScrolledUp] = (0, import_react14.useState)(false);
8488
+ const listRef = (0, import_react15.useRef)(null);
8489
+ const [scrolledUp, setScrolledUp] = (0, import_react15.useState)(false);
8490
+ const [highlighted, setHighlighted] = (0, import_react15.useState)(null);
8491
+ const [seeking, setSeeking] = (0, import_react15.useState)(null);
8077
8492
  const app = state.app;
8078
8493
  const { messages, seen, atStart } = state;
8079
8494
  const welcomeText = state.texts.welcome;
8080
- const rows = (0, import_react14.useMemo)(() => {
8495
+ const rows = (0, import_react15.useMemo)(() => {
8081
8496
  const welcome = atStart ? {
8082
8497
  id: "welcome",
8083
8498
  from: "team",
@@ -8086,65 +8501,95 @@ function MessageList({ state }) {
8086
8501
  attachments: [],
8087
8502
  createdAt: messages[0]?.createdAt ?? openedAt,
8088
8503
  status: "sent",
8089
- error: null
8504
+ error: null,
8505
+ replyTo: null
8090
8506
  } : null;
8091
8507
  return conversationRows(messages, seen, welcome).reverse();
8092
8508
  }, [messages, seen, atStart, welcomeText, openedAt]);
8093
8509
  const newest = rows.at(0)?.message;
8094
8510
  const sending = newest?.from === "contact" && newest.status === "sending" ? newest.id : null;
8095
- (0, import_react14.useEffect)(() => {
8511
+ (0, import_react15.useEffect)(() => {
8096
8512
  if (sending) listRef.current?.scrollToOffset({ offset: 0, animated: true });
8097
8513
  }, [sending]);
8098
- return /* @__PURE__ */ (0, import_jsx_runtime16.jsxs)(import_react_native20.View, { style: styles14.list, children: [
8099
- /* @__PURE__ */ (0, import_jsx_runtime16.jsx)(
8100
- import_react_native20.FlatList,
8514
+ (0, import_react15.useEffect)(() => {
8515
+ if (!highlighted) return;
8516
+ const timer = setTimeout(() => setHighlighted(null), QUOTE_HIGHLIGHT_MS);
8517
+ return () => clearTimeout(timer);
8518
+ }, [highlighted]);
8519
+ (0, import_react15.useEffect)(() => {
8520
+ if (!seeking) return;
8521
+ const step = quoteStepOf(state, seeking);
8522
+ if (step.kind === "older") chat2.loadOlder();
8523
+ if (step.kind === "older" || step.kind === "wait") return;
8524
+ setSeeking(null);
8525
+ if (step.kind === "none") return;
8526
+ const index = rows.findIndex((row) => row.message.id === step.id);
8527
+ listRef.current?.scrollToIndex({ index, animated: true, viewPosition: 0.5 });
8528
+ setHighlighted(step.id);
8529
+ }, [seeking, state, chat2, rows]);
8530
+ const handleQuote = (0, import_react15.useCallback)((replyId) => setSeeking(replyId), []);
8531
+ const handleRetry = (0, import_react15.useCallback)((messageId) => chat2.retry(messageId), [chat2]);
8532
+ const renderItem = (0, import_react15.useCallback)(
8533
+ ({ item }) => /* @__PURE__ */ (0, import_jsx_runtime17.jsx)(MessageBubble, { row: item, app, onRetry: handleRetry, onQuote: handleQuote, highlighted: highlighted === item.message.id }),
8534
+ [app, handleRetry, handleQuote, highlighted]
8535
+ );
8536
+ const handleScrollToIndexFailed = ({ index, averageItemLength }) => {
8537
+ listRef.current?.scrollToOffset({ offset: index * averageItemLength, animated: false });
8538
+ setTimeout(() => listRef.current?.scrollToIndex({ index, animated: true, viewPosition: 0.5 }), RETRY_SCROLL_MS);
8539
+ };
8540
+ return /* @__PURE__ */ (0, import_jsx_runtime17.jsxs)(import_react_native21.View, { style: styles15.list, children: [
8541
+ /* @__PURE__ */ (0, import_jsx_runtime17.jsx)(
8542
+ import_react_native21.FlatList,
8101
8543
  {
8102
8544
  ref: listRef,
8103
8545
  testID: "zean-conversation",
8104
8546
  inverted: true,
8105
8547
  data: rows,
8106
8548
  keyExtractor: (row) => row.message.id,
8107
- renderItem: ({ item }) => /* @__PURE__ */ (0, import_jsx_runtime16.jsx)(MessageBubble, { row: item, app, onRetry: () => chat2.retry(item.message.id) }),
8108
- ListHeaderComponent: /* @__PURE__ */ (0, import_jsx_runtime16.jsxs)(import_react_native20.View, { style: styles14.below, children: [
8109
- state.teamTyping && /* @__PURE__ */ (0, import_jsx_runtime16.jsx)(TypingBubble, { app, sender: state.teamTyping.sender }),
8110
- state.askEmail && /* @__PURE__ */ (0, import_jsx_runtime16.jsx)(EmailForm, { onSubmit: chat2.setEmail }),
8111
- state.email && (!state.online || state.emailGiven) && /* @__PURE__ */ (0, import_jsx_runtime16.jsx)(import_react_native20.Text, { style: [styles14.saved, { color: colors.muted }], children: format(t.email_saved, { email: state.email }) })
8549
+ extraData: highlighted,
8550
+ renderItem,
8551
+ onScrollToIndexFailed: handleScrollToIndexFailed,
8552
+ ListHeaderComponent: /* @__PURE__ */ (0, import_jsx_runtime17.jsxs)(import_react_native21.View, { style: styles15.below, children: [
8553
+ state.teamTyping && /* @__PURE__ */ (0, import_jsx_runtime17.jsx)(TypingBubble, { app, sender: state.teamTyping.sender }),
8554
+ state.askEmail && /* @__PURE__ */ (0, import_jsx_runtime17.jsx)(EmailForm, { onSubmit: chat2.setEmail }),
8555
+ state.email && (!state.online || state.emailGiven) && /* @__PURE__ */ (0, import_jsx_runtime17.jsx)(import_react_native21.Text, { style: [styles15.saved, { color: colors.muted }], children: format(t.email_saved, { email: state.email }) })
8112
8556
  ] }),
8113
- ListFooterComponent: state.hasOlder ? /* @__PURE__ */ (0, import_jsx_runtime16.jsx)(import_react_native20.View, { style: styles14.above, children: state.loadingOlder ? /* @__PURE__ */ (0, import_jsx_runtime16.jsx)(Skeleton, { style: [styles14.bone, styles14.olderBone] }) : /* @__PURE__ */ (0, import_jsx_runtime16.jsx)(
8114
- import_react_native20.Pressable,
8557
+ ListFooterComponent: state.hasOlder ? /* @__PURE__ */ (0, import_jsx_runtime17.jsx)(import_react_native21.View, { style: styles15.above, children: state.loadingOlder ? /* @__PURE__ */ (0, import_jsx_runtime17.jsx)(Skeleton, { style: [styles15.bone, styles15.olderBone] }) : /* @__PURE__ */ (0, import_jsx_runtime17.jsx)(
8558
+ import_react_native21.Pressable,
8115
8559
  {
8116
8560
  onPress: chat2.loadOlder,
8117
8561
  accessibilityRole: "button",
8118
- style: ({ pressed }) => [styles14.earlier, { backgroundColor: colors.surface }, pressed && styles14.pressed],
8119
- children: /* @__PURE__ */ (0, import_jsx_runtime16.jsx)(import_react_native20.Text, { style: [styles14.earlierText, { color: colors.muted }], children: t.earlier })
8562
+ style: ({ pressed }) => [styles15.earlier, { backgroundColor: colors.surface }, pressed && styles15.pressed],
8563
+ children: /* @__PURE__ */ (0, import_jsx_runtime17.jsx)(import_react_native21.Text, { style: [styles15.earlierText, { color: colors.muted }], children: t.earlier })
8120
8564
  }
8121
8565
  ) }) : void 0,
8122
8566
  onScroll: (event) => setScrolledUp(event.nativeEvent.contentOffset.y > NEWEST_BUTTON_OFFSET),
8123
8567
  scrollEventThrottle: 64,
8124
8568
  maintainVisibleContentPosition: scrolledUp ? { minIndexForVisible: 0 } : void 0,
8125
- contentContainerStyle: styles14.content,
8569
+ contentContainerStyle: styles15.content,
8126
8570
  keyboardShouldPersistTaps: "handled",
8127
8571
  keyboardDismissMode: "on-drag",
8128
- style: styles14.list
8572
+ style: styles15.list
8129
8573
  }
8130
8574
  ),
8131
- scrolledUp && /* @__PURE__ */ (0, import_jsx_runtime16.jsx)(
8132
- import_react_native20.Pressable,
8575
+ scrolledUp && /* @__PURE__ */ (0, import_jsx_runtime17.jsx)(
8576
+ import_react_native21.Pressable,
8133
8577
  {
8134
8578
  onPress: () => listRef.current?.scrollToOffset({ offset: 0, animated: true }),
8135
8579
  accessibilityRole: "button",
8136
8580
  accessibilityLabel: t.newest,
8137
8581
  style: ({ pressed }) => [
8138
- styles14.newest,
8582
+ styles15.newest,
8139
8583
  { backgroundColor: colors.surface, borderColor: colors.border },
8140
- pressed && styles14.pressed
8584
+ pressed && styles15.pressed
8141
8585
  ],
8142
- children: /* @__PURE__ */ (0, import_jsx_runtime16.jsx)(Icon, { name: "down", color: colors.text, size: 20 })
8586
+ children: /* @__PURE__ */ (0, import_jsx_runtime17.jsx)(Icon, { name: "down", color: colors.text, size: 20 })
8143
8587
  }
8144
8588
  )
8145
8589
  ] });
8146
8590
  }
8147
- var styles14 = import_react_native20.StyleSheet.create({
8591
+ var RETRY_SCROLL_MS = 250;
8592
+ var styles15 = import_react_native21.StyleSheet.create({
8148
8593
  list: { flex: 1 },
8149
8594
  // Inverted, `flex-end` is the top: a short Conversation starts under the header, as in the web widget.
8150
8595
  content: { flexGrow: 1, justifyContent: "flex-end", paddingBottom: 12, paddingTop: 4 },
@@ -8163,7 +8608,7 @@ var styles14 = import_react_native20.StyleSheet.create({
8163
8608
  width: COMPOSER_BUTTON,
8164
8609
  height: COMPOSER_BUTTON,
8165
8610
  borderRadius: COMPOSER_BUTTON / 2,
8166
- borderWidth: import_react_native20.StyleSheet.hairlineWidth,
8611
+ borderWidth: import_react_native21.StyleSheet.hairlineWidth,
8167
8612
  alignItems: "center",
8168
8613
  justifyContent: "center",
8169
8614
  shadowColor: "#000000",
@@ -8175,26 +8620,26 @@ var styles14 = import_react_native20.StyleSheet.create({
8175
8620
  });
8176
8621
 
8177
8622
  // src/components/PoweredBy.tsx
8178
- var import_react_native21 = require("react-native");
8179
- var import_jsx_runtime17 = require("react/jsx-runtime");
8623
+ var import_react_native22 = require("react-native");
8624
+ var import_jsx_runtime18 = require("react/jsx-runtime");
8180
8625
  function PoweredBy() {
8181
8626
  const { t, colors } = useChatContext();
8182
- return /* @__PURE__ */ (0, import_jsx_runtime17.jsxs)(
8183
- import_react_native21.Pressable,
8627
+ return /* @__PURE__ */ (0, import_jsx_runtime18.jsxs)(
8628
+ import_react_native22.Pressable,
8184
8629
  {
8185
- style: ({ pressed }) => [styles15.row, pressed && styles15.pressed],
8630
+ style: ({ pressed }) => [styles16.row, pressed && styles16.pressed],
8186
8631
  accessibilityRole: "link",
8187
8632
  accessibilityLabel: `${t.powered_by} ${APP_NAME}`,
8188
- onPress: () => void import_react_native21.Linking.openURL(APP_URL),
8633
+ onPress: () => void import_react_native22.Linking.openURL(APP_URL),
8189
8634
  children: [
8190
- /* @__PURE__ */ (0, import_jsx_runtime17.jsx)(import_react_native21.Text, { style: [styles15.text, { color: colors.muted }], children: t.powered_by }),
8191
- /* @__PURE__ */ (0, import_jsx_runtime17.jsx)(Icon, { name: "mark", color: ZEAN_ACCENT_HEX, size: 14 }),
8192
- /* @__PURE__ */ (0, import_jsx_runtime17.jsx)(import_react_native21.Text, { style: [styles15.text, styles15.name, { color: colors.muted }], children: APP_NAME })
8635
+ /* @__PURE__ */ (0, import_jsx_runtime18.jsx)(import_react_native22.Text, { style: [styles16.text, { color: colors.muted }], children: t.powered_by }),
8636
+ /* @__PURE__ */ (0, import_jsx_runtime18.jsx)(Icon, { name: "mark", color: ZEAN_ACCENT_HEX, size: 14 }),
8637
+ /* @__PURE__ */ (0, import_jsx_runtime18.jsx)(import_react_native22.Text, { style: [styles16.text, styles16.name, { color: colors.muted }], children: APP_NAME })
8193
8638
  ]
8194
8639
  }
8195
8640
  );
8196
8641
  }
8197
- var styles15 = import_react_native21.StyleSheet.create({
8642
+ var styles16 = import_react_native22.StyleSheet.create({
8198
8643
  row: { flexDirection: "row", alignItems: "center", justifyContent: "center", alignSelf: "center", gap: 4 },
8199
8644
  pressed: { opacity: 0.6 },
8200
8645
  text: { fontSize: 12 },
@@ -8202,46 +8647,49 @@ var styles15 = import_react_native21.StyleSheet.create({
8202
8647
  });
8203
8648
 
8204
8649
  // src/components/ChatScreen.tsx
8205
- var import_jsx_runtime18 = require("react/jsx-runtime");
8650
+ var import_jsx_runtime19 = require("react/jsx-runtime");
8206
8651
  function ChatScreen({ state, insets, onClose }) {
8207
8652
  const { chat: chat2, t, colors } = useChatContext();
8208
- const rootRef = (0, import_react15.useRef)(null);
8653
+ const rootRef = (0, import_react16.useRef)(null);
8209
8654
  const keyboard = useKeyboardOverlap(rootRef);
8210
8655
  const connectionLost = useConnectionLost(state.connected);
8211
8656
  const app = state.app;
8212
- return /* @__PURE__ */ (0, import_jsx_runtime18.jsxs)(import_react_native22.View, { ref: rootRef, style: [styles16.screen, { backgroundColor: colors.background, paddingBottom: keyboard }], children: [
8213
- /* @__PURE__ */ (0, import_jsx_runtime18.jsx)(ChatHeader, { app, online: state.online, topInset: insets.top, onClose }),
8214
- connectionLost && /* @__PURE__ */ (0, import_jsx_runtime18.jsx)(import_react_native22.View, { style: styles16.notice, children: /* @__PURE__ */ (0, import_jsx_runtime18.jsx)(ChatNotice, { children: t.reconnecting }) }),
8215
- /* @__PURE__ */ (0, import_jsx_runtime18.jsx)(MessageList, { state }),
8216
- /* @__PURE__ */ (0, import_jsx_runtime18.jsxs)(import_react_native22.View, { style: [styles16.footer, { paddingBottom: 8 + (keyboard > 0 ? 0 : insets.bottom) }], children: [
8217
- state.contactCode && state.status === "ready" && /* @__PURE__ */ (0, import_jsx_runtime18.jsx)(ContactCodeCard, { code: state.contactCode, onDismiss: chat2.dismissCode }),
8218
- state.status === "blocked" ? /* @__PURE__ */ (0, import_jsx_runtime18.jsx)(ChatNotice, { children: t.blocked }) : state.status === "unavailable" ? /* @__PURE__ */ (0, import_jsx_runtime18.jsx)(ChatNotice, { children: t.unavailable }) : /* @__PURE__ */ (0, import_jsx_runtime18.jsx)(Composer, {}),
8219
- app.showBadge && /* @__PURE__ */ (0, import_jsx_runtime18.jsx)(PoweredBy, {})
8657
+ return /* @__PURE__ */ (0, import_jsx_runtime19.jsxs)(import_react_native23.View, { ref: rootRef, style: [styles17.screen, { backgroundColor: colors.background, paddingBottom: keyboard }], children: [
8658
+ /* @__PURE__ */ (0, import_jsx_runtime19.jsx)(ChatHeader, { app, online: state.online, topInset: insets.top, onClose }),
8659
+ connectionLost && /* @__PURE__ */ (0, import_jsx_runtime19.jsx)(import_react_native23.View, { style: styles17.notice, children: /* @__PURE__ */ (0, import_jsx_runtime19.jsx)(ChatNotice, { children: t.reconnecting }) }),
8660
+ /* @__PURE__ */ (0, import_jsx_runtime19.jsx)(MessageList, { state }),
8661
+ /* @__PURE__ */ (0, import_jsx_runtime19.jsxs)(import_react_native23.View, { style: [styles17.footer, { paddingBottom: 8 + (keyboard > 0 ? 0 : insets.bottom) }], children: [
8662
+ state.contactCode && state.status === "ready" && /* @__PURE__ */ (0, import_jsx_runtime19.jsx)(ContactCodeCard, { code: state.contactCode, onDismiss: chat2.dismissCode }),
8663
+ state.status === "blocked" ? /* @__PURE__ */ (0, import_jsx_runtime19.jsx)(ChatNotice, { children: t.blocked }) : state.status === "unavailable" ? /* @__PURE__ */ (0, import_jsx_runtime19.jsx)(ChatNotice, { children: t.unavailable }) : (
8664
+ // Another person on the device starts it over: what it held was the previous one's.
8665
+ /* @__PURE__ */ (0, import_jsx_runtime19.jsx)(Composer, {}, state.personKey)
8666
+ ),
8667
+ app.showBadge && /* @__PURE__ */ (0, import_jsx_runtime19.jsx)(PoweredBy, {})
8220
8668
  ] })
8221
8669
  ] });
8222
8670
  }
8223
- var styles16 = import_react_native22.StyleSheet.create({
8671
+ var styles17 = import_react_native23.StyleSheet.create({
8224
8672
  screen: { flex: 1 },
8225
8673
  notice: { paddingHorizontal: 12, paddingTop: 12 },
8226
8674
  footer: { gap: 8, paddingHorizontal: 10, paddingTop: 6 }
8227
8675
  });
8228
8676
 
8229
8677
  // src/components/ChatModal.tsx
8230
- var import_jsx_runtime19 = require("react/jsx-runtime");
8678
+ var import_jsx_runtime20 = require("react/jsx-runtime");
8231
8679
  var STRINGS = { fr, en };
8232
8680
  function ChatModal({ chat: chat2, colorScheme, maxPhotos }) {
8233
- const state = (0, import_react16.useSyncExternalStore)(chat2.subscribe, chat2.getState);
8234
- const { open: open2 } = (0, import_react16.useSyncExternalStore)(subscribeChatView, chatView);
8235
- const deviceScheme = (0, import_react_native23.useColorScheme)();
8681
+ const state = (0, import_react17.useSyncExternalStore)(chat2.subscribe, chat2.getState);
8682
+ const { open: open2 } = (0, import_react17.useSyncExternalStore)(subscribeChatView, chatView);
8683
+ const deviceScheme = (0, import_react_native24.useColorScheme)();
8236
8684
  const scheme = colorScheme ?? (deviceScheme === "dark" ? "dark" : "light");
8237
8685
  const active = useAppActive();
8238
- const dimensions = (0, import_react_native23.useWindowDimensions)();
8239
- const [gallery, setGallery] = (0, import_react16.useState)(null);
8240
- const [openedAt, setOpenedAt] = (0, import_react16.useState)(Date.now);
8686
+ const dimensions = (0, import_react_native24.useWindowDimensions)();
8687
+ const [gallery, setGallery] = (0, import_react17.useState)(null);
8688
+ const [openedAt, setOpenedAt] = (0, import_react17.useState)(Date.now);
8241
8689
  const app = state.app;
8242
8690
  const visible = open2 && app !== null && state.status !== "loading" && state.status !== "hidden";
8243
8691
  const color = app?.color ?? ZEAN_ACCENT_HEX;
8244
- const context = (0, import_react16.useMemo)(
8692
+ const context = (0, import_react17.useMemo)(
8245
8693
  () => ({
8246
8694
  chat: chat2,
8247
8695
  t: STRINGS[state.locale],
@@ -8253,35 +8701,35 @@ function ChatModal({ chat: chat2, colorScheme, maxPhotos }) {
8253
8701
  }),
8254
8702
  [chat2, state.locale, color, scheme, openedAt, maxPhotos]
8255
8703
  );
8256
- const insets = (0, import_react16.useMemo)(screenInsets, [dimensions.width, dimensions.height]);
8257
- (0, import_react16.useEffect)(() => chat2.setOpen(open2 && active), [chat2, open2, active]);
8258
- (0, import_react16.useEffect)(() => {
8704
+ const insets = (0, import_react17.useMemo)(screenInsets, [dimensions.width, dimensions.height]);
8705
+ (0, import_react17.useEffect)(() => chat2.setOpen(open2 && active), [chat2, open2, active]);
8706
+ (0, import_react17.useEffect)(() => {
8259
8707
  if (visible && active && state.unread > 0) chat2.markRead();
8260
8708
  }, [chat2, visible, active, state.unread]);
8261
- (0, import_react16.useEffect)(() => {
8709
+ (0, import_react17.useEffect)(() => {
8262
8710
  if (visible) setOpenedAt(Date.now());
8263
8711
  else setGallery(null);
8264
8712
  }, [visible]);
8265
- return /* @__PURE__ */ (0, import_jsx_runtime19.jsx)(
8266
- import_react_native23.Modal,
8713
+ return /* @__PURE__ */ (0, import_jsx_runtime20.jsx)(
8714
+ import_react_native24.Modal,
8267
8715
  {
8268
8716
  testID: "zean-chat",
8269
8717
  visible,
8270
8718
  animationType: "slide",
8271
- presentationStyle: import_react_native23.Platform.OS === "ios" && !import_react_native23.Platform.isPad ? "pageSheet" : "fullScreen",
8719
+ presentationStyle: import_react_native24.Platform.OS === "ios" && !import_react_native24.Platform.isPad ? "pageSheet" : "fullScreen",
8272
8720
  statusBarTranslucent: true,
8273
8721
  navigationBarTranslucent: true,
8274
- onRequestClose: () => import_react_native23.Platform.OS === "android" && gallery ? setGallery(null) : zean.close(),
8275
- children: app && /* @__PURE__ */ (0, import_jsx_runtime19.jsxs)(ChatContext, { value: context, children: [
8276
- /* @__PURE__ */ (0, import_jsx_runtime19.jsx)(ChatScreen, { state, insets, onClose: zean.close }),
8277
- gallery && /* @__PURE__ */ (0, import_jsx_runtime19.jsx)(ImageViewer, { gallery, topInset: insets.top, onClose: () => setGallery(null) })
8722
+ onRequestClose: () => import_react_native24.Platform.OS === "android" && gallery ? setGallery(null) : zean.close(),
8723
+ children: app && /* @__PURE__ */ (0, import_jsx_runtime20.jsxs)(ChatContext, { value: context, children: [
8724
+ /* @__PURE__ */ (0, import_jsx_runtime20.jsx)(ChatScreen, { state, insets, onClose: zean.close }),
8725
+ gallery && /* @__PURE__ */ (0, import_jsx_runtime20.jsx)(ImageViewer, { gallery, topInset: insets.top, onClose: () => setGallery(null) })
8278
8726
  ] })
8279
8727
  }
8280
8728
  );
8281
8729
  }
8282
8730
 
8283
8731
  // src/components/ZeanChat.tsx
8284
- var import_jsx_runtime20 = require("react/jsx-runtime");
8732
+ var import_jsx_runtime21 = require("react/jsx-runtime");
8285
8733
  function ZeanChat({
8286
8734
  appKey,
8287
8735
  storage,
@@ -8292,12 +8740,12 @@ function ZeanChat({
8292
8740
  maxPhotos,
8293
8741
  backendUrl = backendUrlFor(appKey)
8294
8742
  }) {
8295
- const [chat2, setChat] = (0, import_react17.useState)(null);
8296
- const storageRef = (0, import_react17.useRef)(storage);
8743
+ const [chat2, setChat] = (0, import_react18.useState)(null);
8744
+ const storageRef = (0, import_react18.useRef)(storage);
8297
8745
  const userKey = user ? JSON.stringify(user) : null;
8298
- const identified = (0, import_react17.useRef)(false);
8746
+ const identified = (0, import_react18.useRef)(false);
8299
8747
  const attributesKey = attributes2 ? JSON.stringify(attributes2) : null;
8300
- (0, import_react17.useEffect)(() => {
8748
+ (0, import_react18.useEffect)(() => {
8301
8749
  const started = createChat({
8302
8750
  appKey,
8303
8751
  backendUrl,
@@ -8305,7 +8753,8 @@ function ZeanChat({
8305
8753
  // A chosen language goes first: the chat takes the first one it speaks.
8306
8754
  languages: locale ? [locale] : deviceLanguages(),
8307
8755
  deviceLanguage: deviceLanguages()[0],
8308
- os: deviceOs(),
8756
+ // Read again each time the chat tells the backend about the device.
8757
+ deviceDetails,
8309
8758
  // Checked against the App's Bundle ID or Package name: another app with the same key shows no chat.
8310
8759
  bundle: appBundle(),
8311
8760
  // The Conversation stays on the phone: the next start shows it at once and asks only for newer messages.
@@ -8320,20 +8769,20 @@ function ZeanChat({
8320
8769
  started.destroy();
8321
8770
  };
8322
8771
  }, [appKey, backendUrl, locale]);
8323
- (0, import_react17.useEffect)(() => {
8772
+ (0, import_react18.useEffect)(() => {
8324
8773
  if (userKey) zean.identify(JSON.parse(userKey));
8325
8774
  else if (identified.current) zean.signOut();
8326
8775
  identified.current = userKey !== null;
8327
8776
  }, [userKey]);
8328
- (0, import_react17.useEffect)(() => {
8777
+ (0, import_react18.useEffect)(() => {
8329
8778
  if (attributesKey) zean.setAttributes(JSON.parse(attributesKey));
8330
- }, [attributesKey]);
8331
- return chat2 ? /* @__PURE__ */ (0, import_jsx_runtime20.jsx)(ChatModal, { chat: chat2, colorScheme, maxPhotos }) : null;
8779
+ }, [attributesKey, userKey]);
8780
+ return chat2 ? /* @__PURE__ */ (0, import_jsx_runtime21.jsx)(ChatModal, { chat: chat2, colorScheme, maxPhotos }) : null;
8332
8781
  }
8333
8782
 
8334
8783
  // src/hooks/use-zean.ts
8335
- var import_react18 = require("react");
8784
+ var import_react19 = require("react");
8336
8785
  function useZean() {
8337
- const { unread } = (0, import_react18.useSyncExternalStore)(subscribeChatView, chatView);
8786
+ const { unread } = (0, import_react19.useSyncExternalStore)(subscribeChatView, chatView);
8338
8787
  return { ...zean, unreadCount: unread };
8339
8788
  }