jquery.contextMenu.js 84 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009
  1. /*!
  2. * jQuery contextMenu v2.4.2 - Plugin for simple contextMenu handling
  3. *
  4. * Version: v2.4.2
  5. *
  6. * Authors: Björn Brala (SWIS.nl), Rodney Rehm, Addy Osmani (patches for FF)
  7. * Web: http://swisnl.github.io/jQuery-contextMenu/
  8. *
  9. * Copyright (c) 2011-2017 SWIS BV and contributors
  10. *
  11. * Licensed under
  12. * MIT License http://www.opensource.org/licenses/mit-license
  13. * GPL v3 http://opensource.org/licenses/GPL-3.0
  14. *
  15. * Date: 2017-01-02T09:03:00.678Z
  16. */
  17. // jscs:disable
  18. /* jshint ignore:start */
  19. (function (factory) {
  20. if (typeof define === 'function' && define.amd) {
  21. // AMD. Register as anonymous module.
  22. define(['jquery'], factory);
  23. } else if (typeof exports === 'object') {
  24. // Node / CommonJS
  25. factory(require('jquery'));
  26. } else {
  27. // Browser globals.
  28. factory(jQuery);
  29. }
  30. })(function ($) {
  31. 'use strict';
  32. // TODO: -
  33. // ARIA stuff: menuitem, menuitemcheckbox und menuitemradio
  34. // create <menu> structure if $.support[htmlCommand || htmlMenuitem] and !opt.disableNative
  35. // determine html5 compatibility
  36. $.support.htmlMenuitem = ('HTMLMenuItemElement' in window);
  37. $.support.htmlCommand = ('HTMLCommandElement' in window);
  38. $.support.eventSelectstart = ('onselectstart' in document.documentElement);
  39. /* // should the need arise, test for css user-select
  40. $.support.cssUserSelect = (function(){
  41. var t = false,
  42. e = document.createElement('div');
  43. $.each('Moz|Webkit|Khtml|O|ms|Icab|'.split('|'), function(i, prefix) {
  44. var propCC = prefix + (prefix ? 'U' : 'u') + 'serSelect',
  45. prop = (prefix ? ('-' + prefix.toLowerCase() + '-') : '') + 'user-select';
  46. e.style.cssText = prop + ': text;';
  47. if (e.style[propCC] == 'text') {
  48. t = true;
  49. return false;
  50. }
  51. return true;
  52. });
  53. return t;
  54. })();
  55. */
  56. if (!$.ui || !$.widget) {
  57. // duck punch $.cleanData like jQueryUI does to get that remove event
  58. $.cleanData = (function (orig) {
  59. return function (elems) {
  60. var events, elem, i;
  61. for (i = 0; elems[i] != null; i++) {
  62. elem = elems[i];
  63. try {
  64. // Only trigger remove when necessary to save time
  65. events = $._data(elem, 'events');
  66. if (events && events.remove) {
  67. $(elem).triggerHandler('remove');
  68. }
  69. // Http://bugs.jquery.com/ticket/8235
  70. } catch (e) {}
  71. }
  72. orig(elems);
  73. };
  74. })($.cleanData);
  75. }
  76. /* jshint ignore:end */
  77. // jscs:enable
  78. var // currently active contextMenu trigger
  79. $currentTrigger = null,
  80. // is contextMenu initialized with at least one menu?
  81. initialized = false,
  82. // window handle
  83. $win = $(window),
  84. // number of registered menus
  85. counter = 0,
  86. // mapping selector to namespace
  87. namespaces = {},
  88. // mapping namespace to options
  89. menus = {},
  90. // custom command type handlers
  91. types = {},
  92. // default values
  93. defaults = {
  94. // selector of contextMenu trigger
  95. selector: null,
  96. // where to append the menu to
  97. appendTo: null,
  98. // method to trigger context menu ["right", "left", "hover"]
  99. trigger: 'right',
  100. // hide menu when mouse leaves trigger / menu elements
  101. autoHide: false,
  102. // ms to wait before showing a hover-triggered context menu
  103. delay: 200,
  104. // flag denoting if a second trigger should simply move (true) or rebuild (false) an open menu
  105. // as long as the trigger happened on one of the trigger-element's child nodes
  106. reposition: true,
  107. //ability to select submenu
  108. selectableSubMenu: false,
  109. // Default classname configuration to be able avoid conflicts in frameworks
  110. classNames : {
  111. hover: 'context-menu-hover', // Item hover
  112. disabled: 'context-menu-disabled', // Item disabled
  113. visible: 'context-menu-visible', // Item visible
  114. notSelectable: 'context-menu-not-selectable', // Item not selectable
  115. icon: 'context-menu-icon',
  116. iconEdit: 'context-menu-icon-edit',
  117. iconCut: 'context-menu-icon-cut',
  118. iconCopy: 'context-menu-icon-copy',
  119. iconPaste: 'context-menu-icon-paste',
  120. iconDelete: 'context-menu-icon-delete',
  121. iconAdd: 'context-menu-icon-add',
  122. iconQuit: 'context-menu-icon-quit',
  123. iconLoadingClass: 'context-menu-icon-loading'
  124. },
  125. // determine position to show menu at
  126. determinePosition: function ($menu) {
  127. // position to the lower middle of the trigger element
  128. if ($.ui && $.ui.position) {
  129. // .position() is provided as a jQuery UI utility
  130. // (...and it won't work on hidden elements)
  131. $menu.css('display', 'block').position({
  132. my: 'center top',
  133. at: 'center bottom',
  134. of: this,
  135. offset: '0 5',
  136. collision: 'fit'
  137. }).css('display', 'none');
  138. } else {
  139. // determine contextMenu position
  140. var offset = this.offset();
  141. offset.top += this.outerHeight();
  142. offset.left += this.outerWidth() / 2 - $menu.outerWidth() / 2;
  143. $menu.css(offset);
  144. }
  145. },
  146. // position menu
  147. position: function (opt, x, y) {
  148. var offset;
  149. // determine contextMenu position
  150. if (!x && !y) {
  151. opt.determinePosition.call(this, opt.$menu);
  152. return;
  153. } else if (x === 'maintain' && y === 'maintain') {
  154. // x and y must not be changed (after re-show on command click)
  155. offset = opt.$menu.position();
  156. } else {
  157. // x and y are given (by mouse event)
  158. offset = {top: y, left: x};
  159. }
  160. // correct offset if viewport demands it
  161. var bottom = $win.scrollTop() + $win.height(),
  162. right = $win.scrollLeft() + $win.width(),
  163. height = opt.$menu.outerHeight(),
  164. width = opt.$menu.outerWidth();
  165. if (offset.top + height > bottom) {
  166. offset.top -= height;
  167. }
  168. if (offset.top < 0) {
  169. offset.top = 0;
  170. }
  171. if (offset.left + width > right) {
  172. offset.left -= width;
  173. }
  174. if (offset.left < 0) {
  175. offset.left = 0;
  176. }
  177. opt.$menu.css(offset);
  178. },
  179. // position the sub-menu
  180. positionSubmenu: function ($menu) {
  181. if ($menu === undefined) {
  182. // When user hovers over item (which has sub items) handle.focusItem will call this.
  183. // but the submenu does not exist yet if opt.items is a promise. just return, will
  184. // call positionSubmenu after promise is completed.
  185. return;
  186. }
  187. if ($.ui && $.ui.position) {
  188. // .position() is provided as a jQuery UI utility
  189. // (...and it won't work on hidden elements)
  190. $menu.css('display', 'block').position({
  191. my: 'left top-5',
  192. at: 'right top',
  193. of: this,
  194. collision: 'flipfit fit'
  195. }).css('display', '');
  196. } else {
  197. // determine contextMenu position
  198. var offset = {
  199. top: -9,
  200. left: this.outerWidth() - 5
  201. };
  202. $menu.css(offset);
  203. }
  204. },
  205. // offset to add to zIndex
  206. zIndex: 1,
  207. // show hide animation settings
  208. animation: {
  209. duration: 50,
  210. show: 'slideDown',
  211. hide: 'slideUp'
  212. },
  213. // events
  214. events: {
  215. show: $.noop,
  216. hide: $.noop
  217. },
  218. // default callback
  219. callback: null,
  220. // list of contextMenu items
  221. items: {}
  222. },
  223. // mouse position for hover activation
  224. hoveract = {
  225. timer: null,
  226. pageX: null,
  227. pageY: null
  228. },
  229. // determine zIndex
  230. zindex = function ($t) {
  231. var zin = 0,
  232. $tt = $t;
  233. while (true) {
  234. zin = Math.max(zin, parseInt($tt.css('z-index'), 10) || 0);
  235. $tt = $tt.parent();
  236. if (!$tt || !$tt.length || 'html body'.indexOf($tt.prop('nodeName').toLowerCase()) > -1) {
  237. break;
  238. }
  239. }
  240. return zin;
  241. },
  242. // event handlers
  243. handle = {
  244. // abort anything
  245. abortevent: function (e) {
  246. e.preventDefault();
  247. e.stopImmediatePropagation();
  248. },
  249. // contextmenu show dispatcher
  250. contextmenu: function (e) {
  251. var $this = $(this);
  252. // disable actual context-menu if we are using the right mouse button as the trigger
  253. if (e.data.trigger === 'right') {
  254. e.preventDefault();
  255. e.stopImmediatePropagation();
  256. }
  257. // abort native-triggered events unless we're triggering on right click
  258. if ((e.data.trigger !== 'right' && e.data.trigger !== 'demand') && e.originalEvent) {
  259. return;
  260. }
  261. // Let the current contextmenu decide if it should show or not based on its own trigger settings
  262. if (e.mouseButton !== undefined && e.data) {
  263. if (!(e.data.trigger === 'left' && e.mouseButton === 0) && !(e.data.trigger === 'right' && e.mouseButton === 2)) {
  264. // Mouse click is not valid.
  265. return;
  266. }
  267. }
  268. // abort event if menu is visible for this trigger
  269. if ($this.hasClass('context-menu-active')) {
  270. return;
  271. }
  272. if (!$this.hasClass('context-menu-disabled')) {
  273. // theoretically need to fire a show event at <menu>
  274. // http://www.whatwg.org/specs/web-apps/current-work/multipage/interactive-elements.html#context-menus
  275. // var evt = jQuery.Event("show", { data: data, pageX: e.pageX, pageY: e.pageY, relatedTarget: this });
  276. // e.data.$menu.trigger(evt);
  277. $currentTrigger = $this;
  278. if (e.data.build) {
  279. var built = e.data.build($currentTrigger, e);
  280. // abort if build() returned false
  281. if (built === false) {
  282. return;
  283. }
  284. // dynamically build menu on invocation
  285. e.data = $.extend(true, {}, defaults, e.data, built || {});
  286. // abort if there are no items to display
  287. if (!e.data.items || $.isEmptyObject(e.data.items)) {
  288. // Note: jQuery captures and ignores errors from event handlers
  289. if (window.console) {
  290. (console.error || console.log).call(console, 'No items specified to show in contextMenu');
  291. }
  292. throw new Error('No Items specified');
  293. }
  294. // backreference for custom command type creation
  295. e.data.$trigger = $currentTrigger;
  296. op.create(e.data);
  297. }
  298. var showMenu = false;
  299. for (var item in e.data.items) {
  300. if (e.data.items.hasOwnProperty(item)) {
  301. var visible;
  302. if ($.isFunction(e.data.items[item].visible)) {
  303. visible = e.data.items[item].visible.call($(e.currentTarget), item, e.data);
  304. } else if (typeof e.data.items[item] !== 'undefined' && e.data.items[item].visible) {
  305. visible = e.data.items[item].visible === true;
  306. } else {
  307. visible = true;
  308. }
  309. if (visible) {
  310. showMenu = true;
  311. }
  312. }
  313. }
  314. if (showMenu) {
  315. // show menu
  316. op.show.call($this, e.data, e.pageX, e.pageY);
  317. }
  318. }
  319. },
  320. // contextMenu left-click trigger
  321. click: function (e) {
  322. e.preventDefault();
  323. e.stopImmediatePropagation();
  324. $(this).trigger($.Event('contextmenu', {data: e.data, pageX: e.pageX, pageY: e.pageY}));
  325. },
  326. // contextMenu right-click trigger
  327. mousedown: function (e) {
  328. // register mouse down
  329. var $this = $(this);
  330. // hide any previous menus
  331. if ($currentTrigger && $currentTrigger.length && !$currentTrigger.is($this)) {
  332. $currentTrigger.data('contextMenu').$menu.trigger('contextmenu:hide');
  333. }
  334. // activate on right click
  335. if (e.button === 2) {
  336. $currentTrigger = $this.data('contextMenuActive', true);
  337. }
  338. },
  339. // contextMenu right-click trigger
  340. mouseup: function (e) {
  341. // show menu
  342. var $this = $(this);
  343. if ($this.data('contextMenuActive') && $currentTrigger && $currentTrigger.length && $currentTrigger.is($this) && !$this.hasClass('context-menu-disabled')) {
  344. e.preventDefault();
  345. e.stopImmediatePropagation();
  346. $currentTrigger = $this;
  347. $this.trigger($.Event('contextmenu', {data: e.data, pageX: e.pageX, pageY: e.pageY}));
  348. }
  349. $this.removeData('contextMenuActive');
  350. },
  351. // contextMenu hover trigger
  352. mouseenter: function (e) {
  353. var $this = $(this),
  354. $related = $(e.relatedTarget),
  355. $document = $(document);
  356. // abort if we're coming from a menu
  357. if ($related.is('.context-menu-list') || $related.closest('.context-menu-list').length) {
  358. return;
  359. }
  360. // abort if a menu is shown
  361. if ($currentTrigger && $currentTrigger.length) {
  362. return;
  363. }
  364. hoveract.pageX = e.pageX;
  365. hoveract.pageY = e.pageY;
  366. hoveract.data = e.data;
  367. $document.on('mousemove.contextMenuShow', handle.mousemove);
  368. hoveract.timer = setTimeout(function () {
  369. hoveract.timer = null;
  370. $document.off('mousemove.contextMenuShow');
  371. $currentTrigger = $this;
  372. $this.trigger($.Event('contextmenu', {
  373. data: hoveract.data,
  374. pageX: hoveract.pageX,
  375. pageY: hoveract.pageY
  376. }));
  377. }, e.data.delay);
  378. },
  379. // contextMenu hover trigger
  380. mousemove: function (e) {
  381. hoveract.pageX = e.pageX;
  382. hoveract.pageY = e.pageY;
  383. },
  384. // contextMenu hover trigger
  385. mouseleave: function (e) {
  386. // abort if we're leaving for a menu
  387. var $related = $(e.relatedTarget);
  388. if ($related.is('.context-menu-list') || $related.closest('.context-menu-list').length) {
  389. return;
  390. }
  391. try {
  392. clearTimeout(hoveract.timer);
  393. } catch (e) {
  394. }
  395. hoveract.timer = null;
  396. },
  397. // click on layer to hide contextMenu
  398. layerClick: function (e) {
  399. var $this = $(this),
  400. root = $this.data('contextMenuRoot'),
  401. button = e.button,
  402. x = e.pageX,
  403. y = e.pageY,
  404. target,
  405. offset;
  406. e.preventDefault();
  407. e.stopImmediatePropagation();
  408. setTimeout(function () {
  409. var $window;
  410. var triggerAction = ((root.trigger === 'left' && button === 0) || (root.trigger === 'right' && button === 2));
  411. // find the element that would've been clicked, wasn't the layer in the way
  412. if (document.elementFromPoint && root.$layer) {
  413. root.$layer.hide();
  414. target = document.elementFromPoint(x - $win.scrollLeft(), y - $win.scrollTop());
  415. // also need to try and focus this element if we're in a contenteditable area,
  416. // as the layer will prevent the browser mouse action we want
  417. if (target.isContentEditable) {
  418. var range = document.createRange(),
  419. sel = window.getSelection();
  420. range.selectNode(target);
  421. range.collapse(true);
  422. sel.removeAllRanges();
  423. sel.addRange(range);
  424. }
  425. root.$layer.show();
  426. }
  427. if (root.reposition && triggerAction) {
  428. if (document.elementFromPoint) {
  429. if (root.$trigger.is(target) || root.$trigger.has(target).length) {
  430. root.position.call(root.$trigger, root, x, y);
  431. return;
  432. }
  433. } else {
  434. offset = root.$trigger.offset();
  435. $window = $(window);
  436. // while this looks kinda awful, it's the best way to avoid
  437. // unnecessarily calculating any positions
  438. offset.top += $window.scrollTop();
  439. if (offset.top <= e.pageY) {
  440. offset.left += $window.scrollLeft();
  441. if (offset.left <= e.pageX) {
  442. offset.bottom = offset.top + root.$trigger.outerHeight();
  443. if (offset.bottom >= e.pageY) {
  444. offset.right = offset.left + root.$trigger.outerWidth();
  445. if (offset.right >= e.pageX) {
  446. // reposition
  447. root.position.call(root.$trigger, root, x, y);
  448. return;
  449. }
  450. }
  451. }
  452. }
  453. }
  454. }
  455. if (target && triggerAction) {
  456. root.$trigger.one('contextmenu:hidden', function () {
  457. $(target).contextMenu({ x: x, y: y, button: button });
  458. });
  459. }
  460. if (root != null && root.$menu != null) {
  461. root.$menu.trigger('contextmenu:hide');
  462. }
  463. }, 50);
  464. },
  465. // key handled :hover
  466. keyStop: function (e, opt) {
  467. if (!opt.isInput) {
  468. e.preventDefault();
  469. }
  470. e.stopPropagation();
  471. },
  472. key: function (e) {
  473. var opt = {};
  474. // Only get the data from $currentTrigger if it exists
  475. if ($currentTrigger) {
  476. opt = $currentTrigger.data('contextMenu') || {};
  477. }
  478. // If the trigger happen on a element that are above the contextmenu do this
  479. if (opt.zIndex === undefined) {
  480. opt.zIndex = 0;
  481. }
  482. var targetZIndex = 0;
  483. var getZIndexOfTriggerTarget = function (target) {
  484. if (target.style.zIndex !== '') {
  485. targetZIndex = target.style.zIndex;
  486. } else {
  487. if (target.offsetParent !== null && target.offsetParent !== undefined) {
  488. getZIndexOfTriggerTarget(target.offsetParent);
  489. }
  490. else if (target.parentElement !== null && target.parentElement !== undefined) {
  491. getZIndexOfTriggerTarget(target.parentElement);
  492. }
  493. }
  494. };
  495. getZIndexOfTriggerTarget(e.target);
  496. // If targetZIndex is heigher then opt.zIndex dont progress any futher.
  497. // This is used to make sure that if you are using a dialog with a input / textarea / contenteditable div
  498. // and its above the contextmenu it wont steal keys events
  499. if (targetZIndex > opt.zIndex) {
  500. return;
  501. }
  502. switch (e.keyCode) {
  503. case 9:
  504. case 38: // up
  505. handle.keyStop(e, opt);
  506. // if keyCode is [38 (up)] or [9 (tab) with shift]
  507. if (opt.isInput) {
  508. if (e.keyCode === 9 && e.shiftKey) {
  509. e.preventDefault();
  510. if(opt.$selected) {
  511. opt.$selected.find('input, textarea, select').blur();
  512. }
  513. if (opt.$menu != null) opt.$menu.trigger('prevcommand');
  514. return;
  515. } else if (e.keyCode === 38 && opt.$selected.find('input, textarea, select').prop('type') === 'checkbox') {
  516. // checkboxes don't capture this key
  517. e.preventDefault();
  518. return;
  519. }
  520. } else if (e.keyCode !== 9 || e.shiftKey) {
  521. if (opt.$menu != null) opt.$menu.trigger('prevcommand');
  522. return;
  523. }
  524. break;
  525. // omitting break;
  526. // case 9: // tab - reached through omitted break;
  527. case 40: // down
  528. handle.keyStop(e, opt);
  529. if (opt.isInput) {
  530. if (e.keyCode === 9) {
  531. e.preventDefault();
  532. if(opt.$selected) {
  533. opt.$selected.find('input, textarea, select').blur();
  534. }
  535. if (opt.$menu != null) opt.$menu.trigger('nextcommand');
  536. return;
  537. } else if (e.keyCode === 40 && opt.$selected.find('input, textarea, select').prop('type') === 'checkbox') {
  538. // checkboxes don't capture this key
  539. e.preventDefault();
  540. return;
  541. }
  542. } else {
  543. if (opt.$menu != null) opt.$menu.trigger('nextcommand');
  544. return;
  545. }
  546. break;
  547. case 37: // left
  548. handle.keyStop(e, opt);
  549. if (opt.isInput || !opt.$selected || !opt.$selected.length) {
  550. break;
  551. }
  552. if (!opt.$selected.parent().hasClass('context-menu-root')) {
  553. var $parent = opt.$selected.parent().parent();
  554. opt.$selected.trigger('contextmenu:blur');
  555. opt.$selected = $parent;
  556. return;
  557. }
  558. break;
  559. case 39: // right
  560. handle.keyStop(e, opt);
  561. if (opt.isInput || !opt.$selected || !opt.$selected.length) {
  562. break;
  563. }
  564. var itemdata = opt.$selected.data('contextMenu') || {};
  565. if (itemdata.$menu && opt.$selected.hasClass('context-menu-submenu')) {
  566. opt.$selected = null;
  567. itemdata.$selected = null;
  568. itemdata.$menu.trigger('nextcommand');
  569. return;
  570. }
  571. break;
  572. case 35: // end
  573. case 36: // home
  574. if (opt.$selected && opt.$selected.find('input, textarea, select').length) {
  575. return;
  576. } else {
  577. (opt.$selected && opt.$selected.parent() || opt.$menu)
  578. .children(':not(.' + opt.classNames.disabled + ', .' + opt.classNames.notSelectable + ')')[e.keyCode === 36 ? 'first' : 'last']()
  579. .trigger('contextmenu:focus');
  580. e.preventDefault();
  581. return;
  582. }
  583. break;
  584. case 13: // enter
  585. handle.keyStop(e, opt);
  586. if (opt.isInput) {
  587. if (opt.$selected && !opt.$selected.is('textarea, select')) {
  588. e.preventDefault();
  589. return;
  590. }
  591. break;
  592. }
  593. if (typeof opt.$selected !== 'undefined' && opt.$selected !== null) {
  594. opt.$selected.trigger('mouseup');
  595. }
  596. return;
  597. case 32: // space
  598. case 33: // page up
  599. case 34: // page down
  600. // prevent browser from scrolling down while menu is visible
  601. handle.keyStop(e, opt);
  602. return;
  603. case 27: // esc
  604. handle.keyStop(e, opt);
  605. if (opt.$menu != null) opt.$menu.trigger('contextmenu:hide');
  606. return;
  607. default: // 0-9, a-z
  608. var k = (String.fromCharCode(e.keyCode)).toUpperCase();
  609. if (opt.accesskeys && opt.accesskeys[k]) {
  610. // according to the specs accesskeys must be invoked immediately
  611. opt.accesskeys[k].$node.trigger(opt.accesskeys[k].$menu ? 'contextmenu:focus' : 'mouseup');
  612. return;
  613. }
  614. break;
  615. }
  616. // pass event to selected item,
  617. // stop propagation to avoid endless recursion
  618. e.stopPropagation();
  619. if (typeof opt.$selected !== 'undefined' && opt.$selected !== null) {
  620. opt.$selected.trigger(e);
  621. }
  622. },
  623. // select previous possible command in menu
  624. prevItem: function (e) {
  625. e.stopPropagation();
  626. var opt = $(this).data('contextMenu') || {};
  627. var root = $(this).data('contextMenuRoot') || {};
  628. // obtain currently selected menu
  629. if (opt.$selected) {
  630. var $s = opt.$selected;
  631. opt = opt.$selected.parent().data('contextMenu') || {};
  632. opt.$selected = $s;
  633. }
  634. var $children = opt.$menu.children(),
  635. $prev = !opt.$selected || !opt.$selected.prev().length ? $children.last() : opt.$selected.prev(),
  636. $round = $prev;
  637. // skip disabled or hidden elements
  638. while ($prev.hasClass(root.classNames.disabled) || $prev.hasClass(root.classNames.notSelectable) || $prev.is(':hidden')) {
  639. if ($prev.prev().length) {
  640. $prev = $prev.prev();
  641. } else {
  642. $prev = $children.last();
  643. }
  644. if ($prev.is($round)) {
  645. // break endless loop
  646. return;
  647. }
  648. }
  649. // leave current
  650. if (opt.$selected) {
  651. handle.itemMouseleave.call(opt.$selected.get(0), e);
  652. }
  653. // activate next
  654. handle.itemMouseenter.call($prev.get(0), e);
  655. // focus input
  656. var $input = $prev.find('input, textarea, select');
  657. if ($input.length) {
  658. $input.focus();
  659. }
  660. },
  661. // select next possible command in menu
  662. nextItem: function (e) {
  663. e.stopPropagation();
  664. var opt = $(this).data('contextMenu') || {};
  665. var root = $(this).data('contextMenuRoot') || {};
  666. // obtain currently selected menu
  667. if (opt.$selected) {
  668. var $s = opt.$selected;
  669. opt = opt.$selected.parent().data('contextMenu') || {};
  670. opt.$selected = $s;
  671. }
  672. var $children = opt.$menu.children(),
  673. $next = !opt.$selected || !opt.$selected.next().length ? $children.first() : opt.$selected.next(),
  674. $round = $next;
  675. // skip disabled
  676. while ($next.hasClass(root.classNames.disabled) || $next.hasClass(root.classNames.notSelectable) || $next.is(':hidden')) {
  677. if ($next.next().length) {
  678. $next = $next.next();
  679. } else {
  680. $next = $children.first();
  681. }
  682. if ($next.is($round)) {
  683. // break endless loop
  684. return;
  685. }
  686. }
  687. // leave current
  688. if (opt.$selected) {
  689. handle.itemMouseleave.call(opt.$selected.get(0), e);
  690. }
  691. // activate next
  692. handle.itemMouseenter.call($next.get(0), e);
  693. // focus input
  694. var $input = $next.find('input, textarea, select');
  695. if ($input.length) {
  696. $input.focus();
  697. }
  698. },
  699. // flag that we're inside an input so the key handler can act accordingly
  700. focusInput: function () {
  701. var $this = $(this).closest('.context-menu-item'),
  702. data = $this.data(),
  703. opt = data.contextMenu,
  704. root = data.contextMenuRoot;
  705. root.$selected = opt.$selected = $this;
  706. root.isInput = opt.isInput = true;
  707. },
  708. // flag that we're inside an input so the key handler can act accordingly
  709. blurInput: function () {
  710. var $this = $(this).closest('.context-menu-item'),
  711. data = $this.data(),
  712. opt = data.contextMenu,
  713. root = data.contextMenuRoot;
  714. root.isInput = opt.isInput = false;
  715. },
  716. // :hover on menu
  717. menuMouseenter: function () {
  718. var root = $(this).data().contextMenuRoot;
  719. root.hovering = true;
  720. },
  721. // :hover on menu
  722. menuMouseleave: function (e) {
  723. var root = $(this).data().contextMenuRoot;
  724. if (root.$layer && root.$layer.is(e.relatedTarget)) {
  725. root.hovering = false;
  726. }
  727. },
  728. // :hover done manually so key handling is possible
  729. itemMouseenter: function (e) {
  730. var $this = $(this),
  731. data = $this.data(),
  732. opt = data.contextMenu,
  733. root = data.contextMenuRoot;
  734. root.hovering = true;
  735. // abort if we're re-entering
  736. if (e && root.$layer && root.$layer.is(e.relatedTarget)) {
  737. e.preventDefault();
  738. e.stopImmediatePropagation();
  739. }
  740. // make sure only one item is selected
  741. (opt.$menu ? opt : root).$menu
  742. .children('.' + root.classNames.hover).trigger('contextmenu:blur')
  743. .children('.hover').trigger('contextmenu:blur');
  744. if ($this.hasClass(root.classNames.disabled) || $this.hasClass(root.classNames.notSelectable)) {
  745. opt.$selected = null;
  746. return;
  747. }
  748. $this.trigger('contextmenu:focus');
  749. },
  750. // :hover done manually so key handling is possible
  751. itemMouseleave: function (e) {
  752. var $this = $(this),
  753. data = $this.data(),
  754. opt = data.contextMenu,
  755. root = data.contextMenuRoot;
  756. if (root !== opt && root.$layer && root.$layer.is(e.relatedTarget)) {
  757. if (typeof root.$selected !== 'undefined' && root.$selected !== null) {
  758. root.$selected.trigger('contextmenu:blur');
  759. }
  760. e.preventDefault();
  761. e.stopImmediatePropagation();
  762. root.$selected = opt.$selected = opt.$node;
  763. return;
  764. }
  765. $this.trigger('contextmenu:blur');
  766. },
  767. // contextMenu item click
  768. itemClick: function (e) {
  769. var $this = $(this),
  770. data = $this.data(),
  771. opt = data.contextMenu,
  772. root = data.contextMenuRoot,
  773. key = data.contextMenuKey,
  774. callback;
  775. // abort if the key is unknown or disabled or is a menu
  776. if (!opt.items[key] || $this.is('.' + root.classNames.disabled + ', .context-menu-separator, .' + root.classNames.notSelectable) || ($this.is('.context-menu-submenu') && root.selectableSubMenu === false )) {
  777. return;
  778. }
  779. e.preventDefault();
  780. e.stopImmediatePropagation();
  781. if ($.isFunction(opt.callbacks[key]) && Object.prototype.hasOwnProperty.call(opt.callbacks, key)) {
  782. // item-specific callback
  783. callback = opt.callbacks[key];
  784. } else if ($.isFunction(root.callback)) {
  785. // default callback
  786. callback = root.callback;
  787. } else {
  788. // no callback, no action
  789. return;
  790. }
  791. // hide menu if callback doesn't stop that
  792. if (callback.call(root.$trigger, key, root) !== false) {
  793. root.$menu.trigger('contextmenu:hide');
  794. } else if (root.$menu.parent().length) {
  795. op.update.call(root.$trigger, root);
  796. }
  797. },
  798. // ignore click events on input elements
  799. inputClick: function (e) {
  800. e.stopImmediatePropagation();
  801. },
  802. // hide <menu>
  803. hideMenu: function (e, data) {
  804. var root = $(this).data('contextMenuRoot');
  805. op.hide.call(root.$trigger, root, data && data.force);
  806. },
  807. // focus <command>
  808. focusItem: function (e) {
  809. e.stopPropagation();
  810. var $this = $(this),
  811. data = $this.data(),
  812. opt = data.contextMenu,
  813. root = data.contextMenuRoot;
  814. if ($this.hasClass(root.classNames.disabled) || $this.hasClass(root.classNames.notSelectable)) {
  815. return;
  816. }
  817. $this
  818. .addClass([root.classNames.hover, root.classNames.visible].join(' '))
  819. // select other items and included items
  820. .parent().find('.context-menu-item').not($this)
  821. .removeClass(root.classNames.visible)
  822. .filter('.' + root.classNames.hover)
  823. .trigger('contextmenu:blur');
  824. // remember selected
  825. opt.$selected = root.$selected = $this;
  826. // position sub-menu - do after show so dumb $.ui.position can keep up
  827. if (opt.$node) {
  828. root.positionSubmenu.call(opt.$node, opt.$menu);
  829. }
  830. },
  831. // blur <command>
  832. blurItem: function (e) {
  833. e.stopPropagation();
  834. var $this = $(this),
  835. data = $this.data(),
  836. opt = data.contextMenu,
  837. root = data.contextMenuRoot;
  838. if (opt.autoHide) { // for tablets and touch screens this needs to remain
  839. $this.removeClass(root.classNames.visible);
  840. }
  841. $this.removeClass(root.classNames.hover);
  842. opt.$selected = null;
  843. }
  844. },
  845. // operations
  846. op = {
  847. show: function (opt, x, y) {
  848. var $trigger = $(this),
  849. css = {};
  850. // hide any open menus
  851. $('#context-menu-layer').trigger('mousedown');
  852. // backreference for callbacks
  853. opt.$trigger = $trigger;
  854. // show event
  855. if (opt.events.show.call($trigger, opt) === false) {
  856. $currentTrigger = null;
  857. return;
  858. }
  859. // create or update context menu
  860. op.update.call($trigger, opt);
  861. // position menu
  862. opt.position.call($trigger, opt, x, y);
  863. // make sure we're in front
  864. if (opt.zIndex) {
  865. var additionalZValue = opt.zIndex;
  866. // If opt.zIndex is a function, call the function to get the right zIndex.
  867. if (typeof opt.zIndex === 'function') {
  868. additionalZValue = opt.zIndex.call($trigger, opt);
  869. }
  870. css.zIndex = zindex($trigger) + additionalZValue;
  871. }
  872. // add layer
  873. op.layer.call(opt.$menu, opt, css.zIndex);
  874. // adjust sub-menu zIndexes
  875. opt.$menu.find('ul').css('zIndex', css.zIndex + 1);
  876. // position and show context menu
  877. opt.$menu.css(css)[opt.animation.show](opt.animation.duration, function () {
  878. $trigger.trigger('contextmenu:visible');
  879. });
  880. // make options available and set state
  881. $trigger
  882. .data('contextMenu', opt)
  883. .addClass('context-menu-active');
  884. // register key handler
  885. $(document).off('keydown.contextMenu').on('keydown.contextMenu', handle.key);
  886. // register autoHide handler
  887. if (opt.autoHide) {
  888. // mouse position handler
  889. $(document).on('mousemove.contextMenuAutoHide', function (e) {
  890. // need to capture the offset on mousemove,
  891. // since the page might've been scrolled since activation
  892. var pos = $trigger.offset();
  893. pos.right = pos.left + $trigger.outerWidth();
  894. pos.bottom = pos.top + $trigger.outerHeight();
  895. if (opt.$layer && !opt.hovering && (!(e.pageX >= pos.left && e.pageX <= pos.right) || !(e.pageY >= pos.top && e.pageY <= pos.bottom))) {
  896. /* Additional hover check after short time, you might just miss the edge of the menu */
  897. setTimeout(function () {
  898. if (!opt.hovering && opt.$menu != null) { opt.$menu.trigger('contextmenu:hide'); }
  899. }, 50);
  900. }
  901. });
  902. }
  903. },
  904. hide: function (opt, force) {
  905. var $trigger = $(this);
  906. if (!opt) {
  907. opt = $trigger.data('contextMenu') || {};
  908. }
  909. // hide event
  910. if (!force && opt.events && opt.events.hide.call($trigger, opt) === false) {
  911. return;
  912. }
  913. // remove options and revert state
  914. $trigger
  915. .removeData('contextMenu')
  916. .removeClass('context-menu-active');
  917. if (opt.$layer) {
  918. // keep layer for a bit so the contextmenu event can be aborted properly by opera
  919. setTimeout((function ($layer) {
  920. return function () {
  921. $layer.remove();
  922. };
  923. })(opt.$layer), 10);
  924. try {
  925. delete opt.$layer;
  926. } catch (e) {
  927. opt.$layer = null;
  928. }
  929. }
  930. // remove handle
  931. $currentTrigger = null;
  932. // remove selected
  933. opt.$menu.find('.' + opt.classNames.hover).trigger('contextmenu:blur');
  934. opt.$selected = null;
  935. // collapse all submenus
  936. opt.$menu.find('.' + opt.classNames.visible).removeClass(opt.classNames.visible);
  937. // unregister key and mouse handlers
  938. // $(document).off('.contextMenuAutoHide keydown.contextMenu'); // http://bugs.jquery.com/ticket/10705
  939. $(document).off('.contextMenuAutoHide').off('keydown.contextMenu');
  940. // hide menu
  941. if(opt.$menu){
  942. opt.$menu[opt.animation.hide](opt.animation.duration, function () {
  943. // tear down dynamically built menu after animation is completed.
  944. if (opt.build) {
  945. opt.$menu.remove();
  946. $.each(opt, function (key) {
  947. switch (key) {
  948. case 'ns':
  949. case 'selector':
  950. case 'build':
  951. case 'trigger':
  952. return true;
  953. default:
  954. opt[key] = undefined;
  955. try {
  956. delete opt[key];
  957. } catch (e) {
  958. }
  959. return true;
  960. }
  961. });
  962. }
  963. setTimeout(function () {
  964. $trigger.trigger('contextmenu:hidden');
  965. }, 10);
  966. });
  967. }
  968. },
  969. create: function (opt, root) {
  970. if (root === undefined) {
  971. root = opt;
  972. }
  973. // create contextMenu
  974. opt.$menu = $('<ul class="context-menu-list"></ul>').addClass(opt.className || '').data({
  975. 'contextMenu': opt,
  976. 'contextMenuRoot': root
  977. });
  978. $.each(['callbacks', 'commands', 'inputs'], function (i, k) {
  979. opt[k] = {};
  980. if (!root[k]) {
  981. root[k] = {};
  982. }
  983. });
  984. if(!root.accesskeys){
  985. root.accesskeys = {};
  986. }
  987. function createNameNode(item) {
  988. var $name = $('<span></span>');
  989. if (item._accesskey) {
  990. if (item._beforeAccesskey) {
  991. $name.append(document.createTextNode(item._beforeAccesskey));
  992. }
  993. $('<span></span>')
  994. .addClass('context-menu-accesskey')
  995. .text(item._accesskey)
  996. .appendTo($name);
  997. if (item._afterAccesskey) {
  998. $name.append(document.createTextNode(item._afterAccesskey));
  999. }
  1000. } else {
  1001. if (item.isHtmlName) {
  1002. // restrict use with access keys
  1003. if (typeof item.accesskey !== 'undefined') {
  1004. throw new Error('accesskeys are not compatible with HTML names and cannot be used together in the same item');
  1005. }
  1006. $name.html(item.name);
  1007. } else {
  1008. $name.text(item.name);
  1009. }
  1010. }
  1011. return $name;
  1012. }
  1013. // create contextMenu items
  1014. $.each(opt.items, function (key, item) {
  1015. var $t = $('<li class="context-menu-item"></li>').addClass(item.className || ''),
  1016. $label = null,
  1017. $input = null;
  1018. // iOS needs to see a click-event bound to an element to actually
  1019. // have the TouchEvents infrastructure trigger the click event
  1020. $t.on('click', $.noop);
  1021. // Make old school string seperator a real item so checks wont be
  1022. // akward later.
  1023. // And normalize 'cm_separator' into 'cm_seperator'.
  1024. if (typeof item === 'string' || item.type === 'cm_separator') {
  1025. item = { type : 'cm_seperator' };
  1026. }
  1027. item.$node = $t.data({
  1028. 'contextMenu': opt,
  1029. 'contextMenuRoot': root,
  1030. 'contextMenuKey': key
  1031. });
  1032. // register accesskey
  1033. // NOTE: the accesskey attribute should be applicable to any element, but Safari5 and Chrome13 still can't do that
  1034. if (typeof item.accesskey !== 'undefined') {
  1035. var aks = splitAccesskey(item.accesskey);
  1036. for (var i = 0, ak; ak = aks[i]; i++) {
  1037. if (!root.accesskeys[ak]) {
  1038. root.accesskeys[ak] = item;
  1039. var matched = item.name.match(new RegExp('^(.*?)(' + ak + ')(.*)$', 'i'));
  1040. if (matched) {
  1041. item._beforeAccesskey = matched[1];
  1042. item._accesskey = matched[2];
  1043. item._afterAccesskey = matched[3];
  1044. }
  1045. break;
  1046. }
  1047. }
  1048. }
  1049. if (item.type && types[item.type]) {
  1050. // run custom type handler
  1051. types[item.type].call($t, item, opt, root);
  1052. // register commands
  1053. $.each([opt, root], function (i, k) {
  1054. k.commands[key] = item;
  1055. // Overwrite only if undefined or the item is appended to the root. This so it
  1056. // doesn't overwrite callbacks of root elements if the name is the same.
  1057. if ($.isFunction(item.callback) && (k.callbacks[key] === undefined || opt.type === undefined)) {
  1058. k.callbacks[key] = item.callback;
  1059. }
  1060. });
  1061. } else {
  1062. // add label for input
  1063. if (item.type === 'cm_seperator') {
  1064. $t.addClass('context-menu-separator ' + root.classNames.notSelectable);
  1065. } else if (item.type === 'html') {
  1066. $t.addClass('context-menu-html ' + root.classNames.notSelectable);
  1067. } else if (item.type === 'sub') {
  1068. // We don't want to execute the next else-if if it is a sub.
  1069. } else if (item.type) {
  1070. $label = $('<label></label>').appendTo($t);
  1071. createNameNode(item).appendTo($label);
  1072. $t.addClass('context-menu-input');
  1073. opt.hasTypes = true;
  1074. $.each([opt, root], function (i, k) {
  1075. k.commands[key] = item;
  1076. k.inputs[key] = item;
  1077. });
  1078. } else if (item.items) {
  1079. item.type = 'sub';
  1080. }
  1081. switch (item.type) {
  1082. case 'cm_seperator':
  1083. break;
  1084. case 'text':
  1085. $input = $('<input type="text" value="1" name="" />')
  1086. .attr('name', 'context-menu-input-' + key)
  1087. .val(item.value || '')
  1088. .appendTo($label);
  1089. break;
  1090. case 'textarea':
  1091. $input = $('<textarea name=""></textarea>')
  1092. .attr('name', 'context-menu-input-' + key)
  1093. .val(item.value || '')
  1094. .appendTo($label);
  1095. if (item.height) {
  1096. $input.height(item.height);
  1097. }
  1098. break;
  1099. case 'checkbox':
  1100. $input = $('<input type="checkbox" value="1" name="" />')
  1101. .attr('name', 'context-menu-input-' + key)
  1102. .val(item.value || '')
  1103. .prop('checked', !!item.selected)
  1104. .prependTo($label);
  1105. break;
  1106. case 'radio':
  1107. $input = $('<input type="radio" value="1" name="" />')
  1108. .attr('name', 'context-menu-input-' + item.radio)
  1109. .val(item.value || '')
  1110. .prop('checked', !!item.selected)
  1111. .prependTo($label);
  1112. break;
  1113. case 'select':
  1114. $input = $('<select name=""></select>')
  1115. .attr('name', 'context-menu-input-' + key)
  1116. .appendTo($label);
  1117. if (item.options) {
  1118. $.each(item.options, function (value, text) {
  1119. $('<option></option>').val(value).text(text).appendTo($input);
  1120. });
  1121. $input.val(item.selected);
  1122. }
  1123. break;
  1124. case 'sub':
  1125. createNameNode(item).appendTo($t);
  1126. item.appendTo = item.$node;
  1127. $t.data('contextMenu', item).addClass('context-menu-submenu');
  1128. item.callback = null;
  1129. // If item contains items, and this is a promise, we should create it later
  1130. // check if subitems is of type promise. If it is a promise we need to create
  1131. // it later, after promise has been resolved.
  1132. if ('function' === typeof item.items.then) {
  1133. // probably a promise, process it, when completed it will create the sub menu's.
  1134. op.processPromises(item, root, item.items);
  1135. } else {
  1136. // normal submenu.
  1137. op.create(item, root);
  1138. }
  1139. break;
  1140. case 'html':
  1141. $(item.html).appendTo($t);
  1142. break;
  1143. default:
  1144. $.each([opt, root], function (i, k) {
  1145. k.commands[key] = item;
  1146. // Overwrite only if undefined or the item is appended to the root. This so it
  1147. // doesn't overwrite callbacks of root elements if the name is the same.
  1148. if ($.isFunction(item.callback) && (k.callbacks[key] === undefined || opt.type === undefined)) {
  1149. k.callbacks[key] = item.callback;
  1150. }
  1151. });
  1152. createNameNode(item).appendTo($t);
  1153. break;
  1154. }
  1155. // disable key listener in <input>
  1156. if (item.type && item.type !== 'sub' && item.type !== 'html' && item.type !== 'cm_seperator') {
  1157. $input
  1158. .on('focus', handle.focusInput)
  1159. .on('blur', handle.blurInput);
  1160. if (item.events) {
  1161. $input.on(item.events, opt);
  1162. }
  1163. }
  1164. // add icons
  1165. if (item.icon) {
  1166. if ($.isFunction(item.icon)) {
  1167. item._icon = item.icon.call(this, this, $t, key, item);
  1168. } else {
  1169. if ( typeof(item.icon) === 'string' && item.icon.substring(0,3) === 'fa-' ) {
  1170. // to enable font awesome
  1171. item._icon = root.classNames.icon + ' ' + root.classNames.icon + '--fa fa ' + item.icon;
  1172. } else {
  1173. item._icon = root.classNames.icon + ' ' + root.classNames.icon + '-' + item.icon;
  1174. }
  1175. }
  1176. $t.addClass(item._icon);
  1177. }
  1178. }
  1179. // cache contained elements
  1180. item.$input = $input;
  1181. item.$label = $label;
  1182. // attach item to menu
  1183. $t.appendTo(opt.$menu);
  1184. // Disable text selection
  1185. if (!opt.hasTypes && $.support.eventSelectstart) {
  1186. // browsers support user-select: none,
  1187. // IE has a special event for text-selection
  1188. // browsers supporting neither will not be preventing text-selection
  1189. $t.on('selectstart.disableTextSelect', handle.abortevent);
  1190. }
  1191. });
  1192. // attach contextMenu to <body> (to bypass any possible overflow:hidden issues on parents of the trigger element)
  1193. if (!opt.$node) {
  1194. opt.$menu.css('display', 'none').addClass('context-menu-root');
  1195. }
  1196. opt.$menu.appendTo(opt.appendTo || document.body);
  1197. },
  1198. resize: function ($menu, nested) {
  1199. var domMenu;
  1200. // determine widths of submenus, as CSS won't grow them automatically
  1201. // position:absolute within position:absolute; min-width:100; max-width:200; results in width: 100;
  1202. // kinda sucks hard...
  1203. // determine width of absolutely positioned element
  1204. $menu.css({position: 'absolute', display: 'block'});
  1205. // don't apply yet, because that would break nested elements' widths
  1206. $menu.data('width',
  1207. (domMenu = $menu.get(0)).getBoundingClientRect ?
  1208. Math.ceil(domMenu.getBoundingClientRect().width) :
  1209. $menu.outerWidth() + 1); // outerWidth() returns rounded pixels
  1210. // reset styles so they allow nested elements to grow/shrink naturally
  1211. $menu.css({
  1212. position: 'static',
  1213. minWidth: '0px',
  1214. maxWidth: '100000px'
  1215. });
  1216. // identify width of nested menus
  1217. $menu.find('> li > ul').each(function () {
  1218. op.resize($(this), true);
  1219. });
  1220. // reset and apply changes in the end because nested
  1221. // elements' widths wouldn't be calculatable otherwise
  1222. if (!nested) {
  1223. $menu.find('ul').addBack().css({
  1224. position: '',
  1225. display: '',
  1226. minWidth: '',
  1227. maxWidth: ''
  1228. }).outerWidth(function () {
  1229. return $(this).data('width');
  1230. });
  1231. }
  1232. },
  1233. update: function (opt, root) {
  1234. var $trigger = this;
  1235. if (root === undefined) {
  1236. root = opt;
  1237. op.resize(opt.$menu);
  1238. }
  1239. // re-check disabled for each item
  1240. opt.$menu.children().each(function () {
  1241. var $item = $(this),
  1242. key = $item.data('contextMenuKey'),
  1243. item = opt.items[key],
  1244. disabled = ($.isFunction(item.disabled) && item.disabled.call($trigger, key, root)) || item.disabled === true,
  1245. visible;
  1246. if ($.isFunction(item.visible)) {
  1247. visible = item.visible.call($trigger, key, root);
  1248. } else if (typeof item.visible !== 'undefined') {
  1249. visible = item.visible === true;
  1250. } else {
  1251. visible = true;
  1252. }
  1253. $item[visible ? 'show' : 'hide']();
  1254. // dis- / enable item
  1255. $item[disabled ? 'addClass' : 'removeClass'](root.classNames.disabled);
  1256. if ($.isFunction(item.icon)) {
  1257. $item.removeClass(item._icon);
  1258. item._icon = item.icon.call(this, $trigger, $item, key, item);
  1259. $item.addClass(item._icon);
  1260. }
  1261. if (item.type) {
  1262. // dis- / enable input elements
  1263. $item.find('input, select, textarea').prop('disabled', disabled);
  1264. // update input states
  1265. switch (item.type) {
  1266. case 'text':
  1267. case 'textarea':
  1268. item.$input.val(item.value || '');
  1269. break;
  1270. case 'checkbox':
  1271. case 'radio':
  1272. item.$input.val(item.value || '').prop('checked', !!item.selected);
  1273. break;
  1274. case 'select':
  1275. item.$input.val(item.selected || '');
  1276. break;
  1277. }
  1278. }
  1279. if (item.$menu) {
  1280. // update sub-menu
  1281. op.update.call($trigger, item, root);
  1282. }
  1283. });
  1284. },
  1285. layer: function (opt, zIndex) {
  1286. // add transparent layer for click area
  1287. // filter and background for Internet Explorer, Issue #23
  1288. var $layer = opt.$layer = $('<div id="context-menu-layer" style="position:fixed; z-index:' + zIndex + '; top:0; left:0; opacity: 0; filter: alpha(opacity=0); background-color: #000;"></div>')
  1289. .css({height: $win.height(), width: $win.width(), display: 'block'})
  1290. .data('contextMenuRoot', opt)
  1291. .insertBefore(this)
  1292. .on('contextmenu', handle.abortevent)
  1293. .on('mousedown', handle.layerClick);
  1294. // IE6 doesn't know position:fixed;
  1295. if (document.body.style.maxWidth === undefined) { // IE6 doesn't support maxWidth
  1296. $layer.css({
  1297. 'position': 'absolute',
  1298. 'height': $(document).height()
  1299. });
  1300. }
  1301. return $layer;
  1302. },
  1303. processPromises: function (opt, root, promise) {
  1304. // Start
  1305. opt.$node.addClass(root.classNames.iconLoadingClass);
  1306. function completedPromise(opt,root,items) {
  1307. // Completed promise (dev called promise.resolve). We now have a list of items which can
  1308. // be used to create the rest of the context menu.
  1309. if (items === undefined) {
  1310. // Null result, dev should have checked
  1311. errorPromise(undefined);//own error object
  1312. }
  1313. finishPromiseProcess(opt,root, items);
  1314. }
  1315. function errorPromise(opt,root,errorItem) {
  1316. // User called promise.reject() with an error item, if not, provide own error item.
  1317. if (errorItem === undefined) {
  1318. errorItem = { "error": { name: "No items and no error item", icon: "context-menu-icon context-menu-icon-quit" } };
  1319. if (window.console) {
  1320. (console.error || console.log).call(console, 'When you reject a promise, provide an "items" object, equal to normal sub-menu items');
  1321. }
  1322. } else if(typeof errorItem === 'string'){
  1323. errorItem = { "error": { name: errorItem } };
  1324. }
  1325. finishPromiseProcess(opt,root,errorItem);
  1326. }
  1327. function finishPromiseProcess(opt,root,items) {
  1328. if(root.$menu === undefined || !root.$menu.is(':visible')){
  1329. return;
  1330. }
  1331. opt.$node.removeClass(root.classNames.iconLoadingClass);
  1332. opt.items = items;
  1333. op.create(opt, root, true); // Create submenu
  1334. op.update(opt, root); // Correctly update position if user is already hovered over menu item
  1335. root.positionSubmenu.call(opt.$node, opt.$menu); // positionSubmenu, will only do anything if user already hovered over menu item that just got new subitems.
  1336. }
  1337. // Wait for promise completion. .then(success, error, notify) (we don't track notify). Bind the opt
  1338. // and root to avoid scope problems
  1339. promise.then(completedPromise.bind(this, opt, root), errorPromise.bind(this, opt, root));
  1340. }
  1341. };
  1342. // split accesskey according to http://www.whatwg.org/specs/web-apps/current-work/multipage/editing.html#assigned-access-key
  1343. function splitAccesskey(val) {
  1344. var t = val.split(/\s+/),
  1345. keys = [];
  1346. for (var i = 0, k; k = t[i]; i++) {
  1347. k = k.charAt(0).toUpperCase(); // first character only
  1348. // theoretically non-accessible characters should be ignored, but different systems, different keyboard layouts, ... screw it.
  1349. // a map to look up already used access keys would be nice
  1350. keys.push(k);
  1351. }
  1352. return keys;
  1353. }
  1354. // handle contextMenu triggers
  1355. $.fn.contextMenu = function (operation) {
  1356. var $t = this, $o = operation;
  1357. if (this.length > 0) { // this is not a build on demand menu
  1358. if (operation === undefined) {
  1359. this.first().trigger('contextmenu');
  1360. } else if (operation.x !== undefined && operation.y !== undefined) {
  1361. this.first().trigger($.Event('contextmenu', { pageX: operation.x, pageY: operation.y, mouseButton: operation.button }));
  1362. } else if (operation === 'hide') {
  1363. var $menu = this.first().data('contextMenu') ? this.first().data('contextMenu').$menu : null;
  1364. if($menu){
  1365. $menu.trigger('contextmenu:hide');
  1366. }
  1367. } else if (operation === 'destroy') {
  1368. $.contextMenu('destroy', {context: this});
  1369. } else if ($.isPlainObject(operation)) {
  1370. operation.context = this;
  1371. $.contextMenu('create', operation);
  1372. } else if (operation) {
  1373. this.removeClass('context-menu-disabled');
  1374. } else if (!operation) {
  1375. this.addClass('context-menu-disabled');
  1376. }
  1377. } else {
  1378. $.each(menus, function () {
  1379. if (this.selector === $t.selector) {
  1380. $o.data = this;
  1381. $.extend($o.data, {trigger: 'demand'});
  1382. }
  1383. });
  1384. handle.contextmenu.call($o.target, $o);
  1385. }
  1386. return this;
  1387. };
  1388. // manage contextMenu instances
  1389. $.contextMenu = function (operation, options) {
  1390. if (typeof operation !== 'string') {
  1391. options = operation;
  1392. operation = 'create';
  1393. }
  1394. if (typeof options === 'string') {
  1395. options = {selector: options};
  1396. } else if (options === undefined) {
  1397. options = {};
  1398. }
  1399. // merge with default options
  1400. var o = $.extend(true, {}, defaults, options || {});
  1401. var $document = $(document);
  1402. var $context = $document;
  1403. var _hasContext = false;
  1404. if (!o.context || !o.context.length) {
  1405. o.context = document;
  1406. } else {
  1407. // you never know what they throw at you...
  1408. $context = $(o.context).first();
  1409. o.context = $context.get(0);
  1410. _hasContext = !$(o.context).is(document);
  1411. }
  1412. switch (operation) {
  1413. case 'create':
  1414. // no selector no joy
  1415. if (!o.selector) {
  1416. throw new Error('No selector specified');
  1417. }
  1418. // make sure internal classes are not bound to
  1419. if (o.selector.match(/.context-menu-(list|item|input)($|\s)/)) {
  1420. throw new Error('Cannot bind to selector "' + o.selector + '" as it contains a reserved className');
  1421. }
  1422. if (!o.build && (!o.items || $.isEmptyObject(o.items))) {
  1423. throw new Error('No Items specified');
  1424. }
  1425. counter++;
  1426. o.ns = '.contextMenu' + counter;
  1427. if (!_hasContext) {
  1428. namespaces[o.selector] = o.ns;
  1429. }
  1430. menus[o.ns] = o;
  1431. // default to right click
  1432. if (!o.trigger) {
  1433. o.trigger = 'right';
  1434. }
  1435. if (!initialized) {
  1436. var itemClick = o.itemClickEvent === 'click' ? 'click.contextMenu' : 'mouseup.contextMenu';
  1437. var contextMenuItemObj = {
  1438. // 'mouseup.contextMenu': handle.itemClick,
  1439. // 'click.contextMenu': handle.itemClick,
  1440. 'contextmenu:focus.contextMenu': handle.focusItem,
  1441. 'contextmenu:blur.contextMenu': handle.blurItem,
  1442. 'contextmenu.contextMenu': handle.abortevent,
  1443. 'mouseenter.contextMenu': handle.itemMouseenter,
  1444. 'mouseleave.contextMenu': handle.itemMouseleave
  1445. };
  1446. contextMenuItemObj[itemClick] = handle.itemClick;
  1447. // make sure item click is registered first
  1448. $document
  1449. .on({
  1450. 'contextmenu:hide.contextMenu': handle.hideMenu,
  1451. 'prevcommand.contextMenu': handle.prevItem,
  1452. 'nextcommand.contextMenu': handle.nextItem,
  1453. 'contextmenu.contextMenu': handle.abortevent,
  1454. 'mouseenter.contextMenu': handle.menuMouseenter,
  1455. 'mouseleave.contextMenu': handle.menuMouseleave
  1456. }, '.context-menu-list')
  1457. .on('mouseup.contextMenu', '.context-menu-input', handle.inputClick)
  1458. .on(contextMenuItemObj, '.context-menu-item');
  1459. initialized = true;
  1460. }
  1461. // engage native contextmenu event
  1462. $context
  1463. .on('contextmenu' + o.ns, o.selector, o, handle.contextmenu);
  1464. if (_hasContext) {
  1465. // add remove hook, just in case
  1466. $context.on('remove' + o.ns, function () {
  1467. $(this).contextMenu('destroy');
  1468. });
  1469. }
  1470. switch (o.trigger) {
  1471. case 'hover':
  1472. $context
  1473. .on('mouseenter' + o.ns, o.selector, o, handle.mouseenter)
  1474. .on('mouseleave' + o.ns, o.selector, o, handle.mouseleave);
  1475. break;
  1476. case 'left':
  1477. $context.on('click' + o.ns, o.selector, o, handle.click);
  1478. break;
  1479. /*
  1480. default:
  1481. // http://www.quirksmode.org/dom/events/contextmenu.html
  1482. $document
  1483. .on('mousedown' + o.ns, o.selector, o, handle.mousedown)
  1484. .on('mouseup' + o.ns, o.selector, o, handle.mouseup);
  1485. break;
  1486. */
  1487. }
  1488. // create menu
  1489. if (!o.build) {
  1490. op.create(o);
  1491. }
  1492. break;
  1493. case 'destroy':
  1494. var $visibleMenu;
  1495. if (_hasContext) {
  1496. // get proper options
  1497. var context = o.context;
  1498. $.each(menus, function (ns, o) {
  1499. if (!o) {
  1500. return true;
  1501. }
  1502. // Is this menu equest to the context called from
  1503. if (!$(context).is(o.selector)) {
  1504. return true;
  1505. }
  1506. $visibleMenu = $('.context-menu-list').filter(':visible');
  1507. if ($visibleMenu.length && $visibleMenu.data().contextMenuRoot.$trigger.is($(o.context).find(o.selector))) {
  1508. $visibleMenu.trigger('contextmenu:hide', {force: true});
  1509. }
  1510. try {
  1511. if (menus[o.ns].$menu) {
  1512. menus[o.ns].$menu.remove();
  1513. }
  1514. delete menus[o.ns];
  1515. } catch (e) {
  1516. menus[o.ns] = null;
  1517. }
  1518. $(o.context).off(o.ns);
  1519. return true;
  1520. });
  1521. } else if (!o.selector) {
  1522. $document.off('.contextMenu .contextMenuAutoHide');
  1523. $.each(menus, function (ns, o) {
  1524. $(o.context).off(o.ns);
  1525. });
  1526. namespaces = {};
  1527. menus = {};
  1528. counter = 0;
  1529. initialized = false;
  1530. $('#context-menu-layer, .context-menu-list').remove();
  1531. } else if (namespaces[o.selector]) {
  1532. $visibleMenu = $('.context-menu-list').filter(':visible');
  1533. if ($visibleMenu.length && $visibleMenu.data().contextMenuRoot.$trigger.is(o.selector)) {
  1534. $visibleMenu.trigger('contextmenu:hide', {force: true});
  1535. }
  1536. try {
  1537. if (menus[namespaces[o.selector]].$menu) {
  1538. menus[namespaces[o.selector]].$menu.remove();
  1539. }
  1540. delete menus[namespaces[o.selector]];
  1541. } catch (e) {
  1542. menus[namespaces[o.selector]] = null;
  1543. }
  1544. $document.off(namespaces[o.selector]);
  1545. }
  1546. break;
  1547. case 'html5':
  1548. // if <command> or <menuitem> are not handled by the browser,
  1549. // or options was a bool true,
  1550. // initialize $.contextMenu for them
  1551. if ((!$.support.htmlCommand && !$.support.htmlMenuitem) || (typeof options === 'boolean' && options)) {
  1552. $('menu[type="context"]').each(function () {
  1553. if (this.id) {
  1554. $.contextMenu({
  1555. selector: '[contextmenu=' + this.id + ']',
  1556. items: $.contextMenu.fromMenu(this)
  1557. });
  1558. }
  1559. }).css('display', 'none');
  1560. }
  1561. break;
  1562. default:
  1563. throw new Error('Unknown operation "' + operation + '"');
  1564. }
  1565. return this;
  1566. };
  1567. // import values into <input> commands
  1568. $.contextMenu.setInputValues = function (opt, data) {
  1569. if (data === undefined) {
  1570. data = {};
  1571. }
  1572. $.each(opt.inputs, function (key, item) {
  1573. switch (item.type) {
  1574. case 'text':
  1575. case 'textarea':
  1576. item.value = data[key] || '';
  1577. break;
  1578. case 'checkbox':
  1579. item.selected = data[key] ? true : false;
  1580. break;
  1581. case 'radio':
  1582. item.selected = (data[item.radio] || '') === item.value;
  1583. break;
  1584. case 'select':
  1585. item.selected = data[key] || '';
  1586. break;
  1587. }
  1588. });
  1589. };
  1590. // export values from <input> commands
  1591. $.contextMenu.getInputValues = function (opt, data) {
  1592. if (data === undefined) {
  1593. data = {};
  1594. }
  1595. $.each(opt.inputs, function (key, item) {
  1596. switch (item.type) {
  1597. case 'text':
  1598. case 'textarea':
  1599. case 'select':
  1600. data[key] = item.$input.val();
  1601. break;
  1602. case 'checkbox':
  1603. data[key] = item.$input.prop('checked');
  1604. break;
  1605. case 'radio':
  1606. if (item.$input.prop('checked')) {
  1607. data[item.radio] = item.value;
  1608. }
  1609. break;
  1610. }
  1611. });
  1612. return data;
  1613. };
  1614. // find <label for="xyz">
  1615. function inputLabel(node) {
  1616. return (node.id && $('label[for="' + node.id + '"]').val()) || node.name;
  1617. }
  1618. // convert <menu> to items object
  1619. function menuChildren(items, $children, counter) {
  1620. if (!counter) {
  1621. counter = 0;
  1622. }
  1623. $children.each(function () {
  1624. var $node = $(this),
  1625. node = this,
  1626. nodeName = this.nodeName.toLowerCase(),
  1627. label,
  1628. item;
  1629. // extract <label><input>
  1630. if (nodeName === 'label' && $node.find('input, textarea, select').length) {
  1631. label = $node.text();
  1632. $node = $node.children().first();
  1633. node = $node.get(0);
  1634. nodeName = node.nodeName.toLowerCase();
  1635. }
  1636. /*
  1637. * <menu> accepts flow-content as children. that means <embed>, <canvas> and such are valid menu items.
  1638. * Not being the sadistic kind, $.contextMenu only accepts:
  1639. * <command>, <menuitem>, <hr>, <span>, <p> <input [text, radio, checkbox]>, <textarea>, <select> and of course <menu>.
  1640. * Everything else will be imported as an html node, which is not interfaced with contextMenu.
  1641. */
  1642. // http://www.whatwg.org/specs/web-apps/current-work/multipage/commands.html#concept-command
  1643. switch (nodeName) {
  1644. // http://www.whatwg.org/specs/web-apps/current-work/multipage/interactive-elements.html#the-menu-element
  1645. case 'menu':
  1646. item = {name: $node.attr('label'), items: {}};
  1647. counter = menuChildren(item.items, $node.children(), counter);
  1648. break;
  1649. // http://www.whatwg.org/specs/web-apps/current-work/multipage/commands.html#using-the-a-element-to-define-a-command
  1650. case 'a':
  1651. // http://www.whatwg.org/specs/web-apps/current-work/multipage/commands.html#using-the-button-element-to-define-a-command
  1652. case 'button':
  1653. item = {
  1654. name: $node.text(),
  1655. disabled: !!$node.attr('disabled'),
  1656. callback: (function () {
  1657. return function () {
  1658. $node.click();
  1659. };
  1660. })()
  1661. };
  1662. break;
  1663. // http://www.whatwg.org/specs/web-apps/current-work/multipage/commands.html#using-the-command-element-to-define-a-command
  1664. case 'menuitem':
  1665. case 'command':
  1666. switch ($node.attr('type')) {
  1667. case undefined:
  1668. case 'command':
  1669. case 'menuitem':
  1670. item = {
  1671. name: $node.attr('label'),
  1672. disabled: !!$node.attr('disabled'),
  1673. icon: $node.attr('icon'),
  1674. callback: (function () {
  1675. return function () {
  1676. $node.click();
  1677. };
  1678. })()
  1679. };
  1680. break;
  1681. case 'checkbox':
  1682. item = {
  1683. type: 'checkbox',
  1684. disabled: !!$node.attr('disabled'),
  1685. name: $node.attr('label'),
  1686. selected: !!$node.attr('checked')
  1687. };
  1688. break;
  1689. case 'radio':
  1690. item = {
  1691. type: 'radio',
  1692. disabled: !!$node.attr('disabled'),
  1693. name: $node.attr('label'),
  1694. radio: $node.attr('radiogroup'),
  1695. value: $node.attr('id'),
  1696. selected: !!$node.attr('checked')
  1697. };
  1698. break;
  1699. default:
  1700. item = undefined;
  1701. }
  1702. break;
  1703. case 'hr':
  1704. item = '-------';
  1705. break;
  1706. case 'input':
  1707. switch ($node.attr('type')) {
  1708. case 'text':
  1709. item = {
  1710. type: 'text',
  1711. name: label || inputLabel(node),
  1712. disabled: !!$node.attr('disabled'),
  1713. value: $node.val()
  1714. };
  1715. break;
  1716. case 'checkbox':
  1717. item = {
  1718. type: 'checkbox',
  1719. name: label || inputLabel(node),
  1720. disabled: !!$node.attr('disabled'),
  1721. selected: !!$node.attr('checked')
  1722. };
  1723. break;
  1724. case 'radio':
  1725. item = {
  1726. type: 'radio',
  1727. name: label || inputLabel(node),
  1728. disabled: !!$node.attr('disabled'),
  1729. radio: !!$node.attr('name'),
  1730. value: $node.val(),
  1731. selected: !!$node.attr('checked')
  1732. };
  1733. break;
  1734. default:
  1735. item = undefined;
  1736. break;
  1737. }
  1738. break;
  1739. case 'select':
  1740. item = {
  1741. type: 'select',
  1742. name: label || inputLabel(node),
  1743. disabled: !!$node.attr('disabled'),
  1744. selected: $node.val(),
  1745. options: {}
  1746. };
  1747. $node.children().each(function () {
  1748. item.options[this.value] = $(this).text();
  1749. });
  1750. break;
  1751. case 'textarea':
  1752. item = {
  1753. type: 'textarea',
  1754. name: label || inputLabel(node),
  1755. disabled: !!$node.attr('disabled'),
  1756. value: $node.val()
  1757. };
  1758. break;
  1759. case 'label':
  1760. break;
  1761. default:
  1762. item = {type: 'html', html: $node.clone(true)};
  1763. break;
  1764. }
  1765. if (item) {
  1766. counter++;
  1767. items['key' + counter] = item;
  1768. }
  1769. });
  1770. return counter;
  1771. }
  1772. // convert html5 menu
  1773. $.contextMenu.fromMenu = function (element) {
  1774. var $this = $(element),
  1775. items = {};
  1776. menuChildren(items, $this.children());
  1777. return items;
  1778. };
  1779. // make defaults accessible
  1780. $.contextMenu.defaults = defaults;
  1781. $.contextMenu.types = types;
  1782. // export internal functions - undocumented, for hacking only!
  1783. $.contextMenu.handle = handle;
  1784. $.contextMenu.op = op;
  1785. $.contextMenu.menus = menus;
  1786. });