mediawiki-extensions-Visual.../modules/ve/ui/ve.ui.Toolbar.js

258 lines
6.7 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 UserInterface Toolbar class.
*
* @copyright 2011-2013 VisualEditor Team and others; see AUTHORS.txt
* @license The MIT License (MIT); see LICENSE.txt
*/
/**
* UserInterface toolbar.
*
* @class
* @extends ve.Element
* @mixins ve.EventEmitter
*
* @constructor
* @param {ve.ui.Surface} surface
* @param {Object} [config] Config options
* @cfg {boolean} [actions] Add an actions section opposite to the tools
* @cfg {boolean} [shadow] Add a shadow below the toolbar
*/
ve.ui.Toolbar = function VeUiToolbar( surface, options ) {
// Configuration initialization
options = options || {};
// Parent constructor
ve.Element.call( this, options );
// Mixin constructors
ve.EventEmitter.call( 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
2011-11-30 23:51:06 +00:00
// Properties
this.surface = surface;
this.$bar = this.$$( '<div>' );
this.$tools = this.$$( '<div>' );
this.floating = false;
this.$window = null;
this.windowEvents = {
'resize': ve.bind( this.onWindowResize, this ),
'scroll': ve.bind( this.onWindowScroll, this )
};
// Initialization
this.$tools.addClass( 've-ui-toolbar-tools' );
this.$bar.addClass( 've-ui-toolbar-bar' ).append( this.$tools );
if ( options.actions ) {
this.$actions = this.$$( '<div>' );
this.$actions.addClass( 've-ui-toolbar-actions' );
this.$bar.append( this.$actions );
}
this.$bar.append( '<div style="clear:both"></div>' );
if ( options.shadow ) {
this.$bar.append( '<div class="ve-ui-toolbar-shadow"></div>' );
}
this.$.addClass( 've-ui-toolbar' ).append( this.$bar );
// Events
this.surface.getModel().connect( this, { 'contextChange': 'onContextChange' } );
2011-11-30 23:51:06 +00:00
};
2011-11-29 21:34:56 +00:00
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 */
ve.inheritClass( ve.ui.Toolbar, ve.Element );
ve.mixinClass( ve.ui.Toolbar, ve.EventEmitter );
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 updateState
* @see ve.dm.SurfaceFragment#getAnnotations
* @param {ve.dm.Node[]} nodes List of nodes covered by the current selection
* @param {ve.dm.AnnotationSet} full Annotations that cover all of the current selection
* @param {ve.dm.AnnotationSet} partial Annotations that cover some or all of the current selection
*/
/* Methods */
/**
* Handle window resize events while toolbar floating is enabled.
*
* @return {jQuery.Event} e Window resize event
*/
ve.ui.Toolbar.prototype.onWindowScroll = function () {
var scrollTop = this.$window.scrollTop(),
toolbarOffset = this.$.offset(),
$lastBranch = this.surface.$.find( '.ve-ce-documentNode > .ve-ce-branchNode:visible:last' ),
lastBranchOffset = $lastBranch.offset(),
belowLastBranch = $lastBranch.length &&
scrollTop + this.$bar.height() >= lastBranchOffset.top;
if ( scrollTop > toolbarOffset.top ) {
this.setPosition(
belowLastBranch ? lastBranchOffset.top - this.$.outerHeight() : 0,
toolbarOffset.left,
this.$window.width() - this.$.outerWidth() - toolbarOffset.left
);
} else if ( this.floating ) {
this.resetPosition();
}
};
/**
* Handle window scroll events while toolbar floating is enabled.
*
* Toolbar will stick to the top of the screen unless it would be over or under the last visible
* branch node in the root of the document being edited, at which point it will stop just above it.
*
* @return {jQuery.Event} e Window scroll event
*/
ve.ui.Toolbar.prototype.onWindowResize = function () {
var offset = this.$.offset();
if ( this.floating ) {
this.$bar.css( {
'left': offset.left,
'right': this.$window.width() - this.$.outerWidth() - offset.left
} );
}
};
/**
* Gets the surface the toolbar controls.
*
* @method
* @returns {ve.ui.Surface} Surface being controlled
*/
ve.ui.Toolbar.prototype.getSurface = function () {
return this.surface;
};
/**
* Handle context changes on the surface.
*
* @method
* @emits updateState
*/
ve.ui.Toolbar.prototype.onContextChange = function () {
var i, len, leafNodes,
Death and/or destruction So. It turns out that the design of SurfaceFragment is a little - shall we say - wonky. One of the best things about ve.dm.SurfaceFragment is its magical ability to retain the intention of its range, even as transactions are being processed. This ability is granted by each fragment listening to the surface's change event, and responding by using translateRange for each transaction that gets processed. Surface fragments also have these clever methods that allow you to get a fragment based on another, which makes adjusting the range easy to do inline without having to manually store multiple fragments or modifying the original. This sounded good, and we seemed to all be convinced it was well designed. But if you add a console.log( 'hello' ); to the first line of ve.dm.SurfaceFragment.prototype.onTransact, and then start using the bold tool on various selections of text, you will find that there may indeed be a flaw. What you will probably realize is that the number of times that particular line of code is being called is disturbingly large, and increases each time you do just about anything in the editor. What's going on? How did we get here? Read on… It turns out that fragments are immortal. We create them, they listen to the surface's transact event, we are done with them, but the surface keeps on emitting events to the now long forgotten about fragments. They continue to build up over time, never go out of scope, and bloat the hell out of our program. The same ended up being true of toolbars - and each time the context menu fired up a new one the old one was left in limbo, still responding to events, still taking up memory, but not being visible to the user. All of this immortality was causing strange and difficult to track down problems. This patch fixes this by introducing a destroy method. This method unbinds events, allowing the object to finally fall out of scope and die - and more importantly stop receiving notifications of changes. This is a hack, but Ed will no doubt get this situation sorted out properly by making fragments lazy-evaluate their selections by only storing an identifier of the most recent transaction they were based on, see bug 47343. Change-Id: I18bb986001a44732a7871b9d79dc3015eedfb168
2013-04-18 18:44:40 +00:00
fragment = this.surface.getModel().getFragment( null, false ),
nodes = [];
leafNodes = fragment.getLeafNodes();
for ( i = 0, len = leafNodes.length; i < len; i++ ) {
if ( len === 1 || !leafNodes[i].range || leafNodes[i].range.getLength() ) {
nodes.push( leafNodes[i].node );
}
}
this.emit( 'updateState', nodes, fragment.getAnnotations(), fragment.getAnnotations( true ) );
};
/**
* Initialize all tools and groups.
*
* @method
*/
ve.ui.Toolbar.prototype.addTools = function ( tools ) {
var i, j, group, $group, tool;
for ( i = 0; i < tools.length; i++ ) {
group = tools[i];
// Create group
$group = this.$$( '<div class="ve-ui-toolbar-group"></div>' )
.addClass( 've-ui-toolbar-group-' + group.name );
if ( group.label ) {
$group.append(
this.$$( '<div class="ve-ui-toolbar-label"></div>' ).html( group.label )
);
}
// Add tools
for ( j = 0; j < group.items.length; j++ ) {
tool = ve.ui.toolFactory.create( group.items[j], this );
if ( !tool ) {
throw new Error( 'Unknown tool: ' + group.items[j] );
2011-11-30 23:05:06 +00:00
}
$group.append( tool.$ );
2011-11-29 21:34:56 +00:00
}
// Append group
this.$tools.append( $group );
2011-11-29 21:34:56 +00:00
}
};
Death and/or destruction So. It turns out that the design of SurfaceFragment is a little - shall we say - wonky. One of the best things about ve.dm.SurfaceFragment is its magical ability to retain the intention of its range, even as transactions are being processed. This ability is granted by each fragment listening to the surface's change event, and responding by using translateRange for each transaction that gets processed. Surface fragments also have these clever methods that allow you to get a fragment based on another, which makes adjusting the range easy to do inline without having to manually store multiple fragments or modifying the original. This sounded good, and we seemed to all be convinced it was well designed. But if you add a console.log( 'hello' ); to the first line of ve.dm.SurfaceFragment.prototype.onTransact, and then start using the bold tool on various selections of text, you will find that there may indeed be a flaw. What you will probably realize is that the number of times that particular line of code is being called is disturbingly large, and increases each time you do just about anything in the editor. What's going on? How did we get here? Read on… It turns out that fragments are immortal. We create them, they listen to the surface's transact event, we are done with them, but the surface keeps on emitting events to the now long forgotten about fragments. They continue to build up over time, never go out of scope, and bloat the hell out of our program. The same ended up being true of toolbars - and each time the context menu fired up a new one the old one was left in limbo, still responding to events, still taking up memory, but not being visible to the user. All of this immortality was causing strange and difficult to track down problems. This patch fixes this by introducing a destroy method. This method unbinds events, allowing the object to finally fall out of scope and die - and more importantly stop receiving notifications of changes. This is a hack, but Ed will no doubt get this situation sorted out properly by making fragments lazy-evaluate their selections by only storing an identifier of the most recent transaction they were based on, see bug 47343. Change-Id: I18bb986001a44732a7871b9d79dc3015eedfb168
2013-04-18 18:44:40 +00:00
/**
* Destroys toolbar, removing event handlers and DOM elements.
*
* Call this whenever you are done using a toolbar.
*
* @method
*/
ve.ui.Toolbar.prototype.destroy = function () {
this.disableFloating();
this.surface.getModel().disconnect( this, { 'contextChange': 'onContextChange' } );
Death and/or destruction So. It turns out that the design of SurfaceFragment is a little - shall we say - wonky. One of the best things about ve.dm.SurfaceFragment is its magical ability to retain the intention of its range, even as transactions are being processed. This ability is granted by each fragment listening to the surface's change event, and responding by using translateRange for each transaction that gets processed. Surface fragments also have these clever methods that allow you to get a fragment based on another, which makes adjusting the range easy to do inline without having to manually store multiple fragments or modifying the original. This sounded good, and we seemed to all be convinced it was well designed. But if you add a console.log( 'hello' ); to the first line of ve.dm.SurfaceFragment.prototype.onTransact, and then start using the bold tool on various selections of text, you will find that there may indeed be a flaw. What you will probably realize is that the number of times that particular line of code is being called is disturbingly large, and increases each time you do just about anything in the editor. What's going on? How did we get here? Read on… It turns out that fragments are immortal. We create them, they listen to the surface's transact event, we are done with them, but the surface keeps on emitting events to the now long forgotten about fragments. They continue to build up over time, never go out of scope, and bloat the hell out of our program. The same ended up being true of toolbars - and each time the context menu fired up a new one the old one was left in limbo, still responding to events, still taking up memory, but not being visible to the user. All of this immortality was causing strange and difficult to track down problems. This patch fixes this by introducing a destroy method. This method unbinds events, allowing the object to finally fall out of scope and die - and more importantly stop receiving notifications of changes. This is a hack, but Ed will no doubt get this situation sorted out properly by making fragments lazy-evaluate their selections by only storing an identifier of the most recent transaction they were based on, see bug 47343. Change-Id: I18bb986001a44732a7871b9d79dc3015eedfb168
2013-04-18 18:44:40 +00:00
this.$.remove();
};
/**
* Float the toolbar.
*
* @method
* @param {number} top Top position, in pixels
* @param {number} left Left position, in pixels
* @param {number} right Right position, in pixels
*/
ve.ui.Toolbar.prototype.setPosition = function ( top, left, right ) {
// When switching from default position, manually set the height of the wrapper
if ( !this.floating ) {
this.$
.css( 'height', this.$.height() )
.addClass( 've-ui-toolbar-floating' );
this.floating = true;
}
this.$bar.css( { 'top': top, 'left': left, 'right': right } );
if ( top > 0 ) {
this.$.addClass( 've-ui-toolbar-bottom' );
} else {
this.$.removeClass( 've-ui-toolbar-bottom' );
}
};
/**
* Reset the toolbar to it's default position.
*
* @method
*/
ve.ui.Toolbar.prototype.resetPosition = function () {
this.$
.css( 'height', 'auto' )
.removeClass( 've-ui-toolbar-floating ve-ui-toolbar-bottom' );
this.$bar.css( { 'top': 0, 'left': 0, 'right': 0 } );
this.floating = false;
};
/**
* Add automatic floating behavior to the toolbar.
*
* Toolbar floating is not enabled by default, call this on setup to enable it.
*
* @method
*/
ve.ui.Toolbar.prototype.enableFloating = function () {
this.$window = $( this.getElementWindow() );
this.$window.on( this.windowEvents );
};
/**
* Remove automatic floating behavior to the toolbar.
*
* @method
*/
ve.ui.Toolbar.prototype.disableFloating = function () {
if ( this.$window ) {
this.$window.off( this.windowEvents );
this.$window = null;
}
if ( this.floating ) {
this.resetPosition();
}
};