/
Editable.tsx
382 lines (355 loc) · 11.1 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
import {BaseRange, Transforms, Text} from 'slate'
import React, {useCallback, useMemo, useEffect, forwardRef} from 'react'
import {
Editable as SlateEditable,
ReactEditor,
RenderElementProps,
RenderLeafProps,
} from '@sanity/slate-react'
import {
EditorSelection,
OnBeforeInputFn,
OnCopyFn,
OnPasteFn,
OnPasteResult,
RenderAnnotationFunction,
RenderBlockFunction,
RenderChildFunction,
RenderDecoratorFunction,
RenderListItemFunction,
RenderStyleFunction,
ScrollSelectionIntoViewFunction,
} from '../types/editor'
import {HotkeyOptions} from '../types/options'
import {fromSlateValue, isEqualToEmptyEditor, toSlateValue} from '../utils/values'
import {normalizeSelection} from '../utils/selection'
import {toSlateRange} from '../utils/ranges'
import {debugWithName} from '../utils/debug'
import {Leaf} from './Leaf'
import {Element} from './Element'
import {usePortableTextEditor} from './hooks/usePortableTextEditor'
import {PortableTextEditor} from './PortableTextEditor'
import {createWithInsertData, createWithHotkeys} from './plugins'
import {useForwardedRef} from './hooks/useForwardedRef'
import {usePortableTextEditorReadOnlyStatus} from './hooks/usePortableTextReadOnly'
const debug = debugWithName('component:Editable')
const PLACEHOLDER_STYLE: React.CSSProperties = {
opacity: 0.5,
position: 'absolute',
userSelect: 'none',
pointerEvents: 'none',
}
const NOOP = () => {
// Nope
}
type DOMNode = globalThis.Node
const isDOMNode = (value: unknown): value is DOMNode => {
return value instanceof Node
}
/**
* Check if the target is editable and in the editor.
*/
export const hasEditableTarget = (
editor: ReactEditor,
target: EventTarget | null
): target is DOMNode => {
return isDOMNode(target) && ReactEditor.hasDOMNode(editor, target, {editable: true})
}
export type PortableTextEditableProps = {
hotkeys?: HotkeyOptions
onBeforeInput?: OnBeforeInputFn
onPaste?: OnPasteFn
onCopy?: OnCopyFn
renderAnnotation?: RenderAnnotationFunction
renderBlock?: RenderBlockFunction
renderChild?: RenderChildFunction
renderDecorator?: RenderDecoratorFunction
renderListItem?: RenderListItemFunction
renderPlaceholder?: () => React.ReactNode
renderStyle?: RenderStyleFunction
scrollSelectionIntoView?: ScrollSelectionIntoViewFunction
selection?: EditorSelection
spellCheck?: boolean
}
const EMPTY_DECORATORS: BaseRange[] = []
export const PortableTextEditable = forwardRef(function PortableTextEditable(
props: PortableTextEditableProps & Omit<React.HTMLProps<HTMLDivElement>, 'as' | 'onPaste'>,
forwardedRef: React.ForwardedRef<HTMLDivElement>
) {
const {
hotkeys,
onBeforeInput,
onPaste,
onCopy,
renderAnnotation,
renderBlock,
renderChild,
renderDecorator,
renderListItem,
renderPlaceholder,
renderStyle,
selection: propsSelection,
scrollSelectionIntoView,
spellCheck,
...restProps
} = props
const portableTextEditor = usePortableTextEditor()
const readOnly = usePortableTextEditorReadOnlyStatus()
const ref = useForwardedRef(forwardedRef)
const {change$, keyGenerator, types, slateInstance: slateEditor} = portableTextEditor
const blockTypeName = types.block.name
// React/UI-spesific plugins
const withInsertData = useMemo(
() => createWithInsertData(change$, types, keyGenerator),
[change$, keyGenerator, types]
)
const withHotKeys = useMemo(
() => createWithHotkeys(types, keyGenerator, portableTextEditor, hotkeys),
[hotkeys, keyGenerator, portableTextEditor, types]
)
// Output a minimal React editor inside Editable when in readOnly mode.
// NOTE: make sure all the plugins used here can be safely run over again at any point.
// There will be a problem if they redefine editor methods and then calling the original method within themselves.
useMemo(() => {
if (readOnly) {
debug('Editable is in read only mode')
return withInsertData(slateEditor)
}
debug('Editable is in edit mode')
return withInsertData(withHotKeys(slateEditor))
}, [readOnly, slateEditor, withHotKeys, withInsertData])
const renderElement = useCallback(
(eProps: RenderElementProps) => (
<Element
{...eProps}
types={types}
readOnly={readOnly}
renderBlock={renderBlock}
renderChild={renderChild}
renderListItem={renderListItem}
renderStyle={renderStyle}
spellCheck={spellCheck}
/>
),
[types, spellCheck, readOnly, renderBlock, renderChild, renderListItem, renderStyle]
)
const renderLeaf = useCallback(
(lProps: RenderLeafProps & {leaf: Text & {placeholder?: boolean}}) => {
if (renderPlaceholder && lProps.leaf.placeholder && lProps.text.text === '') {
return (
<>
<div style={PLACEHOLDER_STYLE} contentEditable={false}>
{renderPlaceholder()}
</div>
<Leaf
{...lProps}
keyGenerator={keyGenerator}
types={types}
renderAnnotation={renderAnnotation}
renderChild={renderChild}
renderDecorator={renderDecorator}
readOnly={readOnly}
/>
</>
)
}
return (
<Leaf
{...lProps}
keyGenerator={keyGenerator}
types={types}
renderAnnotation={renderAnnotation}
renderChild={renderChild}
renderDecorator={renderDecorator}
readOnly={readOnly}
/>
)
},
[
keyGenerator,
readOnly,
renderAnnotation,
renderChild,
renderDecorator,
renderPlaceholder,
types,
]
)
// Restore selection from props
useEffect(() => {
if (propsSelection) {
debug(`Selection from props ${JSON.stringify(propsSelection)}`)
const normalizedSelection = normalizeSelection(
propsSelection,
fromSlateValue(slateEditor.children, blockTypeName)
)
if (normalizedSelection !== null) {
debug(`Normalized selection from props ${JSON.stringify(normalizedSelection)}`)
const slateRange = toSlateRange(normalizedSelection, slateEditor)
if (slateRange) {
Transforms.select(slateEditor, slateRange)
// Output selection here in those cases where the editor selection was the same, and there are no set selection operations in the
// editor (this is usually automatically outputted by the withPortableTextSelections plugin)
if (!slateEditor.operations.some((o) => o.type === 'set_selection')) {
change$.next({type: 'selection', selection: normalizedSelection})
}
slateEditor.onChange()
}
}
}
}, [slateEditor, propsSelection, blockTypeName, change$])
// Set initial selection from props
useEffect(() => {
if (propsSelection) {
PortableTextEditor.select(portableTextEditor, propsSelection)
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []) // Only initial
// Handle from props onCopy function
const handleCopy = useCallback(
(event: React.ClipboardEvent<HTMLDivElement>): void | ReactEditor => {
if (onCopy) {
const result = onCopy(event)
// CopyFn may return something to avoid doing default stuff
if (result !== undefined) {
event.preventDefault()
}
}
},
[onCopy]
)
// Handle incoming pasting events in the editor
const handlePaste = useCallback(
(event: React.ClipboardEvent<HTMLDivElement>): Promise<void> | void => {
event.preventDefault()
if (!slateEditor.selection) {
return
}
if (!onPaste) {
debug('Pasting normally')
slateEditor.insertData(event.clipboardData)
return
}
// Resolve it as promise (can be either async promise or sync return value)
new Promise<OnPasteResult>((resolve) => {
resolve(
onPaste({
event,
value: PortableTextEditor.getValue(portableTextEditor),
path: slateEditor.selection?.focus.path || [],
types,
})
)
})
.then((result) => {
debug('Custom paste function from client resolved', result)
change$.next({type: 'loading', isLoading: true})
if (!result || !result.insert) {
debug('No result from custom paste handler, pasting normally')
slateEditor.insertData(event.clipboardData)
return
}
if (result && result.insert) {
slateEditor.insertFragment(toSlateValue(result.insert, {types}))
change$.next({type: 'loading', isLoading: false})
return
}
console.warn('Your onPaste function returned something unexpected:', result)
})
.catch((error) => {
change$.next({type: 'loading', isLoading: false})
console.error(error) // eslint-disable-line no-console
return error
})
},
[change$, onPaste, portableTextEditor, types, slateEditor]
)
const handleOnFocus = useCallback(() => {
change$.next({type: 'focus'})
}, [change$])
const handleOnBlur = useCallback(() => {
change$.next({type: 'blur'})
}, [change$])
const handleOnBeforeInput = useCallback(
(event: Event) => {
if (onBeforeInput) {
onBeforeInput(event)
}
},
[onBeforeInput]
)
const handleKeyDown = slateEditor.pteWithHotKeys
const scrollSelectionIntoViewToSlate = useMemo(() => {
// Use slate-react default scroll into view
if (scrollSelectionIntoView === undefined) {
return undefined
}
// Disable scroll into view totally
if (scrollSelectionIntoView === null) {
return NOOP
}
// Translate PortableTextEditor prop fn to Slate plugin fn
return (editor: ReactEditor, domRange: Range) => {
scrollSelectionIntoView(portableTextEditor, domRange)
}
}, [portableTextEditor, scrollSelectionIntoView])
const decorate = useCallback(() => {
if (isEqualToEmptyEditor(slateEditor.children, types)) {
return [
{
anchor: {
path: [0, 0],
offset: 0,
},
focus: {
path: [0, 0],
offset: 0,
},
placeholder: true,
},
]
}
return EMPTY_DECORATORS
}, [types, slateEditor.children])
// The editor
const slateEditable = useMemo(
() => (
<SlateEditable
autoFocus={false}
className="pt-editable"
decorate={decorate}
onBlur={handleOnBlur}
onCopy={handleCopy}
onDOMBeforeInput={handleOnBeforeInput}
onFocus={handleOnFocus}
onKeyDown={handleKeyDown}
onPaste={handlePaste}
readOnly={readOnly}
renderElement={renderElement}
renderLeaf={renderLeaf}
scrollSelectionIntoView={scrollSelectionIntoViewToSlate}
/>
),
[
decorate,
handleCopy,
handleKeyDown,
handleOnBeforeInput,
handleOnBlur,
handleOnFocus,
handlePaste,
readOnly,
renderElement,
renderLeaf,
scrollSelectionIntoViewToSlate,
]
)
if (!portableTextEditor) {
return null
}
return (
<div ref={ref} {...restProps}>
{slateEditable}
</div>
)
})