Debian Codegraph @

extensions/VisualEditor/modules/ve-mw/ui/inspectors/ve.ui.MWLinkAnnotationInspector.js

raw symbols SCIP
1 /*!
2 * VisualEditor UserInterface LinkAnnotationInspector class.
3 *
4 * @copyright See AUTHORS.txt
5 * @license The MIT License (MIT); see LICENSE.txt
6 */
7
8 /**
9 * Inspector for applying and editing labeled MediaWiki internal and external links.
10 *
11 * @class
12 * @extends ve.ui.LinkAnnotationInspector
13 *
14 * @constructor
15 * @param {Object} [config] Configuration options
16 */
17 ve.ui.MWLinkAnnotationInspector = function VeUiMWLinkAnnotationInspector( config ) {
18 // Parent constructor
19 ve.ui.MWLinkAnnotationInspector.super.call( this, ve.extendObject( { padded: false }, config ) );
20
21 this.$element.addClass( 've-ui-mwLinkAnnotationInspector' );
22 };
23
24 /* Inheritance */
25
26 OO.inheritClass( ve.ui.MWLinkAnnotationInspector, ve.ui.LinkAnnotationInspector );
27
28 /* Static properties */
29
30 ve.ui.MWLinkAnnotationInspector.static.name = 'link';
31
32 ve.ui.MWLinkAnnotationInspector.static.modelClasses = [
33 ve.dm.MWExternalLinkAnnotation,
34 ve.dm.MWInternalLinkAnnotation
35 ];
36
37 ve.ui.MWLinkAnnotationInspector.static.actions = [
38 ...ve.ui.MWLinkAnnotationInspector.static.actions,
39 {
40 action: 'convert',
41 label: null, // see #updateActions
42 modes: [ 'edit', 'insert' ]
43 }
44 ];
45
46 /* Methods */
47
48 /**
49 * @inheritdoc
50 */
51 ve.ui.MWLinkAnnotationInspector.prototype.initialize = function () {
52 // Properties
53 this.allowProtocolInInternal = false;
54 this.internalAnnotationInput = this.createInternalAnnotationInput();
55 this.externalAnnotationInput = this.createExternalAnnotationInput();
56
57 this.linkTypeIndex = new OO.ui.IndexLayout( {
58 expanded: false,
59 framed: false
60 } );
61
62 this.linkTypeIndex.addTabPanels( [
63 new OO.ui.TabPanelLayout( 'internal', {
64 label: mw.config.get( 'wgSiteName' ),
65 expanded: false,
66 scrollable: false,
67 padded: true
68 } ),
69 new OO.ui.TabPanelLayout( 'external', {
70 label: ve.msg( 'visualeditor-linkinspector-button-link-external' ),
71 expanded: false,
72 scrollable: false,
73 padded: true
74 } )
75 ] );
76
77 // Parent method
78 // Parent requires createAnnotationInput to be callable, but tries to move
79 // inputs in the DOM, so call this before we restructure the DOM.
80 ve.ui.MWLinkAnnotationInspector.super.prototype.initialize.call( this );
81
82 this.internalAnnotationField = this.annotationField;
83 this.externalAnnotationField = new OO.ui.FieldLayout(
84 this.externalAnnotationInput,
85 {
86 align: 'top',
87 label: ve.msg( 'visualeditor-linkinspector-title' )
88 }
89 );
90
91 this.onExternalLinkInputChangeDebounced = ve.debounce( this.onExternalLinkInputChange, 750 );
92
93 // Events
94 this.linkTypeIndex.connect( this, { set: 'onLinkTypeIndexSet' } );
95 this.labelInput.connect( this, { change: 'onLabelInputChange' } );
96 this.internalAnnotationInput.connect( this, { change: 'onInternalLinkChange' } );
97 this.externalAnnotationInput.connect( this, { change: 'onExternalLinkChange' } );
98 this.internalAnnotationInput.input.getResults().connect( this, { choose: 'onFormSubmit' } );
99 // Form submit only auto triggers on enter when there is one input
100 this.internalAnnotationInput.getTextInputWidget().connect( this, {
101 change: 'onInternalLinkInputChange',
102 enter: 'onLinkInputEnter'
103 } );
104 this.externalAnnotationInput.getTextInputWidget().connect( this, {
105 change: 'onExternalLinkInputChangeDebounced',
106 enter: 'onLinkInputEnter'
107 } );
108 // this.internalAnnotationInput is already bound by parent class
109 this.externalAnnotationInput.connect( this, { change: 'onAnnotationInputChange' } );
110
111 this.internalAnnotationInput.input.results.connect( this, {
112 add: 'onInternalLinkChangeResultsChange',
113 // Listening to remove causes a flicker, and is not required
114 // as 'add' is always trigger on a change too
115 choose: 'onInternalLinkSearchResultsChoose'
116 } );
117
118 // Initialization
119 // HACK: IndexLayout is absolutely positioned, so place actions inside it
120 this.linkTypeIndex.$content.append( this.$otherActions );
121 this.linkTypeIndex.getTabPanel( 'internal' ).$element.append( this.internalAnnotationField.$element );
122 this.linkTypeIndex.getTabPanel( 'external' ).$element.append( this.externalAnnotationField.$element );
123 // labelField gets moved between tabs when activated
124 if ( OO.ui.isMobile() ) {
125 this.linkTypeIndex.getTabPanel( 'internal' ).$element.prepend( this.labelField.$element );
126 }
127 this.form.$element.empty().append( this.linkTypeIndex.$element );
128 if ( !OO.ui.isMobile() ) {
129 this.externalAnnotationField.setLabel( null );
130 }
131 };
132
133 /**
134 * @return {ve.ui.MWInternalLinkAnnotationWidget}
135 */
136 ve.ui.MWLinkAnnotationInspector.prototype.createInternalAnnotationInput = function () {
137 return new ve.ui.MWInternalLinkAnnotationWidget();
138 };
139
140 /**
141 * @return {ve.ui.MWExternalLinkAnnotationWidget}
142 */
143 ve.ui.MWLinkAnnotationInspector.prototype.createExternalAnnotationInput = function () {
144 return new ve.ui.MWExternalLinkAnnotationWidget();
145 };
146
147 /**
148 * Check if the current input mode is for external links
149 *
150 * @return {boolean} Input mode is for external links
151 */
152 ve.ui.MWLinkAnnotationInspector.prototype.isExternal = function () {
153 return this.linkTypeIndex.getCurrentTabPanelName() === 'external';
154 };
155
156 /**
157 * Handle change events on the label input
158 *
159 * @param {string} value
160 */
161 ve.ui.MWLinkAnnotationInspector.prototype.onLabelInputChange = function () {
162 if ( this.isActive && !this.trackedLabelInputChange ) {
163 ve.track( 'activity.' + this.constructor.static.name, { action: 'label-input' } );
164 this.trackedLabelInputChange = true;
165 }
166 };
167
168 /**
169 * Handle change events on the internal link widget
170 *
171 * @param {ve.dm.MWInternalLinkAnnotation} annotation
172 */
173 ve.ui.MWLinkAnnotationInspector.prototype.onInternalLinkChange = function () {
174 this.updateActions();
175 };
176
177 /**
178 * Handle list change events ('add') from the interal link's result widget
179 *
180 * @param {OO.ui.OptionWidget[]} items Added items
181 * @param {number} index Index of insertion point
182 */
183 ve.ui.MWLinkAnnotationInspector.prototype.onInternalLinkChangeResultsChange = function () {
184 this.updateSize();
185 };
186
187 /**
188 * Handle choose events from the result widget
189 *
190 * @param {OO.ui.OptionWidget} item Chosen item
191 */
192 ve.ui.MWLinkAnnotationInspector.prototype.onInternalLinkSearchResultsChoose = function () {
193 ve.track( 'activity.' + this.constructor.static.name, { action: 'search-pages-choose' } );
194 };
195
196 /**
197 * Handle change events on the external link widget
198 *
199 * @param {ve.dm.MWExternalLinkAnnotation} annotation
200 */
201 ve.ui.MWLinkAnnotationInspector.prototype.onExternalLinkChange = function () {
202 this.updateActions();
203 };
204
205 /**
206 * Handle enter events on the external/internal link inputs
207 *
208 * @param {jQuery.Event} e Key press event
209 */
210 ve.ui.MWLinkAnnotationInspector.prototype.onLinkInputEnter = function () {
211 if ( this.annotationInput.getTextInputWidget().getValue().trim() === '' ) {
212 this.executeAction( 'done' );
213 }
214 this.annotationInput.getTextInputWidget().getValidity()
215 .done( () => {
216 this.executeAction( 'done' );
217 } );
218 };
219
220 /**
221 * @inheritdoc
222 */
223 ve.ui.MWLinkAnnotationInspector.prototype.updateActions = function () {
224 let msg = null;
225
226 ve.ui.MWLinkAnnotationInspector.super.prototype.updateActions.call( this );
227
228 // show/hide convert action
229 const content = this.fragment ? this.fragment.getText() : '';
230 const annotation = this.annotationInput.getAnnotation();
231 const href = annotation && annotation.getHref();
232 if ( href && ve.dm.MWMagicLinkNode.static.validateHref( content, href ) ) {
233 const type = ve.dm.MWMagicLinkType.static.fromContent( content ).type;
234 msg = 'visualeditor-linkinspector-convert-link-' + type.toLowerCase();
235 }
236
237 // Once we toggle the visibility of the ActionWidget, we can't filter
238 // it with `get` any more. So we have to use `forEach`:
239 this.actions.forEach( null, ( action ) => {
240 if ( action.getAction() === 'convert' ) {
241 if ( msg ) {
242 // The following messages are used here:
243 // * visualeditor-linkinspector-convert-link-isbn
244 // * visualeditor-linkinspector-convert-link-pmid
245 // * visualeditor-linkinspector-convert-link-rfc
246 action.setLabel( OO.ui.deferMsg( msg ) );
247 action.toggle( true );
248 } else {
249 action.toggle( false );
250 }
251 }
252 } );
253 };
254
255 /**
256 * Handle change events on the internal link widget's input
257 *
258 * @param {string} value Current value of input widget
259 */
260 ve.ui.MWLinkAnnotationInspector.prototype.onInternalLinkInputChange = function ( value ) {
261 // If this looks like an external link, switch to the correct tabPanel.
262 // Note: We don't care here if it's a *valid* link, so we just
263 // check whether it looks like a URI -- i.e. whether it starts with
264 // something that appears to be a schema per RFC1630. Later the external
265 // link inspector will use getExternalLinkUrlProtocolsRegExp for validity
266 // checking.
267 // Note 2: RFC1630 might be too broad in practice. You don't really see
268 // schemas that use the full set of allowed characters, and we might get
269 // more false positives by checking for them.
270 // Note 3: We allow protocol-relative URIs here.
271 if ( this.internalAnnotationInput.getTextInputWidget().getValue() !== value ) {
272 return;
273 }
274 if ( this.isActive && !this.trackedInternalLinkInputChange && !this.switchingLinkTypes ) {
275 ve.track( 'activity.' + this.constructor.static.name, { action: 'search-pages-input' } );
276 this.trackedInternalLinkInputChange = true;
277 }
278 if (
279 !this.allowProtocolInInternal &&
280 ( /^(?:[a-z][a-z0-9$\-_@.&!*"'(),]*:)?\/\//i ).test( value.trim() )
281 ) {
282 this.linkTypeIndex.setTabPanel( 'external' );
283 // Changing tabPanel focuses and selects the input, so collapse the cursor back to the end.
284 this.externalAnnotationInput.getTextInputWidget().moveCursorToEnd();
285 }
286
287 this.internalAnnotationInput.getTextInputWidget().getValidity()
288 .then(
289 () => {
290 this.internalAnnotationField.setErrors( [] );
291 this.updateSize();
292 }, () => {
293 this.internalAnnotationField.setErrors( [ ve.msg( 'visualeditor-linkinspector-illegal-title' ) ] );
294 this.updateSize();
295 }
296 );
297
298 };
299
300 /**
301 * Handle change events on the external link widget's input
302 *
303 * @param {string} value Current value of input widget
304 */
305 ve.ui.MWLinkAnnotationInspector.prototype.onExternalLinkInputChange = function () {
306 this.externalAnnotationInput.getValidity().then(
307 () => {
308 // clear any invalid-protocol errors
309 this.externalAnnotationField.setErrors( [] );
310 }, ( errortype ) => {
311 // Messages that can be used here:
312 // * visualeditor-linkinspector-invalid-blocked
313 // * visualeditor-linkinspector-invalid-external
314 this.externalAnnotationField.setErrors( [ ve.msg( 'visualeditor-linkinspector-' + errortype ) ] );
315 if ( errortype === 'invalid-blocked' ) {
316 // This has been quite async, so:
317 this.actions.forEach( { actions: [ 'done', 'insert' ] }, ( action ) => {
318 action.setDisabled( true );
319 } );
320 ve.track( 'activity.editCheckReliability', { action: 'link-blocked' } );
321 }
322 }
323 ).always( () => {
324 this.updateSize();
325 } );
326
327 if ( this.isActive && !this.trackedExternalLinkInputChange && !this.switchingLinkTypes ) {
328 ve.track( 'activity.' + this.constructor.static.name, { action: 'external-link-input' } );
329 this.trackedExternalLinkInputChange = true;
330 }
331 };
332
333 /**
334 * @inheritdoc
335 */
336 ve.ui.MWLinkAnnotationInspector.prototype.createAnnotationInput = function () {
337 return this.isExternal() ? this.externalAnnotationInput : this.internalAnnotationInput;
338 };
339
340 /**
341 * @inheritdoc
342 */
343 ve.ui.MWLinkAnnotationInspector.prototype.getSetupProcess = function ( data ) {
344 return ve.ui.MWLinkAnnotationInspector.super.prototype.getSetupProcess.call( this, data )
345 .next( () => {
346 this.isReady = false;
347
348 const isReadOnly = this.isReadOnly();
349 this.linkTypeIndex.setTabPanel(
350 this.initialAnnotation instanceof ve.dm.MWExternalLinkAnnotation ? 'external' : 'internal'
351 );
352 this.annotationInput.setAnnotation( this.initialAnnotation );
353 this.internalAnnotationInput.setReadOnly( isReadOnly );
354 this.externalAnnotationInput.setReadOnly( isReadOnly );
355
356 this.trackedInternalLinkInputChange = false;
357 this.trackedExternalLinkInputChange = false;
358 this.isActive = true;
359 } );
360 };
361
362 /**
363 * @inheritdoc
364 */
365 ve.ui.MWLinkAnnotationInspector.prototype.getReadyProcess = function ( data ) {
366 return ve.ui.MWLinkAnnotationInspector.super.prototype.getReadyProcess.call( this, data )
367 .next( () => {
368 this.isReady = true;
369 // Focus is skipped during setup. (T321026)
370 this.annotationInput.getTextInputWidget().focus();
371 } );
372 };
373
374 /**
375 * @inheritdoc
376 */
377 ve.ui.MWLinkAnnotationInspector.prototype.getActionProcess = function ( action ) {
378 if ( action === 'convert' ) {
379 return new OO.ui.Process( () => {
380 this.close( { action: 'done', convert: true } );
381 } );
382 }
383 return ve.ui.MWLinkAnnotationInspector.super.prototype.getActionProcess.call( this, action );
384 };
385
386 /**
387 * @inheritdoc
388 */
389 ve.ui.MWLinkAnnotationInspector.prototype.getTeardownProcess = function ( data ) {
390 let fragment;
391 return ve.ui.MWLinkAnnotationInspector.super.prototype.getTeardownProcess.call( this, data )
392 .first( () => {
393 // Save the original fragment for later.
394 fragment = this.getFragment();
395
396 this.isActive = false;
397 } )
398 .next( () => {
399 const selection = fragment && fragment.getSelection();
400
401 // Handle conversion to magic link.
402 if ( data && data.convert && selection instanceof ve.dm.LinearSelection ) {
403 const annotations = fragment.getDocument().data
404 .getAnnotationsFromRange( selection.getRange() )
405 // Remove link annotations
406 .filter( ( annotation ) => !/^link/.test( annotation.name ) );
407 const linearData = new ve.dm.ElementLinearData( annotations.store, [
408 {
409 type: 'link/mwMagic',
410 attributes: {
411 content: fragment.getText()
412 }
413 },
414 {
415 type: '/link/mwMagic'
416 }
417 ] );
418 linearData.setAnnotationsAtOffset( 0, annotations );
419 fragment.insertContent( linearData.getData(), true );
420 }
421
422 // Clear dialog state.
423 this.allowProtocolInInternal = false;
424 // Make sure both inputs are cleared
425 this.internalAnnotationInput.setAnnotation( null );
426 this.externalAnnotationInput.setAnnotation( null );
427 } );
428 };
429
430 /**
431 * Handle set events from the linkTypeIndex layout
432 *
433 * @param {OO.ui.TabPanelLayout} tabPanel Current tabPanel
434 */
435 ve.ui.MWLinkAnnotationInspector.prototype.onLinkTypeIndexSet = function ( tabPanel ) {
436 const text = this.annotationInput.getTextInputWidget().getValue(),
437 end = text.length,
438 isExternal = this.isExternal(),
439 inputHasProtocol = ve.init.platform.getExternalLinkUrlProtocolsRegExp().test( text );
440
441 this.switchingLinkTypes = true;
442
443 this.annotationInput = isExternal ? this.externalAnnotationInput : this.internalAnnotationInput;
444
445 if ( OO.ui.isMobile() ) {
446 tabPanel.$element.prepend( this.labelField.$element );
447 }
448
449 this.updateSize();
450
451 // If the user manually switches to internal links with an external link in the input, remember this
452 if ( !isExternal && inputHasProtocol ) {
453 this.allowProtocolInInternal = true;
454 }
455
456 this.annotationInput.getTextInputWidget().setValue( text );
457 if ( this.isReady ) {
458 // Focussing an element that isn't visible yet triggers a
459 // bug in jQuery that prevents future focusses. (T321026)
460 this.annotationInput.getTextInputWidget().focus();
461 }
462 // Select entire link when switching, for ease of replacing entire contents.
463 // Most common case:
464 // 1. Inspector opened, internal-link shown with the selected-word prefilled
465 // 2. User clicks external link tab (unnecessary, because we'd auto-switch, but the user doesn't know that)
466 // 3. User pastes a link, intending to replace the existing prefilled link
467 this.annotationInput.getTextInputWidget().$input[ 0 ].setSelectionRange( 0, end );
468 // Focusing a TextInputWidget normally unsets validity. However, because
469 // we're kind of pretending this is the same input, just in a different
470 // mode, it doesn't make sense to the user that the focus behavior occurs.
471 this.annotationInput.getTextInputWidget().setValidityFlag();
472
473 this.onAnnotationInputChange();
474
475 if ( this.isActive ) {
476 ve.track( 'activity.' + this.constructor.static.name, { action: 'panel-switch' } );
477 }
478
479 this.switchingLinkTypes = false;
480 };
481
482 /**
483 * Gets an annotation object from a fragment.
484 *
485 * The type of link is automatically detected based on some crude heuristics.
486 *
487 * @param {ve.dm.SurfaceFragment} fragment Current selection
488 * @return {ve.dm.MWInternalLinkAnnotation|ve.dm.MWExternalLinkAnnotation|null}
489 */
490 ve.ui.MWLinkAnnotationInspector.prototype.getAnnotationFromFragment = function ( fragment ) {
491 const target = fragment.getText(),
492 title = mw.Title.newFromText( target );
493
494 // Figure out if this is an internal or external link
495 if ( ve.init.platform.getExternalLinkUrlProtocolsRegExp().test( target ) ) {
496 // External link
497 return this.newExternalLinkAnnotation( {
498 type: 'link/mwExternal',
499 attributes: {
500 href: target
501 }
502 } );
503 } else if ( title ) {
504 // Internal link
505 return this.newInternalLinkAnnotationFromTitle( title );
506 } else {
507 // Doesn't look like an external link and mw.Title considered it an illegal value,
508 // for an internal link.
509 return null;
510 }
511 };
512
513 /**
514 * @param {mw.Title} title The title to link to.
515 * @return {ve.dm.MWInternalLinkAnnotation} The annotation.
516 */
517 ve.ui.MWLinkAnnotationInspector.prototype.newInternalLinkAnnotationFromTitle = function ( title ) {
518 return ve.dm.MWInternalLinkAnnotation.static.newFromTitle( title );
519 };
520
521 /**
522 * @param {Object} element
523 * @return {ve.dm.MWExternalLinkAnnotation} The annotation.
524 */
525 ve.ui.MWLinkAnnotationInspector.prototype.newExternalLinkAnnotation = function ( element ) {
526 return new ve.dm.MWExternalLinkAnnotation( element );
527 };
528
529 /**
530 * @inheritdoc
531 */
532 ve.ui.MWLinkAnnotationInspector.prototype.getInsertionText = function () {
533 // Prefer user input, not normalized annotation, to preserve case
534 const label = this.labelInput.getValue().trim();
535 if ( label ) {
536 return label;
537 } else if ( this.isNew && this.isExternal() ) {
538 return '';
539 } else {
540 return this.annotationInput.getTextInputWidget().getValue();
541 }
542 };
543
544 /**
545 * @inheritdoc
546 */
547 ve.ui.MWLinkAnnotationInspector.prototype.getInsertionData = function () {
548 // If this is a new external link with no label, insert an autonumbered link instead of a link annotation
549 // (applying the annotation on this later does nothing because of disallowedAnnotationTypes).
550 // Otherwise call parent method to figure out the text to insert and annotate.
551 if ( this.isNew && this.isExternal() && !this.labelInput.getValue().trim() ) {
552 return [
553 {
554 type: 'link/mwNumberedExternal',
555 attributes: {
556 href: this.annotationInput.getHref()
557 }
558 },
559 { type: '/link/mwNumberedExternal' }
560 ];
561 } else {
562 return this.getInsertionText().split( '' );
563 }
564 };
565
566 // #getInsertionText call annotationInput#getHref, which returns the link title,
567 // so no custmisation is needed.
568
569 /* Registration */
570
571 ve.ui.windowFactory.register( ve.ui.MWLinkAnnotationInspector );