@poolse/react-ui 3.5.0 → 3.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  'use client';
2
- import { forwardRef, useState, useRef, useCallback, useImperativeHandle, useEffect, useMemo, createContext, Fragment as Fragment$1, useContext } from 'react';
2
+ import { forwardRef, useState, useId, useReducer, useRef, useEffect, useImperativeHandle, useCallback, useMemo, createContext, Fragment as Fragment$1, useLayoutEffect, useContext } from 'react';
3
3
  import { jsxs, jsx, Fragment } from 'react/jsx-runtime';
4
- import { useMembers, useAttachmentUpload, useMe, useConversations, useUser, useConversation, usePresence, useMessages, useTyping, useMessageStreams, useRealtimeStatus, isMessageVisibleTo, receiptsOf, computeGroupPosition, sameDay, formatDayLabel, formatCallLogPreview, useLiveCall, canEditOwnMessage, callLogDisplayFor, useThread, useReactions, useAttachmentUrl } from '@poolse/react';
4
+ import { usePoolse, useMembers, useUser, useMe, useConversations, useAttachmentUpload, useConversation, usePresence, useUserPresence, useMessages, useTyping, useMessageStreams, useRealtimeStatus, isMessageVisibleTo, receiptsOf, computeGroupPosition, sameDay, formatDayLabel, useLiveCall, canEditOwnMessage, callLogDisplayFor, useThread, usePresenceMany, formatCallLogPreview, useReactions, useAttachmentUrl, ApiError } from '@poolse/react';
5
5
  import ReactMarkdown from 'react-markdown';
6
6
  import remarkGfm from 'remark-gfm';
7
7
  import { resolveTheme, tokensToCssVariables } from '@poolse/theme';
@@ -747,6 +747,85 @@ function PoolseFonts() {
747
747
  return null;
748
748
  }
749
749
 
750
+ // src/drafts.ts
751
+ var localDraftStorage = {
752
+ get: (key) => {
753
+ try {
754
+ return globalThis.localStorage?.getItem(key) ?? null;
755
+ } catch {
756
+ return null;
757
+ }
758
+ },
759
+ set: (key, value) => {
760
+ try {
761
+ globalThis.localStorage?.setItem(key, value);
762
+ } catch {
763
+ }
764
+ },
765
+ remove: (key) => {
766
+ try {
767
+ globalThis.localStorage?.removeItem(key);
768
+ } catch {
769
+ }
770
+ }
771
+ };
772
+ var memory = /* @__PURE__ */ new Map();
773
+ function draftKey(userId, conversationId) {
774
+ return `poolse:draft:${userId}:${conversationId}`;
775
+ }
776
+ var isEmpty = (d) => d.text.trim() === "" && !d.replyTo;
777
+ function readDraft(storage, key) {
778
+ const held = memory.get(key);
779
+ if (held) return held;
780
+ let raw;
781
+ try {
782
+ raw = storage.get(key);
783
+ } catch {
784
+ return null;
785
+ }
786
+ const hold = (d) => {
787
+ if (d && !memory.has(key)) memory.set(key, d);
788
+ return memory.get(key) ?? d;
789
+ };
790
+ if (raw instanceof Promise)
791
+ return raw.then(
792
+ (r) => hold(parse(r)),
793
+ () => null
794
+ );
795
+ return hold(parse(raw));
796
+ }
797
+ function writeDraft(storage, key, draft) {
798
+ if (isEmpty(draft)) {
799
+ clearDraft(storage, key);
800
+ return;
801
+ }
802
+ memory.set(key, draft);
803
+ const value = JSON.stringify({ v: 1, text: draft.text, replyTo: draft.replyTo });
804
+ try {
805
+ void Promise.resolve(storage.set(key, value)).catch(() => void 0);
806
+ } catch {
807
+ }
808
+ }
809
+ function clearDraft(storage, key) {
810
+ memory.delete(key);
811
+ try {
812
+ void Promise.resolve(storage.remove(key)).catch(() => void 0);
813
+ } catch {
814
+ }
815
+ }
816
+ function parse(raw) {
817
+ if (!raw) return null;
818
+ try {
819
+ const v = JSON.parse(raw);
820
+ const text = typeof v.text === "string" ? v.text : "";
821
+ const replyTo = v.replyTo && typeof v.replyTo === "object" && typeof v.replyTo.id === "string" ? v.replyTo : null;
822
+ const draft = { text, replyTo };
823
+ return isEmpty(draft) ? null : draft;
824
+ } catch {
825
+ return null;
826
+ }
827
+ }
828
+
750
829
  // src/layout.ts
751
830
  function formatMessageTime(iso, format) {
752
831
  if (!iso) return "";
@@ -791,6 +870,488 @@ function LiveCallBanner({ call, inCall, onJoin }) {
791
870
  /* @__PURE__ */ jsx("button", { type: "button", className: "poolse-live-call__join", onClick: () => onJoin(call), children: "Join" })
792
871
  ] });
793
872
  }
873
+ function formatRelativeTime(iso, now = Date.now()) {
874
+ if (!iso) return "";
875
+ const then = new Date(iso).getTime();
876
+ if (Number.isNaN(then)) return "";
877
+ const sec = Math.max(0, Math.floor((now - then) / 1e3));
878
+ if (sec < 60) return "just now";
879
+ if (sec < 3600) return `${Math.floor(sec / 60)}m ago`;
880
+ if (sec < 86400) return `${Math.floor(sec / 3600)}h ago`;
881
+ const days = Math.floor(sec / 86400);
882
+ if (days === 1) return "yesterday";
883
+ if (days < 7) return `${days}d ago`;
884
+ const date = new Date(then);
885
+ const sameYear = date.getFullYear() === new Date(now).getFullYear();
886
+ return date.toLocaleDateString(void 0, {
887
+ month: "short",
888
+ day: "numeric",
889
+ ...sameYear ? {} : { year: "numeric" }
890
+ });
891
+ }
892
+ function useNow(intervalMs = 6e4) {
893
+ const [now, setNow] = useState(() => Date.now());
894
+ useEffect(() => {
895
+ const t = setInterval(() => setNow(Date.now()), intervalMs);
896
+ return () => clearInterval(t);
897
+ }, [intervalMs]);
898
+ return now;
899
+ }
900
+ function PresenceBadge({
901
+ state,
902
+ doNotDisturb = false,
903
+ size = "md",
904
+ className
905
+ }) {
906
+ if (!state || state === "offline") return null;
907
+ const kind = doNotDisturb ? "dnd" : state;
908
+ const label = doNotDisturb ? "Do not disturb" : presenceStateLabel(state);
909
+ return /* @__PURE__ */ jsx(
910
+ "span",
911
+ {
912
+ className: [
913
+ "poolse-presence-badge",
914
+ `poolse-presence-badge--${kind}`,
915
+ `poolse-presence-badge--${size}`,
916
+ className
917
+ ].filter(Boolean).join(" "),
918
+ role: "img",
919
+ "aria-label": label,
920
+ title: label,
921
+ "data-presence": kind,
922
+ children: kind === "in_call" ? /* @__PURE__ */ jsx(PhoneGlyph, {}) : kind === "dnd" ? /* @__PURE__ */ jsx(MoonGlyph, {}) : null
923
+ }
924
+ );
925
+ }
926
+ function presenceStateLabel(state) {
927
+ switch (state) {
928
+ case "online":
929
+ return "Online";
930
+ case "away":
931
+ return "Away";
932
+ case "in_call":
933
+ return "In a call";
934
+ default:
935
+ return "Offline";
936
+ }
937
+ }
938
+ function presenceText(presence, now = Date.now()) {
939
+ if (!presence) return null;
940
+ if (presence.state === "offline") {
941
+ const ago = formatRelativeTime(presence.last_seen_at, now);
942
+ return ago ? `Last seen ${ago}` : "Offline";
943
+ }
944
+ return presenceStateLabel(presence.state);
945
+ }
946
+ function PhoneGlyph() {
947
+ return /* @__PURE__ */ jsx("svg", { viewBox: "0 0 24 24", "aria-hidden": "true", focusable: "false", children: /* @__PURE__ */ jsx(
948
+ "path",
949
+ {
950
+ fill: "currentColor",
951
+ d: "M6.6 10.8a15.1 15.1 0 0 0 6.6 6.6l2.2-2.2a1 1 0 0 1 1-.25 11.4 11.4 0 0 0 3.6.57 1 1 0 0 1 1 1V20a1 1 0 0 1-1 1A17 17 0 0 1 3 4a1 1 0 0 1 1-1h3.5a1 1 0 0 1 1 1c0 1.25.2 2.45.57 3.57a1 1 0 0 1-.25 1z"
952
+ }
953
+ ) });
954
+ }
955
+ function MoonGlyph() {
956
+ return /* @__PURE__ */ jsx("svg", { viewBox: "0 0 24 24", "aria-hidden": "true", focusable: "false", children: /* @__PURE__ */ jsx("path", { fill: "currentColor", d: "M20.5 14.6A8.6 8.6 0 0 1 9.4 3.5a8.6 8.6 0 1 0 11.1 11.1z" }) });
957
+ }
958
+ function Avatar({
959
+ src,
960
+ name,
961
+ online,
962
+ presence,
963
+ userId,
964
+ size = "md",
965
+ className
966
+ }) {
967
+ const initials = computeInitials(name);
968
+ const classes = ["poolse-avatar", size !== "md" ? `poolse-avatar--${size}` : null, className].filter(Boolean).join(" ");
969
+ const badge = presence === true ? userId ? /* @__PURE__ */ jsx(LivePresenceBadge, { userId, size }) : null : presence ? typeof presence === "string" ? /* @__PURE__ */ jsx(PresenceBadge, { state: presence, size, className: "poolse-avatar__badge" }) : /* @__PURE__ */ jsx(
970
+ PresenceBadge,
971
+ {
972
+ state: presence.state,
973
+ doNotDisturb: !!presence.do_not_disturb,
974
+ size,
975
+ className: "poolse-avatar__badge"
976
+ }
977
+ ) : online ? /* @__PURE__ */ jsx("span", { className: "poolse-avatar__presence", "aria-hidden": "true" }) : null;
978
+ return /* @__PURE__ */ jsxs("span", { className: classes, "aria-label": name ?? "avatar", role: "img", children: [
979
+ src ? /* @__PURE__ */ jsx("img", { src, alt: name ?? "" }) : /* @__PURE__ */ jsx("span", { "aria-hidden": "true", children: initials }),
980
+ badge
981
+ ] });
982
+ }
983
+ function LivePresenceBadge({ userId, size }) {
984
+ const presence = useUserPresence(userId);
985
+ if (!presence) return null;
986
+ return /* @__PURE__ */ jsx(
987
+ PresenceBadge,
988
+ {
989
+ state: presence.state,
990
+ doNotDisturb: !!presence.do_not_disturb,
991
+ ...size ? { size } : {},
992
+ className: "poolse-avatar__badge"
993
+ }
994
+ );
995
+ }
996
+ function computeInitials(name) {
997
+ if (!name) return "?";
998
+ const parts = name.trim().split(/\s+/).slice(0, 2);
999
+ return parts.map((p) => p.charAt(0).toUpperCase()).join("").slice(0, 2) || "?";
1000
+ }
1001
+ var RECENT_KEY = "poolse:recent-emoji";
1002
+ var RECENT_MAX = 24;
1003
+ var SEARCH_MAX = 120;
1004
+ var COLUMNS = 8;
1005
+ var dataPromise = null;
1006
+ var loadedData = null;
1007
+ function loadEmojiData() {
1008
+ dataPromise ??= import('./emojiData-DAL22PO7.js').then((m) => {
1009
+ loadedData = m.EMOJI_CATEGORIES;
1010
+ return loadedData;
1011
+ });
1012
+ return dataPromise;
1013
+ }
1014
+ var recentMemory = null;
1015
+ function readRecent() {
1016
+ if (recentMemory) return recentMemory;
1017
+ try {
1018
+ const raw = globalThis.localStorage?.getItem(RECENT_KEY);
1019
+ const parsed = raw ? JSON.parse(raw) : [];
1020
+ recentMemory = Array.isArray(parsed) ? parsed.filter((e) => typeof e === "string").slice(0, RECENT_MAX) : [];
1021
+ } catch {
1022
+ recentMemory = [];
1023
+ }
1024
+ return recentMemory;
1025
+ }
1026
+ function rememberEmoji(emoji) {
1027
+ const next = [emoji, ...readRecent().filter((e) => e !== emoji)].slice(0, RECENT_MAX);
1028
+ recentMemory = next;
1029
+ try {
1030
+ globalThis.localStorage?.setItem(RECENT_KEY, JSON.stringify(next));
1031
+ } catch {
1032
+ }
1033
+ }
1034
+ function EmojiPicker({ onPick, onClose, autoFocus = true, className }) {
1035
+ const [data, setData] = useState(loadedData);
1036
+ const [query, setQuery] = useState("");
1037
+ const [recent] = useState(readRecent);
1038
+ const rootRef = useRef(null);
1039
+ const searchRef = useRef(null);
1040
+ const gridRef = useRef(null);
1041
+ useEffect(() => {
1042
+ if (data) return;
1043
+ let live = true;
1044
+ void loadEmojiData().then((d) => {
1045
+ if (live) setData(d);
1046
+ });
1047
+ return () => {
1048
+ live = false;
1049
+ };
1050
+ }, [data]);
1051
+ useEffect(() => {
1052
+ if (autoFocus) searchRef.current?.focus();
1053
+ }, [autoFocus]);
1054
+ useEffect(() => {
1055
+ if (!onClose) return;
1056
+ const onPointer = (e) => {
1057
+ const t = e.target;
1058
+ if (t instanceof Node && rootRef.current && !rootRef.current.contains(t)) onClose();
1059
+ };
1060
+ document.addEventListener("pointerdown", onPointer, true);
1061
+ return () => document.removeEventListener("pointerdown", onPointer, true);
1062
+ }, [onClose]);
1063
+ const results = useMemo(() => {
1064
+ const q = query.trim().toLowerCase();
1065
+ if (!q || !data) return null;
1066
+ const words = q.split(/\s+/);
1067
+ const out = [];
1068
+ for (const cat of data) {
1069
+ for (const [emoji, keywords] of cat.emojis) {
1070
+ if (words.every((w) => keywords.includes(w))) out.push(emoji);
1071
+ if (out.length >= SEARCH_MAX) return out;
1072
+ }
1073
+ }
1074
+ return out;
1075
+ }, [query, data]);
1076
+ const pick = (emoji) => {
1077
+ rememberEmoji(emoji);
1078
+ onPick(emoji);
1079
+ };
1080
+ const sections = data ? [
1081
+ ...recent.length > 0 ? [{ id: "recent", label: "Recently used", emojis: recent }] : [],
1082
+ ...data.map((c) => ({ id: c.id, label: c.label, emojis: c.emojis.map(([e]) => e) }))
1083
+ ] : [];
1084
+ const jumpTo = (id) => {
1085
+ const el = gridRef.current?.querySelector(`[data-emoji-section="${id}"]`);
1086
+ if (el instanceof HTMLElement) {
1087
+ const grid = gridRef.current;
1088
+ grid.scrollTop = el.offsetTop - grid.offsetTop;
1089
+ }
1090
+ };
1091
+ const onGridKey = (e) => {
1092
+ const keys = {
1093
+ ArrowRight: 1,
1094
+ ArrowLeft: -1,
1095
+ ArrowDown: COLUMNS,
1096
+ ArrowUp: -COLUMNS
1097
+ };
1098
+ const step = keys[e.key];
1099
+ if (step === void 0) return;
1100
+ const buttons = Array.from(
1101
+ gridRef.current?.querySelectorAll(".poolse-emoji-picker__emoji") ?? []
1102
+ );
1103
+ const idx = buttons.findIndex((b) => b === document.activeElement);
1104
+ if (idx === -1) return;
1105
+ const next = buttons[idx + step];
1106
+ if (next) {
1107
+ next.focus();
1108
+ e.preventDefault();
1109
+ } else if (step < 0) {
1110
+ searchRef.current?.focus();
1111
+ e.preventDefault();
1112
+ }
1113
+ };
1114
+ const onRootKey = (e) => {
1115
+ if (e.key === "Escape") {
1116
+ e.stopPropagation();
1117
+ e.preventDefault();
1118
+ onClose?.();
1119
+ }
1120
+ };
1121
+ const emojiButton = (emoji, key) => /* @__PURE__ */ jsx(
1122
+ "button",
1123
+ {
1124
+ type: "button",
1125
+ className: "poolse-emoji-picker__emoji",
1126
+ onClick: () => pick(emoji),
1127
+ "aria-label": emoji,
1128
+ children: emoji
1129
+ },
1130
+ key
1131
+ );
1132
+ return /* @__PURE__ */ jsxs(
1133
+ "div",
1134
+ {
1135
+ ref: rootRef,
1136
+ className: ["poolse-emoji-picker", className].filter(Boolean).join(" "),
1137
+ role: "dialog",
1138
+ "aria-label": "Emoji picker",
1139
+ onKeyDown: onRootKey,
1140
+ children: [
1141
+ /* @__PURE__ */ jsx(
1142
+ "input",
1143
+ {
1144
+ ref: searchRef,
1145
+ type: "search",
1146
+ className: "poolse-emoji-picker__search",
1147
+ placeholder: "Search emoji",
1148
+ "aria-label": "Search emoji",
1149
+ value: query,
1150
+ onChange: (e) => setQuery(e.target.value),
1151
+ onKeyDown: (e) => {
1152
+ if (e.key === "Enter") {
1153
+ e.preventDefault();
1154
+ const first = results?.[0];
1155
+ if (first) pick(first);
1156
+ }
1157
+ if (e.key === "ArrowDown") {
1158
+ e.preventDefault();
1159
+ gridRef.current?.querySelector(".poolse-emoji-picker__emoji")?.focus();
1160
+ }
1161
+ }
1162
+ }
1163
+ ),
1164
+ !results && data ? /* @__PURE__ */ jsx("div", { className: "poolse-emoji-picker__tabs", role: "toolbar", "aria-label": "Emoji categories", children: sections.map((s) => /* @__PURE__ */ jsx(
1165
+ "button",
1166
+ {
1167
+ type: "button",
1168
+ className: "poolse-emoji-picker__tab",
1169
+ "aria-label": s.label,
1170
+ title: s.label,
1171
+ onClick: () => jumpTo(s.id),
1172
+ children: s.id === "recent" ? "\u{1F558}" : s.emojis[0]
1173
+ },
1174
+ s.id
1175
+ )) }) : null,
1176
+ /* @__PURE__ */ jsx("div", { ref: gridRef, className: "poolse-emoji-picker__scroll", onKeyDown: onGridKey, children: !data ? /* @__PURE__ */ jsx("div", { className: "poolse-emoji-picker__empty", children: "Loading\u2026" }) : results ? results.length === 0 ? /* @__PURE__ */ jsx("div", { className: "poolse-emoji-picker__empty", children: "No emoji found" }) : /* @__PURE__ */ jsx("div", { className: "poolse-emoji-picker__grid", role: "group", "aria-label": "Search results", children: results.map((e, i) => emojiButton(e, `${i}-${e}`)) }) : sections.map((s) => /* @__PURE__ */ jsxs("section", { "data-emoji-section": s.id, "aria-label": s.label, children: [
1177
+ /* @__PURE__ */ jsx("div", { className: "poolse-emoji-picker__heading", children: s.label }),
1178
+ /* @__PURE__ */ jsx("div", { className: "poolse-emoji-picker__grid", children: s.emojis.map((e, i) => emojiButton(e, `${s.id}-${i}`)) })
1179
+ ] }, s.id)) })
1180
+ ]
1181
+ }
1182
+ );
1183
+ }
1184
+ function ComposerEmojiButton({
1185
+ disabled,
1186
+ onPick
1187
+ }) {
1188
+ const [open, setOpen] = useState(false);
1189
+ return /* @__PURE__ */ jsxs("div", { className: "poolse-composer__emoji", children: [
1190
+ /* @__PURE__ */ jsx(
1191
+ "button",
1192
+ {
1193
+ type: "button",
1194
+ className: "poolse-composer__attach poolse-composer__emoji-btn",
1195
+ onClick: () => setOpen((o) => !o),
1196
+ onPointerEnter: () => void loadEmojiData(),
1197
+ disabled,
1198
+ "aria-label": "Insert emoji",
1199
+ "aria-expanded": open,
1200
+ title: "Insert emoji",
1201
+ children: /* @__PURE__ */ jsx(PoolseIcon, { name: "emoji", size: 20, label: null })
1202
+ }
1203
+ ),
1204
+ open && /* @__PURE__ */ jsx("div", { className: "poolse-composer__emoji-popover", children: /* @__PURE__ */ jsx(
1205
+ EmojiPicker,
1206
+ {
1207
+ onPick: (emoji) => {
1208
+ setOpen(false);
1209
+ onPick(emoji);
1210
+ },
1211
+ onClose: () => setOpen(false)
1212
+ }
1213
+ ) })
1214
+ ] });
1215
+ }
1216
+ function insertAtCaret(value, text, ta) {
1217
+ const el = ta.current;
1218
+ const start = el?.selectionStart ?? value.length;
1219
+ const end = el?.selectionEnd ?? value.length;
1220
+ const next = value.slice(0, start) + text + value.slice(end);
1221
+ const caret = start + text.length;
1222
+ requestAnimationFrame(() => {
1223
+ const t = ta.current;
1224
+ if (!t) return;
1225
+ t.focus();
1226
+ t.setSelectionRange(caret, caret);
1227
+ });
1228
+ return next;
1229
+ }
1230
+ function attachmentProblem(file, rules) {
1231
+ if (rules.maxFileSize !== void 0 && file.size > rules.maxFileSize) {
1232
+ return `Larger than ${formatBytes(rules.maxFileSize)}`;
1233
+ }
1234
+ const accept = rules.acceptFileTypes;
1235
+ if (accept && accept.length > 0 && !accept.some((rule) => matchesType(file, rule))) {
1236
+ return "This file type isn't allowed";
1237
+ }
1238
+ return null;
1239
+ }
1240
+ function matchesType(file, rule) {
1241
+ const r = rule.trim().toLowerCase();
1242
+ if (!r) return false;
1243
+ if (r.startsWith(".")) return file.name.toLowerCase().endsWith(r);
1244
+ const type = (file.type || "").toLowerCase();
1245
+ if (r.endsWith("/*")) return type.startsWith(r.slice(0, -1));
1246
+ return type === r;
1247
+ }
1248
+ function formatBytes(n) {
1249
+ if (n >= 1024 * 1024 * 1024) return `${trim(n / (1024 * 1024 * 1024))} GB`;
1250
+ if (n >= 1024 * 1024) return `${trim(n / (1024 * 1024))} MB`;
1251
+ if (n >= 1024) return `${trim(n / 1024)} KB`;
1252
+ return `${n} B`;
1253
+ }
1254
+ function trim(x) {
1255
+ return x >= 10 ? String(Math.round(x)) : String(Math.round(x * 10) / 10);
1256
+ }
1257
+ var fileKey = (name, size, type) => `${name}\0${size}\0${type}`;
1258
+ function useComposerAttachments(enabled, rules) {
1259
+ const { queue, uploadAll, cancel, remove } = useAttachmentUpload();
1260
+ const [rejected, setRejected] = useState([]);
1261
+ const thumbs = useRef(/* @__PURE__ */ new Map());
1262
+ useEffect(() => {
1263
+ const map = thumbs.current;
1264
+ return () => {
1265
+ for (const url of map.values()) URL.revokeObjectURL?.(url);
1266
+ map.clear();
1267
+ };
1268
+ }, []);
1269
+ const rulesRef = useRef(rules);
1270
+ rulesRef.current = rules;
1271
+ const addFiles = useCallback(
1272
+ (files) => {
1273
+ if (!enabled || files.length === 0) return;
1274
+ const ok = [];
1275
+ const refused = [];
1276
+ for (const f of files) {
1277
+ const problem = attachmentProblem(f, rulesRef.current);
1278
+ if (problem) {
1279
+ refused.push({
1280
+ localId: `rejected-${Math.random().toString(36).slice(2)}`,
1281
+ filename: f.name,
1282
+ contentType: f.type || "application/octet-stream",
1283
+ byteSize: f.size,
1284
+ status: "error",
1285
+ loaded: 0,
1286
+ attachment: null,
1287
+ error: new Error(problem)
1288
+ });
1289
+ continue;
1290
+ }
1291
+ ok.push(f);
1292
+ if (f.type.startsWith("image/") && typeof URL.createObjectURL === "function") {
1293
+ const key = fileKey(f.name, f.size, f.type);
1294
+ if (!thumbs.current.has(key)) thumbs.current.set(key, URL.createObjectURL(f));
1295
+ }
1296
+ }
1297
+ if (refused.length > 0) setRejected((prev) => [...prev, ...refused]);
1298
+ if (ok.length === 0) return;
1299
+ void uploadAll(
1300
+ ok.map((f) => ({
1301
+ body: f,
1302
+ contentType: f.type || "application/octet-stream",
1303
+ byteSize: f.size,
1304
+ filename: f.name
1305
+ }))
1306
+ ).catch(() => {
1307
+ });
1308
+ },
1309
+ [enabled, uploadAll]
1310
+ );
1311
+ const dismiss = useCallback(
1312
+ (localId) => {
1313
+ if (localId.startsWith("rejected-")) {
1314
+ setRejected((prev) => prev.filter((it) => it.localId !== localId));
1315
+ } else {
1316
+ remove(localId);
1317
+ }
1318
+ },
1319
+ [remove]
1320
+ );
1321
+ const previewFor = useCallback(
1322
+ (item) => thumbs.current.get(fileKey(item.filename, item.byteSize, item.contentType)) ?? null,
1323
+ []
1324
+ );
1325
+ const onPaste = useCallback(
1326
+ (e) => {
1327
+ if (!enabled) return;
1328
+ const files = Array.from(e.clipboardData?.files ?? []);
1329
+ if (files.length === 0) return;
1330
+ e.preventDefault();
1331
+ addFiles(files);
1332
+ },
1333
+ [enabled, addFiles]
1334
+ );
1335
+ const live = queue.filter((it) => it.status !== "cancelled");
1336
+ return {
1337
+ queue,
1338
+ /** Every chip to show: staged uploads, then files refused before upload. */
1339
+ items: [...live, ...rejected],
1340
+ ready: queue.filter((it) => it.status === "ready"),
1341
+ uploading: queue.some((it) => it.status === "pending" || it.status === "uploading"),
1342
+ addFiles,
1343
+ cancel,
1344
+ /** Remove a chip (an upload or a refused file). */
1345
+ dismiss,
1346
+ remove,
1347
+ /** Clear the refused-file chips (after a send). */
1348
+ clearRejected: () => setRejected([]),
1349
+ previewFor,
1350
+ onPaste,
1351
+ /** For the file input's `accept`. */
1352
+ accept: rules.acceptFileTypes?.join(",") || void 0
1353
+ };
1354
+ }
794
1355
 
795
1356
  // src/listAutocomplete.ts
796
1357
  var UNORDERED_RE = /^(\s*)([-*+]) (.*)$/;
@@ -825,12 +1386,18 @@ ${indent}${nextMarker} `;
825
1386
  caret: caret + prefix.length
826
1387
  };
827
1388
  }
828
- function UploadQueueStrip({ items, onCancel, onDismiss }) {
1389
+ function UploadQueueStrip({
1390
+ items,
1391
+ onCancel,
1392
+ onDismiss,
1393
+ previewFor
1394
+ }) {
829
1395
  if (items.length === 0) return null;
830
1396
  return /* @__PURE__ */ jsx("div", { className: "poolse-upload-strip", role: "status", "aria-live": "polite", children: items.map((item) => /* @__PURE__ */ jsx(
831
1397
  UploadChip,
832
1398
  {
833
1399
  item,
1400
+ thumbnail: previewFor?.(item) ?? null,
834
1401
  onCancel: () => onCancel(item.localId),
835
1402
  onDismiss: () => onDismiss(item.localId)
836
1403
  },
@@ -839,6 +1406,7 @@ function UploadQueueStrip({ items, onCancel, onDismiss }) {
839
1406
  }
840
1407
  function UploadChip({
841
1408
  item,
1409
+ thumbnail,
842
1410
  onCancel,
843
1411
  onDismiss
844
1412
  }) {
@@ -852,7 +1420,7 @@ function UploadChip({
852
1420
  className: `poolse-upload-chip poolse-upload-chip--${item.status}`,
853
1421
  "data-status": item.status,
854
1422
  children: [
855
- /* @__PURE__ */ jsx("div", { className: "poolse-upload-chip__icon", "aria-hidden": "true", children: /* @__PURE__ */ jsx(PoolseIcon, { name: isReady ? "check" : "attachment", size: 18, label: null }) }),
1423
+ thumbnail && !isError ? /* @__PURE__ */ jsx("img", { className: "poolse-upload-chip__thumb", src: thumbnail, alt: "", "aria-hidden": "true" }) : /* @__PURE__ */ jsx("div", { className: "poolse-upload-chip__icon", "aria-hidden": "true", children: /* @__PURE__ */ jsx(PoolseIcon, { name: isReady ? "check" : "attachment", size: 18, label: null }) }),
856
1424
  /* @__PURE__ */ jsxs("div", { className: "poolse-upload-chip__body", children: [
857
1425
  /* @__PURE__ */ jsx("div", { className: "poolse-upload-chip__filename", title: item.filename, children: item.filename }),
858
1426
  isError ? /* @__PURE__ */ jsx("div", { className: "poolse-upload-chip__error", children: item.error?.message ?? "Upload failed" }) : isReady ? (
@@ -888,31 +1456,6 @@ function UploadChip({
888
1456
  }
889
1457
  );
890
1458
  }
891
- var MAX_NAME_CHARS = 24;
892
- function UserName({
893
- externalId,
894
- labelFor,
895
- emptyFallback = "Unknown",
896
- className
897
- }) {
898
- const { profile } = useUser(labelFor ? null : externalId);
899
- const name = resolveDisplayName(externalId, profile?.displayName, labelFor, emptyFallback);
900
- return /* @__PURE__ */ jsx("span", { className, children: truncate(name) });
901
- }
902
- function useDisplayName(externalId, labelFor, emptyFallback = "Unknown") {
903
- const { profile } = useUser(labelFor ? null : externalId);
904
- return resolveDisplayName(externalId, profile?.displayName, labelFor, emptyFallback);
905
- }
906
- function resolveDisplayName(externalId, resolved, labelFor, emptyFallback) {
907
- if (!externalId) return emptyFallback;
908
- if (labelFor) return labelFor(externalId);
909
- if (resolved) return resolved;
910
- return externalId;
911
- }
912
- function truncate(s) {
913
- if (s.length <= MAX_NAME_CHARS) return s;
914
- return s.slice(0, MAX_NAME_CHARS - 1) + "\u2026";
915
- }
916
1459
  function useAutogrow(ref, value) {
917
1460
  useEffect(() => {
918
1461
  const ta = ref.current;
@@ -921,6 +1464,7 @@ function useAutogrow(ref, value) {
921
1464
  ta.style.height = `${ta.scrollHeight}px`;
922
1465
  }, [ref, value]);
923
1466
  }
1467
+ var MAX_SUGGESTIONS = 8;
924
1468
  var MentionInput = forwardRef(
925
1469
  function MentionInput2({
926
1470
  conversationId,
@@ -931,52 +1475,83 @@ var MentionInput = forwardRef(
931
1475
  labelFor,
932
1476
  replyingTo,
933
1477
  onCancelReply,
934
- attachments = true
1478
+ attachments = true,
1479
+ emojiPicker = true,
1480
+ maxFileSize,
1481
+ acceptFileTypes,
1482
+ onValueChange
935
1483
  }, ref) {
1484
+ const chat = usePoolse();
936
1485
  const { members } = useMembers(conversationId);
937
1486
  const [value, setValue] = useState("");
938
1487
  const [sending, setSending] = useState(false);
939
1488
  const [mention, setMention] = useState(null);
940
1489
  const [activeIdx, setActiveIdx] = useState(0);
941
- const selectedMentions = useRef(/* @__PURE__ */ new Set());
1490
+ const menuId = useId();
1491
+ const [, bumpProfiles] = useReducer((n) => n + 1, 0);
1492
+ const selectedMentions = useRef(/* @__PURE__ */ new Map());
942
1493
  const taRef = useRef(null);
943
1494
  const fileInputRef = useRef(null);
944
1495
  useAutogrow(taRef, value);
945
- const { queue, uploadAll, cancel: cancelUpload, remove: removeUpload } = useAttachmentUpload();
946
- const visibleUploads = queue.filter((it) => it.status !== "cancelled");
947
- const readyCount = queue.filter((it) => it.status === "ready").length;
948
- const uploading = queue.some((it) => it.status === "pending" || it.status === "uploading");
949
- const addFiles = useCallback(
950
- (files) => {
951
- if (!attachments || files.length === 0) return;
952
- void uploadAll(
953
- files.map((f) => ({
954
- body: f,
955
- contentType: f.type || "application/octet-stream",
956
- byteSize: f.size,
957
- filename: f.name
958
- }))
959
- ).catch(() => {
960
- });
961
- },
962
- [attachments, uploadAll]
1496
+ const uploads = useComposerAttachments(attachments, {
1497
+ ...maxFileSize !== void 0 ? { maxFileSize } : {},
1498
+ ...acceptFileTypes ? { acceptFileTypes } : {}
1499
+ });
1500
+ const { addFiles, uploading } = uploads;
1501
+ const visibleUploads = uploads.items;
1502
+ const readyCount = uploads.ready.length;
1503
+ const valueRef = useRef(value);
1504
+ valueRef.current = value;
1505
+ const onValueChangeRef = useRef(onValueChange);
1506
+ onValueChangeRef.current = onValueChange;
1507
+ const reportedRef = useRef(value);
1508
+ useEffect(() => {
1509
+ if (reportedRef.current === value) return;
1510
+ reportedRef.current = value;
1511
+ onValueChangeRef.current?.(value);
1512
+ }, [value]);
1513
+ useImperativeHandle(
1514
+ ref,
1515
+ () => ({
1516
+ addFiles,
1517
+ getText: () => valueRef.current,
1518
+ setText: (text) => setValue(text),
1519
+ focus: () => taRef.current?.focus()
1520
+ }),
1521
+ [addFiles]
963
1522
  );
964
- useImperativeHandle(ref, () => ({ addFiles }), [addFiles]);
965
- const label = labelFor ?? ((id) => id);
966
- const filtered = mention ? members.filter(
967
- (m) => label(m.external_id).toLowerCase().includes(mention.query.toLowerCase())
968
- ) : [];
1523
+ const label = (id) => labelFor?.(id) ?? chat.users.peek(id)?.displayName ?? id;
1524
+ const meId = chat.me.peek()?.id ?? null;
1525
+ const menuOpen = mention !== null;
1526
+ useEffect(() => {
1527
+ if (!menuOpen || labelFor) return;
1528
+ let live = true;
1529
+ for (const m of members) {
1530
+ if (chat.users.peek(m.external_id) !== void 0) continue;
1531
+ void chat.users.get(m.external_id).then(() => {
1532
+ if (live) bumpProfiles();
1533
+ }).catch(() => void 0);
1534
+ }
1535
+ return () => {
1536
+ live = false;
1537
+ };
1538
+ }, [menuOpen, members, chat, labelFor]);
1539
+ const filtered = mention ? rankMembers(
1540
+ members.filter((m) => m.user_id !== meId),
1541
+ mention.query.toLowerCase(),
1542
+ label
1543
+ ).slice(0, MAX_SUGGESTIONS) : [];
969
1544
  useEffect(() => {
970
1545
  setActiveIdx(0);
971
1546
  }, [filtered.length, mention?.query]);
972
1547
  const submit = async () => {
973
1548
  const trimmed = value.trim();
974
- const ready = queue.filter((it) => it.status === "ready");
1549
+ const ready = uploads.ready;
975
1550
  const hasReady = ready.length > 0;
976
1551
  if (!trimmed && !hasReady || sending || uploading) return;
977
1552
  setSending(true);
978
1553
  try {
979
- const mentions = Array.from(selectedMentions.current);
1554
+ const mentions = [...selectedMentions.current].filter(([, name]) => trimmed.includes(`@${name}`)).map(([id]) => id);
980
1555
  await onSend({
981
1556
  body: trimmed,
982
1557
  ...mentions.length > 0 ? { mentions } : {},
@@ -984,8 +1559,9 @@ var MentionInput = forwardRef(
984
1559
  ...hasReady ? { attachment_ids: ready.map((it) => it.attachment.id) } : {}
985
1560
  });
986
1561
  setValue("");
987
- selectedMentions.current = /* @__PURE__ */ new Set();
988
- for (const it of ready) removeUpload(it.localId);
1562
+ selectedMentions.current = /* @__PURE__ */ new Map();
1563
+ for (const it of ready) uploads.remove(it.localId);
1564
+ uploads.clearRejected();
989
1565
  } finally {
990
1566
  setSending(false);
991
1567
  }
@@ -997,7 +1573,7 @@ var MentionInput = forwardRef(
997
1573
  const after = value.slice(mention.start + 1 + mention.query.length);
998
1574
  const inserted = `@${name} `;
999
1575
  const next = `${before}${inserted}${after}`;
1000
- selectedMentions.current.add(m.user_id);
1576
+ selectedMentions.current.set(m.user_id, name);
1001
1577
  setValue(next);
1002
1578
  setMention(null);
1003
1579
  requestAnimationFrame(() => {
@@ -1110,8 +1686,9 @@ var MentionInput = forwardRef(
1110
1686
  UploadQueueStrip,
1111
1687
  {
1112
1688
  items: visibleUploads,
1113
- onCancel: cancelUpload,
1114
- onDismiss: removeUpload
1689
+ onCancel: uploads.cancel,
1690
+ onDismiss: uploads.dismiss,
1691
+ previewFor: uploads.previewFor
1115
1692
  }
1116
1693
  ),
1117
1694
  /* @__PURE__ */ jsxs("div", { className: "poolse-composer__row", children: [
@@ -1122,6 +1699,7 @@ var MentionInput = forwardRef(
1122
1699
  ref: fileInputRef,
1123
1700
  type: "file",
1124
1701
  multiple: true,
1702
+ ...uploads.accept ? { accept: uploads.accept } : {},
1125
1703
  className: "poolse-attach-input",
1126
1704
  onChange: (e) => {
1127
1705
  const files = Array.from(e.target.files ?? []);
@@ -1152,14 +1730,22 @@ var MentionInput = forwardRef(
1152
1730
  value,
1153
1731
  onChange,
1154
1732
  onKeyDown,
1733
+ onPaste: uploads.onPaste,
1155
1734
  placeholder,
1156
1735
  disabled: disabled || sending,
1157
1736
  "aria-label": placeholder,
1158
1737
  role: "combobox",
1159
1738
  "aria-expanded": Boolean(mention && filtered.length > 0),
1160
- "aria-controls": "poolse-mention-menu",
1739
+ "aria-controls": menuId,
1161
1740
  "aria-autocomplete": "list",
1162
- ...mention && filtered.length > 0 ? { "aria-activedescendant": `poolse-mention-opt-${activeIdx}` } : {}
1741
+ ...mention && filtered.length > 0 ? { "aria-activedescendant": `${menuId}-opt-${activeIdx}` } : {}
1742
+ }
1743
+ ),
1744
+ emojiPicker && /* @__PURE__ */ jsx(
1745
+ ComposerEmojiButton,
1746
+ {
1747
+ disabled: disabled || sending,
1748
+ onPick: (emoji) => setValue((v) => insertAtCaret(v, emoji, taRef))
1163
1749
  }
1164
1750
  ),
1165
1751
  /* @__PURE__ */ jsx(
@@ -1174,38 +1760,46 @@ var MentionInput = forwardRef(
1174
1760
  }
1175
1761
  )
1176
1762
  ] }),
1177
- mention && filtered.length > 0 && /* @__PURE__ */ jsx(
1763
+ mention && filtered.length > 0 && /* @__PURE__ */ jsx("div", { id: menuId, className: "poolse-mention-menu", role: "listbox", "aria-label": "Members", children: filtered.map((m, i) => /* @__PURE__ */ jsx(
1178
1764
  "div",
1179
1765
  {
1180
- id: "poolse-mention-menu",
1181
- className: "poolse-mention-menu",
1182
- role: "listbox",
1183
- "aria-label": "Members",
1184
- children: filtered.map((m, i) => /* @__PURE__ */ jsxs(
1185
- "div",
1186
- {
1187
- id: `poolse-mention-opt-${i}`,
1188
- role: "option",
1189
- "aria-selected": i === activeIdx,
1190
- className: `poolse-mention-menu__item${i === activeIdx ? " poolse-mention-menu__item--active" : ""}`,
1191
- onMouseDown: (e) => {
1192
- e.preventDefault();
1193
- insertMention(m);
1194
- },
1195
- children: [
1196
- /* @__PURE__ */ jsx("span", { children: "@" }),
1197
- /* @__PURE__ */ jsx(UserName, { externalId: m.external_id, ...labelFor ? { labelFor } : {} })
1198
- ]
1199
- },
1200
- m.id
1201
- ))
1202
- }
1203
- )
1766
+ id: `${menuId}-opt-${i}`,
1767
+ role: "option",
1768
+ "aria-selected": i === activeIdx,
1769
+ className: `poolse-mention-menu__item${i === activeIdx ? " poolse-mention-menu__item--active" : ""}`,
1770
+ onMouseEnter: () => setActiveIdx(i),
1771
+ onMouseDown: (e) => {
1772
+ e.preventDefault();
1773
+ insertMention(m);
1774
+ },
1775
+ children: /* @__PURE__ */ jsx(MentionOption, { member: m, name: label(m.external_id) })
1776
+ },
1777
+ m.id
1778
+ )) })
1204
1779
  ]
1205
1780
  }
1206
1781
  );
1207
1782
  }
1208
1783
  );
1784
+ function MentionOption({ member, name }) {
1785
+ const { profile } = useUser(member.external_id);
1786
+ return /* @__PURE__ */ jsxs(Fragment, { children: [
1787
+ /* @__PURE__ */ jsx(Avatar, { src: profile?.avatarUrl ?? null, name, size: "xs" }),
1788
+ /* @__PURE__ */ jsx("span", { className: "poolse-mention-menu__name", children: name }),
1789
+ name !== member.external_id ? /* @__PURE__ */ jsx("span", { className: "poolse-mention-menu__handle", children: member.external_id }) : null
1790
+ ] });
1791
+ }
1792
+ function rankMembers(members, query, label) {
1793
+ const scored = [];
1794
+ for (const m of members) {
1795
+ const name = label(m.external_id).toLowerCase();
1796
+ const ext = m.external_id.toLowerCase();
1797
+ const score = query === "" ? 1 : name.startsWith(query) ? 3 : name.split(/\s+/).some((w) => w.startsWith(query)) ? 2 : name.includes(query) || ext.includes(query) ? 1 : 0;
1798
+ if (score > 0) scored.push({ m, score, name });
1799
+ }
1800
+ scored.sort((a, b) => b.score - a.score || a.name.localeCompare(b.name));
1801
+ return scored.map((s) => s.m);
1802
+ }
1209
1803
  var MessageComposer = forwardRef(
1210
1804
  function MessageComposer2({
1211
1805
  onSend,
@@ -1215,36 +1809,47 @@ var MessageComposer = forwardRef(
1215
1809
  replyingTo,
1216
1810
  onCancelReply,
1217
1811
  labelFor,
1218
- attachments = true
1812
+ attachments = true,
1813
+ emojiPicker = true,
1814
+ maxFileSize,
1815
+ acceptFileTypes,
1816
+ onValueChange
1219
1817
  }, ref) {
1220
1818
  const [value, setValue] = useState("");
1221
1819
  const [sending, setSending] = useState(false);
1222
1820
  const taRef = useRef(null);
1223
1821
  const fileInputRef = useRef(null);
1224
1822
  useAutogrow(taRef, value);
1225
- const { queue, uploadAll, cancel: cancelUpload, remove: removeUpload } = useAttachmentUpload();
1226
- const visibleUploads = queue.filter((it) => it.status !== "cancelled");
1227
- const readyCount = queue.filter((it) => it.status === "ready").length;
1228
- const uploading = queue.some((it) => it.status === "pending" || it.status === "uploading");
1229
- const addFiles = useCallback(
1230
- (files) => {
1231
- if (!attachments || files.length === 0) return;
1232
- void uploadAll(
1233
- files.map((f) => ({
1234
- body: f,
1235
- contentType: f.type || "application/octet-stream",
1236
- byteSize: f.size,
1237
- filename: f.name
1238
- }))
1239
- ).catch(() => {
1240
- });
1241
- },
1242
- [attachments, uploadAll]
1823
+ const uploads = useComposerAttachments(attachments, {
1824
+ ...maxFileSize !== void 0 ? { maxFileSize } : {},
1825
+ ...acceptFileTypes ? { acceptFileTypes } : {}
1826
+ });
1827
+ const { addFiles, uploading } = uploads;
1828
+ const visibleUploads = uploads.items;
1829
+ const readyCount = uploads.ready.length;
1830
+ const valueRef = useRef(value);
1831
+ valueRef.current = value;
1832
+ const onValueChangeRef = useRef(onValueChange);
1833
+ onValueChangeRef.current = onValueChange;
1834
+ const reportedRef = useRef(value);
1835
+ useEffect(() => {
1836
+ if (reportedRef.current === value) return;
1837
+ reportedRef.current = value;
1838
+ onValueChangeRef.current?.(value);
1839
+ }, [value]);
1840
+ useImperativeHandle(
1841
+ ref,
1842
+ () => ({
1843
+ addFiles,
1844
+ getText: () => valueRef.current,
1845
+ setText: (text) => setValue(text),
1846
+ focus: () => taRef.current?.focus()
1847
+ }),
1848
+ [addFiles]
1243
1849
  );
1244
- useImperativeHandle(ref, () => ({ addFiles }), [addFiles]);
1245
1850
  const submit = async () => {
1246
1851
  const trimmed = value.trim();
1247
- const ready = queue.filter((it) => it.status === "ready");
1852
+ const ready = uploads.ready;
1248
1853
  const hasReady = ready.length > 0;
1249
1854
  if (!trimmed && !hasReady || sending || uploading) return;
1250
1855
  const opts = {
@@ -1252,7 +1857,8 @@ var MessageComposer = forwardRef(
1252
1857
  ...hasReady ? { attachment_ids: ready.map((it) => it.attachment.id) } : {}
1253
1858
  };
1254
1859
  setValue("");
1255
- for (const it of ready) removeUpload(it.localId);
1860
+ for (const it of ready) uploads.remove(it.localId);
1861
+ uploads.clearRejected();
1256
1862
  setSending(true);
1257
1863
  try {
1258
1864
  await onSend(trimmed, Object.keys(opts).length > 0 ? opts : void 0);
@@ -1307,8 +1913,9 @@ var MessageComposer = forwardRef(
1307
1913
  UploadQueueStrip,
1308
1914
  {
1309
1915
  items: visibleUploads,
1310
- onCancel: cancelUpload,
1311
- onDismiss: removeUpload
1916
+ onCancel: uploads.cancel,
1917
+ onDismiss: uploads.dismiss,
1918
+ previewFor: uploads.previewFor
1312
1919
  }
1313
1920
  ),
1314
1921
  /* @__PURE__ */ jsxs("div", { className: "poolse-composer__row", children: [
@@ -1319,6 +1926,7 @@ var MessageComposer = forwardRef(
1319
1926
  ref: fileInputRef,
1320
1927
  type: "file",
1321
1928
  multiple: true,
1929
+ ...uploads.accept ? { accept: uploads.accept } : {},
1322
1930
  className: "poolse-attach-input",
1323
1931
  onChange: (e) => {
1324
1932
  const files = Array.from(e.target.files ?? []);
@@ -1349,11 +1957,19 @@ var MessageComposer = forwardRef(
1349
1957
  value,
1350
1958
  onChange,
1351
1959
  onKeyDown,
1960
+ onPaste: uploads.onPaste,
1352
1961
  placeholder,
1353
1962
  disabled: disabled || sending,
1354
1963
  "aria-label": placeholder
1355
1964
  }
1356
1965
  ),
1966
+ emojiPicker && /* @__PURE__ */ jsx(
1967
+ ComposerEmojiButton,
1968
+ {
1969
+ disabled: disabled || sending,
1970
+ onPick: (emoji) => setValue((v) => insertAtCaret(v, emoji, taRef))
1971
+ }
1972
+ ),
1357
1973
  /* @__PURE__ */ jsx(
1358
1974
  "button",
1359
1975
  {
@@ -1399,24 +2015,6 @@ function ReplyChip({
1399
2015
  )
1400
2016
  ] });
1401
2017
  }
1402
- function Avatar({ src, name, online, size = "md", className }) {
1403
- const initials = computeInitials(name);
1404
- const classes = [
1405
- "poolse-avatar",
1406
- size === "sm" ? "poolse-avatar--sm" : null,
1407
- size === "lg" ? "poolse-avatar--lg" : null,
1408
- className
1409
- ].filter(Boolean).join(" ");
1410
- return /* @__PURE__ */ jsxs("span", { className: classes, "aria-label": name ?? "avatar", role: "img", children: [
1411
- src ? /* @__PURE__ */ jsx("img", { src, alt: name ?? "" }) : /* @__PURE__ */ jsx("span", { "aria-hidden": "true", children: initials }),
1412
- online ? /* @__PURE__ */ jsx("span", { className: "poolse-avatar__presence", "aria-hidden": "true" }) : null
1413
- ] });
1414
- }
1415
- function computeInitials(name) {
1416
- if (!name) return "?";
1417
- const parts = name.trim().split(/\s+/).slice(0, 2);
1418
- return parts.map((p) => p.charAt(0).toUpperCase()).join("").slice(0, 2) || "?";
1419
- }
1420
2018
  function CallLogRow({ msg, meId, onCallBack }) {
1421
2019
  const display = callLogDisplayFor(msg, meId);
1422
2020
  if (!display) return null;
@@ -1538,7 +2136,7 @@ function AttachmentPreview({ attachment, onClick }) {
1538
2136
  ),
1539
2137
  /* @__PURE__ */ jsxs("div", { className: "poolse-attachment__file-body", children: [
1540
2138
  /* @__PURE__ */ jsx("div", { className: "poolse-attachment__file-name", children: filename }),
1541
- byteSize !== null && /* @__PURE__ */ jsx("div", { className: "poolse-attachment__file-meta", children: formatBytes(byteSize) })
2139
+ byteSize !== null && /* @__PURE__ */ jsx("div", { className: "poolse-attachment__file-meta", children: formatBytes2(byteSize) })
1542
2140
  ] }),
1543
2141
  /* @__PURE__ */ jsx(
1544
2142
  PoolseIcon,
@@ -1615,21 +2213,274 @@ function Lightbox({
1615
2213
  )
1616
2214
  ]
1617
2215
  }
1618
- );
2216
+ );
2217
+ }
2218
+ function guessContentType(url) {
2219
+ const m = url.match(/\.([a-z0-9]+)(?:\?|#|$)/i);
2220
+ if (!m) return "application/octet-stream";
2221
+ const ext = m[1].toLowerCase();
2222
+ const imageExts = /* @__PURE__ */ new Set(["png", "jpg", "jpeg", "gif", "webp", "avif", "svg"]);
2223
+ if (imageExts.has(ext)) return `image/${ext === "jpg" ? "jpeg" : ext}`;
2224
+ return "application/octet-stream";
2225
+ }
2226
+ function formatBytes2(n) {
2227
+ if (n < 1024) return `${n} B`;
2228
+ if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`;
2229
+ if (n < 1024 * 1024 * 1024) return `${(n / (1024 * 1024)).toFixed(1)} MB`;
2230
+ return `${(n / (1024 * 1024 * 1024)).toFixed(2)} GB`;
2231
+ }
2232
+ var POPOVER_WIDTH = 280;
2233
+ function EditedLabel({ messageId, label = "edited", className }) {
2234
+ const history = useEditHistory(messageId);
2235
+ return /* @__PURE__ */ jsxs(Fragment, { children: [
2236
+ history.label(label, className),
2237
+ history.popover
2238
+ ] });
2239
+ }
2240
+ function useEditHistory(messageId) {
2241
+ const chat = usePoolse();
2242
+ const [open, setOpen] = useState(false);
2243
+ const [forbidden, setForbidden] = useState(false);
2244
+ const [history, setHistory] = useState({ status: "idle" });
2245
+ const [position, setPosition] = useState(null);
2246
+ const buttonRef = useRef(null);
2247
+ const popoverRef = useRef(null);
2248
+ useEffect(() => {
2249
+ setOpen(false);
2250
+ setForbidden(false);
2251
+ setHistory({ status: "idle" });
2252
+ }, [messageId]);
2253
+ const load = () => {
2254
+ setHistory({ status: "loading" });
2255
+ chat.messages.edits(messageId).then((list) => setHistory({ status: "ready", edits: list.data })).catch((err) => {
2256
+ if (err instanceof ApiError && err.status === 403) {
2257
+ setForbidden(true);
2258
+ setOpen(false);
2259
+ return;
2260
+ }
2261
+ setHistory({ status: "error" });
2262
+ });
2263
+ };
2264
+ useLayoutEffect(() => {
2265
+ if (!open) return;
2266
+ const place = () => {
2267
+ const rect = buttonRef.current?.getBoundingClientRect();
2268
+ if (!rect) return;
2269
+ const vw = window.innerWidth || POPOVER_WIDTH + 16;
2270
+ const left = Math.max(8, Math.min(rect.right - POPOVER_WIDTH, vw - POPOVER_WIDTH - 8));
2271
+ const below = rect.top < 200;
2272
+ setPosition(
2273
+ below ? { position: "fixed", left, top: rect.bottom + 6 } : { position: "fixed", left, top: rect.top - 6, transform: "translateY(-100%)" }
2274
+ );
2275
+ };
2276
+ place();
2277
+ window.addEventListener("resize", place);
2278
+ return () => window.removeEventListener("resize", place);
2279
+ }, [open]);
2280
+ useEffect(() => {
2281
+ if (!open) return;
2282
+ const onDown = (e) => {
2283
+ const t = e.target;
2284
+ if (!(t instanceof Node)) return;
2285
+ if (popoverRef.current?.contains(t) || buttonRef.current?.contains(t)) return;
2286
+ setOpen(false);
2287
+ };
2288
+ const onKey = (e) => {
2289
+ if (e.key === "Escape") {
2290
+ setOpen(false);
2291
+ buttonRef.current?.focus();
2292
+ }
2293
+ };
2294
+ const onScroll = (e) => {
2295
+ if (e.target instanceof Node && popoverRef.current?.contains(e.target)) return;
2296
+ setOpen(false);
2297
+ };
2298
+ document.addEventListener("pointerdown", onDown, true);
2299
+ document.addEventListener("keydown", onKey);
2300
+ document.addEventListener("scroll", onScroll, true);
2301
+ return () => {
2302
+ document.removeEventListener("pointerdown", onDown, true);
2303
+ document.removeEventListener("keydown", onKey);
2304
+ document.removeEventListener("scroll", onScroll, true);
2305
+ };
2306
+ }, [open]);
2307
+ const label = (text = "edited", className) => forbidden ? /* @__PURE__ */ jsx("span", { className, children: text }) : /* @__PURE__ */ jsx(
2308
+ "button",
2309
+ {
2310
+ ref: buttonRef,
2311
+ type: "button",
2312
+ className: ["poolse-edited-label", className].filter(Boolean).join(" "),
2313
+ "aria-haspopup": "dialog",
2314
+ "aria-expanded": open,
2315
+ title: "Show edit history",
2316
+ onClick: (e) => {
2317
+ e.stopPropagation();
2318
+ const next = !open;
2319
+ setOpen(next);
2320
+ if (next && (history.status === "idle" || history.status === "error")) load();
2321
+ },
2322
+ children: text
2323
+ }
2324
+ );
2325
+ const popover = open ? /* @__PURE__ */ jsxs(
2326
+ "div",
2327
+ {
2328
+ ref: popoverRef,
2329
+ className: "poolse-edit-history",
2330
+ role: "dialog",
2331
+ "aria-label": "Edit history",
2332
+ style: position ?? { position: "fixed", visibility: "hidden" },
2333
+ onClick: (e) => e.stopPropagation(),
2334
+ children: [
2335
+ /* @__PURE__ */ jsx("div", { className: "poolse-edit-history__title", children: "Edit history" }),
2336
+ history.status === "loading" || history.status === "idle" ? /* @__PURE__ */ jsx("div", { className: "poolse-edit-history__empty", children: "Loading\u2026" }) : history.status === "error" ? /* @__PURE__ */ jsx("div", { className: "poolse-edit-history__empty", children: "Couldn't load the history." }) : history.edits.length === 0 ? /* @__PURE__ */ jsx("div", { className: "poolse-edit-history__empty", children: "No earlier versions." }) : /* @__PURE__ */ jsx("ol", { className: "poolse-edit-history__list", children: history.edits.map((v) => /* @__PURE__ */ jsxs("li", { className: "poolse-edit-history__item", children: [
2337
+ /* @__PURE__ */ jsxs("time", { className: "poolse-edit-history__time", dateTime: v.written_at, children: [
2338
+ v.version === 1 ? "Original \xB7 " : "",
2339
+ formatWhen(v.written_at)
2340
+ ] }),
2341
+ /* @__PURE__ */ jsx("div", { className: "poolse-edit-history__body", children: v.body ?? /* @__PURE__ */ jsx("em", { children: "(no text)" }) })
2342
+ ] }, v.version)) })
2343
+ ]
2344
+ }
2345
+ ) : null;
2346
+ return { label, popover };
2347
+ }
2348
+ function formatWhen(iso) {
2349
+ const d = new Date(iso);
2350
+ if (Number.isNaN(d.getTime())) return "";
2351
+ return d.toLocaleString(void 0, {
2352
+ month: "short",
2353
+ day: "numeric",
2354
+ hour: "2-digit",
2355
+ minute: "2-digit"
2356
+ });
2357
+ }
2358
+ function LinkPreviewCard({ preview, onRemove, className }) {
2359
+ const [imageFailed, setImageFailed] = useState(false);
2360
+ const [faviconFailed, setFaviconFailed] = useState(false);
2361
+ if (!isWebUrl(preview.url)) return null;
2362
+ const image = preview.image_url && isWebUrl(preview.image_url) && !imageFailed;
2363
+ const host = hostOf(preview.url);
2364
+ const remove = onRemove ? /* @__PURE__ */ jsx(
2365
+ "button",
2366
+ {
2367
+ type: "button",
2368
+ className: "poolse-link-preview__remove",
2369
+ "aria-label": "Remove preview",
2370
+ title: "Remove preview",
2371
+ onClick: (e) => {
2372
+ e.preventDefault();
2373
+ e.stopPropagation();
2374
+ onRemove();
2375
+ },
2376
+ children: /* @__PURE__ */ jsx(PoolseIcon, { name: "close", size: 12, label: null })
2377
+ }
2378
+ ) : null;
2379
+ if (preview.type === "image") {
2380
+ const src = preview.image_url && isWebUrl(preview.image_url) ? preview.image_url : preview.url;
2381
+ if (imageFailed) return null;
2382
+ return /* @__PURE__ */ jsxs(
2383
+ "div",
2384
+ {
2385
+ className: ["poolse-link-preview", "poolse-link-preview--image", className].filter(Boolean).join(" "),
2386
+ children: [
2387
+ /* @__PURE__ */ jsx("a", { href: preview.url, target: "_blank", rel: "noopener noreferrer nofollow", children: /* @__PURE__ */ jsx(
2388
+ "img",
2389
+ {
2390
+ className: "poolse-link-preview__picture",
2391
+ src,
2392
+ alt: preview.title ?? host,
2393
+ loading: "lazy",
2394
+ onError: () => setImageFailed(true)
2395
+ }
2396
+ ) }),
2397
+ remove
2398
+ ]
2399
+ }
2400
+ );
2401
+ }
2402
+ const site = preview.site_name || host;
2403
+ return /* @__PURE__ */ jsxs("div", { className: ["poolse-link-preview", className].filter(Boolean).join(" "), children: [
2404
+ /* @__PURE__ */ jsxs(
2405
+ "a",
2406
+ {
2407
+ className: "poolse-link-preview__link",
2408
+ href: preview.url,
2409
+ target: "_blank",
2410
+ rel: "noopener noreferrer nofollow",
2411
+ children: [
2412
+ image ? /* @__PURE__ */ jsx(
2413
+ "img",
2414
+ {
2415
+ className: "poolse-link-preview__image",
2416
+ src: preview.image_url,
2417
+ alt: "",
2418
+ loading: "lazy",
2419
+ onError: () => setImageFailed(true)
2420
+ }
2421
+ ) : null,
2422
+ /* @__PURE__ */ jsxs("span", { className: "poolse-link-preview__text", children: [
2423
+ /* @__PURE__ */ jsxs("span", { className: "poolse-link-preview__site", children: [
2424
+ preview.favicon_url && isWebUrl(preview.favicon_url) && !faviconFailed ? /* @__PURE__ */ jsx(
2425
+ "img",
2426
+ {
2427
+ className: "poolse-link-preview__favicon",
2428
+ src: preview.favicon_url,
2429
+ alt: "",
2430
+ loading: "lazy",
2431
+ onError: () => setFaviconFailed(true)
2432
+ }
2433
+ ) : null,
2434
+ /* @__PURE__ */ jsx("span", { children: site })
2435
+ ] }),
2436
+ preview.title ? /* @__PURE__ */ jsx("span", { className: "poolse-link-preview__title", children: preview.title }) : null,
2437
+ preview.description ? /* @__PURE__ */ jsx("span", { className: "poolse-link-preview__description", children: preview.description }) : null
2438
+ ] })
2439
+ ]
2440
+ }
2441
+ ),
2442
+ remove
2443
+ ] });
1619
2444
  }
1620
- function guessContentType(url) {
1621
- const m = url.match(/\.([a-z0-9]+)(?:\?|#|$)/i);
1622
- if (!m) return "application/octet-stream";
1623
- const ext = m[1].toLowerCase();
1624
- const imageExts = /* @__PURE__ */ new Set(["png", "jpg", "jpeg", "gif", "webp", "avif", "svg"]);
1625
- if (imageExts.has(ext)) return `image/${ext === "jpg" ? "jpeg" : ext}`;
1626
- return "application/octet-stream";
2445
+ function MessageLinkPreviews({
2446
+ message,
2447
+ canRemove
2448
+ }) {
2449
+ const chat = usePoolse();
2450
+ const [hidden, setHidden] = useState(() => /* @__PURE__ */ new Set());
2451
+ const previews = (message.link_previews ?? []).filter((p) => !hidden.has(p.url));
2452
+ if (message.deleted_at || previews.length === 0) return null;
2453
+ const remove = (url) => {
2454
+ setHidden((prev) => new Set(prev).add(url));
2455
+ void chat.messages.update(message.id, { remove_link_previews: [url] }).catch(() => {
2456
+ setHidden((prev) => {
2457
+ const next = new Set(prev);
2458
+ next.delete(url);
2459
+ return next;
2460
+ });
2461
+ });
2462
+ };
2463
+ return /* @__PURE__ */ jsx("div", { className: "poolse-link-previews", children: previews.map((p) => /* @__PURE__ */ jsx(
2464
+ LinkPreviewCard,
2465
+ {
2466
+ preview: p,
2467
+ ...canRemove ? { onRemove: () => remove(p.url) } : {}
2468
+ },
2469
+ p.url
2470
+ )) });
1627
2471
  }
1628
- function formatBytes(n) {
1629
- if (n < 1024) return `${n} B`;
1630
- if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`;
1631
- if (n < 1024 * 1024 * 1024) return `${(n / (1024 * 1024)).toFixed(1)} MB`;
1632
- return `${(n / (1024 * 1024 * 1024)).toFixed(2)} GB`;
2472
+ function hasLinkPreviews(message) {
2473
+ return !message.deleted_at && (message.link_previews?.length ?? 0) > 0;
2474
+ }
2475
+ function isWebUrl(url) {
2476
+ return /^https?:\/\//i.test(url);
2477
+ }
2478
+ function hostOf(url) {
2479
+ try {
2480
+ return new URL(url).hostname.replace(/^www\./, "");
2481
+ } catch {
2482
+ return url;
2483
+ }
1633
2484
  }
1634
2485
 
1635
2486
  // src/bubbleText.ts
@@ -1666,6 +2517,7 @@ function MessageBubble({
1666
2517
  actionsTrigger,
1667
2518
  showAttachments = true,
1668
2519
  timeFormat,
2520
+ linkPreviews = true,
1669
2521
  slots,
1670
2522
  slotContext
1671
2523
  }) {
@@ -1689,7 +2541,8 @@ function MessageBubble({
1689
2541
  const metaOverlay = hasAnyAttachment && imageAttachments.length > 0 && !hasVisibleBody && fileAttachments.length === 0;
1690
2542
  const jumboCount = hasVisibleBody && !hasAnyAttachment && !message.quoted_message_id ? emojiOnlyCount(rawBody) : 0;
1691
2543
  const trimToggleVisible = shouldTrim || expanded && rawBody.length > maxBodyLength + TRIM_BUFFER2;
1692
- const inlineMeta = hasVisibleBody && jumboCount === 0 && !trimToggleVisible && (!markdown || !hasMarkdown(displayBody));
2544
+ const showPreviews = linkPreviews && hasLinkPreviews(message);
2545
+ const inlineMeta = hasVisibleBody && !showPreviews && jumboCount === 0 && !trimToggleVisible && (!markdown || !hasMarkdown(displayBody));
1693
2546
  const className = [
1694
2547
  "poolse-message",
1695
2548
  isSelf ? "poolse-message--self" : "poolse-message--other",
@@ -1703,7 +2556,8 @@ function MessageBubble({
1703
2556
  jumboCount > 0 ? "poolse-message--jumbo" : ""
1704
2557
  ].filter(Boolean).join(" ");
1705
2558
  const time = formatMessageTime(message.inserted_at, timeFormat);
1706
- const showQuoteCard = message.quoted_message !== void 0 && message.quoted_message !== null ? "full" : message.quoted_message_id ? "placeholder" : null;
2559
+ const editHistory = useEditHistory(message.id);
2560
+ const showQuoteCard = message.deleted_at ? null : message.quoted_message !== void 0 && message.quoted_message !== null ? "full" : message.quoted_message_id ? "placeholder" : null;
1707
2561
  return /* @__PURE__ */ jsxs("div", { className, children: [
1708
2562
  actionsTrigger,
1709
2563
  renderSlot(
@@ -1739,9 +2593,12 @@ function MessageBubble({
1739
2593
  ] }) : null
1740
2594
  ),
1741
2595
  (() => {
1742
- const metaContent = /* @__PURE__ */ jsxs(Fragment, { children: [
2596
+ const metaParts = (interactive) => /* @__PURE__ */ jsxs(Fragment, { children: [
1743
2597
  /* @__PURE__ */ jsx("span", { children: time }),
1744
- message.edited_at && !message.deleted_at ? /* @__PURE__ */ jsx("span", { children: "\xB7 edited" }) : null,
2598
+ message.edited_at && !message.deleted_at ? /* @__PURE__ */ jsxs("span", { children: [
2599
+ "\xB7 ",
2600
+ interactive ? editHistory.label() : "edited"
2601
+ ] }) : null,
1745
2602
  isSelf && readState ? /* @__PURE__ */ jsx(
1746
2603
  PoolseIcon,
1747
2604
  {
@@ -1751,7 +2608,8 @@ function MessageBubble({
1751
2608
  }
1752
2609
  ) : null
1753
2610
  ] });
1754
- const body = message.deleted_at ? /* @__PURE__ */ jsx("span", { className: "poolse-message__body--deleted", children: "Message deleted" }) : hasVisibleBody ? /* @__PURE__ */ jsxs(
2611
+ const metaContent = metaParts(true);
2612
+ const body = message.deleted_at ? /* @__PURE__ */ jsx("span", { className: "poolse-message__body--deleted", children: "This message was deleted" }) : hasVisibleBody ? /* @__PURE__ */ jsxs(
1755
2613
  "div",
1756
2614
  {
1757
2615
  className: markdown && !inlineMeta && jumboCount === 0 ? "poolse-message__body poolse-message__body--md" : "poolse-message__body",
@@ -1781,7 +2639,7 @@ function MessageBubble({
1781
2639
  // overlaps a glyph — and when the line is full, the
1782
2640
  // reservation wraps and the meta drops a line, flush
1783
2641
  // right. The WhatsApp trick.
1784
- /* @__PURE__ */ jsx("span", { className: "poolse-message__meta poolse-message__meta--spacer", "aria-hidden": true, children: metaContent }),
2642
+ /* @__PURE__ */ jsx("span", { className: "poolse-message__meta poolse-message__meta--spacer", "aria-hidden": true, children: metaParts(false) }),
1785
2643
  shouldTrim && /* @__PURE__ */ jsx(
1786
2644
  "button",
1787
2645
  {
@@ -1812,7 +2670,9 @@ function MessageBubble({
1812
2670
  const metaClass = metaOverlay ? "poolse-message__meta poolse-message__meta--overlay" : inlineMeta ? "poolse-message__meta poolse-message__meta--inline" : "poolse-message__meta poolse-message__meta--block";
1813
2671
  return /* @__PURE__ */ jsxs(Fragment, { children: [
1814
2672
  renderSlot(slots?.body, slotContext, body),
1815
- /* @__PURE__ */ jsx("span", { className: metaClass, children: metaContent })
2673
+ showPreviews ? /* @__PURE__ */ jsx(MessageLinkPreviews, { message, canRemove: isSelf }) : null,
2674
+ /* @__PURE__ */ jsx("span", { className: metaClass, children: metaContent }),
2675
+ editHistory.popover
1816
2676
  ] });
1817
2677
  })()
1818
2678
  ] });
@@ -1872,7 +2732,7 @@ function QuotedCard({
1872
2732
  "button",
1873
2733
  {
1874
2734
  type: "button",
1875
- className: `poolse-quote ${isSelf ? "poolse-quote--self" : "poolse-quote--other"}`,
2735
+ className: `poolse-quote ${isSelf ? "poolse-quote--self" : "poolse-quote--other"}${isDeleted ? " poolse-quote--deleted" : ""}`,
1876
2736
  onClick: handleClick,
1877
2737
  disabled: !handleClick,
1878
2738
  "aria-label": `Quoted message from ${senderLabel}`,
@@ -2037,10 +2897,15 @@ function ReactionPicker({
2037
2897
  onClose
2038
2898
  }) {
2039
2899
  const rootRef = useRef(null);
2900
+ const [full, setFull] = useState(false);
2040
2901
  useEffect(() => {
2041
2902
  const firstBtn = rootRef.current?.querySelector("button");
2042
2903
  if (firstBtn instanceof HTMLElement) firstBtn.focus();
2043
2904
  }, []);
2905
+ const pick = (emoji) => {
2906
+ rememberEmoji(emoji);
2907
+ onPick(emoji);
2908
+ };
2044
2909
  useEffect(() => {
2045
2910
  if (!onClose) return;
2046
2911
  const onPointer = (e) => {
@@ -2069,7 +2934,10 @@ function ReactionPicker({
2069
2934
  e.preventDefault();
2070
2935
  }
2071
2936
  };
2072
- return /* @__PURE__ */ jsx(
2937
+ if (full) {
2938
+ return /* @__PURE__ */ jsx("div", { ref: rootRef, className: "poolse-reaction-picker poolse-reaction-picker--full", children: /* @__PURE__ */ jsx(EmojiPicker, { onPick: pick, ...onClose ? { onClose } : {} }) });
2939
+ }
2940
+ return /* @__PURE__ */ jsxs(
2073
2941
  "div",
2074
2942
  {
2075
2943
  ref: rootRef,
@@ -2077,18 +2945,34 @@ function ReactionPicker({
2077
2945
  role: "menu",
2078
2946
  "aria-label": "Pick a reaction",
2079
2947
  onKeyDown: onKey,
2080
- children: COMMON_EMOJIS.map((e) => /* @__PURE__ */ jsx(
2081
- "button",
2082
- {
2083
- type: "button",
2084
- role: "menuitem",
2085
- className: "poolse-reaction-picker__btn",
2086
- onClick: () => onPick(e),
2087
- "aria-label": `React with ${e}`,
2088
- children: e
2089
- },
2090
- e
2091
- ))
2948
+ children: [
2949
+ COMMON_EMOJIS.map((e) => /* @__PURE__ */ jsx(
2950
+ "button",
2951
+ {
2952
+ type: "button",
2953
+ role: "menuitem",
2954
+ className: "poolse-reaction-picker__btn",
2955
+ onClick: () => pick(e),
2956
+ "aria-label": `React with ${e}`,
2957
+ children: e
2958
+ },
2959
+ e
2960
+ )),
2961
+ /* @__PURE__ */ jsx(
2962
+ "button",
2963
+ {
2964
+ type: "button",
2965
+ role: "menuitem",
2966
+ className: "poolse-reaction-picker__btn poolse-reaction-picker__more",
2967
+ "aria-label": "More emoji",
2968
+ title: "More emoji",
2969
+ onPointerEnter: () => void loadEmojiData(),
2970
+ onFocus: () => void loadEmojiData(),
2971
+ onClick: () => setFull(true),
2972
+ children: /* @__PURE__ */ jsx(PoolseIcon, { name: "plus", size: 16, label: null })
2973
+ }
2974
+ )
2975
+ ]
2092
2976
  }
2093
2977
  );
2094
2978
  }
@@ -2097,6 +2981,7 @@ function MessageActions({
2097
2981
  onReply,
2098
2982
  onQuote,
2099
2983
  onCopy,
2984
+ onMarkUnread,
2100
2985
  onEdit,
2101
2986
  onDelete,
2102
2987
  moreMenu = false,
@@ -2104,7 +2989,7 @@ function MessageActions({
2104
2989
  }) {
2105
2990
  const [pickerOpen, setPickerOpen] = useState(false);
2106
2991
  const [menuOpen, setMenuOpen] = useState(false);
2107
- const hasMore = !!(onCopy || onEdit || onDelete);
2992
+ const hasMore = !!(onCopy || onMarkUnread || onEdit || onDelete);
2108
2993
  return /* @__PURE__ */ jsxs("div", { className: "poolse-msg-actions", role: "toolbar", "aria-label": "Message actions", children: [
2109
2994
  onReact && /* @__PURE__ */ jsxs(Fragment, { children: [
2110
2995
  /* @__PURE__ */ jsx(
@@ -2151,6 +3036,11 @@ function MessageActions({
2151
3036
  },
2152
3037
  children: [
2153
3038
  onCopy && { label: "Copy", icon: "copy", run: onCopy },
3039
+ onMarkUnread && {
3040
+ label: "Mark unread",
3041
+ icon: "message",
3042
+ run: onMarkUnread
3043
+ },
2154
3044
  onEdit && { label: "Edit", icon: "edit", run: onEdit },
2155
3045
  onDelete && { label: "Delete", icon: "trash", run: onDelete }
2156
3046
  ].filter((item) => !!item).map((item) => /* @__PURE__ */ jsxs(
@@ -2177,6 +3067,7 @@ function MessageActions({
2177
3067
  onReply && /* @__PURE__ */ jsx(ActionButton, { label: "Reply in thread", icon: "messages", onClick: onReply }),
2178
3068
  onQuote && /* @__PURE__ */ jsx(ActionButton, { label: "Reply", icon: "reply", onClick: onQuote }),
2179
3069
  onCopy && /* @__PURE__ */ jsx(ActionButton, { label: "Copy", icon: "copy", onClick: onCopy }),
3070
+ onMarkUnread && /* @__PURE__ */ jsx(ActionButton, { label: "Mark unread", icon: "message", onClick: onMarkUnread }),
2180
3071
  onEdit && /* @__PURE__ */ jsx(ActionButton, { label: "Edit", icon: "edit", onClick: onEdit }),
2181
3072
  onDelete && /* @__PURE__ */ jsx(ActionButton, { label: "Delete", icon: "trash", danger: true, onClick: onDelete }),
2182
3073
  children
@@ -2249,6 +3140,36 @@ function InlineReactions({
2249
3140
  );
2250
3141
  }) });
2251
3142
  }
3143
+ function ThreadSummary({ message, onOpen, maxAvatars = 3, className }) {
3144
+ const now = useNow();
3145
+ const count = message.reply_count ?? 0;
3146
+ if (count <= 0) return null;
3147
+ const participants = (message.thread_participants ?? []).slice(0, maxAvatars);
3148
+ const replies = `${count} ${count === 1 ? "reply" : "replies"}`;
3149
+ const last = formatRelativeTime(message.last_reply_at, now);
3150
+ return /* @__PURE__ */ jsxs(
3151
+ "button",
3152
+ {
3153
+ type: "button",
3154
+ className: ["poolse-thread-summary", className].filter(Boolean).join(" "),
3155
+ onClick: onOpen,
3156
+ "aria-label": `View ${replies}`,
3157
+ children: [
3158
+ participants.length > 0 ? /* @__PURE__ */ jsx("span", { className: "poolse-thread-summary__avatars", "aria-hidden": "true", children: participants.map((p) => /* @__PURE__ */ jsx(ParticipantAvatar, { participant: p }, p.user_id)) }) : /* @__PURE__ */ jsx(PoolseIcon, { name: "messages", size: 12, label: null }),
3159
+ /* @__PURE__ */ jsx("span", { className: "poolse-thread-summary__count", children: replies }),
3160
+ last ? /* @__PURE__ */ jsxs("span", { className: "poolse-thread-summary__last", children: [
3161
+ "\xB7 last reply ",
3162
+ last
3163
+ ] }) : null
3164
+ ]
3165
+ }
3166
+ );
3167
+ }
3168
+ function ParticipantAvatar({ participant }) {
3169
+ const { profile } = useUser(participant.external_id);
3170
+ const name = profile?.displayName ?? participant.external_id ?? "Someone";
3171
+ return /* @__PURE__ */ jsx(Avatar, { src: profile?.avatarUrl ?? null, name, size: "xs" });
3172
+ }
2252
3173
  var TRIM_BUFFER = 40;
2253
3174
  function FlatMessageRow({
2254
3175
  msg,
@@ -2267,12 +3188,15 @@ function FlatMessageRow({
2267
3188
  onDelete,
2268
3189
  onOpenThread,
2269
3190
  onQuote,
3191
+ onMarkUnread,
2270
3192
  labelFor,
2271
3193
  onQuotedClick,
2272
3194
  groupPosition = "standalone",
2273
3195
  maxBodyLength = 0,
2274
3196
  markdown = false,
2275
3197
  showAvatar = layout === "list",
3198
+ showPresence = false,
3199
+ linkPreviews = true,
2276
3200
  onSenderPress,
2277
3201
  onAvatarPress,
2278
3202
  timeFormat,
@@ -2300,10 +3224,19 @@ function FlatMessageRow({
2300
3224
  const deleted = !!msg.deleted_at;
2301
3225
  const time = formatMessageTime(msg.inserted_at, timeFormat);
2302
3226
  const replyCount = msg.reply_count ?? 0;
2303
- const showThreadLink = threads && !deleted && !msg.thread_root_id && replyCount > 0;
3227
+ const showThreadLink = threads && !msg.thread_root_id && replyCount > 0;
2304
3228
  const showActions = actions && !deleted && !editing;
2305
3229
  const timeEl = (className) => /* @__PURE__ */ jsx("time", { className, dateTime: msg.inserted_at, children: time });
2306
3230
  const avatarSize = compact ? "sm" : "md";
3231
+ const avatarEl = /* @__PURE__ */ jsx(
3232
+ Avatar,
3233
+ {
3234
+ src: sender.avatarUrl,
3235
+ name: senderName,
3236
+ size: avatarSize,
3237
+ ...showPresence && msg.sender_external_id ? { presence: true, userId: msg.sender_external_id } : {}
3238
+ }
3239
+ );
2307
3240
  const avatar = !showAvatar ? null : onAvatarPress && !isSelf ? /* @__PURE__ */ jsx(
2308
3241
  "button",
2309
3242
  {
@@ -2311,9 +3244,9 @@ function FlatMessageRow({
2311
3244
  className: "poolse-row__avatar-button",
2312
3245
  "aria-label": senderName,
2313
3246
  onClick: () => onAvatarPress(sender),
2314
- children: /* @__PURE__ */ jsx(Avatar, { src: sender.avatarUrl, name: senderName, size: avatarSize })
3247
+ children: avatarEl
2315
3248
  }
2316
- ) : /* @__PURE__ */ jsx(Avatar, { src: sender.avatarUrl, name: senderName, size: avatarSize });
3249
+ ) : avatarEl;
2317
3250
  const nameStyle = compact ? { color: userColor(msg.sender_external_id ?? msg.sender_id ?? "") } : void 0;
2318
3251
  const name = onSenderPress && !isSelf ? /* @__PURE__ */ jsx(
2319
3252
  "button",
@@ -2329,7 +3262,7 @@ function FlatMessageRow({
2329
3262
  name,
2330
3263
  timeEl("poolse-row__time")
2331
3264
  ] }) : null;
2332
- const quote = msg.quoted_message !== void 0 && msg.quoted_message !== null ? /* @__PURE__ */ jsx(
3265
+ const quote = deleted ? null : msg.quoted_message !== void 0 && msg.quoted_message !== null ? /* @__PURE__ */ jsx(
2333
3266
  QuotedCard,
2334
3267
  {
2335
3268
  quoted: msg.quoted_message,
@@ -2345,8 +3278,14 @@ function FlatMessageRow({
2345
3278
  images.length > 0 && /* @__PURE__ */ jsx(ImageMosaic, { images }),
2346
3279
  files.length > 0 && /* @__PURE__ */ jsx("div", { className: "poolse-message__files", children: files.map((att) => /* @__PURE__ */ jsx(AttachmentPreview, { attachment: att }, att.id)) })
2347
3280
  ] }) : null;
3281
+ const editHistory = useEditHistory(msg.id);
2348
3282
  const meta = /* @__PURE__ */ jsxs(Fragment, { children: [
2349
- msg.edited_at && !deleted ? /* @__PURE__ */ jsx("span", { className: "poolse-row__edited", children: "(edited)" }) : null,
3283
+ msg.edited_at && !deleted ? /* @__PURE__ */ jsxs("span", { className: "poolse-row__edited", children: [
3284
+ "(",
3285
+ editHistory.label(),
3286
+ ")"
3287
+ ] }) : null,
3288
+ editHistory.popover,
2350
3289
  isSelf && readState ? /* @__PURE__ */ jsx("span", { className: "poolse-row__receipt", children: /* @__PURE__ */ jsx(
2351
3290
  PoolseIcon,
2352
3291
  {
@@ -2388,21 +3327,12 @@ function FlatMessageRow({
2388
3327
  onRemove: (e) => void reactionsHook.removeReaction(e)
2389
3328
  }
2390
3329
  ) : null;
2391
- const threadEl = showThreadLink ? /* @__PURE__ */ jsxs(
2392
- "button",
3330
+ const threadEl = showThreadLink ? /* @__PURE__ */ jsx(
3331
+ ThreadSummary,
2393
3332
  {
2394
- type: "button",
3333
+ message: msg,
2395
3334
  className: "poolse-row__thread",
2396
- onClick: onOpenThread,
2397
- "aria-label": `View ${replyCount} ${replyCount === 1 ? "reply" : "replies"}`,
2398
- children: [
2399
- /* @__PURE__ */ jsx(PoolseIcon, { name: "messages", size: 14, label: null }),
2400
- /* @__PURE__ */ jsxs("span", { children: [
2401
- replyCount,
2402
- " ",
2403
- replyCount === 1 ? "reply" : "replies"
2404
- ] })
2405
- ]
3335
+ ...onOpenThread ? { onOpen: onOpenThread } : {}
2406
3336
  }
2407
3337
  ) : null;
2408
3338
  const toolbar = showActions ? /* @__PURE__ */ jsx("div", { className: "poolse-row__toolbar", children: /* @__PURE__ */ jsx(
@@ -2417,6 +3347,7 @@ function FlatMessageRow({
2417
3347
  void navigator?.clipboard?.writeText(msg.body ?? "").catch(() => void 0);
2418
3348
  }
2419
3349
  } : {},
3350
+ ...!isSelf && onMarkUnread ? { onMarkUnread } : {},
2420
3351
  ...isSelf && onStartEdit ? { onEdit: onStartEdit } : {},
2421
3352
  ...isSelf && onDelete ? { onDelete } : {}
2422
3353
  }
@@ -2426,6 +3357,7 @@ function FlatMessageRow({
2426
3357
  quote,
2427
3358
  renderSlot(slots?.attachments, ctx, attachmentsEl),
2428
3359
  renderSlot(slots?.body, ctx, body),
3360
+ linkPreviews && !editing && hasLinkPreviews(msg) ? /* @__PURE__ */ jsx(MessageLinkPreviews, { message: msg, canRemove: isSelf }) : null,
2429
3361
  renderSlot(slots?.reactions, ctx, reactionsEl),
2430
3362
  renderSlot(slots?.thread, ctx, threadEl)
2431
3363
  ] });
@@ -2468,7 +3400,7 @@ function FlatBody({
2468
3400
  }) {
2469
3401
  const [expanded, setExpanded] = useState(false);
2470
3402
  if (message.deleted_at) {
2471
- return /* @__PURE__ */ jsx("div", { className: "poolse-message__body poolse-row__body", children: /* @__PURE__ */ jsx("span", { className: "poolse-message__body--deleted", children: "Message deleted" }) });
3403
+ return /* @__PURE__ */ jsx("div", { className: "poolse-message__body poolse-row__body", children: /* @__PURE__ */ jsx("span", { className: "poolse-message__body--deleted", children: "This message was deleted" }) });
2472
3404
  }
2473
3405
  const raw = message.body ?? "";
2474
3406
  if (!raw) {
@@ -2543,6 +3475,7 @@ function BubbleMessageRow({
2543
3475
  onDelete,
2544
3476
  onOpenThread,
2545
3477
  onQuote,
3478
+ onMarkUnread,
2546
3479
  labelFor,
2547
3480
  onQuotedClick,
2548
3481
  groupPosition = "standalone",
@@ -2550,6 +3483,8 @@ function BubbleMessageRow({
2550
3483
  markdown = false,
2551
3484
  showSenderName = false,
2552
3485
  showAvatar = false,
3486
+ showPresence = false,
3487
+ linkPreviews = true,
2553
3488
  onSenderPress,
2554
3489
  onAvatarPress,
2555
3490
  timeFormat,
@@ -2573,7 +3508,7 @@ function BubbleMessageRow({
2573
3508
  const showReactions = reactions && !msg.deleted_at;
2574
3509
  const showActions = actions && !msg.deleted_at && !editing;
2575
3510
  const replyCount = msg.reply_count ?? 0;
2576
- const showThreadPill = threads && !msg.deleted_at && !msg.thread_root_id && replyCount > 0;
3511
+ const showThreadPill = threads && !msg.thread_root_id && replyCount > 0;
2577
3512
  const handleSave = onSaveEdit ?? (async () => void 0);
2578
3513
  const handleCancel = onCancelEdit ?? (() => void 0);
2579
3514
  const { actionsOpen, setActionsOpen, rowRef, onRowClick } = useRowActions();
@@ -2620,6 +3555,7 @@ function BubbleMessageRow({
2620
3555
  groupPosition,
2621
3556
  senderName,
2622
3557
  avatarUrl: senderProfile?.avatarUrl ?? null,
3558
+ presenceId: showPresence ? msg.sender_external_id : null,
2623
3559
  ...onAvatarPress ? { onAvatarPress: () => onAvatarPress(sender) } : {},
2624
3560
  children: /* @__PURE__ */ jsx(
2625
3561
  MessageBubble,
@@ -2632,6 +3568,7 @@ function BubbleMessageRow({
2632
3568
  showSenderName,
2633
3569
  ...onSenderPress ? { onSenderPress: () => onSenderPress(sender) } : {},
2634
3570
  showAttachments: attachments,
3571
+ linkPreviews,
2635
3572
  ...readState ? { readState } : {},
2636
3573
  ...labelFor ? { labelFor } : {},
2637
3574
  ...onQuotedClick ? { onQuotedClick } : {},
@@ -2673,21 +3610,12 @@ function BubbleMessageRow({
2673
3610
  renderSlot(
2674
3611
  slots?.thread,
2675
3612
  slotContext,
2676
- showThreadPill ? /* @__PURE__ */ jsxs(
2677
- "button",
3613
+ showThreadPill ? /* @__PURE__ */ jsx(
3614
+ ThreadSummary,
2678
3615
  {
2679
- type: "button",
3616
+ message: msg,
2680
3617
  className: `poolse-thread-pill ${isSelf ? "poolse-thread-pill--right" : "poolse-thread-pill--left"}`,
2681
- onClick: onOpenThread,
2682
- "aria-label": `View ${replyCount} ${replyCount === 1 ? "reply" : "replies"}`,
2683
- children: [
2684
- /* @__PURE__ */ jsx(PoolseIcon, { name: "messages", size: 12, label: null }),
2685
- /* @__PURE__ */ jsxs("span", { children: [
2686
- replyCount,
2687
- " ",
2688
- replyCount === 1 ? "reply" : "replies"
2689
- ] })
2690
- ]
3618
+ ...onOpenThread ? { onOpen: onOpenThread } : {}
2691
3619
  }
2692
3620
  ) : null
2693
3621
  ),
@@ -2713,6 +3641,7 @@ function BubbleMessageRow({
2713
3641
  void navigator?.clipboard?.writeText(msg.body ?? "").catch(() => void 0);
2714
3642
  }
2715
3643
  } : {},
3644
+ ...!isSelf && onMarkUnread ? { onMarkUnread } : {},
2716
3645
  ...isSelf && onStartEdit ? { onEdit: onStartEdit } : {},
2717
3646
  ...isSelf && onDelete ? { onDelete } : {}
2718
3647
  }
@@ -2730,11 +3659,21 @@ function BubbleWithAvatar({
2730
3659
  groupPosition,
2731
3660
  senderName,
2732
3661
  avatarUrl,
3662
+ presenceId,
2733
3663
  onAvatarPress,
2734
3664
  children
2735
3665
  }) {
2736
3666
  if (isSelf || !showAvatar) return /* @__PURE__ */ jsx(Fragment, { children });
2737
3667
  const isLastOfCluster = groupPosition === "last" || groupPosition === "standalone";
3668
+ const avatar = /* @__PURE__ */ jsx(
3669
+ Avatar,
3670
+ {
3671
+ src: avatarUrl,
3672
+ name: senderName,
3673
+ size: "sm",
3674
+ ...presenceId ? { presence: true, userId: presenceId } : {}
3675
+ }
3676
+ );
2738
3677
  return /* @__PURE__ */ jsxs("div", { className: "poolse-bubble-shell", children: [
2739
3678
  /* @__PURE__ */ jsx("div", { className: "poolse-bubble-shell__avatar", children: !isLastOfCluster ? null : onAvatarPress ? /* @__PURE__ */ jsx(
2740
3679
  "button",
@@ -2743,9 +3682,9 @@ function BubbleWithAvatar({
2743
3682
  className: "poolse-bubble-shell__avatar-button",
2744
3683
  "aria-label": senderName,
2745
3684
  onClick: onAvatarPress,
2746
- children: /* @__PURE__ */ jsx(Avatar, { src: avatarUrl, name: senderName, size: "sm" })
3685
+ children: avatar
2747
3686
  }
2748
- ) : /* @__PURE__ */ jsx(Avatar, { src: avatarUrl, name: senderName, size: "sm" }) }),
3687
+ ) : avatar }),
2749
3688
  children
2750
3689
  ] });
2751
3690
  }
@@ -2755,7 +3694,9 @@ function ThreadView({
2755
3694
  onClose,
2756
3695
  renderMessage,
2757
3696
  layout,
2758
- timeFormat
3697
+ timeFormat,
3698
+ maxFileSize,
3699
+ acceptFileTypes
2759
3700
  }) {
2760
3701
  const { me } = useMe();
2761
3702
  const {
@@ -2890,7 +3831,9 @@ function ThreadView({
2890
3831
  body,
2891
3832
  ...opts?.attachment_ids && opts.attachment_ids.length > 0 ? { attachment_ids: opts.attachment_ids } : {}
2892
3833
  }),
2893
- placeholder: "Reply in thread\u2026"
3834
+ placeholder: "Reply in thread\u2026",
3835
+ ...maxFileSize !== void 0 ? { maxFileSize } : {},
3836
+ ...acceptFileTypes ? { acceptFileTypes } : {}
2894
3837
  }
2895
3838
  ),
2896
3839
  dragActive && /* @__PURE__ */ jsx("div", { className: "poolse-conversation__drop-overlay", "aria-hidden": "true", children: /* @__PURE__ */ jsxs("div", { className: "poolse-conversation__drop-overlay-inner", children: [
@@ -2902,6 +3845,31 @@ function ThreadView({
2902
3845
  }
2903
3846
  );
2904
3847
  }
3848
+ var MAX_NAME_CHARS = 24;
3849
+ function UserName({
3850
+ externalId,
3851
+ labelFor,
3852
+ emptyFallback = "Unknown",
3853
+ className
3854
+ }) {
3855
+ const { profile } = useUser(labelFor ? null : externalId);
3856
+ const name = resolveDisplayName(externalId, profile?.displayName, labelFor, emptyFallback);
3857
+ return /* @__PURE__ */ jsx("span", { className, children: truncate(name) });
3858
+ }
3859
+ function useDisplayName(externalId, labelFor, emptyFallback = "Unknown") {
3860
+ const { profile } = useUser(labelFor ? null : externalId);
3861
+ return resolveDisplayName(externalId, profile?.displayName, labelFor, emptyFallback);
3862
+ }
3863
+ function resolveDisplayName(externalId, resolved, labelFor, emptyFallback) {
3864
+ if (!externalId) return emptyFallback;
3865
+ if (labelFor) return labelFor(externalId);
3866
+ if (resolved) return resolved;
3867
+ return externalId;
3868
+ }
3869
+ function truncate(s) {
3870
+ if (s.length <= MAX_NAME_CHARS) return s;
3871
+ return s.slice(0, MAX_NAME_CHARS - 1) + "\u2026";
3872
+ }
2905
3873
  function TypingIndicator({ typing, labelFor }) {
2906
3874
  const ids = Array.from(typing);
2907
3875
  const isTyping = ids.length > 0;
@@ -2949,10 +3917,14 @@ function ConversationView({
2949
3917
  reactions = TRUE,
2950
3918
  mentions = TRUE,
2951
3919
  attachments = TRUE,
3920
+ maxFileSize,
3921
+ acceptFileTypes,
3922
+ emojiPicker = TRUE,
2952
3923
  actions = TRUE,
2953
3924
  threads = TRUE,
2954
3925
  quotations = TRUE,
2955
3926
  readReceipts = TRUE,
3927
+ linkPreviews = TRUE,
2956
3928
  markdown = TRUE,
2957
3929
  maxBodyLength = 200,
2958
3930
  grouping = TRUE,
@@ -2961,6 +3933,7 @@ function ConversationView({
2961
3933
  layout = "bubbles",
2962
3934
  density = "comfortable",
2963
3935
  showAvatars,
3936
+ showPresence = false,
2964
3937
  timeFormat,
2965
3938
  slots,
2966
3939
  daySeparators = TRUE,
@@ -2975,7 +3948,9 @@ function ConversationView({
2975
3948
  readOnly = false,
2976
3949
  onCallBack,
2977
3950
  onJoinCall,
2978
- currentCallId = null
3951
+ currentCallId = null,
3952
+ persistDrafts = TRUE,
3953
+ draftStorage
2979
3954
  }) {
2980
3955
  usePoolseFonts(loadFonts);
2981
3956
  const showComposer = composer && !readOnly;
@@ -3007,13 +3982,16 @@ function ConversationView({
3007
3982
  const status = useRealtimeStatus();
3008
3983
  const wantsMemberCount = senderLabels === "auto" || avatars === "auto";
3009
3984
  const membersOn = mentions || readReceipts || wantsMemberCount;
3010
- const { members } = useMembers(membersOn ? conversationId : "");
3985
+ const { members, loading: membersLoading } = useMembers(membersOn ? conversationId : "");
3986
+ const chat = usePoolse();
3011
3987
  const isGroupChat = members.length > 2;
3012
3988
  const showSenderLabelsResolved = senderLabels === "always" || senderLabels === "auto" && isGroupChat;
3013
3989
  const showAvatarsResolved = showAvatars ?? (layout === "list" ? true : layout === "compact" ? false : avatars === "always" || avatars === "auto" && isGroupChat);
3014
3990
  const groupWindowMs = groupWindowMinutes !== void 0 ? groupWindowMinutes * 60 * 1e3 : groupingWindowMs ?? 5 * 60 * 1e3;
3015
3991
  const layoutProps = {
3016
3992
  layout,
3993
+ showPresence,
3994
+ linkPreviews,
3017
3995
  ...timeFormat ? { timeFormat } : {},
3018
3996
  ...slots ? { slots } : {}
3019
3997
  };
@@ -3084,12 +4062,14 @@ function ConversationView({
3084
4062
  if (el) el.scrollTop = el.scrollHeight;
3085
4063
  }, [streamedChars, atBottom]);
3086
4064
  const lastMarkedReadRef = useRef(null);
4065
+ const [markerReadyFor, setMarkerReadyFor] = useState(null);
3087
4066
  useEffect(() => {
3088
4067
  if (!atBottom) return;
3089
4068
  if (messages.length === 0) return;
3090
4069
  const tail = messages[messages.length - 1];
3091
4070
  if (!tail) return;
3092
4071
  if (tail.sequence === Number.MAX_SAFE_INTEGER) return;
4072
+ if (membersOn && markerReadyFor !== conversationId) return;
3093
4073
  if (lastMarkedReadRef.current === tail.id) return;
3094
4074
  lastMarkedReadRef.current = tail.id;
3095
4075
  void markReadUpTo(tail.id).then(() => {
@@ -3097,7 +4077,33 @@ function ConversationView({
3097
4077
  }).catch(() => {
3098
4078
  lastMarkedReadRef.current = null;
3099
4079
  });
3100
- }, [atBottom, messages, markReadUpTo, onMarkedRead, conversationId]);
4080
+ }, [atBottom, messages, markReadUpTo, onMarkedRead, conversationId, membersOn, markerReadyFor]);
4081
+ const [unreadMarker, setUnreadMarker] = useState(null);
4082
+ const markerTakenRef = useRef(null);
4083
+ useEffect(() => {
4084
+ setUnreadMarker(null);
4085
+ markerTakenRef.current = null;
4086
+ }, [conversationId]);
4087
+ useEffect(() => {
4088
+ if (markerTakenRef.current === conversationId) return;
4089
+ if (!membersOn || loading || membersLoading) return;
4090
+ if (members.some((m) => m.conversation_id !== conversationId)) return;
4091
+ if (!me && members.length > 0) return;
4092
+ markerTakenRef.current = conversationId;
4093
+ setMarkerReadyFor(conversationId);
4094
+ const mine = me ? members.find((m) => m.user_id === me.id) : void 0;
4095
+ if (!mine) return;
4096
+ let after = mine.last_read_sequence ?? null;
4097
+ if (after === null && mine.last_read_message_id) {
4098
+ after = messages.find((m) => m.id === mine.last_read_message_id)?.sequence ?? null;
4099
+ if (after === null) return;
4100
+ }
4101
+ setUnreadMarker({
4102
+ conversationId,
4103
+ afterSequence: after ?? 0,
4104
+ lastReadId: mine.last_read_message_id
4105
+ });
4106
+ }, [conversationId, membersOn, loading, membersLoading, me, members, messages]);
3101
4107
  const scrollToBottom = () => {
3102
4108
  const el = listRef.current;
3103
4109
  if (el) el.scrollTop = el.scrollHeight;
@@ -3108,6 +4114,74 @@ function ConversationView({
3108
4114
  () => messages.filter((m) => isMessageVisibleTo(m, meIdForFeed)),
3109
4115
  [messages, meIdForFeed]
3110
4116
  );
4117
+ const marker = unreadMarker && unreadMarker.conversationId === conversationId ? unreadMarker : null;
4118
+ const unread = useMemo(() => {
4119
+ if (!marker) return { firstId: null, reaches: true, any: false };
4120
+ const isUnread = (m) => m.sequence > marker.afterSequence && m.sequence !== Number.MAX_SAFE_INTEGER && m.sender_id !== meIdForFeed;
4121
+ const reaches = !hasMore || visibleMessages.some((m) => m.sequence <= marker.afterSequence);
4122
+ const first = visibleMessages.find(isUnread) ?? null;
4123
+ return {
4124
+ firstId: reaches ? first?.id ?? null : null,
4125
+ reaches,
4126
+ any: first !== null
4127
+ };
4128
+ }, [marker, visibleMessages, hasMore, meIdForFeed]);
4129
+ const dividerRef = useRef(null);
4130
+ const [dividerInView, setDividerInView] = useState(false);
4131
+ const [jumpDismissed, setJumpDismissed] = useState(false);
4132
+ useEffect(() => {
4133
+ setJumpDismissed(false);
4134
+ }, [conversationId, marker?.afterSequence]);
4135
+ useEffect(() => {
4136
+ setDividerInView(false);
4137
+ const el = dividerRef.current;
4138
+ const root = listRef.current;
4139
+ if (!el || !root || typeof IntersectionObserver === "undefined") return;
4140
+ const io = new IntersectionObserver(([entry]) => setDividerInView(!!entry?.isIntersecting), {
4141
+ root,
4142
+ threshold: 0
4143
+ });
4144
+ io.observe(el);
4145
+ return () => io.disconnect();
4146
+ }, [unread.firstId]);
4147
+ const [jump, setJump] = useState(null);
4148
+ const jumpToFirstUnread = () => {
4149
+ if (!marker) return;
4150
+ if (unread.firstId) {
4151
+ scrollDividerIntoView(dividerRef.current);
4152
+ return;
4153
+ }
4154
+ setJump("loading");
4155
+ void loadUntil(marker.lastReadId ?? NO_MESSAGE).catch(() => false).then(() => {
4156
+ if (conversationIdRef.current === marker.conversationId) {
4157
+ setJump((j) => j ? "loaded" : j);
4158
+ }
4159
+ });
4160
+ };
4161
+ useEffect(() => {
4162
+ if (!jump) return;
4163
+ if (unread.firstId) {
4164
+ setJump(null);
4165
+ scrollDividerIntoView(dividerRef.current);
4166
+ } else if (jump === "loaded") {
4167
+ setJump(null);
4168
+ }
4169
+ }, [jump, unread.firstId]);
4170
+ useEffect(() => {
4171
+ setJump(null);
4172
+ }, [conversationId]);
4173
+ const showJump = !!marker && unread.any && !jumpDismissed && (!unread.firstId || !dividerInView);
4174
+ const markUnreadFrom = async (msg) => {
4175
+ const tail = messages[messages.length - 1];
4176
+ if (tail) lastMarkedReadRef.current = tail.id;
4177
+ try {
4178
+ await chat.conversations.one(conversationId).markUnread(msg.id);
4179
+ markerTakenRef.current = conversationId;
4180
+ setUnreadMarker({ conversationId, afterSequence: msg.sequence - 1, lastReadId: null });
4181
+ } catch {
4182
+ setSendNotice("Couldn't mark the message unread.");
4183
+ }
4184
+ };
3111
4185
  const [pendingFocusId, setPendingFocusId] = useState(null);
3112
4186
  const [focusMissing, setFocusMissing] = useState(false);
3113
4187
  const onFocusNotFoundRef = useRef(onFocusMessageNotFound);
@@ -3176,12 +4250,68 @@ function ConversationView({
3176
4250
  () => threadRootId ? messages.find((m) => m.id === threadRootId) ?? null : null,
3177
4251
  [threadRootId, messages]
3178
4252
  );
3179
- const [replyingTo, setReplyingTo] = useState(null);
4253
+ const [replyingTo, setReplyingToState] = useState(null);
4254
+ const mentionComposer = mentions && members.length > 0;
3180
4255
  useEffect(() => {
3181
- setReplyingTo(null);
4256
+ setReplyingToState(null);
3182
4257
  setEditingId(null);
3183
4258
  setThreadRootId(null);
4259
+ setSendNotice(null);
3184
4260
  }, [conversationId]);
4261
+ const meIdForDrafts = me?.id ?? null;
4262
+ const draftsOn = persistDrafts && showComposer;
4263
+ const storage = draftStorage ?? localDraftStorage;
4264
+ const draftRef = useRef({ text: "", replyTo: null });
4265
+ const draftKeyFor = useCallback(
4266
+ () => draftsOn && meIdForDrafts ? draftKey(meIdForDrafts, conversationIdRef.current) : null,
4267
+ [draftsOn, meIdForDrafts]
4268
+ );
4269
+ const saveDraft = useCallback(
4270
+ (patch) => {
4271
+ draftRef.current = { ...draftRef.current, ...patch };
4272
+ const key = draftKeyFor();
4273
+ if (key) writeDraft(storage, key, draftRef.current);
4274
+ },
4275
+ [draftKeyFor, storage]
4276
+ );
4277
+ const setReplyingTo = useCallback(
4278
+ (m) => {
4279
+ setReplyingToState(m);
4280
+ saveDraft({ replyTo: m });
4281
+ },
4282
+ [saveDraft]
4283
+ );
4284
+ useEffect(() => {
4285
+ draftRef.current = { text: "", replyTo: null };
4286
+ const key = draftKeyFor();
4287
+ if (!key) return;
4288
+ let live = true;
4289
+ const apply = (d) => {
4290
+ if (!live || !d) return;
4291
+ const composer2 = composerRef.current;
4292
+ if (d.text && composer2 && composer2.getText() === "") composer2.setText(d.text);
4293
+ draftRef.current = { text: composer2?.getText() || d.text, replyTo: d.replyTo };
4294
+ if (d.replyTo && canQuote) setReplyingToState((cur) => cur ?? d.replyTo);
4295
+ };
4296
+ const found = readDraft(storage, key);
4297
+ if (found instanceof Promise) void found.then(apply);
4298
+ else apply(found);
4299
+ return () => {
4300
+ live = false;
4301
+ };
4302
+ }, [conversationId, draftKeyFor, storage, canQuote, mentionComposer]);
4303
+ const onComposerChange = useCallback((text) => saveDraft({ text }), [saveDraft]);
4304
+ useEffect(() => {
4305
+ if (!replyingTo) return;
4306
+ const current = messages.find((m) => m.id === replyingTo.id);
4307
+ if (current?.deleted_at) setReplyingTo(null);
4308
+ }, [messages, replyingTo, setReplyingTo]);
4309
+ const [sendNotice, setSendNotice] = useState(null);
4310
+ useEffect(() => {
4311
+ if (!sendNotice) return;
4312
+ const t = setTimeout(() => setSendNotice(null), 4e3);
4313
+ return () => clearTimeout(t);
4314
+ }, [sendNotice]);
3185
4315
  const scrollToOriginal = (id) => {
3186
4316
  const root = listRef.current;
3187
4317
  if (!root) return;
@@ -3218,39 +4348,69 @@ function ConversationView({
3218
4348
  const files = Array.from(e.dataTransfer?.files ?? []);
3219
4349
  if (files.length > 0) composerRef.current?.addFiles(files);
3220
4350
  };
3221
- const onSendBody = async (body, opts) => {
3222
- await send({
3223
- body,
3224
- ...opts?.quoted_message_id ? { quoted_message_id: opts.quoted_message_id } : {},
3225
- ...opts?.attachment_ids && opts.attachment_ids.length > 0 ? { attachment_ids: opts.attachment_ids } : {}
3226
- });
3227
- setReplyingTo(null);
4351
+ const sendRequest = async (req) => {
4352
+ try {
4353
+ await send(req);
4354
+ } catch (err) {
4355
+ if (err instanceof ApiError && err.code === "quoted_message_deleted") {
4356
+ setReplyingTo(null);
4357
+ setSendNotice("The message you replied to was deleted.");
4358
+ const body = req.body;
4359
+ if (body) {
4360
+ setTimeout(() => {
4361
+ const composer2 = composerRef.current;
4362
+ if (composer2 && composer2.getText() === "") composer2.setText(body);
4363
+ }, 0);
4364
+ }
4365
+ return;
4366
+ }
4367
+ throw err;
4368
+ }
4369
+ setReplyingToState(null);
4370
+ setUnreadMarker(null);
4371
+ draftRef.current = { text: "", replyTo: null };
4372
+ const key = draftKeyFor();
4373
+ if (key) clearDraft(storage, key);
3228
4374
  };
3229
- const onSendWithMentions = async (req) => {
3230
- await send(req);
3231
- setReplyingTo(null);
4375
+ const onSendBody = (body, opts) => sendRequest({
4376
+ body,
4377
+ ...opts?.quoted_message_id ? { quoted_message_id: opts.quoted_message_id } : {},
4378
+ ...opts?.attachment_ids && opts.attachment_ids.length > 0 ? { attachment_ids: opts.attachment_ids } : {}
4379
+ });
4380
+ const onSendWithMentions = (req) => sendRequest(req);
4381
+ const attachmentRules = {
4382
+ ...maxFileSize !== void 0 ? { maxFileSize } : {},
4383
+ ...acceptFileTypes ? { acceptFileTypes } : {}
3232
4384
  };
3233
- const Composer = mentions && members.length > 0 ? /* @__PURE__ */ jsx(
4385
+ const Composer = mentionComposer ? /* @__PURE__ */ jsx(
3234
4386
  MentionInput,
3235
4387
  {
3236
4388
  ref: composerRef,
4389
+ onValueChange: onComposerChange,
3237
4390
  conversationId,
3238
4391
  onSend: onSendWithMentions,
3239
4392
  onTyping: signalTyping,
3240
4393
  attachments,
4394
+ emojiPicker,
4395
+ ...attachmentRules,
3241
4396
  ...labelFor ? { labelFor } : {},
3242
4397
  ...canQuote ? { replyingTo, onCancelReply: () => setReplyingTo(null) } : {}
3243
- }
4398
+ },
4399
+ conversationId
3244
4400
  ) : /* @__PURE__ */ jsx(
3245
4401
  MessageComposer,
3246
4402
  {
3247
4403
  ref: composerRef,
4404
+ onValueChange: onComposerChange,
3248
4405
  onSend: onSendBody,
3249
4406
  onTyping: signalTyping,
3250
4407
  attachments,
4408
+ emojiPicker,
4409
+ ...attachmentRules,
3251
4410
  ...labelFor ? { labelFor } : {},
3252
4411
  ...canQuote ? { replyingTo, onCancelReply: () => setReplyingTo(null) } : {}
3253
- }
4412
+ },
4413
+ conversationId
3254
4414
  );
3255
4415
  return /* @__PURE__ */ jsxs("div", { className: "poolse-conversation-shell", children: [
3256
4416
  /* @__PURE__ */ jsxs(
@@ -3291,6 +4451,14 @@ function ConversationView({
3291
4451
  }
3292
4452
  ),
3293
4453
  focusMissing && /* @__PURE__ */ jsx("div", { className: "poolse-conversation__status", role: "status", "aria-live": "polite", children: "That message isn't available." }),
4454
+ sendNotice && /* @__PURE__ */ jsx(
4455
+ "div",
4456
+ {
4457
+ className: "poolse-conversation__status poolse-conversation__status--error",
4458
+ role: "alert",
4459
+ children: sendNotice
4460
+ }
4461
+ ),
3294
4462
  /* @__PURE__ */ jsxs(
3295
4463
  "div",
3296
4464
  {
@@ -3302,6 +4470,31 @@ function ConversationView({
3302
4470
  "aria-relevant": "additions",
3303
4471
  children: [
3304
4472
  hasMore && /* @__PURE__ */ jsx("div", { ref: topSentinelRef, "aria-hidden": "true", style: { height: 1 } }),
4473
+ showJump && /* @__PURE__ */ jsxs("div", { className: "poolse-conversation__jump-unread", children: [
4474
+ /* @__PURE__ */ jsxs(
4475
+ "button",
4476
+ {
4477
+ type: "button",
4478
+ className: "poolse-conversation__jump-unread-btn",
4479
+ onClick: jumpToFirstUnread,
4480
+ disabled: jump !== null,
4481
+ children: [
4482
+ /* @__PURE__ */ jsx(PoolseIcon, { name: "chevron-up", size: 14, label: null }),
4483
+ jump ? "Loading\u2026" : "Jump to first unread"
4484
+ ]
4485
+ }
4486
+ ),
4487
+ /* @__PURE__ */ jsx(
4488
+ "button",
4489
+ {
4490
+ type: "button",
4491
+ className: "poolse-conversation__jump-unread-close",
4492
+ "aria-label": "Dismiss",
4493
+ onClick: () => setJumpDismissed(true),
4494
+ children: /* @__PURE__ */ jsx(PoolseIcon, { name: "close", size: 12, label: null })
4495
+ }
4496
+ )
4497
+ ] }),
3305
4498
  loading && messages.length === 0 ? /* @__PURE__ */ jsx("div", { className: "poolse-conversation__empty", children: "Loading\u2026" }) : messages.length === 0 ? /* @__PURE__ */ jsx("div", { className: "poolse-conversation__empty", children: emptyState ?? "No messages yet." }) : visibleMessages.map((msg, idx) => {
3306
4499
  const prev = idx > 0 ? visibleMessages[idx - 1] ?? null : null;
3307
4500
  const next = idx < visibleMessages.length - 1 ? visibleMessages[idx + 1] ?? null : null;
@@ -3359,22 +4552,37 @@ function ConversationView({
3359
4552
  onDelete: () => void deleteMsg(msg.id),
3360
4553
  onOpenThread: () => setThreadRootId(msg.id),
3361
4554
  onQuote: () => setReplyingTo(msg),
4555
+ ...!isSelf && msg.sequence !== Number.MAX_SAFE_INTEGER ? { onMarkUnread: () => void markUnreadFrom(msg) } : {},
3362
4556
  onQuotedClick: scrollToOriginal,
3363
4557
  ...onCallBack ? { onCallBack } : {},
3364
4558
  ...layoutProps,
3365
4559
  mentionsMe: mentionsViewer(msg, me?.id ?? null)
3366
4560
  }
3367
4561
  );
4562
+ const divider = unread.firstId === msg.id ? /* @__PURE__ */ jsx(
4563
+ "div",
4564
+ {
4565
+ ref: dividerRef,
4566
+ className: "poolse-unread-divider",
4567
+ role: "separator",
4568
+ "aria-label": "New messages",
4569
+ children: /* @__PURE__ */ jsx("span", { children: "New messages" })
4570
+ }
4571
+ ) : null;
3368
4572
  if (renderMessage) {
3369
- return /* @__PURE__ */ jsx(Fragment$1, { children: renderMessage(msg, me?.id ?? null, {
3370
- layout,
3371
- groupPosition,
3372
- isRunStart: layout === "compact" || groupPosition === "first" || groupPosition === "standalone",
3373
- renderDefault
3374
- }) }, msg.id);
4573
+ return /* @__PURE__ */ jsxs(Fragment$1, { children: [
4574
+ divider,
4575
+ renderMessage(msg, me?.id ?? null, {
4576
+ layout,
4577
+ groupPosition,
4578
+ isRunStart: layout === "compact" || groupPosition === "first" || groupPosition === "standalone",
4579
+ renderDefault
4580
+ })
4581
+ ] }, msg.id);
3375
4582
  }
3376
4583
  return /* @__PURE__ */ jsxs(Fragment$1, { children: [
3377
4584
  showDaySeparator && /* @__PURE__ */ jsx("div", { className: "poolse-day-separator", "aria-hidden": "false", children: /* @__PURE__ */ jsx("span", { children: formatDayLabel(msg.inserted_at) }) }),
4585
+ divider,
3378
4586
  renderDefault()
3379
4587
  ] }, msg.id);
3380
4588
  }),
@@ -3435,11 +4643,18 @@ function ConversationView({
3435
4643
  rootMessage: threadRoot,
3436
4644
  onClose: () => setThreadRootId(null),
3437
4645
  layout,
3438
- ...timeFormat ? { timeFormat } : {}
4646
+ ...timeFormat ? { timeFormat } : {},
4647
+ ...attachmentRules
3439
4648
  }
3440
4649
  ) })
3441
4650
  ] });
3442
4651
  }
4652
+ var NO_MESSAGE = "00000000-0000-0000-0000-000000000000";
4653
+ function scrollDividerIntoView(el) {
4654
+ if (el && typeof el.scrollIntoView === "function") {
4655
+ el.scrollIntoView({ behavior: "smooth", block: "start" });
4656
+ }
4657
+ }
3443
4658
  function highlightRow(el) {
3444
4659
  if (typeof el.scrollIntoView === "function") {
3445
4660
  el.scrollIntoView({ behavior: "smooth", block: "center" });
@@ -3486,23 +4701,34 @@ function ChatHeader({
3486
4701
  onBack,
3487
4702
  onPress,
3488
4703
  onMembersPress,
3489
- rightSlot
4704
+ rightSlot,
4705
+ showPresence = true
3490
4706
  }) {
3491
4707
  const { me } = useMe();
3492
4708
  const meId = me?.id ?? null;
3493
4709
  const { conversation: conv } = useConversation(conversationId);
3494
4710
  const { members } = useMembers(conversationId);
3495
- const { online } = usePresence(conversationId);
4711
+ const { online } = usePresence(showPresence ? conversationId : "");
3496
4712
  const isDirect = conv?.type === "direct";
3497
4713
  const otherMember = isDirect ? members.find((m) => m.user_id !== meId) : null;
3498
4714
  const otherExtId = otherMember?.external_id ?? null;
3499
4715
  const title = isDirect ? otherExtId ? labelFor?.(otherExtId) ?? otherExtId : conv?.name ?? "Direct chat" : conv?.name ?? "Untitled group";
3500
4716
  const avatarUrl = isDirect && otherExtId ? avatarFor?.(otherExtId) ?? null : null;
3501
- const otherOnline = isDirect && otherExtId ? online.has(otherExtId) : false;
3502
- const subtitle = isDirect ? otherOnline ? "Online" : null : `${members.length} member${members.length === 1 ? "" : "s"}`;
4717
+ const presence = useUserPresence(showPresence && isDirect ? otherExtId : null);
4718
+ const now = useNow();
4719
+ const otherOnline = showPresence && isDirect && otherExtId ? !presence && online.has(otherExtId) : false;
4720
+ const subtitle = isDirect ? !showPresence ? null : presence ? presenceText(presence, now) : otherOnline ? "Online" : null : `${members.length} member${members.length === 1 ? "" : "s"}`;
3503
4721
  const isPressable = typeof onPress === "function";
3504
4722
  const titleContent = /* @__PURE__ */ jsxs(Fragment, { children: [
3505
- /* @__PURE__ */ jsx(Avatar, { src: avatarUrl, name: title, online: otherOnline, size: "md" }),
4723
+ /* @__PURE__ */ jsx(
4724
+ Avatar,
4725
+ {
4726
+ src: avatarUrl,
4727
+ name: title,
4728
+ presence: presence ?? (otherOnline ? "online" : null),
4729
+ size: "md"
4730
+ }
4731
+ ),
3506
4732
  /* @__PURE__ */ jsxs("div", { className: "poolse-chat-header__titles", children: [
3507
4733
  /* @__PURE__ */ jsx("div", { className: "poolse-chat-header__title", children: title }),
3508
4734
  subtitle ? /* @__PURE__ */ jsx("div", { className: "poolse-chat-header__subtitle", children: subtitle }) : null
@@ -3545,7 +4771,15 @@ function ConversationList({
3545
4771
  error: controlledError,
3546
4772
  unreadCounts,
3547
4773
  labelFor,
3548
- avatarFor
4774
+ avatarFor,
4775
+ showPresence = true,
4776
+ density = "comfortable",
4777
+ sections,
4778
+ groupBy,
4779
+ header,
4780
+ hasMore: controlledHasMore,
4781
+ loadingMore: controlledLoadingMore,
4782
+ onLoadMore
3549
4783
  }) {
3550
4784
  const auto = useConversations();
3551
4785
  const { me } = useMe();
@@ -3556,49 +4790,123 @@ function ConversationList({
3556
4790
  const loading = isControlled ? controlledLoading ?? false : auto.loading;
3557
4791
  const error = isControlled ? controlledError ?? null : auto.error;
3558
4792
  const counts = unreadCounts ?? (isControlled ? void 0 : auto.unreadCounts);
3559
- if (loading && conversations.length === 0) {
3560
- return /* @__PURE__ */ jsx("div", { className: "poolse-list poolse-list--placeholder", children: "Loading conversations\u2026" });
3561
- }
3562
- if (error) {
3563
- return /* @__PURE__ */ jsx("div", { className: "poolse-list poolse-list--placeholder poolse-list--error", children: "Failed to load conversations." });
3564
- }
3565
- if (conversations.length === 0) {
3566
- return /* @__PURE__ */ jsx("div", { className: "poolse-list poolse-list--placeholder", children: emptyState ?? "No conversations yet." });
3567
- }
3568
- return /* @__PURE__ */ jsx("ul", { className: "poolse-list", role: "listbox", "aria-label": "Conversations", children: conversations.map((conv) => {
3569
- const selected = selectedId === conv.id;
3570
- const unread = counts?.[conv.id] ?? 0;
3571
- const content = renderItem ? renderItem(conv, selected) : /* @__PURE__ */ jsx(
3572
- DefaultRow,
3573
- {
3574
- conv,
3575
- selected,
3576
- unread,
3577
- meExternalId,
3578
- meId,
3579
- ...labelFor ? { labelFor } : {},
3580
- ...avatarFor ? { avatarFor } : {}
3581
- }
3582
- );
3583
- return /* @__PURE__ */ jsx(
3584
- "li",
3585
- {
3586
- role: "option",
3587
- "aria-selected": selected,
3588
- className: `poolse-list__item${selected ? " poolse-list__item--selected" : ""}`,
3589
- onClick: () => onSelect?.(conv),
3590
- onKeyDown: (e) => {
3591
- if (e.key === "Enter" || e.key === " ") {
3592
- e.preventDefault();
3593
- onSelect?.(conv);
3594
- }
3595
- },
3596
- tabIndex: 0,
3597
- children: content
4793
+ const hasMore = isControlled ? controlledHasMore ?? false : auto.hasMore;
4794
+ const loadingMore = isControlled ? controlledLoadingMore ?? false : auto.loadingMore;
4795
+ const loadMore = isControlled ? onLoadMore : auto.loadMore;
4796
+ const listRef = useRef(null);
4797
+ const sentinelRef = useRef(null);
4798
+ const loadMoreRef = useRef(loadMore);
4799
+ loadMoreRef.current = loadMore;
4800
+ const busyRef = useRef(false);
4801
+ const hasRows = conversations.length > 0;
4802
+ useEffect(() => {
4803
+ const sentinel = sentinelRef.current;
4804
+ const root = listRef.current;
4805
+ if (!sentinel || !root || !hasMore || loadingMore) return;
4806
+ if (typeof IntersectionObserver === "undefined") return;
4807
+ const io = new IntersectionObserver(
4808
+ ([entry]) => {
4809
+ if (!entry?.isIntersecting || busyRef.current) return;
4810
+ const fn = loadMoreRef.current;
4811
+ if (!fn) return;
4812
+ busyRef.current = true;
4813
+ void Promise.resolve().then(fn).catch(() => void 0).finally(() => {
4814
+ busyRef.current = false;
4815
+ });
3598
4816
  },
3599
- conv.id
4817
+ { root, rootMargin: "0px 0px 240px 0px", threshold: 0 }
3600
4818
  );
3601
- }) });
4819
+ io.observe(sentinel);
4820
+ return () => io.disconnect();
4821
+ }, [hasMore, loadingMore, hasRows]);
4822
+ const groups = useMemo(
4823
+ () => groupConversations(conversations, sections ?? (groupBy === "type" ? TYPE_SECTIONS : null)),
4824
+ [conversations, sections, groupBy]
4825
+ );
4826
+ const rootClass = [
4827
+ "poolse-conversation-list",
4828
+ `poolse-conversation-list--density-${density}`
4829
+ ].join(" ");
4830
+ const body = (() => {
4831
+ if (loading && conversations.length === 0) {
4832
+ return /* @__PURE__ */ jsx("div", { className: "poolse-list poolse-list--placeholder", children: "Loading conversations\u2026" });
4833
+ }
4834
+ if (error && conversations.length === 0) {
4835
+ return /* @__PURE__ */ jsx("div", { className: "poolse-list poolse-list--placeholder poolse-list--error", children: "Failed to load conversations." });
4836
+ }
4837
+ if (conversations.length === 0) {
4838
+ return /* @__PURE__ */ jsx("div", { className: "poolse-list poolse-list--placeholder", children: emptyState ?? "No conversations yet." });
4839
+ }
4840
+ const row = (conv) => {
4841
+ const selected = selectedId === conv.id;
4842
+ const unread = counts?.[conv.id] ?? 0;
4843
+ const content = renderItem ? renderItem(conv, selected) : /* @__PURE__ */ jsx(
4844
+ DefaultRow,
4845
+ {
4846
+ conv,
4847
+ selected,
4848
+ unread,
4849
+ meExternalId,
4850
+ meId,
4851
+ showPresence,
4852
+ compact: density === "compact",
4853
+ ...labelFor ? { labelFor } : {},
4854
+ ...avatarFor ? { avatarFor } : {}
4855
+ }
4856
+ );
4857
+ return /* @__PURE__ */ jsx(
4858
+ "li",
4859
+ {
4860
+ role: "option",
4861
+ "aria-selected": selected,
4862
+ className: `poolse-list__item${selected ? " poolse-list__item--selected" : ""}`,
4863
+ onClick: () => onSelect?.(conv),
4864
+ onKeyDown: (e) => {
4865
+ if (e.key === "Enter" || e.key === " ") {
4866
+ e.preventDefault();
4867
+ onSelect?.(conv);
4868
+ }
4869
+ },
4870
+ tabIndex: 0,
4871
+ children: content
4872
+ },
4873
+ conv.id
4874
+ );
4875
+ };
4876
+ return /* @__PURE__ */ jsxs("ul", { ref: listRef, className: "poolse-list", role: "listbox", "aria-label": "Conversations", children: [
4877
+ groups === null ? conversations.map(row) : groups.map((g) => /* @__PURE__ */ jsxs("li", { role: "group", "aria-label": g.title, className: "poolse-list__section", children: [
4878
+ /* @__PURE__ */ jsx("div", { className: "poolse-list__section-title", "aria-hidden": "true", children: g.title }),
4879
+ /* @__PURE__ */ jsx("ul", { className: "poolse-list__section-items", role: "presentation", children: g.conversations.map(row) })
4880
+ ] }, g.title)),
4881
+ loadingMore && /* @__PURE__ */ jsx("li", { className: "poolse-list__loading-more", role: "presentation", children: "Loading\u2026" }),
4882
+ hasMore && /* @__PURE__ */ jsx(
4883
+ "li",
4884
+ {
4885
+ ref: sentinelRef,
4886
+ className: "poolse-list__sentinel",
4887
+ role: "presentation",
4888
+ "aria-hidden": "true"
4889
+ }
4890
+ )
4891
+ ] });
4892
+ })();
4893
+ return /* @__PURE__ */ jsxs("div", { className: rootClass, children: [
4894
+ header !== void 0 && header !== null ? /* @__PURE__ */ jsx("div", { className: "poolse-conversation-list__header", children: header }) : null,
4895
+ body
4896
+ ] });
4897
+ }
4898
+ var TYPE_SECTIONS = [
4899
+ { title: "Channels", filter: (c) => c.type !== "direct" },
4900
+ { title: "Direct messages", filter: (c) => c.type === "direct" }
4901
+ ];
4902
+ function groupConversations(conversations, sections) {
4903
+ if (!sections || sections.length === 0) return null;
4904
+ const out = sections.map((s) => ({ title: s.title, conversations: [] }));
4905
+ for (const conv of conversations) {
4906
+ const i = sections.findIndex((s) => s.filter(conv));
4907
+ if (i !== -1) out[i].conversations.push(conv);
4908
+ }
4909
+ return out.filter((g) => g.conversations.length > 0);
3602
4910
  }
3603
4911
  function DefaultRow({
3604
4912
  conv,
@@ -3606,6 +4914,8 @@ function DefaultRow({
3606
4914
  unread,
3607
4915
  meExternalId,
3608
4916
  meId = null,
4917
+ showPresence,
4918
+ compact = false,
3609
4919
  labelFor,
3610
4920
  avatarFor
3611
4921
  }) {
@@ -3617,13 +4927,21 @@ function DefaultRow({
3617
4927
  const hasUnread = unread > 0;
3618
4928
  const preview = formatCallLogPreview(conv.last_message_preview, meId) ?? conv.last_message_preview ?? (conv.last_sequence > 0 ? `${conv.last_sequence} message${conv.last_sequence === 1 ? "" : "s"}` : "No messages yet");
3619
4929
  return /* @__PURE__ */ jsxs(Fragment, { children: [
3620
- /* @__PURE__ */ jsx(Avatar, { src: avatarUrl, name: title, size: "md" }),
4930
+ /* @__PURE__ */ jsx(
4931
+ Avatar,
4932
+ {
4933
+ src: avatarUrl,
4934
+ name: title,
4935
+ size: compact ? "sm" : "md",
4936
+ ...showPresence && otherExtId ? { presence: true, userId: otherExtId } : {}
4937
+ }
4938
+ ),
3621
4939
  /* @__PURE__ */ jsxs("div", { className: "poolse-list__body", children: [
3622
4940
  /* @__PURE__ */ jsxs("div", { className: "poolse-list__head", children: [
3623
4941
  /* @__PURE__ */ jsx("span", { className: `poolse-list__title${hasUnread ? " poolse-list__title--unread" : ""}`, children: title }),
3624
4942
  time && /* @__PURE__ */ jsx("span", { className: "poolse-list__time", children: time })
3625
4943
  ] }),
3626
- /* @__PURE__ */ jsx("div", { className: "poolse-list__preview", children: preview })
4944
+ compact ? null : /* @__PURE__ */ jsx("div", { className: "poolse-list__preview", children: preview })
3627
4945
  ] }),
3628
4946
  hasUnread && /* @__PURE__ */ jsx(
3629
4947
  "span",
@@ -3649,15 +4967,17 @@ function MemberList({
3649
4967
  labelFor,
3650
4968
  avatarFor,
3651
4969
  onlineExternalIds,
4970
+ showPresence = true,
3652
4971
  canRemove,
3653
4972
  renderItem,
3654
4973
  emptyState
3655
4974
  }) {
3656
4975
  const { members, loading, error, removeMember } = useMembers(conversationId);
3657
- const { online: presenceOnline } = usePresence(
3658
- onlineExternalIds === void 0 ? conversationId : ""
4976
+ const legacy = onlineExternalIds !== void 0;
4977
+ const presences = usePresenceMany(
4978
+ showPresence && !legacy ? members.map((m) => m.external_id) : NO_IDS
3659
4979
  );
3660
- const effectiveOnline = onlineExternalIds ?? presenceOnline;
4980
+ const now = useNow();
3661
4981
  if (loading && members.length === 0) {
3662
4982
  return /* @__PURE__ */ jsx("div", { className: "poolse-list poolse-list--placeholder", children: "Loading members\u2026" });
3663
4983
  }
@@ -3676,7 +4996,8 @@ function MemberList({
3676
4996
  {
3677
4997
  membership: m,
3678
4998
  avatarUrl: avatarFor?.(m.external_id) ?? null,
3679
- online: effectiveOnline.has(m.external_id),
4999
+ presence: !showPresence ? null : legacy ? onlineExternalIds.has(m.external_id) : presences[m.external_id] ?? null,
5000
+ now,
3680
5001
  removable: canRemove?.(m) ?? false,
3681
5002
  onRemove: () => {
3682
5003
  void removeMember(m.external_id);
@@ -3687,20 +5008,22 @@ function MemberList({
3687
5008
  return /* @__PURE__ */ jsx("li", { className: "poolse-list__item", children: content }, m.id);
3688
5009
  }) });
3689
5010
  }
5011
+ var NO_IDS = [];
3690
5012
  function DefaultMemberRow({
3691
5013
  membership,
3692
5014
  avatarUrl,
3693
- online,
5015
+ presence,
5016
+ now,
3694
5017
  removable,
3695
5018
  onRemove,
3696
5019
  labelFor
3697
5020
  }) {
3698
5021
  const name = useDisplayName(membership.external_id, labelFor);
3699
5022
  return /* @__PURE__ */ jsxs("div", { className: "poolse-member-row", children: [
3700
- /* @__PURE__ */ jsx(Avatar, { src: avatarUrl, name, online, size: "md" }),
5023
+ typeof presence === "boolean" ? /* @__PURE__ */ jsx(Avatar, { src: avatarUrl, name, online: presence, size: "md" }) : /* @__PURE__ */ jsx(Avatar, { src: avatarUrl, name, presence, size: "md" }),
3701
5024
  /* @__PURE__ */ jsxs("div", { className: "poolse-member-row__body", children: [
3702
5025
  /* @__PURE__ */ jsx("div", { className: "poolse-member-row__name", children: name }),
3703
- /* @__PURE__ */ jsx("div", { className: "poolse-member-row__sub", children: online ? "online" : "offline" })
5026
+ typeof presence === "boolean" ? /* @__PURE__ */ jsx("div", { className: "poolse-member-row__sub", children: presence ? "online" : "offline" }) : presence ? /* @__PURE__ */ jsx("div", { className: "poolse-member-row__sub", children: presenceText(presence, now) }) : null
3704
5027
  ] }),
3705
5028
  /* @__PURE__ */ jsx(RoleBadge, { role: membership.role }),
3706
5029
  removable && /* @__PURE__ */ jsx(
@@ -4507,6 +5830,6 @@ function PoolseLogo({
4507
5830
  );
4508
5831
  }
4509
5832
 
4510
- export { AttachmentPreview, Avatar, CallControlButton, CallDeviceMenu, CallLogRow, CallVideoGrid, ChatHeader, ConversationList, ConversationView, EditableMessageBubble, GroupDetailsSheet, LiveCallBanner, MemberList, MentionInput, MessageActions, MessageBubble, MessageComposer, PoolseFonts, PoolseIcon, PoolseInbox, PoolseLogo, PoolseTheme, ReactionPicker, ReactionStrip, RoomJoinBar, RoomStage, ThreadView, TypingIndicator, UploadQueueStrip, UserName, UserPickerSheet, useDisplayName, usePoolseFonts, useSystemColorScheme, useTheme };
5833
+ export { AttachmentPreview, Avatar, CallControlButton, CallDeviceMenu, CallLogRow, CallVideoGrid, ChatHeader, ConversationList, ConversationView, EditableMessageBubble, EditedLabel, EmojiPicker, GroupDetailsSheet, LinkPreviewCard, LiveCallBanner, MemberList, MentionInput, MessageActions, MessageBubble, MessageComposer, PoolseFonts, PoolseIcon, PoolseInbox, PoolseLogo, PoolseTheme, PresenceBadge, ReactionPicker, ReactionStrip, RoomJoinBar, RoomStage, ThreadSummary, ThreadView, TypingIndicator, UploadQueueStrip, UserName, UserPickerSheet, formatRelativeTime, loadEmojiData, localDraftStorage, presenceStateLabel, presenceText, useDisplayName, useEditHistory, usePoolseFonts, useSystemColorScheme, useTheme };
4511
5834
  //# sourceMappingURL=index.js.map
4512
5835
  //# sourceMappingURL=index.js.map