29c533d89a4080c64f4dfaf684791256fecb6dc6
[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 = 4000,
7 api = new mw.Api(),
8 pending = null,
9 $form = $( '#editform' ),
10 $text = $form.find( '#wpTextbox1' ),
11 data = {},
12 timer = null;
13
14 function stashEdit( token ) {
15 data = $form.serializeObject();
16
17 pending = api.post( {
18 action: 'stashedit',
19 token: token,
20 title: mw.config.get( 'wgPageName' ),
21 section: data.wpSection,
22 sectiontitle: '',
23 text: data.wpTextbox1,
24 contentmodel: data.model,
25 contentformat: data.format,
26 baserevid: data.parentRevId
27 } );
28 }
29
30 /* Has the edit body text changed since the last stashEdit() call? */
31 function isChanged() {
32 // Normalize line endings to CRLF, like $.fn.serializeObject does.
33 var newText = $text.val().replace( /\r?\n/g, '\r\n' );
34 return newText !== data.wpTextbox1;
35 }
36
37 function onEditChanged() {
38 if ( !isChanged() ) {
39 return;
40 }
41
42 // If a request is in progress, abort it; its payload is stale.
43 if ( pending ) {
44 pending.abort();
45 }
46
47 api.getToken( 'edit' ).then( stashEdit );
48 }
49
50 function onKeyPress( e ) {
51 // Ignore keystrokes that don't modify text, like cursor movements.
52 // See <http://stackoverflow.com/q/2284844>.
53 if ( e.which === 0 ) {
54 return;
55 }
56
57 clearTimeout( timer );
58
59 if ( pending ) {
60 pending.abort();
61 }
62
63 timer = setTimeout( onEditChanged, idleTimeout );
64 }
65
66 // We don't attempt to stash new section edits because in such cases
67 // the parser output varies on the edit summary (since it determines
68 // the new section's name).
69 if ( $form.find( 'input[name=wpSection]' ).val() === 'new' ) {
70 return;
71 }
72
73 $text.on( { change: onEditChanged, keypress: onKeyPress } );
74
75 } );
76 }( mediaWiki, jQuery ) );