Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 27 additions & 1 deletion examples/collaboration/production/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ This example demonstrates:
**Client**: Vue 3 application with SuperDoc editor and Y.js WebSocket provider
**Server**: Fastify server with WebSocket support for Y.js synchronization

**Note**: This example does not persist documents. All collaboration is in-memory and ephemeral. Documents reset when the server restarts.
**Note**: This example uses in-memory storage. Documents persist during the server session but reset when the server restarts. See [server/storage.ts](server/storage.ts) for the storage interface.

## Quick Start

Expand Down Expand Up @@ -89,6 +89,32 @@ collaboration-in-production/
3. Y.js handles CRDT-based conflict resolution automatically
4. Changes propagate in real-time to all connected clients

### First-Time Document Initialization

When collaboration is enabled, SuperDoc ignores the `documents[].data` property by default. This prevents sync conflicts where multiple users might broadcast their local file and overwrite each other.

For new documents (no existing Yjs state), use `isNewFile: true`:

```javascript
// Check if document exists on server
const { exists } = await fetch(`/doc/${documentId}/exists`).then(r => r.json());

const config = {
document: {
id: documentId,
data: exists ? null : docxArrayBuffer, // Provide DOCX for new documents
isNewFile: !exists, // Enables DOCX → Yjs conversion
},
modules: { collaboration: { url: wsUrl } }
};
```

The flow:
1. Server's `onLoad` returns `null` for new documents
2. Client detects this and sets `isNewFile: true` with DOCX data
3. SuperDoc converts the DOCX to Yjs state
4. The state syncs to all connected clients and persists on auto-save

## Extending This Example

To add persistence, you could:
Expand Down
41 changes: 17 additions & 24 deletions examples/collaboration/production/client/src/DocumentEditor.vue
Original file line number Diff line number Diff line change
Expand Up @@ -115,12 +115,27 @@ const init = async () => {
const hideToolbar = route.query['hide-toolbar'] === 'true';
showToolbar.value = !hideToolbar;

// Check if this is a new document (no existing Yjs state on server)
const existsResponse = await fetch(`${apiUrl}/doc/${documentId}/exists`);
const { exists } = await existsResponse.json();

// For new documents, load the default DOCX to initialize collaboration state
let docxData = null;
if (!exists) {
console.log('New document - loading default DOCX for initialization');
const response = await fetch(defaultDocument);
docxData = await response.arrayBuffer();
}

const config = {
selector: '#superdoc',
document: {
id: documentId,
type: 'docx',
isNewFile: false,
// isNewFile: true tells SuperDoc to use the provided data to initialize Yjs state
// This is required for new documents because collaboration ignores data by default
isNewFile: !exists,
data: docxData,
},
pagination: true,
colors: ['#a11134', '#2a7e34', '#b29d11', '#2f4597', '#ab5b22'],
Expand All @@ -137,35 +152,13 @@ const init = async () => {
console.log('SuperDoc is ready', event);
const editor = event.superdoc.activeEditor;
console.log('Active editor:', editor);

// Set up media observer for collaboration
const ydoc = event.superdoc.ydoc;
if (ydoc && editor) {
setupMediaObserver(ydoc, editor);
}
},
onEditorCreate: async (event) => {
// load default doc if current doc is blank
const { editor } = event;

if (!editor?.state) return;
const textContent = editor.state.doc.textContent;

// Check if document is empty (no content or only whitespace)
const isEmpty = !textContent || textContent.trim().length === 0;
if (!isEmpty) return;

try {
// Fetch and load default.docx
const response = await fetch(defaultDocument);
const blob = await response.blob();
const file = new File([blob], 'default.docx', { type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' });

await editor.replaceFile(file);
} catch (error) {
console.error('Error loading default content:', error);
}
},
onContentError: ({ error, documentId, file }) => {
console.error('Content loading error:', error);
console.log('Failed document:', documentId, file);
Expand Down
8 changes: 8 additions & 0 deletions examples/collaboration/production/server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ const SuperDocCollaboration = new CollaborationBuilder()
.onLoad((async (params) => {
try {
const state = await loadDocument(params.documentId);
// Returns null for new documents - client should use isNewFile: true with DOCX data
return state;
} catch(error) {
const err = new Error('Failed to load document: ' + error);
Expand Down Expand Up @@ -65,6 +66,13 @@ fastify.get('/health', async (request, reply) => {
return { status: 'ok', timestamp: new Date().toISOString() };
});

/** Check if a document exists (for first-time initialization) */
fastify.get('/doc/:documentId/exists', async (request, reply) => {
const { documentId } = request.params as { documentId: string };
const state = await loadDocument(documentId);
return { exists: state !== null };
});

/** Generate user info endpoint */
fastify.get('/user', async (request, reply) => {
return generateUser();
Expand Down
29 changes: 19 additions & 10 deletions examples/collaboration/production/server/storage.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,27 @@
import type { StorageFunction } from './storage-types.js';
import { Doc as YDoc, encodeStateAsUpdate } from 'yjs';

const blankDocxYdoc = new YDoc();
const metaMap = blankDocxYdoc.getMap('meta');

// Add minimal DOCX structure that the client expects
metaMap.set('docx', []);
// In-memory storage for demonstration
// In production, replace with your database (PostgreSQL, Redis, etc.)
const documents = new Map<string, Uint8Array>();

export const loadDocument: StorageFunction = async (id: string) => {
// Return an empty Y.js document with minimal DOCX structure
return encodeStateAsUpdate(blankDocxYdoc);
const state = documents.get(id);

// Return null if document doesn't exist yet
// This signals to the client that it should initialize with isNewFile: true
if (!state) {
console.log(`[storage] Document "${id}" not found - returning null for first-time initialization`);
return null;
}

console.log(`[storage] Document "${id}" loaded (${state.byteLength} bytes)`);
return state;
};

export const saveDocument: StorageFunction = async (id: string, file?: Uint8Array) => {
// No-op - just return success
export const saveDocument: StorageFunction = async (id: string, state?: Uint8Array) => {
if (!state) return false;

documents.set(id, state);
console.log(`[storage] Document "${id}" saved (${state.byteLength} bytes)`);
return true;
};
26 changes: 13 additions & 13 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.