-
Notifications
You must be signed in to change notification settings - Fork 4
/
Mentions.stories.tsx
758 lines (728 loc) · 16 KB
/
Mentions.stories.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
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
import { Meta, Story } from '@storybook/react/types-6-0';
import Tippy, { TippyProps } from '@tippyjs/react';
import React, { useCallback, useMemo, useState } from 'react';
import { Descendant, Editor, Range, Transforms } from 'slate';
import {
Editable,
RenderElementProps,
Slate,
useFocused,
useSelected,
useSlate,
} from 'slate-react';
import 'tippy.js/animations/scale.css';
import 'tippy.js/themes/light.css';
import { SlateExtension, useSlateState, useSlateWithExtensions } from '../.';
export default {
title: 'Examples/Mentions',
} as Meta;
export const Default: Story = () => {
const [value, onChange] = useSlateState(initialValue);
const { getMentionSelectProps, ...mentionExtension } = useMentionExtension();
const { getSlateProps, getEditableProps } = useSlateWithExtensions({
value,
onChange,
extensions: [mentionExtension],
});
return (
<Slate {...getSlateProps()}>
<Editable {...getEditableProps()} />
<MentionSelect {...getMentionSelectProps()} />
</Slate>
);
};
/**
* All of the logic for adding and rendering mentions is encapsulated in this plugin
*/
export const useMentionExtension = (): SlateExtension & {
getMentionSelectProps: () => MentionSelectProps;
} => {
// state for Mentions
const [index, setIndex] = useState(0);
const [search, setSearch] = useState('');
const [target, setTarget] = useState<Range | undefined>();
const chars = useMemo(
() =>
CHARACTERS.filter(c =>
c.toLowerCase().startsWith(search.toLowerCase())
).slice(0, 10),
[search]
);
// helper function for inserting a mention
const insertMention = (editor: Editor, character: string) => {
const mention = { type: 'mention', character, children: [{ text: '' }] };
Transforms.insertNodes(editor, mention);
Transforms.move(editor);
};
// handle on key down
const onKeyDown = useCallback<NonNullable<SlateExtension['onKeyDown']>>(
(event, editor) => {
if (target) {
switch (event.key) {
case 'ArrowDown':
event.preventDefault();
setIndex(index >= chars.length - 1 ? 0 : index + 1);
break;
case 'ArrowUp':
event.preventDefault();
setIndex(index <= 0 ? chars.length - 1 : index - 1);
break;
case 'Tab':
case 'Enter':
event.preventDefault();
Transforms.select(editor, target);
insertMention(editor, chars[index]);
setTarget(undefined);
break;
case 'Escape':
event.preventDefault();
setTarget(undefined);
break;
}
}
},
[chars, index, target]
);
// handle on change
const onChange = useCallback<NonNullable<SlateExtension['onChange']>>(
(editor, next) => {
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 next(editor);
}
}
setTarget(undefined);
return next(editor);
},
[]
);
// make mentions inline elements
const isInline = useCallback<NonNullable<SlateExtension['isInline']>>(
(element, editor, next) => {
if (element.type === 'mention') {
return true;
}
return next(element, editor);
},
[]
);
// make mentions void elements
const isVoid = useCallback<NonNullable<SlateExtension['isVoid']>>(
(element, editor, next) => {
if (element.type === 'mention') {
return true;
}
return next(element, editor);
},
[]
);
// render mentions with the MentionElement component
const renderElement = useCallback<
NonNullable<SlateExtension['renderElement']>
>(props => {
if (props.element.type === 'mention') {
return <MentionElement {...props} />;
}
}, []);
// function to get props for the mention select
const getMentionSelectProps = useCallback<() => MentionSelectProps>(() => {
return {
items: chars,
focusedItem: index,
open: target !== undefined,
};
}, [chars, index, target]);
return {
onChange,
onChangeDeps: [onChange],
onKeyDown,
onKeyDownDeps: [onKeyDown],
renderElement,
renderElementDeps: [renderElement],
isInline,
isInlineDeps: [isInline],
isVoid,
isVoidDeps: [isVoid],
getMentionSelectProps,
};
};
/**
* Component which renders a mention element
*/
const MentionElement = ({
attributes,
children,
element,
}: RenderElementProps) => {
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>
);
};
// Functions from Tippy js used in the MentionSelect
// eslint-disable-next-line @typescript-eslint/ban-types
type OffsetFunc = Extract<TippyProps['offset'], Function>;
// eslint-disable-next-line @typescript-eslint/ban-types
type RectFunc = Extract<TippyProps['getReferenceClientRect'], Function>;
// default rect for positioning the mention select
const zeroRect: ClientRect = {
top: 0,
bottom: 0,
height: 0,
width: 0,
left: 0,
right: 0,
};
interface MentionSelectProps {
items: string[];
focusedItem: number;
open: boolean;
}
/**
* Mention Select which uses tippy js to position itself at the current selection
*/
export const MentionSelect: React.FC<MentionSelectProps> = props => {
// get the current selection
const domSelection = window.getSelection();
const editor = useSlate();
const focused = useFocused();
// determine visibility based on selection, range, focus, and props
const visible =
domSelection !== null &&
domSelection.rangeCount === 1 &&
editor.selection !== null &&
Range.isCollapsed(editor.selection) &&
focused &&
props.open;
// function which creates a virtual rectangle to position the tippy at the selection
const getBoundingClientRect = useCallback<RectFunc>(() => {
// if closed return something arbitrary
if (!visible) {
return zeroRect;
}
// return the location of the selection
const domRange = window.getSelection()?.getRangeAt(0);
const rect = domRange?.getBoundingClientRect();
return rect ?? zeroRect;
}, [visible]);
/**
* function which offsets the tippy js portal so that it is positioned at the selection
*/
const offsetFunc = useCallback<OffsetFunc>(
({ popper, reference, placement }) => {
// we offset by the reference width which leads to the rect being
// at the end of the selection, then we offset by popper width over 2
// so the final pop up shows to the bottom right of the cursor
if (placement === 'bottom' || placement === 'top') {
return [reference.width + popper.width / 2, 0];
}
return [0, 0];
},
[]
);
const Content = useMemo(
() => (
<div>
{props.items.map((item, i) => (
<div
key={item}
style={{
backgroundColor: i === props.focusedItem ? '#c2dfe6' : undefined,
}}
>
{item}
</div>
))}
</div>
),
[props.focusedItem, props.items]
);
return (
<Tippy
getReferenceClientRect={getBoundingClientRect}
offset={offsetFunc}
placement={'bottom'}
// use popper options to control when tippy doesn't have room
// defaults to going up
popperOptions={{
modifiers: [
{
name: 'flip',
options: {
fallbackPlacements: ['top'],
},
},
],
}}
visible={visible}
appendTo={document.body}
theme={'light'}
animation={'scale'}
duration={[75, 0]}
content={Content}
></Tippy>
);
};
const initialValue: Descendant[] = [
{
children: [
{
text:
'This example shows how you might implement a simple @-mentions feature that lets users Mention 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',
];