guppy.js

  1. import Doc from './doc.js';
  2. import Engine from './engine.js';
  3. import Mousetrap from '../lib/mousetrap/mousetrap.min.js';
  4. import Settings from './settings.js';
  5. import Symbols from './symbols.js';
  6. import Utils from './utils.js';
  7. import katex from '../lib/katex/katex-modified.min.js';
  8. /**
  9. @class
  10. @classdesc An instance of Guppy. Calling `Guppy(id)` with the ID of
  11. an existing editor will simply return that instance.
  12. @param {string|Node} element - The string id or the Dom Node of the
  13. element that should be converted to an editor.
  14. @constructor
  15. */
  16. var Guppy = function(el, config){
  17. if(!Guppy.initialised) Guppy.init();
  18. // Get the element and try to get its corresponding instance and settings
  19. var element = typeof el === 'string' ? document.getElementById(el) : el;
  20. var instance = Guppy.instances.get(element);
  21. if(instance){
  22. return instance;
  23. }
  24. var self = this;
  25. config = config || {};
  26. var settings = config['settings'] || {};
  27. // Store a record of this instance in case somebody wants it again
  28. Guppy.instances.set(element, this)
  29. config['parent'] = self;
  30. var tab_idx = Guppy.max_tabIndex || 0;
  31. element.tabIndex = tab_idx;
  32. Guppy.max_tabIndex = tab_idx+1;
  33. var buttons = settings['buttons'] || Settings.config.settings['buttons'];
  34. this.buttons_div = document.createElement("div");
  35. this.buttons_div.setAttribute("class","guppy_buttons");
  36. if(buttons){
  37. for(var i = 0; i < buttons.length; i++){
  38. if(buttons[i] == "osk" && Settings.osk){
  39. Guppy.make_button("keyboard", this.buttons_div, function() {
  40. if(Settings.osk.guppy == self){ Settings.osk.detach(self); }
  41. else{ Settings.osk.attach(self); }});
  42. }
  43. else if(buttons[i] == "settings") Guppy.make_button("settings", this.buttons_div, function(){ Settings.toggle("settings", self); });
  44. else if(buttons[i] == "symbols") Guppy.make_button("symbols", this.buttons_div, function(){ Settings.toggle("symbols", self); });
  45. else if(buttons[i] == "controls") Guppy.make_button("help", this.buttons_div, function(){ Settings.toggle("controls", self); });
  46. }
  47. }
  48. this.editor_active = true;
  49. //this.empty_content = settings['empty_content'] || "\\red{[?]}"
  50. this.editor = element;
  51. this.blacklist = [];
  52. this.autoreplace = true;
  53. /** @member {Engine} */
  54. this.engine = new Engine(config);
  55. this.temp_cursor = {"node":null,"caret":0}
  56. this.editor.addEventListener("keydown",Guppy.key_down, false);
  57. this.editor.addEventListener("keyup",Guppy.key_up, false);
  58. this.editor.addEventListener("focus", function() { Guppy.kb.alt_down = false; }, false);
  59. this.render(true);
  60. this.deactivate();
  61. this.recompute_locations_paths();
  62. }
  63. Guppy.instances = new Map()
  64. Guppy.Doc = Doc;
  65. Guppy.active_guppy = null;
  66. Guppy.Symbols = Symbols;
  67. Guppy.Mousetrap = Mousetrap;
  68. Guppy.make_button = function(cls, parent, cb){
  69. var b = document.createElement("div");
  70. b.setAttribute("class","guppy-button "+cls);
  71. parent.appendChild(b);
  72. if(cb){
  73. b.addEventListener("mouseup", function(e){
  74. cb(e);
  75. if(e.cancelBubble!=null) e.cancelBubble = true;
  76. if(e.stopPropagation) e.stopPropagation();
  77. e.preventDefault();
  78. return false;
  79. }, false);
  80. }
  81. return b;
  82. }
  83. /**
  84. Add a symbol to all instances of the editor
  85. @memberof Guppy
  86. @param {string} name - The name of the symbol to add. This is
  87. also the string that will be autoreplaced with the symbol.
  88. @param {Object} symbol - If `template` is present, this is just
  89. the template arguments. Otherwise, it is the complete symbol
  90. specification
  91. @param {Object} symbol.output - Key/value pairs where the key is
  92. the output type (such as "latex" or "asciimath") and the value is
  93. the string by which the output will be rendered in that format.
  94. In this string, {$n} will be substituted with the rendering of the
  95. nth argument. If the nth argument is a d-dimensional list, then
  96. the argument should be specified as {$n{sep_1}{sep_2}...{sep_d}}
  97. where sep_i will be the separator used to separate entries in the
  98. ith dimension. Note that keys are not necessary to describe the
  99. AST or plain-text outputs.
  100. @param {Array} symbol.keys - A list of strings representing
  101. keystrokes that can be used to trigger the insertion of this
  102. symbol. For example, `"^" or `"shift+up"` for the `exponential`
  103. symbol.
  104. @param {Object} symbol.attrs - A specification of the attributes
  105. of the symbol
  106. @param {string} symbol.attrs.type - A longer description of the
  107. symbol type, suitable for searching and text rendering.
  108. @param {string} symbol.attrs.group - The group in which to place
  109. this symbol (for OSK)
  110. @param {Object} [symbol.input] - If the symbol should subsume part
  111. of the existing content of the editor (as in, for example, the
  112. case of exponent), this object will contain the (1-based) index of
  113. the argument in which that content should be placed.
  114. @param {Object} [symbol.ast] - Modifies the default construction
  115. of an entry in the AST for this symbol.
  116. @param {Object} [symbol.ast.type="operator"] - The type of symbol
  117. for AST purposes. Can be "name" (meaning this symbol represents
  118. a variable, as in the case of pi), "number" (meaning this symbol
  119. is a literal value), "operator" (meaning this symbol is a
  120. function or otherwise takes arguments (as in cos or +), or
  121. "pass" (meaning this symbol's first argument will be used as its
  122. AST entry, as in the case of brackets/parentheses).
  123. @param {Object[]} [symbol.args] - A list of specifications, one
  124. for each argument
  125. @param {string} [symbol.args.down] - The index of the argument
  126. to jump to when the "down" arrow is pressed in this argument
  127. @param {string} [symbol.args.up] - The index of the argument
  128. to jump to when the "up" arrow is pressed in this argument
  129. @param {string} [symbol.args.small="no"] - "yes" if the symbol is
  130. small (as in an exponent)
  131. @param {string} [symbol.args.name] - The name of this particular
  132. argument (suitable for searching)
  133. @param {string} [symbol.args.bracket="no"] - "yes" if brackets
  134. should automatically be rendered around this argument when they
  135. might be needed to disambiguate.
  136. @param {string} [symbol.args.delete] - If present, when the
  137. "backspace" key is pressed at the beginning of this argument,
  138. the symbol will be deleted and replaced with the argument whose
  139. index is specified in this parameter. For example, the second
  140. argument of an exponent has this value set to "1", so that when
  141. the exponent is deleted, the base remains.
  142. @param {string} [symbol.args.mode="math"] - Change the mode of an
  143. argument. Can be "text" (meaning the argument will be editable
  144. as and rendered as plain text), "symbol" (meaning the argument
  145. will specify a symbol name and will complete to an actual symbol
  146. when this is entered--only used for the backslash symbol), or
  147. "math" (the default)
  148. @param {string} [symbol.args.is_bracket="no"] - Set to "yes" if
  149. the symbol is itself a bracket/parenthesis equivalent.
  150. @param {string} [template] - The name of the template to use
  151. */
  152. Guppy.add_global_symbol = function(name, symbol, template){
  153. if(template){
  154. symbol = Symbols.make_template_symbol(template, name, symbol);
  155. }
  156. Symbols.symbols[name] = JSON.parse(JSON.stringify(symbol));
  157. for(var [, instance] of Guppy.instances){
  158. instance.engine.symbols[name] = JSON.parse(JSON.stringify(symbol));
  159. }
  160. }
  161. /**
  162. Remove a symbol from all instances of the editor
  163. @memberof Guppy
  164. @param {string} name - The name of the symbol to remove
  165. */
  166. Guppy.remove_global_symbol = function(name){
  167. if(Symbols.symbols[name]){
  168. delete Symbols.symbols[name]
  169. for(var [, instance] of Guppy.instances){
  170. if(instance.engine.symbols[name]){
  171. delete instance.engine.symbols[name];
  172. }
  173. }
  174. }
  175. }
  176. /**
  177. @param {string} name - The name of the setting to configure. Can be "xml_content", "autoreplace", "blank_caret", "empty_content", "blacklist", "buttons", or "cliptype"
  178. @param {Object} val - The value associated with the named setting:
  179. * "xml_content": An XML string with which to initialise the editor's state. (Defaults to "<m><e/></m>".)
  180. * "autoreplace": A string describing how to autoreplace typed text with symbols:
  181. * "auto" (default): Replace symbls greedily
  182. * "whole": Replace only entire tokens
  183. * "delay": Same as "whole", but with 200ms delay before replacement
  184. * "blank_caret": A LaTeX string that specifies what the caret should look like when in a blank spot. If `""`, the default caret is used.
  185. * "empty_content": A LaTeX string that will be displayed when the editor is both inactive and contains no content. (Defaults to "\color{red}{[?]}")
  186. * "blacklist": A list of string symbol names, corresponding to symbols that should not be allowed in this instance of the editor.
  187. * "buttons": A list of strings corresponding to the helper buttons that should be displayed in the editor; should be a subset of ["osk","settings","symbols","controls"]]
  188. * "cliptype": A string describing what gets placed on the system clipboard when content is copied from the editor.
  189. * "text": Use plain-text editor content
  190. * "latex": Use LaTeX rendering of editor content
  191. */
  192. Guppy.configure = function(name, val){
  193. if(name in Settings.settings_options && Settings.settings_options[name].indexOf(val) == -1){
  194. throw "Valid values for " + name + " are " + JSON.stringify(Settings.settings_options[name]);
  195. }
  196. Settings.config.settings[name] = val;
  197. }
  198. /**
  199. @param {string} name - The name of the setting to configure. Can be "xml_content", "autoreplace", "blank_caret", "empty_content", "blacklist", "buttons", or "cliptype"
  200. @param {Object} val - The value associated with the named setting:
  201. "xml_content": An XML string with which to initialise the editor's state. (Defaults to "<m><e/></m>".)
  202. "autoreplace": A string describing how to autoreplace typed text with symbols:
  203. "auto" (default): Replace symbls greedily
  204. "whole": Replace only entire tokens
  205. "delay": Same as "whole", but with 200ms delay before replacement
  206. "blank_caret": A LaTeX string that specifies what the caret should look like when in a blank spot. If `""`, the default caret is used.
  207. "empty_content": A LaTeX string that will be displayed when the editor is both inactive and contains no content. (Defaults to "\color{red}{[?]}")
  208. "blacklist": A list of string symbol names, corresponding to symbols that should not be allowed in this instance of the editor.
  209. "buttons": A list of strings corresponding to the helper buttons that should be displayed in the editor; should be a subset of ["osk","settings","symbols","controls"]]
  210. "cliptype": A string describing what gets placed on the system clipboard when content is copied from the editor.
  211. "text": Use plain-text editor content
  212. "latex": Use LaTeX rendering of editor content
  213. */
  214. Guppy.prototype.configure = function(name, val){
  215. if(name in Settings.settings_options && Settings.settings_options[name].indexOf(val) == -1){
  216. throw "Valid values for " + name + " are " + JSON.stringify(Settings.config.options[name]);
  217. }
  218. this.engine.settings[name] = val;
  219. this.render(true);
  220. }
  221. /**
  222. Render all guppy documents on the page.
  223. @param {string} type - The type of content to render
  224. @param {string} [delim] - The string to delimit mathematical symbols
  225. @param {string} [root_node] - The DOM Element object within which to do the rendering
  226. @memberof Guppy
  227. */
  228. Guppy.render_all = function(t, delim, root_node){
  229. if(!Guppy.initialised) Guppy.init();
  230. Doc.render_all(t, delim, root_node)
  231. }
  232. /**
  233. @param {string} name - The name of an event. Can be:
  234. * change - Called when the editor's content changes. Argument will be a dictionary with keys `old` and `new` containing the old and new documents, respectively.
  235. * left_end - Called when the cursor is at the left-most point and a command is received to move the cursor to the left (e.g., via the left arrow key). Argument will be null.
  236. * right_end - Called when the cursor is at the right-most point and a command is received to move the cursor to the right (e.g., via the right arrow key). Argument will be null.
  237. * done - Called when the enter key is pressed in the editor.
  238. * completion - Called when the editor outputs tab completion options. Argument is a dictionary with the key `candidates`, a list of the options for tab-completion.
  239. * debug - Called when the editor outputs some debug information. Argument is a dictionary with the key `message`.
  240. * error - Called when the editor receives an error. Argument is a dictionary with the key `message`.
  241. * focus - Called when the editor is focused or unfocused. Argument will have a single key `focused` which will be `true` or `false` according to whether the editor is newly focused or newly unfocused (respectively).
  242. @param {function} handler - The function that will be called to handle the given event
  243. */
  244. Guppy.prototype.event = function(name, handler){
  245. if(Settings.config.valid_events.indexOf(name) == -1) {
  246. throw "Valid events are " + JSON.stringify(Settings.config.valid_events);
  247. }
  248. if(name == "focus" && Settings.osk) {
  249. var f = Settings.config.events["focus"];
  250. this.engine.events["focus"] = function(e){
  251. f(e);
  252. handler(e);
  253. if(e.focused) Settings.osk.attach(e.target);
  254. else Settings.osk.detach(e.target);
  255. };
  256. }
  257. else {
  258. this.engine.events[name] = handler;
  259. }
  260. }
  261. /**
  262. @param {string} name - The name of an event. Can be:
  263. * change - Called when the editor's content changes. Argument will be a dictionary with keys `old` and `new` containing the old and new documents, respectively.
  264. * left_end - Called when the cursor is at the left-most point and a command is received to move the cursor to the left (e.g., via the left arrow key). Argument will be null.
  265. * right_end - Called when the cursor is at the right-most point and a command is received to move the cursor to the right (e.g., via the right arrow key). Argument will be null.
  266. * done - Called when the enter key is pressed in the editor.
  267. * completion - Called when the editor outputs tab completion options. Argument is a dictionary with the key `candidates`, a list of the options for tab-completion.
  268. * debug - Called when the editor outputs some debug information. Argument is a dictionary with the key `message`.
  269. * error - Called when the editor receives an error. Argument is a dictionary with the key `message`.
  270. * focus - Called when the editor is focused or unfocused. Argument will have a single key `focused` which will be `true` or `false` according to whether the editor is newly focused or newly unfocused (respectively).
  271. @param {function} handler - The function that will be called to handle the given event
  272. */
  273. Guppy.event = function(name, handler){
  274. if(Settings.config.valid_events.indexOf(name) == -1) {
  275. throw "Valid events are " + JSON.stringify(Settings.config.valid_events);
  276. }
  277. if(name == "focus" && Settings.osk) {
  278. Settings.config.events["focus"] = function(e){
  279. handler(e);
  280. if(e.focused) Settings.osk.attach(e.target);
  281. else Settings.osk.detach(e.target);
  282. };
  283. }
  284. else {
  285. Settings.config.events[name] = handler;
  286. }
  287. }
  288. /**
  289. @param {GuppyOSK} [osk] - A GuppyOSK object to use for the on-screen keyboard if one is desired
  290. */
  291. Guppy.use_osk = function(osk){
  292. Guppy.OSK = osk;
  293. Settings.osk = osk;
  294. if(osk.config.attach == "focus"){
  295. var f = Settings.config.events["focus"];
  296. Settings.config.events["focus"] = function(e){
  297. if(f) f(e);
  298. if(e.focused) osk.attach(e.target);
  299. else osk.detach(e.target);
  300. };
  301. }
  302. }
  303. Guppy.prototype.is_changed = function(){
  304. var bb = this.editor.getElementsByClassName("katex")[0];
  305. if(!bb) return;
  306. var rect = bb.getBoundingClientRect();
  307. var ans = null;
  308. if(this.bounding_box)
  309. ans = this.bounding_box.top != rect.top || this.bounding_box.bottom != rect.bottom || this.bounding_box.right != rect.right || this.bounding_box.left != rect.left;
  310. else
  311. ans = true;
  312. this.bounding_box = rect;
  313. return ans;
  314. }
  315. Guppy.prototype.recompute_locations_paths = function(){
  316. var ans = [];
  317. var bb = this.editor.getElementsByClassName("katex")[0];
  318. if(!bb) return;
  319. var rect = bb.getBoundingClientRect();
  320. ans.push({'path':'all',
  321. 'top':rect.top,
  322. 'bottom':rect.bottom,
  323. 'left':rect.left,
  324. 'right':rect.right});
  325. var elts = this.editor.getElementsByClassName("guppy_elt");
  326. for(var i = 0; i < elts.length; i++){
  327. var elt = elts[i];
  328. if(elt.nodeName == "mstyle") continue;
  329. rect = elt.getBoundingClientRect();
  330. if(rect.top == 0 && rect.bottom == 0 && rect.left == 0 && rect.right == 0) continue;
  331. var cl = elt.classList;
  332. for(var j = 0; j < cl.length; j++){
  333. if(cl[j].indexOf("guppy_loc") == 0){
  334. ans.push({'path':cl[j],
  335. 'top':rect.top,
  336. 'bottom':rect.bottom,
  337. 'left':rect.left,
  338. 'right':rect.right,
  339. 'mid_x':(rect.left+rect.right)/2,
  340. 'mid_y':(rect.bottom+rect.top)/2,
  341. 'blank':(' '+elt.className+' ').indexOf(' guppy_blank ') >= 0});
  342. break;
  343. }
  344. }
  345. }
  346. this.boxes = ans;
  347. }
  348. Guppy.get_loc = function(x,y,current_node,current_caret){
  349. var g = Guppy.active_guppy;
  350. var min_dist = -1;
  351. var mid_dist = 0;
  352. var pos = "";
  353. var opt = null;
  354. var cur = null;
  355. var car = null;
  356. // check if we go to first or last element
  357. var bb = g.editor.getElementsByClassName("katex")[0];
  358. if(!bb) return;
  359. if(current_node){
  360. var current_path = Utils.path_to(current_node);
  361. var current_pos = parseInt(current_path.substring(current_path.lastIndexOf("e")+1));
  362. }
  363. var boxes = g.boxes;
  364. if(!boxes) return;
  365. if(current_node){
  366. current_path = current_path.replace(/e[0-9]+$/,"e");
  367. var boxes2 = [];
  368. for(var i = 0; i < boxes.length; i++){
  369. if(boxes[i].path == "all") continue;
  370. var loc = boxes[i].path.substring(0,boxes[i].path.lastIndexOf("_"));
  371. loc = loc.replace(/e[0-9]+$/,"e");
  372. if(loc == current_path){
  373. boxes2.push(boxes[i]);
  374. }
  375. }
  376. boxes = boxes2;
  377. }
  378. if(!boxes) return;
  379. for(var j = 0; j < boxes.length; j++){
  380. var box = boxes[j];
  381. if(box.path == "all"){
  382. if(!opt) opt = {'path':'guppy_loc_m_e1_0'};
  383. continue;
  384. }
  385. var xdist = Math.max(box.left - x, x - box.right, 0)
  386. var ydist = Math.max(box.top - y, y - box.bottom, 0)
  387. var dist = Math.sqrt(xdist*xdist + ydist*ydist);
  388. if(min_dist == -1 || dist < min_dist){
  389. min_dist = dist;
  390. mid_dist = x - box.mid_x;
  391. opt = box;
  392. }
  393. }
  394. loc = opt.path.substring("guppy_loc".length);
  395. loc = loc.replace(/_/g,"/");
  396. loc = loc.replace(/([0-9]+)(?=.*?\/)/g,"[$1]");
  397. cur = g.engine.doc.xpath_node(loc.substring(0,loc.lastIndexOf("/")), g.engine.doc.root());
  398. car = parseInt(loc.substring(loc.lastIndexOf("/")+1));
  399. // Check if we want the cursor before or after the element
  400. if(mid_dist > 0 && !(opt.blank)){
  401. car++;
  402. }
  403. var ans = {"current":cur,"caret":car,"pos":pos};
  404. if(current_node && opt){
  405. var opt_pos = parseInt(opt.path.substring(opt.path.lastIndexOf("e")+1,opt.path.lastIndexOf("_")));
  406. if(opt_pos < current_pos) pos = "left";
  407. else if(opt_pos > current_pos) pos = "right";
  408. else if(car < current_caret) pos = "left";
  409. else if(car > current_caret) pos = "right";
  410. if(pos) ans['pos'] = pos;
  411. else ans['pos'] = "none";
  412. }
  413. return ans;
  414. }
  415. Guppy.mouse_up = function(){
  416. Guppy.kb.is_mouse_down = false;
  417. var g = Guppy.active_guppy;
  418. if(g) g.render(true);
  419. }
  420. Guppy.mouse_down = function(e){
  421. if(e.target.getAttribute("class") == "guppy-button") return;
  422. var n = e.target;
  423. Guppy.kb.is_mouse_down = true;
  424. while(n != null){
  425. var instance = Guppy.instances.get(n);
  426. if(instance){
  427. e.preventDefault();
  428. var prev_active = Guppy.active_guppy;
  429. for(var [element, gup] of Guppy.instances){
  430. if(element !== n) gup.deactivate();
  431. else gup.activate();
  432. }
  433. var g = Guppy.active_guppy;
  434. var b = Guppy.active_guppy.engine;
  435. g.space_caret = 0;
  436. if(prev_active == g){
  437. if(e.shiftKey){
  438. g.select_to(e.clientX, e.clientY, true);
  439. }
  440. else {
  441. var loc = Guppy.get_loc(e.clientX,e.clientY);
  442. if(!loc) return;
  443. b.current = loc.current;
  444. b.caret = loc.caret;
  445. b.sel_status = Engine.SEL_NONE;
  446. }
  447. g.render(true);
  448. }
  449. return;
  450. }
  451. if(n.classList && n.classList.contains("guppy_osk")){
  452. return;
  453. }
  454. n = n.parentNode;
  455. }
  456. Guppy.active_guppy = null;
  457. for(var [, gup2] of Guppy.instances){
  458. gup2.deactivate();
  459. }
  460. }
  461. Guppy.mouse_move = function(e){
  462. var g = Guppy.active_guppy;
  463. if(!g) return;
  464. if(!Guppy.kb.is_mouse_down){
  465. var bb = g.editor;
  466. var rect = bb.getBoundingClientRect();
  467. if((e.clientX < rect.left || e.clientX > rect.right) || (e.clientY > rect.bottom || e.clientY < rect.top)){
  468. g.temp_cursor = {"node":null,"caret":0};
  469. }
  470. else{
  471. var loc = Guppy.get_loc(e.clientX,e.clientY);
  472. if(!loc) return;
  473. g.temp_cursor = {"node":loc.current,"caret":loc.caret};
  474. }
  475. g.render(g.is_changed());
  476. }
  477. else{
  478. g.select_to(e.clientX,e.clientY, true);
  479. g.render(g.is_changed());
  480. }
  481. }
  482. Guppy.prototype.select_to = function(x, y, mouse){
  483. var sel_caret = this.engine.caret;
  484. var sel_cursor = this.engine.current;
  485. if(this.engine.sel_status == Engine.SEL_CURSOR_AT_START){
  486. sel_cursor = this.engine.sel_end.node;
  487. sel_caret = this.engine.sel_end.caret;
  488. }
  489. else if(this.engine.sel_status == Engine.SEL_CURSOR_AT_END){
  490. sel_cursor = this.engine.sel_start.node;
  491. sel_caret = this.engine.sel_start.caret;
  492. }
  493. var loc = Guppy.get_loc(x,y,sel_cursor,sel_caret);
  494. if(!loc) return;
  495. this.engine.select_to(loc, sel_cursor, sel_caret, mouse);
  496. }
  497. window.addEventListener("mousedown",Guppy.mouse_down, true);
  498. window.addEventListener("mouseup",Guppy.mouse_up, true);
  499. window.addEventListener("mousemove",Guppy.mouse_move, false);
  500. Guppy.prototype.render_node = function(t){
  501. // All the interesting work is done by transform. This function just adds in the cursor and selection-start cursor
  502. var output = "";
  503. if(t == "render"){
  504. var root = this.engine.doc.root();
  505. this.engine.add_paths(root,"m");
  506. this.engine.temp_cursor = this.temp_cursor;
  507. this.engine.add_classes_cursors(root);
  508. this.engine.current.setAttribute("current","yes");
  509. if(this.temp_cursor.node) this.temp_cursor.node.setAttribute("temp","yes");
  510. output = this.engine.get_content("latex",true);
  511. this.engine.remove_cursors_classes(root);
  512. output = output.replace(new RegExp('&amp;','g'), '&');
  513. return output;
  514. }
  515. else{
  516. output = this.engine.get_content(t);
  517. }
  518. return output
  519. }
  520. /**
  521. Render the document
  522. @memberof Guppy
  523. @param {boolean} [updated=false] - Whether there have been visible
  524. changes to the document (i.e. that affect the positions of
  525. elements)
  526. */
  527. Guppy.prototype.render = function(updated){
  528. if(!this.editor_active && this.engine.doc.is_blank()){
  529. katex.render(this.engine.setting("empty_content"),this.editor);
  530. this.editor.appendChild(this.buttons_div);
  531. return;
  532. }
  533. var tex = this.render_node("render");
  534. katex.render(tex,this.editor);
  535. this.editor.appendChild(this.buttons_div);
  536. if(updated){
  537. this.recompute_locations_paths();
  538. }
  539. }
  540. /**
  541. Get the content of the editor as LaTeX
  542. @memberof Guppy
  543. */
  544. Guppy.prototype.latex = function(){
  545. return this.engine.get_content("latex");
  546. }
  547. /**
  548. Get the content of the editor as XML
  549. @memberof Guppy
  550. */
  551. Guppy.prototype.xml = function(){
  552. return this.engine.get_content("xml");
  553. }
  554. /**
  555. Get the content of the editor as a syntax tree, serialised using JSON
  556. @memberof Guppy
  557. */
  558. Guppy.prototype.syntax_tree = function(){
  559. return this.engine.get_content("ast");
  560. }
  561. /**
  562. Get the content of the editor as a list of equations, serialised
  563. using JSON. For example, `x < y = z` will be returned as `[["<", [["var", "x"], ["var", "y"]]],["=", [["var", "y"], ["var", "z"]]]]
  564. @memberof Guppy
  565. */
  566. Guppy.prototype.equations = function(){
  567. return this.engine.get_content("eqns");
  568. }
  569. /**
  570. Get the content of the editor in a parseable text format.
  571. @memberof Guppy
  572. */
  573. Guppy.prototype.text = function(){
  574. return this.engine.get_content("text");
  575. }
  576. /**
  577. Get the content of the editor in AsciiMath.
  578. @memberof Guppy
  579. */
  580. Guppy.prototype.asciimath = function(){
  581. return this.engine.get_content("asciimath");
  582. }
  583. /**
  584. Get the Doc object representing the editor's contents.
  585. @memberof Guppy
  586. */
  587. Guppy.prototype.doc = function(){
  588. return this.engine.doc;
  589. }
  590. /**
  591. Get the content of the editor as a Javascript function, with
  592. user-supplied interpretations of the various symbols. If not
  593. supplied, default interpretations will be given for the following
  594. symbols: `*,+,/,-,^,sqrt,sin,cos,tan,log`
  595. @param {Object} [evaluators] - An object with a key for each
  596. possible symbol type ("exponential", "integral", etc.)
  597. whose values are functions. These functions take in a single
  598. argument, `args`, which is an array of that symbol's arguments,
  599. and should return a function that takes in an object argument
  600. `vars`. In this inner function, to compute e.g. the sum of the
  601. first and second arguments, you would do
  602. `args[0](vars)+args[1](vars)`. This function should return the
  603. result of that symbol's operation.
  604. @returns {function(Object)} - Returns a function that takes in an
  605. object with a key for each variable in the expression and whose
  606. values are the values that will be passed in for those variables.
  607. In addition, this function is augmented with a `vars` member which
  608. is a list of the variables that appear in the expression.
  609. @memberof Guppy
  610. */
  611. Guppy.prototype.func = function(evaluators){
  612. var res = this.engine.get_content("function", evaluators);
  613. var f = res['function'];
  614. f.vars = res.vars;
  615. return f;
  616. }
  617. /**
  618. Recursively evaluate the syntax tree of the editor's contents using specified functions.
  619. @param {Object} [evaluators] - An object with a key for each
  620. possible symbol type ("exponential", "integral", etc.)
  621. whose values are functions that will be applied whenever that
  622. symbol is encountered in the syntax tree. These functions take a
  623. single argument, `args`, which is a list of the results of
  624. evaluating that symbol's arguments.
  625. @returns - Whatever the `evaluators` function for the root symbol
  626. in the syntax tree returns.
  627. @memberof Guppy
  628. */
  629. Guppy.prototype.evaluate = function(evaluators){
  630. return this.engine.doc.evaluate(evaluators);
  631. }
  632. /**
  633. Get a list of the symbols used in the document, in order of
  634. appearance, with each kind of symbol appearing only once. For
  635. example, a document representing `sin(x^3)+sqrt(x^2+x)` will
  636. have symbols `["sin","exponential","square_root"]`.
  637. @param {String[]} [groups] - A list of the groups whose symbols
  638. may be included in the output. If absent, all symbols in the
  639. document will be returned.
  640. @memberof Guppy
  641. */
  642. Guppy.prototype.symbols_used = function(groups){
  643. return this.engine.doc.get_symbols(groups);
  644. }
  645. /**
  646. Get a list of the variable names used in the document.
  647. @memberof Guppy
  648. */
  649. Guppy.prototype.vars = function(){
  650. return this.engine.get_content("function").vars;
  651. }
  652. /**
  653. Set the content of the document from text in the format outputted by `guppy.text()`.
  654. @param {String} text - A string representing the document to import.
  655. @memberof Guppy
  656. */
  657. Guppy.prototype.import_text = function(text){
  658. return this.engine.import_text(text);
  659. }
  660. /**
  661. Set the content of the document from input text in "semantic
  662. LaTeX" format. That is, all functions are represented as
  663. `\funcname{arg1}{arg2}`. For example,
  664. `\defintegral{1}{2}{x^2}{x}`.
  665. @param {String} text - A string representing the document to import.
  666. @memberof Guppy
  667. */
  668. Guppy.prototype.import_latex = function(text){
  669. return this.engine.import_latex(text);
  670. }
  671. /**
  672. Set the content of the document from XML in the format outputted
  673. by `guppy.xml()`.
  674. @param {String} xml - An XML string representing the document to
  675. import.
  676. @memberof Guppy
  677. */
  678. Guppy.prototype.import_xml = function(xml){
  679. return this.engine.set_content(xml);
  680. }
  681. /**
  682. Import a syntax tree from a JSON object formatted as outputted by `guppy.syntax_tree()`.
  683. @param {Object} tree - A JSON object representing the syntax tree to import.
  684. @memberof Guppy
  685. */
  686. Guppy.prototype.import_syntax_tree = function(tree){
  687. return this.engine.import_ast(tree);
  688. }
  689. /**
  690. Focus this instance of the editor
  691. @memberof Guppy
  692. */
  693. Guppy.prototype.activate = function(){
  694. var newly_active = !(this.editor_active);
  695. Guppy.active_guppy = this;
  696. this.editor_active = true;
  697. this.editor.className = this.editor.className.replace(new RegExp('(\\s|^)guppy_inactive(\\s|$)'),' guppy_active ');
  698. this.editor.focus();
  699. this.render(true);
  700. if(newly_active){
  701. this.engine.fire_event("focus",{"focused":true});
  702. }
  703. }
  704. /**
  705. Unfocus this instance of the editor
  706. @memberof Guppy
  707. */
  708. Guppy.prototype.deactivate = function(){
  709. var newly_inactive = this.editor_active;
  710. this.editor_active = false;
  711. var r1 = new RegExp('(?:\\s|^)guppy_active(?:\\s|$)');
  712. var r2 = new RegExp('(?:\\s|^)guppy_inactive(?:\\s|$)');
  713. if(this.editor.className.match(r1)){
  714. this.editor.className = this.editor.className.replace(r1,' guppy_inactive ');
  715. }
  716. else if(!this.editor.className.match(r2)){
  717. this.editor.className += ' guppy_inactive ';
  718. }
  719. Guppy.kb.shift_down = false;
  720. Guppy.kb.ctrl_down = false;
  721. Guppy.kb.alt_down = false;
  722. this.render();
  723. if(newly_inactive) this.engine.fire_event("focus",{"focused":false});
  724. }
  725. // Keyboard stuff
  726. Guppy.kb = {};
  727. Guppy.kb.is_mouse_down = false;
  728. /* keyboard behaviour definitions */
  729. // keys aside from 0-9,a-z,A-Z
  730. Guppy.kb.k_chars = {
  731. "+":"+",
  732. "-":"-",
  733. "*":"*",
  734. ".":"."
  735. };
  736. Guppy.kb.k_text = {
  737. "/":"/",
  738. "*":"*",
  739. "(":"(",
  740. ")":")",
  741. "<":"<",
  742. ">":">",
  743. "|":"|",
  744. "!":"!",
  745. ",":",",
  746. ".":".",
  747. ";":";",
  748. "=":"=",
  749. "[":"[",
  750. "]":"]",
  751. "@":"@",
  752. "'":"'",
  753. "`":"`",
  754. ":":":",
  755. "\"":"\"",
  756. "?":"?",
  757. "space":" ",
  758. };
  759. Guppy.kb.k_controls = {
  760. "up":"up",
  761. "down":"down",
  762. "right":"right",
  763. "left":"left",
  764. "alt+k":"up",
  765. "alt+j":"down",
  766. "alt+l":"right",
  767. "alt+h":"left",
  768. "space":"spacebar",
  769. "home":"home",
  770. "end":"end",
  771. "backspace":"backspace",
  772. "del":"delete_key",
  773. "mod+a":"sel_all",
  774. "mod+c":"sel_copy",
  775. "mod+x":"sel_cut",
  776. "mod+v":"sel_paste",
  777. "mod+z":"undo",
  778. "mod+y":"redo",
  779. "enter":"done",
  780. "mod+shift+right":"list_extend_copy_right",
  781. "mod+shift+left":"list_extend_copy_left",
  782. ",":"list_extend_right",
  783. ";":"list_extend_down",
  784. "mod+right":"list_extend_right",
  785. "mod+left":"list_extend_left",
  786. "mod+up":"list_extend_up",
  787. "mod+down":"list_extend_down",
  788. "mod+shift+up":"list_extend_copy_up",
  789. "mod+shift+down":"list_extend_copy_down",
  790. "mod+backspace":"list_remove",
  791. "mod+shift+backspace":"list_remove_row",
  792. "shift+left":"sel_left",
  793. "shift+right":"sel_right",
  794. ")":"right_paren",
  795. "\\":"backslash",
  796. "tab":"tab"
  797. };
  798. // Will populate keyboard shortcuts for symbols from symbol files
  799. Guppy.kb.k_syms = {};
  800. var i = 0;
  801. // letters
  802. for(i = 65; i <= 90; i++){
  803. Guppy.kb.k_chars[String.fromCharCode(i).toLowerCase()] = String.fromCharCode(i).toLowerCase();
  804. Guppy.kb.k_chars['shift+'+String.fromCharCode(i).toLowerCase()] = String.fromCharCode(i).toUpperCase();
  805. }
  806. // numbers
  807. for(i = 48; i <= 57; i++)
  808. Guppy.kb.k_chars[String.fromCharCode(i)] = String.fromCharCode(i);
  809. Guppy.register_keyboard_handlers = function(){
  810. Mousetrap.addKeycodes({173: '-'}); // Firefox's special minus (needed for _ = sub binding)
  811. var i, name;
  812. // Pull symbol shortcuts from Symbols:
  813. for(name in Symbols.symbols){
  814. var s = Symbols.symbols[name];
  815. if(s.keys)
  816. for(i = 0; i < s.keys.length; i++)
  817. Guppy.kb.k_syms[s.keys[i]] = s.attrs.type;
  818. }
  819. for(i in Guppy.kb.k_chars)
  820. Mousetrap.bind(i,function(i){ return function(){
  821. if(!Guppy.active_guppy) return true;
  822. Guppy.active_guppy.temp_cursor.node = null;
  823. if(Utils.is_text(Guppy.active_guppy.engine.current) && Guppy.kb.k_text[i]){
  824. Guppy.active_guppy.engine.insert_string(Guppy.kb.k_text[i]);
  825. }
  826. else{
  827. Guppy.active_guppy.engine.insert_string(Guppy.kb.k_chars[i]);
  828. }
  829. Guppy.active_guppy.render(true);
  830. return false;
  831. }}(i));
  832. for(i in Guppy.kb.k_syms)
  833. Mousetrap.bind(i,function(i){ return function(){
  834. if(!Guppy.active_guppy) return true;
  835. Guppy.active_guppy.temp_cursor.node = null;
  836. // We always want to skip using this symbol insertion if
  837. // we are in text mode, and additionally we want only to
  838. // insert the corresponding text if there is an overriding
  839. // text representation in Guppy.kb.k_text
  840. if(Utils.is_text(Guppy.active_guppy.engine.current)){
  841. if(Guppy.kb.k_text[i]) Guppy.active_guppy.engine.insert_string(Guppy.kb.k_text[i]);
  842. }
  843. else{
  844. Guppy.active_guppy.engine.space_caret = 0;
  845. //Guppy.active_guppy.engine.insert_symbol(Guppy.kb.k_syms[i]);
  846. Guppy.active_guppy.engine.insert_symbol(Symbols.lookup_type(Guppy.kb.k_syms[i]));
  847. }
  848. Guppy.active_guppy.render(true);
  849. return false;
  850. }}(i));
  851. for(i in Guppy.kb.k_controls)
  852. Mousetrap.bind(i,function(i){ return function(){
  853. if(!Guppy.active_guppy) return true;
  854. // We want to skip using this control sequence only if there is an overriding text representation in Guppy.kb.k_text
  855. if(Utils.is_text(Guppy.active_guppy.engine.current) && Guppy.kb.k_text[i]){
  856. Guppy.active_guppy.engine.insert_string(Guppy.kb.k_text[i]);
  857. }
  858. else{
  859. Guppy.active_guppy.engine.space_caret = 0;
  860. Guppy.active_guppy.engine[Guppy.kb.k_controls[i]]();
  861. Guppy.active_guppy.temp_cursor.node = null;
  862. }
  863. Guppy.active_guppy.render(["up","down","right","left","home","end","sel_left","sel_right"].indexOf(i) < 0);
  864. //Guppy.active_guppy.render(false);
  865. return false;
  866. }}(i));
  867. for(i in Guppy.kb.k_text)
  868. if(!(Guppy.kb.k_chars[i] || Guppy.kb.k_syms[i] || Guppy.kb.k_controls[i])){
  869. Mousetrap.bind(i,function(i){ return function(){
  870. if(!Guppy.active_guppy) return true;
  871. Guppy.active_guppy.temp_cursor.node = null;
  872. if(Utils.is_text(Guppy.active_guppy.engine.current)){
  873. Guppy.active_guppy.engine.insert_string(Guppy.kb.k_text[i]);
  874. }
  875. Guppy.active_guppy.render(true);
  876. return false;
  877. }}(i));
  878. }
  879. }
  880. Guppy.initialised = false;
  881. Guppy.init = function(){
  882. if(Guppy.initialised) return;
  883. Settings.init(Symbols.symbols);
  884. Guppy.register_keyboard_handlers();
  885. Guppy.initialised = true;
  886. }
  887. export default Guppy;