#4866: Replace existing menus with jQueryUI menu

This commit is contained in:
Mike Gelfand
2015-04-30 05:20:48 +00:00
parent 0c01e6e19d
commit 50364a7883
14 changed files with 781 additions and 903 deletions

View File

@@ -4,6 +4,6 @@ dist_data_DATA = \
jquery-ui.min.js \
jquery-migrate.min.js \
jquery.min.js \
jquery.contextmenu.min.js \
jquery.ui-contextmenu.min.js \
jquery.transmenu.min.js \
json2.min.js

View File

@@ -1 +0,0 @@
(function(a){function i(d,h,i,k){var l=f[d],m=i[l.eventPosY],n=i[l.eventPosX];e=a("#"+l.id).find("ul:first").clone(!0),e.css(l.menuStyle).find("li").css(l.itemStyle).hover(function(){a(this).css(l.itemHoverStyle)},function(){a(this).css(l.itemStyle)}).find("img").css({verticalAlign:"middle",paddingRight:"2px"}),b.html(e),!l.onShowMenu||(b=l.onShowMenu(i,b)),a.each(l.bindings,function(c,d){a("#"+c,b).bind("click",function(a){j(),d(h,g)})}),m+b.height()>a(window).height()&&(m=m-b.height()),n+b.width()>a(window).width()&&(n=n-b.width()),b.css({left:n,top:m}).show(),l.shadow&&c.css({width:b.width(),height:b.height(),left:i.pageX+2,top:i.pageY+2}).show(),setTimeout(function(){a(document).click(function(){return a(document).unbind("click"),j(),!1})},0)}function j(){b.hide(),c.hide()}var b,c,d,e,f,g,h={menuStyle:{listStyle:"none",padding:"1px",margin:"0px",backgroundColor:"#fff",border:"1px solid #999",width:"100px"},itemStyle:{margin:"0px",color:"#000",display:"block",cursor:"default",padding:"3px",border:"1px solid #fff",backgroundColor:"transparent"},itemHoverStyle:{border:"1px solid #0a246a",backgroundColor:"#b6bdd2"},eventPosX:"pageX",eventPosY:"pageY",shadow:!0,onContextMenu:null,onShowMenu:null};a.fn.contextMenu=function(d,e){b||(b=a('<div id="jqContextMenu"></div>').hide().css({position:"absolute",zIndex:"500"}).appendTo("body").bind("click",function(a){a.stopPropagation()})),c||(c=a("<div></div>").css({backgroundColor:"#000",position:"absolute",opacity:.2,zIndex:499}).appendTo("body").hide()),f=f||[],f.push({id:d,menuStyle:a.extend({},h.menuStyle,e.menuStyle||{}),itemStyle:a.extend({},h.itemStyle,e.itemStyle||{}),itemHoverStyle:a.extend({},h.itemHoverStyle,e.itemHoverStyle||{}),bindings:e.bindings||{},shadow:e.shadow||e.shadow===!1?e.shadow:h.shadow,onContextMenu:e.onContextMenu||h.onContextMenu,onShowMenu:e.onShowMenu||h.onShowMenu,eventPosX:e.eventPosX||h.eventPosX,eventPosY:e.eventPosY||h.eventPosY});var g=f.length-1;return a(this).bind("contextmenu",function(a){var b=f[g].onContextMenu?f[g].onContextMenu(a):!0;return b&&i(g,this,a,e),!1}),this},a.contextMenu={defaults:function(b){a.each(b,function(b,c){typeof c=="object"&&h[b]?a.extend(h[b],c):h[b]=c})}}})(jQuery),$(function(){$("div.contextMenu").hide()})

View File

@@ -1,156 +0,0 @@
/*
* ContextMenu - jQuery plugin for right-click context menus
*
* Author: Chris Domigan
* Contributors: Dan G. Switzer, II
* Parts of this plugin are inspired by Joern Zaefferer's Tooltip plugin
*
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
* Version: r2
* Date: 16 July 2007
*
* For documentation visit http://www.trendskitchens.co.nz/jquery/contextmenu/
*
*/
(function($) {
var menu, shadow, trigger, content, hash, currentTarget;
var defaults = {
menuStyle: {
listStyle: 'none',
padding: '1px',
margin: '0px',
backgroundColor: '#fff',
border: '1px solid #999',
width: '100px'
},
itemStyle: {
margin: '0px',
color: '#000',
display: 'block',
cursor: 'default',
padding: '3px',
border: '1px solid #fff',
backgroundColor: 'transparent'
},
itemHoverStyle: {
border: '1px solid #0a246a',
backgroundColor: '#b6bdd2'
},
eventPosX: 'pageX',
eventPosY: 'pageY',
shadow : true,
onContextMenu: null,
onShowMenu: null
};
$.fn.contextMenu = function(id, options) {
if (!menu) { // Create singleton menu
menu = $('<div id="jqContextMenu"></div>')
.hide()
.css({position:'absolute', zIndex:'500'})
.appendTo('body')
.bind('click', function(e) {
e.stopPropagation();
});
}
if (!shadow) {
shadow = $('<div></div>')
.css({backgroundColor:'#000',position:'absolute',opacity:0.2,zIndex:499})
.appendTo('body')
.hide();
}
hash = hash || [];
hash.push({
id : id,
menuStyle: $.extend({}, defaults.menuStyle, options.menuStyle || {}),
itemStyle: $.extend({}, defaults.itemStyle, options.itemStyle || {}),
itemHoverStyle: $.extend({}, defaults.itemHoverStyle, options.itemHoverStyle || {}),
bindings: options.bindings || {},
shadow: options.shadow || options.shadow === false ? options.shadow : defaults.shadow,
onContextMenu: options.onContextMenu || defaults.onContextMenu,
onShowMenu: options.onShowMenu || defaults.onShowMenu,
eventPosX: options.eventPosX || defaults.eventPosX,
eventPosY: options.eventPosY || defaults.eventPosY
});
var index = hash.length - 1;
$(this).bind('contextmenu', function(e) {
// Check if onContextMenu() defined
var bShowContext = (!!hash[index].onContextMenu) ? hash[index].onContextMenu(e) : true;
if (bShowContext) display(index, this, e, options);
return false;
});
return this;
};
function display(index, trigger, e, options) {
var cur = hash[index];
var top = e[cur.eventPosY];
var left = e[cur.eventPosX];
content = $('#'+cur.id).find('ul:first').clone(true);
content.css(cur.menuStyle).find('li').css(cur.itemStyle).hover(
function() {
$(this).css(cur.itemHoverStyle);
},
function(){
$(this).css(cur.itemStyle);
}
).find('img').css({verticalAlign:'middle',paddingRight:'2px'});
// Send the content to the menu
menu.html(content);
// if there's an onShowMenu, run it now -- must run after content has been added
// if you try to alter the content variable before the menu.html(), IE6 has issues
// updating the content
if (!!cur.onShowMenu) menu = cur.onShowMenu(e, menu);
$.each(cur.bindings, function(id, func) {
$('#'+id, menu).bind('click', function(e) {
hide();
func(trigger, currentTarget);
});
});
if( top + menu.height() > $(window).height() ) top = top - menu.height();
if( left + menu.width() > $(window).width() ) left = left - menu.width();
menu.css({'left':left,'top':top}).show();
if (cur.shadow) shadow.css({width:menu.width(),height:menu.height(),left:e.pageX+2,top:e.pageY+2}).show();
setTimeout( function() { // Delay for Mozilla
$(document).click( function() {
$(document).unbind('click');
hide();
return false;
});
}, 0);
}
function hide() {
menu.hide();
shadow.hide();
}
// Apply defaults
$.contextMenu = {
defaults : function(userDefaults) {
$.each(userDefaults, function(i, val) {
if (typeof val == 'object' && defaults[i]) {
$.extend(defaults[i], val);
}
else defaults[i] = val;
});
}
};
})(jQuery);
$(function() {
$('div.contextMenu').hide();
});

View File

@@ -1,364 +1,99 @@
/* transMenu - v0.1.5 (2007-07-07)
* Copyright (c) 2007 Roman Weich
* http://p.sohei.org
*
*/
(function($)
{
var defaults = {
onClick: function(){
$(this).find('>a').each(function(){
if ( this.href )
{
window.location = this.href;
}
});
},
arrow_char: '&#x25BA;',
selected_char: '&#x2713;',
subDelay: 300,
direction: 'down',
mainDelay: 10
};
var transMenuSettings;
$.fn.transMenu = function(options)
{
var shown = false;
var liOffset = 2;
transMenuSettings = $.extend({}, defaults, options);
var hideDIV = function(div, delay) {
//a timer running to show the div?
if ( div.timer && !div.isVisible ) {
clearTimeout(div.timer);
} else if (div.timer) {
return; //hide-timer already running
}
if ( div.isVisible ) {
div.timer = setTimeout( function() {
//remove events
$(div).find('ul li').unbind('mouseover', liHoverIn).unbind('mouseout', liHoverOut).unbind('click', transMenuSettings.onClick);
$(div).hide();
div.isVisible = false;
div.timer = null;
}, delay);
}
};
var showDIV = function(div, delay) {
if ( div.timer ) {
clearTimeout(div.timer);
}
if ( !div.isVisible ) {
div.timer = setTimeout( function() {
//check if the mouse is still over the parent item - if not dont show the submenu
if (! $(div).parent().is('.hover')) {
return;
}
//assign events to all div>ul>li-elements
$(div).find('ul li').mouseover(liHoverIn).mouseout(liHoverOut).click(transMenuSettings.onClick);
//positioning
if (! $(div).parent().is('.main')) {
$(div).css('left', $(div).parent().parent().width() - liOffset);
}
if (transMenuSettings.direction == 'up') {
$(div).css('top', ($(div).height() * -1) + $(div).parent().parent().height());
}
div.isVisible = true; //we use this over :visible to speed up traversing
$(div).show();
div.timer = null;
}, delay);
}
};
//same as hover.handlehover in jquery - just can't use hover() directly - need the ability to unbind only the one hover event
var testHandleHover = function(e) {
// Check if mouse(over|out) are still within the same parent element
var p = (e.type == "mouseover" ? e.fromElement : e.toElement) || e.relatedTarget;
// Traverse up the tree
while ( p && p != this ) {
try {
p = p.parentNode;
} catch(e) {
p = this;
}
}
// If we actually just moused on to a sub-element, ignore it
if ( p == this ) {
return false;
}
return true;
};
var mainHoverIn = function(e) {
$(this).addClass('hover').siblings('li.hover').removeClass('hover');
if ( shown ) {
hoverIn(this, transMenuSettings.mainDelay);
}
};
var liHoverIn = function(e) {
if ( !testHandleHover(e) ) {
return false;
}
if ( e.target != this ) {
//look whether the target is a direct child of this (maybe an image)
if ( !isChild(this, e.target) ) {
return;
}
}
hoverIn(this, transMenuSettings.subDelay);
};
var hoverIn = function(li, delay) {
//stop running timers from the other menus on the same level - a little faster than $('>*>div', li.parentNode)
var n = li.parentNode.firstChild;
for ( ; n; n = n.nextSibling ) {
if ( n.nodeType == 1 && n.nodeName.toUpperCase() == 'LI' ) {
var div = getOneChild(n, 'DIV');
//clear show-div timer
if ( div && div.timer && !div.isVisible ) {
clearTimeout(div.timer);
div.timer = null;
}
}
}
//is there a timer running to hide one of the parent divs? stop it
var pNode = li.parentNode;
for ( ; pNode; pNode = pNode.parentNode ) {
if ( pNode.nodeType == 1 && pNode.nodeName.toUpperCase() == 'DIV' ) {
if (pNode.timer) {
clearTimeout(pNode.timer);
pNode.timer = null;
$(pNode.parentNode).addClass('hover');
}
}
}
//highlight the current element
$(li).addClass('hover');
var innerDiv = $(li).children('div');
innerDiv = innerDiv.length ? innerDiv[0] : null;
//is the submenu already visible?
if ( innerDiv && innerDiv.isVisible ) {
//hide-timer running?
if ( innerDiv.timer ) {
clearTimeout(innerDiv.timer);
innerDiv.timer = null;
} else {
return;
}
}
//hide all open menus on the same level and below and unhighlight the li item (but not the current submenu!)
$(li.parentNode.getElementsByTagName('DIV')).each( function() {
if ( this != innerDiv && this.isVisible ) {
hideDIV(this, delay);
$(this.parentNode).removeClass('hover');
}
});
//show the submenu, if there is one
if ( innerDiv ) {
showDIV(innerDiv, delay);
}
};
var liHoverOut = function(e) {
if ( !testHandleHover(e) ) {
return false;
}
if ( e.target != this ) {
//return only if the target is no direct child of this
if ( !isChild(this, e.target) ) {
return;
}
}
// Remove the hover from the submenu item, if the mouse is hovering out of the
// menu (this is only for the last open (levelwise) (sub-)menu)
var div = getOneChild(this, 'DIV');
if ( !div ) {
$(this).removeClass('hover');
} else {
if ( !div.isVisible ) {
$(this).removeClass('hover');
}
}
};
var mainHoverOut = function(e) {
//no need to test e.target==this, as no child has the same event bound
var div = getOneChild(this, 'DIV');
var relTarget = e.relatedTarget || e.toElement; //this is undefined sometimes (e.g. when the mouse moves out of the window), so dont remove hover then
var p;
if ( !shown ) {
$(this).removeClass('hover');
//menuitem has no submenu, so dont remove the hover if the mouse goes outside the menu
} else if ( !div && relTarget ) {
p = $(e.target).parents('UL.trans_menu');
if ( p.contains(relTarget)) {
$(this).removeClass('hover');
}
} else if ( relTarget ) {
//remove hover only when moving to anywhere inside the trans_menu
p = $(e.target).parents('UL.trans_menu');
if ( !div.isVisible && (p.contains(relTarget)) ) {
$(this).removeClass('hover');
}
}
};
var mainClick = function() {
var div = getOneChild(this, 'DIV');
//clicked on an open main-menu-item
if ( div && div.isVisible ) {
clean();
$(this).addClass('hover');
} else {
hoverIn(this, transMenuSettings.mainDelay);
shown = true;
$('ul.trans_menu li').addClass('active');
$(document).bind('mousedown', checkMouse);
}
};
var checkMouse = function(e) {
//is the mouse inside a trans_menu? if yes, is it an open (the current) one?
var vis = false;
$(e.target).parents('UL.trans_menu').find('div').each( function(){
if ( this.isVisible ) {
vis = true;
}
});
if ( !vis ) {
clean();
}
};
var clean = function() {
//remove timeout and hide the divs
$('ul.trans_menu div.outerbox').each(function(){
if ( this.timer ) {
clearTimeout(this.timer);
this.timer = null;
}
if ( this.isVisible ) {
$(this).hide();
this.isVisible = false;
}
});
$('ul.trans_menu li').removeClass('hover');
//remove events
$('ul.trans_menu>li li').unbind('mouseover', liHoverIn).unbind('mouseout', liHoverOut).unbind('click', transMenuSettings.onClick);
$(document).unbind('mousedown', checkMouse);
shown = false;
$('ul.trans_menu li').removeClass('active');
};
var getOneChild = function(elem, name) {
if ( !elem ) {
return null;
}
var n = elem.firstChild;
for ( ; n; n = n.nextSibling ) {
if ( n.nodeType == 1 && n.nodeName.toUpperCase() == name ) {
return n;
}
}
return null;
};
var isChild = function(elem, childElem) {
var n = elem.firstChild;
for ( ; n; n = n.nextSibling ) {
if ( n == childElem ) {
return true;
}
}
return false;
};
return this.each(function() {
//add .contains() to mozilla - http://www.quirksmode.org/blog/archives/2006/01/contains_for_mo.html
if (window.Node && Node.prototype && !Node.prototype.contains) {
Node.prototype.contains = function(arg) {
return !!(this.compareDocumentPosition(arg) & 16);
};
}
if (! $(this).is('.trans_menu')) {
$(this).addClass('trans_menu');
}
//add shadows
$('ul', this).shadowBox();
//assign events
$(this).bind('closemenu', function(){clean();}); //assign closemenu-event, through wich the menu can be closed from outside the plugin
//add click event handling, if there are any elements inside the main menu
var liElems = $(this).children('li');
for ( var j = 0; j < liElems.length; j++ ) {
if ( getOneChild(getOneChild(getOneChild(liElems[j], 'DIV'), 'UL'), 'LI') ) {
$(liElems[j]).click(mainClick);
}
}
//add hover event handling and assign classes
$(liElems).hover(mainHoverIn, mainHoverOut).addClass('main').find('>div').addClass('inner');
//add the little arrow before each submenu
if ( transMenuSettings.arrow_char ) {
var arrow_markup = $("<span class='arrow'>" + transMenuSettings.arrow_char + '</span>');
// Mozilla float/position hack
if ($.browser.mozilla && +$.browser.version.replace(/\./g,'').slice(0,3) < 191) {
arrow_markup.css('margin-top', '-13px');
}
$('div.inner div.outerbox', this).before(arrow_markup);
}
//the floating list elements are destroying the layout..so make it nice again..
$(this).wrap('<div class="main_container"></div>').after('<div style="clear: both; visibility: hidden;"></div>');
});
};
$.fn.transMenu.setDefaults = function(o) {
$.extend(defaults, o);
};
$.fn.shadowBox = function() {
return this.each(function() {
var outer = $('<div class="outerbox"></div>').get(0);
if ( $(this).css('position') == 'absolute' ) {
//if the child(this) is positioned abolute, we have to use relative positioning and shrink the outerbox accordingly to the innerbox
$(outer).css({position:'relative', width:this.offsetWidth, height:this.offsetHeight});
} else {
//shrink the outerbox
$(outer).css('position', 'absolute');
}
//add the boxes
$(this).addClass('innerBox').wrap(outer).
before('<div class="shadowbox1"></div><div class="shadowbox2"></div><div class="shadowbox3"></div>');
});
};
$.fn.selectMenuItem = function() {
if (this.find('span.selected').length == 0) {
this.prepend($("<span class='selected'>" + transMenuSettings.selected_char + "</span>"));
}
return this;
};
$.fn.deselectMenuItem = function() {
return this.find('span.selected').remove();
};
$.fn.menuItemIsSelected = function() {
return (this.find('span.selected').length > 0);
};
$.fn.deselectMenuSiblings = function() {
this.parent().find('span.selected').remove();
this.selectMenuItem();
return this;
};
})(jQuery);
/*
* This file Copyright (C) 2015 Mnemosyne LLC
*
* It may be used under the GNU GPL versions 2 or 3
* or any future license endorsed by Mnemosyne LLC.
*/
$.widget('tr.transMenu', $.ui.menu, {
options: {
open: null,
close: null
},
_create: function() {
this.selectImpl = this.options.select;
this.options.select = $.proxy(this._select, this);
this.element.hide();
this._superApply(arguments);
},
_select: function(event, ui) {
if (ui.item.is("[aria-haspopup='true']"))
return;
ui.id = ui.item.attr("id");
ui.group = ui.item.attr("radio-group");
ui.target = $(event.currentTarget);
if (this.selectImpl(event, ui) !== false)
this.close();
},
open: function(event) {
this.element.show();
this.element.css({ position: "absolute", left: 4, top: -this.element.height() - 4 });
$(document).bind("keydown" + this.eventNamespace, $.proxy(function(event) {
if (event.which === $.ui.keyCode.ESCAPE)
this.close();
}, this));
$(document).bind("mousedown" + this.eventNamespace + " touchstart" + this.eventNamespace, $.proxy(function(event) {
if (!$(event.target).closest(".ui-menu-item").length)
this.close();
}, this));
this._trigger("open", event);
},
close: function(event) {
$(document).unbind("keydown" + this.eventNamespace);
$(document).unbind("mousedown" + this.eventNamespace);
$(document).unbind("touchstart" + this.eventNamespace);
this._close(this.element);
this.element.hide();
this._trigger("close", event);
}
});
(function($)
{
function indicatorClass(type)
{
return ['ui-icon', 'ui-icon-' + type];
}
function findIndicator(item, type)
{
return $(item).find('span.' + indicatorClass(type).join('.'));
}
function createIndicator(item, type)
{
$(item).prepend($("<span class='" + indicatorClass(type).join(' ') + "'></span>"));
}
function indicatorType(item)
{
var group = item.attr('radio-group');
return { type: group !== undefined ? 'bullet' : 'check', group: group };
}
$.fn.selectMenuItem = function() {
var t = indicatorType(this);
if (t.type == 'bullet')
this.parent().find('li[radio-group=' + t.group + '] span.' + indicatorClass(t.type).join('.')).remove();
if (findIndicator(this, t.type).length == 0)
createIndicator(this, t.type);
return this;
};
$.fn.deselectMenuItem = function() {
var t = indicatorType(this);
return findIndicator(this, t.type).remove();
};
$.fn.menuItemIsSelected = function() {
return findIndicator(this, 'bullet').length > 0 || findIndicator(this, 'check').length > 0;
};
})(jQuery);

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,469 @@
/*******************************************************************************
* jquery.ui-contextmenu.js plugin.
*
* jQuery plugin that provides a context menu (based on the jQueryUI menu widget).
*
* @see https://github.com/mar10/jquery-ui-contextmenu
*
* Copyright (c) 2013-2015, Martin Wendt (http://wwWendt.de). Licensed MIT.
*/
(function( factory ) {
"use strict";
if ( typeof define === "function" && define.amd ) {
// AMD. Register as an anonymous module.
define([ "jquery", "jquery-ui/menu" ], factory );
} else {
// Browser globals
factory( jQuery );
}
}(function( $ ) {
"use strict";
var supportSelectstart = "onselectstart" in document.createElement("div"),
match = $.ui.menu.version.match(/^(\d)\.(\d+)/),
uiVersion = {
major: parseInt(match[1], 10),
minor: parseInt(match[2], 10)
},
isLTE110 = ( uiVersion.major < 2 && uiVersion.minor < 11 );
$.widget("moogle.contextmenu", {
version: "@VERSION",
options: {
addClass: "ui-contextmenu", // Add this class to the outer <ul>
autoFocus: false, // Set keyboard focus to first entry on open
autoTrigger: true, // open menu on browser's `contextmenu` event
delegate: null, // selector
hide: { effect: "fadeOut", duration: "fast" },
ignoreParentSelect: true, // Don't trigger 'select' for sub-menu parents
menu: null, // selector or jQuery pointing to <UL>, or a definition hash
position: null, // popup positon
preventContextMenuForPopup: false, // prevent opening the browser's system
// context menu on menu entries
preventSelect: false, // disable text selection of target
show: { effect: "slideDown", duration: "fast" },
taphold: false, // open menu on taphold events (requires external plugins)
uiMenuOptions: {}, // Additional options, used when UI Menu is created
// Events:
beforeOpen: $.noop, // menu about to open; return `false` to prevent opening
blur: $.noop, // menu option lost focus
close: $.noop, // menu was closed
create: $.noop, // menu was initialized
createMenu: $.noop, // menu was initialized (original UI Menu)
focus: $.noop, // menu option got focus
open: $.noop, // menu was opened
select: $.noop // menu option was selected; return `false` to prevent closing
},
/** Constructor */
_create: function() {
var cssText, eventNames, targetId,
opts = this.options;
this.$headStyle = null;
this.$menu = null;
this.menuIsTemp = false;
this.currentTarget = null;
this.previousFocus = null;
if (opts.preventSelect) {
// Create a global style for all potential menu targets
// If the contextmenu was bound to `document`, we apply the
// selector relative to the <body> tag instead
targetId = ($(this.element).is(document) ? $("body")
: this.element).uniqueId().attr("id");
cssText = "#" + targetId + " " + opts.delegate + " { " +
"-webkit-user-select: none; " +
"-khtml-user-select: none; " +
"-moz-user-select: none; " +
"-ms-user-select: none; " +
"user-select: none; " +
"}";
this.$headStyle = $("<style class='moogle-contextmenu-style' />")
.prop("type", "text/css")
.appendTo("head");
try {
this.$headStyle.html(cssText);
} catch ( e ) {
// issue #47: fix for IE 6-8
this.$headStyle[0].styleSheet.cssText = cssText;
}
// TODO: the selectstart is not supported by FF?
if (supportSelectstart) {
this.element.delegate(opts.delegate, "selectstart" + this.eventNamespace,
function(event) {
event.preventDefault();
});
}
}
this._createUiMenu(opts.menu);
eventNames = "contextmenu" + this.eventNamespace;
if (opts.taphold) {
eventNames += " taphold" + this.eventNamespace;
}
this.element.delegate(opts.delegate, eventNames, $.proxy(this._openMenu, this));
},
/** Destructor, called on $().contextmenu("destroy"). */
_destroy: function() {
this.element.undelegate(this.eventNamespace);
this._createUiMenu(null);
if (this.$headStyle) {
this.$headStyle.remove();
this.$headStyle = null;
}
},
/** (Re)Create jQuery UI Menu. */
_createUiMenu: function(menuDef) {
var ct,
opts = this.options;
// Remove temporary <ul> if any
if (this.isOpen()) {
// #58: 'replaceMenu' in beforeOpen causing select: to lose ui.target
ct = this.currentTarget;
// close without animation, to force async mode
this._closeMenu(true);
this.currentTarget = ct;
}
if (this.menuIsTemp) {
this.$menu.remove(); // this will also destroy ui.menu
} else if (this.$menu) {
this.$menu
.menu("destroy")
.removeClass(this.options.addClass)
.hide();
}
this.$menu = null;
this.menuIsTemp = false;
// If a menu definition array was passed, create a hidden <ul>
// and generate the structure now
if ( !menuDef ) {
return;
} else if ($.isArray(menuDef)) {
this.$menu = $.moogle.contextmenu.createMenuMarkup(menuDef);
this.menuIsTemp = true;
}else if ( typeof menuDef === "string" ) {
this.$menu = $(menuDef);
} else {
this.$menu = menuDef;
}
// Create - but hide - the jQuery UI Menu widget
this.$menu
.hide()
.addClass(opts.addClass)
// Create a menu instance that delegates events to our widget
.menu($.extend(true, {}, opts.uiMenuOptions, {
blur: $.proxy(opts.blur, this),
create: $.proxy(opts.createMenu, this),
focus: $.proxy(opts.focus, this),
select: $.proxy(function(event, ui) {
// User selected a menu entry
var retval,
isParent = $.moogle.contextmenu.isMenu(ui.item),
actionHandler = ui.item.data("actionHandler");
ui.cmd = ui.item.attr("data-command");
ui.target = $(this.currentTarget);
// ignore clicks, if they only open a sub-menu
if ( !isParent || !opts.ignoreParentSelect) {
retval = this._trigger.call(this, "select", event, ui);
if ( actionHandler ) {
retval = actionHandler.call(this, event, ui);
}
if ( retval !== false ) {
this._closeMenu.call(this);
}
event.preventDefault();
}
}, this)
}));
},
/** Open popup (called on 'contextmenu' event). */
_openMenu: function(event, recursive) {
var res, promise,
opts = this.options,
posOption = opts.position,
self = this,
manualTrigger = !!event.isTrigger,
ui = { menu: this.$menu, target: $(event.target),
extraData: event.extraData, originalEvent: event,
result: null };
if ( !opts.autoTrigger && !manualTrigger ) {
// ignore browser's `contextmenu` events
return;
}
// Prevent browser from opening the system context menu
event.preventDefault();
this.currentTarget = event.target;
if ( !recursive ) {
res = this._trigger("beforeOpen", event, ui);
promise = (ui.result && $.isFunction(ui.result.promise)) ? ui.result : null;
ui.result = null;
if ( res === false ) {
this.currentTarget = null;
return false;
} else if ( promise ) {
// Handler returned a Deferred or Promise. Delay menu open until
// the promise is resolved
promise.done(function() {
self._openMenu(event, true);
});
this.currentTarget = null;
return false;
}
ui.menu = this.$menu; // Might have changed in beforeOpen
}
// Register global event handlers that close the dropdown-menu
$(document).bind("keydown" + this.eventNamespace, function(event) {
if ( event.which === $.ui.keyCode.ESCAPE ) {
self._closeMenu();
}
}).bind("mousedown" + this.eventNamespace + " touchstart" + this.eventNamespace,
function(event) {
// Close menu when clicked outside menu
if ( !$(event.target).closest(".ui-menu-item").length ) {
self._closeMenu();
}
});
// required for custom positioning (issue #18 and #13).
if ($.isFunction(posOption)) {
posOption = posOption(event, ui);
}
posOption = $.extend({
my: "left top",
at: "left bottom",
// if called by 'open' method, event does not have pageX/Y
of: (event.pageX === undefined) ? event.target : event,
collision: "fit"
}, posOption);
// Finally display the popup
this.$menu
.show() // required to fix positioning error
.css({
position: "absolute",
left: 0,
top: 0
}).position(posOption)
.hide(); // hide again, so we can apply nice effects
if ( opts.preventContextMenuForPopup ) {
this.$menu.bind("contextmenu" + this.eventNamespace, function(event) {
event.preventDefault();
});
}
this._show(this.$menu, opts.show, function() {
// Set focus to first active menu entry
if ( opts.autoFocus ) {
// var $first = self.$menu.children(".ui-menu-item:enabled:first");
// self.$menu.menu("focus", event, $first).focus();
self.$menu.focus();
self.previousFocus = $(event.target);
}
self._trigger.call(self, "open", event, ui);
});
},
/** Close popup. */
_closeMenu: function(immediately) {
var self = this,
hideOpts = immediately ? false : this.options.hide;
// Note: we don't want to unbind the 'contextmenu' event
$(document)
.unbind("mousedown" + this.eventNamespace)
.unbind("touchstart" + this.eventNamespace)
.unbind("keydown" + this.eventNamespace);
self.currentTarget = null; // issue #44 after hide animation is too late
if ( this.$menu ) { // #88: widget might have been destroyed already
this.$menu
.unbind("contextmenu" + this.eventNamespace);
this._hide(this.$menu, hideOpts, function() {
if ( self.previousFocus ) {
self.previousFocus.focus();
self.previousFocus = null;
}
self._trigger("close");
});
} else {
self._trigger("close");
}
},
/** Handle $().contextmenu("option", key, value) calls. */
_setOption: function(key, value) {
switch (key) {
case "menu":
this.replaceMenu(value);
break;
}
$.Widget.prototype._setOption.apply(this, arguments);
},
/** Return ui-menu entry (<LI> tag). */
_getMenuEntry: function(cmd) {
return this.$menu.find("li[data-command=" + cmd + "]");
},
/** Close context menu. */
close: function() {
if (this.isOpen()) {
this._closeMenu();
}
},
/** Enable or disable the menu command. */
enableEntry: function(cmd, flag) {
this._getMenuEntry(cmd).toggleClass("ui-state-disabled", (flag === false));
},
/** Return Menu element (UL). */
getMenu: function() {
return this.$menu;
},
/** Return true if menu is open. */
isOpen: function() {
// return this.$menu && this.$menu.is(":visible");
return !!this.$menu && !!this.currentTarget;
},
/** Open context menu on a specific target (must match options.delegate)
* Optional `extraData` is passed to event handlers as `ui.extraData`.
*/
open: function(target, extraData) {
// Fake a 'contextmenu' event
extraData = extraData || {};
var e = jQuery.Event("contextmenu", { target: target.get(0), extraData: extraData });
return this.element.trigger(e);
},
/** Replace the menu altogether. */
replaceMenu: function(data) {
this._createUiMenu(data);
},
/** Redefine menu entry (title or all of it). */
setEntry: function(cmd, entry) {
var $ul,
$entryLi = this._getMenuEntry(cmd);
if (typeof entry === "string") {
$.moogle.contextmenu.updateTitle($entryLi, entry);
} else {
$entryLi.empty();
entry.cmd = entry.cmd || cmd;
$.moogle.contextmenu.createEntryMarkup(entry, $entryLi);
if ($.isArray(entry.children)) {
$ul = $("<ul/>").appendTo($entryLi);
$.moogle.contextmenu.createMenuMarkup(entry.children, $ul);
}
this.getMenu().menu("refresh");
}
},
/** Show or hide the menu command. */
showEntry: function(cmd, flag) {
this._getMenuEntry(cmd).toggle(flag !== false);
}
});
/*
* Global functions
*/
$.extend($.moogle.contextmenu, {
/** Convert a menu description into a into a <li> content. */
createEntryMarkup: function(entry, $parentLi) {
var $a = null;
if ( !/[^\-\u2014\u2013\s]/.test( entry.title ) ) {
// hyphen, em dash, en dash: separator as defined by UI Menu 1.10
$parentLi.text(entry.title);
} else {
if ( isLTE110 ) {
// jQuery UI Menu 1.10 or before required an `<a>` tag
$parentLi.attr("data-command", entry.cmd);
$a = $("<a/>", {
html: "" + entry.title,
href: "#"
}).appendTo($parentLi);
if ( entry.uiIcon ) {
$a.append($("<span class='ui-icon' />").addClass(entry.uiIcon));
}
} else {
// jQuery UI Menu 1.11+ preferes to avoid `<a>` tags
$parentLi
.attr("data-command", entry.cmd)
.html("" + entry.title);
if ( $.isFunction(entry.action) ) {
$parentLi.data("actionHandler", entry.action);
}
if ( entry.uiIcon ) {
$parentLi
.append($("<span class='ui-icon' />")
.addClass(entry.uiIcon));
}
}
if ( $.isFunction(entry.action) ) {
$parentLi.data("actionHandler", entry.action);
}
if ( entry.disabled ) {
$parentLi.addClass("ui-state-disabled");
}
if ( entry.addClass ) {
$parentLi.addClass(entry.addClass);
}
if ( $.isPlainObject(entry.data) ) {
$parentLi.data(entry.data);
}
}
},
/** Convert a nested array of command objects into a <ul> structure. */
createMenuMarkup: function(options, $parentUl) {
var i, menu, $ul, $li;
if ( $parentUl == null ) {
$parentUl = $("<ul class='ui-helper-hidden' />").appendTo("body");
}
for (i = 0; i < options.length; i++) {
menu = options[i];
$li = $("<li/>").appendTo($parentUl);
$.moogle.contextmenu.createEntryMarkup(menu, $li);
if ( $.isArray(menu.children) ) {
$ul = $("<ul/>").appendTo($li);
$.moogle.contextmenu.createMenuMarkup(menu.children, $ul);
}
}
return $parentUl;
},
/** Returns true if the menu item has child menu items */
isMenu: function(item) {
if ( isLTE110 ) {
return item.has(">a[aria-haspopup='true']").length > 0;
} else {
return item.is("[aria-haspopup='true']");
}
},
/** Replaces the value of elem's first text node child */
replaceFirstTextNodeChild: function(elem, text) {
elem
.contents()
.filter(function() { return this.nodeType === 3; })
.first()
.replaceWith(text);
},
/** Updates the menu item's title */
updateTitle: function(item, title) {
if ( isLTE110 ) {
$.moogle.contextmenu.replaceFirstTextNodeChild($("a", item), title);
} else {
$.moogle.contextmenu.replaceFirstTextNodeChild(item, title);
}
}
});
}));

File diff suppressed because one or more lines are too long