jquery.contextMenu.js 91 KB

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