@micha.bigler/ui-core-micha 2.14.0 → 2.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/README.md +7 -0
  2. package/WORK_ORDERS.md +8 -2
  3. package/dev/entries.jsx +147 -0
  4. package/dev/fixtures.js +26 -0
  5. package/dev/main.jsx +56 -0
  6. package/dev/mockTransport.jsx +128 -0
  7. package/dist/components/charts/BarChart.js +32 -0
  8. package/dist/components/charts/ChartFrame.js +50 -0
  9. package/dist/components/charts/LineChart.js +32 -0
  10. package/dist/components/charts/exportChart.js +67 -0
  11. package/dist/components/charts/formatters.js +23 -0
  12. package/dist/components/charts/palette.js +21 -0
  13. package/dist/i18n/chartsTranslations.js +38 -0
  14. package/dist/i18n/messagingTranslations.js +81 -0
  15. package/dist/index.js +25 -4
  16. package/dist/messaging/AttachmentList.js +43 -0
  17. package/dist/messaging/Composer.js +120 -0
  18. package/dist/messaging/ConversationLaunchers.js +39 -0
  19. package/dist/messaging/ConversationList.js +75 -0
  20. package/dist/messaging/MessageBubble.js +17 -0
  21. package/dist/messaging/MessagingProvider.js +317 -0
  22. package/dist/messaging/MessagingScopeConfig.js +28 -0
  23. package/dist/messaging/PollCard.js +53 -0
  24. package/dist/messaging/ReactionBar.js +44 -0
  25. package/dist/messaging/ReadTicks.js +25 -0
  26. package/dist/messaging/Thread.js +73 -0
  27. package/dist/messaging/api.js +51 -0
  28. package/dist/notifications/NotificationsProvider.js +2 -2
  29. package/dist/notifications/realtime.js +21 -1
  30. package/docs/messaging-deviations.md +36 -0
  31. package/index.html +12 -0
  32. package/package.json +6 -1
  33. package/src/components/charts/BarChart.jsx +44 -0
  34. package/src/components/charts/ChartFrame.jsx +112 -0
  35. package/src/components/charts/LineChart.jsx +44 -0
  36. package/src/components/charts/exportChart.js +71 -0
  37. package/src/components/charts/formatters.js +39 -0
  38. package/src/components/charts/palette.js +24 -0
  39. package/src/i18n/chartsTranslations.ts +38 -0
  40. package/src/i18n/messagingTranslations.ts +81 -0
  41. package/src/index.js +33 -4
  42. package/src/messaging/AttachmentList.jsx +38 -0
  43. package/src/messaging/Composer.jsx +110 -0
  44. package/src/messaging/ConversationLaunchers.jsx +51 -0
  45. package/src/messaging/ConversationList.jsx +78 -0
  46. package/src/messaging/MessageBubble.jsx +37 -0
  47. package/src/messaging/MessagingProvider.jsx +323 -0
  48. package/src/messaging/MessagingScopeConfig.jsx +24 -0
  49. package/src/messaging/PollCard.jsx +36 -0
  50. package/src/messaging/ReactionBar.jsx +46 -0
  51. package/src/messaging/ReadTicks.jsx +23 -0
  52. package/src/messaging/Thread.jsx +71 -0
  53. package/src/messaging/api.js +47 -0
  54. package/src/notifications/NotificationsProvider.jsx +2 -2
  55. package/src/notifications/realtime.jsx +21 -1
  56. package/tests/BarChart.test.jsx +55 -0
  57. package/tests/ChartFrame.test.jsx +122 -0
  58. package/tests/ConversationList.test.jsx +66 -0
  59. package/tests/LineChart.test.jsx +33 -0
  60. package/tests/MessagingProvider.test.jsx +50 -0
  61. package/tests/Thread.test.jsx +100 -0
  62. package/tests/chartsPalette.test.js +39 -0
  63. package/tests/messagingApi.test.js +32 -0
  64. package/tests/messagingComposer.test.jsx +111 -0
  65. package/tests/messagingExports.test.js +20 -0
  66. package/tests/messagingInteractions.test.jsx +112 -0
  67. package/tests/realtime.test.jsx +27 -0
  68. package/vite.config.mjs +6 -0
  69. package/work-orders/CHART-1.md +285 -0
  70. package/work-orders/DX-1.md +166 -0
  71. package/work-orders/MSG-3.md +375 -0
@@ -0,0 +1,323 @@
1
+ import { createContext, useCallback, useContext, useEffect, useMemo, useReducer, useRef } from 'react';
2
+
3
+ import { AuthContext } from '../auth/AuthContext';
4
+ import {
5
+ archiveConversation,
6
+ createBroadcastConversation,
7
+ createGroupConversation,
8
+ getReadStatus,
9
+ getUnreadCount,
10
+ listConversations,
11
+ listMessages,
12
+ listThread,
13
+ patchConversationPreferences,
14
+ createMessage,
15
+ uploadAttachments,
16
+ getAttachment,
17
+ getAttachmentThumbnail,
18
+ addReaction,
19
+ removeReaction,
20
+ createPoll,
21
+ votePoll,
22
+ closePoll,
23
+ getConversationConfig,
24
+ patchConversationConfig,
25
+ } from './api';
26
+ import { useRealtime } from '../notifications/realtime';
27
+
28
+ const MessagingContext = createContext(null);
29
+ export const MESSAGING_ENVELOPE = 'messaging';
30
+ const EMPTY_CACHE = { conversations: {}, messages: {}, threads: {}, polls: {}, reactions: {}, receipts: {}, unread: { unread_count: 0, by_conversation: {} }, cursors: { conversations: null, messages: {}, threads: {} } };
31
+ const DEFAULT_API = {
32
+ listConversations, listMessages, listThread, getReadStatus, getUnreadCount, archiveConversation,
33
+ patchConversationPreferences, createGroupConversation, createBroadcastConversation,
34
+ createMessage, uploadAttachments, getAttachment, getAttachmentThumbnail,
35
+ addReaction, removeReaction, createPoll, votePoll, closePoll, getConversationConfig, patchConversationConfig,
36
+ };
37
+
38
+ function idOf(item) { return item?.id ?? item?.conversation_id ?? item?.message_id ?? item?.poll_id; }
39
+ function mergeById(slice, item) { const id = idOf(item); return id == null ? slice : { ...slice, [id]: { ...slice[id], ...item } }; }
40
+ function resultsOf(response) { return response?.results || []; }
41
+ function clientRequestIdOf(message) { return message?.client_request_id; }
42
+
43
+ /**
44
+ * dcm's DRF validation errors aren't always {detail}: ConversationAttachmentView
45
+ * translates a rejected upload into a field-keyed {"files": [...]} body (the
46
+ * MSG-2 chunk-4 fix — see django-core-micha messaging/views.py), while other
47
+ * endpoints use {detail}. Check every shape a caller might actually receive
48
+ * before falling back to the generic axios error message.
49
+ */
50
+ export function extractApiErrorMessage(error) {
51
+ const data = error?.response?.data;
52
+ if (typeof data?.detail === 'string') return data.detail;
53
+ if (typeof data?.message === 'string') return data.message;
54
+ if (Array.isArray(data?.files)) return data.files.join(' ');
55
+ if (data && typeof data === 'object') {
56
+ const firstArray = Object.values(data).find((value) => Array.isArray(value) && value.length);
57
+ if (firstArray) return firstArray.join(' ');
58
+ }
59
+ return error?.message;
60
+ }
61
+
62
+ function reconcileMessage(messages, message) {
63
+ const requestId = clientRequestIdOf(message);
64
+ const matchingEntry = requestId && Object.entries(messages).find(([, item]) => clientRequestIdOf(item) === requestId);
65
+ if (!matchingEntry) return mergeById(messages, message);
66
+ const [previousKey, previous] = matchingEntry;
67
+ const next = { ...messages };
68
+ delete next[previousKey];
69
+ const id = idOf(message) ?? previousKey;
70
+ next[id] = { ...previous, ...message, id: idOf(message) ?? previous.id, status: message.status || 'sent', error: null };
71
+ return next;
72
+ }
73
+
74
+ export function messagingReducer(state, action) {
75
+ switch (action.type) {
76
+ case 'conversationsLoaded': {
77
+ const conversations = action.results.reduce((next, item) => mergeById(next, item), state.conversations);
78
+ return { ...state, conversations, cursors: { ...state.cursors, conversations: action.nextCursor ?? null } };
79
+ }
80
+ case 'unreadLoaded': return { ...state, unread: action.unread || EMPTY_CACHE.unread };
81
+ case 'messagesLoaded': {
82
+ const messages = action.results.reduce((next, item) => mergeById(next, item), state.messages);
83
+ return { ...state, messages, cursors: { ...state.cursors, messages: { ...state.cursors.messages, [action.conversationId]: action.nextCursor ?? null } } };
84
+ }
85
+ case 'threadLoaded': {
86
+ const messages = action.results.reduce((next, item) => mergeById(next, item), state.messages);
87
+ return { ...state, messages, cursors: { ...state.cursors, threads: { ...state.cursors.threads, [action.rootId]: action.nextCursor ?? null } } };
88
+ }
89
+ case 'conversationUpsert': return { ...state, conversations: mergeById(state.conversations, action.conversation) };
90
+ case 'messageOptimistic': return { ...state, messages: mergeById(state.messages, action.message) };
91
+ case 'messageReconciled': return { ...state, messages: reconcileMessage(state.messages, action.message) };
92
+ case 'messageFailed': {
93
+ const matching = Object.entries(state.messages).find(([, item]) => clientRequestIdOf(item) === action.clientRequestId);
94
+ if (!matching) return state;
95
+ const [key, message] = matching;
96
+ return { ...state, messages: { ...state.messages, [key]: { ...message, status: 'error', error: action.error } } };
97
+ }
98
+ case 'messagePatched': return { ...state, messages: mergeById(state.messages, action.message) };
99
+ case 'frame': return applyFrame(state, action.frame);
100
+ default: return state;
101
+ }
102
+ }
103
+
104
+ export function applyFrame(state, frame) {
105
+ const payload = frame.message || frame.conversation || frame.participant || frame;
106
+ const conversationId = frame.conversation_id ?? payload.conversation_id;
107
+ if (frame.type === 'message') {
108
+ const message = { ...payload, conversation_id: conversationId };
109
+ return { ...state, messages: reconcileMessage(state.messages, message) };
110
+ }
111
+ if (frame.type === 'message_edited') return { ...state, messages: mergeById(state.messages, payload) };
112
+ if (frame.type === 'reaction') {
113
+ const messageId = frame.message_id ?? payload.message_id;
114
+ const previous = state.messages[messageId] || { id: messageId };
115
+ return { ...state, messages: mergeById(state.messages, { ...previous, reactions: payload.reactions || frame.reactions || previous.reactions || [] }) };
116
+ }
117
+ if (frame.type === 'poll_updated') {
118
+ const messageId = frame.message_id ?? payload.message_id;
119
+ const previous = state.messages[messageId] || { id: messageId };
120
+ const poll = payload.poll || frame.poll || payload;
121
+ return { ...state, messages: mergeById(state.messages, { ...previous, poll }), polls: mergeById(state.polls, poll) };
122
+ }
123
+ if (frame.type === 'message_deleted') {
124
+ const previous = state.messages[frame.message_id] || {};
125
+ return { ...state, messages: { ...state.messages, [frame.message_id]: { ...previous, id: frame.message_id, deleted_at: frame.deleted_at, deleted_by: frame.deleted_by, body: null, title: null, link_target: null } } };
126
+ }
127
+ if (frame.type === 'conversation_upsert') return { ...state, conversations: mergeById(state.conversations, payload) };
128
+ // conversation_archived/participant_changed: the design doc names these frame
129
+ // types but doesn't pin their exact payload shape. Treating them as merging
130
+ // onto the conversation record (participant-local fields folded flat, an
131
+ // `archived` flag set) is this chunk's best-effort reading, not a confirmed
132
+ // contract — re-verify against dcm's actual WS payload once available, per
133
+ // the WO's "shape fixtures from the design doc, not from imagination" caution.
134
+ if (frame.type === 'conversation_archived') return { ...state, conversations: mergeById(state.conversations, { ...payload, id: conversationId, archived: true }) };
135
+ if (frame.type === 'participant_changed') return { ...state, conversations: mergeById(state.conversations, { ...payload, id: conversationId }) };
136
+ return state;
137
+ }
138
+
139
+ export function MessagingProvider({ children, filters = {}, activeConversationId = null, api = DEFAULT_API, active = true }) {
140
+ const { subscribe, onReconnect } = useRealtime();
141
+ const { user } = useContext(AuthContext) || {};
142
+ const [cache, dispatch] = useReducer(messagingReducer, EMPTY_CACHE);
143
+ const activeIdRef = useRef(activeConversationId);
144
+ const seenEventsRef = useRef(new Set());
145
+ const filtersRef = useRef(filters);
146
+ activeIdRef.current = activeConversationId;
147
+ filtersRef.current = filters;
148
+
149
+ const refreshConversations = useCallback(async () => {
150
+ const response = await api.listConversations(filtersRef.current);
151
+ dispatch({ type: 'conversationsLoaded', results: resultsOf(response), nextCursor: response?.next_cursor });
152
+ return response;
153
+ }, [api]);
154
+ const refreshUnread = useCallback(async () => {
155
+ const unread = await api.getUnreadCount();
156
+ dispatch({ type: 'unreadLoaded', unread });
157
+ return unread;
158
+ }, [api]);
159
+ const refreshThread = useCallback(async (conversationId = activeIdRef.current, { cursor } = {}) => {
160
+ if (conversationId == null) return null;
161
+ const response = await api.listMessages(conversationId, ...(cursor ? [{ cursor }] : []));
162
+ dispatch({ type: 'messagesLoaded', conversationId, results: resultsOf(response), nextCursor: response?.next_cursor });
163
+ return response;
164
+ }, [api]);
165
+ const loadMoreMessages = useCallback((conversationId = activeIdRef.current) => {
166
+ const cursor = cache.cursors.messages[conversationId];
167
+ return cursor ? refreshThread(conversationId, { cursor }) : Promise.resolve(null);
168
+ }, [cache.cursors.messages, refreshThread]);
169
+ const loadThreadReplies = useCallback(async (rootId, { cursor } = {}) => {
170
+ const response = await api.listThread(rootId, { cursor });
171
+ dispatch({ type: 'threadLoaded', rootId, results: resultsOf(response), nextCursor: response?.next_cursor });
172
+ return response;
173
+ }, [api]);
174
+ const getMessageReadStatus = useCallback((messageId) => api.getReadStatus(messageId), [api]);
175
+ const loadMoreConversations = useCallback(async () => {
176
+ const cursor = cache.cursors.conversations;
177
+ if (!cursor) return null;
178
+ const response = await api.listConversations({ ...filtersRef.current, cursor });
179
+ dispatch({ type: 'conversationsLoaded', results: resultsOf(response), nextCursor: response?.next_cursor });
180
+ return response;
181
+ }, [api, cache.cursors.conversations]);
182
+ const updateConversation = useCallback((conversation) => {
183
+ dispatch({ type: 'conversationUpsert', conversation });
184
+ return conversation;
185
+ }, []);
186
+ const setConversationArchived = useCallback(async (conversationId, archived) => {
187
+ const conversation = await api.archiveConversation(conversationId, archived);
188
+ return updateConversation({ ...conversation, id: conversation?.id ?? conversationId, archived: Boolean(archived) });
189
+ }, [api, updateConversation]);
190
+ const setConversationPreferences = useCallback(async (conversationId, patch) => {
191
+ const conversation = await api.patchConversationPreferences(conversationId, patch);
192
+ return updateConversation({ ...conversation, id: conversation?.id ?? conversationId, ...patch });
193
+ }, [api, updateConversation]);
194
+ const openGroupConversation = useCallback(async (payload) => {
195
+ const conversation = await api.createGroupConversation(payload);
196
+ return updateConversation(conversation);
197
+ }, [api, updateConversation]);
198
+ const openBroadcastConversation = useCallback(async (payload) => {
199
+ const conversation = await api.createBroadcastConversation(payload);
200
+ return updateConversation(conversation);
201
+ }, [api, updateConversation]);
202
+ const sendMessage = useCallback(async (conversationId, payload, { clientRequestId, retry = false } = {}) => {
203
+ const requestId = clientRequestId || payload.client_request_id;
204
+ const optimistic = {
205
+ id: `local-${requestId}`,
206
+ conversation_id: conversationId,
207
+ kind: payload.kind || 'chat',
208
+ body: payload.body || '',
209
+ title: payload.title || null,
210
+ link_target: payload.link_target || null,
211
+ reply_to: payload.reply_to || null,
212
+ client_request_id: requestId,
213
+ created_at: new Date().toISOString(),
214
+ status: 'pending',
215
+ sender: user ? { id: user.id, display_name: user.display_name || user.username } : undefined,
216
+ ...(retry ? {} : {}),
217
+ };
218
+ if (!retry) dispatch({ type: 'messageOptimistic', message: optimistic });
219
+ else dispatch({ type: 'messageReconciled', message: { ...optimistic, status: 'pending', error: null } });
220
+ try {
221
+ const message = await api.createMessage(conversationId, { ...payload, client_request_id: requestId }, { idempotencyKey: requestId });
222
+ dispatch({ type: 'messageReconciled', message: { ...message, conversation_id: message?.conversation_id ?? conversationId, client_request_id: message?.client_request_id ?? requestId } });
223
+ return message;
224
+ } catch (error) {
225
+ dispatch({ type: 'messageFailed', clientRequestId: requestId, error: extractApiErrorMessage(error) });
226
+ throw error;
227
+ }
228
+ }, [api, user]);
229
+ const sendAttachments = useCallback(async (conversationId, formData, { clientRequestId, optimisticMessage, retry = false } = {}) => {
230
+ const optimistic = {
231
+ id: `local-${clientRequestId}`, conversation_id: conversationId, kind: 'chat', body: optimisticMessage?.body || '',
232
+ reply_to: optimisticMessage?.reply_to || null, client_request_id: clientRequestId, created_at: new Date().toISOString(), status: 'pending',
233
+ sender: user ? { id: user.id, display_name: user.display_name || user.username } : undefined,
234
+ attachments: optimisticMessage?.attachments || [],
235
+ };
236
+ if (!retry) dispatch({ type: 'messageOptimistic', message: optimistic });
237
+ else dispatch({ type: 'messageReconciled', message: { ...optimistic, status: 'pending', error: null } });
238
+ try {
239
+ const message = await api.uploadAttachments(conversationId, formData, { idempotencyKey: clientRequestId });
240
+ dispatch({ type: 'messageReconciled', message: { ...message, conversation_id: message?.conversation_id ?? conversationId, client_request_id: message?.client_request_id ?? clientRequestId } });
241
+ return message;
242
+ } catch (error) {
243
+ dispatch({ type: 'messageFailed', clientRequestId, error: extractApiErrorMessage(error) });
244
+ throw error;
245
+ }
246
+ }, [api, user]);
247
+ const patchMessage = useCallback((message) => dispatch({ type: 'messagePatched', message }), []);
248
+ const toggleReaction = useCallback(async (messageId, emoji, active) => {
249
+ const message = cache.messages[messageId] || { id: messageId };
250
+ const reactions = message.reactions || [];
251
+ const current = reactions.find((reaction) => reaction.emoji === emoji);
252
+ const nextReactions = active
253
+ ? reactions.map((reaction) => reaction.emoji === emoji ? { ...reaction, reacted: false, count: Math.max(0, (reaction.count || 1) - 1) } : reaction).filter((reaction) => reaction.count !== 0)
254
+ : current
255
+ ? reactions.map((reaction) => reaction.emoji === emoji ? { ...reaction, reacted: true, count: (reaction.count || 0) + 1 } : reaction)
256
+ : [...reactions, { emoji, count: 1, reacted: true }];
257
+ patchMessage({ ...message, reactions: nextReactions });
258
+ try {
259
+ const result = active ? await api.removeReaction(messageId, emoji) : await api.addReaction(messageId, emoji);
260
+ patchMessage({ ...message, ...(result?.message || result), reactions: result?.reactions || result?.message?.reactions || nextReactions });
261
+ return result;
262
+ } catch (error) { patchMessage(message); throw error; }
263
+ }, [api, cache.messages, patchMessage]);
264
+ const createConversationPoll = useCallback(async (conversationId, payload, { clientRequestId } = {}) => {
265
+ const poll = await api.createPoll(conversationId, { ...payload, client_request_id: clientRequestId }, { idempotencyKey: clientRequestId });
266
+ const message = poll?.message || poll;
267
+ if (message?.id != null) patchMessage({ ...message, conversation_id: message.conversation_id ?? conversationId, poll: message.poll || poll.poll || poll });
268
+ return poll;
269
+ }, [api, patchMessage]);
270
+ const castPollVote = useCallback(async (messageId, poll, optionIds) => {
271
+ const result = await api.votePoll(poll.id, optionIds);
272
+ const nextPoll = { ...poll, ...(result?.poll || result) };
273
+ patchMessage({ ...(cache.messages[messageId] || { id: messageId }), poll: nextPoll });
274
+ return result;
275
+ }, [api, cache.messages, patchMessage]);
276
+ const closeConversationPoll = useCallback(async (messageId, poll) => {
277
+ const result = await api.closePoll(poll.id);
278
+ const nextPoll = { ...poll, ...(result?.poll || result), closed_at: result?.poll?.closed_at || result?.closed_at || new Date().toISOString() };
279
+ patchMessage({ ...(cache.messages[messageId] || { id: messageId }), poll: nextPoll });
280
+ return result;
281
+ }, [api, cache.messages, patchMessage]);
282
+ const loadConversationConfig = useCallback((conversationId) => api.getConversationConfig(conversationId), [api]);
283
+ const saveConversationConfig = useCallback((conversationId, patch) => api.patchConversationConfig(conversationId, patch), [api]);
284
+ const refresh = useCallback(async () => Promise.all([refreshConversations(), refreshUnread(), refreshThread()]), [refreshConversations, refreshThread, refreshUnread]);
285
+
286
+ // `/api/messaging/` is authenticated-only (design §REST). Host apps mount
287
+ // MessagingProvider inside NotificationsProvider, which itself renders its
288
+ // children regardless of auth state — so without this gate a provider
289
+ // mounted before login completes fires three REST calls that spuriously
290
+ // 401. Defaults to true (matches chunk 1's existing tests/harness usage,
291
+ // which don't pass it); a host app gates it with `active={authenticated}`.
292
+ useEffect(() => { if (active) refresh().catch(() => {}); }, [active, refresh]);
293
+ useEffect(() => subscribe(MESSAGING_ENVELOPE, (frame) => {
294
+ if (frame.event_id && seenEventsRef.current.has(frame.event_id)) return;
295
+ if (frame.event_id) {
296
+ seenEventsRef.current.add(frame.event_id);
297
+ if (seenEventsRef.current.size > 500) seenEventsRef.current.delete(seenEventsRef.current.values().next().value);
298
+ }
299
+ dispatch({ type: 'frame', frame });
300
+ }), [subscribe]);
301
+ useEffect(() => {
302
+ if (!active || !onReconnect) return undefined;
303
+ return onReconnect(() => { refresh().catch(() => {}); });
304
+ }, [active, onReconnect, refresh]);
305
+
306
+ const value = useMemo(() => ({
307
+ cache, refresh, refreshConversations, refreshUnread, refreshThread, loadMoreMessages, loadThreadReplies, getMessageReadStatus, loadMoreConversations,
308
+ setConversationArchived, setConversationPreferences, openGroupConversation,
309
+ openBroadcastConversation, sendMessage, sendAttachments, toggleReaction, createConversationPoll, castPollVote, closeConversationPoll,
310
+ loadConversationConfig, saveConversationConfig, currentUser: user, getAttachment: api.getAttachment,
311
+ getAttachmentThumbnail: api.getAttachmentThumbnail, activeConversationId,
312
+ }), [cache, refresh, refreshConversations, refreshUnread, refreshThread, loadMoreMessages, loadThreadReplies, getMessageReadStatus, loadMoreConversations,
313
+ setConversationArchived, setConversationPreferences, openGroupConversation,
314
+ openBroadcastConversation, sendMessage, sendAttachments, toggleReaction, createConversationPoll, castPollVote, closeConversationPoll,
315
+ loadConversationConfig, saveConversationConfig, user, api.getAttachment, api.getAttachmentThumbnail, activeConversationId]);
316
+ return <MessagingContext.Provider value={value}>{children}</MessagingContext.Provider>;
317
+ }
318
+
319
+ export function useMessaging() {
320
+ const context = useContext(MessagingContext);
321
+ if (!context) throw new Error('useMessaging must be used within a MessagingProvider');
322
+ return context;
323
+ }
@@ -0,0 +1,24 @@
1
+ import { Alert, Box, CircularProgress, FormControl, FormControlLabel, InputLabel, MenuItem, Select, Stack, Switch, Typography } from '@mui/material';
2
+ import { useEffect, useState } from 'react';
3
+ import { useTranslation } from 'react-i18next';
4
+
5
+ import { extractApiErrorMessage, useMessaging } from './MessagingProvider';
6
+
7
+ /** Provider-backed scope configuration surface; hosts choose its placement and capability gate. */
8
+ export function MessagingScopeConfig({ conversationId }) {
9
+ const { t } = useTranslation();
10
+ const { loadConversationConfig, saveConversationConfig } = useMessaging();
11
+ const [config, setConfig] = useState(null);
12
+ const [error, setError] = useState(null);
13
+ const [saving, setSaving] = useState(false);
14
+ useEffect(() => { let live = true; loadConversationConfig(conversationId).then((value) => live && setConfig(value)).catch((loadError) => live && setError(t('MessagingConfig.LOAD_ERROR', { message: extractApiErrorMessage(loadError) }))); return () => { live = false; }; }, [conversationId, loadConversationConfig, t]);
15
+ const update = async (patch) => { setSaving(true); setError(null); try { setConfig(await saveConversationConfig(conversationId, patch)); } catch (saveError) { setError(t('MessagingConfig.SAVE_ERROR', { message: extractApiErrorMessage(saveError) })); } finally { setSaving(false); } };
16
+ if (!config) return error
17
+ ? <Alert severity="error" role="alert">{error}</Alert>
18
+ : <Box aria-label={t('MessagingConfig.LOADING')} sx={{ display: 'flex', justifyContent: 'center', py: 4 }}><CircularProgress size={24} /></Box>;
19
+ return <Stack spacing={1} aria-label={t('MessagingConfig.LABEL')}><Typography variant="subtitle1">{t('MessagingConfig.TITLE')}</Typography>{error && <Alert severity="error" role="alert">{error}</Alert>}
20
+ <FormControl fullWidth size="small" disabled={saving}><InputLabel>{t('MessagingConfig.DM_POLICY')}</InputLabel><Select label={t('MessagingConfig.DM_POLICY')} value={config.dm_policy || 'all'} onChange={(event) => update({ dm_policy: event.target.value })}><MenuItem value="all">{t('MessagingConfig.DM_ALL')}</MenuItem><MenuItem value="within_shared_groups">{t('MessagingConfig.DM_SHARED')}</MenuItem><MenuItem value="team_only">{t('MessagingConfig.DM_TEAM')}</MenuItem></Select></FormControl>
21
+ <FormControlLabel control={<Switch checked={Boolean(config.group_chat_enabled)} disabled={saving} onChange={(event) => update({ group_chat_enabled: event.target.checked })} />} label={t('MessagingConfig.GROUP_ENABLED')} />
22
+ <FormControlLabel control={<Switch checked={Boolean(config.everyone_can_post)} disabled={saving || !config.group_chat_enabled} onChange={(event) => update({ everyone_can_post: event.target.checked })} />} label={t('MessagingConfig.EVERYONE_POSTS')} />
23
+ </Stack>;
24
+ }
@@ -0,0 +1,36 @@
1
+ import { Alert, Button, Checkbox, FormControlLabel, Paper, Stack, Typography } from '@mui/material';
2
+ import { useEffect, useState } from 'react';
3
+ import { useTranslation } from 'react-i18next';
4
+
5
+ import { extractApiErrorMessage, useMessaging } from './MessagingProvider';
6
+
7
+ /** Independently mountable live poll view. Server authorization remains authoritative. */
8
+ export function PollCard({ message, canClose: canCloseProp }) {
9
+ const { t } = useTranslation();
10
+ const { castPollVote, closeConversationPoll, currentUser } = useMessaging();
11
+ const poll = message?.poll;
12
+ const [selected, setSelected] = useState([]);
13
+ const [error, setError] = useState(null);
14
+ const [busy, setBusy] = useState(false);
15
+ useEffect(() => setSelected((poll?.options || []).filter((option) => option.selected || option.voted).map((option) => option.id)), [poll]);
16
+ if (!poll) return null;
17
+ const closed = Boolean(poll.closed_at);
18
+ const creatorId = poll.created_by?.id ?? poll.created_by;
19
+ const canClose = canCloseProp ?? poll.can_close ?? message?.can_close ?? message?.permissions?.can_close ?? (creatorId != null && creatorId === currentUser?.id);
20
+ const changeSelection = (id) => setSelected((current) => poll.allow_multiple ? (current.includes(id) ? current.filter((value) => value !== id) : [...current, id]) : (current.includes(id) ? [] : [id]));
21
+ const vote = async () => {
22
+ if (!selected.length) { setError(t('MessagingPoll.SELECT_OPTION')); return; }
23
+ setBusy(true); setError(null);
24
+ try { await castPollVote(message.id, poll, selected); } catch (voteError) { setError(t('MessagingPoll.VOTE_ERROR', { message: extractApiErrorMessage(voteError) })); } finally { setBusy(false); }
25
+ };
26
+ const close = async () => {
27
+ setBusy(true); setError(null);
28
+ try { await closeConversationPoll(message.id, poll); } catch (closeError) { setError(t('MessagingPoll.CLOSE_ERROR', { message: extractApiErrorMessage(closeError) })); } finally { setBusy(false); }
29
+ };
30
+ return <Paper variant="outlined" sx={{ p: 1 }} aria-label={t('MessagingPoll.LABEL')}><Stack spacing={0.5}>
31
+ <Typography variant="subtitle2">{poll.question}</Typography>
32
+ {(poll.options || []).map((option) => <FormControlLabel key={option.id} disabled={closed || busy} control={<Checkbox checked={selected.includes(option.id)} onChange={() => changeSelection(option.id)} />} label={`${option.text || option.label} (${option.vote_count ?? option.votes_count ?? 0})`} />)}
33
+ {error && <Alert severity="error" role="alert">{error}</Alert>}
34
+ <Stack direction="row" spacing={1}><Button size="small" onClick={vote} disabled={closed || busy}>{t('MessagingPoll.VOTE')}</Button>{canClose && !closed && <Button size="small" color="warning" onClick={close} disabled={busy}>{t('MessagingPoll.CLOSE')}</Button>}{closed && <Typography variant="caption">{t('MessagingPoll.CLOSED')}</Typography>}</Stack>
35
+ </Stack></Paper>;
36
+ }
@@ -0,0 +1,46 @@
1
+ import AddReactionOutlinedIcon from '@mui/icons-material/AddReactionOutlined';
2
+ import { Alert, Chip, IconButton, Stack } from '@mui/material';
3
+ import { useState } from 'react';
4
+ import { useTranslation } from 'react-i18next';
5
+
6
+ import { extractApiErrorMessage, useMessaging } from './MessagingProvider';
7
+
8
+ const QUICK_EMOJIS = ['👍', '❤️', '😂', '🎉', '👀'];
9
+
10
+ /** Independently mountable aggregate reaction controls for one message. */
11
+ export function ReactionBar({ message }) {
12
+ const { t } = useTranslation();
13
+ const { toggleReaction } = useMessaging();
14
+ const [expanded, setExpanded] = useState(false);
15
+ const [error, setError] = useState(null);
16
+ // Tracks in-flight emoji toggles for this message so a rapid double-click
17
+ // can't fire two concurrent requests for the same emoji — toggleReaction's
18
+ // rollback-on-failure reverts to a pre-optimistic snapshot, which would
19
+ // silently discard a second, already-succeeded change if both were in
20
+ // flight at once. Disabling the chip while its own request is pending
21
+ // removes the race instead of trying to make concurrent toggles safe.
22
+ const [pending, setPending] = useState(() => new Set());
23
+ const reactions = message?.reactions || [];
24
+ const react = async (emoji, active = false) => {
25
+ if (pending.has(emoji)) return;
26
+ setError(null);
27
+ setPending((current) => new Set(current).add(emoji));
28
+ try { await toggleReaction(message.id, emoji, active); }
29
+ catch (reactionError) { setError(t('MessagingReactions.ERROR', { message: extractApiErrorMessage(reactionError) })); }
30
+ finally { setPending((current) => { const next = new Set(current); next.delete(emoji); return next; }); }
31
+ };
32
+ return <Stack spacing={0.5} aria-label={t('MessagingReactions.LABEL')}>
33
+ <Stack direction="row" spacing={0.5} flexWrap="wrap">
34
+ {reactions.map((reaction) => <Chip key={reaction.emoji} size="small" disabled={pending.has(reaction.emoji)} color={reaction.reacted ? 'primary' : 'default'} label={`${reaction.emoji} ${reaction.count || 0}`} onClick={() => react(reaction.emoji, Boolean(reaction.reacted))} aria-label={t('MessagingReactions.TOGGLE', { emoji: reaction.emoji, count: reaction.count || 0 })} />)}
35
+ <IconButton size="small" aria-label={t('MessagingReactions.ADD')} onClick={() => setExpanded((value) => !value)}><AddReactionOutlinedIcon fontSize="small" /></IconButton>
36
+ </Stack>
37
+ {expanded && <Stack direction="row" spacing={0.25} flexWrap="wrap">{QUICK_EMOJIS.map((emoji) => {
38
+ // A quick-emoji already reflected in the aggregate row must toggle it
39
+ // off, not re-add it — otherwise clicking an already-reacted emoji here
40
+ // optimistically double-increments the count before the API call.
41
+ const existing = reactions.find((reaction) => reaction.emoji === emoji);
42
+ return <Chip key={emoji} size="small" disabled={pending.has(emoji)} color={existing?.reacted ? 'primary' : 'default'} label={emoji} onClick={() => { react(emoji, Boolean(existing?.reacted)); setExpanded(false); }} />;
43
+ })}</Stack>}
44
+ {error && <Alert severity="error" role="alert">{error}</Alert>}
45
+ </Stack>;
46
+ }
@@ -0,0 +1,23 @@
1
+ import { Tooltip, Typography } from '@mui/material';
2
+ import { useEffect, useState } from 'react';
3
+ import { useTranslation } from 'react-i18next';
4
+
5
+ import { useMessaging } from './MessagingProvider';
6
+
7
+ /** Renders only the aggregate receipt unless the server explicitly supplies permitted detail. */
8
+ export function ReadTicks({ messageId, conversation }) {
9
+ const { t } = useTranslation();
10
+ const { getMessageReadStatus } = useMessaging();
11
+ const [status, setStatus] = useState(null);
12
+ useEffect(() => {
13
+ let mounted = true;
14
+ getMessageReadStatus(messageId).then((next) => { if (mounted) setStatus(next); }).catch(() => { if (mounted) setStatus(null); });
15
+ return () => { mounted = false; };
16
+ }, [getMessageReadStatus, messageId]);
17
+ if (!status) return null;
18
+ const label = status.all_read ? t('MessagingReadTicks.ALL_READ') : t('MessagingReadTicks.DELIVERED', { count: status.delivered_count || 0 });
19
+ // The server never returns DM detail; enforce the same carve-out defensively.
20
+ const detail = conversation?.kind === 'direct' ? null : status.recipient_detail;
21
+ const detailText = detail?.map((recipient) => recipient.display_name || recipient.username || recipient.user_id).filter(Boolean).join(', ');
22
+ return <Tooltip title={detailText || label}><Typography component="span" variant="caption" color="text.secondary" aria-label={label}>{label}</Typography></Tooltip>;
23
+ }
@@ -0,0 +1,71 @@
1
+ import { Alert, Box, Button, CircularProgress, Divider, Stack, Typography } from '@mui/material';
2
+ import { useCallback, useContext, useMemo, useRef, useState } from 'react';
3
+ import { useTranslation } from 'react-i18next';
4
+
5
+ import { AuthContext } from '../auth/AuthContext';
6
+ import { MessageBubble } from './MessageBubble';
7
+ import { useMessaging } from './MessagingProvider';
8
+ import { ReadTicks } from './ReadTicks';
9
+
10
+ function chronological(messages) { return [...messages].sort((left, right) => new Date(left.created_at || 0) - new Date(right.created_at || 0)); }
11
+ // A still-pending optimistic row (chunk 4) has a fake `local-<requestId>` id
12
+ // and no durable server row yet — mounting ReadTicks against it would fire a
13
+ // getMessageReadStatus REST call for an id the server has never heard of.
14
+ // Wait for reconciliation (status !== 'pending') before showing read state.
15
+ function canShowReadTicks(message, user) {
16
+ return Boolean(user?.id) && message.sender?.id === user.id && message.status !== 'pending';
17
+ }
18
+
19
+ /**
20
+ * A standalone timeline. Compose/reaction/poll/attachment mutations remain
21
+ * separate chunk collaborators.
22
+ *
23
+ * ReadTicks is only mounted for the current user's own messages (matches
24
+ * jg's `shouldShowReadTick(msg, isOwn)`): a read receipt tells the sender
25
+ * whether their own message was seen, not the recipient anything about a
26
+ * message they're currently reading. Gating here also bounds the number of
27
+ * `getMessageReadStatus` REST calls a rendered timeline fires — one per own
28
+ * message shown, not one per message in the conversation.
29
+ */
30
+ export function Thread({ conversationId, onReplyTargetChange }) {
31
+ const { t } = useTranslation();
32
+ const { user } = useContext(AuthContext) || {};
33
+ const { cache, loadMoreMessages, loadThreadReplies } = useMessaging();
34
+ const scrollRef = useRef(null);
35
+ const [loadingOlder, setLoadingOlder] = useState(false);
36
+ const [error, setError] = useState(null);
37
+ const [replyingTo, setReplyingTo] = useState(null);
38
+ const [openThreads, setOpenThreads] = useState({});
39
+ const conversation = cache.conversations[conversationId];
40
+ const roots = useMemo(() => chronological(Object.values(cache.messages).filter((message) => message.conversation_id === conversationId && !message.reply_to)), [cache.messages, conversationId]);
41
+
42
+ const loadOlder = useCallback(async () => {
43
+ setLoadingOlder(true); setError(null);
44
+ try { await loadMoreMessages(conversationId); } catch { setError(t('MessagingThread.LOAD_ERROR')); } finally { setLoadingOlder(false); }
45
+ }, [conversationId, loadMoreMessages, t]);
46
+ const onScroll = () => { if (scrollRef.current?.scrollTop === 0 && cache.cursors.messages[conversationId] && !loadingOlder) loadOlder(); };
47
+ const reply = (message) => { setReplyingTo(message); onReplyTargetChange?.(message); };
48
+ const toggleReplies = async (root) => {
49
+ if (!openThreads[root.id]) {
50
+ try { await loadThreadReplies(root.id); } catch { setError(t('MessagingThread.REPLIES_ERROR')); return; }
51
+ }
52
+ setOpenThreads((current) => ({ ...current, [root.id]: !current[root.id] }));
53
+ };
54
+ return (
55
+ <Stack spacing={1} sx={{ minWidth: 0 }}>
56
+ {error && <Alert severity="error" role="alert">{error}</Alert>}
57
+ {replyingTo && <Alert severity="info" onClose={() => { setReplyingTo(null); onReplyTargetChange?.(null); }}>{t('MessagingThread.REPLYING_TO', { sender: replyingTo.sender?.display_name || t('MessagingThread.UNKNOWN_SENDER') })}</Alert>}
58
+ <Box ref={scrollRef} onScroll={onScroll} sx={{ maxHeight: 560, overflowY: 'auto', px: 0.5 }} aria-label={t('MessagingThread.TIMELINE')}>
59
+ {cache.cursors.messages[conversationId] && <Box textAlign="center" py={1}><Button onClick={loadOlder} disabled={loadingOlder}>{loadingOlder ? <CircularProgress size={18} /> : t('MessagingThread.LOAD_OLDER')}</Button></Box>}
60
+ {!roots.length && <Typography color="text.secondary" textAlign="center" py={4}>{t('MessagingThread.EMPTY')}</Typography>}
61
+ <Stack spacing={1}>{roots.map((message) => {
62
+ const replies = chronological(Object.values(cache.messages).filter((item) => item.reply_to === message.id));
63
+ return <Stack key={message.id} spacing={0.75}><MessageBubble message={message} onReply={reply}>{canShowReadTicks(message, user) && <ReadTicks messageId={message.id} conversation={conversation} />}</MessageBubble>
64
+ {(message.reply_count || replies.length) > 0 && <Button size="small" onClick={() => toggleReplies(message)}>{openThreads[message.id] ? t('MessagingThread.HIDE_REPLIES') : t('MessagingThread.SHOW_REPLIES', { count: message.reply_count || replies.length })}</Button>}
65
+ {openThreads[message.id] && <Stack spacing={0.75} sx={{ pl: 3, borderLeft: 2, borderColor: 'divider' }}>{replies.map((item) => <MessageBubble key={item.id} message={item} replyTo={message} onReply={reply}>{canShowReadTicks(item, user) && <ReadTicks messageId={item.id} conversation={conversation} />}</MessageBubble>)}</Stack>}
66
+ <Divider /></Stack>;
67
+ })}</Stack>
68
+ </Box>
69
+ </Stack>
70
+ );
71
+ }
@@ -0,0 +1,47 @@
1
+ import apiClient from '../auth/apiClient';
2
+
3
+ const BASE_URL = '/api/messaging/';
4
+ const conversationsUrl = `${BASE_URL}conversations/`;
5
+
6
+ function data(response) {
7
+ return response.data;
8
+ }
9
+
10
+ function requestConfig({ cursor, params, headers } = {}) {
11
+ return {
12
+ ...(params ? { params } : {}),
13
+ ...(cursor ? { params: { ...(params || {}), cursor } } : {}),
14
+ ...(headers ? { headers } : {}),
15
+ };
16
+ }
17
+
18
+ export function listConversations({ cursor, ...filters } = {}) {
19
+ return apiClient.get(conversationsUrl, requestConfig({ cursor, params: filters })).then(data);
20
+ }
21
+ export function createDirectConversation(payload) { return apiClient.post(`${conversationsUrl}direct/`, payload).then(data); }
22
+ export function createGroupConversation(payload) { return apiClient.post(`${conversationsUrl}group/`, payload).then(data); }
23
+ export function createBroadcastConversation(payload) { return apiClient.post(`${conversationsUrl}broadcast/`, payload).then(data); }
24
+ export function createManagedConversation(payload) { return apiClient.post(`${conversationsUrl}managed/`, payload).then(data); }
25
+ export function createObjectThreadConversation(payload) { return apiClient.post(`${conversationsUrl}object-thread/`, payload).then(data); }
26
+ export function getConversationConfig(conversationId) { return apiClient.get(`${conversationsUrl}${conversationId}/config/`).then(data); }
27
+ export function patchConversationConfig(conversationId, patch) { return apiClient.patch(`${conversationsUrl}${conversationId}/config/`, patch).then(data); }
28
+ export function archiveConversation(conversationId, archived) { return apiClient.post(`${conversationsUrl}${conversationId}/archive/`, { archived }).then(data); }
29
+ export function patchConversationPreferences(conversationId, patch) { return apiClient.post(`${conversationsUrl}${conversationId}/preferences/`, patch).then(data); }
30
+ export function listMessages(conversationId, { cursor } = {}) { return apiClient.get(`${conversationsUrl}${conversationId}/messages/`, requestConfig({ cursor })).then(data); }
31
+ export function createMessage(conversationId, payload, { idempotencyKey } = {}) { return apiClient.post(`${conversationsUrl}${conversationId}/messages/`, payload, requestConfig({ headers: idempotencyKey ? { 'Idempotency-Key': idempotencyKey } : undefined })).then(data); }
32
+ export function uploadAttachments(conversationId, formData, { idempotencyKey } = {}) { return apiClient.post(`${conversationsUrl}${conversationId}/attachments/`, formData, requestConfig({ headers: idempotencyKey ? { 'Idempotency-Key': idempotencyKey } : undefined })).then(data); }
33
+ export function createPoll(conversationId, payload, { idempotencyKey } = {}) { return apiClient.post(`${conversationsUrl}${conversationId}/polls/`, payload, requestConfig({ headers: idempotencyKey ? { 'Idempotency-Key': idempotencyKey } : undefined })).then(data); }
34
+ export function getMessage(messageId) { return apiClient.get(`${BASE_URL}messages/${messageId}/`).then(data); }
35
+ export function patchMessage(messageId, patch) { return apiClient.patch(`${BASE_URL}messages/${messageId}/`, patch).then(data); }
36
+ export function deleteMessage(messageId) { return apiClient.delete(`${BASE_URL}messages/${messageId}/`).then(data); }
37
+ export function addReaction(messageId, emoji) { return apiClient.post(`${BASE_URL}messages/${messageId}/reactions/`, { emoji }).then(data); }
38
+ export function removeReaction(messageId, emoji) { return apiClient.delete(`${BASE_URL}messages/${messageId}/reactions/${encodeURIComponent(emoji)}/`).then(data); }
39
+ export function listThread(rootId, { cursor } = {}) { return apiClient.get(`${BASE_URL}messages/${rootId}/thread/`, requestConfig({ cursor })).then(data); }
40
+ export function markThreadRead(rootId, readAt) { return apiClient.post(`${BASE_URL}messages/${rootId}/thread/read/`, readAt ? { read_at: readAt } : {}).then(data); }
41
+ export function markConversationRead(conversationId, readAt) { return apiClient.post(`${conversationsUrl}${conversationId}/read/`, readAt ? { read_at: readAt } : {}).then(data); }
42
+ export function getReadStatus(messageId) { return apiClient.get(`${BASE_URL}messages/${messageId}/read-status/`).then(data); }
43
+ export function votePoll(pollId, optionIds) { return apiClient.post(`${BASE_URL}polls/${pollId}/vote/`, { option_ids: optionIds }).then(data); }
44
+ export function closePoll(pollId) { return apiClient.post(`${BASE_URL}polls/${pollId}/close/`).then(data); }
45
+ export function getAttachment(attachmentId) { return apiClient.get(`${BASE_URL}attachments/${attachmentId}/`, { responseType: 'blob' }).then(data); }
46
+ export function getAttachmentThumbnail(attachmentId) { return apiClient.get(`${BASE_URL}attachments/${attachmentId}/thumbnail/`, { responseType: 'blob' }).then(data); }
47
+ export function getUnreadCount() { return apiClient.get(`${BASE_URL}unread-count/`).then(data); }
@@ -89,7 +89,7 @@ export function NotificationsProvider({ children, wsUrlBase }) {
89
89
  // arrived and patched state before the initial REST response landed.
90
90
  const [seeded, setSeeded] = useState(false);
91
91
 
92
- const { subscribe } = useRealtimeCore({
92
+ const { subscribe, onReconnect } = useRealtimeCore({
93
93
  active: authenticated && seeded,
94
94
  wsUrl: getWebSocketUrl(wsUrlBase),
95
95
  });
@@ -200,7 +200,7 @@ export function NotificationsProvider({ children, wsUrlBase }) {
200
200
  const markDone = useCallback((ids) => mark('done', ids), [mark]);
201
201
 
202
202
  return (
203
- <RealtimeContext.Provider value={{ subscribe }}>
203
+ <RealtimeContext.Provider value={{ subscribe, onReconnect }}>
204
204
  <NotificationsContext.Provider value={{
205
205
  notifications,
206
206
  unreadCount,