Merge "RELEASE-NOTES: Don't imply that HHVM 3.1 is supported"
[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 if ( !mw.config.get( 'wgAjaxEditStash' ) ) {
6 return;
7 }
8
9 $( function () {
10 var idleTimeout = 3000,
11 api = new mw.Api(),
12 pending = null,
13 $form = $( '#editform' ),
14 $text = $form.find( '#wpTextbox1' ),
15 $summary = $form.find( '#wpSummary' ),
16 data = {},
17 timer = null;
18
19 // Send a request to stash the edit to the API.
20 // If a request is in progress, abort it since its payload is stale and the API
21 // may limit concurrent stash parses.
22 function stashEdit() {
23 if ( pending ) {
24 pending.abort();
25 }
26
27 api.getToken( 'csrf' ).then( function ( token ) {
28 data = $form.serializeObject();
29
30 pending = api.post( {
31 action: 'stashedit',
32 token: token,
33 title: mw.config.get( 'wgPageName' ),
34 section: data.wpSection,
35 sectiontitle: '',
36 text: data.wpTextbox1,
37 summary: data.wpSummary,
38 contentmodel: data.model,
39 contentformat: data.format,
40 baserevid: data.parentRevId
41 } );
42 } );
43 }
44
45 // Check if edit body text changed since the last stashEdit() call or if no edit
46 // stash calls have yet been made
47 function isChanged() {
48 // Normalize line endings to CRLF, like $.fn.serializeObject does.
49 var newText = $text.val().replace( /\r?\n/g, '\r\n' );
50 return newText !== data.wpTextbox1;
51 }
52
53 function onEditorIdle() {
54 if ( !isChanged() ) {
55 return;
56 }
57
58 stashEdit();
59 }
60
61 function onTextKeyUp( e ) {
62 // Ignore keystrokes that don't modify text, like cursor movements.
63 // See <http://www.javascripter.net/faq/keycodes.htm> and
64 // <http://www.quirksmode.org/js/keys.html>. We don't have to be
65 // exhaustive, because the cost of misfiring is low.
66 if ( ( e.which >= 33 && e.which <= 40 ) || ( e.which >= 16 && e.which <= 18 ) ) {
67 return;
68 }
69
70 clearTimeout( timer );
71 timer = setTimeout( onEditorIdle, idleTimeout );
72 }
73
74 function onFormLoaded() {
75 if (
76 // Reverts may involve use (undo) links; stash as they review the diff.
77 // Since the form has a pre-filled summary, stash the edit immediately.
78 mw.util.getParamValue( 'undo' ) !== null
79 // Pressing "show changes" and "preview" also signify that the user will
80 // probably save the page soon
81 || $.inArray( $form.find( '#mw-edit-mode' ).val(), [ 'preview', 'diff' ] ) > -1
82 ) {
83 stashEdit();
84 }
85 }
86
87 // We don't attempt to stash new section edits because in such cases
88 // the parser output varies on the edit summary (since it determines
89 // the new section's name).
90 if ( $form.find( 'input[name=wpSection]' ).val() === 'new' ) {
91 return;
92 }
93
94 $text.on( { change: onEditorIdle, keyup: onTextKeyUp } );
95 $summary.on( { focus: onEditorIdle } );
96 onFormLoaded();
97
98 } );
99 }( mediaWiki, jQuery ) );