@rowsncolumns/supabase
v9.0.2
Published
Supabase adapter for real-time collaborative spreadsheets with PostgreSQL persistence and OT
Readme
@rowsncolumns/supabase
Real-time collaborative spreadsheet adapter for Supabase with PostgreSQL persistence and Operational Transformation (OT) for conflict resolution.
Features
- PostgreSQL Persistence: All spreadsheet data is stored in Supabase PostgreSQL
- Real-time Collaboration: Live updates via Supabase Realtime
- Operational Transformation: Conflict resolution for concurrent edits
- Presence Tracking: See active collaborators and their cursors
- Leader Election: Coordinated recalculation via leader election
Installation
npm install @rowsncolumns/supabase @supabase/supabase-js
# or
yarn add @rowsncolumns/supabase @supabase/supabase-jsSetup
1. Run Database Migrations
Run the SQL migration in your Supabase project. You can find the migration file at:
libs/supabase/migrations/001_create_spreadsheet_tables.sqlRun it via Supabase SQL Editor or CLI:
supabase db push2. Deploy Edge Function
Deploy the OT Edge Function to handle operation transformation:
# Copy the edge function to your supabase project
cp -r libs/supabase/edge-functions/spreadsheet-ot supabase/functions/
# Deploy
supabase functions deploy spreadsheet-ot3. Configure Row Level Security
The migration includes example RLS policies based on document ownership. Customize these for your sharing/collaboration requirements.
Usage
import { useSupabase } from "@rowsncolumns/supabase";
import { createClient } from "@supabase/supabase-js";
import { useSpreadsheetState } from "@rowsncolumns/spreadsheet-state";
// Create Supabase client
const supabase = createClient(
process.env.SUPABASE_URL!,
process.env.SUPABASE_ANON_KEY!,
);
function SpreadsheetApp() {
const [sheetData, onChangeSheetData] = useState({});
const [sheets, onChangeSheets] = useState(initialSheets);
// ... other state
const {
activeCell,
activeSheetId,
enqueueGraphOperation,
calculateNow,
// ... other hooks
} = useSpreadsheetState({
sheets,
sheetData,
onChangeSheetData,
onChangeSheets,
// ... other props
onChangeHistory(patches) {
// Send patches to Supabase
onBroadcastPatch(patches);
},
});
// Supabase collaboration hook
const { onBroadcastPatch, users, synced, isLeader, connectionState } = useSupabase({
supabase,
documentId: "my-spreadsheet-id",
userId: currentUser.id,
title: currentUser.name,
sheetId: activeSheetId,
activeCell,
initialSheets,
edgeFunctionUrl: "/functions/v1/spreadsheet-ot",
// State setters
onChangeSheetData,
onChangeSheets,
onChangeTables,
onChangeCharts,
onChangeEmbeds,
// ... other setters
// Calculation
enqueueGraphOperation,
calculateNow,
onError: (err) => console.error("Supabase error:", err),
});
return (
<div>
{/* Connection status */}
<div>
Status: {synced ? "Connected" : "Connecting..."}
Role: {isLeader ? "Leader" : "Follower"}
Users: {users.length + 1}
</div>
{/* Render spreadsheet with users for cursor display */}
<CanvasGrid
users={users}
userId={currentUser.id}
// ... other props
/>
</div>
);
}API
useSupabase(props)
React hook for Supabase-based spreadsheet collaboration.
Props
| Prop | Type | Required | Description |
| ---------------------------- | ------------------ | -------- | --------------------------------- |
| supabase | SupabaseClient | Yes | Supabase client instance |
| documentId | string | Yes | Unique document identifier |
| userId | string \| number | Yes | Current user ID |
| title | string | Yes | User display name |
| sheetId | number | Yes | Active sheet ID |
| activeCell | CellInterface | No | Current active cell |
| initialSheets | Sheet[] | Yes | Initial sheets if document is new |
| disable | boolean | No | Disable collaboration |
| channelName | string | No | Realtime channel name |
| edgeFunctionUrl | string | No | Edge function URL |
| onChangeSheetData | Dispatch | Yes | Sheet data setter |
| onChangeSheets | Dispatch | Yes | Sheets setter |
| onChangeTables | Dispatch | Yes | Tables setter |
| onChangeCharts | Dispatch | No | Charts setter |
| onChangeEmbeds | Dispatch | No | Embeds setter |
| onChangeNamedRanges | Dispatch | No | Named ranges setter |
| onChangeProtectedRanges | Dispatch | No | Protected ranges setter |
| onChangeConditionalFormats | Dispatch | No | Conditional formats setter |
| onChangeDataValidations | Dispatch | No | Data validations setter |
| onChangePivotTables | Dispatch | No | Pivot tables setter |
| onChangeCellXfs | Dispatch | No | Cell formats setter |
| onChangeSharedStrings | Dispatch | No | Shared strings setter |
| enqueueGraphOperation | Function | Yes | Calculation enqueue function |
| calculateNow | Function | Yes | Calculate now function |
| onError | Function | No | Error callback |
Return Value
| Property | Type | Description |
| ------------------ | ----------------- | -------------------------------------------------------- |
| onBroadcastPatch | Function | Broadcast patches to other clients |
| users | Collaborator[] | Active collaborators |
| synced | boolean | Initial sync complete |
| isLeader | boolean | Is leader for recalc coordination |
| connectionState | ConnectionState | Current state: "connected", "connecting", "disconnected" |
Database Schema
The adapter uses the following tables:
spreadsheet_documents- Document metadataspreadsheet_operations- Operation log for OTspreadsheet_cells- Cell data (V3 flat map format)spreadsheet_sheets- Sheet definitionsspreadsheet_collections- Tables, charts, embeds, etc.spreadsheet_shared_strings- Shared strings for text deduplicationspreadsheet_cell_formats- Cell format definitions
Architecture
Client A Supabase Client B
│ │ │
│ submitOp(ops) ──────────►│ │
│ │ Edge Function: │
│ │ 1. Fetch missed ops │
│ │ 2. Transform incoming │
│ │ 3. Persist to PostgreSQL │
│ │ 4. Broadcast via Realtime │
│ │◄─────────── submitOp(ops) │
│ │ │
│◄──────── broadcast(ops) ──┼──────── broadcast(ops) ──►│
│ │ │Related Packages
- @rowsncolumns/sharedb - ShareDB adapter (WebSocket-based OT)
- @rowsncolumns/loro - Loro adapter (CRDT-based)
- @rowsncolumns/supabase-spreadsheet - Ephemeral-only Supabase adapter
License
MIT
