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