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
|
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { Tooltip } from '@mui/material';
import { action, computed, IReactionDisposer, makeObservable, observable, reaction } from 'mobx';
import { observer } from 'mobx-react';
import { lift, wrapIn } from 'prosemirror-commands';
import { Mark, MarkType } from 'prosemirror-model';
import { wrapInList } from 'prosemirror-schema-list';
import { EditorState, NodeSelection, TextSelection } from 'prosemirror-state';
import { EditorView } from 'prosemirror-view';
import * as React from 'react';
import { Doc } from '../../../../fields/Doc';
import { BoolCast, Cast, StrCast } from '../../../../fields/Types';
import { DocServer } from '../../../DocServer';
import { undoBatch, UndoManager } from '../../../util/UndoManager';
import { AntimodeMenu, AntimodeMenuProps } from '../../AntimodeMenu';
import { ObservableReactComponent } from '../../ObservableReactComponent';
import { DocumentView } from '../DocumentView';
import { EquationBox } from '../EquationBox';
import { FieldViewProps } from '../FieldView';
import { FormattedTextBox } from './FormattedTextBox';
import { updateBullets } from './ProsemirrorExampleTransfer';
import './RichTextMenu.scss';
import { schema } from './schema_rts';
const { toggleMark } = require('prosemirror-commands');
@observer
export class RichTextMenu extends AntimodeMenu<AntimodeMenuProps> {
// eslint-disable-next-line no-use-before-define
static _instance: { menu: RichTextMenu | undefined } = observable({ menu: undefined });
static get Instance() {
return RichTextMenu._instance?.menu;
}
public overMenu: boolean = false; // kind of hacky way to prevent selects not being selectable
private _linkToRef = React.createRef<HTMLInputElement>();
layoutDoc: Doc | undefined;
@observable public view?: EditorView = undefined;
public editorProps: FieldViewProps | undefined;
public _brushMap: Map<string, Set<Mark>> = new Map();
@observable private collapsed: boolean = false;
@observable private _noLinkActive: boolean = false;
@observable private _boldActive: boolean = false;
@observable private _italicsActive: boolean = false;
@observable private _underlineActive: boolean = false;
@observable private _strikethroughActive: boolean = false;
@observable private _subscriptActive: boolean = false;
@observable private _superscriptActive: boolean = false;
@observable private _activeFontSize: string = '13px';
@observable private _activeFontFamily: string = '';
@observable private _activeListType: string = '';
@observable private _activeAlignment: string = 'left';
@observable private brushMarks: Set<Mark> = new Set();
@observable private showBrushDropdown: boolean = false;
@observable private _activeFontColor: string = 'black';
@observable private showColorDropdown: boolean = false;
@observable private _activeHighlightColor: string = 'transparent';
@observable private showHighlightDropdown: boolean = false;
@observable private currentLink: string | undefined = '';
@observable private showLinkDropdown: boolean = false;
_reaction: IReactionDisposer | undefined;
constructor(props: AntimodeMenuProps) {
super(props);
makeObservable(this);
RichTextMenu._instance.menu = this;
this.updateMenu(undefined, undefined, props, this.layoutDoc);
this._canFade = false;
this.Pinned = true;
}
@computed get noAutoLink() {
return this._noLinkActive;
}
@computed get bold() {
return this._boldActive;
}
@computed get underline() {
return this._underlineActive;
}
@computed get italics() {
return this._italicsActive;
}
@computed get strikeThrough() {
return this._strikethroughActive;
}
@computed get fontColor() {
return this._activeFontColor;
}
@computed get fontHighlight() {
return this._activeHighlightColor;
}
@computed get fontFamily() {
return this._activeFontFamily;
}
@computed get fontSize() {
return this._activeFontSize;
}
@computed get listStyle() {
return this._activeListType;
}
@computed get textAlign() {
return this._activeAlignment;
}
@computed get textVcenter() {
return BoolCast(this.layoutDoc?._layout_centered);
}
_disposer: IReactionDisposer | undefined;
componentDidMount() {
this._disposer = reaction(
() => DocumentView.Selected().slice(),
() => this.updateMenu(undefined, undefined, undefined, undefined)
);
}
componentWillUnmount() {
this._disposer?.();
}
@action
public updateMenu(view: EditorView | undefined, lastState: EditorState | undefined, props: any, layoutDoc: Doc | undefined) {
if (this._linkToRef.current?.getBoundingClientRect().width) {
return;
}
this.view = view;
this.layoutDoc = layoutDoc;
props && (this.editorProps = props);
// Don't do anything if the document/selection didn't change
if (view && view.hasFocus()) {
if (lastState?.doc.eq(view.state.doc) && lastState.selection.eq(view.state.selection)) return;
}
this.setActiveMarkButtons(this.getActiveMarksOnSelection());
const active = this.getActiveFontStylesOnSelection();
const { activeFamilies } = active;
const { activeSizes } = active;
const { activeColors } = active;
const { activeHighlights } = active;
const refDoc = DocumentView.Selected().lastElement()?.layoutDoc ?? Doc.UserDoc();
const refField = (pfx => (pfx ? pfx + '_' : ''))(DocumentView.Selected().lastElement()?.LayoutFieldKey);
const refVal = (field: string, dflt: string) => StrCast(refDoc[refField + field], StrCast(Doc.UserDoc()[field], dflt));
this._activeListType = this.getActiveListStyle();
this._activeAlignment = this.getActiveAlignment();
this._activeFontFamily = !activeFamilies.length ? StrCast(this.TextView?.Document._text_fontFamily, refVal('fontFamily', 'Arial')) : activeFamilies.length === 1 ? String(activeFamilies[0]) : 'various';
this._activeFontSize = !activeSizes.length ? StrCast(this.TextView?.Document.fontSize, refVal('fontSize', '10px')) : activeSizes[0];
this._activeFontColor = !activeColors.length ? StrCast(this.TextView?.Document.fontColor, refVal('fontColor', 'black')) : activeColors.length > 0 ? String(activeColors[0]) : '...';
this._activeHighlightColor = !activeHighlights.length ? '' : activeHighlights.length > 0 ? String(activeHighlights[0]) : '...';
// update link in current selection
this.getTextLinkTargetTitle().then(targetTitle => this.setCurrentLink(targetTitle));
}
setMark = (mark: Mark, state: EditorState, dispatch: any, dontToggle: boolean = false) => {
if (mark) {
const newPos = state.selection.$anchor.node()?.type === schema.nodes.ordered_list ? state.selection.from : state.selection.from;
const node = (state.selection as NodeSelection).node ?? (newPos >= 0 ? state.doc.nodeAt(newPos) : undefined);
if (node?.type === schema.nodes.ordered_list || node?.type === schema.nodes.list_item) {
const hasMark = node.marks.some(m => m.type === mark.type);
const otherMarks = node.marks.filter(m => m.type !== mark.type);
const addAnyway = node.marks.filter(m => m.type === mark.type && Object.keys(m.attrs).some(akey => m.attrs[akey] !== mark.attrs[akey]));
const markup = state.tr.setNodeMarkup(newPos, node.type, node.attrs, hasMark && !addAnyway ? otherMarks : [...otherMarks, mark]);
dispatch(updateBullets(markup, state.schema));
} else if (state) {
const { tr } = state;
if (dontToggle) {
tr.addMark(state.selection.from, state.selection.to, mark);
dispatch(tr.setSelection(new TextSelection(tr.doc.resolve(state.selection.from), tr.doc.resolve(state.selection.to)))); // bcz: need to redo the selection because ctrl-a selections disappear otherwise
} else {
toggleMark(mark.type, mark.attrs)(state, dispatch);
}
}
this.updateMenu(this.view, undefined, undefined, this.layoutDoc);
}
};
// finds font sizes and families in selection
getActiveAlignment() {
if (this.view && this.TextView?._props.rootSelected?.()) {
const { path } = this.view.state.selection.$from as any;
for (let i = path.length - 3; i < path.length && i >= 0; i -= 3) {
if (path[i]?.type === this.view.state.schema.nodes.paragraph || path[i]?.type === this.view.state.schema.nodes.heading) {
return path[i].attrs.align || 'left';
}
}
}
return 'left';
}
// finds font sizes and families in selection
getActiveListStyle() {
const state = this.view?.state;
if (state) {
const pos = state.selection.$anchor;
for (let i = 0; i < pos.depth; i++) {
const node = pos.node(i);
if (node.type === schema.nodes.ordered_list) {
return node.attrs.mapStyle;
}
}
}
return '';
}
// finds font sizes and families in selection
getActiveFontStylesOnSelection() {
const activeFamilies = new Set<string>();
const activeSizes = new Set<string>();
const activeColors = new Set<string>();
const activeHighlights = new Set<string>();
if (this.view && this.TextView?._props.rootSelected?.()) {
const { state } = this.view;
const pos = this.view.state.selection.$from;
let marks: Mark[] = [...(state.storedMarks ?? [])];
if (state.storedMarks !== null) {
/* empty */
} else if (state.selection.empty) {
for (let i = 0; i <= pos.depth; i++) {
marks = [...Array.from(pos.node(i).marks), ...this.view.state.selection.$anchor.marks(), ...marks];
}
} else {
state.doc.nodesBetween(state.selection.from, state.selection.to, (node /* , pos, parent, index */) => {
node.marks?.filter(mark => !mark.isInSet(marks)).map(mark => marks.push(mark));
});
}
marks.forEach(m => {
m.type === state.schema.marks.pFontFamily && activeFamilies.add(m.attrs.fontFamily);
m.type === state.schema.marks.pFontColor && activeColors.add(m.attrs.fontColor);
m.type === state.schema.marks.pFontSize && activeSizes.add(m.attrs.fontSize);
m.type === state.schema.marks.pFontHighlight && activeHighlights.add(String(m.attrs.fontHighlight));
});
} else if (DocumentView.Selected().some(dv => dv.ComponentView instanceof EquationBox)) {
DocumentView.Selected().forEach(dv => StrCast(dv.Document._text_fontSize) && activeSizes.add(StrCast(dv.Document._text_fontSize)));
}
return { activeFamilies: Array.from(activeFamilies), activeSizes: Array.from(activeSizes), activeColors: Array.from(activeColors), activeHighlights: Array.from(activeHighlights) };
}
getMarksInSelection(state: EditorState) {
const found = new Set<Mark>();
const { from, to } = state.selection as TextSelection;
state.doc.nodesBetween(from, to, node => node.marks.forEach(m => found.add(m)));
return found;
}
// finds all active marks on selection in given group
getActiveMarksOnSelection() {
if (!this.view || !this.TextView?._props.rootSelected?.()) return [] as MarkType[];
const { state } = this.view;
let marks: Mark[] = [...(state.storedMarks ?? [])];
const pos = this.view.state.selection.$from;
if (state.storedMarks !== null) {
/* empty */
} else if (state.selection.empty) {
for (let i = 0; i <= pos.depth; i++) {
marks = [...Array.from(pos.node(i).marks), ...this.view.state.selection.$anchor.marks(), ...marks];
}
} else {
state.doc.nodesBetween(state.selection.from, state.selection.to, (node /* , pos, parent, index */) => {
node.marks?.filter(mark => !mark.isInSet(marks)).map(mark => marks.push(mark));
});
}
const markGroup = [schema.marks.noAutoLinkAnchor, schema.marks.strong, schema.marks.em, schema.marks.underline, schema.marks.strikethrough, schema.marks.superscript, schema.marks.subscript];
return markGroup.filter(markType => {
const mark = state.schema.mark(markType);
return mark.isInSet(marks);
});
}
@action
setActiveMarkButtons(activeMarks: MarkType[] | undefined) {
if (!activeMarks) return;
this._noLinkActive = false;
this._boldActive = false;
this._italicsActive = false;
this._underlineActive = false;
this._strikethroughActive = false;
this._subscriptActive = false;
this._superscriptActive = false;
activeMarks.forEach(mark => {
switch (mark.name) {
case 'noAutoLinkAnchor': this._noLinkActive = true; break;
case 'strong': this._boldActive = true; break;
case 'em': this._italicsActive = true; break;
case 'underline': this._underlineActive = true; break;
case 'strikethrough': this._strikethroughActive = true; break;
case 'subscript': this._subscriptActive = true; break;
case 'superscript': this._superscriptActive = true; break;
default:
} // prettier-ignore
});
}
elideSelection = (txstate: EditorState | undefined = undefined, visibility = false) => {
const state = txstate ?? this.view?.state;
if (!state || state.selection.empty) return false;
const mark = state.schema.marks.summarize.create();
const tr = state.tr.addMark(state.tr.selection.from, state.selection.to, mark);
const text = tr.selection.content();
const elideNode = state.schema.nodes.summary.create({ visibility, text, textslice: text.toJSON() });
const summary = tr.replaceSelectionWith(elideNode).removeMark(tr.selection.from - 1, tr.selection.from, mark);
const expanded = () => {
const endOfElidableText = summary.selection.to + text.content.size;
const res = summary.insert(summary.selection.to, text.content).insert(endOfElidableText, state.schema.nodes.paragraph.create({}));
return res.setSelection(new TextSelection(res.doc.resolve(endOfElidableText + 1)));
};
this.view?.dispatch?.(visibility ? expanded() : summary);
return true;
};
toggleNoAutoLinkAnchor = () => {
if (this.view) {
const mark = this.view.state.schema.mark(this.view.state.schema.marks.noAutoLinkAnchor);
this.setMark(mark, this.view.state, this.view.dispatch, false);
this.TextView.autoLink();
this.view.focus();
}
};
toggleBold = () => {
if (this.view) {
const mark = this.view.state.schema.mark(this.view.state.schema.marks.strong);
this.setMark(mark, this.view.state, this.view.dispatch, false);
this.view.focus();
}
};
toggleUnderline = () => {
if (this.view) {
const mark = this.view.state.schema.mark(this.view.state.schema.marks.underline);
this.setMark(mark, this.view.state, this.view.dispatch, false);
this.view.focus();
}
};
toggleItalics = () => {
if (this.view) {
const mark = this.view.state.schema.mark(this.view.state.schema.marks.em);
this.setMark(mark, this.view.state, this.view.dispatch, false);
this.view.focus();
}
};
setFontField = (value: string, fontField: 'fontSize' | 'fontFamily' | 'fontColor' | 'fontHighlight') => {
if (this.view) {
const { text, paragraph } = this.view.state.schema.nodes;
const selNode = this.view.state.selection.$anchor.node();
if (this.view.state.selection.from === 1 && this.view.state.selection.empty && [undefined, text, paragraph].includes(selNode?.type)) {
this.TextView.dataDoc[this.TextView.fieldKey + `_${fontField}`] = value;
this.view.focus();
}
const attrs: { [key: string]: string } = {};
attrs[fontField] = value;
const fmark = this.view?.state.schema.marks['pF' + fontField.substring(1)].create(attrs);
this.setMark(fmark, this.view.state, (tx: any) => this.view!.dispatch(tx.addStoredMark(fmark)), true);
this.view.focus();
} else {
Doc.UserDoc()[fontField] = value;
this.updateMenu(this.view, undefined, this.props, this.layoutDoc);
}
};
// TODO: remove doesn't work
// remove all node type and apply the passed-in one to the selected text
changeListType = (mapStyle: string) => {
const active = this.view?.state && RichTextMenu.Instance?.getActiveListStyle();
const newMapStyle = active === mapStyle ? '' : mapStyle;
if (!this.view || newMapStyle === '') return;
const inList = this.view.state.selection.$anchor.node(1).type === schema.nodes.ordered_list;
const marks = this.view.state.storedMarks || (this.view.state.selection.$to.parentOffset && this.view.state.selection.$from.marks());
if (inList) {
const tx2 = updateBullets(this.view.state.tr, schema, newMapStyle, this.view.state.doc.resolve(this.view.state.selection.$anchor.before(1) + 1).pos, this.view.state.doc.resolve(this.view.state.selection.$anchor.after(1)).pos);
marks && tx2.ensureMarks([...marks]);
marks && tx2.setStoredMarks([...marks]);
this.view.dispatch(tx2);
} else
!wrapInList(schema.nodes.ordered_list)(this.view.state, (tx2: any) => {
const tx3 = updateBullets(tx2, schema, newMapStyle, this.view!.state.selection.from - 1, this.view!.state.selection.to + 1);
marks && tx3.ensureMarks([...marks]);
marks && tx3.setStoredMarks([...marks]);
this.view!.dispatch(tx3);
});
this.view.focus();
this.updateMenu(this.view, undefined, this.props, this.layoutDoc);
};
insertSummarizer(state: EditorState, dispatch: any) {
if (state.selection.empty) return false;
const mark = state.schema.marks.summarize.create();
const { tr } = state;
tr.addMark(state.selection.from, state.selection.to, mark);
const content = tr.selection.content();
const newNode = state.schema.nodes.summary.create({ visibility: false, text: content, textslice: content.toJSON() });
dispatch?.(tr.replaceSelectionWith(newNode).removeMark(tr.selection.from - 1, tr.selection.from, mark));
return true;
}
vcenterToggle = () => {
this.layoutDoc && (this.layoutDoc._layout_centered = !this.layoutDoc._layout_centered);
};
align = (view: EditorView, dispatch: any, alignment: 'left' | 'right' | 'center') => {
if (this.TextView?._props.rootSelected?.()) {
let { tr } = view.state;
view.state.doc.nodesBetween(view.state.selection.from, view.state.selection.to, (node, pos) => {
if ([schema.nodes.paragraph, schema.nodes.heading].includes(node.type)) {
tr = tr.setNodeMarkup(pos, node.type, { ...node.attrs, align: alignment }, node.marks);
return false;
}
view.focus();
return true;
});
view.focus();
dispatch?.(tr);
}
};
paragraphSetup(state: EditorState, dispatch: any, field: 'inset' | 'indent', value?: 0 | 10 | -10) {
let { tr } = state;
state.doc.nodesBetween(state.selection.from, state.selection.to, (node, pos) => {
if (node.type === schema.nodes.paragraph || node.type === schema.nodes.heading) {
const newValue = !value ?
(node.attrs[field] ? 0 : node.attrs[field] + 10) :
Math.max(0, value); // prettier-ignore
tr = tr.setNodeMarkup(pos, node.type, { ...node.attrs, ...(field === 'inset' ? { inset: newValue } : { indent: newValue }) }, node.marks);
return false;
}
return true;
});
dispatch?.(tr);
return true;
}
insertBlockquote(state: EditorState, dispatch: any) {
const { path } = state.selection.$from as any;
if (path.length > 6 && path[path.length - 6].type === schema.nodes.blockquote) {
lift(state, dispatch);
} else {
wrapIn(schema.nodes.blockquote)(state, dispatch);
}
return true;
}
insertHorizontalRule(state: EditorState, dispatch: any) {
dispatch(state.tr.replaceSelectionWith(state.schema.nodes.horizontal_rule.create()).scrollIntoView());
return true;
}
@action toggleBrushDropdown() {
this.showBrushDropdown = !this.showBrushDropdown;
}
// todo: add brushes to brushMap to save with a style name
onBrushNameKeyPress = (e: React.KeyboardEvent) => {
if (e.key === 'Enter') {
RichTextMenu.Instance?.brushMarks && RichTextMenu.Instance?._brushMap.set(this._brushNameRef.current!.value, RichTextMenu.Instance.brushMarks);
this._brushNameRef.current!.style.background = 'lightGray';
}
};
_brushNameRef = React.createRef<HTMLInputElement>();
@action
clearBrush() {
RichTextMenu.Instance && (RichTextMenu.Instance.brushMarks = new Set());
}
@action
fillBrush() {
if (!this.view) return;
if (!Array.from(this.brushMarks.keys()).length) {
const selectedMarks = this.getMarksInSelection(this.view.state);
if (selectedMarks.size >= 0) {
this.brushMarks = selectedMarks;
}
} else {
const { from, to, $from } = this.view.state.selection;
if (!this.view.state.selection.empty && $from && $from.nodeAfter) {
if (to - from > 0) {
this.view.dispatch(this.view.state.tr.removeMark(from, to));
Array.from(this.brushMarks)
.filter(m => m.type !== schema.marks.user_mark)
.forEach((mark: Mark) => {
this.setMark(mark, this.view!.state, this.view!.dispatch);
});
}
}
}
}
get TextView() {
return (this.view as any)?.TextView as FormattedTextBox;
}
get TextViewFieldKey() {
return this.TextView?._props.fieldKey;
}
@action setActiveHighlight(color: string) {
this._activeHighlightColor = color;
}
@action setCurrentLink(link: string) {
this.currentLink = link;
}
createLinkButton() {
const self = this;
function onLinkChange(e: React.ChangeEvent<HTMLInputElement>) {
self.TextView?.endUndoTypingBatch();
UndoManager.RunInBatch(() => self.setCurrentLink(e.target.value), 'link change');
}
const link = this.currentLink ? this.currentLink : '';
const button = (
<Tooltip title={<div className="dash-tooltip">set hyperlink</div>} placement="bottom">
{
// eslint-disable-next-line jsx-a11y/control-has-associated-label
<button type="button" className="antimodeMenu-button color-preview-button">
<FontAwesomeIcon icon="link" size="lg" />
</button>
}
</Tooltip>
);
const dropdownContent = (
<div className="dropdown link-menu">
<p>Linked to:</p>
<input value={link} ref={this._linkToRef} placeholder="Enter URL" onChange={onLinkChange} />
<button type="button" className="make-button" onPointerDown={() => this.makeLinkToURL(link)}>
Apply hyperlink
</button>
<div className="divider" />
<button type="button" className="remove-button" onPointerDown={() => this.deleteLink()}>
Remove link
</button>
</div>
);
// eslint-disable-next-line no-use-before-define
return <ButtonDropdown view={this.view} key="link button" button={button} dropdownContent={dropdownContent} openDropdownOnButton link />;
}
async getTextLinkTargetTitle() {
if (!this.view) return undefined;
const node = this.view.state.selection.$from.nodeAfter;
const link = node && node.marks.find(m => m.type.name === 'link');
if (link) {
const href = link.attrs.allAnchors.length > 0 ? link.attrs.allAnchors[0].href : undefined;
if (href) {
if (href.indexOf(Doc.localServerPath()) === 0) {
const linkclicked = href.replace(Doc.localServerPath(), '').split('?')[0];
if (linkclicked) {
const linkDoc = await DocServer.GetRefField(linkclicked);
if (linkDoc instanceof Doc) {
const linkAnchor1 = await Cast(linkDoc.link_anchor_1, Doc);
const linkAnchor2 = await Cast(linkDoc.link_anchor_2, Doc);
const currentDoc = DocumentView.Selected().lastElement().Document;
if (currentDoc && linkAnchor1 && linkAnchor2) {
if (Doc.AreProtosEqual(currentDoc, linkAnchor1)) {
return StrCast(linkAnchor2.title);
}
if (Doc.AreProtosEqual(currentDoc, linkAnchor2)) {
return StrCast(linkAnchor1.title);
}
}
}
}
} else {
return href;
}
} else {
return link.attrs.title;
}
}
return undefined;
}
// TODO: should check for valid URL
@undoBatch
makeLinkToURL = (target: string) => {
((this.view as any)?.TextView as FormattedTextBox).makeLinkAnchor(undefined, 'onRadd:rightight', target, target);
};
@undoBatch
deleteLink = () => {
if (this.view) {
const linkAnchor = this.view.state.selection.$from.nodeAfter?.marks.find(m => m.type === this.view!.state.schema.marks.linkAnchor);
if (linkAnchor) {
const allAnchors = linkAnchor.attrs.allAnchors.slice();
this.TextView.RemoveAnchorFromSelection(allAnchors);
// bcz: Argh ... this will remove the link from the document even it's anchored somewhere else in the text which happens if only part of the anchor text was selected.
allAnchors
.filter((aref: any) => aref?.href.indexOf(Doc.localServerPath()) === 0)
.forEach((aref: any) => {
const anchorId = aref.href.replace(Doc.localServerPath(), '').split('?')[0];
anchorId && DocServer.GetRefField(anchorId).then(linkDoc => Doc.DeleteLink?.(linkDoc as Doc));
});
}
}
};
render() {
return null;
}
}
interface ButtonDropdownProps {
view?: EditorView;
button: JSX.Element;
dropdownContent: JSX.Element;
openDropdownOnButton?: boolean;
link?: boolean;
pdf?: boolean;
}
@observer
export class ButtonDropdown extends ObservableReactComponent<ButtonDropdownProps> {
@observable private showDropdown: boolean = false;
private ref: HTMLDivElement | null = null;
constructor(props: any) {
super(props);
makeObservable(this);
}
componentDidMount() {
document.addEventListener('pointerdown', this.onBlur);
}
componentWillUnmount() {
document.removeEventListener('pointerdown', this.onBlur);
}
@action
setShowDropdown(show: boolean) {
this.showDropdown = show;
}
@action
toggleDropdown() {
this.showDropdown = !this.showDropdown;
}
onDropdownClick = (e: React.PointerEvent) => {
e.preventDefault();
e.stopPropagation();
this.toggleDropdown();
};
onBlur = (e: PointerEvent) => {
setTimeout(() => {
if (this.ref !== null && !this.ref.contains(e.target as Node)) {
this.setShowDropdown(false);
}
}, 0);
};
render() {
return (
<div
className="button-dropdown-wrapper"
ref={node => {
this.ref = node;
}}>
{!this._props.pdf ? (
<div className="antimodeMenu-button dropdown-button-combined" onPointerDown={this._props.openDropdownOnButton ? this.onDropdownClick : undefined}>
{this._props.button}
<div style={{ marginTop: '-8.5', position: 'relative' }} onPointerDown={!this._props.openDropdownOnButton ? this.onDropdownClick : undefined}>
<FontAwesomeIcon icon="caret-down" size="sm" />
</div>
</div>
) : (
<>
{this._props.button}
{
// eslint-disable-next-line jsx-a11y/control-has-associated-label
<button type="button" className="dropdown-button antimodeMenu-button" key="antimodebutton" onPointerDown={this.onDropdownClick}>
<FontAwesomeIcon icon="caret-down" size="sm" />
</button>
}
</>
)}
{this.showDropdown ? this._props.dropdownContent : null}
</div>
);
}
}
interface RichTextMenuPluginProps {
editorProps: any;
}
export class RichTextMenuPlugin extends React.Component<RichTextMenuPluginProps> {
// eslint-disable-next-line react/no-unused-class-component-methods
update(view: EditorView, lastState: EditorState | undefined) {
RichTextMenu.Instance?.updateMenu(view, lastState, this.props.editorProps, (view as any).TextView?.layoutDoc);
}
render() {
return null;
}
}
|