MathEvents.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
  1. /* -*- Mode: Javascript; indent-tabs-mode:nil; js-indent-level: 2 -*- */
  2. /* vim: set ts=2 et sw=2 tw=80: */
  3. /*************************************************************
  4. *
  5. * MathJax/extensions/MathEvents.js
  6. *
  7. * Implements the event handlers needed by the output jax to perform
  8. * menu, hover, and other events.
  9. *
  10. * ---------------------------------------------------------------------
  11. *
  12. * Copyright (c) 2011-2013 The MathJax Consortium
  13. *
  14. * Licensed under the Apache License, Version 2.0 (the "License");
  15. * you may not use this file except in compliance with the License.
  16. * You may obtain a copy of the License at
  17. *
  18. * http://www.apache.org/licenses/LICENSE-2.0
  19. *
  20. * Unless required by applicable law or agreed to in writing, software
  21. * distributed under the License is distributed on an "AS IS" BASIS,
  22. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  23. * See the License for the specific language governing permissions and
  24. * limitations under the License.
  25. */
  26. (function (HUB,HTML,AJAX,CALLBACK,LOCALE,OUTPUT,INPUT) {
  27. var VERSION = "2.2";
  28. var EXTENSION = MathJax.Extension;
  29. var ME = EXTENSION.MathEvents = {version: VERSION};
  30. var SETTINGS = HUB.config.menuSettings;
  31. var CONFIG = {
  32. hover: 500, // time required to be considered a hover
  33. frame: {
  34. x: 3.5, y: 5, // frame padding and
  35. bwidth: 1, // frame border width (in pixels)
  36. bcolor: "#A6D", // frame border color
  37. hwidth: "15px", // haze width
  38. hcolor: "#83A" // haze color
  39. },
  40. button: {
  41. x: -4, y: -3, // menu button offsets
  42. wx: -2, // button offset for full-width equations
  43. src: AJAX.fileURL(OUTPUT.imageDir+"/MenuArrow-15.png") // button image
  44. },
  45. fadeinInc: .2, // increment for fade-in
  46. fadeoutInc: .05, // increment for fade-out
  47. fadeDelay: 50, // delay between fade-in or fade-out steps
  48. fadeoutStart: 400, // delay before fade-out after mouseout
  49. fadeoutDelay: 15*1000, // delay before automatic fade-out
  50. styles: {
  51. ".MathJax_Hover_Frame": {
  52. "border-radius": ".25em", // Opera 10.5 and IE9
  53. "-webkit-border-radius": ".25em", // Safari and Chrome
  54. "-moz-border-radius": ".25em", // Firefox
  55. "-khtml-border-radius": ".25em", // Konqueror
  56. "box-shadow": "0px 0px 15px #83A", // Opera 10.5 and IE9
  57. "-webkit-box-shadow": "0px 0px 15px #83A", // Safari and Chrome
  58. "-moz-box-shadow": "0px 0px 15px #83A", // Forefox
  59. "-khtml-box-shadow": "0px 0px 15px #83A", // Konqueror
  60. border: "1px solid #A6D ! important",
  61. display: "inline-block", position:"absolute"
  62. },
  63. ".MathJax_Hover_Arrow": {
  64. position:"absolute",
  65. width:"15px", height:"11px",
  66. cursor:"pointer"
  67. }
  68. }
  69. };
  70. //
  71. // Common event-handling code
  72. //
  73. var EVENT = ME.Event = {
  74. LEFTBUTTON: 0, // the event.button value for left button
  75. RIGHTBUTTON: 2, // the event.button value for right button
  76. MENUKEY: "altKey", // the event value for alternate context menu
  77. Mousedown: function (event) {return EVENT.Handler(event,"Mousedown",this)},
  78. Mouseup: function (event) {return EVENT.Handler(event,"Mouseup",this)},
  79. Mousemove: function (event) {return EVENT.Handler(event,"Mousemove",this)},
  80. Mouseover: function (event) {return EVENT.Handler(event,"Mouseover",this)},
  81. Mouseout: function (event) {return EVENT.Handler(event,"Mouseout",this)},
  82. Click: function (event) {return EVENT.Handler(event,"Click",this)},
  83. DblClick: function (event) {return EVENT.Handler(event,"DblClick",this)},
  84. Menu: function (event) {return EVENT.Handler(event,"ContextMenu",this)},
  85. //
  86. // Call the output jax's event handler or the zoom handler
  87. //
  88. Handler: function (event,type,math) {
  89. if (AJAX.loadingMathMenu) {return EVENT.False(event)}
  90. var jax = OUTPUT[math.jaxID];
  91. if (!event) {event = window.event}
  92. event.isContextMenu = (type === "ContextMenu");
  93. if (jax[type]) {return jax[type](event,math)}
  94. if (EXTENSION.MathZoom) {return EXTENSION.MathZoom.HandleEvent(event,type,math)}
  95. },
  96. //
  97. // Try to cancel the event in every way we can
  98. //
  99. False: function (event) {
  100. if (!event) {event = window.event}
  101. if (event) {
  102. if (event.preventDefault) {event.preventDefault()}
  103. if (event.stopPropagation) {event.stopPropagation()}
  104. event.cancelBubble = true;
  105. event.returnValue = false;
  106. }
  107. return false;
  108. },
  109. //
  110. // Load the contextual menu code, if needed, and post the menu
  111. //
  112. ContextMenu: function (event,math,force) {
  113. //
  114. // Check if we are showing menus
  115. //
  116. var JAX = OUTPUT[math.jaxID], jax = JAX.getJaxFromMath(math);
  117. var show = (JAX.config.showMathMenu != null ? JAX : HUB).config.showMathMenu;
  118. if (!show || (SETTINGS.context !== "MathJax" && !force)) return;
  119. //
  120. // Remove selections, remove hover fades
  121. //
  122. if (ME.msieEventBug) {event = window.event || event}
  123. EVENT.ClearSelection(); HOVER.ClearHoverTimer();
  124. if (jax.hover) {
  125. if (jax.hover.remove) {clearTimeout(jax.hover.remove); delete jax.hover.remove}
  126. jax.hover.nofade = true;
  127. }
  128. //
  129. // If the menu code is loaded,
  130. // Check if localization needs loading;
  131. // If not, post the menu, and return.
  132. // Otherwise wait for the localization to load
  133. // Otherwse load the menu code.
  134. // Try again after the file is loaded.
  135. //
  136. var MENU = MathJax.Menu; var load, fn;
  137. if (MENU) {
  138. if (MENU.loadingDomain) {return EVENT.False(event)}
  139. load = LOCALE.loadDomain("MathMenu");
  140. if (!load) {
  141. MENU.jax = jax;
  142. var source = MENU.menu.Find("Show Math As").menu;
  143. source.items[0].name = jax.sourceMenuTitle;
  144. source.items[0].format = (jax.sourceMenuFormat||"MathML");
  145. source.items[1].name = INPUT[jax.inputJax].sourceMenuTitle;
  146. var MathPlayer = MENU.menu.Find("Math Settings","MathPlayer");
  147. MathPlayer.hidden = !(jax.outputJax === "NativeMML" && HUB.Browser.hasMathPlayer);
  148. return MENU.menu.Post(event);
  149. }
  150. MENU.loadingDomain = true;
  151. fn = function () {delete MENU.loadingDomain};
  152. } else {
  153. if (AJAX.loadingMathMenu) {return EVENT.False(event)}
  154. AJAX.loadingMathMenu = true;
  155. load = AJAX.Require("[MathJax]/extensions/MathMenu.js");
  156. fn = function () {
  157. delete AJAX.loadingMathMenu;
  158. if (!MathJax.Menu) {MathJax.Menu = {}}
  159. }
  160. }
  161. var ev = {
  162. pageX:event.pageX, pageY:event.pageY,
  163. clientX:event.clientX, clientY:event.clientY
  164. };
  165. CALLBACK.Queue(
  166. load, fn, // load the file and delete the marker when done
  167. ["ContextMenu",EVENT,ev,math,force] // call this function again
  168. );
  169. return EVENT.False(event);
  170. },
  171. //
  172. // Mousedown handler for alternate means of accessing menu
  173. //
  174. AltContextMenu: function (event,math) {
  175. var JAX = OUTPUT[math.jaxID];
  176. var show = (JAX.config.showMathMenu != null ? JAX : HUB).config.showMathMenu;
  177. if (show) {
  178. show = (JAX.config.showMathMenuMSIE != null ? JAX : HUB).config.showMathMenuMSIE;
  179. if (SETTINGS.context === "MathJax" && !SETTINGS.mpContext && show) {
  180. if (!ME.noContextMenuBug || event.button !== EVENT.RIGHTBUTTON) return;
  181. } else {
  182. if (!event[EVENT.MENUKEY] || event.button !== EVENT.LEFTBUTTON) return;
  183. }
  184. return JAX.ContextMenu(event,math,true);
  185. }
  186. },
  187. ClearSelection: function () {
  188. if (ME.safariContextMenuBug) {setTimeout("window.getSelection().empty()",0)}
  189. if (document.selection) {setTimeout("document.selection.empty()",0)}
  190. },
  191. getBBox: function (span) {
  192. span.appendChild(ME.topImg);
  193. var h = ME.topImg.offsetTop, d = span.offsetHeight-h, w = span.offsetWidth;
  194. span.removeChild(ME.topImg);
  195. return {w:w, h:h, d:d};
  196. }
  197. };
  198. //
  199. // Handle hover "discoverability"
  200. //
  201. var HOVER = ME.Hover = {
  202. //
  203. // Check if we are moving from a non-MathJax element to a MathJax one
  204. // and either start fading in again (if it is fading out) or start the
  205. // timer for the hover
  206. //
  207. Mouseover: function (event,math) {
  208. if (SETTINGS.discoverable || SETTINGS.zoom === "Hover") {
  209. var from = event.fromElement || event.relatedTarget,
  210. to = event.toElement || event.target;
  211. if (from && to && (from.isMathJax != to.isMathJax ||
  212. HUB.getJaxFor(from) !== HUB.getJaxFor(to))) {
  213. var jax = this.getJaxFromMath(math);
  214. if (jax.hover) {HOVER.ReHover(jax)} else {HOVER.HoverTimer(jax,math)}
  215. return EVENT.False(event);
  216. }
  217. }
  218. },
  219. //
  220. // Check if we are moving from a MathJax element to a non-MathJax one
  221. // and either start fading out, or clear the timer if we haven't
  222. // hovered yet
  223. //
  224. Mouseout: function (event,math) {
  225. if (SETTINGS.discoverable || SETTINGS.zoom === "Hover") {
  226. var from = event.fromElement || event.relatedTarget,
  227. to = event.toElement || event.target;
  228. if (from && to && (from.isMathJax != to.isMathJax ||
  229. HUB.getJaxFor(from) !== HUB.getJaxFor(to))) {
  230. var jax = this.getJaxFromMath(math);
  231. if (jax.hover) {HOVER.UnHover(jax)} else {HOVER.ClearHoverTimer()}
  232. return EVENT.False(event);
  233. }
  234. }
  235. },
  236. //
  237. // Restart hover timer if the mouse moves
  238. //
  239. Mousemove: function (event,math) {
  240. if (SETTINGS.discoverable || SETTINGS.zoom === "Hover") {
  241. var jax = this.getJaxFromMath(math); if (jax.hover) return;
  242. if (HOVER.lastX == event.clientX && HOVER.lastY == event.clientY) return;
  243. HOVER.lastX = event.clientX; HOVER.lastY = event.clientY;
  244. HOVER.HoverTimer(jax,math);
  245. return EVENT.False(event);
  246. }
  247. },
  248. //
  249. // Clear the old timer and start a new one
  250. //
  251. HoverTimer: function (jax,math) {
  252. this.ClearHoverTimer();
  253. this.hoverTimer = setTimeout(CALLBACK(["Hover",this,jax,math]),CONFIG.hover);
  254. },
  255. ClearHoverTimer: function () {
  256. if (this.hoverTimer) {clearTimeout(this.hoverTimer); delete this.hoverTimer}
  257. },
  258. //
  259. // Handle putting up the hover frame
  260. //
  261. Hover: function (jax,math) {
  262. //
  263. // Check if Zoom handles the hover event
  264. //
  265. if (EXTENSION.MathZoom && EXTENSION.MathZoom.Hover({},math)) return;
  266. //
  267. // Get the hover data
  268. //
  269. var JAX = OUTPUT[jax.outputJax],
  270. span = JAX.getHoverSpan(jax,math),
  271. bbox = JAX.getHoverBBox(jax,span,math),
  272. show = (JAX.config.showMathMenu != null ? JAX : HUB).config.showMathMenu;
  273. var dx = CONFIG.frame.x, dy = CONFIG.frame.y, dd = CONFIG.frame.bwidth; // frame size
  274. if (ME.msieBorderWidthBug) {dd = 0}
  275. jax.hover = {opacity:0, id:jax.inputID+"-Hover"};
  276. //
  277. // The frame and menu button
  278. //
  279. var frame = HTML.Element("span",{
  280. id:jax.hover.id, isMathJax: true,
  281. style:{display:"inline-block", width:0, height:0, position:"relative"}
  282. },[["span",{
  283. className:"MathJax_Hover_Frame", isMathJax: true,
  284. style:{
  285. display:"inline-block", position:"absolute",
  286. top:this.Px(-bbox.h-dy-dd-(bbox.y||0)), left:this.Px(-dx-dd+(bbox.x||0)),
  287. width:this.Px(bbox.w+2*dx), height:this.Px(bbox.h+bbox.d+2*dy),
  288. opacity:0, filter:"alpha(opacity=0)"
  289. }}
  290. ]]
  291. );
  292. var button = HTML.Element("span",{
  293. isMathJax: true, id:jax.hover.id+"Menu",
  294. style:{display:"inline-block", "z-index": 1, width:0, height:0, position:"relative"}
  295. },[["img",{
  296. className: "MathJax_Hover_Arrow", isMathJax: true, math: math,
  297. src: CONFIG.button.src, onclick: this.HoverMenu, jax:JAX.id,
  298. style: {
  299. left:this.Px(bbox.w+dx+dd+(bbox.x||0)+CONFIG.button.x),
  300. top:this.Px(-bbox.h-dy-dd-(bbox.y||0)-CONFIG.button.y),
  301. opacity:0, filter:"alpha(opacity=0)"
  302. }
  303. }]]
  304. );
  305. if (bbox.width) {
  306. frame.style.width = button.style.width = bbox.width;
  307. frame.style.marginRight = button.style.marginRight = "-"+bbox.width;
  308. frame.firstChild.style.width = bbox.width;
  309. button.firstChild.style.left = "";
  310. button.firstChild.style.right = this.Px(CONFIG.button.wx);
  311. }
  312. //
  313. // Add the frame and button
  314. //
  315. span.parentNode.insertBefore(frame,span);
  316. if (show) {span.parentNode.insertBefore(button,span)}
  317. if (span.style) {span.style.position = "relative"} // so math is on top of hover frame
  318. //
  319. // Start the hover fade-in
  320. //
  321. this.ReHover(jax);
  322. },
  323. //
  324. // Restart the hover fade in and fade-out timers
  325. //
  326. ReHover: function (jax) {
  327. if (jax.hover.remove) {clearTimeout(jax.hover.remove)}
  328. jax.hover.remove = setTimeout(CALLBACK(["UnHover",this,jax]),CONFIG.fadeoutDelay);
  329. this.HoverFadeTimer(jax,CONFIG.fadeinInc);
  330. },
  331. //
  332. // Start the fade-out
  333. //
  334. UnHover: function (jax) {
  335. if (!jax.hover.nofade) {this.HoverFadeTimer(jax,-CONFIG.fadeoutInc,CONFIG.fadeoutStart)}
  336. },
  337. //
  338. // Handle the fade-in and fade-out
  339. //
  340. HoverFade: function (jax) {
  341. delete jax.hover.timer;
  342. jax.hover.opacity = Math.max(0,Math.min(1,jax.hover.opacity + jax.hover.inc));
  343. jax.hover.opacity = Math.floor(1000*jax.hover.opacity)/1000;
  344. var frame = document.getElementById(jax.hover.id),
  345. button = document.getElementById(jax.hover.id+"Menu");
  346. frame.firstChild.style.opacity = jax.hover.opacity;
  347. frame.firstChild.style.filter = "alpha(opacity="+Math.floor(100*jax.hover.opacity)+")";
  348. if (button) {
  349. button.firstChild.style.opacity = jax.hover.opacity;
  350. button.firstChild.style.filter = frame.style.filter;
  351. }
  352. if (jax.hover.opacity === 1) {return}
  353. if (jax.hover.opacity > 0) {this.HoverFadeTimer(jax,jax.hover.inc); return}
  354. frame.parentNode.removeChild(frame);
  355. if (button) {button.parentNode.removeChild(button)}
  356. if (jax.hover.remove) {clearTimeout(jax.hover.remove)}
  357. delete jax.hover;
  358. },
  359. //
  360. // Set the fade to in or out (via inc) and start the timer, if needed
  361. //
  362. HoverFadeTimer: function (jax,inc,delay) {
  363. jax.hover.inc = inc;
  364. if (!jax.hover.timer) {
  365. jax.hover.timer = setTimeout(CALLBACK(["HoverFade",this,jax]),(delay||CONFIG.fadeDelay));
  366. }
  367. },
  368. //
  369. // Handle a click on the menu button
  370. //
  371. HoverMenu: function (event) {
  372. if (!event) {event = window.event}
  373. return OUTPUT[this.jax].ContextMenu(event,this.math,true);
  374. },
  375. //
  376. // Clear all hover timers
  377. //
  378. ClearHover: function (jax) {
  379. if (jax.hover.remove) {clearTimeout(jax.hover.remove)}
  380. if (jax.hover.timer) {clearTimeout(jax.hover.timer)}
  381. HOVER.ClearHoverTimer();
  382. delete jax.hover;
  383. },
  384. //
  385. // Make a measurement in pixels
  386. //
  387. Px: function (m) {
  388. if (Math.abs(m) < .006) {return "0px"}
  389. return m.toFixed(2).replace(/\.?0+$/,"") + "px";
  390. },
  391. //
  392. // Preload images so they show up with the menu
  393. //
  394. getImages: function () {
  395. var menu = new Image();
  396. menu.src = CONFIG.button.src;
  397. }
  398. };
  399. //
  400. // Handle touch events.
  401. //
  402. // Use double-tap-and-hold as a replacement for context menu event.
  403. // Use double-tap as a replacement for double click.
  404. //
  405. var TOUCH = ME.Touch = {
  406. last: 0, // time of last tap event
  407. delay: 500, // delay time for double-click
  408. //
  409. // Check if this is a double-tap, and if so, start the timer
  410. // for the double-tap and hold (to trigger the contextual menu)
  411. //
  412. start: function (event) {
  413. var now = new Date().getTime();
  414. var dblTap = (now - TOUCH.last < TOUCH.delay && TOUCH.up);
  415. TOUCH.last = now; TOUCH.up = false;
  416. if (dblTap) {
  417. TOUCH.timeout = setTimeout(TOUCH.menu,TOUCH.delay,event,this);
  418. event.preventDefault();
  419. }
  420. },
  421. //
  422. // Check if there is a timeout pending, i.e., we have a
  423. // double-tap and were waiting to see if it is held long
  424. // enough for the menu. Since we got the end before the
  425. // timeout, it is a double-click, not a double-tap-and-hold.
  426. // Prevent the default action and issue a double click.
  427. //
  428. end: function (event) {
  429. var now = new Date().getTime();
  430. TOUCH.up = (now - TOUCH.last < TOUCH.delay);
  431. if (TOUCH.timeout) {
  432. clearTimeout(TOUCH.timeout);
  433. delete TOUCH.timeout; TOUCH.last = 0; TOUCH.up = false;
  434. event.preventDefault();
  435. return EVENT.Handler((event.touches[0]||event.touch),"DblClick",this);
  436. }
  437. },
  438. //
  439. // If the timeout passes without an end event, we issue
  440. // the contextual menu event.
  441. //
  442. menu: function (event,math) {
  443. delete TOUCH.timeout; TOUCH.last = 0; TOUCH.up = false;
  444. return EVENT.Handler((event.touches[0]||event.touch),"ContextMenu",math);
  445. }
  446. };
  447. //
  448. // Mobile screens are small, so use larger version of arrow
  449. //
  450. if (HUB.Browser.isMobile) {
  451. var arrow = CONFIG.styles[".MathJax_Hover_Arrow"];
  452. arrow.width = "25px"; arrow.height = "18px";
  453. CONFIG.button.x = -6;
  454. }
  455. //
  456. // Set up browser-specific values
  457. //
  458. HUB.Browser.Select({
  459. MSIE: function (browser) {
  460. var mode = (document.documentMode || 0);
  461. var isIE8 = browser.versionAtLeast("8.0");
  462. ME.msieBorderWidthBug = (document.compatMode === "BackCompat"); // borders are inside offsetWidth/Height
  463. ME.msieEventBug = browser.isIE9; // must get event from window even though event is passed
  464. ME.msieAlignBug = (!isIE8 || mode < 8); // inline-block spans don't rest on baseline
  465. if (mode < 9) {EVENT.LEFTBUTTON = 1} // IE < 9 has wrong event.button values
  466. },
  467. Safari: function (browser) {
  468. ME.safariContextMenuBug = true; // selection can be started by contextmenu event
  469. },
  470. Opera: function (browser) {
  471. ME.operaPositionBug = true; // position is wrong unless border is used
  472. },
  473. Konqueror: function (browser) {
  474. ME.noContextMenuBug = true; // doesn't produce contextmenu event
  475. }
  476. });
  477. //
  478. // Used in measuring zoom and hover positions
  479. //
  480. ME.topImg = (ME.msieAlignBug ?
  481. HTML.Element("img",{style:{width:0,height:0,position:"relative"},src:"about:blank"}) :
  482. HTML.Element("span",{style:{width:0,height:0,display:"inline-block"}})
  483. );
  484. if (ME.operaPositionBug) {ME.topImg.style.border="1px solid"}
  485. //
  486. // Get configuration from user
  487. //
  488. ME.config = CONFIG = HUB.CombineConfig("MathEvents",CONFIG);
  489. var SETFRAME = function () {
  490. var haze = CONFIG.styles[".MathJax_Hover_Frame"];
  491. haze.border = CONFIG.frame.bwidth+"px solid "+CONFIG.frame.bcolor+" ! important";
  492. haze["box-shadow"] = haze["-webkit-box-shadow"] =
  493. haze["-moz-box-shadow"] = haze["-khtml-box-shadow"] =
  494. "0px 0px "+CONFIG.frame.hwidth+" "+CONFIG.frame.hcolor;
  495. };
  496. //
  497. // Queue the events needed for startup
  498. //
  499. CALLBACK.Queue(
  500. HUB.Register.StartupHook("End Config",{}), // wait until config is complete
  501. [SETFRAME],
  502. ["getImages",HOVER],
  503. ["Styles",AJAX,CONFIG.styles],
  504. ["Post",HUB.Startup.signal,"MathEvents Ready"],
  505. ["loadComplete",AJAX,"[MathJax]/extensions/MathEvents.js"]
  506. );
  507. })(MathJax.Hub,MathJax.HTML,MathJax.Ajax,MathJax.Callback,
  508. MathJax.Localization,MathJax.OutputJax,MathJax.InputJax);