Broadcast your selection
Send your own selection to peers over a websocket as row ids, so every peer paints it correctly under its own sort and filter.
The receiving side is the data-grid-presence add-on, which Show presence covers. This page covers the other direction. You send the local selection to a websocket, and the server relays a snapshot of all peers.
Wire the websocket and send the selection
onSelectionChange on the grid fires on every committed change: a click, a drag-extend step, a row, column, or all selection, and a clear. Its first argument is the stable SelectionState. It holds row ids and column ids and no view positions. The second argument has getRowIds(), which lists every selected row in view order.
toPresenceEntries(selection, details, { id, color, columnIds }) turns the selection into the entry to send. It holds the selected rows and the columns that the ranges, the column channel, and the checked rows cover, in the order of columnIds. It returns [] when nothing is selected. Send that entry:
"use client";
import { useEffect, useRef } from "react";
import { DataGrid, defineColumns } from "@/components/data-grid/data-grid";
import {
toPresenceEntries,
useDataGridPresence,
type PresenceHighlightEntry,
} from "@/components/data-grid-presence/data-grid-presence";
type Row = { id: string; name: string };
const columns = defineColumns<Row>()([
{ id: "name", header: "Name", accessorKey: "name" },
]);
type Props = { rows: Row[]; roomId: string; userId: string; color: string };
export function SharedGrid({ rows, roomId, userId, color }: Props) {
const { plugin, setPresenceHighlights } = useDataGridPresence();
const socketRef = useRef<WebSocket | null>(null);
const timerRef = useRef<ReturnType<typeof setTimeout>>(undefined);
function send(message: object) {
clearTimeout(timerRef.current);
timerRef.current = setTimeout(() => {
const socket = socketRef.current;
if (socket?.readyState !== WebSocket.OPEN) return;
socket.send(JSON.stringify(message));
}, 100);
}
useEffect(() => {
const socket = new WebSocket(`wss://your-server/rooms/${roomId}`);
socketRef.current = socket;
socket.onmessage = (event) => {
let peers: unknown;
try {
peers = JSON.parse(event.data);
} catch {
return;
}
if (!Array.isArray(peers)) return;
setPresenceHighlights(
peers.filter(
(peer): peer is PresenceHighlightEntry =>
typeof peer === "object" &&
peer !== null &&
peer.id !== userId,
),
);
};
return () => {
clearTimeout(timerRef.current);
socket.close();
};
}, [roomId, userId, setPresenceHighlights]);
const columnIds: string[] = columns.map((column) => column.id);
return (
<DataGrid
data={rows}
columns={columns}
getRowId={(row) => row.id}
plugins={[plugin]}
onSelectionChange={(next, details) => {
const [entry] = toPresenceEntries(next, details, {
id: userId,
color,
columnIds,
});
if (!entry) {
send({ type: "leave", id: userId });
return;
}
send({ type: "selection", ...entry });
}}
/>
);
}The sample takes columnIds from the order of columns. If users reorder or hide columns, build columnIds from the visible column order instead, for example with useDataGridVisibleColumns() in a component under the provider.
Relay a snapshot
setPresenceHighlights replaces the whole list. So your server answers every selection or leave message with the full list of peers. Each entry is a row-id range entry with the id, color, rowIds, and columnIds that the peer sent. The sample above filters out the entry of the local user. This relay keeps the last message of each peer:
const peers = new Map<WebSocket, unknown>();
socket.on("message", (data) => {
let message;
try {
message = JSON.parse(String(data));
} catch {
return;
}
if (message?.type === "leave") peers.delete(socket);
else {
const { id, color, rowIds, columnIds } = message ?? {};
// Cap the list lengths here as well.
peers.set(socket, { id, color, rowIds, columnIds });
}
const snapshot = JSON.stringify([...peers.values()]);
for (const client of server.clients) client.send(snapshot);
});The receiver resolves the ids against its own view. The receiver drops a row that a local filter hides and a hidden column. A message from a fuller view therefore paints cleanly on a narrower one.
getRowIds() lists every selected row, and checked rows count too. A select-all of 100,000 rows sends 100,000 ids. Cap the list on the sender or on the server.
- In scroll mode,
getRowIds()skips unloaded rows. A peer paints only the loaded rows of the range.getViewRowIds({ loaded: true })on the grid ref lists the same loaded rows of the whole view. - The sample sends the columns of the main range only. A selection of checked rows or whole columns has no
range, so the sample reports it as a leave. getRowIds()lists the rows of every range and the checked rows together. For several ranges, build the row ids of each range from its corners and the view order, and send one entry per range.- The sample waits 100 ms after the last change before it sends, because a drag fires one change for each step.
Treat every incoming message as untrusted input. The add-on drops malformed entries and repairs a bad label or color: Presence options lists each rule. The add-on renders a label as text.
Related
- Show presence: paint the selections of peers
- Presence options: every option of the add-on
- Selection and cell events: the events behind
onSelectionChange - Selection model: how the grid stores a selection