Debian Codegraph @

resources/src/mediawiki.editRecovery/edit.js

raw symbols SCIP
1 /**
2 * In-progress edit recovery for action=edit
3 */
4 'use strict';
5
6 const storage = require( './storage.js' );
7 const LoadNotification = require( './LoadNotification.js' );
8
9 const pageName = mw.config.get( 'wgPageName' );
10 const section = $( 'input[name="wpSection"]' ).val() || null;
11 const inputFields = {};
12 const fieldNamePrefix = 'field_';
13 let originalData = {};
14 let changeDebounceTimer = null;
15
16 // Number of miliseconds to debounce form input.
17 const debounceTime = 5000;
18
19 // This module is loaded for every edit form, but not all should have Edit Recovery functioning.
20 const wasPosted = mw.config.get( 'wgEditRecoveryWasPosted' );
21 const isUndo = $( 'input[name="wpUndoAfter"]' ).length > 0;
22 const isOldRevision = $( 'input[name="oldid"]' ).val() > 0;
23 const isConflict = mw.config.get( 'wgEditMessage' ) === 'editconflict';
24 const useEditRecovery = !isUndo && !isOldRevision && !isConflict;
25 if ( useEditRecovery ) {
26 mw.hook( 'wikipage.editform' ).add( onLoadHandler );
27 } else {
28 // Always remove the data-saved flag when editing without Edit Recovery.
29 // It may have been set by a previous editing session (within 5 minutes) that did use ER.
30 mw.storage.session.remove( 'EditRecovery-data-saved' );
31 }
32
33 const windowManager = OO.ui.getWindowManager();
34 windowManager.addWindows( [ new mw.widgets.AbandonEditDialog() ] );
35
36 function onLoadHandler( $editForm ) {
37 mw.hook( 'wikipage.editform' ).remove( onLoadHandler );
38
39 // Monitor all text-entry inputs for changes/typing.
40 const inputsToMonitorSelector = 'textarea, select, input:not([type="hidden"], [type="submit"])';
41 const $inputsToMonitor = $editForm.find( inputsToMonitorSelector );
42 $inputsToMonitor.each( ( _i, field ) => {
43 if ( field.classList.contains( 'oo-ui-inputWidget-input' ) ) {
44 try {
45 inputFields[ field.name ] = OO.ui.infuse( field.closest( '.oo-ui-widget' ) );
46 } catch ( e ) {
47 // Ignore any non-infusable widget because we won't be able to set its value.
48 }
49 } else {
50 inputFields[ field.name ] = field;
51 }
52 } );
53 // Save the contents of all of those, as well as the following hidden inputs.
54 const inputsToSaveNames = [ 'wpSection', 'editRevId', 'oldid', 'parentRevId', 'format', 'model' ];
55 const $inputsToSave = $editForm.find( '[name="' + inputsToSaveNames.join( '"], [name="' ) + '"]' );
56 $inputsToSave.each( ( _i, field ) => {
57 inputFields[ field.name ] = field;
58 } );
59
60 // Store the original data for later comparing to the data-to-save. Use the defaultValue/defaultChecked in order to
61 // avoid using any data remembered by the browser. Note that we have to be careful to store with the same types as
62 // it will be done later, in order to correctly compare it (e.g. checkboxes as booleans).
63 Object.keys( inputFields ).forEach( ( fieldName ) => {
64 const field = inputFields[ fieldName ];
65 if ( field.nodeName === 'INPUT' || field.nodeName === 'TEXTAREA' ) {
66 if ( field.type === 'checkbox' ) {
67 // Checkboxes (Minoredit and Watchthis are handled below as they are OOUI widgets).
68 originalData[ fieldNamePrefix + fieldName ] = field.defaultChecked;
69 } else {
70 // Other HTMLInputElements.
71 originalData[ fieldNamePrefix + fieldName ] = field.defaultValue;
72 }
73 } else if ( field.$input !== undefined ) {
74 // OOUI widgets, which may not have been infused by this point.
75 if ( field.$input[ 0 ].type === 'checkbox' ) {
76 // Checkboxes.
77 originalData[ fieldNamePrefix + fieldName ] = field.$input[ 0 ].defaultChecked;
78 } else {
79 // Other OOUI widgets.
80 originalData[ fieldNamePrefix + fieldName ] = field.$input[ 0 ].defaultValue;
81 }
82 }
83 } );
84
85 // Set a short-lived (5m / see postEdit.js) localStorage item to indicate which section is being edited.
86 if ( section ) {
87 mw.storage.session.set( pageName + '-editRecoverySection', section, 300 );
88 }
89 // Open indexedDB database and load any saved data that might be there.
90 storage.openDatabase().then( () => {
91 // Check for and delete any expired data for any page, before loading any saved data for the current page.
92 storage.deleteExpiredData().then( () => {
93 storage.loadData( pageName, section ).then( onLoadData );
94 } );
95 } );
96
97 // Set up cancel handler to delete data.
98 const cancelButton = OO.ui.infuse( $editForm.find( '#mw-editform-cancel' )[ 0 ] );
99 cancelButton.on( 'click', () => {
100 windowManager.openWindow( 'abandonedit' ).closed.then( ( data ) => {
101 if ( data && data.action === 'discard' ) {
102 // Note that originalData is used below in onLoadData() but that's always called before this method.
103 // Here we set originalData to null in order to signal to saveFormData() to deleted the stored data.
104 originalData = null;
105 storage.deleteData( pageName, section ).finally( () => {
106 mw.storage.session.remove( pageName + '-editRecoverySection' );
107 // Release the beforeunload handler from mediawiki.action.edit.editWarning,
108 // per the documentation there
109 $( window ).off( 'beforeunload.editwarning' );
110 location.href = cancelButton.getHref();
111 } );
112 }
113 } );
114 } );
115 }
116
117 function track( metric, value ) {
118 const dbName = mw.config.get( 'wgDBname' );
119 mw.track( `counter.MediaWiki.edit_recovery.${ metric }.by_wiki.${ dbName }`, value );
120 }
121
122 function onLoadData( pageData ) {
123 if ( wasPosted ) {
124 // If this is a POST request, save the current data (e.g. from a preview).
125 saveFormData();
126 }
127 // If there is data stored, load it into the form.
128 if ( !wasPosted && pageData !== undefined && !isSameAsOriginal( pageData, true ) ) {
129 const loadNotification = new LoadNotification( {
130 differentRev: originalData.field_parentRevId !== pageData.field_parentRevId
131 } );
132
133 // statsv: Track the number of times the edit recovery notification is shown.
134 track( 'show', 1 );
135
136 const notification = loadNotification.getNotification();
137 // On 'restore changes'.
138 loadNotification.getRecoverButton().on( 'click', () => {
139 loadData( pageData );
140 notification.close();
141 // statsv: Track the number of times the edit recovery data is recovered.
142 track( 'recover', 1 );
143 } );
144 // On 'discard changes'.
145 loadNotification.getDiscardButton().on( 'click', () => {
146 loadData( originalData );
147 storage.deleteData( pageName, section ).then( () => {
148 notification.close();
149 } );
150 // statsv: Track the number of times the edit recovery data is discarded.
151 track( 'discard', 1 );
152 } );
153 }
154
155 // Add change handlers.
156 Object.keys( inputFields ).forEach( ( fieldName ) => {
157 const field = inputFields[ fieldName ];
158 if ( field.nodeName !== undefined && field.nodeName === 'TEXTAREA' ) {
159 field.addEventListener( 'input', fieldChangeHandler );
160 } else if ( field instanceof OO.ui.Widget ) {
161 field.on( 'change', fieldChangeHandler );
162 } else {
163 field.addEventListener( 'change', fieldChangeHandler );
164 }
165 } );
166 // Also add handlers for when the window is closed or hidden. Saving the data at these points is not guaranteed to
167 // work, but it often does and the save operation is atomic so there's no harm in trying.
168 window.addEventListener( 'beforeunload', saveFormData );
169 window.addEventListener( 'blur', saveFormData );
170
171 /**
172 * Fired after EditRecovery has loaded any recovery data, added event handlers, etc.
173 *
174 * @event ~'editRecovery.loadEnd'
175 * @memberof Hooks
176 * @param {Object} editRecovery
177 * @param {Function} editRecovery.fieldChangeHandler
178 */
179 mw.hook( 'editRecovery.loadEnd' ).fire( { fieldChangeHandler: fieldChangeHandler } );
180 }
181
182 function loadData( pageData ) {
183 Object.keys( inputFields ).forEach( ( fieldName ) => {
184 if ( pageData[ fieldNamePrefix + fieldName ] === undefined ) {
185 return;
186 }
187 const field = inputFields[ fieldName ];
188 const $field = $( field );
189 // Set the field value depending on what type of field it is.
190 if ( field instanceof OO.ui.CheckboxInputWidget ) {
191 // OOUI checkbox widgets.
192 field.setSelected( pageData[ fieldNamePrefix + fieldName ] );
193 } else if ( field instanceof OO.ui.Widget ) {
194 // Other OOUI widgets.
195 field.setValue( pageData[ fieldNamePrefix + fieldName ], field );
196 } else if ( field.nodeName === 'TEXTAREA' ) {
197 // Textareas (also reset caret location to top).
198 $field.textSelection( 'setContents', pageData[ fieldNamePrefix + fieldName ] );
199 $field.textSelection( 'setSelection', { start: 0 } );
200 } else {
201 // Anything else.
202 field.value = pageData[ fieldNamePrefix + fieldName ];
203 }
204 } );
205 }
206
207 function fieldChangeHandler() {
208 clearTimeout( changeDebounceTimer );
209 changeDebounceTimer = setTimeout( saveFormData, debounceTime );
210 }
211
212 /**
213 * Compare a set of form field values to their original values (as at page load time).
214 *
215 * @ignore
216 * @param {Object} pageData The page data to compare to the original.
217 * @param {boolean} [ignoreRevIds=false] Do not use parent revision info when determining similarity.
218 * @return {boolean}
219 */
220 function isSameAsOriginal( pageData, ignoreRevIds = false ) {
221 for ( const fieldName in inputFields ) {
222 if ( ignoreRevIds && ( fieldName === 'editRevId' || fieldName === 'parentRevId' ) ) {
223 continue;
224 }
225 // Trim trailing whitespace from string fields, to approximate what PHP does when saving.
226 let currentVal = pageData[ fieldNamePrefix + fieldName ];
227 if ( typeof currentVal === 'string' ) {
228 currentVal = currentVal.replace( /\s+$/, '' );
229 }
230 let originalVal = originalData[ fieldNamePrefix + fieldName ];
231 if ( typeof originalVal === 'string' ) {
232 originalVal = originalVal.replace( /\s+$/, '' );
233 }
234 if ( currentVal !== originalVal ) {
235 return false;
236 }
237 }
238 return true;
239 }
240
241 function saveFormData() {
242 const pageData = getFormData();
243 if ( ( originalData === null || isSameAsOriginal( pageData ) ) && !wasPosted ) {
244 // Delete the stored data if there's no change,
245 // or if we've flagged originalData as irrelevant,
246 // or if we can't determine this because this page was POSTed.
247 storage.deleteData( pageName, section );
248 mw.storage.session.remove( 'EditRecovery-data-saved' );
249 } else {
250 storage.saveData( pageName, section, pageData );
251 // Flag the data for deletion in the postEdit handler in ./postEdit.js
252 mw.storage.session.set( 'EditRecovery-data-saved', true, 300 );
253 }
254 }
255
256 /**
257 * Get the current form data.
258 *
259 * @ignore
260 * @return {Object}
261 */
262 function getFormData() {
263 const formData = {};
264 Object.keys( inputFields ).forEach( ( fieldName ) => {
265 const field = inputFields[ fieldName ];
266 let newValue = null;
267 if ( !( field instanceof OO.ui.Widget ) && field.nodeName !== undefined && field.nodeName === 'TEXTAREA' ) {
268 // Text areas.
269 newValue = $( field ).textSelection( 'getContents' );
270 } else if ( field instanceof OO.ui.CheckboxInputWidget ) {
271 // OOUI checkbox widgets.
272 newValue = field.isSelected();
273 } else if ( field instanceof OO.ui.Widget ) {
274 // Other OOUI widgets.
275 newValue = field.getValue();
276 } else {
277 // Anything else.
278 newValue = field.value;
279 }
280 formData[ fieldNamePrefix + fieldName ] = newValue;
281 } );
282 return formData;
283 }