API Reference

createClient

Returns a PluvClient instance

This is a re-export of createClient from @pluv/client.

createBundle

Returns a CreateBundle instance

Creates a bundle to be able to access the PluvClient from a react hook.

CreateBundle

This is the bundle returned from createBundle.

createRoomBundle

Returns a CreateRoomBundle instance

Creates a bundle to be able to access PluvRoom capabilities from various react hooks.

1export const {
2 // components
3 PluvRoomProvider,
4
5 // hooks
6 usePluvBroadcast,
7 usePluvCanRedo,
8 usePluvCanUndo,
9 usePluvConnection,
10 usePluvEvent,
11 usePluvMyPresence,
12 usePluvMyself,
13 usePluvOther,
14 usePluvOthers,
15 usePluvRedo,
16 usePluvRoom,
17 usePluvStorage,
18 usePluvTransact,
19 usePluvUndo,
20} = createRoomBundle({
21 /**
22 * @description Define the initial storage for the room
23 */
24 initialStorage: () => ({
25 messages: y.array([
26 y.object({
27 message: "hello",
28 name: "leedavidcs",
29 }),
30 ]),
31 }),
32 /**
33 * @description Define your presence schema
34 */
35 presence: z.object({
36 count: z.number(),
37 }),
38 /**
39 * @description This is the same `captureTimeout` option from yjs's UndoManager.
40 * This specifies a number in ms, during which edits are merged together to be
41 * undone together. Set this to 0, to track each transacted change individually.
42 * @see https://docs.yjs.dev/api/undo-manager
43 * @default 500
44 */
45 captureTimeout: 500,
46 /**
47 * @desription This is the same `trackedOrigins` option from yjs's UndoManager.
48 * This specifies transaction origins (strings only) to filter which transactions
49 * can be undone.
50 * When omitted, the user's connection id will be tracked. When provided,
51 * specifies additional tracked origins besides the user's connection id.
52 * @see https://docs.yjs.dev/api/undo-manager
53 * @default undefined
54 */
55 trackedOrigins: ["user-123"],
56});

PluvProvider

React provider component to allow the PluvClient created by createClient to be accessible in child components via usePluvClient. This is identical to importing the created client, so this is primarily useful for dependency injection when testing.

1<PluvProvider>{children}</PluvProvider>

usePluvClient

Returns PluvClient

Returns the PluvClient that was created via createClient.

CreateRoomBundle

This is the bundle returned from createRoomBundle.

MockedRoomProvider

React provider component to mock PluvRoomProvider. Enables hooks from CreateRoomBundle while completely offline. This can be useful in Storybook within a decorator when mocking PluvRoomProvider.

1import { y } from "@pluv/react";
2import { MockedRoomProvider } from "./io";
3
4<MockedRoomProvider
5 /**
6 * @description Mock events sent and received for hooks in child components.
7 */
8 //
9 events={{
10 EMIT_EMOJI: ({ emojiCode }) => ({
11 EMOJI_RECEIVED: { emojiCode },
12 }),
13 }}
14 /**
15 * @description Define your initial presence
16 */
17 initialPresence={{
18 selectionId: null,
19 }}
20 /**
21 * @description Define the initial initial storage for the room
22 */
23 initialStorage={() => ({
24 messages: y.array([]),
25 })}
26 /**
27 * @description Set the room id
28 */
29 room="my-mock-room"
30>
31 {children}
32</MockedRoomProvider>

PluvRoomProvider

React provider component to enable CreateRoomBundle hooks within child components. Mounting this component connects to a real-time room with other connected users. Unmounting this component will disconnect the room. See Create Rooms for more details.

1import { y } from "@pluv/react";
2import { MockedRoomProvider } from "./io";
3
4<PluvRoomProvider
5 /**
6 * @description Define the user's initial presence
7 */
8 initialPresence={{
9 selectionId: null,
10 }}
11 /**
12 * @description Define the initial storage for the room
13 */
14 initialStorage={() => ({
15 messages: y.array([]),
16 })}
17 /**
18 * @description Emits an error whenever authorization fails, for
19 * monitoring or debugging purposes
20 */
21 onAuthorizationFail={(error: Error) => {
22 console.error(error);
23 }}
24 /**
25 * @description Set the room id
26 */
27 room="my-room-id"
28>
29 {children}
30</PluvRoomProvider>

usePluvBroadcast

Returns (event, data) => void

Returns a broadcast function to emit an event and data to all connected clients. This is type-safe. The first parameter event will be the name of the event specified when creating your backend PluvIO instance and the second parameter data will be the associated response type. See Define Events for more details.

1const broadcast = usePluvBroadcast();
2
3broadcast("EMIT_RECEIVED", { emojiCode: 123 });

usePluvCanRedo

Returns boolean

Checks whether calling PluvRoom.redo will mutate storage.

1const canRedo: boolean = usePluvCanRedo();

usePluvCanUndo

Returns boolean

Checks whether calling PluvRoom.undo will mutate storage.

1const canUndo: boolean = usePluvCanUndo();

usePluvConnection

Returns WebSocketConnection

Returns the websocket connection start of the current user.

1const connection = usePluvConnection();
2// ^? const connection: {
3// id: string | null;
4// state: ConnectionState;
5// }

usePluvEvent

Returns void

Defines a listener for events broadcasted by connected clients. This is type-safe. The first parameter event is the name of the event to listen to from your backend PluvIO instance. The second parameter is a callback containing the data emitted from the broadcasted event.

1usePluvEvent("EMOJI_RECEIVED", ({ emojiCode }) => {
2 console.log(emojiCode);
3});

usePluvMyPresence

Returns [myPresence: TPresence | null, updatePresence: Function]

Returns the current user's presence, and a function to update the user's presence. Using this hook rerenders the component based on a deep-equality check on the user's presence value. This hook accepts a selector to return a modified presence to reduce rerenders.

1const { usePluvMyPresence } = createRoomBundle({
2 presence: z.object({
3 selectionId: z.nullable(z.string()),
4 selectionColor: z.string(),
5 }),
6});
7
8const [
9 // the user's presence
10 myPresence,
11 // a presence updater function
12 updateMyPresence
13] = usePluvMyPresence();
14
15// update individual base properties
16updateMyPresence({ selectionId: "name-input" });
17updateMyPresence({ selectionColor: "#123456" });
18
19// update multiple base properties
20updateMyPresence({
21 selectionId: "name-input",
22 selectionColor: "#123456",
23});
24
25// if you only need a partial presence
26const [myPresence] = usePluvMyPresence(({ selectionId }) => selectionId);
27
28// if you don't need presence, and just want the updater
29const [, updateMyPresence] = usePluvMyPresence(
30 // set selector to return a stable value
31 () => true
32);

usePluvMyself

Returns UserInfo | null

Returns the user-info object for the current user. This hook accepts a selector to return a modified user-info to reduce rerenders.

1const myself = usePluvMyself();
2
3// if you don't need the entire user-info
4const myself = usePluvMyself(({ connectionId }) => connectionId);

usePluvOther

Returns UserInfo | null

Returns the user-info object for a connected user by connectionId string.

1const other = usePluvOther();
2
3// if you don't need the entire user-info
4const other = usePluvOther(({ connectionId }) => connectionId);

usePluvOthers

Returns readonly UserInfo[]

Returns all user-info objects for all connected users. This may trigger a lot of re-renders if presence updates frequently.

Note Consider using this hook only for deriving others' connectionId values to pass into usePluvOther.

1const others = usePluvOthers();
2
3// if you want to just pull out connectionId properties
4const connectionIds = usePluvOthers((others) => {
5 return others.map(({ connectionId }) => connectionId);
6});

usePluvRedo

Returns void

Re-applies the last mutation that was undone via PluvRoom.undo.

For more information see: History

1const redo = usePluvRedo();
2
3redo();

usePluvStorage

Returns [TData | null, Yjs.SharedType | null]

Returns a base-level property of our yjs storage as a serialized value and a Yjs SharedType. The component is re-rendered whenever the Yjs SharedType is updated.

1import { y } from "@pluv/react";
2
3const { usePluvStorage } = createRoomBundle({
4 initialStorage: () => ({
5 messages: y.array(["hello"]),
6 }),
7});
8
9const [messages, sharedType] = usePluvStorage("messages");
10
11sharedType.push(["world~!"]);
12
13messages.map((message, key) => <div key={key}>{message}</div>);

usePluvTransact

Returns void

Performs a mutation that can be tracked as an operation to be undone/redone (undo/redo). When called without an origin, the origin will default to the user's connection id.

You can specify a 2nd parameter to transact with a different transaction origin.

For more information see: History

1const [messages, sharedType] = usePluvStorage("messages");
2const transact = usePluvTransact();
3
4transact((tx) => {
5 sharedType.push(["hello world!"]);
6
7 // Alternatively, access your storage from here
8 tx.messages.push(["hello world!"]);
9});
10
11// This will also be undoable if `"user-123"` is a tracked origin.
12transact(() => {
13 sharedType.push(["hello world!"]);
14}, "user-123");

usePluvUndo

Returns void

Undoes the last mutation that was applied via PluvRoom.transact.

For more information see: History

1const undo = usePluvUndo();
2
3undo();