@ckeditor/ckeditor5-mention 47.6.1 → 48.0.0-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/mentionui.js DELETED
@@ -1,650 +0,0 @@
1
- /**
2
- * @license Copyright (c) 2003-2026, CKSource Holding sp. z o.o. All rights reserved.
3
- * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-licensing-options
4
- */
5
- /**
6
- * @module mention/mentionui
7
- */
8
- import { Plugin } from 'ckeditor5/src/core.js';
9
- import { ButtonView, ContextualBalloon, clickOutsideHandler } from 'ckeditor5/src/ui.js';
10
- import { CKEditorError, Collection, Rect, env, keyCodes, logWarning } from 'ckeditor5/src/utils.js';
11
- import { TextWatcher } from 'ckeditor5/src/typing.js';
12
- import { debounce } from 'es-toolkit/compat';
13
- import { MentionsView } from './ui/mentionsview.js';
14
- import { MentionDomWrapperView } from './ui/domwrapperview.js';
15
- import { MentionListItemView } from './ui/mentionlistitemview.js';
16
- const VERTICAL_SPACING = 3;
17
- // The key codes that mention UI handles when it is open (without commit keys).
18
- const defaultHandledKeyCodes = [
19
- keyCodes.arrowup,
20
- keyCodes.arrowdown,
21
- keyCodes.esc
22
- ];
23
- // Dropdown commit key codes.
24
- const defaultCommitKeyCodes = [
25
- keyCodes.enter,
26
- keyCodes.tab
27
- ];
28
- /**
29
- * The mention UI feature.
30
- */
31
- export class MentionUI extends Plugin {
32
- /**
33
- * The mention view.
34
- */
35
- _mentionsView;
36
- /**
37
- * Stores mention feeds configurations.
38
- */
39
- _mentionsConfigurations;
40
- /**
41
- * The contextual balloon plugin instance.
42
- */
43
- _balloon;
44
- _items = new Collection();
45
- _lastRequested;
46
- /**
47
- * Debounced feed requester. It uses `es-toolkit#debounce` method to delay function call.
48
- */
49
- _requestFeedDebounced;
50
- /**
51
- * @inheritDoc
52
- */
53
- static get pluginName() {
54
- return 'MentionUI';
55
- }
56
- /**
57
- * @inheritDoc
58
- */
59
- static get isOfficialPlugin() {
60
- return true;
61
- }
62
- /**
63
- * @inheritDoc
64
- */
65
- static get requires() {
66
- return [ContextualBalloon];
67
- }
68
- /**
69
- * @inheritDoc
70
- */
71
- constructor(editor) {
72
- super(editor);
73
- this._mentionsView = this._createMentionView();
74
- this._mentionsConfigurations = new Map();
75
- this._requestFeedDebounced = debounce(this._requestFeed, 100);
76
- editor.config.define('mention', { feeds: [] });
77
- }
78
- /**
79
- * @inheritDoc
80
- */
81
- init() {
82
- const editor = this.editor;
83
- const commitKeys = editor.config.get('mention.commitKeys') || defaultCommitKeyCodes;
84
- const handledKeyCodes = defaultHandledKeyCodes.concat(commitKeys);
85
- this._balloon = editor.plugins.get(ContextualBalloon);
86
- // Key listener that handles navigation in mention view.
87
- editor.editing.view.document.on('keydown', (evt, data) => {
88
- if (isHandledKey(data.keyCode) && this._isUIVisible) {
89
- data.preventDefault();
90
- evt.stop(); // Required for Enter key overriding.
91
- if (data.keyCode == keyCodes.arrowdown) {
92
- this._mentionsView.selectNext();
93
- }
94
- if (data.keyCode == keyCodes.arrowup) {
95
- this._mentionsView.selectPrevious();
96
- }
97
- if (commitKeys.includes(data.keyCode)) {
98
- this._mentionsView.executeSelected();
99
- }
100
- if (data.keyCode == keyCodes.esc) {
101
- this._hideUIAndRemoveMarker();
102
- }
103
- }
104
- }, { priority: 'highest' }); // Required to override the Enter key.
105
- // Close the dropdown upon clicking outside of the plugin UI.
106
- clickOutsideHandler({
107
- emitter: this._mentionsView,
108
- activator: () => this._isUIVisible,
109
- contextElements: () => [this._balloon.view.element],
110
- callback: () => this._hideUIAndRemoveMarker()
111
- });
112
- const feeds = editor.config.get('mention.feeds');
113
- for (const mentionDescription of feeds) {
114
- const { feed, marker, dropdownLimit } = mentionDescription;
115
- if (!isValidMentionMarker(marker)) {
116
- /**
117
- * The marker must be a single character.
118
- *
119
- * Correct markers: `'@'`, `'#'`.
120
- *
121
- * Incorrect markers: `'$$'`, `'[@'`.
122
- *
123
- * See {@link module:mention/mentionconfig~MentionConfig}.
124
- *
125
- * @error mentionconfig-incorrect-marker
126
- * @param {string} marker Configured marker
127
- */
128
- throw new CKEditorError('mentionconfig-incorrect-marker', null, { marker });
129
- }
130
- const feedCallback = typeof feed == 'function' ? feed.bind(this.editor) : createFeedCallback(feed);
131
- const itemRenderer = mentionDescription.itemRenderer;
132
- const definition = { marker, feedCallback, itemRenderer, dropdownLimit };
133
- this._mentionsConfigurations.set(marker, definition);
134
- }
135
- this._setupTextWatcher(feeds);
136
- this.listenTo(editor, 'change:isReadOnly', () => {
137
- this._hideUIAndRemoveMarker();
138
- });
139
- this.on('requestFeed:response', (evt, data) => this._handleFeedResponse(data));
140
- this.on('requestFeed:error', () => this._hideUIAndRemoveMarker());
141
- /**
142
- * Checks if a given key code is handled by the mention UI.
143
- */
144
- function isHandledKey(keyCode) {
145
- return handledKeyCodes.includes(keyCode);
146
- }
147
- }
148
- /**
149
- * @inheritDoc
150
- */
151
- destroy() {
152
- super.destroy();
153
- // Destroy created UI components as they are not automatically destroyed (see ckeditor5#1341).
154
- this._mentionsView.destroy();
155
- }
156
- /**
157
- * Returns true when {@link #_mentionsView} is in the {@link module:ui/panel/balloon/contextualballoon~ContextualBalloon} and it is
158
- * currently visible.
159
- */
160
- get _isUIVisible() {
161
- return this._balloon.visibleView === this._mentionsView;
162
- }
163
- /**
164
- * Creates the {@link #_mentionsView}.
165
- */
166
- _createMentionView() {
167
- const locale = this.editor.locale;
168
- const mentionsView = new MentionsView(locale);
169
- mentionsView.items.bindTo(this._items).using(data => {
170
- const { item, marker } = data;
171
- const { dropdownLimit: markerDropdownLimit } = this._mentionsConfigurations.get(marker);
172
- // Set to 10 by default for backwards compatibility. See: #10479
173
- const dropdownLimit = markerDropdownLimit || this.editor.config.get('mention.dropdownLimit') || 10;
174
- if (mentionsView.items.length >= dropdownLimit) {
175
- return null;
176
- }
177
- const listItemView = new MentionListItemView(locale);
178
- const view = this._renderItem(item, marker);
179
- view.delegate('execute').to(listItemView);
180
- listItemView.children.add(view);
181
- listItemView.item = item;
182
- listItemView.marker = marker;
183
- listItemView.on('execute', () => {
184
- mentionsView.fire('execute', {
185
- item,
186
- marker
187
- });
188
- });
189
- return listItemView;
190
- });
191
- mentionsView.on('execute', (evt, data) => {
192
- const editor = this.editor;
193
- const model = editor.model;
194
- const item = data.item;
195
- const marker = data.marker;
196
- const mentionMarker = editor.model.markers.get('mention');
197
- // Create a range on matched text.
198
- const end = model.createPositionAt(model.document.selection.focus);
199
- const start = model.createPositionAt(mentionMarker.getStart());
200
- const range = model.createRange(start, end);
201
- this._hideUIAndRemoveMarker();
202
- editor.execute('mention', {
203
- mention: item,
204
- text: item.text,
205
- marker,
206
- range
207
- });
208
- editor.editing.view.focus();
209
- });
210
- return mentionsView;
211
- }
212
- /**
213
- * Returns item renderer for the marker.
214
- */
215
- _getItemRenderer(marker) {
216
- const { itemRenderer } = this._mentionsConfigurations.get(marker);
217
- return itemRenderer;
218
- }
219
- /**
220
- * Requests a feed from a configured callbacks.
221
- */
222
- _requestFeed(marker, feedText) {
223
- // @if CK_DEBUG_MENTION // console.log( '%c[Feed]%c Requesting for', 'color: blue', 'color: black', `"${ feedText }"` );
224
- // Store the last requested feed - it is used to discard any out-of order requests.
225
- this._lastRequested = feedText;
226
- const { feedCallback } = this._mentionsConfigurations.get(marker);
227
- const feedResponse = feedCallback(feedText);
228
- const isAsynchronous = feedResponse instanceof Promise;
229
- // For synchronous feeds (e.g. callbacks, arrays) fire the response event immediately.
230
- if (!isAsynchronous) {
231
- this.fire('requestFeed:response', { feed: feedResponse, marker, feedText });
232
- return;
233
- }
234
- // Handle the asynchronous responses.
235
- feedResponse
236
- .then(response => {
237
- // Check the feed text of this response with the last requested one so either:
238
- if (this._lastRequested == feedText) {
239
- // It is the same and fire the response event.
240
- this.fire('requestFeed:response', { feed: response, marker, feedText });
241
- }
242
- else {
243
- // It is different - most probably out-of-order one, so fire the discarded event.
244
- this.fire('requestFeed:discarded', { feed: response, marker, feedText });
245
- }
246
- })
247
- .catch(error => {
248
- this.fire('requestFeed:error', { error });
249
- /**
250
- * The callback used for obtaining mention autocomplete feed thrown and error and the mention UI was hidden or
251
- * not displayed at all.
252
- *
253
- * @error mention-feed-callback-error
254
- */
255
- logWarning('mention-feed-callback-error', { marker });
256
- });
257
- }
258
- /**
259
- * Registers a text watcher for the marker.
260
- */
261
- _setupTextWatcher(feeds) {
262
- const editor = this.editor;
263
- const feedsWithPattern = feeds.map(feed => ({
264
- ...feed,
265
- pattern: createRegExp(feed.marker, feed.minimumCharacters || 0)
266
- }));
267
- const watcher = new TextWatcher(editor.model, createTestCallback(feedsWithPattern));
268
- watcher.on('matched', (evt, data) => {
269
- const markerDefinition = getLastValidMarkerInText(feedsWithPattern, data.text);
270
- const selection = editor.model.document.selection;
271
- const focus = selection.focus;
272
- const markerPosition = editor.model.createPositionAt(focus.parent, markerDefinition.position);
273
- if (isPositionInExistingMention(focus) || isMarkerInExistingMention(markerPosition)) {
274
- this._hideUIAndRemoveMarker();
275
- return;
276
- }
277
- const feedText = requestFeedText(markerDefinition, data.text);
278
- const matchedTextLength = markerDefinition.marker.length + feedText.length;
279
- // Create a marker range.
280
- const start = focus.getShiftedBy(-matchedTextLength);
281
- const end = focus.getShiftedBy(-feedText.length);
282
- const markerRange = editor.model.createRange(start, end);
283
- // @if CK_DEBUG_MENTION // console.group( '%c[TextWatcher]%c matched', 'color: red', 'color: black', `"${ feedText }"` );
284
- // @if CK_DEBUG_MENTION // console.log( 'data#text', `"${ data.text }"` );
285
- // @if CK_DEBUG_MENTION // console.log( 'data#range', data.range.start.path, data.range.end.path );
286
- // @if CK_DEBUG_MENTION // console.log( 'marker definition', markerDefinition );
287
- // @if CK_DEBUG_MENTION // console.log( 'marker range', markerRange.start.path, markerRange.end.path );
288
- if (checkIfStillInCompletionMode(editor)) {
289
- const mentionMarker = editor.model.markers.get('mention');
290
- // Update the marker - user might've moved the selection to other mention trigger.
291
- editor.model.change(writer => {
292
- // @if CK_DEBUG_MENTION // console.log( '%c[Editing]%c Updating the marker.', 'color: purple', 'color: black' );
293
- writer.updateMarker(mentionMarker, { range: markerRange });
294
- });
295
- }
296
- else {
297
- editor.model.change(writer => {
298
- // @if CK_DEBUG_MENTION // console.log( '%c[Editing]%c Adding the marker.', 'color: purple', 'color: black' );
299
- writer.addMarker('mention', { range: markerRange, usingOperation: false, affectsData: false });
300
- });
301
- }
302
- this._requestFeedDebounced(markerDefinition.marker, feedText);
303
- // @if CK_DEBUG_MENTION // console.groupEnd();
304
- });
305
- watcher.on('unmatched', () => {
306
- this._hideUIAndRemoveMarker();
307
- });
308
- const mentionCommand = editor.commands.get('mention');
309
- watcher.bind('isEnabled').to(mentionCommand);
310
- return watcher;
311
- }
312
- /**
313
- * Handles the feed response event data.
314
- */
315
- _handleFeedResponse(data) {
316
- const { feed, marker } = data;
317
- // eslint-disable-next-line @stylistic/max-len
318
- // @if CK_DEBUG_MENTION // console.log( `%c[Feed]%c Response for "${ data.feedText }" (${ feed.length })`, 'color: blue', 'color: black', feed );
319
- // If the marker is not in the document happens when the selection had changed and the 'mention' marker was removed.
320
- if (!checkIfStillInCompletionMode(this.editor)) {
321
- return;
322
- }
323
- // Reset the view.
324
- this._items.clear();
325
- for (const feedItem of feed) {
326
- const item = typeof feedItem != 'object' ? { id: feedItem, text: feedItem } : feedItem;
327
- this._items.add({ item, marker });
328
- }
329
- const mentionMarker = this.editor.model.markers.get('mention');
330
- if (this._items.length) {
331
- this._showOrUpdateUI(mentionMarker);
332
- }
333
- else {
334
- // Do not show empty mention UI.
335
- this._hideUIAndRemoveMarker();
336
- }
337
- }
338
- /**
339
- * Shows the mentions balloon. If the panel is already visible, it will reposition it.
340
- */
341
- _showOrUpdateUI(markerMarker) {
342
- if (this._isUIVisible) {
343
- // @if CK_DEBUG_MENTION // console.log( '%c[UI]%c Updating position.', 'color: green', 'color: black' );
344
- // Update balloon position as the mention list view may change its size.
345
- this._balloon.updatePosition(this._getBalloonPanelPositionData(markerMarker, this._mentionsView.position));
346
- }
347
- else {
348
- // @if CK_DEBUG_MENTION // console.log( '%c[UI]%c Showing the UI.', 'color: green', 'color: black' );
349
- this._balloon.add({
350
- view: this._mentionsView,
351
- position: this._getBalloonPanelPositionData(markerMarker, this._mentionsView.position),
352
- singleViewMode: true,
353
- balloonClassName: 'ck-mention-balloon'
354
- });
355
- }
356
- this._mentionsView.position = this._balloon.view.position;
357
- this._mentionsView.selectFirst();
358
- }
359
- /**
360
- * Hides the mentions balloon and removes the 'mention' marker from the markers collection.
361
- */
362
- _hideUIAndRemoveMarker() {
363
- // Remove the mention view from balloon before removing marker - it is used by balloon position target().
364
- if (this._balloon.hasView(this._mentionsView)) {
365
- // @if CK_DEBUG_MENTION // console.log( '%c[UI]%c Hiding the UI.', 'color: green', 'color: black' );
366
- this._balloon.remove(this._mentionsView);
367
- }
368
- if (checkIfStillInCompletionMode(this.editor)) {
369
- // @if CK_DEBUG_MENTION // console.log( '%c[Editing]%c Removing marker.', 'color: purple', 'color: black' );
370
- this.editor.model.change(writer => writer.removeMarker('mention'));
371
- }
372
- // Make the last matched position on panel view undefined so the #_getBalloonPanelPositionData() method will return all positions
373
- // on the next call.
374
- this._mentionsView.position = undefined;
375
- }
376
- /**
377
- * Renders a single item in the autocomplete list.
378
- */
379
- _renderItem(item, marker) {
380
- const editor = this.editor;
381
- let view;
382
- let label = item.id;
383
- const renderer = this._getItemRenderer(marker);
384
- if (renderer) {
385
- const renderResult = renderer(item);
386
- if (typeof renderResult != 'string') {
387
- view = new MentionDomWrapperView(editor.locale, renderResult);
388
- }
389
- else {
390
- label = renderResult;
391
- }
392
- }
393
- if (!view) {
394
- const buttonView = new ButtonView(editor.locale);
395
- buttonView.label = label;
396
- buttonView.withText = true;
397
- view = buttonView;
398
- }
399
- return view;
400
- }
401
- /**
402
- * Creates a position options object used to position the balloon panel.
403
- *
404
- * @param mentionMarker
405
- * @param preferredPosition The name of the last matched position name.
406
- */
407
- _getBalloonPanelPositionData(mentionMarker, preferredPosition) {
408
- const editor = this.editor;
409
- const editing = editor.editing;
410
- const domConverter = editing.view.domConverter;
411
- const mapper = editing.mapper;
412
- const uiLanguageDirection = editor.locale.uiLanguageDirection;
413
- return {
414
- target: () => {
415
- let modelRange = mentionMarker.getRange();
416
- // Target the UI to the model selection range - the marker has been removed so probably the UI will not be shown anyway.
417
- // The logic is used by ContextualBalloon to display another panel in the same place.
418
- if (modelRange.start.root.rootName == '$graveyard') {
419
- modelRange = editor.model.document.selection.getFirstRange();
420
- }
421
- const viewRange = mapper.toViewRange(modelRange);
422
- const rangeRects = Rect.getDomRangeRects(domConverter.viewRangeToDom(viewRange));
423
- return rangeRects.pop();
424
- },
425
- limiter: () => {
426
- const view = this.editor.editing.view;
427
- const viewDocument = view.document;
428
- const editableElement = viewDocument.selection.editableElement;
429
- if (editableElement) {
430
- return view.domConverter.mapViewToDom(editableElement.root);
431
- }
432
- return null;
433
- },
434
- positions: getBalloonPanelPositions(preferredPosition, uiLanguageDirection)
435
- };
436
- }
437
- }
438
- /**
439
- * Returns the balloon positions data callbacks.
440
- */
441
- function getBalloonPanelPositions(preferredPosition, uiLanguageDirection) {
442
- const positions = {
443
- // Positions the panel to the southeast of the caret rectangle.
444
- 'caret_se': (targetRect) => {
445
- return {
446
- top: targetRect.bottom + VERTICAL_SPACING,
447
- left: targetRect.right,
448
- name: 'caret_se',
449
- config: {
450
- withArrow: false
451
- }
452
- };
453
- },
454
- // Positions the panel to the northeast of the caret rectangle.
455
- 'caret_ne': (targetRect, balloonRect) => {
456
- return {
457
- top: targetRect.top - balloonRect.height - VERTICAL_SPACING,
458
- left: targetRect.right,
459
- name: 'caret_ne',
460
- config: {
461
- withArrow: false
462
- }
463
- };
464
- },
465
- // Positions the panel to the southwest of the caret rectangle.
466
- 'caret_sw': (targetRect, balloonRect) => {
467
- return {
468
- top: targetRect.bottom + VERTICAL_SPACING,
469
- left: targetRect.right - balloonRect.width,
470
- name: 'caret_sw',
471
- config: {
472
- withArrow: false
473
- }
474
- };
475
- },
476
- // Positions the panel to the northwest of the caret rect.
477
- 'caret_nw': (targetRect, balloonRect) => {
478
- return {
479
- top: targetRect.top - balloonRect.height - VERTICAL_SPACING,
480
- left: targetRect.right - balloonRect.width,
481
- name: 'caret_nw',
482
- config: {
483
- withArrow: false
484
- }
485
- };
486
- }
487
- };
488
- // Returns only the last position if it was matched to prevent the panel from jumping after the first match.
489
- if (Object.prototype.hasOwnProperty.call(positions, preferredPosition)) {
490
- return [
491
- positions[preferredPosition]
492
- ];
493
- }
494
- // By default, return all position callbacks ordered depending on the UI language direction.
495
- return uiLanguageDirection !== 'rtl' ? [
496
- positions.caret_se,
497
- positions.caret_sw,
498
- positions.caret_ne,
499
- positions.caret_nw
500
- ] : [
501
- positions.caret_sw,
502
- positions.caret_se,
503
- positions.caret_nw,
504
- positions.caret_ne
505
- ];
506
- }
507
- /**
508
- * Returns a marker definition of the last valid occurring marker in a given string.
509
- * If there is no valid marker in a string, it returns undefined.
510
- *
511
- * Example of returned object:
512
- *
513
- * ```ts
514
- * {
515
- * marker: '@',
516
- * position: 4,
517
- * minimumCharacters: 0
518
- * }
519
- * ````
520
- *
521
- * @param feedsWithPattern Registered feeds in editor for mention plugin with created RegExp for matching marker.
522
- * @param text String to find the marker in
523
- * @returns Matched marker's definition
524
- */
525
- function getLastValidMarkerInText(feedsWithPattern, text) {
526
- let lastValidMarker;
527
- for (const feed of feedsWithPattern) {
528
- const currentMarkerLastIndex = text.lastIndexOf(feed.marker);
529
- if (currentMarkerLastIndex > 0 && !text.substring(currentMarkerLastIndex - 1).match(feed.pattern)) {
530
- continue;
531
- }
532
- if (!lastValidMarker || currentMarkerLastIndex >= lastValidMarker.position) {
533
- lastValidMarker = {
534
- marker: feed.marker,
535
- position: currentMarkerLastIndex,
536
- minimumCharacters: feed.minimumCharacters,
537
- pattern: feed.pattern
538
- };
539
- }
540
- }
541
- return lastValidMarker;
542
- }
543
- /**
544
- * Creates a RegExp pattern for the marker.
545
- *
546
- * Function has to be exported to achieve 100% code coverage.
547
- *
548
- * @internal
549
- */
550
- export function createRegExp(marker, minimumCharacters) {
551
- const numberOfCharacters = minimumCharacters == 0 ? '*' : `{${minimumCharacters},}`;
552
- const openAfterCharacters = env.features.isRegExpUnicodePropertySupported ? '\\p{Ps}\\p{Pi}"\'' : '\\(\\[{"\'';
553
- const mentionCharacters = '.';
554
- // I wanted to make an util out of it, but since this regexp uses "u" flag, it became difficult.
555
- // When "u" flag is used, the regexp has "strict" escaping rules, i.e. if you try to escape a character that does not need
556
- // to be escaped, RegExp() will throw. It made it difficult to write a generic util, because different characters are
557
- // allowed in different context. For example, escaping "-" sometimes was correct, but sometimes it threw an error.
558
- marker = marker.replace(/[.*+?^${}()\-|[\]\\]/g, '\\$&');
559
- // The pattern consists of 3 groups:
560
- //
561
- // - 0 (non-capturing): Opening sequence - start of the line, space or an opening punctuation character like "(" or "\"",
562
- // - 1: The marker character(s),
563
- // - 2: Mention input (taking the minimal length into consideration to trigger the UI),
564
- //
565
- // The pattern matches up to the caret (end of string switch - $).
566
- // (0: opening sequence )(1: marker )(2: typed mention )$
567
- const pattern = `(?:^|[ ${openAfterCharacters}])(${marker})(${mentionCharacters}${numberOfCharacters})$`;
568
- return new RegExp(pattern, 'u');
569
- }
570
- /**
571
- * Creates a test callback for the marker to be used in the text watcher instance.
572
- *
573
- * @param feedsWithPattern Feeds of mention plugin configured in editor with RegExp to match marker in text
574
- */
575
- function createTestCallback(feedsWithPattern) {
576
- const textMatcher = (text) => {
577
- const markerDefinition = getLastValidMarkerInText(feedsWithPattern, text);
578
- if (!markerDefinition) {
579
- return false;
580
- }
581
- let splitStringFrom = 0;
582
- if (markerDefinition.position !== 0) {
583
- splitStringFrom = markerDefinition.position - 1;
584
- }
585
- const textToTest = text.substring(splitStringFrom);
586
- return markerDefinition.pattern.test(textToTest);
587
- };
588
- return textMatcher;
589
- }
590
- /**
591
- * Creates a text matcher from the marker.
592
- */
593
- function requestFeedText(markerDefinition, text) {
594
- let splitStringFrom = 0;
595
- if (markerDefinition.position !== 0) {
596
- splitStringFrom = markerDefinition.position - 1;
597
- }
598
- const regExp = createRegExp(markerDefinition.marker, 0);
599
- const textToMatch = text.substring(splitStringFrom);
600
- const match = textToMatch.match(regExp);
601
- return match[2];
602
- }
603
- /**
604
- * The default feed callback.
605
- */
606
- function createFeedCallback(feedItems) {
607
- return (feedText) => {
608
- const filteredItems = feedItems
609
- // Make the default mention feed case-insensitive.
610
- .filter(item => {
611
- // Item might be defined as object.
612
- const itemId = typeof item == 'string' ? item : String(item.id);
613
- // The default feed is case insensitive.
614
- return itemId.toLowerCase().includes(feedText.toLowerCase());
615
- });
616
- return filteredItems;
617
- };
618
- }
619
- /**
620
- * Checks if position in inside or right after a text with a mention.
621
- */
622
- function isPositionInExistingMention(position) {
623
- // The text watcher listens only to changed range in selection - so the selection attributes are not yet available
624
- // and you cannot use selection.hasAttribute( 'mention' ) just yet.
625
- // See https://github.com/ckeditor/ckeditor5-engine/issues/1723.
626
- const hasMention = position.textNode && position.textNode.hasAttribute('mention');
627
- const nodeBefore = position.nodeBefore;
628
- return hasMention || nodeBefore && nodeBefore.is('$text') && nodeBefore.hasAttribute('mention');
629
- }
630
- /**
631
- * Checks if the closest marker offset is at the beginning of a mention.
632
- *
633
- * See https://github.com/ckeditor/ckeditor5/issues/11400.
634
- */
635
- function isMarkerInExistingMention(markerPosition) {
636
- const nodeAfter = markerPosition.nodeAfter;
637
- return nodeAfter && nodeAfter.is('$text') && nodeAfter.hasAttribute('mention');
638
- }
639
- /**
640
- * Checks if string is a valid mention marker.
641
- */
642
- function isValidMentionMarker(marker) {
643
- return !!marker;
644
- }
645
- /**
646
- * Checks the mention plugins is in completion mode (e.g. when typing is after a valid mention string like @foo).
647
- */
648
- function checkIfStillInCompletionMode(editor) {
649
- return editor.model.markers.has('mention');
650
- }