@norio-office/rich-text 0.3.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/types.d.ts CHANGED
@@ -1,22 +1,35 @@
1
1
  import { JSONContent } from '@tiptap/core';
2
+ import { RichTextEditorExportItemKey, RichTextEditorCode, RichTextEditorFeatureItemKey, RichTextEditorInsertMenuItemKey, RichTextEditorOutlinePlacement, RichTextEditorToolbarActionKey } from './feature-codes';
3
+ export type { RichTextEditorExportItemKey, RichTextEditorCode, RichTextEditorFeatureCode, RichTextEditorFeatureItemKey, RichTextEditorInsertMenuItemKey, RichTextEditorOutlinePlacement, RichTextEditorToolbarActionKey, } from './feature-codes';
2
4
  export type RichTextEditorProps = {
3
5
  modelValue?: JSONContent | null;
4
6
  documentName?: string;
5
7
  editable?: boolean;
6
8
  mode?: 'edit' | 'preview';
9
+ showToolbar?: boolean;
7
10
  watermark?: RichTextEditorWatermarkOptions | null;
8
11
  showOutline?: boolean;
9
- outlinePlacement?: 'left' | 'right';
12
+ outlinePlacement?: RichTextEditorOutlinePlacement;
10
13
  messages?: RichTextEditorMessages | null;
14
+ featureCodes?: RichTextEditorCode[] | null;
15
+ enabledFeatureItems?: RichTextEditorFeatureItemKey[] | null;
11
16
  enabledExportItems?: RichTextEditorExportItemKey[] | null;
12
17
  enabledInsertMenuItems?: RichTextEditorInsertMenuItemKey[] | null;
13
18
  enabledToolbarActions?: RichTextEditorToolbarActionKey[] | null;
14
19
  placeholder?: string;
15
20
  mention?: boolean;
21
+ collaboration?: RichTextEditorCollaborationOptions | null;
22
+ comments?: RichTextEditorCommentThread[] | null;
23
+ commentUser?: RichTextEditorCommentUser | null;
24
+ showComments?: boolean;
25
+ commentMention?: boolean;
16
26
  uploadImage?: RichTextEditorUploadHook | null;
17
27
  uploadVideo?: RichTextEditorUploadHook | null;
18
28
  uploadFile?: RichTextEditorUploadHook | null;
29
+ uploadCommentImage?: RichTextEditorUploadHook | null;
19
30
  onUploadError?: RichTextEditorUploadErrorHandler | null;
31
+ commentMentionProvider?: RichTextEditorCommentMentionProvider | null;
32
+ onCommentMentionSearch?: RichTextEditorCommentMentionProvider | null;
20
33
  mentionProvider?: RichTextEditorMentionProvider | null;
21
34
  onMentionSearch?: RichTextEditorMentionProvider | null;
22
35
  };
@@ -28,9 +41,31 @@ export type RichTextEditorWatermarkOptions = {
28
41
  rotate?: number;
29
42
  showInEdit?: boolean;
30
43
  };
31
- export type RichTextEditorExportItemKey = 'pdf' | 'html' | 'image' | 'print';
32
- export type RichTextEditorInsertMenuItemKey = 'image' | 'video' | 'table' | 'local-file' | 'columns' | 'highlight-block' | 'date' | 'code-block' | 'formula' | 'blockquote' | 'emoji' | 'link' | 'divider' | 'countdown' | 'markdown-import';
33
- export type RichTextEditorToolbarActionKey = 'blockquote';
44
+ export type RichTextEditorCollaborationDocument = {
45
+ getXmlFragment: (field: string) => unknown;
46
+ };
47
+ export type RichTextEditorCollaborationAwareness = {
48
+ states: Map<number, unknown>;
49
+ on: (event: 'update', callback: (...args: unknown[]) => void) => void;
50
+ setLocalStateField: (field: string, value: unknown) => void;
51
+ };
52
+ export type RichTextEditorCollaborationProvider = {
53
+ doc?: unknown;
54
+ awareness: RichTextEditorCollaborationAwareness;
55
+ };
56
+ export type RichTextEditorCollaborationUser = {
57
+ name: string;
58
+ color: string;
59
+ [key: string]: unknown;
60
+ };
61
+ export type RichTextEditorCollaborationOptions = {
62
+ document: RichTextEditorCollaborationDocument;
63
+ field?: string;
64
+ provider?: RichTextEditorCollaborationProvider | null;
65
+ user?: RichTextEditorCollaborationUser | null;
66
+ initializeContent?: boolean;
67
+ initialContent?: JSONContent | null;
68
+ };
34
69
  export type RichTextEditorMentionType = 1 | 2;
35
70
  export type RichTextEditorMentionItem = {
36
71
  id: string;
@@ -54,6 +89,7 @@ export type RichTextEditorUploadInput = {
54
89
  kind: RichTextEditorUploadKind;
55
90
  };
56
91
  export type RichTextEditorUploadResult = {
92
+ assetId?: string;
57
93
  url: string;
58
94
  name?: string;
59
95
  size?: number;
@@ -68,15 +104,105 @@ export type RichTextEditorUploadErrorPayload = {
68
104
  error: unknown;
69
105
  };
70
106
  export type RichTextEditorUploadErrorHandler = (payload: RichTextEditorUploadErrorPayload) => void;
107
+ export type RichTextEditorCommentUser = {
108
+ id: string;
109
+ name: string;
110
+ avatar?: string;
111
+ color?: string;
112
+ [key: string]: unknown;
113
+ };
114
+ export type RichTextEditorCommentImage = RichTextEditorUploadResult;
115
+ export type RichTextEditorCommentMentionItem = RichTextEditorMentionItem;
116
+ export type RichTextEditorCommentMentionProviderPayload = RichTextEditorMentionProviderPayload & {
117
+ threadId?: string;
118
+ commentId?: string;
119
+ parentId?: string;
120
+ content: string;
121
+ };
122
+ export type RichTextEditorCommentMentionProvider = (payload: RichTextEditorCommentMentionProviderPayload) => RichTextEditorCommentMentionItem[] | Promise<RichTextEditorCommentMentionItem[]>;
123
+ export type RichTextEditorCommentItem = {
124
+ id: string;
125
+ parentId?: string;
126
+ content: string;
127
+ author: RichTextEditorCommentUser;
128
+ createdAt: string;
129
+ updatedAt?: string;
130
+ images?: RichTextEditorCommentImage[];
131
+ mentions?: RichTextEditorCommentMentionItem[];
132
+ };
133
+ export type RichTextEditorCommentThread = {
134
+ id: string;
135
+ anchorText?: string;
136
+ status?: 'open' | 'resolved';
137
+ comments: RichTextEditorCommentItem[];
138
+ };
139
+ export type RichTextEditorCommentCreatePayload = {
140
+ threadId: string;
141
+ commentId: string;
142
+ anchorText: string;
143
+ content: string;
144
+ images: RichTextEditorCommentImage[];
145
+ mentions: RichTextEditorCommentMentionItem[];
146
+ author: RichTextEditorCommentUser;
147
+ createdAt: string;
148
+ };
149
+ export type RichTextEditorCommentReplyPayload = {
150
+ threadId: string;
151
+ commentId: string;
152
+ parentId?: string;
153
+ targetCommentId?: string;
154
+ targetUserId?: string;
155
+ targetUserName?: string;
156
+ content: string;
157
+ images: RichTextEditorCommentImage[];
158
+ mentions: RichTextEditorCommentMentionItem[];
159
+ author: RichTextEditorCommentUser;
160
+ createdAt: string;
161
+ };
162
+ export type RichTextEditorCommentUpdatePayload = {
163
+ threadId: string;
164
+ commentId: string;
165
+ content: string;
166
+ images?: RichTextEditorCommentImage[];
167
+ mentions: RichTextEditorCommentMentionItem[];
168
+ author?: RichTextEditorCommentUser;
169
+ updatedAt: string;
170
+ };
171
+ export type RichTextEditorCommentSubmitPayload = {
172
+ action: 'create' | 'reply' | 'update';
173
+ threadId: string;
174
+ commentId: string;
175
+ targetCommentId?: string;
176
+ targetUserId?: string;
177
+ targetUserName?: string;
178
+ content: string;
179
+ images?: RichTextEditorCommentImage[];
180
+ mentions: RichTextEditorCommentMentionItem[];
181
+ author?: RichTextEditorCommentUser;
182
+ createdAt?: string;
183
+ updatedAt?: string;
184
+ };
185
+ export type RichTextEditorCommentDeletePayload = {
186
+ threadId: string;
187
+ commentId?: string;
188
+ };
189
+ export type RichTextEditorCommentResolvePayload = {
190
+ threadId: string;
191
+ resolved: boolean;
192
+ };
71
193
  export type RichTextEditorImagePayload = {
194
+ assetId?: string;
72
195
  src: string;
73
196
  alt?: string;
74
197
  name?: string;
75
198
  description?: string;
199
+ descriptionVisible?: boolean;
76
200
  link?: string;
201
+ linkTarget?: '_blank' | '_self';
77
202
  rotation?: number;
78
203
  };
79
204
  export type RichTextEditorVideoPayload = {
205
+ assetId?: string;
80
206
  src: string;
81
207
  name?: string;
82
208
  description?: string;
@@ -86,6 +212,7 @@ export type RichTextEditorVideoPayload = {
86
212
  height?: number;
87
213
  };
88
214
  export type RichTextEditorFilePayload = {
215
+ assetId?: string;
89
216
  url: string;
90
217
  name: string;
91
218
  displayMode?: 'text' | 'card' | 'preview';
@@ -94,6 +221,7 @@ export type RichTextEditorFilePayload = {
94
221
  height?: number;
95
222
  };
96
223
  export type RichTextEditorLocalFilePayload = {
224
+ assetId?: string;
97
225
  url: string;
98
226
  name: string;
99
227
  size?: number;
@@ -138,6 +266,7 @@ export type RichTextEditorInstance = {
138
266
  getActiveOutlinePos: () => number | null;
139
267
  focusOutlineItem: (pos: number) => boolean;
140
268
  onOutlineChange: (handler: RichTextEditorOutlineChangeHandler) => () => void;
269
+ focusCommentThread: (threadId: string) => boolean;
141
270
  };
142
271
  export type OfficeIconProps = {
143
272
  name: string;
@@ -0,0 +1,2 @@
1
+ export declare const colorGrid: readonly [readonly ["#FFFFFF", "#16181D", "#4C5563", "#2F6BFF", "#1DA1F2", "#19B36B", "#F2573F", "#FF8B24", "#F7C200", "#9333EA"], readonly ["#F4F5F7", "#D9DEE7", "#C2C9D6", "#DDE9FF", "#D6EFFB", "#D8F4E5", "#FDE1DD", "#FFE9D2", "#FFF3C4", "#F1D8FF"], readonly ["#E6E8EC", "#BFC6D4", "#A8B1C4", "#BED3FF", "#B9E5F8", "#B8ECD2", "#F9C3BC", "#FFD6AC", "#FFE58C", "#E4BCFF"], readonly ["#D1D5DB", "#9CA3AF", "#6B7280", "#8BB2FF", "#86D3F3", "#7DDEAB", "#F69B8F", "#FFBB79", "#F9D45C", "#CE97FF"], readonly ["#9AA4B2", "#4B5563", "#374151", "#4C7DFF", "#2BAFE3", "#22C55E", "#EF6B59", "#F59E0B", "#D4A500", "#A855F7"], readonly ["#6B7280", "#111827", "#1F2937", "#1D4ED8", "#1473C5", "#15803D", "#DC2626", "#C56A06", "#A16207", "#6B21A8"]];
2
+ export declare const standardColors: string[];
@@ -0,0 +1,13 @@
1
+ export declare const dividerDefaultColor = "#dfe5ee";
2
+ export declare const dividerStyles: readonly [{
3
+ readonly value: "solid";
4
+ readonly label: "实线";
5
+ }, {
6
+ readonly value: "dashed";
7
+ readonly label: "虚线";
8
+ }, {
9
+ readonly value: "dotted";
10
+ readonly label: "点状线";
11
+ }];
12
+ export declare function normalizeDividerStyle(value: unknown): "dashed" | "dotted" | "solid";
13
+ export declare function normalizeDividerColor(value: unknown): string | null;
@@ -0,0 +1,44 @@
1
+ export type TableThemeColors = {
2
+ header: string;
3
+ odd: string;
4
+ even: string;
5
+ };
6
+ export declare const tableThemePresets: readonly [{
7
+ readonly id: "blue";
8
+ readonly name: "经典蓝";
9
+ readonly header: "#1670d2";
10
+ readonly odd: "#e8f2ff";
11
+ readonly even: "#ffffff";
12
+ }, {
13
+ readonly id: "green";
14
+ readonly name: "清新绿";
15
+ readonly header: "#21864b";
16
+ readonly odd: "#e7f5ec";
17
+ readonly even: "#ffffff";
18
+ }, {
19
+ readonly id: "purple";
20
+ readonly name: "优雅紫";
21
+ readonly header: "#7950c5";
22
+ readonly odd: "#f0eafa";
23
+ readonly even: "#ffffff";
24
+ }, {
25
+ readonly id: "orange";
26
+ readonly name: "活力橙";
27
+ readonly header: "#c75312";
28
+ readonly odd: "#fff0e5";
29
+ readonly even: "#ffffff";
30
+ }, {
31
+ readonly id: "pink";
32
+ readonly name: "玫瑰粉";
33
+ readonly header: "#c9346d";
34
+ readonly odd: "#fceaf1";
35
+ readonly even: "#ffffff";
36
+ }, {
37
+ readonly id: "gray";
38
+ readonly name: "简约灰";
39
+ readonly header: "#586574";
40
+ readonly odd: "#edf0f3";
41
+ readonly even: "#ffffff";
42
+ }];
43
+ export declare function normalizeTableTheme(value: unknown): TableThemeColors | null;
44
+ export declare function getTableThemeHTMLAttributes(value: unknown): Record<string, string>;
package/docs/usage.md CHANGED
@@ -13,6 +13,7 @@ import { RichTextEditor } from '@norio-office/rich-text'
13
13
  ## Main Capabilities
14
14
 
15
15
  - rich text editing with a built-in toolbar UI
16
+ - optional Yjs collaboration mode with the same component API
16
17
  - async `@` mention candidates for people and documents
17
18
  - export to PDF, image, and HTML through instance methods
18
19
  - external upload integration for image, video, and file insertion
@@ -44,8 +45,38 @@ async function handleMentionSearch(payload: RichTextEditorMentionProviderPayload
44
45
 
45
46
  `type: 1` means person and `type: 2` means document. The editor inserts a mention only after the user clicks `提及`.
46
47
 
48
+ ## Collaboration
47
49
 
48
- ## Bundled Yjs Server
50
+ Use the optional `collaboration` prop to bind the editor to a Yjs document.
51
+
52
+ ```ts
53
+ import * as Y from 'yjs'
54
+ import { WebsocketProvider } from 'y-websocket'
55
+
56
+ const ydoc = new Y.Doc()
57
+ const provider = new WebsocketProvider('ws://localhost:1234', 'office-word-demo', ydoc)
58
+ ```
59
+
60
+ ```vue
61
+ <RichTextEditor
62
+ v-model="content"
63
+ :collaboration="{
64
+ document: ydoc,
65
+ field: 'content',
66
+ provider,
67
+ user: {
68
+ name: '张三',
69
+ color: '#3b82f6',
70
+ },
71
+ }"
72
+ />
73
+ ```
74
+
75
+ When `collaboration` is omitted, the editor stays in normal single-user mode. When `provider + user` are passed, the editor also renders remote cursors and remote selections.
76
+
77
+ In collaboration mode, the shared Yjs fragment is authoritative. The editor does not write `modelValue` into an empty collaborative fragment by default. If a brand-new room needs initial business content, the host must first confirm this client owns initialization, then pass `initializeContent: true` and `initialContent` inside the `collaboration` object. Do not use those flags when the backend already has a Yjs snapshot.
78
+
79
+ ## Bundled Yjs Server
49
80
 
50
81
  The npm package also ships a minimal websocket server example in `yjs/`.
51
82
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@norio-office/rich-text",
3
- "version": "0.3.0",
3
+ "version": "0.7.0",
4
4
  "description": "A reusable Vue 3 rich text editor component built with Tiptap 3.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.umd.cjs",
@@ -18,6 +18,7 @@
18
18
  "dist",
19
19
  "README.md",
20
20
  "docs",
21
+ "yjs",
21
22
  "LICENSE"
22
23
  ],
23
24
  "sideEffects": [
@@ -39,7 +40,10 @@
39
40
  "@tiptap/core": "^3.22.1",
40
41
  "@tiptap/extension-code-block": "^3.22.1",
41
42
  "@tiptap/extension-code-block-lowlight": "^3.22.1",
43
+ "@tiptap/extension-collaboration": "^3.22.2",
44
+ "@tiptap/extension-collaboration-caret": "^3.22.2",
42
45
  "@tiptap/extension-font-family": "^3.22.1",
46
+ "@tiptap/extension-horizontal-rule": "^3.22.1",
43
47
  "@tiptap/extension-placeholder": "^3.22.1",
44
48
  "@tiptap/extension-subscript": "^3.22.1",
45
49
  "@tiptap/extension-superscript": "^3.22.1",
@@ -54,8 +58,11 @@
54
58
  "@tiptap/pm": "^3.22.1",
55
59
  "@tiptap/starter-kit": "^3.22.1",
56
60
  "@tiptap/vue-3": "^3.22.1",
61
+ "@tiptap/y-tiptap": "^3.0.2",
57
62
  "lowlight": "^3.3.0",
58
- "vue": "^3.5.0"
63
+ "vue": "^3.5.0",
64
+ "y-prosemirror": "^1.2.6",
65
+ "yjs": "^13.6.30"
59
66
  },
60
67
  "dependencies": {
61
68
  "html2canvas": "^1.4.1",
package/yjs/README.md ADDED
@@ -0,0 +1,63 @@
1
+ # Yjs Server Example
2
+
3
+ This folder is shipped with the npm package so consumers can run a minimal `y-websocket`-compatible Yjs server without adding another backend dependency.
4
+
5
+ ## Files
6
+
7
+ - `index.js`: minimal websocket server compatible with `y-websocket`
8
+ - `package.json`: runtime dependencies and `npm run start`
9
+
10
+ ## Start
11
+
12
+ ```bash
13
+ cd yjs
14
+ npm install
15
+ npm run start
16
+ ```
17
+
18
+ By default the server listens on `ws://0.0.0.0:1234`.
19
+
20
+ To override host or port:
21
+
22
+ ```bash
23
+ HOST=0.0.0.0 PORT=1234 npm run start
24
+ ```
25
+
26
+ PowerShell:
27
+
28
+ ```powershell
29
+ $env:HOST="0.0.0.0"
30
+ $env:PORT="1234"
31
+ npm run start
32
+ ```
33
+
34
+ ## Client Link Example
35
+
36
+ ```ts
37
+ import * as Y from 'yjs'
38
+ import { WebsocketProvider } from 'y-websocket'
39
+
40
+ const ydoc = new Y.Doc()
41
+ const provider = new WebsocketProvider('ws://127.0.0.1:1234', 'office-word-demo', ydoc)
42
+ ```
43
+
44
+ ```vue
45
+ <RichTextEditor
46
+ v-model="content"
47
+ :collaboration="{
48
+ document: ydoc,
49
+ field: 'content',
50
+ provider,
51
+ user: {
52
+ name: '张三',
53
+ color: '#3b82f6',
54
+ },
55
+ }"
56
+ />
57
+ ```
58
+
59
+ ## Notes
60
+
61
+ - all collaborators must use the same websocket address and the same room name
62
+ - if clients are on different machines, do not use `127.0.0.1`; use the server's real LAN or public address
63
+ - this sample server is in-memory only; document state is lost after restart
package/yjs/index.js ADDED
@@ -0,0 +1,224 @@
1
+ import http from 'node:http'
2
+
3
+ import * as decoding from 'lib0/decoding'
4
+ import * as encoding from 'lib0/encoding'
5
+ import * as awarenessProtocol from 'y-protocols/awareness'
6
+ import * as syncProtocol from 'y-protocols/sync'
7
+ import WebSocket, { WebSocketServer } from 'ws'
8
+ import * as Y from 'yjs'
9
+
10
+ const host = process.env.HOST || '0.0.0.0'
11
+ const port = Number(process.env.PORT || 1234)
12
+
13
+ const messageSync = 0
14
+ const messageAwareness = 1
15
+ const pingTimeout = 30000
16
+
17
+ const docs = new Map()
18
+
19
+ function getDoc(name) {
20
+ const existing = docs.get(name)
21
+ if (existing) {
22
+ return existing
23
+ }
24
+
25
+ const doc = new Y.Doc()
26
+ const awareness = new awarenessProtocol.Awareness(doc)
27
+ const conns = new Map()
28
+
29
+ awareness.setLocalState(null)
30
+
31
+ doc.on('update', (update) => {
32
+ const encoder = encoding.createEncoder()
33
+ encoding.writeVarUint(encoder, messageSync)
34
+ syncProtocol.writeUpdate(encoder, update)
35
+ const message = encoding.toUint8Array(encoder)
36
+
37
+ conns.forEach((_, conn) => {
38
+ send(conn, message)
39
+ })
40
+ })
41
+
42
+ awareness.on('update', ({ added, updated, removed }, conn) => {
43
+ const changedClients = added.concat(updated, removed)
44
+
45
+ if (conn) {
46
+ const controlledIds = conns.get(conn)
47
+ if (controlledIds) {
48
+ added.forEach((id) => controlledIds.add(id))
49
+ removed.forEach((id) => controlledIds.delete(id))
50
+ }
51
+ }
52
+
53
+ const encoder = encoding.createEncoder()
54
+ encoding.writeVarUint(encoder, messageAwareness)
55
+ encoding.writeVarUint8Array(
56
+ encoder,
57
+ awarenessProtocol.encodeAwarenessUpdate(awareness, changedClients),
58
+ )
59
+
60
+ const message = encoding.toUint8Array(encoder)
61
+ conns.forEach((_, ws) => {
62
+ send(ws, message)
63
+ })
64
+ })
65
+
66
+ const entry = { name, doc, awareness, conns }
67
+ docs.set(name, entry)
68
+ return entry
69
+ }
70
+
71
+ function removeDocIfEmpty(entry) {
72
+ if (entry.conns.size === 0) {
73
+ entry.doc.destroy()
74
+ docs.delete(entry.name)
75
+ }
76
+ }
77
+
78
+ function closeConn(entry, conn) {
79
+ const controlledIds = entry.conns.get(conn)
80
+
81
+ if (controlledIds) {
82
+ entry.conns.delete(conn)
83
+ awarenessProtocol.removeAwarenessStates(
84
+ entry.awareness,
85
+ Array.from(controlledIds),
86
+ null,
87
+ )
88
+ }
89
+
90
+ try {
91
+ conn.close()
92
+ } catch {
93
+ // ignore close failures
94
+ }
95
+
96
+ removeDocIfEmpty(entry)
97
+ console.log(`[disconnect] room=${entry.name} clients=${entry.conns.size}`)
98
+ }
99
+
100
+ function send(conn, message) {
101
+ if (conn.readyState !== WebSocket.OPEN && conn.readyState !== WebSocket.CONNECTING) {
102
+ try {
103
+ conn.close()
104
+ } catch {
105
+ // ignore close failures
106
+ }
107
+ return
108
+ }
109
+
110
+ conn.send(message, (error) => {
111
+ if (error) {
112
+ try {
113
+ conn.close()
114
+ } catch {
115
+ // ignore close failures
116
+ }
117
+ }
118
+ })
119
+ }
120
+
121
+ function setupWSConnection(conn, req) {
122
+ const docName = (req.url || '/').slice(1).split('?')[0] || 'default'
123
+ const entry = getDoc(docName)
124
+
125
+ entry.conns.set(conn, new Set())
126
+ conn.binaryType = 'arraybuffer'
127
+
128
+ conn.on('message', (message) => {
129
+ try {
130
+ const decoder = decoding.createDecoder(new Uint8Array(message))
131
+ const encoder = encoding.createEncoder()
132
+ const messageType = decoding.readVarUint(decoder)
133
+
134
+ switch (messageType) {
135
+ case messageSync:
136
+ encoding.writeVarUint(encoder, messageSync)
137
+ syncProtocol.readSyncMessage(decoder, encoder, entry.doc, conn)
138
+ if (encoding.length(encoder) > 1) {
139
+ send(conn, encoding.toUint8Array(encoder))
140
+ }
141
+ break
142
+ case messageAwareness:
143
+ awarenessProtocol.applyAwarenessUpdate(
144
+ entry.awareness,
145
+ decoding.readVarUint8Array(decoder),
146
+ conn,
147
+ )
148
+ break
149
+ default:
150
+ break
151
+ }
152
+ } catch (error) {
153
+ console.error('[message-error]', error)
154
+ }
155
+ })
156
+
157
+ let pongReceived = true
158
+ const pingInterval = setInterval(() => {
159
+ if (!pongReceived) {
160
+ clearInterval(pingInterval)
161
+ closeConn(entry, conn)
162
+ return
163
+ }
164
+
165
+ pongReceived = false
166
+ try {
167
+ conn.ping()
168
+ } catch {
169
+ clearInterval(pingInterval)
170
+ closeConn(entry, conn)
171
+ }
172
+ }, pingTimeout)
173
+
174
+ conn.on('pong', () => {
175
+ pongReceived = true
176
+ })
177
+
178
+ conn.on('close', () => {
179
+ clearInterval(pingInterval)
180
+ closeConn(entry, conn)
181
+ })
182
+
183
+ conn.on('error', (error) => {
184
+ console.error('[socket-error]', error)
185
+ })
186
+
187
+ const syncEncoder = encoding.createEncoder()
188
+ encoding.writeVarUint(syncEncoder, messageSync)
189
+ syncProtocol.writeSyncStep1(syncEncoder, entry.doc)
190
+ send(conn, encoding.toUint8Array(syncEncoder))
191
+
192
+ const awarenessStates = entry.awareness.getStates()
193
+ if (awarenessStates.size > 0) {
194
+ const awarenessEncoder = encoding.createEncoder()
195
+ encoding.writeVarUint(awarenessEncoder, messageAwareness)
196
+ encoding.writeVarUint8Array(
197
+ awarenessEncoder,
198
+ awarenessProtocol.encodeAwarenessUpdate(
199
+ entry.awareness,
200
+ Array.from(awarenessStates.keys()),
201
+ ),
202
+ )
203
+ send(conn, encoding.toUint8Array(awarenessEncoder))
204
+ }
205
+
206
+ console.log(`[connect] room=${docName} clients=${entry.conns.size}`)
207
+ }
208
+
209
+ const server = http.createServer((_req, res) => {
210
+ res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' })
211
+ res.end('ok')
212
+ })
213
+
214
+ const wss = new WebSocketServer({ noServer: true })
215
+
216
+ server.on('upgrade', (request, socket, head) => {
217
+ wss.handleUpgrade(request, socket, head, (ws) => {
218
+ setupWSConnection(ws, request)
219
+ })
220
+ })
221
+
222
+ server.listen(port, host, () => {
223
+ console.log(`yjs websocket server running at ws://${host}:${port}`)
224
+ })
@@ -0,0 +1,14 @@
1
+ {
2
+ "name": "@norio-office/rich-text-yjs-server",
3
+ "private": true,
4
+ "type": "module",
5
+ "scripts": {
6
+ "start": "node index.js"
7
+ },
8
+ "dependencies": {
9
+ "lib0": "^0.2.102",
10
+ "ws": "^8.18.0",
11
+ "y-protocols": "^1.0.6",
12
+ "yjs": "^13.6.30"
13
+ }
14
+ }