History
@pluv/react
comes with hooks to manipulate history that are built on top of Yjs's UndoManager.
This will allow users to apply undos and redos to Pluv storage mutations.
Relevant Hooks
Undoing a storage mutation
Assume you have storage defined like so:
1import { createBundle, createClient, y } from "@pluv/react";2import type { io } from "../server/io";34const client = createClient<typeof io>({ /* ... */ });56export const { createRoomBundle } = createBundle(client);78export const {9 usePluvCanRedo,10 usePluvCanUndo,11 usePluvRedo,12 usePluvStorage,13 usePluvTransact,14 usePluvUndo,15} = createRoomBundle({16 initialStorage: () => ({17 messages: y.array([18 y.object({19 message: "hello",20 name: "leedavidcs",21 }),22 ]),23 }),24});
To undo a storage mutation, you will need to wrap your mutation with a transaction.
1const transact = usePluvTransact();2const [messages, sharedType] = usePluvStorage();34// We can undo this5transact(() => {6 sharedType.push(["world!"]);7});89// We can also access all shared types to undo like this10transact((tx) => {11 tx.messages.push(["world!"]);12});1314// We cannot undo this15sharedType.push(["world!"]);
Then from anywhere within the PluvRoomProvider
, you can undo your last transacted operation.
1const undo = usePluvUndo();2const redo = usePluvRedo();34undo();5redo();
Custom transaction origins
By default when transact
is called, it will use the user's connection id as the transaction's origin. This should cover the majority of use-cases most of the time. However, if you need additional transaction origins, you can specify them with trackedOrigins
on createRoomBundle
.
1export const { /* ... */ } = createRoomBundle({2 initialStorage: () => ({3 messages: y.array([4 y.object({5 message: "hello",6 name: "leedavidcs",7 }),8 ]),9 }),10 // Additionally track "my-custom-origin"11 trackedOrigins: ["my-custom-origin"],12});1314const transact = usePluvTransact();1516// We can undo this transaction, because "my-custom-origin" is tracked17transact((tx) => {18 tx.messages.push(["world!"]);19}, "my-custom-origin");
Custom capture timeout
By default, when tracked storage mutations are transacted, Pluv will merge all mutations within 500ms to be undone together. To capture each transaction individually, you can configure this capture timeout to 0ms.
1export const { /* ... */ } = createRoomBundle({2 initialStorage: () => ({3 messages: y.array([4 y.object({5 message: "hello",6 name: "leedavidcs",7 }),8 ]),9 }),10 // By default, this is 500ms11 captureTimeout: 500,12});