UNPKG

webgme

Version:

Web-based Generic Modeling Environment

1,178 lines (1,053 loc) 91 kB
/** * jQuery contextMenu v2.7.0 - Plugin for simple contextMenu handling * * Version: v2.7.0 * * Authors: Björn Brala (SWIS.nl), Rodney Rehm, Addy Osmani (patches for FF) * Web: http://swisnl.github.io/jQuery-contextMenu/ * * Copyright (c) 2011-2018 SWIS BV and contributors * * Licensed under * MIT License http://www.opensource.org/licenses/mit-license * * Date: 2018-10-02T14:29:27.777Z */ // jscs:disable /* jshint ignore:start */ (function (factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as anonymous module. define(['jquery'], factory); } else if (typeof exports === 'object') { // Node / CommonJS factory(require('jquery')); } else { // Browser globals. factory(jQuery); } })(function ($) { 'use strict'; // TODO: - // ARIA stuff: menuitem, menuitemcheckbox und menuitemradio // create <menu> structure if $.support[htmlCommand || htmlMenuitem] and !opt.disableNative // determine html5 compatibility $.support.htmlMenuitem = ('HTMLMenuItemElement' in window); $.support.htmlCommand = ('HTMLCommandElement' in window); $.support.eventSelectstart = ('onselectstart' in document.documentElement); /* // should the need arise, test for css user-select $.support.cssUserSelect = (function(){ var t = false, e = document.createElement('div'); $.each('Moz|Webkit|Khtml|O|ms|Icab|'.split('|'), function(i, prefix) { var propCC = prefix + (prefix ? 'U' : 'u') + 'serSelect', prop = (prefix ? ('-' + prefix.toLowerCase() + '-') : '') + 'user-select'; e.style.cssText = prop + ': text;'; if (e.style[propCC] == 'text') { t = true; return false; } return true; }); return t; })(); */ if (!$.ui || !$.widget) { // duck punch $.cleanData like jQueryUI does to get that remove event $.cleanData = (function (orig) { return function (elems) { var events, elem, i; for (i = 0; elems[i] != null; i++) { elem = elems[i]; try { // Only trigger remove when necessary to save time events = $._data(elem, 'events'); if (events && events.remove) { $(elem).triggerHandler('remove'); } // Http://bugs.jquery.com/ticket/8235 } catch (e) { } } orig(elems); }; })($.cleanData); } /* jshint ignore:end */ // jscs:enable var // currently active contextMenu trigger $currentTrigger = null, // is contextMenu initialized with at least one menu? initialized = false, // window handle $win = $(window), // number of registered menus counter = 0, // mapping selector to namespace namespaces = {}, // mapping namespace to options menus = {}, // custom command type handlers types = {}, // default values defaults = { // selector of contextMenu trigger selector: null, // where to append the menu to appendTo: null, // method to trigger context menu ["right", "left", "hover"] trigger: 'right', // hide menu when mouse leaves trigger / menu elements autoHide: false, // ms to wait before showing a hover-triggered context menu delay: 200, // flag denoting if a second trigger should simply move (true) or rebuild (false) an open menu // as long as the trigger happened on one of the trigger-element's child nodes reposition: true, // Flag denoting if a second trigger should close the menu, as long as // the trigger happened on one of the trigger-element's child nodes. // This overrides the reposition option. hideOnSecondTrigger: false, //ability to select submenu selectableSubMenu: false, // Default classname configuration to be able avoid conflicts in frameworks classNames: { hover: 'context-menu-hover', // Item hover disabled: 'context-menu-disabled', // Item disabled visible: 'context-menu-visible', // Item visible notSelectable: 'context-menu-not-selectable', // Item not selectable icon: 'context-menu-icon', iconEdit: 'context-menu-icon-edit', iconCut: 'context-menu-icon-cut', iconCopy: 'context-menu-icon-copy', iconPaste: 'context-menu-icon-paste', iconDelete: 'context-menu-icon-delete', iconAdd: 'context-menu-icon-add', iconQuit: 'context-menu-icon-quit', iconLoadingClass: 'context-menu-icon-loading' }, // determine position to show menu at determinePosition: function ($menu) { // position to the lower middle of the trigger element if ($.ui && $.ui.position) { // .position() is provided as a jQuery UI utility // (...and it won't work on hidden elements) $menu.css('display', 'block').position({ my: 'center top', at: 'center bottom', of: this, offset: '0 5', collision: 'fit' }).css('display', 'none'); } else { // determine contextMenu position var offset = this.offset(); offset.top += this.outerHeight(); offset.left += this.outerWidth() / 2 - $menu.outerWidth() / 2; $menu.css(offset); } }, // position menu position: function (opt, x, y) { var offset; // determine contextMenu position if (!x && !y) { opt.determinePosition.call(this, opt.$menu); return; } else if (x === 'maintain' && y === 'maintain') { // x and y must not be changed (after re-show on command click) offset = opt.$menu.position(); } else { // x and y are given (by mouse event) var offsetParentOffset = opt.$menu.offsetParent().offset(); offset = {top: y - offsetParentOffset.top, left: x -offsetParentOffset.left}; } // correct offset if viewport demands it var bottom = $win.scrollTop() + $win.height(), right = $win.scrollLeft() + $win.width(), height = opt.$menu.outerHeight(), width = opt.$menu.outerWidth(); if (offset.top + height > bottom) { offset.top -= height; } if (offset.top < 0) { offset.top = 0; } if (offset.left + width > right) { offset.left -= width; } if (offset.left < 0) { offset.left = 0; } opt.$menu.css(offset); }, // position the sub-menu positionSubmenu: function ($menu) { if (typeof $menu === 'undefined') { // When user hovers over item (which has sub items) handle.focusItem will call this. // but the submenu does not exist yet if opt.items is a promise. just return, will // call positionSubmenu after promise is completed. return; } if ($.ui && $.ui.position) { // .position() is provided as a jQuery UI utility // (...and it won't work on hidden elements) $menu.css('display', 'block').position({ my: 'left top-5', at: 'right top', of: this, collision: 'flipfit fit' }).css('display', ''); } else { // determine contextMenu position var offset = { top: -9, left: this.outerWidth() - 5 }; $menu.css(offset); } }, // offset to add to zIndex zIndex: 1, // show hide animation settings animation: { duration: 50, show: 'slideDown', hide: 'slideUp' }, // events events: { show: $.noop, hide: $.noop, activated: $.noop }, // default callback callback: null, // list of contextMenu items items: {} }, // mouse position for hover activation hoveract = { timer: null, pageX: null, pageY: null }, // determine zIndex zindex = function ($t) { var zin = 0, $tt = $t; while (true) { zin = Math.max(zin, parseInt($tt.css('z-index'), 10) || 0); $tt = $tt.parent(); if (!$tt || !$tt.length || 'html body'.indexOf($tt.prop('nodeName').toLowerCase()) > -1) { break; } } return zin; }, // event handlers handle = { // abort anything abortevent: function (e) { e.preventDefault(); e.stopImmediatePropagation(); }, // contextmenu show dispatcher contextmenu: function (e) { var $this = $(this); // disable actual context-menu if we are using the right mouse button as the trigger if (e.data.trigger === 'right') { e.preventDefault(); e.stopImmediatePropagation(); } // abort native-triggered events unless we're triggering on right click if ((e.data.trigger !== 'right' && e.data.trigger !== 'demand') && e.originalEvent) { return; } // Let the current contextmenu decide if it should show or not based on its own trigger settings if (typeof e.mouseButton !== 'undefined' && e.data) { if (!(e.data.trigger === 'left' && e.mouseButton === 0) && !(e.data.trigger === 'right' && e.mouseButton === 2)) { // Mouse click is not valid. return; } } // abort event if menu is visible for this trigger if ($this.hasClass('context-menu-active')) { return; } if (!$this.hasClass('context-menu-disabled')) { // theoretically need to fire a show event at <menu> // http://www.whatwg.org/specs/web-apps/current-work/multipage/interactive-elements.html#context-menus // var evt = jQuery.Event("show", { data: data, pageX: e.pageX, pageY: e.pageY, relatedTarget: this }); // e.data.$menu.trigger(evt); $currentTrigger = $this; if (e.data.build) { var built = e.data.build($currentTrigger, e); // abort if build() returned false if (built === false) { return; } // dynamically build menu on invocation e.data = $.extend(true, {}, defaults, e.data, built || {}); // abort if there are no items to display if (!e.data.items || $.isEmptyObject(e.data.items)) { // Note: jQuery captures and ignores errors from event handlers if (window.console) { (console.error || console.log).call(console, 'No items specified to show in contextMenu'); } throw new Error('No Items specified'); } // backreference for custom command type creation e.data.$trigger = $currentTrigger; op.create(e.data); } op.show.call($this, e.data, e.pageX, e.pageY); } }, // contextMenu left-click trigger click: function (e) { e.preventDefault(); e.stopImmediatePropagation(); $(this).trigger($.Event('contextmenu', {data: e.data, pageX: e.pageX, pageY: e.pageY})); }, // contextMenu right-click trigger mousedown: function (e) { // register mouse down var $this = $(this); // hide any previous menus if ($currentTrigger && $currentTrigger.length && !$currentTrigger.is($this)) { $currentTrigger.data('contextMenu').$menu.trigger('contextmenu:hide'); } // activate on right click if (e.button === 2) { $currentTrigger = $this.data('contextMenuActive', true); } }, // contextMenu right-click trigger mouseup: function (e) { // show menu var $this = $(this); if ($this.data('contextMenuActive') && $currentTrigger && $currentTrigger.length && $currentTrigger.is($this) && !$this.hasClass('context-menu-disabled')) { e.preventDefault(); e.stopImmediatePropagation(); $currentTrigger = $this; $this.trigger($.Event('contextmenu', {data: e.data, pageX: e.pageX, pageY: e.pageY})); } $this.removeData('contextMenuActive'); }, // contextMenu hover trigger mouseenter: function (e) { var $this = $(this), $related = $(e.relatedTarget), $document = $(document); // abort if we're coming from a menu if ($related.is('.context-menu-list') || $related.closest('.context-menu-list').length) { return; } // abort if a menu is shown if ($currentTrigger && $currentTrigger.length) { return; } hoveract.pageX = e.pageX; hoveract.pageY = e.pageY; hoveract.data = e.data; $document.on('mousemove.contextMenuShow', handle.mousemove); hoveract.timer = setTimeout(function () { hoveract.timer = null; $document.off('mousemove.contextMenuShow'); $currentTrigger = $this; $this.trigger($.Event('contextmenu', { data: hoveract.data, pageX: hoveract.pageX, pageY: hoveract.pageY })); }, e.data.delay); }, // contextMenu hover trigger mousemove: function (e) { hoveract.pageX = e.pageX; hoveract.pageY = e.pageY; }, // contextMenu hover trigger mouseleave: function (e) { // abort if we're leaving for a menu var $related = $(e.relatedTarget); if ($related.is('.context-menu-list') || $related.closest('.context-menu-list').length) { return; } try { clearTimeout(hoveract.timer); } catch (e) { } hoveract.timer = null; }, // click on layer to hide contextMenu layerClick: function (e) { var $this = $(this), root = $this.data('contextMenuRoot'), button = e.button, x = e.pageX, y = e.pageY, fakeClick = x === undefined, target, offset; e.preventDefault(); setTimeout(function () { // If the click is not real, things break: https://github.com/swisnl/jQuery-contextMenu/issues/132 if(fakeClick){ if (root !== null && typeof root !== 'undefined' && root.$menu !== null && typeof root.$menu !== 'undefined') { root.$menu.trigger('contextmenu:hide'); } return; } var $window; var triggerAction = ((root.trigger === 'left' && button === 0) || (root.trigger === 'right' && button === 2)); // find the element that would've been clicked, wasn't the layer in the way if (document.elementFromPoint && root.$layer) { root.$layer.hide(); target = document.elementFromPoint(x - $win.scrollLeft(), y - $win.scrollTop()); // also need to try and focus this element if we're in a contenteditable area, // as the layer will prevent the browser mouse action we want if (target.isContentEditable) { var range = document.createRange(), sel = window.getSelection(); range.selectNode(target); range.collapse(true); sel.removeAllRanges(); sel.addRange(range); } $(target).trigger(e); root.$layer.show(); } if (root.hideOnSecondTrigger && triggerAction && root.$menu !== null && typeof root.$menu !== 'undefined') { root.$menu.trigger('contextmenu:hide'); return; } if (root.reposition && triggerAction) { if (document.elementFromPoint) { if (root.$trigger.is(target)) { root.position.call(root.$trigger, root, x, y); return; } } else { offset = root.$trigger.offset(); $window = $(window); // while this looks kinda awful, it's the best way to avoid // unnecessarily calculating any positions offset.top += $window.scrollTop(); if (offset.top <= e.pageY) { offset.left += $window.scrollLeft(); if (offset.left <= e.pageX) { offset.bottom = offset.top + root.$trigger.outerHeight(); if (offset.bottom >= e.pageY) { offset.right = offset.left + root.$trigger.outerWidth(); if (offset.right >= e.pageX) { // reposition root.position.call(root.$trigger, root, x, y); return; } } } } } } if (target && triggerAction) { root.$trigger.one('contextmenu:hidden', function () { $(target).contextMenu({x: x, y: y, button: button}); }); } if (root !== null && typeof root !== 'undefined' && root.$menu !== null && typeof root.$menu !== 'undefined') { root.$menu.trigger('contextmenu:hide'); } }, 50); }, // key handled :hover keyStop: function (e, opt) { if (!opt.isInput) { e.preventDefault(); } e.stopPropagation(); }, key: function (e) { var opt = {}; // Only get the data from $currentTrigger if it exists if ($currentTrigger) { opt = $currentTrigger.data('contextMenu') || {}; } // If the trigger happen on a element that are above the contextmenu do this if (typeof opt.zIndex === 'undefined') { opt.zIndex = 0; } var targetZIndex = 0; var getZIndexOfTriggerTarget = function (target) { if (target.style.zIndex !== '') { targetZIndex = target.style.zIndex; } else { if (target.offsetParent !== null && typeof target.offsetParent !== 'undefined') { getZIndexOfTriggerTarget(target.offsetParent); } else if (target.parentElement !== null && typeof target.parentElement !== 'undefined') { getZIndexOfTriggerTarget(target.parentElement); } } }; getZIndexOfTriggerTarget(e.target); // If targetZIndex is heigher then opt.zIndex dont progress any futher. // This is used to make sure that if you are using a dialog with a input / textarea / contenteditable div // and its above the contextmenu it wont steal keys events if (opt.$menu && parseInt(targetZIndex,10) > parseInt(opt.$menu.css("zIndex"),10)) { return; } switch (e.keyCode) { case 9: case 38: // up handle.keyStop(e, opt); // if keyCode is [38 (up)] or [9 (tab) with shift] if (opt.isInput) { if (e.keyCode === 9 && e.shiftKey) { e.preventDefault(); if (opt.$selected) { opt.$selected.find('input, textarea, select').blur(); } if (opt.$menu !== null && typeof opt.$menu !== 'undefined') { opt.$menu.trigger('prevcommand'); } return; } else if (e.keyCode === 38 && opt.$selected.find('input, textarea, select').prop('type') === 'checkbox') { // checkboxes don't capture this key e.preventDefault(); return; } } else if (e.keyCode !== 9 || e.shiftKey) { if (opt.$menu !== null && typeof opt.$menu !== 'undefined') { opt.$menu.trigger('prevcommand'); } return; } break; // omitting break; // case 9: // tab - reached through omitted break; case 40: // down handle.keyStop(e, opt); if (opt.isInput) { if (e.keyCode === 9) { e.preventDefault(); if (opt.$selected) { opt.$selected.find('input, textarea, select').blur(); } if (opt.$menu !== null && typeof opt.$menu !== 'undefined') { opt.$menu.trigger('nextcommand'); } return; } else if (e.keyCode === 40 && opt.$selected.find('input, textarea, select').prop('type') === 'checkbox') { // checkboxes don't capture this key e.preventDefault(); return; } } else { if (opt.$menu !== null && typeof opt.$menu !== 'undefined') { opt.$menu.trigger('nextcommand'); } return; } break; case 37: // left handle.keyStop(e, opt); if (opt.isInput || !opt.$selected || !opt.$selected.length) { break; } if (!opt.$selected.parent().hasClass('context-menu-root')) { var $parent = opt.$selected.parent().parent(); opt.$selected.trigger('contextmenu:blur'); opt.$selected = $parent; return; } break; case 39: // right handle.keyStop(e, opt); if (opt.isInput || !opt.$selected || !opt.$selected.length) { break; } var itemdata = opt.$selected.data('contextMenu') || {}; if (itemdata.$menu && opt.$selected.hasClass('context-menu-submenu')) { opt.$selected = null; itemdata.$selected = null; itemdata.$menu.trigger('nextcommand'); return; } break; case 35: // end case 36: // home if (opt.$selected && opt.$selected.find('input, textarea, select').length) { return; } else { (opt.$selected && opt.$selected.parent() || opt.$menu) .children(':not(.' + opt.classNames.disabled + ', .' + opt.classNames.notSelectable + ')')[e.keyCode === 36 ? 'first' : 'last']() .trigger('contextmenu:focus'); e.preventDefault(); return; } break; case 13: // enter handle.keyStop(e, opt); if (opt.isInput) { if (opt.$selected && !opt.$selected.is('textarea, select')) { e.preventDefault(); return; } break; } if (typeof opt.$selected !== 'undefined' && opt.$selected !== null) { opt.$selected.trigger('mouseup'); } return; case 32: // space case 33: // page up case 34: // page down // prevent browser from scrolling down while menu is visible handle.keyStop(e, opt); return; case 27: // esc handle.keyStop(e, opt); if (opt.$menu !== null && typeof opt.$menu !== 'undefined') { opt.$menu.trigger('contextmenu:hide'); } return; default: // 0-9, a-z var k = (String.fromCharCode(e.keyCode)).toUpperCase(); if (opt.accesskeys && opt.accesskeys[k]) { // according to the specs accesskeys must be invoked immediately opt.accesskeys[k].$node.trigger(opt.accesskeys[k].$menu ? 'contextmenu:focus' : 'mouseup'); return; } break; } // pass event to selected item, // stop propagation to avoid endless recursion e.stopPropagation(); if (typeof opt.$selected !== 'undefined' && opt.$selected !== null) { opt.$selected.trigger(e); } }, // select previous possible command in menu prevItem: function (e) { e.stopPropagation(); var opt = $(this).data('contextMenu') || {}; var root = $(this).data('contextMenuRoot') || {}; // obtain currently selected menu if (opt.$selected) { var $s = opt.$selected; opt = opt.$selected.parent().data('contextMenu') || {}; opt.$selected = $s; } var $children = opt.$menu.children(), $prev = !opt.$selected || !opt.$selected.prev().length ? $children.last() : opt.$selected.prev(), $round = $prev; // skip disabled or hidden elements while ($prev.hasClass(root.classNames.disabled) || $prev.hasClass(root.classNames.notSelectable) || $prev.is(':hidden')) { if ($prev.prev().length) { $prev = $prev.prev(); } else { $prev = $children.last(); } if ($prev.is($round)) { // break endless loop return; } } // leave current if (opt.$selected) { handle.itemMouseleave.call(opt.$selected.get(0), e); } // activate next handle.itemMouseenter.call($prev.get(0), e); // focus input var $input = $prev.find('input, textarea, select'); if ($input.length) { $input.focus(); } }, // select next possible command in menu nextItem: function (e) { e.stopPropagation(); var opt = $(this).data('contextMenu') || {}; var root = $(this).data('contextMenuRoot') || {}; // obtain currently selected menu if (opt.$selected) { var $s = opt.$selected; opt = opt.$selected.parent().data('contextMenu') || {}; opt.$selected = $s; } var $children = opt.$menu.children(), $next = !opt.$selected || !opt.$selected.next().length ? $children.first() : opt.$selected.next(), $round = $next; // skip disabled while ($next.hasClass(root.classNames.disabled) || $next.hasClass(root.classNames.notSelectable) || $next.is(':hidden')) { if ($next.next().length) { $next = $next.next(); } else { $next = $children.first(); } if ($next.is($round)) { // break endless loop return; } } // leave current if (opt.$selected) { handle.itemMouseleave.call(opt.$selected.get(0), e); } // activate next handle.itemMouseenter.call($next.get(0), e); // focus input var $input = $next.find('input, textarea, select'); if ($input.length) { $input.focus(); } }, // flag that we're inside an input so the key handler can act accordingly focusInput: function () { var $this = $(this).closest('.context-menu-item'), data = $this.data(), opt = data.contextMenu, root = data.contextMenuRoot; root.$selected = opt.$selected = $this; root.isInput = opt.isInput = true; }, // flag that we're inside an input so the key handler can act accordingly blurInput: function () { var $this = $(this).closest('.context-menu-item'), data = $this.data(), opt = data.contextMenu, root = data.contextMenuRoot; root.isInput = opt.isInput = false; }, // :hover on menu menuMouseenter: function () { var root = $(this).data().contextMenuRoot; root.hovering = true; }, // :hover on menu menuMouseleave: function (e) { var root = $(this).data().contextMenuRoot; if (root.$layer && root.$layer.is(e.relatedTarget)) { root.hovering = false; } }, // :hover done manually so key handling is possible itemMouseenter: function (e) { var $this = $(this), data = $this.data(), opt = data.contextMenu, root = data.contextMenuRoot; root.hovering = true; // abort if we're re-entering if (e && root.$layer && root.$layer.is(e.relatedTarget)) { e.preventDefault(); e.stopImmediatePropagation(); } // make sure only one item is selected (opt.$menu ? opt : root).$menu .children('.' + root.classNames.hover).trigger('contextmenu:blur') .children('.hover').trigger('contextmenu:blur'); if ($this.hasClass(root.classNames.disabled) || $this.hasClass(root.classNames.notSelectable)) { opt.$selected = null; return; } $this.trigger('contextmenu:focus'); }, // :hover done manually so key handling is possible itemMouseleave: function (e) { var $this = $(this), data = $this.data(), opt = data.contextMenu, root = data.contextMenuRoot; if (root !== opt && root.$layer && root.$layer.is(e.relatedTarget)) { if (typeof root.$selected !== 'undefined' && root.$selected !== null) { root.$selected.trigger('contextmenu:blur'); } e.preventDefault(); e.stopImmediatePropagation(); root.$selected = opt.$selected = opt.$node; return; } if(opt && opt.$menu && opt.$menu.hasClass('context-menu-visible')){ return; } $this.trigger('contextmenu:blur'); }, // contextMenu item click itemClick: function (e) { var $this = $(this), data = $this.data(), opt = data.contextMenu, root = data.contextMenuRoot, key = data.contextMenuKey, callback; // abort if the key is unknown or disabled or is a menu if (!opt.items[key] || $this.is('.' + root.classNames.disabled + ', .context-menu-separator, .' + root.classNames.notSelectable) || ($this.is('.context-menu-submenu') && root.selectableSubMenu === false )) { return; } e.preventDefault(); e.stopImmediatePropagation(); if ($.isFunction(opt.callbacks[key]) && Object.prototype.hasOwnProperty.call(opt.callbacks, key)) { // item-specific callback callback = opt.callbacks[key]; } else if ($.isFunction(root.callback)) { // default callback callback = root.callback; } else { // no callback, no action return; } // hide menu if callback doesn't stop that if (callback.call(root.$trigger, key, root, e) !== false) { root.$menu.trigger('contextmenu:hide'); } else if (root.$menu.parent().length) { op.update.call(root.$trigger, root); } }, // ignore click events on input elements inputClick: function (e) { e.stopImmediatePropagation(); }, // hide <menu> hideMenu: function (e, data) { var root = $(this).data('contextMenuRoot'); op.hide.call(root.$trigger, root, data && data.force); }, // focus <command> focusItem: function (e) { e.stopPropagation(); var $this = $(this), data = $this.data(), opt = data.contextMenu, root = data.contextMenuRoot; if ($this.hasClass(root.classNames.disabled) || $this.hasClass(root.classNames.notSelectable)) { return; } $this .addClass([root.classNames.hover, root.classNames.visible].join(' ')) // select other items and included items .parent().find('.context-menu-item').not($this) .removeClass(root.classNames.visible) .filter('.' + root.classNames.hover) .trigger('contextmenu:blur'); // remember selected opt.$selected = root.$selected = $this; if(opt && opt.$node && opt.$node.hasClass('context-menu-submenu')){ opt.$node.addClass(root.classNames.hover); } // position sub-menu - do after show so dumb $.ui.position can keep up if (opt.$node) { root.positionSubmenu.call(opt.$node, opt.$menu); } }, // blur <command> blurItem: function (e) { e.stopPropagation(); var $this = $(this), data = $this.data(), opt = data.contextMenu, root = data.contextMenuRoot; if (opt.autoHide) { // for tablets and touch screens this needs to remain $this.removeClass(root.classNames.visible); } $this.removeClass(root.classNames.hover); opt.$selected = null; } }, // operations op = { show: function (opt, x, y) { var $trigger = $(this), css = {}; // hide any open menus $('#context-menu-layer').trigger('mousedown'); // backreference for callbacks opt.$trigger = $trigger; // show event if (opt.events.show.call($trigger, opt) === false) { $currentTrigger = null; return; } // create or update context menu var hasVisibleItems = op.update.call($trigger, opt); if (hasVisibleItems === false) { $currentTrigger = null; return; } // position menu opt.position.call($trigger, opt, x, y); // make sure we're in front if (opt.zIndex) { var additionalZValue = opt.zIndex; // If opt.zIndex is a function, call the function to get the right zIndex. if (typeof opt.zIndex === 'function') { additionalZValue = opt.zIndex.call($trigger, opt); } css.zIndex = zindex($trigger) + additionalZValue; } // add layer op.layer.call(opt.$menu, opt, css.zIndex); // adjust sub-menu zIndexes opt.$menu.find('ul').css('zIndex', css.zIndex + 1); // position and show context menu opt.$menu.css(css)[opt.animation.show](opt.animation.duration, function () { $trigger.trigger('contextmenu:visible'); op.activated(opt); opt.events.activated(opt); }); // make options available and set state $trigger .data('contextMenu', opt) .addClass('context-menu-active'); // register key handler $(document).off('keydown.contextMenu').on('keydown.contextMenu', handle.key); // register autoHide handler if (opt.autoHide) { // mouse position handler $(document).on('mousemove.contextMenuAutoHide', function (e) { // need to capture the offset on mousemove, // since the page might've been scrolled since activation var pos = $trigger.offset(); pos.right = pos.left + $trigger.outerWidth(); pos.bottom = pos.top + $trigger.outerHeight(); if (opt.$layer && !opt.hovering && (!(e.pageX >= pos.left && e.pageX <= pos.right) || !(e.pageY >= pos.top && e.pageY <= pos.bottom))) { /* Additional hover check after short time, you might just miss the edge of the menu */ setTimeout(function () { if (!opt.hovering && opt.$menu !== null && typeof opt.$menu !== 'undefined') { opt.$menu.trigger('contextmenu:hide'); } }, 50); } }); } }, hide: function (opt, force) { var $trigger = $(this); if (!opt) { opt = $trigger.data('contextMenu') || {}; } // hide event if (!force && opt.events && opt.events.hide.call($trigger, opt) === false) { return; } // remove options and revert state $trigger .removeData('contextMenu') .removeClass('context-menu-active'); if (opt.$layer) { // keep layer for a bit so the contextmenu event can be aborted properly by opera setTimeout((function ($layer) { return function () { $layer.remove(); }; })(opt.$layer), 10); try { delete opt.$layer; } catch (e) { opt.$layer = null; } } // remove handle $currentTrigger = null; // remove selected opt.$menu.find('.' + opt.classNames.hover).trigger('contextmenu:blur'); opt.$selected = null; // collapse all submenus opt.$menu.find('.' + opt.classNames.visible).removeClass(opt.classNames.visible); // unregister key and mouse handlers // $(document).off('.contextMenuAutoHide keydown.contextMenu'); // http://bugs.jquery.com/ticket/10705 $(document).off('.contextMenuAutoHide').off('keydown.contextMenu'); // hide menu if (opt.$menu) { opt.$menu[opt.animation.hide](opt.animation.duration, function () { // tear down dynamically built menu after animation is completed. if (opt.build) { opt.$menu.remove(); $.each(opt, function (key) { switch (key) { case 'ns': case 'selector': case 'build': case 'trigger': return true; default: opt[key] = undefined; try { delete opt[key]; } catch (e) { } return true; } }); } setTimeout(function () { $trigger.trigger('contextmenu:hidden'); }, 10); }); } }, create: function (opt, root) { if (typeof root === 'undefined') { root = opt; } // create contextMenu opt.$menu = $('<ul class="context-menu-list"></ul>').addClass(opt.className || '').data({ 'contextMenu': opt, 'contextMenuRoot': root }); $.each(['callbacks', 'commands', 'inputs'], function (i, k) { opt[k] = {}; if (!root[k]) { root[k] = {}; } }); if (!root.accesskeys) { root.accesskeys = {}; } function createNameNode(item) { var $name = $('<span></span>'); if (item._accesskey) { if (item._beforeAccesskey) { $name.append(document.createTextNode(item._beforeAccesskey)); } $('<span></span>') .addClass('context-menu-accesskey') .text(item._accesskey) .appendTo($name); if (item._afterAccesskey) { $name.append(document.createTextNode(item._afterAccesskey)); } } else { if (item.isHtmlName) { // restrict use with access keys if (typeof item.accesskey !== 'undefined') { throw new Error('accesskeys are not compatible with HTML names and cannot be used together in the same item'); } $name.html(item.name); } else { $name.text(item.name); } } return $name; } // create contextMenu items $.each(opt.items, function (key, item) { var $t = $('<li class="context-menu-item"></li>').addClass(item.className || ''), $label = null, $input = null; // iOS needs to see a click-event bound to an element to actually // have the TouchEvents infrastructure trigger the click event $t.on('click', $.noop); // Make old school string seperator a real item so checks wont be // akward later. // And normalize 'cm_separator' into 'cm_seperator'. if (typeof item === 'string' || item.type === 'cm_separator') { item = {type: 'cm_seperator'}; } item.$node = $t.data({ 'contextMenu': opt, 'contextMenuRoot': root, 'contextMenuKey': key