Perform edit stashing for ?undo and ?oldid reverts
[lhc/web/wiklou.git] / resources / src / mediawiki.action / mediawiki.action.edit.stash.js
1 /*!
2 * Scripts for pre-emptive edit preparing on action=edit
3 */
4 ( function ( mw, $ ) {
5 $( function () {
6 var idleTimeout = 3000,
7 api = new mw.Api(),
8 pending = null,
9 $form = $( '#editform' ),
10 $text = $form.find( '#wpTextbox1' ),
11 $summary = $form.find( '#wpSummary' ),
12 data = {},
13 timer = null;
14
15 // Send a request to stash the edit to the API.
16 // If a request is in progress, abort it since its payload is stale and the API
17 // may limit concurrent stash parses.
18 function stashEdit() {
19 if ( pending ) {
20 pending.abort();
21 }
22
23 api.getToken( 'csrf' ).then( function ( token ) {
24 data = $form.serializeObject();
25
26 pending = api.post( {
27 action: 'stashedit',
28 token: token,
29 title: mw.config.get( 'wgPageName' ),
30 section: data.wpSection,
31 sectiontitle: '',
32 text: data.wpTextbox1,
33 contentmodel: data.model,
34 contentformat: data.format,
35 baserevid: data.parentRevId
36 } );
37 } );
38 }
39
40 // Check if edit body text changed since the last stashEdit() call or if no edit
41 // stash calls have yet been made
42 function isChanged() {
43 // Normalize line endings to CRLF, like $.fn.serializeObject does.
44 var newText = $text.val().replace( /\r?\n/g, '\r\n' );
45 return newText !== data.wpTextbox1;
46 }
47
48 function onTextChanged() {
49 if ( !isChanged() ) {
50 return;
51 }
52
53 stashEdit();
54 }
55
56 function onTextKeyPress( e ) {
57 // Ignore keystrokes that don't modify text, like cursor movements.
58 // See <http://stackoverflow.com/q/2284844>.
59 if ( e.which === 0 ) {
60 return;
61 }
62
63 clearTimeout( timer );
64
65 if ( pending ) {
66 pending.abort();
67 }
68
69 timer = setTimeout( onTextChanged, idleTimeout );
70 }
71
72 function onFormLoaded() {
73 // Reverts may involve use (undo) links; stash as they review the diff.
74 // Since the form has a pre-filled summary, stash the edit immediately.
75 if ( mw.util.getParamValue( 'undo' ) !== null ) {
76 stashEdit();
77 }
78 }
79
80 // We don't attempt to stash new section edits because in such cases
81 // the parser output varies on the edit summary (since it determines
82 // the new section's name).
83 if ( $form.find( 'input[name=wpSection]' ).val() === 'new' ) {
84 return;
85 }
86
87 $text.on( { change: onTextChanged, keypress: onTextKeyPress } );
88 $summary.on( { focus: onTextChanged } );
89 onFormLoaded();
90
91 } );
92 }( mediaWiki, jQuery ) );