Debian Codegraph @

extensions/VisualEditor/lib/ve/src/ui/dialogs/ve.ui.FindAndReplaceDialog.js

raw symbols SCIP
1 /*!
2 * VisualEditor UserInterface FindAndReplaceDialog class.
3 *
4 * @copyright See AUTHORS.txt
5 */
6
7 /**
8 * Find and replace dialog.
9 *
10 * @class
11 * @extends ve.ui.ToolbarDialog
12 *
13 * @constructor
14 * @param {Object} [config] Configuration options
15 */
16 ve.ui.FindAndReplaceDialog = function VeUiFindAndReplaceDialog( config ) {
17 // Parent constructor
18 ve.ui.FindAndReplaceDialog.super.call( this, config );
19
20 // Pre-initialization
21 this.$element.addClass( 've-ui-findAndReplaceDialog' );
22 };
23
24 /* Inheritance */
25
26 OO.inheritClass( ve.ui.FindAndReplaceDialog, ve.ui.ToolbarDialog );
27
28 ve.ui.FindAndReplaceDialog.static.name = 'findAndReplace';
29
30 // Invisible title for accessibility
31 ve.ui.FindAndReplaceDialog.static.title =
32 OO.ui.deferMsg( 'visualeditor-find-and-replace-title' );
33
34 ve.ui.FindAndReplaceDialog.static.handlesSource = true;
35
36 /**
37 * Maximum number of results to render
38 *
39 * @property {number}
40 */
41 ve.ui.FindAndReplaceDialog.static.maxRenderedResults = 100;
42
43 /* Methods */
44
45 /**
46 * @inheritdoc
47 */
48 ve.ui.FindAndReplaceDialog.prototype.initialize = function () {
49 // Parent method
50 ve.ui.FindAndReplaceDialog.super.prototype.initialize.call( this );
51
52 // Properties
53 this.surface = null;
54 this.invalidRegex = false;
55 this.initialFragment = null;
56 this.startOffset = 0;
57 this.fragments = [];
58 this.results = 0;
59 this.isClipped = false;
60 this.replacing = false;
61 this.focusedIndex = 0;
62 this.query = null;
63 this.findText = new OO.ui.TextInputWidget( {
64 placeholder: ve.msg( 'visualeditor-find-and-replace-find-text' ),
65 value: ve.userConfig( 'visualeditor-findAndReplace-findText' ),
66 validate: () => !this.invalidRegex,
67 tabIndex: 1
68 } );
69 this.findText.$input.attr( 'aria-label', ve.msg( 'visualeditor-find-and-replace-find-text' ) );
70 this.updateUserConfigDebounced = ve.debounce( this.updateUserConfig.bind( this ), 500 );
71
72 this.previousButton = new OO.ui.ButtonWidget( {
73 icon: 'previous',
74 title: ve.msg( 'visualeditor-find-and-replace-previous-button' ) + ' ' +
75 ve.ui.triggerRegistry.getMessages( 'findPrevious' ).join( ', ' ),
76 tabIndex: 2
77 } );
78 this.nextButton = new OO.ui.ButtonWidget( {
79 icon: 'next',
80 title: ve.msg( 'visualeditor-find-and-replace-next-button' ) + ' ' +
81 ve.ui.triggerRegistry.getMessages( 'findNext' ).join( ', ' ),
82 tabIndex: 2
83 } );
84 this.matchCaseToggle = new OO.ui.ToggleButtonWidget( {
85 icon: 'searchCaseSensitive',
86 title: ve.msg( 'visualeditor-find-and-replace-match-case' ),
87 value: ve.userConfig( 'visualeditor-findAndReplace-matchCase' ),
88 tabIndex: 2
89 } );
90 this.regexToggle = new OO.ui.ToggleButtonWidget( {
91 icon: 'searchRegularExpression',
92 title: ve.msg( 'visualeditor-find-and-replace-regular-expression' ),
93 value: ve.userConfig( 'visualeditor-findAndReplace-regex' ),
94 tabIndex: 2
95 } );
96 this.wordToggle = new OO.ui.ToggleButtonWidget( {
97 icon: 'quotes',
98 title: ve.msg( 'visualeditor-find-and-replace-word' ),
99 value: ve.userConfig( 'visualeditor-findAndReplace-word' ),
100 tabIndex: 2
101 } );
102 this.diacriticToggle = new OO.ui.ToggleButtonWidget( {
103 icon: 'searchDiacritics',
104 title: ve.msg( 'visualeditor-find-and-replace-diacritic' ),
105 value: ve.userConfig( 'visualeditor-findAndReplace-diacritic' ),
106 tabIndex: 2
107 } );
108
109 this.replaceText = new OO.ui.TextInputWidget( {
110 placeholder: ve.msg( 'visualeditor-find-and-replace-replace-text' ),
111 value: ve.userConfig( 'visualeditor-findAndReplace-replaceText' ),
112 tabIndex: 1
113 } );
114 this.replaceText.$input.attr( 'aria-label', ve.msg( 'visualeditor-find-and-replace-replace-text' ) );
115
116 this.replaceButton = new OO.ui.ButtonWidget( {
117 label: ve.msg( 'visualeditor-find-and-replace-replace-button' ),
118 tabIndex: 1
119 } );
120 this.replaceAllButton = new OO.ui.ButtonWidget( {
121 label: ve.msg( 'visualeditor-find-and-replace-replace-all-button' ),
122 tabIndex: 1
123 } );
124 const doneButton = new OO.ui.ButtonWidget( {
125 classes: [ 've-ui-findAndReplaceDialog-cell' ],
126 label: ve.msg( 'visualeditor-find-and-replace-done' ),
127 tabIndex: 1
128 } );
129
130 const optionsGroup = new OO.ui.ButtonGroupWidget( {
131 classes: [ 've-ui-findAndReplaceDialog-cell' ],
132 items: [
133 this.matchCaseToggle,
134 this.regexToggle,
135 this.wordToggle,
136 this.diacriticToggle
137 ]
138 } );
139 const navigateGroup = new OO.ui.ButtonGroupWidget( {
140 classes: [ 've-ui-findAndReplaceDialog-cell' ],
141 items: [
142 this.previousButton,
143 this.nextButton
144 ]
145 } );
146 const replaceGroup = new OO.ui.ButtonGroupWidget( {
147 classes: [ 've-ui-findAndReplaceDialog-cell' ],
148 items: [
149 this.replaceButton,
150 this.replaceAllButton
151 ]
152 } );
153 const $findRow = $( '<div>' ).addClass( 've-ui-findAndReplaceDialog-row' );
154 const $replaceRow = $( '<div>' ).addClass( 've-ui-findAndReplaceDialog-row' );
155
156 // Events
157 this.onWindowScrollThrottled = ve.throttle( this.onWindowScroll.bind( this ), 250 );
158 this.updateFragmentsThrottled = ve.throttle( this.updateFragments.bind( this ), 250 );
159 this.renderFragmentsThrottled = ve.throttle( this.renderFragments.bind( this ), 250 );
160 this.findText.connect( this, {
161 change: 'onFindChange',
162 enter: 'onFindReplaceTextEnter'
163 } );
164 this.replaceText.connect( this, {
165 change: 'onReplaceChange',
166 enter: 'onFindReplaceTextEnter'
167 } );
168 this.matchCaseToggle.connect( this, { change: 'onFindChange' } );
169 this.regexToggle.connect( this, { change: 'onFindChange' } );
170 this.wordToggle.connect( this, { change: 'onFindChange' } );
171 this.diacriticToggle.connect( this, { change: 'onFindChange' } );
172 this.nextButton.connect( this, { click: 'findNext' } );
173 this.previousButton.connect( this, { click: 'findPrevious' } );
174 this.replaceButton.connect( this, { click: 'onReplaceButtonClick' } );
175 this.replaceAllButton.connect( this, { click: 'onReplaceAllButtonClick' } );
176 doneButton.connect( this, { click: 'close' } );
177
178 this.tabIndexScope = new ve.ui.TabIndexScope( {
179 root: this.$element
180 } );
181
182 // Initialization
183 this.$content.addClass( 've-ui-findAndReplaceDialog-content' );
184 this.$body
185 .append(
186 $findRow.append(
187 $( '<div>' ).addClass( 've-ui-findAndReplaceDialog-cell ve-ui-findAndReplaceDialog-cell-input' ).append(
188 this.findText.$element
189 ),
190 navigateGroup.$element,
191 optionsGroup.$element
192 ),
193 $replaceRow.append(
194 $( '<div>' ).addClass( 've-ui-findAndReplaceDialog-cell ve-ui-findAndReplaceDialog-cell-input' ).append(
195 this.replaceText.$element
196 ),
197 replaceGroup.$element,
198 doneButton.$element
199 )
200 );
201 };
202
203 /**
204 * @inheritdoc
205 */
206 ve.ui.FindAndReplaceDialog.prototype.getSetupProcess = function ( data ) {
207 data = data || {};
208 return ve.ui.FindAndReplaceDialog.super.prototype.getSetupProcess.call( this, data )
209 .first( () => {
210 this.surface = data.surface;
211
212 // Events
213 this.surface.getModel().connect( this, { documentUpdate: 'onSurfaceModelDocumentUpdate' } );
214 this.surface.getView().connect( this, { position: 'onSurfaceViewPosition' } );
215 this.surface.$scrollListener[ 0 ].addEventListener( 'scroll', this.onWindowScrollThrottled, { passive: true } );
216
217 this.updateFragments();
218 this.renderFragments();
219 } );
220 };
221
222 /**
223 * @inheritdoc
224 */
225 ve.ui.FindAndReplaceDialog.prototype.getReadyProcess = function ( data ) {
226 return ve.ui.FindAndReplaceDialog.super.prototype.getReadyProcess.call( this, data )
227 .next( () => {
228 this.focus();
229 } );
230 };
231
232 /**
233 * @inheritdoc
234 */
235 ve.ui.FindAndReplaceDialog.prototype.getTeardownProcess = function ( data ) {
236 return ve.ui.FindAndReplaceDialog.super.prototype.getTeardownProcess.call( this, data )
237 .next( () => {
238 const surfaceView = this.surface.getView(),
239 surfaceModel = this.surface.getModel();
240
241 // Events
242 this.surface.getModel().disconnect( this );
243 surfaceView.disconnect( this );
244 this.surface.$scrollListener[ 0 ].removeEventListener( 'scroll', this.onWindowScrollThrottled );
245
246 let selection;
247 if ( this.fragments.length ) {
248 // Either the active search result…
249 selection = this.fragments[ this.focusedIndex ].getSelection();
250 } else {
251 // … or the initial selection
252 selection = this.initialFragment.getSelection();
253 }
254 surfaceModel.setSelection( selection );
255
256 // Generates ve-ce-surface-selections-findResults CSS class
257 surfaceView.drawSelections( 'findResults', [] );
258 this.fragments = [];
259 this.surface = null;
260 this.focusedIndex = 0;
261 } );
262 };
263
264 /**
265 * Handle documentUpdate events from the surface model
266 */
267 ve.ui.FindAndReplaceDialog.prototype.onSurfaceModelDocumentUpdate = function () {
268 if ( this.replacing ) {
269 return;
270 }
271 this.updateFragmentsThrottled();
272 };
273
274 /**
275 * Handle position events from the surface view
276 */
277 ve.ui.FindAndReplaceDialog.prototype.onSurfaceViewPosition = function () {
278 if ( this.replacing ) {
279 return;
280 }
281 this.renderFragmentsThrottled();
282 };
283
284 /**
285 * Handle window scroll events
286 */
287 ve.ui.FindAndReplaceDialog.prototype.onWindowScroll = function () {
288 if ( this.isClipped ) {
289 // If viewport clipping is being used, reposition results based on the current viewport
290 this.renderFragments();
291 }
292 };
293
294 /**
295 * Handle change events to the find inputs (text or match case)
296 */
297 ve.ui.FindAndReplaceDialog.prototype.onFindChange = function () {
298 this.updateFragments();
299 this.renderFragments();
300 this.highlightFocused( true );
301 this.diacriticToggle.setDisabled( this.regexToggle.getValue() );
302 this.updateUserConfigDebounced();
303 };
304
305 /**
306 * Handle change events to the replace input
307 */
308 ve.ui.FindAndReplaceDialog.prototype.onReplaceChange = function () {
309 this.updateUserConfigDebounced();
310 };
311
312 /**
313 * Remember inputs in the dialog in user config.
314 */
315 ve.ui.FindAndReplaceDialog.prototype.updateUserConfig = function () {
316 ve.userConfig( {
317 'visualeditor-findAndReplace-findText': this.findText.getValue(),
318 'visualeditor-findAndReplace-matchCase': this.matchCaseToggle.getValue(),
319 'visualeditor-findAndReplace-regex': this.regexToggle.getValue(),
320 'visualeditor-findAndReplace-word': this.wordToggle.getValue(),
321 'visualeditor-findAndReplace-diacritic': this.diacriticToggle.getValue(),
322 'visualeditor-findAndReplace-replaceText': this.replaceText.getValue()
323 } );
324 };
325
326 /**
327 * Handle enter events on the find text and replace text inputs
328 *
329 * @param {jQuery.Event} e
330 */
331 ve.ui.FindAndReplaceDialog.prototype.onFindReplaceTextEnter = function ( e ) {
332 if ( !this.results ) {
333 return;
334 }
335 if ( e.shiftKey ) {
336 this.findPrevious();
337 } else {
338 this.findNext();
339 }
340 };
341
342 /**
343 * Update search result fragments
344 */
345 ve.ui.FindAndReplaceDialog.prototype.updateFragments = function () {
346 const surfaceModel = this.surface.getModel(),
347 documentModel = surfaceModel.getDocument(),
348 isReadOnly = surfaceModel.isReadOnly(),
349 matchCase = this.matchCaseToggle.getValue(),
350 isRegex = this.regexToggle.getValue(),
351 wholeWord = this.wordToggle.getValue(),
352 diacriticInsensitive = this.diacriticToggle.getValue(),
353 find = this.findText.getValue();
354 let ranges = [];
355
356 this.invalidRegex = false;
357
358 if ( isRegex && find ) {
359 try {
360
361 this.query = new RegExp( find, matchCase ? 'g' : 'gi' );
362 } catch ( e ) {
363 this.invalidRegex = true;
364 this.query = '';
365 }
366 } else {
367 this.query = find;
368 }
369 this.findText.setValidityFlag();
370
371 this.fragments = [];
372 let startIndex;
373 if ( this.query ) {
374 ranges = documentModel.findText( this.query, {
375 caseSensitiveString: matchCase,
376 diacriticInsensitiveString: diacriticInsensitive,
377 noOverlaps: true,
378 wholeWord: wholeWord
379 } );
380 for ( let i = 0, l = ranges.length; i < l; i++ ) {
381 this.fragments.push( surfaceModel.getLinearFragment( ranges[ i ], true, true ) );
382 if ( startIndex === undefined && ranges[ i ].start >= this.startOffset ) {
383 startIndex = this.fragments.length - 1;
384 }
385 }
386 }
387 this.results = this.fragments.length;
388 this.focusedIndex = startIndex || 0;
389 this.nextButton.setDisabled( !this.results );
390 this.previousButton.setDisabled( !this.results );
391 this.replaceText.setDisabled( isReadOnly );
392 this.replaceButton.setDisabled( !this.results || isReadOnly );
393 this.replaceAllButton.setDisabled( !this.results || isReadOnly );
394 };
395
396 /**
397 * Position results markers
398 */
399 ve.ui.FindAndReplaceDialog.prototype.renderFragments = function () {
400 // The methods is called after a delay (renderFragmentsThrottled/onWindowScrollThrottled)
401 // Check the dialog hasn't been torn down, or that the surface view hasn't been destroyed
402 if ( !this.surface || !this.surface.getView().attachedRoot.isLive() ) {
403 return;
404 }
405
406 let start = 0;
407 let end = this.results;
408
409 // When there are a large number of results, calculate the viewport range for clipping
410 if ( this.results > 50 ) {
411 const viewportRange = this.surface.getView().getViewportRange( true, 50 );
412 for ( let i = 0; i < this.results; i++ ) {
413 const selection = this.fragments[ i ].getSelection();
414 if ( viewportRange && selection.getRange().start < viewportRange.start ) {
415 start = i + 1;
416 continue;
417 }
418 if ( viewportRange && selection.getRange().end > viewportRange.end ) {
419 end = i;
420 break;
421 }
422 }
423 }
424
425 // When there are too many results to render, just render the current one
426 if ( end - start <= this.constructor.static.maxRenderedResults ) {
427 this.renderRangeOfFragments( new ve.Range( start, end ) );
428 } else {
429 this.renderRangeOfFragments( new ve.Range( this.focusedIndex, this.focusedIndex + 1 ) );
430 }
431 };
432
433 /**
434 * Render subset of search result fragments
435 *
436 * @param {ve.Range} range Range of fragments to render. N.B. This is a range in the
437 * results array, not a document range.
438 */
439 ve.ui.FindAndReplaceDialog.prototype.renderRangeOfFragments = function ( range ) {
440 const selections = [];
441 for ( let i = range.start; i < range.end; i++ ) {
442 selections.push(
443 this.surface.getView().getSelection( this.fragments[ i ].getSelection() )
444 );
445 }
446 // Generates ve-ce-surface-selections-findResults CSS class
447 this.surface.getView().drawSelections( 'findResults', selections );
448 this.isClipped = range.getLength() < this.results;
449 this.highlightFocused();
450 };
451
452 /**
453 * Highlight the focused result marker
454 *
455 * @param {boolean} scrollIntoView Scroll the marker into view
456 */
457 ve.ui.FindAndReplaceDialog.prototype.highlightFocused = function ( scrollIntoView ) {
458 const surfaceView = this.surface.getView();
459
460 if ( this.results ) {
461 this.findText.setLabel(
462 ve.msg( 'visualeditor-find-and-replace-results',
463 ve.init.platform.formatNumber( this.focusedIndex + 1 ),
464 ve.init.platform.formatNumber( this.results )
465 )
466 );
467 } else {
468 this.findText.setLabel(
469 this.invalidRegex ? ve.msg( 'visualeditor-find-and-replace-invalid-regex' ) : ''
470 );
471 return;
472 }
473
474 if ( this.focusedSelection ) {
475 const $focusedSelection = surfaceView.getDrawnSelection( 'findResults', this.focusedSelection );
476 if ( $focusedSelection ) {
477 $focusedSelection.removeClass( 've-ce-surface-selections-findResult-focused' );
478 }
479 }
480
481 const selection = this.fragments[ this.focusedIndex ].getSelection();
482 this.startOffset = selection.getCoveringRange().start;
483
484 const $selection = surfaceView.getDrawnSelection( 'findResults', selection );
485 if ( $selection ) {
486 $selection.addClass( 've-ce-surface-selections-findResult-focused' );
487 }
488
489 if ( scrollIntoView ) {
490 surfaceView.getSurface().scrollSelectionIntoView(
491 this.fragments[ this.focusedIndex ].getSelection(),
492 { animate: true }
493 );
494 }
495
496 this.focusedSelection = selection;
497 };
498
499 /**
500 * Focus the dialog
501 */
502 ve.ui.FindAndReplaceDialog.prototype.focus = function () {
503 this.findText.focus().select();
504 };
505
506 /**
507 * Find the selected text on opening
508 */
509 ve.ui.FindAndReplaceDialog.prototype.findSelected = function () {
510 const fragment = this.surface.getModel().getFragment( null, true );
511
512 this.initialFragment = fragment;
513 this.startOffset = ve.getProp( this.initialFragment.getSelection().getRanges(
514 this.initialFragment.getDocument()
515 ), 0, 'start' ) || 0;
516
517 const text = fragment.getText();
518 if ( text && text !== this.findText.getValue() ) {
519 this.findText.setValue( text );
520 }
521
522 this.focus();
523 };
524
525 /**
526 * Find the next result
527 */
528 ve.ui.FindAndReplaceDialog.prototype.findNext = function () {
529 this.focusedIndex = ( this.focusedIndex + 1 ) % this.results;
530 this.highlightFocused( true );
531 };
532
533 /**
534 * Find the previous result
535 */
536 ve.ui.FindAndReplaceDialog.prototype.findPrevious = function () {
537 this.focusedIndex = ( this.focusedIndex + this.results - 1 ) % this.results;
538 this.highlightFocused( true );
539 };
540
541 /**
542 * Handle click events on the replace button
543 */
544 ve.ui.FindAndReplaceDialog.prototype.onReplaceButtonClick = function () {
545 if ( !this.results ) {
546 return;
547 }
548
549 this.replace( this.focusedIndex );
550
551 // Find the next fragment after this one ends. Ensures that if we replace
552 // 'foo' with 'foofoo' we don't select the just-inserted text.
553 const end = this.fragments[ this.focusedIndex ].getSelection().getRange().end;
554
555 this.updateFragments();
556
557 while ( this.fragments[ this.focusedIndex ] && this.fragments[ this.focusedIndex ].getSelection().getRange().end <= end ) {
558 this.focusedIndex++;
559 }
560 // We may have iterated off the end, or run out of results
561 this.focusedIndex = this.results ? this.focusedIndex % this.results : 0;
562
563 this.renderFragments();
564
565 // Wherever we end up, scroll to whatever we've got focused
566 this.highlightFocused( true );
567 };
568
569 /**
570 * Handle click events on the previous all button
571 */
572 ve.ui.FindAndReplaceDialog.prototype.onReplaceAllButtonClick = function () {
573 const surfaceView = this.surface.getView(),
574 wasActivated = !surfaceView.isDeactivated();
575
576 if ( wasActivated ) {
577 surfaceView.deactivate();
578 }
579 for ( let i = 0, l = this.results; i < l; i++ ) {
580 this.replace( i );
581 }
582 if ( wasActivated ) {
583 surfaceView.activate();
584 }
585
586 this.updateFragments();
587 this.renderFragments();
588 };
589
590 /**
591 * Replace the result at a specified index
592 *
593 * @param {number} index Index to replace
594 */
595 ve.ui.FindAndReplaceDialog.prototype.replace = function ( index ) {
596 const replace = this.replaceText.getValue();
597
598 // Prevent replace from triggering throttled redraws
599 this.replacing = true;
600
601 if ( this.query instanceof RegExp ) {
602 this.fragments[ index ].insertContent(
603 this.fragments[ index ].getText().replace( this.query, replace ),
604 true
605 );
606 } else {
607 this.fragments[ index ].insertContent( replace, true );
608 }
609
610 // 'position' event is deferred, so block that too
611 setTimeout( () => {
612 this.replacing = false;
613 } );
614 };
615
616 /**
617 * @inheritdoc
618 */
619 ve.ui.FindAndReplaceDialog.prototype.getActionProcess = function ( action ) {
620 if ( action === 'findSelected' || action === 'findNext' || action === 'findPrevious' ) {
621 return new OO.ui.Process( this[ action ], this );
622 }
623 return ve.ui.FindAndReplaceDialog.super.prototype.getActionProcess.call( this, action );
624 };
625
626 /* Registration */
627
628 ve.ui.windowFactory.register( ve.ui.FindAndReplaceDialog );