Debian Codegraph @

extensions/TemplateData/modules/ext.templateDataGenerator.editTemplatePage/Dialog.js

raw symbols SCIP
1 const
2 LanguageSearchWidget = require( './widgets/LanguageSearchWidget.js' ),
3 Metrics = require( './Metrics.js' ),
4 Model = require( 'ext.templateDataGenerator.data' ).Model,
5 ParamImportWidget = require( './widgets/ParamImportWidget.js' ),
6 ParamSelectWidget = require( './widgets/ParamSelectWidget.js' ),
7 ParamWidget = require( './widgets/ParamWidget.js' );
8
9 /**
10 * TemplateData Dialog
11 *
12 * @class
13 * @extends OO.ui.ProcessDialog
14 *
15 * @constructor
16 * @param {Object} config Dialog configuration object
17 *
18 * @external LanguageResultWidget
19 */
20 function Dialog( config ) {
21 // Parent constructor
22 Dialog.super.call( this, config );
23
24 this.model = null;
25 this.modified = false;
26 this.language = null;
27 this.availableLanguages = [];
28 this.selectedParamKey = '';
29 this.propInputs = {};
30 this.propFieldLayout = {};
31 this.isSetup = false;
32 this.mapsCache = undefined;
33 this.descriptionChanged = false;
34 this.paramsReordered = false;
35 this.paramPropertyChangeTracking = {};
36
37 // Initialize
38 this.$element.addClass( 'tdg-templateDataDialog' );
39 }
40
41 /* Inheritance */
42
43 OO.inheritClass( Dialog, OO.ui.ProcessDialog );
44
45 /* Static properties */
46 Dialog.static.name = 'TemplateDataDialog';
47 Dialog.static.title = mw.msg( 'templatedata-modal-title' );
48 Dialog.static.size = 'large';
49 Dialog.static.actions = [
50 {
51 action: 'apply',
52 label: mw.msg( 'templatedata-modal-button-apply' ),
53 flags: [ 'primary', 'progressive' ],
54 modes: 'list'
55 },
56 {
57 action: 'done',
58 label: mw.msg( 'templatedata-modal-button-done' ),
59 flags: [ 'primary', 'progressive' ],
60 modes: [ 'edit', 'maps' ]
61 },
62 {
63 action: 'add',
64 label: mw.msg( 'templatedata-modal-button-addparam' ),
65 icon: 'add',
66 flags: [ 'progressive' ],
67 modes: 'list'
68 },
69 {
70 action: 'delete',
71 label: mw.msg( 'templatedata-modal-button-delparam' ),
72 modes: 'edit',
73 flags: 'destructive'
74 },
75 {
76 action: 'cancel',
77 label: mw.msg( 'templatedata-modal-button-cancel' ),
78 modes: 'maps',
79 flags: 'destructive'
80 },
81 {
82 label: mw.msg( 'templatedata-modal-button-cancel' ),
83 flags: [ 'safe', 'close' ],
84 modes: [ 'list', 'error' ]
85 },
86 {
87 action: 'back',
88 label: mw.msg( 'templatedata-modal-button-back' ),
89 flags: [ 'safe', 'back' ],
90 modes: [ 'language', 'add' ]
91 }
92 ];
93
94 /**
95 * Initialize window contents.
96 *
97 * The first time the window is opened, #initialize is called so that changes to the window that
98 * will persist between openings can be made. See #getSetupProcess for a way to make changes each
99 * time the window opens.
100 *
101 * @throws {Error} If not attached to a manager
102 * @chainable
103 */
104 Dialog.prototype.initialize = function () {
105 // Parent method
106 Dialog.super.prototype.initialize.call( this );
107
108 this.$spinner = $( '<div>' ).addClass( 'tdg-spinner' ).text( 'working...' );
109 this.$body.append( this.$spinner );
110
111 this.noticeMessage = new OO.ui.MessageWidget()
112 .toggle( false );
113
114 this.panels = new OO.ui.StackLayout( { continuous: false } );
115
116 this.listParamsPanel = new OO.ui.PanelLayout( { padded: true, scrollable: true } );
117 this.editParamPanel = new OO.ui.PanelLayout( { padded: true } );
118 this.languagePanel = new OO.ui.PanelLayout();
119 this.addParamPanel = new OO.ui.PanelLayout( { padded: true } );
120 this.editMapsPanel = new OO.ui.PanelLayout();
121
122 // Language panel
123 this.newLanguageSearch = new LanguageSearchWidget();
124
125 // Add parameter panel
126 this.newParamInput = new OO.ui.TextInputWidget( {
127 placeholder: mw.msg( 'templatedata-modal-placeholder-paramkey' )
128 } );
129 this.addParamButton = new OO.ui.ButtonWidget( {
130 label: mw.msg( 'templatedata-modal-button-addparam' ),
131 flags: [ 'progressive', 'primary' ],
132 disabled: true
133 } );
134 const addParamFieldlayout = new OO.ui.ActionFieldLayout(
135 this.newParamInput,
136 this.addParamButton,
137 {
138 align: 'top',
139 label: mw.msg( 'templatedata-modal-title-addparam' )
140 }
141 );
142
143 // Maps panel
144 this.templateMapsInput = new OO.ui.MultilineTextInputWidget( {
145 classes: [ 'mw-templateData-template-maps-input mw-editfont-monospace' ],
146 autosize: true,
147 rows: this.getBodyHeight() / 22.5,
148 maxRows: this.getBodyHeight() / 22.5,
149 placeholder: mw.msg( 'templatedata-modal-placeholder-mapinfo' ),
150 scrollable: true
151 } );
152 this.removeMapButton = new OO.ui.ButtonWidget( {
153 classes: [ 'mw-templateData-template-remove-map-button' ],
154 label: mw.msg( 'templatedata-modal-button-removemap' ),
155 icon: 'trash',
156 flags: [ 'destructive' ]
157 } );
158 this.addNewMapButton = new OO.ui.ButtonWidget( {
159 classes: [ 'mw-templateData-template-add-map-button' ],
160 label: mw.msg( 'templatedata-modal-button-addmap' ),
161 icon: 'add',
162 framed: false,
163 flags: [ 'progressive' ]
164 } );
165 this.newMapNameInput = new OO.ui.TextInputWidget( {
166 value: '',
167 placeholder: mw.msg( 'templatedata-modal-placeholder-prompt-map-name' ),
168 classes: [ 'mw-templateData-template-map-prompter' ]
169 } );
170 this.cancelAddMapButton = new OO.ui.ButtonWidget( {
171 label: mw.msg( 'templatedata-modal-button-cancel' ),
172 framed: false,
173 flags: [ 'destructive' ]
174 } );
175 this.saveAddMapButton = new OO.ui.ButtonWidget( {
176 label: mw.msg( 'templatedata-modal-button-done' ),
177 framed: false,
178 flags: [ 'primary', 'progressive' ]
179 } );
180 this.mapsGroup = new OO.ui.OutlineSelectWidget( {
181 classes: [ 'mw-templateData-template-map-group' ]
182 } );
183 const addNewMapButtonPanel = new OO.ui.PanelLayout( {
184 classes: [ 'mw-templateData-template-add-map-button-panel' ],
185 padded: true,
186 expanded: true
187 } );
188 const mapsListPanel = new OO.ui.PanelLayout( {
189 expanded: true,
190 scrollable: true
191 } );
192 const mapsListMenuLayout = new OO.ui.MenuLayout( {
193 classes: [ 'mw-templateData-template-map-list-menu-panel' ],
194 menuPosition: 'top',
195 expanded: true,
196 contentPanel: mapsListPanel,
197 menuPanel: addNewMapButtonPanel
198 } );
199 const mapsContentPanel = new OO.ui.PanelLayout( {
200 padded: true,
201 expanded: true
202 } );
203 const templateMapsMenuLayout = new OO.ui.MenuLayout( {
204 contentPanel: mapsContentPanel,
205 menuPanel: mapsListMenuLayout
206 } );
207
208 // Param list panel (main)
209 this.languageDropdownWidget = new OO.ui.DropdownWidget();
210 this.languagePanelButton = new OO.ui.ButtonWidget( {
211 label: mw.msg( 'templatedata-modal-button-add-language' ),
212 flags: [ 'progressive' ]
213 } );
214
215 const languageActionFieldLayout = new OO.ui.ActionFieldLayout(
216 this.languageDropdownWidget,
217 this.languagePanelButton,
218 {
219 align: 'left',
220 label: mw.msg( 'templatedata-modal-title-language' )
221 }
222 );
223
224 this.descriptionInput = new OO.ui.MultilineTextInputWidget( {
225 autosize: true
226 } );
227 this.templateDescriptionFieldset = new OO.ui.FieldsetLayout( {
228 items: [ this.descriptionInput ]
229 } );
230 // Add Maps panel button
231 this.mapsPanelButton = new OO.ui.ButtonWidget( {
232 label: mw.msg( 'templatedata-modal-button-map' ),
233 classes: [ 'mw-templateData-maps-panel-button' ]
234 } );
235 this.paramListNoticeMessage = new OO.ui.MessageWidget();
236 this.paramListNoticeMessage.toggle( false );
237
238 this.paramSelect = new ParamSelectWidget();
239 this.paramImport = new ParamImportWidget();
240 const templateParamsFieldset = new OO.ui.FieldsetLayout( {
241 label: mw.msg( 'templatedata-modal-title-templateparams' ),
242 items: [ this.paramSelect, this.paramImport ]
243 } );
244
245 this.templateFormatSelectWidget = new OO.ui.ButtonSelectWidget();
246 this.templateFormatSelectWidget.addItems( [
247 new OO.ui.ButtonOptionWidget( {
248 data: null,
249 label: mw.msg( 'templatedata-modal-format-null' )
250 } ),
251 new OO.ui.ButtonOptionWidget( {
252 data: 'inline',
253 icon: 'template-format-inline',
254 label: mw.msg( 'templatedata-modal-format-inline' )
255 } ),
256 new OO.ui.ButtonOptionWidget( {
257 data: 'block',
258 icon: 'template-format-block',
259 label: mw.msg( 'templatedata-modal-format-block' )
260 } ),
261 new OO.ui.ButtonOptionWidget( {
262 data: 'custom',
263 icon: 'settings',
264 label: mw.msg( 'templatedata-modal-format-custom' )
265 } )
266 ] );
267 this.templateFormatInputWidget = new OO.ui.TextInputWidget( {
268 placeholder: mw.msg( 'templatedata-modal-format-placeholder' )
269 } );
270
271 const templateFormatFieldSet = new OO.ui.FieldsetLayout( {
272 label: mw.msg( 'templatedata-modal-title-templateformat' ),
273 items: [
274 new OO.ui.FieldLayout( this.templateFormatSelectWidget ),
275 new OO.ui.FieldLayout( this.templateFormatInputWidget, {
276 align: 'top',
277 label: mw.msg( 'templatedata-modal-title-templateformatstring' )
278 } )
279 ]
280 } );
281
282 // Param details panel
283 this.$paramDetailsContainer = $( '<div>' )
284 .addClass( 'tdg-templateDataDialog-paramDetails' );
285
286 this.listParamsPanel.$element
287 .addClass( 'tdg-templateDataDialog-listParamsPanel' )
288 .append(
289 this.paramListNoticeMessage.$element,
290 languageActionFieldLayout.$element,
291 this.templateDescriptionFieldset.$element,
292 new OO.ui.FieldLayout( this.mapsPanelButton ).$element,
293 templateFormatFieldSet.$element,
294 templateParamsFieldset.$element
295 );
296 this.paramEditNoticeMessage = new OO.ui.MessageWidget();
297 this.paramEditNoticeMessage.toggle( false );
298 // Edit panel
299 this.editParamPanel.$element
300 .addClass( 'tdg-templateDataDialog-editParamPanel' )
301 .append(
302 this.paramEditNoticeMessage.$element,
303 this.$paramDetailsContainer
304 );
305 // Language panel
306 this.languagePanel.$element
307 .addClass( 'tdg-templateDataDialog-languagePanel' )
308 .append(
309 this.newLanguageSearch.$element
310 );
311 this.addParamPanel.$element
312 .addClass( 'tdg-templateDataDialog-addParamPanel' )
313 .append( addParamFieldlayout.$element );
314
315 // Maps panel
316 mapsListPanel.$element
317 .addClass( 'tdg-templateDataDialog-mapsListPanel' )
318 .append( this.mapsGroup.$element );
319 this.newMapNameInput.$element.hide();
320 this.cancelAddMapButton.$element.hide();
321 this.saveAddMapButton.$element.hide();
322 addNewMapButtonPanel.$element
323 .addClass( 'tdg-templateDataDialog-addNewMapButtonPanel' )
324 .append(
325 this.addNewMapButton.$element,
326 this.newMapNameInput.$element,
327 this.cancelAddMapButton.$element,
328 this.saveAddMapButton.$element
329 );
330 mapsContentPanel.$element
331 .addClass( 'tdg-templateDataDialog-mapsContentPanel' )
332 .append(
333 this.removeMapButton.$element,
334 this.templateMapsInput.$element
335 );
336 this.editMapsPanel.$element
337 .addClass( 'tdg-templateDataDialog-editMapsPanel' )
338 .append( templateMapsMenuLayout.$element );
339 this.panels.addItems( [
340 this.listParamsPanel,
341 this.editParamPanel,
342 this.languagePanel,
343 this.addParamPanel,
344 this.editMapsPanel
345 ] );
346 this.panels.setItem( this.listParamsPanel );
347 this.panels.$element.addClass( 'tdg-templateDataDialog-panels' );
348
349 // Build param details panel
350 this.$paramDetailsContainer.append( this.createParamDetails() );
351
352 // Initialization
353 this.$body.append(
354 this.noticeMessage.$element,
355 this.panels.$element
356 );
357
358 // Events
359 this.newLanguageSearch.getResults().connect( this, { choose: 'onNewLanguageSearchResultsChoose' } );
360 this.newParamInput.connect( this, { change: 'onAddParamInputChange', enter: 'onAddParamButtonClick' } );
361 this.addParamButton.connect( this, { click: 'onAddParamButtonClick' } );
362 this.descriptionInput.connect( this, { change: 'onDescriptionInputChange' } );
363 this.languagePanelButton.connect( this, { click: 'onLanguagePanelButton' } );
364 this.languageDropdownWidget.getMenu().connect( this, { select: 'onLanguageDropdownWidgetSelect' } );
365 this.mapsPanelButton.connect( this, { click: 'onMapsPanelButton' } );
366 this.addNewMapButton.connect( this, { click: 'onAddNewMapClick' } );
367 this.cancelAddMapButton.connect( this, { click: 'onCancelAddingMap' } );
368 this.saveAddMapButton.connect( this, { click: 'onEmbedNewMap' } );
369 this.newMapNameInput.connect( this, { enter: 'onEmbedNewMap' } );
370 this.mapsGroup.connect( this, { select: 'onMapsGroupSelect' } );
371 this.removeMapButton.connect( this, { click: 'onMapItemRemove' } );
372 this.templateMapsInput.connect( this, { change: 'onMapInfoChange' } );
373 this.paramSelect.connect( this, {
374 choose: 'onParamSelectChoose',
375 reorder: 'onParamSelectReorder'
376 } );
377 this.paramImport.connect( this, { click: 'importParametersFromTemplateCode' } );
378 this.templateFormatSelectWidget.connect( this, { choose: 'onTemplateFormatSelectWidgetChoose' } );
379 this.templateFormatInputWidget.connect( this, {
380 change: 'onTemplateFormatInputWidgetChange',
381 enter: 'onTemplateFormatInputWidgetEnter'
382 } );
383 };
384
385 /**
386 * Respond to model change of description event
387 *
388 * @param {string} description New description
389 */
390 Dialog.prototype.onModelChangeDescription = function ( description ) {
391 this.descriptionInput.setValue( description );
392 };
393
394 /**
395 * Respond to model change of map info event
396 *
397 * @param {Object|undefined} map
398 */
399 Dialog.prototype.onModelChangeMapInfo = function ( map ) {
400 const selectedItem = this.mapsGroup.findSelectedItem();
401 map = map || {};
402 this.mapsCache = OO.copy( map );
403 if ( selectedItem ) {
404 this.templateMapsInput.setValue( this.stringifyObject( map[ selectedItem.label ] ) );
405 }
406 };
407
408 /**
409 * Respond to add param input change.
410 *
411 * @param {string} value New parameter name
412 */
413 Dialog.prototype.onAddParamInputChange = function ( value ) {
414 const allProps = Model.static.getAllProperties( true );
415
416 value = value.trim();
417 const invalid = !value || allProps.name.restrict.test( value );
418 const used = this.model.isParamExists( value ) && !this.model.isParamDeleted( value );
419 this.addParamButton.setDisabled( invalid || used );
420 };
421
422 /**
423 * Respond to change of param order from the model
424 *
425 * @param {string[]} paramOrderArray The array of keys in order
426 */
427 Dialog.prototype.onModelChangeParamOrder = function () {
428 // Refresh the parameter widget
429 this.repopulateParamSelectWidget();
430 };
431
432 /**
433 * Respond to change of param property from the model
434 *
435 * @param {string} paramKey Parameter key
436 * @param {string} prop Property name
437 * @param {Mixed} value
438 * @param {string} language
439 */
440 Dialog.prototype.onModelChangeProperty = function ( paramKey, prop, value ) {
441 // Refresh the parameter widget
442 if ( paramKey === this.selectedParamKey && prop === 'name' ) {
443 this.selectedParamKey = value;
444 }
445 };
446
447 /**
448 * Respond to a change in the model
449 */
450 Dialog.prototype.onModelChange = function () {
451 this.modified = true;
452 this.updateActions();
453 };
454
455 /**
456 * Set action abilities according to whether the model is modified
457 */
458 Dialog.prototype.updateActions = function () {
459 this.actions.setAbilities( { apply: this.modified } );
460 };
461
462 /**
463 * Respond to param order widget reorder event
464 *
465 * @param {OO.ui.OptionWidget} item Item reordered
466 * @param {number} newIndex New index of the item
467 */
468 Dialog.prototype.onParamSelectReorder = function ( item, newIndex ) {
469 if ( !this.paramsReordered ) {
470 Metrics.logEvent( 'parameter-reorder' );
471 }
472 this.paramsReordered = true;
473
474 this.model.reorderParamOrderKey( item.getData(), newIndex );
475 };
476
477 /**
478 * Respond to description input change event
479 *
480 * @param {string} value Description value
481 */
482 Dialog.prototype.onDescriptionInputChange = function ( value ) {
483 if ( !this.descriptionChanged ) {
484 Metrics.logEvent( 'template-description-change' );
485 }
486 this.descriptionChanged = true;
487
488 if ( this.model.getTemplateDescription( this.language ) !== value ) {
489 this.model.setTemplateDescription( value, this.language );
490 }
491 };
492
493 /**
494 * Create items for the returned maps and add them to the maps group
495 *
496 * @param {Object|undefined} mapsObject
497 */
498 Dialog.prototype.populateMapsItems = function ( mapsObject ) {
499 mapsObject = mapsObject || {};
500 const mapKeysList = Object.keys( mapsObject );
501
502 const items = mapKeysList.map( ( mapKey ) => new OO.ui.OutlineOptionWidget( {
503 label: mapKey
504 } ) );
505
506 this.mapsGroup.clearItems();
507 this.mapsGroup.addItems( items );
508
509 // Maps is not empty anymore
510 this.updateActions();
511 };
512
513 /**
514 * Respond to edit maps input change event
515 *
516 * @param {string} value map info value
517 */
518 Dialog.prototype.onMapInfoChange = function ( value ) {
519 const selectedItem = this.mapsGroup.findSelectedItem();
520 // Update map Info
521 this.model.maps = this.model.getMapInfo() || {};
522 if ( selectedItem ) {
523 if ( this.model.getMapInfo()[ selectedItem.label ] !== value ) {
524 // Disable Done button in case of invalid JSON
525 try {
526 // This parsing method keeps only the last key/value pair if duplicate keys are defined, and does not throw an error.
527 // Our model will be updated with a valid maps object, but the user may lose their input if it has duplicate key.
528 this.mapsCache[ selectedItem.label ] = JSON.parse( value );
529 this.actions.setAbilities( { done: true } );
530 } catch ( err ) {
531 // Otherwise disable the done button if maps object is populated
532 this.actions.setAbilities( { done: false } );
533 } finally {
534 if ( this.mapsGroup.items.length === 0 ) {
535 this.actions.setAbilities( { done: true } );
536 this.removeMapButton.setDisabled( true );
537 }
538 }
539 }
540 }
541 };
542
543 /**
544 * Handle click event for Add new map button
545 */
546 Dialog.prototype.onAddNewMapClick = function () {
547 // Add new text input in maps elements to prompt the map name
548 this.newMapNameInput.$element.show();
549 this.cancelAddMapButton.$element.show();
550 this.saveAddMapButton.$element.show();
551 this.addNewMapButton.$element.hide();
552 this.newMapNameInput.setValue( '' );
553 this.newMapNameInput.focus();
554 this.mapsGroup.selectItem( null );
555
556 // Text-area show "adding a new map.." message in templateMapsInput and disable the input.
557 this.templateMapsInput.setDisabled( true );
558 this.templateMapsInput.setValue( mw.msg( 'templatedata-modal-placeholder-add-new-map-input' ) );
559
560 // Disable the removing functionality for maps
561 this.removeMapButton.setDisabled( true );
562
563 // move the list panel down as add new map expanded
564 this.editMapsPanel.$element.addClass( 'tdg-templateDataDialog-addingNewMap' );
565 };
566
567 /**
568 * Handle clicking cancel button (for add new map panel)
569 *
570 * @param {OO.ui.OutlineOptionWidget} [highlightNext] item to be highlighted after adding a new map canceled/done
571 */
572 Dialog.prototype.onCancelAddingMap = function ( highlightNext ) {
573 // Remove the text-area input, cancel button, and show add new map button
574 this.newMapNameInput.$element.hide();
575 this.cancelAddMapButton.$element.hide();
576 this.saveAddMapButton.$element.hide();
577 this.addNewMapButton.$element.show();
578 // move the list panel up back as add new map shrank
579 this.editMapsPanel.$element.removeClass( 'tdg-templateDataDialog-addingNewMap' );
580 this.removeMapButton.setDisabled( false );
581 this.mapsGroup.selectItem( highlightNext || this.mapsGroup.findFirstSelectableItem() );
582 };
583
584 /**
585 * Handle clicking Enter event for promptMapName
586 *
587 * @param {jQuery.Event} response response from Enter action on promptMapName
588 */
589 Dialog.prototype.onEmbedNewMap = function ( response ) {
590 const mapNameValue = response ? response.target.value : this.newMapNameInput.getValue();
591 this.mapsCache = this.mapsCache || {};
592 // Create a new empty map in maps object
593 this.mapsCache[ mapNameValue ] = {};
594 const newlyAddedMap = new OO.ui.OutlineOptionWidget( {
595 label: mapNameValue
596 } );
597 // Add the new map item and select it
598 if ( mapNameValue.length !== 0 ) {
599 this.mapsGroup.addItems( [ newlyAddedMap ], 0 );
600 } else {
601 delete this.mapsCache[ mapNameValue ];
602 }
603 this.onCancelAddingMap( newlyAddedMap );
604 };
605
606 /**
607 * Handle click event for the remove button
608 */
609 Dialog.prototype.onMapItemRemove = function () {
610 const item = this.mapsGroup.findSelectedItem();
611 if ( item ) {
612 this.mapsGroup.removeItems( [ item ] );
613 // Remove the highlighted map from maps object
614 delete this.mapsCache[ item.label ];
615 }
616
617 // Highlight another item, or show the search panel if the maps group is now empty
618 this.onMapsGroupSelect();
619 };
620
621 /**
622 * Respond to a map group being selected
623 */
624 Dialog.prototype.onMapsGroupSelect = function () {
625 // Highlight new item
626 const item = this.mapsGroup.findSelectedItem();
627
628 if ( !item ) {
629 this.templateMapsInput.setDisabled( true );
630 this.templateMapsInput.setValue( '' );
631 } else {
632 // Cancel the process of adding a map, Cannot call onCancelAddingMap because these two functions
633 // cannot be called recursively
634 // Remove the text-area input, cancel button, and show add new map button
635 this.newMapNameInput.$element.hide();
636 this.cancelAddMapButton.$element.hide();
637 this.saveAddMapButton.$element.hide();
638 this.addNewMapButton.$element.show();
639 // move the list panel up back as add new map shrank
640 this.editMapsPanel.$element.removeClass( 'tdg-templateDataDialog-addingNewMap' );
641 this.removeMapButton.setDisabled( $.isEmptyObject( this.mapsCache ) );
642
643 this.mapsGroup.selectItem( item );
644 this.templateMapsInput.setDisabled( false );
645
646 // Scroll item into view in menu
647 OO.ui.Element.static.scrollIntoView( item.$element[ 0 ] );
648
649 // Populate the mapsContentPanel
650 this.mapsCache = this.mapsCache || {};
651 const currentMapInfo = this.mapsCache[ item.label ];
652 this.templateMapsInput.setValue( this.stringifyObject( currentMapInfo ) );
653 }
654 };
655
656 /**
657 * Stringify objects in the dialog with space of 4, mainly maps objects
658 *
659 * @param {Object} object maps object
660 * @return {string} serialized form
661 */
662 Dialog.prototype.stringifyObject = function ( object ) {
663 return JSON.stringify( object, null, 4 );
664 };
665
666 /**
667 * Respond to add language button click
668 */
669 Dialog.prototype.onLanguagePanelButton = function () {
670 this.switchPanels( this.languagePanel );
671 };
672
673 /**
674 * Respond to language select widget select event
675 *
676 * @param {OO.ui.OptionWidget} item Selected item
677 */
678 Dialog.prototype.onLanguageDropdownWidgetSelect = function ( item ) {
679 const language = item ? item.getData() : this.language;
680
681 // Change current language
682 if ( language !== this.language ) {
683 this.language = language;
684
685 // Update description label
686 this.templateDescriptionFieldset.setLabel( mw.msg( 'templatedata-modal-title-templatedesc', this.language ) );
687
688 // Update description value
689 this.descriptionInput.setValue( this.model.getTemplateDescription( language ) )
690 .$input.attr( { lang: mw.language.bcp47( language ), dir: 'auto' } );
691
692 // Update all param descriptions in the param select widget
693 this.repopulateParamSelectWidget();
694
695 // Update the parameter detail page
696 this.updateParamDetailsLanguage();
697
698 this.emit( 'change-language', this.language );
699 }
700 };
701
702 /**
703 * Handle choose events from the new language search widget
704 *
705 * @param {OO.ui.OptionWidget} item Chosen item
706 */
707 Dialog.prototype.onNewLanguageSearchResultsChoose = function ( item ) {
708 const newLanguage = item.getData().code;
709
710 if ( newLanguage ) {
711 if ( this.availableLanguages.indexOf( newLanguage ) === -1 ) {
712 // Add new language
713 this.availableLanguages.push( newLanguage );
714 const languageButton = new OO.ui.MenuOptionWidget( {
715 data: newLanguage,
716 label: $.uls.data.getAutonym( newLanguage )
717 } );
718 this.languageDropdownWidget.getMenu().addItems( [ languageButton ] );
719 }
720
721 // Select the new item
722 this.languageDropdownWidget.getMenu().selectItemByData( newLanguage );
723 }
724
725 // Go to the main panel
726 this.switchPanels();
727 };
728
729 /**
730 * Respond to edit maps button click
731 */
732 Dialog.prototype.onMapsPanelButton = function () {
733 const item = this.mapsGroup.findSelectedItem() || this.mapsGroup.findFirstSelectableItem();
734 this.switchPanels( this.editMapsPanel );
735 // Select first item
736 this.mapsGroup.selectItem( item );
737 };
738
739 /**
740 * Respond to add parameter button
741 */
742 Dialog.prototype.onAddParamButtonClick = function () {
743 if ( this.addParamButton.isDisabled() ) {
744 return;
745 }
746
747 const newParamKey = this.newParamInput.getValue().trim();
748 if ( this.model.isParamDeleted( newParamKey ) ) {
749 this.model.emptyParamData( newParamKey );
750 } else if ( !this.model.isParamExists( newParamKey ) ) {
751 this.model.addParam( newParamKey );
752 this.addParamToSelectWidget( newParamKey );
753 }
754 // Reset the input
755 this.newParamInput.setValue( '' );
756
757 // Go back to list
758 this.switchPanels();
759 };
760
761 /**
762 * Respond to choose event from the param select widget
763 *
764 * @param {OO.ui.OptionWidget} item Parameter item
765 */
766 Dialog.prototype.onParamSelectChoose = function ( item ) {
767 const paramKey = item.getData();
768
769 this.selectedParamKey = paramKey;
770
771 // The panel with the `propInputs` widgets must be made visible before changing their value.
772 // Otherwise the autosize feature of MultilineTextInputWidget doesn't work.
773 this.switchPanels( this.editParamPanel );
774 // Fill in parameter detail
775 this.getParameterDetails( paramKey );
776 };
777
778 /**
779 * Respond to choose event from the template format select widget
780 *
781 * @param {OO.ui.OptionWidget} item Format item
782 */
783 Dialog.prototype.onTemplateFormatSelectWidgetChoose = function ( item ) {
784 const format = item.getData(),
785 shortcuts = {
786 inline: '{{_|_=_}}',
787 block: '{{_\n| _ = _\n}}'
788 };
789 if ( format !== 'custom' ) {
790 this.model.setTemplateFormat( format );
791 this.templateFormatInputWidget.setDisabled( true );
792 if ( format !== null ) {
793 this.templateFormatInputWidget.setValue(
794 this.formatToDisplay( shortcuts[ format ] )
795 );
796 }
797 } else {
798 this.templateFormatInputWidget.setDisabled( false );
799 this.onTemplateFormatInputWidgetChange(
800 this.templateFormatInputWidget.getValue()
801 );
802 }
803 };
804
805 Dialog.prototype.formatToDisplay = function ( s ) {
806 // Use '↔' (\u21b5) as a fancy newline (which doesn't start a new line).
807 return s.replace( /\n/g, '\u21b5' );
808 };
809 Dialog.prototype.displayToFormat = function ( s ) {
810 // Allow user to type \n or \\n (literal backslash, n) for a new line.
811 return s.replace( /\n|\\n|\u21b5/g, '\n' );
812 };
813
814 /**
815 * Respond to change event from the template format input widget
816 *
817 * @param {string} value Input widget value
818 */
819 Dialog.prototype.onTemplateFormatInputWidgetChange = function ( value ) {
820 const item = this.templateFormatSelectWidget.findSelectedItem();
821 if ( item.getData() === 'custom' ) {
822 // Convert literal newlines or backslash-n to our fancy character
823 // replacement.
824 const normalized = this.formatToDisplay( this.displayToFormat( value ) );
825 if ( normalized !== value ) {
826 this.templateFormatInputWidget.setValue( normalized );
827 // Will recurse to actually set value in model.
828 } else {
829 this.model.setTemplateFormat( this.displayToFormat( value.trim() ) );
830 }
831 }
832 };
833
834 /**
835 * Respond to enter event from the template format input widget
836 */
837 Dialog.prototype.onTemplateFormatInputWidgetEnter = function () {
838 /* Synthesize a '\n' when enter is pressed. */
839 this.templateFormatInputWidget.insertContent( this.formatToDisplay( '\n' ) );
840 };
841
842 Dialog.prototype.onParamPropertyInputChange = function ( propName, value ) {
843 let $errors = $( [] );
844 const prop = Model.static.getAllProperties( true )[ propName ],
845 propInput = this.propInputs[ propName ];
846
847 if ( propName === 'type' ) {
848 const selected = propInput.getMenu().findSelectedItem();
849 value = selected ? selected.getData() : prop.default;
850 } else if ( prop.type === 'array' ) {
851 value = propInput.getValue();
852 }
853
854 if ( propName === 'type' ) {
855 this.toggleSuggestedValues( value );
856 }
857
858 if ( propName === 'name' ) {
859 const invalid = !value || prop.restrict.test( value );
860 const changed = value !== this.selectedParamKey;
861 if ( invalid ) {
862 $errors = $errors.add( $( '<p>' ).text( mw.msg( 'templatedata-modal-errormsg', '|', '=', '}}' ) ) );
863 } else if ( changed && this.model.getAllParamNames().indexOf( value ) !== -1 ) {
864 // We're changing the name. Make sure it doesn't conflict.
865 $errors = $errors.add( $( '<p>' ).text( mw.msg( 'templatedata-modal-errormsg-duplicate-name' ) ) );
866 }
867 }
868
869 propInput.$element.toggleClass( 'tdg-editscreen-input-error', !!$errors.length );
870
871 // Check if there is a dependent input to activate
872 const dependentField = prop.textValue;
873 if ( dependentField && this.propFieldLayout[ dependentField ] ) {
874 // The textValue property depends on this property
875 // toggle its view
876 this.propFieldLayout[ dependentField ].toggle( !!value );
877 this.propInputs[ dependentField ].setValue( this.model.getParamProperty( this.selectedParamKey, dependentField ) );
878 }
879
880 // Validate
881 // FIXME: Don't read model information from the DOM
882 // eslint-disable-next-line no-jquery/no-global-selector
883 const anyInputError = !!$( '.tdg-templateDataDialog-paramInput.tdg-editscreen-input-error' ).length;
884
885 // Disable the 'done' button if there are any errors in the inputs
886 this.actions.setAbilities( { done: !anyInputError } );
887 if ( $errors.length ) {
888 this.toggleNoticeMessage( 'edit', true, 'error', $errors );
889 } else {
890 this.toggleNoticeMessage( 'edit', false );
891 this.model.setParamProperty( this.selectedParamKey, propName, value, this.language );
892 }
893
894 // If we're changing the aliases and the name has an error, poke its change
895 // handler in case that error was because of a duplicate name with its own
896 // aliases.
897 // FIXME: Don't read model information from the DOM
898 // eslint-disable-next-line no-jquery/no-class-state
899 if ( propName === 'aliases' && this.propInputs.name.$element.hasClass( 'tdg-editscreen-input-error' ) ) {
900 this.onParamPropertyInputChange( 'name', this.propInputs.name.getValue() );
901 }
902
903 this.trackPropertyChange( propName );
904 };
905
906 Dialog.prototype.toggleSuggestedValues = function ( type ) {
907 const suggestedValuesAllowedTypes = [
908 'content',
909 'line',
910 'number',
911 'string',
912 'unbalanced-wikitext',
913 'unknown'
914 ];
915
916 // Don't show the suggested values field when the feature flag is
917 // disabled, or for inapplicable types.
918 this.propFieldLayout.suggestedvalues.toggle(
919 suggestedValuesAllowedTypes.indexOf( type ) !== -1
920 );
921 };
922
923 /**
924 * Set the parameter details in the detail panel.
925 *
926 * @param {string} paramKey
927 */
928 Dialog.prototype.getParameterDetails = function ( paramKey ) {
929 const paramData = this.model.getParamData( paramKey );
930 const allProps = Model.static.getAllProperties( true );
931
932 this.stopParameterInputTracking();
933
934 for ( const prop in this.propInputs ) {
935 this.changeParamPropertyInput( paramKey, prop, paramData[ prop ], this.language );
936 // Show/hide dependents
937 if ( allProps[ prop ].textValue ) {
938 this.propFieldLayout[ allProps[ prop ].textValue ].toggle( !!paramData[ prop ] );
939 }
940 }
941 // Update suggested values field visibility
942 this.toggleSuggestedValues( paramData.type || allProps.type.default );
943
944 let status;
945 // This accepts one of the three booleans only if the other two are false
946 if ( paramData.deprecated ) {
947 status = !paramData.required && !paramData.suggested && 'deprecated';
948 } else if ( paramData.required ) {
949 status = !paramData.deprecated && !paramData.suggested && 'required';
950 } else if ( paramData.suggested ) {
951 status = !paramData.deprecated && !paramData.required && 'suggested';
952 } else {
953 status = 'optional';
954 }
955 // Status is false at this point when more than one was set to true
956 this.propFieldLayout.status.toggle( status );
957 this.propFieldLayout.deprecated.toggle( !status );
958 this.propFieldLayout.required.toggle( !status );
959 this.propFieldLayout.suggested.toggle( !status );
960 if ( !status ) {
961 // No unambiguous status found, can't use the dropdown
962 this.propInputs.status.getMenu().disconnect( this );
963 } else {
964 this.changeParamPropertyInput( paramKey, 'status', status );
965 this.propInputs.status.getMenu().connect( this, {
966 choose: function ( item ) {
967 const selected = item.getData();
968 // Forward selection from the dropdown to the hidden checkboxes, these get saved
969 this.propInputs.deprecated.setSelected( selected === 'deprecated' );
970 this.propInputs.required.setSelected( selected === 'required' );
971 this.propInputs.suggested.setSelected( selected === 'suggested' );
972 }
973 } );
974 }
975
976 this.startParameterInputTracking( paramData );
977 };
978
979 Dialog.prototype.stopParameterInputTracking = function () {
980 this.paramPropertyChangeTracking = {};
981 };
982
983 /**
984 * Temporary metrics to understand how properties are edited, see T260343.
985 *
986 * @param {Object} paramValues parameter property values at dialog open time
987 */
988 Dialog.prototype.startParameterInputTracking = function ( paramValues ) {
989 this.paramPropertyChangeTracking = {};
990 for ( const prop in this.propInputs ) {
991 // Set to true, unless one of the exceptions applies.
992 this.paramPropertyChangeTracking[ prop ] = !(
993 // Setting type when we already have a specific type.
994 ( prop === 'type' && paramValues[ prop ] !== undefined && paramValues[ prop ] !== 'unknown' ) ||
995
996 // Setting priority but already required, suggested, or deprecated.
997 ( ( prop === 'required' || prop === 'suggested' || prop === 'deprecated' ) &&
998 ( paramValues.required || paramValues.suggested || paramValues.deprecated ) ) ||
999
1000 // Fields ignored by tracking.
1001 ( prop === 'name' || prop === 'aliases' || prop === 'autovalue' || prop === 'deprecatedValue' )
1002 );
1003 }
1004 };
1005
1006 Dialog.prototype.trackPropertyChange = function ( property ) {
1007 const eventKey = ( property === 'required' || property === 'suggested' || property === 'deprecated' ) ?
1008 'parameter-priority-change' : 'parameter-' + property + '-change';
1009
1010 if ( this.paramPropertyChangeTracking[ property ] ) {
1011 Metrics.logEvent( eventKey );
1012 }
1013 this.paramPropertyChangeTracking[ property ] = false;
1014
1015 // These properties form a conceptual group; suppress additional events.
1016 if ( property === 'required' || property === 'suggested' || property === 'deprecated' ) {
1017 this.paramPropertyChangeTracking.required =
1018 this.paramPropertyChangeTracking.suggested =
1019 this.paramPropertyChangeTracking.deprecated = false;
1020 }
1021 };
1022
1023 /**
1024 * Reset contents on reload
1025 */
1026 Dialog.prototype.reset = function () {
1027 this.language = null;
1028 this.availableLanguages = [];
1029 if ( this.paramSelect ) {
1030 this.paramSelect.clearItems();
1031 this.selectedParamKey = '';
1032 }
1033
1034 if ( this.languageDropdownWidget ) {
1035 this.languageDropdownWidget.getMenu().clearItems();
1036 }
1037 };
1038
1039 /**
1040 * Empty and repopulate the parameter select widget.
1041 */
1042 Dialog.prototype.repopulateParamSelectWidget = function () {
1043 if ( !this.isSetup ) {
1044 return;
1045 }
1046
1047 const paramList = this.model.getParams(),
1048 paramOrder = this.model.getTemplateParamOrder();
1049
1050 this.paramSelect.clearItems();
1051
1052 // Update all param descriptions in the param select widget
1053 for ( const i in paramOrder ) {
1054 const paramKey = paramList[ paramOrder[ i ] ];
1055 if ( paramKey && !paramKey.deleted ) {
1056 this.addParamToSelectWidget( paramOrder[ i ] );
1057 }
1058 }
1059
1060 // Check if there are potential parameters to add
1061 // from the template source code
1062 const missingParams = this.model.getMissingParams();
1063 this.paramImport
1064 .toggle( !!missingParams.length )
1065 .buildParamLabel( missingParams );
1066 };
1067
1068 /**
1069 * Change parameter property
1070 *
1071 * @param {string} paramKey Parameter key
1072 * @param {string} propName Property name
1073 * @param {Mixed} [value] Property value
1074 * @param {string} [lang] Language
1075 */
1076 Dialog.prototype.changeParamPropertyInput = function ( paramKey, propName, value, lang ) {
1077 const prop = Model.static.getAllProperties( true )[ propName ];
1078 let propInput = this.propInputs[ propName ];
1079
1080 switch ( prop.type ) {
1081 case 'select':
1082 propInput = propInput.getMenu();
1083 propInput.selectItem( propInput.findItemFromData( value || prop.default ) );
1084 break;
1085 case 'boolean':
1086 propInput.setSelected( !!value );
1087 break;
1088 case 'array':
1089 value = value || [];
1090 propInput.setValue( value.map(
1091 // TagMultiselectWidget accepts nothing but strings or objects with a .data property
1092 ( v ) => v && v.data ? v : String( v )
1093 ) );
1094 break;
1095 default:
1096 if ( typeof value === 'object' ) {
1097 value = value[ lang || this.language ];
1098 }
1099 propInput.setValue( value || '' );
1100 }
1101 };
1102
1103 /**
1104 * Add parameter to the list
1105 *
1106 * @param {string} paramKey Parameter key in the model
1107 */
1108 Dialog.prototype.addParamToSelectWidget = function ( paramKey ) {
1109 const data = this.model.getParamData( paramKey );
1110 this.paramSelect.addItems( [ new ParamWidget( {
1111 key: paramKey,
1112 label: this.model.getParamValue( paramKey, 'label', this.language ),
1113 aliases: data.aliases,
1114 description: this.model.getParamValue( paramKey, 'description', this.language )
1115 } )
1116 // Forward keyboard-triggered events from the OptionWidget to the SelectWidget
1117 .connect( this.paramSelect, { choose: [ 'emit', 'choose' ] } )
1118 ] );
1119 };
1120
1121 /**
1122 * Create the information page about individual parameters
1123 *
1124 * @return {jQuery} Editable details page for the parameter
1125 */
1126 Dialog.prototype.createParamDetails = function () {
1127 const paramProperties = Model.static.getAllProperties( true );
1128
1129 // Fieldset
1130 const paramFieldset = new OO.ui.FieldsetLayout();
1131
1132 for ( const propName in paramProperties ) {
1133 const prop = paramProperties[ propName ];
1134 const config = {};
1135 let propInput;
1136 // Create the property inputs
1137 switch ( prop.type ) {
1138 case 'select': {
1139 propInput = new OO.ui.DropdownWidget( config );
1140 const items = [];
1141 for ( const i in prop.children ) {
1142 items.push( new OO.ui.MenuOptionWidget( {
1143 data: prop.children[ i ],
1144
1145 // The following messages are used here:
1146 // * templatedata-doc-param-status-optional
1147 // * templatedata-doc-param-status-deprecated
1148 // * templatedata-doc-param-status-required
1149 // * templatedata-doc-param-status-suggested
1150 // * templatedata-doc-param-type-boolean, templatedata-doc-param-type-content,
1151 // * templatedata-doc-param-type-date, templatedata-doc-param-type-line,
1152 // * templatedata-doc-param-type-number, templatedata-doc-param-type-string,
1153 // * templatedata-doc-param-type-unbalanced-wikitext, templatedata-doc-param-type-unknown,
1154 // * templatedata-doc-param-type-url, templatedata-doc-param-type-wiki-file-name,
1155 // * templatedata-doc-param-type-wiki-page-name, templatedata-doc-param-type-wiki-template-name,
1156 // * templatedata-doc-param-type-wiki-user-name
1157 label: mw.msg( 'templatedata-doc-param-' + propName + '-' + prop.children[ i ] )
1158 } ) );
1159 }
1160 propInput.getMenu().addItems( items );
1161 break;
1162 }
1163 case 'boolean':
1164 propInput = new OO.ui.CheckboxInputWidget( config );
1165 break;
1166 case 'array':
1167 config.allowArbitrary = true;
1168 config.placeholder = mw.msg( 'templatedata-modal-placeholder-multiselect' );
1169 propInput = new OO.ui.TagMultiselectWidget( config );
1170 break;
1171 default:
1172 config.autosize = true;
1173 if ( !prop.multiline ) {
1174 config.rows = 1;
1175 config.allowLinebreaks = false;
1176 }
1177 propInput = new OO.ui.MultilineTextInputWidget( config );
1178 break;
1179 }
1180
1181 this.propInputs[ propName ] = propInput;
1182
1183 // The following classes are used here:
1184 // * tdg-templateDataDialog-paramInput tdg-templateDataDialog-paramList-aliases
1185 // * tdg-templateDataDialog-paramInput tdg-templateDataDialog-paramList-autovalue
1186 // * tdg-templateDataDialog-paramInput tdg-templateDataDialog-paramList-default
1187 // * tdg-templateDataDialog-paramInput tdg-templateDataDialog-paramList-deprecated
1188 // * tdg-templateDataDialog-paramInput tdg-templateDataDialog-paramList-deprecatedValue
1189 // * tdg-templateDataDialog-paramInput tdg-templateDataDialog-paramList-description
1190 // * tdg-templateDataDialog-paramInput tdg-templateDataDialog-paramList-example
1191 // * tdg-templateDataDialog-paramInput tdg-templateDataDialog-paramList-label
1192 // * tdg-templateDataDialog-paramInput tdg-templateDataDialog-paramList-name
1193 // * tdg-templateDataDialog-paramInput tdg-templateDataDialog-paramList-required
1194 // * tdg-templateDataDialog-paramInput tdg-templateDataDialog-paramList-suggested
1195 // * tdg-templateDataDialog-paramInput tdg-templateDataDialog-paramList-suggestedvalues
1196 // * tdg-templateDataDialog-paramInput tdg-templateDataDialog-paramList-type
1197 propInput.$element
1198 .addClass( 'tdg-templateDataDialog-paramInput tdg-templateDataDialog-paramList-' + propName );
1199
1200 this.propFieldLayout[ propName ] = new OO.ui.FieldLayout( propInput, {
1201 align: 'left',
1202 // The following messages are used here:
1203 // * templatedata-modal-table-param-aliases
1204 // * templatedata-modal-table-param-autovalue
1205 // * templatedata-modal-table-param-default
1206 // * templatedata-modal-table-param-deprecated
1207 // * templatedata-modal-table-param-deprecatedValue
1208 // * templatedata-modal-table-param-description
1209 // * templatedata-modal-table-param-example
1210 // * templatedata-modal-table-param-label
1211 // * templatedata-modal-table-param-name
1212 // * templatedata-modal-table-param-required
1213 // * templatedata-modal-table-param-suggested
1214 // * templatedata-modal-table-param-suggestedvalues
1215 // * templatedata-modal-table-param-type
1216 label: mw.msg( 'templatedata-modal-table-param-' + propName )
1217 } );
1218
1219 // Event
1220 if ( propInput instanceof OO.ui.DropdownWidget ) {
1221 propInput.getMenu().connect( this, { choose: [ 'onParamPropertyInputChange', propName ] } );
1222 } else {
1223 propInput.connect( this, { change: [ 'onParamPropertyInputChange', propName ] } );
1224 }
1225 // Append to parameter section
1226 paramFieldset.$element.append( this.propFieldLayout[ propName ].$element );
1227 }
1228 return paramFieldset.$element;
1229 };
1230
1231 /**
1232 * Update the labels for parameter property inputs that include language, so
1233 * they show the currently used language.
1234 */
1235 Dialog.prototype.updateParamDetailsLanguage = function () {
1236 const languageProps = Model.static.getPropertiesWithLanguage();
1237
1238 for ( let i = 0; i < languageProps.length; i++ ) {
1239 const prop = languageProps[ i ];
1240 // The following messages are used here:
1241 // * templatedata-modal-table-param-aliases
1242 // * templatedata-modal-table-param-autovalue
1243 // * templatedata-modal-table-param-default
1244 // * templatedata-modal-table-param-deprecated
1245 // * templatedata-modal-table-param-deprecatedValue
1246 // * templatedata-modal-table-param-description
1247 // * templatedata-modal-table-param-example
1248 // * templatedata-modal-table-param-label
1249 // * templatedata-modal-table-param-name
1250 // * templatedata-modal-table-param-required
1251 // * templatedata-modal-table-param-suggested
1252 // * templatedata-modal-table-param-suggestedvalues
1253 // * templatedata-modal-table-param-type
1254 const label = mw.msg( 'templatedata-modal-table-param-' + prop, this.language );
1255 this.propFieldLayout[ prop ].setLabel( label );
1256 this.propInputs[ prop ]
1257 .$input.attr( { lang: mw.language.bcp47( this.language ), dir: 'auto' } );
1258 }
1259 };
1260
1261 /**
1262 * Override getBodyHeight to create a tall dialog relative to the screen.
1263 *
1264 * @return {number} Body height
1265 */
1266 Dialog.prototype.getBodyHeight = function () {
1267 return window.innerHeight - 200;
1268 };
1269
1270 /**
1271 * Show or hide the notice message in the dialog with a set message.
1272 *
1273 * Hides all other notices messages when called, not just the one specified.
1274 *
1275 * @param {string} [type='list'] Which notice label to show: 'list', 'edit' or 'global'
1276 * @param {boolean} [isShowing=false] Show or hide the message
1277 * @param {string} [noticeMessageType='notice'] Message type: 'notice', 'error', 'warning', 'success'
1278 * @param {jQuery|string|OO.ui.HtmlSnippet|Function|null} [noticeMessageLabel] The message to display
1279 */
1280 Dialog.prototype.toggleNoticeMessage = function ( type, isShowing, noticeMessageType, noticeMessageLabel ) {
1281 // Hide all
1282 this.noticeMessage.toggle( false );
1283 this.paramEditNoticeMessage.toggle( false );
1284 this.paramListNoticeMessage.toggle( false );
1285
1286 if ( noticeMessageLabel ) {
1287 // See which error to display
1288 let noticeReference;
1289 if ( type === 'global' ) {
1290 noticeReference = this.noticeMessage;
1291 } else if ( type === 'edit' ) {
1292 noticeReference = this.paramEditNoticeMessage;
1293 } else {
1294 noticeReference = this.paramListNoticeMessage;
1295 }
1296 // FIXME: Don't read model information from the DOM
1297 // eslint-disable-next-line no-jquery/no-sizzle
1298 isShowing = isShowing || !noticeReference.$element.is( ':visible' );
1299
1300 noticeReference.setLabel( noticeMessageLabel );
1301 noticeReference.setType( noticeMessageType );
1302 noticeReference.toggle( isShowing );
1303 }
1304 };
1305
1306 /**
1307 * Import parameters from the source code.
1308 */
1309 Dialog.prototype.importParametersFromTemplateCode = function () {
1310 const response = this.model.importSourceCodeParameters();
1311 // Repopulate the list
1312 this.repopulateParamSelectWidget();
1313
1314 let $message = $( [] ),
1315 state = 'success';
1316 if ( response.imported.length === 0 ) {
1317 $message = $( '<p>' ).text( mw.msg( 'templatedata-modal-errormsg-import-noparams' ) );
1318 state = 'error';
1319 } else {
1320 $message = $message.add(
1321 $( '<p>' ).text(
1322 mw.msg( 'templatedata-modal-notice-import-numparams', response.imported.length, response.imported.join( mw.msg( 'comma-separator' ) ) )
1323 )
1324 );
1325 }
1326
1327 this.toggleNoticeMessage( 'list', true, state, $message );
1328 };
1329
1330 /**
1331 * Get a process for setting up a window for use.
1332 *
1333 * @param {Object} data Dialog opening data
1334 * @param {Model} data.model
1335 * @param {OO.ui.Element} data.editNoticeMessage
1336 * @return {OO.ui.Process} Setup process
1337 */
1338 Dialog.prototype.getSetupProcess = function ( data ) {
1339 return Dialog.super.prototype.getSetupProcess.call( this, data )
1340 .next( () => {
1341 this.isSetup = false;
1342
1343 this.reset();
1344
1345 // The dialog must be supplied with a reference to a model
1346 this.model = data.model;
1347 this.modified = false;
1348
1349 // Hide the panels and display a spinner
1350 this.$spinner.show();
1351 this.panels.$element.hide();
1352 this.toggleNoticeMessage( 'global', false );
1353 this.toggleNoticeMessage( 'list', false );
1354
1355 // Start with parameter list
1356 this.switchPanels();
1357
1358 // Events
1359 this.model.connect( this, {
1360 'change-description': 'onModelChangeDescription',
1361 'change-map': 'onModelChangeMapInfo',
1362 'change-paramOrder': 'onModelChangeParamOrder',
1363 'change-property': 'onModelChangeProperty',
1364 change: 'onModelChange'
1365 } );
1366
1367 // Setup the dialog
1368 this.setupDetailsFromModel();
1369
1370 this.newLanguageSearch.addResults();
1371
1372 // Bring in the editNoticeMessage from the main page
1373 this.listParamsPanel.$element.prepend(
1374 data.editNoticeMessage.$element
1375 );
1376
1377 this.availableLanguages = this.model.getExistingLanguageCodes().slice();
1378 const defaultLanguage = this.model.getDefaultLanguage();
1379 if ( this.availableLanguages.indexOf( defaultLanguage ) === -1 ) {
1380 this.availableLanguages.unshift( defaultLanguage );
1381 }
1382 const items = this.availableLanguages.map( ( lang ) => new OO.ui.MenuOptionWidget( {
1383 data: lang,
1384 label: $.uls.data.getAutonym( lang )
1385 } ) );
1386 this.languageDropdownWidget.getMenu()
1387 .addItems( items )
1388 // Trigger the initial language choice
1389 .selectItemByData( defaultLanguage );
1390
1391 this.isSetup = true;
1392
1393 this.repopulateParamSelectWidget();
1394
1395 // Show the panel
1396 this.$spinner.hide();
1397 this.panels.$element.show();
1398
1399 this.actions.setAbilities( { apply: false } );
1400 } );
1401 };
1402
1403 /**
1404 * Set up the list of parameters from the model. This should happen
1405 * after initialization of the model.
1406 */
1407 Dialog.prototype.setupDetailsFromModel = function () {
1408 // Set up description
1409 this.descriptionInput.setValue( this.model.getTemplateDescription( this.language ) );
1410
1411 // set up maps
1412 this.populateMapsItems( this.model.getMapInfo() );
1413 this.mapsCache = OO.copy( this.model.getMapInfo() );
1414 this.onMapsGroupSelect();
1415 if ( this.model.getMapInfo() !== undefined ) {
1416 const firstMapItem = Object.keys( this.model.getMapInfo() )[ 0 ];
1417 this.templateMapsInput.setValue( this.stringifyObject( this.model.getMapInfo()[ firstMapItem ] ) );
1418 } else {
1419 this.templateMapsInput.setValue( '' );
1420 this.templateMapsInput.setDisabled( true );
1421 }
1422
1423 // Set up format
1424 const format = this.model.getTemplateFormat();
1425 if ( format === 'inline' || format === 'block' || format === null ) {
1426 this.templateFormatSelectWidget.selectItemByData( format );
1427 this.templateFormatInputWidget.setDisabled( true );
1428 } else {
1429 this.templateFormatSelectWidget.selectItemByData( 'custom' );
1430 this.templateFormatInputWidget.setValue( this.formatToDisplay( format ) );
1431 this.templateFormatInputWidget.setDisabled( false );
1432 }
1433
1434 // Repopulate the parameter list
1435 this.repopulateParamSelectWidget();
1436
1437 Metrics.logEvent( this.model.getOriginalTemplateDataObject() ?
1438 'dialog-open-edit' : 'dialog-open-create' );
1439 };
1440
1441 /**
1442 * Switch between stack layout panels
1443 *
1444 * @param {OO.ui.PanelLayout} [panel] Panel to switch to, defaults to the first panel
1445 */
1446 Dialog.prototype.switchPanels = function ( panel ) {
1447 panel = panel || this.listParamsPanel;
1448
1449 this.panels.setItem( panel );
1450 this.listParamsPanel.$element.toggle( panel === this.listParamsPanel );
1451 this.editParamPanel.$element.toggle( panel === this.editParamPanel );
1452 this.languagePanel.$element.toggle( panel === this.languagePanel );
1453 this.addParamPanel.$element.toggle( panel === this.addParamPanel );
1454 this.editMapsPanel.$element.toggle( panel === this.editMapsPanel );
1455
1456 switch ( panel ) {
1457 case this.listParamsPanel:
1458 this.actions.setMode( 'list' );
1459 // Reset message
1460 this.toggleNoticeMessage( 'list', false );
1461 // Deselect parameter
1462 this.paramSelect.selectItem( null );
1463 // Repopulate the list to account for any changes
1464 if ( this.model ) {
1465 this.repopulateParamSelectWidget();
1466 }
1467 break;
1468 case this.editParamPanel:
1469 this.actions.setMode( 'edit' );
1470 // Deselect parameter
1471 this.paramSelect.selectItem( null );
1472 this.editParamPanel.focus();
1473 break;
1474 case this.addParamPanel:
1475 this.actions.setMode( 'add' );
1476 this.newParamInput.focus();
1477 break;
1478 case this.editMapsPanel:
1479 this.actions.setMode( 'maps' );
1480 this.templateMapsInput.adjustSize( true ).focus();
1481 break;
1482 case this.languagePanel:
1483 this.actions.setMode( 'language' );
1484 this.newLanguageSearch.query.focus();
1485 break;
1486 }
1487 };
1488
1489 /**
1490 * Get a process for taking action.
1491 *
1492 * @param {string} [action] Symbolic name of action
1493 * @return {OO.ui.Process} Action process
1494 */
1495 Dialog.prototype.getActionProcess = function ( action ) {
1496 if ( action === 'add' ) {
1497 return new OO.ui.Process( () => {
1498 this.switchPanels( this.addParamPanel );
1499 } );
1500 }
1501 if ( action === 'done' ) {
1502 return new OO.ui.Process( () => {
1503 // setMapInfo with the value and keep the done button active
1504 this.model.setMapInfo( this.mapsCache );
1505 this.model.originalMaps = OO.copy( this.mapsCache );
1506 this.switchPanels();
1507 } );
1508 }
1509 if ( action === 'back' ) {
1510 return new OO.ui.Process( () => {
1511 this.switchPanels();
1512 } );
1513 }
1514 if ( action === 'maps' ) {
1515 return new OO.ui.Process( () => {
1516 this.switchPanels( this.editMapsPanel );
1517 } );
1518 }
1519 if ( action === 'cancel' ) {
1520 return new OO.ui.Process( () => {
1521 this.mapsCache = OO.copy( this.model.getOriginalMapsInfo() );
1522 this.model.restoreOriginalMaps();
1523 this.populateMapsItems( this.mapsCache );
1524 this.onCancelAddingMap();
1525 this.switchPanels();
1526 } );
1527 }
1528 if ( action === 'delete' ) {
1529 return new OO.ui.Process( () => {
1530 this.model.deleteParam( this.selectedParamKey );
1531 this.switchPanels();
1532 } );
1533 }
1534 if ( action === 'apply' ) {
1535 return new OO.ui.Process( () => {
1536 Metrics.logEvent( this.model.getOriginalTemplateDataObject() ?
1537 'save-page-edit' : 'save-page-create' );
1538
1539 this.emit( 'apply', this.model.outputTemplateData() );
1540 this.close( { action: action } );
1541 } );
1542 }
1543 if ( !action && this.modified ) {
1544 return new OO.ui.Process(
1545 () => OO.ui.confirm( mw.msg( 'templatedata-modal-confirmcancel' ) )
1546 .then( ( result ) => {
1547 if ( result ) {
1548 this.close();
1549 } else {
1550 return $.Deferred().resolve().promise();
1551 }
1552 } )
1553 );
1554 }
1555 // Fallback to parent handler
1556 return Dialog.super.prototype.getActionProcess.call( this, action );
1557 };
1558
1559 module.exports = Dialog;