Debian Codegraph @

extensions/VisualEditor/modules/ve-mw/ui/widgets/ve.ui.MWAceEditorWidget.js

raw symbols SCIP
1 /*!
2 * VisualEditor UserInterface MWAceEditorWidget class.
3 *
4 * @copyright See AUTHORS.txt
5 */
6
7 /* global ace */
8
9 /**
10 * Text input widget which use an Ace editor instance when available
11 *
12 * For the most part this can be treated just like a TextInputWidget with
13 * a few extra considerations:
14 *
15 * - For performance it is recommended to destroy the editor when
16 * you are finished with it, using #teardown. If you need to use
17 * the widget again let the editor can be restored with #setup.
18 * - After setting an initial value the undo stack can be reset
19 * using clearUndoStack so that you can't undo past the initial
20 * state.
21 *
22 * @class
23 * @extends ve.ui.WhitespacePreservingTextInputWidget
24 *
25 * @constructor
26 * @param {Object} [config] Configuration options
27 * @param {string} [config.autocomplete='none'] Symbolic name of autocomplete
28 * mode: 'none', 'basic' (requires the user to press Ctrl-Space) or
29 * 'live' (shows a list of suggestions as the user types)
30 * @param {Array} [config.autocompleteWordList=null] List of words to
31 * autocomplete to
32 */
33 ve.ui.MWAceEditorWidget = function VeUiMWAceEditorWidget( config ) {
34 // Configuration
35 config = config || {};
36
37 this.autocomplete = config.autocomplete || 'none';
38 this.autocompleteWordList = config.autocompleteWordList || null;
39
40 this.$ace = $( '<div>' ).attr( 'dir', 'ltr' );
41 this.editor = null;
42 // Initialise to a rejected promise for the setValue call in the parent constructor
43 this.loadingPromise = ve.createDeferred().reject().promise();
44 this.styleHeight = null;
45
46 // Parent constructor
47 ve.ui.MWAceEditorWidget.super.call( this, config );
48
49 // Clear the fake loading promise and setup properly
50 this.loadingPromise = null;
51 this.setup();
52
53 this.$element
54 .append( this.$ace )
55 .addClass( 've-ui-mwAceEditorWidget' );
56 };
57
58 /* Inheritance */
59
60 OO.inheritClass( ve.ui.MWAceEditorWidget, ve.ui.WhitespacePreservingTextInputWidget );
61
62 /* Events */
63
64 /**
65 * The editor has resized
66 *
67 * @event ve.ui.MWAceEditorWidget#resize
68 */
69
70 /* Methods */
71
72 /**
73 * Setup the Ace editor instance
74 */
75 ve.ui.MWAceEditorWidget.prototype.setup = function () {
76 if ( !this.loadingPromise ) {
77 this.loadingPromise = mw.loader.getState( 'ext.codeEditor.ace' ) ?
78 mw.loader.using( 'ext.codeEditor.ace' ) :
79 ve.createDeferred().reject().promise();
80 // Resolved promises will run synchronously, so ensure #setupEditor
81 // runs after this.loadingPromise is stored.
82 this.loadingPromise.done( this.setupEditor.bind( this ) );
83 }
84 };
85
86 /**
87 * Destroy the Ace editor instance
88 */
89 ve.ui.MWAceEditorWidget.prototype.teardown = function () {
90 this.loadingPromise.done( () => {
91 this.$input.removeClass( 'oo-ui-element-hidden' );
92 this.editor.destroy();
93 this.editor = null;
94 } ).always( () => {
95 this.loadingPromise = null;
96 } );
97 };
98
99 /**
100 * Setup the Ace editor
101 *
102 * @fires ve.ui.MWAceEditorWidget#resize
103 */
104 ve.ui.MWAceEditorWidget.prototype.setupEditor = function () {
105 let basePath = mw.config.get( 'wgExtensionAssetsPath', '' );
106
107 if ( basePath.slice( 0, 2 ) === '//' ) {
108 // ACE uses web workers, which have importScripts, which don't like relative links.
109 basePath = window.location.protocol + basePath;
110 }
111 ace.config.set( 'basePath', basePath + '/CodeEditor/modules/ace' );
112
113 this.$input.addClass( 'oo-ui-element-hidden' );
114 this.editor = ace.edit( this.$ace[ 0 ] );
115 this.setMinRows( this.minRows );
116
117 // Autocompletion
118 this.editor.setOptions( {
119 enableBasicAutocompletion: this.autocomplete !== 'none',
120 enableLiveAutocompletion: this.autocomplete === 'live'
121 } );
122 if ( this.autocompleteWordList ) {
123 const completer = {
124 getCompletions: ( editor, session, pos, prefix, callback ) => {
125 const wordList = this.autocompleteWordList;
126 callback( null, wordList.map( ( word ) => ( {
127 caption: word,
128 value: word,
129 meta: 'static'
130 } ) ) );
131 }
132 };
133 ace.require( 'ace/ext/language_tools' ).addCompleter( completer );
134 }
135
136 this.editor.getSession().on( 'change', this.onEditorChange.bind( this ) );
137 this.editor.renderer.on( 'resize', this.onEditorResize.bind( this ) );
138 this.setEditorValue( this.getValue() );
139 // Force resize (T303964)
140
141 this.editor.resize( true );
142 };
143
144 /**
145 * Set the autocomplete property
146 *
147 * @param {string} mode Symbolic name of autocomplete mode
148 * @return {ve.ui.MWAceEditorWidget}
149 * @chainable
150 */
151 ve.ui.MWAceEditorWidget.prototype.setAutocomplete = function ( mode ) {
152 this.autocomplete = mode;
153 this.loadingPromise.done( () => {
154 this.editor.renderer.setOptions( {
155 enableBasicAutocompletion: this.autocomplete !== 'none',
156 enableLiveAutocompletion: this.autocomplete === 'live'
157 } );
158 } );
159 return this;
160 };
161
162 /**
163 * @inheritdoc
164 */
165 ve.ui.MWAceEditorWidget.prototype.setValue = function ( value ) {
166 // Always do something synchronously so that getValue can be used immediately.
167 // setEditorValue is called once when the loadingPromise resolves in setupEditor.
168 if ( this.loadingPromise.state() === 'resolved' ) {
169 this.setEditorValue( value );
170 } else {
171 ve.ui.MWAceEditorWidget.super.prototype.setValue.call( this, value );
172 }
173 return this;
174 };
175
176 /**
177 * Set the value of the Ace editor widget
178 *
179 * @param {string} value
180 * @return {ve.ui.MWAceEditorWidget}
181 * @chainable
182 */
183 ve.ui.MWAceEditorWidget.prototype.setEditorValue = function ( value ) {
184 if ( value !== this.editor.getValue() ) {
185 const selectionState = this.editor.session.selection.toJSON();
186 this.editor.setValue( value );
187 this.editor.session.selection.fromJSON( selectionState );
188 }
189 return this;
190 };
191
192 /**
193 * Set the minimum number of rows in the Ace editor widget
194 *
195 * @param {number} minRows The minimum number of rows
196 * @return {ve.ui.MWAceEditorWidget}
197 * @chainable
198 */
199 ve.ui.MWAceEditorWidget.prototype.setMinRows = function ( minRows ) {
200 this.minRows = minRows;
201 this.loadingPromise.done( () => {
202 this.editor.setOptions( {
203 minLines: this.minRows || 3,
204 maxLines: this.autosize ? this.maxRows : this.minRows || 3
205 } );
206 } );
207 // TODO: Implement minRows setter for OO.ui.TextInputWidget
208 // and call it here in loadingPromise.fail
209 return this;
210 };
211
212 /**
213 * @inheritdoc
214 */
215 ve.ui.MWAceEditorWidget.prototype.setReadOnly = function ( readOnly ) {
216 // Parent method
217 ve.ui.MWAceEditorWidget.super.prototype.setReadOnly.call( this, readOnly );
218
219 this.loadingPromise.done( () => {
220 this.editor.setReadOnly( this.isReadOnly() );
221 } );
222
223 this.$element.toggleClass( 've-ui-mwAceEditorWidget-readOnly', !!this.isReadOnly() );
224 return this;
225 };
226
227 /**
228 * @inheritdoc
229 */
230 ve.ui.MWAceEditorWidget.prototype.getRange = function () {
231 let lines;
232 function posToOffset( row, col ) {
233 let offset = 0;
234
235 for ( let r = 0; r < row; r++ ) {
236 offset += lines[ r ].length;
237 offset++; // for the newline character
238 }
239 return offset + col;
240 }
241
242 if ( this.editor ) {
243 lines = this.editor.getSession().getDocument().getAllLines();
244
245 const selection = this.editor.getSelection();
246 const isBackwards = selection.isBackwards();
247 const range = selection.getRange();
248 const start = posToOffset( range.start.row, range.start.column );
249 const end = posToOffset( range.end.row, range.end.column );
250
251 return {
252 from: isBackwards ? end : start,
253 to: isBackwards ? start : end
254 };
255 } else {
256 return ve.ui.MWAceEditorWidget.super.prototype.getRange.call( this );
257 }
258 };
259
260 /**
261 * @inheritdoc
262 */
263 ve.ui.MWAceEditorWidget.prototype.selectRange = function ( from, to ) {
264 this.focus();
265 this.loadingPromise.done( () => {
266 const doc = this.editor.getSession().getDocument(),
267 lines = doc.getAllLines();
268
269 to = to || from;
270
271 function offsetToPos( offset ) {
272 let row = 0,
273 pos = 0;
274
275 while ( row < lines.length && pos + lines[ row ].length < offset ) {
276 pos += lines[ row ].length;
277 pos++; // for the newline character
278 row++;
279 }
280 const col = offset - pos;
281 return { row: row, column: col };
282 }
283
284 const fromOffset = offsetToPos( from );
285 const toOffset = offsetToPos( to );
286
287 const selection = this.editor.getSelection();
288 const range = selection.getRange();
289 range.setStart( fromOffset.row, fromOffset.column );
290 range.setEnd( toOffset.row, toOffset.column );
291 selection.setSelectionRange( range );
292 } ).fail( () => {
293 ve.ui.MWAceEditorWidget.super.prototype.selectRange.call( this, from, to );
294 } );
295 return this;
296 };
297
298 /**
299 * Handle change events from the Ace editor
300 */
301 ve.ui.MWAceEditorWidget.prototype.onEditorChange = function () {
302 // Call setValue on the parent to keep the value property in sync with the editor
303 ve.ui.MWAceEditorWidget.super.prototype.setValue.call( this, this.editor.getValue() );
304 };
305
306 /**
307 * Handle resize events from the Ace editor
308 *
309 * @fires ve.ui.MWAceEditorWidget#resize
310 */
311 ve.ui.MWAceEditorWidget.prototype.onEditorResize = function () {
312 // On the first setup the editor doesn't resize until the end of the cycle
313 setTimeout( this.emit.bind( this, 'resize' ) );
314 };
315
316 /**
317 * Clear the editor's undo stack
318 *
319 * @return {ve.ui.MWAceEditorWidget}
320 * @chainable
321 */
322 ve.ui.MWAceEditorWidget.prototype.clearUndoStack = function () {
323 this.loadingPromise.done( () => {
324 this.editor.session.setUndoManager(
325 new ace.UndoManager()
326 );
327 } );
328 return this;
329 };
330
331 /**
332 * Toggle the visibility of line numbers
333 *
334 * @param {boolean} visible
335 * @return {ve.ui.MWAceEditorWidget}
336 * @chainable
337 */
338 ve.ui.MWAceEditorWidget.prototype.toggleLineNumbers = function ( visible ) {
339 this.loadingPromise.done( () => {
340 this.editor.setOption( 'showLineNumbers', visible );
341 } );
342 return this;
343 };
344
345 /**
346 * Toggle the visibility of the print margin
347 *
348 * @param {boolean} visible
349 * @return {ve.ui.MWAceEditorWidget}
350 * @chainable
351 */
352 ve.ui.MWAceEditorWidget.prototype.togglePrintMargin = function ( visible ) {
353 this.loadingPromise.done( () => {
354 this.editor.renderer.setShowPrintMargin( visible );
355 } );
356 return this;
357 };
358
359 /**
360 * Set the language mode of the editor (programming language)
361 *
362 * @param {string} lang Language
363 * @return {ve.ui.MWAceEditorWidget}
364 * @chainable
365 */
366 ve.ui.MWAceEditorWidget.prototype.setLanguage = function ( lang ) {
367 this.loadingPromise.done( () => {
368 ace.config.loadModule( 'ace/ext/modelist', ( modelist ) => {
369 if ( !modelist || !modelist.modesByName[ lang ] ) {
370 lang = 'text';
371 }
372 this.editor.getSession().setMode( 'ace/mode/' + lang );
373 } );
374 } );
375 return this;
376 };
377
378 /**
379 * Focus the editor
380 *
381 * @return {ve.ui.MWAceEditorWidget}
382 * @chainable
383 */
384 ve.ui.MWAceEditorWidget.prototype.focus = function () {
385 this.loadingPromise.done( () => {
386 this.editor.focus();
387 } ).fail( () => {
388 ve.ui.MWAceEditorWidget.super.prototype.focus.call( this );
389 } );
390 return this;
391 };
392
393 /**
394 * @inheritdoc
395 * @param {boolean} [force=false] Force a resize call on Ace editor
396 */
397 ve.ui.MWAceEditorWidget.prototype.adjustSize = function ( force ) {
398 // If the editor has loaded, resize events are emitted from #onEditorResize
399 // so do nothing here unless this is a user triggered resize, otherwise call the parent method.
400 if ( force ) {
401 this.loadingPromise.done( () => {
402
403 this.editor.resize();
404 } );
405 }
406 this.loadingPromise.fail( () => {
407 // Parent method
408 ve.ui.MWAceEditorWidget.super.prototype.adjustSize.call( this );
409 } );
410 return this;
411 };