Debian Codegraph @

extensions/VisualEditor/modules/ve-mw/ui/dialogs/ve.ui.MWTemplateDialog.js

raw symbols SCIP
1 /*!
2 * VisualEditor user interface MWTemplateDialog class.
3 *
4 * @copyright See AUTHORS.txt
5 * @license The MIT License (MIT); see LICENSE.txt
6 */
7
8 /**
9 * Abstract base class for dialogs that allow to insert and edit MediaWiki transclusions, i.e. a
10 * sequence of one or more template invocations that strictly belong to each other (e.g. because
11 * they are unbalanced), possibly mixed with raw wikitext snippets. Currently used for:
12 * - {@see ve.ui.MWTransclusionDialog} for arbitrary transclusions. Registered via the name
13 * "transclusion".
14 * - {@see ve.ui.MWCitationDialog} in the Cite extension for the predefined citation types from
15 * [[MediaWiki:visualeditor-cite-tool-definition.json]]. These are strictly limited to a single
16 * template invocation. Registered via the name "cite".
17 *
18 * @class
19 * @abstract
20 * @extends ve.ui.NodeDialog
21 *
22 * @constructor
23 * @param {Object} [config] Configuration options
24 * @property {ve.dm.MWTransclusionModel|null} transclusionModel
25 * @property {ve.ui.MWTransclusionOutlineWidget} sidebar
26 * @property {boolean} [canGoBack=false]
27 */
28 ve.ui.MWTemplateDialog = function VeUiMWTemplateDialog( config ) {
29 // Parent constructor
30 ve.ui.MWTemplateDialog.super.call( this, config );
31
32 // Properties
33 this.transclusionModel = null;
34 this.loaded = false;
35 this.altered = false;
36 this.canGoBack = false;
37 this.preventReselection = false;
38
39 this.confirmDialogs = new ve.ui.WindowManager( { factory: ve.ui.windowFactory, isolate: true } );
40 $( OO.ui.getTeleportTarget() ).append( this.confirmDialogs.$element );
41 };
42
43 /* Inheritance */
44
45 OO.inheritClass( ve.ui.MWTemplateDialog, ve.ui.NodeDialog );
46
47 /* Static Properties */
48
49 ve.ui.MWTemplateDialog.static.modelClasses = [ ve.dm.MWTransclusionNode ];
50
51 /**
52 * Configuration for the {@see ve.ui.MWTwoPaneTransclusionDialogLayout} used in this dialog.
53 *
54 * @static
55 * @property {Object}
56 * @inheritable
57 */
58 ve.ui.MWTemplateDialog.static.bookletLayoutConfig = {};
59
60 /* Methods */
61
62 /**
63 * @inheritdoc
64 */
65 ve.ui.MWTemplateDialog.prototype.getReadyProcess = function ( data ) {
66 return ve.ui.MWTemplateDialog.super.prototype.getReadyProcess.call( this, data )
67 .next( () => {
68 if ( this.transclusionModel.isEmpty() ) {
69 // Focus the template placeholder input field.
70 this.bookletLayout.focus();
71 }
72
73 this.bookletLayout.getPagesOrdered().forEach( ( page ) => {
74 if ( page instanceof ve.ui.MWParameterPage ) {
75 page.updateSize();
76 }
77 } );
78 } );
79 };
80
81 /**
82 * Update dialog actions whenever the content changes.
83 *
84 * @private
85 */
86 ve.ui.MWTemplateDialog.prototype.touch = function () {
87 if ( this.loaded ) {
88 this.altered = true;
89 this.setApplicableStatus();
90 }
91 };
92
93 /**
94 * Handle parts being replaced.
95 *
96 * @protected
97 * @param {ve.dm.MWTransclusionPartModel|null} removed Removed part
98 * @param {ve.dm.MWTransclusionPartModel|null} added Added part
99 */
100 ve.ui.MWTemplateDialog.prototype.onReplacePart = function ( removed, added ) {
101 const removePages = [];
102
103 if ( removed ) {
104 // Remove parameter pages of removed templates
105 if ( removed instanceof ve.dm.MWTemplateModel ) {
106 const params = removed.getParameters();
107 for ( const name in params ) {
108 removePages.push( params[ name ].getId() );
109 }
110 removed.disconnect( this );
111 }
112 removePages.push( removed.getId() );
113 this.bookletLayout.removePages( removePages );
114 }
115
116 if ( added ) {
117 const page = this.getPageFromPart( added );
118 if ( page ) {
119 let reselect;
120
121 this.bookletLayout.addPages( [ page ], this.transclusionModel.getIndex( added ) );
122 if ( removed ) {
123 // When we're replacing a part, it can only be a template placeholder
124 // becoming an actual template. Focus this new template.
125 reselect = added.getId();
126 }
127
128 if ( added instanceof ve.dm.MWTemplateModel ) {
129 // Prevent selection changes while parameters are added
130 this.preventReselection = true;
131
132 // Add existing params to templates (the template might be being moved)
133 const names = added.getOrderedParameterNames();
134 for ( let i = 0; i < names.length; i++ ) {
135 this.onAddParameter( added.getParameter( names[ i ] ) );
136 }
137 added.connect( this, { add: 'onAddParameter', remove: 'onRemoveParameter' } );
138
139 this.preventReselection = false;
140
141 if ( this.loaded ) {
142 if ( reselect ) {
143 this.bookletLayout.focusPart( reselect );
144 }
145 }
146
147 const documentedParameters = added.getSpec().getDocumentedParameterOrder(),
148 undocumentedParameters = added.getSpec().getUndocumentedParameterNames();
149
150 if ( !documentedParameters.length || undocumentedParameters.length ) {
151 page.addPlaceholderParameter();
152 }
153 }
154 }
155 }
156
157 if ( added || removed ) {
158 this.touch();
159 }
160 this.updateTitle();
161 };
162
163 /**
164 * Handle add param events.
165 *
166 * @private
167 * @param {ve.dm.MWParameterModel} param Added param
168 */
169 ve.ui.MWTemplateDialog.prototype.onAddParameter = function ( param ) {
170 let page;
171
172 if ( param.getName() ) {
173 page = new ve.ui.MWParameterPage( param, {
174 $overlay: this.$overlay, readOnly: this.isReadOnly()
175 } )
176 .connect( this, {
177 hasValueChange: 'onHasValueChange'
178 } );
179 } else {
180 // Create parameter placeholder.
181 page = new ve.ui.MWAddParameterPage( param, param.getId(), {
182 $overlay: this.$overlay
183 } )
184 .connect( this, {
185 templateParameterAdded: this.bookletLayout.focusPart.bind( this.bookletLayout )
186 } );
187 }
188 this.bookletLayout.addPages( [ page ], this.transclusionModel.getIndex( param ) );
189 if ( this.loaded ) {
190 this.touch();
191
192 if ( page instanceof ve.ui.MWParameterPage ) {
193 page.updateSize();
194 }
195 }
196 };
197
198 /**
199 * Handle remove param events.
200 *
201 * @private
202 * @param {ve.dm.MWParameterModel} param Removed param
203 */
204 ve.ui.MWTemplateDialog.prototype.onRemoveParameter = function ( param ) {
205 this.bookletLayout.removePages( [ param.getId() ] );
206
207 this.touch();
208 };
209
210 /**
211 * Sets transclusion applicable status
212 *
213 * If the transclusion is empty or only contains a placeholder it will not be insertable.
214 * If the transclusion only contains a placeholder it will not be editable.
215 *
216 * @private
217 */
218 ve.ui.MWTemplateDialog.prototype.setApplicableStatus = function () {
219 const canSave = !this.transclusionModel.isEmpty();
220 this.actions.setAbilities( { done: canSave && this.altered } );
221 };
222
223 /**
224 * @inheritdoc
225 */
226 ve.ui.MWTemplateDialog.prototype.getBodyHeight = function () {
227 return 400;
228 };
229
230 /**
231 * Get a page for a transclusion part.
232 *
233 * @protected
234 * @param {ve.dm.MWTransclusionModel} part Part to get page for
235 * @return {OO.ui.PageLayout|null} Page for part, null if no matching page could be found
236 */
237 ve.ui.MWTemplateDialog.prototype.getPageFromPart = function ( part ) {
238 if ( part instanceof ve.dm.MWTemplateModel ) {
239 return new ve.ui.MWTemplatePage( part, part.getId(), { $overlay: this.$overlay, isReadOnly: this.isReadOnly() } );
240 } else if ( part instanceof ve.dm.MWTemplatePlaceholderModel ) {
241 return new ve.ui.MWTemplatePlaceholderPage(
242 part,
243 part.getId(),
244 { $overlay: this.$overlay }
245 );
246 }
247 return null;
248 };
249
250 /**
251 * @inheritdoc
252 */
253 ve.ui.MWTemplateDialog.prototype.getSelectedNode = function ( data ) {
254 const selectedNode = ve.ui.MWTemplateDialog.super.prototype.getSelectedNode.call( this );
255
256 // Data initialization
257 data = data || {};
258
259 // Require template to match if specified
260 if ( selectedNode && data.template && !selectedNode.isSingleTemplate( data.template ) ) {
261 return null;
262 }
263
264 return selectedNode;
265 };
266
267 /**
268 * Update the dialog title.
269 *
270 * @protected
271 */
272 ve.ui.MWTemplateDialog.prototype.updateTitle = function () {
273 let title = ve.msg( 'visualeditor-dialog-transclusion-loading' );
274
275 if ( this.transclusionModel.isSingleTemplate() ) {
276 const part = this.transclusionModel.getParts()[ 0 ];
277 if ( part instanceof ve.dm.MWTemplateModel ) {
278 title = ve.msg(
279 this.getMode() === 'insert' ?
280 'visualeditor-dialog-transclusion-title-insert-known-template' :
281 'visualeditor-dialog-transclusion-title-edit-known-template',
282 part.getSpec().getLabel()
283 );
284 } else {
285 title = ve.msg( 'visualeditor-dialog-transclusion-title-insert-template' );
286 }
287 }
288 this.title.setLabel( title );
289 };
290
291 /**
292 * @inheritdoc
293 */
294 ve.ui.MWTemplateDialog.prototype.initialize = function () {
295 // Parent method
296 ve.ui.MWTemplateDialog.super.prototype.initialize.call( this );
297
298 // Properties
299 this.bookletLayout = new ve.ui.MWTwoPaneTransclusionDialogLayout( this.constructor.static.bookletLayoutConfig );
300 // TODO: Remove once all references are gone.
301 this.sidebar = this.bookletLayout.sidebar;
302
303 // Initialization
304 this.$content.addClass( 've-ui-mwTemplateDialog' );
305 // bookletLayout is appended after the form has been built in getSetupProcess for performance
306 };
307
308 /**
309 * If the user has left blank required parameters, confirm that they actually want to do this.
310 * If no required parameters were left blank, or if they were but the user decided to go ahead
311 * anyway, the returned deferred will be resolved.
312 * Otherwise, the returned deferred will be rejected.
313 *
314 * @private
315 * @return {jQuery.Deferred}
316 */
317 ve.ui.MWTemplateDialog.prototype.checkRequiredParameters = function () {
318 const blankRequired = [],
319 deferred = ve.createDeferred();
320
321 this.bookletLayout.stackLayout.getItems().forEach( ( page ) => {
322 if ( !( page instanceof ve.ui.MWParameterPage ) ) {
323 return;
324 }
325 if ( page.parameter.isRequired() && !page.valueInput.getValue() ) {
326 blankRequired.push( mw.msg(
327 'quotation-marks',
328 page.parameter.template.getSpec().getParameterLabel( page.parameter.getName() )
329 ) );
330 }
331 } );
332 if ( blankRequired.length ) {
333 this.confirmDialogs.openWindow( 'requiredparamblankconfirm', {
334 message: mw.msg(
335 'visualeditor-dialog-transclusion-required-parameter-is-blank',
336 mw.language.listToText( blankRequired ),
337 blankRequired.length
338 ),
339 title: mw.msg(
340 'visualeditor-dialog-transclusion-required-parameter-dialog-title',
341 blankRequired.length
342 )
343 } ).closed.then( ( data ) => {
344 if ( data && data.action === 'ok' ) {
345 deferred.resolve();
346 } else {
347 deferred.reject();
348 }
349 } );
350 } else {
351 deferred.resolve();
352 }
353 return deferred.promise();
354 };
355
356 /**
357 * @inheritdoc
358 */
359 ve.ui.MWTemplateDialog.prototype.getActionProcess = function ( action ) {
360 if ( action === 'done' ) {
361 return new OO.ui.Process( () => {
362 const deferred = ve.createDeferred();
363 this.checkRequiredParameters().done( () => {
364 const surfaceModel = this.getFragment().getSurface(),
365 obj = this.transclusionModel.getPlainObject();
366
367 this.pushPending();
368
369 let modelPromise = ve.createDeferred().resolve().promise();
370 if ( this.selectedNode instanceof ve.dm.MWTransclusionNode ) {
371 this.transclusionModel.updateTransclusionNode( surfaceModel, this.selectedNode );
372 // TODO: updating the node could result in the inline/block state change
373 } else if ( obj !== null ) {
374 // Collapse returns a new fragment, so update this.fragment
375 this.fragment = this.getFragment().collapseToEnd();
376 modelPromise = this.transclusionModel.insertTransclusionNode( this.getFragment() );
377 }
378
379 // TODO tracking will only be implemented temporarily to answer questions on
380 // template usage for the Technical Wishes topic area see T258917
381 const templateEvent = {
382 action: 'save',
383 // eslint-disable-next-line camelcase
384 template_names: []
385 };
386 const editCountBucket = mw.config.get( 'wgUserEditCountBucket' );
387 if ( editCountBucket !== null ) {
388 // eslint-disable-next-line camelcase
389 templateEvent.user_edit_count_bucket = editCountBucket;
390 }
391 const parts = this.transclusionModel.getParts();
392 for ( let i = 0; i < parts.length; i++ ) {
393 // Only {@see ve.dm.MWTemplateModel} have a title
394 const title = parts[ i ].getTitle && parts[ i ].getTitle();
395 if ( title ) {
396 templateEvent.template_names.push( title );
397 }
398 }
399 mw.track( 'event.VisualEditorTemplateDialogUse', templateEvent );
400
401 return modelPromise.then( () => {
402 this.close( { action: action } ).closed.always( this.popPending.bind( this ) );
403 } );
404 } ).always( deferred.resolve );
405
406 return deferred;
407 } );
408 }
409
410 return ve.ui.MWTemplateDialog.super.prototype.getActionProcess.call( this, action );
411 };
412
413 /**
414 * @inheritdoc
415 */
416 ve.ui.MWTemplateDialog.prototype.getSetupProcess = function ( data ) {
417 data = data || {};
418 return ve.ui.MWTemplateDialog.super.prototype.getSetupProcess.call( this, data )
419 .next( () => {
420 let promise;
421
422 // Properties
423 this.loaded = false;
424 this.altered = false;
425 this.transclusionModel = new ve.dm.MWTransclusionModel( this.getFragment().getDocument() );
426
427 // Events
428 this.transclusionModel.connect( this, {
429 replace: 'onReplacePart',
430 change: 'touch'
431 } );
432
433 // Detach the form while building for performance
434 this.bookletLayout.$element.detach();
435
436 this.transclusionModel.connect( this.bookletLayout, { replace: 'onReplacePart' } );
437
438 // Initialization
439 if ( !this.selectedNode ) {
440 if ( data.template ) {
441 // The template name is from MediaWiki:Visualeditor-cite-tool-definition.json,
442 // passed via a ve.ui.Command, which triggers a ve.ui.MWCitationAction, which
443 // executes ve.ui.WindowAction.open(), which opens this dialog.
444 const template = ve.dm.MWTemplateModel.newFromName(
445 this.transclusionModel, data.template
446 );
447 promise = this.transclusionModel.addPart( template );
448 } else {
449 // Open the dialog to add a new template, always starting with a placeholder
450 const placeholderPage = new ve.dm.MWTemplatePlaceholderModel( this.transclusionModel );
451 promise = this.transclusionModel.addPart( placeholderPage );
452 promise.then( () => {
453 this.bookletLayout.setPage( placeholderPage.getId() );
454 } );
455 this.canGoBack = true;
456 }
457 } else {
458 // Open the dialog to edit an existing template
459
460 // TODO tracking will only be implemented temporarily to answer questions on
461 // template usage for the Technical Wishes topic area see T258917
462 const templateEvent = {
463 action: 'edit',
464 // eslint-disable-next-line camelcase
465 template_names: []
466 };
467 const editCountBucket = mw.config.get( 'wgUserEditCountBucket' );
468 if ( editCountBucket !== null ) {
469 // eslint-disable-next-line camelcase
470 templateEvent.user_edit_count_bucket = editCountBucket;
471 }
472 for ( let i = 0; i < this.selectedNode.partsList.length; i++ ) {
473 if ( this.selectedNode.partsList[ i ].templatePage ) {
474 templateEvent.template_names.push( this.selectedNode.partsList[ i ].templatePage );
475 }
476 }
477 mw.track( 'event.VisualEditorTemplateDialogUse', templateEvent );
478
479 promise = this.transclusionModel
480 .load( ve.copy( this.selectedNode.getAttribute( 'mw' ) ) )
481 .then( this.initializeTemplateParameters.bind( this ) );
482 }
483 this.actions.setAbilities( { done: false } );
484
485 return promise.then( () => {
486 // Add missing required and suggested parameters to each transclusion.
487 this.transclusionModel.addPromptedParameters();
488
489 this.$body.append( this.bookletLayout.$element );
490 this.$element.addClass( 've-ui-mwTemplateDialog-ready' );
491 this.loaded = true;
492 } );
493 } );
494 };
495
496 /**
497 * Intentionally empty. This is provided for Wikia extensibility.
498 */
499 ve.ui.MWTemplateDialog.prototype.initializeTemplateParameters = function () {};
500
501 /**
502 * @private
503 * @param {string} pageName
504 * @param {boolean} hasValue
505 */
506 ve.ui.MWTemplateDialog.prototype.onHasValueChange = function ( pageName, hasValue ) {
507 this.sidebar.toggleHasValueByPageName( pageName, hasValue );
508 };
509
510 /**
511 * @inheritdoc
512 */
513 ve.ui.MWTemplateDialog.prototype.getTeardownProcess = function ( data ) {
514 return ve.ui.MWTemplateDialog.super.prototype.getTeardownProcess.call( this, data )
515 .first( () => {
516 // Cleanup
517 this.$element.removeClass( 've-ui-mwTemplateDialog-ready' );
518 this.transclusionModel.disconnect( this );
519 this.transclusionModel.abortAllApiRequests();
520 this.transclusionModel = null;
521 this.bookletLayout.clearPages();
522 this.content = null;
523 } );
524 };