utils/dump.js

/*
    Copyright 2008-2026
        Matthias Ehmann,
        Michael Gerhaeuser,
        Carsten Miller,
        Bianca Valentin,
        Alfred Wassermann,
        Peter Wilfahrt

    This file is part of JSXGraph.

    JSXGraph is free software dual licensed under the GNU LGPL or MIT License.

    You can redistribute it and/or modify it under the terms of the

      * GNU Lesser General Public License as published by
        the Free Software Foundation, either version 3 of the License, or
        (at your option) any later version
      OR
      * MIT License: https://github.com/jsxgraph/jsxgraph/blob/master/LICENSE.MIT

    JSXGraph is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public License and
    the MIT License along with JSXGraph. If not, see <https://www.gnu.org/licenses/>
    and <https://opensource.org/licenses/MIT/>.
 */

/*global JXG: true, define: true*/
/*jslint nomen: true, plusplus: true*/

/**
 * @fileoverview The JXG.Dump namespace provides methods to save a board to javascript.
 */

import JXG from "../jxg.js";
import Type from "./type.js";

/**
 * The JXG.Dump namespace provides classes and methods to save a board to javascript.
 * @namespace
 */
JXG.Dump = {
    /**
     * Adds markers to every element of the board
     * @param {JXG.Board} board
     * @param {Array|String} markers
     * @param {Array} values
     */
    addMarkers: function (board, markers, values) {
        var e, l, i;

        if (!Type.isArray(markers)) {
            markers = [markers];
        }

        if (!Type.isArray(values)) {
            values = [values];
        }

        l = Math.min(markers.length, values.length);

        markers.length = l;
        values.length = l;

        for (e in board.objects) {
            if (board.objects.hasOwnProperty(e)) {
                for (i = 0; i < l; i++) {
                    board.objects[e][markers[i]] = values[i];
                }
            }
        }
    },

    /**
     * Removes markers from every element on the board.
     * @param {JXG.Board} board
     * @param {Array|String} markers
     */
    deleteMarkers: function (board, markers) {
        var e, l, i;

        if (!Type.isArray(markers)) {
            markers = [markers];
        }

        l = markers.length;

        markers.length = l;

        for (e in board.objects) {
            if (board.objects.hasOwnProperty(e)) {
                for (i = 0; i < l; i++) {
                    delete board.objects[e][markers[i]];
                }
            }
        }
    },

    /**
     * Stringifies a string, i.e. puts some quotation marks around `s` if it is of type string.
     * @param {*} s
     * @returns {String} " + s + "
     */
    str: function (s) {
        if (typeof s === "string" && s.slice(0, 7) !== 'function') {
            s = '"' + s + '"';
        }

        return s;
    },

    /**
     * Recursively determine the difference between objects instance and def.
     * @param {Object} instance Attribute object of the element. Usually a copy is supplied
     * @param {Object} def Default attributes, the instance is compared to
     * @param {String} pre Helper string for debug output
     * @returns Boolean true if all elements can be deleted
     * @private
     */
    _minimizeSubObject: function(instance, def, pre) {
        var p, pl, del,
            deleteAll = true,
            copy = instance;

        for (p in def) {
            if (def.hasOwnProperty(p)) {
                pl = p.toLowerCase();
                // console.log(pre + 'Test', pl, typeof def[p])

                if ((def[p] === copy[pl]) || (!Type.exists(def[p]) && !Type.exists(copy[pl])) ) {
                    // Equality is determined for strings and numbers.
                    // For different arrays or objects, '===' is always false.

                    // console.log(pre + "\tdelete", p)
                    delete copy[pl];
                } else if (Type.isArray(def[p]) && Type.isArray(copy[pl])) {
                    // Compare two arrays
                    // console.log(p, 'arrays', 'instance:', copy[pl], 'default:', def[p])
                    if (Type.cmpArrays(copy[pl], def[p])) {
                        // console.log(pre + "\t\tdelete array", p);
                        delete copy[pl];
                    } else {
                        // console.log(pre + '\t keep array')
                        deleteAll = false;
                    }
                } else {
                    if (Type.exists(def[p]) && typeof def[p] === 'object' &&
                        Type.exists(copy[pl]) && typeof copy[pl] === 'object'
                    ) {
                        // Recursively compare two objects
                        del = this._minimizeSubObject(copy[pl], def[p], pre + '\t');
                        if (del) {
                            // console.log(pre + "--> delete obj", p)
                            delete copy[pl];
                        } else {
                            // console.log(pre + '|', 'keep obj')
                            // console.log('default:', def[p], 'copy:', copy[pl])
                            deleteAll = false;
                        }
                    } else {
                        // console.log(pre + '|', 'keep', pl)
                        deleteAll = false;
                    }
                }
            }
        }
        if (deleteAll && Object.keys(def).length === 0 && Object.keys(copy).length !== 0) {
            // If def is empty and copy is non-empty, we keep copy.
            // This is the case if copy is filled with entries from an inherited element,
            // like label is inherited from text.
            deleteAll = false;
        }

        // console.log(pre + 'deleteAll', deleteAll)
        return deleteAll;
    },

    /**
     * Eliminate default values given by {@link JXG.Options} from the attributes object.
     * @param {Object} instance Attribute object of the element
     * @param {Object} s Arbitrary number of objects `instance` will be compared to. Usually these are
     * sub-objects of the {@link JXG.Board#options} structure.
     * @returns {Object} Minimal attributes object
     */
    minimizeObject: function (instance, s) {
        var i, del,
            def = {},
            copy = Type.deepCopy(instance),
            defaults = [];

        for (i = 1; i < arguments.length; i++) {
            defaults.push(arguments[i]);
        }

        // First, take the generic GeometryElement options ('elements')
        def = Type.deepCopy(def, JXG.Options.elements, true);
        // Second, take the options supplied as parameters
        for (i = defaults.length - 1; i >= 0; i--) {
            def = Type.deepCopy(def, defaults[i], true);
        }

        // console.log('element', copy)
        // console.log('default', def)
        // "copy" is a copy of the attribute object of the element
        del = this._minimizeSubObject(copy, def, ' ');
        // console.log('del', del)
        if (del === true) {
            copy = {};
        }

        /*
        // Original
        for (p in def) {
            if (def.hasOwnProperty(p)) {
                pl = p.toLowerCase();

                // Original. Does not work for gradient: null
                // if (def[p] !== null && typeof def[p] !== "object" && def[p] === copy[pl]) {
                //     delete copy[pl];
                // }
            }
        }
        */
        return copy;
    },

    /**
     * Prepare the attributes object for an element to be dumped as JavaScript or JessieCode code.
     * @param {JXG.Board} board
     * @param {JXG.GeometryElement} obj Geometry element which attributes object is generated
     * @returns {Object} An attributes object.
     */
    prepareAttributes: function (board, obj) {
        var a, s, o;

        o = JXG.Options[obj.elType] || {};
        // console.log('prepareAttributes', obj.id, obj.getAttributes(), o)
        a = this.minimizeObject(obj.getAttributes(), o);

        for (s in obj.subs) {
            if (obj.subs.hasOwnProperty(s)) {
                // console.log('sub', s)
                a[s] = this.minimizeObject(
                    obj.subs[s].getAttributes(),
                    o[s],
                    JXG.Options[obj.subs[s].elType] || {}
                );
                a[s].id = obj.subs[s].id;
                a[s].name = obj.subs[s].name;
            }
        }

        // Handle label separately
        if (Type.exists(a.label)) {
            o = JXG.Options.label || {};
            a.label = this.minimizeObject(a.label, o);
            if (Type.isEmpty(a.label)) {
                delete a.label;
            }
        }

        // Handle layer if it still exists
        if (Type.exists(a.layer)) {
            o = JXG.Options.layer || {};
            if (a.layer === o[obj.elType]) {
                delete a.layer;
            }
        }
        // Handle draft = false separately, see options.js - JXG.Validator
        if (Type.exists(a.draft) && a.draft === false) {
            delete a.draft;
        }

        a.id = obj.id;
        a.name = obj.name;

        return a;
    },

    setBoundingBox: function (methods, board, boardVarName) {
        methods.push({
            obj: boardVarName,
            method: "setBoundingBox",
            params: [board.getBoundingBox(), board.keepaspectratio]
        });

        return methods;
    },

    /**
     * Generate a store-able structure with all elements. This is used by {@link JXG.Dump#toJessie} and
     * {@link JXG.Dump#toJavaScript} to generate the script.
     * @param {JXG.Board} board
     * @param {Boolean} [json=false] If a JavaScript object for JSON should be returned then do
     * not enclose strings in quotes.
     * @returns {Array} An array with all metadata necessary to save the construction.
     * @see JXG.Dump#toJSON
     * @see JXG.Dump#toJavaScript
     * @see JXG.Dump#toJessie
     */
    dump: function (board, json) {
        var e,
            obj,
            element,
            s,
            props = [],
            methods = [],
            elementList = [],
            len = board.objectsList.length;

        this.addMarkers(board, "dumped", false);

        for (e = 0; e < len; e++) {
            obj = board.objectsList[e];
            element = {};

            if (!obj.dumped && obj.dump) {
                element.type = obj.getType();
                element.parents = obj.getParents().slice();
                element.children = [];

                // Extract coordinates of a point
                if (element.type === "point" && element.parents[0] === 1) {
                    element.parents = element.parents.slice(1);
                }

                for (s = 0; s < element.parents.length; s++) {
                    if (
                        !(json === true) && // This is needed in Dump.toJSON()
                        Type.isString(element.parents[s]) &&
                        element.parents[s][0] !== "'" &&
                        element.parents[s][0] !== '"'
                    ) {
                        element.parents[s] = '"' + element.parents[s] + '"';
                    } else if (Type.isArray(element.parents[s])) {
                        element.parents[s] = "[" + element.parents[s].toString() + "]";
                    }
                }

                element.attributes = this.prepareAttributes(board, obj);
                if (element.type === "glider" && obj.onPolygon) {
                    props.push({
                        obj: obj.id,
                        prop: "onPolygon",
                        val: true
                    });
                }

                elementList.push(element);
            }
        }

        this.deleteMarkers(board, 'dumped');

        return {
            elements: elementList,
            props: props,
            methods: methods
        };
    },

    /**
     * Converts an array of different values into a parameter string that can be used by the code generators.
     * @param {Array} a
     * @param {function} converter A function that is used to transform the elements of `a`. Usually
     * {@link JXG.toJSON} or {@link JXG.Dump.toJCAN} are used.
     * @returns {String}
     */
    arrayToParamStr: function (a, converter) {
        var i,
            s = [];

        for (i = 0; i < a.length; i++) {
            s.push(converter.call(this, a[i]));
        }

        return s.join(", ");
    },

    /**
     * Converts a JavaScript object into a JCAN (JessieCode Attribute Notation) string.
     * @param {Object} obj A JavaScript object, functions will be ignored.
     * @returns {String} The given object stored in a JCAN string.
     */
    toJCAN: function (obj) {
        var i, list, prop;

        switch (typeof obj) {
            case "object":
                if (obj) {
                    list = [];

                    if (Type.isArray(obj)) {
                        for (i = 0; i < obj.length; i++) {
                            list.push(this.toJCAN(obj[i]));
                        }

                        return "[" + list.join(",") + "]";
                    }

                    for (prop in obj) {
                        if (obj.hasOwnProperty(prop)) {
                            list.push(prop + ": " + this.toJCAN(obj[prop]));
                        }
                    }

                    return "<<" + list.join(", ") + ">> ";
                }
                return 'null';
            case "string":
                return "'" + obj.replace(/\\/g, "\\\\").replace(/(["'])/g, "\\$1") + "'";
            case "number":
            case "boolean":
                return obj.toString();
            case "null":
                return 'null';
        }
    },

    /**
     * Exports the construction in `board` to JessieCode.
     * @param {JXG.Board} board
     * @param {Boolean} [noAttributes=false] If true, output contains no attributes beside 'id' and 'name'
     * @returns {String} The construction as JessieCode code
     * @see JXG.Dump#dump
     * @see JXG.Dump#toJSON
     * @see JXG.Dump#toJavaScript
     */
    toJessie: function (board, noAttributes) {
        var i, a,
            elements,
            id,
            dump = this.dump(board),
            script = [];

        dump.methods = this.setBoundingBox(dump.methods, board, "$board");

        elements = dump.elements;
        // Delete unwanted attributes
        if (noAttributes === true) {
            for (i = 0; i < elements.length; i++) {
                for (a in elements[i].attributes) {
                    if (elements[i].attributes.hasOwnProperty(a) && a !== 'id' && a !== 'name') {
                        delete elements[i].attributes[a];
                    }
                }
            }
        }

        for (i = 0; i < elements.length; i++) {
            if (elements[i].attributes.name.length > 0) {
                script.push("// " + elements[i].attributes.name);
            }
            script.push(
                "s" + i + " = " + elements[i].type +
                    "(" + elements[i].parents.join(", ") + ") " +
                    this.toJCAN(elements[i].attributes).replace(/\n/, "\\n") + ";"
            );

            if (elements[i].type === 'axis') {
                // Handle the case that remove[All]Ticks had been called.
                id = elements[i].attributes.id;
                if (board.objects[id].defaultTicks === null) {
                    script.push("s" + i + ".removeAllTicks();");
                }
            }
            script.push("");
        }

        for (i = 0; i < dump.methods.length; i++) {
            script.push(
                dump.methods[i].obj +
                    "." +
                    dump.methods[i].method +
                    "(" +
                    this.arrayToParamStr(dump.methods[i].params, this.toJCAN) +
                    ");"
            );
            script.push("");
        }

        for (i = 0; i < dump.props.length; i++) {
            script.push(
                dump.props[i].obj +
                    "." +
                    dump.props[i].prop +
                    " = " +
                    this.toJCAN(dump.props[i].val) +
                    ";"
            );
            script.push("");
        }

        return script.join("\n");
    },

    /**
     * Export the construction as JSON string. Wrapper of {@link JXG.Dump#dump}, i.e.
     * a store-able structure with all elements.
     *
     * @param {JXG.Board} board
     * @param {Boolean} [asObj=false] If false, return a JSON string, else return a JavaScript object.
     * @returns {String} The construction as JSON string (or object)
     *
     * @see JXG.Dump#dump
     * @see JXG.Dump#toJessie
     * @see JXG.Dump#toJavaScript
     */
    toJSON: function(board, asObj) {
        var dump = this.dump(board, true),
            i, el, c,
            elements = dump.elements;

        for (i = 0; i < elements.length; i++) {
            elements[i].properties = {};
            elements[i].ancestors = [];

            el = board.objects[elements[i].attributes.id];
            if (Type.exists(el)) {
                for (c in el.childElements) {
                    if (el.childElements.hasOwnProperty(c) && el.childElements[c].dump) {
                        elements[i].children.push(c);
                    }
                }
                elements[i].children = Type.uniqueArray(elements[i].children);

                // For JSON: draggable is draggable AND visible
                elements[i].properties.isDraggable = el.isDraggable && el.visPropCalc.visible;
                elements[i].properties.elType = el.elType;

                //console.log(el.ancestors)
                for (c in el.ancestors) {
                    if (el.ancestors.hasOwnProperty(c) && el.ancestors[c].dump) {
                        elements[i].ancestors.push(c);
                    }
                }
                elements[i].ancestors = Type.uniqueArray(elements[i].ancestors);
            }
        }
        dump.userLog = board.userLog.slice();

        if (asObj === true) {
            return dump;
        }
        return JSON.stringify(dump);
    },

    /**
     * Exports the construction in `board` to JavaScript.
     * @param {JXG.Board} board
     * @returns {String} The construction as JavaScript code
     * @see JXG.Dump#dump
     * @see JXG.Dump#toJSON
     * @see JXG.Dump#toJessie
     */
    toJavaScript: function (board) {
        var i,
            elements,
            id,
            dump = this.dump(board),
            script = [];

        dump.methods = this.setBoundingBox(dump.methods, board, 'board');

        elements = dump.elements;

        for (i = 0; i < elements.length; i++) {
            script.push(
                'board.create("' +
                    elements[i].type +
                    '", [' +
                    elements[i].parents.join(", ") +
                    "], " +
                    Type.toJSON(elements[i].attributes) +
                    ");"
            );

            if (elements[i].type === 'axis') {
                // Handle the case that remove[All]Ticks had been called.
                id = elements[i].attributes.id;
                if (board.objects[id].defaultTicks === null) {
                    script.push(
                        'board.objects["' +
                            id +
                            '"].removeTicks(board.objects["' +
                            id +
                            '"].defaultTicks);'
                    );
                }
            }
        }

        for (i = 0; i < dump.methods.length; i++) {
            script.push(
                dump.methods[i].obj +
                    "." +
                    dump.methods[i].method +
                    "(" +
                    this.arrayToParamStr(dump.methods[i].params, Type.toJSON) +
                    ");"
            );
            script.push("");
        }

        for (i = 0; i < dump.props.length; i++) {
            script.push(
                dump.props[i].obj +
                    "." +
                    dump.props[i].prop +
                    " = " +
                    Type.toJSON(dump.props[i].val) +
                    ";"
            );
            script.push("");
        }

        return script.join("\n");
    }
};

export default JXG.Dump;