<commit_before>const element = document.documentElement;
const $body = document.getElementsByTagName("body")[0];

// http://tinyurl.com/phansux
export default function viewportDimensions() {
    return {
        width: window.innerWidth || eleement.clientWidth || $body.clientWidth,
        height: window.innerHeight || element.clientHeight || $body.clientHeight
    };
}
<commit_msg>Fixed typo in variable name<commit_after>const element = document.documentElement;
const $body = document.getElementsByTagName("body")[0];

// http://tinyurl.com/phansux
export default function viewportDimensions() {
    return {
        width: window.innerWidth || element.clientWidth || $body.clientWidth,
        height: window.innerHeight || element.clientHeight || $body.clientHeight
    };
}
<|endoftext|>


<commit_before>/*!
 * App and Base Marionette Module
 * base.js
 * http://baycg.com/
 *
 * Copyright 2014, Brett Grimes
 * Licensed under the MIT license.
 * http://www.opensource.org/licenses/mit-license.php
 *
 * Date: 09-Feb-2014
 */

// Create the application instance
App = new Backbone.Marionette.Application();

// Define the Application initialization function
App.addInitializer(function (options) {
    // Define the constants for the application
    App.Constants = {
        DayInMS: 86400000,
        GameDate: new Date(),
        NumberOfMonthsToShow: 3,
        Title: "Major League Baseball Box Scores",
        Teams: {    // This will be filled during the data fetch
            AL: {}, // (Key, Value) => (TeamAbbr, TeamName)
            NL: {}  // (Key, Value) => (TeamAbbr, TeamName)
        },
        Leagues: {
            "mlb": "MLB",
            "aaa": "MILB AAA",
            "nat": "National Team",
            "aax": "MILB AA - Eastern League",
            "afa": "MILB High A - Florida State League",
            "afx": "MILB Low A - Midwest League",
            "asx": "MILB Short A - NY/PA League"
        },
        RefreshTimeoutLimitMS: 10000
    };

    // Add the display region
    App.addRegions({
        main: "#lCenter"
    });

    // Start the base module
    var base = App.module("Base");
    base.start();
});

// Definition for the Base module
// Contains the Controller, Model and Layout for the page
App.module("Base", function (Mod, App, Backbone, Marionette, $, _) {

    // Define the constants for the module
    Mod.Constants = {
        ViewType: {
            Full: "list",
            Summary: "grid"
        }
    };

    // Base.Controller definition
    Mod.Controller = Marionette.Controller.extend({
        // Initialization for the Base.Controller
        initialize: function () {
            // Create an instance of the Base.Layout for the page
            this.scoresLayout = new Mod.Layout({
                model: new Mod.Model()
            });
            // Show the layout in the Application display region
            App.main.show(this.scoresLayout);
        }
    });

    // Intialization for the Module
    Mod.addInitializer(function (options) {
        // Create an instance of the Base.Controller
        Mod.controller = new Mod.Controller();
    });

    // Base.Model definition
    Mod.Model = Backbone.Model.extend({
        defaults: {
            GameDate: new Date(),
            copyright: "",
            League: "mlb"
        }
    });

    // Base.Layout definition
    Mod.Layout = Marionette.Layout.extend({
        // The layout template id
        template: "#mlb-scores-layout",

        // Define the attributes on the main element
        attributes: {
            style: "margin:20px;"
        },

        // Define a header, content and footer region in the Base.Layout
        regions: {
            header: "#mlb-scores-layout-header",
            content: "#mlb-scores-layout-content",
            footer: "#mlb-scores-layout-footer"
        },

        // Initialization of the Base.Layout
        initialize: function () {
            // Create an instance of the MLBScores Module and start it
            this.gamesModule = App.module("MLBScores");
            this.gamesModule.start();

            // Set an event handler for view type changes
            this.listenTo(App.vent, "changed:viewtype", function (viewType) {
                viewType = viewType || this.currentViewType;
                // Swap the content views based on the given view type using the existing model data
                switch (viewType) {
                    default:
                    case Mod.Constants.ViewType.Full:
                        this.content.show(new App.MLBScores.ContentList({
                            model: this.content.currentView.model
                        }));
                        break;
                    case Mod.Constants.ViewType.Summary:
                        this.content.show(new App.MLBScores.ContentGrid({
                            model: this.content.currentView.model
                        }));
                        break;
                }
                // Update the cache of the current view type
                this.currentViewType = viewType;
            }, this);
        },

        // Show the page content in the Base.Layout
        onRender: function () {
            var $window = $(window)
            // Adjust the display height
            this.$el.height($window.height() - 45);  // TODO: this needs adjusting for browsers on iOS

            // Create and show a new instance of the MLBScores.Header view
            this.header.show(new App.MLBScores.Header({
                model: new App.Base.Model()
            }));

            // Create and show a new instance of the MLBScores.Footer view
            this.footer.show(new App.MLBScores.Footer({
                model: new App.Base.Model()
            }));

            // Cache the current content view type
            this.currentViewType = Mod.Constants.ViewType.Full;

            // Create the full list
            this.content.show(new App.MLBScores.ContentList({
                model: new App.MLBScores.Model({
                    GameDate: new Date(App.Constants.GameDate.getTime()),
                    copyright: "",
                    League: "mlb"
                })
            }));

            // Switch to the gird view if on a smaller screen
            if ($window.width() < 1000) {
                App.vent.trigger("changed:viewtype", "grid");
            }
        }
    });
});<commit_msg>Fixing..<commit_after>/*!
 * App and Base Marionette Module
 * base.js
 * http://baycg.com/
 *
 * Copyright 2014, Brett Grimes
 * Licensed under the MIT license.
 * http://www.opensource.org/licenses/mit-license.php
 *
 * Date: 09-Feb-2014
 */

// Create the application instance
App = new Backbone.Marionette.Application();

// Define the Application initialization function
App.addInitializer(function (options) {
    // Define the constants for the application
    App.Constants = {
        DayInMS: 86400000,
        GameDate: new Date(),
        NumberOfMonthsToShow: 3,
        Title: "Major League Baseball Box Scores",
        Teams: {    // This will be filled during the data fetch
            AL: {}, // (Key, Value) => (TeamAbbr, TeamName)
            NL: {}  // (Key, Value) => (TeamAbbr, TeamName)
        },
        Leagues: {
            "mlb": "MLB",
            "aaa": "MILB AAA",
            "nat": "National Team",
            "aax": "MILB AA - Eastern League",
            "afa": "MILB High A - Florida State League",
            "afx": "MILB Low A - Midwest League",
            "asx": "MILB Short A - NY/PA League"
        },
        RefreshTimeoutLimitMS: 10000
    };

    // Add the display region
    App.addRegions({
        main: "#lCenter"
    });

    // Start the base module
    var base = App.module("Base");
    base.start();
});

// Definition for the Base module
// Contains the Controller, Model and Layout for the page
App.module("Base", function (Mod, App, Backbone, Marionette, $, _) {

    // Define the constants for the module
    Mod.Constants = {
        ViewType: {
            Full: "list",
            Summary: "grid"
        }
    };

    // Base.Controller definition
    Mod.Controller = Marionette.Controller.extend({
        // Initialization for the Base.Controller
        initialize: function () {
            // Create an instance of the Base.Layout for the page
            this.scoresLayout = new Mod.Layout({
                model: new Mod.Model()
            });
            // Show the layout in the Application display region
            App.main.show(this.scoresLayout);
        }
    });

    // Intialization for the Module
    Mod.addInitializer(function (options) {
        // Create an instance of the Base.Controller
        Mod.controller = new Mod.Controller();
    });

    // Base.Model definition
    Mod.Model = Backbone.Model.extend({
        defaults: {
            GameDate: new Date(),
            copyright: "",
            League: "mlb"
        }
    });

    // Base.Layout definition
    Mod.Layout = Marionette.Layout.extend({
        // The layout template id
        template: "#mlb-scores-layout",

        // Define the attributes on the main element
        attributes: {
            style: "margin:20px;"
        },

        // Define a header, content and footer region in the Base.Layout
        regions: {
            header: "#mlb-scores-layout-header",
            content: "#mlb-scores-layout-content",
            footer: "#mlb-scores-layout-footer"
        },

        // Initialization of the Base.Layout
        initialize: function () {
            // Create an instance of the MLBScores Module and start it
            this.gamesModule = App.module("MLBScores");
            this.gamesModule.start();

            // Set an event handler for view type changes
            this.listenTo(App.vent, "changed:viewtype", function (viewType) {
                viewType = viewType || this.currentViewType;
                // Swap the content views based on the given view type using the existing model data
                switch (viewType) {
                    case Mod.Constants.ViewType.Full:
                        this.content.show(new App.MLBScores.ContentList({
                            model: this.content.currentView.model
                        }));
                        break;
                    case Mod.Constants.ViewType.Summary:
                        this.content.show(new App.MLBScores.ContentGrid({
                            model: this.content.currentView.model
                        }));
                        break;
                }
                // Update the cache of the current view type
                this.currentViewType = viewType;
            }, this);
        },

        // Show the page content in the Base.Layout
        onRender: function () {
            var $window = $(window)
            // Adjust the display height
            this.$el.height($window.height() - 45);  // TODO: this needs adjusting for browsers on iOS

            // Create and show a new instance of the MLBScores.Header view
            this.header.show(new App.MLBScores.Header({
                model: new App.Base.Model()
            }));

            // Create and show a new instance of the MLBScores.Footer view
            this.footer.show(new App.MLBScores.Footer({
                model: new App.Base.Model()
            }));

            // Cache the current content view type
            this.currentViewType = Mod.Constants.ViewType.Full;

            // Create the full list
            this.content.show(new App.MLBScores.ContentList({
                model: new App.MLBScores.Model({
                    GameDate: new Date(App.Constants.GameDate.getTime()),
                    copyright: "",
                    League: "mlb"
                })
            }));

            // Switch to the gird view if on a smaller screen
            if ($window.width() < 1000) {
                this.header.ui.grid.click();
            }
        }
    });
});<|endoftext|>


<commit_before>FuzzyOctoTribble.DialogBox = function (spec, my) {
    var that = {};
    var dialog = spec.dialogContent;
    var onComplete = spec.onComplete;
    var displayedText = "";
    my = my || {};

    var $dialogContainer = $(document.createElement('div'));
    $dialogContainer.addClass('dialog-container text-font');
    var $innerDialog = $(document.createElement('div'));
    $dialogContainer.append($innerDialog);
    var $next = $(document.createElement('div'));
    $next.text('>');
    $next.css('position', 'absolute');
    $next.css('bottom', '0px');
    $next.css('right', '10px');
    $next.css('font-size', '30px');
    $next.hide();
    $dialogContainer.append($next);
    $('.game-window').append($dialogContainer);

    var showDialog = function () {
        $innerDialog.empty();
        var writer = dialog.split(' ');
        var showArrow = false;
        for (var i = 0; i < writer.length; i++) {
            var currentText = $innerDialog.text();
            $innerDialog.text(currentText + ' ' + writer[i]);
            if ($innerDialog.innerHeight() > $dialogContainer.height()) {
                $innerDialog.text(currentText);
                writer.splice(0, i);
                showArrow = true;
                dialog = writer.join(' ');
                break;
            }
        }

        displayedText = $innerDialog.text();

        if (showArrow) {
            $next.show();
        }
        else {
            $next.hide();
            dialog = '';
        }

    }

    var nextDialog = function () {
        if (dialog) {
            showDialog();
        }
        else {
            $dialogContainer.remove();
            $(window).unbind('resize', resizeDialog);
            if (that.onComplete) {
                that.onComplete();
            }
            if (onComplete) {
                onComplete();
            }
        }
    }

    resizeDialog = function () {
        if (dialog) {
            dialog = displayedText + ' ' + dialog;
        } else {
            dialog = displayedText;
        }

        nextDialog();
    }

    $(window).bind('resize', resizeDialog);

    that.confirm = function () {
        nextDialog();
    }

    showDialog();

    return that;
}<commit_msg>Added ability to click through dialog<commit_after>FuzzyOctoTribble.DialogBox = function (spec, my) {
    var that = {};
    var dialog = spec.dialogContent;
    var onComplete = spec.onComplete;
    var displayedText = "";
    my = my || {};

    var $dialogContainer = $(document.createElement('div'));
    $dialogContainer.addClass('dialog-container text-font');
    var $innerDialog = $(document.createElement('div'));
    $dialogContainer.append($innerDialog);
    var $next = $(document.createElement('div'));
    $next.text('>');
    $next.css('position', 'absolute');
    $next.css('bottom', '0px');
    $next.css('right', '10px');
    $next.css('font-size', '30px');
    $next.hide();
    $dialogContainer.append($next);
    $('.game-window').append($dialogContainer);

    var showDialog = function () {
        $innerDialog.empty();
        var writer = dialog.split(' ');
        var showArrow = false;
        for (var i = 0; i < writer.length; i++) {
            var currentText = $innerDialog.text();
            $innerDialog.text(currentText + ' ' + writer[i]);
            if ($innerDialog.innerHeight() > $dialogContainer.height()) {
                $innerDialog.text(currentText);
                writer.splice(0, i);
                showArrow = true;
                dialog = writer.join(' ');
                break;
            }
        }

        displayedText = $innerDialog.text();

        if (showArrow) {
            $next.show();
        }
        else {
            $next.hide();
            dialog = '';
        }

    }

    var nextDialog = function () {
        if (dialog) {
            showDialog();
        }
        else {
            $dialogContainer.remove();
            $(window).unbind('resize', resizeDialog);
            if (that.onComplete) {
                that.onComplete();
            }
            if (onComplete) {
                onComplete();
            }
        }
    }

    resizeDialog = function () {
        if (dialog) {
            dialog = displayedText + ' ' + dialog;
        } else {
            dialog = displayedText;
        }

        nextDialog();
    }

    $(window).bind('resize', resizeDialog);

    that.confirm = function () {
        nextDialog();
    }

    $dialogContainer.on('click', function () {
        that.confirm();
    });

    showDialog();

    return that;
}<|endoftext|>


<commit_before>/**
 * [define_activity.js]
    encoding=utf-8
 */

 var ACTIVITY = {
    "GOTO_BED" : 101,
    "GET_UP" : 102
 };
 if( !this.window ){
     exports.ACTIVITY = ACTIVITY;
 }

<commit_msg>使わなくなったファイルを削除<commit_after><|endoftext|>


<commit_before>import {divideURL} from '../utils/utils';
import CatalogueFactory from '../catalogue-factory/CatalogueDataObjectFactory';
import persistenceManager from '../persistence/PersistenceManager';

class RuntimeCatalogue {

    constructor(runtimeFactory) {
        if (!runtimeFactory) throw Error('The catalogue needs the runtimeFactory');

        let _this = this;
        _this._factory = new CatalogueFactory(false, undefined);
        _this.httpRequest = runtimeFactory.createHttpRequest();
    }

    /**
     * Get a Catalogue Data Object (Descriptor) from a URL, and construct it using the provided function
     * @param {String} descriptorURL - e.g. mydomain.com/.well-known/hyperty/MyHyperty
     * @param {function} createFunc - e.g. _createHyperty
     * @returns {Promise}
     */
    getDescriptor(descriptorURL, createFunc) {
        let _this = this;
        // console.log("getDescriptor", descriptorURL);

        return new Promise(function (resolve, reject) {

            _this.httpRequest.get(descriptorURL + "/version").then(function (result) {
                if (persistenceManager.getVersion(descriptorURL) >= result) {
                    // return saved version
                    console.log("returning saved version:", persistenceManager.get(descriptorURL));
                    resolve(createFunc(_this, persistenceManager.get(descriptorURL)))
                } else {
                    // request the json
                    _this.httpRequest.get(descriptorURL).then(function (result) {
                        result = JSON.parse(result);

                        if (result["ERROR"]) {
                            // TODO handle error properly
                            reject(result);
                        } else {
                            // console.log("creating descriptor based on: ", result);
                            let descriptor = createFunc(_this, result);
                            persistenceManager.set(descriptorURL, descriptor.version, result);
                            // console.log("created descriptor object:", hyperty);
                            resolve(descriptor);
                        }
                    });
                }
            });
        });
    }

    /**
     * Get HypertyDescriptor
     * @param hypertyURL - e.g. mydomain.com/.well-known/hyperty/MyHyperty
     * @returns {Promise}
     */
    getHypertyDescriptor(hypertyURL) {
        let _this = this;
        return _this.getDescriptor(hypertyURL, _this._createHyperty)
    }

    /**
     * Get StubDescriptor
     * @param stubURL - e.g. mydomain.com/.well-known/protostub/MyProtostub
     * @returns {Promise}
     */
    getStubDescriptor(stubURL) {
        let _this = this;
        return _this.getDescriptor(runtimeURL, _this._createStub)
    }

    /**
     * Get RuntimeDescriptor
     * @param runtimeURL - e.g. mydomain.com/.well-known/runtime/MyRuntime
     * @returns {Promise}
     */
    getRuntimeDescriptor(runtimeURL) {
        let _this = this;
        return _this.getDescriptor(runtimeURL, _this._createRuntimeDescriptor)
    }

    /**
     * Get DataSchemaDescriptor
     * @param dataSchemaURL - e.g. mydomain.com/.well-known/dataschema/MyDataSchema
     * @returns {Promise}
     */
    getDataSchemaDescriptor(dataSchemaURL) {
        let _this = this;
        return _this.getDescriptor(runtimeURL, _this._createDataSchema)
    }

    /**
     * Get IDPProxyDescriptor
     * @param idpProxyURL - e.g. mydomain.com/.well-known/idp-proxy/MyProxy
     * @returns {Promise}
     */
    getIdpProxyDescriptor(idpProxyURL) {
        let _this = this;
        return _this.getDescriptor(runtimeURL, _this._createIdpProxy)
    }

    /**
     * Create HypertyDescriptor based on raw object that contains its attributes
     * @param _this
     * @param rawHyperty
     * @returns {HypertyDescriptor}
     */
    _createHyperty(_this, rawHyperty) {
        // create the descriptor
        let hyperty = _this._factory.createHypertyDescriptorObject(
            rawHyperty["cguid"],
            rawHyperty["version"],
            rawHyperty["objectName"],
            rawHyperty["description"],
            rawHyperty["language"],
            rawHyperty["sourcePackageURL"],
            rawHyperty["type"] || rawHyperty["hypertyType"],
            rawHyperty["dataObjects"]
        );

        // optional fields
        hyperty.configuration = rawHyperty["configuration"];
        hyperty.constraints = rawHyperty["constraints"];
        hyperty.messageSchema = rawHyperty["messageSchema"];
        hyperty.policies = rawHyperty["policies"];
        hyperty.signature = rawHyperty["signature"];

        // parse and attach sourcePackage
        let sourcePackage = rawHyperty["sourcePackage"];
        if (sourcePackage) {
            // console.log("hyperty has sourcePackage:", sourcePackage);
            hyperty.sourcePackage = _this._createSourcePackage(_this, sourcePackage);
        }

        return hyperty;
    }

    /**
     * Create ProtocolStubDescriptor based on raw object that contains its attributes
     * @param _this
     * @param rawStub
     * @returns {ProtocolStubDescriptor}
     */
    _createStub(_this, rawStub) {
        // console.log("creating stub descriptor based on: ", rawStub);

        // create the descriptor
        let stub = _this._factory.createProtoStubDescriptorObject(
            rawStub["cguid"],
            rawStub["version"],
            rawStub["objectName"],
            rawStub["description"],
            rawStub["language"],
            rawStub["sourcePackageURL"],
            rawStub["messageSchemas"],
            rawStub["configuration"],
            rawStub["constraints"]
        );

        // optional fields
        stub.signature = rawStub["signature"];

        // parse and attach the sourcePackage
        let sourcePackage = rawStub["sourcePackage"];
        if (sourcePackage) {
            sourcePackage = _this._createSourcePackage(_this, sourcePackage);
            stub.sourcePackage = sourcePackage;
        }

        return stub;
    }

    /**
     * Create HypertyRuntimeDescriptor based on raw object that contains its attributes
     * @param _this
     * @param rawRuntime
     * @returns {HypertyRuntimeDescriptor}
     */
    _createRuntimeDescriptor(_this, rawRuntime) {
        // parse capabilities first
        try {
            rawRuntime["hypertyCapabilities"] = JSON.parse(rawRuntime["hypertyCapabilities"]);
            rawRuntime["protocolCapabilities"] = JSON.parse(rawRuntime["protocolCapabilities"]);
        } catch (e) {
            // already json object
        }
        console.log("creating runtime descriptor based on: ", rawRuntime);

        // create the descriptor
        let runtime = _this._factory.createHypertyRuntimeDescriptorObject(
            rawRuntime["cguid"],
            rawRuntime["version"],
            rawRuntime["objectName"],
            rawRuntime["description"],
            rawRuntime["language"],
            rawRuntime["sourcePackageURL"],
            rawRuntime["type"] || rawRuntime["runtimeType"],
            rawRuntime["hypertyCapabilities"],
            rawRuntime["protocolCapabilities"]
        );

        // optional fields
        runtime.signature = rawRuntime["signature"];

        // parse and attach sourcePackage
        let sourcePackage = rawRuntime["sourcePackage"];
        if (sourcePackage) {
            // console.log("runtime has sourcePackage:", sourcePackage);
            runtime.sourcePackage = _this._createSourcePackage(_this, sourcePackage);
        }
        return runtime;
    }

    /**
     * Create DataObjectSchema based on raw object that contains its attributes
     * @param _this
     * @param rawSchema
     * @returns {DataObjectSchema}
     */
    _createDataSchema(_this, rawSchema) {
        console.log("creating dataSchema based on: ", rawSchema);

        // FIXME: accessControlPolicy field not needed?
        // create the descriptor
        let dataSchema = _this._factory.createDataObjectSchema(
            rawSchema["cguid"],
            rawSchema["version"],
            rawSchema["objectName"],
            rawSchema["description"],
            rawSchema["language"],
            rawSchema["sourcePackageURL"]
        );

        // optional fields
        dataSchema.signature = rawSchema["signature"];

        // parse and attach sourcePackage
        let sourcePackage = rawSchema["sourcePackage"];
        if (sourcePackage) {
            // console.log("dataSchema has sourcePackage:", sourcePackage);
            dataSchema.sourcePackage = _this._createSourcePackage(_this, sourcePackage);
        }

        console.log("created dataSchema descriptor object:", dataSchema);
        return dataSchema;
    }

    /**
     * Create ProtocolStubDescriptor based on raw object that contains its attributes
     * @param _this
     * @param rawProxy
     * @returns {ProtocolStubDescriptor}
     */
    _createIdpProxy(_this, rawProxy) {
        // console.log("creating idpproxy descriptor based on: ", rawProxy);

        // create the descriptor
        let idpproxy = _this._factory.createProtoStubDescriptorObject(
            rawProxy["cguid"],
            rawProxy["version"],
            rawProxy["objectName"],
            rawProxy["description"],
            rawProxy["language"],
            rawProxy["sourcePackageURL"],
            rawProxy["messageSchemas"],
            rawProxy["configuration"],
            rawProxy["constraints"]
        );

        // optional fields
        idpproxy.signature = rawProxy["signature"];

        // parse and attach the sourcePackage
        let sourcePackage = rawProxy["sourcePackage"];
        if (sourcePackage) {
            sourcePackage = _this._createSourcePackage(_this, sourcePackage);
            idpproxy.sourcePackage = sourcePackage;
        }

        return idpproxy;
    }

    _createSourcePackage(_this, sp) {
        //console.log("creating sourcePackage. factory:", factory, ", raw package:", sp);
        try {
            sp = JSON.parse(sp);
        } catch (e) {
            console.log("parsing sourcePackage failed. already parsed? -> ", sp);
        }

        // check encoding
        if (sp["encoding"] === "base64") {
            sp["sourceCode"] = atob(sp["sourceCode"]);
        }

        let sourcePackage = _this.factory.createSourcePackage(sp["sourceCodeClassname"], sp["sourceCode"]);
        if (sp["encoding"])
            sourcePackage.encoding = sp["encoding"];

        if (sp["signature"])
            sourcePackage.signature = sp["signature"];

        return sourcePackage;
    }

    /**
     * Get source Package from a URL
     * @param sourcePackageURL - e.g. mydomain.com/.well-known/hyperty/MyHyperty/sourcePackage
     * @returns {Promise}
     */
    getSourcePackageFromURL(sourcePackageURL) {
        let _this = this;

        console.log("getting sourcePackage from:", sourcePackageURL);
        console.warn("-------------------------------------------------------------------------------------------");
        console.warn("ATTENTION: This function may fail if the sourceCode of the the sourcePackage is very large!");
        console.warn("-------------------------------------------------------------------------------------------");

        return new Promise(function (resolve, reject) {
            _this.httpRequest.get(sourcePackageURL).then(function (result) {
                //console.log("got raw sourcePackage:", result);
                if (result["ERROR"]) {
                    // TODO handle error properly
                    reject(result);
                } else {
                    result = JSON.parse(result);
                    let sourcePackage = _this._createSourcePackage(_this, result);
                    resolve(sourcePackage);
                }
            }).catch(function (reason) {
                reject(reason);
            });

        });

    }

    /**
     * Returns the sourceCode of a given descriptor
     * @param {CatalogueDataObject} descriptor - Catalogue Object that was retrieved using e.g. getHypertyDescriptor()
     * @returns {Promise}
     */
    getSourceCodeFromDescriptor(descriptor) {
        let _this = this;
        return new Promise(function (resolve, reject) {
            if (descriptor.sourcePackage) {
                //console.log("descriptor has sourcePackage");
                //console.log("returning sourceCode:", descriptor.sourcePackage.sourceCode);
                resolve(descriptor.sourcePackage.sourceCode);
            } else {
                if (persistenceManager.getVersion(descriptor.sourcePackageURL + "/sourceCode") >= descriptor.version) {
                    console.log("returning cached version from persistence manager");
                    resolve(persistenceManager.get(descriptor.sourcePackageURL + "/sourceCode"));
                } else {
                    _this.httpRequest.get(descriptor.sourcePackageURL + "/sourceCode").then(function (sourceCode) {
                        if (sourceCode["ERROR"]) {
                            // TODO handle error properly
                            reject(sourceCode);
                        } else {
                            persistenceManager.set(descriptor.sourcePackageURL + "/sourceCode", descriptor.version, sourceCode);
                            resolve(sourceCode);
                        }
                    });
                }
            }
        });
    }

    set runtimeURL(runtimeURL) {
        let _this = this;
        _this._runtimeURL = runtimeURL;
    }

    get runtimeURL() {
        let _this = this;
        return _this._runtimeURL;
    }

    deleteFromPM(url) {
        persistenceManager.delete(url);
    }

}

export default RuntimeCatalogue;
<commit_msg>Update RuntimeCatalogue.js<commit_after>import {divideURL} from '../utils/utils';
import CatalogueFactory from '../catalogue-factory/CatalogueDataObjectFactory';
import persistenceManager from '../persistence/PersistenceManager';

class RuntimeCatalogue {

    constructor(runtimeFactory) {
        if (!runtimeFactory) throw Error('The catalogue needs the runtimeFactory');

        let _this = this;
        _this._factory = new CatalogueFactory(false, undefined);
        _this.httpRequest = runtimeFactory.createHttpRequest();
    }

    /**
     * Get a Catalogue Data Object (Descriptor) from a URL, and construct it using the provided function
     * @param {String} descriptorURL - e.g. mydomain.com/.well-known/hyperty/MyHyperty
     * @param {function} createFunc - e.g. _createHyperty
     * @returns {Promise}
     */
    getDescriptor(descriptorURL, createFunc) {
        let _this = this;
        // console.log("getDescriptor", descriptorURL);

        return new Promise(function (resolve, reject) {

            _this.httpRequest.get(descriptorURL + "/version").then(function (result) {
                if (persistenceManager.getVersion(descriptorURL) >= result) {
                    // return saved version
                    console.log("returning saved version:", persistenceManager.get(descriptorURL));
                    resolve(createFunc(_this, persistenceManager.get(descriptorURL)))
                } else {
                    // request the json
                    _this.httpRequest.get(descriptorURL).then(function (result) {
                        result = JSON.parse(result);

                        if (result["ERROR"]) {
                            // TODO handle error properly
                            reject(result);
                        } else {
                            // console.log("creating descriptor based on: ", result);
                            let descriptor = createFunc(_this, result);
                            persistenceManager.set(descriptorURL, descriptor.version, result);
                            // console.log("created descriptor object:", hyperty);
                            resolve(descriptor);
                        }
                    });
                }
            });
        });
    }

    /**
     * Get HypertyDescriptor
     * @param hypertyURL - e.g. mydomain.com/.well-known/hyperty/MyHyperty
     * @returns {Promise}
     */
    getHypertyDescriptor(hypertyURL) {
        let _this = this;
        return _this.getDescriptor(hypertyURL, _this._createHyperty)
    }

    /**
     * Get StubDescriptor
     * @param stubURL - e.g. mydomain.com/.well-known/protostub/MyProtostub
     * @returns {Promise}
     */
    getStubDescriptor(stubURL) {
        let _this = this;
        return _this.getDescriptor(runtimeURL, _this._createStub)
    }

    /**
     * Get RuntimeDescriptor
     * @param runtimeURL - e.g. mydomain.com/.well-known/runtime/MyRuntime
     * @returns {Promise}
     */
    getRuntimeDescriptor(runtimeURL) {
        let _this = this;
        return _this.getDescriptor(runtimeURL, _this._createRuntimeDescriptor)
    }

    /**
     * Get DataSchemaDescriptor
     * @param dataSchemaURL - e.g. mydomain.com/.well-known/dataschema/MyDataSchema
     * @returns {Promise}
     */
    getDataSchemaDescriptor(dataSchemaURL) {
        let _this = this;
        return _this.getDescriptor(runtimeURL, _this._createDataSchema)
    }

    /**
     * Get IDPProxyDescriptor
     * @param idpProxyURL - e.g. mydomain.com/.well-known/idp-proxy/MyProxy
     * @returns {Promise}
     */
    getIdpProxyDescriptor(idpProxyURL) {
        let _this = this;
        return _this.getDescriptor(runtimeURL, _this._createIdpProxy)
    }

    /**
     * Create HypertyDescriptor based on raw object that contains its attributes
     * @param _this
     * @param rawHyperty
     * @returns {HypertyDescriptor}
     */
    _createHyperty(_this, rawHyperty) {
        // create the descriptor
        let hyperty = _this._factory.createHypertyDescriptorObject(
            rawHyperty["cguid"],
            rawHyperty["version"],
            rawHyperty["objectName"],
            rawHyperty["description"],
            rawHyperty["language"],
            rawHyperty["sourcePackageURL"],
            rawHyperty["type"] || rawHyperty["hypertyType"],
            rawHyperty["dataObjects"]
        );

        // optional fields
        hyperty.configuration = rawHyperty["configuration"];
        hyperty.constraints = rawHyperty["constraints"];
        hyperty.messageSchema = rawHyperty["messageSchema"];
        hyperty.policies = rawHyperty["policies"];
        hyperty.signature = rawHyperty["signature"];

        // parse and attach sourcePackage
        let sourcePackage = rawHyperty["sourcePackage"];
        if (sourcePackage) {
            // console.log("hyperty has sourcePackage:", sourcePackage);
            hyperty.sourcePackage = _this._createSourcePackage(_this, sourcePackage);
        }

        return hyperty;
    }

    /**
     * Create ProtocolStubDescriptor based on raw object that contains its attributes
     * @param _this
     * @param rawStub
     * @returns {ProtocolStubDescriptor}
     */
    _createStub(_this, rawStub) {
        // console.log("creating stub descriptor based on: ", rawStub);

        // create the descriptor
        let stub = _this._factory.createProtoStubDescriptorObject(
            rawStub["cguid"],
            rawStub["version"],
            rawStub["objectName"],
            rawStub["description"],
            rawStub["language"],
            rawStub["sourcePackageURL"],
            rawStub["messageSchemas"],
            rawStub["configuration"],
            rawStub["constraints"]
        );

        // optional fields
        stub.signature = rawStub["signature"];

        // parse and attach the sourcePackage
        let sourcePackage = rawStub["sourcePackage"];
        if (sourcePackage) {
            sourcePackage = _this._createSourcePackage(_this, sourcePackage);
            stub.sourcePackage = sourcePackage;
        }

        return stub;
    }

    /**
     * Create HypertyRuntimeDescriptor based on raw object that contains its attributes
     * @param _this
     * @param rawRuntime
     * @returns {HypertyRuntimeDescriptor}
     */
    _createRuntimeDescriptor(_this, rawRuntime) {
        // parse capabilities first
        try {
            rawRuntime["hypertyCapabilities"] = JSON.parse(rawRuntime["hypertyCapabilities"]);
            rawRuntime["protocolCapabilities"] = JSON.parse(rawRuntime["protocolCapabilities"]);
        } catch (e) {
            // already json object
        }
        console.log("creating runtime descriptor based on: ", rawRuntime);

        // create the descriptor
        let runtime = _this._factory.createHypertyRuntimeDescriptorObject(
            rawRuntime["cguid"],
            rawRuntime["version"],
            rawRuntime["objectName"],
            rawRuntime["description"],
            rawRuntime["language"],
            rawRuntime["sourcePackageURL"],
            rawRuntime["type"] || rawRuntime["runtimeType"],
            rawRuntime["hypertyCapabilities"],
            rawRuntime["protocolCapabilities"]
        );

        // optional fields
        runtime.signature = rawRuntime["signature"];

        // parse and attach sourcePackage
        let sourcePackage = rawRuntime["sourcePackage"];
        if (sourcePackage) {
            // console.log("runtime has sourcePackage:", sourcePackage);
            runtime.sourcePackage = _this._createSourcePackage(_this, sourcePackage);
        }
        return runtime;
    }

    /**
     * Create DataObjectSchema based on raw object that contains its attributes
     * @param _this
     * @param rawSchema
     * @returns {DataObjectSchema}
     */
    _createDataSchema(_this, rawSchema) {
        console.log("creating dataSchema based on: ", rawSchema);

        // FIXME: accessControlPolicy field not needed?
        // create the descriptor
        let dataSchema = _this._factory.createDataObjectSchema(
            rawSchema["cguid"],
            rawSchema["version"],
            rawSchema["objectName"],
            rawSchema["description"],
            rawSchema["language"],
            rawSchema["sourcePackageURL"]
        );

        // optional fields
        dataSchema.signature = rawSchema["signature"];

        // parse and attach sourcePackage
        let sourcePackage = rawSchema["sourcePackage"];
        if (sourcePackage) {
            // console.log("dataSchema has sourcePackage:", sourcePackage);
            dataSchema.sourcePackage = _this._createSourcePackage(_this, sourcePackage);
        }

        console.log("created dataSchema descriptor object:", dataSchema);
        return dataSchema;
    }

    /**
     * Create ProtocolStubDescriptor based on raw object that contains its attributes
     * @param _this
     * @param rawProxy
     * @returns {ProtocolStubDescriptor}
     */
    _createIdpProxy(_this, rawProxy) {
        // console.log("creating idpproxy descriptor based on: ", rawProxy);

        // create the descriptor
        let idpproxy = _this._factory.createProtoStubDescriptorObject(
            rawProxy["cguid"],
            rawProxy["version"],
            rawProxy["objectName"],
            rawProxy["description"],
            rawProxy["language"],
            rawProxy["sourcePackageURL"],
            rawProxy["messageSchemas"],
            rawProxy["configuration"],
            rawProxy["constraints"]
        );

        // optional fields
        idpproxy.signature = rawProxy["signature"];

        // parse and attach the sourcePackage
        let sourcePackage = rawProxy["sourcePackage"];
        if (sourcePackage) {
            sourcePackage = _this._createSourcePackage(_this, sourcePackage);
            idpproxy.sourcePackage = sourcePackage;
        }

        return idpproxy;
    }

    _createSourcePackage(_this, sp) {
        try {
            sp = JSON.parse(sp);
        } catch (e) {
            console.log("parsing sourcePackage failed. already parsed? -> ", sp);
        }

        // check encoding
        if (sp["encoding"] === "base64") {
            sp["sourceCode"] = atob(sp["sourceCode"]);
        }

        let sourcePackage = _this._factory.createSourcePackage(sp["sourceCodeClassname"], sp["sourceCode"]);
        if (sp["encoding"])
            sourcePackage.encoding = sp["encoding"];

        if (sp["signature"])
            sourcePackage.signature = sp["signature"];

        return sourcePackage;
    }

    /**
     * Get source Package from a URL
     * @param sourcePackageURL - e.g. mydomain.com/.well-known/hyperty/MyHyperty/sourcePackage
     * @returns {Promise}
     */
    getSourcePackageFromURL(sourcePackageURL) {
        let _this = this;

        console.log("getting sourcePackage from:", sourcePackageURL);
        console.warn("-------------------------------------------------------------------------------------------");
        console.warn("ATTENTION: This function may fail if the sourceCode of the the sourcePackage is very large!");
        console.warn("-------------------------------------------------------------------------------------------");

        return new Promise(function (resolve, reject) {
            _this.httpRequest.get(sourcePackageURL).then(function (result) {
                //console.log("got raw sourcePackage:", result);
                if (result["ERROR"]) {
                    // TODO handle error properly
                    reject(result);
                } else {
                    result = JSON.parse(result);
                    let sourcePackage = _this._createSourcePackage(_this, result);
                    resolve(sourcePackage);
                }
            }).catch(function (reason) {
                reject(reason);
            });

        });

    }

    /**
     * Returns the sourceCode of a given descriptor
     * @param {CatalogueDataObject} descriptor - Catalogue Object that was retrieved using e.g. getHypertyDescriptor()
     * @returns {Promise}
     */
    getSourceCodeFromDescriptor(descriptor) {
        let _this = this;
        return new Promise(function (resolve, reject) {
            if (descriptor.sourcePackage) {
                //console.log("descriptor has sourcePackage");
                //console.log("returning sourceCode:", descriptor.sourcePackage.sourceCode);
                resolve(descriptor.sourcePackage.sourceCode);
            } else {
                if (persistenceManager.getVersion(descriptor.sourcePackageURL + "/sourceCode") >= descriptor.version) {
                    console.log("returning cached version from persistence manager");
                    resolve(persistenceManager.get(descriptor.sourcePackageURL + "/sourceCode"));
                } else {
                    _this.httpRequest.get(descriptor.sourcePackageURL + "/sourceCode").then(function (sourceCode) {
                        if (sourceCode["ERROR"]) {
                            // TODO handle error properly
                            reject(sourceCode);
                        } else {
                            persistenceManager.set(descriptor.sourcePackageURL + "/sourceCode", descriptor.version, sourceCode);
                            resolve(sourceCode);
                        }
                    });
                }
            }
        });
    }

    set runtimeURL(runtimeURL) {
        let _this = this;
        _this._runtimeURL = runtimeURL;
    }

    get runtimeURL() {
        let _this = this;
        return _this._runtimeURL;
    }

    deleteFromPM(url) {
        persistenceManager.delete(url);
    }

}

export default RuntimeCatalogue;
<|endoftext|>


<commit_before>// @ts-check

import { GraphQLString, GraphQLFloat, GraphQLObjectType, GraphQLNonNull } from "graphql"
import { mutationWithClientMutationId } from "graphql-relay"

import config from "config"
import BidderPosition from "schema/bidder_position"

const { PREDICTION_ENDPOINT } = config

// the description_md must be a function to delay interpolation of string literal
const biddingErrors = [
  {
    id: "ERROR_BID_LOW",
    gravity_key: "Please enter a bid higher than",
    header: "Your bid wasn't high enough",
    description_md: () => `Another bidder placed a higher max bid or the same max bid before you did.  \
 Bid again to take the lead.`,
  },
  {
    id: "ERROR_SALE_CLOSED",
    gravity_key: "Sale Closed to Bids",
    header: "Lot closed",
    description_md: () => "Sorry, your bid wasn’t received before the lot closed.",
  },
  {
    id: "ERROR_LIVE_BIDDING_STARTED",
    gravity_key: "Live Bidding has Started",
    header: "Live bidding has started",
    description_md: (params) => `Sorry, your bid wasn’t received before live bidding started.\
 To continue bidding, please [join the live auction](${params.liveAuctionUrl}).`,
  },
  {
    id: "ERROR_BIDDER_NOT_QUALIFIED",
    gravity_key: "Bidder not qualified to bid on this auction.",
    header: "Bid not placed",
    description_md: () => `Your bid can’t be placed at this time.\
 Please contact [support@artsy.net](mailto:support@artsy.net) for more information.`,

  },
  {
    id: "ERROR_UNKNOWN",
    gravity_key: "unknown error",
    header: "Bid not placed",
    description_md: () => `Your bid can’t be placed at this time.\
 Please contact [support@artsy.net](mailto:support@artsy.net) for more information.`,
  },
]

const BidderPositionMutationResultType = new GraphQLObjectType({
  name: "BidderPositionMutationResult",
  fields: () => ({
    status: {
      type: new GraphQLNonNull(GraphQLString),
    },
    message_header: {
      type: GraphQLString,
    },
    message_description_md: {
      type: GraphQLString,
    },
    position: {
      type: BidderPosition.type,
    },
  }),
})

// @ts-ignore
export const BidderPositionMutation = mutationWithClientMutationId({
  name: "BidderPosition",
  description:
    "Creates a bidder position",
  inputFields: {
    sale_id: {
      type: new GraphQLNonNull(GraphQLString),
    },
    artwork_id: {
      type: new GraphQLNonNull(GraphQLString),
    },
    max_bid_amount_cents: {
      type: new GraphQLNonNull(GraphQLFloat),
    },
  },
  outputFields: {
    result: {
      type: BidderPositionMutationResultType,
      resolve: (result) => result,
    },
  },
  mutateAndGetPayload: (
    { sale_id, artwork_id, max_bid_amount_cents },
    _request,
    {
      rootValue: {
        accessToken,
        createBidderPositionLoader,
      },
    }
  ) => {
    if (!accessToken) {
      return new Error("You need to be signed in to perform this action")
    }
    return createBidderPositionLoader({ sale_id, artwork_id, max_bid_amount_cents })
      .then(p => { return { status: "SUCCESS", position: p } })
      .catch(e => {
        const errorSplit = e.message.split(" - ")
        const errorObject = errorSplit.length > 1 ? JSON.parse(e.message.split(" - ")[1]) : null
        if (errorObject && errorObject.type === "param_error") {
          const error = biddingErrors.find(d => errorObject.message.trim().startsWith(d.gravity_key)) ||
            errorObject.ERROR_UNKNOWN
          const liveAuctionUrl = `${PREDICTION_ENDPOINT}/${sale_id}`
          return {
            status: error.id,
            message_header: error.header,
            message_description_md: error.description_md({ liveAuctionUrl }),
          }
        }
        return new Error(e)
      })
  },
})
<commit_msg>handle gravity error format for sale started msg<commit_after>// @ts-check

import { GraphQLString, GraphQLFloat, GraphQLObjectType, GraphQLNonNull } from "graphql"
import { mutationWithClientMutationId } from "graphql-relay"

import config from "config"
import BidderPosition from "schema/bidder_position"

const { PREDICTION_ENDPOINT } = config

// the description_md must be a function to delay interpolation of string literal
const biddingErrors = [
  {
    id: "ERROR_BID_LOW",
    gravity_key: "Please enter a bid higher than",
    header: "Your bid wasn't high enough",
    description_md: () => `Another bidder placed a higher max bid or the same max bid before you did.  \
 Bid again to take the lead.`,
  },
  {
    id: "ERROR_SALE_CLOSED",
    gravity_key: "Sale Closed to Bids",
    header: "Lot closed",
    description_md: () => "Sorry, your bid wasn’t received before the lot closed.",
  },
  {
    id: "ERROR_LIVE_BIDDING_STARTED",
    gravity_key: "Live Bidding has Started",
    header: "Live bidding has started",
    description_md: (params) => `Sorry, your bid wasn’t received before live bidding started.\
 To continue bidding, please [join the live auction](${params.liveAuctionUrl}).`,
  },
  {
    id: "ERROR_BIDDER_NOT_QUALIFIED",
    gravity_key: "Bidder not qualified to bid on this auction.",
    header: "Bid not placed",
    description_md: () => `Your bid can’t be placed at this time.\
 Please contact [support@artsy.net](mailto:support@artsy.net) for more information.`,

  },
  {
    id: "ERROR_UNKNOWN",
    gravity_key: "unknown error",
    header: "Bid not placed",
    description_md: () => `Your bid can’t be placed at this time.\
 Please contact [support@artsy.net](mailto:support@artsy.net) for more information.`,
  },
]

const BidderPositionMutationResultType = new GraphQLObjectType({
  name: "BidderPositionMutationResult",
  fields: () => ({
    status: {
      type: new GraphQLNonNull(GraphQLString),
    },
    message_header: {
      type: GraphQLString,
    },
    message_description_md: {
      type: GraphQLString,
    },
    position: {
      type: BidderPosition.type,
    },
  }),
})

// @ts-ignore
export const BidderPositionMutation = mutationWithClientMutationId({
  name: "BidderPosition",
  description:
    "Creates a bidder position",
  inputFields: {
    sale_id: {
      type: new GraphQLNonNull(GraphQLString),
    },
    artwork_id: {
      type: new GraphQLNonNull(GraphQLString),
    },
    max_bid_amount_cents: {
      type: new GraphQLNonNull(GraphQLFloat),
    },
  },
  outputFields: {
    result: {
      type: BidderPositionMutationResultType,
      resolve: (result) => result,
    },
  },
  mutateAndGetPayload: (
    { sale_id, artwork_id, max_bid_amount_cents },
    _request,
    {
      rootValue: {
        accessToken,
        createBidderPositionLoader,
      },
    }
  ) => {
    if (!accessToken) {
      return new Error("You need to be signed in to perform this action")
    }
    return createBidderPositionLoader({ sale_id, artwork_id, max_bid_amount_cents })
      .then(p => { return { status: "SUCCESS", position: p } })
      .catch(e => {
        const errorSplit = e.message.split(" - ")
        const errorObject = errorSplit.length > 1 ? JSON.parse(e.message.split(" - ")[1]) : null
        if (errorObject) {
          const errorMessage = errorObject.message || errorObject.error
          const error = biddingErrors.find(d => errorMessage.trim().startsWith(d.gravity_key)) ||
            errorObject.ERROR_UNKNOWN
          const liveAuctionUrl = `${PREDICTION_ENDPOINT}/${sale_id}`
          return {
            status: error.id,
            message_header: error.header,
            message_description_md: error.description_md({ liveAuctionUrl }),
          }
        }
        return new Error(e)
      })
  },
})
<|endoftext|>


<commit_before>define([
  'jquery',
  'core/media',
  'text!templates/component/text/link-modal.html'
], function ($, media, linkModalTemplate) {
  var $activeNode = null
    , $linkModal = $(linkModalTemplate)
    , $linkedUrl = $linkModal.find('.linked-url')
    , $resultTargets = $linkModal.find('[data-result]')
    , $modal
    , $workingElement;

  /**
   * Get the node of the selection start
   */
  function getSelectionStartNode() {
    var node, selection;
    if (window.getSelection) { // FF3.6, Safari4, Chrome5 (DOM Standards)
      selection = getSelection();
      node = selection.anchorNode;
    }

    if (!node && document.selection) { // IE
      selection = document.selection;
      var range = selection.getRangeAt ? selection.getRangeAt(0) : selection.createRange();
      node = range.commonAncestorContainer ? range.commonAncestorContainer :
             range.parentElement ? range.parentElement() : range.item(0);
    }

    if (node) {
      return (node.nodeName == "#text" ? node.parentNode : node);
    }

    return false;
  }

  function openModal() {
    if (!$modal) {
      $modal = $linkModal.modal({show: false});
    }

    if (show) {
      $modal.modal('show');
    }

    return $modal;
  }

  return {
    deactivate : function ($anchor) {
      $anchor = $anchor || $activeNode;

      $anchor.contents().unwrap();
    },
    initialize : function () {
      var selection = window.getSelection(), range, clonedRange, span, $anchorWrapper;

      if (selection.rangeCount) {
        $anchorWrapper = $(document.createElement('a'));
        range = selection.getRangeAt(0);
        clonedRange = range.cloneRange();
        span = document.createElement('span');

        span.appendChild(range.cloneContents());

        if (span.innerHTML === '') {
          return false;
        }

        clonedRange.surroundContents($anchorWrapper[0]);
        selection.removeAllRanges();
        selection.addRange(clonedRange);

        return $anchorWrapper;
      }

      return false;
    },
    activate   : function ($element) {
      var isNew = false
        , self = this;

      $workingElement = $element || $activeNode;

      if (!$workingElement) {
        $workingElement = this.initialize();
        isNew = true;

        if (!$workingElement) {
          return;
        }
      }

      $linkedUrl.val($workingElement.attr('href'));

      if ($modal) {
        $modal.modal('show');

        return;
      }

      $modal = $linkModal.modal();

      $linkModal.find('.choose-media').on('click', function() {
        media.selectFile(function(chosenFile) {
          if (!chosenFile) {
            return;
          }

          var location = window.location;

          $linkedUrl.val(location.protocol + '//' + location.host + chosenFile.url);
        });
      });

      $resultTargets.on('click', function() {

        var result = $(this).data('result');

        if (!result && isNew) {
          self.deactivate($workingElement);
        }

        if (result) {
          $workingElement.attr('href', $linkedUrl.val());

          if (isNew) {
            console.log('Called.', $workingElement);
          }

          $modal.modal('hide');
        }
      });
    },

    // @todo Follow up: Trail ends in modal destruction. Probably not (un)setting popover visibility or something similar.
    isActive   : function () {
      var $node = $(getSelectionStartNode());

      console.log('----');

      console.log('a');

      if ($node.is('a')) {
        console.log('b');
        if ($activeNode && $activeNode[0] !== $node[0]) {
          console.log('c');
          $activeNode.popover('hide');
          $activeNode.data('popover-visible', false);
        }
        console.log('d');
        if (!$node.data('popover-visible')) {
          console.log('e');
          $node.popover('show');
          $node.data('popover-visible', true);

          $activeNode = $node;
        }
        console.log('f');
        return true;
      }
      console.log('g');
      if (null !== $activeNode) {
        console.log('h');
        $activeNode.data('popover-visible', false);
        $activeNode.popover('hide');

        $activeNode = null;
      }
      console.log('i');

      return false;
    }
  };
});
<commit_msg>Fixed isNew removal bug and removed unused function<commit_after>define([
  'jquery',
  'core/media',
  'text!templates/component/text/link-modal.html'
], function ($, media, linkModalTemplate) {
  var $activeNode = null
    , $linkModal = $(linkModalTemplate)
    , $linkedUrl = $linkModal.find('.linked-url')
    , $resultTargets = $linkModal.find('[data-result]')
    , $modal
    , $workingElement;

  /**
   * Get the node of the selection start
   */
  function getSelectionStartNode() {
    var node, selection;
    if (window.getSelection) { // FF3.6, Safari4, Chrome5 (DOM Standards)
      selection = getSelection();
      node = selection.anchorNode;
    }

    if (!node && document.selection) { // IE
      selection = document.selection;
      var range = selection.getRangeAt ? selection.getRangeAt(0) : selection.createRange();
      node = range.commonAncestorContainer ? range.commonAncestorContainer :
             range.parentElement ? range.parentElement() : range.item(0);
    }

    if (node) {
      return (node.nodeName == "#text" ? node.parentNode : node);
    }

    return false;
  }

  return {
    deactivate : function ($anchor) {
      $anchor = $anchor || $activeNode;

      if ($modal) {
        $model.data('modal', null);
      }

      $anchor.contents().unwrap();
    },

    initialize : function () {
      var selection = window.getSelection(), range, clonedRange, span, $anchorWrapper;

      if (selection.rangeCount) {
        $anchorWrapper = $(document.createElement('a'));
        range = selection.getRangeAt(0);
        clonedRange = range.cloneRange();
        span = document.createElement('span');

        span.appendChild(range.cloneContents());

        if (span.innerHTML === '') {
          return false;
        }

        clonedRange.surroundContents($anchorWrapper[0]);
        selection.removeAllRanges();
        selection.addRange(clonedRange);

        return $anchorWrapper;
      }

      return false;
    },

    activate   : function ($element) {
      var isNew = false
        , self = this;

      $workingElement = $element || $activeNode;

      if (!$workingElement) {
        $workingElement = this.initialize();
        isNew = true;

        if (!$workingElement) {
          return;
        }
      }

      $linkedUrl.val($workingElement.attr('href'));

      if ($modal) {
        $modal.modal('show');

        return;
      }

      $modal = $linkModal.modal();

      $linkModal.find('.choose-media').on('click', function() {
        media.selectFile(function(chosenFile) {
          if (!chosenFile) {
            return;
          }

          var location = window.location;

          $linkedUrl.val(location.protocol + '//' + location.host + chosenFile.url);
        });
      });

      $resultTargets.on('click', function() {

        var result = $(this).data('result');

        if (!result && isNew) {
          self.deactivate($workingElement);
        }

        if (result) {
          $workingElement.attr('href', $linkedUrl.val());

          if (isNew) {
            console.log('Called.', $workingElement);
          }

          $modal.modal('hide');
        }
      });
    },

    // @todo Follow up: Trail ends in modal destruction. Probably not (un)setting popover visibility or something similar.
    isActive   : function () {
      var $node = $(getSelectionStartNode());

      console.log('----');

      console.log('a');

      if ($node.is('a')) {
        console.log('b');
        if ($activeNode && $activeNode[0] !== $node[0]) {
          console.log('c');
          $activeNode.popover('hide');
          $activeNode.data('popover-visible', false);
        }
        console.log('d');
        if (!$node.data('popover-visible')) {
          console.log('e');
          $node.popover('show');
          $node.data('popover-visible', true);

          $activeNode = $node;
        }
        console.log('f');
        return true;
      }
      console.log('g');
      if (null !== $activeNode) {
        console.log('h');
        $activeNode.data('popover-visible', false);
        $activeNode.popover('hide');

        $activeNode = null;
      }
      console.log('i');

      return false;
    }
  };
});
<|endoftext|>


<commit_before>/**
 * @author       Richard Davey <rich@photonstorm.com>
 * @author       Pavle Goloskokovic <pgoloskokovic@gmail.com> (http://prunegames.com)
 * @copyright    2020 Photon Storm Ltd.
 * @license      {@link https://opensource.org/licenses/MIT|MIT License}
 */

var BaseSoundManager = require('../BaseSoundManager');
var Class = require('../../utils/Class');
var Events = require('../events');
var HTML5AudioSound = require('./HTML5AudioSound');

/**
 * HTML5 Audio implementation of the Sound Manager.
 *
 * To play multiple instances of the same HTML5 Audio sound, you need to provide an `instances` value when
 * loading the sound with the Loader:
 *
 * ```javascript
 * this.load.audio('explosion', 'explosion.mp3', {
 *     instances: 2
 * });
 * ```
 *
 * Not all browsers can play all audio formats.
 *
 * There is a good guide to what's supported: [Cross-browser audio basics: Audio codec support](https://developer.mozilla.org/en-US/Apps/Fundamentals/Audio_and_video_delivery/Cross-browser_audio_basics#Audio_Codec_Support).
 *
 * @class HTML5AudioSoundManager
 * @extends Phaser.Sound.BaseSoundManager
 * @memberof Phaser.Sound
 * @constructor
 * @since 3.0.0
 *
 * @param {Phaser.Game} game - Reference to the current game instance.
 */
var HTML5AudioSoundManager = new Class({

    Extends: BaseSoundManager,

    initialize:

    function HTML5AudioSoundManager (game)
    {
        /**
         * Flag indicating whether if there are no idle instances of HTML5 Audio tag,
         * for any particular sound, if one of the used tags should be hijacked and used
         * for succeeding playback or if succeeding Phaser.Sound.HTML5AudioSound#play
         * call should be ignored.
         *
         * @name Phaser.Sound.HTML5AudioSoundManager#override
         * @type {boolean}
         * @default true
         * @since 3.0.0
         */
        this.override = true;

        /**
         * Value representing time difference, in seconds, between calling
         * play method on an audio tag and when it actually starts playing.
         * It is used to achieve more accurate delayed sound playback.
         *
         * You might need to tweak this value to get the desired results
         * since audio play delay varies depending on the browser/platform.
         *
         * @name Phaser.Sound.HTML5AudioSoundManager#audioPlayDelay
         * @type {number}
         * @default 0.1
         * @since 3.0.0
         */
        this.audioPlayDelay = 0.1;

        /**
         * A value by which we should offset the loop end marker of the
         * looping sound to compensate for lag, caused by changing audio
         * tag playback position, in order to achieve gapless looping.
         *
         * You might need to tweak this value to get the desired results
         * since loop lag varies depending on the browser/platform.
         *
         * @name Phaser.Sound.HTML5AudioSoundManager#loopEndOffset
         * @type {number}
         * @default 0.05
         * @since 3.0.0
         */
        this.loopEndOffset = 0.05;

        /**
         * An array for keeping track of all the sounds
         * that were paused when game lost focus.
         *
         * @name Phaser.Sound.HTML5AudioSoundManager#onBlurPausedSounds
         * @type {Phaser.Sound.HTML5AudioSound[]}
         * @private
         * @default []
         * @since 3.0.0
         */
        this.onBlurPausedSounds = [];

        this.locked = 'ontouchstart' in window;

        /**
         * A queue of all actions performed on sound objects while audio was locked.
         * Once the audio gets unlocked, after an explicit user interaction,
         * all actions will be performed in chronological order.
         * Array of object types: { sound: Phaser.Sound.HTML5AudioSound, name: string, value?: * }
         *
         * @name Phaser.Sound.HTML5AudioSoundManager#lockedActionsQueue
         * @type {array}
         * @private
         * @since 3.0.0
         */
        this.lockedActionsQueue = this.locked ? [] : null;

        /**
         * Property that actually holds the value of global mute
         * for HTML5 Audio sound manager implementation.
         *
         * @name Phaser.Sound.HTML5AudioSoundManager#_mute
         * @type {boolean}
         * @private
         * @default false
         * @since 3.0.0
         */
        this._mute = false;

        /**
         * Property that actually holds the value of global volume
         * for HTML5 Audio sound manager implementation.
         *
         * @name Phaser.Sound.HTML5AudioSoundManager#_volume
         * @type {boolean}
         * @private
         * @default 1
         * @since 3.0.0
         */
        this._volume = 1;

        BaseSoundManager.call(this, game);

        if (this.locked)
        {
            this.unlock();
        }
    },

    /**
     * Adds a new sound into the sound manager.
     *
     * @method Phaser.Sound.HTML5AudioSoundManager#add
     * @since 3.0.0
     *
     * @param {string} key - Asset key for the sound.
     * @param {Phaser.Types.Sound.SoundConfig} [config] - An optional config object containing default sound settings.
     *
     * @return {Phaser.Sound.HTML5AudioSound} The new sound instance.
     */
    add: function (key, config)
    {
        var sound = new HTML5AudioSound(this, key, config);

        this.sounds.push(sound);

        return sound;
    },

    /**
     * Unlocks HTML5 Audio loading and playback on mobile
     * devices on the initial explicit user interaction.
     *
     * @method Phaser.Sound.HTML5AudioSoundManager#unlock
     * @since 3.0.0
     */
    unlock: function ()
    {
        console.log('unlock');

        this.locked = false;

        var _this = this;

        this.game.cache.audio.entries.each(function (key, tags)
        {
            for (var i = 0; i < tags.length; i++)
            {
                if (tags[i].dataset.locked === 'true')
                {
                    _this.locked = true;

                    return false;
                }
            }

            return true;
        });

        // if (!this.locked)
        // {
        //     console.log('unlock bail 1');
        //     return;
        // }

        var moved = false;

        var detectMove = function ()
        {
            moved = true;
        };

        var unlock = function ()
        {
            console.log('unlock->unlock!', moved);

            if (moved)
            {
                moved = false;
                return;
            }

            document.body.removeEventListener('touchmove', detectMove);
            document.body.removeEventListener('touchend', unlock);

            _this.emit(Events.UNLOCKED, _this);

            var lockedTags = [];

            _this.game.cache.audio.entries.each(function (key, tags)
            {
                for (var i = 0; i < tags.length; i++)
                {
                    var tag = tags[i];

                    if (tag.dataset.locked === 'true')
                    {
                        lockedTags.push(tag);
                    }
                }

                return true;
            });

            if (lockedTags.length === 0)
            {
                return;
            }

            var lastTag = lockedTags[lockedTags.length - 1];

            lastTag.oncanplaythrough = function ()
            {
                lastTag.oncanplaythrough = null;

                lockedTags.forEach(function (tag)
                {
                    tag.dataset.locked = 'false';
                });

                _this.unlocked = true;
            };

            lockedTags.forEach(function (tag)
            {
                tag.load();
            });
        };

        this.once(Events.UNLOCKED, function ()
        {
            console.log('unlocked event handler', this.lockedActionsQueue.length);

            /*
            this.forEachActiveSound(function (sound)
            {
                if (sound.currentMarker === null && sound.duration === 0)
                {
                    sound.duration = sound.tags[0].duration;
                }

                sound.totalDuration = sound.tags[0].duration;
            });

            while (this.lockedActionsQueue.length)
            {
                var lockedAction = this.lockedActionsQueue.shift();

                if (lockedAction.sound[lockedAction.prop].apply)
                {
                    lockedAction.sound[lockedAction.prop].apply(lockedAction.sound, lockedAction.value || []);
                }
                else
                {
                    lockedAction.sound[lockedAction.prop] = lockedAction.value;
                }
            }
            */

        }, this);

        console.log('unlock added listeners');

        document.body.addEventListener('touchmove', detectMove, false);
        document.body.addEventListener('touchend', unlock, false);
    },

    /**
     * Method used internally for pausing sound manager if
     * Phaser.Sound.HTML5AudioSoundManager#pauseOnBlur is set to true.
     *
     * @method Phaser.Sound.HTML5AudioSoundManager#onBlur
     * @protected
     * @since 3.0.0
     */
    onBlur: function ()
    {
        this.forEachActiveSound(function (sound)
        {
            if (sound.isPlaying)
            {
                this.onBlurPausedSounds.push(sound);
                sound.onBlur();
            }
        });
    },

    /**
     * Method used internally for resuming sound manager if
     * Phaser.Sound.HTML5AudioSoundManager#pauseOnBlur is set to true.
     *
     * @method Phaser.Sound.HTML5AudioSoundManager#onFocus
     * @protected
     * @since 3.0.0
     */
    onFocus: function ()
    {
        this.onBlurPausedSounds.forEach(function (sound)
        {
            sound.onFocus();
        });

        this.onBlurPausedSounds.length = 0;
    },

    /**
     * Method used internally by Phaser.Sound.HTML5AudioSound class methods and property setters
     * to check if sound manager is locked and then either perform action immediately or queue it
     * to be performed once the sound manager gets unlocked.
     *
     * @method Phaser.Sound.HTML5AudioSoundManager#isLocked
     * @protected
     * @since 3.0.0
     *
     * @param {Phaser.Sound.HTML5AudioSound} sound - Sound object on which to perform queued action.
     * @param {string} prop - Name of the method to be called or property to be assigned a value to.
     * @param {*} [value] - An optional parameter that either holds an array of arguments to be passed to the method call or value to be set to the property.
     *
     * @return {boolean} Whether the sound manager is locked.
     */
    isLocked: function (sound, prop, value)
    {
        if (sound.tags[0].dataset.locked === 'true')
        {
            this.lockedActionsQueue.push({
                sound: sound,
                prop: prop,
                value: value
            });

            return true;
        }

        return false;
    },

    /**
     * Sets the muted state of all this Sound Manager.
     *
     * @method Phaser.Sound.HTML5AudioSoundManager#setMute
     * @fires Phaser.Sound.Events#GLOBAL_MUTE
     * @since 3.3.0
     *
     * @param {boolean} value - `true` to mute all sounds, `false` to unmute them.
     *
     * @return {Phaser.Sound.HTML5AudioSoundManager} This Sound Manager.
     */
    setMute: function (value)
    {
        this.mute = value;

        return this;
    },

    /**
     * Sets the volume of this Sound Manager.
     *
     * @method Phaser.Sound.HTML5AudioSoundManager#setVolume
     * @fires Phaser.Sound.Events#GLOBAL_VOLUME
     * @since 3.3.0
     *
     * @param {number} value - The global volume of this Sound Manager.
     *
     * @return {Phaser.Sound.HTML5AudioSoundManager} This Sound Manager.
     */
    setVolume: function (value)
    {
        this.volume = value;

        return this;
    },

    /**
     * @name Phaser.Sound.HTML5AudioSoundManager#volume
     * @type {number}
     * @fires Phaser.Sound.Events#GLOBAL_VOLUME
     * @since 3.0.0
     */
    volume: {

        get: function ()
        {
            return this._volume;
        },

        set: function (value)
        {
            this._volume = value;

            this.forEachActiveSound(function (sound)
            {
                sound.updateVolume();
            });

            this.emit(Events.GLOBAL_VOLUME, this, value);
        }

    },

    /**
     * @name Phaser.Sound.HTML5AudioSoundManager#mute
     * @type {boolean}
     * @fires Phaser.Sound.Events#GLOBAL_MUTE
     * @since 3.0.0
     */
    mute: {

        get: function ()
        {
            return this._mute;
        },

        set: function (value)
        {
            this._mute = value;

            this.forEachActiveSound(function (sound)
            {
                sound.updateMute();
            });

            this.emit(Events.GLOBAL_MUTE, this, value);
        }

    },

    /**
     * Calls Phaser.Sound.BaseSoundManager#destroy method
     * and cleans up all HTML5 Audio related stuff.
     *
     * @method Phaser.Sound.HTML5AudioSoundManager#destroy
     * @since 3.0.0
     */
    destroy: function ()
    {
        BaseSoundManager.prototype.destroy.call(this);

        this.onBlurPausedSounds.length = 0;
        this.onBlurPausedSounds = null;
    }

});

module.exports = HTML5AudioSoundManager;
<commit_msg>New unlock handler<commit_after>/**
 * @author       Richard Davey <rich@photonstorm.com>
 * @author       Pavle Goloskokovic <pgoloskokovic@gmail.com> (http://prunegames.com)
 * @copyright    2020 Photon Storm Ltd.
 * @license      {@link https://opensource.org/licenses/MIT|MIT License}
 */

var BaseSoundManager = require('../BaseSoundManager');
var Class = require('../../utils/Class');
var Events = require('../events');
var GameEvents = require('../../core/events');
var HTML5AudioSound = require('./HTML5AudioSound');

/**
 * HTML5 Audio implementation of the Sound Manager.
 *
 * To play multiple instances of the same HTML5 Audio sound, you need to provide an `instances` value when
 * loading the sound with the Loader:
 *
 * ```javascript
 * this.load.audio('explosion', 'explosion.mp3', {
 *     instances: 2
 * });
 * ```
 *
 * Not all browsers can play all audio formats.
 *
 * There is a good guide to what's supported: [Cross-browser audio basics: Audio codec support](https://developer.mozilla.org/en-US/Apps/Fundamentals/Audio_and_video_delivery/Cross-browser_audio_basics#Audio_Codec_Support).
 *
 * @class HTML5AudioSoundManager
 * @extends Phaser.Sound.BaseSoundManager
 * @memberof Phaser.Sound
 * @constructor
 * @since 3.0.0
 *
 * @param {Phaser.Game} game - Reference to the current game instance.
 */
var HTML5AudioSoundManager = new Class({

    Extends: BaseSoundManager,

    initialize:

    function HTML5AudioSoundManager (game)
    {
        /**
         * Flag indicating whether if there are no idle instances of HTML5 Audio tag,
         * for any particular sound, if one of the used tags should be hijacked and used
         * for succeeding playback or if succeeding Phaser.Sound.HTML5AudioSound#play
         * call should be ignored.
         *
         * @name Phaser.Sound.HTML5AudioSoundManager#override
         * @type {boolean}
         * @default true
         * @since 3.0.0
         */
        this.override = true;

        /**
         * Value representing time difference, in seconds, between calling
         * play method on an audio tag and when it actually starts playing.
         * It is used to achieve more accurate delayed sound playback.
         *
         * You might need to tweak this value to get the desired results
         * since audio play delay varies depending on the browser/platform.
         *
         * @name Phaser.Sound.HTML5AudioSoundManager#audioPlayDelay
         * @type {number}
         * @default 0.1
         * @since 3.0.0
         */
        this.audioPlayDelay = 0.1;

        /**
         * A value by which we should offset the loop end marker of the
         * looping sound to compensate for lag, caused by changing audio
         * tag playback position, in order to achieve gapless looping.
         *
         * You might need to tweak this value to get the desired results
         * since loop lag varies depending on the browser/platform.
         *
         * @name Phaser.Sound.HTML5AudioSoundManager#loopEndOffset
         * @type {number}
         * @default 0.05
         * @since 3.0.0
         */
        this.loopEndOffset = 0.05;

        /**
         * An array for keeping track of all the sounds
         * that were paused when game lost focus.
         *
         * @name Phaser.Sound.HTML5AudioSoundManager#onBlurPausedSounds
         * @type {Phaser.Sound.HTML5AudioSound[]}
         * @private
         * @default []
         * @since 3.0.0
         */
        this.onBlurPausedSounds = [];

        /**
         * A queue of all actions performed on sound objects while audio was locked.
         * Once the audio gets unlocked, after an explicit user interaction,
         * all actions will be performed in chronological order.
         * Array of object types: { sound: Phaser.Sound.HTML5AudioSound, name: string, value?: * }
         *
         * @name Phaser.Sound.HTML5AudioSoundManager#lockedActionsQueue
         * @type {array}
         * @private
         * @since 3.0.0
         */
        this.lockedActionsQueue = [];

        /**
         * Property that actually holds the value of global mute
         * for HTML5 Audio sound manager implementation.
         *
         * @name Phaser.Sound.HTML5AudioSoundManager#_mute
         * @type {boolean}
         * @private
         * @default false
         * @since 3.0.0
         */
        this._mute = false;

        /**
         * Property that actually holds the value of global volume
         * for HTML5 Audio sound manager implementation.
         *
         * @name Phaser.Sound.HTML5AudioSoundManager#_volume
         * @type {boolean}
         * @private
         * @default 1
         * @since 3.0.0
         */
        this._volume = 1;

        /**
         * The Audio cache, where audio data is stored.
         *
         * @name Phaser.Sound.HTML5AudioSoundManager#cache
         * @type {Phaser.Cache.BaseCache}
         * @since 3.60.0
         */
        this.cache = game.cache.audio;

        this.locked = 'ontouchstart' in window;

        BaseSoundManager.call(this, game);

        if (this.locked && game.isBooted)
        {
            this.unlock();
        }
        else
        {
            game.events.once(GameEvents.BOOT, this.unlock, this);
        }
    },

    /**
     * Adds a new sound into the sound manager.
     *
     * @method Phaser.Sound.HTML5AudioSoundManager#add
     * @since 3.0.0
     *
     * @param {string} key - Asset key for the sound.
     * @param {Phaser.Types.Sound.SoundConfig} [config] - An optional config object containing default sound settings.
     *
     * @return {Phaser.Sound.HTML5AudioSound} The new sound instance.
     */
    add: function (key, config)
    {
        var sound = new HTML5AudioSound(this, key, config);

        this.sounds.push(sound);

        return sound;
    },

    /**
     * Unlocks the Audio API on the initial input event.
     *
     * @method Phaser.Sound.HTML5AudioSoundManager#unlock
     * @since 3.0.0
     */
    unlock: function ()
    {
        console.log('HTML5AudioSoundManager.unlock');

        var _this = this;

        var body = document.body;
        var bodyAdd = body.addEventListener;
        var bodyRemove = body.removeEventListener;

        var unlockHandler = function unlockHandler ()
        {
            _this.createAudioTags();

            bodyRemove('touchstart', unlockHandler);
            bodyRemove('touchend', unlockHandler);
            bodyRemove('click', unlockHandler);
            bodyRemove('keydown', unlockHandler);
        };

        if (body)
        {
            bodyAdd('touchstart', unlockHandler, false);
            bodyAdd('touchend', unlockHandler, false);
            bodyAdd('click', unlockHandler, false);
            bodyAdd('keydown', unlockHandler, false);
        }

        this.cache.entries.each(function (key, tags)
        {
            for (var i = 0; i < tags.length; i++)
            {
                tags[i].dataset.locked = true;
            }
        });
    },

    /**
     *
     *
     * @method Phaser.Sound.HTML5AudioSoundManager#createAudioTags
     * @since 3.60.0
     */
    createAudioTags: function ()
    {
        console.log('HTML5AudioSoundManager.createAudioTags');

        if (!this.locked)
        {
            console.log('unlock bail 1 - unlock already called');
            return;
        }

        this.locked = false;

        this.emit(Events.UNLOCKED, this);

        var lockedTags = [];

        this.cache.entries.each(function (key, tags)
        {
            for (var i = 0; i < tags.length; i++)
            {
                var tag = tags[i];

                if (tag.dataset.locked === 'true')
                {
                    lockedTags.push(tag);
                }
            }

            return true;
        });

        if (lockedTags.length === 0)
        {
            return;
        }

        var lastTag = lockedTags[lockedTags.length - 1];

        lastTag.oncanplaythrough = function ()
        {
            lastTag.oncanplaythrough = null;

            lockedTags.forEach(function (tag)
            {
                tag.dataset.locked = 'false';
            });
        };

        lockedTags.forEach(function (tag)
        {
            tag.load();
        });

        console.log('unlocked event handler', this.lockedActionsQueue.length);

        this.forEachActiveSound(function (sound)
        {
            if (sound.currentMarker === null && sound.duration === 0)
            {
                sound.duration = sound.tags[0].duration;
            }

            sound.totalDuration = sound.tags[0].duration;
        });

        var len = this.lockedActionsQueue.length;

        for (var i = 0; i < len; i++)
        {
            var lockedAction = this.lockedActionsQueue.shift();

            console.log(lockedAction);

            if (lockedAction.sound[lockedAction.prop].apply)
            {
                lockedAction.sound[lockedAction.prop].apply(lockedAction.sound, lockedAction.value || []);
            }
            else
            {
                lockedAction.sound[lockedAction.prop] = lockedAction.value;
            }
        }

        /*
        var _this = this;

        this.game.cache.audio.entries.each(function (key, tags)
        {
            for (var i = 0; i < tags.length; i++)
            {
                if (tags[i].dataset.locked === 'true')
                {
                    console.log('dataset locked', i);

                    _this.locked = true;

                    return false;
                }
            }

            return true;
        });

        var moved = false;

        var detectMove = function ()
        {
            moved = true;
        };
        */

        /*
        var unlock = function ()
        {
            console.log('unlock->unlock!', moved);

            if (moved)
            {
                moved = false;
                return;
            }

            document.body.removeEventListener('touchmove', detectMove);
            document.body.removeEventListener('touchend', unlock);

            _this.emit(Events.UNLOCKED, _this);

            var lockedTags = [];

            _this.game.cache.audio.entries.each(function (key, tags)
            {
                for (var i = 0; i < tags.length; i++)
                {
                    var tag = tags[i];

                    if (tag.dataset.locked === 'true')
                    {
                        lockedTags.push(tag);
                    }
                }

                return true;
            });

            if (lockedTags.length === 0)
            {
                return;
            }

            var lastTag = lockedTags[lockedTags.length - 1];

            lastTag.oncanplaythrough = function ()
            {
                lastTag.oncanplaythrough = null;

                lockedTags.forEach(function (tag)
                {
                    tag.dataset.locked = 'false';
                });

                _this.unlocked = true;
            };

            lockedTags.forEach(function (tag)
            {
                tag.load();
            });
        };

        this.once(Events.UNLOCKED, function ()
        {
            console.log('unlocked event handler', this.lockedActionsQueue.length);

            this.forEachActiveSound(function (sound)
            {
                if (sound.currentMarker === null && sound.duration === 0)
                {
                    sound.duration = sound.tags[0].duration;
                }

                sound.totalDuration = sound.tags[0].duration;
            });

            var len = this.lockedActionsQueue.length;

            for (var i = 0; i < len; i++)
            {
                var lockedAction = this.lockedActionsQueue.shift();

                console.log(lockedAction);

                if (lockedAction.sound[lockedAction.prop].apply)
                {
                    lockedAction.sound[lockedAction.prop].apply(lockedAction.sound, lockedAction.value || []);
                }
                else
                {
                    lockedAction.sound[lockedAction.prop] = lockedAction.value;
                }
            }
        }, this);

        console.log('unlock added listeners');

        document.body.addEventListener('touchmove', detectMove, false);
        document.body.addEventListener('touchend', unlock, false);
        */
    },

    /**
     * Method used internally for pausing sound manager if
     * Phaser.Sound.HTML5AudioSoundManager#pauseOnBlur is set to true.
     *
     * @method Phaser.Sound.HTML5AudioSoundManager#onBlur
     * @protected
     * @since 3.0.0
     */
    onBlur: function ()
    {
        this.forEachActiveSound(function (sound)
        {
            if (sound.isPlaying)
            {
                this.onBlurPausedSounds.push(sound);
                sound.onBlur();
            }
        });
    },

    /**
     * Method used internally for resuming sound manager if
     * Phaser.Sound.HTML5AudioSoundManager#pauseOnBlur is set to true.
     *
     * @method Phaser.Sound.HTML5AudioSoundManager#onFocus
     * @protected
     * @since 3.0.0
     */
    onFocus: function ()
    {
        this.onBlurPausedSounds.forEach(function (sound)
        {
            sound.onFocus();
        });

        this.onBlurPausedSounds.length = 0;
    },

    /**
     * Method used internally by Phaser.Sound.HTML5AudioSound class methods and property setters
     * to check if sound manager is locked and then either perform action immediately or queue it
     * to be performed once the sound manager gets unlocked.
     *
     * @method Phaser.Sound.HTML5AudioSoundManager#isLocked
     * @protected
     * @since 3.0.0
     *
     * @param {Phaser.Sound.HTML5AudioSound} sound - Sound object on which to perform queued action.
     * @param {string} prop - Name of the method to be called or property to be assigned a value to.
     * @param {*} [value] - An optional parameter that either holds an array of arguments to be passed to the method call or value to be set to the property.
     *
     * @return {boolean} Whether the sound manager is locked.
     */
    isLocked: function (sound, prop, value)
    {
        if (sound.tags[0].dataset.locked === 'true')
        {
            this.lockedActionsQueue.push({
                sound: sound,
                prop: prop,
                value: value
            });

            return true;
        }

        return false;
    },

    /**
     * Sets the muted state of all this Sound Manager.
     *
     * @method Phaser.Sound.HTML5AudioSoundManager#setMute
     * @fires Phaser.Sound.Events#GLOBAL_MUTE
     * @since 3.3.0
     *
     * @param {boolean} value - `true` to mute all sounds, `false` to unmute them.
     *
     * @return {Phaser.Sound.HTML5AudioSoundManager} This Sound Manager.
     */
    setMute: function (value)
    {
        this.mute = value;

        return this;
    },

    /**
     * Sets the volume of this Sound Manager.
     *
     * @method Phaser.Sound.HTML5AudioSoundManager#setVolume
     * @fires Phaser.Sound.Events#GLOBAL_VOLUME
     * @since 3.3.0
     *
     * @param {number} value - The global volume of this Sound Manager.
     *
     * @return {Phaser.Sound.HTML5AudioSoundManager} This Sound Manager.
     */
    setVolume: function (value)
    {
        this.volume = value;

        return this;
    },

    /**
     * @name Phaser.Sound.HTML5AudioSoundManager#volume
     * @type {number}
     * @fires Phaser.Sound.Events#GLOBAL_VOLUME
     * @since 3.0.0
     */
    volume: {

        get: function ()
        {
            return this._volume;
        },

        set: function (value)
        {
            this._volume = value;

            this.forEachActiveSound(function (sound)
            {
                sound.updateVolume();
            });

            this.emit(Events.GLOBAL_VOLUME, this, value);
        }

    },

    /**
     * @name Phaser.Sound.HTML5AudioSoundManager#mute
     * @type {boolean}
     * @fires Phaser.Sound.Events#GLOBAL_MUTE
     * @since 3.0.0
     */
    mute: {

        get: function ()
        {
            return this._mute;
        },

        set: function (value)
        {
            this._mute = value;

            this.forEachActiveSound(function (sound)
            {
                sound.updateMute();
            });

            this.emit(Events.GLOBAL_MUTE, this, value);
        }

    },

    /**
     * Calls Phaser.Sound.BaseSoundManager#destroy method
     * and cleans up all HTML5 Audio related stuff.
     *
     * @method Phaser.Sound.HTML5AudioSoundManager#destroy
     * @since 3.0.0
     */
    destroy: function ()
    {
        BaseSoundManager.prototype.destroy.call(this);

        this.onBlurPausedSounds.length = 0;
        this.onBlurPausedSounds = null;
    }

});

module.exports = HTML5AudioSoundManager;
<|endoftext|>