Debian Codegraph @

extensions/WikiEditor/modules/jquery.wikiEditor.js

raw symbols SCIP
1 /**
2 * This plugin provides a way to build a wiki-text editing user interface around a textarea.
3 *
4 * @example To initialize without any modules,
5 * overqualified `div#edittoolbar` to avoid MediaWiki's heading to id automatism:
6 * $( 'div#edittoolbar' ).wikiEditor();
7 *
8 * @example To initialize with one or more modules, or to add modules after it's already been initialized:
9 * $( 'textarea#wpTextbox1' ).wikiEditor( 'addModule', 'toolbar', { ... config ... } );
10 */
11 /**
12 * @private
13 */
14 var hasOwn = Object.prototype.hasOwnProperty,
15
16 /**
17 * Array of language codes.
18 *
19 * @private
20 */
21 fallbackChain = ( function () {
22 // eslint-disable-next-line no-jquery/no-class-state
23 var isRTL = $( document.body ).hasClass( 'rtl' ),
24 chain = mw.language.getFallbackLanguageChain();
25
26 // Do not fallback to 'en'
27 if ( chain.length >= 2 && !/^en-/.test( chain[ chain.length - 2 ] ) ) {
28 chain.pop();
29 }
30 if ( isRTL ) {
31 chain.push( 'default-rtl' );
32 }
33 chain.push( 'default' );
34 return chain;
35 }() );
36
37 /**
38 * Helper function to mark the automatic message functionality in
39 * the autoMsg and autoSafeMsg functions as deprecated.
40 *
41 * @private
42 * @param {string} property
43 * @param {string} key
44 */
45 function deprecateAutoMsg( property, key ) {
46 var searchParam = mw.config.get( 'wgSearchType' ) === 'CirrusSearch' ?
47 'insource:/' + property + 'Msg: \'' + key + '\'/' :
48 property + 'Msg: ' + key;
49 var searchUri = mw.config.get( 'wgServer' ) +
50 mw.util.getUrl(
51 'Special:Search',
52 { search: searchParam, ns2: 1, ns8: 1 }
53 );
54 if ( searchUri.slice( 0, 2 ) === '//' ) {
55 searchUri = location.protocol + searchUri;
56 }
57
58 var messageMethod;
59 if ( property === 'html' || property === 'text' || property === 'title' ) {
60 messageMethod = 'mw.message( ' + JSON.stringify( key ) + ' ).parse()';
61 } else {
62 messageMethod = 'mw.msg( ' + JSON.stringify( key ) + ' )';
63 }
64 var deprecationMsg = mw.log.makeDeprecated(
65 'wikiEditor_autoMsg',
66 'WikiEditor: Use `' + property + ': ' + messageMethod + '` instead of `' + property + 'Msg: ' + JSON.stringify( key ) + '`.\nSearch: ' + searchUri
67 );
68 deprecationMsg();
69 }
70
71 /**
72 * Global static object for wikiEditor that provides generally useful functionality to all modules and contexts.
73 */
74 $.wikiEditor = {
75 /**
76 * For each module that is loaded, static code shared by all instances is loaded into this object organized by
77 * module name. The existence of a module in this object only indicates the module is available. To check if a
78 * module is in use by a specific context check the context.modules object.
79 */
80 modules: {
81 toolbar: require( './jquery.wikiEditor.toolbar.js' ),
82 dialogs: require( './jquery.wikiEditor.dialogs.js' )
83 },
84
85 /**
86 * A context can be extended, such as adding iframe support, on a per-wikiEditor instance basis.
87 */
88 extensions: {},
89
90 /**
91 * In some cases like with the iframe's HTML file, it's convenient to have a lookup table of all instances of the
92 * WikiEditor. Each context contains an instance field which contains a key that corresponds to a reference to the
93 * textarea which the WikiEditor was build around. This way, by passing a simple integer you can provide a way back
94 * to a specific context.
95 */
96 instances: [],
97
98 /**
99 * Path to images - this is a bit messy, and it would need to change if this code (and images) gets moved into the
100 * core - or anywhere for that matter...
101 */
102 imgPath: mw.config.get( 'wgExtensionAssetsPath' ) + '/WikiEditor/modules/images/',
103
104 /**
105 * Checks if a module has a specific requirement
106 *
107 * @param {Object} module Module object
108 * @param {string} requirement String identifying requirement
109 * @return {boolean}
110 */
111 isRequired: function ( module, requirement ) {
112 if ( typeof module.req !== 'undefined' ) {
113 for ( var req in module.req ) {
114 if ( module.req[ req ] === requirement ) {
115 return true;
116 }
117 }
118 }
119 return false;
120 },
121
122 /**
123 * Provides a way to extract messages from objects. Wraps a mw.message( ... ).text() call.
124 *
125 * FIXME: This is a security nightmare. Only use is for the help toolbar panel. Inline the
126 * special need instead?
127 * FIXME: Also, this is ludicrously complex. Just use mw.message().text() directly.
128 *
129 * @deprecated Since v0.5.4. Use mw.message() directly instead of <key>Msg
130 *
131 * @param {Object} object Object to extract messages from
132 * @param {string} property String of name of property which contains the message. This should be the base name of the
133 * property, which means that in the case of the object { this: 'that', fooMsg: 'bar' }, passing property as 'this'
134 * would return the raw text 'that', while passing property as 'foo' would return the internationalized message
135 * with the key 'bar'.
136 * @return {string}
137 */
138 autoMsg: function ( object, property ) {
139 // Accept array of possible properties, of which the first one found will be used
140 if ( typeof property === 'object' ) {
141 for ( var i in property ) {
142 if ( property[ i ] in object || property[ i ] + 'Msg' in object ) {
143 property = property[ i ];
144 break;
145 }
146 }
147 }
148 if ( property in object ) {
149 return object[ property ];
150 } else if ( property + 'Msg' in object ) {
151 var p = object[ property + 'Msg' ];
152 if ( Array.isArray( p ) && p.length >= 2 ) {
153 deprecateAutoMsg( property, p[ 0 ] );
154 return mw.message.apply( mw.message, p ).text();
155 } else {
156 deprecateAutoMsg( property, p );
157 // eslint-disable-next-line mediawiki/msg-doc
158 return mw.message( p ).text();
159 }
160 } else {
161 return '';
162 }
163 },
164
165 /**
166 * Provides a way to extract messages from objects. Wraps a mw.message( ... ).escaped() call.
167 *
168 * FIXME: This is ludicrously complex. Just use mw.message().escaped() directly.
169 *
170 * @deprecated Since v0.5.4. Use mw.message() directly instead of <key>Msg
171 *
172 * @param {Object} object Object to extract messages from
173 * @param {string} property String of name of property which contains the message. This should be the base name of the
174 * property, which means that in the case of the object { this: 'that', fooMsg: 'bar' }, passing property as 'this'
175 * would return the raw text 'that', while passing property as 'foo' would return the internationalized message
176 * with the key 'bar'. This is then escaped.
177 * @return {string}
178 */
179 autoSafeMsg: function ( object, property ) {
180 // Accept array of possible properties, of which the first one found will be used
181 if ( typeof property === 'object' ) {
182 for ( var i in property ) {
183 if ( property[ i ] in object || property[ i ] + 'Msg' in object ) {
184 property = property[ i ];
185 break;
186 }
187 }
188 }
189 if ( property in object ) {
190 return object[ property ];
191 } else if ( property + 'Msg' in object ) {
192 var p = object[ property + 'Msg' ];
193 if ( Array.isArray( p ) && p.length >= 2 ) {
194 deprecateAutoMsg( property, p[ 0 ] );
195 return mw.message.apply( mw.message, p ).escaped();
196 } else {
197 deprecateAutoMsg( property, p );
198 // eslint-disable-next-line mediawiki/msg-doc
199 return mw.message( p ).escaped();
200 }
201 } else {
202 return '';
203 }
204 },
205
206 /**
207 * Provides a way to extract a property of an object in a certain language, falling back on the property keyed as
208 * 'default' or 'default-rtl'. If such key doesn't exist, the object itself is considered the actual value, which
209 * should ideally be the case so that you may use a string or object of any number of strings keyed by language
210 * with a default.
211 *
212 * @param {Object} object Object to extract property from
213 * @return {Object}
214 */
215 autoLang: function ( object ) {
216 for ( var i = 0; i < fallbackChain.length; i++ ) {
217 var key = fallbackChain[ i ];
218 if ( hasOwn.call( object, key ) ) {
219 return object[ key ];
220 }
221 }
222 return object;
223 },
224
225 /**
226 * Provides a way to extract the path of an icon in a certain language, automatically appending a version number for
227 * caching purposes and prepending an image path when icon paths are relative.
228 *
229 * @param {Object} icon Icon object from e.g. toolbar config
230 * @param {string} path Default icon path, defaults to $.wikiEditor.imgPath
231 * @return {Object}
232 */
233 autoIcon: function ( icon, path ) {
234 path = path || $.wikiEditor.imgPath;
235
236 for ( var i = 0; i < fallbackChain.length; i++ ) {
237 var key = fallbackChain[ i ];
238 if ( icon && hasOwn.call( icon, key ) ) {
239 var src = icon[ key ];
240
241 // Return a data URL immediately
242 if ( src.slice( 0, 5 ) === 'data:' ) {
243 return src;
244 }
245
246 // Prepend path if src is not absolute
247 if ( src.slice( 0, 7 ) !== 'http://' && src.slice( 0, 8 ) !== 'https://' && src[ 0 ] !== '/' ) {
248 src = path + src;
249 }
250 return src;
251 }
252 }
253 return icon;
254 }
255 };
256
257 /**
258 * jQuery plugin that provides a way to initialize a wikiEditor instance on a textarea.
259 *
260 * @return {jQuery}
261 */
262 $.fn.wikiEditor = function () {
263 /* Initialization */
264
265 // The wikiEditor context is stored in the element's data, so when this function gets called again we can pick up right
266 // where we left off
267 var context = $( this ).data( 'wikiEditor-context' );
268 // On first call, we need to set things up, but on all following calls we can skip right to the API handling
269 if ( !context ) {
270
271 // Star filling the context with useful data - any jQuery selections, as usual should be named with a preceding $
272 context = {
273 // Reference to the textarea element which the wikiEditor is being built around
274 $textarea: $( this ),
275 // Reference to the focused element before the dialog opens, so it can be restored once it closes
276 $focusedElem: null,
277 // Container for any number of mutually exclusive views that are accessible by tabs
278 views: {},
279 // Container for any number of module-specific data - only including data for modules in use on this context
280 modules: {},
281 // General place to shove bits of data into
282 data: {},
283 // Unique numeric ID of this instance used both for looking up and differentiating instances of wikiEditor
284 instance: $.wikiEditor.instances.push( $( this ) ) - 1,
285 // Saved selection state for old IE (<=10)
286 savedSelection: null,
287 // List of extensions active on this context
288 extensions: []
289 };
290
291 /**
292 * Externally Accessible API
293 *
294 * These are available using calls to $( selection ).wikiEditor( call, data ) where selection is a jQuery selection
295 * of the textarea that the wikiEditor instance was built around.
296 */
297
298 context.api = {
299 /*!
300 * Activates a module on a specific context with optional configuration data.
301 *
302 * @param data Either a string of the name of a module to add without any additional configuration parameters,
303 * or an object with members keyed with module names and valued with configuration objects.
304 */
305 addModule: function ( ctx, data ) {
306 var modules = {};
307 if ( typeof data === 'string' ) {
308 modules[ data ] = {};
309 } else if ( typeof data === 'object' ) {
310 modules = data;
311 }
312 for ( var module in modules ) {
313 // Check for the existence of an available module with a matching name and a create function
314 if ( typeof module === 'string' && typeof $.wikiEditor.modules[ module ] !== 'undefined' ) {
315 // Extend the context's core API with this module's own API calls
316 if ( 'api' in $.wikiEditor.modules[ module ] ) {
317 for ( var call in $.wikiEditor.modules[ module ].api ) {
318 // Modules may not overwrite existing API functions - first come, first serve
319 if ( !( call in ctx.api ) ) {
320 ctx.api[ call ] = $.wikiEditor.modules[ module ].api[ call ];
321 }
322 }
323 }
324 // Activate the module on this context
325 if ( 'fn' in $.wikiEditor.modules[ module ] &&
326 'create' in $.wikiEditor.modules[ module ].fn &&
327 typeof ctx.modules[ module ] === 'undefined'
328 ) {
329 // Add a place for the module to put it's own stuff
330 ctx.modules[ module ] = {};
331 // Tell the module to create itself on the context
332 $.wikiEditor.modules[ module ].fn.create( ctx, modules[ module ] );
333 }
334 }
335 }
336 }
337 };
338
339 /**
340 * Event Handlers
341 *
342 * These act as filters returning false if the event should be ignored or returning true if it should be passed
343 * on to all modules. This is also where we can attach some extra information to the events.
344 */
345
346 context.evt = {
347 /* Empty until extensions add some; see jquery.wikiEditor.iframe.js for examples. */
348 };
349
350 /* Internal Functions */
351
352 context.fn = {
353 /**
354 * Executes core event filters as well as event handlers provided by modules.
355 *
356 * @param {string} name
357 * @param {Object} event
358 * @return {boolean}
359 */
360 trigger: function ( name, event ) {
361 // Event is an optional argument, but from here on out, at least the type field should be dependable
362 event = event || { type: 'custom' };
363 // Ensure there's a place for extra information to live
364 event.data = event.data || {};
365
366 // Allow filtering to occur
367 if ( name in context.evt ) {
368 if ( !context.evt[ name ]( event ) ) {
369 return false;
370 }
371 }
372 var returnFromModules = true;
373 // Pass the event around to all modules activated on this context
374
375 for ( var module in context.modules ) {
376 if (
377 module in $.wikiEditor.modules &&
378 'evt' in $.wikiEditor.modules[ module ] &&
379 name in $.wikiEditor.modules[ module ].evt
380 ) {
381 var ret = $.wikiEditor.modules[ module ].evt[ name ]( context, event );
382 if ( ret !== null ) {
383 // if 1 returns false, the end result is false
384 returnFromModules = returnFromModules && ret;
385 }
386 }
387 }
388 return returnFromModules;
389 },
390
391 /**
392 * Adds a button to the UI
393 *
394 * @param {Object} options
395 * @return {jQuery}
396 */
397 addButton: function ( options ) {
398 // Ensure that buttons and tabs are visible
399 context.$controls.show();
400 context.$buttons.show();
401 return $( '<button>' )
402 .text( $.wikiEditor.autoMsg( options, 'caption' ) )
403 .on( 'click', options.action )
404 .appendTo( context.$buttons );
405 },
406
407 /**
408 * Adds a view to the UI, which is accessed using a set of tabs. Views are mutually exclusive and by default a
409 * wikitext view will be present. Only when more than one view exists will the tabs will be visible.
410 *
411 * @param {Object} options
412 * @return {jQuery}
413 */
414 addView: function ( options ) {
415 // Adds a tab
416 function addTab( opts ) {
417 // Ensure that buttons and tabs are visible
418 context.$controls.show();
419 context.$tabs.show();
420 // Return the newly appended tab
421 return $( '<div>' )
422 .attr( 'rel', 'wikiEditor-ui-view-' + opts.name )
423 .addClass( context.view === opts.name ? 'current' : null )
424 .append( $( '<a>' )
425 .attr( 'tabindex', 0 )
426 .on( 'mousedown', function () {
427 // No dragging!
428 return false;
429 } )
430 .on( 'click keydown', function ( event ) {
431 if (
432 event.type === 'click' ||
433 event.type === 'keydown' && event.key === 'Enter'
434 ) {
435 context.$ui.find( '.wikiEditor-ui-view' ).hide();
436 context.$ui.find( '.' + $( this ).parent().attr( 'rel' ) ).show();
437 context.$tabs.find( 'div' ).removeClass( 'current' );
438 $( this ).parent().addClass( 'current' );
439 $( this ).trigger( 'blur' );
440 if ( 'init' in opts && typeof opts.init === 'function' ) {
441 opts.init( context );
442 }
443 event.preventDefault();
444 return false;
445 }
446 } )
447 .text( $.wikiEditor.autoMsg( opts, 'title' ) )
448 )
449 .appendTo( context.$tabs );
450 }
451 // Automatically add the previously not-needed wikitext tab
452 if ( !context.$tabs.children().length ) {
453 addTab( { name: 'wikitext', title: mw.message( 'wikieditor-wikitext-tab' ).parse() } );
454 }
455 // Add the tab for the view we were actually asked to add
456 addTab( options );
457 // Return newly appended view
458 // eslint-disable-next-line mediawiki/class-doc
459 return $( '<div>' )
460 .addClass( 'wikiEditor-ui-view wikiEditor-ui-view-' + options.name )
461 .hide()
462 .appendTo( context.$ui );
463 },
464
465 /**
466 * Save text selection
467 */
468 saveSelection: function () {
469 context.$focusedElem = $( ':focus' );
470 context.$textarea.trigger( 'focus' );
471 context.savedSelection = context.$textarea.textSelection( 'getCaretPosition', { startAndEnd: true } );
472 },
473
474 /**
475 * Restore text selection
476 */
477 restoreSelection: function () {
478 if ( context.savedSelection ) {
479 context.$textarea.trigger( 'focus' );
480 context.$textarea.textSelection( 'setSelection', { start: context.savedSelection[ 0 ], end: context.savedSelection[ 1 ] } );
481 context.savedSelection = null;
482 }
483 if ( context.$focusedElem ) {
484 context.$focusedElem.trigger( 'focus' );
485 }
486 }
487 };
488
489 /**
490 * Base UI Construction
491 *
492 * The UI is built from several containers, the outer-most being a div classed as "wikiEditor-ui". These containers
493 * provide a certain amount of "free" layout, but in some situations procedural layout is needed, which is performed
494 * as a response to the "resize" event.
495 */
496
497 /* Preserving cursor and focus state, which will get lost due to wrapAll */
498 var hasFocus = context.$textarea.is( ':focus' );
499 var cursorPos = context.$textarea.textSelection( 'getCaretPosition', { startAndEnd: true } );
500 // Encapsulate the textarea with some containers for layout
501 context.$textarea
502 .wrapAll( $( '<div>' ).addClass( 'wikiEditor-ui' ) )
503 .wrapAll( $( '<div>' ).addClass( 'wikiEditor-ui-view wikiEditor-ui-view-wikitext' ) )
504 .wrapAll( $( '<div>' ).addClass( 'wikiEditor-ui-left' ) )
505 .wrapAll( $( '<div>' ).addClass( 'wikiEditor-ui-bottom' ) )
506 .wrapAll( $( '<div>' ).addClass( 'wikiEditor-ui-text' ) );
507 // Restore scroll position after this wrapAll (tracked by mediawiki.action.edit)
508 context.$textarea.prop( 'scrollTop', $( '#wpScrolltop' ).val() );
509 // Restore focus and cursor if needed
510 if ( hasFocus ) {
511 context.$textarea.trigger( 'focus' );
512 context.$textarea.textSelection( 'setSelection', { start: cursorPos[ 0 ], end: cursorPos[ 1 ] } );
513 }
514
515 // Get references to some of the newly created containers
516 context.$ui = context.$textarea.parent().parent().parent().parent().parent();
517 context.$wikitext = context.$textarea.parent().parent().parent().parent();
518 // Add in tab and button containers
519 context.$wikitext.before(
520 $( '<div>' ).addClass( 'wikiEditor-ui-controls' ).append(
521 $( '<div>' ).addClass( 'wikiEditor-ui-tabs' ).hide(),
522 $( '<div>' ).addClass( 'wikiEditor-ui-buttons' )
523 ),
524 $( '<div>' ).addClass( 'wikiEditor-ui-clear' )
525 );
526 // Get references to some of the newly created containers
527 context.$controls = context.$ui.find( '.wikiEditor-ui-buttons' ).hide();
528 context.$buttons = context.$ui.find( '.wikiEditor-ui-buttons' );
529 context.$tabs = context.$ui.find( '.wikiEditor-ui-tabs' );
530 // Clear all floating after the UI
531 context.$ui.after( $( '<div>' ).addClass( 'wikiEditor-ui-clear' ) );
532 // Attach a right container
533 context.$wikitext.append(
534 $( '<div>' ).addClass( 'wikiEditor-ui-right' ),
535 $( '<div>' ).addClass( 'wikiEditor-ui-clear' )
536 );
537 // Attach a top container to the left pane
538 context.$wikitext.find( '.wikiEditor-ui-left' ).prepend( $( '<div>' ).addClass( 'wikiEditor-ui-top' ) );
539 // Setup the initial view
540 context.view = 'wikitext';
541 // Trigger the "resize" event anytime the window is resized
542 $( window ).on( 'resize', function ( event ) {
543 context.fn.trigger( 'resize', event );
544 } );
545 }
546
547 /* API Execution */
548
549 // Since javascript gives arguments as an object, we need to convert them so they can be used more easily
550 var args = $.makeArray( arguments );
551
552 // Dynamically setup core extensions for modules that are required
553 if ( args[ 0 ] === 'addModule' && typeof args[ 1 ] !== 'undefined' ) {
554 var modulesArg = args[ 1 ];
555 if ( typeof modulesArg !== 'object' ) {
556 modulesArg = {};
557 modulesArg[ args[ 1 ] ] = '';
558 }
559 for ( var m in modulesArg ) {
560 if ( m in $.wikiEditor.modules ) {
561 // Activate all required core extensions on context
562 for ( var extension in $.wikiEditor.extensions ) {
563 if (
564 $.wikiEditor.isRequired( $.wikiEditor.modules[ m ], extension ) &&
565 context.extensions.indexOf( extension ) === -1
566 ) {
567 context.extensions[ context.extensions.length ] = extension;
568 $.wikiEditor.extensions[ extension ]( context );
569 }
570 }
571 break;
572 }
573 }
574 }
575
576 // There would need to be some arguments if the API is being called
577 if ( args.length > 0 ) {
578 // Handle API calls
579 var callArg = args.shift();
580 if ( callArg in context.api ) {
581 context.api[ callArg ]( context, args[ 0 ] || {} );
582 }
583 }
584
585 // Store the context for next time, and support chaining
586 return $( this ).data( 'wikiEditor-context', context );
587
588 };