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