@messenger-box/tailwind-ui-inbox 10.0.3-alpha.70 → 10.0.3-alpha.72

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 (155) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/lib/components/AIAgent/AIAgent.d.ts +14 -0
  3. package/lib/components/AIAgent/AIAgent.d.ts.map +1 -0
  4. package/lib/components/AIAgent/AIAgent.js +1148 -0
  5. package/lib/components/AIAgent/AIAgent.js.map +1 -0
  6. package/lib/components/AIAgent/index.d.ts +2 -0
  7. package/lib/components/AIAgent/index.d.ts.map +1 -0
  8. package/lib/components/InboxMessage/InputComponent.d.ts +9 -0
  9. package/lib/components/InboxMessage/InputComponent.d.ts.map +1 -0
  10. package/lib/components/InboxMessage/InputComponent.js +210 -0
  11. package/lib/components/InboxMessage/InputComponent.js.map +1 -0
  12. package/lib/components/InboxMessage/LeftSidebar.d.ts +2 -0
  13. package/lib/components/InboxMessage/LeftSidebar.d.ts.map +1 -1
  14. package/lib/components/InboxMessage/LeftSidebar.js +16 -5
  15. package/lib/components/InboxMessage/LeftSidebar.js.map +1 -1
  16. package/lib/components/InboxMessage/MessageInput.d.ts.map +1 -1
  17. package/lib/components/InboxMessage/MessageInput.js +14 -10
  18. package/lib/components/InboxMessage/MessageInput.js.map +1 -1
  19. package/lib/components/InboxMessage/MessageInputComponent.d.ts +9 -0
  20. package/lib/components/InboxMessage/MessageInputComponent.d.ts.map +1 -0
  21. package/lib/components/InboxMessage/MessageInputComponent.js +173 -0
  22. package/lib/components/InboxMessage/MessageInputComponent.js.map +1 -0
  23. package/lib/components/InboxMessage/Messages.d.ts +3 -1
  24. package/lib/components/InboxMessage/Messages.d.ts.map +1 -1
  25. package/lib/components/InboxMessage/Messages.js +16 -60
  26. package/lib/components/InboxMessage/Messages.js.map +1 -1
  27. package/lib/components/InboxMessage/MessagesBuilderUi.d.ts +17 -0
  28. package/lib/components/InboxMessage/MessagesBuilderUi.d.ts.map +1 -0
  29. package/lib/components/InboxMessage/MessagesBuilderUi.js +162 -0
  30. package/lib/components/InboxMessage/MessagesBuilderUi.js.map +1 -0
  31. package/lib/components/InboxMessage/UploadImageButton.d.ts +1 -0
  32. package/lib/components/InboxMessage/UploadImageButton.d.ts.map +1 -1
  33. package/lib/components/InboxMessage/UploadImageButton.js +3 -3
  34. package/lib/components/InboxMessage/UploadImageButton.js.map +1 -1
  35. package/lib/components/InboxMessage/index.d.ts +3 -0
  36. package/lib/components/InboxMessage/index.d.ts.map +1 -1
  37. package/lib/components/InboxMessage/message-widgets/CommonMessage.d.ts.map +1 -1
  38. package/lib/components/InboxMessage/message-widgets/CommonMessage.js +11 -6
  39. package/lib/components/InboxMessage/message-widgets/CommonMessage.js.map +1 -1
  40. package/lib/components/InboxMessage/message-widgets/ModernMessageGroup.d.ts +14 -0
  41. package/lib/components/InboxMessage/message-widgets/ModernMessageGroup.d.ts.map +1 -0
  42. package/lib/components/InboxMessage/message-widgets/ModernMessageGroup.js +1525 -0
  43. package/lib/components/InboxMessage/message-widgets/ModernMessageGroup.js.map +1 -0
  44. package/lib/components/InboxMessage/message-widgets/PlainMessage.d.ts.map +1 -1
  45. package/lib/components/InboxMessage/message-widgets/PlainMessage.js +6 -3
  46. package/lib/components/InboxMessage/message-widgets/PlainMessage.js.map +1 -1
  47. package/lib/components/InboxMessage/message-widgets/SlackLikeMessageGroup.d.ts +2 -0
  48. package/lib/components/InboxMessage/message-widgets/SlackLikeMessageGroup.d.ts.map +1 -1
  49. package/lib/components/InboxMessage/message-widgets/SlackLikeMessageGroup.js +225 -26
  50. package/lib/components/InboxMessage/message-widgets/SlackLikeMessageGroup.js.map +1 -1
  51. package/lib/components/InboxMessage/message-widgets/index.d.ts +1 -0
  52. package/lib/components/InboxMessage/message-widgets/index.d.ts.map +1 -1
  53. package/lib/components/index.d.ts +2 -1
  54. package/lib/components/index.d.ts.map +1 -1
  55. package/lib/compute.d.ts.map +1 -1
  56. package/lib/compute.js +79 -3
  57. package/lib/compute.js.map +1 -1
  58. package/lib/config/env-config.d.ts +6 -0
  59. package/lib/config/env-config.d.ts.map +1 -1
  60. package/lib/config/env-config.js +19 -1
  61. package/lib/config/env-config.js.map +1 -1
  62. package/lib/container/AiInbox.d.ts +15 -0
  63. package/lib/container/AiInbox.d.ts.map +1 -0
  64. package/lib/container/AiInbox.js +1520 -0
  65. package/lib/container/AiInbox.js.map +1 -0
  66. package/lib/container/AiInboxWithLoader.d.ts +36 -0
  67. package/lib/container/AiInboxWithLoader.d.ts.map +1 -0
  68. package/lib/container/AiInboxWithLoader.js +300 -0
  69. package/lib/container/AiInboxWithLoader.js.map +1 -0
  70. package/lib/container/AiLandingInput.d.ts +4 -0
  71. package/lib/container/AiLandingInput.d.ts.map +1 -0
  72. package/lib/container/AiLandingInput.js +164 -0
  73. package/lib/container/AiLandingInput.js.map +1 -0
  74. package/lib/container/Inbox.d.ts.map +1 -1
  75. package/lib/container/Inbox.js +177 -58
  76. package/lib/container/Inbox.js.map +1 -1
  77. package/lib/container/InboxAiMessagesLoader.d.ts +36 -0
  78. package/lib/container/InboxAiMessagesLoader.d.ts.map +1 -0
  79. package/lib/container/InboxAiMessagesLoader.js +47 -0
  80. package/lib/container/InboxAiMessagesLoader.js.map +1 -0
  81. package/lib/container/InboxContainer.d.ts +12 -0
  82. package/lib/container/InboxContainer.d.ts.map +1 -0
  83. package/lib/container/InboxContainer.js +31 -0
  84. package/lib/container/InboxContainer.js.map +1 -0
  85. package/lib/container/InboxTemplate1.d.ts +15 -0
  86. package/lib/container/InboxTemplate1.d.ts.map +1 -0
  87. package/lib/container/InboxTemplate1.js +1375 -0
  88. package/lib/container/InboxTemplate1.js.map +1 -0
  89. package/lib/container/InboxTemplate1WithLoader.d.ts +36 -0
  90. package/lib/container/InboxTemplate1WithLoader.d.ts.map +1 -0
  91. package/lib/container/InboxTemplate2.d.ts +15 -0
  92. package/lib/container/InboxTemplate2.d.ts.map +1 -0
  93. package/lib/container/InboxTemplate2.js +1426 -0
  94. package/lib/container/InboxTemplate2.js.map +1 -0
  95. package/lib/container/InboxWithAiLoader.d.ts +15 -0
  96. package/lib/container/InboxWithAiLoader.d.ts.map +1 -0
  97. package/lib/container/InboxWithAiLoader.js +56 -0
  98. package/lib/container/InboxWithAiLoader.js.map +1 -0
  99. package/lib/container/ServiceInbox.js +1 -1
  100. package/lib/container/ServiceInbox.js.map +1 -1
  101. package/lib/container/ThreadMessages.js +1 -1
  102. package/lib/container/ThreadMessages.js.map +1 -1
  103. package/lib/container/ThreadMessagesInbox.js +1 -1
  104. package/lib/container/ThreadMessagesInbox.js.map +1 -1
  105. package/lib/container/Threads.js +1 -1
  106. package/lib/container/Threads.js.map +1 -1
  107. package/lib/container/index.d.ts +4 -1
  108. package/lib/container/index.d.ts.map +1 -1
  109. package/lib/index.js +1 -1
  110. package/lib/machines/aiAgentMachine.d.ts +3 -0
  111. package/lib/machines/aiAgentMachine.d.ts.map +1 -0
  112. package/lib/machines/aiAgentMachine.js +1040 -0
  113. package/lib/machines/aiAgentMachine.js.map +1 -0
  114. package/lib/machines/types.d.ts +77 -0
  115. package/lib/machines/types.d.ts.map +1 -0
  116. package/lib/routes.json +40 -0
  117. package/lib/templates/InboxWithAi.d.ts +15 -0
  118. package/lib/templates/InboxWithAi.d.ts.map +1 -0
  119. package/lib/templates/InboxWithAi.js +405 -0
  120. package/lib/templates/InboxWithAi.js.map +1 -0
  121. package/lib/templates/InboxWithAi.tsx +502 -0
  122. package/package.json +7 -5
  123. package/src/components/AIAgent/AIAgent.tsx +1351 -0
  124. package/src/components/AIAgent/README.md +82 -0
  125. package/src/components/AIAgent/index.ts +1 -0
  126. package/src/components/InboxMessage/InputComponent.tsx +263 -0
  127. package/src/components/InboxMessage/LeftSidebar.tsx +14 -4
  128. package/src/components/InboxMessage/MessageInput.tsx +73 -66
  129. package/src/components/InboxMessage/MessageInputComponent.tsx +245 -0
  130. package/src/components/InboxMessage/Messages.tsx +24 -68
  131. package/src/components/InboxMessage/MessagesBuilderUi.tsx +205 -0
  132. package/src/components/InboxMessage/UploadImageButton.tsx +3 -2
  133. package/src/components/InboxMessage/index.ts +3 -0
  134. package/src/components/InboxMessage/message-widgets/CommonMessage.tsx +39 -21
  135. package/src/components/InboxMessage/message-widgets/ModernMessageGroup.tsx +1968 -0
  136. package/src/components/InboxMessage/message-widgets/PlainMessage.tsx +6 -2
  137. package/src/components/InboxMessage/message-widgets/SlackLikeMessageGroup.tsx +337 -53
  138. package/src/components/InboxMessage/message-widgets/index.ts +1 -0
  139. package/src/components/index.ts +4 -0
  140. package/src/compute.ts +83 -2
  141. package/src/config/env-config.ts +6 -0
  142. package/src/container/AiInbox.tsx +1796 -0
  143. package/src/container/AiInboxWithLoader.tsx +356 -0
  144. package/src/container/AiLandingInput.tsx +168 -0
  145. package/src/container/Inbox.tsx +280 -130
  146. package/src/container/InboxAiMessagesLoader.tsx +68 -0
  147. package/src/container/InboxContainer.tsx +35 -0
  148. package/src/container/InboxTemplate1.tsx +1542 -0
  149. package/src/container/InboxTemplate1WithLoader.tsx +338 -0
  150. package/src/container/InboxTemplate2.tsx +1606 -0
  151. package/src/container/InboxWithAiLoader.tsx +76 -0
  152. package/src/container/index.ts +15 -1
  153. package/src/machines/aiAgentMachine.ts +1248 -0
  154. package/src/machines/types.ts +59 -0
  155. package/src/templates/InboxWithAi.tsx +502 -0
@@ -0,0 +1,1542 @@
1
+ import React, {
2
+ ReactNode,
3
+ useCallback,
4
+ useEffect,
5
+ useMemo,
6
+ useReducer,
7
+ useRef,
8
+ createContext,
9
+ useContext,
10
+ } from 'react';
11
+ import { orderBy, uniqBy } from 'lodash-es';
12
+ import {
13
+ OnChatMessageAddedDocument as CHAT_MESSAGE_ADDED,
14
+ useSendMessagesMutation,
15
+ GetChannelsByUserDocument,
16
+ MessagesDocument,
17
+ } from 'common/graphql';
18
+ import { useUploadFiles } from '@messenger-box/platform-client';
19
+ import { IFileInfo, RoomType, PostTypeEnum } from 'common';
20
+ import { useSelector, shallowEqual } from 'react-redux';
21
+ import { useNavigate, useParams } from '@remix-run/react';
22
+ import { LeftSidebar, MessagesBuilderUi, InputComponent } from '../components';
23
+ import { Store, userSelector } from '@adminide-stack/user-auth0-client';
24
+ import { IUserState } from '@adminide-stack/core';
25
+ import { config } from '../config';
26
+ import { applyFooterStyles } from './apply-footer-styles';
27
+ import { objectId } from '@messenger-box/core';
28
+ import { ThreadsInbox } from './ThreadsInbox';
29
+ import { ThreadMessagesInbox } from './ThreadMessagesInbox';
30
+ import { useApolloClient } from '@apollo/client';
31
+ import { SubscriptionHandler } from '../components/InboxMessage/SubscriptionHandler';
32
+
33
+ const { MESSAGES_PER_PAGE } = config;
34
+
35
+ // Context for sharing tab state between header and sidebar
36
+ const TabContext = createContext<{
37
+ activeTab: string;
38
+ setActiveTab: (tab: string) => void;
39
+ }>({
40
+ activeTab: 'design',
41
+ setActiveTab: () => {},
42
+ });
43
+
44
+ // Types
45
+ interface DrawerProps {
46
+ isOpen: boolean;
47
+ onClose: () => void;
48
+ children: ReactNode;
49
+ title?: string;
50
+ }
51
+
52
+ export interface InboxProps {
53
+ channelFilters?: Record<string, unknown>;
54
+ channelRole?: string;
55
+ supportServices?: boolean;
56
+ pathPrefix?: string;
57
+ data?: any;
58
+ orgName?: string;
59
+ }
60
+
61
+ interface MobilePreviewState {
62
+ mobilePreviewVisibility: boolean;
63
+ mobilePreviewText: string | ReactNode;
64
+ mobilePreviewCTAText: string | ReactNode;
65
+ }
66
+
67
+ // Static utility hooks and components
68
+ const useMediaQuery = (query: string) => {
69
+ const [matches, setMatches] = React.useState(false);
70
+
71
+ useEffect(() => {
72
+ if (typeof window === 'undefined') return;
73
+
74
+ const mediaQuery = window.matchMedia(query);
75
+ const updateMatches = () => setMatches(mediaQuery.matches);
76
+
77
+ updateMatches();
78
+ mediaQuery.addEventListener('change', updateMatches);
79
+ return () => mediaQuery.removeEventListener('change', updateMatches);
80
+ }, [query]);
81
+
82
+ return matches;
83
+ };
84
+
85
+ // Hook to get window dimensions
86
+ const useWindowDimensions = () => {
87
+ const [windowDimensions, setWindowDimensions] = React.useState({
88
+ width: typeof window !== 'undefined' ? window.innerWidth : 1024,
89
+ height: typeof window !== 'undefined' ? window.innerHeight : 768,
90
+ });
91
+
92
+ useEffect(() => {
93
+ if (typeof window === 'undefined') return;
94
+
95
+ const handleResize = () => {
96
+ setWindowDimensions({
97
+ width: window.innerWidth,
98
+ height: window.innerHeight,
99
+ });
100
+ };
101
+
102
+ window.addEventListener('resize', handleResize);
103
+ handleResize(); // Set initial dimensions
104
+
105
+ return () => window.removeEventListener('resize', handleResize);
106
+ }, []);
107
+
108
+ return windowDimensions;
109
+ };
110
+
111
+ // Static components
112
+ const Spinner = React.memo(({ className = '' }: { className?: string }) => (
113
+ <div className={`animate-spin rounded-full border-4 border-gray-200 border-t-blue-500 ${className}`}>
114
+ <span className="sr-only">Loading...</span>
115
+ </div>
116
+ ));
117
+
118
+ const Drawer = React.memo(({ isOpen, onClose, children, title }: DrawerProps) => {
119
+ if (!isOpen) return null;
120
+
121
+ return (
122
+ <div className="fixed inset-0 z-50 overflow-hidden">
123
+ <div className="absolute inset-0 bg-black bg-opacity-50" onClick={onClose} />
124
+ <div className="absolute bottom-0 left-0 right-0 bg-white rounded-t-lg shadow-lg max-h-[80vh] flex flex-col overflow-hidden">
125
+ <div className="flex items-center justify-between p-4 border-b border-gray-200 flex-shrink-0">
126
+ <h2 className="text-lg font-semibold truncate">{title}</h2>
127
+ <button
128
+ onClick={onClose}
129
+ className="p-1 hover:bg-gray-100 rounded-full transition-colors flex-shrink-0 ml-2"
130
+ >
131
+ <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
132
+ <path
133
+ strokeLinecap="round"
134
+ strokeLinejoin="round"
135
+ strokeWidth={2}
136
+ d="M6 18L18 6M6 6l12 12"
137
+ />
138
+ </svg>
139
+ </button>
140
+ </div>
141
+ <div className="flex-1 p-4 overflow-y-auto" style={{ minHeight: 0 }}>
142
+ {children}
143
+ </div>
144
+ </div>
145
+ </div>
146
+ );
147
+ });
148
+
149
+ const EmptyState = React.memo(() => (
150
+ <div className="h-full flex items-center justify-center bg-gray-100 p-4 sm:p-6 overflow-hidden">
151
+ <div className="text-center max-w-sm mx-auto">
152
+ <div className="text-3xl sm:text-4xl text-gray-400 mb-4">💬</div>
153
+ <h3 className="text-lg sm:text-xl font-semibold text-gray-600 mb-2">Welcome to Messenger</h3>
154
+ <p className="text-sm sm:text-base text-gray-500 leading-relaxed">
155
+ Select a conversation from the sidebar to start messaging
156
+ </p>
157
+ </div>
158
+ </div>
159
+ ));
160
+
161
+ // Mobile preview reducer
162
+ const mobilePreviewReducer = (
163
+ state: MobilePreviewState,
164
+ action: { payload: Partial<MobilePreviewState>; type: string },
165
+ ) => {
166
+ if (action.type === 'update') {
167
+ return { ...state, ...action.payload };
168
+ }
169
+ return state;
170
+ };
171
+
172
+ const InboxTemplate1 = (props: InboxProps) => {
173
+ const [activeTab, setActiveTab] = React.useState('design');
174
+
175
+ return (
176
+ <TabContext.Provider value={{ activeTab, setActiveTab }}>
177
+ <InboxTemplate1Internal {...props} />
178
+ </TabContext.Provider>
179
+ );
180
+ };
181
+
182
+ const InboxTemplate1Internal = (props: InboxProps) => {
183
+ const { channelFilters: channelFilterProp, channelRole, supportServices, data, orgName, pathPrefix = null } = props;
184
+ const { id: pathChannelId, postId: pathPostId } = useParams();
185
+ const navigate = useNavigate();
186
+ const apolloClient = useApolloClient();
187
+
188
+ // Reduced state - only UI state remains, data comes from Apollo cache
189
+ const [isBottomDrawerOpen, setBottomDrawer] = React.useState(false);
190
+ const [mobilePreviewState, localDispatch] = useReducer(mobilePreviewReducer, {
191
+ mobilePreviewVisibility: false,
192
+ mobilePreviewText: false,
193
+ mobilePreviewCTAText: false,
194
+ });
195
+
196
+ // Hooks - improved responsive breakpoints with better granularity
197
+ const { width: windowWidth, height: windowHeight } = useWindowDimensions();
198
+ const isMobileView = useMediaQuery('(max-width: 640px)');
199
+ const isSmallTabletView = useMediaQuery('(min-width: 641px) and (max-width: 900px)');
200
+ const isTabletView = useMediaQuery('(min-width: 901px) and (max-width: 1024px)');
201
+ const isDesktopView = useMediaQuery('(min-width: 1025px)');
202
+ const isLargeDesktopView = useMediaQuery('(min-width: 1440px)');
203
+ const isSmallScreen = useMediaQuery('(max-width: 900px)');
204
+ // const auth = useSelector(userSelector);
205
+ const auth: any = useSelector<Store.Auth, IUserState>(userSelector, shallowEqual);
206
+ // const user = useSelector((state: any) => state.user, shallowEqual);
207
+
208
+ // Data destructuring from Apollo queries
209
+ const GetChannelsByUserQuery = data?.[0];
210
+ const {
211
+ data: userChannels,
212
+ loading: userChannelsLoading,
213
+ refetch: getChannelsRefetch,
214
+ } = GetChannelsByUserQuery || {};
215
+
216
+ // Get data directly from Apollo cache instead of local state
217
+ const channels = useMemo(() => {
218
+ if (!userChannels?.channelsByUser && !userChannels?.supportServiceChannels) return [];
219
+
220
+ return uniqBy([...(userChannels?.supportServiceChannels ?? []), ...(userChannels?.channelsByUser ?? [])], 'id');
221
+ }, [userChannels]);
222
+
223
+ // Memoize stable channel array to prevent unnecessary re-renders
224
+ const stableChannels = useMemo(() => {
225
+ return channels || [];
226
+ }, [channels]);
227
+
228
+ // Memoized values derived from Apollo cache data
229
+ const channelFilters = useMemo(() => {
230
+ const filters = { ...channelFilterProp };
231
+ const channelType = filters?.type ?? RoomType.Direct;
232
+ filters.type = supportServices ? [channelType, RoomType.Service] : channelType;
233
+ return filters;
234
+ }, [channelFilterProp, supportServices]);
235
+
236
+ const users = useMemo(() => {
237
+ return (
238
+ channels?.reduce((acc, curr) => {
239
+ const newMembers = curr.members?.filter(({ user }) => !acc.find(({ id }) => id === user.id)) || [];
240
+ return [...acc, ...newMembers.map(({ user }) => user)];
241
+ }, []) || []
242
+ );
243
+ }, [channels]);
244
+
245
+ // const currentUser = useMemo(
246
+ // () => users?.find((user) => user && user.alias?.includes(auth?.authUserId)),
247
+ // [users, auth?.authUserId],
248
+ // );
249
+ const currentUser = auth;
250
+
251
+ const channelName = useMemo(() => {
252
+ if (!channels || !pathChannelId) return '';
253
+
254
+ const currChannel = channels?.find((ch) => ch.id === pathChannelId);
255
+ if (!currChannel) return '';
256
+
257
+ const { members, title, type } = currChannel;
258
+
259
+ if (type === RoomType.Direct && members?.length >= 2) {
260
+ const otherUser = members.find((member) => member.user.id !== currentUser?.id);
261
+ if (otherUser?.user) {
262
+ const { givenName, familyName } = otherUser.user;
263
+ if (givenName && familyName) return `${givenName} ${familyName}`;
264
+ return givenName || familyName || title || 'Direct Message';
265
+ }
266
+ return title || 'Direct Message';
267
+ }
268
+
269
+ if (type === RoomType.Direct && members?.length === 1) {
270
+ if (members[0].user?.givenName && members[0]?.user?.familyName) {
271
+ return `${members[0].user?.givenName} ${members[0].user?.familyName}`;
272
+ }
273
+ return members[0].user?.givenName || members[0].user?.familyName || 'Direct Message';
274
+ }
275
+
276
+ return title || 'Channel';
277
+ }, [channels, pathChannelId, currentUser]);
278
+
279
+ // Effects
280
+ useEffect(() => {
281
+ applyFooterStyles();
282
+
283
+ // Optimistic refetch with cache update
284
+ const timeout = setTimeout(() => {
285
+ getChannelsRefetch?.({
286
+ role: channelRole,
287
+ criteria: orgName
288
+ ? { ...channelFilters, orgName: channelFilters?.orgName || orgName || '' }
289
+ : channelFilters,
290
+ supportServices: !!supportServices,
291
+ supportServiceCriteria: { type: RoomType.Service },
292
+ });
293
+ }, 0);
294
+ return () => clearTimeout(timeout);
295
+ }, [channelRole, channelFilters, supportServices, getChannelsRefetch]);
296
+
297
+ // Optimistic navigation with cache updates
298
+ const handleSelectChannel = useCallback(
299
+ async (channelId: string, pId: string | null = null) => {
300
+ // Optimistic UI update
301
+ const mainPath = orgName
302
+ ? pId
303
+ ? `/o/${orgName}/ai-messenger/${channelId}/${pId}`
304
+ : `/o/${orgName}/ai-messenger/${channelId}`
305
+ : pId
306
+ ? `/inbox/${channelId}/${pId}`
307
+ : `/inbox/${channelId}`;
308
+ const basePath = pathPrefix ? `${pathPrefix}${mainPath}` : mainPath;
309
+
310
+ const searchParams = new URLSearchParams();
311
+ // if (channelRole) searchParams.set('channelRole', channelRole);
312
+ // if (orgName) searchParams.set('orgName', orgName);
313
+
314
+ const newPath = searchParams.toString() ? `${basePath}?${searchParams.toString()}` : basePath;
315
+ navigate(newPath, { replace: true });
316
+
317
+ // Optimistically update Apollo cache for immediate UI feedback
318
+ try {
319
+ apolloClient.writeQuery({
320
+ query: MessagesDocument,
321
+ variables: {
322
+ channelId: channelId.toString(),
323
+ parentId: null,
324
+ limit: MESSAGES_PER_PAGE,
325
+ },
326
+ data: {
327
+ messages: {
328
+ __typename: 'Messages',
329
+ data: [],
330
+ totalCount: 0,
331
+ messagesRefId: channelId,
332
+ },
333
+ },
334
+ });
335
+ } catch (error) {
336
+ // Cache write might fail if query hasn't been executed yet, that's OK
337
+ console.debug('Cache write failed (expected on first load):', error);
338
+ }
339
+ },
340
+ [navigate, apolloClient, orgName, channelRole, pathPrefix],
341
+ );
342
+
343
+ const detailSidebarOptions = useMemo(
344
+ () => ({
345
+ isMobileView,
346
+ isSmallTabletView,
347
+ isTabletView,
348
+ isDesktopView,
349
+ isLargeDesktopView,
350
+ isSmallScreen,
351
+ setMobilePreviewCTAText: (v: string | ReactNode) =>
352
+ localDispatch({ payload: { mobilePreviewCTAText: v }, type: 'update' }),
353
+ setMobilePreviewText: (v: string | ReactNode) =>
354
+ localDispatch({ payload: { mobilePreviewText: v }, type: 'update' }),
355
+ setMobilePreviewVisibility: (v: boolean) =>
356
+ localDispatch({ payload: { mobilePreviewVisibility: v }, type: 'update' }),
357
+ }),
358
+ [isMobileView, isSmallTabletView, isTabletView, isDesktopView, isLargeDesktopView, isSmallScreen],
359
+ );
360
+
361
+ return (
362
+ <div
363
+ className="border-t border-gray-300 flex overflow-hidden"
364
+ style={{
365
+ height: `${windowHeight}px`,
366
+ maxHeight: '100vh',
367
+ }}
368
+ >
369
+ {/* Left Sidebar - Responsive Design */}
370
+ <div
371
+ className={`
372
+ flex-shrink-0 bg-gray-50 border-r border-gray-300 overflow-hidden transition-all duration-300 ease-in-out
373
+ ${isMobileView && pathChannelId ? 'hidden' : ''}
374
+ `}
375
+ style={{
376
+ width:
377
+ isMobileView && !pathChannelId
378
+ ? '100%'
379
+ : isMobileView && pathChannelId
380
+ ? '0px'
381
+ : isSmallTabletView
382
+ ? `${Math.min(288, windowWidth * 0.35)}px` // w-72 or 35% of window
383
+ : isTabletView
384
+ ? `${Math.min(320, windowWidth * 0.3)}px` // w-80 or 30% of window
385
+ : isLargeDesktopView
386
+ ? `${Math.min(384, windowWidth * 0.25)}px` // w-96 or 25% of window
387
+ : `${Math.min(320, windowWidth * 0.28)}px`, // w-80 or 28% of window
388
+ height: `${windowHeight}px`,
389
+ maxHeight: '100vh',
390
+ }}
391
+ >
392
+ <LeftSidebar
393
+ currentUser={currentUser}
394
+ userChannels={stableChannels}
395
+ userChannelsLoading={userChannelsLoading}
396
+ users={users}
397
+ handleSelectChannel={handleSelectChannel}
398
+ selectedChannelId={pathChannelId}
399
+ channelToTop={0}
400
+ getChannelsRefetch={getChannelsRefetch}
401
+ role={channelRole}
402
+ messagesQuery={data?.[1]}
403
+ windowHeight={windowHeight}
404
+ windowWidth={windowWidth}
405
+ />
406
+ </div>
407
+
408
+ {/* Main Content Area - Responsive */}
409
+ <div
410
+ className={`
411
+ flex-1 min-w-0 flex flex-col overflow-hidden transition-all duration-300 ease-in-out
412
+ ${isMobileView && !pathChannelId ? 'hidden' : 'flex'}
413
+ `}
414
+ style={{
415
+ minWidth: isSmallScreen ? '300px' : isDesktopView ? '500px' : '400px',
416
+ width: 'auto',
417
+ height: `${windowHeight}px`,
418
+ maxHeight: '100vh',
419
+ }}
420
+ >
421
+ {pathChannelId ? (
422
+ <ContentComponent
423
+ channelId={pathChannelId}
424
+ postId={pathPostId}
425
+ channelRole={channelRole}
426
+ pathPrefix={props.pathPrefix}
427
+ isMobileView={isMobileView}
428
+ isSmallTabletView={isSmallTabletView}
429
+ isTabletView={isTabletView}
430
+ isDesktopView={isDesktopView}
431
+ isLargeDesktopView={isLargeDesktopView}
432
+ isSmallScreen={isSmallScreen}
433
+ windowWidth={windowWidth}
434
+ windowHeight={windowHeight}
435
+ mobilePreviewState={mobilePreviewState}
436
+ detailSidebarOptions={detailSidebarOptions}
437
+ isBottomDrawerOpen={isBottomDrawerOpen}
438
+ setBottomDrawer={setBottomDrawer}
439
+ channelName={channelName}
440
+ loaderdata={data}
441
+ />
442
+ ) : (
443
+ <EmptyState />
444
+ )}
445
+ </div>
446
+
447
+ {/* Right Sidebar - Desktop Only */}
448
+ {pathChannelId && data?.[1] && isDesktopView && (
449
+ <RightSidebarContent
450
+ MessagesLoaderQuery={data?.[1]}
451
+ selectedPost={null}
452
+ detailSidebarOptions={detailSidebarOptions}
453
+ windowWidth={windowWidth}
454
+ windowHeight={windowHeight}
455
+ />
456
+ )}
457
+ </div>
458
+ );
459
+ };
460
+
461
+ const HeaderWithTabs = React.memo((props: any) => {
462
+ const { channelName, isMobileView, isSmallTabletView, isSmallScreen, mobilePreviewState, setBottomDrawer } = props;
463
+
464
+ return (
465
+ <div
466
+ className={`border-b border-gray-200 bg-white flex-shrink-0 z-10 ${
467
+ isSmallScreen ? 'px-3 py-3' : 'px-4 sm:px-6 py-4'
468
+ }`}
469
+ >
470
+ <div className="flex items-center justify-between">
471
+ <div className="flex items-center space-x-2 min-w-0 flex-1">
472
+ {/* Mobile/Small Screen Back Button */}
473
+ {(isMobileView || isSmallTabletView) && (
474
+ <button
475
+ className="p-2 hover:bg-gray-100 rounded-full transition-colors flex-shrink-0"
476
+ onClick={() => window.history.back()}
477
+ aria-label="Go back"
478
+ >
479
+ <svg
480
+ className="w-5 h-5 text-gray-600"
481
+ fill="none"
482
+ stroke="currentColor"
483
+ viewBox="0 0 24 24"
484
+ >
485
+ <path
486
+ strokeLinecap="round"
487
+ strokeLinejoin="round"
488
+ strokeWidth={2}
489
+ d="M15 19l-7-7 7-7"
490
+ />
491
+ </svg>
492
+ </button>
493
+ )}
494
+ <h2 className={`font-semibold text-gray-800 truncate ${isSmallScreen ? 'text-base' : 'text-lg'}`}>
495
+ {channelName}
496
+ </h2>
497
+ </div>
498
+
499
+ {/* Mobile Preview Button */}
500
+ {(isMobileView || isSmallTabletView) && mobilePreviewState?.mobilePreviewVisibility && (
501
+ <button
502
+ className="text-sm px-3 py-1 bg-teal-500 hover:bg-teal-600 text-white rounded-md transition-colors flex-shrink-0"
503
+ onClick={() => setBottomDrawer(true)}
504
+ >
505
+ {mobilePreviewState?.mobilePreviewCTAText}
506
+ </button>
507
+ )}
508
+ </div>
509
+ </div>
510
+ );
511
+ });
512
+
513
+ const ContentComponent = React.memo((props: any) => {
514
+ const {
515
+ channelId,
516
+ channelRole,
517
+ pathPrefix,
518
+ postId,
519
+ isMobileView,
520
+ isSmallTabletView,
521
+ isTabletView,
522
+ isDesktopView,
523
+ isLargeDesktopView,
524
+ isSmallScreen,
525
+ windowWidth,
526
+ windowHeight,
527
+ mobilePreviewState,
528
+ detailSidebarOptions,
529
+ isBottomDrawerOpen,
530
+ setBottomDrawer,
531
+ channelName,
532
+ loaderdata,
533
+ } = props;
534
+
535
+ const ViewChannelDetailLoaderQuery = loaderdata?.[2];
536
+ const MessagesLoaderQuery = loaderdata?.[1];
537
+
538
+ const [selectedPost, setSelectedPost] = React.useState(null);
539
+ const { data: channelData, loading: channelLoading } = ViewChannelDetailLoaderQuery || {};
540
+
541
+ const onMessageClick = useCallback((msg: any) => {
542
+ setSelectedPost(msg);
543
+ }, []);
544
+
545
+ const channelsDetail = useMemo(() => {
546
+ return channelData?.viewChannelDetail || null;
547
+ }, [channelData]);
548
+
549
+ return (
550
+ <div className="flex overflow-hidden" style={{ height: `${windowHeight}px`, maxHeight: '100vh' }}>
551
+ {/* Main Chat Content */}
552
+ <div className="flex-1 flex flex-col min-w-0 overflow-hidden">
553
+ {/* Channel Header */}
554
+ {channelId && (
555
+ <HeaderWithTabs
556
+ channelName={channelName}
557
+ isMobileView={isMobileView}
558
+ isSmallTabletView={isSmallTabletView}
559
+ isSmallScreen={isSmallScreen}
560
+ mobilePreviewState={mobilePreviewState}
561
+ setBottomDrawer={setBottomDrawer}
562
+ loaderdata={loaderdata}
563
+ />
564
+ )}
565
+
566
+ {/* Mobile Preview */}
567
+ {(isMobileView || isSmallTabletView) && channelId && mobilePreviewState?.mobilePreviewVisibility && (
568
+ <div className={`mt-4 ${isSmallScreen ? 'mx-3' : 'mx-4'}`}>
569
+ <div className="mb-2">
570
+ <div className="w-full flex justify-between items-center gap-2 mb-[5px]">
571
+ <span className="truncate flex-1 text-sm">{mobilePreviewState?.mobilePreviewText}</span>
572
+ <button
573
+ className="text-sm px-3 py-2 bg-teal-500 hover:bg-teal-600 text-white rounded-md transition-colors flex-shrink-0"
574
+ onClick={() => setBottomDrawer(true)}
575
+ >
576
+ {mobilePreviewState?.mobilePreviewCTAText}
577
+ </button>
578
+ </div>
579
+ </div>
580
+ <hr className="border-gray-200" />
581
+ </div>
582
+ )}
583
+
584
+ {/* Content based on postId */}
585
+ <div className="flex-1 flex flex-col min-h-0 overflow-hidden">
586
+ {channelId && (
587
+ <>
588
+ {postId ? (
589
+ postId === '1' ? (
590
+ <ThreadsInbox
591
+ channelId={channelId}
592
+ role={channelRole}
593
+ pathPrefix={pathPrefix}
594
+ setChannelId={() => {}}
595
+ setPostId={() => {}}
596
+ setGoBack={() => {}}
597
+ />
598
+ ) : (
599
+ <ThreadMessagesInbox
600
+ channelId={channelId}
601
+ postId={postId}
602
+ role={channelRole}
603
+ goBack={false}
604
+ pathPrefix={pathPrefix}
605
+ setPostId={() => {}}
606
+ setChannelId={() => {}}
607
+ onMessageClick={onMessageClick}
608
+ />
609
+ )
610
+ ) : (
611
+ <MessagesComponent
612
+ channelId={channelId}
613
+ MessagesLoaderQuery={MessagesLoaderQuery}
614
+ channelsDetail={channelsDetail}
615
+ channelLoading={channelLoading}
616
+ onMessageClick={onMessageClick}
617
+ isSmallScreen={isSmallScreen}
618
+ isDesktopView={isDesktopView}
619
+ windowHeight={windowHeight}
620
+ windowWidth={windowWidth}
621
+ />
622
+ )}
623
+ </>
624
+ )}
625
+ </div>
626
+ </div>
627
+
628
+ {/* Mobile/Small Screen Drawer */}
629
+ {(isMobileView || isSmallTabletView) && (
630
+ <Drawer
631
+ isOpen={isBottomDrawerOpen}
632
+ onClose={() => setBottomDrawer(false)}
633
+ title={mobilePreviewState.mobilePreviewText as string}
634
+ >
635
+ <RightSidebarWrapper
636
+ MessagesLoaderQuery={MessagesLoaderQuery}
637
+ selectedPost={selectedPost}
638
+ detailSidebarOptions={detailSidebarOptions}
639
+ />
640
+ </Drawer>
641
+ )}
642
+ </div>
643
+ );
644
+ });
645
+
646
+ const RightSidebarWrapper = React.memo(({ MessagesLoaderQuery, selectedPost, detailSidebarOptions }: any) => {
647
+ const { data } = MessagesLoaderQuery || {};
648
+ const { activeTab, setActiveTab } = useContext(TabContext);
649
+
650
+ const sortedMessages = useMemo(() => {
651
+ const messages = data?.messages?.data || [];
652
+ return orderBy(uniqBy(messages, 'id'), ['createdAt'], ['asc']);
653
+ }, [data?.messages?.data]);
654
+
655
+ const handleRefreshSandbox = useCallback(() => {
656
+ console.log('Refreshing sandbox...');
657
+ }, []);
658
+
659
+ if (!sortedMessages.length) return null;
660
+
661
+ return (
662
+ <div className="h-full flex flex-col overflow-hidden bg-white">
663
+ {/* Header with tabs and refresh icon */}
664
+ <div className="flex-shrink-0 border-b border-gray-200">
665
+ <div className="flex items-center justify-between px-4 py-3">
666
+ <div className="flex items-center space-x-1">
667
+ <button
668
+ onClick={() => setActiveTab('design')}
669
+ className={`flex items-center space-x-2 px-3 py-2 text-sm font-medium rounded-lg transition-colors ${
670
+ activeTab === 'design'
671
+ ? 'bg-blue-500 text-white'
672
+ : 'text-gray-600 hover:text-gray-900 hover:bg-gray-50'
673
+ }`}
674
+ >
675
+ <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
676
+ <path
677
+ strokeLinecap="round"
678
+ strokeLinejoin="round"
679
+ strokeWidth={2}
680
+ d="M4 5a1 1 0 011-1h14a1 1 0 011 1v2a1 1 0 01-1 1H5a1 1 0 01-1-1V5zM4 13a1 1 0 011-1h6a1 1 0 011 1v6a1 1 0 01-1 1H5a1 1 0 01-1-1v-6zM16 13a1 1 0 011-1h2a1 1 0 011 1v6a1 1 0 01-1 1h-2a1 1 0 01-1-1v-6z"
681
+ />
682
+ </svg>
683
+ <span>Design</span>
684
+ </button>
685
+ <button
686
+ onClick={() => setActiveTab('interact')}
687
+ className={`flex items-center space-x-2 px-3 py-2 text-sm font-medium rounded-lg transition-colors ${
688
+ activeTab === 'interact'
689
+ ? 'bg-blue-500 text-white'
690
+ : 'text-gray-600 hover:text-gray-900 hover:bg-gray-50'
691
+ }`}
692
+ >
693
+ <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
694
+ <path
695
+ strokeLinecap="round"
696
+ strokeLinejoin="round"
697
+ strokeWidth={2}
698
+ d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"
699
+ />
700
+ <path
701
+ strokeLinecap="round"
702
+ strokeLinejoin="round"
703
+ strokeWidth={2}
704
+ d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"
705
+ />
706
+ </svg>
707
+ <span>Interact</span>
708
+ </button>
709
+ <button
710
+ onClick={() => setActiveTab('code')}
711
+ className={`flex items-center space-x-2 px-3 py-2 text-sm font-medium rounded-lg transition-colors ${
712
+ activeTab === 'code'
713
+ ? 'bg-blue-500 text-white'
714
+ : 'text-gray-600 hover:text-gray-900 hover:bg-gray-50'
715
+ }`}
716
+ >
717
+ <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
718
+ <path
719
+ strokeLinecap="round"
720
+ strokeLinejoin="round"
721
+ strokeWidth={2}
722
+ d="M10 20l4-16m4 4l4 4-4 4M6 16l-4-4 4-4"
723
+ />
724
+ </svg>
725
+ <span>Code</span>
726
+ </button>
727
+ </div>
728
+
729
+ {/* Refresh icon */}
730
+ <button
731
+ onClick={handleRefreshSandbox}
732
+ className="p-2 text-gray-600 hover:text-gray-900 hover:bg-gray-50 rounded-lg transition-colors"
733
+ title="Refresh Sandbox"
734
+ >
735
+ <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
736
+ <path
737
+ strokeLinecap="round"
738
+ strokeLinejoin="round"
739
+ strokeWidth={2}
740
+ d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"
741
+ />
742
+ </svg>
743
+ </button>
744
+ </div>
745
+ </div>
746
+
747
+ {/* Content Area */}
748
+ <div className="flex-1 overflow-hidden">
749
+ {activeTab === 'design' ? (
750
+ <div className="h-full flex items-center justify-center bg-gray-50">
751
+ <div className="text-center">
752
+ {/* Next.js Logo */}
753
+ <div className="mb-8">
754
+ <svg className="w-32 h-16 mx-auto text-black" viewBox="0 0 394 80" fill="currentColor">
755
+ <path d="M262 0h68.5v12.7h-27.2v66.6h-13.6V12.7H262V0ZM149 0v12.7H94v20.4h44.3v12.6H94v21h55v12.6H80.5V0h68.4zm34.3 0h-17.8l63.8 79.4h17.9l-32-39.7 32-39.7h-17.9l-23 28.6-23-28.6zm18.3 56.7-9-11-27.1 33.7h17.8l18.3-22.7z" />
756
+ <path d="M81 79.3 17 0H0v79.3h13.6V17l50.2 62.3H81Zm252.6-.4c-1 0-1.8-.4-2.5-1s-1.1-1.6-1.1-2.6.3-1.8 1-2.5 1.6-1 2.6-1 1.8.3 2.5 1a3.4 3.4 0 0 1 .6 4.3 3.7 3.7 0 0 1-3 1.8zm23.2-33.5h6v23.3c0 2.1-.4 4-1.3 5.5a9.1 9.1 0 0 1-3.8 3.5c-1.6.8-3.5 1.3-5.7 1.3-2 0-3.7-.4-5.3-1s-2.8-1.8-3.7-3.2c-.9-1.3-1.4-3-1.4-5h6c.1.8.3 1.6.7 2.2s1 1.2 1.6 1.5c.7.4 1.5.5 2.4.5 1 0 1.8-.2 2.4-.6a4 4 0 0 0 1.6-1.8c.3-.8.5-1.8.5-3V45.5zm30.9 9.1a4.4 4.4 0 0 0-2-3.3 7.5 7.5 0 0 0-4.3-1.1c-1.3 0-2.4.2-3.3.5-.9.4-1.6 1-2 1.6a3.5 3.5 0 0 0-.3 4c.3.5.7.9 1.3 1.2l1.8 1 2 .5 3.2.8c1.3.3 2.5.7 3.7 1.2a13 13 0 0 1 3.2 1.8 8.1 8.1 0 0 1 3 6.5c0 2-.5 3.7-1.5 5.1a10 10 0 0 1-4.4 3.5c-1.8.8-4.1 1.2-6.8 1.2-2.6 0-4.9-.4-6.8-1.2-2-.8-3.4-2-4.5-3.5a10 10 0 0 1-1.7-5.6h6a5 5 0 0 0 3.5 4.6c1 .4 2.2.6 3.4.6 1.3 0 2.5-.2 3.5-.6 1-.4 1.8-1 2.4-1.7a4 4 0 0 0 .8-2.4c0-.9-.2-1.6-.7-2.2a11 11 0 0 0-2.1-1.4l-3.2-1-3.8-1c-2.8-.7-5-1.7-6.6-3.2a7.2 7.2 0 0 1-2.4-5.7 8 8 0 0 1 1.7-5 10 10 0 0 1 4.3-3.5c2-.8 4-1.2 6.4-1.2 2.3 0 4.4.4 6.2 1.2 1.8.8 3.2 2 4.2 3.4 1 1.4 1.5 3 1.5 5h-5.8z" />
757
+ </svg>
758
+ </div>
759
+
760
+ <div className="space-y-4 text-gray-600">
761
+ <h3 className="text-lg font-semibold text-gray-900">Design View</h3>
762
+ <p className="font-mono text-sm bg-gray-100 px-3 py-1 rounded">
763
+ Design components and UI
764
+ </p>
765
+ <p>Customize and preview your design changes.</p>
766
+ </div>
767
+
768
+ <div className="mt-8 space-y-4">
769
+ <button className="bg-black text-white px-6 py-3 rounded-full hover:bg-gray-800 transition-colors flex items-center space-x-2 mx-auto">
770
+ <svg className="w-4 h-4" fill="currentColor" viewBox="0 0 24 24">
771
+ <path d="M12 2L2 7v10c0 5.55 3.84 9.739 9 11 5.16-1.261 9-5.45 9-11V7l-10-5z" />
772
+ </svg>
773
+ <span>Design now</span>
774
+ </button>
775
+ <p className="text-sm text-gray-500 underline cursor-pointer hover:text-gray-700">
776
+ View design docs
777
+ </p>
778
+ </div>
779
+ </div>
780
+ </div>
781
+ ) : activeTab === 'interact' ? (
782
+ <div className="h-full flex items-center justify-center bg-blue-50">
783
+ <div className="text-center">
784
+ {/* Interact Icon */}
785
+ <div className="mb-8">
786
+ <svg
787
+ className="w-32 h-32 mx-auto text-blue-500"
788
+ fill="none"
789
+ stroke="currentColor"
790
+ viewBox="0 0 24 24"
791
+ >
792
+ <path
793
+ strokeLinecap="round"
794
+ strokeLinejoin="round"
795
+ strokeWidth={1}
796
+ d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"
797
+ />
798
+ <path
799
+ strokeLinecap="round"
800
+ strokeLinejoin="round"
801
+ strokeWidth={1}
802
+ d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"
803
+ />
804
+ </svg>
805
+ </div>
806
+
807
+ <div className="space-y-4 text-gray-600">
808
+ <h3 className="text-lg font-semibold text-gray-900">Interactive Mode</h3>
809
+ <p className="font-mono text-sm bg-blue-100 px-3 py-1 rounded">
810
+ Live interaction and testing
811
+ </p>
812
+ <p>Test and interact with your components in real-time.</p>
813
+ </div>
814
+
815
+ <div className="mt-8 space-y-4">
816
+ <button className="bg-blue-500 text-white px-6 py-3 rounded-full hover:bg-blue-600 transition-colors flex items-center space-x-2 mx-auto">
817
+ <svg className="w-4 h-4" fill="currentColor" viewBox="0 0 24 24">
818
+ <path d="M8 5v14l11-7z" />
819
+ </svg>
820
+ <span>Start Interacting</span>
821
+ </button>
822
+ <p className="text-sm text-gray-500 underline cursor-pointer hover:text-gray-700">
823
+ Learn about interactions
824
+ </p>
825
+ </div>
826
+ </div>
827
+ </div>
828
+ ) : (
829
+ <div className="h-full bg-gray-900 text-gray-300 p-4 overflow-auto">
830
+ <div className="font-mono text-sm">
831
+ <div className="mb-4">
832
+ <div className="text-green-400">// app/page.tsx</div>
833
+ </div>
834
+ <div className="space-y-2">
835
+ <div>
836
+ <span className="text-purple-400">export</span>{' '}
837
+ <span className="text-purple-400">default</span>{' '}
838
+ <span className="text-blue-400">function</span>{' '}
839
+ <span className="text-yellow-400">Home</span>() {'{'}
840
+ </div>
841
+ <div className="ml-4">
842
+ <span className="text-purple-400">return</span> (
843
+ </div>
844
+ <div className="ml-8">
845
+ {'<'}
846
+ <span className="text-red-400">main</span>{' '}
847
+ <span className="text-green-400">className</span>=
848
+ <span className="text-yellow-400">
849
+ "flex min-h-screen flex-col items-center justify-between p-24"
850
+ </span>
851
+ {'>'}
852
+ </div>
853
+ <div className="ml-12">
854
+ {'<'}
855
+ <span className="text-red-400">div</span>{' '}
856
+ <span className="text-green-400">className</span>=
857
+ <span className="text-yellow-400">
858
+ "z-10 max-w-5xl w-full items-center justify-between font-mono text-sm lg:flex"
859
+ </span>
860
+ {'>'}
861
+ </div>
862
+ <div className="ml-16">
863
+ {'<'}
864
+ <span className="text-red-400">p</span>{' '}
865
+ <span className="text-green-400">className</span>=
866
+ <span className="text-yellow-400">
867
+ "fixed left-0 top-0 flex w-full justify-center border-b border-gray-300
868
+ bg-gradient-to-b from-zinc-200 pb-6 pt-8 backdrop-blur-2xl
869
+ dark:border-neutral-800 dark:bg-zinc-800/30 dark:from-inherit lg:static
870
+ lg:w-auto lg:rounded-xl lg:border lg:bg-gray-200 lg:p-4 lg:dark:bg-zinc-800/30"
871
+ </span>
872
+ {'>'}
873
+ </div>
874
+ <div className="ml-20 text-gray-400">Get started by editing&nbsp;</div>
875
+ <div className="ml-20">
876
+ {'<'}
877
+ <span className="text-red-400">code</span>{' '}
878
+ <span className="text-green-400">className</span>=
879
+ <span className="text-yellow-400">"font-mono font-bold"</span>
880
+ {'>'}app/page.tsx{'</'}
881
+ <span className="text-red-400">code</span>
882
+ {'>'}
883
+ </div>
884
+ <div className="ml-16">
885
+ {'</'}
886
+ <span className="text-red-400">p</span>
887
+ {'>'}
888
+ </div>
889
+ <div className="ml-12">
890
+ {'</'}
891
+ <span className="text-red-400">div</span>
892
+ {'>'}
893
+ </div>
894
+ <div className="ml-8">
895
+ {'</'}
896
+ <span className="text-red-400">main</span>
897
+ {'>'}
898
+ </div>
899
+ <div className="ml-4">);</div>
900
+ <div>{'}'}</div>
901
+ </div>
902
+ </div>
903
+ </div>
904
+ )}
905
+ </div>
906
+ </div>
907
+ );
908
+ });
909
+
910
+ const RightSidebarContent = React.memo(
911
+ ({ MessagesLoaderQuery, selectedPost, detailSidebarOptions, windowWidth, windowHeight }: any) => {
912
+ const { data } = MessagesLoaderQuery || {};
913
+
914
+ const sortedMessages = useMemo(() => {
915
+ const messages = data?.messages?.data || [];
916
+ return orderBy(uniqBy(messages, 'id'), ['createdAt'], ['asc']);
917
+ }, [data?.messages?.data]);
918
+
919
+ if (!sortedMessages.length) return null;
920
+
921
+ return (
922
+ <div
923
+ className="border-l border-gray-200 bg-white flex-shrink-0 overflow-hidden"
924
+ style={{
925
+ width: `${windowWidth * 0.35}px`, // 35% of window width
926
+ height: `${windowHeight}px`,
927
+ maxHeight: '100vh',
928
+ }}
929
+ >
930
+ <RightSidebarWrapper
931
+ MessagesLoaderQuery={MessagesLoaderQuery}
932
+ selectedPost={selectedPost}
933
+ detailSidebarOptions={detailSidebarOptions}
934
+ />
935
+ </div>
936
+ );
937
+ },
938
+ );
939
+
940
+ const MessagesComponent = React.memo((props: any) => {
941
+ const {
942
+ channelId,
943
+ MessagesLoaderQuery,
944
+ channelsDetail,
945
+ channelLoading,
946
+ onMessageClick,
947
+ isSmallScreen,
948
+ isDesktopView,
949
+ windowHeight = 768,
950
+ windowWidth = 1024,
951
+ } = props;
952
+
953
+ const messageRootListRef = useRef(null);
954
+ const messageListRef = useRef(null);
955
+ const apolloClient = useApolloClient();
956
+ const [isLoadingOlder, setIsLoadingOlder] = React.useState(false);
957
+ const isLoadingOlderRef = useRef(false);
958
+ const scrollTimeoutRef = useRef(null);
959
+
960
+ const auth = useSelector(userSelector);
961
+ const { startUpload } = useUploadFiles();
962
+ const [sendMsg] = useSendMessagesMutation();
963
+
964
+ const { data, loading: messageLoading, fetchMore: fetchMoreMessages, subscribeToMore } = MessagesLoaderQuery || {};
965
+ // Add dummy messages with modern formatting to showcase the new UI
966
+ const dummyMessages = [
967
+ {
968
+ id: 'dummy-1',
969
+ message: `# Modern Next.js-Style Application
970
+
971
+ I'll help you build a modern Next.js-style application. Let me first examine the current homepage and then completely rebuild it to create a beautiful, modern "next app" experience.`,
972
+ createdAt: new Date(Date.now() + 2000).toISOString(),
973
+ author: {
974
+ id: 'ai-assistant',
975
+ username: 'AI Assistant',
976
+ givenName: 'AI',
977
+ familyName: 'Assistant',
978
+ picture: '/default-avatar.svg',
979
+ },
980
+ files: { data: [], totalCount: 0 },
981
+ },
982
+ {
983
+ id: 'dummy-2',
984
+ message: `## Key Features:
985
+
986
+ - **Professional Navigation** - Clean header with logo and navigation links
987
+ - **Hero Section** - Compelling headline with gradient text effects and code preview
988
+ - **Feature Cards** - Showcase of Next.js capabilities with modern icons
989
+ - **Call-to-Action** - Clear conversion paths for user engagement
990
+ - **Footer** - Comprehensive site navigation and branding
991
+
992
+ ### Design Highlights:
993
+
994
+ - Modern gradient branding (blue to purple to pink)
995
+ - Clean typography with proper hierarchy
996
+ - Responsive grid layouts for all screen sizes
997
+ - Subtle backdrop blur effects and modern cards
998
+ - Smooth scroll behavior and enhanced visual effects
999
+ - Production-ready color palette with proper light/dark mode support`,
1000
+ createdAt: new Date(Date.now() + 3000).toISOString(),
1001
+ author: {
1002
+ id: 'ai-assistant',
1003
+ username: 'AI Assistant',
1004
+ givenName: 'AI',
1005
+ familyName: 'Assistant',
1006
+ picture: '/default-avatar.svg',
1007
+ },
1008
+ files: { data: [], totalCount: 0 },
1009
+ },
1010
+ {
1011
+ id: 'dummy-3',
1012
+ message: `### Technical Implementation:
1013
+
1014
+ Uses existing **shadcn/ui components** (Button, Card, Badge)
1015
+ .`,
1016
+ createdAt: new Date(Date.now() + 4000).toISOString(),
1017
+ author: {
1018
+ id: 'ai-assistant',
1019
+ username: 'AI Assistant',
1020
+ givenName: 'AI',
1021
+ familyName: 'Assistant',
1022
+ picture: '/default-avatar.svg',
1023
+ },
1024
+ files: { data: [], totalCount: 0 },
1025
+ },
1026
+ {
1027
+ id: 'dummy-4',
1028
+ message: `\`\`\`typescript
1029
+ export default function Home() {
1030
+ return (
1031
+ <main className="flex min-h-screen flex-col items-center">
1032
+ <div className="z-10 max-w-5xl w-full items-center">
1033
+ <p className="fixed left-0 top-0 flex w-full justify-center">
1034
+ Get started by editing app/page.tsx
1035
+ </p>
1036
+ </div>
1037
+ </main>
1038
+ );
1039
+ }\`\`\`
1040
+ .`,
1041
+ createdAt: new Date(Date.now() + 4000).toISOString(),
1042
+ author: {
1043
+ id: 'ai-assistant',
1044
+ username: 'AI Assistant',
1045
+ givenName: 'AI',
1046
+ familyName: 'Assistant',
1047
+ picture: '/default-avatar.svg',
1048
+ },
1049
+ files: { data: [], totalCount: 0 },
1050
+ },
1051
+ {
1052
+ id: 'tool-status-1',
1053
+ message: `<div class="px-3 py-2 bg-gray-100 border border-gray-300 rounded-lg text-sm text-gray-700" style="border-radius: 5px !important;">🔧 Running tool</div>`,
1054
+ createdAt: new Date(Date.now() + 5000).toISOString(),
1055
+ author: {
1056
+ id: 'system-tool',
1057
+ username: 'System Tool',
1058
+ givenName: 'System',
1059
+ familyName: 'Tool',
1060
+ picture: '/default-avatar.svg',
1061
+ },
1062
+ files: { data: [], totalCount: 0 },
1063
+ },
1064
+ {
1065
+ id: 'tool-status-2',
1066
+ message: `<div class="px-3 py-2 bg-gray-100 border border-gray-300 rounded-lg text-sm text-gray-700" style="border-radius: 5px !important;">🔧 Running tool</div>`,
1067
+ createdAt: new Date(Date.now() + 5500).toISOString(),
1068
+ author: {
1069
+ id: 'system-tool',
1070
+ username: 'System Tool',
1071
+ givenName: 'System',
1072
+ familyName: 'Tool',
1073
+ picture: '/default-avatar.svg',
1074
+ },
1075
+ files: { data: [], totalCount: 0 },
1076
+ },
1077
+ {
1078
+ id: 'bullet-point-1',
1079
+ message: `<div>
1080
+ <h1 class="text-xl font-bold">Installation process</h1>
1081
+ <ul>
1082
+ <li>Install Node.js</li>
1083
+ <li>Install npm</li>
1084
+ <li>Install React</li>
1085
+ <li>Install Tailwind CSS</li>
1086
+ <li>Install shadcn/ui</li>
1087
+ <li>Install Next.js</li>
1088
+ <li>Install TypeScript</li>
1089
+ <li>Install ESLint</li>
1090
+ <li>Install Prettier</li>
1091
+ </ul> </div>`,
1092
+ createdAt: new Date(Date.now() + 5500).toISOString(),
1093
+ author: {
1094
+ id: 'bullet-tool',
1095
+ username: 'System Tool',
1096
+ givenName: 'System',
1097
+ familyName: 'Tool',
1098
+ picture: '/default-avatar.svg',
1099
+ },
1100
+ files: { data: [], totalCount: 0 },
1101
+ },
1102
+ ];
1103
+
1104
+ console.log('dummyMessages', JSON.stringify(dummyMessages, null, 2));
1105
+
1106
+ // Get messages directly from Apollo cache
1107
+ const messages = useMemo(() => {
1108
+ const messagesData = data?.messages?.data || [];
1109
+ dummyMessages.forEach((msg) => messagesData.push(msg));
1110
+ return orderBy(uniqBy(messagesData, 'id'), ['createdAt'], ['asc']);
1111
+ }, [data?.messages?.data]);
1112
+
1113
+ const totalCount = data?.messages?.totalCount || 0;
1114
+
1115
+ const scrollToBottom = useCallback(() => {
1116
+ if (messageRootListRef?.current) {
1117
+ messageRootListRef.current.scrollTop = messageRootListRef.current.scrollHeight;
1118
+ }
1119
+ }, []);
1120
+
1121
+ // Auto-scroll on new messages (but not when loading older messages)
1122
+ useEffect(() => {
1123
+ if (!isLoadingOlderRef.current) {
1124
+ const timer = setTimeout(() => scrollToBottom(), 100);
1125
+ return () => clearTimeout(timer);
1126
+ }
1127
+ }, [messages.length, scrollToBottom]);
1128
+
1129
+ const onFetchOld = useCallback(
1130
+ async (skip: number) => {
1131
+ if (channelId && fetchMoreMessages && !isLoadingOlder) {
1132
+ try {
1133
+ setIsLoadingOlder(true);
1134
+ isLoadingOlderRef.current = true;
1135
+ // Capture current scroll height before fetching
1136
+ const oldScrollHeight = messageRootListRef?.current?.scrollHeight || 0;
1137
+
1138
+ await fetchMoreMessages({
1139
+ variables: {
1140
+ channelId: channelId.toString(),
1141
+ parentId: null,
1142
+ skip,
1143
+ },
1144
+ updateQuery: (prev, { fetchMoreResult }) => {
1145
+ if (!fetchMoreResult) return prev;
1146
+
1147
+ const newMessages = fetchMoreResult.messages.data;
1148
+ const existingMessages = prev.messages?.data || [];
1149
+
1150
+ return {
1151
+ ...prev,
1152
+ messages: {
1153
+ ...fetchMoreResult.messages,
1154
+ data: uniqBy([...newMessages, ...existingMessages], 'id'),
1155
+ },
1156
+ };
1157
+ },
1158
+ });
1159
+
1160
+ // Maintain scroll position after loading older messages
1161
+ setTimeout(() => {
1162
+ if (messageRootListRef?.current) {
1163
+ const newScrollHeight = messageRootListRef.current.scrollHeight;
1164
+ const scrollDiff = newScrollHeight - oldScrollHeight;
1165
+ // For normal flex layout, maintain position by adjusting scroll offset
1166
+ messageRootListRef.current.scrollTop = scrollDiff;
1167
+ }
1168
+ // Reset the loading flag after position is maintained
1169
+ setTimeout(() => {
1170
+ isLoadingOlderRef.current = false;
1171
+ }, 50);
1172
+ }, 100);
1173
+ } catch (error) {
1174
+ console.error('Error fetching older messages:', error);
1175
+ isLoadingOlderRef.current = false;
1176
+ } finally {
1177
+ setIsLoadingOlder(false);
1178
+ }
1179
+ }
1180
+ },
1181
+ [channelId, fetchMoreMessages, isLoadingOlder],
1182
+ );
1183
+
1184
+ // Scroll to bottom when channel changes
1185
+ useEffect(() => {
1186
+ if (channelId && messages.length > 0) {
1187
+ isLoadingOlderRef.current = false; // Reset flag on channel change
1188
+ const timer = setTimeout(() => scrollToBottom(), 200);
1189
+ return () => clearTimeout(timer);
1190
+ }
1191
+ }, [channelId, scrollToBottom]);
1192
+
1193
+ // Alternative scroll detection for Firefox
1194
+ useEffect(() => {
1195
+ const element = messageRootListRef.current;
1196
+ if (!element) return;
1197
+
1198
+ // Firefox-specific scroll detection using passive listeners
1199
+ const handleScrollEnd = () => {
1200
+ if (!isLoadingOlder && element) {
1201
+ const { scrollTop } = element;
1202
+ const isAtTop = Math.round(scrollTop) <= 30;
1203
+ const hasMoreMessages = totalCount > messages.length;
1204
+
1205
+ if (isAtTop && hasMoreMessages) {
1206
+ console.log('ScrollEnd triggered load more (Firefox):', {
1207
+ scrollTop: Math.round(scrollTop),
1208
+ totalCount,
1209
+ messagesLength: messages.length,
1210
+ });
1211
+ onFetchOld(messages.length);
1212
+ }
1213
+ }
1214
+ };
1215
+
1216
+ // Use scrollend event if available (modern Firefox/Chrome)
1217
+ if ('onscrollend' in element) {
1218
+ element.addEventListener('scrollend', handleScrollEnd, { passive: true });
1219
+ return () => {
1220
+ element.removeEventListener('scrollend', handleScrollEnd);
1221
+ };
1222
+ }
1223
+ }, [totalCount, messages.length, onFetchOld, isLoadingOlder]);
1224
+
1225
+ // Cleanup scroll timeout on unmount
1226
+ useEffect(() => {
1227
+ return () => {
1228
+ if (scrollTimeoutRef.current) {
1229
+ clearTimeout(scrollTimeoutRef.current);
1230
+ }
1231
+ };
1232
+ }, []);
1233
+
1234
+ const onMessagesScroll = useCallback(
1235
+ async (e: any) => {
1236
+ // Throttle scroll events for better performance, especially in Firefox
1237
+ if (scrollTimeoutRef.current) {
1238
+ clearTimeout(scrollTimeoutRef.current);
1239
+ }
1240
+
1241
+ scrollTimeoutRef.current = setTimeout(async () => {
1242
+ if (messageRootListRef.current && !isLoadingOlder) {
1243
+ const element = messageRootListRef.current;
1244
+ const { clientHeight, scrollHeight, scrollTop } = element;
1245
+
1246
+ // Firefox-compatible scroll detection
1247
+ // Use Math.ceil to handle Firefox's fractional scrollTop values
1248
+ const isAtTop = Math.ceil(scrollTop) <= 25;
1249
+ const hasMoreMessages = totalCount > messages.length;
1250
+
1251
+ // Additional Firefox-specific check
1252
+ const isFirefox = navigator.userAgent.includes('Firefox');
1253
+ const firefoxAdjustedTop = isFirefox ? Math.round(scrollTop) <= 30 : isAtTop;
1254
+
1255
+ if ((isAtTop || firefoxAdjustedTop) && hasMoreMessages) {
1256
+ console.log('Triggering load more:', {
1257
+ scrollTop: Math.ceil(scrollTop),
1258
+ originalScrollTop: scrollTop,
1259
+ totalCount,
1260
+ messagesLength: messages.length,
1261
+ scrollHeight,
1262
+ clientHeight,
1263
+ browser: isFirefox ? 'Firefox' : 'Other',
1264
+ isAtTop,
1265
+ firefoxAdjustedTop,
1266
+ });
1267
+ await onFetchOld(messages.length);
1268
+ }
1269
+ }
1270
+ }, 100);
1271
+ },
1272
+ [totalCount, messages.length, onFetchOld, isLoadingOlder],
1273
+ );
1274
+
1275
+ // Optimistic message sending with Apollo cache updates
1276
+ const handleSend = useCallback(
1277
+ async (message: string, files: any[] = []) => {
1278
+ // Allow sending if there's either a message or files
1279
+ if ((!message || !message.trim()) && (!files || files.length === 0)) return;
1280
+ if (!channelId) return;
1281
+
1282
+ try {
1283
+ const postId = objectId();
1284
+ const currentDate = new Date();
1285
+
1286
+ const createOptimisticMessage = (files?: any[]) => ({
1287
+ __typename: 'Post' as const,
1288
+ id: postId,
1289
+ message,
1290
+ createdAt: currentDate.toISOString(),
1291
+ updatedAt: currentDate.toISOString(),
1292
+ author: {
1293
+ __typename: 'UserAccount' as const,
1294
+ id: auth?.id,
1295
+ givenName: auth?.profile?.given_name || '',
1296
+ familyName: auth?.profile?.family_name || '',
1297
+ email: auth?.profile?.email || '',
1298
+ username: auth?.profile?.nickname || '',
1299
+ fullName: auth?.profile?.name || '',
1300
+ picture: auth?.profile?.picture || '',
1301
+ alias: [auth?.authUserId ?? ''],
1302
+ tokens: [],
1303
+ },
1304
+ isDelivered: false, // Will be true once confirmed by server
1305
+ isRead: false,
1306
+ type: 'TEXT' as PostTypeEnum,
1307
+ parentId: null,
1308
+ fromServer: false,
1309
+ channel: {
1310
+ __typename: 'Channel' as const,
1311
+ id: channelId,
1312
+ },
1313
+ propsConfiguration: {
1314
+ __typename: 'MachineConfiguration' as const,
1315
+ id: null,
1316
+ resource: '' as any,
1317
+ contents: null,
1318
+ keys: null,
1319
+ target: null,
1320
+ overrides: null,
1321
+ },
1322
+ props: {},
1323
+ files: {
1324
+ __typename: 'FilesInfo' as const,
1325
+ data: files || [],
1326
+ totalCount: files?.length || 0,
1327
+ },
1328
+ replies: {
1329
+ __typename: 'Messages' as const,
1330
+ data: [],
1331
+ totalCount: 0,
1332
+ },
1333
+ });
1334
+
1335
+ const optimisticMessage = createOptimisticMessage(files);
1336
+
1337
+ if (files?.length > 0) {
1338
+ const uploadResponse = await startUpload({
1339
+ file: files,
1340
+ saveUploadedFile: { variables: { postId } },
1341
+ createUploadLink: { variables: { postId } },
1342
+ });
1343
+
1344
+ const uploadedFiles = uploadResponse.data as unknown as IFileInfo[];
1345
+ if (uploadedFiles) {
1346
+ const fileIds = uploadedFiles.map((f: any) => f.id);
1347
+ await sendMsg({
1348
+ variables: { postId, channelId, content: message, files: fileIds },
1349
+ optimisticResponse: {
1350
+ __typename: 'Mutation',
1351
+ sendMessage: createOptimisticMessage(uploadedFiles),
1352
+ },
1353
+ update: (cache, { data: mutationData }) => {
1354
+ if (!mutationData?.sendMessage) return;
1355
+
1356
+ // Update messages cache optimistically
1357
+ const messagesQuery = {
1358
+ query: MessagesDocument,
1359
+ variables: {
1360
+ channelId: channelId.toString(),
1361
+ parentId: null,
1362
+ limit: MESSAGES_PER_PAGE,
1363
+ },
1364
+ };
1365
+
1366
+ try {
1367
+ const existingData = cache.readQuery(messagesQuery) as any;
1368
+ if (existingData?.messages) {
1369
+ cache.writeQuery({
1370
+ ...messagesQuery,
1371
+ data: {
1372
+ messages: {
1373
+ ...existingData.messages,
1374
+ data: [
1375
+ ...(existingData.messages.data || []),
1376
+ mutationData.sendMessage,
1377
+ ],
1378
+ totalCount: (existingData.messages.totalCount || 0) + 1,
1379
+ },
1380
+ },
1381
+ });
1382
+ }
1383
+ } catch (error) {
1384
+ console.debug('Cache update failed (expected on first message):', error);
1385
+ }
1386
+ },
1387
+ });
1388
+ }
1389
+ } else {
1390
+ await sendMsg({
1391
+ variables: { channelId, content: message },
1392
+ optimisticResponse: {
1393
+ __typename: 'Mutation',
1394
+ sendMessage: optimisticMessage,
1395
+ },
1396
+ update: (cache, { data: mutationData }) => {
1397
+ if (!mutationData?.sendMessage) return;
1398
+
1399
+ // Update messages cache optimistically
1400
+ const messagesQuery = {
1401
+ query: MessagesDocument,
1402
+ variables: {
1403
+ channelId: channelId.toString(),
1404
+ parentId: null,
1405
+ limit: MESSAGES_PER_PAGE,
1406
+ },
1407
+ };
1408
+
1409
+ try {
1410
+ const existingData = cache.readQuery(messagesQuery) as any;
1411
+ if (existingData?.messages) {
1412
+ cache.writeQuery({
1413
+ ...messagesQuery,
1414
+ data: {
1415
+ messages: {
1416
+ ...existingData.messages,
1417
+ data: [...(existingData.messages.data || []), mutationData.sendMessage],
1418
+ totalCount: (existingData.messages.totalCount || 0) + 1,
1419
+ },
1420
+ },
1421
+ });
1422
+ }
1423
+ } catch (error) {
1424
+ console.debug('Cache update failed (expected on first message):', error);
1425
+ }
1426
+ },
1427
+ });
1428
+ }
1429
+ } catch (error) {
1430
+ console.error('Error sending message:', error);
1431
+ }
1432
+ },
1433
+ [channelId, auth, startUpload, sendMsg],
1434
+ );
1435
+
1436
+ // Show loading spinner for initial load
1437
+ if ((messageLoading || channelLoading) && messages.length === 0) {
1438
+ return (
1439
+ <div className="flex-1 flex justify-center items-center">
1440
+ <Spinner className="w-12 h-12" />
1441
+ </div>
1442
+ );
1443
+ }
1444
+
1445
+ return (
1446
+ <>
1447
+ <div
1448
+ ref={messageRootListRef}
1449
+ className={`overflow-y-scroll bg-white ${
1450
+ isSmallScreen ? 'p-2 px-3' : isDesktopView ? 'p-6 px-8' : 'p-4 px-6'
1451
+ }`}
1452
+ onScroll={onMessagesScroll}
1453
+ style={{
1454
+ height: `${windowHeight - 140}px`, // Subtract header + input height
1455
+ maxHeight: '100vh',
1456
+ scrollbarWidth: 'thin',
1457
+ scrollbarColor: '#cbd5e0 #f7fafc',
1458
+ overflowY: 'scroll',
1459
+ WebkitOverflowScrolling: 'touch',
1460
+ backgroundAttachment: 'fixed',
1461
+ }}
1462
+ >
1463
+ <div className="min-h-full">
1464
+ {messages.length > 0 ? (
1465
+ <>
1466
+ {/* Loading indicator for older messages at the top */}
1467
+ {isLoadingOlder && (
1468
+ <div className="flex justify-center py-4">
1469
+ <div className="flex items-center space-x-2 text-gray-500">
1470
+ <Spinner className="w-4 h-4" />
1471
+ <span className="text-sm">Loading older messages...</span>
1472
+ </div>
1473
+ </div>
1474
+ )}
1475
+ <MessagesBuilderUi
1476
+ innerRef={messageListRef}
1477
+ channelId={channelId}
1478
+ currentUser={auth}
1479
+ channelMessages={messages}
1480
+ totalCount={totalCount}
1481
+ onMessageClick={onMessageClick}
1482
+ isDesktopView={isDesktopView || false}
1483
+ isSmallScreen={isSmallScreen || false}
1484
+ />
1485
+ <SubscriptionHandler
1486
+ subscribeToMore={subscribeToMore}
1487
+ document={CHAT_MESSAGE_ADDED}
1488
+ variables={{ channelId: channelId.toString() }}
1489
+ enabled={!!channelId && !!subscribeToMore}
1490
+ updateQuery={(prev: any, { subscriptionData }: any) => {
1491
+ console.log('Subscription updateQuery called:', { prev, subscriptionData });
1492
+ if (!subscriptionData.data) {
1493
+ console.log('No subscription data, returning prev');
1494
+ return prev;
1495
+ }
1496
+ const newMessage = subscriptionData.data.chatMessageAdded;
1497
+ console.log('New message received via subscription:', newMessage);
1498
+
1499
+ return {
1500
+ ...prev,
1501
+ messages: {
1502
+ ...prev?.messages,
1503
+ data: uniqBy([...(prev?.messages?.data || []), newMessage], 'id'),
1504
+ totalCount: (prev?.messages?.totalCount || 0) + 1,
1505
+ },
1506
+ };
1507
+ }}
1508
+ onError={(error) => {
1509
+ console.error('Subscription error:', error);
1510
+ }}
1511
+ />
1512
+ </>
1513
+ ) : (
1514
+ <div className="flex items-center justify-center text-gray-500 min-h-96">
1515
+ <div className="text-center max-w-sm mx-auto px-4">
1516
+ <div className="text-6xl mb-4 opacity-50">💬</div>
1517
+ <h3 className="text-lg font-semibold text-gray-600 mb-2">No messages yet</h3>
1518
+ <p className="text-sm text-gray-500">
1519
+ Start the conversation by sending a message below!
1520
+ </p>
1521
+ </div>
1522
+ </div>
1523
+ )}
1524
+ </div>
1525
+ </div>
1526
+ <div className="flex-shrink-0 border-t border-gray-200 bg-white">
1527
+ <InputComponent channelId={channelId} placeholder="Message" />
1528
+ </div>
1529
+ </>
1530
+ );
1531
+ });
1532
+
1533
+ // Display names for debugging
1534
+ InboxTemplate1.displayName = 'Inbox';
1535
+ InboxTemplate1Internal.displayName = 'InboxTemplate1Internal';
1536
+ HeaderWithTabs.displayName = 'HeaderWithTabs';
1537
+ ContentComponent.displayName = 'ContentComponent';
1538
+ MessagesComponent.displayName = 'MessagesComponent';
1539
+ RightSidebarWrapper.displayName = 'RightSidebarWrapper';
1540
+ RightSidebarContent.displayName = 'RightSidebarContent';
1541
+
1542
+ export default React.memo(InboxTemplate1);