Aller au contenu principal

Live

Methods

connectToDevServer(url: string, isAnimator: boolean): void Updated

Change default SDK connnect endpoint. Used locally to connect to the devserver.

attention

This function call should not be present in a production build.

// For vite
if (import.meta.env.DEV) connectToDevServer("http://localhost:3000");

getWindowContext()

Collect current window context name.

const windowContext = getWindowContext();

Type:

getPopupContext()

Collect current popup context name. This is the registered context while calling openPopup().

const popupContext = getPopupContext();

Type:

  • popupContext: string{ "label": "🚀 Getting Started", "position": 2 }

getUsers()

Return room animator, all users and teams.

const {
animator, // Room animator
me, // Current user
users, // All other users
teams, // Active teams
} = await getUsers();

Types:

registerUsers(users: { username?: string, avatar?: string }[])

attention

Only the animator can call this function.

Register users to the room.

const users = await registerUsers([
{ username: "John" },
{ username: "Doe", avatar: "https://example.com/avatar.png" },
{},
]);

console.log(users)
// Output: [{ id: '<random_id>', username: 'John' }, { id: '<random_id>', username: 'Doe', avatar: 'https://example.com/avatar.png' }, { id: '<random_id>', username: 'Anonymous' }]

Type:

unregisterUsers(userIds: string[])

attention

Only the animator can call this function.

Unregister users from the room. This will remove users and their data from the room.

await unregisterUsers([
"<user_id_1>",
"<user_id_2>",
]);

getTeams()

Collect active room teams.

const teams = await getTeams();

Type:

getData(id?: string)

Collect room stored data in globalData object.

  • If no id is given, returns all global data.
  • If an id is given, returns only the global data with the given id.
const globalData = {
fruit: {
id: "fruit",
value: "apple",
},
vegetable: {
id: "vegetable",
value: "salad",
},
};

// Returns all global data
let data = await getData();
console.log(data);
// Output: { fruit: { id: 'fruit', value: 'apple' }, vegetable: { id: 'vegetable', value: 'salad' } }

// Returns only global data with id : 'dataId'
data = await getData("fruit");
console.log(data);
// Output: { fruit: { id: 'fruit', value: 'apple' } }

Type:

attention

If no global data is found for the given id, the returned value for the given id will be an undefined.

data = await getData("animal");
console.log(data);
// Output: { animal: undefined }

getUserData(userId?: string, dataId?: string)

Collect room stored data in userData object.

  • If no userId is given, returns all users data.
  • If an userId is given, returns only the data of the given userId.
  • You can give dataId to select only data with the given id for each user.
const userData = {
jhon: {
fruit: {
id: "fruit",
value: "apple",
},
vegetable: {
id: "vegetable",
value: "salad",
},
},
joe: {
fruit: {
id: "fruit",
value: "strawberry",
},
},
};

// Returns all users data
let data = await getUserData();
console.log(data);
// Output: { jhon: { fruit: { id: 'fruit', value: 'apple' }, vegetable: { id: 'vegetable', value: 'salad' } }, joe: { fruit: { id: 'fruit', value: 'strawberry' } } }

// Returns only data of user with id : 'userId'
data = await getUserData("jhon");
console.log(data);
// Output: { jhon: { fruit: { id: 'fruit', value: 'apple' }, vegetable: { id: 'vegetable', value: 'salad' } } }

// Returns only 'fruit' data for each user
data = await getUserData(undefined, "fruit");
// Output: { jhon: { fruit: { id: 'fruit', value: 'apple' } }, joe: { fruit: { id: 'fruit', value: 'strawberry' } } }

// Returns only 'fruit' data for user 'joe'
data = await getUserData("joe", "fruit");
console.log(data);
// Output: { joe: { fruit: { id: 'fruit', value: 'strawberry' } } }

Type:

attention

If no user data is found for the given userId, the returned value for the given userId will be undefined.

data = await getUserData("max");
console.log(data);
// Output: { max: undefined }

Also, if the given dataId doen't exists, user data will be undefined.

data = await getUserData("joe", "vegetable");
console.log(data["joe"]["vegetable"].value);
// Canno't read properties of undefined. (data['jhon']['animal'] is undefined)

getAssets()

Collect room assets content (tags & files).

const { tags, files } = await getAssets();

Types:

remarque

Returned files path are relative to the current instance. If you are on k-hubs.com and returned path is /static/file/.... The full path is https://k-hubs.com/static/file/...

getRoomConfig()

Collect room configuration.

const config = await getRoomConfig();

Type:

getRoomContext()

Collect room context.

const context = await getRoomContext();

Type:

updateProfile(user: { username?: string; avatar?: string })

Update current user profile.

const updated = await updateProfile({ username: "Joe" }); // Update username to "Joe"

Type:

setData(data: IDataSet[])

Save given data into the room. For each data:

  • If data.isGlobal === true, then the data will be stored into the globalData object.
  • Else it will be stored into the userData object.
  • If data.userId is specified, the data will be stored into specified userData
setData([
{ id: "fruit", value: "apple" },
{ id: "fruit", value: "strawberry", isGlobal: true },
{ id: "fruit", value: "cherry", userId: "jhon" },
]);

console.log(getData("fruit")); // { fruit: { id: 'fruit', value: 'strawberry' } }
console.log(getUserData("fruit")); // { [currentUserId]: { fruit: { id: 'fruit', value: 'apple' } }, jhon: { fruit: { id: 'fruit', value: 'cherry' } } }
remarque

data will not be sent to other users. To send data to other users use sendData().

cleanUserData(userId: string): Promise<void>

Remove all data stored in the userData object for the specified user. This operation clears all user-specific data but does not affect global data or other users' data.

attention

This action is irreversible. Once user data is cleaned, it cannot be recovered.

cleanUserData("john");

console.log(getUserData("john")); // {['john']: {}}

sendData(data: IData[], userIds?: string[])

Send all given data to other users.

  • If userIds is given, each data will be only sent to given userIds.
  • Else each data will be send to all user.
// Jhon send data to everyone
const data = [
{ id: "fruit", value: "apple" },
{ id: "animal", value: "dog" },
];
sendData(data);

// send data only to Joe and Max
sendData(data, ["joe", "max"]);

sendToAnimator(data: IData[])

Send all given data to the room animator.

const data = [
{ id: "fruit", value: "apple" },
{ id: "animal", value: "dog" },
];
sendToAnimator(data);
astuce

To listen for sendData and sendToAnimator, use onDataSend listener.

sendFiles(files: File[])

Upload files to current room. Given files must be type of File.

const file1 = new File(); // avatar.png
const file2 = new File(); // text.txt
const uplodedFiles = await sendFiles([file1, file2]);

console.log(uploadedFiles); // [{ name: 'avatar', ... }, { name: 'text', ... }]

Type:

updateFile(fileId: string, name?: string, file?: string)

Update a previous uploaded file.

const updatedFile = await updateFile("file1", "New name");
console.log(updatedFile); // { name: 'New name', ... }

Type:

updateRoomContextSharedData(data: Partial<IRoomContext['sharedData']>)

Update room context shared data. Pass a partial object with desired fields to update. Existing fields will not be changed.

await updateRoomContextSharedData({ users: { "user-1": { score: 10 } } });

openPopup(context: string, features?: string)

Open a popup window with given context as name. You can customise window features with the features argument.

const popup = openPopup("console");

Type:

Listeners

Use these functions to listen for incoming events from server.

attention

When you register a listener with the on... function and you unregister a listener with the off... function, the given callback to each function must be the same function instance.

// Bad ❌
onUserJoin((user) => {
console.log(user);
});
offUserJoin((user) => {
console.log(user);
});

// Good ✅
const callback = (user) => console.log(user);

onUserJoin(callback);
offUserJoin(callback);

onUserJoin(callback: (user: IRoomUser) => void)

Register a listener for the userJoin event. The given callback is trigered when a user connect to the room. When the callback is trigered, it takes the connected user as parameters. Its type is IRoomUser.

const connectCallback = (user: IRoomUser) => console.log(user);
// Listen for join event.
onUserJoin(connectCallback);

// Jhon connected ...
// Console output: { id: 'jhon', username: 'Jhon', ... }

offUserJoin(callback: (user: IRoomUser) => void)

Unregister a previous onUserJoin listener.

offUserJoin(connectCallback);

onUserLeave(callback: (userId: string) => void)

Register a listener for the userLeave event. the given callback is trigered when a user disconnect from the room. When the callback is trigered, it takes the disconnected userId as parameter.

const disconnectCallback = (userId: string) => console.log(userId);
// Listen for leave event.
onUserLeave(disconnectCallback);

// Jhon diconnected ...
// Console output: 'jhon'

offUserLeave(callback: (userId: string) => void)

Unregister a previous onUserLeave listener.

offUserLeave(disconnectCallback);

onUserUpdate(callback: (user: IRoomUser) => void): void

Register a listener for the userUpdate event fired when an user call updateProfile().

const userUpdateCallback = (user: IRoomUser) => console.log(user);
// Listen for user update event.
onUserUpdate(userUpdateCallback);

// Jhon update his username to 'Jhon Doe' ...
// Console output: { 'id': 'jhon', username: 'Jhon Doe' }

offUserUpdate(callback: (user: IRoomUser) => void): void

Unregister a previous `onUserUpdate listener.

offUserUpdate(onUserUpdateCallback);

onDataSend(dataId: string, callback: (data: IReceivedData) => void)

const onFruitCallback = (data: IReceivedData) => console.log(data);
onDataSend('fruit', onFruitCallback);

// Jhon sendData({ id: 'fruit', value: 'apple' })
// Console output: { id: 'fruit', value: 'apple', senderUserId: 'jhon' }

offDataSend(dataId: string, callback: (data: IReceivedData) => void)

Unregister a previous onDataSend listener.

offDataSend("fruit", onFruitCallback);