-
Notifications
You must be signed in to change notification settings - Fork 124
/
Copy pathEditable.tsx
490 lines (419 loc) · 17.8 KB
/
Editable.tsx
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
import React, { useEffect, useRef } from 'react'
import { connect } from 'react-redux'
import { throttle } from 'lodash'
import he from 'he'
import classNames from 'classnames'
import { importText, setEditingValue, setInvalidState } from '../action-creators'
import { isMobile } from '../browser'
import globals from '../globals'
import { store } from '../store'
import ContentEditable, { ContentEditableEvent } from 'react-contenteditable'
import { shortcutEmitter } from '../shortcuts'
import { Child, Connected, Context, Path, TutorialChoice } from '../types'
import { GenericObject } from '../utilTypes'
// constants
import {
EDIT_THROTTLE,
EM_TOKEN,
MODIFIER_KEYS,
ROOT_TOKEN,
TUTORIAL2_STEP_CONTEXT1,
TUTORIAL2_STEP_CONTEXT1_PARENT,
TUTORIAL2_STEP_CONTEXT2,
TUTORIAL2_STEP_CONTEXT2_PARENT,
TUTORIAL_CONTEXT,
TUTORIAL_CONTEXT1_PARENT,
TUTORIAL_CONTEXT2_PARENT,
} from '../constants'
// util
import {
addEmojiSpace,
asyncFocus,
clearSelection,
contextOf,
ellipsize,
ellipsizeUrl,
equalPath,
hashContext,
head,
isDivider,
isElementHiddenByAutoFocus,
isHTML,
isURL,
pathToContext,
setSelection,
strip,
} from '../util'
// selectors
import {
attributeEquals,
chain,
getContexts,
getSetting,
getStyle,
getThought,
getThoughts,
hasChild,
isContextViewActive,
} from '../selectors'
// the amount of time in milliseconds since lastUpdated before the thought placeholder changes to something more facetious
const EMPTY_THOUGHT_TIMEOUT = 5 * 1000
// eslint-disable-next-line jsdoc/require-jsdoc
const stopPropagation = (e: React.MouseEvent) => e.stopPropagation()
interface EditableProps {
contextChain: Child[][],
cursorOffset?: number,
disabled?: boolean,
isEditing?: boolean,
rank: number,
showContexts?: boolean,
style?: GenericObject<string>,
thoughtsRanked: Path,
onKeyDownAction?: () => void,
}
/**
* An editable thought with throttled editing.
* Use rank instead of headRank(thoughtsRanked) as it will be different for context view.
*/
const Editable = ({ disabled, isEditing, thoughtsRanked, contextChain, cursorOffset, showContexts, rank, style, onKeyDownAction, dispatch }: Connected<EditableProps>) => {
const state = store.getState()
const thoughts = pathToContext(thoughtsRanked)
const thoughtsResolved = contextChain.length ? chain(state, contextChain, thoughtsRanked) : thoughtsRanked
const value = head(showContexts ? contextOf(thoughts) : thoughts) || ''
const readonly = hasChild(state, thoughts, '=readonly')
const uneditable = hasChild(state, thoughts, '=uneditable')
const context = showContexts && thoughts.length > 2 ? contextOf(contextOf(thoughts))
: !showContexts && thoughts.length > 1 ? contextOf(thoughts)
: [ROOT_TOKEN]
const childrenOptions = getThoughts(state, [...context, 'Options'])
const options = childrenOptions.length > 0 ?
childrenOptions.map(child => child.value.toLowerCase())
: null
const isTableColumn1 = attributeEquals(store.getState(), context, '=view', 'Table')
// store the old value so that we have a transcendental head when it is changed
const oldValueRef = useRef(value)
const thought = getThought(state, value)
const childrenLabel = getThoughts(state, [...thoughts, '=label'])
// store ContentEditable ref to update DOM without re-rendering the Editable during editing
const contentRef = React.useRef<HTMLInputElement>(null)
// =style attribute on the thought itself
const styleAttr = getStyle(state, thoughtsRanked)
/** Toggle invalid-option class using contentRef. */
const setContentInvalidState = (value: boolean) =>
contentRef.current && contentRef.current.classList[value ? 'add' : 'remove']('invalid-option')
/** Set or reset invalid state. */
const invalidStateError = (invalidValue: string | null) => {
const isInvalid = invalidValue != null
store.dispatch({ type: 'error', value: isInvalid ? `Invalid Value: "${invalidValue}"` : null })
setInvalidState(isInvalid)
// the Editable cannot connect to state.invalidState, as it would re-render during editing
// instead, we use setContentInvalidState to manipulate the DOM directly
setContentInvalidState(isInvalid)
}
/** Set the cursor on the thought. */
const setCursorOnThought = ({ editing }: { editing?: boolean } = {}) => {
const { cursorBeforeEdit, cursor } = store.getState() // use fresh state
const isEditing = equalPath(cursorBeforeEdit, thoughtsResolved)
const thoughtsRankedLive = cursor && isEditing
? contextOf(thoughtsRanked).concat(head(showContexts ? contextOf(cursor) : cursor))
: thoughtsRanked
dispatch({
type: 'setCursor',
contextChain,
cursorHistoryClear: true,
editing,
// set offset to null to prevent setSelection on next render
// to use the existing offset after a user clicks or touches the screent
// when cursor is changed through another method, such as cursorDown, offset will be reset
offset: null,
thoughtsRanked: thoughtsRankedLive,
})
}
/**
* Dispatches existingThoughtChange and has tutorial logic.
* Debounced from onChangeHandler.
* Since variables inside this function won't get updated between re-render so passing latest context, rank etc as params.
*/
const thoughtChangeHandler = (newValue: string, { context, showContexts, rank, thoughtsRanked, contextChain }: { context: Context, showContexts?: boolean, rank: number, thoughtsRanked: Path, contextChain: Child[][] }) => {
invalidStateError(null)
// make sure to get updated state
const state = store.getState()
const oldValue = oldValueRef.current
// safari adds <br> to empty contenteditables after editing, so strip them out
// make sure empty thoughts are truly empty
if (contentRef.current && newValue.length === 0) {
contentRef.current.innerHTML = newValue
}
const thought = getThought(state, oldValue)
if (thought) {
dispatch({ type: 'existingThoughtChange', context, showContexts, oldValue, newValue, rankInContext: rank, thoughtsRanked, contextChain })
// rerender so that triple dash is converted into divider
// otherwise nothing would be rerendered because the thought is still being edited
if (isDivider(newValue)) {
dispatch({ type: 'render' })
// remove selection so that the focusOffset does not cause a split false positive in newThought
clearSelection()
}
// store the value so that we have a transcendental head when it is changed
oldValueRef.current = newValue
const tutorialChoice = +(getSetting(state, 'Tutorial Choice') || 0) as TutorialChoice
const tutorialStep = +(getSetting(state, 'Tutorial Step') || 1)
if (newValue && (
(
Math.floor(tutorialStep) === TUTORIAL2_STEP_CONTEXT1_PARENT &&
newValue.toLowerCase() === TUTORIAL_CONTEXT1_PARENT[tutorialChoice].toLowerCase()
) || (
Math.floor(tutorialStep) === TUTORIAL2_STEP_CONTEXT2_PARENT &&
newValue.toLowerCase() === TUTORIAL_CONTEXT2_PARENT[tutorialChoice].toLowerCase()
) || (
(
Math.floor(tutorialStep) === TUTORIAL2_STEP_CONTEXT1 ||
Math.floor(tutorialStep) === TUTORIAL2_STEP_CONTEXT2
) &&
newValue.toLowerCase() === TUTORIAL_CONTEXT[tutorialChoice].toLowerCase()
)
)) {
dispatch({ type: 'tutorialNext' })
}
}
}
// using useRef hook to store throttled function so that it can persist even between component re-renders, so that throttle.flush method can be used properly
const throttledChangeRef = useRef(throttle(thoughtChangeHandler, EDIT_THROTTLE, { leading: false }))
/** Set the selection to the current Editable at the cursor offset. */
const setSelectionToCursorOffset = () => {
if (contentRef.current) {
setSelection(contentRef.current, { offset: cursorOffset })
}
}
useEffect(() => {
const { editing, noteFocus, dragHold } = state
// focus on the ContentEditable element if editing
// if cursorOffset is null, do not setSelection to preserve click/touch offset, unless there is no browser selection
// NOTE: asyncFocus() also needs to be called on mobile BEFORE the action that triggers the re-render is dispatched
if (isEditing && contentRef.current && (!isMobile || editing) && !noteFocus && (cursorOffset !== null || !window.getSelection()?.focusNode) && !dragHold) {
/*
Mobile Safari: Auto-Capitalization broken if selection is set synchronously.
When a new thought is created, the Shift key should be on for Auto-Capitalization.
Only occurs on Enter or Backspace, not gesture.
Even stranger, the issue only showed up when newThought was converted to a reducer (ecc3b3be).
For some reason, setTimeout fixes it.
*/
if (isMobile) {
asyncFocus()
setTimeout(setSelectionToCursorOffset)
}
else {
setSelectionToCursorOffset()
}
}
/** Flushes pending edits. */
const flush = () => throttledChangeRef.current.flush()
shortcutEmitter.on('shortcut', flush)
// flush edits and remove handler on unmount
return () => {
throttledChangeRef.current.flush()
shortcutEmitter.off('shortcut', flush)
}
}, [isEditing, cursorOffset])
/** Performs meta validation and calls thoughtChangeHandler immediately or using throttled reference. */
const onChangeHandler = (e: ContentEditableEvent) => {
// make sure to get updated state
const state = store.getState()
// NOTE: When Subthought components are re-rendered on edit, change is called with identical old and new values (?) causing an infinite loop
// @ts-ignore
const oldValue = oldValueRef.current
const newValue = e.target ? addEmojiSpace(he.decode(strip(e.target.value, { preserveFormatting: true }))) : oldValue
// TODO: Disable keypress
// e.preventDefault() does not work
// disabled={readonly} removes contenteditable property
dispatch(setEditingValue(newValue))
if (newValue === oldValue) {
if (readonly || uneditable || options) invalidStateError(null)
// if we cancel the edit, we have to cancel pending its
// this can occur for example by editing a value away from and back to its
throttledChangeRef.current.cancel()
return
}
const oldValueClean = oldValue === EM_TOKEN ? 'em' : ellipsize(oldValue)
if (readonly) {
dispatch({ type: 'error', value: `"${ellipsize(oldValueClean)}" is read-only and cannot be edited.` })
throttledChangeRef.current.cancel() // see above
return
}
else if (uneditable) {
dispatch({ type: 'error', value: `"${ellipsize(oldValueClean)}" is uneditable.` })
throttledChangeRef.current.cancel() // see above
return
}
else if (options && !options.includes(newValue.toLowerCase())) {
invalidStateError(newValue)
throttledChangeRef.current.cancel() // see above
return
}
const newNumContext = getContexts(state, newValue).length
const isNewValueURL = isURL(newValue)
const contextLengthChange = newNumContext > 0 || newNumContext !== getContexts(state, oldValueRef.current).length - 1
const urlChange = isNewValueURL || isNewValueURL !== isURL(oldValueRef.current)
// run the thoughtChangeHandler immediately if superscript changes or it's a url (also when it changes true to false)
if (contextLengthChange || urlChange) {
// update new supercript value and url boolean
throttledChangeRef.current.flush()
thoughtChangeHandler(newValue, { context, showContexts, rank, thoughtsRanked, contextChain })
}
else throttledChangeRef.current(newValue, { context, showContexts, rank, thoughtsRanked, contextChain })
}
/** Imports text that is pasted onto the thought. */
const onPaste = (e: React.ClipboardEvent) => {
const plainText = e.clipboardData.getData('text/plain')
const htmlText = e.clipboardData.getData('text/html')
// pasting from mobile copy (e.g. Choose "Share" in Twitter and select "Copy") results in blank plainText and htmlText
// the text will still be pasted if we do not preventDefault, it just won't get stripped of html properly
// See: https://github.com/cybersemics/em/issues/286
if (plainText || htmlText) {
e.preventDefault()
throttledChangeRef.current.flush()
// import into the live thoughts
// neither ref.current is set here nor can newValue be stored from onChange
// not sure exactly why, but it appears that the DOM node has been removed before the paste handler is called
const { cursor, cursorBeforeEdit } = store.getState()
const thoughtsRankedLive = cursor && equalPath(cursorBeforeEdit, thoughtsRanked)
? cursor
: thoughtsRanked
// text/plain may contain text that ultimately looks like html (contains <li>) and should be parsed as html
// pass the untrimmed old value to importText so that the whitespace is not loss when combining the existing value with the pasted value
const rawDestValue = strip(contentRef.current!.innerHTML, { preventTrim: true })
dispatch(importText(thoughtsRankedLive, isHTML(plainText)
? plainText
: htmlText || plainText,
{ rawDestValue })).then(({ newValue }: { newValue: string }) => {
if (newValue) oldValueRef.current = newValue
})
}
}
/** Flushes edits and updates certain state variables on blur. */
const onBlur = () => {
const { invalidState } = state
throttledChangeRef.current.flush()
// on blur remove error, remove invalid-option class, and reset editable html
if (invalidState) {
invalidStateError(null)
contentRef.current!.innerHTML = oldValueRef.current
}
// wait until the next render to determine if we have really blurred
// otherwise editing may be incorrectly set to false when clicking on another thought from edit mode (which results in a blur and focus in quick succession)
if (isMobile) {
setTimeout(() => {
if (!window.getSelection()?.focusNode) {
dispatch({ type: 'editing', value: false })
}
})
}
}
/**
* Sets the cursor on focus.
* Prevented by mousedown event above for hidden thoughts.
*/
const onFocus = () => {
// must get new state
const state = store.getState()
// not sure if this can happen, but I observed some glitchy behavior with the cursor moving when a drag and drop is completed so check dragInProgress to be. safe
if (!state.dragInProgress) {
// it is possible that the focus event fires with no onTouchEnd.
// in this case, make sure it is not a valid attempt to enter edit mode.
// we cannot assume all focus events without touchEnd events are false positives, because the user may have simply pressed tab/next field
const falseFocus =
// no cursor
!state.cursor ||
// clicking a different thought (when not editing)
(!state.editing && !equalPath(thoughtsResolved, state.cursorBeforeEdit))
setCursorOnThought({ editing: !falseFocus })
// remove the selection caused by the falseFocus
if (falseFocus) {
if (document.activeElement) {
// @ts-ignore
document.activeElement.blur()
}
clearSelection()
}
}
}
/**
* Sets the cursor on the thought when the mouse is clicked.
* Focus can only be prevented in mousedown event.
*/
const onMouseDown = (e: React.MouseEvent) => {
// if editing is disabled, set the cursor since onFocus will not trigger
if (disabled) {
setCursorOnThought()
}
// disable focus on hidden thoughts
// @ts-ignore
else if (isElementHiddenByAutoFocus(e.target)) {
e.preventDefault()
dispatch({ type: 'cursorBack' })
}
// stop propagation to AppComponent which would otherwise call cursorBack
e.stopPropagation()
}
/** Sets the cursor on the thought when the touch event ends without a drag. */
const onTouchEnd = (e: React.TouchEvent) => {
// make sure to get updated state
const state = store.getState()
showContexts = showContexts || isContextViewActive(state, pathToContext(thoughtsRanked))
if (
!globals.touching &&
// not sure if this can happen, but I observed some glitchy behavior with the cursor moving when a drag and drop is completed so check dragInProgress to be safe
!state.dragInProgress &&
!isElementHiddenByAutoFocus(e.target as HTMLElement) &&
(
// no cursor
!state.cursor ||
// clicking a different thought (when not editing)
(!state.editing && !equalPath(thoughtsResolved, state.cursorBeforeEdit))
)) {
// prevent focus to allow navigation with mobile keyboard down
e.preventDefault()
setCursorOnThought()
}
}
/**
* Prevents onKeyDownAction call for shift, alt or ctrl keys.
*/
const onKeyDown = (e: React.KeyboardEvent) => {
if (e.key in MODIFIER_KEYS) return
onKeyDownAction!()
}
return <ContentEditable
disabled={disabled}
innerRef={contentRef}
className={classNames({
editable: true,
['editable-' + hashContext(thoughtsResolved, rank)]: true,
empty: value.length === 0
})}
html={value === EM_TOKEN ? '<b>em</b>'
: isEditing ? value
: childrenLabel.length > 0
? childrenLabel[0].value
: ellipsizeUrl(value)
}
placeholder={isTableColumn1 ? ''
// @ts-ignore
: thought && new Date() - new Date(thought.lastUpdated) > EMPTY_THOUGHT_TIMEOUT ? 'This is an empty thought'
: 'Add a thought'}
// stop propagation to prevent default content onClick (which removes the cursor)
onClick={stopPropagation}
onTouchEnd={onTouchEnd}
onMouseDown={onMouseDown}
onFocus={onFocus}
onBlur={onBlur}
onChange={onChangeHandler}
onPaste={onPaste}
onKeyDown={onKeyDownAction ? onKeyDown : undefined}
style={{
...style, // style prop
...styleAttr, // style attribute
}}
/>
}
export default connect()(Editable)