-
-
Notifications
You must be signed in to change notification settings - Fork 2.2k
Expand file tree
/
Copy pathinline.ts
More file actions
603 lines (505 loc) · 15.6 KB
/
inline.ts
File metadata and controls
603 lines (505 loc) · 15.6 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
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
/* eslint-disable @typescript-eslint/no-non-null-assertion */
import Module from '../../__module';
import $ from '../../dom';
import SelectionUtils from '../../selection';
import * as _ from '../../utils';
import type { InlineTool as IInlineTool } from '../../../../types';
import I18n from '../../i18n';
import { I18nInternalNS } from '../../i18n/namespace-internal';
import Shortcuts from '../../utils/shortcuts';
import type { ModuleConfig } from '../../../types-internal/module-config';
import { CommonInternalSettings } from '../../tools/base';
import type { Popover, PopoverItemHtmlParams, PopoverItemParams, WithChildren } from '../../utils/popover';
import { PopoverItemType } from '../../utils/popover';
import { PopoverInline } from '../../utils/popover/popover-inline';
import type InlineToolAdapter from 'src/components/tools/inline';
/**
* Inline Toolbar elements
*/
interface InlineToolbarNodes {
wrapper: HTMLElement | undefined;
}
/**
* Inline toolbar with actions that modifies selected text fragment
*
* |¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯|
* | B i [link] [mark] |
* |________________________|
*/
export default class InlineToolbar extends Module<InlineToolbarNodes> {
/**
* CSS styles
*/
public CSS = {
inlineToolbar: 'ce-inline-toolbar',
};
/**
* State of inline toolbar
*/
public opened = false;
/**
* Popover instance reference
*/
private popover: Popover | null = null;
/**
* Margin above/below the Toolbar
*/
// eslint-disable-next-line @typescript-eslint/no-magic-numbers
private readonly toolbarVerticalMargin: number = _.isMobileScreen() ? 20 : 6;
/**
* Currently visible tools instances
*/
private tools: Map<InlineToolAdapter, IInlineTool> = new Map();
/**
* @param moduleConfiguration - Module Configuration
* @param moduleConfiguration.config - Editor's config
* @param moduleConfiguration.eventsDispatcher - Editor's event dispatcher
*/
constructor({ config, eventsDispatcher }: ModuleConfig) {
super({
config,
eventsDispatcher,
});
window.requestIdleCallback(
() => {
this.make();
},
{ timeout: 2000 }
);
}
/**
* Moving / appearance
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/
/**
* Shows Inline Toolbar if something is selected
*
* @param [needToClose] - pass true to close toolbar if it is not allowed.
* Avoid to use it just for closing IT, better call .close() clearly.
*/
public async tryToShow(needToClose = false): Promise<void> {
if (needToClose) {
this.close();
}
if (!this.allowedToShow()) {
return;
}
await this.open();
this.Editor.Toolbar.close();
}
/**
* Hides Inline Toolbar
*/
public close(): void {
if (!this.opened) {
return;
}
for (const [tool, toolInstance] of this.tools) {
const shortcut = this.getToolShortcut(tool.name);
if (shortcut !== undefined) {
Shortcuts.remove(this.Editor.UI.nodes.redactor, shortcut);
}
/**
* @todo replace 'clear' with 'destroy'
*/
if (_.isFunction(toolInstance.clear)) {
toolInstance.clear();
}
}
this.tools = new Map();
this.reset();
this.opened = false;
this.popover?.hide();
this.popover?.destroy();
this.popover = null;
}
/**
* Check if node is contained by Inline Toolbar
*
* @param {Node} node — node to check
*/
public containsNode(node: Node): boolean {
if (this.nodes.wrapper === undefined) {
return false;
}
return this.nodes.wrapper.contains(node);
}
/**
* Removes UI and its components
*/
public destroy(): void {
this.removeAllNodes();
this.popover?.destroy();
this.popover = null;
}
/**
* Making DOM
*/
private make(): void {
this.nodes.wrapper = $.make('div', [
this.CSS.inlineToolbar,
...(this.isRtl ? [ this.Editor.UI.CSS.editorRtlFix ] : []),
]);
if (import.meta.env.MODE === 'test') {
this.nodes.wrapper.setAttribute('data-cy', 'inline-toolbar');
}
/**
* Append the inline toolbar to the editor.
*/
$.append(this.Editor.UI.nodes.wrapper, this.nodes.wrapper);
}
/**
* Shows Inline Toolbar
*/
private async open(): Promise<void> {
if (this.opened) {
return;
}
/**
* Show Inline Toolbar
*/
this.opened = true;
if (this.popover !== null) {
this.popover.destroy();
}
this.createToolsInstances();
const popoverItems = await this.getPopoverItems();
this.popover = new PopoverInline({
items: popoverItems,
scopeElement: this.Editor.API.methods.ui.nodes.redactor,
messages: {
nothingFound: I18n.ui(I18nInternalNS.ui.popover, 'Nothing found'),
search: I18n.ui(I18nInternalNS.ui.popover, 'Filter'),
},
});
this.move(this.popover.size.width);
this.nodes.wrapper?.append(this.popover.getElement());
this.popover.show();
}
/**
* Move Toolbar to the selected text
*
* @param popoverWidth - width of the toolbar popover
*/
private move(popoverWidth: number): void {
const selectionRect = SelectionUtils.rect as DOMRect;
const wrapperOffset = this.Editor.UI.nodes.wrapper.getBoundingClientRect();
const newCoords = {
x: selectionRect.x - wrapperOffset.x,
y: selectionRect.y +
selectionRect.height -
// + window.scrollY
wrapperOffset.top +
this.toolbarVerticalMargin,
};
const realRightCoord = newCoords.x + popoverWidth + wrapperOffset.x;
/**
* Prevent InlineToolbar from overflowing the content zone on the right side
*/
if (realRightCoord > this.Editor.UI.contentRect.right) {
newCoords.x = this.Editor.UI.contentRect.right - popoverWidth - wrapperOffset.x;
}
this.nodes.wrapper!.style.left = Math.floor(newCoords.x) + 'px';
this.nodes.wrapper!.style.top = Math.floor(newCoords.y) + 'px';
}
/**
* Clear orientation classes and reset position
*/
private reset(): void {
this.nodes.wrapper!.style.left = '0';
this.nodes.wrapper!.style.top = '0';
}
/**
* Need to show Inline Toolbar or not
*/
private allowedToShow(): boolean {
/**
* Tags conflicts with window.selection function.
* Ex. IMG tag returns null (Firefox) or Redactors wrapper (Chrome)
*/
const tagsConflictsWithSelection = ['IMG', 'INPUT'];
const currentSelection = SelectionUtils.get();
const selectedText = SelectionUtils.text;
// old browsers
if (!currentSelection || !currentSelection.anchorNode) {
return false;
}
// empty selection
if (currentSelection.isCollapsed || selectedText.length < 1) {
return false;
}
const target = !$.isElement(currentSelection.anchorNode)
? currentSelection.anchorNode.parentElement
: currentSelection.anchorNode;
if (target === null) {
return false;
}
if (currentSelection !== null && tagsConflictsWithSelection.includes(target.tagName)) {
return false;
}
/**
* Check if there is at leas one tool enabled by current Block's Tool
*/
const currentBlock = this.Editor.BlockManager.getBlock(currentSelection.anchorNode as HTMLElement);
if (!currentBlock) {
return false;
}
/**
* Check that at least one tool is available for the current block
*/
const toolsAvailable = this.getTools();
const isAtLeastOneToolAvailable = toolsAvailable.some((tool) => currentBlock.tool.inlineTools.has(tool.name));
if (isAtLeastOneToolAvailable === false) {
return false;
}
/**
* Inline toolbar will be shown only if the target is contenteditable
* In Read-Only mode, the target should be contenteditable with "false" value
*/
const contenteditable = target.closest('[contenteditable]');
return contenteditable !== null;
}
/**
* Working with Tools
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/
/**
* Returns tools that are available for current block
*
* Used to check if Inline Toolbar could be shown
* and to render tools in the Inline Toolbar
*/
private getTools(): InlineToolAdapter[] {
const currentBlock = this.Editor.BlockManager.currentBlock;
if (!currentBlock) {
return [];
}
const inlineTools = Array.from(currentBlock.tool.inlineTools.values());
return inlineTools.filter((tool) => {
/**
* We support inline tools in read only mode.
* Such tools should have isReadOnlySupported flag set to true
*/
if (this.Editor.ReadOnly.isEnabled && tool.isReadOnlySupported !== true) {
return false;
}
return true;
});
}
/**
* Constructs tools instances and saves them to this.tools
*/
private createToolsInstances(): void {
this.tools = new Map();
const tools = this.getTools();
tools.forEach((tool) => {
const instance = tool.create();
this.tools.set(tool, instance);
});
}
/**
* Returns Popover Items for tools segregated by their appearance type: regular items and custom html elements.
*/
private async getPopoverItems(): Promise<PopoverItemParams[]> {
const popoverItems = [] as PopoverItemParams[];
let i = 0;
for (const [tool, instance] of this.tools) {
const renderedTool = await instance.render();
/** Enable tool shortcut */
const shortcut = this.getToolShortcut(tool.name);
if (shortcut !== undefined) {
try {
this.enableShortcuts(tool.name, shortcut);
} catch (e) {}
}
const shortcutBeautified = shortcut !== undefined ? _.beautifyShortcut(shortcut) : undefined;
const toolTitle = I18n.t(
I18nInternalNS.toolNames,
tool.title || _.capitalize(tool.name)
);
[ renderedTool ].flat().forEach((item) => {
const commonPopoverItemParams = {
name: tool.name,
onActivate: () => {
this.toolClicked(instance);
},
hint: {
title: toolTitle,
description: shortcutBeautified,
},
} as PopoverItemParams;
if ($.isElement(item)) {
/**
* Deprecated way to add custom html elements to the Inline Toolbar
*/
const popoverItem = {
...commonPopoverItemParams,
element: item,
type: PopoverItemType.Html,
} as PopoverItemParams;
/**
* If tool specifies actions in deprecated manner, append them as children
*/
if (_.isFunction(instance.renderActions)) {
const actions = instance.renderActions();
(popoverItem as WithChildren<PopoverItemHtmlParams>).children = {
isOpen: instance.checkState?.(SelectionUtils.get()!),
/** Disable keyboard navigation in actions, as it might conflict with enter press handling */
isFlippable: false,
items: [
{
type: PopoverItemType.Html,
element: actions,
},
],
onClose: () => {
if (_.isFunction(instance.clear)) {
instance.clear();
}
},
};
} else {
/**
* Legacy inline tools might perform some UI mutating logic in checkState method, so, call it just in case
*/
instance.checkState?.(SelectionUtils.get()!);
}
popoverItems.push(popoverItem);
} else if (item.type === PopoverItemType.Html) {
/**
* Actual way to add custom html elements to the Inline Toolbar
*/
popoverItems.push({
...commonPopoverItemParams,
...item,
type: PopoverItemType.Html,
});
} else if (item.type === PopoverItemType.Separator) {
/**
* Separator item
*/
popoverItems.push({
type: PopoverItemType.Separator,
});
} else {
/**
* Default item
*/
const popoverItem = {
...commonPopoverItemParams,
...item,
type: PopoverItemType.Default,
} as PopoverItemParams;
/**
* Prepend the separator if item has children and not the first one
*/
if ('children' in popoverItem && i !== 0) {
popoverItems.push({
type: PopoverItemType.Separator,
});
}
popoverItems.push(popoverItem);
/**
* Append a separator after the item if it has children and not the last one
*/
if ('children' in popoverItem && i < this.tools.size - 1) {
popoverItems.push({
type: PopoverItemType.Separator,
});
}
}
});
i++;
}
return popoverItems;
}
/**
* Get shortcut name for tool
*
* @param toolName — Tool name
*/
private getToolShortcut(toolName: string): string | undefined {
const { Tools } = this.Editor;
/**
* Enable shortcuts
* Ignore tool that doesn't have shortcut or empty string
*/
const tool = Tools.inlineTools.get(toolName);
/**
* 1) For internal tools, check public getter 'shortcut'
* 2) For external tools, check tool's settings
* 3) If shortcut is not set in settings, check Tool's public property
*/
const internalTools = Tools.internal.inlineTools;
if (Array.from(internalTools.keys()).includes(toolName)) {
return this.inlineTools[toolName][CommonInternalSettings.Shortcut];
}
return tool?.shortcut;
}
/**
* Enable Tool shortcut with Editor Shortcuts Module
*
* @param toolName - tool name
* @param shortcut - shortcut according to the ShortcutData Module format
*/
private enableShortcuts(toolName: string, shortcut: string): void {
Shortcuts.add({
name: shortcut,
handler: (event) => {
const { currentBlock } = this.Editor.BlockManager;
/**
* Editor is not focused
*/
if (!currentBlock) {
return;
}
/**
* We allow to fire shortcut with empty selection (isCollapsed=true)
* it can be used by tools like «Mention» that works without selection:
* Example: by SHIFT+@ show dropdown and insert selected username
*/
// if (SelectionUtils.isCollapsed) return;
if (currentBlock.tool.enabledInlineTools === false) {
return;
}
event.preventDefault();
this.popover?.activateItemByName(toolName);
},
/**
* We need to bind shortcut to the document to make it work in read-only mode
*/
on: document,
});
}
/**
* Inline Tool button clicks
*
* @param tool - Tool's instance
*/
private toolClicked(tool: IInlineTool): void {
const range = SelectionUtils.range;
tool.surround?.(range);
this.checkToolsState();
}
/**
* Check Tools` state by selection
*/
private checkToolsState(): void {
this.tools?.forEach((toolInstance) => {
toolInstance.checkState?.(SelectionUtils.get()!);
});
}
/**
* Get inline tools tools
* Tools that has isInline is true
*/
private get inlineTools(): { [name: string]: IInlineTool } {
const result = {} as { [name: string]: IInlineTool } ;
Array
.from(this.Editor.Tools.inlineTools.entries())
.forEach(([name, tool]) => {
result[name] = tool.create();
});
return result;
}
}