-
Notifications
You must be signed in to change notification settings - Fork 47
/
index.js
207 lines (174 loc) · 5.81 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
/**
* External dependencies
*/
import { v4 as uuidv4 } from 'uuid';
import { noop, sample } from 'lodash';
import { createDocument } from './yjs-doc';
import { postDocToObject, updatePostDoc } from './algorithms/yjs';
/**
* WordPress dependencies
*/
import { useDispatch, useSelect } from '@wordpress/data';
import { useEffect, useRef } from '@wordpress/element';
/**
* Internal dependencies
*/
import { addCollabFilters } from './filters';
import { registerCollabFormats } from './formats';
const debug = require( 'debug' )( 'iso-editor:collab' );
/** @typedef {import('..').CollaborationSettings} CollaborationSettings */
/** @typedef {import('..').CollaborationTransport} CollaborationTransport */
/** @typedef {import('..').CollaborationTransportDocMessage} CollaborationTransportDocMessage */
/** @typedef {import('..').CollaborationTransportSelectionMessage} CollaborationTransportSelectionMessage */
/** @typedef {import('..').EditorSelection} EditorSelection */
/** @typedef {import('../../block-editor-contents').OnUpdate} OnUpdate */
export const defaultColors = [ '#4676C0', '#6F6EBE', '#9063B6', '#C3498D', '#9E6D14', '#3B4856', '#4A807A' ];
/**
* @param {object} opts - Hook options
* @param {() => object[]} opts.getBlocks - Content to initialize the Yjs doc with.
* @param {OnUpdate} opts.onRemoteDataChange - Function to update editor blocks in redux state.
* @param {CollaborationSettings} opts.settings
* @param {import('../../../store/peers/actions').setAvailablePeers} opts.setAvailablePeers
* @param {import('../../../store/peers/actions').setPeerSelection} opts.setPeerSelection
*
* @typedef IsoEditorSelection
* @property {object} selectionStart
* @property {object} selectionEnd
*/
async function initYDoc( { getBlocks, onRemoteDataChange, settings, setPeerSelection, setAvailablePeers } ) {
const { channelId, transport } = settings;
/** @type string */
const identity = uuidv4();
debug( `initYDoc (identity: ${ identity })` );
const doc = createDocument( {
identity,
applyDataChanges: updatePostDoc,
getData: postDocToObject,
/** @param {object} message */
sendMessage: ( message ) => {
debug( 'sendDocMessage', message );
transport.sendMessage( { type: 'doc', identity, message } );
},
} );
/** @param {CollaborationTransportDocMessage|CollaborationTransportSelectionMessage} data */
const onReceiveMessage = ( data ) => {
debug( 'remote change received by transport', data );
switch ( data.type ) {
case 'doc': {
doc.receiveMessage( data.message );
break;
}
case 'selection': {
setPeerSelection( data.identity, data.selection );
break;
}
}
};
doc.onRemoteDataChange( ( changes ) => {
debug( 'remote change received by ydoc', changes );
onRemoteDataChange( changes.blocks );
} );
return transport
.connect( {
user: {
identity,
name: settings.username,
color: settings.caretColor || sample( defaultColors ),
avatarUrl: settings.avatarUrl,
},
onReceiveMessage,
setAvailablePeers: ( peers ) => {
debug( 'setAvailablePeers', peers );
setAvailablePeers( peers );
},
channelId,
} )
.then( ( { isFirstInChannel } ) => {
debug( `connected (channelId: ${ channelId })` );
if ( isFirstInChannel ) {
debug( 'first in channel' );
// Fetching the blocks from redux now, after the transport has successfully connected,
// ensures that we don't initialize the Yjs doc with stale blocks.
// (This can happen if <IsolatedBlockEditor> is given an onLoad handler.)
doc.startSharing( { title: '', blocks: getBlocks() } );
} else {
doc.connect();
}
const applyChangesToYjs = ( blocks ) => {
if ( doc.getState() !== 'on' ) {
return;
}
debug( 'local changes applied to ydoc' );
doc.applyDataChanges( { blocks } );
};
const sendSelection = ( start, end ) => {
debug( 'sendSelection', start, end );
transport.sendMessage( {
type: 'selection',
identity,
selection: {
start,
end,
},
} );
};
const disconnect = () => {
transport.disconnect();
doc.disconnect();
};
window.addEventListener( 'beforeunload', () => disconnect() );
return { applyChangesToYjs, sendSelection, disconnect };
} );
}
/**
* @param {object} opts - Hook options
* @param {CollaborationSettings} [opts.settings]
*/
export default function useYjs( { settings } ) {
const onBlocksChange = useRef( noop );
const onSelectionChange = useRef( noop );
const { blocks, getBlocks, selectionStart, selectionEnd } = useSelect( ( select ) => {
return {
blocks: select( 'isolated/editor' ).getBlocks(),
getBlocks: select( 'isolated/editor' ).getBlocks,
selectionStart: select( 'core/block-editor' ).getSelectionStart(),
selectionEnd: select( 'core/block-editor' ).getSelectionEnd(),
};
}, [] );
const { setAvailablePeers, setPeerSelection, updateBlocksWithUndo } = useDispatch( 'isolated/editor' );
useEffect( () => {
if ( ! settings?.enabled ) {
return;
}
if ( ! settings.transport ) {
console.error( `Collaborative editor is disabled because a transport module wasn't provided.` );
return;
}
debug( 'registered collab formats' );
registerCollabFormats();
debug( 'added collab filters' );
addCollabFilters();
let onUnmount = noop;
initYDoc( {
onRemoteDataChange: updateBlocksWithUndo,
settings,
getBlocks,
setPeerSelection,
setAvailablePeers,
} ).then( ( { applyChangesToYjs, sendSelection, disconnect } ) => {
onUnmount = () => {
debug( 'unmount' );
disconnect();
};
onBlocksChange.current = applyChangesToYjs;
onSelectionChange.current = sendSelection;
} );
return () => onUnmount();
}, [] );
useEffect( () => {
onBlocksChange.current( blocks );
}, [ blocks ] );
useEffect( () => {
onSelectionChange.current( selectionStart, selectionEnd );
}, [ selectionStart, selectionEnd ] );
}