forked from ianstormtaylor/slate
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mentions.tsx
630 lines (611 loc) · 12.7 KB
/
mentions.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
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
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
import React, { useMemo, useCallback, useRef, useEffect, useState } from 'react'
import { Node, Editor, Transforms, Range, createEditor } from 'slate'
import { withHistory } from 'slate-history'
import {
Slate,
Editable,
ReactEditor,
withReact,
useSelected,
useFocused,
} from 'slate-react'
import { Portal } from '../components'
const MentionExample = () => {
const ref = useRef<HTMLDivElement | null>()
const [value, setValue] = useState<Node[]>(initialValue)
const [target, setTarget] = useState<Range | undefined>()
const [index, setIndex] = useState(0)
const [search, setSearch] = useState('')
const renderElement = useCallback(props => <Element {...props} />, [])
const editor = useMemo(
() => withMentions(withReact(withHistory(createEditor()))),
[]
)
const chars = CHARACTERS.filter(c =>
c.toLowerCase().startsWith(search.toLowerCase())
).slice(0, 10)
const onKeyDown = useCallback(
event => {
if (target) {
switch (event.key) {
case 'ArrowDown':
event.preventDefault()
const prevIndex = index >= chars.length - 1 ? 0 : index + 1
setIndex(prevIndex)
break
case 'ArrowUp':
event.preventDefault()
const nextIndex = index <= 0 ? chars.length - 1 : index - 1
setIndex(nextIndex)
break
case 'Tab':
case 'Enter':
event.preventDefault()
Transforms.select(editor, target)
insertMention(editor, chars[index])
setTarget(null)
break
case 'Escape':
event.preventDefault()
setTarget(null)
break
}
}
},
[index, search, target]
)
useEffect(() => {
if (target && chars.length > 0) {
const el = ref.current
const domRange = ReactEditor.toDOMRange(editor, target)
const rect = domRange.getBoundingClientRect()
el.style.top = `${rect.top + window.pageYOffset + 24}px`
el.style.left = `${rect.left + window.pageXOffset}px`
}
}, [chars.length, editor, index, search, target])
return (
<Slate
editor={editor}
value={value}
onChange={value => {
setValue(value)
const { selection } = editor
if (selection && Range.isCollapsed(selection)) {
const [start] = Range.edges(selection)
const wordBefore = Editor.before(editor, start, { unit: 'word' })
const before = wordBefore && Editor.before(editor, wordBefore)
const beforeRange = before && Editor.range(editor, before, start)
const beforeText = beforeRange && Editor.string(editor, beforeRange)
const beforeMatch = beforeText && beforeText.match(/^@(\w+)$/)
const after = Editor.after(editor, start)
const afterRange = Editor.range(editor, start, after)
const afterText = Editor.string(editor, afterRange)
const afterMatch = afterText.match(/^(\s|$)/)
if (beforeMatch && afterMatch) {
setTarget(beforeRange)
setSearch(beforeMatch[1])
setIndex(0)
return
}
}
setTarget(null)
}}
>
<Editable
renderElement={renderElement}
onKeyDown={onKeyDown}
placeholder="Enter some text..."
/>
{target && chars.length > 0 && (
<Portal>
<div
ref={ref}
style={{
top: '-9999px',
left: '-9999px',
position: 'absolute',
zIndex: 1,
padding: '3px',
background: 'white',
borderRadius: '4px',
boxShadow: '0 1px 5px rgba(0,0,0,.2)',
}}
>
{chars.map((char, i) => (
<div
key={char}
style={{
padding: '1px 3px',
borderRadius: '3px',
background: i === index ? '#B4D5FF' : 'transparent',
}}
>
{char}
</div>
))}
</div>
</Portal>
)}
</Slate>
)
}
const withMentions = editor => {
const { isInline, isVoid } = editor
editor.isInline = element => {
return element.type === 'mention' ? true : isInline(element)
}
editor.isVoid = element => {
return element.type === 'mention' ? true : isVoid(element)
}
return editor
}
const insertMention = (editor, character) => {
const mention = { type: 'mention', character, children: [{ text: '' }] }
Transforms.insertNodes(editor, mention)
Transforms.move(editor)
}
const Element = props => {
const { attributes, children, element } = props
switch (element.type) {
case 'mention':
return <MentionElement {...props} />
default:
return <p {...attributes}>{children}</p>
}
}
const MentionElement = ({ attributes, children, element }) => {
const selected = useSelected()
const focused = useFocused()
return (
<span
{...attributes}
contentEditable={false}
style={{
padding: '3px 3px 2px',
margin: '0 1px',
verticalAlign: 'baseline',
display: 'inline-block',
borderRadius: '4px',
backgroundColor: '#eee',
fontSize: '0.9em',
boxShadow: selected && focused ? '0 0 0 2px #B4D5FF' : 'none',
}}
>
@{element.character}
{children}
</span>
)
}
const initialValue = [
{
children: [
{
text:
'This example shows how you might implement a simple @-mentions feature that lets users autocomplete mentioning a user by their username. Which, in this case means Star Wars characters. The mentions are rendered as void inline elements inside the document.',
},
],
},
{
children: [
{ text: 'Try mentioning characters, like ' },
{
type: 'mention',
character: 'R2-D2',
children: [{ text: '' }],
},
{ text: ' or ' },
{
type: 'mention',
character: 'Mace Windu',
children: [{ text: '' }],
},
{ text: '!' },
],
},
]
const CHARACTERS = [
'Aayla Secura',
'Adi Gallia',
'Admiral Dodd Rancit',
'Admiral Firmus Piett',
'Admiral Gial Ackbar',
'Admiral Ozzel',
'Admiral Raddus',
'Admiral Terrinald Screed',
'Admiral Trench',
'Admiral U.O. Statura',
'Agen Kolar',
'Agent Kallus',
'Aiolin and Morit Astarte',
'Aks Moe',
'Almec',
'Alton Kastle',
'Amee',
'AP-5',
'Armitage Hux',
'Artoo',
'Arvel Crynyd',
'Asajj Ventress',
'Aurra Sing',
'AZI-3',
'Bala-Tik',
'Barada',
'Bargwill Tomder',
'Baron Papanoida',
'Barriss Offee',
'Baze Malbus',
'Bazine Netal',
'BB-8',
'BB-9E',
'Ben Quadinaros',
'Berch Teller',
'Beru Lars',
'Bib Fortuna',
'Biggs Darklighter',
'Black Krrsantan',
'Bo-Katan Kryze',
'Boba Fett',
'Bobbajo',
'Bodhi Rook',
'Borvo the Hutt',
'Boss Nass',
'Bossk',
'Breha Antilles-Organa',
'Bren Derlin',
'Brendol Hux',
'BT-1',
'C-3PO',
'C1-10P',
'Cad Bane',
'Caluan Ematt',
'Captain Gregor',
'Captain Phasma',
'Captain Quarsh Panaka',
'Captain Rex',
'Carlist Rieekan',
'Casca Panzoro',
'Cassian Andor',
'Cassio Tagge',
'Cham Syndulla',
'Che Amanwe Papanoida',
'Chewbacca',
'Chi Eekway Papanoida',
'Chief Chirpa',
'Chirrut Îmwe',
'Ciena Ree',
'Cin Drallig',
'Clegg Holdfast',
'Cliegg Lars',
'Coleman Kcaj',
'Coleman Trebor',
'Colonel Kaplan',
'Commander Bly',
'Commander Cody (CC-2224)',
'Commander Fil (CC-3714)',
'Commander Fox',
'Commander Gree',
'Commander Jet',
'Commander Wolffe',
'Conan Antonio Motti',
'Conder Kyl',
'Constable Zuvio',
'Cordé',
'Cpatain Typho',
'Crix Madine',
'Cut Lawquane',
'Dak Ralter',
'Dapp',
'Darth Bane',
'Darth Maul',
'Darth Tyranus',
'Daultay Dofine',
'Del Meeko',
'Delian Mors',
'Dengar',
'Depa Billaba',
'Derek Klivian',
'Dexter Jettster',
'Dineé Ellberger',
'DJ',
'Doctor Aphra',
'Doctor Evazan',
'Dogma',
'Dormé',
'Dr. Cylo',
'Droidbait',
'Droopy McCool',
'Dryden Vos',
'Dud Bolt',
'Ebe E. Endocott',
'Echuu Shen-Jon',
'Eeth Koth',
'Eighth Brother',
'Eirtaé',
'Eli Vanto',
'Ellé',
'Ello Asty',
'Embo',
'Eneb Ray',
'Enfys Nest',
'EV-9D9',
'Evaan Verlaine',
'Even Piell',
'Ezra Bridger',
'Faro Argyus',
'Feral',
'Fifth Brother',
'Finis Valorum',
'Finn',
'Fives',
'FN-1824',
'FN-2003',
'Fodesinbeed Annodue',
'Fulcrum',
'FX-7',
'GA-97',
'Galen Erso',
'Gallius Rax',
'Garazeb "Zeb" Orrelios',
'Gardulla the Hutt',
'Garrick Versio',
'Garven Dreis',
'Gavyn Sykes',
'Gideon Hask',
'Gizor Dellso',
'Gonk droid',
'Grand Inquisitor',
'Greeata Jendowanian',
'Greedo',
'Greer Sonnel',
'Grievous',
'Grummgar',
'Gungi',
'Hammerhead',
'Han Solo',
'Harter Kalonia',
'Has Obbit',
'Hera Syndulla',
'Hevy',
'Hondo Ohnaka',
'Huyang',
'Iden Versio',
'IG-88',
'Ima-Gun Di',
'Inquisitors',
'Inspector Thanoth',
'Jabba',
'Jacen Syndulla',
'Jan Dodonna',
'Jango Fett',
'Janus Greejatus',
'Jar Jar Binks',
'Jas Emari',
'Jaxxon',
'Jek Tono Porkins',
'Jeremoch Colton',
'Jira',
'Jobal Naberrie',
'Jocasta Nu',
'Joclad Danva',
'Joh Yowza',
'Jom Barell',
'Joph Seastriker',
'Jova Tarkin',
'Jubnuk',
'Jyn Erso',
'K-2SO',
'Kanan Jarrus',
'Karbin',
'Karina the Great',
'Kes Dameron',
'Ketsu Onyo',
'Ki-Adi-Mundi',
'King Katuunko',
'Kit Fisto',
'Kitster Banai',
'Klaatu',
'Klik-Klak',
'Korr Sella',
'Kylo Ren',
'L3-37',
'Lama Su',
'Lando Calrissian',
'Lanever Villecham',
'Leia Organa',
'Letta Turmond',
'Lieutenant Kaydel Ko Connix',
'Lieutenant Thire',
'Lobot',
'Logray',
'Lok Durd',
'Longo Two-Guns',
'Lor San Tekka',
'Lorth Needa',
'Lott Dod',
'Luke Skywalker',
'Lumat',
'Luminara Unduli',
'Lux Bonteri',
'Lyn Me',
'Lyra Erso',
'Mace Windu',
'Malakili',
'Mama the Hutt',
'Mars Guo',
'Mas Amedda',
'Mawhonic',
'Max Rebo',
'Maximilian Veers',
'Maz Kanata',
'ME-8D9',
'Meena Tills',
'Mercurial Swift',
'Mina Bonteri',
'Miraj Scintel',
'Mister Bones',
'Mod Terrik',
'Moden Canady',
'Mon Mothma',
'Moradmin Bast',
'Moralo Eval',
'Morley',
'Mother Talzin',
'Nahdar Vebb',
'Nahdonnis Praji',
'Nien Nunb',
'Niima the Hutt',
'Nines',
'Norra Wexley',
'Nute Gunray',
'Nuvo Vindi',
'Obi-Wan Kenobi',
'Odd Ball',
'Ody Mandrell',
'Omi',
'Onaconda Farr',
'Oola',
'OOM-9',
'Oppo Rancisis',
'Orn Free Taa',
'Oro Dassyne',
'Orrimarko',
'Osi Sobeck',
'Owen Lars',
'Pablo-Jill',
'Padmé Amidala',
'Pagetti Rook',
'Paige Tico',
'Paploo',
'Petty Officer Thanisson',
'Pharl McQuarrie',
'Plo Koon',
'Po Nudo',
'Poe Dameron',
'Poggle the Lesser',
'Pong Krell',
'Pooja Naberrie',
'PZ-4CO',
'Quarrie',
'Quay Tolsite',
'Queen Apailana',
'Queen Jamillia',
'Queen Neeyutnee',
'Qui-Gon Jinn',
'Quiggold',
'Quinlan Vos',
'R2-D2',
'R2-KT',
'R3-S6',
'R4-P17',
'R5-D4',
'RA-7',
'Rabé',
'Rako Hardeen',
'Ransolm Casterfo',
'Rappertunie',
'Ratts Tyerell',
'Raymus Antilles',
'Ree-Yees',
'Reeve Panzoro',
'Rey',
'Ric Olié',
'Riff Tamson',
'Riley',
'Rinnriyin Di',
'Rio Durant',
'Rogue Squadron',
'Romba',
'Roos Tarpals',
'Rose Tico',
'Rotta the Hutt',
'Rukh',
'Rune Haako',
'Rush Clovis',
'Ruwee Naberrie',
'Ryoo Naberrie',
'Sabé',
'Sabine Wren',
'Saché',
'Saelt-Marae',
'Saesee Tiin',
'Salacious B. Crumb',
'San Hill',
'Sana Starros',
'Sarco Plank',
'Sarkli',
'Satine Kryze',
'Savage Opress',
'Sebulba',
'Senator Organa',
'Sergeant Kreel',
'Seventh Sister',
'Shaak Ti',
'Shara Bey',
'Shmi Skywalker',
'Shu Mai',
'Sidon Ithano',
'Sifo-Dyas',
'Sim Aloo',
'Siniir Rath Velus',
'Sio Bibble',
'Sixth Brother',
'Slowen Lo',
'Sly Moore',
'Snaggletooth',
'Snap Wexley',
'Snoke',
'Sola Naberrie',
'Sora Bulq',
'Strono Tuggs',
'Sy Snootles',
'Tallissan Lintra',
'Tarfful',
'Tasu Leech',
'Taun We',
'TC-14',
'Tee Watt Kaa',
'Teebo',
'Teedo',
'Teemto Pagalies',
'Temiri Blagg',
'Tessek',
'Tey How',
'Thane Kyrell',
'The Bendu',
'The Smuggler',
'Thrawn',
'Tiaan Jerjerrod',
'Tion Medon',
'Tobias Beckett',
'Tulon Voidgazer',
'Tup',
'U9-C4',
'Unkar Plutt',
'Val Beckett',
'Vanden Willard',
'Vice Admiral Amilyn Holdo',
'Vober Dand',
'WAC-47',
'Wag Too',
'Wald',
'Walrus Man',
'Warok',
'Wat Tambor',
'Watto',
'Wedge Antilles',
'Wes Janson',
'Wicket W. Warrick',
'Wilhuff Tarkin',
'Wollivan',
'Wuher',
'Wullf Yularen',
'Xamuel Lennox',
'Yaddle',
'Yarael Poof',
'Yoda',
'Zam Wesell',
'Zev Senesca',
'Ziro the Hutt',
'Zuckuss',
]
export default MentionExample