Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: change subscribeWithSelector API declaration #1382

Merged
merged 7 commits into from
Oct 28, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 22 additions & 2 deletions src/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ function isPatch<T>(value: T | Patch<T>): value is Patch<T> {
export class StateStore<T extends Record<string, unknown>> {
private handlerSet = new Set<Handler<T>>();

private static logCount = 5;

constructor(private value: T) {}

public next = (newValueOrPatch: T | Patch<T>): void => {
Expand Down Expand Up @@ -36,13 +38,31 @@ export class StateStore<T extends Record<string, unknown>> {
};
};

public subscribeWithSelector = <O extends readonly unknown[]>(selector: (nextValue: T) => O, handler: Handler<O>) => {
public subscribeWithSelector = <O extends Readonly<Record<string, unknown>> | Readonly<unknown[]>>(
selector: (nextValue: T) => O,
handler: Handler<O>,
) => {
// begin with undefined to reduce amount of selector calls
let selectedValues: O | undefined;

const wrappedHandler: Handler<T> = (nextValue) => {
const newlySelectedValues = selector(nextValue);
const hasUpdatedValues = selectedValues?.some((value, index) => value !== newlySelectedValues[index]) ?? true;

let hasUpdatedValues = !selectedValues;

if (Array.isArray(newlySelectedValues) && StateStore.logCount > 0) {
console.warn(
'[StreamChat]: The API of our StateStore has changed. Instead of returning an array in the selector, please return a named object of properties.',
);
StateStore.logCount--;
}

for (const key in selectedValues) {
// @ts-ignore TODO: remove array support (Readonly<unknown[]>)
if (selectedValues[key] === newlySelectedValues[key]) continue;
hasUpdatedValues = true;
break;
}

if (!hasUpdatedValues) return;

Expand Down
11 changes: 7 additions & 4 deletions src/thread.ts
Original file line number Diff line number Diff line change
Expand Up @@ -197,8 +197,11 @@ export class Thread<SCG extends ExtendableGenerics = DefaultGenerics> {

private subscribeMarkActiveThreadRead = () => {
return this.state.subscribeWithSelector(
(nextValue) => [nextValue.active, ownUnreadCountSelector(this.client.userID)(nextValue)],
([active, unreadMessageCount]) => {
(nextValue) => ({
active: nextValue.active,
unreadMessageCount: ownUnreadCountSelector(this.client.userID)(nextValue),
}),
({ active, unreadMessageCount }) => {
if (!active || !unreadMessageCount) return;
this.throttledMarkAsRead();
},
Expand All @@ -207,8 +210,8 @@ export class Thread<SCG extends ExtendableGenerics = DefaultGenerics> {

private subscribeReloadActiveStaleThread = () =>
this.state.subscribeWithSelector(
(nextValue) => [nextValue.active, nextValue.isStateStale],
([active, isStateStale]) => {
(nextValue) => ({ active: nextValue.active, isStateStale: nextValue.isStateStale }),
({ active, isStateStale }) => {
if (active && isStateStale) {
this.reload();
}
Expand Down
10 changes: 5 additions & 5 deletions src/thread_manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -119,9 +119,9 @@ export class ThreadManager<SCG extends ExtendableGenerics = DefaultGenerics> {

private subscribeManageThreadSubscriptions = () =>
this.state.subscribeWithSelector(
(nextValue) => [nextValue.threads] as const,
([nextThreads], prev) => {
const [prevThreads = []] = prev ?? [];
(nextValue) => ({ threads: nextValue.threads }),
({ threads: nextThreads }, prev) => {
const { threads: prevThreads = [] } = prev ?? {};
// Thread instance was removed if there's no thread with the given id at all,
// or it was replaced with a new instance
const removedThreads = prevThreads.filter((thread) => thread !== this.threadsById[thread.id]);
Expand All @@ -133,8 +133,8 @@ export class ThreadManager<SCG extends ExtendableGenerics = DefaultGenerics> {

private subscribeReloadOnActivation = () =>
this.state.subscribeWithSelector(
(nextValue) => [nextValue.active],
([active]) => {
(nextValue) => ({ active: nextValue.active }),
({ active }) => {
if (active) this.reload();
},
);
Expand Down
2 changes: 1 addition & 1 deletion src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -963,10 +963,10 @@ export type CreateChannelOptions<StreamChatGenerics extends ExtendableGenerics =
reminders?: boolean;
replies?: boolean;
search?: boolean;
skip_last_msg_update_for_system_msgs?: boolean;
typing_events?: boolean;
uploads?: boolean;
url_enrichment?: boolean;
skip_last_msg_update_for_system_msgs?: boolean;
};

export type CreateCommandOptions<StreamChatGenerics extends ExtendableGenerics = DefaultGenerics> = {
Expand Down
9 changes: 6 additions & 3 deletions test/unit/threads.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1322,14 +1322,17 @@ describe('Threads 2.0', () => {
},
}));
const spy = sinon.spy();
threadManager.state.subscribeWithSelector((nextValue) => [nextValue.pagination.isLoadingNext], spy);
threadManager.state.subscribeWithSelector(
(nextValue) => ({ isLoadingNext: nextValue.pagination.isLoadingNext }),
spy,
);
spy.resetHistory();

await threadManager.loadNextPage();

expect(spy.callCount).to.equal(2);
expect(spy.firstCall.calledWith([true])).to.be.true;
expect(spy.lastCall.calledWith([false])).to.be.true;
expect(spy.firstCall.calledWith({ isLoadingNext: true })).to.be.true;
expect(spy.lastCall.calledWith({ isLoadingNext: false })).to.be.true;
});

it('updates thread list and pagination', async () => {
Expand Down
Loading