-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathDocument.js
467 lines (426 loc) · 13.4 KB
/
Document.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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
import React, { Component } from 'react';
import CopyToClipboard from 'react-copy-to-clipboard';
import withOfflineState from 'react-offline-hoc';
import classNames from 'classnames';
import AppBar from '@material-ui/core/AppBar';
import ChevronLeftIcon from '@material-ui/icons/ChevronLeft';
import ChevronRightIcon from '@material-ui/icons/ChevronRight';
import Drawer from '@material-ui/core/Drawer';
import Divider from '@material-ui/core/Divider';
import IconButton from '@material-ui/core/IconButton';
import MenuIcon from '@material-ui/icons/Menu';
import SaveIcon from '@material-ui/icons/Save';
import Tabs from '@material-ui/core/Tabs';
import Tab from '@material-ui/core/Tab';
import Tooltip from '@material-ui/core/Tooltip';
import { withStyles } from '@material-ui/core/styles';
import FileCopy from '@material-ui/icons/FileCopy';
import DiffMatchPatch from 'diff-match-patch';
import tinydate from 'tinydate';
import { saveAs } from 'file-saver';
import { createAutomergeWorker } from '@wirelineio/automerge-worker';
import Collaborators from '../components/Collaborators';
import Editor from '../components/Editor';
import Preview from '../components/EditorPreview';
import History from '../components/History';
import Layout from '../components/Layout';
import { withSwarm } from '../p2p/swarm';
const drawerWidth = 300;
const styles = theme => ({
root: {
flex: 1,
display: 'flex',
height: '100%',
width: '100%'
},
editorContainer: {
flex: 1,
display: 'flex',
width: '100%',
justifyContent: 'flex-start',
backgroundColor: theme.palette.background.paper
},
title: {
margin: `${theme.spacing.unit}px ${theme.spacing.unit * 4}px 0 ${theme
.spacing.unit * 2}px`
},
items: {
overflow: 'auto',
flex: 1
},
layoutExtraIcons: {
display: 'inline-flex'
},
tabHeader: {
backgroundColor: theme.palette.grey[200]
},
asideBar: {
zIndex: theme.zIndex.drawer + 1,
transition: theme.transitions.create(['width', 'margin'], {
easing: theme.transitions.easing.sharp,
duration: theme.transitions.duration.leavingScreen
})
},
asideBarShift: {
width: `calc(100% - ${drawerWidth}px)`,
transition: theme.transitions.create(['width', 'margin'], {
easing: theme.transitions.easing.sharp,
duration: theme.transitions.duration.enteringScreen
})
},
hide: {
display: 'none'
},
drawer: {
width: drawerWidth,
flexShrink: 0
},
drawerContent: {
overflow: 'hidden',
width: drawerWidth,
backgroundColor: theme.palette.grey[200],
borderLeft: `1px solid ${theme.palette.grey[500]}`,
maxWidth: `${drawerWidth}px`,
'& > header': {
height: '100%'
}
},
drawerOpen: {
transition: theme.transitions.create('width', {
easing: theme.transitions.easing.sharp,
duration: theme.transitions.duration.enteringScreen
})
},
drawerClose: {
transition: theme.transitions.create('width', {
easing: theme.transitions.easing.sharp,
duration: theme.transitions.duration.leavingScreen
}),
overflowX: 'hidden',
width: theme.spacing.unit * 7 + 1,
[theme.breakpoints.up('sm')]: {
width: theme.spacing.unit * 9 + 1
}
},
drawerHeader: {
display: 'flex',
alignItems: 'center',
...theme.mixins.toolbar,
justifyContent: 'flex-start'
},
content: {
flexGrow: 1,
transition: theme.transitions.create('margin', {
easing: theme.transitions.easing.sharp,
duration: theme.transitions.duration.leavingScreen
})
},
contentShift: {
transition: theme.transitions.create('margin', {
easing: theme.transitions.easing.easeOut,
duration: theme.transitions.duration.enteringScreen
}),
marginRight: 0
}
});
const stamp = tinydate('{HH}:{mm}:{ss}');
class Document extends Component {
constructor() {
super();
this.dmp = new DiffMatchPatch();
this.original = undefined;
this.offlineChanges = [];
this.amWorker = createAutomergeWorker();
this.incomingOperationChange = this.incomingOperationChange.bind(this);
this.state = {
documentTitle: 'p2pdoc',
attachedEvents: false,
peerValue: {},
text: '',
localHistory: [],
collaborators: new Set(),
swarmReady: false,
tabValue: 0,
openDrawer: false
};
}
static getDerivedStateFromProps({ swarm }) {
if (swarm !== null) {
return {
swarmReady: true
};
}
return null;
}
async incomingOperationChange(data) {
const { username, operation } = data;
if (username === this.props.username) return;
console.log('INCOMING OPERATION');
console.log('new operation from:', username);
console.log('new operation content:', operation);
if (operation.original) {
await this.amWorker.createDocumentFromChanges(
this.props.username,
this.state.documentTitle,
operation.peerValue
);
const text = await this.amWorker.getDocumentContent(
this.state.documentTitle
);
this.setState(prevState => ({
original: operation.original ? operation.original : prevState.original,
text,
localHistory: [...this.state.localHistory, operation.diff || '']
}));
} else {
this.amWorker.applyChanges(
this.state.documentTitle,
operation.peerValue,
{ local: false, notify: false }
);
}
}
componentDidMount() {
const { swarm, username } = this.props;
if (!swarm) return;
if (this.state.attachedEvents) return;
this.amWorker.on(
'changes',
({ documentId, changes, content, data: { notify, local } }) => {
if (!local) {
// Note(dk): INCOMING OPERATION update
// This is a like the continuation of the work done in `incomingOperationChange`.
// Since amWorker is async (event-based), we need this hook to get notified from succesfully
// applied operations/changes.
this.setState(prevState => ({
text: content
}));
}
if (!notify) return;
console.log('SENDING OPERATION', changes);
// NOTE(dk): here we are sharing with our peers changes we have made locally.
swarm.writeOperation({
notify,
local,
peerValue: changes,
username,
diff: changes[0].message
});
}
);
swarm.on('join', data => {
console.log('NEW COLLABORATOR', data);
const { username } = data;
this.setState(({ collaborators }) => ({
collaborators: new Set(collaborators).add(username)
}));
});
swarm.on('operation', this.incomingOperationChange);
this.setState({ attachedEvents: true });
}
componentWillUnmount() {
const { swarm } = this.props;
if (swarm !== null) swarm.removeAllListeners('operation');
}
updatePeerValue = async val => {
const { swarm, username } = this.props;
const { text } = val;
// NOTE(dk): this portion should run only once on the creator doc. I choose to use a combination of a
// local value as a safeguard and something that should be unique for the creator... but I'm not sure
// of the last one.
if (!this.state.original && swarm.db.local.secretKey) {
console.log('ORIGINAL COPY');
// document creation
const { changes } = await this.amWorker.createDocument(
username,
this.state.documentTitle
);
this.doc = changes;
this.setState({ original: true });
swarm.writeOperation({
peerValue: changes,
username,
original: true,
diff: `${username} created the doc - ${stamp(new Date(Date.now()))}`
});
}
/***************************** Update text using diff_main ********/
const diff = this.dmp.diff_main(this.state.text, text);
this.dmp.diff_cleanupSemantic(diff);
const patches = this.dmp.patch_make(this.state.text, diff);
patches.forEach(patch => {
let idx = patch.start1;
let historyMessage = '';
patch.diffs.forEach(([operation, changeText]) => {
switch (operation) {
case 1: // Insertion
historyMessage = `${username} added (${changeText}) - ${stamp(
new Date(Date.now())
)}`;
console.log(historyMessage);
this.amWorker.applyOperations(
this.state.documentTitle,
[{ type: 'insert', rangeOffset: idx, text: changeText }],
{ notify: true, local: true }
);
idx += changeText.length;
break;
case 0: // No Change
idx += changeText.length;
break;
case -1: // Deletion
historyMessage = `${username} removed (${changeText}) - ${stamp(
new Date(Date.now())
)}`;
this.amWorker.applyOperations(
this.state.documentTitle,
[
{
type: 'delete',
rangeOffset: idx,
rangeLength: changeText.length
}
],
{ notify: true, local: true }
);
break;
default:
break;
}
// Local update
this.setState({
text,
localHistory: [...this.state.localHistory, historyMessage || '']
});
});
});
};
handleTabChange = (event, value) => {
this.setState({ tabValue: value });
};
sharedLink = () => {
const { swarm } = this.props;
const { protocol, host, pathname } = window.location;
return `${protocol}//${host}${pathname}#/${swarm.db.key.toString('hex')}`;
};
handleDrawerOpen = () => {
this.setState({ openDrawer: true });
};
handleDrawerClose = () => {
this.setState({ openDrawer: false });
};
saveMe = () => {
const blob = new Blob([this.state.text], {
type: 'text/plain;charset=utf-8'
});
saveAs(blob, 'caracara.md');
};
render() {
const { classes, username, hasDraftId } = this.props;
const {
attachedEvents,
tabValue,
localHistory,
collaborators,
openDrawer
} = this.state;
return (
<Layout
username={username}
titleBar={
attachedEvents && (
<div className={classes.layoutExtraIcons}>
<Tooltip title="Download your Doc">
<IconButton color="inherit" onClick={this.saveMe}>
<SaveIcon />
</IconButton>
</Tooltip>
<CopyToClipboard text={this.sharedLink()}>
<Tooltip title="Share your Doc">
<IconButton disabled={!attachedEvents} color="inherit">
<FileCopy />
</IconButton>
</Tooltip>
</CopyToClipboard>
<IconButton
color="inherit"
aria-label="Open drawer"
onClick={this.handleDrawerOpen}
className={classNames({
[classes.hide]: this.state.openDrawer
})}
>
<MenuIcon />
</IconButton>
</div>
)
}
>
{attachedEvents && (
<div
className={classNames(classes.root, classes.content, {
[classes.contentShift]: openDrawer
})}
>
<div className={classes.editorContainer}>
<Editor
text={this.state.text}
updatePeerValue={this.updatePeerValue}
isAuthor={!hasDraftId}
/>
<Preview text={this.state.text} />
</div>
<aside>
<Drawer
variant="persistent"
anchor="right"
open={openDrawer}
elevation={0}
classes={{ paper: classes.drawerContent }}
className={classNames(classes.drawer, {
[classes.drawerOpen]: this.state.open,
[classes.drawerClose]: !this.state.open
})}
>
<div className={classes.drawerHeader}>
<IconButton onClick={this.handleDrawerClose}>
{!openDrawer ? <ChevronLeftIcon /> : <ChevronRightIcon />}
</IconButton>
</div>
<Divider />
<AppBar
position="static"
classes={{ root: classes.tabHeader }}
className={classNames({
[classes.asideBarShift]: this.state.open
})}
elevation={0}
>
<Tabs
value={tabValue}
onChange={this.handleTabChange}
textColor="primary"
indicatorColor="primary"
>
<Tab label="History" />
<Tab label="Collaborators" />
</Tabs>
{tabValue === 0 && (
<History history={localHistory} classes={classes} />
)}
{tabValue === 1 && (
<Collaborators
users={Array.from(collaborators)}
classes={classes}
/>
)}
</AppBar>
</Drawer>
</aside>
</div>
)}
</Layout>
);
}
}
export default withOfflineState(withSwarm(withStyles(styles)(Document)));