jquery.contextMenu.js 92 KB

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