mediawiki-extensions-Visual.../modules/ve-mw/init/targets/ve.init.mw.DesktopArticleTarget.js

1360 lines
40 KiB
JavaScript
Raw Normal View History

JSDuck: Generated code documentation! See CODING.md for how to run it. Mistakes fixed: * Warning: Unknown type function -> Function * Warning: Unknown type DOMElement -> HTMLElement * Warning: Unknown type DOM Node -> HTMLElement * Warning: Unknown type Integer -> Mixed * Warning: Unknown type Command -> ve.Command * Warning: Unknown type any -> number * Warning: Unknown type ve.Transaction -> ve.dm.Transaction * Warning: Unknown type ve.dm.AnnotationSet -> ve.AnnotationSet * Warning: Unknown type false -> boolean * Warning: Unknown type ve.dm.AlienNode ve.dm doesn't have a generic AlienNode like ve.ce -> Unknown type ve.dm.AlienInlineNode|ve.dm.AlienBlockNode * Warning: Unknown type ve.ve.Surface -> ve.ce.Surface * ve.example.lookupNode: -> Last @param should be @return * ve.dm.Transaction.prototype.pushReplace: -> @param {Array] should be @param {Array} * Warning: ve.BranchNode.js:27: {@link ve.Node#hasChildren} links to non-existing member -> (removed) * Warning: ve.LeafNode.js:21: {@link ve.Node#hasChildren} links to non-existing member -> (removed) Differences fixed: * Variadic arguments are like @param {Type...} [name] instead of @param {Type} [name...] * Convert all file headers from /** to /*! because JSDuck tries to parse all /** blocks and fails to parse with all sorts of errors for "Global property", "Unnamed property", and "Duplicate property". Find: \/\*\*([^@]+)(@copyright) Replace: /*!$1$2 * Indented blocks are considered code examples. A few methods had documentation with numbered lists that were indented, which have now been updated to not be intended. * The free-form text descriptions are parsed with Markdown, which requires lists to be separated from paragraphs by an empty line. And we should use `backticks` instead of {braces} for inline code in text paragraphs. * Doc blocks for classes and their constructor have to be in the correct order (@constructor, @param, @return must be before @class, @abstract, @extends etc.) * `@extends Class` must not have Class {wrapped} * @throws must start with a {Type} * @example means something else. It is used for an inline demo iframe, not code block. For that simply indent with spaces. * @member means something else. Non-function properties are marked with @property, not @member. * To create a link to a class or member, in most cases the name is enough to create a link. E.g. Foo, Foo.bar, Foo.bar#quux, where a hash stands for "instance member", so Foo.bar#quux, links to Foo.bar.prototype.quux (the is not supported, as "prototype" is considered an implementation detail, it only indexes class name and method name). If the magic linker doesn't work for some case, the verbose syntax is {@link #target label}. * @property can't have sub-properties (nested @param and @return values are supported, only @static @property can't be nested). We only have one case of this, which can be worked around by moving those in a new virtual class. The code is unaltered (only moved down so that it isn't with the scope of the main @class block). ve.dm.TransactionProcessor.processors. New: * @mixins: Classes mixed into the current class. * @event: Events that can be emitted by a class. These are also inherited by subclasses. (+ @param, @return and @preventable). So ve.Node#event-attach is inherited to ve.dm.BreakNode, just like @method is. * @singleton: Plain objects such as ve, ve.dm, ve.ce were missing documentation causing a tree error. Documented those as a JSDuck singleton, which they but just weren't documented yet. NB: Members of @singleton don't need @static (if present, triggers a compiler warning). * @chainable: Shorthand for "@return this". We were using "@return {classname}" which is ambiguous (returns the same instance or another instance?), @chainable is specifically for "@return this". Creates proper labels in the generated HTML pages. Removed: * @mixin: (not to be confused with @mixins). Not supported by JSDuck. Every class is standalone anyway. Where needed marked them @class + @abstract instead. Change-Id: I6a7c9e8ee8f995731bc205d666167874eb2ebe23
2013-01-04 08:54:17 +00:00
/*!
* VisualEditor MediaWiki Initialization DesktopArticleTarget class.
*
* @copyright 2011-2015 VisualEditor Team and others; see AUTHORS.txt
* @license The MIT License (MIT); see LICENSE.txt
*/
/*global confirm, alert */
/**
* MediaWiki desktop article target.
*
* @class
JSDuck: Generated code documentation! See CODING.md for how to run it. Mistakes fixed: * Warning: Unknown type function -> Function * Warning: Unknown type DOMElement -> HTMLElement * Warning: Unknown type DOM Node -> HTMLElement * Warning: Unknown type Integer -> Mixed * Warning: Unknown type Command -> ve.Command * Warning: Unknown type any -> number * Warning: Unknown type ve.Transaction -> ve.dm.Transaction * Warning: Unknown type ve.dm.AnnotationSet -> ve.AnnotationSet * Warning: Unknown type false -> boolean * Warning: Unknown type ve.dm.AlienNode ve.dm doesn't have a generic AlienNode like ve.ce -> Unknown type ve.dm.AlienInlineNode|ve.dm.AlienBlockNode * Warning: Unknown type ve.ve.Surface -> ve.ce.Surface * ve.example.lookupNode: -> Last @param should be @return * ve.dm.Transaction.prototype.pushReplace: -> @param {Array] should be @param {Array} * Warning: ve.BranchNode.js:27: {@link ve.Node#hasChildren} links to non-existing member -> (removed) * Warning: ve.LeafNode.js:21: {@link ve.Node#hasChildren} links to non-existing member -> (removed) Differences fixed: * Variadic arguments are like @param {Type...} [name] instead of @param {Type} [name...] * Convert all file headers from /** to /*! because JSDuck tries to parse all /** blocks and fails to parse with all sorts of errors for "Global property", "Unnamed property", and "Duplicate property". Find: \/\*\*([^@]+)(@copyright) Replace: /*!$1$2 * Indented blocks are considered code examples. A few methods had documentation with numbered lists that were indented, which have now been updated to not be intended. * The free-form text descriptions are parsed with Markdown, which requires lists to be separated from paragraphs by an empty line. And we should use `backticks` instead of {braces} for inline code in text paragraphs. * Doc blocks for classes and their constructor have to be in the correct order (@constructor, @param, @return must be before @class, @abstract, @extends etc.) * `@extends Class` must not have Class {wrapped} * @throws must start with a {Type} * @example means something else. It is used for an inline demo iframe, not code block. For that simply indent with spaces. * @member means something else. Non-function properties are marked with @property, not @member. * To create a link to a class or member, in most cases the name is enough to create a link. E.g. Foo, Foo.bar, Foo.bar#quux, where a hash stands for "instance member", so Foo.bar#quux, links to Foo.bar.prototype.quux (the is not supported, as "prototype" is considered an implementation detail, it only indexes class name and method name). If the magic linker doesn't work for some case, the verbose syntax is {@link #target label}. * @property can't have sub-properties (nested @param and @return values are supported, only @static @property can't be nested). We only have one case of this, which can be worked around by moving those in a new virtual class. The code is unaltered (only moved down so that it isn't with the scope of the main @class block). ve.dm.TransactionProcessor.processors. New: * @mixins: Classes mixed into the current class. * @event: Events that can be emitted by a class. These are also inherited by subclasses. (+ @param, @return and @preventable). So ve.Node#event-attach is inherited to ve.dm.BreakNode, just like @method is. * @singleton: Plain objects such as ve, ve.dm, ve.ce were missing documentation causing a tree error. Documented those as a JSDuck singleton, which they but just weren't documented yet. NB: Members of @singleton don't need @static (if present, triggers a compiler warning). * @chainable: Shorthand for "@return this". We were using "@return {classname}" which is ambiguous (returns the same instance or another instance?), @chainable is specifically for "@return this". Creates proper labels in the generated HTML pages. Removed: * @mixin: (not to be confused with @mixins). Not supported by JSDuck. Every class is standalone anyway. Where needed marked them @class + @abstract instead. Change-Id: I6a7c9e8ee8f995731bc205d666167874eb2ebe23
2013-01-04 08:54:17 +00:00
* @extends ve.init.mw.Target
*
* @constructor
* @param {Object} config Configuration options
*/
ve.init.mw.DesktopArticleTarget = function VeInitMwDesktopArticleTarget( config ) {
Load RL modules in one load.php request, rather than in two stages This introduces TargetLoader, which manages plugins and RL modules in a slightly more generic fashion so that Targets themselves don't have to. This allows us to load all RL modules in one load.php request, rather than first loading ViewPageTarget which then loads the other modules. TargetLoader loads in the bottom queue, so it will be loaded as part of the main load.php request, but in VPT.init.js we still have to wait for it with using() because it might not have arrived yet. This also degrades gracefully on cached pages where TargetLoader isn't in the bottom queue: it'll be loaded as a separate request instead, which is suboptimal but no worse that what we were doing before. Right now TargetLoader is small enough that it could also be in the top queue, but in the future we want to add things like the action=visualeditor API request to it, and mw.Api is relatively big. Note: this also makes a breaking change to the plugin API: plugin callbacks no longer receive the target instance as a parameter, as they're now executed before the target has been constructed rather than after. In the long term, if we want to give plugins access to the target instance, we could give them the target promise somehow. For now, I've killed this feature because nothing used it and the change from a direct object reference to a promise would have been a breaking change anyway. Also fixed incorrect documentation index for ve.init.mw.ViewPageTarget.init. Bug: T53569 Change-Id: Ibfa6abbeaf872ae2aadc6ed9d5beba7473ea441a
2015-02-26 01:22:44 +00:00
// A workaround, as default URI does not get updated after pushState (bug 72334)
var currentUri = new mw.Uri( location.href );
// Parent constructor
ve.init.mw.DesktopArticleTarget.super.call(
this, mw.config.get( 'wgRelevantPageName' ), currentUri.query.oldid, config
);
// Parent constructor bound key event handlers, but we don't want them bound until
// we activate; so unbind them again
this.unbindHandlers();
this.onWatchToggleHandler = this.onWatchToggle.bind( this );
// Properties
this.onBeforeUnloadFallback = null;
this.onUnloadHandler = this.onUnload.bind( this );
this.active = false;
this.activating = false;
this.deactivating = false;
this.edited = false;
this.recreating = false;
this.activatingDeferred = null;
this.toolbarSetupDeferred = null;
this.welcomeDialog = null;
this.welcomeDialogPromise = null;
this.checkboxFields = null;
this.checkboxesByName = null;
this.$otherFields = null;
// 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.popState = {
tag: 'visualeditor'
};
this.scrollTop = null;
this.currentUri = currentUri;
this.section = currentUri.query.vesection;
this.initialEditSummary = currentUri.query.summary;
this.namespaceName = mw.config.get( 'wgCanonicalNamespace' );
this.viewUri = new mw.Uri( mw.util.getUrl( this.pageName ) );
this.isViewPage = (
mw.config.get( 'wgAction' ) === 'view' &&
currentUri.query.diff === undefined
);
this.originalDocumentTitle = document.title;
this.tabLayout = mw.config.get( 'wgVisualEditorConfig' ).tabLayout;
this.events = new ve.init.mw.TargetEvents( this );
// Initialization
this.$element.addClass( 've-init-mw-desktopArticleTarget' );
if ( history.replaceState ) {
// We replace the current state with one that's marked with our tag. This way, when users
// use the Back button to exit the editor we can restore Read mode. This is because we want
// to ignore foreign states in onWindowPopState. Without this, the Read state is foreign.
// FIXME: There should be a much better solution than this.
history.replaceState( this.popState, document.title, currentUri );
}
this.setupSkinTabs();
window.addEventListener( 'popstate', this.onWindowPopState.bind( this ) );
};
Object management: Object create/inherit/clone utilities * For the most common case: - replace ve.extendClass with ve.inheritClass (chose slightly different names to detect usage of the old/new one, and I like 'inherit' better). - move it up to below the constructor, see doc block for why. * Cases where more than 2 arguments were passed to ve.extendClass are handled differently depending on the case. In case of a longer inheritance tree, the other arguments could be omitted (like in "ve.ce.FooBar, ve.FooBar, ve.Bar". ve.ce.FooBar only needs to inherit from ve.FooBar, because ve.ce.FooBar inherits from ve.Bar). In the case of where it previously had two mixins with ve.extendClass(), either one becomes inheritClass and one a mixin, both to mixinClass(). No visible changes should come from this commit as the instances still all have the same visible properties in the end. No more or less than before. * Misc.: - Be consistent in calling parent constructors in the same order as the inheritance. - Add missing @extends and @param documentation. - Replace invalid {Integer} type hint with {Number}. - Consistent doc comments order: @class, @abstract, @constructor, @extends, @params. - Fix indentation errors A fairly common mistake was a superfluous space before the identifier on the assignment line directly below the documentation comment. $ ack "^ [^*]" --js modules/ve - Typo "Inhertiance" -> "Inheritance". - Replacing the other confusing comment "Inheritance" (inside the constructor) with "Parent constructor". - Add missing @abstract for ve.ui.Tool. - Corrected ve.FormatDropdownTool to ve.ui.FormatDropdownTool.js - Add function names to all @constructor functions. Now that we have inheritance it is important and useful to have these functions not be anonymous. Example of debug shot: http://cl.ly/image/1j3c160w3D45 Makes the difference between < documentNode; > ve_dm_DocumentNode ... : ve_dm_BranchNode ... : ve_dm_Node ... : ve_dm_Node ... : Object ... without names (current situation): < documentNode; > Object ... : Object ... : Object ... : Object ... : Object ... though before this commit, it really looks like this (flattened since ve.extendClass really did a mixin): < documentNode; > Object ... ... ... Pattern in Sublime (case-sensitive) to find nameless constructor functions: "^ve\..*\.([A-Z])([^\.]+) = function \(" Change-Id: Iab763954fb8cf375900d7a9a92dec1c755d5407e
2012-09-05 06:07:47 +00:00
/* Inheritance */
OO.inheritClass( ve.init.mw.DesktopArticleTarget, ve.init.mw.Target );
Object management: Object create/inherit/clone utilities * For the most common case: - replace ve.extendClass with ve.inheritClass (chose slightly different names to detect usage of the old/new one, and I like 'inherit' better). - move it up to below the constructor, see doc block for why. * Cases where more than 2 arguments were passed to ve.extendClass are handled differently depending on the case. In case of a longer inheritance tree, the other arguments could be omitted (like in "ve.ce.FooBar, ve.FooBar, ve.Bar". ve.ce.FooBar only needs to inherit from ve.FooBar, because ve.ce.FooBar inherits from ve.Bar). In the case of where it previously had two mixins with ve.extendClass(), either one becomes inheritClass and one a mixin, both to mixinClass(). No visible changes should come from this commit as the instances still all have the same visible properties in the end. No more or less than before. * Misc.: - Be consistent in calling parent constructors in the same order as the inheritance. - Add missing @extends and @param documentation. - Replace invalid {Integer} type hint with {Number}. - Consistent doc comments order: @class, @abstract, @constructor, @extends, @params. - Fix indentation errors A fairly common mistake was a superfluous space before the identifier on the assignment line directly below the documentation comment. $ ack "^ [^*]" --js modules/ve - Typo "Inhertiance" -> "Inheritance". - Replacing the other confusing comment "Inheritance" (inside the constructor) with "Parent constructor". - Add missing @abstract for ve.ui.Tool. - Corrected ve.FormatDropdownTool to ve.ui.FormatDropdownTool.js - Add function names to all @constructor functions. Now that we have inheritance it is important and useful to have these functions not be anonymous. Example of debug shot: http://cl.ly/image/1j3c160w3D45 Makes the difference between < documentNode; > ve_dm_DocumentNode ... : ve_dm_BranchNode ... : ve_dm_Node ... : ve_dm_Node ... : Object ... without names (current situation): < documentNode; > Object ... : Object ... : Object ... : Object ... : Object ... though before this commit, it really looks like this (flattened since ve.extendClass really did a mixin): < documentNode; > Object ... ... ... Pattern in Sublime (case-sensitive) to find nameless constructor functions: "^ve\..*\.([A-Z])([^\.]+) = function \(" Change-Id: Iab763954fb8cf375900d7a9a92dec1c755d5407e
2012-09-05 06:07:47 +00:00
/* Events */
/**
* @event deactivate
*/
/* Static Properties */
/**
* Compatibility map used with jQuery.client to black-list incompatible browsers.
*
* @static
JSDuck: Generated code documentation! See CODING.md for how to run it. Mistakes fixed: * Warning: Unknown type function -> Function * Warning: Unknown type DOMElement -> HTMLElement * Warning: Unknown type DOM Node -> HTMLElement * Warning: Unknown type Integer -> Mixed * Warning: Unknown type Command -> ve.Command * Warning: Unknown type any -> number * Warning: Unknown type ve.Transaction -> ve.dm.Transaction * Warning: Unknown type ve.dm.AnnotationSet -> ve.AnnotationSet * Warning: Unknown type false -> boolean * Warning: Unknown type ve.dm.AlienNode ve.dm doesn't have a generic AlienNode like ve.ce -> Unknown type ve.dm.AlienInlineNode|ve.dm.AlienBlockNode * Warning: Unknown type ve.ve.Surface -> ve.ce.Surface * ve.example.lookupNode: -> Last @param should be @return * ve.dm.Transaction.prototype.pushReplace: -> @param {Array] should be @param {Array} * Warning: ve.BranchNode.js:27: {@link ve.Node#hasChildren} links to non-existing member -> (removed) * Warning: ve.LeafNode.js:21: {@link ve.Node#hasChildren} links to non-existing member -> (removed) Differences fixed: * Variadic arguments are like @param {Type...} [name] instead of @param {Type} [name...] * Convert all file headers from /** to /*! because JSDuck tries to parse all /** blocks and fails to parse with all sorts of errors for "Global property", "Unnamed property", and "Duplicate property". Find: \/\*\*([^@]+)(@copyright) Replace: /*!$1$2 * Indented blocks are considered code examples. A few methods had documentation with numbered lists that were indented, which have now been updated to not be intended. * The free-form text descriptions are parsed with Markdown, which requires lists to be separated from paragraphs by an empty line. And we should use `backticks` instead of {braces} for inline code in text paragraphs. * Doc blocks for classes and their constructor have to be in the correct order (@constructor, @param, @return must be before @class, @abstract, @extends etc.) * `@extends Class` must not have Class {wrapped} * @throws must start with a {Type} * @example means something else. It is used for an inline demo iframe, not code block. For that simply indent with spaces. * @member means something else. Non-function properties are marked with @property, not @member. * To create a link to a class or member, in most cases the name is enough to create a link. E.g. Foo, Foo.bar, Foo.bar#quux, where a hash stands for "instance member", so Foo.bar#quux, links to Foo.bar.prototype.quux (the is not supported, as "prototype" is considered an implementation detail, it only indexes class name and method name). If the magic linker doesn't work for some case, the verbose syntax is {@link #target label}. * @property can't have sub-properties (nested @param and @return values are supported, only @static @property can't be nested). We only have one case of this, which can be worked around by moving those in a new virtual class. The code is unaltered (only moved down so that it isn't with the scope of the main @class block). ve.dm.TransactionProcessor.processors. New: * @mixins: Classes mixed into the current class. * @event: Events that can be emitted by a class. These are also inherited by subclasses. (+ @param, @return and @preventable). So ve.Node#event-attach is inherited to ve.dm.BreakNode, just like @method is. * @singleton: Plain objects such as ve, ve.dm, ve.ce were missing documentation causing a tree error. Documented those as a JSDuck singleton, which they but just weren't documented yet. NB: Members of @singleton don't need @static (if present, triggers a compiler warning). * @chainable: Shorthand for "@return this". We were using "@return {classname}" which is ambiguous (returns the same instance or another instance?), @chainable is specifically for "@return this". Creates proper labels in the generated HTML pages. Removed: * @mixin: (not to be confused with @mixins). Not supported by JSDuck. Every class is standalone anyway. Where needed marked them @class + @abstract instead. Change-Id: I6a7c9e8ee8f995731bc205d666167874eb2ebe23
2013-01-04 08:54:17 +00:00
* @property
*/
ve.init.mw.DesktopArticleTarget.static.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: [ [ '>=', 7 ] ],
chrome: [ [ '>=', 19 ] ],
opera: [ [ '>=', 15 ] ]
}
};
ve.init.mw.DesktopArticleTarget.static.platformType = 'desktop';
/* Events */
/**
* @event saveWorkflowBegin
* Fired when user clicks the button to open the save dialog.
*/
/**
* @event saveWorkflowEnd
* Fired when user exits the save workflow
*/
/**
* @event saveReview
* Fired when user initiates review changes in save workflow
*/
/**
* @event saveInitiated
* Fired when user initiates saving of the document
*/
/* Methods */
/**
* Verify that a PopStateEvent correlates to a state we created.
*
* @param {Mixed} popState From PopStateEvent#state
* @return {boolean}
*/
ve.init.mw.DesktopArticleTarget.prototype.verifyPopState = function ( popState ) {
return popState && popState.tag === 'visualeditor';
};
/**
* @inheritdoc
*/
ve.init.mw.DesktopArticleTarget.prototype.setupToolbar = function ( surface ) {
var toolbar,
wasSetup = !!this.toolbar,
target = this;
ve.track( 'trace.setupToolbar.enter' );
// Parent method
ve.init.mw.DesktopArticleTarget.super.prototype.setupToolbar.call( this, surface );
toolbar = this.getToolbar();
ve.track( 'trace.setupToolbar.exit' );
if ( !wasSetup ) {
setTimeout( function () {
var height = toolbar.$bar.outerHeight();
toolbar.$element.css( 'height', height );
toolbar.$element.one( 'transitionend', function () {
// Clear to allow growth during use and when resizing window
toolbar.$element.css( 'height', '' );
target.toolbarSetupDeferred.resolve();
} );
} );
this.toolbarSetupDeferred.done( function () {
var surface = target.getSurface();
// Check the surface wasn't torn down while the toolbar was animating
if ( surface ) {
ve.track( 'trace.initializeToolbar.enter' );
target.getToolbar().initialize();
surface.getView().emit( 'position' );
surface.getContext().updateDimensions();
ve.track( 'trace.initializeToolbar.exit' );
ve.track( 'trace.activate.exit' );
}
} );
}
};
/**
* @inheritdoc
*/
ve.init.mw.DesktopArticleTarget.prototype.attachToolbar = function () {
// Move the toolbar to top of target, before heading etc.
// Avoid re-attaching as it breaks CSS animations
if ( !this.toolbar.$element.parent().is( this.$element ) ) {
this.toolbar.$element
// Set 0 before attach (expanded in #setupToolbar)
.css( 'height', '0' )
.addClass( 've-init-mw-desktopArticleTarget-toolbar' );
this.$element.prepend( this.toolbar.$element );
}
};
/**
* Set up notices for things like unknown browsers.
* Needs to be done on each activation because localNoticeMessages is cleared in clearState.
*/
ve.init.mw.DesktopArticleTarget.prototype.setupLocalNoticeMessages = function () {
if ( mw.config.get( 'wgTranslatePageTranslation' ) === 'source' ) {
// Warn users if they're on a source of the Page Translation feature
this.localNoticeMessages.push( 'visualeditor-pagetranslationwarning' );
}
if ( !(
'vewhitelist' in this.currentUri.query ||
$.client.test( this.constructor.static.compatibility.whitelist, null, true )
) ) {
// Show warning in unknown browsers that pass the support test
// Continue at own risk.
this.localNoticeMessages.push( 'visualeditor-browserwarning' );
}
};
/**
* @inheritdoc
*/
ve.init.mw.DesktopArticleTarget.prototype.loadSuccess = function ( response ) {
var $checkboxes, defaults, data,
target = this;
// Parent method
ve.init.mw.DesktopArticleTarget.super.prototype.loadSuccess.apply( this, arguments );
data = response ? response.visualeditor : {};
this.checkboxFields = [];
this.checkboxesByName = {};
this.$otherFields = $( [] );
if ( data.checkboxes ) {
defaults = {
wpMinoredit: !!mw.user.options.get( 'minordefault' ),
wpWatchthis: !!mw.user.options.get( 'watchdefault' ) ||
( !!mw.user.options.get( 'watchcreations' ) && !this.pageExists ) ||
data.watched === ''
};
$checkboxes = $( '<div>' ).html( ve.getObjectValues( data.checkboxes ).join( '' ) );
$checkboxes.find( 'input[type=checkbox]' ).each( function () {
var $label, title, checkbox,
$this = $( this ),
name = $this.attr( 'name' ),
id = $this.attr( 'id' );
if ( !name ) {
// This really shouldn't happen..
return;
}
// Label with for=id
if ( id ) {
$label = $checkboxes.find( 'label[for=' + id + ']' );
}
// Label wrapped input
if ( !$label ) {
$label = $this.closest( 'label' );
}
if ( $label ) {
title = $label.attr( 'title' );
$label.find( 'a' ).attr( 'target', '_blank' );
}
checkbox = new OO.ui.CheckboxInputWidget( {
value: $this.attr( 'value' ),
selected: name && defaults[ name ]
} );
// HACK: CheckboxInputWidget doesn't support access keys
checkbox.$input.attr( 'accesskey', $( this ).attr( 'accesskey' ) );
target.checkboxFields.push(
new OO.ui.FieldLayout( checkbox, {
align: 'inline',
label: $label ? $label.contents() : undefined,
title: title
} )
);
target.checkboxesByName[ name ] = checkbox;
} );
this.$otherFields = $checkboxes.find( 'input[type!=checkbox]' );
}
};
/**
* Handle the watch button being toggled on/off.
*
* @param {jQuery.Event} e Event object whih triggered the event
* @param {string} actionPerformed 'watch' or 'unwatch'
*/
ve.init.mw.DesktopArticleTarget.prototype.onWatchToggle = function ( e, actionPerformed ) {
if ( !this.active && !this.activating ) {
return;
}
if ( this.checkboxesByName.wpWatchthis ) {
this.checkboxesByName.wpWatchthis.setSelected(
!!mw.user.options.get( 'watchdefault' ) ||
( !!mw.user.options.get( 'watchcreations' ) && !this.pageExists ) ||
actionPerformed === 'watch'
);
}
};
/**
* @inheritdoc
*/
ve.init.mw.DesktopArticleTarget.prototype.bindHandlers = function () {
ve.init.mw.DesktopArticleTarget.super.prototype.bindHandlers.call( this );
if ( this.onWatchToggleHandler ) {
$( '#ca-watch, #ca-unwatch' ).on( 'watchpage.mw', this.onWatchToggleHandler );
}
};
/**
* @inheritdoc
*/
ve.init.mw.DesktopArticleTarget.prototype.unbindHandlers = function () {
ve.init.mw.DesktopArticleTarget.super.prototype.unbindHandlers.call( this );
if ( this.onWatchToggleHandler ) {
$( '#ca-watch, #ca-unwatch' ).off( 'watchpage.mw', this.onWatchToggleHandler );
}
};
/**
* Switch to edit mode.
*
* @param {jQuery.Promise} [dataPromise] Promise for pending request from
* mw.libs.ve.targetLoader#requestPageData, if any
* @return {jQuery.Promise}
*/
ve.init.mw.DesktopArticleTarget.prototype.activate = function ( dataPromise ) {
var surface,
target = this;
if ( !this.active && !this.activating ) {
this.activating = true;
this.activatingDeferred = $.Deferred();
this.toolbarSetupDeferred = $.Deferred();
this.maybeShowWelcomeDialog();
$( 'html' ).removeClass( 've-loading' ).addClass( 've-activating' );
$.when( this.activatingDeferred, this.toolbarSetupDeferred ).done( function () {
$( 'html' ).removeClass( 've-activating' ).addClass( 've-active' );
// We have to focus the page after hiding the original content, otherwise
// in firefox the contentEditable container was below the view page, and
// 'focus' scrolled the screen down.
target.getSurface().getView().focus();
} ).fail( function () {
$( 'html' ).removeClass( 've-activating' );
mw.ViewPageTarget: Use CSS instead of JS for DOM hiding/muting * Use .ve-activated for elements changed in activate() - hideReadOnlyContent() - mutePageContent() - mutePageTitle * Use .ve-active for elements changed in onSurfaceReady() - hidePageContent() * Set 've-activated' class from activate() instead of transformPage() to consolidate reflows and minimise DOM interaction. It's still in the same (synchronous) execution path, but a few statements earlier now. * Remove obsolete #toc wrapper. This <div> (with data property to distinguish it from potentially foreign parents in the future) was there to aid slideDown/slideUp animations, because those don't work well on table elements. See eba7d58dd19d9. * Remove obsolete setTimeout in restorePageTitle(). The removal of .ve-init-mw-viewPageTarget-pageTitle was delayed by one second (introduced in Ibc3fa2fb7 / 4cc88b9850). This was to account for a jQuery animation we no longer use. * Remove unused '.ve-init-mw-viewPageTarget-transform-muted' * Remove unused '.ve-init-mw-viewPageTarget-transform' * Remove unused '.ve-init-mw-viewPageTarget-pageTitle' The resulting stylesheet exposes that we're not consistent in whether elements hide immediately (ve-activated) or once the surface is ready (ve-active). This is intentionally kept as-is within this commit. Of the different elements that had their opacity changed, only firstHeading was being animated. This animation was removed. Bug: T88590 Bug: T87160 Change-Id: I87033456f715d99a88425e38e8ac5171144f4ec8
2015-02-05 01:45:19 +00:00
} );
this.bindHandlers();
this.originalEditondbclick = mw.user.options.get( 'editondblclick' );
mw.user.options.set( 'editondblclick', 0 );
// User interface changes
this.transformPage();
this.setupLocalNoticeMessages();
this.saveScrollPosition();
// Create dummy surface to show toolbar while loading
surface = this.addSurface( [] );
surface.disable();
// setSurface creates dummy toolbar
this.dummyToolbar = true;
this.setSurface( surface );
// Disconnect the tool factory listeners so the toolbar
// doesn't start showing new tools as they load, too
// much flickering
this.getToolbar().getToolFactory().off( 'register' );
// Disable all the tools
this.getToolbar().updateToolState();
this.load( dataPromise );
}
return this.activatingDeferred.promise();
};
/**
* Determines whether we want to switch to view mode or not (displaying a dialog if necessary)
* Then, if we do, actually switches to view mode.
*
* A dialog will not be shown if deactivate() is called while activation is still in progress,
* or if the noDialog parameter is set to true. If deactivate() is called while the target
* is deactivating, or while it's not active and not activating, nothing happens.
*
* @param {boolean} [noDialog] Do not display a dialog
* @param {string} [trackMechanism] Abort mechanism; used for event tracking if present
*/
ve.init.mw.DesktopArticleTarget.prototype.deactivate = function ( noDialog, trackMechanism ) {
Update VE core submodule to master (f2277ea) New changes: 56de6f5 Localisation updates from https://translatewiki.net. f8bda64 Widgetise demo menu 6ac48d8 Localisation updates from https://translatewiki.net. 365e131 builderloader: Omit value for boolean "disabled" attribute per HTML5 706e4b3 Prevent double counting of DM nodes in getNodeAndOffset b141a7d Update OOjs UI to v0.1.0-pre (d2451ac748) c5b3921 Localisation updates from https://translatewiki.net. 1606983 Update reference to ConfirmationDialog to use MessageDialog Deletions: * Styles for ve.ui.MWBetaWelcomeDialog - not needed anymore because OO.ui.MessageDialog provides them * Styles for ve.ui.MWGalleryInspector - not needed anymore because ve.ui.MWExtensionInspector provides part of them and the rest are being replaced by programatic sizing Modifications: * ve.ui.MWLinkTargetInputWidget - Added support for validation and href getter * Split message between tool and dialog title for ve.ui.MWEditModeTool and ve.ui.MWWikitextSwitchConfirmDialog General changes: * Updated inheritance. * Added manager param to constructors of dialogs and inspectors. * Updated use of show/hide with toggle. * Added meaningful descriptions of dialog and inspector classes. * Configured dialog and inspector sizes statically. * Configured dialog action buttons statically. * Interfaced with OO.ui.ActionSet to control action buttons. * Moved applyChanges code into getActionProcess methods. * Always using .next in setup/ready process getters and .first in hold/teardown process getters. Change-Id: Ia74732e6e32c0808eee021f0a26225b9e6c3f971
2014-07-14 21:32:49 +00:00
var target = this;
if ( this.deactivating || ( !this.active && !this.activating ) ) {
return;
}
// Just in case this wasn't closed before
if ( this.welcomeDialog ) {
this.welcomeDialog.close();
}
if ( noDialog || this.activating || !this.edited ) {
this.cancel( trackMechanism );
} else {
this.getSurface().dialogs.openWindow( 'cancelconfirm' ).then( function ( opened ) {
opened.then( function ( closing ) {
closing.then( function ( data ) {
if ( data && data.action === 'discard' ) {
target.cancel( trackMechanism );
}
} );
} );
} );
}
};
/**
* Switch to view mode
*
* @param {string} [trackMechanism] Abort mechanism; used for event tracking if present
*/
ve.init.mw.DesktopArticleTarget.prototype.cancel = function ( trackMechanism ) {
var abortType,
target = this,
promises = [];
// Event tracking
if ( trackMechanism ) {
if ( this.activating ) {
abortType = 'preinit';
} else if ( !this.edited ) {
abortType = 'nochange';
} else if ( this.saving ) {
abortType = 'abandonMidsave';
} else {
// switchwith and switchwithout do not go through this code path,
// they go through switchToWikitextEditor() instead
abortType = 'abandon';
}
ve.track( 'mwedit.abort', {
type: abortType,
mechanism: trackMechanism
} );
}
Update VE core submodule to master (f2277ea) New changes: 56de6f5 Localisation updates from https://translatewiki.net. f8bda64 Widgetise demo menu 6ac48d8 Localisation updates from https://translatewiki.net. 365e131 builderloader: Omit value for boolean "disabled" attribute per HTML5 706e4b3 Prevent double counting of DM nodes in getNodeAndOffset b141a7d Update OOjs UI to v0.1.0-pre (d2451ac748) c5b3921 Localisation updates from https://translatewiki.net. 1606983 Update reference to ConfirmationDialog to use MessageDialog Deletions: * Styles for ve.ui.MWBetaWelcomeDialog - not needed anymore because OO.ui.MessageDialog provides them * Styles for ve.ui.MWGalleryInspector - not needed anymore because ve.ui.MWExtensionInspector provides part of them and the rest are being replaced by programatic sizing Modifications: * ve.ui.MWLinkTargetInputWidget - Added support for validation and href getter * Split message between tool and dialog title for ve.ui.MWEditModeTool and ve.ui.MWWikitextSwitchConfirmDialog General changes: * Updated inheritance. * Added manager param to constructors of dialogs and inspectors. * Updated use of show/hide with toggle. * Added meaningful descriptions of dialog and inspector classes. * Configured dialog and inspector sizes statically. * Configured dialog action buttons statically. * Interfaced with OO.ui.ActionSet to control action buttons. * Moved applyChanges code into getActionProcess methods. * Always using .next in setup/ready process getters and .first in hold/teardown process getters. Change-Id: Ia74732e6e32c0808eee021f0a26225b9e6c3f971
2014-07-14 21:32:49 +00:00
this.deactivating = true;
$( 'html' ).addClass( 've-deactivating' ).removeClass( 've-activated ve-active' );
// User interface changes
if ( this.elementsThatHadOurAccessKey ) {
this.elementsThatHadOurAccessKey.attr( 'accesskey', ve.msg( 'accesskey-save' ) );
}
this.restorePage();
this.unbindHandlers();
mw.user.options.set( 'editondblclick', this.originalEditondbclick );
this.originalEditondbclick = undefined;
if ( this.toolbarSaveButton ) {
// If deactivate is called before a successful load, then the save button has not yet been
// fully set up so disconnecting it would throw an error when trying call methods on the
// button property (bug 46456)
this.toolbarSaveButton.disconnect( this );
this.toolbarSaveButton.$element.detach();
this.getToolbar().$actions.empty();
}
// Check we got as far as setting up the surface
if ( this.active ) {
this.teardownUnloadHandlers();
// If we got as far as setting up the surface, tear that down
promises.push( this.teardownSurface() );
} else if ( this.toolbar ) {
// If a dummy toolbar was created, destroy it
this.toolbar.destroy();
}
$.when.apply( null, promises ).done( function () {
Update VE core submodule to master (f2277ea) New changes: 56de6f5 Localisation updates from https://translatewiki.net. f8bda64 Widgetise demo menu 6ac48d8 Localisation updates from https://translatewiki.net. 365e131 builderloader: Omit value for boolean "disabled" attribute per HTML5 706e4b3 Prevent double counting of DM nodes in getNodeAndOffset b141a7d Update OOjs UI to v0.1.0-pre (d2451ac748) c5b3921 Localisation updates from https://translatewiki.net. 1606983 Update reference to ConfirmationDialog to use MessageDialog Deletions: * Styles for ve.ui.MWBetaWelcomeDialog - not needed anymore because OO.ui.MessageDialog provides them * Styles for ve.ui.MWGalleryInspector - not needed anymore because ve.ui.MWExtensionInspector provides part of them and the rest are being replaced by programatic sizing Modifications: * ve.ui.MWLinkTargetInputWidget - Added support for validation and href getter * Split message between tool and dialog title for ve.ui.MWEditModeTool and ve.ui.MWWikitextSwitchConfirmDialog General changes: * Updated inheritance. * Added manager param to constructors of dialogs and inspectors. * Updated use of show/hide with toggle. * Added meaningful descriptions of dialog and inspector classes. * Configured dialog and inspector sizes statically. * Configured dialog action buttons statically. * Interfaced with OO.ui.ActionSet to control action buttons. * Moved applyChanges code into getActionProcess methods. * Always using .next in setup/ready process getters and .first in hold/teardown process getters. Change-Id: Ia74732e6e32c0808eee021f0a26225b9e6c3f971
2014-07-14 21:32:49 +00:00
// If there is a load in progress, abort it
if ( target.loading ) {
target.loading.abort();
Update VE core submodule to master (f2277ea) New changes: 56de6f5 Localisation updates from https://translatewiki.net. f8bda64 Widgetise demo menu 6ac48d8 Localisation updates from https://translatewiki.net. 365e131 builderloader: Omit value for boolean "disabled" attribute per HTML5 706e4b3 Prevent double counting of DM nodes in getNodeAndOffset b141a7d Update OOjs UI to v0.1.0-pre (d2451ac748) c5b3921 Localisation updates from https://translatewiki.net. 1606983 Update reference to ConfirmationDialog to use MessageDialog Deletions: * Styles for ve.ui.MWBetaWelcomeDialog - not needed anymore because OO.ui.MessageDialog provides them * Styles for ve.ui.MWGalleryInspector - not needed anymore because ve.ui.MWExtensionInspector provides part of them and the rest are being replaced by programatic sizing Modifications: * ve.ui.MWLinkTargetInputWidget - Added support for validation and href getter * Split message between tool and dialog title for ve.ui.MWEditModeTool and ve.ui.MWWikitextSwitchConfirmDialog General changes: * Updated inheritance. * Added manager param to constructors of dialogs and inspectors. * Updated use of show/hide with toggle. * Added meaningful descriptions of dialog and inspector classes. * Configured dialog and inspector sizes statically. * Configured dialog action buttons statically. * Interfaced with OO.ui.ActionSet to control action buttons. * Moved applyChanges code into getActionProcess methods. * Always using .next in setup/ready process getters and .first in hold/teardown process getters. Change-Id: Ia74732e6e32c0808eee021f0a26225b9e6c3f971
2014-07-14 21:32:49 +00:00
}
target.clearState();
target.docToSave = null;
target.initialEditSummary = new mw.Uri().query.summary;
target.deactivating = false;
target.activating = false;
target.activatingDeferred.reject();
$( 'html' ).removeClass( 've-deactivating' );
// Move remaining elements back out of the target
target.$element.parent().append( target.$element.children() );
mw.hook( 've.deactivationComplete' ).fire( target.edited );
} );
};
/**
* @inheritdoc
*/
ve.init.mw.DesktopArticleTarget.prototype.loadFail = function ( errorText, error ) {
// Parent method
ve.init.mw.DesktopArticleTarget.super.prototype.loadFail.apply( this, arguments );
// 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 (
error &&
Object.prototype.hasOwnProperty.call( error, 'error' ) &&
Object.prototype.hasOwnProperty.call( error.error, 'info' )
) {
error = error.error.info;
}
if (
errorText === 'http' &&
( error.statusText !== 'abort' || error.xhr.status !== 504 ) &&
confirm( ve.msg( 'visualeditor-loadwarning', 'HTTP ' + error.xhr.status ) )
) {
this.load();
} else if (
errorText === 'http' && error.xhr.status === 504 &&
confirm( ve.msg( 'visualeditor-timeout' ) )
) {
if ( 'veaction' in this.currentUri.query ) {
delete this.currentUri.query.veaction;
}
this.currentUri.query.action = 'edit';
location.href = this.currentUri.toString();
} else if (
errorText !== 'http' &&
typeof error === 'string' &&
confirm( ve.msg( 'visualeditor-loadwarning', errorText + ': ' + error ) )
) {
this.load();
} else {
// Something weird happened? Deactivate
// Not passing trackMechanism because we don't know what happened
// and this is not a user action
this.deactivate( true );
}
};
/**
* @inheritdoc
*/
ve.init.mw.DesktopArticleTarget.prototype.onSurfaceReady = function () {
var surfaceReadyTime = ve.now(),
target = this;
if ( !this.activating ) {
// Activation was aborted before we got here. Do nothing
// TODO are there things we need to clean up?
return;
}
mw.ViewPageTarget: Use CSS instead of JS for DOM hiding/muting * Use .ve-activated for elements changed in activate() - hideReadOnlyContent() - mutePageContent() - mutePageTitle * Use .ve-active for elements changed in onSurfaceReady() - hidePageContent() * Set 've-activated' class from activate() instead of transformPage() to consolidate reflows and minimise DOM interaction. It's still in the same (synchronous) execution path, but a few statements earlier now. * Remove obsolete #toc wrapper. This <div> (with data property to distinguish it from potentially foreign parents in the future) was there to aid slideDown/slideUp animations, because those don't work well on table elements. See eba7d58dd19d9. * Remove obsolete setTimeout in restorePageTitle(). The removal of .ve-init-mw-viewPageTarget-pageTitle was delayed by one second (introduced in Ibc3fa2fb7 / 4cc88b9850). This was to account for a jQuery animation we no longer use. * Remove unused '.ve-init-mw-viewPageTarget-transform-muted' * Remove unused '.ve-init-mw-viewPageTarget-transform' * Remove unused '.ve-init-mw-viewPageTarget-pageTitle' The resulting stylesheet exposes that we're not consistent in whether elements hide immediately (ve-activated) or once the surface is ready (ve-active). This is intentionally kept as-is within this commit. Of the different elements that had their opacity changed, only firstHeading was being animated. This animation was removed. Bug: T88590 Bug: T87160 Change-Id: I87033456f715d99a88425e38e8ac5171144f4ec8
2015-02-05 01:45:19 +00:00
this.activating = false;
// TODO: mwTocWidget should probably live in a ve.ui.MWSurface subclass
if ( mw.config.get( 'wgVisualEditorConfig' ).enableTocWidget ) {
this.getSurface().mwTocWidget = new ve.ui.MWTocWidget( this.getSurface() );
}
// Track how long it takes for the first transaction to happen
this.surface.getModel().getDocument().once( 'transact', function () {
ve.track( 'mwtiming.behavior.firstTransaction', {
duration: ve.now() - surfaceReadyTime,
targetName: target.constructor.static.name
} );
} );
// Update UI
this.changeDocumentTitle();
this.restoreScrollPosition();
// Parent method
ve.init.mw.DesktopArticleTarget.super.prototype.onSurfaceReady.apply( this, arguments );
this.setupUnloadHandlers();
this.maybeShowMetaDialog();
this.activatingDeferred.resolve();
this.events.trackActivationComplete();
mw.hook( 've.activationComplete' ).fire();
};
/**
* Handle Escape key presses.
*
* @param {jQuery.Event} e Keydown event
*/
ve.init.mw.DesktopArticleTarget.prototype.onDocumentKeyDown = function ( e ) {
var target = this;
// Parent method
ve.init.mw.DesktopArticleTarget.super.prototype.onDocumentKeyDown.apply( this, arguments );
if ( e.which === OO.ui.Keys.ESCAPE ) {
setTimeout( function () {
// Listeners should stopPropagation if they handle the escape key, but
// also check they didn't fire after this event, as would be the case if
// they were bound to the document.
if ( !e.isPropagationStopped() ) {
target.deactivate( false, 'navigate-read' );
}
} );
e.preventDefault();
}
};
/**
* Handle clicks on the view tab.
*
* @method
* @param {jQuery.Event} e Mouse click event
*/
ve.init.mw.DesktopArticleTarget.prototype.onViewTabClick = function ( e ) {
if ( ( e.which && e.which !== 1 ) || e.shiftKey || e.altKey || e.ctrlKey || e.metaKey ) {
return;
}
this.deactivate( false, 'navigate-read' );
e.preventDefault();
};
/**
* @inheritdoc
*/
ve.init.mw.DesktopArticleTarget.prototype.saveComplete = function (
html, categoriesHtml, newid, isRedirect, displayTitle, lastModified, contentSub, modules, jsconfigvars
) {
var newUrlParams, watchChecked;
// Parent method
ve.init.mw.DesktopArticleTarget.super.prototype.saveComplete.apply( this, arguments );
if ( !this.pageExists || this.restoring ) {
// This is a page creation or restoration, refresh the page
this.teardownUnloadHandlers();
newUrlParams = newid === undefined ? {} : { venotify: this.restoring ? 'restored' : 'created' };
if ( isRedirect ) {
newUrlParams.redirect = 'no';
}
location.href = this.viewUri.extend( newUrlParams );
} 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.hasOwnProperty( 'watch' ) ) {
watchChecked = this.checkboxesByName.wpWatchthis && this.checkboxesByName.wpWatchthis.isSelected();
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,
wgRevisionId: newid
} );
this.revid = newid;
}
// Update module JS config values and notify ResourceLoader of any new
// modules needed to be added to the page
mw.config.set( jsconfigvars );
mw.loader.load( modules );
this.saveDialog.reset();
this.replacePageContent(
html,
categoriesHtml,
displayTitle,
lastModified,
contentSub
);
if ( newid !== undefined ) {
$( '#t-permalink a, #coll-download-as-rl a' ).each( function () {
var uri = new mw.Uri( $( this ).attr( 'href' ) );
uri.query.oldid = newid;
$( this ).attr( 'href', uri.toString() );
} );
}
this.setupSectionEditLinks();
// Tear down the target now that we're done saving
// Not passing trackMechanism because this isn't an abort action
this.deactivate( true );
if ( newid !== undefined ) {
mw.hook( 'postEdit' ).fire( {
message: ve.msg( 'postedit-confirmation-saved', mw.user )
} );
}
}
};
/**
* @inheritdoc
*/
ve.init.mw.DesktopArticleTarget.prototype.serializeFail = function ( jqXHR, status ) {
// Parent method
ve.init.mw.DesktopArticleTarget.super.prototype.serializeFail.apply( this, arguments );
alert( ve.msg( 'visualeditor-serializeerror', status ) );
this.getSurface().getDialogs().closeWindow( 'wikitextswitchconfirm' );
// 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.popPending();
}
};
/**
* Handle clicks on the MwMeta button in the toolbar.
*
* @method
* @param {jQuery.Event} e Mouse click event
*/
ve.init.mw.DesktopArticleTarget.prototype.onToolbarMetaButtonClick = function () {
this.getSurface().getDialogs().openWindow( 'meta' );
};
/**
* Open the dialog to switch to edit source mode with the current wikitext, or just do it straight
* away if the document is unmodified. If we open the dialog, the document opacity will be set to
* half, which can be reset with the resetDocumentOpacity function.
*
* @inheritdoc
*/
ve.init.mw.DesktopArticleTarget.prototype.editSource = function () {
if ( !this.getSurface().getModel().hasBeenModified() && !this.fromEditedState ) {
this.switchToWikitextEditor( true, false );
return;
}
this.getSurface().getView().getDocument().getDocumentNode().$element.css( 'opacity', 0.5 );
this.getSurface().getDialogs().openWindow( 'wikitextswitchconfirm', { target: this } );
};
/**
* @inheritdoc
*/
ve.init.mw.DesktopArticleTarget.prototype.getSaveFields = function () {
var name, fieldValues = {};
for ( name in this.checkboxesByName ) {
if ( this.checkboxesByName[ name ].isSelected() ) {
fieldValues[ name ] = this.checkboxesByName[ name ].getValue();
}
}
this.$otherFields.each( function () {
var $this = $( this ),
name = $this.prop( 'name' );
if ( name ) {
fieldValues[ name ] = $this.val();
}
} );
return ve.extendObject(
fieldValues,
ve.init.mw.DesktopArticleTarget.super.prototype.getSaveFields.call( this )
);
};
/**
* Switch to viewing mode.
*
Update VE core submodule to master (f2277ea) New changes: 56de6f5 Localisation updates from https://translatewiki.net. f8bda64 Widgetise demo menu 6ac48d8 Localisation updates from https://translatewiki.net. 365e131 builderloader: Omit value for boolean "disabled" attribute per HTML5 706e4b3 Prevent double counting of DM nodes in getNodeAndOffset b141a7d Update OOjs UI to v0.1.0-pre (d2451ac748) c5b3921 Localisation updates from https://translatewiki.net. 1606983 Update reference to ConfirmationDialog to use MessageDialog Deletions: * Styles for ve.ui.MWBetaWelcomeDialog - not needed anymore because OO.ui.MessageDialog provides them * Styles for ve.ui.MWGalleryInspector - not needed anymore because ve.ui.MWExtensionInspector provides part of them and the rest are being replaced by programatic sizing Modifications: * ve.ui.MWLinkTargetInputWidget - Added support for validation and href getter * Split message between tool and dialog title for ve.ui.MWEditModeTool and ve.ui.MWWikitextSwitchConfirmDialog General changes: * Updated inheritance. * Added manager param to constructors of dialogs and inspectors. * Updated use of show/hide with toggle. * Added meaningful descriptions of dialog and inspector classes. * Configured dialog and inspector sizes statically. * Configured dialog action buttons statically. * Interfaced with OO.ui.ActionSet to control action buttons. * Moved applyChanges code into getActionProcess methods. * Always using .next in setup/ready process getters and .first in hold/teardown process getters. Change-Id: Ia74732e6e32c0808eee021f0a26225b9e6c3f971
2014-07-14 21:32:49 +00:00
* @return {jQuery.Promise} Promise resolved when surface is torn down
*/
ve.init.mw.DesktopArticleTarget.prototype.teardownSurface = function () {
var target = this,
promises = [];
Update VE core submodule to master (f2277ea) New changes: 56de6f5 Localisation updates from https://translatewiki.net. f8bda64 Widgetise demo menu 6ac48d8 Localisation updates from https://translatewiki.net. 365e131 builderloader: Omit value for boolean "disabled" attribute per HTML5 706e4b3 Prevent double counting of DM nodes in getNodeAndOffset b141a7d Update OOjs UI to v0.1.0-pre (d2451ac748) c5b3921 Localisation updates from https://translatewiki.net. 1606983 Update reference to ConfirmationDialog to use MessageDialog Deletions: * Styles for ve.ui.MWBetaWelcomeDialog - not needed anymore because OO.ui.MessageDialog provides them * Styles for ve.ui.MWGalleryInspector - not needed anymore because ve.ui.MWExtensionInspector provides part of them and the rest are being replaced by programatic sizing Modifications: * ve.ui.MWLinkTargetInputWidget - Added support for validation and href getter * Split message between tool and dialog title for ve.ui.MWEditModeTool and ve.ui.MWWikitextSwitchConfirmDialog General changes: * Updated inheritance. * Added manager param to constructors of dialogs and inspectors. * Updated use of show/hide with toggle. * Added meaningful descriptions of dialog and inspector classes. * Configured dialog and inspector sizes statically. * Configured dialog action buttons statically. * Interfaced with OO.ui.ActionSet to control action buttons. * Moved applyChanges code into getActionProcess methods. * Always using .next in setup/ready process getters and .first in hold/teardown process getters. Change-Id: Ia74732e6e32c0808eee021f0a26225b9e6c3f971
2014-07-14 21:32:49 +00:00
// Update UI
promises.push( this.teardownToolbar(), this.teardownDebugBar() );
this.restoreDocumentTitle();
if ( this.getSurface().mwTocWidget ) {
this.getSurface().mwTocWidget.teardown();
}
if ( this.saveDialog ) {
if ( this.saveDialog.isOpened() ) {
// If the save dialog is still open (from saving) close it
promises.push( this.saveDialog.close() );
}
// Release the reference
this.saveDialog = null;
}
Update VE core submodule to master (f2277ea) New changes: 56de6f5 Localisation updates from https://translatewiki.net. f8bda64 Widgetise demo menu 6ac48d8 Localisation updates from https://translatewiki.net. 365e131 builderloader: Omit value for boolean "disabled" attribute per HTML5 706e4b3 Prevent double counting of DM nodes in getNodeAndOffset b141a7d Update OOjs UI to v0.1.0-pre (d2451ac748) c5b3921 Localisation updates from https://translatewiki.net. 1606983 Update reference to ConfirmationDialog to use MessageDialog Deletions: * Styles for ve.ui.MWBetaWelcomeDialog - not needed anymore because OO.ui.MessageDialog provides them * Styles for ve.ui.MWGalleryInspector - not needed anymore because ve.ui.MWExtensionInspector provides part of them and the rest are being replaced by programatic sizing Modifications: * ve.ui.MWLinkTargetInputWidget - Added support for validation and href getter * Split message between tool and dialog title for ve.ui.MWEditModeTool and ve.ui.MWWikitextSwitchConfirmDialog General changes: * Updated inheritance. * Added manager param to constructors of dialogs and inspectors. * Updated use of show/hide with toggle. * Added meaningful descriptions of dialog and inspector classes. * Configured dialog and inspector sizes statically. * Configured dialog action buttons statically. * Interfaced with OO.ui.ActionSet to control action buttons. * Moved applyChanges code into getActionProcess methods. * Always using .next in setup/ready process getters and .first in hold/teardown process getters. Change-Id: Ia74732e6e32c0808eee021f0a26225b9e6c3f971
2014-07-14 21:32:49 +00:00
return $.when.apply( null, promises ).then( function () {
Update VE core submodule to master (f2277ea) New changes: 56de6f5 Localisation updates from https://translatewiki.net. f8bda64 Widgetise demo menu 6ac48d8 Localisation updates from https://translatewiki.net. 365e131 builderloader: Omit value for boolean "disabled" attribute per HTML5 706e4b3 Prevent double counting of DM nodes in getNodeAndOffset b141a7d Update OOjs UI to v0.1.0-pre (d2451ac748) c5b3921 Localisation updates from https://translatewiki.net. 1606983 Update reference to ConfirmationDialog to use MessageDialog Deletions: * Styles for ve.ui.MWBetaWelcomeDialog - not needed anymore because OO.ui.MessageDialog provides them * Styles for ve.ui.MWGalleryInspector - not needed anymore because ve.ui.MWExtensionInspector provides part of them and the rest are being replaced by programatic sizing Modifications: * ve.ui.MWLinkTargetInputWidget - Added support for validation and href getter * Split message between tool and dialog title for ve.ui.MWEditModeTool and ve.ui.MWWikitextSwitchConfirmDialog General changes: * Updated inheritance. * Added manager param to constructors of dialogs and inspectors. * Updated use of show/hide with toggle. * Added meaningful descriptions of dialog and inspector classes. * Configured dialog and inspector sizes statically. * Configured dialog action buttons statically. * Interfaced with OO.ui.ActionSet to control action buttons. * Moved applyChanges code into getActionProcess methods. * Always using .next in setup/ready process getters and .first in hold/teardown process getters. Change-Id: Ia74732e6e32c0808eee021f0a26225b9e6c3f971
2014-07-14 21:32:49 +00:00
// Destroy surface
while ( target.surfaces.length ) {
target.surfaces.pop().destroy();
Update VE core submodule to master (f2277ea) New changes: 56de6f5 Localisation updates from https://translatewiki.net. f8bda64 Widgetise demo menu 6ac48d8 Localisation updates from https://translatewiki.net. 365e131 builderloader: Omit value for boolean "disabled" attribute per HTML5 706e4b3 Prevent double counting of DM nodes in getNodeAndOffset b141a7d Update OOjs UI to v0.1.0-pre (d2451ac748) c5b3921 Localisation updates from https://translatewiki.net. 1606983 Update reference to ConfirmationDialog to use MessageDialog Deletions: * Styles for ve.ui.MWBetaWelcomeDialog - not needed anymore because OO.ui.MessageDialog provides them * Styles for ve.ui.MWGalleryInspector - not needed anymore because ve.ui.MWExtensionInspector provides part of them and the rest are being replaced by programatic sizing Modifications: * ve.ui.MWLinkTargetInputWidget - Added support for validation and href getter * Split message between tool and dialog title for ve.ui.MWEditModeTool and ve.ui.MWWikitextSwitchConfirmDialog General changes: * Updated inheritance. * Added manager param to constructors of dialogs and inspectors. * Updated use of show/hide with toggle. * Added meaningful descriptions of dialog and inspector classes. * Configured dialog and inspector sizes statically. * Configured dialog action buttons statically. * Interfaced with OO.ui.ActionSet to control action buttons. * Moved applyChanges code into getActionProcess methods. * Always using .next in setup/ready process getters and .first in hold/teardown process getters. Change-Id: Ia74732e6e32c0808eee021f0a26225b9e6c3f971
2014-07-14 21:32:49 +00:00
}
target.active = false;
} );
};
/**
* Modify tabs in the skin to support in-place editing.
* Edit tab is bound outside the module in mw.DesktopArticleTarget.init.
*
* @method
*/
ve.init.mw.DesktopArticleTarget.prototype.setupSkinTabs = function () {
var target = this;
if ( this.isViewPage ) {
// Allow instant switching back to view mode, without refresh
$( '#ca-view a, #ca-nstab-visualeditor a' )
.click( this.onViewTabClick.bind( this ) );
$( '#ca-viewsource, #ca-edit' ).click( function ( e ) {
if ( !target.active || e.which !== 1 || e.shiftKey || e.altKey || e.ctrlKey || e.metaKey ) {
return;
}
if ( target.getSurface() && !target.deactivating ) {
target.editSource();
if ( target.getSurface().getModel().hasBeenModified() || target.fromEditedState ) {
e.preventDefault();
}
}
} );
}
mw.hook( 've.skinTabSetupComplete' ).fire();
};
/**
* Modify page content to make section edit links activate the editor.
* Dummy replaced by init.js so that we can call it again from #saveSuccess after
* replacing the page contents with the new html.
*/
ve.init.mw.DesktopArticleTarget.prototype.setupSectionEditLinks = null;
/**
* @inheritdoc
*/
ve.init.mw.DesktopArticleTarget.prototype.attachToolbarSaveButton = function () {
this.actionsToolbar = new ve.ui.TargetToolbar( this );
this.actionsToolbar.setup( [
{ include: [ 'help', 'notices' ] },
{
type: 'list',
icon: 'menu',
title: ve.msg( 'visualeditor-pagemenu-tooltip' ),
include: [ 'meta', 'settings', 'advancedSettings', 'categories', 'languages', 'findAndReplace' ]
},
{ include: [ 'editModeSource' ] }
], this.getSurface() );
this.toolbar.$actions.append( this.actionsToolbar.$element, this.toolbarSaveButton.$element );
this.actionsToolbar.initialize();
// Make the toolbar recalculate its sizes for narrow/wide switching.
// This really should not be necessary.
this.toolbar.narrowThreshold = this.toolbar.$group.width() + this.toolbar.$actions.width();
};
/**
* @inheritdoc
*/
ve.init.mw.DesktopArticleTarget.prototype.openSaveDialog = function () {
var windowAction = ve.ui.actionFactory.create( 'window', this.getSurface() );
Update VE core submodule to master (f2277ea) New changes: 56de6f5 Localisation updates from https://translatewiki.net. f8bda64 Widgetise demo menu 6ac48d8 Localisation updates from https://translatewiki.net. 365e131 builderloader: Omit value for boolean "disabled" attribute per HTML5 706e4b3 Prevent double counting of DM nodes in getNodeAndOffset b141a7d Update OOjs UI to v0.1.0-pre (d2451ac748) c5b3921 Localisation updates from https://translatewiki.net. 1606983 Update reference to ConfirmationDialog to use MessageDialog Deletions: * Styles for ve.ui.MWBetaWelcomeDialog - not needed anymore because OO.ui.MessageDialog provides them * Styles for ve.ui.MWGalleryInspector - not needed anymore because ve.ui.MWExtensionInspector provides part of them and the rest are being replaced by programatic sizing Modifications: * ve.ui.MWLinkTargetInputWidget - Added support for validation and href getter * Split message between tool and dialog title for ve.ui.MWEditModeTool and ve.ui.MWWikitextSwitchConfirmDialog General changes: * Updated inheritance. * Added manager param to constructors of dialogs and inspectors. * Updated use of show/hide with toggle. * Added meaningful descriptions of dialog and inspector classes. * Configured dialog and inspector sizes statically. * Configured dialog action buttons statically. * Interfaced with OO.ui.ActionSet to control action buttons. * Moved applyChanges code into getActionProcess methods. * Always using .next in setup/ready process getters and .first in hold/teardown process getters. Change-Id: Ia74732e6e32c0808eee021f0a26225b9e6c3f971
2014-07-14 21:32:49 +00:00
// Open the dialog
windowAction.open( 'mwSave', {
target: this,
editSummary: this.initialEditSummary,
checkboxFields: this.checkboxFields,
checkboxesByName: this.checkboxesByName
} );
this.initialEditSummary = undefined;
};
/**
* Remember the window's scroll position.
*/
ve.init.mw.DesktopArticleTarget.prototype.saveScrollPosition = function () {
this.scrollTop = $( window ).scrollTop();
};
/**
* Restore the window's scroll position.
*/
ve.init.mw.DesktopArticleTarget.prototype.restoreScrollPosition = function () {
if ( this.scrollTop ) {
$( window ).scrollTop( this.scrollTop );
this.scrollTop = null;
}
};
/**
* Hide the toolbar.
*
* @return {jQuery.Promise} Promise which resolves when toolbar is hidden
*/
ve.init.mw.DesktopArticleTarget.prototype.teardownToolbar = function () {
var target = this,
deferred = $.Deferred();
this.toolbar.$element.css( 'height', this.toolbar.$bar.outerHeight() );
setTimeout( function () {
target.toolbar.$element.css( 'height', '0' );
target.toolbar.$element.one( 'transitionend', function () {
target.toolbar.destroy();
target.toolbar = null;
deferred.resolve();
} );
} );
return deferred.promise();
};
/**
* Hide the debug bar.
*
* @return {jQuery.Promise} Promise which resolves when debug bar is hidden
*/
ve.init.mw.DesktopArticleTarget.prototype.teardownDebugBar = function () {
var target = this;
if ( this.debugBar ) {
return this.debugBar.$element.slideUp( 'fast' ).promise().then( function () {
target.debugBar.$element.remove();
target.debugBar = null;
} );
}
return $.Deferred().resolve().promise();
};
/**
* Change the document title to state that we are now editing.
*/
ve.init.mw.DesktopArticleTarget.prototype.changeDocumentTitle = function () {
var pageName = mw.config.get( 'wgPageName' ),
title = mw.Title.newFromText( pageName );
if ( title ) {
pageName = title.getPrefixedText();
}
document.title = ve.msg(
this.pageExists ? 'editing' : 'creating',
pageName
) + ' - ' + mw.config.get( 'wgSiteName' );
};
/**
* Restore the original document title.
*/
ve.init.mw.DesktopArticleTarget.prototype.restoreDocumentTitle = function () {
document.title = this.originalDocumentTitle;
};
/**
* Page modifications for switching to edit mode.
*/
ve.init.mw.DesktopArticleTarget.prototype.transformPage = function () {
var uri;
// Deselect current mode (e.g. "view" or "history"). In skins like monobook that don't have
// separate tab sections for content actions and namespaces the below is a no-op.
$( '#p-views' ).find( 'li.selected' ).removeClass( 'selected' );
$( '#ca-ve-edit' ).addClass( 'selected' );
mw.hook( 've.activate' ).fire();
// Move all native content inside the target
this.$element.append( this.$element.siblings() );
// Push veaction=edit url in history (if not already. If we got here by a veaction=edit
// permalink then it will be there already and the constructor called #activate)
if ( !this.actFromPopState && history.pushState && this.currentUri.query.veaction !== 'edit' ) {
// Set the current URL
uri = this.currentUri;
uri.query.veaction = 'edit';
delete uri.query.action;
mw.config.set( 'wgAction', 'view' );
history.pushState( this.popState, document.title, uri );
}
this.actFromPopState = false;
};
/**
* Page modifications for switching back to view mode.
*/
ve.init.mw.DesktopArticleTarget.prototype.restorePage = function () {
var uri, keys;
// Skins like monobook don't have a tab for view mode and instead just have the namespace tab
// selected. We didn't deselect the namespace tab, so we're ready after deselecting #ca-ve-edit.
// In skins having #ca-view (like Vector), select that.
$( '#ca-ve-edit' ).removeClass( 'selected' );
$( '#ca-view' ).addClass( 'selected' );
mw.hook( 've.deactivate' ).fire();
this.emit( 'deactivate' );
// Push article url into history
if ( !this.actFromPopState && history.pushState ) {
// Remove the VisualEditor query parameters
uri = this.currentUri;
if ( 'veaction' in uri.query ) {
delete uri.query.veaction;
}
if ( 'vesection' in uri.query ) {
delete uri.query.vesection;
}
if ( 'action' in uri.query ) {
delete uri.query.action;
mw.config.set( 'wgAction', 'view' );
}
// If there are any other query parameters left, re-use that uri object.
// Otherwise use the canonical style view url (T44553, T102363).
keys = Object.keys( uri.query );
if ( !keys.length || ( keys.length === 1 && keys[ 0 ] === 'title' ) ) {
history.pushState( this.popState, document.title, this.viewUri );
} else {
history.pushState( this.popState, document.title, uri );
}
}
this.actFromPopState = false;
};
/**
* @param {Event} e Native event object
*/
ve.init.mw.DesktopArticleTarget.prototype.onWindowPopState = function ( e ) {
var newUri;
if ( !this.verifyPopState( e.state ) ) {
// Ignore popstate events fired for states not created by us
// This also filters out the initial fire in Chrome (bug 57901).
return;
}
newUri = this.currentUri = new mw.Uri( location.href );
if ( !this.active && newUri.query.veaction === 'edit' ) {
this.actFromPopState = true;
this.activate();
}
if ( this.active && newUri.query.veaction !== 'edit' ) {
this.actFromPopState = true;
this.deactivate( false, 'navigate-back' );
}
};
/**
* Replace the page content with new HTML.
*
* @method
* @param {string} html Rendered HTML from server
* @param {string} categoriesHtml Rendered categories HTML from server
* @param {string} displayTitle HTML to show as the page title
* @param {Object} lastModified Object containing user-formatted date
* and time strings, or undefined if we made no change.
* @param {string} contentSub HTML to show as the content subtitle
*/
ve.init.mw.DesktopArticleTarget.prototype.replacePageContent = function (
html, categoriesHtml, displayTitle, lastModified, contentSub
) {
var $editableContent, $imgContent,
$content = $( $.parseHTML( html ) );
if ( lastModified ) {
// If we were not viewing the most recent revision before (a requirement
// for lastmod to have been added by MediaWiki), we will be now.
if ( !$( '#footer-info-lastmod' ).length ) {
$( '#footer-info' ).prepend(
$( '<li>' ).attr( 'id', 'footer-info-lastmod' )
);
}
$( '#footer-info-lastmod' ).html( ' ' + mw.msg(
'lastmodifiedat',
lastModified.date,
lastModified.time
) );
}
$imgContent = $( '#mw-imagepage-content' );
if ( $imgContent.length ) {
// On file pages, we only want to replace the (local) description.
$editableContent = $imgContent;
} else if ( $( '#mw-pages' ).length ) {
// It would be nice if MW core did this for us...
if ( !$( '#ve-cat-description' ).length ) {
$( '#mw-content-text > :not(div:has(#mw-pages))' ).wrapAll(
$( '<div>' )
.attr( 'id', 've-cat-description' )
);
}
$editableContent = $( '#ve-cat-description' );
} else {
$editableContent = $( '#mw-content-text' );
}
mw.hook( 'wikipage.content' ).fire( $editableContent.empty().append( $content ) );
if ( displayTitle ) {
$( '#content > #firstHeading > span:first' ).html( displayTitle );
}
$( '#catlinks' ).replaceWith( categoriesHtml );
$( '#contentSub' ).html( contentSub );
};
/**
* Get the numeric index of a section in the page.
*
* @method
* @param {HTMLElement} heading Heading element of section
*/
ve.init.mw.DesktopArticleTarget.prototype.getEditSection = function ( heading ) {
var $page = $( '#mw-content-text' ),
section = 0;
Kranitor #1: On-boarding '''Kranitor commits''' are commits by Krinkle with his janitor hat on. Must never contain functional changes mixed with miscellaneous changes. .gitignore: * Add .DS_Store to the ignore list so that browsing the directories on Mac OS X, will not add these files to the list of untracked files. * Fix missing newline at end of file .jshintrc * raises -> throws * +module (QUnit.module) * remove 'Node' (as of node-jshint 1.7.2 this is now part of 'browser:true', as it should be) Authors: * Adding myself MWExtension/VisualEditor.php * Fix default value of wgVisualEditorParsoidURL to not point to the experimental instance in WMF Labs. Issues: * ve.ce.TextNode: - Fix TODO: Don't perform a useless clone of an already-jQuerified object. - Use .html() to set html content instead of encapsulating between two strings. This is slightly faster but more importantly safer, and prevents situations where the resulting jQuery collection actually contains 2 elements instead of 1, thus messing up what .contents() is iterating over. * ve.ce.Document.test.js - Fix: ReferenceError: assert is not defined * ve.dm.Document.test.js - Fix: ReferenceError: assert is not defined * ve.dm.Transaction.test.js - Fix: ReferenceError: assert is not defined * ve.dm.TransactionProcessor.test.js - Fix: ReferenceError: assert is not defined * ext.visualEditor.viewPageTarget - Missing dependency on 'mediawiki.Title' Code conventions / Misc cleanup * Various JSHint warnings. * Whitespace * jQuery(): Use '<tag>' for element creation, use '<valid><xml/></valid>' for parsing * Use the default operator instead of ternary when the condition and first value are the same. x = foo ? foo : bar; -> x = foo || bar; Because contrary to some programming language (PHP...), in JS the default operator does not enforce a boolean result but returns the original value, hence it being called the 'default' operator, as opposed to the 'or' operator. * No need to call addClass() twice, it takes a space-separated list (jQuery splits by space and adds if needed) * Use .on( event[, selector], fn ) instead of the deprecated routers to it such as .bind(), .delegate() and .live(). All these three are now built-in and fully compatible with .on() * Add 'XXX:' comments for suspicious code that I don't want to change as part of a clean up commit. * Remove unused variables (several var x = this; where x was not used anywhere, possibly from boilerplate copy/paste) * Follows-up Trevor's commit that converts test suites to the new QUnit format. Also removed the globals since we no longer use those any more. Change-Id: I7e37c9bff812e371c7f65a6fd85d9e2af3e0a22f
2012-07-27 08:43:33 +00:00
$page.find( 'h1, h2, h3, h4, h5, h6' ).not( '#toc h2' ).each( function () {
section++;
if ( this === heading ) {
return false;
}
} );
return section;
};
/**
* Store the section for which the edit link has been triggered.
*
* @method
* @param {HTMLElement} heading Heading element of section
*/
ve.init.mw.DesktopArticleTarget.prototype.saveEditSection = function ( heading ) {
this.section = this.getEditSection( heading );
};
/**
* Add onunload and onbeforeunload handlers.
*
* @method
*/
ve.init.mw.DesktopArticleTarget.prototype.setupUnloadHandlers = function () {
// Remember any already set beforeunload handler
this.onBeforeUnloadFallback = window.onbeforeunload;
// Attach our handlers
window.onbeforeunload = this.onBeforeUnload.bind( this );
window.addEventListener( 'unload', this.onUnloadHandler );
};
/**
* Remove onunload and onbeforunload handlers.
*
* @method
*/
ve.init.mw.DesktopArticleTarget.prototype.teardownUnloadHandlers = function () {
// Restore whatever previous onbeforeunload hook existed
window.onbeforeunload = this.onBeforeUnloadFallback;
this.onBeforeUnloadFallback = null;
window.removeEventListener( 'unload', this.onUnloadHandler );
};
/**
* Show the beta dialog as needed
*/
ve.init.mw.DesktopArticleTarget.prototype.maybeShowWelcomeDialog = function () {
var usePrefs, prefSaysShow, urlSaysHide, windowManager,
target = this;
this.welcomeDialogPromise = $.Deferred();
if ( mw.config.get( 'wgVisualEditorConfig' ).showBetaWelcome ) {
// Set up a temporary window manager
windowManager = new OO.ui.WindowManager( {
classes: [
've-init-mw-desktopArticleTarget-windowManager',
've-init-mw-desktopArticleTarget-windowManager-welcome'
]
} );
$( 'body' ).append( windowManager.$element );
this.welcomeDialog = new ve.ui.MWWelcomeDialog();
windowManager.addWindows( [ this.welcomeDialog ] );
// Only use the preference value if the user is logged-in.
// If the user is anonymous, we can't save the preference
// after showing the dialog. And we don't intend to use this
// preference to influence anonymous users (use the config
// variable for that; besides the pref value would be stale if
// the wiki uses static html caching).
usePrefs = !mw.user.isAnon();
prefSaysShow = usePrefs && !mw.user.options.get( 'visualeditor-hidebetawelcome' );
urlSaysHide = 'vehidebetadialog' in this.currentUri.query;
if (
!urlSaysHide &&
(
prefSaysShow ||
(
!usePrefs &&
localStorage.getItem( 've-beta-welcome-dialog' ) === null &&
$.cookie( 've-beta-welcome-dialog' ) === null
)
)
) {
windowManager.openWindow( this.welcomeDialog )
.then( function ( opened ) {
return opened;
} )
.then( function ( closing ) {
return closing;
} )
.then( function () {
// Detach the temporary window manager
windowManager.destroy();
target.welcomeDialogPromise.resolve();
} );
} else {
this.welcomeDialogPromise.resolve();
}
if ( prefSaysShow ) {
new mw.Api().postWithToken( 'options', {
action: 'options',
change: 'visualeditor-hidebetawelcome=1'
} );
// No need to set a cookie every time for logged-in users that have already
// set the hidebetawelcome=1 preference, but only if this isn't a one-off
// view of the page via the hiding GET parameter.
} else if ( !usePrefs && !urlSaysHide ) {
try {
localStorage.setItem( 've-beta-welcome-dialog', 1 );
} catch ( e ) {
$.cookie( 've-beta-welcome-dialog', 1, { path: '/', expires: 30 } );
}
}
} else {
this.welcomeDialogPromise.reject();
}
};
/**
* Show the meta dialog as needed on load.
*/
ve.init.mw.DesktopArticleTarget.prototype.maybeShowMetaDialog = function () {
var target = this;
this.welcomeDialogPromise
.always( function () {
// Pop out the notices when the welcome dialog is closed
target.actionsToolbar.tools.notices.getPopup().toggle( true );
} );
if ( this.getSurface().getModel().metaList.getItemsInGroup( 'mwRedirect' ).length ) {
this.getSurface().getDialogs().openWindow( 'meta', {
page: 'settings',
fragment: this.getSurface().getModel().getFragment()
Update VE core submodule to master (f2277ea) New changes: 56de6f5 Localisation updates from https://translatewiki.net. f8bda64 Widgetise demo menu 6ac48d8 Localisation updates from https://translatewiki.net. 365e131 builderloader: Omit value for boolean "disabled" attribute per HTML5 706e4b3 Prevent double counting of DM nodes in getNodeAndOffset b141a7d Update OOjs UI to v0.1.0-pre (d2451ac748) c5b3921 Localisation updates from https://translatewiki.net. 1606983 Update reference to ConfirmationDialog to use MessageDialog Deletions: * Styles for ve.ui.MWBetaWelcomeDialog - not needed anymore because OO.ui.MessageDialog provides them * Styles for ve.ui.MWGalleryInspector - not needed anymore because ve.ui.MWExtensionInspector provides part of them and the rest are being replaced by programatic sizing Modifications: * ve.ui.MWLinkTargetInputWidget - Added support for validation and href getter * Split message between tool and dialog title for ve.ui.MWEditModeTool and ve.ui.MWWikitextSwitchConfirmDialog General changes: * Updated inheritance. * Added manager param to constructors of dialogs and inspectors. * Updated use of show/hide with toggle. * Added meaningful descriptions of dialog and inspector classes. * Configured dialog and inspector sizes statically. * Configured dialog action buttons statically. * Interfaced with OO.ui.ActionSet to control action buttons. * Moved applyChanges code into getActionProcess methods. * Always using .next in setup/ready process getters and .first in hold/teardown process getters. Change-Id: Ia74732e6e32c0808eee021f0a26225b9e6c3f971
2014-07-14 21:32:49 +00:00
} );
}
};
/**
* Handle before unload event.
*
* @method
*/
ve.init.mw.DesktopArticleTarget.prototype.onBeforeUnload = function () {
var fallbackResult;
// Check if someone already set on onbeforeunload hook
if ( this.onBeforeUnloadFallback ) {
// Get the result of their onbeforeunload hook
fallbackResult = this.onBeforeUnloadFallback();
// If it returned something, exit here and return their message
if ( fallbackResult !== undefined ) {
return fallbackResult;
}
}
// Check if there's been an edit
if ( this.getSurface() && this.edited && !this.submitting && mw.user.options.get( 'useeditwarning' ) ) {
// Return our message
return ve.msg( 'visualeditor-viewpage-savewarning' );
}
};
/**
* Handle unload event.
*
* @method
*/
ve.init.mw.DesktopArticleTarget.prototype.onUnload = function () {
if ( !this.submitting ) {
ve.track( 'mwedit.abort', {
type: this.edited ? 'unknown-edited' : 'unknown',
mechanism: 'navigate'
} );
}
};
/**
* Switches to the wikitext editor, either keeping (default) or discarding changes.
*
* @param {boolean} [discardChanges] Whether to discard changes or not.
* @param {boolean} [modified] Whether there were any changes at all.
*/
ve.init.mw.DesktopArticleTarget.prototype.switchToWikitextEditor = function ( discardChanges, modified ) {
var target = this;
if ( discardChanges ) {
if ( modified ) {
ve.track( 'mwedit.abort', { type: 'switchwithout', mechanism: 'navigate' } );
} else {
ve.track( 'mwedit.abort', { type: 'switchnochange', mechanism: 'navigate' } );
}
this.submitting = true;
location.href = this.viewUri.clone().extend( {
action: 'edit',
veswitched: 1
} ).toString();
} else {
this.serialize(
this.docToSave || this.getSurface().getDom(),
function ( wikitext ) {
ve.track( 'mwedit.abort', { type: 'switchwith', mechanism: 'navigate' } );
target.submitWithSaveFields( { wpDiff: 1, veswitched: 1 }, wikitext );
}
);
}
};
/**
* Resets the document opacity when we've decided to cancel switching to the wikitext editor.
*/
ve.init.mw.DesktopArticleTarget.prototype.resetDocumentOpacity = function () {
this.getSurface().getView().getDocument().getDocumentNode().$element.css( 'opacity', 1 );
};