Merge "Sync up with Parsoid parserTests.txt"
[lhc/web/wiklou.git] / resources / src / mediawiki.action / mediawiki.action.edit.preview.js
1 /*!
2 * Live edit preview.
3 */
4 ( function ( mw, $ ) {
5
6 /**
7 * @ignore
8 * @param {jQuery.Event} e
9 */
10 function doLivePreview( e ) {
11 var isDiff, api, parseRequest, diffRequest, postData, copySelectors, section,
12 $wikiPreview, $wikiDiff, $editform, $textbox, $summary, $copyElements, $spinner, $errorBox;
13
14 isDiff = ( e.target.name === 'wpDiff' );
15 $wikiPreview = $( '#wikiPreview' );
16 $wikiDiff = $( '#wikiDiff' );
17 $editform = $( '#editform' );
18 $textbox = $editform.find( '#wpTextbox1' );
19 $summary = $editform.find( '#wpSummary' );
20 $spinner = $( '.mw-spinner-preview' );
21 $errorBox = $( '.errorbox' );
22 section = $editform.find( '[name="wpSection"]' ).val();
23
24 if ( $textbox.length === 0 ) {
25 return;
26 }
27 // Show changes for a new section is not yet supported
28 if ( isDiff && section === 'new' ) {
29 return;
30 }
31 e.preventDefault();
32
33 // Remove any previously displayed errors
34 $errorBox.remove();
35 // Show #wikiPreview if it's hidden to be able to scroll to it
36 // (if it is hidden, it's also empty, so nothing changes in the rendering)
37 $wikiPreview.show();
38
39 // Jump to where the preview will appear
40 $wikiPreview[ 0 ].scrollIntoView();
41
42 copySelectors = [
43 // Main
44 '.mw-indicators',
45 '#firstHeading',
46 '#wikiPreview',
47 '#wikiDiff',
48 '#catlinks',
49 '#p-lang',
50 // Editing-related
51 '.templatesUsed',
52 '.limitreport',
53 '.mw-summary-preview'
54 ];
55 $copyElements = $( copySelectors.join( ',' ) );
56
57 // Not shown during normal preview, to be removed if present
58 $( '.mw-newarticletext' ).remove();
59
60 if ( $spinner.length === 0 ) {
61 $spinner = $.createSpinner( {
62 size: 'large',
63 type: 'block'
64 } )
65 .addClass( 'mw-spinner-preview' )
66 .css( 'margin-top', '1em' );
67 $wikiPreview.before( $spinner );
68 } else {
69 $spinner.show();
70 }
71
72 // Can't use fadeTo because it calls show(), and we might want to keep some elements hidden
73 // (e.g. empty #catlinks)
74 $copyElements.animate( { opacity: 0.4 }, 'fast' );
75
76 api = new mw.Api();
77 postData = {
78 formatversion: 2,
79 action: 'parse',
80 title: mw.config.get( 'wgPageName' ),
81 summary: $summary.textSelection( 'getContents' ),
82 prop: ''
83 };
84
85 if ( isDiff ) {
86 $wikiPreview.hide();
87
88 if ( postData.summary ) {
89 parseRequest = api.post( postData );
90 }
91
92 diffRequest = api.post( {
93 formatversion: 2,
94 action: 'query',
95 prop: 'revisions',
96 titles: mw.config.get( 'wgPageName' ),
97 rvdifftotext: $textbox.textSelection( 'getContents' ),
98 rvdifftotextpst: true,
99 rvprop: '',
100 rvsection: section === '' ? undefined : section
101 } );
102
103 // Wait for the summary before showing the diff so the page doesn't jump twice
104 $.when( diffRequest, parseRequest ).done( function ( response ) {
105 var diffHtml;
106 try {
107 diffHtml = response[ 0 ].query.pages[ 0 ]
108 .revisions[ 0 ].diff.body;
109 $wikiDiff.find( 'table.diff tbody' ).html( diffHtml );
110 mw.hook( 'wikipage.diff' ).fire( $wikiDiff.find( 'table.diff' ) );
111 } catch ( err ) {
112 // "result.blah is undefined" error, ignore
113 mw.log.warn( err );
114 }
115 $wikiDiff.show();
116 } );
117 } else {
118 $wikiDiff.hide();
119
120 $.extend( postData, {
121 prop: 'text|indicators|displaytitle|modules|jsconfigvars|categorieshtml|templates|langlinks|limitreporthtml',
122 text: $textbox.textSelection( 'getContents' ),
123 pst: true,
124 preview: true,
125 sectionpreview: section !== '',
126 disableeditsection: true,
127 useskin: mw.config.get( 'skin' ),
128 uselang: mw.config.get( 'wgUserLanguage' )
129 } );
130 if ( section === 'new' ) {
131 postData.section = 'new';
132 postData.sectiontitle = postData.summary;
133 }
134
135 parseRequest = api.post( postData );
136 parseRequest.done( function ( response ) {
137 var li, newList, $displaytitle, $content, $parent, $list;
138 if ( response.parse.jsconfigvars ) {
139 mw.config.set( response.parse.jsconfigvars );
140 }
141 if ( response.parse.modules ) {
142 mw.loader.load( response.parse.modules.concat(
143 response.parse.modulescripts,
144 response.parse.modulestyles
145 ) );
146 }
147
148 newList = [];
149 $.each( response.parse.indicators, function ( name, indicator ) {
150 newList.push(
151 $( '<div>' )
152 .addClass( 'mw-indicator' )
153 .attr( 'id', mw.util.escapeId( 'mw-indicator-' + name ) )
154 .html( indicator )
155 .get( 0 ),
156 // Add a whitespace between the <div>s because
157 // they get displayed with display: inline-block
158 document.createTextNode( '\n' )
159 );
160 } );
161 $( '.mw-indicators' ).empty().append( newList );
162
163 if ( response.parse.displaytitle ) {
164 $displaytitle = $( $.parseHTML( response.parse.displaytitle ) );
165 $( '#firstHeading' ).msg(
166 mw.config.get( 'wgEditMessage', 'editing' ),
167 $displaytitle
168 );
169 document.title = mw.msg(
170 'pagetitle',
171 mw.msg(
172 mw.config.get( 'wgEditMessage', 'editing' ),
173 $displaytitle.text()
174 )
175 );
176 }
177 if ( response.parse.categorieshtml ) {
178 $content = $( $.parseHTML( response.parse.categorieshtml ) );
179 mw.hook( 'wikipage.categories' ).fire( $content );
180 $( '.catlinks[data-mw="interface"]' ).replaceWith( $content );
181 }
182 if ( response.parse.templates ) {
183 newList = [];
184 $.each( response.parse.templates, function ( i, template ) {
185 li = $( '<li>' )
186 .append( $( '<a>' )
187 .attr( {
188 href: mw.util.getUrl( template.title ),
189 'class': ( template.exists ? '' : 'new' )
190 } )
191 .text( template.title )
192 );
193 newList.push( li );
194 } );
195
196 $editform.find( '.templatesUsed .mw-editfooter-list' ).detach().empty().append( newList ).appendTo( '.templatesUsed' );
197 }
198 if ( response.parse.limitreporthtml ) {
199 $( '.limitreport' ).html( response.parse.limitreporthtml );
200 }
201 if ( response.parse.langlinks && mw.config.get( 'skin' ) === 'vector' ) {
202 newList = [];
203 $.each( response.parse.langlinks, function ( i, langlink ) {
204 li = $( '<li>' )
205 .addClass( 'interlanguage-link interwiki-' + langlink.lang )
206 .append( $( '<a>' )
207 .attr( {
208 href: langlink.url,
209 title: langlink.title + ' - ' + langlink.langname,
210 lang: langlink.lang,
211 hreflang: langlink.lang
212 } )
213 .text( langlink.autonym )
214 );
215 newList.push( li );
216 } );
217 $list = $( '#p-lang ul' );
218 $parent = $list.parent();
219 $list.detach().empty().append( newList ).prependTo( $parent );
220 }
221
222 if ( response.parse.text ) {
223 $content = $wikiPreview.children( '.mw-content-ltr,.mw-content-rtl' );
224 $content
225 .detach()
226 .html( response.parse.text );
227
228 mw.hook( 'wikipage.content' ).fire( $content );
229
230 // Reattach
231 $wikiPreview.append( $content );
232
233 $wikiPreview.show();
234 }
235 } );
236 }
237 $.when( parseRequest, diffRequest ).done( function ( parseResp ) {
238 var parse = parseResp && parseResp[ 0 ].parse,
239 isSubject = ( section === 'new' ),
240 summaryMsg = isSubject ? 'subject-preview' : 'summary-preview',
241 $summaryPreview = $editform.find( '.mw-summary-preview' ).empty();
242 if ( parse && parse.parsedsummary ) {
243 $summaryPreview.append(
244 mw.message( summaryMsg ).parse(),
245 ' ',
246 $( '<span>' ).addClass( 'comment' ).html(
247 // There is no equivalent to rawParams
248 mw.message( 'parentheses' ).escaped()
249 // .replace() use $ as start of a pattern.
250 // $$ is the pattern for '$'.
251 // The inner .replace() duplicates any $ and
252 // the outer .replace() simplifies the $$.
253 .replace( '$1', parse.parsedsummary.replace( /\$/g, '$$$$' ) )
254 )
255 );
256 }
257 mw.hook( 'wikipage.editform' ).fire( $editform );
258 } ).always( function () {
259 $spinner.hide();
260 $copyElements.animate( {
261 opacity: 1
262 }, 'fast' );
263 } ).fail( function ( code, result ) {
264 // This just shows the error for whatever request failed first
265 var errorMsg = 'API error: ' + code;
266 if ( code === 'http' ) {
267 errorMsg = 'HTTP error: ';
268 if ( result.exception ) {
269 errorMsg += result.exception;
270 } else {
271 errorMsg += result.textStatus;
272 }
273 }
274 $errorBox = $( '<div>' )
275 .addClass( 'errorbox' )
276 .html( '<strong>' + mw.message( 'previewerrortext' ).escaped() + '</strong><br>' )
277 .append( document.createTextNode( errorMsg ) );
278 $wikiDiff.hide();
279 $wikiPreview.hide().before( $errorBox );
280 } );
281 }
282
283 $( function () {
284 // Do not enable on user .js/.css pages, as there's no sane way of "previewing"
285 // the scripts or styles without reloading the page.
286 if ( $( '#mw-userjsyoucanpreview' ).length || $( '#mw-usercssyoucanpreview' ).length ) {
287 return;
288 }
289
290 // The following elements can change in a preview but are not output
291 // by the server when they're empty until the preview response.
292 // TODO: Make the server output these always (in a hidden state), so we don't
293 // have to fish and (hopefully) put them in the right place (since skins
294 // can change where they are output).
295
296 if ( !document.getElementById( 'p-lang' ) && document.getElementById( 'p-tb' ) && mw.config.get( 'skin' ) === 'vector' ) {
297 $( '.portal:last' ).after(
298 $( '<div>' ).attr( {
299 'class': 'portal',
300 id: 'p-lang',
301 role: 'navigation',
302 'aria-labelledby': 'p-lang-label'
303 } )
304 .append( $( '<h3>' ).attr( 'id', 'p-lang-label' ).text( mw.msg( 'otherlanguages' ) ) )
305 .append( $( '<div>' ).addClass( 'body' ).append( '<ul>' ) )
306 );
307 }
308
309 if ( !$( '.mw-summary-preview' ).length ) {
310 $( '#wpSummary' ).after(
311 $( '<div>' ).addClass( 'mw-summary-preview' )
312 );
313 }
314
315 if ( !document.getElementById( 'wikiDiff' ) && document.getElementById( 'wikiPreview' ) ) {
316 $( '#wikiPreview' ).after(
317 $( '<div>' )
318 .hide()
319 .attr( 'id', 'wikiDiff' )
320 .html( '<table class="diff"><col class="diff-marker"/><col class="diff-content"/>' +
321 '<col class="diff-marker"/><col class="diff-content"/><tbody/></table>' )
322 );
323 }
324
325 // This should be moved down to '#editform', but is kept on the body for now
326 // because the LiquidThreads extension is re-using this module with only half
327 // the EditPage (doesn't include #editform presumably, T57463).
328 $( document.body ).on( 'click', '#wpPreview, #wpDiff', doLivePreview );
329 } );
330
331 }( mediaWiki, jQuery ) );