/*! * VisualEditor MediaWiki Initialization ViewPageTarget class. * * @copyright 2011-2014 VisualEditor Team and others; see AUTHORS.txt * @license The MIT License (MIT); see LICENSE.txt */ /*global mw, confirm, alert */ /** * Initialization MediaWiki view page target. * * @class * @extends ve.init.mw.Target * * @constructor */ ve.init.mw.ViewPageTarget = function VeInitMwViewPageTarget() { var prefName, prefValue, browserWhitelisted, currentUri = new mw.Uri(), conf = mw.config.get( 'wgVisualEditorConfig' ); // Parent constructor ve.init.mw.Target.call( this, $( '#content' ), mw.config.get( 'wgRelevantPageName' ), currentUri.query.oldid ); // Properties this.$spinner = $( '
' ); this.toolbarCancelButton = null; this.toolbarSaveButton = null; this.saveDialog = null; this.onBeforeUnloadFallback = null; this.onBeforeUnloadHandler = null; this.timings = {}; this.active = false; this.activating = false; this.deactivating = false; this.edited = false; // If this is true then #transformPage / #restorePage will not call pushState // This is to avoid adding a new history entry for the url we just got from onpopstate // (which would mess up with the expected order of Back/Forwards browsing) this.actFromPopState = false; this.scrollTop = null; this.currentUri = currentUri; this.section = currentUri.query.vesection; this.initialEditSummary = ''; this.namespaceName = mw.config.get( 'wgCanonicalNamespace' ); this.viewUri = new mw.Uri( mw.util.getUrl( this.pageName ) ); this.veEditUri = this.viewUri.clone().extend( { 'veaction': 'edit' } ); this.isViewPage = ( mw.config.get( 'wgAction' ) === 'view' && currentUri.query.diff === undefined ); this.originalDocumentTitle = document.title; this.tabLayout = mw.config.get( 'wgVisualEditorConfig' ).tabLayout; /** * @property {jQuery.Promise|null} */ this.sanityCheckPromise = null; // Add modules specific to desktop (modules shared with mobile go in MWTarget) this.modules.push( 'ext.visualEditor.mwformatting', 'ext.visualEditor.mwgallery', 'ext.visualEditor.mwimage', 'ext.visualEditor.mwmeta', 'ext.visualEditor.mwreference', 'ext.visualEditor.mwtransclusion' ); // Load preference modules for ( prefName in conf.preferenceModules ) { prefValue = mw.config.get( 'wgUserName' ) === null ? conf.defaultUserOptions[prefName] : mw.user.options.get( prefName, conf.defaultUserOptions[prefName] ); if ( prefValue && prefValue !== '0' ) { this.modules.push( conf.preferenceModules[prefName] ); } } browserWhitelisted = ( 'vewhitelist' in currentUri.query || $.client.test( ve.init.mw.ViewPageTarget.compatibility.whitelist, null, true ) ); // Events this.connect( this, { 'save': 'onSave', 'saveErrorEmpty': 'onSaveErrorEmpty', 'saveAsyncBegin': 'onSaveAsyncBegin', 'saveAsyncComplete': 'onSaveAsyncComplete', 'saveErrorSpamBlacklist': 'onSaveErrorSpamBlacklist', 'saveErrorAbuseFilter': 'onSaveErrorAbuseFilter', 'saveErrorNewUser': 'onSaveErrorNewUser', 'saveErrorCaptcha': 'onSaveErrorCaptcha', 'saveErrorUnknown': 'onSaveErrorUnknown', 'loadError': 'onLoadError', 'surfaceReady': 'onSurfaceReady', 'editConflict': 'onEditConflict', 'showChanges': 'onShowChanges', 'showChangesError': 'onShowChangesError', 'noChanges': 'onNoChanges', 'serializeError': 'onSerializeError', 'sanityCheckComplete': 'updateToolbarSaveButtonState' } ); if ( !browserWhitelisted ) { // Show warning in unknown browsers that pass the support test // Continue at own risk. this.localNoticeMessages.push( 'visualeditor-browserwarning' ); } if ( currentUri.query.venotify ) { // The following messages can be used here: // visualeditor-notification-saved // visualeditor-notification-created // visualeditor-notification-restored mw.hook( 'postEdit' ).fire( { 'message': ve.msg( 'visualeditor-notification-' + currentUri.query.venotify, new mw.Title( this.pageName ).toText() ) } ); if ( window.history.replaceState ) { delete currentUri.query.venotify; window.history.replaceState( null, document.title, currentUri ); } } this.setupSkinTabs(); window.addEventListener( 'popstate', ve.bind( this.onWindowPopState, this ) ) ; }; /* Inheritance */ OO.inheritClass( ve.init.mw.ViewPageTarget, ve.init.mw.Target ); /* Static Properties */ /** * Compatibility map used with jQuery.client to black-list incompatible browsers. * * @static * @property */ ve.init.mw.ViewPageTarget.compatibility = { // The key is the browser name returned by jQuery.client // The value is either null (match all versions) or a list of tuples // containing an inequality (<,>,<=,>=) and a version number 'whitelist': { 'firefox': [['>=', 15]], 'iceweasel': [['>=', 10]], 'safari': [['>=', 5]], 'chrome': [['>=', 19]] } }; /* Methods */ /** * @inheritdoc */ ve.init.mw.ViewPageTarget.prototype.setUpToolbar = function () { var $firstHeading = $( '#firstHeading' ); // Parent method ve.init.mw.Target.prototype.setUpToolbar.call( this ); this.toolbar.enableFloatable(); this.toolbar.$element .addClass( 've-init-mw-viewPageTarget-toolbar' ); // Move the toolbar to before #firstHeading if it exists if ( $firstHeading.length ) { this.toolbar.$element.insertBefore( $firstHeading ); } this.toolbar.$bar.slideDown( 'fast', ve.bind( function () { // Check the surface wasn't torn down while the toolbar was animating if ( this.surface ) { this.toolbar.initialize(); this.surface.emit( 'position' ); this.surface.getContext().update(); } }, this ) ); }; /** * Switch to edit mode. * * @method */ ve.init.mw.ViewPageTarget.prototype.activate = function () { if ( !this.active && !this.activating ) { this.activating = true; this.timings.activationStart = ve.now(); // User interface changes this.transformPage(); this.showSpinner(); this.hideTableOfContents(); this.mutePageContent(); this.mutePageTitle(); this.saveScrollPosition(); this.load( [ 'site', 'user' ] ); } }; /** * Switch to view mode. * * @method */ ve.init.mw.ViewPageTarget.prototype.deactivate = function ( override ) { if ( override || ( this.active && !this.deactivating ) ) { if ( override || !this.edited || confirm( ve.msg( 'visualeditor-viewpage-savewarning' ) ) ) { this.deactivating = true; // User interface changes if ( ve.msg( 'accesskey-save' ) !== '-' && ve.msg( 'accesskey-save' ) !== '' ) { this.elementsThatHadOurAccessKey.attr( 'accesskey', ve.msg( 'accesskey-save' ) ); } this.restorePage(); this.hideSpinner(); this.showTableOfContents(); if ( this.toolbarCancelButton ) { // If deactivate is called before a successful load, then // setupToolbarButtons has not been called yet and as such tearDownToolbarButtons // would throw an error when trying call methods on the button property (bug 46456) this.tearDownToolbarButtons(); this.detachToolbarButtons(); } // Check we got as far as setting up the surface if ( this.active ) { // If we got as far as setting up the surface, tear that down this.tearDownSurface(); } // Show/restore components that are otherwise handled by tearDownSurface this.showPageContent(); this.restorePageTitle(); // If there is a load in progress, abort it if ( this.loading ) { this.loading.abort(); } this.clearState(); this.docToSave = null; this.initialEditSummary = ''; this.deactivating = false; mw.hook( 've.deactivationComplete' ).fire( this.edited ); } } }; /** * Handle failed DOM load event. * * @method * @param {jqXHR|null} jqXHR jQuery XHR object * @param {string} status Text status message * @param {Mixed|null} error Thrown exception or HTTP error string */ ve.init.mw.ViewPageTarget.prototype.onLoadError = function ( jqXHR, status ) { // Don't show an error if the load was manually aborted // The response.status check here is to catch aborts triggered by navigation away from the page if ( status !== 'abort' && ( !jqXHR || jqXHR.status !== 0 ) && confirm( ve.msg( 'visualeditor-loadwarning', status ) ) ) { this.load(); } else { this.activating = false; // User interface changes this.deactivate( true ); } }; /** * Once surface is ready ready, init UI * * @method */ ve.init.mw.ViewPageTarget.prototype.onSurfaceReady = function () { this.activating = false; this.surface.getModel().getDocument().connect( this, { 'transact': 'recordLastTransactionTime' } ); this.surface.getModel().connect( this, { 'documentUpdate': 'checkForWikitextWarning', 'history': 'updateToolbarSaveButtonState' } ); this.surface.setPasteRules( this.constructor.static.pasteRules ); // Update UI this.transformPageTitle(); this.changeDocumentTitle(); this.hidePageContent(); this.hideSpinner(); this.$document[0].focus(); this.setupToolbarButtons(); this.attachToolbarButtons(); this.restoreScrollPosition(); this.restoreEditSection(); this.setupBeforeUnloadHandler(); this.maybeShowDialogs(); ve.track( 'performance.system.activation', { 'duration': ve.now() - this.timings.activationStart } ); mw.hook( 've.activationComplete' ).fire(); }; /** * Handle successful DOM save event. * * @method * @param {string} html Rendered page HTML from server * @param {string} categoriesHtml Rendered categories HTML from server * @param {number} [newid] New revision id, undefined if unchanged */ ve.init.mw.ViewPageTarget.prototype.onSave = function ( html, categoriesHtml, newid ) { ve.track( 'performance.user.saveComplete', { 'duration': ve.now() - this.timings.saveDialogSave } ); if ( !this.pageExists || this.restoring ) { // This is a page creation or restoration, refresh the page this.tearDownBeforeUnloadHandler(); window.location.href = this.viewUri.extend( { 'venotify': this.restoring ? 'restored' : 'created' } ); } else { // Update watch link to match 'watch checkbox' in save dialog. // User logged in if module loaded. // Just checking for mw.page.watch is not enough because in Firefox // there is Object.prototype.watch... if ( mw.page.watch && mw.page.watch.updateWatchLink ) { var watchChecked = this.saveDialog.$saveOptions .find( '.ve-ui-mwSaveDialog-checkboxes' ) .find( '#wpWatchthis' ) .prop( 'checked' ); mw.page.watch.updateWatchLink( $( '#ca-watch a, #ca-unwatch a' ), watchChecked ? 'unwatch': 'watch' ); } // If we were explicitly editing an older version, make sure we won't // load the same old version again, now that we've saved the next edit // will be against the latest version. // TODO: What about oldid in the url? this.restoring = false; if ( newid !== undefined ) { mw.config.set( 'wgCurRevisionId', newid ); this.revid = newid; } this.saveDialog.close(); this.saveDialog.reset(); this.replacePageContent( html, categoriesHtml ); this.setupSectionEditLinks(); this.tearDownBeforeUnloadHandler(); this.deactivate( true ); mw.hook( 'postEdit' ).fire( { 'message': ve.msg( 'visualeditor-notification-saved', new mw.Title( this.pageName ).toText() ) } ); } }; /** * Update save dialog when async begins * * @method */ ve.init.mw.ViewPageTarget.prototype.onSaveAsyncBegin = function () { this.saveDialog.saveButton.setDisabled( true ); this.saveDialog.$loadingIcon.show(); }; /** * Update save dialog when async completes * * @method */ ve.init.mw.ViewPageTarget.prototype.onSaveAsyncComplete = function () { this.saveDialog.saveButton.setDisabled( false ); this.saveDialog.$loadingIcon.hide(); }; /** * Update save dialog message on general error * * @method */ ve.init.mw.ViewPageTarget.prototype.onSaveErrorEmpty = function () { this.showSaveError( ve.msg( 'visualeditor-saveerror', 'Empty server response' ) ); this.saveDialog.saveButton.setDisabled( true ); }; /** * Update save dialog message on spam blacklist error * * @method * @param {Object} editApi */ ve.init.mw.ViewPageTarget.prototype.onSaveErrorSpamBlacklist = function ( editApi ) { this.showSaveError( // TODO: Use mediawiki.language equivalant of Language.php::listToText once it exists ve.msg( 'spamprotectiontext' ) + ' ' + ve.msg( 'spamprotectionmatch', editApi.spamblacklist.split( '|' ).join( ', ' ) ) ); this.saveDialog.saveButton.setDisabled( true ); }; /** * Update save dialog message on spam blacklist error * * @method * @param {Object} editApi */ ve.init.mw.ViewPageTarget.prototype.onSaveErrorAbuseFilter = function ( editApi ) { this.showSaveError( $.parseHTML( editApi.warning ), false ); // Don't disable the save button. If the action is not disallowed the user may save the // edit by pressing Save again. The AbuseFilter API currently has no way to distinguish // between filter triggers that are and aren't disallowing the action. }; /** * Update save dialog when token fetch indicates another user is logged in * * @method * @param {boolean|undefined} isAnon Is newly logged in user anonymous. If * undefined, user is logged in */ ve.init.mw.ViewPageTarget.prototype.onSaveErrorNewUser = function ( isAnon ) { var badToken, userMsg; badToken = document.createTextNode( mw.msg( 'visualeditor-savedialog-error-badtoken' ) + ' ' ); // mediawiki.jqueryMsg has a bug with [[User:$1|$1]] (bug 51388) if ( isAnon ) { userMsg = 'visualeditor-savedialog-identify-anon'; } else { userMsg = 'visualeditor-savedialog-identify-user---' + mw.config.get( 'wgUserName' ); } this.showSaveError( $( badToken ).add( $.parseHTML( mw.message( userMsg ).parse() ) ), 'warning' ); this.saveDialog.saveButton.setDisabled( false ); }; /** * Update save dialog on captcha error * * @method * @param {Object} editApi */ ve.init.mw.ViewPageTarget.prototype.onSaveErrorCaptcha = function ( editApi ) { this.captcha = { input: new OO.ui.TextInputWidget(), id: editApi.captcha.id }; this.showSaveError( $( '' ).append(
$( '' ).text( mw.msg( 'captcha-label' ) ),
document.createTextNode( mw.msg( 'colon-separator' ) ),
$( $.parseHTML( mw.message( 'fancycaptcha-edit' ).parse() ) )
.filter( 'a' ).attr( 'target', '_blank' ).end()
),
$( '' ).attr( 'src', editApi.captcha.url ),
this.captcha.input.$element
), false
);
};
/**
* Update save dialog message on unknown error
*
* @method
* @param {Object} editApi
* @param {Object|null} data API response data
*/
ve.init.mw.ViewPageTarget.prototype.onSaveErrorUnknown = function ( editApi, data ) {
this.showSaveError(
document.createTextNode(
( editApi && editApi.info ) ||
( data.error && data.error.info ) ||
( editApi && editApi.code ) ||
( data.error && data.error.code ) ||
'Unknown error'
)
);
this.saveDialog.saveButton.setDisabled( true );
};
/**
* Update save dialog api-save-error message
*
* @method
* @param {string|jQuery|Node[]} msg Message content (string of HTML, jQuery object or array of
* Node objects)
* @param {string|boolean} wrap Whether to wrap the message in a paragraph and if
* so, how. One of "warning", "error" or false.
*/
ve.init.mw.ViewPageTarget.prototype.showSaveError = function ( msg, wrap ) {
wrap = wrap || 'error';
this.saveDialog.clearMessage( 'api-save-error' );
this.saveDialog.showMessage( 'api-save-error', msg, { 'wrap': wrap } );
};
/**
* Handle Show changes event.
*
* @method
* @param {string} diffHtml
*/
ve.init.mw.ViewPageTarget.prototype.onShowChanges = function ( diffHtml ) {
ve.track( 'performance.user.reviewComplete', { 'duration': ve.now() - this.timings.saveDialogReview } );
// Invalidate the viewer diff on next change
this.surface.getModel().getDocument().once( 'transact',
ve.bind( this.saveDialog.clearDiff, this.saveDialog )
);
this.saveDialog.setDiffAndReview( diffHtml );
};
/**
* Handle Serialize event.
*
* @method
* @param {string} wikitext
*/
ve.init.mw.ViewPageTarget.prototype.onSerialize = function ( wikitext ) {
ve.track( 'performance.user.reviewComplete', { 'duration': ve.now() - this.timings.saveDialogReview } );
// Invalidate the viewer wikitext on next change
this.surface.getModel().getDocument().once( 'transact',
ve.bind( this.saveDialog.clearDiff, this.saveDialog )
);
this.saveDialog.setDiffAndReview( $( '' ).text( wikitext ) );
};
/**
* Handle failed show changes event.
*
* @method
* @param {Object} jqXHR
* @param {string} status Text status message
*/
ve.init.mw.ViewPageTarget.prototype.onShowChangesError = function ( jqXHR, status ) {
ve.track( 'performance.user.reviewError', { 'duration': ve.now() - this.timings.saveDialogReview } );
alert( ve.msg( 'visualeditor-differror', status ) );
this.saveDialog.$loadingIcon.hide();
};
/**
* Called if a call to target.serialize() failed.
*
* @method
* @param {jqXHR|null} jqXHR
* @param {string} status Text status message
*/
ve.init.mw.ViewPageTarget.prototype.onSerializeError = function ( jqXHR, status ) {
if ( this.timings.saveDialogOpen ) {
// This function can be called by the switch to wikitext button as well, so only log
// reviewError if we actually got here from the save dialog
ve.track( 'performance.user.reviewError', { 'duration': ve.now() - this.timings.saveDialogReview } );
}
alert( ve.msg( 'visualeditor-serializeerror', status ) );
// It's possible to get here while the save dialog has never been opened (if the user uses
// the switch to source mode option)
if ( this.saveDialog ) {
this.saveDialog.$loadingIcon.hide();
}
};
/**
* Handle edit conflict event.
*
* @method
*/
ve.init.mw.ViewPageTarget.prototype.onEditConflict = function () {
ve.track( 'performance.user.saveError.editconflict', {
'duration': ve.now() - this.timings.saveDialogSave,
'retries': this.timings.saveRetries
} );
this.saveDialog.$loadingIcon.hide();
this.saveDialog.swapPanel( 'conflict' );
};
/**
* Handle failed show changes event.
*
* @method
*/
ve.init.mw.ViewPageTarget.prototype.onNoChanges = function () {
ve.track( 'performance.user.reviewComplete', { 'duration': ve.now() - this.timings.saveDialogReview } );
this.saveDialog.$loadingIcon.hide();
this.saveDialog.swapPanel( 'nochanges' );
this.saveDialog.reviewGoodButton.setDisabled( false );
};
/**
* Handle clicks on the view tab.
*
* @method
* @param {jQuery.Event} e Mouse click event
*/
ve.init.mw.ViewPageTarget.prototype.onViewTabClick = function ( e ) {
if ( ( e.which && e.which !== 1 ) || e.shiftKey || e.altKey || e.ctrlKey || e.metaKey ) {
return;
}
if ( this.active ) {
this.deactivate();
// Prevent the edit tab's normal behavior
e.preventDefault();
} else if ( this.activating ) {
this.deactivate( true );
this.activating = false;
e.preventDefault();
}
};
/**
* Handle clicks on the save button in the toolbar.
*
* @method
* @param {jQuery.Event} e Mouse click event
*/
ve.init.mw.ViewPageTarget.prototype.onToolbarSaveButtonClick = function () {
if ( this.edited || this.restoring ) {
this.showSaveDialog();
}
};
/**
* Handle clicks on the save button in the toolbar.
*
* @method
* @param {jQuery.Event} e Mouse click event
*/
ve.init.mw.ViewPageTarget.prototype.onToolbarCancelButtonClick = function () {
this.deactivate();
};
/**
* Handle clicks on the MwMeta button in the toolbar.
*
* @method
* @param {jQuery.Event} e Mouse click event
*/
ve.init.mw.ViewPageTarget.prototype.onToolbarMetaButtonClick = function () {
this.surface.getDialogs().getWindow( 'meta' ).open();
};
/**
* Record the time of the last transaction in response to a 'transact' event on the document.
*/
ve.init.mw.ViewPageTarget.prototype.recordLastTransactionTime = function () {
this.timings.lastTransaction = ve.now();
};
/**
* Check if the user is entering wikitext, and show a notification if they are.
*
* This check is fairly simplistic: it checks whether the content branch node the selection is in
* looks like wikitext, so it can trigger if the user types in a paragraph that has pre-existing
* wikitext-like content.
*
* This method is bound to the 'documentUpdate' event on the surface model, and unbinds itself when
* the wikitext notification is displayed.
*
* @param {ve.dm.Transaction} transaction
*/
ve.init.mw.ViewPageTarget.prototype.checkForWikitextWarning = function () {
var text, doc = this.surface.getView().getDocument(),
selection = this.surface.getModel().getSelection(),
node = doc.getNodeFromOffset( selection.start ),
textMatches,
viewPageTarget = this;
if ( !( node instanceof ve.ce.ContentBranchNode ) ) {
return;
}
text = ve.ce.getDomText( node.$element[0] );
textMatches = text.match( /\[\[|\{\{|''|