forked from ianstormtaylor/slate
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathinlines.tsx
More file actions
549 lines (489 loc) · 13.2 KB
/
Copy pathinlines.tsx
File metadata and controls
549 lines (489 loc) · 13.2 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
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
import isUrl from 'is-url'
import type React from 'react'
import { type PointerEvent, useMemo } from 'react'
import {
defineEditorExtension,
type EditorUpdateTransaction,
NodeApi,
RangeApi,
} from 'slate'
import { isHotkey } from 'slate-dom'
import * as SlateReact from 'slate-react'
import {
Editable,
type RenderElementProps,
type RenderTextProps,
useEditor,
useEditorSelector,
useElementSelected,
useSlateEditor,
} from 'slate-react'
import { cn } from '@/utils/cn'
import { Button, Icon, Toolbar } from './components'
import type {
BadgeElement,
ButtonElement,
CustomEditor,
CustomElement,
LinkElement,
ParagraphElement,
} from './custom-types.d'
const InlinesExample = () => {
const editor = useSlateEditor({
extensions: [inline()],
initialValue: [
{
type: 'paragraph',
children: [
{
text: 'In addition to block nodes, you can create inline nodes. Here is a ',
},
{
type: 'link',
url: 'https://en.wikipedia.org/wiki/Hypertext',
children: [{ text: 'hyperlink' }],
},
{
text: ', and here is a more unusual inline: an ',
},
{
type: 'button',
children: [{ text: 'editable button' }],
},
{
text: '! Here is a read-only inline: ',
},
{
type: 'badge',
children: [{ text: 'Approved' }],
},
{
text: '.',
},
],
},
{
type: 'paragraph',
children: [
{
text: 'There are two ways to add links. You can either add a link via the toolbar icon above, or if you want in on a little secret, copy a URL to your clipboard and paste it while a range of text is selected. ',
},
// The following is an example of an inline at the end of a block.
// This is an edge case that can cause issues.
{
type: 'link',
url: 'https://twitter.com/JustMissEmma/status/1448679899531726852',
children: [{ text: 'Finally, here is our favorite dog video.' }],
},
{ text: '' },
],
},
],
})
const onKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => {
const selection = editor.read((state) => state.selection.get())
// Default left/right behavior is unit:'character'.
// This fails to distinguish between two cursor positions, such as
// <inline>foo<cursor/></inline> vs <inline>foo</inline><cursor/>.
// Here we modify the behavior to unit:'offset'.
// This lets the user step into and out of the inline without stepping over characters.
// You may wish to customize this further to only use unit:'offset' in specific cases.
if (selection && RangeApi.isCollapsed(selection)) {
if (isHotkey('left', event)) {
editor.update((tx) => {
tx.selection.move({ unit: 'offset', reverse: true })
})
return true
}
if (isHotkey('right', event)) {
editor.update((tx) => {
tx.selection.move({ unit: 'offset' })
})
return true
}
}
}
return (
<SlateReact.Slate editor={editor}>
<Toolbar>
<AddLinkButton />
<RemoveLinkButton />
<ToggleEditableButtonButton />
</Toolbar>
<Editable
onKeyDown={onKeyDown}
placeholder="Enter some text..."
renderElement={renderElement}
renderText={InlineText}
/>
</SlateReact.Slate>
)
}
const inline = () =>
defineEditorExtension<CustomEditor>()({
clipboard: {
insertData(data, { editor, next }) {
const text = data.getData('text/plain')
if (text && isUrl(text)) {
wrapLink(editor, text)
return true
}
return next()
},
},
name: 'inline',
transforms: {
insertText({ next, text, tx }) {
if (isUrl(text)) {
insertLinkText(tx, text)
return true
}
if (insertLinkedTextSegments(tx, text)) {
return true
}
return next()
},
},
elements: [
{ inline: true, type: 'link' },
{ inline: true, type: 'button' },
{ inline: true, readOnly: true, selectable: false, type: 'badge' },
],
})
const URL_TEXT_PATTERN = /https?:\/\/[^\s]+/gi
const trimUrlPunctuation = (text: string) => {
const suffix = text.match(/[.,!?;:]+$/)?.[0] ?? ''
if (!suffix) {
return { suffix: '', url: text }
}
return {
suffix,
url: text.slice(0, -suffix.length),
}
}
const splitLinkedTextSegments = (text: string) => {
const segments: Array<{ text: string; url?: true }> = []
let cursor = 0
for (const match of text.matchAll(URL_TEXT_PATTERN)) {
const raw = match[0]
const index = match.index ?? 0
const { suffix, url } = trimUrlPunctuation(raw)
if (!url || !isUrl(url)) {
continue
}
if (index > cursor) {
segments.push({ text: text.slice(cursor, index) })
}
segments.push({ text: url, url: true })
if (suffix) {
segments.push({ text: suffix })
}
cursor = index + raw.length
}
if (segments.length === 0) {
return null
}
if (cursor < text.length) {
segments.push({ text: text.slice(cursor) })
}
return segments
}
const insertLinkText = (
tx: EditorUpdateTransaction<CustomElement[]>,
url: string
) => {
if (
tx.nodes.some({
match: (n) => NodeApi.isElement(n) && n.type === 'link',
})
) {
tx.nodes.unwrap({
match: (n) => NodeApi.isElement(n) && n.type === 'link',
})
}
const selection = tx.selection.get()
const isCollapsed = selection && RangeApi.isCollapsed(selection)
const link: LinkElement = {
type: 'link',
url,
children: isCollapsed ? [{ text: url }] : [],
}
if (isCollapsed) {
tx.nodes.insert(link)
tx.selection.move({ unit: 'offset' })
} else {
tx.nodes.wrap(link, { split: true })
tx.selection.collapse({ edge: 'end' })
tx.selection.move({ unit: 'offset' })
}
}
const insertLinkedTextSegments = (
tx: EditorUpdateTransaction<CustomElement[]>,
text: string
) => {
const selection = tx.selection.get()
if (!selection || !RangeApi.isCollapsed(selection)) {
return false
}
const segments = splitLinkedTextSegments(text)
if (!segments) {
return false
}
for (const segment of segments) {
if (segment.url) {
insertLinkText(tx, segment.text)
} else {
tx.text.insert(segment.text)
}
}
return true
}
const renderElement = (props: RenderElementProps<CustomElement>) => {
switch (props.element.type) {
case 'badge':
return <BadgeComponent {...(props as RenderElementProps<BadgeElement>)} />
case 'button':
return (
<EditableButtonComponent
{...(props as RenderElementProps<ButtonElement>)}
/>
)
case 'link':
return <LinkComponent {...(props as RenderElementProps<LinkElement>)} />
case 'paragraph':
return (
<ParagraphComponent
{...(props as RenderElementProps<ParagraphElement>)}
/>
)
}
}
const isLinkActive = (editor: CustomEditor): boolean => {
return editor.read((state) =>
state.nodes.some({
match: (n) => NodeApi.isElement(n) && n.type === 'link',
})
)
}
const isButtonActive = (editor: CustomEditor): boolean => {
return editor.read((state) =>
state.nodes.some({
match: (n) => NodeApi.isElement(n) && n.type === 'button',
})
)
}
const unwrapLink = (editor: CustomEditor) => {
editor.update((tx) => {
tx.nodes.unwrap({
match: (n) => NodeApi.isElement(n) && n.type === 'link',
})
})
}
const unwrapButton = (editor: CustomEditor) => {
editor.update((tx) => {
tx.nodes.unwrap({
match: (n) => NodeApi.isElement(n) && n.type === 'button',
})
})
}
const wrapLink = (editor: CustomEditor, url: string) => {
if (isLinkActive(editor)) {
unwrapLink(editor)
}
const selection = editor.read((state) => state.selection.get())
const isCollapsed = selection && RangeApi.isCollapsed(selection)
const link: LinkElement = {
type: 'link',
url,
children: isCollapsed ? [{ text: url }] : [],
}
editor.update((tx) => {
if (isCollapsed) {
tx.nodes.insert(link)
tx.selection.move({ unit: 'offset' })
} else {
tx.nodes.wrap(link, { split: true })
}
})
return true
}
const wrapButton = (editor: CustomEditor) => {
if (isButtonActive(editor)) {
unwrapButton(editor)
}
const selection = editor.read((state) => state.selection.get())
const isCollapsed = selection && RangeApi.isCollapsed(selection)
const button: ButtonElement = {
type: 'button',
children: isCollapsed ? [{ text: 'Edit me!' }] : [],
}
editor.update((tx) => {
if (isCollapsed) {
tx.nodes.insert(button)
} else {
tx.nodes.wrap(button, { split: true })
tx.selection.collapse({ edge: 'end' })
}
})
}
// Put this at the start and end of an inline component to work around this Chromium bug:
// https://bugs.chromium.org/p/chromium/issues/detail?id=1249405
const InlineChromiumBugfix = () => (
<span className="slate-inlines-chromium-bugfix" contentEditable={false}>
{String.fromCodePoint(160) /* Non-breaking space */}
</span>
)
const allowedSchemes = ['http:', 'https:', 'mailto:', 'tel:']
const LinkComponent = ({
attributes,
children,
element,
}: RenderElementProps<LinkElement>) => {
const selected = useElementSelected()
const safeUrl = useMemo(() => {
let parsedUrl: URL | null = null
try {
parsedUrl = new URL(element.url)
} catch {}
if (parsedUrl && allowedSchemes.includes(parsedUrl.protocol)) {
return parsedUrl.href
}
return 'about:blank'
}, [element.url])
return (
<a
{...attributes}
className={cn(selected && 'slate-inlines-link-selected')}
href={safeUrl}
>
<InlineChromiumBugfix />
{children}
<InlineChromiumBugfix />
</a>
)
}
const EditableButtonComponent = ({
attributes,
children,
}: RenderElementProps<ButtonElement>) => {
return (
/*
This is a span with button-like CSS rather than a native button.
Chrome and Safari handle display:inline-block poorly inside
contenteditable, and CSS cannot override the native button display:
- https://bugs.webkit.org/show_bug.cgi?id=105898
- https://bugs.chromium.org/p/chromium/issues/detail?id=1088403
- https://github.com/w3c/csswg-drafts/issues/3226
*/
<span
{...attributes}
// Margin is necessary to clearly show the cursor adjacent to the button
className="slate-inlines-editable-button"
onClick={(ev) => ev.preventDefault()}
>
<InlineChromiumBugfix />
{children}
<InlineChromiumBugfix />
</span>
)
}
const BadgeComponent = ({
attributes,
children,
}: RenderElementProps<BadgeElement>) => {
const selected = useElementSelected()
return (
<span
{...attributes}
className={cn('slate-inlines-badge', selected && 'is-selected')}
contentEditable={false}
data-playwright-selected={selected}
>
<InlineChromiumBugfix />
{children}
<InlineChromiumBugfix />
</span>
)
}
const ParagraphComponent = ({
attributes,
children,
}: RenderElementProps<ParagraphElement>) => <p {...attributes}>{children}</p>
const InlineText = (props: RenderTextProps) => {
const { attributes, children, text } = props
return (
<span
// Keeps end-of-block clicks outside the trailing inline in Chromium.
// https://github.com/ianstormtaylor/slate/issues/4704#issuecomment-1006696364
className={cn(text.text === '' && 'slate-inlines-empty-text')}
{...attributes}
>
{children}
</span>
)
}
const AddLinkButton = () => {
const editor = useEditor<CustomEditor>()
const active = useEditorSelector((editor: CustomEditor) =>
isLinkActive(editor)
)
return (
<Button
active={active}
onClick={() => {
const url = window.prompt('Enter the URL of the link:')
if (!url) return
if (editor.read((state) => state.selection.get())) {
wrapLink(editor, url)
}
}}
onPointerDown={(event: PointerEvent<HTMLButtonElement>) =>
event.preventDefault()
}
>
<Icon>link</Icon>
</Button>
)
}
const RemoveLinkButton = () => {
const editor = useEditor<CustomEditor>()
const active = useEditorSelector((editor: CustomEditor) =>
isLinkActive(editor)
)
return (
<Button
active={active}
onClick={() => {
if (isLinkActive(editor)) {
unwrapLink(editor)
}
}}
onPointerDown={(event: PointerEvent<HTMLButtonElement>) =>
event.preventDefault()
}
>
<Icon>link_off</Icon>
</Button>
)
}
const ToggleEditableButtonButton = () => {
const editor = useEditor<CustomEditor>()
return (
<Button
active
onClick={() => {
if (isButtonActive(editor)) {
unwrapButton(editor)
} else if (editor.read((state) => state.selection.get())) {
wrapButton(editor)
}
}}
onPointerDown={(event: PointerEvent<HTMLButtonElement>) =>
event.preventDefault()
}
>
<Icon>smart_button</Icon>
</Button>
)
}
export default InlinesExample