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

Refactor space updates #180

Merged
merged 3 commits into from
Sep 22, 2023
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: 4 additions & 20 deletions src/Locations.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import { nanoid } from 'nanoid';

import EventEmitter, {
InvalidArgumentError,
inspect,
Expand All @@ -11,6 +9,7 @@ import type { SpaceMember } from './types.js';
import type { PresenceMember } from './utilities/types.js';
import type Space from './Space.js';
import { ERR_NOT_ENTERED_SPACE } from './Errors.js';
import SpaceUpdate from './SpaceUpdate.js';

Comment on lines 9 to +12
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm confused, why do imports have extensions? Is that normal?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Have a look at this issue microsoft/TypeScript#16577 (comment) and our own here #76. .js extensions provide the widest compatibility when loading in different environments, after bundling.

type LocationsEventMap = {
update: { member: SpaceMember; currentLocation: unknown; previousLocation: unknown };
Expand All @@ -19,10 +18,7 @@ type LocationsEventMap = {
export default class Locations extends EventEmitter<LocationsEventMap> {
private lastLocationUpdate: Record<string, PresenceMember['data']['locationUpdate']['id']> = {};

constructor(
private space: Space,
private presenceUpdate: (update: PresenceMember['data'], extras?: PresenceMember['extras']) => Promise<void>,
) {
constructor(private space: Space, private presenceUpdate: Space['presenceUpdate']) {
super();
}

Expand Down Expand Up @@ -61,20 +57,8 @@ export default class Locations extends EventEmitter<LocationsEventMap> {
throw ERR_NOT_ENTERED_SPACE();
}

const update: PresenceMember['data'] = {
profileUpdate: {
id: null,
current: self.profileData,
},
locationUpdate: {
id: nanoid(),
previous: self.location,
current: location,
},
};

const extras = this.space.locks.getLockExtras(self.connectionId);
await this.presenceUpdate(update, extras);
const update = new SpaceUpdate({ self, extras: this.space.locks.getLockExtras(self.connectionId) });
await this.presenceUpdate(update.updateLocation(location));
}

subscribe<K extends EventKey<LocationsEventMap>>(
Expand Down
23 changes: 6 additions & 17 deletions src/Locks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ import EventEmitter, {
type EventListener,
} from './utilities/EventEmitter.js';

import SpaceUpdate from './SpaceUpdate.js';

export class LockAttributes extends Map<string, string> {
toJSON() {
return Object.fromEntries(this);
Expand All @@ -34,10 +36,7 @@ export default class Locks extends EventEmitter<LockEventMap> {
// have requested.
private locks: Map<string, Map<string, Lock>>;

constructor(
private space: Space,
private presenceUpdate: (update: PresenceMember['data'], extras?: any) => Promise<void>,
) {
constructor(private space: Space, private presenceUpdate: Space['presenceUpdate']) {
super();
this.locks = new Map();
}
Expand Down Expand Up @@ -267,19 +266,9 @@ export default class Locks extends EventEmitter<LockEventMap> {
pendingLock.reason = ERR_LOCK_IS_LOCKED();
}

updatePresence(member: SpaceMember) {
const update: PresenceMember['data'] = {
profileUpdate: {
id: null,
current: member.profileData,
},
locationUpdate: {
id: null,
current: member?.location ?? null,
previous: null,
},
};
return this.presenceUpdate(update, this.getLockExtras(member.connectionId));
updatePresence(self: SpaceMember) {
const update = new SpaceUpdate({ self, extras: this.getLockExtras(self.connectionId) });
return this.presenceUpdate(update.noop());
}

getLock(id: string, connectionId: string): Lock | undefined {
Expand Down
111 changes: 105 additions & 6 deletions src/Space.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -153,10 +153,28 @@ describe('Space', () => {
presenceMap,
space,
}) => {
presenceMap.set('1', createPresenceMessage('enter'));
presenceMap.set(
'1',
createPresenceMessage('enter', {
data: {
profileUpdate: {
id: 1,
current: { color: 'black' },
},
locationUpdate: {
id: null,
current: null,
previous: null,
},
},
}),
);
const updateSpy = vi.spyOn(presence, 'update');
await space.updateProfileData((profileData) => ({ ...profileData, name: 'Betty' }));
expect(updateSpy).toHaveBeenNthCalledWith(1, createProfileUpdate({ current: { name: 'Betty' } }));
expect(updateSpy).toHaveBeenNthCalledWith(
1,
createProfileUpdate({ current: { name: 'Betty', color: 'black' } }),
);
});
});

Expand All @@ -174,13 +192,94 @@ describe('Space', () => {
});

describe('leave', () => {
it<SpaceTestContext>('leaves a space successfully', async ({ presence, presenceMap, space }) => {
presenceMap.set('1', createPresenceMessage('enter'));
it<SpaceTestContext>('leaves a space successfully and does not nullify presence data', async ({
presence,
presenceMap,
space,
}) => {
presenceMap.set(
'1',
createPresenceMessage('enter', {
data: {
profileUpdate: { id: 1, current: { name: 'Betty' } },
locationUpdate: { id: null, current: { slide: 1 }, previous: null },
},
}),
);

await space.enter();
const spy = vi.spyOn(presence, 'leave');
await space.leave();
expect(spy).toHaveBeenCalledOnce();
expect(spy).toHaveBeenNthCalledWith(1, {
profileUpdate: {
id: null,
current: { name: 'Betty' },
},
locationUpdate: {
id: null,
current: { slide: 1 },
previous: null,
},
});
});

it<SpaceTestContext>('leaves a space successfully and nullifies presence data', async ({
presence,
presenceMap,
space,
}) => {
presenceMap.set(
'1',
createPresenceMessage('enter', {
data: {
profileUpdate: { id: 1, current: { name: 'Betty' } },
locationUpdate: { id: null, current: { slide: 1 }, previous: null },
},
}),
);

const spy = vi.spyOn(presence, 'leave');
await space.leave(null);
expect(spy).toHaveBeenNthCalledWith(1, {
profileUpdate: {
id: 'NanoidID',
current: null,
},
locationUpdate: {
id: null,
current: { slide: 1 },
previous: null,
},
});
});

it<SpaceTestContext>('leaves a space successfully and updates presence data', async ({
presence,
presenceMap,
space,
}) => {
presenceMap.set(
'1',
createPresenceMessage('enter', {
data: {
profileUpdate: { id: 1, current: { name: 'Betty' } },
locationUpdate: { id: null, current: { slide: 1 }, previous: null },
},
}),
);

const spy = vi.spyOn(presence, 'leave');
await space.leave({ colorWhenLeft: 'blue' });
expect(spy).toHaveBeenNthCalledWith(1, {
profileUpdate: {
id: 'NanoidID',
current: { colorWhenLeft: 'blue' },
},
locationUpdate: {
id: null,
current: { slide: 1 },
previous: null,
},
});
});
});

Expand Down
75 changes: 27 additions & 48 deletions src/Space.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import Ably, { Types } from 'ably';
import { nanoid } from 'nanoid';

import EventEmitter, {
InvalidArgumentError,
Expand All @@ -11,9 +10,9 @@ import Locations from './Locations.js';
import Cursors from './Cursors.js';
import Members from './Members.js';
import Locks from './Locks.js';
import SpaceUpdate, { type SpacePresenceData } from './SpaceUpdate.js';

import { ERR_NOT_ENTERED_SPACE } from './Errors.js';

import { isFunction, isObject } from './utilities/is.js';

import type { SpaceOptions, SpaceMember, ProfileData } from './types.js';
Expand Down Expand Up @@ -63,21 +62,21 @@ class Space extends EventEmitter<SpaceEventsMap> {
this.locks = new Locks(this, this.presenceUpdate);
}

private presenceUpdate = (data: PresenceMember['data'], extras?: PresenceMember['extras']) => {
private presenceUpdate = ({ data, extras }: SpacePresenceData) => {
if (!extras) {
return this.channel.presence.update(data);
}
return this.channel.presence.update(Ably.Realtime.PresenceMessage.fromValues({ data, extras }));
};

private presenceEnter = (data: PresenceMember['data'], extras?: PresenceMember['extras']) => {
private presenceEnter = ({ data, extras }: SpacePresenceData) => {
if (!extras) {
return this.channel.presence.enter(data);
}
return this.channel.presence.enter(Ably.Realtime.PresenceMessage.fromValues({ data, extras }));
};

private presenceLeave = (data: PresenceMember['data'], extras?: PresenceMember['extras']) => {
private presenceLeave = ({ data, extras }: SpacePresenceData) => {
if (!extras) {
return this.channel.presence.leave(data);
}
Expand Down Expand Up @@ -123,25 +122,12 @@ class Space extends EventEmitter<SpaceEventsMap> {
resolve(members);
});

this.presenceEnter({
profileUpdate: {
id: nanoid(),
current: profileData,
},
locationUpdate: {
id: null,
current: null,
previous: null,
},
});
const update = new SpaceUpdate({ self: null, extras: null });
this.presenceEnter(update.updateProfileData(profileData));
});
}

async updateProfileData(
profileDataOrUpdateFn:
| Record<string, unknown>
| ((update: Record<string, unknown> | null) => Record<string, unknown>),
): Promise<void> {
async updateProfileData(profileDataOrUpdateFn: ProfileData | ((update: ProfileData) => ProfileData)): Promise<void> {
const self = await this.members.getSelf();

if (!isObject(profileDataOrUpdateFn) && !isFunction(profileDataOrUpdateFn)) {
Expand All @@ -150,25 +136,20 @@ class Space extends EventEmitter<SpaceEventsMap> {
);
}

const update = {
profileUpdate: {
id: nanoid(),
current: isFunction(profileDataOrUpdateFn) ? profileDataOrUpdateFn(null) : profileDataOrUpdateFn,
},
locationUpdate: {
id: null,
current: self?.location ?? null,
previous: null,
},
};
let update = new SpaceUpdate({ self, extras: self ? this.locks.getLockExtras(self.connectionId) : null });

if (!self) {
await this.presenceEnter(update);
const data = update.updateProfileData(
isFunction(profileDataOrUpdateFn) ? profileDataOrUpdateFn(null) : profileDataOrUpdateFn,
);
await this.presenceEnter(data);
return;
} else {
const data = update.updateProfileData(
isFunction(profileDataOrUpdateFn) ? profileDataOrUpdateFn(self.profileData) : profileDataOrUpdateFn,
);
return this.presenceUpdate(data);
}

const extras = this.locks.getLockExtras(self.connectionId);
return this.presenceUpdate(update, extras);
}

async leave(profileData: ProfileData = null) {
Expand All @@ -178,19 +159,17 @@ class Space extends EventEmitter<SpaceEventsMap> {
throw ERR_NOT_ENTERED_SPACE();
}

const update = {
profileUpdate: {
id: profileData ? nanoid() : null,
current: profileData ?? null,
},
locationUpdate: {
id: null,
current: self?.location ?? null,
previous: null,
},
};
const update = new SpaceUpdate({ self, extras: this.locks.getLockExtras(self.connectionId) });
let data;

// Use arguments so it's possible to deliberately nullify profileData on leave
if (arguments.length > 0) {
data = update.updateProfileData(profileData);
} else {
data = update.noop();
}

await this.presenceLeave(update);
await this.presenceLeave(data);
}

async getState(): Promise<{ members: SpaceMember[] }> {
Expand Down
Loading
Loading