1 /*
  2     Copyright 2008-2025
  3         Matthias Ehmann,
  4         Michael Gerhaeuser,
  5         Carsten Miller,
  6         Bianca Valentin,
  7         Alfred Wassermann,
  8         Peter Wilfahrt
  9 
 10     This file is part of JSXGraph.
 11 
 12     JSXGraph is free software dual licensed under the GNU LGPL or MIT License.
 13 
 14     You can redistribute it and/or modify it under the terms of the
 15 
 16       * GNU Lesser General Public License as published by
 17         the Free Software Foundation, either version 3 of the License, or
 18         (at your option) any later version
 19       OR
 20       * MIT License: https://github.com/jsxgraph/jsxgraph/blob/master/LICENSE.MIT
 21 
 22     JSXGraph is distributed in the hope that it will be useful,
 23     but WITHOUT ANY WARRANTY; without even the implied warranty of
 24     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 25     GNU Lesser General Public License for more details.
 26 
 27     You should have received a copy of the GNU Lesser General Public License and
 28     the MIT License along with JSXGraph. If not, see <https://www.gnu.org/licenses/>
 29     and <https://opensource.org/licenses/MIT/>.
 30  */
 31 
 32 /*global JXG: true, document:true, jQuery:true, define: true, window: true*/
 33 /*jslint nomen: true, plusplus: true*/
 34 
 35 /**
 36  * @fileoverview The JSXGraph object is defined in this file. JXG.JSXGraph controls all boards.
 37  * It has methods to create, save, load and free boards. Additionally some helper functions are
 38  * defined in this file directly in the JXG namespace.
 39  *
 40  */
 41 
 42 import JXG from "./jxg.js";
 43 import Env from "./utils/env.js";
 44 import Type from "./utils/type.js";
 45 // import Mat from "./math/math.js";
 46 import Board from "./base/board.js";
 47 import FileReader from "./reader/file.js";
 48 import Options from "./options.js";
 49 import SVGRenderer from "./renderer/svg.js";
 50 import VMLRenderer from "./renderer/vml.js";
 51 import CanvasRenderer from "./renderer/canvas.js";
 52 import NoRenderer from "./renderer/no.js";
 53 
 54 /**
 55  * Constructs a new JSXGraph singleton object.
 56  * @class The JXG.JSXGraph singleton stores all properties required
 57  * to load, save, create and free a board.
 58  */
 59 JXG.JSXGraph = {
 60     /**
 61      * Stores the renderer that is used to draw the boards.
 62      * @type String
 63      */
 64     rendererType: (function () {
 65         Options.board.renderer = 'no';
 66 
 67         if (Env.supportsVML()) {
 68             Options.board.renderer = 'vml';
 69             // Ok, this is some real magic going on here. IE/VML always was so
 70             // terribly slow, except in one place: Examples placed in a moodle course
 71             // was almost as fast as in other browsers. So i grabbed all the css and
 72             // lib scripts from our moodle, added them to a jsxgraph example and it
 73             // worked. next step was to strip all the css/lib code which didn't affect
 74             // the VML update speed. The following five lines are what was left after
 75             // the last step and yes - it basically does nothing but reads two
 76             // properties of document.body on every mouse move. why? we don't know. if
 77             // you know, please let us know.
 78             //
 79             // If we want to use the strict mode we have to refactor this a little bit. Let's
 80             // hope the magic isn't gone now. Anywho... it's only useful in old versions of IE
 81             // which should not be used anymore.
 82             document.onmousemove = function () {
 83                 var t;
 84 
 85                 if (document.body) {
 86                     t = document.body.scrollLeft;
 87                     t += document.body.scrollTop;
 88                 }
 89 
 90                 return t;
 91             };
 92         }
 93 
 94         if (Env.supportsCanvas()) {
 95             Options.board.renderer = 'canvas';
 96         }
 97 
 98         if (Env.supportsSVG()) {
 99             Options.board.renderer = 'svg';
100         }
101 
102         // we are inside node
103         if (Env.isNode() && Env.supportsCanvas()) {
104             Options.board.renderer = 'canvas';
105         }
106 
107         if (Env.isNode() || Options.renderer === 'no') {
108             Options.text.display = 'internal';
109             Options.infobox.display = 'internal';
110         }
111 
112         return Options.board.renderer;
113     })(),
114 
115     /**
116      * Initialize the rendering engine
117      *
118      * @param  {String} box        id of or reference to the div element which hosts the JSXGraph construction
119      * @param  {Object} dim        The dimensions of the board
120      * @param  {Object} doc        Usually, this is document object of the browser window.  If false or null, this defaults
121      * to the document object of the browser.
122      * @param  {Object} attrRenderer Attribute 'renderer', specifies the rendering engine. Possible values are 'auto', 'svg',
123      *  'canvas', 'no', and 'vml'.
124      * @returns {Object}           Reference to the rendering engine object.
125      * @private
126      */
127     initRenderer: function (box, dim, doc, attrRenderer) {
128         var boxid, renderer;
129 
130         // Former version:
131         // doc = doc || document
132         if ((!Type.exists(doc) || doc === false) && typeof document === 'object') {
133             doc = document;
134         }
135 
136         if (typeof doc === "object" && box !== null) {
137             boxid = (Type.isString(box)) ? doc.getElementById(box) : box;
138 
139             // Remove everything from the container before initializing the renderer and the board
140             while (boxid.firstChild) {
141                 boxid.removeChild(boxid.firstChild);
142             }
143         } else {
144             boxid = box;
145         }
146 
147         // If attrRenderer is not supplied take the first available renderer
148         if (attrRenderer === undefined || attrRenderer === 'auto') {
149             attrRenderer = this.rendererType;
150         }
151         // create the renderer
152         if (attrRenderer === 'svg') {
153             renderer = new SVGRenderer(boxid, dim);
154         } else if (attrRenderer === 'vml') {
155             renderer = new VMLRenderer(boxid);
156         } else if (attrRenderer === 'canvas') {
157             renderer = new CanvasRenderer(boxid, dim);
158         } else {
159             renderer = new NoRenderer();
160         }
161 
162         return renderer;
163     },
164 
165     /**
166      * Merge the user supplied attributes with the attributes in options.js
167      *
168      * @param {Object} attributes User supplied attributes
169      * @returns {Object} Merged attributes for the board
170      *
171      * @private
172      */
173     _setAttributes: function (attributes, options) {
174         // merge attributes
175         var attr = Type.copyAttributes(attributes, options, 'board'),
176 
177             // These attributes - which are objects - have to be copied separately.
178             list = [
179                 'drag', 'fullscreen',
180                 'intl',
181                 'keyboard', 'logging',
182                 'pan', 'resize',
183                 'screenshot', 'selection',
184                 'zoom'
185             ],
186             len = list.length, i, key;
187 
188         for (i = 0; i < len; i++) {
189             key = list[i];
190             attr[key] = Type.copyAttributes(attr, options, 'board', key);
191         }
192         attr.navbar = Type.copyAttributes(attr.navbar, options, 'navbar');
193 
194         // Treat moveTarget separately, because deepCopy will not work here.
195         // Reason: moveTarget will be an HTML node and it is prevented that Type.deepCopy will copy it.
196         attr.movetarget =
197             attributes.moveTarget || attributes.movetarget || options.board.moveTarget;
198 
199         return attr;
200     },
201 
202     /**
203      * Further initialization of the board. Set some properties from attribute values.
204      *
205      * @param {JXG.Board} board
206      * @param {Object} attr attributes object
207      * @param {Object} dimensions Object containing dimensions of the canvas
208      *
209      * @private
210      */
211     _fillBoard: function (board, attr, dimensions) {
212         board.initInfobox(attr.infobox);
213         board.maxboundingbox = attr.maxboundingbox;
214         board.resizeContainer(dimensions.width, dimensions.height, true, true);
215         board._createSelectionPolygon(attr);
216         board.renderer.drawNavigationBar(board, attr.navbar);
217         JXG.boards[board.id] = board;
218     },
219 
220     /**
221      *
222      * @param {String|Object} container id of or reference to the HTML element in which the board is painted.
223      * @param {Object} attr An object that sets some of the board properties.
224      *
225      * @private
226      */
227     _setARIA: function (container, attr) {
228         var doc = attr.document,
229             node_jsx;
230             // Unused variables, made obsolete in db3e50f4dfa8b86b1ff619b578e243a97b41151c
231             // doc_glob,
232             // newNode,
233             // parent,
234             // id_label,
235             // id_description;
236 
237             if (typeof doc !== 'object') {
238                 if (!Env.isBrowser) {
239                     return;
240                 }
241                 doc = document;
242             }
243 
244         node_jsx = (Type.isString(container)) ? doc.getElementById(container) : container;
245         node_jsx.setAttribute("role", 'region');
246         node_jsx.setAttribute("aria-label", attr.title);              // set by initBoard( {title:})
247 
248         // doc_glob = node_jsx.ownerDocument; // This is the window.document element, needed below.
249         // parent = node_jsx.parentNode;
250 
251     },
252 
253     /**
254      * Remove the two corresponding ARIA divs when freeing a board
255      *
256      * @param {JXG.Board} board
257      *
258      * @private
259      */
260     _removeARIANodes: function (board) {
261         var node, id, doc;
262 
263         doc = board.document || document;
264         if (typeof doc !== 'object') {
265             return;
266         }
267 
268         id = board.containerObj.getAttribute("aria-labelledby");
269         node = doc.getElementById(id);
270         if (node && node.parentNode) {
271             node.parentNode.removeChild(node);
272         }
273         id = board.containerObj.getAttribute("aria-describedby");
274         node = doc.getElementById(id);
275         if (node && node.parentNode) {
276             node.parentNode.removeChild(node);
277         }
278     },
279 
280     /**
281      * Initialize a new board.
282      *
283      * @param {String|Object} box id of or reference to the HTML element in which the board is painted.
284      * @param {Object} attributes An object that sets some of the board properties.
285      * See {@link JXG.Board} for a list of available attributes of the board.
286      * Most of these attributes can also be set via {@link JXG.Options},
287      *
288      * @returns {JXG.Board} Reference to the created board.
289      *
290      * @see JXG.AbstractRenderer#drawNavigationBar
291      * @example
292      * var board = JXG.JSXGraph.initBoard('jxgbox', {
293      *     boundingbox: [-10, 5, 10, -5],
294      *     keepaspectratio: false,
295      *     axis: true
296      * });
297      *
298      * </pre><div id="JXGc0f76e98-20bc-4224-9016-7ffa10770dff" class="jxgbox" style="width: 600px; height: 300px;"></div>
299      * <script type="text/javascript">
300      *     (function() {
301      *         var board = JXG.JSXGraph.initBoard('JXGc0f76e98-20bc-4224-9016-7ffa10770dff', {
302      *         boundingbox: [-10, 5, 10, -5],
303      *         keepaspectratio: false,
304      *         axis: true
305      *     });
306      *
307      *     })();
308      *
309      * </script><pre>
310      *
311      *
312      * @example
313      * const board = JXG.JSXGraph.initBoard('jxgbox', {
314      *   boundingbox: [-10, 10, 10, -10],
315      *   axis: true,
316      *   showCopyright: true,
317      *   showFullscreen: true,
318      *   showScreenshot: false,
319      *   showClearTraces: false,
320      *   showInfobox: false,
321      *   showNavigation: true,
322      *   grid: false,
323      *   defaultAxes: {
324      *     x: {
325      *       withLabel: true,
326      *       label: {
327      *         position: '95% left',
328      *         offset: [-10, 10]
329      *       },
330      *       lastArrow: {
331      *         type: 4,
332      *         size: 10
333      *       }
334      *     },
335      *     y: {
336      *       withLabel: true,
337      *       label: {
338      *         position: '0.90fr right',
339      *         offset: [6, -6]
340      *       },
341      *       lastArrow: {
342      *         type: 4,
343      *         size: 10
344      *       }
345      *     }
346      *   }
347      * });
348      *
349      * </pre><div id="JXG4ced167d-3235-48bc-84e9-1a28fce00f6a" class="jxgbox" style="width: 300px; height: 300px;"></div>
350      * <script type="text/javascript">
351      *     (function() {
352      *         var board = JXG.JSXGraph.initBoard('JXG4ced167d-3235-48bc-84e9-1a28fce00f6a', {
353      *       boundingbox: [-10, 10, 10, -10],
354      *       axis: true,
355      *       showCopyright: true,
356      *       showFullscreen: true,
357      *       showScreenshot: false,
358      *       showClearTraces: false,
359      *       showInfobox: false,
360      *       showNavigation: true,
361      *       grid: false,
362      *       defaultAxes: {
363      *         x: {
364      *           withLabel: true,
365      *           label: {
366      *             position: '95% left',
367      *             offset: [0, 0]
368      *           },
369      *           lastArrow: {
370      *             type: 4,
371      *             size: 10
372      *           }
373      *         },
374      *         y: {
375      *           withLabel: true,
376      *           label: {
377      *             position: '0.90fr right',
378      *             offset: [0, 0]
379      *           },
380      *           lastArrow: {
381      *             type: 4,
382      *             size: 10
383      *           }
384      *         }
385      *       }
386      *     });
387      *
388      *     })();
389      *
390      * </script><pre>
391      * @example
392      * const board = JXG.JSXGraph.initBoard('jxgbox', {
393      *     boundingbox: [-5, 5, 5, -5],
394      *     intl: {
395      *         enabled: false,
396      *         locale: 'en-EN'
397      *     },
398      *     keepaspectratio: true,
399      *     axis: true,
400      *     defaultAxes: {
401      *         x: {
402      *             ticks: {
403      *                 intl: {
404      *                         enabled: true,
405      *                         options: {
406      *                             style: 'unit',
407      *                             unit: 'kilometer-per-hour',
408      *                             unitDisplay: 'narrow'
409      *                         }
410      *                 }
411      *             }
412      *         },
413      *         y: {
414      *             ticks: {
415      *             }
416      *         }
417      *     },
418      *     infobox: {
419      *         fontSize: 20,
420      *         intl: {
421      *             enabled: true,
422      *             options: {
423      *                 minimumFractionDigits: 4,
424      *                 maximumFractionDigits: 5
425      *             }
426      *         }
427      *     }
428      * });
429      *
430      * </pre><div id="JXGdac54e59-f1e8-4fa6-bbcc-7486f7f6f960" class="jxgbox" style="width: 600px; height: 600px;"></div>
431      * <script type="text/javascript">
432      *     (function() {
433      *         var board = JXG.JSXGraph.initBoard('JXGdac54e59-f1e8-4fa6-bbcc-7486f7f6f960', {
434      *         boundingbox: [-5, 5, 5, -5],
435      *         intl: {
436      *             enabled: false,
437      *             locale: 'en-EN'
438      *         },
439      *         keepaspectratio: true,
440      *         axis: true,
441      *         defaultAxes: {
442      *             x: {
443      *                 ticks: {
444      *                     intl: {
445      *                             enabled: true,
446      *                             options: {
447      *                                 style: 'unit',
448      *                                 unit: 'kilometer-per-hour',
449      *                                 unitDisplay: 'narrow'
450      *                             }
451      *                     }
452      *                 }
453      *             },
454      *             y: {
455      *                 ticks: {
456      *                 }
457      *             }
458      *         },
459      *         infobox: {
460      *             fontSize: 20,
461      *             intl: {
462      *                 enabled: true,
463      *                 options: {
464      *                     minimumFractionDigits: 4,
465      *                     maximumFractionDigits: 5
466      *                 }
467      *             }
468      *         }
469      *     });
470      *
471      *     })();
472      *
473      * </script><pre>
474      *
475      *
476      */
477     //  *
478     //  * @param {Array} [attributes.boundingbox=[-5, 5, 5, -5]] An array containing four numbers describing the left, top, right and bottom boundary of the board in user coordinates
479     //  * @param {Boolean} [attributes.keepaspectratio=false] If <tt>true</tt>, the bounding box is adjusted to the same aspect ratio as the aspect ratio of the div containing the board.
480     //  * @param {Boolean} [attributes.showCopyright=false] Show the copyright string in the top left corner.
481     //  * @param {Boolean} [attributes.showNavigation=false] Show the navigation buttons in the bottom right corner.
482     //  * @param {Object} [attributes.zoom] Allow the user to zoom with the mouse wheel or the two-fingers-zoom gesture.
483     //  * @param {Object} [attributes.pan] Allow the user to pan with shift+drag mouse or two-fingers-pan gesture.
484     //  * @param {Object} [attributes.drag] Allow the user to drag objects with a pointer device.
485     //  * @param {Object} [attributes.keyboard] Allow the user to drag objects with arrow keys on keyboard.
486     //  * @param {Boolean} [attributes.axis=false] If set to true, show the axis. Can also be set to an object that is given to both axes as an attribute object.
487     //  * @param {Boolean|Object} [attributes.grid] If set to true, shows the grid. Can also be set to an object that is given to the grid as its attribute object.
488     //  * @param {Boolean} [attributes.registerEvents=true] Register mouse / touch events.
489     initBoard: function (box, attributes) {
490         var originX, originY, unitX, unitY, w, h,
491             offX = 0, offY = 0,
492             renderer, dimensions, bbox,
493             attr, axattr, axattr_x, axattr_y,
494             options,
495             theme = {},
496             board;
497 
498         attributes = attributes || {};
499         // Merge a possible theme
500         if (attributes.theme !== 'default' && Type.exists(JXG.themes[attributes.theme])) {
501             theme = JXG.themes[attributes.theme];
502         }
503         options = Type.deepCopy(Options, theme, true);
504         attr = this._setAttributes(attributes, options);
505 
506         dimensions = Env.getDimensions(box, attr.document);
507 
508         if (attr.unitx || attr.unity) {
509             originX = Type.def(attr.originx, 150);
510             originY = Type.def(attr.originy, 150);
511             unitX = Type.def(attr.unitx, 50);
512             unitY = Type.def(attr.unity, 50);
513         } else {
514             bbox = attr.boundingbox;
515             if (bbox[0] < attr.maxboundingbox[0]) {
516                 bbox[0] = attr.maxboundingbox[0];
517             }
518             if (bbox[1] > attr.maxboundingbox[1]) {
519                 bbox[1] = attr.maxboundingbox[1];
520             }
521             if (bbox[2] > attr.maxboundingbox[2]) {
522                 bbox[2] = attr.maxboundingbox[2];
523             }
524             if (bbox[3] < attr.maxboundingbox[3]) {
525                 bbox[3] = attr.maxboundingbox[3];
526             }
527 
528             // Size of HTML div.
529             // If zero, the size is set to a small value to avoid
530             // division by zero.
531             // w = Math.max(parseInt(dimensions.width, 10), Mat.eps);
532             // h = Math.max(parseInt(dimensions.height, 10), Mat.eps);
533             w = parseInt(dimensions.width, 10);
534             h = parseInt(dimensions.height, 10);
535 
536             if (Type.exists(bbox) && attr.keepaspectratio) {
537                 /*
538                  * If the boundingbox attribute is given and the ratio of height and width of the
539                  * sides defined by the bounding box and the ratio of the dimensions of the div tag
540                  * which contains the board do not coincide, then the smaller side is chosen.
541                  */
542                 unitX = w / (bbox[2] - bbox[0]);
543                 unitY = h / (bbox[1] - bbox[3]);
544 
545                 if (Math.abs(unitX) < Math.abs(unitY)) {
546                     unitY = (Math.abs(unitX) * unitY) / Math.abs(unitY);
547                     // Add the additional units in equal portions above and below
548                     offY = (h / unitY - (bbox[1] - bbox[3])) * 0.5;
549                 } else {
550                     unitX = (Math.abs(unitY) * unitX) / Math.abs(unitX);
551                     // Add the additional units in equal portions left and right
552                     offX = (w / unitX - (bbox[2] - bbox[0])) * 0.5;
553                 }
554             } else {
555                 unitX = w / (bbox[2] - bbox[0]);
556                 unitY = h / (bbox[1] - bbox[3]);
557             }
558             originX = -unitX * (bbox[0] - offX);
559             originY = unitY * (bbox[1] + offY);
560         }
561 
562         renderer = this.initRenderer(box, dimensions, attr.document, attr.renderer);
563         this._setARIA(box, attr);
564 
565         // Create the board.
566         // board.options will contain the user supplied board attributes
567         board = new Board(
568             box,
569             renderer,
570             attr.id,
571             [originX, originY],
572             /*attr.zoomfactor * */ attr.zoomx,
573             /*attr.zoomfactor * */ attr.zoomy,
574             unitX,
575             unitY,
576             dimensions.width,
577             dimensions.height,
578             attr
579         );
580 
581         board.keepaspectratio = attr.keepaspectratio;
582 
583         this._fillBoard(board, attr, dimensions);
584 
585         // Create elements like axes, grid, navigation, ...
586         board.suspendUpdate();
587         attr = board.attr;
588         if (attr.axis) {
589             axattr = typeof attr.axis === "object" ? attr.axis : {};
590 
591             // The defaultAxes attributes are overwritten by user supplied axis object.
592             axattr_x = Type.deepCopy(options.board.defaultaxes.x, axattr);
593             axattr_y = Type.deepCopy(options.board.defaultaxes.y, axattr);
594 
595             // The user supplied defaultAxes attributes are merged in.
596             if (attr.defaultaxes.x) {
597                 axattr_x = Type.deepCopy(axattr_x, attr.defaultaxes.x);
598             }
599             if (attr.defaultaxes.y) {
600                 axattr_y = Type.deepCopy(axattr_y, attr.defaultaxes.y);
601             }
602 
603             board.defaultAxes = {};
604             board.defaultAxes.x = board.create("axis", [[0, 0], [1, 0]], axattr_x);
605             board.defaultAxes.y = board.create("axis", [[0, 0], [0, 1]], axattr_y);
606         }
607         if (attr.grid) {
608             board.create("grid", [], typeof attr.grid === "object" ? attr.grid : {});
609         }
610         board.unsuspendUpdate();
611 
612         return board;
613     },
614 
615     /**
616      * Load a board from a file containing a construction made with either GEONExT,
617      * Intergeo, Geogebra, or Cinderella.
618      * @param {String|Object} box id of or reference to the HTML element in which the board is painted.
619      * @param {String} file base64 encoded string.
620      * @param {String} format containing the file format: 'Geonext' or 'Intergeo'.
621      * @param {Object} attributes Attributes for the board and 'encoding'.
622      *  Compressed files need encoding 'iso-8859-1'. Otherwise it probably is 'utf-8'.
623      * @param {Function} callback
624      * @returns {JXG.Board} Reference to the created board.
625      * @see JXG.FileReader
626      * @see JXG.GeonextReader
627      * @see JXG.GeogebraReader
628      * @see JXG.IntergeoReader
629      * @see JXG.CinderellaReader
630      *
631      * @example
632      * // Uncompressed file
633      * var board = JXG.JSXGraph.loadBoardFromFile('jxgbox', 'filename', 'geonext',
634      *      {encoding: 'utf-8'},
635      *      function (board) { console.log("Done loading"); }
636      * );
637      * // Compressed file
638      * var board = JXG.JSXGraph.loadBoardFromFile('jxgbox', 'filename', 'geonext',
639      *      {encoding: 'iso-8859-1'},
640      *      function (board) { console.log("Done loading"); }
641      * );
642      *
643      * @example
644      * // From <input type="file" id="localfile" />
645      * var file = document.getElementById('localfile').files[0];
646      * JXG.JSXGraph.loadBoardFromFile('jxgbox', file, 'geonext',
647      *      {encoding: 'utf-8'},
648      *      function (board) { console.log("Done loading"); }
649      * );
650      */
651     loadBoardFromFile: function (box, file, format, attributes, callback) {
652         var attr, renderer, board, dimensions, encoding;
653 
654         attributes = attributes || {};
655         attr = this._setAttributes(attributes);
656 
657         dimensions = Env.getDimensions(box, attr.document);
658         renderer = this.initRenderer(box, dimensions, attr.document, attr.renderer);
659         this._setARIA(box, attr);
660 
661         /* User default parameters, in parse* the values in the gxt files are submitted to board */
662         board = new Board(
663             box,
664             renderer,
665             "",
666             [150, 150],
667             1,
668             1,
669             50,
670             50,
671             dimensions.width,
672             dimensions.height,
673             attr
674         );
675         this._fillBoard(board, attr, dimensions);
676         encoding = attr.encoding || "iso-8859-1";
677         FileReader.parseFileContent(file, board, format, true, encoding, callback);
678 
679         return board;
680     },
681 
682     /**
683      * Load a board from a base64 encoded string containing a construction made with either GEONExT,
684      * Intergeo, Geogebra, or Cinderella.
685      * @param {String|Object} box id of or reference to the HTML element in which the board is painted.
686      * @param {String} string base64 encoded string.
687      * @param {String} format containing the file format: 'Geonext', 'Intergeo', 'Geogebra'.
688      * @param {Object} attributes Attributes for the board and 'encoding'.
689      *  Compressed files need encoding 'iso-8859-1'. Otherwise it probably is 'utf-8'.
690      * @param {Function} callback
691      * @returns {JXG.Board} Reference to the created board.
692      * @see JXG.FileReader
693      * @see JXG.GeonextReader
694      * @see JXG.GeogebraReader
695      * @see JXG.IntergeoReader
696      * @see JXG.CinderellaReader
697      */
698     loadBoardFromString: function (box, string, format, attributes, callback) {
699         var attr, renderer, board, dimensions;
700 
701         attributes = attributes || {};
702         attr = this._setAttributes(attributes);
703 
704         dimensions = Env.getDimensions(box, attr.document);
705         renderer = this.initRenderer(box, dimensions, attr.document, attr.renderer);
706         this._setARIA(box, attr);
707 
708         /* User default parameters, in parse* the values in the gxt files are submitted to board */
709         board = new Board(
710             box,
711             renderer,
712             "",
713             [150, 150],
714             1.0,
715             1.0,
716             50,
717             50,
718             dimensions.width,
719             dimensions.height,
720             attr
721         );
722         this._fillBoard(board, attr, dimensions);
723         FileReader.parseString(string, board, format, true, callback);
724 
725         return board;
726     },
727 
728     /**
729      * Delete a board and all its contents.
730      * @param {JXG.Board|String} board id of or reference to the DOM element in which the board is drawn.
731      *
732      */
733     freeBoard: function (board) {
734         var el;
735 
736         if (typeof board === 'string') {
737             board = JXG.boards[board];
738         }
739 
740         this._removeARIANodes(board);
741         board.removeEventHandlers();
742         board.suspendUpdate();
743 
744         // Remove all objects from the board.
745         for (el in board.objects) {
746             if (board.objects.hasOwnProperty(el)) {
747                 board.objects[el].remove();
748             }
749         }
750 
751         // Remove all the other things, left on the board, XHTML save
752         while (board.containerObj.firstChild) {
753             board.containerObj.removeChild(board.containerObj.firstChild);
754         }
755 
756         // Tell the browser the objects aren't needed anymore
757         for (el in board.objects) {
758             if (board.objects.hasOwnProperty(el)) {
759                 delete board.objects[el];
760             }
761         }
762 
763         // Free the renderer and the algebra object
764         delete board.renderer;
765 
766         // clear the creator cache
767         board.jc.creator.clearCache();
768         delete board.jc;
769 
770         // Finally remove the board itself from the boards array
771         delete JXG.boards[board.id];
772     },
773 
774     /**
775      * @deprecated Use JXG#registerElement
776      * @param element
777      * @param creator
778      */
779     registerElement: function (element, creator) {
780         JXG.deprecated("JXG.JSXGraph.registerElement()", "JXG.registerElement()");
781         JXG.registerElement(element, creator);
782     }
783 };
784 
785 // JessieScript/JessieCode startup:
786 // Search for script tags of type text/jessiecode and execute them.
787 if (Env.isBrowser && typeof window === 'object' && typeof document === 'object') {
788     Env.addEvent(window, 'load',
789         function () {
790             var type, i, j, div, id,
791                 board, txt, width, height, maxWidth, aspectRatio,
792                 cssClasses, bbox, axis, grid, code, src, request,
793                 postpone = false,
794 
795                 scripts = document.getElementsByTagName('script'),
796                 init = function (code, type, bbox) {
797                     var board = JXG.JSXGraph.initBoard(id, {
798                         boundingbox: bbox,
799                         keepaspectratio: true,
800                         grid: grid,
801                         axis: axis,
802                         showReload: true
803                     });
804 
805                     if (type.toLowerCase().indexOf('script') > -1) {
806                         board.construct(code);
807                     } else {
808                         try {
809                             board.jc.parse(code);
810                         } catch (e2) {
811                             JXG.debug(e2);
812                         }
813                     }
814 
815                     return board;
816                 },
817                 makeReload = function (board, code, type, bbox) {
818                     return function () {
819                         var newBoard;
820 
821                         JXG.JSXGraph.freeBoard(board);
822                         newBoard = init(code, type, bbox);
823                         newBoard.reload = makeReload(newBoard, code, type, bbox);
824                     };
825                 };
826 
827             for (i = 0; i < scripts.length; i++) {
828                 type = scripts[i].getAttribute("type", false);
829 
830                 if (
831                     Type.exists(type) &&
832                     (type.toLowerCase() === "text/jessiescript" ||
833                         type.toLowerCase() === "jessiescript" ||
834                         type.toLowerCase() === "text/jessiecode" ||
835                         type.toLowerCase() === 'jessiecode')
836                 ) {
837                     cssClasses = scripts[i].getAttribute("class", false) || "";
838                     width = scripts[i].getAttribute("width", false) || "";
839                     height = scripts[i].getAttribute("height", false) || "";
840                     maxWidth = scripts[i].getAttribute("maxwidth", false) || "100%";
841                     aspectRatio = scripts[i].getAttribute("aspectratio", false) || "1/1";
842                     bbox = scripts[i].getAttribute("boundingbox", false) || "-5, 5, 5, -5";
843                     id = scripts[i].getAttribute("container", false);
844                     src = scripts[i].getAttribute("src", false);
845 
846                     bbox = bbox.split(",");
847                     if (bbox.length !== 4) {
848                         bbox = [-5, 5, 5, -5];
849                     } else {
850                         for (j = 0; j < bbox.length; j++) {
851                             bbox[j] = parseFloat(bbox[j]);
852                         }
853                     }
854                     axis = Type.str2Bool(scripts[i].getAttribute("axis", false) || 'false');
855                     grid = Type.str2Bool(scripts[i].getAttribute("grid", false) || 'false');
856 
857                     if (!Type.exists(id)) {
858                         id = "jessiescript_autgen_jxg_" + i;
859                         div = document.createElement('div');
860                         div.setAttribute("id", id);
861 
862                         txt = width !== "" ? "width:" + width + ";" : "";
863                         txt += height !== "" ? "height:" + height + ";" : "";
864                         txt += maxWidth !== "" ? "max-width:" + maxWidth + ";" : "";
865                         txt += aspectRatio !== "" ? "aspect-ratio:" + aspectRatio + ";" : "";
866 
867                         div.setAttribute("style", txt);
868                         div.setAttribute("class", "jxgbox " + cssClasses);
869                         try {
870                             document.body.insertBefore(div, scripts[i]);
871                         } catch (e) {
872                             // there's probably jquery involved...
873                             if (Type.exists(jQuery) && typeof jQuery === 'object') {
874                                 jQuery(div).insertBefore(scripts[i]);
875                             }
876                         }
877                     } else {
878                         div = document.getElementById(id);
879                     }
880 
881                     code = "";
882 
883                     if (Type.exists(src)) {
884                         postpone = true;
885                         request = new XMLHttpRequest();
886                         request.open("GET", src);
887                         request.overrideMimeType("text/plain; charset=x-user-defined");
888                         /* jshint ignore:start */
889                         request.addEventListener("load", function () {
890                             if (this.status < 400) {
891                                 code = this.responseText + "\n" + code;
892                                 board = init(code, type, bbox);
893                                 board.reload = makeReload(board, code, type, bbox);
894                             } else {
895                                 throw new Error(
896                                     "\nJSXGraph: failed to load file",
897                                     src,
898                                     ":",
899                                     this.responseText
900                                 );
901                             }
902                         });
903                         request.addEventListener("error", function (e) {
904                             throw new Error("\nJSXGraph: failed to load file", src, ":", e);
905                         });
906                         /* jshint ignore:end */
907                         request.send();
908                     } else {
909                         postpone = false;
910                     }
911 
912                     if (document.getElementById(id)) {
913                         code = scripts[i].innerHTML;
914                         code = code.replace(/<!\[CDATA\[/g, "").replace(/\]\]>/g, "");
915                         scripts[i].innerHTML = code;
916 
917                         if (!postpone) {
918                             // Do no wait for data from "src" attribute
919                             board = init(code, type, bbox);
920                             board.reload = makeReload(board, code, type, bbox);
921                         }
922                     } else {
923                         JXG.debug(
924                             "JSXGraph: Apparently the div injection failed. Can't create a board, sorry."
925                         );
926                     }
927                 }
928             }
929         },
930         window
931     );
932 }
933 
934 export default JXG.JSXGraph;
935