0
# Document Management
1
2
Core document functionality for creating, managing, and synchronizing collaborative documents. The Doc class serves as the central container that manages shared types and handles synchronization state.
3
4
## Capabilities
5
6
### Doc Class
7
8
The main document class that serves as the root container for all shared types in a collaborative session.
9
10
```typescript { .api }
11
/**
12
* Main document class that manages shared types and synchronization
13
*/
14
class Doc {
15
constructor(options?: DocOpts);
16
17
/** Unique client identifier for this document instance */
18
readonly clientID: number;
19
20
/** Globally unique identifier for this document */
21
readonly guid: string;
22
23
/** Collection identifier for grouping related documents */
24
readonly collectionid: string | null;
25
26
/** Whether garbage collection is enabled */
27
readonly gc: boolean;
28
29
/** Map of shared types by name */
30
readonly share: Map<string, AbstractType<YEvent<any>>>;
31
32
/** Whether the document has been loaded */
33
readonly isLoaded: boolean;
34
35
/** Whether the document is synchronized with remote state */
36
readonly isSynced: boolean;
37
38
/** Whether the document has been destroyed */
39
readonly isDestroyed: boolean;
40
41
/** Promise that resolves when document is loaded */
42
readonly whenLoaded: Promise<Doc>;
43
44
/** Promise that resolves when document is synced */
45
readonly whenSynced: Promise<void>;
46
}
47
48
interface DocOpts {
49
/** Custom client ID (auto-generated if not provided) */
50
clientID?: number;
51
52
/** Custom document GUID (auto-generated if not provided) */
53
guid?: string;
54
55
/** Collection identifier for grouping documents */
56
collectionid?: string | null;
57
58
/** Enable/disable garbage collection (default: true) */
59
gc?: boolean;
60
61
/** Custom garbage collection filter function */
62
gcFilter?: (item: Item) => boolean;
63
64
/** Custom metadata for the document */
65
meta?: any;
66
67
/** Whether to automatically load the document */
68
autoLoad?: boolean;
69
70
/** Whether the document should be loaded */
71
shouldLoad?: boolean;
72
}
73
```
74
75
**Usage Examples:**
76
77
```typescript
78
import * as Y from "yjs";
79
80
// Create a basic document
81
const doc = new Y.Doc();
82
83
// Create document with options
84
const docWithOptions = new Y.Doc({
85
clientID: 12345,
86
guid: "my-document-id",
87
gc: false, // Disable garbage collection
88
meta: { author: "Alice", version: "1.0" }
89
});
90
```
91
92
### Getting Shared Types
93
94
Retrieve or create shared types within the document.
95
96
```typescript { .api }
97
/**
98
* Get or create a shared type by name and constructor
99
* @param name - Name of the shared type
100
* @param TypeConstructor - Constructor function for the type
101
* @returns Instance of the shared type
102
*/
103
get<Type>(name: string, TypeConstructor?: Type): InstanceType<Type>;
104
105
/**
106
* Get or create a YArray with the given name
107
* @param name - Name of the array (default: random)
108
* @returns YArray instance
109
*/
110
getArray<T>(name?: string): YArray<T>;
111
112
/**
113
* Get or create a YText with the given name
114
* @param name - Name of the text (default: random)
115
* @returns YText instance
116
*/
117
getText(name?: string): YText;
118
119
/**
120
* Get or create a YMap with the given name
121
* @param name - Name of the map (default: random)
122
* @returns YMap instance
123
*/
124
getMap<T>(name?: string): YMap<T>;
125
126
/**
127
* Get or create a YXmlElement with the given name
128
* @param name - Name of the element (default: random)
129
* @returns YXmlElement instance
130
*/
131
getXmlElement<KV = { [key: string]: any }>(name?: string): YXmlElement<KV>;
132
133
/**
134
* Get or create a YXmlFragment with the given name
135
* @param name - Name of the fragment (default: random)
136
* @returns YXmlFragment instance
137
*/
138
getXmlFragment(name?: string): YXmlFragment;
139
```
140
141
**Usage Examples:**
142
143
```typescript
144
import * as Y from "yjs";
145
146
const doc = new Y.Doc();
147
148
// Get shared types by name
149
const users = doc.getArray<User>("users");
150
const settings = doc.getMap<any>("settings");
151
const content = doc.getText("content");
152
const xmlDoc = doc.getXmlFragment("document");
153
154
// Using generic get method
155
const customArray = doc.get("custom", Y.Array);
156
```
157
158
### Transaction Management
159
160
Execute multiple operations atomically within a single transaction.
161
162
```typescript { .api }
163
/**
164
* Execute a function within a transaction context
165
* @param f - Function to execute within transaction
166
* @param origin - Optional origin identifier for the transaction
167
* @returns Result of the function execution
168
*/
169
transact<T>(f: (transaction: Transaction) => T, origin?: any): T;
170
```
171
172
**Usage Examples:**
173
174
```typescript
175
import * as Y from "yjs";
176
177
const doc = new Y.Doc();
178
const yarray = doc.getArray("items");
179
const ymap = doc.getMap("metadata");
180
181
// Execute multiple operations in a single transaction
182
doc.transact((transaction) => {
183
yarray.push(["item1", "item2"]);
184
ymap.set("lastModified", new Date().toISOString());
185
ymap.set("itemCount", yarray.length);
186
}, "batch-update");
187
188
// The origin can be used to identify the source of changes
189
doc.transact(() => {
190
yarray.delete(0, 1);
191
}, { type: "user-action", userId: "alice" });
192
```
193
194
### Document Lifecycle
195
196
Control document loading, synchronization, and cleanup.
197
198
```typescript { .api }
199
/**
200
* Request that the document be loaded
201
*/
202
load(): void;
203
204
/**
205
* Get all subdocuments contained within this document
206
* @returns Set of subdocuments
207
*/
208
getSubdocs(): Set<Doc>;
209
210
/**
211
* Get GUIDs of all subdocuments
212
* @returns Set of subdocument GUIDs
213
*/
214
getSubdocGuids(): Set<string>;
215
216
/**
217
* Convert document to JSON (deprecated - use individual type toJSON methods)
218
* @returns JSON representation of shared types
219
*/
220
toJSON(): { [key: string]: any };
221
222
/**
223
* Destroy the document and clean up resources
224
*/
225
destroy(): void;
226
```
227
228
**Usage Examples:**
229
230
```typescript
231
import * as Y from "yjs";
232
233
const doc = new Y.Doc();
234
235
// Load document
236
doc.load();
237
238
// Wait for document to be loaded
239
await doc.whenLoaded;
240
241
// Wait for synchronization
242
await doc.whenSynced;
243
244
// Check subdocuments
245
const subdocs = doc.getSubdocs();
246
console.log(`Found ${subdocs.size} subdocuments`);
247
248
// Clean up when done
249
doc.destroy();
250
```
251
252
### Document Events
253
254
Observe document-level events for loading, synchronization, and subdocument changes.
255
256
```typescript { .api }
257
/**
258
* Document event types
259
*/
260
interface DocEvents {
261
load: (doc: Doc) => void;
262
sync: (doc: Doc, isSynced: boolean) => void;
263
beforeTransaction: (transaction: Transaction, doc: Doc) => void;
264
afterTransaction: (transaction: Transaction, doc: Doc) => void;
265
beforeObserverCalls: (transaction: Transaction, doc: Doc) => void;
266
afterObserverCalls: (transaction: Transaction, doc: Doc) => void;
267
subdocs: (doc: Doc, changes: { loaded: Set<Doc>; added: Set<Doc>; removed: Set<Doc> }) => void;
268
destroy: (doc: Doc) => void;
269
}
270
```
271
272
**Usage Examples:**
273
274
```typescript
275
import * as Y from "yjs";
276
277
const doc = new Y.Doc();
278
279
// Listen for document events
280
doc.on("load", () => {
281
console.log("Document loaded");
282
});
283
284
doc.on("sync", (isSynced) => {
285
console.log("Sync status changed:", isSynced);
286
});
287
288
doc.on("subdocs", ({ loaded, added, removed }) => {
289
console.log("Subdocuments changed:", { loaded, added, removed });
290
});
291
292
doc.on("destroy", () => {
293
console.log("Document destroyed");
294
});
295
```
296
297
### Advanced Document Features
298
299
Advanced functionality for specialized use cases.
300
301
```typescript { .api }
302
/**
303
* Get current state vector of the document
304
* @param doc - Document to get state from
305
* @returns State vector as Map
306
*/
307
function getState(doc: Doc): Map<number, number>;
308
309
/**
310
* Attempt garbage collection on the document
311
* @param ds - Delete set to garbage collect
312
* @param store - Struct store
313
* @param gcFilter - Filter function for garbage collection
314
*/
315
function tryGc(ds: DeleteSet, store: StructStore, gcFilter: (item: Item) => boolean): void;
316
```
317
318
**Usage Examples:**
319
320
```typescript
321
import * as Y from "yjs";
322
323
const doc = new Y.Doc();
324
325
// Get current document state
326
const state = Y.getState(doc);
327
console.log("Document state:", state);
328
329
// Custom garbage collection (advanced usage)
330
const deleteSet = Y.createDeleteSet();
331
Y.tryGc(deleteSet, doc._store, (item) => {
332
// Custom logic to determine if item should be garbage collected
333
return item.deleted && Date.now() - item.timestamp > 3600000; // 1 hour
334
});
335
```