Debian Codegraph @

extensions/WikiEditor/modules/realtimepreview/RealtimePreview.js

raw symbols SCIP
1 var ResizingDragBar = require( './ResizingDragBar.js' );
2 var TwoPaneLayout = require( './TwoPaneLayout.js' );
3 var ErrorLayout = require( './ErrorLayout.js' );
4 var ManualWidget = require( './ManualWidget.js' );
5 var localStorage = require( 'mediawiki.storage' ).local;
6
7 /**
8 * @class
9 */
10 function RealtimePreview() {
11 this.configData = mw.loader.moduleRegistry[ 'ext.wikiEditor' ].script.files[ 'data.json' ];
12 // Preference name, must match what's in extension.json and Hooks.php.
13 this.prefName = 'wikieditor-realtimepreview';
14 this.userPref = this.getUserPref();
15 this.enabled = this.userPref;
16 this.twoPaneLayout = new TwoPaneLayout();
17 this.pagePreview = require( 'mediawiki.page.preview' );
18 // @todo This shouldn't be required, but the preview element is added in PHP
19 // and can have attributes with values (such as `dir`) that aren't easily accessible from here,
20 // and we need to duplicate here what Live Preview does in core.
21 var $previewContent = $( '#wikiPreview .mw-content-ltr, #wikiPreview .mw-content-rtl' ).first().clone();
22 this.$previewNode = $( '<div>' )
23 .addClass( 'ext-WikiEditor-realtimepreview-preview' )
24 .attr( 'tabindex', '1' ) // T317108
25 .append( $previewContent );
26
27 // Loading bar.
28 this.$loadingBar = $( '<div>' ).addClass( 'ext-WikiEditor-realtimepreview-loadingbar' ).append( '<div>' );
29 this.$loadingBar.hide();
30
31 // Error layout.
32 this.errorLayout = new ErrorLayout();
33 this.errorLayout.getReloadButton().connect( this, {
34 click: function () {
35 this.doRealtimePreview( true );
36 mw.hook( 'ext.WikiEditor.realtimepreview.reloadError' ).fire( this );
37 }.bind( this )
38 } );
39
40 // Manual reload button (visible on hover).
41 this.reloadButton = new OO.ui.ButtonWidget( {
42 classes: [ 'ext-WikiEditor-reloadButton' ],
43 icon: 'reload',
44 label: mw.msg( 'wikieditor-realtimepreview-reload' ),
45 accessKey: mw.msg( 'accesskey-wikieditor-realtimepreview' ),
46 title: mw.msg( 'wikieditor-realtimepreview-reload-title' )
47 } );
48 this.reloadButton.connect( this, {
49 click: function () {
50 // Only refresh the preview if we're enabled.
51 if ( this.enabled ) {
52 this.doRealtimePreview( true );
53 }
54 // Let other things happen after refreshing.
55 mw.hook( 'ext.WikiEditor.realtimepreview.reloadHover' ).fire( this );
56 }.bind( this )
57 } );
58
59 // Manual mode widget.
60 this.manualWidget = new ManualWidget( this, this.reloadButton );
61 // Set up a property for reducedMotion — useful for customising the UI message.
62 this.reducedMotion = window.matchMedia( '(prefers-reduced-motion: reduce)' ).matches;
63 // If the user has "prefers-reduced-motion" set, force us into manual mode.
64 this.inManualMode = this.reducedMotion;
65
66 this.twoPaneLayout.getPane2().append( this.manualWidget.$element, this.reloadButton.$element, this.$loadingBar, this.$previewNode, this.errorLayout.$element );
67 this.eventNames = 'change.realtimepreview input.realtimepreview cut.realtimepreview paste.realtimepreview';
68 // Used to ensure we wait for a response before making new requests.
69 this.isPreviewing = false;
70 this.previewPending = false;
71 this.lastWikitext = null;
72 // Used to average response times and automatically disable realtime preview if it's very slow.
73 this.responseTimes = [];
74 }
75
76 /**
77 * @public
78 * @param {Object} context The WikiEditor context.
79 * @return {jQuery}
80 */
81 RealtimePreview.prototype.getToolbarButton = function ( context ) {
82 this.context = context;
83 var $uiText = context.$ui.find( '.wikiEditor-ui-text' );
84
85 // Fix the height of the textarea, before adding a resizing bar below it.
86 var height = context.$textarea.height();
87 $uiText.css( 'height', height + 'px' );
88 context.$textarea.removeAttr( 'rows cols' );
89 context.$textarea.addClass( 'ext-WikiEditor-realtimepreview-textbox' );
90
91 // Add the resizing bar.
92 var bottomDragBar = new ResizingDragBar( { isEW: false } );
93 $uiText.after( bottomDragBar.$element );
94
95 // Create and configure the toolbar button.
96 this.button = new OO.ui.ToggleButtonWidget( {
97 label: mw.msg( 'wikieditor-realtimepreview-preview' ),
98 icon: 'article',
99 value: this.enabled,
100 framed: false,
101 // T305953; So we can find usage of this class later: .tool
102 classes: [ 'tool', 'ext-WikiEditor-realtimepreview-button' ]
103 } );
104 this.button.connect( this, { change: [ this.toggle, true ] } );
105 if ( !this.isScreenWideEnough() ) {
106 this.enabled = false;
107 this.button.toggle( false );
108 }
109
110 // Hide or show the preview and toolbar button when the window is resized.
111 $( window ).on( 'resize', this.enableFeatureWhenScreenIsWideEnough.bind( this ) );
112
113 // Remove the old onboarding-status storage that was discontinued in March 2023.
114 localStorage.remove( 'WikiEditor-RealtimePreview-onboarding-dismissed' );
115
116 return $( '<div>' ).append( this.button.$element );
117 };
118
119 /**
120 * Get the user preference for Realtime Preview.
121 *
122 * @public
123 * @return {boolean}
124 */
125 RealtimePreview.prototype.getUserPref = function () {
126 return ( typeof this.userPref !== 'undefined' ) ? this.userPref : mw.user.options.get( this.prefName ) > 0;
127 };
128
129 /**
130 * Enable or disable Realtime Preview.
131 *
132 * @param {boolean} [enable=true] Whether to enable or disable.
133 * @param {boolean} [saveUserPref=true] Whether to save the user preference.
134 * @public
135 */
136 RealtimePreview.prototype.setEnabled = function ( enable, saveUserPref ) {
137 // Set this.enabled to the opposite of what we want, and then toggle it to the desired state.
138 this.enabled = ( typeof enable === 'boolean' ) ? !enable : false;
139 this.toggle( saveUserPref );
140 };
141
142 /**
143 * Save the user preference for Realtime Preview.
144 *
145 * @private
146 */
147 RealtimePreview.prototype.saveUserPref = function () {
148 this.userPref = this.enabled ? 1 : 0;
149 ( new mw.Api() ).saveOption( this.prefName, this.userPref );
150 };
151
152 /**
153 * Toggle the two-pane preview display.
154 *
155 * @param {boolean} [saveUserPref=true] Whether to save the user preference.
156 * @private
157 */
158 RealtimePreview.prototype.toggle = function ( saveUserPref ) {
159 var $uiText = this.context.$ui.find( '.wikiEditor-ui-text' );
160 var $textarea = this.context.$textarea;
161 var $form = $textarea.parents( 'form' );
162
163 // Save the current cursor selection and focused element.
164 var cursorPos = $textarea.textSelection( 'getCaretPosition', { startAndEnd: true } );
165 var focusedElement = document.activeElement;
166
167 // Remove or add the layout to the DOM.
168 if ( this.enabled ) {
169 // Move height from the TwoPaneLayout to the text UI div.
170 $uiText.css( 'height', this.twoPaneLayout.$element.height() + 'px' );
171
172 // Put the text div back to being after the layout, and then hide the layout.
173 this.twoPaneLayout.$element.after( $uiText );
174 this.twoPaneLayout.$element.hide();
175
176 // Remove the keyup handler.
177 $textarea.off( this.eventNames );
178 $form.off( 'reset.realtimepreview' );
179
180 // Let other things happen after disabling.
181 mw.hook( 'ext.WikiEditor.realtimepreview.disable' ).fire( this );
182
183 } else {
184 // Add the layout before the text div of the UI and then move the text div into it.
185 $uiText.before( this.twoPaneLayout.$element );
186 this.twoPaneLayout.setPane1( $uiText );
187 this.twoPaneLayout.$element.show();
188
189 // Move explicit height from text-ui (which may have been set via manual resizing), to panes.
190 this.twoPaneLayout.$element.css( 'height', $uiText.height() + 'px' );
191 $uiText.css( 'height', '100%' );
192
193 // Load the preview when enabling,
194 this.doRealtimePreview();
195 // and also on keyup, change, paste etc.
196 $textarea
197 .off( this.eventNames )
198 .on( this.eventNames, this.getEventHandler() );
199 $form.off( 'reset.realtimepreview' )
200 .on( 'reset.realtimepreview', this.getEventHandler() );
201
202 // Hide or show the manual-reload message bar.
203 this.manualWidget.toggle( this.inManualMode );
204
205 // Let other things happen after enabling.
206 mw.hook( 'ext.WikiEditor.realtimepreview.enable' ).fire( this );
207 }
208
209 // Restore current selection.
210 $textarea.textSelection( 'setSelection', { start: cursorPos[ 0 ], end: cursorPos[ 1 ] } );
211 $textarea.textSelection( 'scrollToCaretPosition' );
212 // Focus on whatever had focus before, in case it wasn't the textarea.
213 focusedElement.focus();
214
215 // Record the toggle state and update the button.
216 this.enabled = !this.enabled;
217 this.button.$element.toggleClass( 'tool-active', this.enabled ); // T305953
218 this.button.setFlags( { progressive: this.enabled } );
219
220 if ( typeof saveUserPref === 'undefined' || ( typeof saveUserPref === 'boolean' && saveUserPref ) ) {
221 this.saveUserPref();
222 }
223 };
224
225 /**
226 * @public
227 * @return {Function}
228 */
229 RealtimePreview.prototype.getEventHandler = function () {
230 return mw.util.debounce(
231 function () {
232 // Only do preview if we're not in manual mode (as set in this.checkResponseTimes()).
233 if ( !this.inManualMode ) {
234 this.doRealtimePreview();
235 }
236 }.bind( this ),
237 this.configData.realtimeDebounce
238 );
239 };
240
241 /**
242 * Check if screen meets minimum width requirement for Realtime Preview.
243 *
244 * @public
245 * @return {boolean}
246 */
247 RealtimePreview.prototype.isScreenWideEnough = function () {
248 return this.context.$ui.width() > 600;
249 };
250
251 /**
252 * Display feature (buttons and functionality) only when screen is wide enough
253 *
254 * @private
255 */
256 RealtimePreview.prototype.enableFeatureWhenScreenIsWideEnough = function () {
257 var previewButtonIsVisible = this.button.isVisible();
258 var isScreenWideEnough = this.isScreenWideEnough();
259 if ( !isScreenWideEnough && previewButtonIsVisible ) {
260 this.button.toggle( false );
261 this.reloadButton.setDisabled( true );
262 if ( this.enabled ) {
263 this.setEnabled( false, false );
264 }
265 } else if ( isScreenWideEnough && !previewButtonIsVisible ) {
266 this.button.toggle( true );
267 this.reloadButton.setDisabled( false );
268 // if user preference and realtime disable
269 if ( !this.enabled && this.getUserPref() ) {
270 this.setEnabled( true, false );
271 }
272 }
273 };
274
275 /**
276 * @private
277 * @param {jQuery} $msg
278 */
279 RealtimePreview.prototype.showError = function ( $msg ) {
280 this.$previewNode.hide();
281 this.reloadButton.toggle( false );
282 this.manualWidget.toggle( false );
283 // There is no need for a default message because mw.Api.getErrorMessage() will
284 // always provide something (even for no network connection, server-side fatal errors, etc.).
285 this.errorLayout.setMessage( $msg );
286 this.errorLayout.toggle( true );
287 };
288
289 /**
290 * @private
291 * @param {number} time
292 */
293 RealtimePreview.prototype.checkResponseTimes = function ( time ) {
294 // Don't track response times if we're already in manual mode or an error is shown.
295 if ( this.inManualMode || this.errorLayout.isVisible() ) {
296 return;
297 }
298
299 this.responseTimes.push( Date.now() - time );
300 if ( this.responseTimes.length < 3 ) {
301 return;
302 }
303
304 var totalResponseTime = this.responseTimes.reduce( function ( a, b ) {
305 return a + b;
306 }, 0 );
307
308 if ( ( totalResponseTime / this.responseTimes.length ) > this.configData.realtimeDisableDuration ) {
309 this.inManualMode = true;
310 this.manualWidget.toggle( true );
311 mw.hook( 'ext.WikiEditor.realtimepreview.stop' ).fire( this );
312 }
313
314 this.responseTimes.shift();
315 };
316
317 /**
318 * @private
319 * @param {boolean} forceUpdate For the preview to update, even if the wikitext is unchanged,
320 * e.g. when the user presses the 'reload' button.
321 */
322 RealtimePreview.prototype.doRealtimePreview = function ( forceUpdate ) {
323 // Wait for a response before making any new requests.
324 if ( this.isPreviewing ) {
325 // Queue up one final preview once this one finishes.
326 this.previewPending = true;
327 return;
328 }
329
330 var $textareaNode = $( '#wpTextbox1' );
331 var wikitext = $textareaNode.textSelection( 'getContents' );
332 if ( !forceUpdate && wikitext === this.lastWikitext ) {
333 // Wikitext unchanged, no update necessary
334 return;
335 }
336 this.lastWikitext = wikitext;
337
338 this.isPreviewing = true;
339 this.$loadingBar.show();
340 this.$previewNode.show();
341 this.reloadButton.setDisabled( true );
342 this.manualWidget.setDisabled( true );
343 this.errorLayout.toggle( false );
344 var loadingSelectors = this.pagePreview.getLoadingSelectors()
345 // config.$previewNode below is a clone of #wikiPreview with a different selector!
346 // config.$diffNode defaults to #wikiDiff but is disabled below and never updated.
347 .filter( function ( selector ) {
348 return selector.indexOf( '#wiki' ) !== 0;
349 } );
350 loadingSelectors.push( '.ext-WikiEditor-realtimepreview-preview' );
351 loadingSelectors.push( '.ext-WikiEditor-ManualWidget' );
352 loadingSelectors.push( '.ext-WikiEditor-realtimepreview-ErrorLayout' );
353 var time = Date.now();
354
355 this.pagePreview.doPreview( {
356 $textareaNode: $textareaNode,
357 $previewNode: this.$previewNode,
358 $spinnerNode: false,
359 loadingSelectors: loadingSelectors,
360 // Don't hide the diff view, if visible.
361 $diffNode: null
362 } ).done( function () {
363 this.errorLayout.toggle( false );
364 }.bind( this ) ).fail( function ( code, result ) {
365 this.showError( ( new mw.Api() ).getErrorMessage( result ) );
366 mw.log.error( 'WikiEditor realtime preview error', result );
367 }.bind( this ) ).always( function () {
368 this.$loadingBar.hide();
369 this.reloadButton.setDisabled( false );
370 if ( !this.errorLayout.isVisible() ) {
371 // Only re-show the reload button if no error message is currently showing.
372 this.reloadButton.toggle( true );
373 }
374 // Show the manual mode if applicable (but not if an error is displayed).
375 this.manualWidget.toggle( this.inManualMode && !this.errorLayout.isVisible() );
376 this.manualWidget.setDisabled( false );
377 this.isPreviewing = false;
378 this.checkResponseTimes( time );
379
380 if ( this.previewPending ) {
381 this.previewPending = false;
382 this.doRealtimePreview();
383 }
384 mw.hook( 'ext.WikiEditor.realtimepreview.loaded' ).fire( this );
385 }.bind( this ) );
386 };
387
388 module.exports = RealtimePreview;