Create a new instance of the Spaces library.
The Spaces library constructor is overloaded allowing it to be instantiated using a ClientOptions object:
Deprecated: the ClientOptions option will be removed in the next release. Use the Ably client instance method described underneath.
import Spaces from '@ably-labs/spaces';
const spaces = new Spaces({ key: "<API-key>", clientId: "<client-ID>" });
Or an instance of the realtime, promise-based Ably client:
import { Realtime } from 'ably/promise';
import Spaces from '@ably-labs/spaces';
const client = new Realtime.Promise({ key: "<API-key>", clientId: "<client-ID>" });
const spaces = new Spaces(client);
In both cases, a clientId is required.
An API key will required for basic authentication. We strongly recommended that you use token authentication in any production environments.
Refer to the Ably docs for the JS SDK for information on setting up a realtime promise client.
Instance of the Ably-JS client that was passed to the constructor.
type ably = Ably.RealtimePromise;
Version of the Spaces library.
type version = string;
Get or create a Space instance. Returns a Space instance. Configure the space by passing SpaceOptions as the second argument.
type get = (name: string, options?: SpaceOptions) => Promise<Space>;
Used to configure a Space instance on creation.
type SpaceOptions = {
offlineTimeout?: number;
cursors?: CursorsOptions;
};
Number of milliseconds after a user loses connection or closes their browser window to wait before their SpaceMember object is removed from the members list. The default is 120000ms (2 minutes).
Options relating to configuring the cursors API (see below).
type CursorsOptions = {
outboundBatchInterval?: number;
paginationLimit?: number;
};
The interval in milliseconds at which a batch of cursor positions are published. This is multiplied by the number of members in the space minus 1. The default value is 100ms.
The number of pages searched from history for the last published cursor position. The default is 5.
An instance of a Space created using spaces.get. Inherits from EventEmitter.
An instance of Cursors.
type cursors = instanceof Cursors;
An instance of Locations.
type locations = instanceof Locations;
Enter the space. Can optionally take profileData
. This data can be an arbitrary JSON-serializable object which will be attached to the member object. Returns all current space members.
type enter = (profileData?: Record<string, unknown>) => Promise<SpaceMember[]>;
Leave the space. Can optionally take profileData
. This triggers the leave
event, but does not immediately remove the member from the space. See offlineTimeout.
type leave = (profileData?: Record<string, unknown>) => Promise<void>;
Update profileData
. This data can be an arbitrary JSON-serializable object which is attached to the member object. If the connection
has not entered the space, calling updateProfileData
will call enter
instead.
type updateProfileData = (profileDataOrUpdateFn?: unknown| (unknown) => unknown) => Promise<void>;
A function can also be passed in. This function will receive the existing profileData
and lets you update based on the existing value of profileData
:
await space.updateProfileData((oldProfileData) => {
const newProfileData = getNewProfileData();
return { ...oldProfileData, ...newProfileData };
})
Listen to events for the space. See EventEmitter for overloading usage.
Available events:
-
Listen to updates to members.
space.on('membersUpdate', (members: SpaceMember[]) => {});
Triggers on:
- presence updates (
enter
,leave
,update
andpresent
events) - location updates
The argument supplied to the callback is an array of SpaceMember (members) objects within the space.
- presence updates (
-
Listen to enter events of members.
space.on('enter', (member: SpaceMember) => {})
The argument supplied to the callback is a SpaceMember object representing the member entering the space.
-
Listen to leave events of members. Note that the leave event will only fire once the offlineTimeout has passed.
space.on('leave', (member: SpaceMember) => {})
The argument supplied to the callback is a SpaceMember object representing the member leaving the space.
Remove all event listeners, all event listeners for an event, or specific listeners. See EventEmitter for detailed usage.
space.off('enter');
Returns an array of all SpaceMember objects (members) currently in the space, including any who have left and not yet timed out. (see: offlineTimeout)
type getMembers = () => SpaceMember[];
Gets the SpaceMember object which relates to the local connection. Will return undefined
if the client hasn't entered the space yet.
type getSelf = () => SpaceMember | undefined;
A SpaceMember represents a member within a Space instance. Each new connection that enters will create a new member, even if they have the same clientId
.
type SpaceMember = {
clientId: string;
connectionId: string;
isConnected: boolean;
profileData: Record<string, unknown>;
location: Location;
lastEvent: PresenceEvent;
};
The client identifier for the user, provided to the ably client instance.
Identifier for the connection used by the user. This is a unique identifier.
Whether the user is connected to Ably.
Optional user data that can be attached to a user, such as a username or image to display in an avatar stack.
The current location of the user within the space.
The most recent event emitted by presence and its timestamp. Events will be either enter
, leave
, update
or present
.
type PresenceEvent = {
name: 'enter' | 'leave' | 'update' | 'present';
timestamp: number;
};
Handles the tracking of member locations within a space. Inherits from EventEmitter.
Set your current location. Location can be any JSON-serializable object. Emits a locationUpdate event to all connected clients in this space.
type set = (update: Location) => void;
Get location for self
space.locations.getSelf()
Get location for all members
space.locations.getAll()
Get location for other members
space.locations.getOthers()
Listen to events for locations. See EventEmitter for overloading usage.
Available events:
-
Fires when a member updates their location. The argument supplied to the event listener is an LocationUpdate.
space.locations.on('locationUpdate', (locationUpdate: LocationUpdate) => {});
Remove all event listeners, all event listeners for an event, or specific listeners. See EventEmitter for detailed usage.
space.locations.off('locationUpdate');
Represents a location in an application.
type Location = string | Record<string, unknown> | null;
Represents a change between locations for a given SpaceMember
.
type LocationUpdate = {
member: SpaceMember;
currentLocation: Location;
previousLocation: Location;
};
Handles tracking of member cursors within a space. Inherits from EventEmitter.
Set the position of a cursor. This will emit a CursorUpdate
event. If a member has not yet entered the space, this method will error.
A CursorUpdate
is an object with 2 properties. position
is an object with 2 required properties, x
and y
. These represent the position of the cursor on a 2D plane. A second optional property, data
can also be passed. This is an object of any shape and is meant for data associated with the cursor movement (like drag or hover calculation results):
type set = (update: { position: CursorPosition, data?: CursorData })
Example usage:
window.addEventListener('mousemove', ({ clientX, clientY }) => {
space.cursors.set({ position: { x: clientX, y: clientY }, data: { color: "red" } });
});
Get the last CursorUpdate for each connection.
type getAll = () => Record<ConnectionId, CursorUpdate>;
Example:
const lastPositions = space.cursors.getAll();
Listen to CursorUpdate
events. See EventEmitter for overloading usage.
Available events:
-
Emits an event when a new cursor position is set. The argument supplied to the event listener is a CursorUpdate.
space.cursors.on('cursorsUpdate', (cursorUpdate: CursorUpdate) => {});
Remove all event listeners, all event listeners for an event, or specific listeners. See EventEmitter for detailed usage.
space.cursors.off('cursorsUpdate');
Represents an update to a cursor.
type CursorUpdate = {
name: string;
clientId: string;
connectionId: string;
position: CursorPosition;
data?: CursorData;
};
Represents a cursors position.
type CursorPosition = {
x: number;
y: number;
};
Represent data that can be associated with a cursor update.
type CursorData = Record<string, unknown>;