@poolse/react-ui 3.5.0 → 3.6.1

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
  ] });
@@ -1865,14 +2725,15 @@ function QuotedCard({
1865
2725
  labelFor,
1866
2726
  onClick
1867
2727
  }) {
1868
- const senderLabel = quoted.sender_external_id ? labelFor?.(quoted.sender_external_id) ?? quoted.sender_external_id : "Unknown";
2728
+ const { profile: quotedSender } = useUser(quoted.sender_external_id ?? null);
2729
+ const senderLabel = quoted.sender_external_id ? labelFor?.(quoted.sender_external_id) ?? quotedSender?.displayName ?? quoted.sender_external_id : "Unknown";
1869
2730
  const isDeleted = !!quoted.deleted_at;
1870
2731
  const handleClick = onClick ? () => onClick(quoted.id) : void 0;
1871
2732
  return /* @__PURE__ */ jsxs(
1872
2733
  "button",
1873
2734
  {
1874
2735
  type: "button",
1875
- className: `poolse-quote ${isSelf ? "poolse-quote--self" : "poolse-quote--other"}`,
2736
+ className: `poolse-quote ${isSelf ? "poolse-quote--self" : "poolse-quote--other"}${isDeleted ? " poolse-quote--deleted" : ""}`,
1876
2737
  onClick: handleClick,
1877
2738
  disabled: !handleClick,
1878
2739
  "aria-label": `Quoted message from ${senderLabel}`,
@@ -2037,10 +2898,15 @@ function ReactionPicker({
2037
2898
  onClose
2038
2899
  }) {
2039
2900
  const rootRef = useRef(null);
2901
+ const [full, setFull] = useState(false);
2040
2902
  useEffect(() => {
2041
2903
  const firstBtn = rootRef.current?.querySelector("button");
2042
2904
  if (firstBtn instanceof HTMLElement) firstBtn.focus();
2043
2905
  }, []);
2906
+ const pick = (emoji) => {
2907
+ rememberEmoji(emoji);
2908
+ onPick(emoji);
2909
+ };
2044
2910
  useEffect(() => {
2045
2911
  if (!onClose) return;
2046
2912
  const onPointer = (e) => {
@@ -2069,7 +2935,10 @@ function ReactionPicker({
2069
2935
  e.preventDefault();
2070
2936
  }
2071
2937
  };
2072
- return /* @__PURE__ */ jsx(
2938
+ if (full) {
2939
+ return /* @__PURE__ */ jsx("div", { ref: rootRef, className: "poolse-reaction-picker poolse-reaction-picker--full", children: /* @__PURE__ */ jsx(EmojiPicker, { onPick: pick, ...onClose ? { onClose } : {} }) });
2940
+ }
2941
+ return /* @__PURE__ */ jsxs(
2073
2942
  "div",
2074
2943
  {
2075
2944
  ref: rootRef,
@@ -2077,18 +2946,34 @@ function ReactionPicker({
2077
2946
  role: "menu",
2078
2947
  "aria-label": "Pick a reaction",
2079
2948
  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
- ))
2949
+ children: [
2950
+ COMMON_EMOJIS.map((e) => /* @__PURE__ */ jsx(
2951
+ "button",
2952
+ {
2953
+ type: "button",
2954
+ role: "menuitem",
2955
+ className: "poolse-reaction-picker__btn",
2956
+ onClick: () => pick(e),
2957
+ "aria-label": `React with ${e}`,
2958
+ children: e
2959
+ },
2960
+ e
2961
+ )),
2962
+ /* @__PURE__ */ jsx(
2963
+ "button",
2964
+ {
2965
+ type: "button",
2966
+ role: "menuitem",
2967
+ className: "poolse-reaction-picker__btn poolse-reaction-picker__more",
2968
+ "aria-label": "More emoji",
2969
+ title: "More emoji",
2970
+ onPointerEnter: () => void loadEmojiData(),
2971
+ onFocus: () => void loadEmojiData(),
2972
+ onClick: () => setFull(true),
2973
+ children: /* @__PURE__ */ jsx(PoolseIcon, { name: "plus", size: 16, label: null })
2974
+ }
2975
+ )
2976
+ ]
2092
2977
  }
2093
2978
  );
2094
2979
  }
@@ -2097,6 +2982,7 @@ function MessageActions({
2097
2982
  onReply,
2098
2983
  onQuote,
2099
2984
  onCopy,
2985
+ onMarkUnread,
2100
2986
  onEdit,
2101
2987
  onDelete,
2102
2988
  moreMenu = false,
@@ -2104,7 +2990,7 @@ function MessageActions({
2104
2990
  }) {
2105
2991
  const [pickerOpen, setPickerOpen] = useState(false);
2106
2992
  const [menuOpen, setMenuOpen] = useState(false);
2107
- const hasMore = !!(onCopy || onEdit || onDelete);
2993
+ const hasMore = !!(onCopy || onMarkUnread || onEdit || onDelete);
2108
2994
  return /* @__PURE__ */ jsxs("div", { className: "poolse-msg-actions", role: "toolbar", "aria-label": "Message actions", children: [
2109
2995
  onReact && /* @__PURE__ */ jsxs(Fragment, { children: [
2110
2996
  /* @__PURE__ */ jsx(
@@ -2151,6 +3037,11 @@ function MessageActions({
2151
3037
  },
2152
3038
  children: [
2153
3039
  onCopy && { label: "Copy", icon: "copy", run: onCopy },
3040
+ onMarkUnread && {
3041
+ label: "Mark unread",
3042
+ icon: "message",
3043
+ run: onMarkUnread
3044
+ },
2154
3045
  onEdit && { label: "Edit", icon: "edit", run: onEdit },
2155
3046
  onDelete && { label: "Delete", icon: "trash", run: onDelete }
2156
3047
  ].filter((item) => !!item).map((item) => /* @__PURE__ */ jsxs(
@@ -2177,6 +3068,7 @@ function MessageActions({
2177
3068
  onReply && /* @__PURE__ */ jsx(ActionButton, { label: "Reply in thread", icon: "messages", onClick: onReply }),
2178
3069
  onQuote && /* @__PURE__ */ jsx(ActionButton, { label: "Reply", icon: "reply", onClick: onQuote }),
2179
3070
  onCopy && /* @__PURE__ */ jsx(ActionButton, { label: "Copy", icon: "copy", onClick: onCopy }),
3071
+ onMarkUnread && /* @__PURE__ */ jsx(ActionButton, { label: "Mark unread", icon: "message", onClick: onMarkUnread }),
2180
3072
  onEdit && /* @__PURE__ */ jsx(ActionButton, { label: "Edit", icon: "edit", onClick: onEdit }),
2181
3073
  onDelete && /* @__PURE__ */ jsx(ActionButton, { label: "Delete", icon: "trash", danger: true, onClick: onDelete }),
2182
3074
  children
@@ -2249,6 +3141,36 @@ function InlineReactions({
2249
3141
  );
2250
3142
  }) });
2251
3143
  }
3144
+ function ThreadSummary({ message, onOpen, maxAvatars = 3, className }) {
3145
+ const now = useNow();
3146
+ const count = message.reply_count ?? 0;
3147
+ if (count <= 0) return null;
3148
+ const participants = (message.thread_participants ?? []).slice(0, maxAvatars);
3149
+ const replies = `${count} ${count === 1 ? "reply" : "replies"}`;
3150
+ const last = formatRelativeTime(message.last_reply_at, now);
3151
+ return /* @__PURE__ */ jsxs(
3152
+ "button",
3153
+ {
3154
+ type: "button",
3155
+ className: ["poolse-thread-summary", className].filter(Boolean).join(" "),
3156
+ onClick: onOpen,
3157
+ "aria-label": `View ${replies}`,
3158
+ children: [
3159
+ 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 }),
3160
+ /* @__PURE__ */ jsx("span", { className: "poolse-thread-summary__count", children: replies }),
3161
+ last ? /* @__PURE__ */ jsxs("span", { className: "poolse-thread-summary__last", children: [
3162
+ "\xB7 last reply ",
3163
+ last
3164
+ ] }) : null
3165
+ ]
3166
+ }
3167
+ );
3168
+ }
3169
+ function ParticipantAvatar({ participant }) {
3170
+ const { profile } = useUser(participant.external_id);
3171
+ const name = profile?.displayName ?? participant.external_id ?? "Someone";
3172
+ return /* @__PURE__ */ jsx(Avatar, { src: profile?.avatarUrl ?? null, name, size: "xs" });
3173
+ }
2252
3174
  var TRIM_BUFFER = 40;
2253
3175
  function FlatMessageRow({
2254
3176
  msg,
@@ -2267,12 +3189,15 @@ function FlatMessageRow({
2267
3189
  onDelete,
2268
3190
  onOpenThread,
2269
3191
  onQuote,
3192
+ onMarkUnread,
2270
3193
  labelFor,
2271
3194
  onQuotedClick,
2272
3195
  groupPosition = "standalone",
2273
3196
  maxBodyLength = 0,
2274
3197
  markdown = false,
2275
3198
  showAvatar = layout === "list",
3199
+ showPresence = false,
3200
+ linkPreviews = true,
2276
3201
  onSenderPress,
2277
3202
  onAvatarPress,
2278
3203
  timeFormat,
@@ -2300,10 +3225,19 @@ function FlatMessageRow({
2300
3225
  const deleted = !!msg.deleted_at;
2301
3226
  const time = formatMessageTime(msg.inserted_at, timeFormat);
2302
3227
  const replyCount = msg.reply_count ?? 0;
2303
- const showThreadLink = threads && !deleted && !msg.thread_root_id && replyCount > 0;
3228
+ const showThreadLink = threads && !msg.thread_root_id && replyCount > 0;
2304
3229
  const showActions = actions && !deleted && !editing;
2305
3230
  const timeEl = (className) => /* @__PURE__ */ jsx("time", { className, dateTime: msg.inserted_at, children: time });
2306
3231
  const avatarSize = compact ? "sm" : "md";
3232
+ const avatarEl = /* @__PURE__ */ jsx(
3233
+ Avatar,
3234
+ {
3235
+ src: sender.avatarUrl,
3236
+ name: senderName,
3237
+ size: avatarSize,
3238
+ ...showPresence && msg.sender_external_id ? { presence: true, userId: msg.sender_external_id } : {}
3239
+ }
3240
+ );
2307
3241
  const avatar = !showAvatar ? null : onAvatarPress && !isSelf ? /* @__PURE__ */ jsx(
2308
3242
  "button",
2309
3243
  {
@@ -2311,9 +3245,9 @@ function FlatMessageRow({
2311
3245
  className: "poolse-row__avatar-button",
2312
3246
  "aria-label": senderName,
2313
3247
  onClick: () => onAvatarPress(sender),
2314
- children: /* @__PURE__ */ jsx(Avatar, { src: sender.avatarUrl, name: senderName, size: avatarSize })
3248
+ children: avatarEl
2315
3249
  }
2316
- ) : /* @__PURE__ */ jsx(Avatar, { src: sender.avatarUrl, name: senderName, size: avatarSize });
3250
+ ) : avatarEl;
2317
3251
  const nameStyle = compact ? { color: userColor(msg.sender_external_id ?? msg.sender_id ?? "") } : void 0;
2318
3252
  const name = onSenderPress && !isSelf ? /* @__PURE__ */ jsx(
2319
3253
  "button",
@@ -2329,7 +3263,7 @@ function FlatMessageRow({
2329
3263
  name,
2330
3264
  timeEl("poolse-row__time")
2331
3265
  ] }) : null;
2332
- const quote = msg.quoted_message !== void 0 && msg.quoted_message !== null ? /* @__PURE__ */ jsx(
3266
+ const quote = deleted ? null : msg.quoted_message !== void 0 && msg.quoted_message !== null ? /* @__PURE__ */ jsx(
2333
3267
  QuotedCard,
2334
3268
  {
2335
3269
  quoted: msg.quoted_message,
@@ -2345,8 +3279,14 @@ function FlatMessageRow({
2345
3279
  images.length > 0 && /* @__PURE__ */ jsx(ImageMosaic, { images }),
2346
3280
  files.length > 0 && /* @__PURE__ */ jsx("div", { className: "poolse-message__files", children: files.map((att) => /* @__PURE__ */ jsx(AttachmentPreview, { attachment: att }, att.id)) })
2347
3281
  ] }) : null;
3282
+ const editHistory = useEditHistory(msg.id);
2348
3283
  const meta = /* @__PURE__ */ jsxs(Fragment, { children: [
2349
- msg.edited_at && !deleted ? /* @__PURE__ */ jsx("span", { className: "poolse-row__edited", children: "(edited)" }) : null,
3284
+ msg.edited_at && !deleted ? /* @__PURE__ */ jsxs("span", { className: "poolse-row__edited", children: [
3285
+ "(",
3286
+ editHistory.label(),
3287
+ ")"
3288
+ ] }) : null,
3289
+ editHistory.popover,
2350
3290
  isSelf && readState ? /* @__PURE__ */ jsx("span", { className: "poolse-row__receipt", children: /* @__PURE__ */ jsx(
2351
3291
  PoolseIcon,
2352
3292
  {
@@ -2388,21 +3328,12 @@ function FlatMessageRow({
2388
3328
  onRemove: (e) => void reactionsHook.removeReaction(e)
2389
3329
  }
2390
3330
  ) : null;
2391
- const threadEl = showThreadLink ? /* @__PURE__ */ jsxs(
2392
- "button",
3331
+ const threadEl = showThreadLink ? /* @__PURE__ */ jsx(
3332
+ ThreadSummary,
2393
3333
  {
2394
- type: "button",
3334
+ message: msg,
2395
3335
  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
- ]
3336
+ ...onOpenThread ? { onOpen: onOpenThread } : {}
2406
3337
  }
2407
3338
  ) : null;
2408
3339
  const toolbar = showActions ? /* @__PURE__ */ jsx("div", { className: "poolse-row__toolbar", children: /* @__PURE__ */ jsx(
@@ -2417,6 +3348,7 @@ function FlatMessageRow({
2417
3348
  void navigator?.clipboard?.writeText(msg.body ?? "").catch(() => void 0);
2418
3349
  }
2419
3350
  } : {},
3351
+ ...!isSelf && onMarkUnread ? { onMarkUnread } : {},
2420
3352
  ...isSelf && onStartEdit ? { onEdit: onStartEdit } : {},
2421
3353
  ...isSelf && onDelete ? { onDelete } : {}
2422
3354
  }
@@ -2426,6 +3358,7 @@ function FlatMessageRow({
2426
3358
  quote,
2427
3359
  renderSlot(slots?.attachments, ctx, attachmentsEl),
2428
3360
  renderSlot(slots?.body, ctx, body),
3361
+ linkPreviews && !editing && hasLinkPreviews(msg) ? /* @__PURE__ */ jsx(MessageLinkPreviews, { message: msg, canRemove: isSelf }) : null,
2429
3362
  renderSlot(slots?.reactions, ctx, reactionsEl),
2430
3363
  renderSlot(slots?.thread, ctx, threadEl)
2431
3364
  ] });
@@ -2468,7 +3401,7 @@ function FlatBody({
2468
3401
  }) {
2469
3402
  const [expanded, setExpanded] = useState(false);
2470
3403
  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" }) });
3404
+ 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
3405
  }
2473
3406
  const raw = message.body ?? "";
2474
3407
  if (!raw) {
@@ -2543,6 +3476,7 @@ function BubbleMessageRow({
2543
3476
  onDelete,
2544
3477
  onOpenThread,
2545
3478
  onQuote,
3479
+ onMarkUnread,
2546
3480
  labelFor,
2547
3481
  onQuotedClick,
2548
3482
  groupPosition = "standalone",
@@ -2550,6 +3484,8 @@ function BubbleMessageRow({
2550
3484
  markdown = false,
2551
3485
  showSenderName = false,
2552
3486
  showAvatar = false,
3487
+ showPresence = false,
3488
+ linkPreviews = true,
2553
3489
  onSenderPress,
2554
3490
  onAvatarPress,
2555
3491
  timeFormat,
@@ -2573,7 +3509,7 @@ function BubbleMessageRow({
2573
3509
  const showReactions = reactions && !msg.deleted_at;
2574
3510
  const showActions = actions && !msg.deleted_at && !editing;
2575
3511
  const replyCount = msg.reply_count ?? 0;
2576
- const showThreadPill = threads && !msg.deleted_at && !msg.thread_root_id && replyCount > 0;
3512
+ const showThreadPill = threads && !msg.thread_root_id && replyCount > 0;
2577
3513
  const handleSave = onSaveEdit ?? (async () => void 0);
2578
3514
  const handleCancel = onCancelEdit ?? (() => void 0);
2579
3515
  const { actionsOpen, setActionsOpen, rowRef, onRowClick } = useRowActions();
@@ -2620,6 +3556,7 @@ function BubbleMessageRow({
2620
3556
  groupPosition,
2621
3557
  senderName,
2622
3558
  avatarUrl: senderProfile?.avatarUrl ?? null,
3559
+ presenceId: showPresence ? msg.sender_external_id : null,
2623
3560
  ...onAvatarPress ? { onAvatarPress: () => onAvatarPress(sender) } : {},
2624
3561
  children: /* @__PURE__ */ jsx(
2625
3562
  MessageBubble,
@@ -2632,6 +3569,7 @@ function BubbleMessageRow({
2632
3569
  showSenderName,
2633
3570
  ...onSenderPress ? { onSenderPress: () => onSenderPress(sender) } : {},
2634
3571
  showAttachments: attachments,
3572
+ linkPreviews,
2635
3573
  ...readState ? { readState } : {},
2636
3574
  ...labelFor ? { labelFor } : {},
2637
3575
  ...onQuotedClick ? { onQuotedClick } : {},
@@ -2673,21 +3611,12 @@ function BubbleMessageRow({
2673
3611
  renderSlot(
2674
3612
  slots?.thread,
2675
3613
  slotContext,
2676
- showThreadPill ? /* @__PURE__ */ jsxs(
2677
- "button",
3614
+ showThreadPill ? /* @__PURE__ */ jsx(
3615
+ ThreadSummary,
2678
3616
  {
2679
- type: "button",
3617
+ message: msg,
2680
3618
  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
- ]
3619
+ ...onOpenThread ? { onOpen: onOpenThread } : {}
2691
3620
  }
2692
3621
  ) : null
2693
3622
  ),
@@ -2713,6 +3642,7 @@ function BubbleMessageRow({
2713
3642
  void navigator?.clipboard?.writeText(msg.body ?? "").catch(() => void 0);
2714
3643
  }
2715
3644
  } : {},
3645
+ ...!isSelf && onMarkUnread ? { onMarkUnread } : {},
2716
3646
  ...isSelf && onStartEdit ? { onEdit: onStartEdit } : {},
2717
3647
  ...isSelf && onDelete ? { onDelete } : {}
2718
3648
  }
@@ -2730,11 +3660,21 @@ function BubbleWithAvatar({
2730
3660
  groupPosition,
2731
3661
  senderName,
2732
3662
  avatarUrl,
3663
+ presenceId,
2733
3664
  onAvatarPress,
2734
3665
  children
2735
3666
  }) {
2736
3667
  if (isSelf || !showAvatar) return /* @__PURE__ */ jsx(Fragment, { children });
2737
3668
  const isLastOfCluster = groupPosition === "last" || groupPosition === "standalone";
3669
+ const avatar = /* @__PURE__ */ jsx(
3670
+ Avatar,
3671
+ {
3672
+ src: avatarUrl,
3673
+ name: senderName,
3674
+ size: "sm",
3675
+ ...presenceId ? { presence: true, userId: presenceId } : {}
3676
+ }
3677
+ );
2738
3678
  return /* @__PURE__ */ jsxs("div", { className: "poolse-bubble-shell", children: [
2739
3679
  /* @__PURE__ */ jsx("div", { className: "poolse-bubble-shell__avatar", children: !isLastOfCluster ? null : onAvatarPress ? /* @__PURE__ */ jsx(
2740
3680
  "button",
@@ -2743,9 +3683,9 @@ function BubbleWithAvatar({
2743
3683
  className: "poolse-bubble-shell__avatar-button",
2744
3684
  "aria-label": senderName,
2745
3685
  onClick: onAvatarPress,
2746
- children: /* @__PURE__ */ jsx(Avatar, { src: avatarUrl, name: senderName, size: "sm" })
3686
+ children: avatar
2747
3687
  }
2748
- ) : /* @__PURE__ */ jsx(Avatar, { src: avatarUrl, name: senderName, size: "sm" }) }),
3688
+ ) : avatar }),
2749
3689
  children
2750
3690
  ] });
2751
3691
  }
@@ -2755,7 +3695,9 @@ function ThreadView({
2755
3695
  onClose,
2756
3696
  renderMessage,
2757
3697
  layout,
2758
- timeFormat
3698
+ timeFormat,
3699
+ maxFileSize,
3700
+ acceptFileTypes
2759
3701
  }) {
2760
3702
  const { me } = useMe();
2761
3703
  const {
@@ -2890,7 +3832,9 @@ function ThreadView({
2890
3832
  body,
2891
3833
  ...opts?.attachment_ids && opts.attachment_ids.length > 0 ? { attachment_ids: opts.attachment_ids } : {}
2892
3834
  }),
2893
- placeholder: "Reply in thread\u2026"
3835
+ placeholder: "Reply in thread\u2026",
3836
+ ...maxFileSize !== void 0 ? { maxFileSize } : {},
3837
+ ...acceptFileTypes ? { acceptFileTypes } : {}
2894
3838
  }
2895
3839
  ),
2896
3840
  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 +3846,31 @@ function ThreadView({
2902
3846
  }
2903
3847
  );
2904
3848
  }
3849
+ var MAX_NAME_CHARS = 24;
3850
+ function UserName({
3851
+ externalId,
3852
+ labelFor,
3853
+ emptyFallback = "Unknown",
3854
+ className
3855
+ }) {
3856
+ const { profile } = useUser(labelFor ? null : externalId);
3857
+ const name = resolveDisplayName(externalId, profile?.displayName, labelFor, emptyFallback);
3858
+ return /* @__PURE__ */ jsx("span", { className, children: truncate(name) });
3859
+ }
3860
+ function useDisplayName(externalId, labelFor, emptyFallback = "Unknown") {
3861
+ const { profile } = useUser(labelFor ? null : externalId);
3862
+ return resolveDisplayName(externalId, profile?.displayName, labelFor, emptyFallback);
3863
+ }
3864
+ function resolveDisplayName(externalId, resolved, labelFor, emptyFallback) {
3865
+ if (!externalId) return emptyFallback;
3866
+ if (labelFor) return labelFor(externalId);
3867
+ if (resolved) return resolved;
3868
+ return externalId;
3869
+ }
3870
+ function truncate(s) {
3871
+ if (s.length <= MAX_NAME_CHARS) return s;
3872
+ return s.slice(0, MAX_NAME_CHARS - 1) + "\u2026";
3873
+ }
2905
3874
  function TypingIndicator({ typing, labelFor }) {
2906
3875
  const ids = Array.from(typing);
2907
3876
  const isTyping = ids.length > 0;
@@ -2949,10 +3918,14 @@ function ConversationView({
2949
3918
  reactions = TRUE,
2950
3919
  mentions = TRUE,
2951
3920
  attachments = TRUE,
3921
+ maxFileSize,
3922
+ acceptFileTypes,
3923
+ emojiPicker = TRUE,
2952
3924
  actions = TRUE,
2953
3925
  threads = TRUE,
2954
3926
  quotations = TRUE,
2955
3927
  readReceipts = TRUE,
3928
+ linkPreviews = TRUE,
2956
3929
  markdown = TRUE,
2957
3930
  maxBodyLength = 200,
2958
3931
  grouping = TRUE,
@@ -2961,6 +3934,7 @@ function ConversationView({
2961
3934
  layout = "bubbles",
2962
3935
  density = "comfortable",
2963
3936
  showAvatars,
3937
+ showPresence = false,
2964
3938
  timeFormat,
2965
3939
  slots,
2966
3940
  daySeparators = TRUE,
@@ -2975,7 +3949,9 @@ function ConversationView({
2975
3949
  readOnly = false,
2976
3950
  onCallBack,
2977
3951
  onJoinCall,
2978
- currentCallId = null
3952
+ currentCallId = null,
3953
+ persistDrafts = TRUE,
3954
+ draftStorage
2979
3955
  }) {
2980
3956
  usePoolseFonts(loadFonts);
2981
3957
  const showComposer = composer && !readOnly;
@@ -3007,13 +3983,16 @@ function ConversationView({
3007
3983
  const status = useRealtimeStatus();
3008
3984
  const wantsMemberCount = senderLabels === "auto" || avatars === "auto";
3009
3985
  const membersOn = mentions || readReceipts || wantsMemberCount;
3010
- const { members } = useMembers(membersOn ? conversationId : "");
3986
+ const { members, loading: membersLoading } = useMembers(membersOn ? conversationId : "");
3987
+ const chat = usePoolse();
3011
3988
  const isGroupChat = members.length > 2;
3012
3989
  const showSenderLabelsResolved = senderLabels === "always" || senderLabels === "auto" && isGroupChat;
3013
3990
  const showAvatarsResolved = showAvatars ?? (layout === "list" ? true : layout === "compact" ? false : avatars === "always" || avatars === "auto" && isGroupChat);
3014
3991
  const groupWindowMs = groupWindowMinutes !== void 0 ? groupWindowMinutes * 60 * 1e3 : groupingWindowMs ?? 5 * 60 * 1e3;
3015
3992
  const layoutProps = {
3016
3993
  layout,
3994
+ showPresence,
3995
+ linkPreviews,
3017
3996
  ...timeFormat ? { timeFormat } : {},
3018
3997
  ...slots ? { slots } : {}
3019
3998
  };
@@ -3084,12 +4063,14 @@ function ConversationView({
3084
4063
  if (el) el.scrollTop = el.scrollHeight;
3085
4064
  }, [streamedChars, atBottom]);
3086
4065
  const lastMarkedReadRef = useRef(null);
4066
+ const [markerReadyFor, setMarkerReadyFor] = useState(null);
3087
4067
  useEffect(() => {
3088
4068
  if (!atBottom) return;
3089
4069
  if (messages.length === 0) return;
3090
4070
  const tail = messages[messages.length - 1];
3091
4071
  if (!tail) return;
3092
4072
  if (tail.sequence === Number.MAX_SAFE_INTEGER) return;
4073
+ if (membersOn && markerReadyFor !== conversationId) return;
3093
4074
  if (lastMarkedReadRef.current === tail.id) return;
3094
4075
  lastMarkedReadRef.current = tail.id;
3095
4076
  void markReadUpTo(tail.id).then(() => {
@@ -3097,7 +4078,33 @@ function ConversationView({
3097
4078
  }).catch(() => {
3098
4079
  lastMarkedReadRef.current = null;
3099
4080
  });
3100
- }, [atBottom, messages, markReadUpTo, onMarkedRead, conversationId]);
4081
+ }, [atBottom, messages, markReadUpTo, onMarkedRead, conversationId, membersOn, markerReadyFor]);
4082
+ const [unreadMarker, setUnreadMarker] = useState(null);
4083
+ const markerTakenRef = useRef(null);
4084
+ useEffect(() => {
4085
+ setUnreadMarker(null);
4086
+ markerTakenRef.current = null;
4087
+ }, [conversationId]);
4088
+ useEffect(() => {
4089
+ if (markerTakenRef.current === conversationId) return;
4090
+ if (!membersOn || loading || membersLoading) return;
4091
+ if (members.some((m) => m.conversation_id !== conversationId)) return;
4092
+ if (!me && members.length > 0) return;
4093
+ markerTakenRef.current = conversationId;
4094
+ setMarkerReadyFor(conversationId);
4095
+ const mine = me ? members.find((m) => m.user_id === me.id) : void 0;
4096
+ if (!mine) return;
4097
+ let after = mine.last_read_sequence ?? null;
4098
+ if (after === null && mine.last_read_message_id) {
4099
+ after = messages.find((m) => m.id === mine.last_read_message_id)?.sequence ?? null;
4100
+ if (after === null) return;
4101
+ }
4102
+ setUnreadMarker({
4103
+ conversationId,
4104
+ afterSequence: after ?? 0,
4105
+ lastReadId: mine.last_read_message_id
4106
+ });
4107
+ }, [conversationId, membersOn, loading, membersLoading, me, members, messages]);
3101
4108
  const scrollToBottom = () => {
3102
4109
  const el = listRef.current;
3103
4110
  if (el) el.scrollTop = el.scrollHeight;
@@ -3108,6 +4115,74 @@ function ConversationView({
3108
4115
  () => messages.filter((m) => isMessageVisibleTo(m, meIdForFeed)),
3109
4116
  [messages, meIdForFeed]
3110
4117
  );
4118
+ const marker = unreadMarker && unreadMarker.conversationId === conversationId ? unreadMarker : null;
4119
+ const unread = useMemo(() => {
4120
+ if (!marker) return { firstId: null, reaches: true, any: false };
4121
+ const isUnread = (m) => m.sequence > marker.afterSequence && m.sequence !== Number.MAX_SAFE_INTEGER && m.sender_id !== meIdForFeed;
4122
+ const reaches = !hasMore || visibleMessages.some((m) => m.sequence <= marker.afterSequence);
4123
+ const first = visibleMessages.find(isUnread) ?? null;
4124
+ return {
4125
+ firstId: reaches ? first?.id ?? null : null,
4126
+ reaches,
4127
+ any: first !== null
4128
+ };
4129
+ }, [marker, visibleMessages, hasMore, meIdForFeed]);
4130
+ const dividerRef = useRef(null);
4131
+ const [dividerInView, setDividerInView] = useState(false);
4132
+ const [jumpDismissed, setJumpDismissed] = useState(false);
4133
+ useEffect(() => {
4134
+ setJumpDismissed(false);
4135
+ }, [conversationId, marker?.afterSequence]);
4136
+ useEffect(() => {
4137
+ setDividerInView(false);
4138
+ const el = dividerRef.current;
4139
+ const root = listRef.current;
4140
+ if (!el || !root || typeof IntersectionObserver === "undefined") return;
4141
+ const io = new IntersectionObserver(([entry]) => setDividerInView(!!entry?.isIntersecting), {
4142
+ root,
4143
+ threshold: 0
4144
+ });
4145
+ io.observe(el);
4146
+ return () => io.disconnect();
4147
+ }, [unread.firstId]);
4148
+ const [jump, setJump] = useState(null);
4149
+ const jumpToFirstUnread = () => {
4150
+ if (!marker) return;
4151
+ if (unread.firstId) {
4152
+ scrollDividerIntoView(dividerRef.current);
4153
+ return;
4154
+ }
4155
+ setJump("loading");
4156
+ void loadUntil(marker.lastReadId ?? NO_MESSAGE).catch(() => false).then(() => {
4157
+ if (conversationIdRef.current === marker.conversationId) {
4158
+ setJump((j) => j ? "loaded" : j);
4159
+ }
4160
+ });
4161
+ };
4162
+ useEffect(() => {
4163
+ if (!jump) return;
4164
+ if (unread.firstId) {
4165
+ setJump(null);
4166
+ scrollDividerIntoView(dividerRef.current);
4167
+ } else if (jump === "loaded") {
4168
+ setJump(null);
4169
+ }
4170
+ }, [jump, unread.firstId]);
4171
+ useEffect(() => {
4172
+ setJump(null);
4173
+ }, [conversationId]);
4174
+ const showJump = !!marker && unread.any && !jumpDismissed && (!unread.firstId || !dividerInView);
4175
+ const markUnreadFrom = async (msg) => {
4176
+ const tail = messages[messages.length - 1];
4177
+ if (tail) lastMarkedReadRef.current = tail.id;
4178
+ try {
4179
+ await chat.conversations.one(conversationId).markUnread(msg.id);
4180
+ markerTakenRef.current = conversationId;
4181
+ setUnreadMarker({ conversationId, afterSequence: msg.sequence - 1, lastReadId: null });
4182
+ } catch {
4183
+ setSendNotice("Couldn't mark the message unread.");
4184
+ }
4185
+ };
3111
4186
  const [pendingFocusId, setPendingFocusId] = useState(null);
3112
4187
  const [focusMissing, setFocusMissing] = useState(false);
3113
4188
  const onFocusNotFoundRef = useRef(onFocusMessageNotFound);
@@ -3176,12 +4251,68 @@ function ConversationView({
3176
4251
  () => threadRootId ? messages.find((m) => m.id === threadRootId) ?? null : null,
3177
4252
  [threadRootId, messages]
3178
4253
  );
3179
- const [replyingTo, setReplyingTo] = useState(null);
4254
+ const [replyingTo, setReplyingToState] = useState(null);
4255
+ const mentionComposer = mentions && members.length > 0;
3180
4256
  useEffect(() => {
3181
- setReplyingTo(null);
4257
+ setReplyingToState(null);
3182
4258
  setEditingId(null);
3183
4259
  setThreadRootId(null);
4260
+ setSendNotice(null);
3184
4261
  }, [conversationId]);
4262
+ const meIdForDrafts = me?.id ?? null;
4263
+ const draftsOn = persistDrafts && showComposer;
4264
+ const storage = draftStorage ?? localDraftStorage;
4265
+ const draftRef = useRef({ text: "", replyTo: null });
4266
+ const draftKeyFor = useCallback(
4267
+ () => draftsOn && meIdForDrafts ? draftKey(meIdForDrafts, conversationIdRef.current) : null,
4268
+ [draftsOn, meIdForDrafts]
4269
+ );
4270
+ const saveDraft = useCallback(
4271
+ (patch) => {
4272
+ draftRef.current = { ...draftRef.current, ...patch };
4273
+ const key = draftKeyFor();
4274
+ if (key) writeDraft(storage, key, draftRef.current);
4275
+ },
4276
+ [draftKeyFor, storage]
4277
+ );
4278
+ const setReplyingTo = useCallback(
4279
+ (m) => {
4280
+ setReplyingToState(m);
4281
+ saveDraft({ replyTo: m });
4282
+ },
4283
+ [saveDraft]
4284
+ );
4285
+ useEffect(() => {
4286
+ draftRef.current = { text: "", replyTo: null };
4287
+ const key = draftKeyFor();
4288
+ if (!key) return;
4289
+ let live = true;
4290
+ const apply = (d) => {
4291
+ if (!live || !d) return;
4292
+ const composer2 = composerRef.current;
4293
+ if (d.text && composer2 && composer2.getText() === "") composer2.setText(d.text);
4294
+ draftRef.current = { text: composer2?.getText() || d.text, replyTo: d.replyTo };
4295
+ if (d.replyTo && canQuote) setReplyingToState((cur) => cur ?? d.replyTo);
4296
+ };
4297
+ const found = readDraft(storage, key);
4298
+ if (found instanceof Promise) void found.then(apply);
4299
+ else apply(found);
4300
+ return () => {
4301
+ live = false;
4302
+ };
4303
+ }, [conversationId, draftKeyFor, storage, canQuote, mentionComposer]);
4304
+ const onComposerChange = useCallback((text) => saveDraft({ text }), [saveDraft]);
4305
+ useEffect(() => {
4306
+ if (!replyingTo) return;
4307
+ const current = messages.find((m) => m.id === replyingTo.id);
4308
+ if (current?.deleted_at) setReplyingTo(null);
4309
+ }, [messages, replyingTo, setReplyingTo]);
4310
+ const [sendNotice, setSendNotice] = useState(null);
4311
+ useEffect(() => {
4312
+ if (!sendNotice) return;
4313
+ const t = setTimeout(() => setSendNotice(null), 4e3);
4314
+ return () => clearTimeout(t);
4315
+ }, [sendNotice]);
3185
4316
  const scrollToOriginal = (id) => {
3186
4317
  const root = listRef.current;
3187
4318
  if (!root) return;
@@ -3218,39 +4349,69 @@ function ConversationView({
3218
4349
  const files = Array.from(e.dataTransfer?.files ?? []);
3219
4350
  if (files.length > 0) composerRef.current?.addFiles(files);
3220
4351
  };
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);
4352
+ const sendRequest = async (req) => {
4353
+ try {
4354
+ await send(req);
4355
+ } catch (err) {
4356
+ if (err instanceof ApiError && err.code === "quoted_message_deleted") {
4357
+ setReplyingTo(null);
4358
+ setSendNotice("The message you replied to was deleted.");
4359
+ const body = req.body;
4360
+ if (body) {
4361
+ setTimeout(() => {
4362
+ const composer2 = composerRef.current;
4363
+ if (composer2 && composer2.getText() === "") composer2.setText(body);
4364
+ }, 0);
4365
+ }
4366
+ return;
4367
+ }
4368
+ throw err;
4369
+ }
4370
+ setReplyingToState(null);
4371
+ setUnreadMarker(null);
4372
+ draftRef.current = { text: "", replyTo: null };
4373
+ const key = draftKeyFor();
4374
+ if (key) clearDraft(storage, key);
3228
4375
  };
3229
- const onSendWithMentions = async (req) => {
3230
- await send(req);
3231
- setReplyingTo(null);
4376
+ const onSendBody = (body, opts) => sendRequest({
4377
+ body,
4378
+ ...opts?.quoted_message_id ? { quoted_message_id: opts.quoted_message_id } : {},
4379
+ ...opts?.attachment_ids && opts.attachment_ids.length > 0 ? { attachment_ids: opts.attachment_ids } : {}
4380
+ });
4381
+ const onSendWithMentions = (req) => sendRequest(req);
4382
+ const attachmentRules = {
4383
+ ...maxFileSize !== void 0 ? { maxFileSize } : {},
4384
+ ...acceptFileTypes ? { acceptFileTypes } : {}
3232
4385
  };
3233
- const Composer = mentions && members.length > 0 ? /* @__PURE__ */ jsx(
4386
+ const Composer = mentionComposer ? /* @__PURE__ */ jsx(
3234
4387
  MentionInput,
3235
4388
  {
3236
4389
  ref: composerRef,
4390
+ onValueChange: onComposerChange,
3237
4391
  conversationId,
3238
4392
  onSend: onSendWithMentions,
3239
4393
  onTyping: signalTyping,
3240
4394
  attachments,
4395
+ emojiPicker,
4396
+ ...attachmentRules,
3241
4397
  ...labelFor ? { labelFor } : {},
3242
4398
  ...canQuote ? { replyingTo, onCancelReply: () => setReplyingTo(null) } : {}
3243
- }
4399
+ },
4400
+ conversationId
3244
4401
  ) : /* @__PURE__ */ jsx(
3245
4402
  MessageComposer,
3246
4403
  {
3247
4404
  ref: composerRef,
4405
+ onValueChange: onComposerChange,
3248
4406
  onSend: onSendBody,
3249
4407
  onTyping: signalTyping,
3250
4408
  attachments,
4409
+ emojiPicker,
4410
+ ...attachmentRules,
3251
4411
  ...labelFor ? { labelFor } : {},
3252
4412
  ...canQuote ? { replyingTo, onCancelReply: () => setReplyingTo(null) } : {}
3253
- }
4413
+ },
4414
+ conversationId
3254
4415
  );
3255
4416
  return /* @__PURE__ */ jsxs("div", { className: "poolse-conversation-shell", children: [
3256
4417
  /* @__PURE__ */ jsxs(
@@ -3291,6 +4452,14 @@ function ConversationView({
3291
4452
  }
3292
4453
  ),
3293
4454
  focusMissing && /* @__PURE__ */ jsx("div", { className: "poolse-conversation__status", role: "status", "aria-live": "polite", children: "That message isn't available." }),
4455
+ sendNotice && /* @__PURE__ */ jsx(
4456
+ "div",
4457
+ {
4458
+ className: "poolse-conversation__status poolse-conversation__status--error",
4459
+ role: "alert",
4460
+ children: sendNotice
4461
+ }
4462
+ ),
3294
4463
  /* @__PURE__ */ jsxs(
3295
4464
  "div",
3296
4465
  {
@@ -3302,6 +4471,31 @@ function ConversationView({
3302
4471
  "aria-relevant": "additions",
3303
4472
  children: [
3304
4473
  hasMore && /* @__PURE__ */ jsx("div", { ref: topSentinelRef, "aria-hidden": "true", style: { height: 1 } }),
4474
+ showJump && /* @__PURE__ */ jsxs("div", { className: "poolse-conversation__jump-unread", children: [
4475
+ /* @__PURE__ */ jsxs(
4476
+ "button",
4477
+ {
4478
+ type: "button",
4479
+ className: "poolse-conversation__jump-unread-btn",
4480
+ onClick: jumpToFirstUnread,
4481
+ disabled: jump !== null,
4482
+ children: [
4483
+ /* @__PURE__ */ jsx(PoolseIcon, { name: "chevron-up", size: 14, label: null }),
4484
+ jump ? "Loading\u2026" : "Jump to first unread"
4485
+ ]
4486
+ }
4487
+ ),
4488
+ /* @__PURE__ */ jsx(
4489
+ "button",
4490
+ {
4491
+ type: "button",
4492
+ className: "poolse-conversation__jump-unread-close",
4493
+ "aria-label": "Dismiss",
4494
+ onClick: () => setJumpDismissed(true),
4495
+ children: /* @__PURE__ */ jsx(PoolseIcon, { name: "close", size: 12, label: null })
4496
+ }
4497
+ )
4498
+ ] }),
3305
4499
  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
4500
  const prev = idx > 0 ? visibleMessages[idx - 1] ?? null : null;
3307
4501
  const next = idx < visibleMessages.length - 1 ? visibleMessages[idx + 1] ?? null : null;
@@ -3359,22 +4553,37 @@ function ConversationView({
3359
4553
  onDelete: () => void deleteMsg(msg.id),
3360
4554
  onOpenThread: () => setThreadRootId(msg.id),
3361
4555
  onQuote: () => setReplyingTo(msg),
4556
+ ...!isSelf && msg.sequence !== Number.MAX_SAFE_INTEGER ? { onMarkUnread: () => void markUnreadFrom(msg) } : {},
3362
4557
  onQuotedClick: scrollToOriginal,
3363
4558
  ...onCallBack ? { onCallBack } : {},
3364
4559
  ...layoutProps,
3365
4560
  mentionsMe: mentionsViewer(msg, me?.id ?? null)
3366
4561
  }
3367
4562
  );
4563
+ const divider = unread.firstId === msg.id ? /* @__PURE__ */ jsx(
4564
+ "div",
4565
+ {
4566
+ ref: dividerRef,
4567
+ className: "poolse-unread-divider",
4568
+ role: "separator",
4569
+ "aria-label": "New messages",
4570
+ children: /* @__PURE__ */ jsx("span", { children: "New messages" })
4571
+ }
4572
+ ) : null;
3368
4573
  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);
4574
+ return /* @__PURE__ */ jsxs(Fragment$1, { children: [
4575
+ divider,
4576
+ renderMessage(msg, me?.id ?? null, {
4577
+ layout,
4578
+ groupPosition,
4579
+ isRunStart: layout === "compact" || groupPosition === "first" || groupPosition === "standalone",
4580
+ renderDefault
4581
+ })
4582
+ ] }, msg.id);
3375
4583
  }
3376
4584
  return /* @__PURE__ */ jsxs(Fragment$1, { children: [
3377
4585
  showDaySeparator && /* @__PURE__ */ jsx("div", { className: "poolse-day-separator", "aria-hidden": "false", children: /* @__PURE__ */ jsx("span", { children: formatDayLabel(msg.inserted_at) }) }),
4586
+ divider,
3378
4587
  renderDefault()
3379
4588
  ] }, msg.id);
3380
4589
  }),
@@ -3435,11 +4644,18 @@ function ConversationView({
3435
4644
  rootMessage: threadRoot,
3436
4645
  onClose: () => setThreadRootId(null),
3437
4646
  layout,
3438
- ...timeFormat ? { timeFormat } : {}
4647
+ ...timeFormat ? { timeFormat } : {},
4648
+ ...attachmentRules
3439
4649
  }
3440
4650
  ) })
3441
4651
  ] });
3442
4652
  }
4653
+ var NO_MESSAGE = "00000000-0000-0000-0000-000000000000";
4654
+ function scrollDividerIntoView(el) {
4655
+ if (el && typeof el.scrollIntoView === "function") {
4656
+ el.scrollIntoView({ behavior: "smooth", block: "start" });
4657
+ }
4658
+ }
3443
4659
  function highlightRow(el) {
3444
4660
  if (typeof el.scrollIntoView === "function") {
3445
4661
  el.scrollIntoView({ behavior: "smooth", block: "center" });
@@ -3486,23 +4702,34 @@ function ChatHeader({
3486
4702
  onBack,
3487
4703
  onPress,
3488
4704
  onMembersPress,
3489
- rightSlot
4705
+ rightSlot,
4706
+ showPresence = true
3490
4707
  }) {
3491
4708
  const { me } = useMe();
3492
4709
  const meId = me?.id ?? null;
3493
4710
  const { conversation: conv } = useConversation(conversationId);
3494
4711
  const { members } = useMembers(conversationId);
3495
- const { online } = usePresence(conversationId);
4712
+ const { online } = usePresence(showPresence ? conversationId : "");
3496
4713
  const isDirect = conv?.type === "direct";
3497
4714
  const otherMember = isDirect ? members.find((m) => m.user_id !== meId) : null;
3498
4715
  const otherExtId = otherMember?.external_id ?? null;
3499
4716
  const title = isDirect ? otherExtId ? labelFor?.(otherExtId) ?? otherExtId : conv?.name ?? "Direct chat" : conv?.name ?? "Untitled group";
3500
4717
  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"}`;
4718
+ const presence = useUserPresence(showPresence && isDirect ? otherExtId : null);
4719
+ const now = useNow();
4720
+ const otherOnline = showPresence && isDirect && otherExtId ? !presence && online.has(otherExtId) : false;
4721
+ const subtitle = isDirect ? !showPresence ? null : presence ? presenceText(presence, now) : otherOnline ? "Online" : null : `${members.length} member${members.length === 1 ? "" : "s"}`;
3503
4722
  const isPressable = typeof onPress === "function";
3504
4723
  const titleContent = /* @__PURE__ */ jsxs(Fragment, { children: [
3505
- /* @__PURE__ */ jsx(Avatar, { src: avatarUrl, name: title, online: otherOnline, size: "md" }),
4724
+ /* @__PURE__ */ jsx(
4725
+ Avatar,
4726
+ {
4727
+ src: avatarUrl,
4728
+ name: title,
4729
+ presence: presence ?? (otherOnline ? "online" : null),
4730
+ size: "md"
4731
+ }
4732
+ ),
3506
4733
  /* @__PURE__ */ jsxs("div", { className: "poolse-chat-header__titles", children: [
3507
4734
  /* @__PURE__ */ jsx("div", { className: "poolse-chat-header__title", children: title }),
3508
4735
  subtitle ? /* @__PURE__ */ jsx("div", { className: "poolse-chat-header__subtitle", children: subtitle }) : null
@@ -3545,7 +4772,15 @@ function ConversationList({
3545
4772
  error: controlledError,
3546
4773
  unreadCounts,
3547
4774
  labelFor,
3548
- avatarFor
4775
+ avatarFor,
4776
+ showPresence = true,
4777
+ density = "comfortable",
4778
+ sections,
4779
+ groupBy,
4780
+ header,
4781
+ hasMore: controlledHasMore,
4782
+ loadingMore: controlledLoadingMore,
4783
+ onLoadMore
3549
4784
  }) {
3550
4785
  const auto = useConversations();
3551
4786
  const { me } = useMe();
@@ -3556,49 +4791,123 @@ function ConversationList({
3556
4791
  const loading = isControlled ? controlledLoading ?? false : auto.loading;
3557
4792
  const error = isControlled ? controlledError ?? null : auto.error;
3558
4793
  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
4794
+ const hasMore = isControlled ? controlledHasMore ?? false : auto.hasMore;
4795
+ const loadingMore = isControlled ? controlledLoadingMore ?? false : auto.loadingMore;
4796
+ const loadMore = isControlled ? onLoadMore : auto.loadMore;
4797
+ const listRef = useRef(null);
4798
+ const sentinelRef = useRef(null);
4799
+ const loadMoreRef = useRef(loadMore);
4800
+ loadMoreRef.current = loadMore;
4801
+ const busyRef = useRef(false);
4802
+ const hasRows = conversations.length > 0;
4803
+ useEffect(() => {
4804
+ const sentinel = sentinelRef.current;
4805
+ const root = listRef.current;
4806
+ if (!sentinel || !root || !hasMore || loadingMore) return;
4807
+ if (typeof IntersectionObserver === "undefined") return;
4808
+ const io = new IntersectionObserver(
4809
+ ([entry]) => {
4810
+ if (!entry?.isIntersecting || busyRef.current) return;
4811
+ const fn = loadMoreRef.current;
4812
+ if (!fn) return;
4813
+ busyRef.current = true;
4814
+ void Promise.resolve().then(fn).catch(() => void 0).finally(() => {
4815
+ busyRef.current = false;
4816
+ });
3598
4817
  },
3599
- conv.id
4818
+ { root, rootMargin: "0px 0px 240px 0px", threshold: 0 }
3600
4819
  );
3601
- }) });
4820
+ io.observe(sentinel);
4821
+ return () => io.disconnect();
4822
+ }, [hasMore, loadingMore, hasRows]);
4823
+ const groups = useMemo(
4824
+ () => groupConversations(conversations, sections ?? (groupBy === "type" ? TYPE_SECTIONS : null)),
4825
+ [conversations, sections, groupBy]
4826
+ );
4827
+ const rootClass = [
4828
+ "poolse-conversation-list",
4829
+ `poolse-conversation-list--density-${density}`
4830
+ ].join(" ");
4831
+ const body = (() => {
4832
+ if (loading && conversations.length === 0) {
4833
+ return /* @__PURE__ */ jsx("div", { className: "poolse-list poolse-list--placeholder", children: "Loading conversations\u2026" });
4834
+ }
4835
+ if (error && conversations.length === 0) {
4836
+ return /* @__PURE__ */ jsx("div", { className: "poolse-list poolse-list--placeholder poolse-list--error", children: "Failed to load conversations." });
4837
+ }
4838
+ if (conversations.length === 0) {
4839
+ return /* @__PURE__ */ jsx("div", { className: "poolse-list poolse-list--placeholder", children: emptyState ?? "No conversations yet." });
4840
+ }
4841
+ const row = (conv) => {
4842
+ const selected = selectedId === conv.id;
4843
+ const unread = counts?.[conv.id] ?? 0;
4844
+ const content = renderItem ? renderItem(conv, selected) : /* @__PURE__ */ jsx(
4845
+ DefaultRow,
4846
+ {
4847
+ conv,
4848
+ selected,
4849
+ unread,
4850
+ meExternalId,
4851
+ meId,
4852
+ showPresence,
4853
+ compact: density === "compact",
4854
+ ...labelFor ? { labelFor } : {},
4855
+ ...avatarFor ? { avatarFor } : {}
4856
+ }
4857
+ );
4858
+ return /* @__PURE__ */ jsx(
4859
+ "li",
4860
+ {
4861
+ role: "option",
4862
+ "aria-selected": selected,
4863
+ className: `poolse-list__item${selected ? " poolse-list__item--selected" : ""}`,
4864
+ onClick: () => onSelect?.(conv),
4865
+ onKeyDown: (e) => {
4866
+ if (e.key === "Enter" || e.key === " ") {
4867
+ e.preventDefault();
4868
+ onSelect?.(conv);
4869
+ }
4870
+ },
4871
+ tabIndex: 0,
4872
+ children: content
4873
+ },
4874
+ conv.id
4875
+ );
4876
+ };
4877
+ return /* @__PURE__ */ jsxs("ul", { ref: listRef, className: "poolse-list", role: "listbox", "aria-label": "Conversations", children: [
4878
+ groups === null ? conversations.map(row) : groups.map((g) => /* @__PURE__ */ jsxs("li", { role: "group", "aria-label": g.title, className: "poolse-list__section", children: [
4879
+ /* @__PURE__ */ jsx("div", { className: "poolse-list__section-title", "aria-hidden": "true", children: g.title }),
4880
+ /* @__PURE__ */ jsx("ul", { className: "poolse-list__section-items", role: "presentation", children: g.conversations.map(row) })
4881
+ ] }, g.title)),
4882
+ loadingMore && /* @__PURE__ */ jsx("li", { className: "poolse-list__loading-more", role: "presentation", children: "Loading\u2026" }),
4883
+ hasMore && /* @__PURE__ */ jsx(
4884
+ "li",
4885
+ {
4886
+ ref: sentinelRef,
4887
+ className: "poolse-list__sentinel",
4888
+ role: "presentation",
4889
+ "aria-hidden": "true"
4890
+ }
4891
+ )
4892
+ ] });
4893
+ })();
4894
+ return /* @__PURE__ */ jsxs("div", { className: rootClass, children: [
4895
+ header !== void 0 && header !== null ? /* @__PURE__ */ jsx("div", { className: "poolse-conversation-list__header", children: header }) : null,
4896
+ body
4897
+ ] });
4898
+ }
4899
+ var TYPE_SECTIONS = [
4900
+ { title: "Channels", filter: (c) => c.type !== "direct" },
4901
+ { title: "Direct messages", filter: (c) => c.type === "direct" }
4902
+ ];
4903
+ function groupConversations(conversations, sections) {
4904
+ if (!sections || sections.length === 0) return null;
4905
+ const out = sections.map((s) => ({ title: s.title, conversations: [] }));
4906
+ for (const conv of conversations) {
4907
+ const i = sections.findIndex((s) => s.filter(conv));
4908
+ if (i !== -1) out[i].conversations.push(conv);
4909
+ }
4910
+ return out.filter((g) => g.conversations.length > 0);
3602
4911
  }
3603
4912
  function DefaultRow({
3604
4913
  conv,
@@ -3606,24 +4915,35 @@ function DefaultRow({
3606
4915
  unread,
3607
4916
  meExternalId,
3608
4917
  meId = null,
4918
+ showPresence,
4919
+ compact = false,
3609
4920
  labelFor,
3610
4921
  avatarFor
3611
4922
  }) {
3612
4923
  const isDirect = conv.type === "direct";
3613
4924
  const otherExtId = isDirect && meExternalId ? (conv.member_external_ids ?? []).find((x) => x !== meExternalId) : null;
3614
- const title = isDirect ? otherExtId ? labelFor?.(otherExtId) ?? otherExtId : conv.name ?? "Direct chat" : conv.name ?? "Untitled group";
3615
- const avatarUrl = isDirect ? otherExtId ? avatarFor?.(otherExtId) ?? null : conv.avatar_url ?? null : conv.avatar_url ?? null;
4925
+ const { profile: other } = useUser(isDirect && otherExtId ? otherExtId : null);
4926
+ const title = isDirect ? otherExtId ? labelFor?.(otherExtId) ?? other?.displayName ?? otherExtId : conv.name ?? "Direct chat" : conv.name ?? "Untitled group";
4927
+ const avatarUrl = isDirect ? otherExtId ? avatarFor?.(otherExtId) ?? other?.avatarUrl ?? null : conv.avatar_url ?? null : conv.avatar_url ?? null;
3616
4928
  const time = conv.last_message_at ? formatRelative(conv.last_message_at) : "";
3617
4929
  const hasUnread = unread > 0;
3618
4930
  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
4931
  return /* @__PURE__ */ jsxs(Fragment, { children: [
3620
- /* @__PURE__ */ jsx(Avatar, { src: avatarUrl, name: title, size: "md" }),
4932
+ /* @__PURE__ */ jsx(
4933
+ Avatar,
4934
+ {
4935
+ src: avatarUrl,
4936
+ name: title,
4937
+ size: compact ? "sm" : "md",
4938
+ ...showPresence && otherExtId ? { presence: true, userId: otherExtId } : {}
4939
+ }
4940
+ ),
3621
4941
  /* @__PURE__ */ jsxs("div", { className: "poolse-list__body", children: [
3622
4942
  /* @__PURE__ */ jsxs("div", { className: "poolse-list__head", children: [
3623
4943
  /* @__PURE__ */ jsx("span", { className: `poolse-list__title${hasUnread ? " poolse-list__title--unread" : ""}`, children: title }),
3624
4944
  time && /* @__PURE__ */ jsx("span", { className: "poolse-list__time", children: time })
3625
4945
  ] }),
3626
- /* @__PURE__ */ jsx("div", { className: "poolse-list__preview", children: preview })
4946
+ compact ? null : /* @__PURE__ */ jsx("div", { className: "poolse-list__preview", children: preview })
3627
4947
  ] }),
3628
4948
  hasUnread && /* @__PURE__ */ jsx(
3629
4949
  "span",
@@ -3649,15 +4969,17 @@ function MemberList({
3649
4969
  labelFor,
3650
4970
  avatarFor,
3651
4971
  onlineExternalIds,
4972
+ showPresence = true,
3652
4973
  canRemove,
3653
4974
  renderItem,
3654
4975
  emptyState
3655
4976
  }) {
3656
4977
  const { members, loading, error, removeMember } = useMembers(conversationId);
3657
- const { online: presenceOnline } = usePresence(
3658
- onlineExternalIds === void 0 ? conversationId : ""
4978
+ const legacy = onlineExternalIds !== void 0;
4979
+ const presences = usePresenceMany(
4980
+ showPresence && !legacy ? members.map((m) => m.external_id) : NO_IDS
3659
4981
  );
3660
- const effectiveOnline = onlineExternalIds ?? presenceOnline;
4982
+ const now = useNow();
3661
4983
  if (loading && members.length === 0) {
3662
4984
  return /* @__PURE__ */ jsx("div", { className: "poolse-list poolse-list--placeholder", children: "Loading members\u2026" });
3663
4985
  }
@@ -3676,7 +4998,8 @@ function MemberList({
3676
4998
  {
3677
4999
  membership: m,
3678
5000
  avatarUrl: avatarFor?.(m.external_id) ?? null,
3679
- online: effectiveOnline.has(m.external_id),
5001
+ presence: !showPresence ? null : legacy ? onlineExternalIds.has(m.external_id) : presences[m.external_id] ?? null,
5002
+ now,
3680
5003
  removable: canRemove?.(m) ?? false,
3681
5004
  onRemove: () => {
3682
5005
  void removeMember(m.external_id);
@@ -3687,20 +5010,22 @@ function MemberList({
3687
5010
  return /* @__PURE__ */ jsx("li", { className: "poolse-list__item", children: content }, m.id);
3688
5011
  }) });
3689
5012
  }
5013
+ var NO_IDS = [];
3690
5014
  function DefaultMemberRow({
3691
5015
  membership,
3692
5016
  avatarUrl,
3693
- online,
5017
+ presence,
5018
+ now,
3694
5019
  removable,
3695
5020
  onRemove,
3696
5021
  labelFor
3697
5022
  }) {
3698
5023
  const name = useDisplayName(membership.external_id, labelFor);
3699
5024
  return /* @__PURE__ */ jsxs("div", { className: "poolse-member-row", children: [
3700
- /* @__PURE__ */ jsx(Avatar, { src: avatarUrl, name, online, size: "md" }),
5025
+ typeof presence === "boolean" ? /* @__PURE__ */ jsx(Avatar, { src: avatarUrl, name, online: presence, size: "md" }) : /* @__PURE__ */ jsx(Avatar, { src: avatarUrl, name, presence, size: "md" }),
3701
5026
  /* @__PURE__ */ jsxs("div", { className: "poolse-member-row__body", children: [
3702
5027
  /* @__PURE__ */ jsx("div", { className: "poolse-member-row__name", children: name }),
3703
- /* @__PURE__ */ jsx("div", { className: "poolse-member-row__sub", children: online ? "online" : "offline" })
5028
+ 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
5029
  ] }),
3705
5030
  /* @__PURE__ */ jsx(RoleBadge, { role: membership.role }),
3706
5031
  removable && /* @__PURE__ */ jsx(
@@ -4507,6 +5832,6 @@ function PoolseLogo({
4507
5832
  );
4508
5833
  }
4509
5834
 
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 };
5835
+ 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
5836
  //# sourceMappingURL=index.js.map
4512
5837
  //# sourceMappingURL=index.js.map