-
Notifications
You must be signed in to change notification settings - Fork 52
/
Copy pathEditor.js
566 lines (485 loc) · 18.5 KB
/
Editor.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
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
import React from 'react/addons'
import classNames from 'classnames'
import Spinner from 'react-spinkit'
import _ from 'lodash'
import EditorActions from '../flux/EditorActions'
import EditorStore from '../flux/EditorStore'
import EditorLine from './EditorLine'
import Cursor from './Cursor'
import DebugEditor from './DebugEditor'
import { BASE_CHAR, EOF } from '../core/RichText'
import { elementPosition } from '../core/dom'
import SwarmClientMixin from './SwarmClientMixin'
import TextReplicaMixin from './TextReplicaMixin'
import SharedCursorMixin from './SharedCursorMixin'
import TextInput from './TextInput'
import {ATTR, hasAttributeFor} from '../core/attributes'
import { charEq, linesEq, lineContainingChar } from '../core/EditorCommon'
import ReactUtils from '../core/ReactUtils'
import { sourceOf } from '../core/replica'
import TextFontMetrics from '../core/TextFontMetrics'
require('../styles/internal.less')
const T = React.PropTypes
export default React.createClass({
propTypes: {
id: T.string.isRequired,
eventEmitter: T.object.isRequired,
fonts: T.shape({
regular: T.object,
bold: T.object,
boldItalic: T.object,
italic: T.object
}),
fontSize: T.number.isRequired,
minFontSize: T.number.isRequired,
unitsPerEm: T.number.isRequired,
width: T.number.isRequired,
margin: T.shape({
horizontal: T.number,
vertical: T.number
}).isRequired,
userId: T.string.isRequired,
userName: T.string,
cursorColorSpace: T.arrayOf(T.string), // TODO allow it to be a function as well
initialFocus: T.bool,
wsPort: T.number,
renderOptimizations: T.bool,
debugEditor: T.bool,
showErrorNotification: T.bool,
errorNotification: T.string
},
mixins: [SwarmClientMixin, TextReplicaMixin, SharedCursorMixin],
getDefaultProps() {
return {
initialFocus: true,
// The default cursor color space is a less harsh variation of the 11 Boynton colors:
// http://alumni.media.mit.edu/~wad/color/palette.html
// See also:
// http://stackoverflow.com/a/4382138/430128
// https://eleanormaclure.files.wordpress.com/2011/03/colour-coding.pdf
cursorColorSpace: [
'rgb(29, 105, 20)', // green
'rgb(129, 38, 192)', // purple,
'rgb(42, 75, 215)', // blue
'rgb(41, 208, 208)', // cyan
'rgb(173, 35, 35)', // red
'rgb(255, 146, 51)', // orange
'rgb(129, 197, 122)', // light green
'rgb(157, 175, 255)', // light blue
'rgb(255, 205, 243)', // pink
'rgb(255, 238, 51)', // yellow
'rgb(129, 74, 25)' // brown
],
renderOptimizations: true,
debugEditor: false,
showErrorNotification: true,
errorNotification: 'There was an unexpected error. You may need to refresh the page.'
}
},
getInitialState() {
return EditorStore.getState()
},
componentWillMount() {
TextFontMetrics.setConfig(this.props)
this._createReplica()
EditorActions.initialize(this.props, this.replica)
},
componentWillReceiveProps(nextProps) {
TextFontMetrics.setConfig(this.props)
EditorActions.initialize(nextProps, this.replica)
if(this.props.fontSize !== nextProps.fontSize || this.props.width !== nextProps.width) {
EditorActions.reflow()
}
},
componentDidMount() {
this.clickCount = 0
EditorStore.listen(this.onStateChange)
},
shouldComponentUpdate(nextProps, nextState) {
if(!nextProps.renderOptimizations) {
return true
}
// for better performance make sure objects are immutable so that we can do reference equality checks
let stateEqual = this.state.loaded === nextState.loaded
&& this.state.focus === nextState.focus
&& this.state.positionEolStart == nextState.positionEolStart
&& this.state.selectionActive == nextState.selectionActive
&& this.state.cursorMotion == nextState.cursorMotion
&& this.state.error === nextState.error
&& ReactUtils.deepEquals(this.state.position, nextState.position, charEq)
&& ReactUtils.deepEquals(this.state.selectionLeftChar, nextState.selectionLeftChar, charEq)
&& ReactUtils.deepEquals(this.state.selectionRightChar, nextState.selectionRightChar, charEq)
&& ReactUtils.deepEquals(this.state.activeAttributes, nextState.activeAttributes)
&& ReactUtils.deepEquals(this.state.remoteNameReveal, nextState.remoteNameReveal)
if(!stateEqual) return true
let remoteCursorsIds = this.state.remoteCursors ? Object.keys(this.state.remoteCursors) : []
let nextRemoteCursorsIds = nextState.remoteCursors ? Object.keys(nextState.remoteCursors) : []
if(remoteCursorsIds.length !== nextRemoteCursorsIds.length) return true
for(let i = 0; i < remoteCursorsIds.length; i++) {
let id = remoteCursorsIds[i]
if(!ReactUtils.deepEquals(this.state.remoteCursors[id], nextState.remoteCursors[id], _.isEqual,
[r => r.color, r => r.name, r => r.state])) return true
}
if(this.state.lines.length !== nextState.lines.length) return true
for(let i = 0; i < this.state.lines.length; i++) {
if(!ReactUtils.deepEquals(this.state.lines[i], nextState.lines[i], linesEq)) return true
}
// check props too, even though this check is fast and normally we would do faster checks first,
// put after state checks b/c Editor props rarely change
let propsEqual = this.props.fontSize === nextProps.fontSize
&& this.props.minFontSize === nextProps.minFontSize
&& this.props.unitsPerEm === nextProps.unitsPerEm
&& this.props.width === nextProps.width
&& this.props.margin.horizontal === nextProps.margin.horizontal
&& this.props.margin.vertical === nextProps.margin.vertical
&& this.props.userId === nextProps.userId
&& this.props.userName === nextProps.userName
&& this.props.debugEditor === nextProps.debugEditor
return !propsEqual
},
componentWillUnmount() {
EditorStore.unlisten(this.onStateChange)
},
onStateChange(state) {
this.setState(state)
},
_setRenderOptimizations(renderOptimizations) {
this.setProps({renderOptimizations: renderOptimizations})
},
_createReplica() {
this.createTextReplica()
this.registerCb(this._replicaInitCb, this._replicaUpdateCb)
},
_replicaInitCb(spec, op, replica) { // eslint-disable-line no-unused-vars
// set our own replica for future use
this.replicaSource = sourceOf(spec)
EditorActions.replicaInitialized()
this.createSharedCursor()
},
_replicaUpdateCb(spec, op, replica) { // eslint-disable-line no-unused-vars
if(this.replicaSource === sourceOf(spec)) return
EditorActions.replicaUpdated()
},
_mouseEventToCoordinates(e) {
// target is the particular element within the editor clicked on, current target is the entire editor div
let targetPosition = elementPosition(e.currentTarget)
return {
x: e.pageX - targetPosition.x,
y: e.pageY - targetPosition.y
}
},
_doOnSingleClick(e) {
let coordinates = this._mouseEventToCoordinates(e)
if(!coordinates) {
return
}
if(e.shiftKey) {
EditorActions.selectToCoordinates(coordinates)
} else {
EditorActions.navigateToCoordinates(coordinates)
}
},
_doOnDoubleClick() {
EditorActions.selectWordAtCurrentPosition()
},
_onMouseDown(e) {
if(!this.state.focus) {
EditorActions.focusInput()
}
if(this.clickReset) {
clearTimeout(this.clickReset)
this.clickReset = null
}
let clickCount = this.clickCount
this.clickCount += 1
this.clickReset = setTimeout(() => {
this.clickCount = 0
}, 250)
if(clickCount === 0) {
this._doOnSingleClick(e)
} else if (clickCount === 1) {
// note that _doOnSingleClick has already executed here
this._doOnDoubleClick(e)
} //else if(this.clickCount === 2) // TODO handle triple-click
e.preventDefault()
e.stopPropagation()
},
_onMouseMove(e) {
if(e.buttons !== 1) return
if(!this.state.focus) {
EditorActions.focusInput()
}
let coordinates = this._mouseEventToCoordinates(e)
if(!coordinates) return
EditorActions.selectToCoordinates(coordinates)
e.preventDefault()
e.stopPropagation()
},
_onMouseUp(e) {
if(this.state.selectionActive) {
EditorActions.setActiveAttributes()
}
},
_dismissError() {
EditorActions.dismissEditorError()
},
// RENDERING ---------------------------------------------------------------------------------------------------------
_searchLinesWithSelection(selection) {
if(!selection) {
selection = {
selectionActive: this.state.selectionActive,
selectionLeftChar: this.state.selectionLeftChar,
selectionRightChar: this.state.selectionRightChar
}
}
if(!this.state.lines || this.state.lines.length === 0 || !selection.selectionActive) {
return null
}
let left = lineContainingChar(this.state.lines, this.replica.getCharRelativeTo(selection.selectionLeftChar, 1, 'eof'))
if(!left) {
return null
}
let right = lineContainingChar(this.state.lines.slice(left.index), selection.selectionRightChar, null)
if(!right) {
return null
}
return {
left: left.index,
right: right.index + left.index
}
},
_computeSelection(lineIndex, lineHeight, selection, linesWithSelection, color) {
if(!selection.selectionActive) {
return null
}
// lines outside the selection range
if(linesWithSelection && (lineIndex < linesWithSelection.left || lineIndex > linesWithSelection.right)) {
return null
}
let selectionData = (leftX, widthX) => {
let height = Math.round(lineHeight * 10) / 10
// local cursor (no color) without focus is grey
if(!color && !this.state.focus) {
color = 'rgb(0, 0, 0)'
}
return {
left: leftX,
width: widthX,
height: height,
color: color
}
}
let line = this.state.lines[lineIndex]
// middle lines
if(linesWithSelection && (lineIndex > linesWithSelection.left && lineIndex < linesWithSelection.right)) {
let selectionWidthX = line.advance
if(line.isEof() || line.end.char === '\n') {
selectionWidthX += TextFontMetrics.advanceXForSpace(this.props.fontSize)
}
return selectionData(0, selectionWidthX)
}
// last line with EOF
if(line && line.isEof() && selection.selectionRightChar === EOF) {
return selectionData(0, TextFontMetrics.advanceXForSpace(this.props.fontSize))
}
// empty editor (no line and selection is from BASE_CHAR to EOF)
if(!line
&& charEq(selection.selectionLeftChar, BASE_CHAR)
&& charEq(selection.selectionRightChar, EOF)) {
return selectionData(0, TextFontMetrics.advanceXForSpace(this.props.fontSize))
}
let selectionLeftX = 0
let selectionWidthX
let selectionAddSpace
if(lineIndex === linesWithSelection.left) {
// TODO change selection height and font size dynamically
selectionLeftX = TextFontMetrics.advanceXForChars(this.props.fontSize, line.charsTo(selection.selectionLeftChar))
}
if(lineIndex === linesWithSelection.right) {
let selectionChars = selectionLeftX > 0 ?
line.charsBetween(selection.selectionLeftChar, selection.selectionRightChar) :
line.charsTo(selection.selectionRightChar)
if(selectionChars.length === 0) {
return null
}
selectionWidthX = TextFontMetrics.advanceXForChars(this.props.fontSize, selectionChars)
selectionAddSpace = selectionChars[selectionChars.length - 1].char === '\n'
} else {
selectionWidthX = line.advance - selectionLeftX
selectionAddSpace = line.isEof() || line.end.char === '\n'
}
if(selectionAddSpace) {
selectionWidthX += TextFontMetrics.advanceXForSpace(this.props.fontSize)
}
return selectionData(selectionLeftX, selectionWidthX)
},
_renderLine(line, index, lineHeight, localSelection, remoteSelections) {
let computedSelection = localSelection ?
this._computeSelection(index, lineHeight, localSelection.selection, localSelection.lines) :
null
let computedRemoteSelections = remoteSelections
.filter(s => s)
.map(s => this._computeSelection(index, lineHeight, s.selection, s.lines, s.color))
.filter(s => s)
return (
<EditorLine key={index} line={line} lineHeight={lineHeight}
fontSize={this.props.fontSize} selection={computedSelection} remoteSelections={computedRemoteSelections}
renderOptimizations={this.props.renderOptimizations}/>
)
},
_cursorPosition(lineHeight, position, positionEolStart) {
// the initial render before the component is mounted has no position or lines
if (!position || !this.state.lines) {
return null
}
if(charEq(BASE_CHAR, position) || this.state.lines.length === 0) {
return {
position: position,
positionEolStart: positionEolStart,
left: this.props.margin.horizontal,
top: this.props.margin.vertical
}
}
let result = lineContainingChar(this.state.lines, position, positionEolStart)
if(!result) {
return null
}
let {line, index, endOfLine} = result
let previousLineHeights = line ? lineHeight * index : 0
let cursorAdvanceX
if(!line || (endOfLine && positionEolStart && index < this.state.lines.length - 1)) {
cursorAdvanceX = 0
} else {
let positionChars = line.charsTo(position)
cursorAdvanceX = TextFontMetrics.advanceXForChars(this.props.fontSize, positionChars)
}
return {
position: position,
positionEolStart: positionEolStart,
left: this.props.margin.horizontal + cursorAdvanceX,
top: this.props.margin.vertical + previousLineHeights
}
},
_renderError() {
if(this.props.showErrorNotification && this.state.error) {
return (
<div className="ritzy-error-notification">{ this.props.errorNotification }
<button className="ritzy-error-notification-dismiss" onClick={this._dismissError}>x</button>
</div>
)
}
},
_renderInput(cursorPosition) {
let left = cursorPosition ? cursorPosition.left : 0
let top = cursorPosition ? cursorPosition.top : 0
return (
<TextInput id={this.props.id} ref="input" coordinates={{x: left, y: top}} focused={this.state.focus}
renderOptimizations={this.props.renderOptimizations}/>
)
},
_renderCursor(cursorPosition, lineHeight, remote) {
if(remote) {
let id = remote._id
let revealName = this.state.remoteNameReveal.has(id)
return (
<Cursor key={id} cursorPosition={cursorPosition} lineHeight={lineHeight}
remoteNameReveal={revealName} remote={remote} renderOptimizations={this.props.renderOptimizations}/>
)
} else {
return (
<Cursor key="local" ref="cursor" cursorPosition={cursorPosition} lineHeight={lineHeight}
cursorMotion={this.state.cursorMotion} activeAttributes={this.state.activeAttributes}
selectionActive={this.state.selectionActive} focus={this.state.focus}
renderOptimizations={this.props.renderOptimizations}/>
)
}
},
_renderRemoteCursors(lineHeight) {
return Object.keys(this.state.remoteCursors).filter(id => this.state.remoteCursors[id].state.position).map(id => {
let remoteCursor = this.state.remoteCursors[id]
let remotePosition
try {
remotePosition = this.replica.getChar(remoteCursor.state.position)
} catch (e) {
console.warn('Error obtaining remote position, ignoring.', e)
return null
}
// show remote cursors in same position as local one (subtly prompts user to move his local cursor somewhere else)
if(remotePosition) {
let cursorPosition = this._cursorPosition(lineHeight, remotePosition, remoteCursor.state.positionEolStart)
if(cursorPosition) {
return this._renderCursor(cursorPosition, lineHeight, remoteCursor)
}
}
return null
})
},
_renderEditorContents() {
if(this.state.loaded) {
let lineHeight = TextFontMetrics.lineHeight(this.props.fontSize)
let cursorPosition = this._cursorPosition(lineHeight, this.state.position, this.state.positionEolStart)
let createSelectionData = (source, color) => {
let selection = {
selectionActive: source.selectionActive,
selectionLeftChar: source.selectionLeftChar,
selectionRightChar: source.selectionRightChar
}
let linesWithSelection = this._searchLinesWithSelection(selection)
if(!linesWithSelection) {
return null
}
return {
selection: selection,
lines: linesWithSelection,
color: color
}
}
let localSelection = createSelectionData(this.state)
let remoteSelections = Object.keys(this.state.remoteCursors).filter(id => this.state.remoteCursors[id].state.selectionActive).map(id => {
let remoteCursor = this.state.remoteCursors[id]
return createSelectionData(remoteCursor.state, remoteCursor.color)
})
return (
<div>
{this._renderInput(cursorPosition)}
<div className="ritzy-internal-text-contents text-contents" style={{position: 'relative'}}>
{ this.state.lines.length > 0 ?
this.state.lines.map((line, index) => this._renderLine(line, index, lineHeight, localSelection, remoteSelections) ) :
<EditorLine lineHeight={lineHeight} fontSize={this.props.fontSize} renderOptimizations={this.props.renderOptimizations}/> }
</div>
{this._renderCursor(cursorPosition, lineHeight)}
{this._renderRemoteCursors(lineHeight)}
</div>
)
} else {
return (
<Spinner spinnerName='three-bounce' noFadeIn/>
)
}
},
_renderDebugEditor() {
if(!this.props.debugEditor) {
return null
}
return (
<DebugEditor editorState={this.state} replica={this.replica} searchLinesWithSelection={this._searchLinesWithSelection} setRenderOptimizations={this._setRenderOptimizations}/>
)
},
render() {
//console.trace('render')
let wrapperStyle = {
width: this.props.width,
padding: `${this.props.margin.vertical}px ${this.props.margin.horizontal}px`
}
return (
<div style={{boxSizing: 'content-box'}}>
{this._renderError()}
<div className="ritzy-internal-text-content-wrapper text-content-wrapper"
style={wrapperStyle} onMouseDown={this._onMouseDown} onMouseUp={this._onMouseUp} onMouseMove={this._onMouseMove}>
{this._renderEditorContents()}
</div>
{this._renderDebugEditor()}
</div>
)
}
})