Debian Codegraph @

extensions/WikiEditor/modules/jquery.wikiEditor.dialogs.config.js

raw symbols SCIP
1 /**
2 * Configuration of Dialog module for wikiEditor
3 *
4 * @private
5 */
6 var toolbarModule = require( './jquery.wikiEditor.toolbar.js' ),
7 InsertLinkTitleInputField = require( './insertlink/TitleInputField.js' ),
8 LinkTextField = require( './insertlink/LinkTextField.js' ),
9 LinkTypeField = require( './insertlink/LinkTypeField.js' ),
10 insertLinkTitleInputField = new InsertLinkTitleInputField(),
11 insertLinkLinkTextField = new LinkTextField(),
12 insertLinkLinkTypeField = new LinkTypeField(),
13 configData = require( './data.json' );
14
15 function triggerButtonClick( element ) {
16 // The dialog action should always be a DOMElement.
17 var dialogAction = $( element ).data( 'dialogaction' );
18 var $button = dialogAction ? $( dialogAction ) : $( element ).find( 'button' ).first();
19 // Since we're reading from data attribute, make sure we got an element before clicking.
20 // Note when closing a dialog this can be false leading to TypeError: $button.trigger is not a function
21 // (T261529)
22 if ( $button ) {
23 $button.trigger( 'click' );
24 }
25 }
26
27 module.exports = {
28 /**
29 * @param {jQuery} $textarea
30 * @memberof module:ext.wikiEditor
31 */
32 replaceIcons: function ( $textarea ) {
33 $textarea
34 .wikiEditor( 'addToToolbar', {
35 section: 'main',
36 group: 'insert',
37 tools: {
38 link: {
39 label: mw.msg( 'wikieditor-toolbar-tool-link' ),
40 type: 'button',
41 oouiIcon: 'link',
42 action: {
43 type: 'dialog',
44 module: 'insert-link'
45 }
46 },
47 file: {
48 label: mw.msg( 'wikieditor-toolbar-tool-file' ),
49 type: 'button',
50 oouiIcon: 'image',
51 action: {
52 type: 'dialog',
53 module: 'insert-file'
54 }
55 }
56 }
57 } )
58 .wikiEditor( 'addToToolbar', {
59 section: 'advanced',
60 group: 'insert',
61 tools: {
62 table: {
63 label: mw.msg( 'wikieditor-toolbar-tool-table' ),
64 type: 'button',
65 oouiIcon: 'table',
66 action: {
67 type: 'dialog',
68 module: 'insert-table'
69 }
70 }
71 }
72 } )
73 .wikiEditor( 'addToToolbar', {
74 section: 'advanced',
75 groups: {
76 search: {
77 tools: {
78 replace: {
79 label: mw.msg( 'wikieditor-toolbar-tool-replace' ),
80 type: 'button',
81 oouiIcon: 'articleSearch',
82 action: {
83 type: 'dialog',
84 module: 'search-and-replace'
85 }
86 }
87 }
88 }
89 }
90 } );
91 },
92
93 /**
94 * @return {Object}
95 * @memberof module:ext.wikiEditor
96 */
97 getDefaultConfig: function () {
98 return { dialogs: {
99 'insert-link': {
100 title: mw.message( 'wikieditor-toolbar-tool-link-title' ).parse(),
101 id: 'wikieditor-toolbar-link-dialog',
102 html: $( '<fieldset>' ).append(
103 insertLinkTitleInputField.$element,
104 insertLinkLinkTextField.$element,
105 insertLinkLinkTypeField.$element
106 ),
107
108 init: function () {
109 /**
110 * Convenience function for enabling/disabling the main insert button. This is a workaround for
111 * the fact that the button isn't yet in the DOM when init() is run, so we have to query for it
112 * in the event handlers.
113 *
114 * @param {boolean} enable Whether to enable or disable the button
115 */
116 var setButtonState = function ( enable ) {
117 $( '.wikieditor-toolbar-tool-link-insert' ).button( 'option', 'disabled', !enable );
118 };
119 // Automatically copy the value of the internal link page title field to the link text field unless the
120 // user has changed the link text field - this is a convenience thing since most link texts are going to
121 // be the same as the page title.
122 insertLinkTitleInputField.connect( this, {
123 change: function ( val ) {
124 insertLinkLinkTypeField.setIsExternal( insertLinkTitleInputField.isExternal() );
125 insertLinkLinkTextField.setValueIfUntouched( val );
126 setButtonState( val !== '' );
127 },
128 invalid: function () {
129 setButtonState( false );
130 }
131 } );
132 // Tell the title input field when the internal/external radio changes.
133 insertLinkLinkTypeField.connect( this, {
134 change: function ( isExternal ) {
135 var urlMode = isExternal ?
136 LinkTypeField.static.LINK_MODE_EXTERNAL :
137 LinkTypeField.static.LINK_MODE_INTERNAL;
138 insertLinkTitleInputField.setUrlMode( urlMode );
139 }
140 } );
141 },
142 dialog: {
143 width: 500,
144 dialogClass: 'wikiEditor-toolbar-dialog',
145 buttons: {
146 'wikieditor-toolbar-tool-link-insert': {
147 class: 'wikieditor-toolbar-tool-link-insert',
148 text: mw.msg( 'wikieditor-toolbar-tool-link-insert' ),
149 click: function () {
150 var that = this;
151
152 function escapeInternalText( s ) {
153 return s.replace( /(\]{2,})/g, '<nowiki>$1</nowiki>' );
154 }
155 function escapeExternalTarget( s ) {
156 return s.replace( / /g, '%20' )
157 .replace( /\[/g, '%5B' )
158 .replace( /\]/g, '%5D' );
159 }
160 function escapeExternalText( s ) {
161 return s.replace( /(\]+)/g, '<nowiki>$1</nowiki>' );
162 }
163
164 // Make sure that this button isn't disabled.
165 if ( $( '.wikieditor-toolbar-tool-link-insert' ).button( 'option', 'disabled' ) ) {
166 return;
167 }
168
169 var target = insertLinkTitleInputField.getField().getValue();
170 var text = insertLinkLinkTextField.getField().getValue();
171 if ( text.trim() === '' ) {
172 // [[Foo| ]] creates an invisible link
173 // Instead, generate [[Foo|]]
174 text = '';
175 }
176 var insertText = '';
177 if ( insertLinkLinkTypeField.isInternal() ) {
178 if ( target === text || !text.length ) {
179 insertText = '[[' + target + ']]';
180 } else {
181 insertText = '[[' + target + '|' + escapeInternalText( text ) + ']]';
182 }
183 } else {
184 target = target.trim();
185 // Prepend http:// if there is no protocol
186 if ( !/^[a-z]+:\/\/./.test( target ) ) {
187 target = 'http://' + target;
188 }
189
190 // Detect if this is really an internal link in disguise
191 var match = target.match( $( this ).data( 'articlePathRegex' ) );
192 if ( match && !$( this ).data( 'ignoreLooksInternal' ) ) {
193 var buttons = {};
194 buttons[ mw.msg( 'wikieditor-toolbar-tool-link-lookslikeinternal-int' ) ] =
195 function () {
196 var titleValue = match[ 1 ];
197 try {
198 titleValue = decodeURI( titleValue );
199 } catch ( ex ) {
200 // Ignore invalid URLs; use plain titleValue instead.
201 }
202 insertLinkTitleInputField.getField().setValue( titleValue );
203 insertLinkTitleInputField.setUrlMode( LinkTypeField.static.LINK_MODE_INTERNAL );
204 $( this ).dialog( 'close' );
205 // Select the first match (i.e. the value set above) so that the
206 // message under the title field will be updated correctly.
207 insertLinkTitleInputField.getField().selectFirstMatch();
208 };
209 buttons[ mw.msg( 'wikieditor-toolbar-tool-link-lookslikeinternal-ext' ) ] =
210 function () {
211 $( that ).data( 'ignoreLooksInternal', true );
212 $( that ).closest( '.ui-dialog' ).find( 'button' ).first().trigger( 'click' );
213 $( that ).data( 'ignoreLooksInternal', false );
214 $( this ).dialog( 'close' );
215 };
216 $.wikiEditor.modules.dialogs.quickDialog(
217 mw.msg( 'wikieditor-toolbar-tool-link-lookslikeinternal', match[ 1 ] ),
218 { buttons: buttons }
219 );
220 return;
221 }
222
223 var escTarget = escapeExternalTarget( target );
224 var escText = escapeExternalText( text );
225
226 if ( escTarget === escText ) {
227 insertText = escTarget;
228 } else if ( text === '' ) {
229 insertText = '[' + escTarget + ']';
230 } else {
231 insertText = '[' + escTarget + ' ' + escText + ']';
232 }
233 }
234
235 var whitespace = $( '#wikieditor-toolbar-link-dialog' ).data( 'whitespace' );
236 // Preserve whitespace in selection when replacing
237 if ( whitespace ) {
238 insertText = whitespace[ 0 ] + insertText + whitespace[ 1 ];
239 }
240 $( this ).dialog( 'close' );
241 toolbarModule.fn.doAction( $( this ).data( 'context' ), {
242 type: 'replace',
243 options: {
244 pre: insertText
245 }
246 }, $( this ) );
247
248 // Blank form
249 insertLinkTitleInputField.reset();
250 insertLinkLinkTextField.getField().setValue( '' );
251 insertLinkLinkTypeField.getField().selectItem( null );
252 }
253 },
254 'wikieditor-toolbar-tool-link-cancel': function () {
255 $( this ).dialog( 'close' );
256 }
257 },
258 open: function () {
259 // Obtain the server name without the protocol. wgServer may be protocol-relative
260
261 var serverName = mw.config.get( 'wgServer' ).replace( /^(https?:)?\/\//, '' );
262 // Cache the articlepath regex
263
264 $( this ).data( 'articlePathRegex', new RegExp(
265 '^https?://' + mw.util.escapeRegExp( serverName + mw.config.get( 'wgArticlePath' ) )
266 .replace( /\\\$1/g, '(.*)' ) + '$'
267 ) );
268 // Pre-fill the text fields based on the current selection
269 var context = $( this ).data( 'context' );
270 var selection = context.$textarea.textSelection( 'getSelection' );
271
272 insertLinkTitleInputField.getField().focus();
273 // Trigger the change event, so the link status indicator is up to date.
274 // It may be triggered again for the selection, below.
275 insertLinkTitleInputField.getField().emit( 'change', insertLinkTitleInputField.getField().getValue() );
276
277 $( '#wikieditor-toolbar-link-dialog' ).data( 'whitespace', [ '', '' ] );
278 if ( selection !== '' ) {
279 var matches, target, text, isExternal;
280 if ( ( matches = selection.match( /^(\s*)\[\[([^\]|]+)(\|([^\]|]*))?\]\](\s*)$/ ) ) ) {
281 // [[foo|bar]] or [[foo]]
282 target = matches[ 2 ];
283 text = ( matches[ 4 ] ? matches[ 4 ] : matches[ 2 ] );
284 isExternal = false;
285 // Preserve whitespace when replacing
286 $( '#wikieditor-toolbar-link-dialog' ).data( 'whitespace', [ matches[ 1 ], matches[ 5 ] ] );
287 } else if ( ( matches = selection.match( /^(\s*)\[([^\] ]+)( ([^\]]+))?\](\s*)$/ ) ) ) {
288 // [http://www.example.com foo] or [http://www.example.com]
289 target = matches[ 2 ];
290 text = ( matches[ 4 ] || '' );
291 isExternal = true;
292 // Preserve whitespace when replacing
293 $( '#wikieditor-toolbar-link-dialog' ).data( 'whitespace', [ matches[ 1 ], matches[ 5 ] ] );
294 } else {
295 // Trim any leading and trailing whitespace from the selection,
296 // but preserve it when replacing
297 target = text = selection.trim();
298 if ( target.length < selection.length ) {
299 $( '#wikieditor-toolbar-link-dialog' ).data( 'whitespace', [
300 selection.slice( 0, selection.indexOf( target.charAt( 0 ) ) ),
301 selection.slice( selection.lastIndexOf( target.charAt( target.length - 1 ) ) + 1 ) ]
302 );
303 }
304 }
305
306 // Change the values of the title and text fields to the parts extracted from the selection.
307 if ( typeof target !== 'undefined' ) {
308 insertLinkTitleInputField.getField().setValue( target );
309 }
310 if ( typeof text !== 'undefined' ) {
311 insertLinkLinkTextField.getField().setValue( text );
312 }
313 // Don't overwrite values from user's selection.
314 insertLinkLinkTextField.setTouched( true );
315
316 if ( typeof isExternal !== 'undefined' ) {
317 var urlMode = isExternal ?
318 LinkTypeField.static.LINK_MODE_EXTERNAL :
319 LinkTypeField.static.LINK_MODE_INTERNAL;
320 insertLinkTitleInputField.setUrlMode( urlMode );
321 }
322 }
323
324 if ( !$( this ).data( 'dialogkeypressset' ) ) {
325 $( this ).data( 'dialogkeypressset', true );
326 // Execute the action associated with the first button
327 // when the user presses Enter
328 $( this ).closest( '.ui-dialog' ).on( 'keypress', function ( e ) {
329 if ( ( e.keyCode || e.which ) === 13 ) {
330 triggerButtonClick( this );
331 e.preventDefault();
332 }
333 } );
334
335 // Make tabbing to a button and pressing
336 // Enter do what people expect
337 $( this ).closest( '.ui-dialog' ).find( 'button' ).on( 'focus', function () {
338 $( this ).closest( '.ui-dialog' ).data( 'dialogaction', this );
339 } );
340 }
341 }
342 }
343 },
344 'insert-file': {
345 title: mw.message( 'wikieditor-toolbar-tool-file-title' ).parse(),
346 id: 'wikieditor-toolbar-file-dialog',
347 htmlTemplate: 'dialogInsertFile.html',
348 init: function () {
349 var magicWordsI18N = configData.magicWords;
350
351 $( this ).find( '[data-i18n-magic]' )
352 .text( function () {
353 return magicWordsI18N[ $( this ).attr( 'data-i18n-magic' ) ][ 0 ];
354 } )
355 .removeAttr( 'data-i18n-magic' );
356
357 var defaultMsg = mw.msg( 'wikieditor-toolbar-file-default' );
358 $( this ).find( '#wikieditor-toolbar-file-size' )
359 .attr( 'placeholder', defaultMsg )
360 // The message may be long in some languages
361 .attr( 'size', defaultMsg.length );
362 $( this ).find( '[rel]' )
363 .text( function () {
364 // eslint-disable-next-line mediawiki/msg-doc
365 return mw.msg( $( this ).attr( 'rel' ) );
366 } )
367 .removeAttr( 'rel' );
368
369 var altHelpText = mw.msg( 'wikieditor-toolbar-file-alt-help' );
370 var altHelpLabel = mw.msg( 'wikieditor-toolbar-file-alt-help-label' );
371 // Expandable help message for 'alt text' field
372 $( this ).find( '.wikieditor-toolbar-file-alt-help' ).text( altHelpLabel );
373 $( '.wikieditor-toolbar-file-alt-help' ).on( 'click', function () {
374 $( this ).text( function ( i, text ) {
375 return text === altHelpLabel ? altHelpText : altHelpLabel;
376 } );
377 } );
378
379 // Preload modules of file upload dialog.
380 mw.loader.load( [
381 'mediawiki.ForeignStructuredUpload.BookletLayout',
382 'mediawiki.Upload.Dialog',
383 'oojs-ui-windows'
384 ] );
385 },
386 dialog: {
387 resizable: false,
388 dialogClass: 'wikiEditor-toolbar-dialog',
389 width: 590,
390 buttons: {
391 'wikieditor-toolbar-tool-file-insert': function () {
392 var hasPxRgx = /.+px$/,
393 magicWordsI18N = configData.magicWords;
394 var fileName = $( '#wikieditor-toolbar-file-target' ).val();
395 var caption = $( '#wikieditor-toolbar-file-caption' ).val();
396 var fileAlt = $( '#wikieditor-toolbar-file-alt' ).val();
397 var fileFloat = $( '#wikieditor-toolbar-file-float' ).val();
398 var fileFormat = $( '#wikieditor-toolbar-file-format' ).val();
399 var fileSize = $( '#wikieditor-toolbar-file-size' ).val();
400 var whitespace = $( '#wikieditor-toolbar-file-dialog' ).data( 'whitespace' );
401 // Append px to end to size if not already contains it
402 if ( fileSize !== '' && !hasPxRgx.test( fileSize ) ) {
403 fileSize += 'px';
404 }
405 if ( fileName !== '' ) {
406 var fileTitle = mw.Title.newFromText( fileName );
407 // Append file namespace prefix to filename if not already contains it
408 if ( fileTitle && fileTitle.getNamespaceId() !== 6 ) {
409 fileTitle = mw.Title.makeTitle( 6, fileName );
410 }
411 if ( fileTitle ) {
412 fileName = fileTitle.toText();
413 }
414 }
415 var options = [ fileSize, fileFormat, fileFloat ];
416 // Filter empty values
417 options = options.filter( function ( val ) {
418 return val.length && val !== 'default';
419 } );
420 if ( fileAlt.length ) {
421 options.push( magicWordsI18N.img_alt[ 0 ].replace( '$1', fileAlt ) );
422 }
423 if ( caption.length ) {
424 options.push( caption );
425 }
426
427 var fileUse = options.length === 0 ? fileName : ( fileName + '|' + options.join( '|' ) );
428 $( this ).dialog( 'close' );
429 toolbarModule.fn.doAction(
430 $( this ).data( 'context' ),
431 {
432 type: 'replace',
433 options: {
434 pre: whitespace[ 0 ] + '[[',
435 peri: fileUse,
436 post: ']]' + whitespace[ 1 ],
437 ownline: true
438 }
439 },
440 $( this )
441 );
442
443 // Restore form state
444 $( [ '#wikieditor-toolbar-file-target',
445 '#wikieditor-toolbar-file-caption',
446 '#wikieditor-toolbar-file-alt',
447 '#wikieditor-toolbar-file-size' ].join( ',' )
448 ).val( '' );
449 $( '#wikieditor-toolbar-file-float' ).val( 'default' );
450 $( '#wikieditor-toolbar-file-format' ).val( magicWordsI18N.img_thumbnail[ 0 ] );
451 },
452 'wikieditor-toolbar-tool-file-cancel': function () {
453 $( this ).dialog( 'close' );
454 },
455 'wikieditor-toolbar-tool-file-upload': function () {
456 $( this ).dialog( 'close' );
457 mw.loader.using( [
458 'mediawiki.ForeignStructuredUpload.BookletLayout',
459 'mediawiki.Upload.Dialog',
460 'oojs-ui-windows'
461 ] ).then( function () {
462 var windowManager = new OO.ui.WindowManager(),
463 uploadDialog = new mw.Upload.Dialog( {
464 bookletClass: mw.ForeignStructuredUpload.BookletLayout
465 } );
466
467 windowManager.$element.appendTo( document.body );
468 windowManager.addWindows( [ uploadDialog ] );
469 windowManager.openWindow( uploadDialog );
470
471 uploadDialog.uploadBooklet.on( 'fileSaved', function ( imageInfo ) {
472 uploadDialog.close();
473 windowManager.$element.remove();
474
475 $.wikiEditor.modules.dialogs.api.openDialog( this, 'insert-file' );
476 $( '#wikieditor-toolbar-file-target' ).val( imageInfo.canonicaltitle );
477 } );
478 } );
479 }
480 },
481 open: function () {
482 var magicWordsI18N = configData.magicWords,
483 fileData = {
484 pre: '',
485 post: '',
486 fileName: '',
487 caption: '',
488 fileAlt: '',
489 fileSize: '',
490 fileFloat: 'default',
491 fileFormat: magicWordsI18N.img_thumbnail[ 0 ]
492 };
493
494 var parseFileSyntax = function ( wikitext ) {
495 var escapedPipe = '\u0001';
496 if ( wikitext.indexOf( escapedPipe ) !== -1 ) {
497 return false;
498 }
499 var match = /^(\s*)\[\[(.*)\]\](\s*)$/.exec( wikitext );
500 if ( !match ) {
501 return false;
502 }
503 // Escape pipes inside links and templates,
504 // then split the parameters at the remaining pipes
505 var params = match[ 2 ].replace( /\[\[[^[\]]*\]\]|\{\{[^{}]\}\}/g, function ( link ) {
506 return link.replace( /\|/g, escapedPipe );
507 } ).split( '|' );
508 var file = mw.Title.newFromText( params[ 0 ] );
509 if ( !file || file.getNamespaceId() !== 6 ) {
510 return false;
511 }
512 var result = {
513 pre: match[ 1 ],
514 post: match[ 3 ],
515 fileName: file.getMainText()
516 };
517 for ( var i = 1; i < params.length; i++ ) {
518 var paramOrig = params[ i ];
519 var param = paramOrig.toLowerCase();
520 if ( magicWordsI18N.img_right.indexOf( param ) !== -1 ) {
521 result.fileFloat = magicWordsI18N.img_right[ 0 ];
522 } else if ( magicWordsI18N.img_left.indexOf( param ) !== -1 ) {
523 result.fileFloat = magicWordsI18N.img_left[ 0 ];
524 } else if ( magicWordsI18N.img_none.indexOf( param ) !== -1 ) {
525 result.fileFloat = magicWordsI18N.img_none[ 0 ];
526 } else if ( magicWordsI18N.img_center.indexOf( param ) !== -1 ) {
527 result.fileFloat = magicWordsI18N.img_center[ 0 ];
528 } else if ( magicWordsI18N.img_thumbnail.indexOf( param ) !== -1 ) {
529 result.fileFormat = magicWordsI18N.img_thumbnail[ 0 ];
530 } else if ( magicWordsI18N.img_framed.indexOf( param ) !== -1 ) {
531 result.fileFormat = magicWordsI18N.img_framed[ 0 ];
532 } else if ( magicWordsI18N.img_frameless.indexOf( param ) !== -1 ) {
533 result.fileFormat = magicWordsI18N.img_frameless[ 0 ];
534 } else if ( magicWordsI18N.img_alt.indexOf( param.split( '=', 2 )[ 0 ] + '=$1' ) !== -1 ) {
535 result.fileAlt = paramOrig.split( '=', 2 )[ 1 ];
536 } else if ( /.+px$/.test( param ) ) {
537 result.fileSize = param.replace( /px$/, '' );
538 } else if ( param === '' ) {
539 continue;
540 } else if ( i === params.length - 1 ) { // Last param -> caption
541 result.caption = paramOrig.replace( new RegExp( mw.util.escapeRegExp( escapedPipe ), 'g' ), '|' );
542 } else { // Unknown param
543 return false;
544 }
545 }
546 if ( !result.fileFormat ) {
547 result.fileFormat = 'default';
548 }
549 return result;
550 };
551
552 // Retrieve the current selection
553 var context = $( this ).data( 'context' );
554 var selection = context.$textarea.textSelection( 'getSelection' );
555
556 // Pre-fill the text fields based on the current selection
557 if ( selection !== '' ) {
558 fileData = Object.assign( fileData, parseFileSyntax( selection ) );
559 }
560
561 // Initialize the form fields
562 $( '#wikieditor-toolbar-file-dialog' )
563 .data( 'whitespace', [ fileData.pre, fileData.post ] );
564 $( '#wikieditor-toolbar-file-target' ).val( fileData.fileName );
565 $( '#wikieditor-toolbar-file-caption' ).val( fileData.caption );
566 $( '#wikieditor-toolbar-file-alt' ).val( fileData.fileAlt );
567 $( '#wikieditor-toolbar-file-float' ).val( fileData.fileFloat );
568 $( '#wikieditor-toolbar-file-format' ).val( fileData.fileFormat );
569 $( '#wikieditor-toolbar-file-size' ).val( fileData.fileSize );
570
571 // Set focus
572 $( '#wikieditor-toolbar-file-target' ).trigger( 'focus' );
573
574 if ( !( $( this ).data( 'dialogkeypressset' ) ) ) {
575 $( this ).data( 'dialogkeypressset', true );
576 // Execute the action associated with the first button
577 // when the user presses Enter
578 $( this ).closest( '.ui-dialog' ).on( 'keypress', function ( e ) {
579 if ( e.which === 13 ) {
580 triggerButtonClick( this );
581 e.preventDefault();
582 }
583 } );
584
585 // Make tabbing to a button and pressing
586 // Enter do what people expect
587 $( this ).closest( '.ui-dialog' ).find( 'button' ).on( 'focus', function () {
588 $( this ).closest( '.ui-dialog' ).data( 'dialogaction', this );
589 } );
590 }
591 }
592 }
593 },
594 'insert-table': {
595 title: mw.message( 'wikieditor-toolbar-tool-table-title' ).parse(),
596 id: 'wikieditor-toolbar-table-dialog',
597 htmlTemplate: 'dialogInsertTable.html',
598 init: function () {
599 $( this ).find( '[rel]' ).each( function () {
600 // eslint-disable-next-line mediawiki/msg-doc
601 $( this ).text( mw.msg( $( this ).attr( 'rel' ) ) );
602 } );
603
604 $( '#wikieditor-toolbar-table-dimensions-rows' ).val( 3 );
605 $( '#wikieditor-toolbar-table-dimensions-columns' ).val( 3 );
606 $( '#wikieditor-toolbar-table-wikitable' ).on( 'click', function () {
607 // eslint-disable-next-line no-jquery/no-class-state
608 $( '.wikieditor-toolbar-table-preview' ).toggleClass( 'wikitable' );
609 } );
610
611 // Hack for sortable preview: dynamically adding
612 // sortable class doesn't work, so we use a clone
613 $( '#wikieditor-toolbar-table-preview' )
614 .clone()
615 .attr( 'id', 'wikieditor-toolbar-table-preview2' )
616 .addClass( 'sortable' )
617 .insertAfter( $( '#wikieditor-toolbar-table-preview' ) )
618 .hide();
619
620 mw.loader.using( 'jquery.tablesorter', function () {
621 $( '#wikieditor-toolbar-table-preview2' ).tablesorter();
622 } );
623
624 $( '#wikieditor-toolbar-table-sortable' ).on( 'click', function () {
625 // Swap the currently shown one clone with the other one
626 $( '#wikieditor-toolbar-table-preview' )
627 .hide()
628 .attr( 'id', 'wikieditor-toolbar-table-preview3' );
629 $( '#wikieditor-toolbar-table-preview2' )
630 .attr( 'id', 'wikieditor-toolbar-table-preview' )
631 .show();
632 $( '#wikieditor-toolbar-table-preview3' ).attr( 'id', 'wikieditor-toolbar-table-preview2' );
633 } );
634
635 $( '#wikieditor-toolbar-table-dimensions-header' ).on( 'click', function () {
636 // Instead of show/hiding, switch the HTML around
637 // We do this because the sortable tables script styles the first row,
638 // visible or not
639 var headerHTML = $( '.wikieditor-toolbar-table-preview-header' ).html(),
640 hiddenHTML = $( '.wikieditor-toolbar-table-preview-hidden' ).html();
641 $( '.wikieditor-toolbar-table-preview-header' ).html( hiddenHTML );
642 $( '.wikieditor-toolbar-table-preview-hidden' ).html( headerHTML );
643 var $sortable = $( '#wikieditor-toolbar-table-preview, #wikieditor-toolbar-table-preview2' )
644 .filter( '.sortable' );
645 mw.loader.using( 'jquery.tablesorter', function () {
646 $sortable.tablesorter();
647 } );
648 } );
649 },
650 dialog: {
651 resizable: false,
652 dialogClass: 'wikiEditor-toolbar-dialog',
653 width: 590,
654 buttons: {
655 'wikieditor-toolbar-tool-table-insert': function () {
656 var rowsVal = $( '#wikieditor-toolbar-table-dimensions-rows' ).val(),
657 colsVal = $( '#wikieditor-toolbar-table-dimensions-columns' ).val(),
658 rows = parseInt( rowsVal, 10 ),
659 cols = parseInt( colsVal, 10 ),
660 header = $( '#wikieditor-toolbar-table-dimensions-header' ).prop( 'checked' ) ? 1 : 0;
661 if ( isNaN( rows ) || isNaN( cols ) || String( rows ) !== rowsVal || String( cols ) !== colsVal || rowsVal < 0 || colsVal < 0 ) {
662 // eslint-disable-next-line no-alert
663 alert( mw.msg( 'wikieditor-toolbar-tool-table-invalidnumber' ) );
664 return;
665 }
666 if ( rows + header === 0 || cols === 0 ) {
667 // eslint-disable-next-line no-alert
668 alert( mw.msg( 'wikieditor-toolbar-tool-table-zero' ) );
669 return;
670 }
671 if ( ( rows * cols ) > 1000 ) {
672 // eslint-disable-next-line no-alert
673 alert( mw.msg( 'wikieditor-toolbar-tool-table-toomany', mw.language.convertNumber( 1000 ) ) );
674 return;
675 }
676 var captionText = mw.msg( 'wikieditor-toolbar-tool-table-example-caption' );
677 var headerText = mw.msg( 'wikieditor-toolbar-tool-table-example-header' );
678 var normalText = mw.msg( 'wikieditor-toolbar-tool-table-example' );
679 var table = '';
680 table += '|+ ' + captionText + '\n';
681 for ( var r = 0; r < rows + header; r++ ) {
682 table += '|-\n';
683 for ( var c = 0; c < cols; c++ ) {
684 var isHeader = ( header && r === 0 );
685 var delim = isHeader ? '!' : '|';
686 if ( c > 0 ) {
687 delim += delim;
688 }
689 table += delim + ' ' + ( isHeader ? headerText : normalText ) + ' ';
690 }
691 // Replace trailing space by newline
692 // table[table.length - 1] is read-only
693 table = table.slice( 0, table.length - 1 ) + '\n';
694 }
695 var classes = [];
696 if ( $( '#wikieditor-toolbar-table-wikitable' ).is( ':checked' ) ) {
697 classes.push( 'wikitable' );
698 }
699 if ( $( '#wikieditor-toolbar-table-sortable' ).is( ':checked' ) ) {
700 classes.push( 'sortable' );
701 }
702 var classStr = classes.length > 0 ? ' class="' + classes.join( ' ' ) + '"' : '';
703 $( this ).dialog( 'close' );
704 toolbarModule.fn.doAction(
705 $( this ).data( 'context' ),
706 {
707 type: 'replace',
708 options: {
709 pre: '{|' + classStr + '\n',
710 peri: table,
711 post: '|}',
712 ownline: true
713 }
714 },
715 $( this )
716 );
717
718 // Restore form state
719 $( '#wikieditor-toolbar-table-dimensions-rows' ).val( 3 );
720 $( '#wikieditor-toolbar-table-dimensions-columns' ).val( 3 );
721 // Simulate clicks instead of setting values, so the according
722 // actions are performed
723 if ( !$( '#wikieditor-toolbar-table-dimensions-header' ).is( ':checked' ) ) {
724 $( '#wikieditor-toolbar-table-dimensions-header' ).trigger( 'click' );
725 }
726 if ( !$( '#wikieditor-toolbar-table-wikitable' ).is( ':checked' ) ) {
727 $( '#wikieditor-toolbar-table-wikitable' ).trigger( 'click' );
728 }
729 if ( $( '#wikieditor-toolbar-table-sortable' ).is( ':checked' ) ) {
730 $( '#wikieditor-toolbar-table-sortable' ).trigger( 'click' );
731 }
732 },
733 'wikieditor-toolbar-tool-table-cancel': function () {
734 $( this ).dialog( 'close' );
735 }
736 },
737 open: function () {
738 $( '#wikieditor-toolbar-table-dimensions-rows' ).trigger( 'focus' );
739 if ( !( $( this ).data( 'dialogkeypressset' ) ) ) {
740 $( this ).data( 'dialogkeypressset', true );
741 // Execute the action associated with the first button
742 // when the user presses Enter
743 $( this ).closest( '.ui-dialog' ).on( 'keypress', function ( e ) {
744 if ( ( e.keyCode || e.which ) === 13 ) {
745 triggerButtonClick( this );
746 e.preventDefault();
747 }
748 } );
749
750 // Make tabbing to a button and pressing
751 // Enter do what people expect
752 $( this ).closest( '.ui-dialog' ).find( 'button' ).on( 'focus', function () {
753 $( this ).closest( '.ui-dialog' ).data( 'dialogaction', this );
754 } );
755 }
756 }
757 }
758 },
759 'search-and-replace': {
760 title: mw.message( 'wikieditor-toolbar-tool-replace-title' ).parse(),
761 id: 'wikieditor-toolbar-replace-dialog',
762 htmlTemplate: 'dialogReplace.html',
763 init: function () {
764 $( this ).find( '[rel]' ).each( function () {
765 // eslint-disable-next-line mediawiki/msg-doc
766 $( this ).text( mw.msg( $( this ).attr( 'rel' ) ) );
767 } );
768
769 // TODO: Find a cleaner way to share this function
770 $( this ).data( 'replaceCallback', function ( mode ) {
771 $( '#wikieditor-toolbar-replace-nomatch, #wikieditor-toolbar-replace-success, #wikieditor-toolbar-replace-emptysearch, #wikieditor-toolbar-replace-invalidregex' ).hide();
772
773 // Search string cannot be empty
774 var searchStr = $( '#wikieditor-toolbar-replace-search' ).val();
775 if ( searchStr === '' ) {
776 $( '#wikieditor-toolbar-replace-emptysearch' ).show();
777 return;
778 }
779
780 // Replace string can be empty
781 var replaceStr = $( '#wikieditor-toolbar-replace-replace' ).val();
782
783 // Prepare the regular expression flags
784 var flags = 'm';
785 var matchCase = $( '#wikieditor-toolbar-replace-case' ).is( ':checked' );
786 if ( !matchCase ) {
787 flags += 'i';
788 }
789 var isRegex = $( '#wikieditor-toolbar-replace-regex' ).is( ':checked' );
790 if ( !isRegex ) {
791 searchStr = mw.util.escapeRegExp( searchStr );
792 }
793 var matchWord = $( '#wikieditor-toolbar-replace-word' ).is( ':checked' );
794 if ( matchWord ) {
795 searchStr = '\\b(?:' + searchStr + ')\\b';
796 }
797 if ( mode === 'replaceAll' ) {
798 flags += 'g';
799 }
800
801 var regex;
802 try {
803 regex = new RegExp( searchStr, flags );
804 } catch ( e ) {
805 $( '#wikieditor-toolbar-replace-invalidregex' )
806 .text( mw.msg( 'wikieditor-toolbar-tool-replace-invalidregex',
807 e.message ) )
808 .show();
809 return;
810 }
811
812 var $textarea = $( this ).data( 'context' ).$textarea;
813 var text = $textarea.textSelection( 'getContents' );
814 var match = false;
815 var offset, textRemainder;
816 if ( mode !== 'replaceAll' ) {
817 offset = $( this ).data( mode === 'replace' ? 'matchIndex' : 'offset' );
818 textRemainder = text.slice( offset );
819 match = textRemainder.match( regex );
820 }
821 if ( !match ) {
822 // Search hit BOTTOM, continuing at TOP
823 // TODO: Add a "Wrap around" option.
824 offset = 0;
825 textRemainder = text;
826 match = textRemainder.match( regex );
827 }
828
829 if ( !match ) {
830 $( '#wikieditor-toolbar-replace-nomatch' ).show();
831 } else if ( mode === 'replaceAll' ) {
832 $textarea.textSelection( 'setContents', text.replace( regex, replaceStr ) );
833 $( '#wikieditor-toolbar-replace-success' )
834 .text( mw.msg( 'wikieditor-toolbar-tool-replace-success', mw.language.convertNumber( match.length ) ) )
835 .show();
836 $( this ).data( 'offset', 0 );
837 } else {
838
839 var start, end;
840 if ( mode === 'replace' ) {
841
842 var actualReplacement;
843 if ( isRegex ) {
844 // If backreferences (like $1) are used, the actual actual replacement string will be different
845 actualReplacement = match[ 0 ].replace( regex, replaceStr );
846 } else {
847 actualReplacement = replaceStr;
848 }
849
850 if ( match ) {
851 // Do the replacement
852 $textarea.textSelection( 'encapsulateSelection', {
853 peri: actualReplacement,
854 replace: true,
855 selectionStart: offset + match.index,
856 selectionEnd: offset + match.index + match[ 0 ].length,
857 selectPeri: true
858 } );
859 // Reload the text after replacement
860 text = $textarea.textSelection( 'getContents' );
861 }
862
863 // Find the next instance
864 offset = offset + match.index + actualReplacement.length;
865 textRemainder = text.slice( offset );
866 match = textRemainder.match( regex );
867 if ( !match ) {
868 // If no new string was found, try searching from the beginning.
869 // TODO: Add a "Wrap around" option.
870 offset = 0;
871 textRemainder = text;
872 match = textRemainder.match( regex );
873 }
874 if ( !match ) {
875 // Give up
876 match = { index: 0, 0: { length: 0 } };
877 }
878 }
879 start = offset + match.index;
880 end = start + match[ 0 ].length;
881
882 $( this ).data( 'matchIndex', start );
883
884 $textarea.textSelection( 'setSelection', {
885 start: start,
886 end: end } );
887 $textarea.textSelection( 'scrollToCaretPosition' );
888 $( this ).data( 'offset', end );
889 $textarea[ 0 ].focus();
890 }
891 } );
892 },
893 dialog: {
894 width: 500,
895 dialogClass: 'wikiEditor-toolbar-dialog',
896 modal: false,
897 buttons: {
898 'wikieditor-toolbar-tool-replace-button-findnext': function ( e ) {
899 $( this ).closest( '.ui-dialog' ).data( 'dialogaction', e.target );
900 $( this ).data( 'replaceCallback' ).call( this, 'find' );
901 },
902 'wikieditor-toolbar-tool-replace-button-replace': function ( e ) {
903 $( this ).closest( '.ui-dialog' ).data( 'dialogaction', e.target );
904 $( this ).data( 'replaceCallback' ).call( this, 'replace' );
905 },
906 'wikieditor-toolbar-tool-replace-button-replaceall': function ( e ) {
907 $( this ).closest( '.ui-dialog' ).data( 'dialogaction', e.target );
908 $( this ).data( 'replaceCallback' ).call( this, 'replaceAll' );
909 },
910 'wikieditor-toolbar-tool-replace-close': function () {
911 $( this ).dialog( 'close' );
912 }
913 },
914 open: function () {
915 var that = this;
916 $( this ).data( { offset: 0, matchIndex: 0 } );
917
918 $( '#wikieditor-toolbar-replace-search' ).trigger( 'focus' );
919 $( '#wikieditor-toolbar-replace-nomatch, #wikieditor-toolbar-replace-success, #wikieditor-toolbar-replace-emptysearch, #wikieditor-toolbar-replace-invalidregex' ).hide();
920 if ( !( $( this ).data( 'onetimeonlystuff' ) ) ) {
921 $( this ).data( 'onetimeonlystuff', true );
922 // Execute the action associated with the first button
923 // when the user presses Enter
924 $( this ).closest( '.ui-dialog' ).on( 'keypress', function ( e ) {
925 if ( ( e.keyCode || e.which ) === 13 ) {
926 triggerButtonClick( this );
927 e.preventDefault();
928 }
929 } );
930 // Make tabbing to a button and pressing
931 // Enter do what people expect
932 $( this ).closest( '.ui-dialog' ).find( 'button' ).on( 'focus', function () {
933 $( this ).closest( '.ui-dialog' ).data( 'dialogaction', this );
934 } );
935 }
936 var $dialog = $( this ).closest( '.ui-dialog' );
937 that = this;
938 $( this ).data( 'context' ).$textarea
939 .on( 'keypress.srdialog', function ( e ) {
940 if ( e.which === 13 ) {
941 // Enter
942 triggerButtonClick( $dialog );
943 e.preventDefault();
944 } else if ( e.which === 27 ) {
945 // Escape
946 $( that ).dialog( 'close' );
947 }
948 } );
949 },
950 close: function () {
951 $( this ).data( 'context' ).$textarea
952 .off( 'keypress.srdialog' );
953 $( this ).closest( '.ui-dialog' ).data( 'dialogaction', false );
954 }
955 }
956 }
957 } };
958 }
959
960 };