Skip to content

Commit 691df98

Browse files
committed
fix: more fixes from review
1 parent f4a0ce5 commit 691df98

9 files changed

Lines changed: 363 additions & 220 deletions

File tree

‎projects/stream-chat-angular/src/lib/channel-preview/channel-preview.component.spec.ts‎

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -494,13 +494,15 @@ describe('ChannelPreviewComponent', () => {
494494

495495
expect(component.latestMessageStatus).toBe('delivered');
496496

497-
channel.state.read['otheruser'] = {
498-
last_read: latestMessage.created_at,
499-
unread_messages: 0,
500-
user: { id: 'otheruser' },
501-
} as unknown as MockChannel['state']['read'][string];
502-
channel.handleEvent('message.read', {
503-
message: latestMessage,
497+
// stream-chat updates the read state (and the read receipts) on message.read events
498+
(channel.state as unknown as MockStateStore<Channel['state']>).partialNext({
499+
read: {
500+
otheruser: {
501+
last_read: latestMessage.created_at,
502+
unread_messages: 0,
503+
user: { id: 'otheruser' },
504+
},
505+
} as unknown as Channel['state']['read'],
504506
});
505507

506508
expect(component.latestMessageStatus).toBe('read');

‎projects/stream-chat-angular/src/lib/channel-preview/channel-preview.component.ts‎

Lines changed: 23 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -72,11 +72,24 @@ export class ChannelPreviewComponent implements OnInit, OnDestroy {
7272
({ latestMessage }) => {
7373
this.ngZone.run(() => {
7474
this.setLatestMessage(latestMessage ?? undefined);
75+
this.updateLatestMessageStatus();
7576
this.updateUnreadState();
7677
});
7778
}
7879
);
7980
this.subscriptions.push({ unsubscribe: unsubscribeFromLatestMessage });
81+
// Read receipts are tracked by stream-chat, the message list uses the same data
82+
const unsubscribeFromReadReceipts =
83+
this.channel!.messageReceiptsTracker.snapshotStore.subscribeWithSelector(
84+
(state) => ({ revision: state.revision }),
85+
(_, prev) => {
86+
if (!prev) {
87+
return;
88+
}
89+
this.ngZone.run(() => this.updateLatestMessageStatus());
90+
}
91+
);
92+
this.subscriptions.push({ unsubscribe: unsubscribeFromReadReceipts });
8093
// stream-chat updates the unread count after the latest message (message.new), so the latest message subscription reads the previous count
8194
const ownUserId = this.chatClientService.chatClient.user?.id;
8295
const unsubscribeFromUnreadCount =
@@ -146,23 +159,22 @@ export class ChannelPreviewComponent implements OnInit, OnDestroy {
146159
void this.channelService.setAsActiveChannel(this.channel!);
147160
}
148161

149-
private setLatestMessage(localMessage?: LocalMessage) {
150-
const message = localMessage;
162+
private setLatestMessage(message?: LocalMessage) {
151163
this.latestMessage = message;
152164
if (!message) {
153165
this.latestMessageText = 'streamChat.Nothing yet...';
154-
} else if (message?.deleted_at) {
166+
} else if (message.deleted_at) {
155167
this.latestMessageText = 'streamChat.Message deleted';
156-
} else if (message?.text) {
168+
} else if (message.text) {
157169
this.latestMessageText =
158170
getMessageTranslation(
159-
localMessage,
171+
message,
160172
this.channel,
161173
this.chatClientService.chatClient.user
162174
) || message.text;
163-
} else if (message?.attachments && message.attachments.length) {
175+
} else if (message.attachments && message.attachments.length) {
164176
this.latestMessageText = 'streamChat.🏙 Attachment...';
165-
} else if (message?.poll_id) {
177+
} else if (message.poll_id) {
166178
this.latestMessageText = `📊 ${message.poll?.name}`;
167179
}
168180
if (this.latestMessage && this.latestMessage.type === 'regular') {
@@ -175,7 +187,7 @@ export class ChannelPreviewComponent implements OnInit, OnDestroy {
175187
}
176188
}
177189

178-
private updateUnreadState() {
190+
private updateLatestMessageStatus() {
179191
if (
180192
this.channel &&
181193
this.latestMessage &&
@@ -190,6 +202,9 @@ export class ChannelPreviewComponent implements OnInit, OnDestroy {
190202
} else {
191203
this.latestMessageStatus = undefined;
192204
}
205+
}
206+
207+
private updateUnreadState() {
193208
if (
194209
(this.isActive && !this.isUnreadMessageWasCalled) ||
195210
!this.canSendReadEvents

‎projects/stream-chat-angular/src/lib/channel.service.spec.ts‎

Lines changed: 75 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -638,30 +638,39 @@ describe('ChannelService', () => {
638638
expect(spy).not.toHaveBeenCalled();
639639
});
640640

641-
it('should load messages of the channel, if channel is not yet initialized', async () => {
641+
it(`shouldn't emit channel switch start, if the channel is already active`, async () => {
642642
await init();
643-
const channel = generateMockChannels(1)[0];
644-
channel.cid = 'not-initialized';
643+
const spy = jasmine.createSpy();
644+
service.channelSwitchState$.subscribe(spy);
645+
spy.calls.reset();
646+
service.setAsActiveChannel(getLatestValue(service.activeChannel$)!);
647+
648+
expect(spy).not.toHaveBeenCalled();
649+
});
650+
651+
it('should load messages of the active channel on reload, if channel is not yet initialized', async () => {
652+
await init();
653+
const channel = getActiveChannel();
645654
(channel as unknown as { initialized: boolean }).initialized = false;
646655
spyOn(channel, 'watch').and.callThrough();
647-
service.setAsActiveChannel(channel);
656+
spyOn(channel.messagePaginator, 'reload');
657+
await service.reloadActiveChannelMessages();
648658

649659
expect(channel.watch).toHaveBeenCalledWith();
660+
expect(channel.messagePaginator.reload).not.toHaveBeenCalled();
650661
});
651662

652-
it('should emit error, if loading messages of the channel failed', async () => {
663+
it('should emit error, if loading messages of the active channel failed', async () => {
653664
await init();
654-
const channel = generateMockChannels(1)[0];
655-
channel.cid = 'not-initialized';
665+
const channel = getActiveChannel();
656666
(channel as unknown as { initialized: boolean }).initialized = false;
657667
const error = apiError('GetOrCreateChannel failed with error: "error"');
658668
spyOn(channel, 'watch').and.rejectWith(error);
659669
const notificationService = TestBed.inject(NotificationService);
660670
spyOn(notificationService, 'addTemporaryNotification');
661671
const paginationStateSpy = jasmine.createSpy();
662672
service.activeChannelMessagesPaginationState$.subscribe(paginationStateSpy);
663-
service.setAsActiveChannel(channel);
664-
await settle();
673+
await service.reloadActiveChannelMessages();
665674

666675
expect(paginationStateSpy).toHaveBeenCalledWith(
667676
jasmine.objectContaining({ isLoading: true })
@@ -674,6 +683,14 @@ describe('ChannelService', () => {
674683
);
675684
});
676685

686+
it('should return the same messages from #activeChannelMessages as #activeChannelMessages$', async () => {
687+
await init();
688+
const messages = getLatestValue(service.activeChannelMessages$);
689+
690+
expect(service.activeChannelMessages).toBe(messages);
691+
expect(service.activeChannelMessages.every((m) => !!m.readBy)).toBeTrue();
692+
});
693+
677694
it('should emit #activeChannelMessages$', async () => {
678695
await init();
679696
const spy = jasmine.createSpy();
@@ -873,7 +890,7 @@ describe('ChannelService', () => {
873890

874891
it('should load more thread replies', async () => {
875892
await init();
876-
const parentMessage = service.activeChannelMessages[0] as StreamMessage;
893+
const parentMessage = service.activeChannelMessages[0];
877894
await service.setAsActiveParentMessage(
878895
getLatestValue(service.activeChannelMessages$).find(
879896
(m) => m.id === parentMessage.id
@@ -2469,15 +2486,16 @@ describe('ChannelService', () => {
24692486
).not.toBeUndefined();
24702487
});
24712488

2472-
it('should only update #readBy of the latest message, if read state changes', async () => {
2489+
it('should only update the messages with changed #readBy, if read state changes', async () => {
24732490
await init();
24742491
const channel = getActiveChannel();
24752492
const before = getLatestValue(service.activeChannelMessages$);
2493+
const lastReadIndex = 10;
24762494
const user = { id: 'jack', name: 'Jack' } as UserResponse;
2477-
// jack read every message
2495+
// jack read the messages until (and including) lastReadIndex
24782496
const read = {
24792497
[user.id]: {
2480-
last_read: dateToNs(new Date()),
2498+
last_read: before[lastReadIndex].created_at,
24812499
user,
24822500
unread_messages: 0,
24832501
},
@@ -2489,9 +2507,30 @@ describe('ChannelService', () => {
24892507
const after = getLatestValue(service.activeChannelMessages$);
24902508

24912509
expect(after).not.toBe(before);
2492-
expect(after[after.length - 1]).not.toBe(before[before.length - 1]);
2493-
expect(after[after.length - 1].readBy.map((u) => u.id)).toEqual(['jack']);
2494-
after.slice(0, -1).forEach((m, i) => expect(m).toBe(before[i]));
2510+
after.forEach((m, i) => {
2511+
if (i <= lastReadIndex) {
2512+
expect(m).not.toBe(before[i]);
2513+
expect(m.readBy.map((u) => u.id)).toEqual(['jack']);
2514+
} else {
2515+
expect(m).toBe(before[i]);
2516+
expect(m.readBy).toEqual([]);
2517+
}
2518+
});
2519+
});
2520+
2521+
it(`shouldn't emit the message list, if read state changes don't change #readBy`, async () => {
2522+
await init();
2523+
const channel = getActiveChannel();
2524+
const spy = jasmine.createSpy();
2525+
service.activeChannelMessages$.subscribe(spy);
2526+
spy.calls.reset();
2527+
const read = {} as Channel['state']['read'];
2528+
channel.state.read = read;
2529+
(channel.state as unknown as MockStateStore<{ read: unknown }>).partialNext(
2530+
{ read }
2531+
);
2532+
2533+
expect(spy).not.toHaveBeenCalled();
24952534
});
24962535

24972536
it('should recalculate #readBy, if a channel is activated again (read events received while the channel was inactive)', async () => {
@@ -2516,38 +2555,45 @@ describe('ChannelService', () => {
25162555
(channel.state as unknown as MockStateStore<{ read: unknown }>).partialNext(
25172556
{ read }
25182557
);
2558+
const spy = jasmine.createSpy();
2559+
service.activeChannelMessages$.subscribe(spy);
2560+
spy.calls.reset();
25192561
service.setAsActiveChannel(channel);
25202562
const after = getLatestValue(service.activeChannelMessages$);
25212563

25222564
expect(after[after.length - 1].readBy.map((u) => u.id)).toEqual(['jack']);
2565+
// The message list is emitted once, with the up-to-date readBy lists
2566+
expect(spy).toHaveBeenCalledTimes(1);
25232567
});
25242568

25252569
it('should update #readBy of every message, if a user is updated', async () => {
25262570
await init();
25272571
const channel = getActiveChannel();
25282572
const user = { id: 'jack', name: 'Jack' } as UserResponse;
2529-
const read = {
2573+
const setRead = (read: Channel['state']['read']) => {
2574+
channel.state.read = read;
2575+
(
2576+
channel.state as unknown as MockStateStore<{ read: unknown }>
2577+
).partialNext({ read });
2578+
};
2579+
setRead({
25302580
[user.id]: {
25312581
last_read: dateToNs(new Date()),
25322582
user,
25332583
unread_messages: 0,
25342584
},
2535-
} as unknown as Channel['state']['read'];
2536-
channel.state.read = read;
2537-
// Simulate a channel switch, so readBy is calculated for every message
2538-
service.deselectActiveChannel();
2539-
service.setAsActiveChannel(channel);
2585+
} as unknown as Channel['state']['read']);
25402586
const before = getLatestValue(service.activeChannelMessages$);
25412587

25422588
expect(before.every((m) => m.readBy[0]?.name === 'Jack')).toBeTrue();
25432589

2544-
channel.state.read = {
2545-
[user.id]: { ...read[user.id], user: { ...user, name: 'Jack Updated' } },
2546-
} as unknown as Channel['state']['read'];
2547-
events$.next({
2548-
eventType: 'user.updated',
2549-
event: { type: 'user.updated', user },
2550-
} as unknown as ClientEvent);
2590+
// stream-chat updates the users of the read state on user.updated events
2591+
setRead({
2592+
[user.id]: {
2593+
...channel.state.read[user.id],
2594+
user: { ...user, name: 'Jack Updated' },
2595+
},
2596+
} as unknown as Channel['state']['read']);
25512597
const after = getLatestValue(service.activeChannelMessages$);
25522598

25532599
expect(after.every((m) => m.readBy[0]?.name === 'Jack Updated')).toBeTrue();

‎projects/stream-chat-angular/src/lib/channel.service.thread.spec.ts‎

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -484,6 +484,17 @@ describe('ChannelService - threads', () => {
484484
);
485485
}));
486486

487+
it('should return the same messages from #activeChannelThreadReplies as #activeThreadMessages$', async () => {
488+
await init();
489+
await service.setAsActiveParentMessage(mockMessage());
490+
const replies = getLatestValue<StreamMessage[]>(
491+
service.activeThreadMessages$
492+
);
493+
494+
expect(replies.length).toBeGreaterThan(0);
495+
expect(service.activeChannelThreadReplies).toBe(replies);
496+
});
497+
487498
it('should set empty readBy field for thread messages', async () => {
488499
await init();
489500
const message = mockMessage();
@@ -751,6 +762,71 @@ describe('ChannelService - threads', () => {
751762
expect(parentMessageSpy).toHaveBeenCalledWith(undefined);
752763
});
753764

765+
it('should release the active thread, if custom handler deselects the parent message', async () => {
766+
await init();
767+
const channel = getActiveChannel();
768+
const parentMessage = getChannelMessages()[0];
769+
await service.setAsActiveParentMessage(parentMessage);
770+
const thread = getThread(parentMessage.id);
771+
service.customChannelTruncatedHandler = (
772+
_,
773+
__,
774+
___,
775+
____,
776+
_____,
777+
parentMessageSetter
778+
) => parentMessageSetter(undefined);
779+
channel.handleEvent('channel.truncated', {
780+
type: 'channel.truncated',
781+
cid: channel.cid,
782+
channel: { cid: channel.cid },
783+
});
784+
785+
expect(getLatestValue(service.activeParentMessageId$)).toBeUndefined();
786+
expect(getLatestValue(service.activeThreadMessages$)).toEqual([]);
787+
expect(thread.state.getLatestValue().active).toBeFalse();
788+
789+
await service.setAsActiveParentMessage(parentMessage);
790+
791+
expect(getLatestValue(service.activeParentMessageId$)).toBe(
792+
parentMessage.id
793+
);
794+
expect(thread.state.getLatestValue().active).toBeTrue();
795+
});
796+
797+
it('should switch the active thread, if custom handler sets a new parent message', async () => {
798+
await init();
799+
const channel = getActiveChannel();
800+
const [parentMessage, newParentMessage] = getChannelMessages();
801+
await service.setAsActiveParentMessage(parentMessage);
802+
const thread = getThread(parentMessage.id);
803+
service.customChannelTruncatedHandler = (
804+
_,
805+
__,
806+
___,
807+
____,
808+
_____,
809+
parentMessageSetter
810+
) => parentMessageSetter(newParentMessage);
811+
channel.handleEvent('channel.truncated', {
812+
type: 'channel.truncated',
813+
cid: channel.cid,
814+
channel: { cid: channel.cid },
815+
});
816+
await Promise.resolve();
817+
const newThread = getThread(newParentMessage.id);
818+
819+
expect(getLatestValue(service.activeParentMessageId$)).toBe(
820+
newParentMessage.id
821+
);
822+
expect(thread.state.getLatestValue().active).toBeFalse();
823+
expect(
824+
getLatestValue<StreamMessage[]>(service.activeThreadMessages$).map(
825+
(m) => m.id
826+
)
827+
).toEqual(newThread.messagePaginator.items!.map((m) => m.id));
828+
});
829+
754830
it('should emit thread messages if reactions change', async () => {
755831
await init();
756832
const parentMessage = mockMessage();

0 commit comments

Comments
 (0)