<commit_before>define(["underscore", "flow", "sprd/util/ProductUtil", 'text/entity/TextFlow', 'sprd/type/Style', 'sprd/entity/DesignConfiguration', 'sprd/entity/TextConfiguration'],
    function(_, flow, ProductUtil, TextFlow, Style, DesignConfiguration, TextConfiguration) {

    return {

        /***
         * set the product type and converts all configurations
         *
         * @param {sprd.model.ProductType} productType
         * @param callback
         */
        setProductType: function (product, productType, callback) {

            var self = this,
                appearance,
                view;

            flow()
                .seq(function (cb) {
                    productType.fetch(null, cb);
                })
                .seq(function () {
                    if (product.$.appearance) {
                        appearance = productType.getClosestAppearance(product.$.appearance.getMainColor());
                    } else {
                        appearance = productType.getDefaultAppearance();
                    }
                })
                .seq(function () {
                    // determinate closest view for new product type
                    var currentView = product.$.view;

                    if (currentView) {
                        view = productType.getViewByPerspective(currentView.$.perspective);
                    }

                    if (!view) {
                        view = productType.getDefaultView();
                    }

                })
                .seq(function () {
                    // TODO: convert all configurations: size, position, print type

                    var configurations = product.$.configurations.$items,
                        removeConfigurations = [];

                    for (var i = 0; i < configurations.length; i++) {
                        var configuration = configurations[i],
                            currentPrintArea = configuration.$.printArea,
                            currentView = currentPrintArea.getDefaultView(),
                            targetView = null,
                            targetPrintArea = null;

                        if (currentView) {
                            targetView = productType.getViewByPerspective(currentView.$.perspective);
                        }

                        if (targetView) {
                            targetPrintArea = targetView.getDefaultPrintArea();
                        }

                        if (targetPrintArea && configuration.isAllowedOnPrintArea(targetPrintArea)) {
                            configuration.set('printArea', targetPrintArea);

                            var currentPrintAreaWidth = currentPrintArea.get("boundary.size.width");
                            var currentPrintAreaHeight = currentPrintArea.get("boundary.size.height");
                            var targetPrintAreaWidth = targetPrintArea.get("boundary.size.width");
                            var targetPrintAreaHeight = targetPrintArea.get("boundary.size.height");

                            var preferredPrintType = null;
                            var preferredScale;
                            var preferredOffset;

                            var currentConfigurationWidth = configuration.width();
                            var currentConfigurationHeight = configuration.height();

                            // find new print type
                            var possiblePrintTypes = configuration.getPossiblePrintTypesForPrintArea(targetPrintArea, appearance.$.id);
                            var printType = configuration.$.printType;

                            var center = {
                                x: configuration.$.offset.$.x + currentConfigurationWidth / 2,
                                y: configuration.$.offset.$.y + currentConfigurationHeight / 2
                            };

                            if (printType && !_.contains(possiblePrintTypes, printType)) {
                                // print type not possible any more
                                printType = null;
                            }

                            if (printType) {
                                var index = _.indexOf(possiblePrintTypes, printType);
                                if (index >= 0) {
                                    // remove print type from original position
                                    possiblePrintTypes.splice(index, 1);
                                }

                                // and add it to first position
                                possiblePrintTypes.unshift(printType);
                            }

                            var optimalScale = Math.min(
                                targetPrintAreaWidth / currentPrintAreaWidth,
                                targetPrintAreaHeight / currentPrintAreaHeight
                            ) * Math.abs(configuration.$.scale.x);

                            var allowScale = configuration.allowScale();

                            for (var j = 0; j < possiblePrintTypes.length; j++) {
                                printType = possiblePrintTypes[j];

                                var factor = optimalScale;
                                var minimumScale = optimalScale;

                                if (printType.isEnlargeable()) {
                                    minimumScale = configuration.minimumScale();
                                }

                                var configurationPrintTypeSize = configuration.getSizeForPrintType(printType);

                                var maximumScale = Math.min(
                                    printType.get("size.width") / configurationPrintTypeSize.$.width,
                                    printType.get("size.height") / configurationPrintTypeSize.$.height);

                                if (!allowScale && (maximumScale < 1 || minimumScale > 1)) {
                                    continue;
                                }
                                if (minimumScale > maximumScale) {
                                    continue;
                                }

                                factor = Math.max(factor, minimumScale);
                                factor = Math.min(factor, maximumScale);

                                preferredScale = {
                                    x: factor,
                                    y: factor
                                };

                                preferredPrintType = printType;
                                break;
                            }

                            if (preferredPrintType) {

                                configuration.set({
                                    printType: preferredPrintType,
                                    scale: preferredScale
                                });

                                preferredOffset = {
                                    x: targetPrintAreaWidth * center.x / currentPrintAreaWidth - configuration.width() / 2,
                                    y: targetPrintAreaHeight * center.y / currentPrintAreaHeight - configuration.height() / 2
                                };

                                configuration.$.offset.set(preferredOffset);

                            } else {
                                // remove configuration
                                removeConfigurations.push(configuration);
                            }

                        } else {
                            // no print area found, remove configuration
                            removeConfigurations.push(configuration);
                        }
                    }

                    product.$.configurations.remove(removeConfigurations);

                })
                .seq(function () {
                    // first set product type
                    // and then the appearance, because appearance depends on product type
                    product.set({
                        productType: productType,
                        view: view,
                        appearance: appearance
                    });
                })
                .exec(callback);

        },

        addDesign: function (product, params, callback) {
            params = _.defaults({}, params, {
                design: null,
                perspective: null, // front, back, etc...
                view: null,
                printArea: null,
                printType: null,
                designColorRGBs: null,
                designColorIds: null
            });

            var self = this,
                design = params.design,
                productType = product.$.productType,
                printArea = params.printArea,
                view = params.view,
                appearance = product.$.appearance,
                printType = params.printType;

            if (!design) {
                callback(new Error("No design"));
                return;
            }

            if (!productType) {
                callback(new Error("ProductType not set"));
                return;
            }

            if (!appearance) {
                callback(new Error("Appearance for product not set"));
                return;
            }

            flow()
                .par(function (cb) {
                    design.fetch(null, cb);
                }, function (cb) {
                    productType.fetch(null, cb);
                })
                .seq("printArea", function () {

                    if (!printArea && params.perspective && !view) {
                        view = productType.getViewByPerspective(params.perspective);
                    }

                    if (!printArea && view) {
                        // get print area by view
                        if (!productType.containsView(view)) {
                            throw new Error("View not on ProductType");
                        }

                        // TODO: look for print area that supports print types, etc...
                        printArea = view.getDefaultPrintArea();
                    }

                    view = product.$.view || product.getDefaultView();
                    if (!printArea && view) {
                        printArea = view.getDefaultPrintArea();
                    }

                    if (!printArea) {
                        throw new Error("target PrintArea couldn't be found.");
                    }

                    if (printArea.get("restrictions.designAllowed") === false) {
                        throw new Error("designs cannot be added to this print area");
                    }

                    return printArea;
                })
                .seq("printType", function () {
                    var possiblePrintTypes = ProductUtil.getPossiblePrintTypesForDesignOnPrintArea(design, printArea, appearance.$.id);

                    if (printType && !_.contains(possiblePrintTypes, printType)) {
                        throw new Error("PrintType not possible for design and printArea");
                    }

                    printType = printType || possiblePrintTypes[0];

                    if (!printType) {
                        throw new Error("No printType available");
                    }

                    return printType;
                })
                .seq(function (cb) {
                    printType.fetch(null, cb);
                })
                .seq("designConfiguration", function () {
                    var entity = product.createEntity(DesignConfiguration);
                    entity.set({
                        printType: printType,
                        printArea: printArea,
                        design: design,
                        designColorIds: params.designColorIds,
                        designColorRGBs: params.designColorRGBs
                    });
                    return entity;
                })
                .seq(function (cb) {
                    this.vars["designConfiguration"].init(cb);
                })
                .seq(function () {
                    // determinate position
                    self._positionConfiguration(this.vars["designConfiguration"]);
                })
                .exec(function (err, results) {
                    !err && product._addConfiguration(results.designConfiguration);
                    callback && callback(err, results.designConfiguration);
                });

        },

        addText: function (product, params, callback) {

            params = _.defaults({}, params, {
                text: null,
                fontFamily: null,
                perspective: null, // front, back, etc...
                view: null,
                printArea: null,
                printType: null,
                fontStyle: "normal",
                fontWeight: "normal"
            });

            var self = this,
                context = product.$.context,
                text = params.text,
                productType = product.$.productType,
                printArea = params.printArea,
                view = params.view,
                font = null,
                appearance = product.$.appearance,
                printType = params.printType;

            if (!text) {
                callback(new Error("No text"));
                return;
            }

            if (!productType) {
                callback(new Error("ProductType not set"));
                return;
            }

            if (!appearance) {
                callback(new Error("Appearance for product not set"));
                return;
            }

            flow()
                .par({
                    fontFamilies: function (cb) {
                        if (params.fontFamily) {
                            cb();
                        } else {
                            context.$.fontFamilies.fetch({
                                fullData: true
                            }, cb);
                        }
                    },
                    productType: function (cb) {
                        productType.fetch(null, cb);
                    }
                })
                .seq("fontFamily", function () {
                    var fontFamily = params.fontFamily || this.vars["fontFamilies"].at(0);
                    if (!fontFamily) {
                        throw new Error("No found");
                    }

                    font = fontFamily.getFont(params.fontWeight, params.fontStyle);

                    if (!font) {
                        product.log("Font with for required style & weight not found. Fallback to default font", "warn");
                    }

                    font = font || fontFamily.getDefaultFont();

                    if (!font) {
                        throw new Error("No font in family found");
                    }

                    return fontFamily;
                })
                .seq("printArea", function () {

                    if (!printArea && params.perspective && !view) {
                        view = productType.getViewByPerspective(params.perspective);
                    }

                    if (!printArea && view) {
                        // get print area by view
                        if (!productType.containsView(view)) {
                            throw new Error("View not on ProductType");
                        }

                        // TODO: look for print area that supports print types, etc...
                        printArea = view.getDefaultPrintArea();
                    }

                    view = product.$.view || product.getDefaultView();
                    if (!printArea && view) {
                        printArea = view.getDefaultPrintArea();
                    }

                    if (!printArea) {
                        throw new Error("target PrintArea couldn't be found.");
                    }

                    if (printArea.get("restrictions.textAllowed") === false) {
                        throw new Error("text cannot be added to this print area");
                    }

                    return printArea;
                })
                .seq("printType", function () {
                    var fontFamily = this.vars.fontFamily;
                    var possiblePrintTypes = ProductUtil.getPossiblePrintTypesForTextOnPrintArea(fontFamily, printArea, appearance.$.id);

                    if (printType && !_.contains(possiblePrintTypes, printType)) {
                        throw new Error("PrintType not possible for text and printArea");
                    }

                    printType = printType || possiblePrintTypes[0];

                    if (!printType) {
                        throw new Error("No printType available");
                    }

                    return printType;
                })
                .seq(function (cb) {
                    printType.fetch(null, cb);
                })
                .seq("printTypeColor", function () {
                    var color = product.appearanceBrightness() !== "dark" ? "#000000" : "#FFFFFF";
                    color = printType.getClosestPrintColor(color);

                    if (!color) {
                        throw "No print type color";
                    }

                    return color;
                })
                .seq("configuration", function () {

                    var textFlow = TextFlow.initializeFromText(text);
                    textFlow.set("style", new Style({
                        font: font,
                        fontSize: 20,
                        printTypeColor: this.vars["printTypeColor"]
                    }));

                    var entity = product.createEntity(TextConfiguration);
                    entity.set({
                        printType: printType,
                        printArea: printArea,
                        textFlow: textFlow
                    });
                    return entity;
                })
                .seq(function (cb) {
                    this.vars["configuration"].init(cb);
                })
                .seq(function () {
                    // determinate position
                    self._positionConfiguration(this.vars["configuration"]);
                })
                .exec(function (err, results) {
                    !err && product._addConfiguration(results.configuration);
                    callback && callback(err, results.configuration);
                });

        },

        _positionConfiguration: function (configuration) {

            var printArea = configuration.$.printArea,
                printAreaWidth = printArea.get("boundary.size.width"),
                printAreaHeight = printArea.get("boundary.size.height"),
                defaultBox = printArea.$.defaultBox || {
                    x: 0,
                    y: 0,
                    width: printAreaWidth,
                    height: printAreaHeight
                },
                boundingBox,
                defaultBoxCenterX = defaultBox.x + defaultBox.width / 2,
                defaultBoxCenterY = defaultBox.y + defaultBox.height / 2,
                offset = configuration.$.offset.clone(),
                newScale;

            boundingBox = configuration._getBoundingBox();

            // position centered within defaultBox
            offset.set({
                x: defaultBoxCenterX - boundingBox.width / 2,
                y: defaultBox.y
            });

            if (offset.$.x < 0 || offset.$.x + boundingBox.width > printAreaWidth) {

                // hard boundary error
                var maxPossibleWidthToHardBoundary = Math.min(defaultBoxCenterX, printAreaWidth - defaultBoxCenterX) * 2;

                // scale to avoid hard boundary error
                var scaleToAvoidCollision = maxPossibleWidthToHardBoundary / boundingBox.width;

                // scale to fit into default box
                var scaleToFixDefaultBox = defaultBox.width / boundingBox.width;

                // TODO: first use scaleToFixDefaultBox and use scaleToAvoidCollission only if
                // scaleToFitDefaultBox is not possible for print type

                newScale = scaleToFixDefaultBox; // scaleToFixDefaultBox;

                configuration.set("scale", {
                    x: newScale,
                    y: newScale
                });

                boundingBox = configuration._getBoundingBox();

                // position centered within defaultBox
                offset.set({
                    x: defaultBoxCenterX - boundingBox.width / 2,
                    y: defaultBox.y
                });
            }

            if (boundingBox.height > printAreaHeight) {
                // y-scale needed to fit print area

                // calculate maxScale to fix height
                var maxScaleToFitPrintArea = configuration.$.scale.y * printAreaHeight / boundingBox.height;
                var maxScaleToFitDefaultBox = configuration.$.scale.y * defaultBox.height / boundingBox.height;

                // TODO: try the two different scales, prefer defaultBox and fallback to printArea if size to small
                newScale = maxScaleToFitPrintArea;

                configuration.set("scale", {
                    x: newScale,
                    y: newScale
                });

                boundingBox = configuration._getBoundingBox();

                // position centered within defaultBox
                offset.set({
                    x: defaultBoxCenterX - boundingBox.width / 2,
                    y: defaultBoxCenterY - boundingBox.height / 2
                });

            }

            if (offset.$.y < 0 || offset.$.y + boundingBox.height > printAreaHeight) {
                // hard boundary error

                // center in print area
                offset.set({
                    y: printAreaHeight / 2 - boundingBox.height / 2
                });
            }

            configuration.set({
                offset: offset
            });

        }

    };

});<commit_msg>apply initial formatting via ApplyStyleToElementOperation<commit_after>define(["underscore", "flow", "sprd/util/ProductUtil", 'text/entity/TextFlow', 'sprd/type/Style', 'sprd/entity/DesignConfiguration', 'sprd/entity/TextConfiguration', 'text/operation/ApplyStyleToElementOperation', 'text/entity/TextRange'],
    function (_, flow, ProductUtil, TextFlow, Style, DesignConfiguration, TextConfiguration, ApplyStyleToElementOperation, TextRange) {

        return {

            /***
             * set the product type and converts all configurations
             *
             * @param {sprd.model.ProductType} productType
             * @param callback
             */
            setProductType: function (product, productType, callback) {

                var self = this,
                    appearance,
                    view;

                flow()
                    .seq(function (cb) {
                        productType.fetch(null, cb);
                    })
                    .seq(function () {
                        if (product.$.appearance) {
                            appearance = productType.getClosestAppearance(product.$.appearance.getMainColor());
                        } else {
                            appearance = productType.getDefaultAppearance();
                        }
                    })
                    .seq(function () {
                        // determinate closest view for new product type
                        var currentView = product.$.view;

                        if (currentView) {
                            view = productType.getViewByPerspective(currentView.$.perspective);
                        }

                        if (!view) {
                            view = productType.getDefaultView();
                        }

                    })
                    .seq(function () {
                        // TODO: convert all configurations: size, position, print type

                        var configurations = product.$.configurations.$items,
                            removeConfigurations = [];

                        for (var i = 0; i < configurations.length; i++) {
                            var configuration = configurations[i],
                                currentPrintArea = configuration.$.printArea,
                                currentView = currentPrintArea.getDefaultView(),
                                targetView = null,
                                targetPrintArea = null;

                            if (currentView) {
                                targetView = productType.getViewByPerspective(currentView.$.perspective);
                            }

                            if (targetView) {
                                targetPrintArea = targetView.getDefaultPrintArea();
                            }

                            if (targetPrintArea && configuration.isAllowedOnPrintArea(targetPrintArea)) {
                                configuration.set('printArea', targetPrintArea);

                                var currentPrintAreaWidth = currentPrintArea.get("boundary.size.width");
                                var currentPrintAreaHeight = currentPrintArea.get("boundary.size.height");
                                var targetPrintAreaWidth = targetPrintArea.get("boundary.size.width");
                                var targetPrintAreaHeight = targetPrintArea.get("boundary.size.height");

                                var preferredPrintType = null;
                                var preferredScale;
                                var preferredOffset;

                                var currentConfigurationWidth = configuration.width();
                                var currentConfigurationHeight = configuration.height();

                                // find new print type
                                var possiblePrintTypes = configuration.getPossiblePrintTypesForPrintArea(targetPrintArea, appearance.$.id);
                                var printType = configuration.$.printType;

                                var center = {
                                    x: configuration.$.offset.$.x + currentConfigurationWidth / 2,
                                    y: configuration.$.offset.$.y + currentConfigurationHeight / 2
                                };

                                if (printType && !_.contains(possiblePrintTypes, printType)) {
                                    // print type not possible any more
                                    printType = null;
                                }

                                if (printType) {
                                    var index = _.indexOf(possiblePrintTypes, printType);
                                    if (index >= 0) {
                                        // remove print type from original position
                                        possiblePrintTypes.splice(index, 1);
                                    }

                                    // and add it to first position
                                    possiblePrintTypes.unshift(printType);
                                }

                                var optimalScale = Math.min(
                                    targetPrintAreaWidth / currentPrintAreaWidth,
                                    targetPrintAreaHeight / currentPrintAreaHeight
                                ) * Math.abs(configuration.$.scale.x);

                                var allowScale = configuration.allowScale();

                                for (var j = 0; j < possiblePrintTypes.length; j++) {
                                    printType = possiblePrintTypes[j];

                                    var factor = optimalScale;
                                    var minimumScale = optimalScale;

                                    if (printType.isEnlargeable()) {
                                        minimumScale = configuration.minimumScale();
                                    }

                                    var configurationPrintTypeSize = configuration.getSizeForPrintType(printType);

                                    var maximumScale = Math.min(
                                        printType.get("size.width") / configurationPrintTypeSize.$.width,
                                        printType.get("size.height") / configurationPrintTypeSize.$.height);

                                    if (!allowScale && (maximumScale < 1 || minimumScale > 1)) {
                                        continue;
                                    }
                                    if (minimumScale > maximumScale) {
                                        continue;
                                    }

                                    factor = Math.max(factor, minimumScale);
                                    factor = Math.min(factor, maximumScale);

                                    preferredScale = {
                                        x: factor,
                                        y: factor
                                    };

                                    preferredPrintType = printType;
                                    break;
                                }

                                if (preferredPrintType) {

                                    configuration.set({
                                        printType: preferredPrintType,
                                        scale: preferredScale
                                    });

                                    preferredOffset = {
                                        x: targetPrintAreaWidth * center.x / currentPrintAreaWidth - configuration.width() / 2,
                                        y: targetPrintAreaHeight * center.y / currentPrintAreaHeight - configuration.height() / 2
                                    };

                                    configuration.$.offset.set(preferredOffset);

                                } else {
                                    // remove configuration
                                    removeConfigurations.push(configuration);
                                }

                            } else {
                                // no print area found, remove configuration
                                removeConfigurations.push(configuration);
                            }
                        }

                        product.$.configurations.remove(removeConfigurations);

                    })
                    .seq(function () {
                        // first set product type
                        // and then the appearance, because appearance depends on product type
                        product.set({
                            productType: productType,
                            view: view,
                            appearance: appearance
                        });
                    })
                    .exec(callback);

            },

            addDesign: function (product, params, callback) {
                params = _.defaults({}, params, {
                    design: null,
                    perspective: null, // front, back, etc...
                    view: null,
                    printArea: null,
                    printType: null,
                    designColorRGBs: null,
                    designColorIds: null
                });

                var self = this,
                    design = params.design,
                    productType = product.$.productType,
                    printArea = params.printArea,
                    view = params.view,
                    appearance = product.$.appearance,
                    printType = params.printType;

                if (!design) {
                    callback(new Error("No design"));
                    return;
                }

                if (!productType) {
                    callback(new Error("ProductType not set"));
                    return;
                }

                if (!appearance) {
                    callback(new Error("Appearance for product not set"));
                    return;
                }

                flow()
                    .par(function (cb) {
                        design.fetch(null, cb);
                    }, function (cb) {
                        productType.fetch(null, cb);
                    })
                    .seq("printArea", function () {

                        if (!printArea && params.perspective && !view) {
                            view = productType.getViewByPerspective(params.perspective);
                        }

                        if (!printArea && view) {
                            // get print area by view
                            if (!productType.containsView(view)) {
                                throw new Error("View not on ProductType");
                            }

                            // TODO: look for print area that supports print types, etc...
                            printArea = view.getDefaultPrintArea();
                        }

                        view = product.$.view || product.getDefaultView();
                        if (!printArea && view) {
                            printArea = view.getDefaultPrintArea();
                        }

                        if (!printArea) {
                            throw new Error("target PrintArea couldn't be found.");
                        }

                        if (printArea.get("restrictions.designAllowed") === false) {
                            throw new Error("designs cannot be added to this print area");
                        }

                        return printArea;
                    })
                    .seq("printType", function () {
                        var possiblePrintTypes = ProductUtil.getPossiblePrintTypesForDesignOnPrintArea(design, printArea, appearance.$.id);

                        if (printType && !_.contains(possiblePrintTypes, printType)) {
                            throw new Error("PrintType not possible for design and printArea");
                        }

                        printType = printType || possiblePrintTypes[0];

                        if (!printType) {
                            throw new Error("No printType available");
                        }

                        return printType;
                    })
                    .seq(function (cb) {
                        printType.fetch(null, cb);
                    })
                    .seq("designConfiguration", function () {
                        var entity = product.createEntity(DesignConfiguration);
                        entity.set({
                            printType: printType,
                            printArea: printArea,
                            design: design,
                            designColorIds: params.designColorIds,
                            designColorRGBs: params.designColorRGBs
                        });
                        return entity;
                    })
                    .seq(function (cb) {
                        this.vars["designConfiguration"].init(cb);
                    })
                    .seq(function () {
                        // determinate position
                        self._positionConfiguration(this.vars["designConfiguration"]);
                    })
                    .exec(function (err, results) {
                        !err && product._addConfiguration(results.designConfiguration);
                        callback && callback(err, results.designConfiguration);
                    });

            },

            addText: function (product, params, callback) {

                params = _.defaults({}, params, {
                    text: null,
                    fontFamily: null,
                    perspective: null, // front, back, etc...
                    view: null,
                    printArea: null,
                    printType: null,
                    fontStyle: "normal",
                    fontWeight: "normal"
                });

                var self = this,
                    context = product.$.context,
                    text = params.text,
                    productType = product.$.productType,
                    printArea = params.printArea,
                    view = params.view,
                    font = null,
                    appearance = product.$.appearance,
                    printType = params.printType;

                if (!text) {
                    callback(new Error("No text"));
                    return;
                }

                if (!productType) {
                    callback(new Error("ProductType not set"));
                    return;
                }

                if (!appearance) {
                    callback(new Error("Appearance for product not set"));
                    return;
                }

                flow()
                    .par({
                        fontFamilies: function (cb) {
                            if (params.fontFamily) {
                                cb();
                            } else {
                                context.$.fontFamilies.fetch({
                                    fullData: true
                                }, cb);
                            }
                        },
                        productType: function (cb) {
                            productType.fetch(null, cb);
                        }
                    })
                    .seq("fontFamily", function () {
                        var fontFamily = params.fontFamily || this.vars["fontFamilies"].at(0);
                        if (!fontFamily) {
                            throw new Error("No found");
                        }

                        font = fontFamily.getFont(params.fontWeight, params.fontStyle);

                        if (!font) {
                            product.log("Font with for required style & weight not found. Fallback to default font", "warn");
                        }

                        font = font || fontFamily.getDefaultFont();

                        if (!font) {
                            throw new Error("No font in family found");
                        }

                        return fontFamily;
                    })
                    .seq("printArea", function () {

                        if (!printArea && params.perspective && !view) {
                            view = productType.getViewByPerspective(params.perspective);
                        }

                        if (!printArea && view) {
                            // get print area by view
                            if (!productType.containsView(view)) {
                                throw new Error("View not on ProductType");
                            }

                            // TODO: look for print area that supports print types, etc...
                            printArea = view.getDefaultPrintArea();
                        }

                        view = product.$.view || product.getDefaultView();
                        if (!printArea && view) {
                            printArea = view.getDefaultPrintArea();
                        }

                        if (!printArea) {
                            throw new Error("target PrintArea couldn't be found.");
                        }

                        if (printArea.get("restrictions.textAllowed") === false) {
                            throw new Error("text cannot be added to this print area");
                        }

                        return printArea;
                    })
                    .seq("printType", function () {
                        var fontFamily = this.vars.fontFamily;
                        var possiblePrintTypes = ProductUtil.getPossiblePrintTypesForTextOnPrintArea(fontFamily, printArea, appearance.$.id);

                        if (printType && !_.contains(possiblePrintTypes, printType)) {
                            throw new Error("PrintType not possible for text and printArea");
                        }

                        printType = printType || possiblePrintTypes[0];

                        if (!printType) {
                            throw new Error("No printType available");
                        }

                        return printType;
                    })
                    .seq(function (cb) {
                        printType.fetch(null, cb);
                    })
                    .seq("printTypeColor", function () {
                        var color = product.appearanceBrightness() !== "dark" ? "#000000" : "#FFFFFF";
                        color = printType.getClosestPrintColor(color);

                        if (!color) {
                            throw "No print type color";
                        }

                        return color;
                    })
                    .seq("configuration", function () {

                        var textFlow = TextFlow.initializeFromText(text);

                        (new ApplyStyleToElementOperation(TextRange.createTextRange(0, textFlow.textLength()), textFlow, new Style({
                            font: font,
                            fontSize: 20,
                            printTypeColor: this.vars["printTypeColor"]
                        }))).doOperation();

                        var entity = product.createEntity(TextConfiguration);
                        entity.set({
                            printType: printType,
                            printArea: printArea,
                            textFlow: textFlow
                        });
                        return entity;
                    })
                    .seq(function (cb) {
                        this.vars["configuration"].init(cb);
                    })
                    .seq(function () {
                        // determinate position
                        self._positionConfiguration(this.vars["configuration"]);
                    })
                    .exec(function (err, results) {
                        !err && product._addConfiguration(results.configuration);
                        callback && callback(err, results.configuration);
                    });

            },

            _positionConfiguration: function (configuration) {

                var printArea = configuration.$.printArea,
                    printAreaWidth = printArea.get("boundary.size.width"),
                    printAreaHeight = printArea.get("boundary.size.height"),
                    defaultBox = printArea.$.defaultBox || {
                        x: 0,
                        y: 0,
                        width: printAreaWidth,
                        height: printAreaHeight
                    },
                    boundingBox,
                    defaultBoxCenterX = defaultBox.x + defaultBox.width / 2,
                    defaultBoxCenterY = defaultBox.y + defaultBox.height / 2,
                    offset = configuration.$.offset.clone(),
                    newScale;

                boundingBox = configuration._getBoundingBox();

                // position centered within defaultBox
                offset.set({
                    x: defaultBoxCenterX - boundingBox.width / 2,
                    y: defaultBox.y
                });

                if (offset.$.x < 0 || offset.$.x + boundingBox.width > printAreaWidth) {

                    // hard boundary error
                    var maxPossibleWidthToHardBoundary = Math.min(defaultBoxCenterX, printAreaWidth - defaultBoxCenterX) * 2;

                    // scale to avoid hard boundary error
                    var scaleToAvoidCollision = maxPossibleWidthToHardBoundary / boundingBox.width;

                    // scale to fit into default box
                    var scaleToFixDefaultBox = defaultBox.width / boundingBox.width;

                    // TODO: first use scaleToFixDefaultBox and use scaleToAvoidCollission only if
                    // scaleToFitDefaultBox is not possible for print type

                    newScale = scaleToFixDefaultBox; // scaleToFixDefaultBox;

                    configuration.set("scale", {
                        x: newScale,
                        y: newScale
                    });

                    boundingBox = configuration._getBoundingBox();

                    // position centered within defaultBox
                    offset.set({
                        x: defaultBoxCenterX - boundingBox.width / 2,
                        y: defaultBox.y
                    });
                }

                if (boundingBox.height > printAreaHeight) {
                    // y-scale needed to fit print area

                    // calculate maxScale to fix height
                    var maxScaleToFitPrintArea = configuration.$.scale.y * printAreaHeight / boundingBox.height;
                    var maxScaleToFitDefaultBox = configuration.$.scale.y * defaultBox.height / boundingBox.height;

                    // TODO: try the two different scales, prefer defaultBox and fallback to printArea if size to small
                    newScale = maxScaleToFitPrintArea;

                    configuration.set("scale", {
                        x: newScale,
                        y: newScale
                    });

                    boundingBox = configuration._getBoundingBox();

                    // position centered within defaultBox
                    offset.set({
                        x: defaultBoxCenterX - boundingBox.width / 2,
                        y: defaultBoxCenterY - boundingBox.height / 2
                    });

                }

                if (offset.$.y < 0 || offset.$.y + boundingBox.height > printAreaHeight) {
                    // hard boundary error

                    // center in print area
                    offset.set({
                        y: printAreaHeight / 2 - boundingBox.height / 2
                    });
                }

                configuration.set({
                    offset: offset
                });

            }

        };

    });<|endoftext|>


<commit_before>const {client} = require('nightwatch-cucumber');
const {defineSupportCode} = require('cucumber');

defineSupportCode(({Given, Then}) => {

    Given(/^I open the home page$/, () => {
        const homePage = client.page.home();

        return homePage
            .navigate()
            .waitForElementVisible('@body', 1000);
    });

    Then(/^the title is "(.*?)"$/, (text) => {
        return client.assert.title(text);
    });

    Then(/^the page should contain text "(.*?)"$/, (text) => {
        const homePage = client.page.home();
        return homePage.assert.containsText('@root', text);
    });
});<commit_msg>Extract home page from steps<commit_after>const {client} = require('nightwatch-cucumber');
const {defineSupportCode} = require('cucumber');

const homePage = client.page.home();

defineSupportCode(({Given, Then}) => {

    Given(/^I open the home page$/, () => {
        return homePage
            .navigate()
            .waitForElementVisible('@body', 1000);
    });

    Then(/^the title is "(.*?)"$/, (text) => {
        return client.assert.title(text);
    });

    Then(/^the page should contain text "(.*?)"$/, (text) => {
        return homePage.assert.containsText('@root', text);
    });
});<|endoftext|>


<commit_before>/**
 * Flat view class.
 *
 * @constructor FORGE.ViewFlat
 * @param {FORGE.Viewer} viewer - {@link FORGE.Viewer} reference.
 * @param {Object} [options] - The view options
 * @extends {FORGE.ViewBase}
 */
FORGE.ViewFlat = function(viewer, options)
{
    FORGE.ViewBase.call(this, viewer, options, "ViewFlat", FORGE.ViewType.FLAT);

    /**
     * Repeat texture horizontally
     * @type {boolean}
     * @private
     */
    this._repeatX = false;

    /**
     * Repeat texture vertically
     * @type {boolean}
     * @private
     */
    this._repeatY = false;

    this._boot();
};

FORGE.ViewFlat.prototype = Object.create(FORGE.ViewBase.prototype);
FORGE.ViewFlat.prototype.constructor = FORGE.ViewFlat;

/**
 * Boot sequence.
 *
 * @method FORGE.ViewFlat#_boot
 * @private
 */
FORGE.ViewFlat.prototype._boot = function()
{
    FORGE.ViewBase.prototype._boot.call(this);

    this._shaderSTW = /** @type {ScreenToWorldProgram} */ (FORGE.Utils.extendSimpleObject({}, FORGE.ShaderLib.screenToWorld.flat));
    this._shaderWTS = /** @type {WorldToScreenProgram} */ (FORGE.Utils.extendSimpleObject({}, FORGE.ShaderLib.worldToScreen.flat));

    this._yawMin = FORGE.Math.degToRad(-360);
    this._yawMax = FORGE.Math.degToRad(360);

    this._pitchMin = FORGE.Math.degToRad(-180);
    this._pitchMax = FORGE.Math.degToRad(180);

    this._fovMin = FORGE.Math.degToRad(20);
    this._fovMax = FORGE.Math.degToRad(180);
};

/**
 * Update view params.
 * @method FORGE.ViewFlat#_updateViewParams
 * @private
 */
FORGE.ViewFlat.prototype._updateViewParams = function()
{
    var vfov = FORGE.Math.degToRad(this._viewer.camera.fov);

    // When repeat is ON, set yaw and pitch min and max depending on
    // texture and screen ratios

    if (this._viewer.renderer.backgroundRenderer instanceof FORGE.BackgroundShaderRenderer)
    {
        if (this._repeatX === false)
        {
            var hfov = vfov * this._viewer.renderer.displayResolution.ratio;
            var texRatio = this._viewer.renderer.backgroundRenderer.textureSize.ratio;
            this._yawMax = Math.min(360, Math.max(0, (Math.PI * texRatio - hfov) * 0.5)); // image
            this._yawMin = -this._yawMax;
        }
        else
        {
            this._yawMin = FORGE.Math.degToRad(-360);
            this._yawMax = FORGE.Math.degToRad(360);
        }

        if (this._repeatY === false)
        {
            this._pitchMax = 0.5 * Math.max(0, Math.PI - vfov);
            this._pitchMin = -this._pitchMax;
        }
        else
        {
            this._pitchMin = FORGE.Math.degToRad(-180);
            this._pitchMax = FORGE.Math.degToRad(180);
        }

        this._viewer.view.notifyChange();
    }

    // Mesh rendering in flat view is limited around -+ 20 degrees
    else
    {
        this._yawMax = this._pitchMax = FORGE.Math.degToRad(20);
        this._yawMin = -this._yawMax;
        this._pitchMin = -this._pitchMax;
    }
};

/**
 * Update uniforms.
 *
 * @method FORGE.ViewFlat#updateUniforms
 * @param {FORGEUniform} uniforms
 */
FORGE.ViewFlat.prototype.updateUniforms = function(uniforms)
{
    this._updateViewParams();

    if (typeof uniforms === "undefined")
    {
        return;
    }

    if (uniforms.hasOwnProperty("tRepeatX"))
    {
        uniforms.tRepeatX.value = this._repeatX ? 1 : 0;
    }

    if (uniforms.hasOwnProperty("tRepeatY"))
    {
        uniforms.tRepeatY.value = this._repeatY ? 1 : 0;
    }

    if (uniforms.hasOwnProperty("tYaw"))
    {
        uniforms.tYaw.value = FORGE.Math.degToRad(this._viewer.camera.yaw);
    }

    if (uniforms.hasOwnProperty("tPitch"))
    {
        uniforms.tPitch.value = FORGE.Math.degToRad(this._viewer.camera.pitch);
    }

    if (uniforms.hasOwnProperty("tFov"))
    {
        uniforms.tFov.value = FORGE.Math.degToRad(this._viewer.renderer.camera.fov);
    }
};

/**
 * Convert a point from world space to screen space.
 *
 * @method FORGE.ViewFlat#worldToScreen
 * @return {THREE.Vector2} point in screen coordinates
 */
FORGE.ViewFlat.prototype.worldToScreen = function()
{
    return new THREE.Vector2();
};

/**
 * Convert a point from screen space to world space.
 *
 * @method FORGE.ViewFlat#screenToWorld
 * @return {THREE.Vector3} world point
 */
FORGE.ViewFlat.prototype.screenToWorld = function()
{
    return new THREE.Vector3();
};

/**
 * Destroy method.
 *
 * @method FORGE.ViewFlat#destroy
 */
FORGE.ViewFlat.prototype.destroy = function()
{
    FORGE.ViewBase.prototype.destroy.call(this);
};

/**
 * Get and set the repeat X beahvior.
 * @name  FORGE.ViewFlat#repeatX
 * @type {string}
 */
Object.defineProperty(FORGE.ViewFlat.prototype, "repeatX",
{
    /** @this {FORGE.ViewFlat} */
    get: function()
    {
        return this._repeatX;
    },

    /** @this {FORGE.ViewFlat} */
    set: function(value)
    {
        this._repeatX = value;
        this._updateViewParams();

        // Notify the view manager of the change
        this._viewer.view.notifyChange();
    }
});

/**
 * Get and set the repeat Y beahvior.
 * @name  FORGE.ViewFlat#repeatY
 * @type {string}
 */
Object.defineProperty(FORGE.ViewFlat.prototype, "repeatY",
{
    /** @this {FORGE.ViewFlat} */
    get: function()
    {
        return this._repeatY;
    },

    /** @this {FORGE.ViewFlat} */
    set: function(value)
    {
        this._repeatY = value;
        this._updateViewParams();

        // Notify the view manager of the change
        this._viewer.view.notifyChange();
    }
});
<commit_msg>Read repeatX and repeatY of flat view from its options<commit_after>/**
 * Flat view class.
 *
 * @constructor FORGE.ViewFlat
 * @param {FORGE.Viewer} viewer - {@link FORGE.Viewer} reference.
 * @param {Object} [options] - The view options
 * @extends {FORGE.ViewBase}
 */
FORGE.ViewFlat = function(viewer, options)
{
    FORGE.ViewBase.call(this, viewer, options, "ViewFlat", FORGE.ViewType.FLAT);

    /**
     * Repeat texture horizontally
     * @type {boolean}
     * @private
     */
    this._repeatX = false;

    /**
     * Repeat texture vertically
     * @type {boolean}
     * @private
     */
    this._repeatY = false;

    this._boot();
};

FORGE.ViewFlat.prototype = Object.create(FORGE.ViewBase.prototype);
FORGE.ViewFlat.prototype.constructor = FORGE.ViewFlat;

/**
 * Boot sequence.
 *
 * @method FORGE.ViewFlat#_boot
 * @private
 */
FORGE.ViewFlat.prototype._boot = function()
{
    FORGE.ViewBase.prototype._boot.call(this);

    this._shaderSTW = /** @type {ScreenToWorldProgram} */ (FORGE.Utils.extendSimpleObject({}, FORGE.ShaderLib.screenToWorld.flat));
    this._shaderWTS = /** @type {WorldToScreenProgram} */ (FORGE.Utils.extendSimpleObject({}, FORGE.ShaderLib.worldToScreen.flat));

    this._yawMin = FORGE.Math.degToRad(-360);
    this._yawMax = FORGE.Math.degToRad(360);

    this._pitchMin = FORGE.Math.degToRad(-180);
    this._pitchMax = FORGE.Math.degToRad(180);

    this._fovMin = FORGE.Math.degToRad(20);
    this._fovMax = FORGE.Math.degToRad(180);

    this._repeatX = this._options.repeatX || false;
    this._repeatY = this._options.repeatY || false;
};

/**
 * Update view params.
 * @method FORGE.ViewFlat#_updateViewParams
 * @private
 */
FORGE.ViewFlat.prototype._updateViewParams = function()
{
    var vfov = FORGE.Math.degToRad(this._viewer.camera.fov);

    // When repeat is ON, set yaw and pitch min and max depending on
    // texture and screen ratios

    if (this._viewer.renderer.backgroundRenderer instanceof FORGE.BackgroundShaderRenderer)
    {
        if (this._repeatX === false)
        {
            var hfov = vfov * this._viewer.renderer.displayResolution.ratio;
            var texRatio = this._viewer.renderer.backgroundRenderer.textureSize.ratio;
            this._yawMax = Math.min(360, Math.max(0, (Math.PI * texRatio - hfov) * 0.5)); // image
            this._yawMin = -this._yawMax;
        }
        else
        {
            this._yawMin = FORGE.Math.degToRad(-360);
            this._yawMax = FORGE.Math.degToRad(360);
        }

        if (this._repeatY === false)
        {
            this._pitchMax = 0.5 * Math.max(0, Math.PI - vfov);
            this._pitchMin = -this._pitchMax;
        }
        else
        {
            this._pitchMin = FORGE.Math.degToRad(-180);
            this._pitchMax = FORGE.Math.degToRad(180);
        }

        this._viewer.view.notifyChange();
    }

    // Mesh rendering in flat view is limited around -+ 20 degrees
    else
    {
        this._yawMax = this._pitchMax = FORGE.Math.degToRad(20);
        this._yawMin = -this._yawMax;
        this._pitchMin = -this._pitchMax;
    }
};

/**
 * Update uniforms.
 *
 * @method FORGE.ViewFlat#updateUniforms
 * @param {FORGEUniform} uniforms
 */
FORGE.ViewFlat.prototype.updateUniforms = function(uniforms)
{
    this._updateViewParams();

    if (typeof uniforms === "undefined")
    {
        return;
    }

    if (uniforms.hasOwnProperty("tRepeatX"))
    {
        uniforms.tRepeatX.value = this._repeatX ? 1 : 0;
    }

    if (uniforms.hasOwnProperty("tRepeatY"))
    {
        uniforms.tRepeatY.value = this._repeatY ? 1 : 0;
    }

    if (uniforms.hasOwnProperty("tYaw"))
    {
        uniforms.tYaw.value = FORGE.Math.degToRad(this._viewer.camera.yaw);
    }

    if (uniforms.hasOwnProperty("tPitch"))
    {
        uniforms.tPitch.value = FORGE.Math.degToRad(this._viewer.camera.pitch);
    }

    if (uniforms.hasOwnProperty("tFov"))
    {
        uniforms.tFov.value = FORGE.Math.degToRad(this._viewer.renderer.camera.fov);
    }
};

/**
 * Convert a point from world space to screen space.
 *
 * @method FORGE.ViewFlat#worldToScreen
 * @return {THREE.Vector2} point in screen coordinates
 */
FORGE.ViewFlat.prototype.worldToScreen = function()
{
    return new THREE.Vector2();
};

/**
 * Convert a point from screen space to world space.
 *
 * @method FORGE.ViewFlat#screenToWorld
 * @return {THREE.Vector3} world point
 */
FORGE.ViewFlat.prototype.screenToWorld = function()
{
    return new THREE.Vector3();
};

/**
 * Destroy method.
 *
 * @method FORGE.ViewFlat#destroy
 */
FORGE.ViewFlat.prototype.destroy = function()
{
    FORGE.ViewBase.prototype.destroy.call(this);
};

/**
 * Get and set the repeat X beahvior.
 * @name  FORGE.ViewFlat#repeatX
 * @type {string}
 */
Object.defineProperty(FORGE.ViewFlat.prototype, "repeatX",
{
    /** @this {FORGE.ViewFlat} */
    get: function()
    {
        return this._repeatX;
    },

    /** @this {FORGE.ViewFlat} */
    set: function(value)
    {
        this._repeatX = value;
        this._updateViewParams();

        // Notify the view manager of the change
        this._viewer.view.notifyChange();
    }
});

/**
 * Get and set the repeat Y beahvior.
 * @name  FORGE.ViewFlat#repeatY
 * @type {string}
 */
Object.defineProperty(FORGE.ViewFlat.prototype, "repeatY",
{
    /** @this {FORGE.ViewFlat} */
    get: function()
    {
        return this._repeatY;
    },

    /** @this {FORGE.ViewFlat} */
    set: function(value)
    {
        this._repeatY = value;
        this._updateViewParams();

        // Notify the view manager of the change
        this._viewer.view.notifyChange();
    }
});
<|endoftext|>


<commit_before>// Author: Boy Baukema
// http://github.com/relaxnow
module.exports =
{
	reporter: function (results, data)
	{
		"use strict";

		var files = {},
			out = [],
			pairs = {
				"&": "&",
				'"': """,
				"'": "'",
				"<": "<",
				">": ">"
			},
			file, fileName, i, issue, globals, unuseds;

		function encode(s) {
			for (var r in pairs) {
				if (typeof(s) !== "undefined") {
					s = s.replace(new RegExp(r, "g"), pairs[r]);
				}
			}
			return s || "";
		}

		results.forEach(function (result) {
			// Register the file
			result.file = result.file.replace(/^\.\//, '');
			if (!files[result.file]) {
				files[result.file] = [];
			}

			// Add the error
			files[result.file].push({
				severity: 'error',
				line: result.error.line,
				column: result.error.character,
				message: result.error.reason,
				source: result.error.raw
			});
		});

		data.forEach(function (result) {
			file = data.file;
			globals = result.implieds;
			unuseds = result.unused;

			// Register the file
			result.file = result.file.replace(/^\.\//, '');
			if (!files[result.file]) {
				files[result.file] = [];
			}

			if (globals) {
				globals.forEach(function (global) {
					files[result.file].push({
						severity: 'warning',
						line: global.line,
						column: 0,
						message: "Implied global '" + global.name + "'",
						source: 'jshint.implied-globals'
					});
				});
			}
			if (unuseds) {
				unuseds.forEach(function (unused) {
					files[result.file].push({
						severity: 'warning',
						line: unused.line,
						column: 0,
						message: "Unused variable: '" + unused.name + "'",
						source: 'jshint.implied-unuseds'
					});
				});
			}
		});

		out.push("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
		out.push("<checkstyle version=\"4.3\">");

		for (fileName in files) {
			if (files.hasOwnProperty(fileName)) {
				out.push("\t<file name=\"" + fileName + "\">");
				for (i = 0; i < files[fileName].length; i++) {
					issue = files[fileName][i];
					out.push(
						"\t\t<error " +
							"line=\"" + issue.line + "\" " +
							"column=\"" + issue.column + "\" " +
							"severity=\"" + issue.severity + "\" " +
							"message=\"" + encode(issue.message) + "\" " +
							"source=\"" + encode(issue.source) + "\" " +
							"/>"
					);
				}
				out.push("\t</file>");
			}
		}

		out.push("</checkstyle>");

		process.stdout.write(out.join("\n") + "\n");
	}
};
<commit_msg>Fixes #977 - Adding the error code to the checkstyle message when --verbose is specified, and changing the source to just provide the error code.  The old way of using the raw message was useless, and breaks the categorization in Jenkins<commit_after>// Author: Boy Baukema
// http://github.com/relaxnow
module.exports =
{
	reporter: function (results, data, opts)
	{
		"use strict";

		var files = {},
			out = [],
			pairs = {
				"&": "&",
				'"': """,
				"'": "'",
				"<": "<",
				">": ">"
			},
			file, fileName, i, issue, globals, unuseds, errorMessage;

		opts = opts || {};

		function encode(s) {
			for (var r in pairs) {
				if (typeof(s) !== "undefined") {
					s = s.replace(new RegExp(r, "g"), pairs[r]);
				}
			}
			return s || "";
		}

		results.forEach(function (result) {
			// Register the file
			result.file = result.file.replace(/^\.\//, '');
			if (!files[result.file]) {
				files[result.file] = [];
			}

			// Create the error message
			errorMessage = result.error.reason;
			if (opts.verbose) {
				errorMessage += ' (' + result.error.code + ')';
			}

			// Add the error
			files[result.file].push({
				severity: 'error',
				line: result.error.line,
				column: result.error.character,
				message: errorMessage,
				source: result.error.code
			});
		});

		data.forEach(function (result) {
			file = data.file;
			globals = result.implieds;
			unuseds = result.unused;

			// Register the file
			result.file = result.file.replace(/^\.\//, '');
			if (!files[result.file]) {
				files[result.file] = [];
			}

			if (globals) {
				globals.forEach(function (global) {
					files[result.file].push({
						severity: 'warning',
						line: global.line,
						column: 0,
						message: "Implied global '" + global.name + "'",
						source: 'jshint.implied-globals'
					});
				});
			}
			if (unuseds) {
				unuseds.forEach(function (unused) {
					files[result.file].push({
						severity: 'warning',
						line: unused.line,
						column: 0,
						message: "Unused variable: '" + unused.name + "'",
						source: 'jshint.implied-unuseds'
					});
				});
			}
		});

		out.push("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
		out.push("<checkstyle version=\"4.3\">");

		for (fileName in files) {
			if (files.hasOwnProperty(fileName)) {
				out.push("\t<file name=\"" + fileName + "\">");
				for (i = 0; i < files[fileName].length; i++) {
					issue = files[fileName][i];
					out.push(
						"\t\t<error " +
							"line=\"" + issue.line + "\" " +
							"column=\"" + issue.column + "\" " +
							"severity=\"" + issue.severity + "\" " +
							"message=\"" + encode(issue.message) + "\" " +
							"source=\"" + encode(issue.source) + "\" " +
							"/>"
					);
				}
				out.push("\t</file>");
			}
		}

		out.push("</checkstyle>");

		process.stdout.write(out.join("\n") + "\n");
	}
};
<|endoftext|>


<commit_before>const fs = require('fs');
const assert = require('power-assert');
const npm = require('../../package.json');
const bower = require('../../bower.json');
const component = require('../../component.json');
const composer = require('../../composer.json');

const packages = [
	npm,
	bower,
	component,
	composer
];

describe('Package', () => {

	describe('Name', () => {

		it(`should be equal to ${npm.name}`, () => {
			packages.map((referenceValue, referenceIndex) => {
				packages.map((compareValue, compareIndex) => {
					if (referenceIndex !== compareIndex) assert(referenceValue.name, compareValue.name);
				});
			});
		});

	});

	describe('Version', () => {

		it(`should be equal to v${npm.version}`, () => {
			packages.map((referenceValue, referenceIndex) => {
				packages.map((compareValue, compareIndex) => {
					if (referenceIndex !== compareIndex) assert(referenceValue.version, compareValue.version);
				});
			});
		});

	});

	describe('Description', () => {

		it(`should be equal to ${npm.description}`, () => {
			packages.map((referenceValue, referenceIndex) => {
				packages.map((compareValue, compareIndex) => {
					if (referenceIndex !== compareIndex) assert(referenceValue.description, compareValue.description);
				});
			});
		});

	});

	describe('Homepage', () => {

		it(`should be equal to ${npm.homepage}`, () => {
			packages.map((referenceValue, referenceIndex) => {
				packages.map((compareValue, compareIndex) => {
					if (referenceIndex !== compareIndex) assert(referenceValue.homepage, compareValue.homepage);
				});
			});
		});

	});

	describe('Repository', () => {

		it(`should be equal to ${npm.repository}`, () => {
			packages.map((referenceValue, referenceIndex) => {
				packages.map((compareValue, compareIndex) => {
					if (referenceIndex !== compareIndex) assert(referenceValue.repository, compareValue.repository);
				});
			});
		});

	});

	describe('License', () => {

		it(`should be equal to ${npm.license}`, () => {
			packages.map((referenceValue, referenceIndex) => {
				packages.map((compareValue, compareIndex) => {
					if (referenceIndex !== compareIndex) assert(referenceValue.license, compareValue.license);
				});
			});
		});

	});

	describe('Author Name', () => {

		it(`should be equal to ${npm.author}`, () => {
			packages.map((referenceValue, referenceIndex) => {
				packages.map((compareValue, compareIndex) => {
					if (referenceIndex !== compareIndex) assert(referenceValue.author, compareValue.author);
				});
			});
		});

	});

	describe('Main File', () => {

		it(`should be equal to ${npm.main}`, () => {
			packages.map((referenceValue, referenceIndex) => {
				packages.map((compareValue, compareIndex) => {
					if (referenceIndex !== compareIndex) assert(referenceValue.main, compareValue.main);
				});
			});
		});

	});

	describe('Ignore', () => {

		it('should be equal', () => {
			packages.map((referenceValue, referenceIndex) => {
				packages.map((compareValue, compareIndex) => {
					if (referenceIndex !== compareIndex) assert(referenceValue.ignore, compareValue.ignore);
				});
			});
		});

	});

	describe('Keywords', () => {

		it('should be equal', () => {
			packages.map((referenceValue, referenceIndex) => {
				packages.map((compareValue, compareIndex) => {
					if (referenceIndex !== compareIndex) assert(referenceValue.keywords, compareValue.keywords);
				});
			});
		});

	});

});
<commit_msg>Removing unused declaration<commit_after>const assert = require('power-assert');
const npm = require('../../package.json');
const bower = require('../../bower.json');
const component = require('../../component.json');
const composer = require('../../composer.json');

const packages = [
	npm,
	bower,
	component,
	composer
];

describe('Package', () => {

	describe('Name', () => {

		it(`should be equal to ${npm.name}`, () => {
			packages.map((referenceValue, referenceIndex) => {
				packages.map((compareValue, compareIndex) => {
					if (referenceIndex !== compareIndex) assert(referenceValue.name, compareValue.name);
				});
			});
		});

	});

	describe('Version', () => {

		it(`should be equal to v${npm.version}`, () => {
			packages.map((referenceValue, referenceIndex) => {
				packages.map((compareValue, compareIndex) => {
					if (referenceIndex !== compareIndex) assert(referenceValue.version, compareValue.version);
				});
			});
		});

	});

	describe('Description', () => {

		it(`should be equal to ${npm.description}`, () => {
			packages.map((referenceValue, referenceIndex) => {
				packages.map((compareValue, compareIndex) => {
					if (referenceIndex !== compareIndex) assert(referenceValue.description, compareValue.description);
				});
			});
		});

	});

	describe('Homepage', () => {

		it(`should be equal to ${npm.homepage}`, () => {
			packages.map((referenceValue, referenceIndex) => {
				packages.map((compareValue, compareIndex) => {
					if (referenceIndex !== compareIndex) assert(referenceValue.homepage, compareValue.homepage);
				});
			});
		});

	});

	describe('Repository', () => {

		it(`should be equal to ${npm.repository}`, () => {
			packages.map((referenceValue, referenceIndex) => {
				packages.map((compareValue, compareIndex) => {
					if (referenceIndex !== compareIndex) assert(referenceValue.repository, compareValue.repository);
				});
			});
		});

	});

	describe('License', () => {

		it(`should be equal to ${npm.license}`, () => {
			packages.map((referenceValue, referenceIndex) => {
				packages.map((compareValue, compareIndex) => {
					if (referenceIndex !== compareIndex) assert(referenceValue.license, compareValue.license);
				});
			});
		});

	});

	describe('Author Name', () => {

		it(`should be equal to ${npm.author}`, () => {
			packages.map((referenceValue, referenceIndex) => {
				packages.map((compareValue, compareIndex) => {
					if (referenceIndex !== compareIndex) assert(referenceValue.author, compareValue.author);
				});
			});
		});

	});

	describe('Main File', () => {

		it(`should be equal to ${npm.main}`, () => {
			packages.map((referenceValue, referenceIndex) => {
				packages.map((compareValue, compareIndex) => {
					if (referenceIndex !== compareIndex) assert(referenceValue.main, compareValue.main);
				});
			});
		});

	});

	describe('Ignore', () => {

		it('should be equal', () => {
			packages.map((referenceValue, referenceIndex) => {
				packages.map((compareValue, compareIndex) => {
					if (referenceIndex !== compareIndex) assert(referenceValue.ignore, compareValue.ignore);
				});
			});
		});

	});

	describe('Keywords', () => {

		it('should be equal', () => {
			packages.map((referenceValue, referenceIndex) => {
				packages.map((compareValue, compareIndex) => {
					if (referenceIndex !== compareIndex) assert(referenceValue.keywords, compareValue.keywords);
				});
			});
		});

	});

});
<|endoftext|>


<commit_before>var buster = require('buster-assertions');
var assert = buster.assert;
var refute = buster.refute;
var help = require('../lib/validateHelpers.js');

var hook = require('../../lib/hook/pasties.js');

describe('Pasties hooks', function () {

    it('should store probes', function () {

        var options = {
            'key': Math.random() * 1000 * Date.now()
        };
        var calls = 0;
        var arg;
        var injected = [];
        var api = {
            injectLocalJs: function (str) {
                injected.push(str);
            },
            getOptions: function () {
                return options;
            },
            evaluate: function (fn, _opt) {
                arg = _opt;
                global.window = {
                    initManager: function () {
                        calls++;
                    }
                };
                calls++;
                res = fn();
                global.window = null;
                return res;
            }
        };

        hook.onPageOpen(api);

        assert.equals(calls, 2);
        assert(arg, 'should have collected initManager argument');
        assert.equals(arg, JSON.stringify(options));
    });

});

var validator = require('../../lib/validator/pasties.js');
describe('Pasties validator', function () {

    it.skip('should evaluate client total size and report', function(){});
    it.skip('should evaluate responsive position', function(){});
    it.skip('should evaluate css position', function(){});

    it('should call next', function (done) {
        validator.validate(null, null, done);
    });

});
<commit_msg>renamed file<commit_after>var buster = require('buster-assertions');
var assert = buster.assert;
var refute = buster.refute;
var help = require('../lib/validateHelpers.js');

var hook = require('../../lib/hook/pasties.js');

describe('Pasties hooks', function () {

    it('should store probes', function () {

        var options = {
            'key': Math.random() * 1000 * Date.now()
        };
        var calls = 0;
        var arg;
        var injected = [];
        var api = {
            injectLocalJs: function (str) {
                injected.push(str);
            },
            getOptions: function () {
                return options;
            },
            evaluate: function (fn, _opt) {
                arg = _opt;
                global.window = {
                    initManager: function () {
                        calls++;
                    }
                };
                calls++;
                res = fn();
                global.window = null;
                return res;
            }
        };

        hook.onPageOpen(api);

        assert.equals(calls, 2);
        assert(arg, 'should have collected initManager argument');
        assert.equals(arg, JSON.stringify(options));
    });

});

var validator = require('../../lib/validator/css.js');
describe('Pasties validator', function () {

    it.skip('should evaluate client total size and report', function(){});
    it.skip('should evaluate responsive position', function(){});
    it.skip('should evaluate css position', function(){});

    it('should call next', function (done) {
        validator.validate(null, null, done);
    });

});
<|endoftext|>


<commit_before>import { getUrlExtension } from '../src/utilities/urlExtension.js';

describe( 'getUrlExtension', () => {

	it.each( [
		'https://nasa.gov/foo/bar/baz.qux/tileset.json',
		'https://nasa.gov/foo/bar/baz.qux/tileset.json?foo=bar',
		'https://nasa.gov/foo/bar/baz.qux/tileset.json?a.b=c.d',
		'https://nasa.gov/tileset.json',
		'https://nasa.gov//tileset.json',
		'file:///Users/JaneScientist/code/3DTilesRendererJS/example/b3dmExample.json',
		'foo.json',
		'foo.json?a=b',
		'/foo.json',
	] )( 'parses the json extension out of %s', url => {

		expect( getUrlExtension( url ) ).toBe( 'json' );

	} );

	it.each( [
		'https://nasa.gov',
		'https://nasa.gov/',
		'https://nasa.gov/tileset',
		'https://nasa.gov/sg/b3dm/NeveTzedek3.420160/tileset?foo=bar',
		'https://nasa.gov/sg/b3dm/NeveTzedek3.420160/tileset?a.b=c.d',
		'https://nasa.gov/tileset',
		'https://nasa.gov/tileset.',
		'Pleiades',
	] )( 'returns null for strings that are not URLs with extensions %s', url => {

		expect( getUrlExtension( url ) ).toBeNull();

	} );

} );
<commit_msg>Add more test cases.<commit_after>import { getUrlExtension } from '../src/utilities/urlExtension.js';

describe( 'getUrlExtension', () => {

	it.each( [
		'https://nasa.gov/foo/bar/baz.qux/tileset.json',
		'https://nasa.gov/foo/bar/baz.qux/tileset.json?foo=bar',
		'https://nasa.gov/foo/bar/baz.qux/tileset.json?a.b=c.d',
		'https://nasa.gov/tileset.json',
		'https://nasa.gov//tileset.json',
		'file:///Users/JaneScientist/code/3DTilesRendererJS/example/b3dmExample.json',
		'foo.json',
		'/foo/bar.json',
		'foo.json?a=b',
		'/foo.json',
		'/foo/bar.json',
	] )( 'parses the json extension out of %s', url => {

		expect( getUrlExtension( url ) ).toBe( 'json' );

	} );

	it.each( [
		'https://nasa.gov',
		'https://nasa.gov/',
		'https://nasa.gov/tileset',
		'https://nasa.gov/sg/b3dm/NeveTzedek3.420160/tileset?foo=bar',
		'https://nasa.gov/sg/b3dm/NeveTzedek3.420160/tileset?a.b=c.d',
		'https://nasa.gov/tileset',
		'https://nasa.gov/tileset.',
		'Pleiades',
	] )( 'returns null for strings that are not URLs with extensions %s', url => {

		expect( getUrlExtension( url ) ).toBeNull();

	} );

} );
<|endoftext|>


<commit_before>export default () => ({
  clear: jest.fn(() => Promise.resolve()),
  persist: jest.fn(data => Promise.resolve(data)),
  restore: jest.fn(() => Promise.resolve())
})
<commit_msg>Return authenticated key in storage restore<commit_after>export default () => ({
  clear: jest.fn(() => Promise.resolve()),
  persist: jest.fn(data => Promise.resolve(data)),
  restore: jest.fn(() => Promise.resolve({ authenticated: {}}))
})
<|endoftext|>