Repository navigation
Expand file tree
/
Copy pathNote.tsx
More file actions
405 lines (368 loc) · 18.7 KB
/
Copy pathNote.tsx
File metadata and controls
405 lines (368 loc) · 18.7 KB
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
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import ContentEditableModule, { ContentEditableEvent } from 'react-contenteditable'
import { useDispatch, useSelector } from 'react-redux'
import { css, cx } from '../../styled-system/css'
import { textNoteRecipe } from '../../styled-system/recipes'
import Path from '../@types/Path'
import SimplePath from '../@types/SimplePath'
import { cursorDownActionCreator as cursorDown } from '../actions/cursorDown'
import { deleteThoughtActionCreator as deleteThought } from '../actions/deleteThought'
import { editNotePathActionCreator as editNotePath } from '../actions/editNotePath'
import { editThoughtActionCreator as editThought } from '../actions/editThought'
import { keyboardOpenActionCreator as keyboardOpen } from '../actions/keyboardOpen'
import { setCursorActionCreator as setCursor } from '../actions/setCursor'
import { setDescendantActionCreator as setDescendant } from '../actions/setDescendant'
import { setNoteFocusActionCreator as setNoteFocus } from '../actions/setNoteFocus'
import { toggleNoteActionCreator as toggleNote } from '../actions/toggleNote'
import { isTouch } from '../browser'
import preventAutoscroll, { preventAutoscrollEnd } from '../device/preventAutoscroll'
import * as selection from '../device/selection'
import useFreshCallback from '../hooks/useFreshCallback'
import { firstVisibleChild, getChildrenSorted } from '../selectors/getChildren'
import getThoughtById from '../selectors/getThoughtById'
import noteThought from '../selectors/noteThought'
import noteValue from '../selectors/noteValue'
import resolveNoteKey from '../selectors/resolveNoteKey'
import resolveNotePath from '../selectors/resolveNotePath'
import store from '../stores/app'
import editableSyncStore from '../stores/editableSyncStore'
import appendToPath from '../util/appendToPath'
import applyOuterTags from '../util/applyOuterTags'
import equalPathHead from '../util/equalPathHead'
import getCommandState from '../util/getCommandState'
import head from '../util/head'
import strip from '../util/strip'
import trimHtml from '../util/trimHtml'
import useCaretRestore from './Editable/useCaretRestore'
import useOnCut from './Editable/useOnCut'
import FauxCaret from './FauxCaret'
// react-contenteditable is CommonJS that sets __esModule. Because em's package.json has "type": "module", Vite resolves
// its default import to module.exports rather than module.exports.default, while Vitest unwraps it to the component.
// See https://vite.dev/guide/migration#consistent-commonjs-interop.
const ContentEditable =
(ContentEditableModule as unknown as { default?: typeof ContentEditableModule }).default ?? ContentEditableModule
/** Renders an editable note that modifies the content of the hidden =note attribute. */
const Note = React.memo(
({
disabled,
path,
}: {
/** Disables interaction with the note. Used when the note is hidden by autofocus but remains in th DOM. */
disabled?: boolean
path: Path
}) => {
const dispatch = useDispatch()
const noteRef: { current: HTMLElement | null } = useRef(null)
const fontSize = useSelector(state => state.fontSize)
const generating = useSelector(state => !!getThoughtById(state, head(path))?.generating)
const hasFocus = useSelector(state => state.noteFocus && equalPathHead(state.cursor, path))
const [justPasted, setJustPasted] = useState(false)
// A draft preserves the user's comma spacing while typing. A forced editor refresh (e.g. undo/redo)
// invalidates it in the same render, before the caret effect runs, so it cannot mask the restored value.
const [noteDraft, setNoteDraft] = useState<{ value: string; editableNonce: number } | null>(null)
/** Gets the value of the note. Returns null if no note exists or if the context view is active. */
const note = useSelector(state => noteValue(state, path))
const editableNonce = useSelector(state => state.editableNonce)
// Formatting applied to the note while it was empty is held on the note's thought until the user types (#3910).
// Style the placeholder with it so that the empty note previews the formatting its text will take.
// Only the colors preview. react-contenteditable re-renders only when one of the props it watches changes, and
// `style` is one while `data-*` is not, so the color reaches the DOM but the data-placeholder-* attributes that
// drive bold/italic/underline/strikethrough/code never do. Moving Note onto the app's own ContentEditable, which
// spreads props without that gate, fixes it and is out of scope here.
const pendingFormat = useSelector(state => noteThought(state, path)?.pendingFormat)
const placeholderCommandState = useMemo(
() => (pendingFormat ? getCommandState(pendingFormat) : null),
[pendingFormat],
)
const placeholderForeColor =
typeof placeholderCommandState?.foreColor === 'string' ? placeholderCommandState.foreColor : undefined
const placeholderBackColor =
typeof placeholderCommandState?.backColor === 'string' ? placeholderCommandState.backColor : undefined
// A note is short enough that the trackpad's hit test lands outside it from the moment the space bar is
// pressed, so the caret escapes without any drag at all. It only escapes from the end, where the note abuts
// the parent thought, so that is where it belongs when restored. (#3276)
useCaretRestore({ editableRef: noteRef, enabled: !!hasFocus, end: true })
/** Focus Handling with useFreshCallback. */
const onFocus = useFreshCallback(() => {
preventAutoscrollEnd(noteRef.current)
const state = store.getState()
const targetPath = resolveNotePath(state, path)
const { noteId } = resolveNoteKey(state, head(path))
if (targetPath && !noteId) {
setNoteDraft({ value: noteValue(state, path) ?? '', editableNonce: state.editableNonce })
}
// Bail if state already has the caret on this note. Then the focus did not come from the user: it came from the
// effect below placing the caret, which focuses the note as a side effect. There is no cursor to move, but
// setCursor would still clear the one-shot noteOffset the effect is in the middle of honoring and recompute
// cursorOffset, and the undo enhancer records those as a fresh navigation action — discarding the redo stack the
// moment an undo restores a note caret, so the note edit that was just undone has no redo step.
if (state.noteFocus && equalPathHead(state.cursor, path)) return
dispatch(
setCursor({
path,
cursorHistoryClear: true,
isKeyboardOpen: true,
noteOffset: null,
noteFocus: true,
}),
)
}, [dispatch, path])
// set the caret on the note if editing this thought and noteFocus is true
useEffect(() => {
const { noteOffset } = store.getState()
// cursor must be true if note is focused
if (hasFocus && noteOffset !== null) {
selection.set(noteRef.current!, { offset: noteOffset })
// Clear noteOffset after placing the caret so it acts as a one-shot request. Otherwise repeatedly
// restoring the caret to the same offset (e.g. applying a font color over a background color multiple
// times) would set noteOffset to an unchanged value, the effect would not re-run, and the caret would
// be left wherever the note's re-render dropped it instead of the requested offset (#4630).
dispatch(setNoteFocus({ value: true, offset: null }))
}
}, [dispatch, editableNonce, hasFocus])
/** Handles note keyboard shortcuts. */
const onKeyDown = useCallback(
(e: React.KeyboardEvent) => {
// Only unmodified keys are note navigation. A chord that includes a command modifier belongs to a command
// (e.g. Cmd + Shift + ArrowDown is Move Thought Down), so let it propagate to the global keyDown handler
// instead of swallowing it as Cursor Down or Toggle Note (#4954).
if (e.metaKey || e.ctrlKey || e.altKey) return
// delete empty note
const note = noteValue(store.getState(), path)
// select thought
if (e.key === 'Escape' || e.key === 'ArrowUp') {
e.stopPropagation()
e.preventDefault()
dispatch(toggleNote())
}
// delete empty note
// (delete non-empty note is handled by delete command, which allows mobile gesture to work)
// note may be '' or null if the attribute child was deleted
else if (e.key === 'Backspace' && !note) {
e.stopPropagation()
e.preventDefault()
// delete target thought if it exists
dispatch((dispatch, getState) => {
const state = getState()
const targetPath = resolveNotePath(state, path) ?? path
const targetThought = targetPath ? getThoughtById(state, head(targetPath)) : undefined
if (targetThought) {
dispatch(deleteThought({ pathParent: path, thoughtId: targetThought.id }))
}
})
dispatch(setNoteFocus({ value: false }))
} else if (e.key === 'ArrowDown') {
e.stopPropagation()
e.preventDefault()
dispatch(cursorDown())
}
},
[dispatch, path],
)
/** Updates the =note attribute when the note text is edited. */
const onChange = useCallback(
(e: ContentEditableEvent) => {
if (editableSyncStore.getState().suppressChange) return
// calculate pathToContext onChange not in render for performance
const value = justPasted
? // if just pasted, strip all HTML from value
(setJustPasted(false), strip(e.target.value))
: // Mobile Safari inserts <br> when all text is deleted
// Strip <br> from beginning and end of text
e.target.value.replace(/^<br>|<br>$/gi, '')
const noteOffset = noteRef.current ? selection.offsetFromNode(noteRef.current) : null
// update the referenced thought directly if it exists
dispatch((dispatch, getState) => {
const state = getState()
const resolvedTargetPath = resolveNotePath(state, path)
const targetPath = resolvedTargetPath ?? path
const { noteId } = resolveNoteKey(state, head(path))
if (!noteId && resolvedTargetPath) {
const values = value.split(',').map(value => value.trim())
setNoteDraft({ value, editableNonce: state.editableNonce })
dispatch(
editNotePath({
noteOffset: noteOffset ?? undefined,
path: targetPath,
values,
undoLabel: 'Edit Note',
}),
)
return
}
const noteThoughtValue = firstVisibleChild(state, head(targetPath))
if (noteThoughtValue) {
// The formatting held while the note was empty is transferred onto the first text typed into it (#3910).
// editThought drops the held copy, and force re-renders the note with the tags in place so that the browser
// carries them through the rest of the typing.
const wrappedValue =
noteThoughtValue.pendingFormat && noteThoughtValue.value.length === 0 && value.length > 0
? applyOuterTags(value, noteThoughtValue.pendingFormat)
: value
dispatch(
editThought({
path: appendToPath(targetPath, noteThoughtValue.id) as SimplePath,
oldValue: noteThoughtValue.value,
newValue: wrappedValue,
noteOffset: noteOffset ?? undefined,
force: wrappedValue !== value,
undoLabel: 'Edit Note',
}),
)
} else {
dispatch(
setDescendant({
path: targetPath,
values: [value],
undoLabel: 'Edit Note',
}),
)
}
})
},
[dispatch, path, justPasted],
)
/** Trims the saved note and updates focus and keyboard state when editing ends. */
const onBlur = useFreshCallback(
(e: React.FocusEvent) => {
if (editableSyncStore.getState().suppressBlurSync || editableSyncStore.getState().suppressChange) return
// Input saves synchronously. Trim fresh state rather than replaying the DOM, which may be stale after a
// command or undo. Only update an existing note so blur cannot recreate one that was just deleted.
dispatch((dispatch, getState) => {
const state = getState()
const targetPath = resolveNotePath(state, path)
if (!targetPath) return
const { noteId } = resolveNoteKey(state, head(path))
if (noteId) {
const thought = firstVisibleChild(state, head(targetPath))
if (!thought) return
const value = trimHtml(thought.value)
if (value !== thought.value) {
dispatch(
editThought({
path: appendToPath(targetPath, thought.id) as SimplePath,
oldValue: thought.value,
newValue: value,
undoLabel: 'Edit Note',
}),
)
}
} else {
const children = getChildrenSorted(state, head(targetPath))
const values = children.map(child => trimHtml(child.value))
if (values.some((value, index) => value !== children[index].value)) {
dispatch(editNotePath({ path: targetPath, values, undoLabel: 'Edit Note' }))
}
}
})
setNoteDraft(null)
if (!selection.isNote(e.relatedTarget)) {
dispatch(setNoteFocus({ value: false }))
}
if (isTouch && !selection.isThought()) {
dispatch(keyboardOpen({ value: false }))
}
},
[dispatch, path],
)
const onMouseDown = useCallback(() => preventAutoscroll(noteRef.current), [noteRef])
const onCopy = useCallback((e: React.ClipboardEvent) => {
const html = selection.html()
const text = selection.text()
if (!html || !text) return
e.clipboardData.setData('text/html', html)
e.clipboardData.setData('text/plain', text)
e.clipboardData.setData('text/em', 'true')
e.preventDefault()
}, [])
const onCut = useOnCut()
if (note === null) return null
return (
<div
aria-label='note'
data-generating-note={generating || undefined}
className={cx(
textNoteRecipe(),
css({
fontSize: 'sm',
lineHeight: 1.25,
// negative margin to compensate for line-height. See .thought-container
marginTop: -3,
position: 'relative',
marginBottom: '2px',
padding: '0 0 4px 0',
}),
)}
style={{
// offset editable's margin-left, which is dynamically set based on font size
marginLeft: fontSize - 14,
}}
>
<span className={css({ fontSize: '1.2em', position: 'absolute', margin: '-0.175em 0 0 0.0875em' })}>
<FauxCaret caretType='noteStart' />
</span>
<ContentEditable
html={(noteDraft?.editableNonce === editableNonce ? noteDraft.value : note) ?? ''}
innerRef={noteRef as React.RefObject<HTMLElement>}
aria-label='note-editable'
data-thought-id={head(path)}
placeholder='Enter a note'
data-placeholder-bold={placeholderCommandState?.bold || undefined}
data-placeholder-code={placeholderCommandState?.code || undefined}
data-placeholder-italic={placeholderCommandState?.italic || undefined}
data-placeholder-strikethrough={placeholderCommandState?.strikethrough || undefined}
data-placeholder-underline={placeholderCommandState?.underline || undefined}
style={{
...(placeholderForeColor ? { '--placeholder-color': placeholderForeColor } : null),
...(placeholderBackColor ? { '--placeholder-background-color': placeholderBackColor } : null),
...(placeholderForeColor || placeholderBackColor ? { '--placeholder-opacity': 0.5 } : null),
}}
className={css({
display: 'inline-block',
padding: '0 1em 0 0.333em',
// Match thoughts so the browser keeps typed spaces as whitespace that trimHtml can trim.
whiteSpace: 'pre-wrap',
})}
// For some reason, pointerEvents: 'none' on ContentEditable or its parent does prevent onFocus.
// This is strange, as it seems to prevent onFocus in Subthought.tsx.
disabled={disabled}
// Prevent drag-and-drop of text selection between thoughts and notes. This also disables dragging
// text within the note, which was previously possible on mobile but not desktop. This may be addressed
// on both platforms by https://github.com/cybersemics/em/issues/3739.
onDrop={isTouch ? (e: React.DragEvent) => e.preventDefault() : undefined}
onKeyDown={onKeyDown}
onChange={onChange}
// Text copied from a note and pasted on a thought should not bring along the note's default color and italicization. (#3779)
onCopy={onCopy}
onCut={onCut}
onPaste={(e: React.ClipboardEvent) => {
// mobile Safari copies URLs as 'text/uri-list' when the share button is used
const text = e.clipboardData.getData('text/plain') || e.clipboardData.getData('text/uri-list')
// Pasting from mobile copy (e.g. Choose "Share" in Twitter and select "Copy") can result in a blank clipboard
// that the browser still pastes, so fall back to the default paste and strip the HTML it inserts in onChange.
// See: https://github.com/cybersemics/em/issues/286
if (!text) {
setJustPasted(true)
return
}
// Insert the plain text rather than letting the browser paste HTML. WebKit wraps pasted text in a span with
// inline styles and a trailing newline, and stripping them in onChange leaves a value that no longer matches
// the DOM, so the note re-renders and the caret jumps to the end on iOS and is dropped on Android (#3828).
// insertText leaves the caret after the pasted text and the DOM in sync with the value.
e.preventDefault()
document.execCommand('insertText', false, text)
}}
onBlur={onBlur}
onFocus={onFocus}
onMouseDown={onMouseDown}
role='button'
/>
<span className={css({ fontSize: '1.1em', position: 'absolute', margin: '-0.15em 0 0 -1.175em' })}>
<FauxCaret caretType='noteEnd' />
</span>
</div>
)
},
)
Note.displayName = 'Note'
export default Note