-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
Copy pathplugin.js
1486 lines (1333 loc) · 46.1 KB
/
plugin.js
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
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @license Copyright (c) 2003-2020, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/
'use strict';
( function() {
CKEDITOR.plugins.add( 'autocomplete', {
requires: 'textwatcher',
onLoad: function() {
CKEDITOR.document.appendStyleSheet( this.path + 'skins/default.css' );
},
isSupportedEnvironment: function() {
return !CKEDITOR.env.ie || CKEDITOR.env.version > 8;
}
} );
/**
* The main class implementing a generic [Autocomplete](https://ckeditor.com/cke4/addon/autocomplete) feature in the editor.
* It acts as a controller that works with the {@link CKEDITOR.plugins.autocomplete.model model} and
* {@link CKEDITOR.plugins.autocomplete.view view} classes.
*
* It is possible to maintain multiple autocomplete instances for a single editor at a time.
* In order to create an autocomplete instance use its {@link #constructor constructor}.
*
* @class CKEDITOR.plugins.autocomplete
* @since 4.10.0
* @constructor Creates a new instance of autocomplete and attaches it to the editor.
*
* In order to initialize the autocomplete feature it is enough to instantiate this class with
* two required callbacks:
*
* * {@link CKEDITOR.plugins.autocomplete.configDefinition#textTestCallback config.textTestCallback} – A function being called by
* the {@link CKEDITOR.plugins.textWatcher text watcher} plugin, as new text is being inserted.
* Its purpose is to determine whether a given range should be matched or not.
* See {@link CKEDITOR.plugins.textWatcher#constructor} for more details.
* There is also {@link CKEDITOR.plugins.textMatch#match} which is a handy helper for that purpose.
* * {@link CKEDITOR.plugins.autocomplete.configDefinition#dataCallback config.dataCallback} – A function that should return
* (through its callback) suggestion data for the current query string.
*
* # Creating an autocomplete instance
*
* Depending on your use case, put this code in the {@link CKEDITOR.pluginDefinition#init} callback of your
* plugin or, for example, in the {@link CKEDITOR.editor#instanceReady} event listener. Ensure that you loaded the
* {@link CKEDITOR.plugins.textMatch Text Match} plugin.
*
* ```javascript
* var itemsArray = [ { id: 1, name: '@Andrew' }, { id: 2, name: '@Kate' } ];
*
* // Called when the user types in the editor or moves the caret.
* // The range represents the caret position.
* function textTestCallback( range ) {
* // You do not want to autocomplete a non-empty selection.
* if ( !range.collapsed ) {
* return null;
* }
*
* // Use the text match plugin which does the tricky job of doing
* // a text search in the DOM. The matchCallback function should return
* // a matching fragment of the text.
* return CKEDITOR.plugins.textMatch.match( range, matchCallback );
* }
*
* // Returns the position of the matching text.
* // It matches with a word starting from the '@' character
* // up to the caret position.
* function matchCallback( text, offset ) {
* // Get the text before the caret.
* var left = text.slice( 0, offset ),
* // Will look for an '@' character followed by word characters.
* match = left.match( /@\w*$/ );
*
* if ( !match ) {
* return null;
* }
*
* return { start: match.index, end: offset };
* }
*
* // Returns (through its callback) the suggestions for the current query.
* function dataCallback( matchInfo, callback ) {
* // Simple search.
* // Filter the entire items array so only the items that start
* // with the query remain.
* var suggestions = itemsArray.filter( function( item ) {
* return item.name.toLowerCase().indexOf( matchInfo.query.toLowerCase() ) == 0;
* } );
*
* // Note: The callback function can also be executed asynchronously
* // so dataCallback can do XHR requests or use any other asynchronous API.
* callback( suggestions );
* }
*
* // Finally, instantiate the autocomplete class.
* new CKEDITOR.plugins.autocomplete( editor, {
* textTestCallback: textTestCallback,
* dataCallback: dataCallback
* } );
* ```
*
* # Changing the behavior of the autocomplete class by subclassing it
*
* This plugin will expose a `CKEDITOR.plugins.customAutocomplete` class which uses
* a custom view that positions the panel relative to the {@link CKEDITOR.editor#container}.
*
* ```javascript
* CKEDITOR.plugins.add( 'customautocomplete', {
* requires: 'autocomplete',
*
* onLoad: function() {
* var View = CKEDITOR.plugins.autocomplete.view,
* Autocomplete = CKEDITOR.plugins.autocomplete;
*
* function CustomView( editor ) {
* // Call the parent class constructor.
* View.call( this, editor );
* }
* // Inherit the view methods.
* CustomView.prototype = CKEDITOR.tools.prototypedCopy( View.prototype );
*
* // Change the positioning of the panel, so it is stretched
* // to 100% of the editor container width and is positioned
* // relative to the editor container.
* CustomView.prototype.updatePosition = function( range ) {
* var caretRect = this.getViewPosition( range ),
* container = this.editor.container;
*
* this.setPosition( {
* // Position the panel relative to the editor container.
* left: container.$.offsetLeft,
* top: caretRect.top,
* bottom: caretRect.bottom
* } );
* // Stretch the panel to 100% of the editor container width.
* this.element.setStyle( 'width', container.getSize( 'width' ) + 'px' );
* };
*
* function CustomAutocomplete( editor, configDefinition ) {
* // Call the parent class constructor.
* Autocomplete.call( this, editor, configDefinition );
* }
* // Inherit the autocomplete methods.
* CustomAutocomplete.prototype = CKEDITOR.tools.prototypedCopy( Autocomplete.prototype );
*
* CustomAutocomplete.prototype.getView = function() {
* return new CustomView( this.editor );
* }
*
* // Expose the custom autocomplete so it can be used later.
* CKEDITOR.plugins.customAutocomplete = CustomAutocomplete;
* }
* } );
* ```
* @param {CKEDITOR.editor} editor The editor to watch.
* @param {CKEDITOR.plugins.autocomplete.configDefinition} config Configuration object for this autocomplete instance.
*/
function Autocomplete( editor, config ) {
var configKeystrokes = editor.config.autocomplete_commitKeystrokes || CKEDITOR.config.autocomplete_commitKeystrokes;
/**
* The editor instance that autocomplete is attached to.
*
* @readonly
* @property {CKEDITOR.editor}
*/
this.editor = editor;
/**
* Indicates throttle threshold expressed in milliseconds, reducing text checks frequency.
*
* @property {Number} [throttle=20]
*/
this.throttle = config.throttle !== undefined ? config.throttle : 20;
/**
* The autocomplete view instance.
*
* @readonly
* @property {CKEDITOR.plugins.autocomplete.view}
*/
this.view = this.getView();
/**
* The autocomplete model instance.
*
* @readonly
* @property {CKEDITOR.plugins.autocomplete.model}
*/
this.model = this.getModel( config.dataCallback );
this.model.itemsLimit = config.itemsLimit;
/**
* The autocomplete text watcher instance.
*
* @readonly
* @property {CKEDITOR.plugins.textWatcher}
*/
this.textWatcher = this.getTextWatcher( config.textTestCallback );
/**
* The autocomplete keystrokes used to finish autocompletion with the selected view item.
* The property is using the {@link CKEDITOR.config#autocomplete_commitKeystrokes} configuration option as default keystrokes.
* You can change this property to set individual keystrokes for the plugin instance.
*
* @property {Number[]}
* @readonly
*/
this.commitKeystrokes = CKEDITOR.tools.array.isArray( configKeystrokes ) ? configKeystrokes.slice() : [ configKeystrokes ];
/**
* Listeners registered by this autocomplete instance.
*
* @private
*/
this._listeners = [];
/**
* Template of markup to be inserted as the autocomplete item gets committed.
*
* You can use {@link CKEDITOR.plugins.autocomplete.model.item item} properties to customize the template.
*
* ```javascript
* var outputTemplate = `<a href="/tracker/{ticket}">#{ticket} ({name})</a>`;
* ```
*
* @readonly
* @property {CKEDITOR.template} [outputTemplate=null]
*/
this.outputTemplate = config.outputTemplate !== undefined ? new CKEDITOR.template( config.outputTemplate ) : null;
if ( config.itemTemplate ) {
this.view.itemTemplate = new CKEDITOR.template( config.itemTemplate );
}
// Attach autocomplete when editor instance is ready (#2114).
if ( this.editor.status === 'ready' ) {
this.attach();
} else {
this.editor.on( 'instanceReady', function() {
this.attach();
}, this );
}
editor.on( 'destroy', function() {
this.destroy();
}, this );
}
Autocomplete.prototype = {
/**
* Attaches the autocomplete to the {@link #editor}.
*
* * The view is appended to the DOM and the listeners are attached.
* * The {@link #textWatcher text watcher} is attached to the editor.
* * The listeners on the {@link #model} and {@link #view} events are added.
*/
attach: function() {
var editor = this.editor,
win = CKEDITOR.document.getWindow(),
editable = editor.editable(),
editorScrollableElement = editable.isInline() ? editable : editable.getDocument();
// iOS classic editor listens on frame parent element for editor `scroll` event (#1910).
if ( CKEDITOR.env.iOS && !editable.isInline() ) {
editorScrollableElement = iOSViewportElement( editor );
}
this.view.append();
this.view.attach();
this.textWatcher.attach();
this._listeners.push( this.textWatcher.on( 'matched', this.onTextMatched, this ) );
this._listeners.push( this.textWatcher.on( 'unmatched', this.onTextUnmatched, this ) );
this._listeners.push( this.model.on( 'change-data', this.modelChangeListener, this ) );
this._listeners.push( this.model.on( 'change-selectedItemId', this.onSelectedItemId, this ) );
this._listeners.push( this.view.on( 'change-selectedItemId', this.onSelectedItemId, this ) );
this._listeners.push( this.view.on( 'click-item', this.onItemClick, this ) );
// Update view position on viewport change.
// Note: CKEditor's event system has a limitation that one function
// cannot be used as listener for the same event more than once. Hence, wrapper functions.
this._listeners.push( win.on( 'scroll', function() {
this.viewRepositionListener();
}, this ) );
this._listeners.push( editorScrollableElement.on( 'scroll', function() {
this.viewRepositionListener();
}, this ) );
this._listeners.push( editor.on( 'contentDom', onContentDom, this ) );
// Don't let browser to focus dropdown element (#2107).
this._listeners.push( this.view.element.on( 'mousedown', function( e ) {
e.data.preventDefault();
}, null, null, 9999 ) );
// Attach if editor is already initialized.
if ( editable ) {
onContentDom.call( this );
}
function onContentDom() {
// Priority 5 to get before the enterkey.
// Note: CKEditor's event system has a limitation that one function (in this case this.onKeyDown)
// cannot be used as listener for the same event more than once. Hence, wrapper function.
this._listeners.push( editable.on( 'keydown', function( evt ) {
this.onKeyDown( evt );
}, this, null, 5 ) );
}
},
/**
* Closes the view and sets its {@link CKEDITOR.plugins.autocomplete.model#isActive state} to inactive.
*/
close: function() {
this.model.setActive( false );
this.view.close();
},
/**
* Commits the currently chosen or given item. HTML is generated for this item using the
* {@link #getHtmlToInsert} method and then it is inserted into the editor. The item is inserted
* into the {@link CKEDITOR.plugins.autocomplete.model#range query's range}, so the query text is
* replaced by the inserted HTML.
*
* @param {Number/String} [itemId] If given, then the specified item will be inserted into the editor
* instead of the currently chosen one.
*/
commit: function( itemId ) {
if ( !this.model.isActive ) {
return;
}
this.close();
if ( itemId == null ) {
itemId = this.model.selectedItemId;
// If non item is selected abort commit.
if ( itemId == null ) {
return;
}
}
var item = this.model.getItemById( itemId ),
editor = this.editor;
editor.fire( 'saveSnapshot' );
editor.getSelection().selectRanges( [ this.model.range ] );
editor.insertHtml( this.getHtmlToInsert( item ), 'text' );
editor.fire( 'saveSnapshot' );
},
/**
* Destroys the autocomplete instance.
* View element and event listeners will be removed from the DOM.
*/
destroy: function() {
CKEDITOR.tools.array.forEach( this._listeners, function( obj ) {
obj.removeListener();
} );
this._listeners = [];
this.view.element && this.view.element.remove();
},
/**
* Returns HTML that should be inserted into the editor when the item is committed.
*
* See also the {@link #commit} method.
*
* @param {CKEDITOR.plugins.autocomplete.model.item} item
* @returns {String} The HTML to insert.
*/
getHtmlToInsert: function( item ) {
var encodedItem = encodeItem( item );
return this.outputTemplate ? this.outputTemplate.output( encodedItem ) : encodedItem.name;
},
/**
* Creates and returns the model instance. This method is used when
* initializing the autocomplete and can be overwritten in order to
* return an instance of a different class than the default model.
*
* @param {Function} dataCallback See {@link CKEDITOR.plugins.autocomplete.configDefinition#dataCallback configDefinition.dataCallback}.
* @returns {CKEDITOR.plugins.autocomplete.model} The model instance.
*/
getModel: function( dataCallback ) {
var that = this;
return new Model( function( matchInfo, callback ) {
return dataCallback.call( this, CKEDITOR.tools.extend( {
// Make sure autocomplete instance is available in the callback (#2108).
autocomplete: that
}, matchInfo ), callback );
} );
},
/**
* Creates and returns the text watcher instance. This method is used while
* initializing the autocomplete and can be overwritten in order to
* return an instance of a different class than the default text watcher.
*
* @param {Function} textTestCallback See the {@link CKEDITOR.plugins.autocomplete} arguments.
* @returns {CKEDITOR.plugins.textWatcher} The text watcher instance.
*/
getTextWatcher: function( textTestCallback ) {
return new CKEDITOR.plugins.textWatcher( this.editor, textTestCallback, this.throttle );
},
/**
* Creates and returns the view instance. This method is used while
* initializing the autocomplete and can be overwritten in order to
* return an instance of a different class than the default view.
*
* @returns {CKEDITOR.plugins.autocomplete.view} The view instance.
*/
getView: function() {
return new View( this.editor );
},
/**
* Opens the panel if {@link CKEDITOR.plugins.autocomplete.model#hasData there is any data available}.
*/
open: function() {
if ( this.model.hasData() ) {
this.model.setActive( true );
this.view.open();
this.model.selectFirst();
this.view.updatePosition( this.model.range );
}
},
// LISTENERS ------------------
/**
* The function that should be called when the view has to be repositioned, e.g on scroll.
*
* @private
*/
viewRepositionListener: function() {
if ( this.model.isActive ) {
this.view.updatePosition( this.model.range );
}
},
/**
* The function that should be called once the model data has changed.
*
* @param {CKEDITOR.eventInfo} evt
* @private
*/
modelChangeListener: function( evt ) {
if ( this.model.hasData() ) {
this.view.updateItems( evt.data );
this.open();
} else {
this.close();
}
},
/**
* The function that should be called once a view item was clicked.
*
* @param {CKEDITOR.eventInfo} evt
* @private
*/
onItemClick: function( evt ) {
this.commit( evt.data );
},
/**
* The function that should be called on every `keydown` event occurred within the {@link CKEDITOR.editable editable} element.
*
* @param {CKEDITOR.dom.event} evt
* @private
*/
onKeyDown: function( evt ) {
if ( !this.model.isActive ) {
return;
}
var keyCode = evt.data.getKey(),
handled = false;
// Esc key.
if ( keyCode == 27 ) {
this.close();
this.textWatcher.unmatch();
handled = true;
// Down Arrow.
} else if ( keyCode == 40 ) {
this.model.selectNext();
handled = true;
// Up Arrow.
} else if ( keyCode == 38 ) {
this.model.selectPrevious();
handled = true;
// Completion keys.
} else if ( CKEDITOR.tools.indexOf( this.commitKeystrokes, keyCode ) != -1 ) {
this.commit();
this.textWatcher.unmatch();
handled = true;
}
if ( handled ) {
evt.cancel();
evt.data.preventDefault();
this.textWatcher.consumeNext();
}
},
/**
* The function that should be called once an item was selected.
*
* @param {CKEDITOR.eventInfo} evt
* @private
*/
onSelectedItemId: function( evt ) {
this.model.setItem( evt.data );
this.view.selectItem( evt.data );
},
/**
* The function that should be called once a text was matched by the {@link CKEDITOR.plugins.textWatcher text watcher}
* component.
*
* @param {CKEDITOR.eventInfo} evt
* @private
*/
onTextMatched: function( evt ) {
this.model.setActive( false );
this.model.setQuery( evt.data.text, evt.data.range );
},
/**
* The function that should be called once a text was unmatched by the {@link CKEDITOR.plugins.textWatcher text watcher}
* component.
*
* @param {CKEDITOR.eventInfo} evt
* @private
*/
onTextUnmatched: function() {
// Remove query and request ID to avoid opening view for invalid callback (#1984).
this.model.query = null;
this.model.lastRequestId = null;
this.close();
}
};
/**
* Class representing the autocomplete view.
*
* In order to use a different view, implement a new view class and override
* the {@link CKEDITOR.plugins.autocomplete#getView} method.
*
* ```javascript
* myAutocomplete.prototype.getView = function() {
* return new myView( this.editor );
* };
* ```
*
* You can also modify this autocomplete instance on the fly.
*
* ```javascript
* myAutocomplete.prototype.getView = function() {
* // Call the original getView method.
* var view = CKEDITOR.plugins.autocomplete.prototype.getView.call( this );
*
* // Override one property.
* view.itemTemplate = new CKEDITOR.template( '<li data-id={id}><img src="{iconSrc}" alt="..."> {name}</li>' );
*
* return view;
* };
* ```
*
* **Note:** This class is marked as private, which means that its API might be subject to change in order to
* provide further enhancements.
*
* @class CKEDITOR.plugins.autocomplete.view
* @since 4.10.0
* @private
* @mixins CKEDITOR.event
* @constructor Creates the autocomplete view instance.
* @param {CKEDITOR.editor} editor The editor instance.
*/
function View( editor ) {
/**
* The panel's item template used to render matches in the dropdown.
*
* You can use {@link CKEDITOR.plugins.autocomplete.model#data data item} properties to customize the template.
*
* A minimal template must be wrapped with a HTML `li` element containing the `data-id="{id}"` attribute.
*
* ```javascript
* var itemTemplate = '<li data-id="{id}"><img src="{iconSrc}" alt="{name}">{name}</li>';
* ```
*
* @readonly
* @property {CKEDITOR.template}
*/
this.itemTemplate = new CKEDITOR.template( '<li data-id="{id}">{name}</li>' );
/**
* The editor instance.
*
* @readonly
* @property {CKEDITOR.editor}
*/
this.editor = editor;
/**
* The ID of the selected item.
*
* @readonly
* @property {Number/String} selectedItemId
*/
/**
* The document to which the view is attached. It is set by the {@link #append} method.
*
* @readonly
* @property {CKEDITOR.dom.document} document
*/
/**
* The view's main element. It is set by the {@link #append} method.
*
* @readonly
* @property {CKEDITOR.dom.element} element
*/
/**
* Event fired when an item in the panel is clicked.
*
* @event click-item
* @param {String} The clicked item {@link CKEDITOR.plugins.autocomplete.model.item#id}. Note: the ID
* is stringified due to the way how it is stored in the DOM.
*/
/**
* Event fired when the {@link #selectedItemId} property changes.
*
* @event change-selectedItemId
* @param {Number/String} data The new value.
*/
}
View.prototype = {
/**
* Appends the {@link #element main element} to the DOM.
*/
append: function() {
this.document = CKEDITOR.document;
this.element = this.createElement();
this.document.getBody().append( this.element );
},
/**
* Removes existing items and appends given items to the {@link #element}.
*
* @param {CKEDITOR.dom.documentFragment} itemsFragment The document fragment with item elements.
*/
appendItems: function( itemsFragment ) {
this.element.setHtml( '' );
this.element.append( itemsFragment );
},
/**
* Attaches the view's listeners to the DOM elements.
*/
attach: function() {
this.element.on( 'click', function( evt ) {
var target = evt.data.getTarget(),
itemElement = target.getAscendant( this.isItemElement, true );
if ( itemElement ) {
this.fire( 'click-item', itemElement.data( 'id' ) );
}
}, this );
this.element.on( 'mouseover', function( evt ) {
var target = evt.data.getTarget();
if ( this.element.contains( target ) ) {
// Find node containing data-id attribute inside target node tree (#2187).
target = target.getAscendant( function( element ) {
return element.hasAttribute( 'data-id' );
}, true );
if ( !target ) {
return;
}
var itemId = target.data( 'id' );
this.fire( 'change-selectedItemId', itemId );
}
}, this );
},
/**
* Closes the panel.
*/
close: function() {
this.element.removeClass( 'cke_autocomplete_opened' );
},
/**
* Creates and returns the view's main element.
*
* @private
* @returns {CKEDITOR.dom.element}
*/
createElement: function() {
var el = new CKEDITOR.dom.element( 'ul', this.document );
el.addClass( 'cke_autocomplete_panel' );
// Below float panels and context menu, but above maximized editor (-5).
el.setStyle( 'z-index', this.editor.config.baseFloatZIndex - 3 );
return el;
},
/**
* Creates the item element based on the {@link #itemTemplate}.
*
* @param {CKEDITOR.plugins.autocomplete.model.item} item The item for which an element will be created.
* @returns {CKEDITOR.dom.element}
*/
createItem: function( item ) {
var encodedItem = encodeItem( item );
return CKEDITOR.dom.element.createFromHtml( this.itemTemplate.output( encodedItem ), this.document );
},
/**
* Returns the view position based on a given `range`.
*
* Indicates the start position of the autocomplete dropdown.
* The value returned by this function is passed to the {@link #setPosition} method
* by the {@link #updatePosition} method.
*
* @param {CKEDITOR.dom.range} range The range of the text match.
* @returns {Object} Represents the position of the caret. The value is relative to the panel's offset parent.
* @returns {Number} rect.left
* @returns {Number} rect.top
* @returns {Number} rect.bottom
*/
getViewPosition: function( range ) {
// Use the last rect so the view will be
// correctly positioned with a word split into few lines.
var rects = range.getClientRects(),
viewPositionRect = rects[ rects.length - 1 ],
offset,
editable = this.editor.editable();
if ( editable.isInline() ) {
offset = CKEDITOR.document.getWindow().getScrollPosition();
} else {
offset = editable.getParent().getDocumentPosition( CKEDITOR.document );
}
// Consider that offset host might be repositioned on its own.
// Similar to #1048. See https://github.com/ckeditor/ckeditor4/pull/1732#discussion_r182790235.
var hostElement = CKEDITOR.document.getBody();
if ( hostElement.getComputedStyle( 'position' ) === 'static' ) {
hostElement = hostElement.getParent();
}
var offsetCorrection = hostElement.getDocumentPosition();
offset.x -= offsetCorrection.x;
offset.y -= offsetCorrection.y;
return {
top: ( viewPositionRect.top + offset.y ),
bottom: ( viewPositionRect.top + viewPositionRect.height + offset.y ),
left: ( viewPositionRect.left + offset.x )
};
},
/**
* Gets the item element by the item ID.
*
* @param {Number/String} itemId
* @returns {CKEDITOR.dom.element} The item element.
*/
getItemById: function( itemId ) {
return this.element.findOne( 'li[data-id="' + itemId + '"]' );
},
/**
* Checks whether a given node is the item element.
*
* @param {CKEDITOR.dom.node} node
* @returns {Boolean}
*/
isItemElement: function( node ) {
return node.type == CKEDITOR.NODE_ELEMENT &&
Boolean( node.data( 'id' ) );
},
/**
* Opens the panel.
*/
open: function() {
this.element.addClass( 'cke_autocomplete_opened' );
},
/**
* Selects the item in the panel and scrolls the list to show it if needed.
* The {@link #selectedItemId currently selected item} is deselected first.
*
* @param {Number/String} itemId The ID of the item that should be selected.
*/
selectItem: function( itemId ) {
if ( this.selectedItemId != null ) {
this.getItemById( this.selectedItemId ).removeClass( 'cke_autocomplete_selected' );
}
var itemElement = this.getItemById( itemId );
itemElement.addClass( 'cke_autocomplete_selected' );
this.selectedItemId = itemId;
this.scrollElementTo( itemElement );
},
/**
* Sets the position of the panel. This method only performs the check
* for the available space below and above the specified `rect` and
* positions the panel in the best place.
*
* This method is used by the {@link #updatePosition} method which
* controls how the panel should be positioned on the screen, for example
* based on the caret position and/or the editor position.
*
* @param {Object} rect Represents the position of a vertical (e.g. a caret) line relative to which
* the panel should be positioned.
* @param {Number} rect.left The position relative to the panel's offset parent in pixels.
* For example, the position of the caret.
* @param {Number} rect.top The position relative to the panel's offset parent in pixels.
* For example, the position of the upper end of the caret.
* @param {Number} rect.bottom The position relative to the panel's offset parent in pixels.
* For example, the position of the bottom end of the caret.
*/
setPosition: function( rect ) {
var editor = this.editor,
viewHeight = this.element.getSize( 'height' ),
editable = editor.editable(),
// Bounding rect where the view should fit (visible editor viewport).
editorViewportRect;
// iOS classic editor has different viewport element (#1910).
if ( CKEDITOR.env.iOS && !editable.isInline() ) {
editorViewportRect = iOSViewportElement( editor ).getClientRect( true );
} else {
editorViewportRect = editable.isInline() ? editable.getClientRect( true ) : editor.window.getFrame().getClientRect( true );
}
// How much space is there for the view above and below the specified rect.
var spaceAbove = rect.top - editorViewportRect.top,
spaceBelow = editorViewportRect.bottom - rect.bottom,
top;
// As a default, keep the view inside the editor viewport.
// +---------------------------------------------+
// | editor viewport |
// | |
// | |
// | |
// | █ - caret position |
// | +--------------+ |
// | | view | |
// | +--------------+ |
// | |
// | |
// +---------------------------------------------+
top = rect.top < editorViewportRect.top ? editorViewportRect.top : Math.min( editorViewportRect.bottom, rect.bottom );
// If the view doesn't fit below the caret position and fits above, set it there.
// This means that the position below the caret is preferred.
// +---------------------------------------------+
// | |
// | editor viewport |
// | +--------------+ |
// | | | |
// | | view | |
// | | | |
// | +--------------+ |
// | █ - caret position |
// | |
// +---------------------------------------------+
if ( viewHeight > spaceBelow && viewHeight < spaceAbove ) {
top = rect.top - viewHeight;
}
// If the caret position is below the view - keep it at the bottom edge.
// +---------------------------------------------+
// | editor viewport |
// | |
// | +--------------+ |
// | | | |
// | | view | |
// | | | |
// +-----+==============+------------------------+
// | |
// | █ - caret position |
// | |
// +---------------------------------------------+
if ( editorViewportRect.bottom < rect.bottom ) {
top = Math.min( rect.top - viewHeight, editorViewportRect.bottom - viewHeight );
}
// If the caret position is above the view - keep it at the top edge.
// +---------------------------------------------+
// | |
// | █ - caret position |
// | |
// +-----+==============+------------------------+
// | | | |
// | | view | |
// | | | |
// | +--------------+ |
// | |
// | editor viewport |
// +---------------------------------------------+
if ( editorViewportRect.top > rect.top ) {
top = Math.max( rect.bottom, editorViewportRect.top );
}
this.element.setStyles( {
left: rect.left + 'px',
top: top + 'px'
} );
},
/**
* Scrolls the list so the item element is visible in it.
*
* @param {CKEDITOR.dom.element} itemElement
*/
scrollElementTo: function( itemElement ) {
itemElement.scrollIntoParent( this.element );
},
/**
* Updates the list of items in the panel.
*
* @param {CKEDITOR.plugins.autocomplete.model.item[]} items.
*/
updateItems: function( items ) {
var i,
frag = new CKEDITOR.dom.documentFragment( this.document );
for ( i = 0; i < items.length; ++i ) {
frag.append( this.createItem( items[ i ] ) );
}
this.appendItems( frag );
this.selectedItemId = null;
},
/**
* Updates the position of the panel.
*
* By default this method finds the position of the caret and uses
* {@link #setPosition} to move the panel to the best position close
* to the caret.
*
* @param {CKEDITOR.dom.range} range The range of the text match.
*/
updatePosition: function( range ) {
this.setPosition( this.getViewPosition( range ) );
}
};
CKEDITOR.event.implementOn( View.prototype );
/**
* Class representing the autocomplete model.
*
* In case you want to modify the model behavior, check out the
* {@link CKEDITOR.plugins.autocomplete.view} documentation. It contains
* examples of how to easily override the default behavior.
*
* A model instance is created by the {@link CKEDITOR.plugins.autocomplete#getModel} method.
*
* **Note:** This class is marked as private, which means that its API might be subject to change in order to
* provide further enhancements.
*
* @class CKEDITOR.plugins.autocomplete.model
* @since 4.10.0
* @private
* @mixins CKEDITOR.event