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 // components3 PluvRoomProvider,45 // hooks6 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 room23 */24 initialStorage: () => ({25 messages: y.array([26 y.object({27 message: "hello",28 name: "leedavidcs",29 }),30 ]),31 }),32 /**33 * @description Define your presence schema34 */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 be41 * undone together. Set this to 0, to track each transacted change individually.42 * @see https://docs.yjs.dev/api/undo-manager43 * @default 50044 */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 transactions49 * 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-manager53 * @default undefined54 */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";34<MockedRoomProvider5 /**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 presence16 */17 initialPresence={{18 selectionId: null,19 }}20 /**21 * @description Define the initial initial storage for the room22 */23 initialStorage={() => ({24 messages: y.array([]),25 })}26 /**27 * @description Set the room id28 */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";34<PluvRoomProvider5 /**6 * @description Define the user's initial presence7 */8 initialPresence={{9 selectionId: null,10 }}11 /**12 * @description Define the initial storage for the room13 */14 initialStorage={() => ({15 messages: y.array([]),16 })}17 /**18 * @description Emits an error whenever authorization fails, for19 * monitoring or debugging purposes20 */21 onAuthorizationFail={(error: Error) => {22 console.error(error);23 }}24 /**25 * @description Set the room id26 */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();23broadcast("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});78const [9 // the user's presence10 myPresence,11 // a presence updater function12 updateMyPresence13] = usePluvMyPresence();1415// update individual base properties16updateMyPresence({ selectionId: "name-input" });17updateMyPresence({ selectionColor: "#123456" });1819// update multiple base properties20updateMyPresence({21 selectionId: "name-input",22 selectionColor: "#123456",23});2425// if you only need a partial presence26const [myPresence] = usePluvMyPresence(({ selectionId }) => selectionId);2728// if you don't need presence, and just want the updater29const [, updateMyPresence] = usePluvMyPresence(30 // set selector to return a stable value31 () => true32);
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();23// if you don't need the entire user-info4const myself = usePluvMyself(({ connectionId }) => connectionId);
usePluvOther
Returns UserInfo | null
Returns the user-info object for a connected user by connectionId
string.
1const other = usePluvOther();23// if you don't need the entire user-info4const 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 intousePluvOther
.
1const others = usePluvOthers();23// if you want to just pull out connectionId properties4const 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();23redo();
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";23const { usePluvStorage } = createRoomBundle({4 initialStorage: () => ({5 messages: y.array(["hello"]),6 }),7});89const [messages, sharedType] = usePluvStorage("messages");1011sharedType.push(["world~!"]);1213messages.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();34transact((tx) => {5 sharedType.push(["hello world!"]);67 // Alternatively, access your storage from here8 tx.messages.push(["hello world!"]);9});1011// 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();23undo();