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