@tuturuuu/ui 0.24.0 → 0.25.2

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.
@@ -28,6 +28,7 @@ interface MessageListProps {
28
28
  onOpenAttachment?: (attachment: ChatAttachment) => void;
29
29
  onToggleReaction?: (messageId: string, emoji: string) => void;
30
30
  readOnly?: boolean;
31
+ typingLabel?: string;
31
32
  wsId: string;
32
33
  }
33
34
 
@@ -48,6 +49,7 @@ export function MessageList({
48
49
  onOpenAttachment,
49
50
  onToggleReaction,
50
51
  readOnly,
52
+ typingLabel,
51
53
  wsId,
52
54
  }: MessageListProps) {
53
55
  const t = useTranslations('chat');
@@ -210,7 +212,7 @@ export function MessageList({
210
212
  </Button>
211
213
  </div>
212
214
  ) : item.type === 'typing' ? (
213
- <AgentTypingIndicator />
215
+ <AgentTypingIndicator label={typingLabel} />
214
216
  ) : (
215
217
  <MessageRow
216
218
  currentUserId={currentUserId}
@@ -270,7 +272,7 @@ function MessageRow({
270
272
  );
271
273
  }
272
274
 
273
- function AgentTypingIndicator() {
275
+ function AgentTypingIndicator({ label }: { label?: string }) {
274
276
  const t = useTranslations('chat');
275
277
 
276
278
  return (
@@ -279,7 +281,7 @@ function AgentTypingIndicator() {
279
281
  <LoaderCircle className="size-4 animate-spin" />
280
282
  </div>
281
283
  <div className="rounded-md border bg-muted/40 px-3 py-2 text-muted-foreground text-sm">
282
- <span className="sr-only">{t('agent_typing')}</span>
284
+ <span className="sr-only">{label ?? t('agent_typing')}</span>
283
285
  <span aria-hidden="true" className="flex items-center gap-1">
284
286
  <span className="size-1.5 animate-pulse rounded-full bg-current" />
285
287
  <span className="size-1.5 animate-pulse rounded-full bg-current delay-150" />
@@ -8,7 +8,7 @@ type RouterLike = {
8
8
  replace: (href: string, options?: { scroll?: boolean }) => void;
9
9
  };
10
10
 
11
- export type ChatDetailsTarget = 'agent' | null;
11
+ export type ChatDetailsTarget = 'agent' | 'external' | null;
12
12
 
13
13
  export function buildChatSelectionHref({
14
14
  conversationId,
@@ -8,6 +8,13 @@ import type {
8
8
  export type ChatConversationScope = 'external' | 'personal' | 'workspaces';
9
9
  export type ChatConversationArchiveFilter = 'active' | 'all' | 'archived';
10
10
 
11
+ export type ChatConversationDeliveryState =
12
+ | 'deleted'
13
+ | 'failed'
14
+ | 'seen'
15
+ | 'sending'
16
+ | 'sent';
17
+
11
18
  export const DEFAULT_CHAT_SCOPE: ChatConversationScope = 'personal';
12
19
  export const CHAT_CONVERSATION_TYPE_FILTERS = [
13
20
  'direct',
@@ -87,6 +94,40 @@ export function getChatConversationScope(
87
94
  return 'workspaces';
88
95
  }
89
96
 
97
+ export function getChatConversationQueueDetails(
98
+ conversation: Pick<
99
+ ChatConversation,
100
+ 'latestMessage' | 'metadata' | 'updatedAt'
101
+ >
102
+ ) {
103
+ const latestMessage = conversation.latestMessage;
104
+ const phone = readNonEmptyString(conversation.metadata.phone);
105
+
106
+ return {
107
+ deliveryState: latestMessage
108
+ ? getChatConversationDeliveryState(latestMessage)
109
+ : null,
110
+ phone,
111
+ preview: latestMessage?.deletedAt
112
+ ? null
113
+ : (readNonEmptyString(latestMessage?.content) ??
114
+ readNonEmptyString(latestMessage?.attachments[0]?.filename)),
115
+ timestamp: latestMessage?.createdAt ?? conversation.updatedAt,
116
+ };
117
+ }
118
+
119
+ export function getChatConversationDeliveryState(
120
+ message: Pick<ChatMessage, 'deletedAt' | 'metadata'>
121
+ ): ChatConversationDeliveryState {
122
+ if (message.deletedAt) return 'deleted';
123
+
124
+ const status = readNonEmptyString(message.metadata.status)?.toLowerCase();
125
+ if (status && /fail|error|reject/u.test(status)) return 'failed';
126
+ if (status && /seen|read/u.test(status)) return 'seen';
127
+ if (status && /pending|queue|sending/u.test(status)) return 'sending';
128
+ return 'sent';
129
+ }
130
+
90
131
  export function isChatConversation(value: unknown): value is ChatConversation {
91
132
  const conversation = value as Partial<ChatConversation> | null | undefined;
92
133
 
@@ -115,14 +115,10 @@ describe('mergeWorkspaceSelectWorkspaces', () => {
115
115
  });
116
116
 
117
117
  it('keeps workspace fallback images outside Radix AvatarImage context', () => {
118
- const workspaceSelectSource = readFileSync(
119
- join(process.cwd(), 'src/components/ui/custom/workspace-select.tsx'),
118
+ const workspaceIconSource = readFileSync(
119
+ join(process.cwd(), 'src/components/ui/custom/workspace-select-icon.tsx'),
120
120
  'utf8'
121
121
  );
122
- const workspaceIconSource = workspaceSelectSource.slice(
123
- workspaceSelectSource.indexOf('function WorkspaceIcon'),
124
- workspaceSelectSource.indexOf('export function WorkspaceSelect')
125
- );
126
122
 
127
123
  expect(workspaceIconSource).toContain('<AvatarFallback');
128
124
  expect(workspaceIconSource).toContain('<Image');
@@ -0,0 +1,141 @@
1
+ import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
2
+ import { fireEvent, render, screen, waitFor } from '@testing-library/react';
3
+ import type { WorkspaceInvitationRecord } from '@tuturuuu/internal-api/workspaces';
4
+ import { NextIntlClientProvider } from 'next-intl';
5
+ import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
6
+ import { Command, CommandInput, CommandList } from '../../command';
7
+ import {
8
+ useWorkspaceInvitations,
9
+ WorkspaceInvitationItems,
10
+ } from '../workspace-select-invitations';
11
+
12
+ const mocks = vi.hoisted(() => ({
13
+ acceptWorkspaceInvite: vi.fn(),
14
+ declineWorkspaceInvite: vi.fn(),
15
+ listWorkspaceInvitations: vi.fn(),
16
+ }));
17
+
18
+ vi.mock('@tuturuuu/internal-api/workspaces', () => ({
19
+ acceptWorkspaceInvite: mocks.acceptWorkspaceInvite,
20
+ declineWorkspaceInvite: mocks.declineWorkspaceInvite,
21
+ listWorkspaceInvitations: mocks.listWorkspaceInvitations,
22
+ }));
23
+
24
+ const invitation: WorkspaceInvitationRecord = {
25
+ createdAt: null,
26
+ matchedEmail: 'invitee@example.com',
27
+ source: 'email',
28
+ type: 'MEMBER',
29
+ workspace: {
30
+ avatar_url: null,
31
+ handle: 'acme',
32
+ id: 'workspace-1',
33
+ logo_url: null,
34
+ name: 'Acme',
35
+ personal: false,
36
+ },
37
+ };
38
+
39
+ const messages = {
40
+ common: {
41
+ guest_access: 'Guest',
42
+ members: 'Member',
43
+ retry: 'Retry',
44
+ },
45
+ 'workspace-invitation': {
46
+ accept: 'Accept',
47
+ 'accept-error': 'Could not accept',
48
+ 'accept-success': 'Accepted',
49
+ 'decline-error': 'Could not decline',
50
+ 'decline-success': 'Declined',
51
+ 'direct-invite': 'Direct invitation',
52
+ 'email-invite': 'Email invitation',
53
+ 'list-eyebrow': 'Pending invitations',
54
+ reject: 'Decline',
55
+ },
56
+ };
57
+
58
+ function Harness({
59
+ onAccepted = vi.fn(),
60
+ onDeclined = vi.fn(),
61
+ }: {
62
+ onAccepted?: (value: WorkspaceInvitationRecord) => void;
63
+ onDeclined?: () => void;
64
+ }) {
65
+ const controller = useWorkspaceInvitations({
66
+ cacheScope: 'user-1',
67
+ enabled: true,
68
+ onAccepted,
69
+ onDeclined,
70
+ });
71
+
72
+ return (
73
+ <Command>
74
+ <CommandInput aria-label="Search" />
75
+ <CommandList>
76
+ <WorkspaceInvitationItems
77
+ controller={controller}
78
+ fallbackLogoUrl="/logo.svg"
79
+ />
80
+ </CommandList>
81
+ </Command>
82
+ );
83
+ }
84
+
85
+ function renderHarness(props: Parameters<typeof Harness>[0] = {}) {
86
+ const queryClient = new QueryClient({
87
+ defaultOptions: { queries: { retry: false } },
88
+ });
89
+ return render(
90
+ <QueryClientProvider client={queryClient}>
91
+ <NextIntlClientProvider locale="en" messages={messages}>
92
+ <Harness {...props} />
93
+ </NextIntlClientProvider>
94
+ </QueryClientProvider>
95
+ );
96
+ }
97
+
98
+ describe('workspace invitation picker items', () => {
99
+ beforeAll(() => {
100
+ globalThis.ResizeObserver = class ResizeObserver {
101
+ disconnect() {}
102
+ observe() {}
103
+ unobserve() {}
104
+ };
105
+ });
106
+
107
+ beforeEach(() => {
108
+ vi.clearAllMocks();
109
+ mocks.listWorkspaceInvitations.mockResolvedValue({
110
+ invitations: [invitation],
111
+ });
112
+ mocks.acceptWorkspaceInvite.mockResolvedValue(undefined);
113
+ mocks.declineWorkspaceInvite.mockResolvedValue(undefined);
114
+ });
115
+
116
+ it('accepts the highlighted invitation and reports the accepted workspace', async () => {
117
+ const onAccepted = vi.fn();
118
+ renderHarness({ onAccepted });
119
+
120
+ const option = await screen.findByRole('option', { name: /Acme/ });
121
+ fireEvent.click(option);
122
+
123
+ await waitFor(() =>
124
+ expect(mocks.acceptWorkspaceInvite).toHaveBeenCalledWith('workspace-1')
125
+ );
126
+ await waitFor(() => expect(onAccepted).toHaveBeenCalledWith(invitation));
127
+ });
128
+
129
+ it('declines in place without activating the accept option', async () => {
130
+ const onDeclined = vi.fn();
131
+ renderHarness({ onDeclined });
132
+
133
+ fireEvent.click(await screen.findByRole('button', { name: 'Decline' }));
134
+
135
+ await waitFor(() =>
136
+ expect(mocks.declineWorkspaceInvite).toHaveBeenCalledWith('workspace-1')
137
+ );
138
+ expect(mocks.acceptWorkspaceInvite).not.toHaveBeenCalled();
139
+ await waitFor(() => expect(onDeclined).toHaveBeenCalledOnce());
140
+ });
141
+ });
@@ -22,6 +22,11 @@ import {
22
22
  X,
23
23
  XCircle,
24
24
  } from '@tuturuuu/icons';
25
+ import { updateNotificationMetadata } from '@tuturuuu/internal-api';
26
+ import {
27
+ acceptWorkspaceInvite,
28
+ declineWorkspaceInvite,
29
+ } from '@tuturuuu/internal-api/workspaces';
25
30
  import { Button } from '@tuturuuu/ui/button';
26
31
  import {
27
32
  dedupeNotifications,
@@ -61,6 +66,11 @@ interface NotificationPopoverClientProps {
61
66
  archiveAllText?: string;
62
67
  emptyArchiveText?: string;
63
68
  loadingMoreText?: string;
69
+ retryText?: string;
70
+ acceptText?: string;
71
+ declineText?: string;
72
+ acceptedText?: string;
73
+ declinedText?: string;
64
74
  /** Base URL for external redirect (e.g. 'https://tuturuuu.com'). When set, "View All" links to {webAppUrl}/{wsId}/notifications. */
65
75
  webAppUrl?: string;
66
76
  }
@@ -93,6 +103,11 @@ export default function NotificationPopoverClient({
93
103
  archiveAllText = 'Archive all',
94
104
  emptyArchiveText = 'No archived notifications yet.',
95
105
  loadingMoreText = 'Loading more...',
106
+ retryText = 'Retry',
107
+ acceptText = 'Accept',
108
+ declineText = 'Decline',
109
+ acceptedText = 'Joined',
110
+ declinedText = 'Declined',
96
111
  webAppUrl,
97
112
  }: NotificationPopoverClientProps) {
98
113
  const [open, setOpen] = useState(false);
@@ -111,11 +126,13 @@ export default function NotificationPopoverClient({
111
126
 
112
127
  // Accurate unread count from dedicated endpoint
113
128
  const { data: unreadCount = 0 } = useUnreadCount(wsIdForFiltering, {
129
+ cacheScope: userId,
114
130
  enabled: Boolean(userId),
115
131
  });
116
132
 
117
133
  // Infinite scroll for inbox (unread) and archive (read)
118
134
  const inboxQuery = useInfiniteNotifications({
135
+ cacheScope: userId,
119
136
  wsId: wsIdForFiltering,
120
137
  unreadOnly: true,
121
138
  pageSize: 15,
@@ -123,6 +140,7 @@ export default function NotificationPopoverClient({
123
140
  });
124
141
 
125
142
  const archiveQuery = useInfiniteNotifications({
143
+ cacheScope: userId,
126
144
  wsId: wsIdForFiltering,
127
145
  readOnly: true,
128
146
  pageSize: 15,
@@ -176,7 +194,9 @@ export default function NotificationPopoverClient({
176
194
  <Button
177
195
  variant="ghost"
178
196
  size="icon"
179
- className="group relative hidden flex-none transition-all md:flex"
197
+ aria-label={notificationsText}
198
+ title={notificationsText}
199
+ className="group relative flex size-10 flex-none transition-all"
180
200
  >
181
201
  <Bell className="h-6 w-6" />
182
202
  {unreadCount > 0 && (
@@ -261,6 +281,11 @@ export default function NotificationPopoverClient({
261
281
  noNotificationsText={noNotificationsText}
262
282
  emptyArchiveText={emptyArchiveText}
263
283
  loadingMoreText={loadingMoreText}
284
+ retryText={retryText}
285
+ acceptText={acceptText}
286
+ declineText={declineText}
287
+ acceptedText={acceptedText}
288
+ declinedText={declinedText}
264
289
  markAsReadText={markAsReadText}
265
290
  markAsUnreadText={markAsUnreadText}
266
291
  onMarkAsRead={handleMarkAsRead}
@@ -293,6 +318,11 @@ function NotificationList({
293
318
  noNotificationsText,
294
319
  emptyArchiveText,
295
320
  loadingMoreText,
321
+ retryText,
322
+ acceptText,
323
+ declineText,
324
+ acceptedText,
325
+ declinedText,
296
326
  markAsReadText,
297
327
  markAsUnreadText,
298
328
  onMarkAsRead,
@@ -307,6 +337,11 @@ function NotificationList({
307
337
  noNotificationsText: string;
308
338
  emptyArchiveText: string;
309
339
  loadingMoreText: string;
340
+ retryText: string;
341
+ acceptText: string;
342
+ declineText: string;
343
+ acceptedText: string;
344
+ declinedText: string;
310
345
  markAsReadText: string;
311
346
  markAsUnreadText: string;
312
347
  onMarkAsRead: (id: string, isUnread: boolean) => void;
@@ -357,6 +392,21 @@ function NotificationList({
357
392
  <p className="mt-1 text-foreground/40 text-xs">
358
393
  {query.error instanceof Error ? query.error.message : 'Unknown error'}
359
394
  </p>
395
+ <Button
396
+ className="mt-3"
397
+ disabled={query.isFetching}
398
+ onClick={() => query.refetch()}
399
+ size="sm"
400
+ type="button"
401
+ variant="outline"
402
+ >
403
+ {query.isFetching ? (
404
+ <Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" />
405
+ ) : (
406
+ <RotateCcw className="mr-1.5 h-3.5 w-3.5" />
407
+ )}
408
+ {retryText}
409
+ </Button>
360
410
  </div>
361
411
  );
362
412
  }
@@ -406,6 +456,10 @@ function NotificationList({
406
456
  markAsUnreadText={markAsUnreadText}
407
457
  queryClient={queryClient}
408
458
  onActionComplete={onActionComplete}
459
+ acceptText={acceptText}
460
+ declineText={declineText}
461
+ acceptedText={acceptedText}
462
+ declinedText={declinedText}
409
463
  />
410
464
  ))}
411
465
 
@@ -431,6 +485,10 @@ interface NotificationCardProps {
431
485
  markAsUnreadText: string;
432
486
  queryClient: any;
433
487
  onActionComplete?: () => void;
488
+ acceptText: string;
489
+ declineText: string;
490
+ acceptedText: string;
491
+ declinedText: string;
434
492
  }
435
493
 
436
494
  function getWorkspaceInviteWorkspaceId(notification: Notification) {
@@ -456,6 +514,10 @@ function NotificationCard({
456
514
  markAsUnreadText,
457
515
  queryClient,
458
516
  onActionComplete,
517
+ acceptText,
518
+ declineText,
519
+ acceptedText,
520
+ declinedText,
459
521
  }: NotificationCardProps) {
460
522
  const isUnread = !notification.read_at;
461
523
  const [processingAction, setProcessingAction] = useState<string | null>(null);
@@ -477,58 +539,34 @@ function NotificationCard({
477
539
  break;
478
540
  }
479
541
 
480
- const url = `/api/workspaces/${targetWsId}/${
481
- accept ? 'accept-invite' : 'decline-invite'
482
- }`;
483
-
484
- const res = await fetch(url, { method: 'POST' });
485
-
486
- if (res.ok) {
487
- const updateRes = await fetch(
488
- `/api/v1/notifications/${notification.id}/metadata`,
489
- {
490
- method: 'PATCH',
491
- headers: { 'Content-Type': 'application/json' },
492
- body: JSON.stringify({
493
- action_taken: accept ? 'accepted' : 'declined',
494
- action_timestamp: new Date().toISOString(),
495
- }),
496
- }
497
- );
498
-
499
- if (updateRes.ok) {
500
- await Promise.all([
501
- queryClient.invalidateQueries({
502
- queryKey: ['workspaces'],
503
- refetchType: 'active',
504
- }),
505
- queryClient.invalidateQueries({
506
- queryKey: ['notifications'],
507
- refetchType: 'active',
508
- }),
509
- queryClient.refetchQueries({
510
- queryKey: ['notifications'],
511
- type: 'active',
512
- }),
513
- ]);
514
-
515
- toast.success(
516
- accept
517
- ? 'Workspace invite accepted'
518
- : 'Workspace invite declined'
519
- );
520
-
521
- onMarkAsRead(notification.id, true);
522
- router.refresh();
523
- onActionComplete?.();
524
- } else {
525
- toast.error('Failed to update notification');
526
- }
527
- } else {
528
- const errorData = await res.json();
529
- console.error('Failed to process invite:', errorData);
530
- toast.error(errorData.error || 'Failed to process invite');
531
- }
542
+ await (accept
543
+ ? acceptWorkspaceInvite(targetWsId)
544
+ : declineWorkspaceInvite(targetWsId));
545
+ await updateNotificationMetadata(notification.id, {
546
+ action_taken: accept ? 'accepted' : 'declined',
547
+ action_timestamp: new Date().toISOString(),
548
+ });
549
+
550
+ await Promise.all([
551
+ queryClient.invalidateQueries({
552
+ queryKey: ['workspaces'],
553
+ refetchType: 'active',
554
+ }),
555
+ queryClient.invalidateQueries({
556
+ queryKey: ['notifications'],
557
+ refetchType: 'active',
558
+ }),
559
+ queryClient.refetchQueries({
560
+ queryKey: ['notifications'],
561
+ type: 'active',
562
+ }),
563
+ ]);
564
+
565
+ toast.success(accept ? acceptedText : declinedText);
566
+
567
+ onMarkAsRead(notification.id, true);
568
+ router.refresh();
569
+ onActionComplete?.();
532
570
  break;
533
571
  }
534
572
  default:
@@ -597,13 +635,15 @@ function NotificationCard({
597
635
  {notification.data.action_taken === 'accepted' ? (
598
636
  <>
599
637
  <CheckCircle2 className="h-3 w-3 text-dynamic-green" />
600
- <span className="font-medium text-dynamic-green">Joined</span>
638
+ <span className="font-medium text-dynamic-green">
639
+ {acceptedText}
640
+ </span>
601
641
  </>
602
642
  ) : (
603
643
  <>
604
644
  <XCircle className="h-3 w-3 text-foreground/40" />
605
645
  <span className="font-medium text-foreground/60">
606
- Declined
646
+ {declinedText}
607
647
  </span>
608
648
  </>
609
649
  )}
@@ -627,7 +667,7 @@ function NotificationCard({
627
667
  ) : (
628
668
  <X className="h-3 w-3" />
629
669
  )}
630
- Decline
670
+ {declineText}
631
671
  </Button>
632
672
  <Button
633
673
  size="sm"
@@ -644,7 +684,7 @@ function NotificationCard({
644
684
  ) : (
645
685
  <Check className="h-3 w-3" />
646
686
  )}
647
- Accept
687
+ {acceptText}
648
688
  </Button>
649
689
  </div>
650
690
  ) : isTaskEntityNotification ? (
@@ -0,0 +1,58 @@
1
+ import { cn } from '@tuturuuu/utils/format';
2
+ import Image from 'next/image';
3
+ import { Avatar, AvatarFallback, AvatarImage } from '../avatar';
4
+ import { TUTURUUU_LOGO_URL } from './tuturuuu-logo';
5
+ import { resolveWorkspaceAvatarUrl } from './workspace-select-helpers';
6
+
7
+ export function WorkspaceIcon({
8
+ name,
9
+ avatarUrl,
10
+ className,
11
+ fallbackLogoUrl = TUTURUUU_LOGO_URL,
12
+ }: {
13
+ name?: string | null;
14
+ avatarUrl?: string | null;
15
+ className?: string;
16
+ fallbackLogoUrl?: string;
17
+ }) {
18
+ const resolvedAvatarUrl = resolveWorkspaceAvatarUrl(avatarUrl);
19
+ const shouldSkipFallbackOptimization = /^https?:\/\//u.test(fallbackLogoUrl);
20
+
21
+ return (
22
+ <Avatar
23
+ className={cn(
24
+ 'h-5 max-h-5 min-h-5 w-5 min-w-5 max-w-5 flex-none overflow-hidden',
25
+ resolvedAvatarUrl ? 'rounded-xs' : 'rounded-sm',
26
+ className
27
+ )}
28
+ >
29
+ <AvatarImage
30
+ alt={name || 'Workspace'}
31
+ className={cn(
32
+ 'h-full w-full object-cover',
33
+ resolvedAvatarUrl ? 'rounded-xs' : 'rounded-sm'
34
+ )}
35
+ src={
36
+ resolvedAvatarUrl ||
37
+ (name ? `https://avatar.vercel.sh/${name}.png` : undefined)
38
+ }
39
+ />
40
+ <AvatarFallback
41
+ className={cn(
42
+ 'h-full w-full text-xs',
43
+ resolvedAvatarUrl ? 'rounded-xs' : 'rounded-sm'
44
+ )}
45
+ >
46
+ <Image
47
+ alt=""
48
+ aria-hidden="true"
49
+ className="h-full w-full object-cover"
50
+ height={20}
51
+ src={fallbackLogoUrl}
52
+ unoptimized={shouldSkipFallbackOptimization}
53
+ width={20}
54
+ />
55
+ </AvatarFallback>
56
+ </Avatar>
57
+ );
58
+ }