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

359 lines
8.9 KiB
JavaScript
Raw Normal View History

/**
* VisualEditor user interface Context class.
*
* @copyright 2011-2012 VisualEditor Team and others; see AUTHORS.txt
* @license The MIT License (MIT); see LICENSE.txt
*/
2011-11-29 23:29:02 +00:00
/**
* Creates an ve.ui.Context object.
*
2011-11-29 23:29:02 +00:00
* @class
* @constructor
* @param surface
2011-11-29 23:29:02 +00:00
* @param {jQuery} $overlay DOM selection to add nodes to
*/
ve.ui.Context = function VeUiContext( surface, $overlay ) {
if ( !surface ) {
return;
}
2011-12-02 00:30:50 +00:00
// Properties
this.surface = surface;
this.inspectors = {};
this.inspector = null;
this.position = null;
this.visible = false;
this.selecting = false;
// Base elements
this.$ = $( '<div class="ve-ui-context"></div>' );
this.$callout = $( '<div class="ve-ui-context-callout"></div>' );
this.$inner = $( '<div class="ve-ui-context-inner"></div>' )
.appendTo( this.$ );
this.$menu = $( '<div class="ve-ui-context-menu"></div>' )
.appendTo( this.$inner );
// Inspectors
this.$inspectors = $( '<div class="ve-ui-context-inspectors"></div>' )
.appendTo ( this.$inner );
this.$overlay = $( '<div class="ve-ui-context-frame-overlay"></div>' )
.appendTo( this.$ );
// Append base
this.$.prepend( this.$callout );
( $overlay || $( 'body' ) ).append( this.$ );
// Create Frame for inspectors.
this.frameView = new ve.ui.Frame( {
'stylesheets': [
ve.init.platform.getModulesUrl() + '/ve/ui/styles/ve.ui.Inspector.css',
ve.init.platform.getModulesUrl() +
( window.devicePixelRatio > 1 ?
'/ve/ui/styles/ve.ui.Inspector.Icons-vector.css' :
'/ve/ui/styles/ve.ui.Inspector.Icons-raster.css' )
]
}, this.$inspectors );
// Events
this.surface.getModel().addListenerMethods( this, { 'change': 'onChange' } );
this.surface.getView()
.addListenerMethods( this, {
'selectionStart': 'onSelectionStart',
'selectionEnd': 'onSelectionEnd'
} )
.getDocument().getDocumentNode().$.on( {
'focus': ve.bind( this.onDocumentFocus, this ),
'blur': ve.bind( this.onDocumentBlur, this )
} );
};
/* Methods */
/**
* Responds to change events on the model.
*
* @method
* @param {ve.dm.Transaction} tx Change transaction
* @param {ve.Range} selection Change selection
*/
ve.ui.Context.prototype.onChange = function ( tx, selection ) {
if ( selection && !this.selecting ) {
this.update();
}
};
/**
* Responds to selection start events on the view.
*
* @method
*/
ve.ui.Context.prototype.onSelectionStart = function () {
this.selecting = true;
this.unset();
};
/**
* Responds to selection end events on the view.
*
* @method
*/
ve.ui.Context.prototype.onSelectionEnd = function () {
this.selecting = false;
this.update();
};
/**
* Updates the context menu.
*
* @method
*/
ve.ui.Context.prototype.update = function () {
var surfaceModel = this.surface.getModel(),
doc = surfaceModel.getDocument(),
sel = surfaceModel.getSelection(),
annotations = doc.getAnnotationsFromRange( sel ).get(),
inspectors = [],
name,
i;
if ( annotations.length > 0 ) {
// Look for inspectors that match annotations.
for ( i = 0; i < annotations.length; i++ ) {
name = annotations[i].name.split( '/' )[0];
// Add inspector on demand.
if ( this.initInspector( name ) ) {
inspectors.push( name );
}
}
}
// Build inspector menu.
if ( inspectors.length > 0 && !this.inspector ) {
this.$menu.empty();
// Toolbar
this.$toolbar = $( '<div class="ve-ui-context-toolbar"></div>' );
// Create inspector toolbar
this.toolbarView = new ve.ui.Toolbar(
this.$toolbar,
this.surface,
[{ 'name': 'inspectors', 'items' : inspectors }]
);
// Note: Menu attaches the provided $tool element to the container.
this.menuView = new ve.ui.Menu(
[ { 'name': 'tools', '$': this.$toolbar } ], // Tools
null, // Callback
this.$menu, // Container
this.$inner // Parent
);
this.set();
} else if ( !this.selection || !this.selection.equals( sel ) ) {
// Cache current selection
this.selection = sel;
this.unset();
this.update();
} else {
this.unset();
}
};
ve.ui.Context.prototype.unset = function () {
if ( this.inspector ) {
this.closeInspector( false );
this.$overlay.hide();
}
if ( this.menuView ) {
this.obscure( this.$menu );
}
this.close();
};
ve.ui.Context.prototype.obscure = function ( el ) {
el.css( {
'top': -5000
} );
};
ve.ui.Context.prototype.reveal = function ( el ) {
el.css( {
'top': 0
} );
};
ve.ui.Context.prototype.getSelectionPosition = function () {
var selectionRect = this.surface.getView().getSelectionRect();
return new ve.Position( selectionRect.end.x, selectionRect.end.y );
};
ve.ui.Context.prototype.open = function () {
this.$.css( 'visibility', 'visible' );
};
ve.ui.Context.prototype.close = function () {
this.$.css( 'visibility', 'hidden' );
};
ve.ui.Context.prototype.set = function () {
this.position = this.getSelectionPosition();
Make use of new jshint options * Restricting "camelcase": No changes, we were passing all of these already * Explicitly unrestricting "forin" and "plusplus" These are off by default in node-jshint, but some distro of jshint and editors that use their own wrapper around jshint instead of node-jshint (Eclipse?) may have different defaults. Therefor setting them to false explicitly. This also serves as a reminder for the future so we'll always know we don't pass that, in case we would want to change that. * Fix order ("quotemark" before "regexp") * Restricting "unused" We're not passing all of this, which is why I've set it to false for now. But I did put it in .jshintrc as placeholder. I've fixed most of them, there's some left where there is no clean solution. * While at it fix a few issues: - Unused variables ($target, $window) - Bad practices (using jQuery context for find instead of creation) - Redundant /*global */ comments - Parameters that are not used and don't have documentation either - Lines longer than 100 chars @ 4 spaces/tab * Note: - ve.ce.Surface.prototype.onChange takes two arguments but never uses the former. And even the second one can be null/undefined. Aside from that, the .change() function emits another event for the transaction already. Looks like this should be refactored a bit, two more separated events probably or one that is actually used better. - Also cleaned up a lot of comments, some of which were missing, others were incorrect - Reworked the contentChange event so we are no longer using the word new as an object key; expanded a complex object into multiple arguments being passed through the event to make it easier to work with and document Change-Id: I8490815a508c6c379d5f9a743bb4aefd14576aa6
2012-08-07 06:02:18 +00:00
this.$.css( {
'left': this.position.left,
'top': this.position.top
} );
// Open context.
this.open();
function getDimensions () {
var height, width;
if ( this.inspector ) {
height = this.$inspectors.outerHeight( true );
width = this.$inspectors.outerWidth( true );
} else {
height = this.$menu.outerHeight( true );
width = this.$menu.outerWidth( true );
}
return {
'height': height,
'width': width
};
}
function getLeft () {
var width = getDimensions.call( this ).width,
left = -( width / 2 );
// Boundary checking left.
if ( this.position.left < width / 2 ) {
left = -( this.$.children().outerWidth( true ) / 2 ) - ( this.position.left / 2 );
// Checking right.
} else if ( $( 'body' ).width() - this.position.left < width ) {
left = -( width - ( ( $( 'body' ).width() - this.position.left ) / 2) );
}
return left;
}
if ( this.inspector ) {
// Reveal inspector
this.reveal( this.$inspectors );
this.$overlay.show();
} else {
if ( !this.visible ) {
// Fade in the context.
this.$.fadeIn( 'fast' );
this.visible = true;
}
// Reveal menu
this.reveal( this.$menu );
2011-11-29 23:29:02 +00:00
}
// Position inner context.
this.$inner.css( {
'left': getLeft.call( this ),
'height': getDimensions.call( this ).height,
'width': getDimensions.call( this ).width
} );
2011-11-29 23:29:02 +00:00
};
// Method to position iframe overlay above or below an element.
ve.ui.Context.prototype.setOverlayPosition = function ( config ) {
var left, top;
if (
config === undefined ||
! ( 'overlay' in config )
) {
return;
}
// Set iframe overlay below element.
left = -( this.$inner.width() / 2 ) + config.el.offset().left;
top = config.el.offset().top + config.el.outerHeight( true );
// Set position.
config.overlay.css( {
'left': left,
'top': top,
// RTL position fix.
'width': config.overlay.children().outerWidth( true )
} );
};
/* Inspector methods */
/* Lazy load inspectors on demand */
ve.ui.Context.prototype.initInspector = function ( name ) {
// Add inspector on demand.
if ( ve.ui.inspectorFactory.lookup( name ) ) {
if ( !( name in this.inspectors ) ) {
this.addInspector( name, ve.ui.inspectorFactory.create( name, this ) );
this.obscure( this.$inspectors );
}
return true;
}
return false;
};
ve.ui.Context.prototype.addInspector = function ( name, inspector ) {
if ( name in this.inspectors ) {
throw new Error( 'Duplicate inspector error. Previous registration with the same name: ' + name );
}
inspector.$.hide();
this.inspectors[name] = inspector;
this.frameView.$.append( inspector.$ );
};
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
ve.ui.Context.prototype.openInspector = function ( name ) {
if ( !this.initInspector( name ) ) {
throw new Error( 'Missing inspector. Can not open nonexistent inspector: ' + name );
}
// Close menu
if ( this.menuView ) {
this.obscure( this.$menu );
}
// Fade in context if menu is closed.
// At this point, menuView could be undefined or not open.
if ( this.menuView === undefined || !this.menuView.isOpen() ) {
this.$.fadeIn( 'fast' );
}
// Open the inspector by name.
this.inspectors[name].open();
// Resize frame to the size of the inspector.
this.resizeFrame( this.inspectors[name] );
// Save name of inspector open.
this.inspector = name;
// Cache selection, in the case of manually opened inspector.
this.selection = this.surface.getModel().getSelection();
// Set inspector
this.set();
};
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
ve.ui.Context.prototype.closeInspector = function ( accept ) {
if ( this.inspector ) {
this.obscure( this.$inspectors );
this.inspectors[this.inspector].close( accept );
this.inspector = null;
this.close();
}
this.update();
};
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
// Currently sizes to dimensions of specified inspector.
ve.ui.Context.prototype.resizeFrame = function ( inspector ) {
this.frameView.$frame.css( {
'width': inspector.$.outerWidth(),
'height': inspector.$.outerHeight()
} );
};
ve.ui.Context.prototype.getSurface = function () {
return this.surface;
};
/* Events */
ve.ui.Context.prototype.onDocumentFocus = function () {
$( window ).on( 'resize.ve-ui-context scroll.ve-ui-context',
ve.bind( this.update, this ) );
};
ve.ui.Context.prototype.onDocumentBlur = function () {
if ( !this.inspector ) {
$( window ).off( 'resize.ve-ui-context scroll.ve-ui-context' );
}
2011-11-29 23:29:02 +00:00
};